Compare commits

...
34 Commits
Author SHA1 Message Date
Richard Shiue ee404369ff fix: row document images (#7322)
* fix: row document images

* fix: calendar

* chore: fallback to documentbloc
2025-02-05 16:42:18 +08:00
Lucas.Xu 58ea654ddf chore: update changelog.md 2025-02-05 16:40:49 +08:00
Lucas.Xu cc14793535 chore: bump version 0.8.3 2025-02-05 14:20:18 +08:00
Nathan.fooo 122fb89c87 chore: fix ai page user profile refresh (#7317) 2025-02-04 20:40:06 +08:00
Lucas e9201cce72 fix: editor stuck on image loading loop when uploading image in row document (#7313)
* fix: editor stuck on image loading loop when uploading image in row document

* test: editor stuck on image loading loop when uploading image in row document
2025-02-04 18:03:28 +08:00
Nathan.fooo 5e5693e249 chore: Support new error code (#7311)
* chore: fetch model list

* chore: suppor new error code
2025-02-03 20:52:31 +08:00
Nathan 5ac0eded3c chore: fetch model list 2025-02-01 23:50:58 +08:00
Lucas dd6b285cd3 chore: update CHANGELOG.md (#7276) 2025-01-23 17:55:12 +08:00
FakhriAzzouz 8b0d5d76a2 New Arabic Translations (#7260)
* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦
2025-01-23 14:02:32 +08:00
Morn 85b69bde15 chore: cancel button not visible in [Reset to Default] for shortcuts(#7171) (#7257) 2025-01-23 13:58:48 +08:00
Morn dd812d0501 chore: rename [font scale factor] to [scale factor] (#7267) 2025-01-23 13:58:09 +08:00
Richard Shiue a79f825ff1 chore: restrict uploadable image types (#7269)
* chore: restrict image format

* chore: code cleanup
2025-01-23 10:51:15 +08:00
Lucas 862e5629e3 fix: v0.8.2 launch review issues (#7266)
* fix: unable to copy table from Apple Notes

* fix: disable pasting a table into another table

* fix: ignore the delete shortcut if the next node is a simple table node
2025-01-22 22:46:03 +08:00
Richard Shiue c5a91e10df chore: support pasting image links that have no file extension (#7262)
* test: speed up copypasta tests

* chore: strip away markdown syntax if message is image only

* chore: paste image urls with no file extension

* test: add integration test

* test: group tests

* chore: apply code suggestions to 3 files
2025-01-22 22:13:18 +08:00
Lucas 0b0e10baa8 feat: turn -> into to → in document (#7256)
* chore: bump version 0.8.2

* feat: turn -> into to → in document

* Revert "chore: bump version 0.8.2"

This reverts commit 45efd4d7d7.

* test: add shortcut tests
2025-01-22 15:05:22 +08:00
Nathan ec18a3c443 chore: update docs 2025-01-22 09:47:06 +08:00
Nathan.fooo a0867ed688 chore: return ai image error (#7263) 2025-01-22 09:42:24 +08:00
Nathan.fooo cdf8e68ff2 Update plan desc (#7258)
* chore: update plan desc

* chore: update plan desc
2025-01-22 02:02:30 +08:00
Richard Shiue af92303e38 fix: launch review issues 0.8.2 (#7261) 2025-01-21 22:17:53 +08:00
Lucas 504041d75a chore: bump version 0.8.2 (#7255) 2025-01-21 13:31:40 +08:00
Lucas 06ab965413 chore: only enable document integrity check when enableDocumentInternalLog is on (#7251)
* chore: only enable document integrity check when enableDocumentInternalLog is on

* feat: copy divider and table from ChatGPT

* test: add copy from ChatGPT test

* feat: support copying link from keyboard clipboard
2025-01-21 13:29:31 +08:00
Morn 42bd4884fd feat: support custom image icon (#7236)
* feat: supporting upload custom image as icon

* feat: support custom image icon on mobile

* chore: clean code
2025-01-21 11:58:45 +08:00
Lucas 0c057243bc chore: bump client api (#7249)
* chore: bump client api

* chore: set default publish info to true
2025-01-21 09:18:25 +08:00
Lucas 8fdc6e9638 feat: support pasting table from notion, google docs and google sheet (#7247)
* feat: support pasting table from Notion

* test: add google docs / googles sheets table test

* fix: google docs test

* fix: paste table from notion test
2025-01-21 09:12:57 +08:00
Morn 187f7409ce feat: enable customizing icons for database views (#7187)
* feat: enable set icon for databse tab

* chore: resolve conflicts

* feat: enable changing dabtabse icon on mobile
2025-01-20 17:55:01 +08:00
Morn e3ce6e8b4b fix: use WindowSizeManager to zoom on mobile (#7215) 2025-01-20 17:54:26 +08:00
Richard Shiue cfe481759f chore: bump table column width when saving chat message to page (#7243)
* chore: bump table column width when saving chat message to page

* test: add unit test
2025-01-20 13:28:02 +08:00
Richard Shiue 6bcef33d05 chore: trim markdown text (#7242)
* chore: trim markdown text

* chore: trim before saving
2025-01-20 11:47:03 +08:00
Lucas aa8c9bad9f fix: remove app from homepage url (#7233)
* fix: remove app from namespace url

* fix: banner issue on mobile

* Revert "fix: remove app from namespace url"

This reverts commit 4bd5f3f590.

* fix: remove app from namespace url
2025-01-17 20:55:22 +08:00
Richard Shiue 1723886f3a feat: save messages as a new page (#7224) 2025-01-17 20:38:55 +08:00
FakhriAzzouz 63c7f7b6fe chore: update ar-SA translations (#7216)
* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦
2025-01-17 10:08:09 +08:00
Lucas f35dfaf525 fix: improve the document diff function to prevent partial ordering issues (#7217)
* fix: improve the document diff function to prevent partial ordering issues

* fix: improve the document diff function to prevent partial ordering issues

* fix: nested block padding issues

* fix: improve the document diff function to prevent partial ordering issues

* chore: update editor version

* test: add no diff test and update text diff test

* test: delete and insert text diff with different id

* test: insert single text / delete single text tests

* test: multiple delete and update diff

* test: multiple insert and update diff

* chore: revert cargo changes

* chore: remove unused code

* chore: optimize the code logic
2025-01-16 21:01:23 +08:00
Richard Shiue eead2d20f5 fix: pass alwaysDistributeColumnWidths to simple table block (#7228) 2025-01-16 16:42:24 +08:00
Richard Shiue f73c2540c6 chore: reorganize code (#7206) 2025-01-15 19:57:47 +08:00
185 changed files with 5996 additions and 1713 deletions

No files matched your search

+20 -1
View File
@@ -1,6 +1,25 @@
# Release Notes
## Version 0.8.3 - 05/02/2025
### New Features
- Support OpenAI o3-mini model
### Bug Fixes
- Fixed an issue where users were unable to upload images in row pages
- Fixed an issue where users were unable to upload files on Android devices
## Version 0.8.2 - 23/01/2025
### New Features
- Customized database view icons
- Support for uploading images as custom icons
- Enabled selecting multiple AI messages to save into a document
- Added the ability to scale the app's display size on mobile
- Support for pasting image links without file extensions
### Bug Fixes
- Fixed an issue where pasting tables from other apps wasn't working
- Fixed homepage URL issues in Settings
- Fixed an issue where the 'Cancel' button was not visible on the Shortcuts page
## Version 0.8.1 - 14/01/2025
### New Features:
### New Features
- AI Chat Layout Options: Customize how AI responses appear with new layouts—List, Table, Image with Text, and Media Only
- DALL-E Integration: Generate stunning AI images from text prompts, now available in AI Chat
- Improved Desktop Search: Find what you need faster using keywords or by asking questions in natural language
+123 -123
View File
@@ -1,125 +1,125 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
// This task only builds the Dart code of AppFlowy.
// It supports both the desktop and mobile version.
"name": "AF: Build Dart Only",
"request": "launch",
"program": "./lib/main.dart",
"type": "dart",
"env": {
"RUST_LOG": "debug",
},
// uncomment the following line to testing performance.
// "flutterMode": "profile",
"cwd": "${workspaceRoot}/appflowy_flutter"
},
{
// This task builds the Rust and Dart code of AppFlowy.
"name": "AF-desktop: Build All",
"request": "launch",
"program": "./lib/main.dart",
"type": "dart",
"preLaunchTask": "AF: Build Appflowy Core",
"env": {
"RUST_LOG": "trace",
"RUST_BACKTRACE": "1"
},
"cwd": "${workspaceRoot}/appflowy_flutter"
},
{
// This task builds will:
// - call the clean task,
// - rebuild all the generated Files (including freeze and language files)
// - rebuild the the Rust and Dart code of AppFlowy.
"name": "AF-desktop: Clean + Rebuild All",
"request": "launch",
"program": "./lib/main.dart",
"type": "dart",
"preLaunchTask": "AF: Clean + Rebuild All",
"env": {
"RUST_LOG": "trace"
},
"cwd": "${workspaceRoot}/appflowy_flutter"
},
{
"name": "AF-iOS: Build All",
"request": "launch",
"program": "./lib/main.dart",
"type": "dart",
"preLaunchTask": "AF: Build Appflowy Core For iOS",
"env": {
"RUST_LOG": "trace"
},
"cwd": "${workspaceRoot}/appflowy_flutter"
},
{
"name": "AF-iOS: Clean + Rebuild All",
"request": "launch",
"program": "./lib/main.dart",
"type": "dart",
"preLaunchTask": "AF: Clean + Rebuild All (iOS)",
"env": {
"RUST_LOG": "trace"
},
"cwd": "${workspaceRoot}/appflowy_flutter"
},
{
"name": "AF-iOS-Simulator: Build All",
"request": "launch",
"program": "./lib/main.dart",
"type": "dart",
"preLaunchTask": "AF: Build Appflowy Core For iOS Simulator",
"env": {
"RUST_LOG": "trace"
},
"cwd": "${workspaceRoot}/appflowy_flutter"
},
{
"name": "AF-iOS-Simulator: Clean + Rebuild All",
"request": "launch",
"program": "./lib/main.dart",
"type": "dart",
"preLaunchTask": "AF: Clean + Rebuild All (iOS Simulator)",
"env": {
"RUST_LOG": "trace"
},
"cwd": "${workspaceRoot}/appflowy_flutter"
},
{
"name": "AF-Android: Build All",
"request": "launch",
"program": "./lib/main.dart",
"type": "dart",
"preLaunchTask": "AF: Build Appflowy Core For Android",
"env": {
"RUST_LOG": "trace"
},
"cwd": "${workspaceRoot}/appflowy_flutter"
},
{
"name": "AF-Android: Clean + Rebuild All",
"request": "launch",
"program": "./lib/main.dart",
"type": "dart",
"preLaunchTask": "AF: Clean + Rebuild All (Android)",
"env": {
"RUST_LOG": "trace"
},
"cwd": "${workspaceRoot}/appflowy_flutter"
},
{
"name": "AF-desktop: Debug Rust",
"type": "lldb",
"request": "attach",
"pid": "${command:pickMyProcess}"
// To launch the application directly, use the following configuration:
// "request": "launch",
// "program": "[YOUR_APPLICATION_PATH]",
},
]
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
// This task only builds the Dart code of AppFlowy.
// It supports both the desktop and mobile version.
"name": "AF: Build Dart Only",
"request": "launch",
"program": "./lib/main.dart",
"type": "dart",
"env": {
"RUST_LOG": "debug",
},
// uncomment the following line to testing performance.
// "flutterMode": "profile",
"cwd": "${workspaceRoot}/appflowy_flutter"
},
{
// This task builds the Rust and Dart code of AppFlowy.
"name": "AF-desktop: Build All",
"request": "launch",
"program": "./lib/main.dart",
"type": "dart",
"preLaunchTask": "AF: Build Appflowy Core",
"env": {
"RUST_LOG": "trace",
"RUST_BACKTRACE": "1"
},
"cwd": "${workspaceRoot}/appflowy_flutter"
},
{
// This task builds will:
// - call the clean task,
// - rebuild all the generated Files (including freeze and language files)
// - rebuild the the Rust and Dart code of AppFlowy.
"name": "AF-desktop: Clean + Rebuild All",
"request": "launch",
"program": "./lib/main.dart",
"type": "dart",
"preLaunchTask": "AF: Clean + Rebuild All",
"env": {
"RUST_LOG": "trace"
},
"cwd": "${workspaceRoot}/appflowy_flutter"
},
{
"name": "AF-iOS: Build All",
"request": "launch",
"program": "./lib/main.dart",
"type": "dart",
"preLaunchTask": "AF: Build Appflowy Core For iOS",
"env": {
"RUST_LOG": "trace"
},
"cwd": "${workspaceRoot}/appflowy_flutter"
},
{
"name": "AF-iOS: Clean + Rebuild All",
"request": "launch",
"program": "./lib/main.dart",
"type": "dart",
"preLaunchTask": "AF: Clean + Rebuild All (iOS)",
"env": {
"RUST_LOG": "trace"
},
"cwd": "${workspaceRoot}/appflowy_flutter"
},
{
"name": "AF-iOS-Simulator: Build All",
"request": "launch",
"program": "./lib/main.dart",
"type": "dart",
"preLaunchTask": "AF: Build Appflowy Core For iOS Simulator",
"env": {
"RUST_LOG": "trace"
},
"cwd": "${workspaceRoot}/appflowy_flutter"
},
{
"name": "AF-iOS-Simulator: Clean + Rebuild All",
"request": "launch",
"program": "./lib/main.dart",
"type": "dart",
"preLaunchTask": "AF: Clean + Rebuild All (iOS Simulator)",
"env": {
"RUST_LOG": "trace"
},
"cwd": "${workspaceRoot}/appflowy_flutter"
},
{
"name": "AF-Android: Build All",
"request": "launch",
"program": "./lib/main.dart",
"type": "dart",
"preLaunchTask": "AF: Build Appflowy Core For Android",
"env": {
"RUST_LOG": "trace"
},
"cwd": "${workspaceRoot}/appflowy_flutter"
},
{
"name": "AF-Android: Clean + Rebuild All",
"request": "launch",
"program": "./lib/main.dart",
"type": "dart",
"preLaunchTask": "AF: Clean + Rebuild All (Android)",
"env": {
"RUST_LOG": "trace"
},
"cwd": "${workspaceRoot}/appflowy_flutter"
},
{
"name": "AF-desktop: Debug Rust",
"type": "lldb",
"request": "attach",
"pid": "${command:pickMyProcess}"
// To launch the application directly, use the following configuration:
// "request": "launch",
// "program": "[YOUR_APPLICATION_PATH]",
},
]
}
+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.1"
APPFLOWY_VERSION = "0.8.3"
FLUTTER_DESKTOP_FEATURES = "dart"
PRODUCT_NAME = "AppFlowy"
MACOSX_DEPLOYMENT_TARGET = "11.0"
@@ -1,5 +1,6 @@
import 'data_migration/data_migration_test_runner.dart'
as data_migration_test_runner;
import 'database/database_test_runner.dart' as database_test_runner;
import 'document/document_test_runner.dart' as document_test_runner;
import 'set_env.dart' as preset_af_cloud_env_test;
import 'sidebar/sidebar_icon_test.dart' as sidebar_icon_test;
@@ -28,4 +29,7 @@ Future<void> main() async {
sidebar_move_page_test.main();
sidebar_rename_untitled_test.main();
sidebar_icon_test.main();
// database
database_test_runner.main();
}
@@ -0,0 +1,80 @@
import 'dart:io';
import 'package:appflowy/core/config/kv.dart';
import 'package:appflowy/core/config/kv_keys.dart';
import 'package:appflowy/env/cloud_env.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/image/resizeable_image.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pbenum.dart';
import 'package:appflowy_editor/appflowy_editor.dart'
hide UploadImageMenu, ResizableImage;
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import '../../../shared/constants.dart';
import '../../../shared/database_test_op.dart';
import '../../../shared/mock/mock_file_picker.dart';
import '../../../shared/util.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
// copy link to block
group('database image:', () {
testWidgets('insert image', (tester) async {
await tester.initializeAppFlowy(
cloudType: AuthenticatorType.appflowyCloudSelfHost,
);
await tester.tapGoogleLoginInButton();
await tester.expectToSeeHomePageWithGetStartedPage();
// open the first row detail page and upload an image
await tester.createNewPageInSpace(
spaceName: Constants.generalSpaceName,
layout: ViewLayoutPB.Grid,
pageName: 'database image',
);
await tester.openFirstRowDetailPage();
// insert an image block
{
await tester.editor.tapLineOfEditorAt(0);
await tester.editor.showSlashMenu();
await tester.editor.tapSlashMenuItemWithName(
LocaleKeys.document_slashMenu_name_image.tr(),
);
}
// upload an image
{
final image = await rootBundle.load('assets/test/images/sample.jpeg');
final tempDirectory = await getTemporaryDirectory();
final imagePath = p.join(tempDirectory.path, 'sample.jpeg');
final file = File(imagePath)
..writeAsBytesSync(image.buffer.asUint8List());
mockPickFilePaths(
paths: [imagePath],
);
await getIt<KeyValueStorage>().set(KVKeys.kCloudType, '0');
await tester.tapButtonWithName(
LocaleKeys.document_imageBlock_upload_placeholder.tr(),
);
await tester.pumpAndSettle();
expect(find.byType(ResizableImage), findsOneWidget);
final node = tester.editor.getCurrentEditorState().getNodeAtPath([0])!;
expect(node.type, ImageBlockKeys.type);
expect(node.attributes[ImageBlockKeys.url], isNotEmpty);
// remove the temp file
file.deleteSync();
}
});
});
}
@@ -0,0 +1,9 @@
import 'package:integration_test/integration_test.dart';
import 'database_image_test.dart' as database_image_test;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
database_image_test.main();
}
@@ -120,6 +120,10 @@ void main() {
widget is PublishedViewItem &&
widget.publishInfoView.view.name == pageName,
);
if (pageItem.evaluate().isEmpty) {
return;
}
expect(pageItem, findsOneWidget);
// comment it out because it's not allowed to update the namespace in free plan
@@ -257,6 +261,10 @@ More actions for published page:
widget is PublishedViewItem &&
widget.publishInfoView.view.name == pageName,
);
if (pageItem.evaluate().isEmpty) {
return;
}
expect(pageItem, findsOneWidget);
final copyLinkItem = find.text(LocaleKeys.shareAction_copyLink.tr());
@@ -0,0 +1,190 @@
import 'dart:convert';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/database/tab_bar/desktop/tab_bar_add_button.dart';
import 'package:appflowy/plugins/database/tab_bar/desktop/tab_bar_header.dart';
import 'package:appflowy/plugins/database/widgets/database_layout_ext.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/header/emoji_icon_widget.dart';
import 'package:appflowy/shared/icon_emoji_picker/icon_picker.dart';
import 'package:appflowy/shared/icon_emoji_picker/recent_icons.dart';
import 'package:appflowy/workspace/presentation/home/menu/sidebar/shared/sidebar_folder.dart';
import 'package:appflowy/workspace/presentation/home/menu/view/view_item.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/setting_entities.pbenum.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import '../../shared/emoji.dart';
import '../../shared/util.dart';
void main() {
setUpAll(() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
RecentIcons.enable = false;
});
tearDownAll(() {
RecentIcons.enable = true;
});
testWidgets('change icon', (tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
final iconData = await tester.loadIcon();
const pageName = 'Database';
await tester.createNewPageWithNameUnderParent(
layout: ViewLayoutPB.Grid,
name: pageName,
);
/// create board
final addButton = find.byType(AddDatabaseViewButton);
await tester.tapButton(addButton);
await tester.tapButton(
find.text(
'${LocaleKeys.grid_createView.tr()} ${DatabaseLayoutPB.Board.layoutName}',
findRichText: true,
),
);
/// create calendar
await tester.tapButton(addButton);
await tester.tapButton(
find.text(
'${LocaleKeys.grid_createView.tr()} ${DatabaseLayoutPB.Calendar.layoutName}',
findRichText: true,
),
);
final databaseTabBarItem = find.byType(DatabaseTabBarItem);
expect(databaseTabBarItem, findsNWidgets(3));
final gridItem = databaseTabBarItem.first,
boardItem = databaseTabBarItem.at(1),
calendarItem = databaseTabBarItem.last;
/// change the icon of grid
/// the first tapping is to select specific item
/// the second tapping is to show the menu
await tester.tapButton(gridItem);
await tester.tapButton(gridItem);
/// change icon
await tester
.tapButton(find.text(LocaleKeys.disclosureAction_changeIcon.tr()));
await tester.tapIcon(iconData, enableColor: false);
final gridIcon = find.descendant(
of: gridItem,
matching: find.byType(RawEmojiIconWidget),
);
final gridIconWidget =
gridIcon.evaluate().first.widget as RawEmojiIconWidget;
final iconsData = IconsData.fromJson(jsonDecode(iconData.emoji));
final gridIconsData =
IconsData.fromJson(jsonDecode(gridIconWidget.emoji.emoji));
expect(gridIconsData.iconName, iconsData.iconName);
/// change the icon of board
await tester.tapButton(boardItem);
await tester.tapButton(boardItem);
await tester
.tapButton(find.text(LocaleKeys.disclosureAction_changeIcon.tr()));
await tester.tapIcon(iconData, enableColor: false);
final boardIcon = find.descendant(
of: boardItem,
matching: find.byType(RawEmojiIconWidget),
);
final boardIconWidget =
boardIcon.evaluate().first.widget as RawEmojiIconWidget;
final boardIconsData =
IconsData.fromJson(jsonDecode(boardIconWidget.emoji.emoji));
expect(boardIconsData.iconName, iconsData.iconName);
/// change the icon of calendar
await tester.tapButton(calendarItem);
await tester.tapButton(calendarItem);
await tester
.tapButton(find.text(LocaleKeys.disclosureAction_changeIcon.tr()));
await tester.tapIcon(iconData, enableColor: false);
final calendarIcon = find.descendant(
of: calendarItem,
matching: find.byType(RawEmojiIconWidget),
);
final calendarIconWidget =
calendarIcon.evaluate().first.widget as RawEmojiIconWidget;
final calendarIconsData =
IconsData.fromJson(jsonDecode(calendarIconWidget.emoji.emoji));
expect(calendarIconsData.iconName, iconsData.iconName);
});
testWidgets('change database icon from sidebar', (tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
final iconData = await tester.loadIcon();
final icon = IconsData.fromJson(jsonDecode(iconData.emoji)), emoji = '😄';
const pageName = 'Database';
await tester.createNewPageWithNameUnderParent(
layout: ViewLayoutPB.Grid,
name: pageName,
);
final viewItem = find.descendant(
of: find.byType(SidebarFolder),
matching: find.byWidgetPredicate(
(w) => w is ViewItem && w.view.name == pageName,
),
);
/// change icon to emoji
await tester.tapButton(
find.descendant(
of: viewItem,
matching: find.byType(FlowySvg),
),
);
await tester.tapEmoji(emoji);
final iconWidget = find.descendant(
of: viewItem,
matching: find.byType(RawEmojiIconWidget),
);
expect(
(iconWidget.evaluate().first.widget as RawEmojiIconWidget).emoji.emoji,
emoji,
);
/// the icon will not be displayed in database item
Finder databaseIcon = find.descendant(
of: find.byType(DatabaseTabBarItem),
matching: find.byType(FlowySvg),
);
expect(
(databaseIcon.evaluate().first.widget as FlowySvg).svg,
FlowySvgs.icon_grid_s,
);
/// change emoji to icon
await tester.tapButton(iconWidget);
await tester.tapIcon(iconData);
expect(
(iconWidget.evaluate().first.widget as RawEmojiIconWidget).emoji.emoji,
iconData.emoji,
);
databaseIcon = find.descendant(
of: find.byType(DatabaseTabBarItem),
matching: find.byType(RawEmojiIconWidget),
);
final databaseIconWidget =
databaseIcon.evaluate().first.widget as RawEmojiIconWidget;
final databaseIconsData =
IconsData.fromJson(jsonDecode(databaseIconWidget.emoji.emoji));
expect(icon.svgString, databaseIconsData.svgString);
expect(icon.color, isNotEmpty);
expect(icon.color, databaseIconsData.color);
/// the icon in database item should not show the color
expect(databaseIconWidget.enableColor, false);
});
}
@@ -19,7 +19,7 @@ import '../../shared/util.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('copy and paste in document', () {
group('copy and paste in document:', () {
testWidgets('paste multiple lines at the first line', (tester) async {
// mock the clipboard
const lines = 3;
@@ -172,305 +172,314 @@ void main() {
},
);
});
});
testWidgets('paste text on part of bullet list', (tester) async {
const plainText = 'test';
testWidgets('paste text on part of bullet list', (tester) async {
const plainText = 'test';
await tester.pasteContent(
plainText: plainText,
beforeTest: (editorState) async {
final transaction = editorState.transaction;
transaction.insertNodes(
[0],
[
Node(
type: BulletedListBlockKeys.type,
attributes: {
'delta': [
{"insert": "bullet list"},
],
},
),
],
);
// Set the selection to the second numbered list node (which has empty delta)
transaction.afterSelection = Selection(
start: Position(path: [0], offset: 7),
end: Position(path: [0], offset: 11),
);
await editorState.apply(transaction);
await tester.pumpAndSettle();
},
(editorState) {
final node = editorState.getNodeAtPath([0]);
expect(node?.delta?.toPlainText(), 'bullet test');
expect(node?.type, BulletedListBlockKeys.type);
},
);
});
testWidgets('paste image(png) from memory', (tester) async {
final image = await rootBundle.load('assets/test/images/sample.png');
final bytes = image.buffer.asUint8List();
await tester.pasteContent(image: ('png', bytes), (editorState) {
expect(editorState.document.root.children.length, 1);
final node = editorState.getNodeAtPath([0])!;
expect(node.type, ImageBlockKeys.type);
expect(node.attributes[ImageBlockKeys.url], isNotNull);
});
});
testWidgets('paste image(jpeg) from memory', (tester) async {
final image = await rootBundle.load('assets/test/images/sample.jpeg');
final bytes = image.buffer.asUint8List();
await tester.pasteContent(image: ('jpeg', bytes), (editorState) {
expect(editorState.document.root.children.length, 1);
final node = editorState.getNodeAtPath([0])!;
expect(node.type, ImageBlockKeys.type);
expect(node.attributes[ImageBlockKeys.url], isNotNull);
});
});
testWidgets('paste image(gif) from memory', (tester) async {
final image = await rootBundle.load('assets/test/images/sample.gif');
final bytes = image.buffer.asUint8List();
await tester.pasteContent(image: ('gif', bytes), (editorState) {
expect(editorState.document.root.children.length, 1);
final node = editorState.getNodeAtPath([0])!;
expect(node.type, ImageBlockKeys.type);
expect(node.attributes[ImageBlockKeys.url], isNotNull);
});
});
testWidgets(
'format the selected text to href when pasting url if available',
(tester) async {
const text = 'appflowy';
const url = 'https://appflowy.io';
await tester.pasteContent(
plainText: url,
plainText: plainText,
beforeTest: (editorState) async {
await tester.ime.insertText(text);
await tester.editor.updateSelection(
Selection.single(
path: [0],
startOffset: 0,
endOffset: text.length,
),
final transaction = editorState.transaction;
transaction.insertNodes(
[0],
[
Node(
type: BulletedListBlockKeys.type,
attributes: {
'delta': [
{"insert": "bullet list"},
],
},
),
],
);
},
(editorState) {
final node = editorState.getNodeAtPath([0])!;
expect(node.type, ParagraphBlockKeys.type);
expect(node.delta!.toJson(), [
{
'insert': text,
'attributes': {'href': url},
}
]);
},
);
},
);
// https://github.com/AppFlowy-IO/AppFlowy/issues/3263
testWidgets(
'paste the image from clipboard when html and image are both available',
(tester) async {
const html =
'''<meta charset='utf-8'><img src="https://user-images.githubusercontent.com/9403740/262918875-603f4adb-58dd-49b5-8201-341d354935fd.png" alt="image"/>''';
final image = await rootBundle.load('assets/test/images/sample.png');
final bytes = image.buffer.asUint8List();
await tester.pasteContent(
html: html,
image: ('png', bytes),
(editorState) {
expect(editorState.document.root.children.length, 1);
final node = editorState.getNodeAtPath([0])!;
expect(node.type, ImageBlockKeys.type);
},
);
},
);
// Set the selection to the second numbered list node (which has empty delta)
transaction.afterSelection = Selection(
start: Position(path: [0], offset: 7),
end: Position(path: [0], offset: 11),
);
testWidgets('paste the html content contains section', (tester) async {
const html =
'''<meta charset='utf-8'><section style="margin: 0px 8px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgba(255, 255, 255, 0.6); font-family: system-ui, -apple-system, &quot;system-ui&quot;, &quot;Helvetica Neue&quot;, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei UI&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 15px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: 0.544px; orphans: 2; text-align: justify; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(25, 25, 25); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><span style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgb(0, 160, 113);"><strong style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important;">AppFlowy</strong></span></section><section style="margin: 0px 8px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgba(255, 255, 255, 0.6); font-family: system-ui, -apple-system, &quot;system-ui&quot;, &quot;Helvetica Neue&quot;, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei UI&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 15px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: 0.544px; orphans: 2; text-align: justify; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(25, 25, 25); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><span style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgb(0, 160, 113);"><strong style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important;">Hello World</strong></span></section>''';
await tester.pasteContent(html: html, (editorState) {
expect(editorState.document.root.children.length, 2);
final node1 = editorState.getNodeAtPath([0])!;
final node2 = editorState.getNodeAtPath([1])!;
expect(node1.type, ParagraphBlockKeys.type);
expect(node2.type, ParagraphBlockKeys.type);
});
});
testWidgets('paste the html from google translation', (tester) async {
const html =
'''<meta charset='utf-8'><section style="margin: 0px 8px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgba(255, 255, 255, 0.6); font-family: system-ui, -apple-system, &quot;system-ui&quot;, &quot;Helvetica Neue&quot;, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei UI&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 15px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: 0.544px; orphans: 2; text-align: justify; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(25, 25, 25); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><span style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgb(0, 160, 113);"><strong style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important;"><font style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; vertical-align: inherit;"><font style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; vertical-align: inherit;">new force</font></font></strong></span></section><section style="margin: 0px 8px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgba(255, 255, 255, 0.6); font-family: system-ui, -apple-system, &quot;system-ui&quot;, &quot;Helvetica Neue&quot;, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei UI&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 15px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: 0.544px; orphans: 2; text-align: justify; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(25, 25, 25); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><span style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgb(0, 160, 113);"><strong style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important;"><font style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; vertical-align: inherit;"><font style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; vertical-align: inherit;">Assessment focus: potential motivations, empathy</font></font></strong></span></section><section style="margin: 0px 8px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgba(255, 255, 255, 0.6); font-family: system-ui, -apple-system, &quot;system-ui&quot;, &quot;Helvetica Neue&quot;, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei UI&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 15px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: 0.544px; orphans: 2; text-align: justify; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(25, 25, 25); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><br style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important;"></section><section style="margin: 0px 8px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgba(255, 255, 255, 0.6); font-family: system-ui, -apple-system, &quot;system-ui&quot;, &quot;Helvetica Neue&quot;, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei UI&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 15px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: 0.544px; orphans: 2; text-align: justify; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(25, 25, 25); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><font style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-Line truncated
await tester.pasteContent(html: html, (editorState) {
expect(editorState.document.root.children.length, 8);
});
});
testWidgets(
'auto convert url to link preview block',
(tester) async {
const url = 'https://appflowy.io';
await tester.pasteContent(plainText: url, (editorState) async {
// the second one is the paragraph node
expect(editorState.document.root.children.length, 2);
final node = editorState.getNodeAtPath([0])!;
expect(node.type, LinkPreviewBlockKeys.type);
expect(node.attributes[LinkPreviewBlockKeys.url], url);
});
// hover on the link preview block
// click the more button
// and select convert to link
await tester.hoverOnWidget(
find.byType(CustomLinkPreviewWidget),
onHover: () async {
final convertToLinkButton = find.byWidgetPredicate((widget) {
return widget is MenuBlockButton &&
widget.tooltip ==
LocaleKeys.document_plugins_urlPreview_convertToLink.tr();
});
expect(convertToLinkButton, findsOneWidget);
await tester.tap(convertToLinkButton);
await editorState.apply(transaction);
await tester.pumpAndSettle();
},
(editorState) {
final node = editorState.getNodeAtPath([0]);
expect(node?.delta?.toPlainText(), 'bullet test');
expect(node?.type, BulletedListBlockKeys.type);
},
);
});
await tester.pumpAndSettle();
final editorState = tester.editor.getCurrentEditorState();
final textNode = editorState.getNodeAtPath([0])!;
expect(textNode.type, ParagraphBlockKeys.type);
expect(textNode.delta!.toJson(), [
{
'insert': url,
'attributes': {'href': url},
}
]);
},
);
testWidgets(
'ctrl/cmd+z to undo the auto convert url to link preview block',
(tester) async {
const url = 'https://appflowy.io';
await tester.pasteContent(plainText: url, (editorState) async {
// the second one is the paragraph node
expect(editorState.document.root.children.length, 2);
testWidgets('paste image(png) from memory', (tester) async {
final image = await rootBundle.load('assets/test/images/sample.png');
final bytes = image.buffer.asUint8List();
await tester.pasteContent(image: ('png', bytes), (editorState) {
expect(editorState.document.root.children.length, 1);
final node = editorState.getNodeAtPath([0])!;
expect(node.type, LinkPreviewBlockKeys.type);
expect(node.attributes[LinkPreviewBlockKeys.url], url);
expect(node.type, ImageBlockKeys.type);
expect(node.attributes[ImageBlockKeys.url], isNotNull);
});
await tester.editor.tapLineOfEditorAt(0);
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyZ,
isControlPressed:
UniversalPlatform.isLinux || UniversalPlatform.isWindows,
isMetaPressed: UniversalPlatform.isMacOS,
);
await tester.pumpAndSettle();
final editorState = tester.editor.getCurrentEditorState();
final node = editorState.getNodeAtPath([0])!;
expect(node.type, ParagraphBlockKeys.type);
expect(node.delta!.toJson(), [
{
'insert': url,
'attributes': {'href': url},
}
]);
},
);
testWidgets(
'paste the nodes start with non-delta node',
(tester) async {
await tester.pasteContent((_) {});
const text = 'Hello World';
final editorState = tester.editor.getCurrentEditorState();
final transaction = editorState.transaction;
// [image_block]
// [paragraph_block]
transaction.insertNodes([
0,
], [
customImageNode(url: ''),
paragraphNode(text: text),
]);
await editorState.apply(transaction);
await tester.pumpAndSettle();
await tester.editor.tapLineOfEditorAt(0);
// select all and copy
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyA,
isControlPressed:
UniversalPlatform.isLinux || UniversalPlatform.isWindows,
isMetaPressed: UniversalPlatform.isMacOS,
);
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyC,
isControlPressed:
UniversalPlatform.isLinux || UniversalPlatform.isWindows,
isMetaPressed: UniversalPlatform.isMacOS,
);
// put the cursor to the end of the paragraph block
await tester.editor.tapLineOfEditorAt(0);
// paste the content
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyV,
isControlPressed:
UniversalPlatform.isLinux || UniversalPlatform.isWindows,
isMetaPressed: UniversalPlatform.isMacOS,
);
await tester.pumpAndSettle();
// expect the image and the paragraph block are inserted below the cursor
expect(editorState.getNodeAtPath([0])!.type, CustomImageBlockKeys.type);
expect(editorState.getNodeAtPath([1])!.type, ParagraphBlockKeys.type);
expect(editorState.getNodeAtPath([2])!.type, CustomImageBlockKeys.type);
expect(editorState.getNodeAtPath([3])!.type, ParagraphBlockKeys.type);
},
);
testWidgets('paste the url without protocol', (tester) async {
// paste the image that from local file
const plainText = '1.jpg';
final image = await rootBundle.load('assets/test/images/sample.jpeg');
final bytes = image.buffer.asUint8List();
await tester.pasteContent(plainText: plainText, image: ('jpeg', bytes),
(editorState) {
final node = editorState.getNodeAtPath([0])!;
expect(node.type, ImageBlockKeys.type);
expect(node.attributes[ImageBlockKeys.url], isNotEmpty);
});
});
testWidgets('paste the image url', (tester) async {
const plainText = 'https://appflowy.io/1.jpg';
final image = await rootBundle.load('assets/test/images/sample.jpeg');
final bytes = image.buffer.asUint8List();
await tester.pasteContent(plainText: plainText, image: ('jpeg', bytes),
(editorState) {
final node = editorState.getNodeAtPath([0])!;
expect(node.type, ImageBlockKeys.type);
expect(node.attributes[ImageBlockKeys.url], isNotEmpty);
testWidgets('paste image(jpeg) from memory', (tester) async {
final image = await rootBundle.load('assets/test/images/sample.jpeg');
final bytes = image.buffer.asUint8List();
await tester.pasteContent(image: ('jpeg', bytes), (editorState) {
expect(editorState.document.root.children.length, 1);
final node = editorState.getNodeAtPath([0])!;
expect(node.type, ImageBlockKeys.type);
expect(node.attributes[ImageBlockKeys.url], isNotNull);
});
});
});
const testMarkdownText = '''
testWidgets('paste image(gif) from memory', (tester) async {
final image = await rootBundle.load('assets/test/images/sample.gif');
final bytes = image.buffer.asUint8List();
await tester.pasteContent(image: ('gif', bytes), (editorState) {
expect(editorState.document.root.children.length, 1);
final node = editorState.getNodeAtPath([0])!;
expect(node.type, ImageBlockKeys.type);
expect(node.attributes[ImageBlockKeys.url], isNotNull);
});
});
testWidgets(
'format the selected text to href when pasting url if available',
(tester) async {
const text = 'appflowy';
const url = 'https://appflowy.io';
await tester.pasteContent(
plainText: url,
beforeTest: (editorState) async {
await tester.ime.insertText(text);
await tester.editor.updateSelection(
Selection.single(
path: [0],
startOffset: 0,
endOffset: text.length,
),
);
},
(editorState) {
final node = editorState.getNodeAtPath([0])!;
expect(node.type, ParagraphBlockKeys.type);
expect(node.delta!.toJson(), [
{
'insert': text,
'attributes': {'href': url},
}
]);
},
);
},
);
// https://github.com/AppFlowy-IO/AppFlowy/issues/3263
testWidgets(
'paste the image from clipboard when html and image are both available',
(tester) async {
const html =
'''<meta charset='utf-8'><img src="https://user-images.githubusercontent.com/9403740/262918875-603f4adb-58dd-49b5-8201-341d354935fd.png" alt="image"/>''';
final image = await rootBundle.load('assets/test/images/sample.png');
final bytes = image.buffer.asUint8List();
await tester.pasteContent(
html: html,
image: ('png', bytes),
(editorState) {
expect(editorState.document.root.children.length, 1);
final node = editorState.getNodeAtPath([0])!;
expect(node.type, ImageBlockKeys.type);
},
);
},
);
testWidgets('paste the html content contains section', (tester) async {
const html =
'''<meta charset='utf-8'><section style="margin: 0px 8px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgba(255, 255, 255, 0.6); font-family: system-ui, -apple-system, &quot;system-ui&quot;, &quot;Helvetica Neue&quot;, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei UI&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 15px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: 0.544px; orphans: 2; text-align: justify; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(25, 25, 25); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><span style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgb(0, 160, 113);"><strong style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important;">AppFlowy</strong></span></section><section style="margin: 0px 8px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgba(255, 255, 255, 0.6); font-family: system-ui, -apple-system, &quot;system-ui&quot;, &quot;Helvetica Neue&quot;, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei UI&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 15px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: 0.544px; orphans: 2; text-align: justify; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(25, 25, 25); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><span style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgb(0, 160, 113);"><strong style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important;">Hello World</strong></span></section>''';
await tester.pasteContent(html: html, (editorState) {
expect(editorState.document.root.children.length, 2);
final node1 = editorState.getNodeAtPath([0])!;
final node2 = editorState.getNodeAtPath([1])!;
expect(node1.type, ParagraphBlockKeys.type);
expect(node2.type, ParagraphBlockKeys.type);
});
});
testWidgets('paste the html from google translation', (tester) async {
const html =
'''<meta charset='utf-8'><section style="margin: 0px 8px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgba(255, 255, 255, 0.6); font-family: system-ui, -apple-system, &quot;system-ui&quot;, &quot;Helvetica Neue&quot;, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei UI&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 15px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: 0.544px; orphans: 2; text-align: justify; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(25, 25, 25); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><span style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgb(0, 160, 113);"><strong style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important;"><font style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; vertical-align: inherit;"><font style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; vertical-align: inherit;">new force</font></font></strong></span></section><section style="margin: 0px 8px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgba(255, 255, 255, 0.6); font-family: system-ui, -apple-system, &quot;system-ui&quot;, &quot;Helvetica Neue&quot;, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei UI&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 15px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: 0.544px; orphans: 2; text-align: justify; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(25, 25, 25); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><span style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgb(0, 160, 113);"><strong style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important;"><font style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; vertical-align: inherit;"><font style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; vertical-align: inherit;">Assessment focus: potential motivations, empathy</font></font></strong></span></section><section style="margin: 0px 8px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgba(255, 255, 255, 0.6); font-family: system-ui, -apple-system, &quot;system-ui&quot;, &quot;Helvetica Neue&quot;, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei UI&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 15px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: 0.544px; orphans: 2; text-align: justify; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(25, 25, 25); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><br style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important;"></section><section style="margin: 0px 8px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important; color: rgba(255, 255, 255, 0.6); font-family: system-ui, -apple-system, &quot;system-ui&quot;, &quot;Helvetica Neue&quot;, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei UI&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 15px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: 0.544px; orphans: 2; text-align: justify; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(25, 25, 25); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><font style="margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: bordeLine truncated
await tester.pasteContent(html: html, (editorState) {
expect(editorState.document.root.children.length, 8);
});
});
testWidgets(
'auto convert url to link preview block',
(tester) async {
const url = 'https://appflowy.io';
await tester.pasteContent(plainText: url, (editorState) async {
// the second one is the paragraph node
expect(editorState.document.root.children.length, 2);
final node = editorState.getNodeAtPath([0])!;
expect(node.type, LinkPreviewBlockKeys.type);
expect(node.attributes[LinkPreviewBlockKeys.url], url);
});
// hover on the link preview block
// click the more button
// and select convert to link
await tester.hoverOnWidget(
find.byType(CustomLinkPreviewWidget),
onHover: () async {
final convertToLinkButton = find.byWidgetPredicate((widget) {
return widget is MenuBlockButton &&
widget.tooltip ==
LocaleKeys.document_plugins_urlPreview_convertToLink.tr();
});
expect(convertToLinkButton, findsOneWidget);
await tester.tap(convertToLinkButton);
await tester.pumpAndSettle();
},
);
await tester.pumpAndSettle();
final editorState = tester.editor.getCurrentEditorState();
final textNode = editorState.getNodeAtPath([0])!;
expect(textNode.type, ParagraphBlockKeys.type);
expect(textNode.delta!.toJson(), [
{
'insert': url,
'attributes': {'href': url},
}
]);
},
);
testWidgets(
'ctrl/cmd+z to undo the auto convert url to link preview block',
(tester) async {
const url = 'https://appflowy.io';
await tester.pasteContent(plainText: url, (editorState) async {
// the second one is the paragraph node
expect(editorState.document.root.children.length, 2);
final node = editorState.getNodeAtPath([0])!;
expect(node.type, LinkPreviewBlockKeys.type);
expect(node.attributes[LinkPreviewBlockKeys.url], url);
});
await tester.editor.tapLineOfEditorAt(0);
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyZ,
isControlPressed:
UniversalPlatform.isLinux || UniversalPlatform.isWindows,
isMetaPressed: UniversalPlatform.isMacOS,
);
await tester.pumpAndSettle();
final editorState = tester.editor.getCurrentEditorState();
final node = editorState.getNodeAtPath([0])!;
expect(node.type, ParagraphBlockKeys.type);
expect(node.delta!.toJson(), [
{
'insert': url,
'attributes': {'href': url},
}
]);
},
);
testWidgets(
'paste the nodes start with non-delta node',
(tester) async {
await tester.pasteContent((_) {});
const text = 'Hello World';
final editorState = tester.editor.getCurrentEditorState();
final transaction = editorState.transaction;
// [image_block]
// [paragraph_block]
transaction.insertNodes([
0,
], [
customImageNode(url: ''),
paragraphNode(text: text),
]);
await editorState.apply(transaction);
await tester.pumpAndSettle();
await tester.editor.tapLineOfEditorAt(0);
// select all and copy
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyA,
isControlPressed:
UniversalPlatform.isLinux || UniversalPlatform.isWindows,
isMetaPressed: UniversalPlatform.isMacOS,
);
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyC,
isControlPressed:
UniversalPlatform.isLinux || UniversalPlatform.isWindows,
isMetaPressed: UniversalPlatform.isMacOS,
);
// put the cursor to the end of the paragraph block
await tester.editor.tapLineOfEditorAt(0);
// paste the content
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyV,
isControlPressed:
UniversalPlatform.isLinux || UniversalPlatform.isWindows,
isMetaPressed: UniversalPlatform.isMacOS,
);
await tester.pumpAndSettle();
// expect the image and the paragraph block are inserted below the cursor
expect(editorState.getNodeAtPath([0])!.type, CustomImageBlockKeys.type);
expect(editorState.getNodeAtPath([1])!.type, ParagraphBlockKeys.type);
expect(editorState.getNodeAtPath([2])!.type, CustomImageBlockKeys.type);
expect(editorState.getNodeAtPath([3])!.type, ParagraphBlockKeys.type);
},
);
testWidgets('paste the url without protocol', (tester) async {
// paste the image that from local file
const plainText = '1.jpg';
final image = await rootBundle.load('assets/test/images/sample.jpeg');
final bytes = image.buffer.asUint8List();
await tester.pasteContent(plainText: plainText, image: ('jpeg', bytes),
(editorState) {
final node = editorState.getNodeAtPath([0])!;
expect(node.type, ImageBlockKeys.type);
expect(node.attributes[ImageBlockKeys.url], isNotEmpty);
});
});
testWidgets('paste the image url', (tester) async {
const plainText = 'https://appflowy.io/1.jpg';
final image = await rootBundle.load('assets/test/images/sample.jpeg');
final bytes = image.buffer.asUint8List();
await tester.pasteContent(plainText: plainText, image: ('jpeg', bytes),
(editorState) {
final node = editorState.getNodeAtPath([0])!;
expect(node.type, ImageBlockKeys.type);
expect(node.attributes[ImageBlockKeys.url], isNotEmpty);
});
});
testWidgets('paste image url without extension', (tester) async {
const plainText =
'https://images.unsplash.com/photo-1469474968028-56623f02e42e?ixlib=rb-4.0.3&q=85&fm=jpg&crop=entropy&cs=srgb&dl=david-marcu-78A265wPiO4-unsplash.jpg&w=640';
await tester.pasteContent(plainText: plainText, (editorState) {
final node = editorState.getNodeAtPath([0])!;
expect(node.type, ImageBlockKeys.type);
expect(node.attributes[ImageBlockKeys.url], isNotEmpty);
});
});
const testMarkdownText = '''
# I'm h1
## I'm h2
### I'm h3
@@ -478,34 +487,35 @@ void main() {
##### I'm h5
###### I'm h6''';
testWidgets('paste markdowns', (tester) async {
await tester.pasteContent(
plainText: testMarkdownText,
(editorState) {
final children = editorState.document.root.children;
expect(children.length, 6);
for (int i = 1; i <= children.length; i++) {
final text = children[i - 1].delta!.toPlainText();
expect(text, 'I\'m h$i');
}
},
);
});
testWidgets('paste markdowns', (tester) async {
await tester.pasteContent(
plainText: testMarkdownText,
(editorState) {
final children = editorState.document.root.children;
expect(children.length, 6);
for (int i = 1; i <= children.length; i++) {
final text = children[i - 1].delta!.toPlainText();
expect(text, 'I\'m h$i');
}
},
);
});
testWidgets('paste markdowns as plain', (tester) async {
await tester.pasteContent(
plainText: testMarkdownText,
pasteAsPlain: true,
(editorState) {
final children = editorState.document.root.children;
expect(children.length, 6);
for (int i = 1; i <= children.length; i++) {
final text = children[i - 1].delta!.toPlainText();
final expectText = '${'#' * i} I\'m h$i';
expect(text, expectText);
}
},
);
testWidgets('paste markdowns as plain', (tester) async {
await tester.pasteContent(
plainText: testMarkdownText,
pasteAsPlain: true,
(editorState) {
final children = editorState.document.root.children;
expect(children.length, 6);
for (int i = 1; i <= children.length; i++) {
final text = children[i - 1].delta!.toPlainText();
final expectText = '${'#' * i} I\'m h$i';
expect(text, expectText);
}
},
);
});
});
}
@@ -523,7 +533,7 @@ extension on WidgetTester {
await tapAnonymousSignInButton();
// create a new document
await createNewPageWithNameUnderParent(name: 'Test Document');
await createNewPageWithNameUnderParent();
// tap the editor
await tapButton(find.byType(AppFlowyEditor));
@@ -546,7 +556,7 @@ extension on WidgetTester {
isShiftPressed: pasteAsPlain,
isMetaPressed: Platform.isMacOS,
);
await pumpAndSettle();
await pumpAndSettle(const Duration(milliseconds: 1000));
test(editor.getCurrentEditorState());
}
@@ -1,3 +1,5 @@
import 'dart:io';
import 'package:appflowy/plugins/base/emoji/emoji_picker.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/base/emoji_picker_button.dart';
import 'package:appflowy/shared/icon_emoji_picker/flowy_icon_emoji_picker.dart';
@@ -5,8 +7,11 @@ import 'package:appflowy/shared/icon_emoji_picker/recent_icons.dart';
import 'package:appflowy/workspace/presentation/widgets/view_title_bar.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:flowy_infra_ui/style_widget/text_field.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import '../../shared/base.dart';
import '../../shared/common_operations.dart';
@@ -209,4 +214,49 @@ void main() {
);
}
});
testWidgets('Update page custom icon in title bar', (tester) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
/// prepare local image
final imagePath = await rootBundle.load('assets/test/images/sample.jpeg');
final tempDirectory = await getTemporaryDirectory();
final localImagePath = p.join(tempDirectory.path, 'sample.jpeg');
final imageFile = File(localImagePath)
..writeAsBytesSync(imagePath.buffer.asUint8List());
final iconData = EmojiIconData.custom(imageFile.path);
// create document, board, grid and calendar views
for (final value in ViewLayoutPB.values) {
if (value == ViewLayoutPB.Chat) {
continue;
}
await tester.createNewPageWithNameUnderParent(
name: value.name,
parentName: gettingStarted,
layout: value,
);
// update its icon
await tester.updatePageIconInTitleBarByName(
name: value.name,
layout: value,
icon: iconData,
);
tester.expectViewHasIcon(
value.name,
value,
iconData,
);
tester.expectViewTitleHasIcon(
value.name,
value,
iconData,
);
}
});
}
@@ -1,9 +1,10 @@
import 'package:integration_test/integration_test.dart';
import 'desktop/uncategorized/tabs_test.dart' as tabs_test;
import 'desktop/database/database_icon_test.dart' as database_icon_test;
import 'desktop/first_test/first_test.dart' as first_test;
import 'desktop/uncategorized/code_block_language_selector_test.dart'
as code_language_selector;
import 'desktop/first_test/first_test.dart' as first_test;
import 'desktop/uncategorized/tabs_test.dart' as tabs_test;
Future<void> main() async {
await runIntegration9OnDesktop();
@@ -15,4 +16,5 @@ Future<void> runIntegration9OnDesktop() async {
first_test.main();
tabs_test.main();
code_language_selector.main();
database_icon_test.main();
}
@@ -0,0 +1,65 @@
import 'dart:io';
import 'package:appflowy/mobile/presentation/base/view_page/app_bar_buttons.dart';
import 'package:appflowy/mobile/presentation/presentation.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/header/emoji_icon_widget.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/page_style/_page_style_icon.dart';
import 'package:appflowy/shared/icon_emoji_picker/flowy_icon_emoji_picker.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import '../../shared/emoji.dart';
import '../../shared/util.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('document title:', () {
testWidgets('update page custom icon in title bar', (tester) async {
await tester.launchInAnonymousMode();
/// prepare local image
final imagePath = await rootBundle.load('assets/test/images/sample.jpeg');
final tempDirectory = await getTemporaryDirectory();
final localImagePath = p.join(tempDirectory.path, 'sample.jpeg');
final imageFile = File(localImagePath)
..writeAsBytesSync(imagePath.buffer.asUint8List());
final iconData = EmojiIconData.custom(imageFile.path);
/// create an empty page
await tester
.tapButton(find.byKey(BottomNavigationBarItemType.add.valueKey));
/// show Page style page
await tester.tapButton(find.byType(MobileViewPageLayoutButton));
final pageStyleIcon = find.byType(PageStyleIcon);
final iconInPageStyleIcon = find.descendant(
of: pageStyleIcon,
matching: find.byType(RawEmojiIconWidget),
);
expect(iconInPageStyleIcon, findsNothing);
/// show icon picker
await tester.tapButton(pageStyleIcon);
/// upload custom icon
await tester.pickImage(iconData);
/// check result
final documentPage = find.byType(MobileDocumentScreen);
final rawEmojiIconWidget = find
.descendant(
of: documentPage,
matching: find.byType(RawEmojiIconWidget),
)
.evaluate()
.first
.widget as RawEmojiIconWidget;
final iconDataInWidget = rawEmojiIconWidget.emoji;
expect(iconDataInWidget.type, FlowyIconType.custom);
});
});
}
@@ -0,0 +1,48 @@
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/mobile/presentation/home/setting/settings_popup_menu.dart';
import 'package:appflowy/workspace/presentation/home/hotkeys.dart';
import 'package:appflowy/workspace/presentation/widgets/more_view_actions/widgets/font_size_stepper.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import '../../shared/util.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('test for change scale factor', (tester) async {
await tester.launchInAnonymousMode();
/// tap [Setting] button
await tester.tapButton(find.byType(HomePageSettingsPopupMenu));
await tester
.tapButton(find.text(LocaleKeys.settings_popupMenuItem_settings.tr()));
/// tap [Font Scale Factor]
await tester.tapButton(
find.text(LocaleKeys.settings_appearance_fontScaleFactor.tr()),
);
/// drag slider
final slider = find.descendant(
of: find.byType(FontSizeStepper),
matching: find.byType(Slider),
);
await tester.slideToValue(slider, 0.8);
expect(appflowyScaleFactor, 0.8);
await tester.slideToValue(slider, 0.9);
expect(appflowyScaleFactor, 0.9);
await tester.slideToValue(slider, 1.0);
expect(appflowyScaleFactor, 1.0);
await tester.slideToValue(slider, 1.1);
expect(appflowyScaleFactor, 1.1);
await tester.slideToValue(slider, 1.2);
expect(appflowyScaleFactor, 1.2);
});
}
@@ -13,6 +13,7 @@ import 'package:appflowy/workspace/application/settings/prelude.dart';
import 'package:flowy_infra/uuid.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
@@ -235,6 +236,25 @@ extension AppFlowyTestBase on WidgetTester {
Future<void> wait(int milliseconds) async {
await pumpAndSettle(Duration(milliseconds: milliseconds));
}
Future<void> slideToValue(
Finder slider,
double value, {
double paddingOffset = 24.0,
}) async {
final sliderWidget = slider.evaluate().first.widget as Slider;
final range = sliderWidget.max - sliderWidget.min;
final initialRate = (value - sliderWidget.min) / range;
final totalWidth = getSize(slider).width - (2 * paddingOffset);
final zeroPoint = getTopLeft(slider) +
Offset(
paddingOffset + initialRate * totalWidth,
getSize(slider).height / 2,
);
final calculatedOffset = value * (totalWidth / 100);
await dragFrom(zeroPoint, Offset(calculatedOffset, 0));
await pumpAndSettle();
}
}
extension AppFlowyFinderTestBase on CommonFinders {
@@ -671,6 +671,8 @@ extension CommonOperations on WidgetTester {
await tapEmoji(icon.emoji);
} else if (icon.type == FlowyIconType.icon) {
await tapIcon(icon);
} else if (icon.type == FlowyIconType.custom) {
await pickImage(icon);
}
await pumpAndSettle();
}
@@ -3,8 +3,12 @@ import 'dart:convert';
import 'package:appflowy/shared/icon_emoji_picker/flowy_icon_emoji_picker.dart';
import 'package:appflowy/shared/icon_emoji_picker/icon_color_picker.dart';
import 'package:appflowy/shared/icon_emoji_picker/icon_picker.dart';
import 'package:appflowy/shared/icon_emoji_picker/icon_uploader.dart';
import 'package:appflowy/shared/icon_emoji_picker/tab.dart';
import 'package:appflowy/workspace/presentation/home/menu/sidebar/space/space_icon_popup.dart';
import 'package:cross_file/cross_file.dart';
import 'package:desktop_drop/desktop_drop.dart';
import 'package:flowy_infra_ui/style_widget/primary_rounded_button.dart';
import 'package:flowy_svg/flowy_svg.dart';
import 'package:flutter/material.dart';
import 'package:flutter_emoji_mart/flutter_emoji_mart.dart';
@@ -21,7 +25,7 @@ extension EmojiTestExtension on WidgetTester {
await tapButton(emojiWidget);
}
Future<void> tapIcon(EmojiIconData icon) async {
Future<void> tapIcon(EmojiIconData icon, {bool enableColor = true}) async {
final iconsData = IconsData.fromJson(jsonDecode(icon.emoji));
final pickTab = find.byType(PickerTab);
expect(pickTab, findsOneWidget);
@@ -40,23 +44,64 @@ extension EmojiTestExtension on WidgetTester {
);
await tapButton(selectedSvg.first);
final colorPicker = find.byType(IconColorPicker);
expect(colorPicker, findsOneWidget);
final selectedColor = find.descendant(
of: colorPicker,
matching: find.byWidgetPredicate((w) {
if (w is Container) {
final d = w.decoration;
if (d is ShapeDecoration) {
if (d.color ==
Color(int.parse(iconsData.color ?? builtInSpaceColors.first))) {
return true;
if (enableColor) {
final colorPicker = find.byType(IconColorPicker);
expect(colorPicker, findsOneWidget);
final selectedColor = find.descendant(
of: colorPicker,
matching: find.byWidgetPredicate((w) {
if (w is Container) {
final d = w.decoration;
if (d is ShapeDecoration) {
if (d.color ==
Color(
int.parse(iconsData.color ?? builtInSpaceColors.first),
)) {
return true;
}
}
}
}
return false;
}),
return false;
}),
);
await tapButton(selectedColor);
}
}
Future<void> pickImage(EmojiIconData icon) async {
final pickTab = find.byType(PickerTab);
expect(pickTab, findsOneWidget);
await pumpAndSettle();
/// switch to custom tab
final iconTab = find.descendant(
of: pickTab,
matching: find.text(PickerTabType.custom.tr),
);
await tapButton(selectedColor);
expect(iconTab, findsOneWidget);
await tapButton(iconTab);
/// mock for dragging image
final dropTarget = find.descendant(
of: find.byType(IconUploader),
matching: find.byType(DropTarget),
);
expect(dropTarget, findsOneWidget);
final dropTargetWidget = dropTarget.evaluate().first.widget as DropTarget;
dropTargetWidget.onDragDone?.call(
DropDoneDetails(
files: [XFile(icon.emoji)],
localPosition: Offset.zero,
globalPosition: Offset.zero,
),
);
await pumpAndSettle(const Duration(seconds: 3));
/// confirm to upload
final confirmButton = find.descendant(
of: find.byType(IconUploader),
matching: find.byType(PrimaryRoundedButton),
);
await tapButton(confirmButton);
}
}
@@ -7,6 +7,7 @@ import 'package:appflowy/plugins/database/widgets/row/row_detail.dart';
import 'package:appflowy/plugins/document/presentation/banner.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/header/document_cover_widget.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/header/emoji_icon_widget.dart';
import 'package:appflowy/shared/appflowy_network_image.dart';
import 'package:appflowy/shared/icon_emoji_picker/flowy_icon_emoji_picker.dart';
import 'package:appflowy/shared/icon_emoji_picker/icon_picker.dart';
import 'package:appflowy/workspace/application/sidebar/folder/folder_bloc.dart';
@@ -21,6 +22,7 @@ import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_svg/flowy_svg.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:string_validator/string_validator.dart';
import 'package:universal_platform/universal_platform.dart';
import 'util.dart';
@@ -249,6 +251,20 @@ extension Expectation on WidgetTester {
),
);
expect(icon, findsOneWidget);
} else if (type == FlowyIconType.custom) {
if (isURL(data.emoji)) {
final image = find.descendant(
of: pageName,
matching: find.byType(FlowyNetworkImage),
);
expect(image, findsOneWidget);
} else {
final image = find.descendant(
of: pageName,
matching: find.byType(Image),
);
expect(image, findsOneWidget);
}
}
}
@@ -273,6 +289,20 @@ extension Expectation on WidgetTester {
),
);
expect(icon, findsOneWidget);
} else if (type == FlowyIconType.custom) {
if (isURL(data.emoji)) {
final image = find.descendant(
of: find.byType(ViewTitleBar),
matching: find.byType(FlowyNetworkImage),
);
expect(image, findsOneWidget);
} else {
final image = find.descendant(
of: find.byType(ViewTitleBar),
matching: find.byType(Image),
);
expect(image, findsOneWidget);
}
}
}
@@ -1,9 +1,9 @@
import 'dart:async';
import 'dart:convert';
import 'package:appflowy/ai/error.dart';
import 'package:appflowy/ai/openai_client.dart';
import 'package:appflowy/ai/text_completion.dart';
import 'package:appflowy/ai/service/error.dart';
import 'package:appflowy/ai/service/openai_client.dart';
import 'package:appflowy/ai/service/text_completion.dart';
import 'package:http/http.dart' as http;
import 'package:mocktail/mocktail.dart';
+22 -22
View File
@@ -175,36 +175,36 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/webview_flutter_wkwebview/ios"
SPEC CHECKSUMS:
app_links: e70ca16b4b0f88253b3b3660200d4a10b4ea9795
appflowy_backend: 144c20d8bfb298c4e10fa3fa6701a9f41bf98b88
connectivity_plus: bf0076dd84a130856aa636df1c71ccaff908fa1d
device_info_plus: 97af1d7e84681a90d0693e63169a5d50e0839a0d
app_links: c5161ac5ab5383ad046884568b4b91cb52df5d91
appflowy_backend: 78f6a053f756e6bc29bcc5a2106cbe77b756e97a
connectivity_plus: 481668c94744c30c53b8895afb39159d1e619bdf
device_info_plus: 71ffc6ab7634ade6267c7a93088ed7e4f74e5896
DKImagePickerController: b512c28220a2b8ac7419f21c491fc8534b7601ac
DKPhotoGallery: fdfad5125a9fdda9cc57df834d49df790dbb4179
file_picker: 09aa5ec1ab24135ccd7a1621c46c84134bfd6655
flowy_infra_ui: 0455e1fa8c51885aa1437848e361e99419f34ebc
file_picker: 9b3292d7c8bc68c8a7bf8eb78f730e49c8efc517
flowy_infra_ui: 931b73a18b54a392ab6152eebe29a63a30751f53
Flutter: e0871f40cf51350855a761d2e70bf5af5b9b5de7
fluttertoast: e9a18c7be5413da53898f660530c56f35edfba9c
image_picker_ios: c560581cceedb403a6ff17f2f816d7fea1421fc1
integration_test: ce0a3ffa1de96d1a89ca0ac26fca7ea18a749ef4
irondash_engine_context: 3458bf979b90d616ffb8ae03a150bafe2e860cc9
keyboard_height_plugin: 43fa8bba20fd5c4fdeed5076466b8b9d43cc6b86
open_filex: 6e26e659846ec990262224a12ef1c528bb4edbe4
package_info_plus: c0502532a26c7662a62a356cebe2692ec5fe4ec4
path_provider_foundation: 2b6b4c569c0fb62ec74538f866245ac84301af46
permission_handler_apple: 9878588469a2b0d0fc1e048d9f43605f92e6cec2
fluttertoast: 76fea30fcf04176325f6864c87306927bd7d2038
image_picker_ios: 7fe1ff8e34c1790d6fff70a32484959f563a928a
integration_test: d5929033778cc4991a187e4e1a85396fa4f59b3a
irondash_engine_context: 8e58ca8e0212ee9d1c7dc6a42121849986c88486
keyboard_height_plugin: ef70a8181b29f27670e9e2450814ca6b6dc05b05
open_filex: 432f3cd11432da3e39f47fcc0df2b1603854eff1
package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
path_provider_foundation: 080d55be775b7414fd5a5ef3ac137b97b097e564
permission_handler_apple: 4ed2196e43d0651e8ff7ca3483a069d469701f2d
ReachabilitySwift: 985039c6f7b23a1da463388634119492ff86c825
SDWebImage: b9a731e1d6307f44ca703b3976d18c24ca561e84
Sentry: 1fe34e9c2cbba1e347623610d26db121dcb569f1
sentry_flutter: a39c2a2d67d5e5b9cb0b94a4985c76dd5b3fc737
share_plus: 8b6f8b3447e494cca5317c8c3073de39b3600d1f
shared_preferences_foundation: fcdcbc04712aee1108ac7fda236f363274528f78
sqflite: 673a0e54cc04b7d6dba8d24fb8095b31c3a99eec
super_native_extensions: 4916b3c627a9c7fffdc48a23a9eca0b1ac228fa7
sentry_flutter: e24b397f9a61fa5bbefd8279c3b2242ca86faa90
share_plus: 50da8cb520a8f0f65671c6c6a99b3617ed10a58a
shared_preferences_foundation: 9e1978ff2562383bd5676f64ec4e9aa8fa06a6f7
sqflite: c35dad70033b8862124f8337cc994a809fcd9fa3
super_native_extensions: b763c02dc3a8fd078389f410bf15149179020cb4
SwiftyGif: 6c3eafd0ce693cad58bb63d2b2fb9bacb8552780
Toast: 91b396c56ee72a5790816f40d3a94dd357abc196
url_launcher_ios: 5334b05cef931de560670eeae103fd3e431ac3fe
webview_flutter_wkwebview: 2a23822e9039b7b1bc52e5add778e5d89ad488d1
url_launcher_ios: 694010445543906933d732453a59da0a173ae33d
webview_flutter_wkwebview: 45a041c7831641076618876de3ba75c712860c6b
PODFILE CHECKSUM: d0d9b4ff572d8695c38eb3f9b490f55cdfc57eca
+12
View File
@@ -0,0 +1,12 @@
export 'widgets/loading_indicator.dart';
export 'widgets/prompt_input/action_buttons.dart';
export 'widgets/prompt_input/desktop_input_text_field.dart';
export 'widgets/prompt_input/file_attachment_list.dart';
export 'widgets/prompt_input/layout_define.dart';
export 'widgets/prompt_input/mention_page_bottom_sheet.dart';
export 'widgets/prompt_input/mention_page_menu.dart';
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/send_button.dart';
@@ -3,7 +3,6 @@ import 'dart:ffi';
import 'dart:isolate';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
@@ -14,6 +13,41 @@ import 'ai_client.dart';
import 'error.dart';
import 'text_completion.dart';
enum AskAIAction {
summarize,
fixSpelling,
improveWriting,
makeItLonger;
String get toInstruction => switch (this) {
summarize => 'Tl;dr',
fixSpelling => 'Correct this to standard English:',
improveWriting => 'Rewrite this in your own words:',
makeItLonger => 'Make this text longer:',
};
String prompt(String input) => switch (this) {
summarize => '$input\n\n$toInstruction',
_ => "$toInstruction\n\n$input",
};
static AskAIAction from(int index) => switch (index) {
0 => summarize,
1 => fixSpelling,
2 => improveWriting,
3 => makeItLonger,
_ => fixSpelling
};
String get name => switch (this) {
summarize => LocaleKeys.document_plugins_smartEditSummarize.tr(),
fixSpelling => LocaleKeys.document_plugins_smartEditFixSpelling.tr(),
improveWriting =>
LocaleKeys.document_plugins_smartEditImproveWriting.tr(),
makeItLonger => LocaleKeys.document_plugins_smartEditMakeLonger.tr(),
};
}
class AppFlowyAIService implements AIRepository {
@override
Future<FlowyResult<List<String>, AIError>> generateImage({
@@ -105,6 +139,24 @@ class CompletionStream {
);
}
if (event == "AI_IMAGE_RESPONSE_LIMIT") {
onError(
AIError(
message: LocaleKeys.sideBar_aiImageResponseLimit.tr(),
code: AIErrorCode.aiImageResponseLimitExceeded,
),
);
}
if (event.startsWith("AI_MAX_REQUIRED:")) {
final msg = event.substring(16);
onError(
AIError(
message: msg,
),
);
}
if (event.startsWith("start:")) {
await onStart();
}
@@ -17,6 +17,8 @@ class AIError with _$AIError {
enum AIErrorCode {
@JsonValue('AIResponseLimitExceeded')
aiResponseLimitExceeded,
@JsonValue('AIImageResponseLimitExceeded')
aiImageResponseLimitExceeded,
@JsonValue('Other')
other,
}
@@ -3,8 +3,8 @@ import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
/// An animated generating indicator for an AI response
class ChatAILoading extends StatelessWidget {
const ChatAILoading({
class AILoadingIndicator extends StatelessWidget {
const AILoadingIndicator({
super.key,
this.text = "",
this.duration = const Duration(seconds: 1),
@@ -6,9 +6,7 @@ import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/style_widget/icon_button.dart';
import 'package:flowy_infra_ui/widget/flowy_tooltip.dart';
import '../layout_define.dart';
enum SendButtonState { enabled, streaming, disabled }
import 'layout_define.dart';
class PromptInputAttachmentButton extends StatelessWidget {
const PromptInputAttachmentButton({required this.onTap, super.key});
@@ -67,57 +65,3 @@ class PromptInputMentionButton extends StatelessWidget {
);
}
}
class PromptInputSendButton extends StatelessWidget {
const PromptInputSendButton({
super.key,
required this.buttonSize,
required this.iconSize,
required this.state,
required this.onSendPressed,
required this.onStopStreaming,
});
final double buttonSize;
final double iconSize;
final SendButtonState state;
final VoidCallback onSendPressed;
final VoidCallback onStopStreaming;
@override
Widget build(BuildContext context) {
return FlowyIconButton(
width: buttonSize,
icon: switch (state) {
SendButtonState.enabled => FlowySvg(
FlowySvgs.ai_send_filled_s,
size: Size.square(iconSize),
color: Theme.of(context).colorScheme.primary,
),
SendButtonState.disabled => FlowySvg(
FlowySvgs.ai_send_filled_s,
size: Size.square(iconSize),
color: Theme.of(context).disabledColor,
),
SendButtonState.streaming => FlowySvg(
FlowySvgs.ai_stop_filled_s,
size: Size.square(iconSize),
color: Theme.of(context).colorScheme.primary,
),
},
onPressed: () {
switch (state) {
case SendButtonState.enabled:
onSendPressed();
break;
case SendButtonState.streaming:
onStopStreaming();
break;
case SendButtonState.disabled:
break;
}
},
hoverColor: Colors.transparent,
);
}
}
@@ -0,0 +1,53 @@
import 'package:appflowy/plugins/ai_chat/application/chat_input_control_cubit.dart';
import 'package:appflowy/plugins/ai_chat/presentation/layout_define.dart';
import 'package:extended_text_field/extended_text_field.dart';
import 'package:flutter/material.dart';
import 'mentioned_page_text_span.dart';
class PromptInputTextField extends StatelessWidget {
const PromptInputTextField({
super.key,
required this.cubit,
required this.textController,
required this.textFieldFocusNode,
required this.contentPadding,
this.hintText = "",
});
final ChatInputControlCubit cubit;
final TextEditingController textController;
final FocusNode textFieldFocusNode;
final EdgeInsetsGeometry contentPadding;
final String hintText;
@override
Widget build(BuildContext context) {
return ExtendedTextField(
controller: textController,
focusNode: textFieldFocusNode,
decoration: InputDecoration(
border: InputBorder.none,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
contentPadding: contentPadding,
hintText: hintText,
hintStyle: AIChatUILayout.inputHintTextStyle(context),
isCollapsed: true,
isDense: true,
),
keyboardType: TextInputType.multiline,
textCapitalization: TextCapitalization.sentences,
minLines: 1,
maxLines: null,
style: Theme.of(context).textTheme.bodyMedium,
specialTextSpanBuilder: PromptInputTextSpanBuilder(
inputControlCubit: cubit,
specialTextStyle: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.primary,
fontWeight: FontWeight.w600,
),
),
);
}
}
@@ -8,10 +8,10 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:styled_widget/styled_widget.dart';
import '../layout_define.dart';
import 'layout_define.dart';
class ChatInputFile extends StatelessWidget {
const ChatInputFile({
class PromptInputFile extends StatelessWidget {
const PromptInputFile({
super.key,
required this.chatId,
required this.onDeleted,
@@ -0,0 +1,42 @@
import 'package:flutter/widgets.dart';
class DesktopAIPromptSizes {
const DesktopAIPromptSizes._();
static const attachedFilesBarPadding =
EdgeInsets.only(left: 8.0, top: 8.0, right: 8.0);
static const attachedFilesPreviewHeight = 48.0;
static const attachedFilesPreviewSpacing = 12.0;
static const predefinedFormatButtonHeight = 28.0;
static const predefinedFormatIconHeight = 16.0;
static const textFieldMinHeight = 36.0;
static const textFieldContentPadding =
EdgeInsetsDirectional.fromSTEB(14.0, 8.0, 14.0, 8.0);
static const actionBarButtonSize = 28.0;
static const actionBarIconSize = 16.0;
static const actionBarSendButtonSize = 32.0;
static const actionBarSendButtonIconSize = 24.0;
}
class MobileAIPromptSizes {
const MobileAIPromptSizes._();
static const attachedFilesBarHeight = 68.0;
static const attachedFilesBarPadding =
EdgeInsets.only(top: 8.0, left: 8.0, right: 8.0, bottom: 4.0);
static const attachedFilesPreviewHeight = 56.0;
static const attachedFilesPreviewSpacing = 8.0;
static const predefinedFormatButtonHeight = 32.0;
static const predefinedFormatIconHeight = 20.0;
static const textFieldMinHeight = 32.0;
static const textFieldContentPadding =
EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0);
static const mentionIconSize = 20.0;
static const sendButtonSize = 32.0;
}
@@ -8,7 +8,7 @@ import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'chat_mention_page_menu.dart';
import 'mention_page_menu.dart';
Future<ViewPB?> showPageSelectorSheet(
BuildContext context, {
@@ -19,30 +19,32 @@ const double _noPageHeight = 20.0;
const double _fixedWidth = 360.0;
const double _maxHeight = 328.0;
class ChatInputAnchor {
ChatInputAnchor(this.anchorKey, this.layerLink);
class PromptInputAnchor {
PromptInputAnchor(this.anchorKey, this.layerLink);
final GlobalKey<State<StatefulWidget>> anchorKey;
final LayerLink layerLink;
}
class ChatMentionPageMenu extends StatefulWidget {
const ChatMentionPageMenu({
class PromptInputMentionPageMenu extends StatefulWidget {
const PromptInputMentionPageMenu({
super.key,
required this.anchor,
required this.textController,
required this.onPageSelected,
});
final ChatInputAnchor anchor;
final PromptInputAnchor anchor;
final TextEditingController textController;
final void Function(ViewPB view) onPageSelected;
@override
State<ChatMentionPageMenu> createState() => _ChatMentionPageMenuState();
State<PromptInputMentionPageMenu> createState() =>
_PromptInputMentionPageMenuState();
}
class _ChatMentionPageMenuState extends State<ChatMentionPageMenu> {
class _PromptInputMentionPageMenuState
extends State<PromptInputMentionPageMenu> {
@override
void initState() {
super.initState();
@@ -92,7 +94,7 @@ class _ChatMentionPageMenuState extends State<ChatMentionPageMenu> {
],
),
child: TextFieldTapRegion(
child: ChatMentionPageList(
child: PromptInputMentionPageList(
onPageSelected: widget.onPageSelected,
),
),
@@ -143,8 +145,8 @@ class _ChatMentionPageMenuState extends State<ChatMentionPageMenu> {
}
}
class ChatMentionPageList extends StatefulWidget {
const ChatMentionPageList({
class PromptInputMentionPageList extends StatefulWidget {
const PromptInputMentionPageList({
super.key,
required this.onPageSelected,
});
@@ -152,10 +154,12 @@ class ChatMentionPageList extends StatefulWidget {
final void Function(ViewPB view) onPageSelected;
@override
State<ChatMentionPageList> createState() => _ChatMentionPageListState();
State<PromptInputMentionPageList> createState() =>
_PromptInputMentionPageListState();
}
class _ChatMentionPageListState extends State<ChatMentionPageList> {
class _PromptInputMentionPageListState
extends State<PromptInputMentionPageList> {
final autoScrollController = SimpleAutoScrollController(
suggestedRowHeight: _itemHeight,
beginGetter: (rect) => rect.top + 8.0,
@@ -5,8 +5,8 @@ import 'package:easy_localization/easy_localization.dart';
import 'package:extended_text_library/extended_text_library.dart';
import 'package:flutter/material.dart';
class ChatInputTextSpanBuilder extends SpecialTextSpanBuilder {
ChatInputTextSpanBuilder({
class PromptInputTextSpanBuilder extends SpecialTextSpanBuilder {
PromptInputTextSpanBuilder({
required this.inputControlCubit,
this.specialTextStyle,
});
@@ -5,21 +5,20 @@ 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:universal_platform/universal_platform.dart';
import '../layout_define.dart';
import 'layout_define.dart';
class PromptInputDesktopToggleFormatButton extends StatelessWidget {
const PromptInputDesktopToggleFormatButton({
super.key,
required this.showFormatBar,
required this.predefinedFormat,
required this.predefinedTextFormat,
required this.onTap,
});
final bool showFormatBar;
final ImageFormat predefinedFormat;
final TextFormat? predefinedTextFormat;
final PredefinedFormat predefinedFormat;
final VoidCallback onTap;
@override
@@ -49,15 +48,11 @@ class ChangeFormatBar extends StatelessWidget {
const ChangeFormatBar({
super.key,
required this.predefinedFormat,
required this.buttonSize,
required this.iconSize,
required this.spacing,
required this.onSelectPredefinedFormat,
});
final PredefinedFormat? predefinedFormat;
final double buttonSize;
final double iconSize;
final double spacing;
final void Function(PredefinedFormat) onSelectPredefinedFormat;
@@ -106,15 +101,15 @@ class ChangeFormatBar extends StatelessWidget {
child: FlowyTooltip(
message: format.i18n,
child: SizedBox.square(
dimension: buttonSize,
dimension: _buttonSize,
child: FlowyHover(
isSelected: () => format == predefinedFormat?.imageFormat,
child: Center(
child: FlowySvg(
format.icon,
size: format == ImageFormat.textAndImage
? Size(21.0 / 16.0 * iconSize, iconSize)
: Size.square(iconSize),
? Size(21.0 / 16.0 * _iconSize, _iconSize)
: Size.square(_iconSize),
),
),
),
@@ -152,13 +147,13 @@ class ChangeFormatBar extends StatelessWidget {
child: FlowyTooltip(
message: format.i18n,
child: SizedBox.square(
dimension: buttonSize,
dimension: _buttonSize,
child: FlowyHover(
isSelected: () => format == predefinedFormat?.textFormat,
child: Center(
child: FlowySvg(
format.icon,
size: Size.square(iconSize),
size: Size.square(_iconSize),
),
),
),
@@ -166,6 +161,18 @@ class ChangeFormatBar extends StatelessWidget {
),
);
}
double get _buttonSize {
return UniversalPlatform.isMobile
? MobileAIPromptSizes.predefinedFormatButtonHeight
: DesktopAIPromptSizes.predefinedFormatButtonHeight;
}
double get _iconSize {
return UniversalPlatform.isMobile
? MobileAIPromptSizes.predefinedFormatIconHeight
: DesktopAIPromptSizes.predefinedFormatIconHeight;
}
}
class PromptInputMobileToggleFormatButton extends StatelessWidget {
@@ -18,8 +18,8 @@ import 'package:flowy_infra_ui/style_widget/hover.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../layout_define.dart';
import 'chat_mention_page_menu.dart';
import 'layout_define.dart';
import 'mention_page_menu.dart';
class PromptInputDesktopSelectSourcesButton extends StatefulWidget {
const PromptInputDesktopSelectSourcesButton({
@@ -0,0 +1,70 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:universal_platform/universal_platform.dart';
import 'layout_define.dart';
enum SendButtonState { enabled, streaming, disabled }
class PromptInputSendButton extends StatelessWidget {
const PromptInputSendButton({
super.key,
required this.state,
required this.onSendPressed,
required this.onStopStreaming,
});
final SendButtonState state;
final VoidCallback onSendPressed;
final VoidCallback onStopStreaming;
@override
Widget build(BuildContext context) {
return FlowyIconButton(
width: _buttonSize,
icon: switch (state) {
SendButtonState.enabled => FlowySvg(
FlowySvgs.ai_send_filled_s,
size: Size.square(_iconSize),
color: Theme.of(context).colorScheme.primary,
),
SendButtonState.disabled => FlowySvg(
FlowySvgs.ai_send_filled_s,
size: Size.square(_iconSize),
color: Theme.of(context).disabledColor,
),
SendButtonState.streaming => FlowySvg(
FlowySvgs.ai_stop_filled_s,
size: Size.square(_iconSize),
color: Theme.of(context).colorScheme.primary,
),
},
onPressed: () {
switch (state) {
case SendButtonState.enabled:
onSendPressed();
break;
case SendButtonState.streaming:
onStopStreaming();
break;
case SendButtonState.disabled:
break;
}
},
hoverColor: Colors.transparent,
);
}
double get _buttonSize {
return UniversalPlatform.isMobile
? MobileAIPromptSizes.sendButtonSize
: DesktopAIPromptSizes.actionBarSendButtonSize;
}
double get _iconSize {
return UniversalPlatform.isMobile
? MobileAIPromptSizes.sendButtonSize
: DesktopAIPromptSizes.actionBarSendButtonIconSize;
}
}
+1
View File
@@ -247,6 +247,7 @@ Future<AppFlowyCloudConfiguration> configurationFromUri(
// In development mode, the app is configured to access the AppFlowy cloud server directly through specific ports.
// This setup bypasses the need for Nginx, meaning that the AppFlowy cloud should be running without an Nginx server
// in the development environment.
// If you modify following code, please update the corresponding documentation in the appflowy billing.
if (authenticatorType == AuthenticatorType.appflowyCloudDevelop) {
return AppFlowyCloudConfiguration(
base_url: "$baseUrl:8000",
@@ -21,6 +21,7 @@ extension MobileRouter on BuildContext {
bool showMoreButton = true,
String? fixedTitle,
String? blockId,
List<String>? tabs,
}) async {
// set the current view before pushing the new view
getIt<MenuSharedState>().latestOpenView = view;
@@ -37,6 +38,9 @@ extension MobileRouter on BuildContext {
queryParameters[MobileDocumentScreen.viewBlockId] = blockId;
}
}
if (tabs != null) {
queryParameters[MobileDocumentScreen.viewSelectTabs] = tabs.join('-');
}
final uri = Uri(
path: view.routeName,
@@ -10,6 +10,7 @@ import 'package:appflowy/plugins/document/presentation/document_collaborators.da
import 'package:appflowy/plugins/document/presentation/editor_plugins/header/emoji_icon_widget.dart';
import 'package:appflowy/shared/feature_flags.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/startup/plugin/plugin.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/user/application/reminder/reminder_bloc.dart';
@@ -34,6 +35,7 @@ class MobileViewPage extends StatefulWidget {
this.fixedTitle,
this.showMoreButton = true,
this.blockId,
this.tabs = const [PickerTabType.emoji, PickerTabType.icon],
});
/// view id
@@ -43,6 +45,7 @@ class MobileViewPage extends StatefulWidget {
final Map<String, dynamic>? arguments;
final bool showMoreButton;
final String? blockId;
final List<PickerTabType> tabs;
// only used in row page
final String? fixedTitle;
@@ -193,6 +196,7 @@ class _MobileViewPageState extends State<MobileViewPage> {
data: {
MobileDocumentScreen.viewFixedTitle: widget.fixedTitle,
MobileDocumentScreen.viewBlockId: widget.blockId,
MobileDocumentScreen.viewSelectTabs: widget.tabs,
},
);
},
@@ -242,6 +246,7 @@ class _MobileViewPageState extends State<MobileViewPage> {
view: view,
isImmersiveMode: isImmersiveMode,
appBarOpacity: _appBarOpacity,
tabs: widget.tabs,
),
]);
}
@@ -9,6 +9,7 @@ import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart';
import 'package:appflowy/plugins/document/presentation/editor_notification.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/page_style/page_style_bottom_sheet.dart';
import 'package:appflowy/plugins/shared/share/share_bloc.dart';
import 'package:appflowy/shared/icon_emoji_picker/tab.dart';
import 'package:appflowy/workspace/application/favorite/favorite_bloc.dart';
import 'package:appflowy/workspace/application/view/prelude.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
@@ -123,9 +124,11 @@ class MobileViewPageLayoutButton extends StatelessWidget {
required this.view,
required this.isImmersiveMode,
required this.appBarOpacity,
required this.tabs,
});
final ViewPB view;
final List<PickerTabType> tabs;
final bool isImmersiveMode;
final ValueListenable appBarOpacity;
@@ -156,6 +159,7 @@ class MobileViewPageLayoutButton extends StatelessWidget {
],
child: PageStyleBottomSheet(
view: context.read<ViewBloc>().state.view,
tabs: tabs,
),
),
);
@@ -8,6 +8,7 @@ import 'package:appflowy/plugins/database/application/cell/cell_controller.dart'
import 'package:appflowy/plugins/database/application/cell/cell_controller_builder.dart';
import 'package:appflowy/plugins/database/application/database_controller.dart';
import 'package:appflowy/plugins/database/grid/presentation/layout/sizes.dart';
import 'package:appflowy/shared/icon_emoji_picker/tab.dart';
import 'package:appflowy/workspace/application/view/prelude.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy_backend/log.dart';
@@ -116,6 +117,7 @@ class _OpenRowPageButtonState extends State<OpenRowPageButton> {
addInRecent: false,
showMoreButton: false,
fixedTitle: fieldName,
tabs: [PickerTabType.emoji.name],
);
}
}
@@ -5,6 +5,8 @@ import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart';
import 'package:appflowy/mobile/presentation/widgets/widgets.dart';
import 'package:appflowy/plugins/database/application/database_controller.dart';
import 'package:appflowy/plugins/database/application/tab_bar_bloc.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/workspace/application/view/view_bloc.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
@@ -163,9 +165,20 @@ class MobileDatabaseViewListButton extends StatelessWidget {
}
Widget _buildViewIconButton(BuildContext context, ViewPB view) {
final iconData = view.icon.toEmojiIconData();
Widget icon;
if (iconData.isEmpty || iconData.type != FlowyIconType.icon) {
icon = view.defaultIcon();
} else {
icon = RawEmojiIconWidget(
emoji: iconData,
emojiSize: 14.0,
enableColor: false,
);
}
return SizedBox.square(
dimension: 20.0,
child: view.defaultIcon(),
child: icon,
);
}
@@ -1,11 +1,16 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/mobile/presentation/bottom_sheet/show_mobile_bottom_sheet.dart';
import 'package:appflowy/mobile/presentation/bottom_sheet/show_transition_bottom_sheet.dart';
import 'package:appflowy/mobile/presentation/widgets/flowy_mobile_quick_action_button.dart';
import 'package:appflowy/plugins/database/application/database_controller.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/workspace/application/view/view_bloc.dart';
import 'package:appflowy/workspace/application/view/view_service.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
@@ -49,6 +54,41 @@ class MobileDatabaseViewQuickActions extends StatelessWidget {
}
}),
const MobileQuickActionDivider(),
_actionButton(
context,
_Action.changeIcon,
() {
showMobileBottomSheet(
context,
showDragHandle: true,
showDivider: false,
showHeader: true,
title: LocaleKeys.titleBar_pageIcon.tr(),
backgroundColor: AFThemeExtension.of(context).background,
enableDraggableScrollable: true,
minChildSize: 0.6,
initialChildSize: 0.61,
scrollableWidgetBuilder: (_, controller) {
return Expanded(
child: FlowyIconEmojiPicker(
tabs: const [PickerTabType.icon],
enableBackgroundColorSelection: false,
onSelectedEmoji: (r) {
ViewBackendService.updateViewIcon(
viewId: view.id,
viewIcon: r.data,
);
Navigator.pop(context);
},
),
);
},
builder: (_) => const SizedBox.shrink(),
).then((_) => Navigator.pop(context));
},
!isInline,
),
const MobileQuickActionDivider(),
_actionButton(
context,
_Action.duplicate,
@@ -91,14 +131,16 @@ class MobileDatabaseViewQuickActions extends StatelessWidget {
enum _Action {
edit,
duplicate,
delete;
changeIcon,
delete,
duplicate;
String get label {
return switch (this) {
edit => LocaleKeys.grid_settings_editView.tr(),
duplicate => LocaleKeys.button_duplicate.tr(),
delete => LocaleKeys.button_delete.tr(),
changeIcon => LocaleKeys.disclosureAction_changeIcon.tr(),
};
}
@@ -107,6 +149,7 @@ enum _Action {
edit => FlowySvgs.view_item_rename_s,
duplicate => FlowySvgs.duplicate_s,
delete => FlowySvgs.trash_s,
changeIcon => FlowySvgs.change_icon_s,
};
}
@@ -1,4 +1,5 @@
import 'package:appflowy/mobile/presentation/base/mobile_view_page.dart';
import 'package:appflowy/shared/icon_emoji_picker/tab.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:flutter/material.dart';
@@ -10,6 +11,7 @@ class MobileDocumentScreen extends StatelessWidget {
this.showMoreButton = true,
this.fixedTitle,
this.blockId,
this.tabs = const [PickerTabType.emoji, PickerTabType.icon],
});
/// view id
@@ -18,6 +20,7 @@ class MobileDocumentScreen extends StatelessWidget {
final bool showMoreButton;
final String? fixedTitle;
final String? blockId;
final List<PickerTabType> tabs;
static const routeName = '/docs';
static const viewId = 'id';
@@ -25,6 +28,7 @@ class MobileDocumentScreen extends StatelessWidget {
static const viewShowMoreButton = 'show_more_button';
static const viewFixedTitle = 'fixed_title';
static const viewBlockId = 'block_id';
static const viewSelectTabs = 'select_tabs';
@override
Widget build(BuildContext context) {
@@ -35,6 +39,7 @@ class MobileDocumentScreen extends StatelessWidget {
showMoreButton: showMoreButton,
fixedTitle: fixedTitle,
blockId: blockId,
tabs: tabs,
);
}
}
@@ -3,6 +3,7 @@ import 'package:appflowy/mobile/application/mobile_router.dart';
import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart';
import 'package:appflowy/mobile/presentation/home/section_folder/mobile_home_section_folder_header.dart';
import 'package:appflowy/mobile/presentation/page_item/mobile_view_item.dart';
import 'package:appflowy/shared/icon_emoji_picker/tab.dart';
import 'package:appflowy/workspace/application/menu/sidebar_sections_bloc.dart';
import 'package:appflowy/workspace/application/sidebar/folder/folder_bloc.dart';
import 'package:appflowy/workspace/application/view/view_bloc.dart';
@@ -101,7 +102,14 @@ class _Pages extends StatelessWidget {
level: 0,
leftPadding: HomeSpaceViewSizes.leftPadding,
isFeedback: false,
onSelected: context.pushView,
onSelected: (v) => context.pushView(
v,
tabs: [
PickerTabType.emoji,
PickerTabType.icon,
PickerTabType.custom,
].map((e) => e.name).toList(),
),
endActionPane: (context) {
final view = context.read<ViewBloc>().state.view;
return buildEndActionPane(
@@ -11,6 +11,7 @@ import 'package:appflowy/plugins/document/presentation/editor_plugins/header/emo
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/shared/appflowy_network_image.dart';
import 'package:appflowy/shared/flowy_gradient_colors.dart';
import 'package:appflowy/shared/icon_emoji_picker/tab.dart';
import 'package:appflowy/util/string_extension.dart';
import 'package:appflowy/util/theme_extension.dart';
import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart';
@@ -81,7 +82,14 @@ class MobileViewPage extends StatelessWidget {
spaceRatio: 4,
),
child: AnimatedGestureDetector(
onTapUp: () => context.pushView(view),
onTapUp: () => context.pushView(
view,
tabs: [
PickerTabType.emoji,
PickerTabType.icon,
PickerTabType.custom,
].map((e) => e.name).toList(),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
@@ -140,7 +148,8 @@ class MobileViewPage extends StatelessWidget {
final iconUrl = userProfile?.iconUrl;
if (iconUrl == null ||
iconUrl.isEmpty ||
view.createdBy != userProfile?.id) {
view.createdBy != userProfile?.id ||
!isURL(iconUrl)) {
return const SizedBox.shrink();
}
@@ -182,7 +191,7 @@ class MobileViewPage extends StatelessWidget {
WidgetSpan(
child: SizedBox(
width: 20,
child: EmojiIconWidget(
child: RawEmojiIconWidget(
emoji: icon,
emojiSize: 18.0,
),
@@ -206,7 +215,7 @@ class MobileViewPage extends StatelessWidget {
Widget _buildAuthor(BuildContext context, RecentViewState state) {
return FlowyText.regular(
// view.createdBy.toString(),
'Lucas',
'',
fontSize: 12.0,
color: Theme.of(context).hintColor,
overflow: TextOverflow.ellipsis,
@@ -4,6 +4,7 @@ import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart';
import 'package:appflowy/mobile/presentation/home/space/mobile_space_header.dart';
import 'package:appflowy/mobile/presentation/home/space/mobile_space_menu.dart';
import 'package:appflowy/mobile/presentation/page_item/mobile_view_item.dart';
import 'package:appflowy/shared/icon_emoji_picker/tab.dart';
import 'package:appflowy/shared/list_extension.dart';
import 'package:appflowy/workspace/application/sidebar/folder/folder_bloc.dart';
import 'package:appflowy/workspace/application/sidebar/space/space_bloc.dart';
@@ -151,7 +152,14 @@ class _Pages extends StatelessWidget {
level: 0,
leftPadding: HomeSpaceViewSizes.leftPadding,
isFeedback: false,
onSelected: context.pushView,
onSelected: (v) => context.pushView(
v,
tabs: [
PickerTabType.emoji,
PickerTabType.icon,
PickerTabType.custom,
].map((e) => e.name).toList(),
),
endActionPane: (context) {
final view = context.read<ViewBloc>().state.view;
final actions = [
@@ -6,6 +6,7 @@ import 'package:appflowy/mobile/presentation/home/tab/_tab_bar.dart';
import 'package:appflowy/mobile/presentation/home/tab/space_order_bloc.dart';
import 'package:appflowy/mobile/presentation/presentation.dart';
import 'package:appflowy/mobile/presentation/setting/workspace/invite_members_screen.dart';
import 'package:appflowy/shared/icon_emoji_picker/tab.dart';
import 'package:appflowy/workspace/application/menu/sidebar_sections_bloc.dart';
import 'package:appflowy/workspace/application/sidebar/folder/folder_bloc.dart';
import 'package:appflowy/workspace/application/sidebar/space/space_bloc.dart';
@@ -82,7 +83,14 @@ class _MobileSpaceTabState extends State<MobileSpaceTab>
listener: (context, state) {
final lastCreatedPage = state.lastCreatedRootView;
if (lastCreatedPage != null) {
context.pushView(lastCreatedPage);
context.pushView(
lastCreatedPage,
tabs: [
PickerTabType.emoji,
PickerTabType.icon,
PickerTabType.custom,
].map((e) => e.name).toList(),
);
}
},
),
@@ -300,7 +300,8 @@ class _SingleMobileInnerViewItemState extends State<SingleMobileInnerViewItem> {
}
Widget _buildViewIcon() {
final icon = widget.view.icon.value.isNotEmpty
final iconData = widget.view.icon.toEmojiIconData();
final icon = iconData.isNotEmpty
? EmojiIconWidget(
emoji: widget.view.icon.toEmojiIconData(),
emojiSize: Platform.isAndroid ? 16.0 : 18.0,
@@ -19,7 +19,7 @@ class AppearanceSettingGroup extends StatelessWidget {
settingItemList: const [
ThemeSetting(),
FontSetting(),
TextScaleSetting(),
DisplaySizeSetting(),
RTLSetting(),
],
);
@@ -1,39 +1,55 @@
import 'package:flutter/material.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart';
import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/startup/tasks/app_window_size_manager.dart';
import 'package:appflowy/workspace/presentation/home/hotkeys.dart';
import 'package:appflowy/workspace/presentation/widgets/more_view_actions/widgets/font_size_stepper.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter/material.dart';
import 'package:scaled_app/scaled_app.dart';
import '../setting.dart';
const int _divisions = 4;
const double _minMobileScaleFactor = 0.8;
const double _maxMobileScaleFactor = 1.2;
class TextScaleSetting extends StatelessWidget {
const TextScaleSetting({
class DisplaySizeSetting extends StatefulWidget {
const DisplaySizeSetting({
super.key,
});
@override
State<DisplaySizeSetting> createState() => _DisplaySizeSettingState();
}
class _DisplaySizeSettingState extends State<DisplaySizeSetting> {
double scaleFactor = 1.0;
final windowSizeManager = WindowSizeManager();
@override
void initState() {
super.initState();
windowSizeManager.getScaleFactor().then((v) {
if (v != scaleFactor && mounted) {
setState(() {
scaleFactor = v;
});
}
});
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final textScaleFactor =
context.watch<AppearanceSettingsCubit>().state.textScaleFactor;
return MobileSettingItem(
name: LocaleKeys.settings_appearance_fontScaleFactor.tr(),
name: LocaleKeys.settings_appearance_displaySize.tr(),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
FlowyText(
// map the text scale factor to the 0-1
// 0.8 - 0.0
// 0.9 - 0.5
// 1.0 - 1.0
((_divisions + 1) * textScaleFactor - _divisions)
.toStringAsFixed(2),
scaleFactor.toStringAsFixed(2),
color: theme.colorScheme.onSurface,
),
const Icon(Icons.chevron_right),
@@ -45,17 +61,15 @@ class TextScaleSetting extends StatelessWidget {
showHeader: true,
showDragHandle: true,
showDivider: false,
title: LocaleKeys.settings_appearance_fontScaleFactor.tr(),
title: LocaleKeys.settings_appearance_displaySize.tr(),
builder: (context) {
return FontSizeStepper(
value: textScaleFactor,
minimumValue: 0.8,
maximumValue: 1.0,
value: scaleFactor,
minimumValue: _minMobileScaleFactor,
maximumValue: _maxMobileScaleFactor,
divisions: _divisions,
onChanged: (newTextScaleFactor) {
context
.read<AppearanceSettingsCubit>()
.setTextScaleFactor(newTextScaleFactor);
onChanged: (newScaleFactor) async {
await _setScale(newScaleFactor);
},
);
},
@@ -63,4 +77,22 @@ class TextScaleSetting extends StatelessWidget {
},
);
}
Future<void> _setScale(double value) async {
if (FlowyRunner.currentMode == IntegrationMode.integrationTest) {
// The integration test will fail if we check the scale factor in the test.
// #0 ScaledWidgetsFlutterBinding.Eval ()
// #1 ScaledWidgetsFlutterBinding.instance (package:scaled_app/scaled_app.dart:66:62)
// ignore: invalid_use_of_visible_for_testing_member
appflowyScaleFactor = value;
} else {
ScaledWidgetsFlutterBinding.instance.scaleFactor = (_) => value;
}
if (mounted) {
setState(() {
scaleFactor = value;
});
}
await windowSizeManager.setScaleFactor(value);
}
}
@@ -98,6 +98,20 @@ class ChatAIMessageBloc extends Bloc<ChatAIMessageEvent, ChatAIMessageState> {
),
);
},
onAIImageResponseLimit: () {
emit(
state.copyWith(
messageState: const MessageState.onAIImageResponseLimit(),
),
);
},
onAIMaxRequired: (message) {
emit(
state.copyWith(
messageState: MessageState.onAIMaxRequired(message),
),
);
},
receiveMetadata: (metadata) {
Log.debug("AI Steps: ${metadata.progress?.step}");
emit(
@@ -129,11 +143,22 @@ class ChatAIMessageBloc extends Bloc<ChatAIMessageEvent, ChatAIMessageState> {
add(const ChatAIMessageEvent.onAIResponseLimit());
}
},
onAIImageResponseLimit: () {
if (!isClosed) {
add(const ChatAIMessageEvent.onAIImageResponseLimit());
}
},
onMetadata: (metadata) {
if (!isClosed) {
add(ChatAIMessageEvent.receiveMetadata(metadata));
}
},
onAIMaxRequired: (message) {
if (!isClosed) {
Log.info(message);
add(ChatAIMessageEvent.onAIMaxRequired(message));
}
},
);
}
}
@@ -145,6 +170,10 @@ class ChatAIMessageEvent with _$ChatAIMessageEvent {
const factory ChatAIMessageEvent.retry() = _Retry;
const factory ChatAIMessageEvent.retryResult(String text) = _RetryResult;
const factory ChatAIMessageEvent.onAIResponseLimit() = _OnAIResponseLimit;
const factory ChatAIMessageEvent.onAIImageResponseLimit() =
_OnAIImageResponseLimit;
const factory ChatAIMessageEvent.onAIMaxRequired(String message) =
_OnAIMaxRquired;
const factory ChatAIMessageEvent.receiveMetadata(
MetadataCollection metadata,
) = _ReceiveMetadata;
@@ -178,6 +207,8 @@ class ChatAIMessageState with _$ChatAIMessageState {
class MessageState with _$MessageState {
const factory MessageState.onError(String error) = _Error;
const factory MessageState.onAIResponseLimit() = _AIResponseLimit;
const factory MessageState.onAIImageResponseLimit() = _AIImageResponseLimit;
const factory MessageState.onAIMaxRequired(String message) = _AIMaxRequired;
const factory MessageState.ready() = _Ready;
const factory MessageState.loading() = _Loading;
}
@@ -14,6 +14,8 @@ import 'package:flutter/foundation.dart';
import 'package:flutter_chat_core/flutter_chat_core.dart';
class ChatEditDocumentService {
const ChatEditDocumentService._();
static Future<ViewPB?> saveMessagesToNewPage(
String chatPageName,
String parentViewId,
@@ -29,7 +31,10 @@ class ChatEditDocumentService {
return null;
}
final document = customMarkdownToDocument(completeMessage);
final document = customMarkdownToDocument(
completeMessage,
tableWidth: 250.0,
);
final initialBytes =
DocumentDataPBFromTo.fromDocument(document)?.writeToBuffer();
if (initialBytes == null) {
@@ -45,12 +50,13 @@ class ChatEditDocumentService {
).toNullable();
}
static Future<void> addMessageToPage(
static Future<void> addMessagesToPage(
String documentId,
TextMessage message,
List<TextMessage> messages,
) async {
if (message.text.isEmpty) {
Log.error('Message is empty');
// Convert messages to markdown and trim the last empty newline.
final completeMessage = messages.map((m) => m.text).join('\n').trimRight();
if (completeMessage.isEmpty) {
return;
}
@@ -69,7 +75,10 @@ class ChatEditDocumentService {
return;
}
final messageDocument = customMarkdownToDocument(message.text);
final messageDocument = customMarkdownToDocument(
completeMessage,
tableWidth: 250.0,
);
if (messageDocument.isEmpty) {
Log.error('Failed to convert message to document');
return;
@@ -12,13 +12,13 @@ class ChatMemberBloc extends Bloc<ChatMemberEvent, ChatMemberState> {
ChatMemberBloc() : super(const ChatMemberState()) {
on<ChatMemberEvent>(
(event, emit) async {
event.when(
await event.when(
receiveMemberInfo: (String id, WorkspaceMemberPB memberInfo) {
final members = Map<String, ChatMember>.from(state.members);
members[id] = ChatMember(info: memberInfo);
emit(state.copyWith(members: members));
},
getMemberInfo: (String userId) {
getMemberInfo: (String userId) async {
if (state.members.containsKey(userId)) {
// Member info already exists. Debouncing refresh member info from backend would be better.
return;
@@ -27,19 +27,15 @@ class ChatMemberBloc extends Bloc<ChatMemberEvent, ChatMemberState> {
final payload = WorkspaceMemberIdPB(
uid: Int64.parseInt(userId),
);
UserEventGetMemberInfo(payload).send().then((result) {
if (!isClosed) {
result.fold((member) {
add(
ChatMemberEvent.receiveMemberInfo(
userId,
member,
),
);
}, (err) {
Log.error("Error getting member info: $err");
});
}
await UserEventGetMemberInfo(payload).send().then((result) {
result.fold(
(member) {
if (!isClosed) {
add(ChatMemberEvent.receiveMemberInfo(userId, member));
}
},
(err) => Log.error("Error getting member info: $err"),
);
});
},
);
@@ -25,6 +25,17 @@ class AnswerStream {
} else if (event == "AI_RESPONSE_LIMIT") {
_aiLimitReached = true;
_onAIResponseLimit?.call();
} else if (event == "AI_IMAGE_RESPONSE_LIMIT") {
_aiImageLimitReached = true;
_onAIImageResponseLimit?.call();
} else if (event.startsWith("AI_MAX_REQUIRED:")) {
final msg = event.substring(16);
// If the callback is not registered yet, add the event to the buffer.
if (_onAIMaxRequired != null) {
_onAIMaxRequired!(msg);
} else {
_pendingAIMaxRequiredEvents.add(msg);
}
}
},
onDone: () {
@@ -42,6 +53,7 @@ class AnswerStream {
late StreamSubscription<String> _subscription;
bool _hasStarted = false;
bool _aiLimitReached = false;
bool _aiImageLimitReached = false;
String? _error;
String _text = "";
@@ -51,11 +63,17 @@ class AnswerStream {
void Function()? _onEnd;
void Function(String error)? _onError;
void Function()? _onAIResponseLimit;
void Function()? _onAIImageResponseLimit;
void Function(String message)? _onAIMaxRequired;
void Function(MetadataCollection metadataCollection)? _onMetadata;
// Buffer for events that occur before listen() is called.
final List<String> _pendingAIMaxRequiredEvents = [];
int get nativePort => _port.sendPort.nativePort;
bool get hasStarted => _hasStarted;
bool get aiLimitReached => _aiLimitReached;
bool get aiImageLimitReached => _aiImageLimitReached;
String? get error => _error;
String get text => _text;
@@ -71,6 +89,8 @@ class AnswerStream {
void Function()? onEnd,
void Function(String error)? onError,
void Function()? onAIResponseLimit,
void Function()? onAIImageResponseLimit,
void Function(String message)? onAIMaxRequired,
void Function(MetadataCollection metadata)? onMetadata,
}) {
_onData = onData;
@@ -78,7 +98,17 @@ class AnswerStream {
_onEnd = onEnd;
_onError = onError;
_onAIResponseLimit = onAIResponseLimit;
_onAIImageResponseLimit = onAIImageResponseLimit;
_onMetadata = onMetadata;
_onAIMaxRequired = onAIMaxRequired;
// Flush any buffered AI_MAX_REQUIRED events.
if (_onAIMaxRequired != null && _pendingAIMaxRequiredEvents.isNotEmpty) {
for (final msg in _pendingAIMaxRequiredEvents) {
_onAIMaxRequired!(msg);
}
_pendingAIMaxRequiredEvents.clear();
}
_onStart?.call();
}
@@ -0,0 +1,96 @@
import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';
import 'package:appflowy/plugins/util.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_chat_core/flutter_chat_core.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'chat_select_message_bloc.freezed.dart';
class ChatSelectMessageBloc
extends Bloc<ChatSelectMessageEvent, ChatSelectMessageState> {
ChatSelectMessageBloc({required this.viewNotifier})
: super(ChatSelectMessageState.initial()) {
_dispatch();
}
final ViewPluginNotifier viewNotifier;
void _dispatch() {
on<ChatSelectMessageEvent>(
(event, emit) {
event.when(
toggleSelectingMessages: () {
if (state.isSelectingMessages) {
emit(ChatSelectMessageState.initial());
} else {
emit(state.copyWith(isSelectingMessages: true));
}
},
toggleSelectMessage: (Message message) {
if (state.selectedMessages.contains(message)) {
emit(
state.copyWith(
selectedMessages: state.selectedMessages
.where((m) => m != message)
.toList(),
),
);
} else {
emit(
state.copyWith(
selectedMessages: [...state.selectedMessages, message],
),
);
}
},
selectAllMessages: (List<Message> messages) {
final filtered = messages.where(isAIMessage).toList();
emit(state.copyWith(selectedMessages: filtered));
},
unselectAllMessages: () {
emit(state.copyWith(selectedMessages: const []));
},
saveAsPage: () {
emit(ChatSelectMessageState.initial());
},
);
},
);
}
bool isMessageSelected(String messageId) =>
state.selectedMessages.any((m) => m.id == messageId);
bool isAIMessage(Message message) {
return message.author.id == aiResponseUserId ||
message.author.id == systemUserId ||
message.author.id.startsWith("streamId:");
}
}
@freezed
class ChatSelectMessageEvent with _$ChatSelectMessageEvent {
const factory ChatSelectMessageEvent.toggleSelectingMessages() =
_ToggleSelectingMessages;
const factory ChatSelectMessageEvent.toggleSelectMessage(Message message) =
_ToggleSelectMessage;
const factory ChatSelectMessageEvent.selectAllMessages(
List<Message> messages,
) = _SelectAllMessages;
const factory ChatSelectMessageEvent.unselectAllMessages() =
_UnselectAllMessages;
const factory ChatSelectMessageEvent.saveAsPage() = _SaveAsPage;
}
@freezed
class ChatSelectMessageState with _$ChatSelectMessageState {
const factory ChatSelectMessageState({
required bool isSelectingMessages,
required List<Message> selectedMessages,
}) = _ChatSelectMessageState;
factory ChatSelectMessageState.initial() => const ChatSelectMessageState(
isSelectingMessages: false,
selectedMessages: [],
);
}
@@ -1,14 +1,22 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_select_message_bloc.dart';
import 'package:appflowy/plugins/ai_chat/chat_page.dart';
import 'package:appflowy/plugins/util.dart';
import 'package:appflowy/startup/plugin/plugin.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy/workspace/application/view_info/view_info_bloc.dart';
import 'package:appflowy/workspace/presentation/home/home_stack.dart';
import 'package:appflowy/workspace/presentation/home/menu/view/view_action_type.dart';
import 'package:appflowy/workspace/presentation/widgets/favorite_button.dart';
import 'package:appflowy/workspace/presentation/widgets/more_view_actions/more_view_actions.dart';
import 'package:appflowy/workspace/presentation/widgets/more_view_actions/widgets/common_view_action.dart';
import 'package:appflowy/workspace/presentation/widgets/tab_bar_item.dart';
import 'package:appflowy/workspace/presentation/widgets/view_title_bar.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.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';
@@ -46,13 +54,16 @@ class AIChatPagePlugin extends Plugin {
}) : notifier = ViewPluginNotifier(view: view);
late final ViewInfoBloc _viewInfoBloc;
late final _chatMessageSelectorBloc =
ChatSelectMessageBloc(viewNotifier: notifier);
@override
final ViewPluginNotifier notifier;
@override
PluginWidgetBuilder get widgetBuilder => AIChatPagePluginWidgetBuilder(
bloc: _viewInfoBloc,
viewInfoBloc: _viewInfoBloc,
chatMessageSelectorBloc: _chatMessageSelectorBloc,
notifier: notifier,
);
@@ -71,6 +82,7 @@ class AIChatPagePlugin extends Plugin {
@override
void dispose() {
_viewInfoBloc.close();
_chatMessageSelectorBloc.close();
notifier.dispose();
}
}
@@ -78,11 +90,13 @@ class AIChatPagePlugin extends Plugin {
class AIChatPagePluginWidgetBuilder extends PluginWidgetBuilder
with NavigationItem {
AIChatPagePluginWidgetBuilder({
required this.bloc,
required this.viewInfoBloc,
required this.chatMessageSelectorBloc,
required this.notifier,
});
final ViewInfoBloc bloc;
final ViewInfoBloc viewInfoBloc;
final ChatSelectMessageBloc chatMessageSelectorBloc;
final ViewPluginNotifier notifier;
int? deletedViewIndex;
@@ -110,8 +124,11 @@ class AIChatPagePluginWidgetBuilder extends PluginWidgetBuilder
return const SizedBox();
}
return BlocProvider.value(
value: bloc,
return MultiBlocProvider(
providers: [
BlocProvider.value(value: chatMessageSelectorBloc),
BlocProvider.value(value: viewInfoBloc),
],
child: AIChatPage(
userProfile: context.userProfile!,
key: ValueKey(notifier.view.id),
@@ -134,4 +151,51 @@ class AIChatPagePluginWidgetBuilder extends PluginWidgetBuilder
@override
EdgeInsets get contentPadding => EdgeInsets.zero;
@override
Widget? get rightBarItem => MultiBlocProvider(
providers: [
BlocProvider.value(value: viewInfoBloc),
BlocProvider.value(value: chatMessageSelectorBloc),
],
child: BlocBuilder<ChatSelectMessageBloc, ChatSelectMessageState>(
builder: (context, state) {
if (state.isSelectingMessages) {
return const SizedBox.shrink();
}
return Row(
mainAxisSize: MainAxisSize.min,
children: [
ViewFavoriteButton(
key: ValueKey('favorite_button_${notifier.view.id}'),
view: notifier.view,
),
const HSpace(4),
MoreViewActions(
key: ValueKey(notifier.view.id),
view: notifier.view,
customActions: [
CustomViewAction(
view: notifier.view,
leftIcon: FlowySvgs.ai_add_to_page_s,
label: LocaleKeys.moreAction_saveAsNewPage.tr(),
onTap: () {
chatMessageSelectorBloc.add(
const ChatSelectMessageEvent
.toggleSelectingMessages(),
);
},
),
ViewAction(
type: ViewMoreActionType.divider,
view: notifier.view,
),
],
),
],
);
},
),
);
}
@@ -1,6 +1,7 @@
import 'dart:io';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/ai_chat/presentation/chat_message_selector_banner.dart';
import 'package:appflowy/workspace/application/view/view_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
@@ -22,10 +23,11 @@ import 'application/ai_prompt_input_bloc.dart';
import 'application/chat_bloc.dart';
import 'application/chat_entity.dart';
import 'application/chat_member_bloc.dart';
import 'application/chat_select_message_bloc.dart';
import 'application/chat_message_stream.dart';
import 'presentation/animated_chat_list.dart';
import 'presentation/chat_input/desktop_ai_prompt_input.dart';
import 'presentation/chat_input/mobile_ai_prompt_input.dart';
import 'presentation/chat_input/desktop_chat_input.dart';
import 'presentation/chat_input/mobile_chat_input.dart';
import 'presentation/chat_related_question.dart';
import 'presentation/chat_welcome_page.dart';
import 'presentation/layout_define.dart';
@@ -106,20 +108,22 @@ class _ChatContentPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Container(
constraints: const BoxConstraints(maxWidth: 784),
margin: UniversalPlatform.isDesktop
? const EdgeInsets.symmetric(horizontal: 60.0)
: null,
child: ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
child: BlocBuilder<ChatBloc, ChatState>(
builder: (context, state) {
return switch (state.loadingState) {
LoadChatMessageStatus.ready => Column(
children: [
Expanded(
return BlocBuilder<ChatBloc, ChatState>(
builder: (context, state) {
return switch (state.loadingState) {
LoadChatMessageStatus.ready => Column(
children: [
ChatMessageSelectorBanner(
view: view,
allMessages: context.read<ChatBloc>().chatController.messages,
),
Expanded(
child: Align(
alignment: Alignment.topCenter,
child: _wrapConstraints(
ScrollConfiguration(
behavior: ScrollConfiguration.of(context)
.copyWith(scrollbars: false),
child: Chat(
chatController:
context.read<ChatBloc>().chatController,
@@ -135,15 +139,27 @@ class _ChatContentPage extends StatelessWidget {
),
),
),
_buildInput(context),
],
),
),
_ => const Center(child: CircularProgressIndicator.adaptive()),
};
},
),
),
),
),
_wrapConstraints(
_builtInput(context),
),
],
),
_ => const Center(child: CircularProgressIndicator.adaptive()),
};
},
);
}
Widget _wrapConstraints(Widget child) {
return Container(
constraints: const BoxConstraints(maxWidth: 784),
margin: UniversalPlatform.isDesktop
? const EdgeInsets.symmetric(horizontal: 60.0)
: null,
child: child,
);
}
@@ -193,31 +209,38 @@ class _ChatContentPage extends StatelessWidget {
final refSourceJsonString =
message.metadata?[messageRefSourceJsonStringKey] as String?;
return BlocBuilder<ChatBloc, ChatState>(
builder: (context, state) {
final chatController = context.read<ChatBloc>().chatController;
final messages = chatController.messages
.where((e) => onetimeMessageTypeFromMeta(e.metadata) == null);
final isLastMessage =
messages.isEmpty ? false : messages.last.id == message.id;
return ChatAIMessageWidget(
user: message.author,
messageUserId: message.id,
message: message,
stream: stream is AnswerStream ? stream : null,
questionId: questionId,
chatId: view.id,
refSourceJsonString: refSourceJsonString,
isStreaming: state.promptResponseState != PromptResponseState.ready,
isLastMessage: isLastMessage,
onSelectedMetadata: (metadata) =>
_onSelectMetadata(context, metadata),
onRegenerate: () => context
.read<ChatBloc>()
.add(ChatEvent.regenerateAnswer(message.id, null)),
onChangeFormat: (format) => context
.read<ChatBloc>()
.add(ChatEvent.regenerateAnswer(message.id, format)),
return BlocSelector<ChatSelectMessageBloc, ChatSelectMessageState, bool>(
selector: (state) => state.isSelectingMessages,
builder: (context, isSelectingMessages) {
return BlocBuilder<ChatBloc, ChatState>(
builder: (context, state) {
final chatController = context.read<ChatBloc>().chatController;
final messages = chatController.messages
.where((e) => onetimeMessageTypeFromMeta(e.metadata) == null);
final isLastMessage =
messages.isEmpty ? false : messages.last.id == message.id;
return ChatAIMessageWidget(
user: message.author,
messageUserId: message.id,
message: message,
stream: stream is AnswerStream ? stream : null,
questionId: questionId,
chatId: view.id,
refSourceJsonString: refSourceJsonString,
isStreaming:
state.promptResponseState != PromptResponseState.ready,
isLastMessage: isLastMessage,
isSelectingMessages: isSelectingMessages,
onSelectedMetadata: (metadata) =>
_onSelectMetadata(context, metadata),
onRegenerate: () => context
.read<ChatBloc>()
.add(ChatEvent.regenerateAnswer(message.id, null)),
onChangeFormat: (format) => context
.read<ChatBloc>()
.add(ChatEvent.regenerateAnswer(message.id, format)),
);
},
);
},
);
@@ -265,74 +288,100 @@ class _ChatContentPage extends StatelessWidget {
);
}
return ChatAnimatedListReversed(
scrollController: scrollController,
itemBuilder: itemBuilder,
onLoadPreviousMessages: () {
bloc.add(const ChatEvent.loadPreviousMessages());
return BlocSelector<ChatSelectMessageBloc, ChatSelectMessageState, bool>(
selector: (state) => state.isSelectingMessages,
builder: (context, isSelectingMessages) {
return ChatAnimatedListReversed(
scrollController: scrollController,
itemBuilder: itemBuilder,
bottomPadding: isSelectingMessages
? 48.0 + DesktopAIChatSizes.messageActionBarIconSize
: 8.0,
onLoadPreviousMessages: () {
bloc.add(const ChatEvent.loadPreviousMessages());
},
);
},
);
}
Widget _buildInput(BuildContext context) {
return Padding(
padding: AIChatUILayout.safeAreaInsets(context),
child: BlocSelector<ChatBloc, ChatState, bool>(
selector: (state) {
return state.promptResponseState == PromptResponseState.ready;
},
builder: (context, canSendMessage) {
final chatBloc = context.read<ChatBloc>();
Widget _builtInput(BuildContext context) {
return BlocSelector<ChatSelectMessageBloc, ChatSelectMessageState, bool>(
selector: (state) => state.isSelectingMessages,
builder: (context, isSelectingMessages) {
return AnimatedSwitcher(
duration: const Duration(milliseconds: 150),
transitionBuilder: (child, animation) {
return SizeTransition(
sizeFactor: animation,
axisAlignment: -1,
child: child,
);
},
child: isSelectingMessages
? const SizedBox.shrink()
: Padding(
padding: AIChatUILayout.safeAreaInsets(context),
child: BlocSelector<ChatBloc, ChatState, bool>(
selector: (state) {
return state.promptResponseState ==
PromptResponseState.ready;
},
builder: (context, canSendMessage) {
final chatBloc = context.read<ChatBloc>();
return UniversalPlatform.isDesktop
? DesktopAIPromptInput(
chatId: view.id,
isStreaming: !canSendMessage,
onStopStreaming: () {
chatBloc.add(const ChatEvent.stopStream());
},
onSubmitted: (text, format, metadata) {
chatBloc.add(
ChatEvent.sendMessage(
message: text,
format: format,
metadata: metadata,
),
);
},
onUpdateSelectedSources: (ids) {
chatBloc.add(
ChatEvent.updateSelectedSources(
selectedSourcesIds: ids,
),
);
},
)
: MobileAIPromptInput(
chatId: view.id,
isStreaming: !canSendMessage,
onStopStreaming: () {
chatBloc.add(const ChatEvent.stopStream());
},
onSubmitted: (text, format, metadata) {
chatBloc.add(
ChatEvent.sendMessage(
message: text,
format: format,
metadata: metadata,
),
);
},
onUpdateSelectedSources: (ids) {
chatBloc.add(
ChatEvent.updateSelectedSources(
selectedSourcesIds: ids,
),
);
},
);
},
),
return UniversalPlatform.isDesktop
? DesktopChatInput(
chatId: view.id,
isStreaming: !canSendMessage,
onStopStreaming: () {
chatBloc.add(const ChatEvent.stopStream());
},
onSubmitted: (text, format, metadata) {
chatBloc.add(
ChatEvent.sendMessage(
message: text,
format: format,
metadata: metadata,
),
);
},
onUpdateSelectedSources: (ids) {
chatBloc.add(
ChatEvent.updateSelectedSources(
selectedSourcesIds: ids,
),
);
},
)
: MobileChatInput(
chatId: view.id,
isStreaming: !canSendMessage,
onStopStreaming: () {
chatBloc.add(const ChatEvent.stopStream());
},
onSubmitted: (text, format, metadata) {
chatBloc.add(
ChatEvent.sendMessage(
message: text,
format: format,
metadata: metadata,
),
);
},
onUpdateSelectedSources: (ids) {
chatBloc.add(
ChatEvent.updateSelectedSources(
selectedSourcesIds: ids,
),
);
},
);
},
),
),
);
},
);
}
@@ -10,15 +10,13 @@ import 'package:string_validator/string_validator.dart';
import 'layout_define.dart';
class ChatAIAvatar extends StatelessWidget {
const ChatAIAvatar({
super.key,
});
const ChatAIAvatar({super.key});
@override
Widget build(BuildContext context) {
return Container(
width: DesktopAIConvoSizes.avatarSize,
height: DesktopAIConvoSizes.avatarSize,
width: DesktopAIChatSizes.avatarSize,
height: DesktopAIChatSizes.avatarSize,
clipBehavior: Clip.hardEdge,
decoration: const BoxDecoration(shape: BoxShape.circle),
foregroundDecoration: ShapeDecoration(
@@ -61,8 +59,8 @@ class ChatUserAvatar extends StatelessWidget {
child = _buildEmojiAvatar(context);
}
return Container(
width: DesktopAIConvoSizes.avatarSize,
height: DesktopAIConvoSizes.avatarSize,
width: DesktopAIChatSizes.avatarSize,
height: DesktopAIChatSizes.avatarSize,
clipBehavior: Clip.hardEdge,
decoration: const BoxDecoration(shape: BoxShape.circle),
foregroundDecoration: ShapeDecoration(
@@ -102,7 +100,7 @@ class ChatUserAvatar extends StatelessWidget {
Widget _buildUrlAvatar(BuildContext context) {
return CircleAvatar(
backgroundColor: Colors.transparent,
radius: DesktopAIConvoSizes.avatarSize / 2,
radius: DesktopAIChatSizes.avatarSize / 2,
child: Image.network(
iconUrl,
fit: BoxFit.cover,
@@ -115,7 +113,7 @@ class ChatUserAvatar extends StatelessWidget {
Widget _buildEmojiAvatar(BuildContext context) {
return CircleAvatar(
backgroundColor: Colors.transparent,
radius: DesktopAIConvoSizes.avatarSize / 2,
radius: DesktopAIChatSizes.avatarSize / 2,
child: builtInSVGIcons.contains(iconUrl)
? FlowySvg(
FlowySvgData('emoji/$iconUrl'),
@@ -1,27 +1,21 @@
import 'package:appflowy/ai/ai.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/ai_chat/application/ai_prompt_input_bloc.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_input_control_cubit.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:extended_text_field/extended_text_field.dart';
import 'package:flowy_infra/file_picker/file_picker_service.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../application/chat_entity.dart';
import '../layout_define.dart';
import 'ai_prompt_buttons.dart';
import 'chat_input_file.dart';
import 'chat_input_span.dart';
import 'chat_mention_page_menu.dart';
import 'predefined_format_buttons.dart';
import 'select_sources_menu.dart';
class DesktopAIPromptInput extends StatefulWidget {
const DesktopAIPromptInput({
class DesktopChatInput extends StatefulWidget {
const DesktopChatInput({
super.key,
required this.chatId,
required this.isStreaming,
@@ -38,10 +32,10 @@ class DesktopAIPromptInput extends StatefulWidget {
final void Function(List<String>) onUpdateSelectedSources;
@override
State<DesktopAIPromptInput> createState() => _DesktopAIPromptInputState();
State<DesktopChatInput> createState() => _DesktopChatInputState();
}
class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
class _DesktopChatInputState extends State<DesktopChatInput> {
final textFieldKey = GlobalKey();
final layerLink = LayerLink();
final overlayController = OverlayPortalController();
@@ -55,6 +49,7 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
textFormat: TextFormat.bulletList,
);
late SendButtonState sendButtonState;
bool isComposing = false;
@override
void initState() {
@@ -110,8 +105,8 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
child: OverlayPortal(
controller: overlayController,
overlayChildBuilder: (context) {
return ChatMentionPageMenu(
anchor: ChatInputAnchor(textFieldKey, layerLink),
return PromptInputMentionPageMenu(
anchor: PromptInputAnchor(textFieldKey, layerLink),
textController: textController,
onPageSelected: handlePageSelected,
);
@@ -123,9 +118,8 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
? Theme.of(context).colorScheme.primary
: Theme.of(context).colorScheme.outline,
width: focusNode.hasFocus ? 1.5 : 1.0,
strokeAlign: BorderSide.strokeAlignOutside,
),
borderRadius: DesktopAIPromptSizes.promptFrameRadius,
borderRadius: const BorderRadius.all(Radius.circular(12.0)),
),
child: Column(
mainAxisSize: MainAxisSize.min,
@@ -137,7 +131,7 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
DesktopAIPromptSizes.attachedFilesPreviewHeight,
),
child: TextFieldTapRegion(
child: ChatInputFile(
child: PromptInputFile(
chatId: widget.chatId,
onDeleted: (file) => context
.read<AIPromptInputBloc>()
@@ -161,12 +155,7 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
const EdgeInsetsDirectional.only(start: 8.0),
child: ChangeFormatBar(
predefinedFormat: predefinedFormat,
spacing: DesktopAIPromptSizes
.predefinedFormatBarButtonSpacing,
iconSize: DesktopAIPromptSizes
.predefinedFormatIconHeight,
buttonSize: DesktopAIPromptSizes
.predefinedFormatButtonHeight,
spacing: 4.0,
onSelectPredefinedFormat: (format) {
setState(() => predefinedFormat = format);
},
@@ -182,8 +171,7 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
overlayController: overlayController,
focusNode: focusNode,
showPredefinedFormats: showPredefinedFormatSection,
predefinedFormat: predefinedFormat.imageFormat,
predefinedTextFormat: predefinedFormat.textFormat,
predefinedFormat: predefinedFormat,
onTogglePredefinedFormatSection: () {
setState(() {
showPredefinedFormatSection =
@@ -191,7 +179,7 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
});
},
sendButtonState: sendButtonState,
onSendPressed: handleSendPressed,
onSendPressed: handleSend,
onStopStreaming: widget.onStopStreaming,
onUpdateSelectedSources:
widget.onUpdateSelectedSources,
@@ -208,18 +196,6 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
);
}
BoxConstraints getTextFieldConstraints() {
double minHeight = DesktopAIPromptSizes.textFieldMinHeight +
DesktopAIPromptSizes.actionBarHeight +
DesktopAIPromptSizes.actionBarPadding.vertical;
double maxHeight = 300;
if (showPredefinedFormatSection) {
minHeight += DesktopAIPromptSizes.predefinedFormatButtonHeight;
maxHeight += DesktopAIPromptSizes.predefinedFormatButtonHeight;
}
return BoxConstraints(minHeight: minHeight, maxHeight: maxHeight);
}
void cancelMentionPage() {
if (overlayController.isShowing) {
inputControlCubit.reset();
@@ -237,7 +213,7 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
}
}
void handleSendPressed() {
void handleSend() {
if (widget.isStreaming) {
return;
}
@@ -260,13 +236,16 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
}
void handleTextControllerChanged() {
if (!textController.value.composing.isCollapsed) {
setState(() {
// update whether send button is clickable
updateSendButtonState();
isComposing = !textController.value.composing.isCollapsed;
});
if (isComposing) {
return;
}
// update whether send button is clickable
setState(() => updateSendButtonState());
// handle text and selection changes ONLY when mentioning a page
// disable mention
@@ -323,6 +302,16 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
}
}
KeyEventResult handleKeyEvent(FocusNode node, KeyEvent event) {
if (event.character == '@') {
WidgetsBinding.instance.addPostFrameCallback((_) {
inputControlCubit.startSearching(textController.value);
overlayController.show();
});
}
return KeyEventResult.ignored;
}
void handlePageSelected(ViewPB view) {
final newText = textController.text.replaceRange(
inputControlCubit.filterStartPosition,
@@ -341,36 +330,69 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
overlayController.hide();
}
BoxConstraints getTextFieldConstraints() {
double minHeight = DesktopAIPromptSizes.textFieldMinHeight +
DesktopAIPromptSizes.actionBarSendButtonSize +
DesktopAIChatSizes.inputActionBarMargin.vertical;
double maxHeight = 300;
if (showPredefinedFormatSection) {
minHeight += DesktopAIPromptSizes.predefinedFormatButtonHeight;
maxHeight += DesktopAIPromptSizes.predefinedFormatButtonHeight;
}
return BoxConstraints(minHeight: minHeight, maxHeight: maxHeight);
}
Widget inputTextField() {
return Actions(
actions: buildActions(),
child: CompositedTransformTarget(
link: layerLink,
child: BlocBuilder<AIPromptInputBloc, AIPromptInputState>(
builder: (context, state) {
return _PromptTextField(
key: textFieldKey,
cubit: inputControlCubit,
textController: textController,
textFieldFocusNode: focusNode,
showPredefinedFormatSection: showPredefinedFormatSection,
hintText: switch (state.aiType) {
AIType.appflowyAI => LocaleKeys.chat_inputMessageHint.tr(),
AIType.localAI => LocaleKeys.chat_inputLocalAIMessageHint.tr()
},
// onStartMentioningPage: () {
// WidgetsBinding.instance.addPostFrameCallback((_) {
// inputControlCubit.startSearching(textController.value);
// overlayController.show();
// });
// },
);
},
return Shortcuts(
shortcuts: buildShortcuts(),
child: Actions(
actions: buildActions(),
child: CompositedTransformTarget(
link: layerLink,
child: BlocBuilder<AIPromptInputBloc, AIPromptInputState>(
builder: (context, state) {
return PromptInputTextField(
key: textFieldKey,
cubit: inputControlCubit,
textController: textController,
textFieldFocusNode: focusNode,
contentPadding: calculateContentPadding(),
hintText: switch (state.aiType) {
AIType.appflowyAI => LocaleKeys.chat_inputMessageHint.tr(),
AIType.localAI => LocaleKeys.chat_inputLocalAIMessageHint.tr()
},
);
},
),
),
),
);
}
EdgeInsetsGeometry calculateContentPadding() {
final top = showPredefinedFormatSection
? DesktopAIPromptSizes.predefinedFormatButtonHeight
: 0.0;
final bottom = DesktopAIPromptSizes.actionBarSendButtonSize +
DesktopAIChatSizes.inputActionBarMargin.vertical;
return DesktopAIPromptSizes.textFieldContentPadding
.add(EdgeInsets.only(top: top, bottom: bottom));
}
Map<ShortcutActivator, Intent> buildShortcuts() {
if (isComposing) {
return const {};
}
return const {
SingleActivator(LogicalKeyboardKey.arrowUp): _FocusPreviousItemIntent(),
SingleActivator(LogicalKeyboardKey.arrowDown): _FocusNextItemIntent(),
SingleActivator(LogicalKeyboardKey.escape): _CancelMentionPageIntent(),
SingleActivator(LogicalKeyboardKey.enter): _SubmitOrMentionPageIntent(),
};
}
Map<Type, Action<Intent>> buildActions() {
return {
_FocusPreviousItemIntent: CallbackAction<_FocusPreviousItemIntent>(
@@ -404,7 +426,7 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
orElse: () {},
);
} else {
handleSendPressed();
handleSend();
}
return;
},
@@ -413,115 +435,6 @@ class _DesktopAIPromptInputState extends State<DesktopAIPromptInput> {
}
}
class _PromptTextField extends StatefulWidget {
const _PromptTextField({
super.key,
required this.cubit,
required this.textController,
required this.textFieldFocusNode,
this.showPredefinedFormatSection = false,
this.hintText = "",
// this.onStartMentioningPage,
});
final ChatInputControlCubit cubit;
final TextEditingController textController;
final FocusNode textFieldFocusNode;
final bool showPredefinedFormatSection;
final String hintText;
// final void Function()? onStartMentioningPage;
@override
State<_PromptTextField> createState() => _PromptTextFieldState();
}
class _PromptTextFieldState extends State<_PromptTextField> {
bool isComposing = false;
@override
void initState() {
super.initState();
// widget.textFieldFocusNode.onKeyEvent = handleKeyEvent;
widget.textController.addListener(onTextChanged);
}
@override
void dispose() {
// widget.textFieldFocusNode.onKeyEvent = null;
widget.textController.removeListener(onTextChanged);
super.dispose();
}
@override
Widget build(BuildContext context) {
return Shortcuts(
shortcuts: buildShortcuts(),
child: ExtendedTextField(
controller: widget.textController,
focusNode: widget.textFieldFocusNode,
decoration: InputDecoration(
border: InputBorder.none,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
contentPadding: calculateContentPadding(),
hintText: widget.hintText,
hintStyle: AIChatUILayout.inputHintTextStyle(context),
isCollapsed: true,
isDense: true,
),
keyboardType: TextInputType.multiline,
textCapitalization: TextCapitalization.sentences,
minLines: 1,
maxLines: null,
style: Theme.of(context).textTheme.bodyMedium,
specialTextSpanBuilder: ChatInputTextSpanBuilder(
inputControlCubit: widget.cubit,
specialTextStyle: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.primary,
fontWeight: FontWeight.w600,
),
),
),
);
}
// KeyEventResult handleKeyEvent(FocusNode node, KeyEvent event) {
// if (event.character == '@') {
// widget.onStartMentioningPage();
// }
// return KeyEventResult.ignored;
// }
void onTextChanged() {
setState(
() => isComposing = !widget.textController.value.composing.isCollapsed,
);
}
EdgeInsetsGeometry calculateContentPadding() {
final top = widget.showPredefinedFormatSection
? DesktopAIPromptSizes.predefinedFormatButtonHeight
: 0.0;
const bottom = DesktopAIPromptSizes.actionBarHeight;
return DesktopAIPromptSizes.textFieldContentPadding
.add(EdgeInsets.only(top: top, bottom: bottom));
}
Map<ShortcutActivator, Intent> buildShortcuts() {
if (isComposing) {
return const {};
}
return const {
SingleActivator(LogicalKeyboardKey.arrowUp): _FocusPreviousItemIntent(),
SingleActivator(LogicalKeyboardKey.arrowDown): _FocusNextItemIntent(),
SingleActivator(LogicalKeyboardKey.escape): _CancelMentionPageIntent(),
SingleActivator(LogicalKeyboardKey.enter): _SubmitOrMentionPageIntent(),
};
}
}
class _SubmitOrMentionPageIntent extends Intent {
const _SubmitOrMentionPageIntent();
}
@@ -545,7 +458,6 @@ class _PromptBottomActions extends StatelessWidget {
required this.focusNode,
required this.sendButtonState,
required this.predefinedFormat,
required this.predefinedTextFormat,
required this.onTogglePredefinedFormatSection,
required this.showPredefinedFormats,
required this.onSendPressed,
@@ -557,8 +469,7 @@ class _PromptBottomActions extends StatelessWidget {
final OverlayPortalController overlayController;
final FocusNode focusNode;
final bool showPredefinedFormats;
final ImageFormat predefinedFormat;
final TextFormat? predefinedTextFormat;
final PredefinedFormat predefinedFormat;
final void Function() onTogglePredefinedFormatSection;
final SendButtonState sendButtonState;
final void Function() onSendPressed;
@@ -568,8 +479,8 @@ class _PromptBottomActions extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
height: DesktopAIPromptSizes.actionBarHeight,
margin: DesktopAIPromptSizes.actionBarPadding,
height: DesktopAIPromptSizes.actionBarSendButtonSize,
margin: DesktopAIChatSizes.inputActionBarMargin,
child: BlocBuilder<AIPromptInputBloc, AIPromptInputState>(
builder: (context, state) {
if (state.chatState == null) {
@@ -585,7 +496,7 @@ class _PromptBottomActions extends StatelessWidget {
if (state.aiType == AIType.appflowyAI) ...[
_selectSourcesButton(context),
const HSpace(
DesktopAIPromptSizes.actionBarButtonSpacing,
DesktopAIChatSizes.inputActionBarButtonSpacing,
),
],
// _mentionButton(context),
@@ -595,7 +506,7 @@ class _PromptBottomActions extends StatelessWidget {
if (state.supportChatWithFile) ...[
_attachmentButton(context),
const HSpace(
DesktopAIPromptSizes.actionBarButtonSpacing,
DesktopAIChatSizes.inputActionBarButtonSpacing,
),
],
_sendButton(),
@@ -610,7 +521,6 @@ class _PromptBottomActions extends StatelessWidget {
return PromptInputDesktopToggleFormatButton(
showFormatBar: showPredefinedFormats,
predefinedFormat: predefinedFormat,
predefinedTextFormat: predefinedTextFormat,
onTap: onTogglePredefinedFormatSection,
);
}
@@ -669,8 +579,6 @@ class _PromptBottomActions extends StatelessWidget {
Widget _sendButton() {
return PromptInputSendButton(
buttonSize: DesktopAIPromptSizes.actionBarHeight,
iconSize: DesktopAIPromptSizes.sendButtonSize,
state: sendButtonState,
onSendPressed: onSendPressed,
onStopStreaming: onStopStreaming,
@@ -1,3 +1,4 @@
import 'package:appflowy/ai/ai.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/ai_chat/application/ai_prompt_input_bloc.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';
@@ -10,15 +11,9 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../layout_define.dart';
import 'ai_prompt_buttons.dart';
import 'chat_input_file.dart';
import 'chat_input_span.dart';
import 'chat_mention_page_bottom_sheet.dart';
import 'predefined_format_buttons.dart';
import 'select_sources_bottom_sheet.dart';
class MobileAIPromptInput extends StatefulWidget {
const MobileAIPromptInput({
class MobileChatInput extends StatefulWidget {
const MobileChatInput({
super.key,
required this.chatId,
required this.isStreaming,
@@ -35,10 +30,10 @@ class MobileAIPromptInput extends StatefulWidget {
final void Function(List<String>) onUpdateSelectedSources;
@override
State<MobileAIPromptInput> createState() => _MobileAIPromptInputState();
State<MobileChatInput> createState() => _MobileChatInputState();
}
class _MobileAIPromptInputState extends State<MobileAIPromptInput> {
class _MobileChatInputState extends State<MobileChatInput> {
final inputControlCubit = ChatInputControlCubit();
final focusNode = FocusNode();
final textController = TextEditingController();
@@ -108,7 +103,8 @@ class _MobileAIPromptInputState extends State<MobileAIPromptInput> {
color: Color.fromRGBO(0, 0, 0, 0.05),
),
],
borderRadius: MobileAIPromptSizes.promptFrameRadius,
borderRadius:
const BorderRadius.vertical(top: Radius.circular(8.0)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -119,7 +115,7 @@ class _MobileAIPromptInputState extends State<MobileAIPromptInput> {
MobileAIPromptSizes.attachedFilesBarPadding.vertical +
MobileAIPromptSizes.attachedFilesPreviewHeight,
),
child: ChatInputFile(
child: PromptInputFile(
chatId: widget.chatId,
onDeleted: (file) => context
.read<AIPromptInputBloc>()
@@ -128,31 +124,31 @@ class _MobileAIPromptInputState extends State<MobileAIPromptInput> {
),
if (showPredefinedFormatSection)
TextFieldTapRegion(
child: Container(
padding: MobileAIPromptSizes.predefinedFormatBarPadding,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: ChangeFormatBar(
predefinedFormat: predefinedFormat,
spacing: MobileAIPromptSizes
.predefinedFormatBarButtonSpacing,
iconSize:
MobileAIPromptSizes.predefinedFormatIconHeight,
buttonSize:
MobileAIPromptSizes.predefinedFormatButtonHeight,
spacing: 8.0,
onSelectPredefinedFormat: (format) {
setState(() => predefinedFormat = format);
},
),
),
),
)
else
const VSpace(8.0),
inputTextField(context),
Row(
children: [
const HSpace(8.0),
leadingButtons(context),
const Spacer(),
sendButton(),
const HSpace(12.0),
],
Container(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Row(
children: [
const HSpace(8.0),
leadingButtons(context),
const Spacer(),
sendButton(),
const HSpace(12.0),
],
),
),
],
),
@@ -278,7 +274,7 @@ class _MobileAIPromptInputState extends State<MobileAIPromptInput> {
maxLines: null,
style:
Theme.of(context).textTheme.bodyMedium?.copyWith(height: 20 / 14),
specialTextSpanBuilder: ChatInputTextSpanBuilder(
specialTextSpanBuilder: PromptInputTextSpanBuilder(
inputControlCubit: inputControlCubit,
specialTextStyle: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.primary,
@@ -291,40 +287,32 @@ class _MobileAIPromptInputState extends State<MobileAIPromptInput> {
}
Widget leadingButtons(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: _LeadingActions(
// onMention: () {
// textController.text += '@';
// if (!focusNode.hasFocus) {
// focusNode.requestFocus();
// }
// WidgetsBinding.instance.addPostFrameCallback((_) {
// mentionPage(context);
// });
// },
showPredefinedFormatSection: showPredefinedFormatSection,
predefinedFormat: predefinedFormat,
onTogglePredefinedFormatSection: () {
setState(() {
showPredefinedFormatSection = !showPredefinedFormatSection;
});
},
onUpdateSelectedSources: widget.onUpdateSelectedSources,
),
return _LeadingActions(
// onMention: () {
// textController.text += '@';
// if (!focusNode.hasFocus) {
// focusNode.requestFocus();
// }
// WidgetsBinding.instance.addPostFrameCallback((_) {
// mentionPage(context);
// });
// },
showPredefinedFormatSection: showPredefinedFormatSection,
predefinedFormat: predefinedFormat,
onTogglePredefinedFormatSection: () {
setState(() {
showPredefinedFormatSection = !showPredefinedFormatSection;
});
},
onUpdateSelectedSources: widget.onUpdateSelectedSources,
);
}
Widget sendButton() {
return Container(
alignment: Alignment.bottomCenter,
child: PromptInputSendButton(
buttonSize: MobileAIPromptSizes.sendButtonSize,
iconSize: MobileAIPromptSizes.sendButtonSize,
onSendPressed: handleSendPressed,
onStopStreaming: widget.onStopStreaming,
state: sendButtonState,
),
return PromptInputSendButton(
state: sendButtonState,
onSendPressed: handleSendPressed,
onStopStreaming: widget.onStopStreaming,
);
}
}
@@ -0,0 +1,314 @@
import 'dart:async';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_edit_document_service.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_select_message_bloc.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_select_sources_cubit.dart';
import 'package:appflowy/plugins/document/application/prelude.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/application/sidebar/space/space_bloc.dart';
import 'package:appflowy/workspace/application/tabs/tabs_bloc.dart';
import 'package:appflowy/workspace/application/user/prelude.dart';
import 'package:appflowy/workspace/application/view/prelude.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.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 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_chat_core/flutter_chat_core.dart';
import 'message/ai_message_action_bar.dart';
import 'message/message_util.dart';
class ChatMessageSelectorBanner extends StatelessWidget {
const ChatMessageSelectorBanner({
super.key,
required this.view,
this.allMessages = const [],
});
final ViewPB view;
final List<Message> allMessages;
@override
Widget build(BuildContext context) {
return BlocBuilder<ChatSelectMessageBloc, ChatSelectMessageState>(
builder: (context, state) {
if (!state.isSelectingMessages) {
return const SizedBox.shrink();
}
final selectedAmount = state.selectedMessages.length;
final totalAmount = allMessages.length;
final allSelected = selectedAmount == totalAmount;
return Container(
height: 48,
color: const Color(0xFF00BCF0),
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
children: [
GestureDetector(
onTap: () {
if (selectedAmount > 0) {
_unselectAllMessages(context);
} else {
_selectAllMessages(context);
}
},
child: FlowySvg(
allSelected
? FlowySvgs.checkbox_ai_selected_s
: selectedAmount > 0
? FlowySvgs.checkbox_ai_minus_s
: FlowySvgs.checkbox_ai_empty_s,
blendMode: BlendMode.dstIn,
size: const Size.square(18),
),
),
const HSpace(8),
Expanded(
child: FlowyText.semibold(
allSelected
? LocaleKeys.chat_selectBanner_allSelected.tr()
: selectedAmount > 0
? LocaleKeys.chat_selectBanner_nSelected
.tr(args: [selectedAmount.toString()])
: LocaleKeys.chat_selectBanner_selectMessages.tr(),
figmaLineHeight: 16,
color: Colors.white,
),
),
SaveToPageButton(
view: view,
),
const HSpace(8),
MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: () => context.read<ChatSelectMessageBloc>().add(
const ChatSelectMessageEvent.toggleSelectingMessages(),
),
child: const FlowySvg(
FlowySvgs.close_m,
color: Colors.white,
size: Size.square(24),
),
),
),
],
),
);
},
);
}
void _selectAllMessages(BuildContext context) => context
.read<ChatSelectMessageBloc>()
.add(ChatSelectMessageEvent.selectAllMessages(allMessages));
void _unselectAllMessages(BuildContext context) => context
.read<ChatSelectMessageBloc>()
.add(const ChatSelectMessageEvent.unselectAllMessages());
}
class SaveToPageButton extends StatefulWidget {
const SaveToPageButton({
super.key,
required this.view,
});
final ViewPB view;
@override
State<SaveToPageButton> createState() => _SaveToPageButtonState();
}
class _SaveToPageButtonState extends State<SaveToPageButton> {
final popoverController = PopoverController();
@override
Widget build(BuildContext context) {
final userWorkspaceBloc = context.read<UserWorkspaceBloc>();
final userProfile = userWorkspaceBloc.userProfile;
final workspaceId =
userWorkspaceBloc.state.currentWorkspace?.workspaceId ?? '';
return MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => SpaceBloc(
userProfile: userProfile,
workspaceId: workspaceId,
)..add(const SpaceEvent.initial(openFirstPage: false)),
),
BlocProvider(
create: (context) => ChatSettingsCubit(hideDisabled: true),
),
],
child: BlocSelector<SpaceBloc, SpaceState, ViewPB?>(
selector: (state) => state.currentSpace,
builder: (context, spaceView) {
return AppFlowyPopover(
controller: popoverController,
triggerActions: PopoverTriggerFlags.none,
margin: EdgeInsets.zero,
offset: const Offset(0, 18),
direction: PopoverDirection.bottomWithRightAligned,
constraints: const BoxConstraints.tightFor(width: 300, height: 400),
child: buildButton(context, spaceView),
popupBuilder: (_) => buildPopover(context),
);
},
),
);
}
Widget buildButton(BuildContext context, ViewPB? spaceView) {
return BlocBuilder<ChatSelectMessageBloc, ChatSelectMessageState>(
builder: (context, state) {
final selectedAmount = state.selectedMessages.length;
return Opacity(
opacity: selectedAmount == 0 ? 0.5 : 1,
child: FlowyTextButton(
LocaleKeys.chat_selectBanner_saveButton.tr(),
onPressed: selectedAmount == 0
? null
: () async {
final documentId = getOpenedDocumentId();
if (documentId != null) {
await onAddToExistingPage(context, documentId);
await forceReload(documentId);
await Future.delayed(const Duration(milliseconds: 500));
await updateSelection(documentId);
} else {
if (spaceView != null) {
context
.read<ChatSettingsCubit>()
.refreshSources([spaceView], spaceView);
}
popoverController.show();
}
},
fontColor: Colors.white,
borderColor: Colors.white,
fillColor: Colors.transparent,
padding: const EdgeInsets.symmetric(
horizontal: 12.0,
vertical: 6.0,
),
),
);
},
);
}
Widget buildPopover(BuildContext context) {
return BlocProvider.value(
value: context.read<ChatSettingsCubit>(),
child: SaveToPagePopoverContent(
onAddToNewPage: (parentViewId) async {
await addMessageToNewPage(context, parentViewId);
popoverController.close();
},
onAddToExistingPage: (documentId) async {
final view = await onAddToExistingPage(context, documentId);
if (context.mounted) {
openPageFromMessage(context, view);
}
await Future.delayed(const Duration(milliseconds: 500));
await updateSelection(documentId);
popoverController.close();
},
),
);
}
Future<ViewPB?> onAddToExistingPage(
BuildContext context,
String documentId,
) async {
final bloc = context.read<ChatSelectMessageBloc>();
final selectedMessages = [
...bloc.state.selectedMessages.whereType<TextMessage>(),
]..sort((a, b) => a.createdAt.compareTo(b.createdAt));
await ChatEditDocumentService.addMessagesToPage(
documentId,
selectedMessages,
);
await Future.delayed(const Duration(milliseconds: 500));
final view = await ViewBackendService.getView(documentId).toNullable();
if (context.mounted) {
showSaveMessageSuccessToast(context, view);
}
bloc.add(const ChatSelectMessageEvent.saveAsPage());
return view;
}
Future<void> addMessageToNewPage(
BuildContext context,
String parentViewId,
) async {
final bloc = context.read<ChatSelectMessageBloc>();
final selectedMessages = [
...bloc.state.selectedMessages.whereType<TextMessage>(),
]..sort((a, b) => a.createdAt.compareTo(b.createdAt));
final newView = await ChatEditDocumentService.saveMessagesToNewPage(
widget.view.nameOrDefault,
parentViewId,
selectedMessages,
);
if (context.mounted) {
showSaveMessageSuccessToast(context, newView);
openPageFromMessage(context, newView);
}
bloc.add(const ChatSelectMessageEvent.saveAsPage());
}
Future<void> forceReload(String documentId) async {
final bloc = DocumentBloc.findOpen(documentId);
if (bloc == null) {
return;
}
await bloc.forceReloadDocumentState();
}
Future<void> updateSelection(String documentId) async {
final bloc = DocumentBloc.findOpen(documentId);
if (bloc == null) {
return;
}
await bloc.forceReloadDocumentState();
final editorState = bloc.state.editorState;
final lastNodePath = editorState?.getLastSelectable()?.$1.path;
if (editorState == null || lastNodePath == null) {
return;
}
unawaited(
editorState.updateSelectionWithReason(
Selection.collapsed(Position(path: lastNodePath)),
),
);
}
String? getOpenedDocumentId() {
final pageManager = getIt<TabsBloc>().state.currentPageManager;
if (!pageManager.showSecondaryPluginNotifier.value) {
return null;
}
return pageManager.secondaryNotifier.plugin.id;
}
}
@@ -3,6 +3,8 @@ import 'package:flutter/material.dart';
import 'package:universal_platform/universal_platform.dart';
class AIChatUILayout {
const AIChatUILayout._();
static EdgeInsets safeAreaInsets(BuildContext context) {
final query = MediaQuery.of(context);
return UniversalPlatform.isMobile
@@ -28,63 +30,22 @@ class AIChatUILayout {
}
}
class DesktopAIPromptSizes {
static const promptFrameRadius = BorderRadius.all(Radius.circular(12.0));
class DesktopAIChatSizes {
const DesktopAIChatSizes._();
static const attachedFilesBarPadding =
EdgeInsets.only(left: 8.0, top: 8.0, right: 8.0);
static const attachedFilesPreviewHeight = 48.0;
static const attachedFilesPreviewSpacing = 12.0;
static const predefinedFormatButtonHeight = 28.0;
static const predefinedFormatIconHeight = 16.0;
static const predefinedFormatBarButtonSpacing = 4.0;
static const textFieldMinHeight = 36.0;
static const textFieldContentPadding =
EdgeInsetsDirectional.fromSTEB(14.0, 8.0, 14.0, 8.0);
static const actionBarHeight = 32.0;
static const actionBarPadding = EdgeInsetsDirectional.fromSTEB(8, 0, 8, 4);
static const actionBarButtonSize = 28.0;
static const actionBarIconSize = 16.0;
static const actionBarButtonSpacing = 4.0;
static const sendButtonSize = 24.0;
}
class MobileAIPromptSizes {
static const promptFrameRadius =
BorderRadius.vertical(top: Radius.circular(8.0));
static const attachedFilesBarHeight = 68.0;
static const attachedFilesBarPadding =
EdgeInsets.only(top: 8.0, left: 8.0, right: 8.0, bottom: 4.0);
static const attachedFilesPreviewHeight = 56.0;
static const attachedFilesPreviewSpacing = 8.0;
static const predefinedFormatButtonHeight = 32.0;
static const predefinedFormatIconHeight = 20.0;
static const predefinedFormatBarButtonSpacing = 8.0;
static const predefinedFormatBarPadding = EdgeInsets.all(8.0);
static const textFieldMinHeight = 32.0;
static const textFieldContentPadding =
EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0);
static const mentionIconSize = 20.0;
static const sendButtonSize = 32.0;
}
class DesktopAIConvoSizes {
static const avatarSize = 32.0;
static const avatarAndChatBubbleSpacing = 12.0;
static const actionBarIconSize = 28.0;
static const actionBarIconSpacing = 8.0;
static const hoverActionBarPadding = EdgeInsets.all(2.0);
static const hoverActionBarRadius = BorderRadius.all(Radius.circular(8.0));
static const hoverActionBarIconRadius =
static const messageActionBarIconSize = 28.0;
static const messageHoverActionBarPadding = EdgeInsets.all(2.0);
static const messageHoverActionBarRadius =
BorderRadius.all(Radius.circular(8.0));
static const messageHoverActionBarIconRadius =
BorderRadius.all(Radius.circular(6.0));
static const actionBarIconRadius = BorderRadius.all(Radius.circular(8.0));
static const messageActionBarIconRadius =
BorderRadius.all(Radius.circular(8.0));
static const inputActionBarMargin =
EdgeInsetsDirectional.fromSTEB(8, 0, 8, 4);
static const inputActionBarButtonSpacing = 4.0;
}
@@ -52,7 +52,7 @@ class _AppFlowyEditorMarkdownState extends State<_AppFlowyEditorMarkdown> {
void initState() {
super.initState();
editorState = _parseMarkdown(widget.markdown);
editorState = _parseMarkdown(widget.markdown.trim());
scrollController = EditorScrollController(
editorState: editorState,
shrinkWrap: true,
@@ -65,7 +65,7 @@ class _AppFlowyEditorMarkdownState extends State<_AppFlowyEditorMarkdown> {
if (oldWidget.markdown != widget.markdown) {
editorState.dispose();
editorState = _parseMarkdown(widget.markdown);
editorState = _parseMarkdown(widget.markdown.trim());
scrollController.dispose();
scrollController = EditorScrollController(
editorState: editorState,
@@ -1,6 +1,9 @@
import 'dart:async';
import 'dart:convert';
import 'package:appflowy/ai/widgets/prompt_input/layout_define.dart';
import 'package:appflowy/ai/widgets/prompt_input/predefined_format_buttons.dart';
import 'package:appflowy/ai/widgets/prompt_input/select_sources_menu.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_ai_message_bloc.dart';
@@ -10,6 +13,7 @@ import 'package:appflowy/plugins/ai_chat/application/chat_select_sources_cubit.d
import 'package:appflowy/plugins/document/application/prelude.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/clipboard_service.dart';
import 'package:appflowy/shared/markdown_to_document.dart';
import 'package:appflowy/shared/patterns/common_patterns.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/util/theme_extension.dart';
import 'package:appflowy/workspace/application/sidebar/space/space_bloc.dart';
@@ -30,8 +34,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_chat_core/flutter_chat_core.dart';
import '../chat_input/predefined_format_buttons.dart';
import '../chat_input/select_sources_menu.dart';
import '../layout_define.dart';
import 'message_util.dart';
@@ -64,16 +66,15 @@ class _AIMessageActionBarState extends State<AIMessageActionBar> {
final child = SeparatedRow(
mainAxisSize: MainAxisSize.min,
separatorBuilder: () =>
const HSpace(DesktopAIConvoSizes.actionBarIconSpacing),
separatorBuilder: () => const HSpace(8.0),
children: _buildChildren(),
);
return widget.showDecoration
? Container(
padding: const EdgeInsets.all(2.0),
padding: DesktopAIChatSizes.messageHoverActionBarPadding,
decoration: BoxDecoration(
borderRadius: DesktopAIConvoSizes.hoverActionBarRadius,
borderRadius: DesktopAIChatSizes.messageHoverActionBarRadius,
border: Border.all(
color: isLightMode
? const Color(0x1F1F2329)
@@ -153,21 +154,25 @@ class CopyButton extends StatelessWidget {
return FlowyTooltip(
message: LocaleKeys.settings_menu_clickToCopy.tr(),
child: FlowyIconButton(
width: DesktopAIConvoSizes.actionBarIconSize,
width: DesktopAIChatSizes.messageActionBarIconSize,
hoverColor: AFThemeExtension.of(context).lightGreyHover,
radius: isInHoverBar
? DesktopAIConvoSizes.hoverActionBarIconRadius
: DesktopAIConvoSizes.actionBarIconRadius,
? DesktopAIChatSizes.messageHoverActionBarIconRadius
: DesktopAIChatSizes.messageActionBarIconRadius,
icon: FlowySvg(
FlowySvgs.copy_s,
color: Theme.of(context).hintColor,
size: const Size.square(16),
),
onPressed: () async {
final document = customMarkdownToDocument(textMessage.text);
final messageText = textMessage.text.trim();
final document = customMarkdownToDocument(
messageText,
tableWidth: 250.0,
);
await getIt<ClipboardService>().setData(
ClipboardServiceData(
plainText: textMessage.text,
plainText: _stripMarkdownIfNecessary(messageText),
inAppJson: jsonEncode(document.toJson()),
),
);
@@ -181,6 +186,17 @@ class CopyButton extends StatelessWidget {
),
);
}
String _stripMarkdownIfNecessary(String plainText) {
// match and capture inner url as group
final matches = singleLineMarkdownImageRegex.allMatches(plainText);
if (matches.length != 1) {
return plainText;
}
return matches.first[1] ?? plainText;
}
}
class RegenerateButton extends StatelessWidget {
@@ -198,11 +214,11 @@ class RegenerateButton extends StatelessWidget {
return FlowyTooltip(
message: LocaleKeys.chat_regenerate.tr(),
child: FlowyIconButton(
width: DesktopAIConvoSizes.actionBarIconSize,
width: DesktopAIChatSizes.messageActionBarIconSize,
hoverColor: AFThemeExtension.of(context).lightGreyHover,
radius: isInHoverBar
? DesktopAIConvoSizes.hoverActionBarIconRadius
: DesktopAIConvoSizes.actionBarIconRadius,
? DesktopAIChatSizes.messageHoverActionBarIconRadius
: DesktopAIChatSizes.messageActionBarIconRadius,
icon: FlowySvg(
FlowySvgs.ai_undo_s,
color: Theme.of(context).hintColor,
@@ -258,11 +274,11 @@ class _ChangeFormatButtonState extends State<ChangeFormatButton> {
message: LocaleKeys.chat_changeFormat_actionButton.tr(),
child: FlowyIconButton(
width: 32.0,
height: DesktopAIConvoSizes.actionBarIconSize,
height: DesktopAIChatSizes.messageActionBarIconSize,
hoverColor: AFThemeExtension.of(context).lightGreyHover,
radius: widget.isInHoverBar
? DesktopAIConvoSizes.hoverActionBarIconRadius
: DesktopAIConvoSizes.actionBarIconRadius,
? DesktopAIChatSizes.messageHoverActionBarIconRadius
: DesktopAIChatSizes.messageActionBarIconRadius,
icon: Row(
mainAxisSize: MainAxisSize.min,
children: [
@@ -309,7 +325,7 @@ class _ChangeFormatPopoverContentState
return Container(
padding: const EdgeInsets.all(2.0),
decoration: BoxDecoration(
borderRadius: DesktopAIConvoSizes.hoverActionBarRadius,
borderRadius: DesktopAIChatSizes.messageHoverActionBarRadius,
border: Border.all(
color: isLightMode
? const Color(0x1F1F2329)
@@ -348,8 +364,6 @@ class _ChangeFormatPopoverContentState
children: [
ChangeFormatBar(
spacing: 2.0,
iconSize: 16.0,
buttonSize: DesktopAIPromptSizes.predefinedFormatButtonHeight,
predefinedFormat: predefinedFormat,
onSelectPredefinedFormat: (format) {
setState(() => predefinedFormat = format);
@@ -456,11 +470,11 @@ class _SaveToPageButtonState extends State<SaveToPageButton> {
return FlowyTooltip(
message: LocaleKeys.chat_addToPageButton.tr(),
child: FlowyIconButton(
width: DesktopAIConvoSizes.actionBarIconSize,
width: DesktopAIChatSizes.messageActionBarIconSize,
hoverColor: AFThemeExtension.of(context).lightGreyHover,
radius: widget.isInHoverBar
? DesktopAIConvoSizes.hoverActionBarIconRadius
: DesktopAIConvoSizes.actionBarIconRadius,
? DesktopAIChatSizes.messageHoverActionBarIconRadius
: DesktopAIChatSizes.messageActionBarIconRadius,
icon: FlowySvg(
FlowySvgs.ai_add_to_page_s,
color: Theme.of(context).hintColor,
@@ -490,7 +504,7 @@ class _SaveToPageButtonState extends State<SaveToPageButton> {
Widget buildPopover(BuildContext context) {
return BlocProvider.value(
value: context.read<ChatSettingsCubit>(),
child: _SaveToPagePopoverContent(
child: SaveToPagePopoverContent(
onAddToNewPage: (parentViewId) {
addMessageToNewPage(context, parentViewId);
popoverController.close();
@@ -513,9 +527,9 @@ class _SaveToPageButtonState extends State<SaveToPageButton> {
BuildContext context,
String documentId,
) async {
await ChatEditDocumentService.addMessageToPage(
await ChatEditDocumentService.addMessagesToPage(
documentId,
widget.textMessage,
[widget.textMessage],
);
await Future.delayed(const Duration(milliseconds: 500));
final view = await ViewBackendService.getView(documentId).toNullable();
@@ -543,35 +557,6 @@ class _SaveToPageButtonState extends State<SaveToPageButton> {
}
}
void showSaveMessageSuccessToast(BuildContext context, ViewPB? view) {
if (view == null) {
return;
}
showToastNotification(
context,
richMessage: TextSpan(
children: [
TextSpan(
text: LocaleKeys.chat_addToNewPageSuccessToast.tr(),
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: const Color(0xFFFFFFFF),
),
),
const TextSpan(
text: ' ',
),
TextSpan(
text: view.nameOrDefault,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: const Color(0xFFFFFFFF),
fontWeight: FontWeight.w700,
),
),
],
),
);
}
Future<void> forceReload(String documentId) async {
final bloc = DocumentBloc.findOpen(documentId);
if (bloc == null) {
@@ -607,8 +592,9 @@ class _SaveToPageButtonState extends State<SaveToPageButton> {
}
}
class _SaveToPagePopoverContent extends StatelessWidget {
const _SaveToPagePopoverContent({
class SaveToPagePopoverContent extends StatelessWidget {
const SaveToPagePopoverContent({
super.key,
required this.onAddToNewPage,
required this.onAddToExistingPage,
});
@@ -6,6 +6,7 @@ import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart';
import 'package:appflowy/mobile/presentation/widgets/flowy_mobile_quick_action_button.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_edit_document_service.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_entity.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_select_message_bloc.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/clipboard_service.dart';
import 'package:appflowy/shared/markdown_to_document.dart';
import 'package:appflowy/startup/startup.dart';
@@ -15,12 +16,13 @@ import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_chat_core/flutter_chat_core.dart';
import 'package:go_router/go_router.dart';
import 'package:universal_platform/universal_platform.dart';
import '../chat_avatar.dart';
import '../chat_input/chat_mention_page_bottom_sheet.dart';
import '../../../../ai/widgets/prompt_input/mention_page_bottom_sheet.dart';
import '../layout_define.dart';
import 'ai_message_action_bar.dart';
import 'ai_change_format_bottom_sheet.dart';
@@ -37,6 +39,7 @@ class ChatAIMessageBubble extends StatelessWidget {
required this.child,
required this.showActions,
this.isLastMessage = false,
this.isSelectingMessages = false,
this.onRegenerate,
this.onChangeFormat,
});
@@ -45,27 +48,25 @@ class ChatAIMessageBubble extends StatelessWidget {
final Widget child;
final bool showActions;
final bool isLastMessage;
final bool isSelectingMessages;
final void Function()? onRegenerate;
final void Function(PredefinedFormat)? onChangeFormat;
@override
Widget build(BuildContext context) {
final avatarAndMessage = Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const ChatAIAvatar(),
const HSpace(DesktopAIConvoSizes.avatarAndChatBubbleSpacing),
Expanded(child: child),
],
final messageWidget = _WrapIsSelectingMessage(
isSelectingMessages: isSelectingMessages,
message: message,
child: child,
);
return showActions
return !isSelectingMessages && showActions
? UniversalPlatform.isMobile
? _wrapPopMenu(avatarAndMessage)
? _wrapPopMenu(messageWidget)
: isLastMessage
? _wrapBottomActions(avatarAndMessage)
: _wrapHover(avatarAndMessage)
: avatarAndMessage;
? _wrapBottomActions(messageWidget)
: _wrapHover(messageWidget)
: messageWidget;
}
Widget _wrapBottomActions(Widget child) {
@@ -119,8 +120,8 @@ class ChatAIBottomInlineActions extends StatelessWidget {
const VSpace(16.0),
Padding(
padding: const EdgeInsetsDirectional.only(
start: DesktopAIConvoSizes.avatarSize +
DesktopAIConvoSizes.avatarAndChatBubbleSpacing,
start: DesktopAIChatSizes.avatarSize +
DesktopAIChatSizes.avatarAndChatBubbleSpacing,
),
child: AIMessageActionBar(
message: message,
@@ -199,8 +200,8 @@ class _ChatAIMessageHoverState extends State<ChatAIMessageHover> {
link: layerLink,
targetAnchor: Alignment.bottomLeft,
offset: const Offset(
DesktopAIConvoSizes.avatarSize +
DesktopAIConvoSizes.avatarAndChatBubbleSpacing,
DesktopAIChatSizes.avatarSize +
DesktopAIChatSizes.avatarAndChatBubbleSpacing,
0,
),
child: Align(
@@ -220,10 +221,10 @@ class _ChatAIMessageHoverState extends State<ChatAIMessageHover> {
child: Container(
constraints: BoxConstraints(
maxWidth: 784,
maxHeight: DesktopAIConvoSizes.actionBarIconSize +
DesktopAIConvoSizes.hoverActionBarPadding.vertical,
maxHeight: DesktopAIChatSizes.messageActionBarIconSize +
DesktopAIChatSizes
.messageHoverActionBarPadding.vertical,
),
alignment: Alignment.topLeft,
child: hoverBubble || hoverActionBar || overrideVisibility
? AIMessageActionBar(
message: widget.message,
@@ -283,8 +284,8 @@ class _ChatAIMessageHoverState extends State<ChatAIMessageHover> {
return messageOffset.dy +
messageHeight +
DesktopAIConvoSizes.actionBarIconSize +
DesktopAIConvoSizes.hoverActionBarPadding.vertical <=
DesktopAIChatSizes.messageActionBarIconSize +
DesktopAIChatSizes.messageHoverActionBarPadding.vertical <=
scrollableOffset.dy + scrollableHeight;
}
@@ -413,9 +414,9 @@ class ChatAIMessagePopup extends StatelessWidget {
return;
}
await ChatEditDocumentService.addMessageToPage(
await ChatEditDocumentService.addMessagesToPage(
selectedView.id,
message as TextMessage,
[message as TextMessage],
);
if (context.mounted) {
@@ -429,3 +430,85 @@ class ChatAIMessagePopup extends StatelessWidget {
);
}
}
class _WrapIsSelectingMessage extends StatelessWidget {
const _WrapIsSelectingMessage({
required this.message,
required this.child,
this.isSelectingMessages = false,
});
final Message message;
final Widget child;
final bool isSelectingMessages;
@override
Widget build(BuildContext context) {
return BlocBuilder<ChatSelectMessageBloc, ChatSelectMessageState>(
builder: (context, state) {
final isSelected =
context.read<ChatSelectMessageBloc>().isMessageSelected(message.id);
return GestureDetector(
onTap: () {
if (isSelectingMessages) {
context
.read<ChatSelectMessageBloc>()
.add(ChatSelectMessageEvent.toggleSelectMessage(message));
}
},
behavior: isSelectingMessages ? HitTestBehavior.opaque : null,
child: DecoratedBox(
decoration: BoxDecoration(
color: isSelected
? Theme.of(context).colorScheme.tertiaryContainer
: null,
borderRadius: const BorderRadius.all(Radius.circular(8.0)),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (isSelectingMessages)
ChatSelectMessageIndicator(isSelected: isSelected)
else
const ChatAIAvatar(),
const HSpace(DesktopAIChatSizes.avatarAndChatBubbleSpacing),
Expanded(
child: IgnorePointer(
ignoring: isSelectingMessages,
child: child,
),
),
],
),
),
);
},
);
}
}
class ChatSelectMessageIndicator extends StatelessWidget {
const ChatSelectMessageIndicator({
super.key,
required this.isSelected,
});
final bool isSelected;
@override
Widget build(BuildContext context) {
return MouseRegion(
cursor: SystemMouseCursors.click,
child: SizedBox.square(
dimension: 30.0,
child: Center(
child: FlowySvg(
isSelected ? FlowySvgs.check_filled_s : FlowySvgs.uncheck_s,
blendMode: BlendMode.dst,
size: const Size.square(20),
),
),
),
);
}
}
@@ -1,3 +1,4 @@
import 'package:appflowy/ai/widgets/loading_indicator.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_ai_message_bloc.dart';
import 'package:appflowy/plugins/ai_chat/application/chat_bloc.dart';
@@ -15,7 +16,6 @@ import '../layout_define.dart';
import 'ai_markdown_text.dart';
import 'ai_message_bubble.dart';
import 'ai_metadata.dart';
import 'loading_indicator.dart';
import 'error_text_message.dart';
/// [ChatAIMessageWidget] includes both the text of the AI response as well as
@@ -38,6 +38,7 @@ class ChatAIMessageWidget extends StatelessWidget {
this.onChangeFormat,
this.isLastMessage = false,
this.isStreaming = false,
this.isSelectingMessages = false,
});
final User user;
@@ -53,6 +54,7 @@ class ChatAIMessageWidget extends StatelessWidget {
final void Function(PredefinedFormat)? onChangeFormat;
final bool isStreaming;
final bool isLastMessage;
final bool isSelectingMessages;
@override
Widget build(BuildContext context) {
@@ -83,14 +85,14 @@ class ChatAIMessageWidget extends StatelessWidget {
loading: () => ChatAIMessageBubble(
message: message,
showActions: false,
child: ChatAILoading(text: loadingText),
child: AILoadingIndicator(text: loadingText),
),
ready: () {
return state.text.isEmpty
? ChatAIMessageBubble(
message: message,
showActions: false,
child: ChatAILoading(text: loadingText),
child: AILoadingIndicator(text: loadingText),
)
: ChatAIMessageBubble(
message: message,
@@ -98,6 +100,7 @@ class ChatAIMessageWidget extends StatelessWidget {
showActions: stream == null &&
state.text.isNotEmpty &&
!isStreaming,
isSelectingMessages: isSelectingMessages,
onRegenerate: onRegenerate,
onChangeFormat: onChangeFormat,
child: Column(
@@ -129,6 +132,16 @@ class ChatAIMessageWidget extends StatelessWidget {
LocaleKeys.sideBar_askOwnerToUpgradeToAIMax.tr(),
);
},
onAIImageResponseLimit: () {
return ChatErrorMessageWidget(
errorMessage: LocaleKeys.sideBar_purchaseAIMax.tr(),
);
},
onAIMaxRequired: (message) {
return ChatErrorMessageWidget(
errorMessage: message,
);
},
),
),
);
@@ -6,7 +6,7 @@ import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import 'package:universal_platform/universal_platform.dart';
/// Opens a message in the right hand sidebar on desktop, and push the page
@@ -30,3 +30,32 @@ void openPageFromMessage(BuildContext context, ViewPB? view) {
context.pushView(view);
}
}
void showSaveMessageSuccessToast(BuildContext context, ViewPB? view) {
if (view == null) {
return;
}
showToastNotification(
context,
richMessage: TextSpan(
children: [
TextSpan(
text: LocaleKeys.chat_addToNewPageSuccessToast.tr(),
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: const Color(0xFFFFFFFF),
),
),
const TextSpan(
text: ' ',
),
TextSpan(
text: view.nameOrDefault,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: const Color(0xFFFFFFFF),
fontWeight: FontWeight.w700,
),
),
],
),
);
}
@@ -58,13 +58,13 @@ class ChatUserMessageBubble extends StatelessWidget {
return [
const Spacer(),
_buildBubble(context),
const HSpace(DesktopAIConvoSizes.avatarAndChatBubbleSpacing),
const HSpace(DesktopAIChatSizes.avatarAndChatBubbleSpacing),
_buildAvatar(),
];
} else {
return [
_buildAvatar(),
const HSpace(DesktopAIConvoSizes.avatarAndChatBubbleSpacing),
const HSpace(DesktopAIChatSizes.avatarAndChatBubbleSpacing),
_buildBubble(context),
const Spacer(),
];
@@ -12,17 +12,20 @@ class MobileEmojiPickerScreen extends StatelessWidget {
super.key,
this.title,
this.selectedType,
this.documentId,
this.tabs = const [PickerTabType.emoji, PickerTabType.icon],
});
final PickerTabType? selectedType;
final String? title;
final String? documentId;
final List<PickerTabType> tabs;
static const routeName = '/emoji_picker';
static const pageTitle = 'title';
static const iconSelectedType = 'iconSelectedType';
static const iconSelectedType = 'iconSelected_type';
static const selectTabs = 'tabs';
static const uploadDocumentId = 'document_id';
@override
Widget build(BuildContext context) {
@@ -33,6 +36,7 @@ class MobileEmojiPickerScreen extends StatelessWidget {
body: SafeArea(
child: FlowyIconEmojiPicker(
tabs: tabs,
documentId: documentId,
initialType: selectedType,
onSelectedEmoji: (r) {
context.pop<EmojiIconData>(r.data);
@@ -32,6 +32,7 @@ class EmojiText extends StatelessWidget {
strutStyle: const StrutStyle(forceStrutHeight: true),
fallbackFontFamily: _cachedFallbackFontFamily,
lineHeight: lineHeight,
isEmoji: true,
);
}
@@ -1,6 +1,7 @@
import 'dart:io';
import 'package:appflowy/util/field_type_extension.dart';
import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart';
import 'package:flutter/material.dart' hide Card;
import 'package:flutter/services.dart';
@@ -856,10 +857,13 @@ void _openCard({
FlowyOverlay.show(
context: context,
builder: (_) => RowDetailPage(
databaseController: databaseController,
rowController: rowController,
userProfile: context.read<BoardBloc>().userProfile,
builder: (_) => BlocProvider.value(
value: context.read<UserWorkspaceBloc>(),
child: RowDetailPage(
databaseController: databaseController,
rowController: rowController,
userProfile: context.read<BoardBloc>().userProfile,
),
),
);
}
@@ -1,5 +1,6 @@
import 'dart:io';
import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart';
import 'package:flutter/material.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
@@ -426,10 +427,13 @@ class HiddenGroupPopupItemList extends StatelessWidget {
onPressed: () {
FlowyOverlay.show(
context: context,
builder: (_) => RowDetailPage(
databaseController: databaseController,
rowController: rowController,
userProfile: context.read<BoardBloc>().userProfile,
builder: (_) => BlocProvider.value(
value: context.read<UserWorkspaceBloc>(),
child: RowDetailPage(
databaseController: databaseController,
rowController: rowController,
userProfile: context.read<BoardBloc>().userProfile,
),
),
);
PopoverContainer.of(context).close();
@@ -1,5 +1,6 @@
import 'package:appflowy/plugins/database/application/row/row_controller.dart';
import 'package:appflowy/plugins/database/widgets/row/row_detail.dart';
import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart';
import 'package:flutter/material.dart';
import 'package:appflowy/mobile/presentation/database/card/card_detail/mobile_card_detail_screen.dart';
@@ -178,10 +179,13 @@ class _EventCardState extends State<EventCard> {
FlowyOverlay.show(
context: context,
builder: (_) => RowDetailPage(
databaseController: widget.databaseController,
rowController: rowController,
userProfile: context.read<CalendarBloc>().userProfile,
builder: (_) => BlocProvider.value(
value: context.read<UserWorkspaceBloc>(),
child: RowDetailPage(
databaseController: widget.databaseController,
rowController: rowController,
userProfile: context.read<CalendarBloc>().userProfile,
),
),
);
},
@@ -1,5 +1,6 @@
import 'package:appflowy/plugins/database/grid/presentation/grid_page.dart';
import 'package:appflowy/plugins/database/tab_bar/desktop/setting_menu.dart';
import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:flutter/material.dart';
@@ -13,7 +14,6 @@ import 'package:appflowy/plugins/database/calendar/application/calendar_bloc.dar
import 'package:appflowy/plugins/database/calendar/application/unschedule_event_bloc.dart';
import 'package:appflowy/plugins/database/grid/presentation/layout/sizes.dart';
import 'package:appflowy/plugins/database/tab_bar/tab_bar_view.dart';
import 'package:appflowy/workspace/application/view/view_bloc.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:calendar_view/calendar_view.dart';
import 'package:easy_localization/easy_localization.dart';
@@ -390,7 +390,7 @@ void showEventDetails({
context: context,
builder: (BuildContext overlayContext) {
return BlocProvider.value(
value: context.read<ViewBloc>(),
value: context.read<UserWorkspaceBloc>(),
child: RowDetailPage(
rowController: rowController,
databaseController: databaseController,
@@ -457,14 +457,18 @@ class _UnscheduledEventsButtonState extends State<UnscheduledEventsButton> {
),
),
),
popupBuilder: (_) => BlocProvider.value(
value: context.read<CalendarBloc>(),
child: BlocProvider.value(
value: context.read<ViewBloc>(),
child: UnscheduleEventsList(
databaseController: widget.databaseController,
unscheduleEvents: state.unscheduleEvents,
popupBuilder: (_) => MultiBlocProvider(
providers: [
BlocProvider.value(
value: context.read<CalendarBloc>(),
),
BlocProvider.value(
value: context.read<UserWorkspaceBloc>(),
),
],
child: UnscheduleEventsList(
databaseController: widget.databaseController,
unscheduleEvents: state.unscheduleEvents,
),
),
);
@@ -2,6 +2,7 @@ import 'dart:async';
import 'package:appflowy/plugins/database/grid/presentation/widgets/toolbar/grid_setting_bar.dart';
import 'package:appflowy/plugins/database/tab_bar/desktop/setting_menu.dart';
import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart';
import 'package:flutter/material.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
@@ -13,7 +14,6 @@ import 'package:appflowy/plugins/database/widgets/cell/editable_cell_builder.dar
import 'package:appflowy/shared/flowy_error_page.dart';
import 'package:appflowy/workspace/application/action_navigation/action_navigation_bloc.dart';
import 'package:appflowy/workspace/application/action_navigation/navigation_action.dart';
import 'package:appflowy/workspace/application/view/view_bloc.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
@@ -196,7 +196,7 @@ class _GridPageState extends State<GridPage> {
FlowyOverlay.show(
context: context,
builder: (_) => BlocProvider.value(
value: context.read<ViewBloc>(),
value: context.read<UserWorkspaceBloc>(),
child: RowDetailPage(
databaseController: context.read<GridBloc>().databaseController,
rowController: rowController,
@@ -233,7 +233,7 @@ class _GridPageState extends State<GridPage> {
FlowyOverlay.show(
context: context,
builder: (_) => BlocProvider.value(
value: context.read<ViewBloc>(),
value: context.read<UserWorkspaceBloc>(),
child: RowDetailPage(
databaseController:
context.read<GridBloc>().databaseController,
@@ -559,7 +559,7 @@ class _GridRowsState extends State<_GridRows> {
}
return BlocProvider.value(
value: context.read<ViewBloc>(),
value: context.read<UserWorkspaceBloc>(),
child: RowDetailPage(
rowController: RowController(
viewId: viewId,
@@ -2,7 +2,11 @@ import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/database/application/tab_bar_bloc.dart';
import 'package:appflowy/plugins/database/tab_bar/tab_bar_view.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/icon_emoji_picker/tab.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy/workspace/application/view/view_service.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
@@ -115,9 +119,9 @@ class _DatabaseTabBarState extends State<DatabaseTabBar> {
view: state.tabBars[index].view,
isSelected: state.selectedIndex == index,
onTap: (selectedView) {
context.read<DatabaseTabBarBloc>().add(
DatabaseTabBarEvent.selectView(selectedView.id),
);
context
.read<DatabaseTabBarBloc>()
.add(DatabaseTabBarEvent.selectView(selectedView.id));
},
),
separatorBuilder: (context, index) => VerticalDivider(
@@ -179,7 +183,7 @@ class DatabaseTabBarItem extends StatelessWidget {
}
}
class TabBarItemButton extends StatelessWidget {
class TabBarItemButton extends StatefulWidget {
const TabBarItemButton({
super.key,
required this.view,
@@ -191,77 +195,150 @@ class TabBarItemButton extends StatelessWidget {
final bool isSelected;
final VoidCallback onTap;
@override
State<TabBarItemButton> createState() => _TabBarItemButtonState();
}
class _TabBarItemButtonState extends State<TabBarItemButton> {
final menuController = PopoverController();
final iconController = PopoverController();
@override
Widget build(BuildContext context) {
return PopoverActionList<TabBarViewAction>(
Color? color;
if (!widget.isSelected) {
color = Theme.of(context).hintColor;
}
if (Theme.of(context).brightness == Brightness.dark) {
color = null;
}
return AppFlowyPopover(
controller: menuController,
constraints: const BoxConstraints(
minWidth: 120,
maxWidth: 460,
maxHeight: 300,
),
direction: PopoverDirection.bottomWithCenterAligned,
actions: TabBarViewAction.values,
buildChild: (controller) {
Color? color;
if (!isSelected) {
color = Theme.of(context).hintColor;
}
if (Theme.of(context).brightness == Brightness.dark) {
color = null;
}
return IntrinsicWidth(
child: FlowyButton(
radius: Corners.s6Border,
hoverColor: AFThemeExtension.of(context).greyHover,
onTap: onTap,
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 5),
onSecondaryTap: () {
controller.show();
},
leftIcon: FlowySvg(
view.iconData,
size: const Size(14, 14),
color: color,
),
text: FlowyText(
view.nameOrDefault,
lineHeight: 1.0,
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
color: color,
fontWeight: isSelected ? FontWeight.w500 : FontWeight.w400,
clickHandler: PopoverClickHandler.gestureDetector,
popupBuilder: (_) {
return IntrinsicHeight(
child: IntrinsicWidth(
child: Column(
children: [
ActionCellWidget(
action: TabBarViewAction.rename,
itemHeight: ActionListSizes.itemHeight,
onSelected: (action) {
NavigatorTextFieldDialog(
title: LocaleKeys.menuAppHeader_renameDialog.tr(),
value: widget.view.nameOrDefault,
onConfirm: (newValue, _) {
context.read<DatabaseTabBarBloc>().add(
DatabaseTabBarEvent.renameView(
widget.view.id,
newValue,
),
);
},
).show(context);
menuController.close();
},
),
AppFlowyPopover(
controller: iconController,
direction: PopoverDirection.rightWithCenterAligned,
constraints: BoxConstraints.loose(const Size(364, 356)),
margin: const EdgeInsets.all(0),
child: ActionCellWidget(
action: TabBarViewAction.changeIcon,
itemHeight: ActionListSizes.itemHeight,
onSelected: (action) {
iconController.show();
},
),
popupBuilder: (context) {
return FlowyIconEmojiPicker(
tabs: const [PickerTabType.icon],
enableBackgroundColorSelection: false,
onSelectedEmoji: (r) {
ViewBackendService.updateViewIcon(
viewId: widget.view.id,
viewIcon: r.data,
);
if (!r.keepOpen) {
iconController.close();
menuController.close();
}
},
);
},
),
ActionCellWidget(
action: TabBarViewAction.delete,
itemHeight: ActionListSizes.itemHeight,
onSelected: (action) {
NavigatorAlertDialog(
title: LocaleKeys.grid_deleteView.tr(),
confirm: () {
context.read<DatabaseTabBarBloc>().add(
DatabaseTabBarEvent.deleteView(widget.view.id),
);
},
).show(context);
menuController.close();
},
),
],
),
),
);
},
onSelected: (action, controller) {
switch (action) {
case TabBarViewAction.rename:
NavigatorTextFieldDialog(
title: LocaleKeys.menuAppHeader_renameDialog.tr(),
value: view.nameOrDefault,
onConfirm: (newValue, _) {
context.read<DatabaseTabBarBloc>().add(
DatabaseTabBarEvent.renameView(view.id, newValue),
);
},
).show(context);
break;
case TabBarViewAction.delete:
NavigatorAlertDialog(
title: LocaleKeys.grid_deleteView.tr(),
confirm: () {
context.read<DatabaseTabBarBloc>().add(
DatabaseTabBarEvent.deleteView(view.id),
);
},
).show(context);
break;
}
controller.close();
},
child: IntrinsicWidth(
child: FlowyButton(
radius: Corners.s6Border,
hoverColor: AFThemeExtension.of(context).greyHover,
onTap: () {
if (widget.isSelected) menuController.show();
widget.onTap.call();
},
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 5),
onSecondaryTap: () {
menuController.show();
},
leftIcon: _buildViewIcon(),
text: FlowyText(
widget.view.nameOrDefault,
lineHeight: 1.0,
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
color: color,
fontWeight: widget.isSelected ? FontWeight.w500 : FontWeight.w400,
),
),
),
);
}
Widget _buildViewIcon() {
final iconData = widget.view.icon.toEmojiIconData();
Widget icon;
if (iconData.isEmpty || iconData.type != FlowyIconType.icon) {
icon = widget.view.defaultIcon();
} else {
icon = RawEmojiIconWidget(
emoji: iconData,
emojiSize: 14.0,
enableColor: false,
);
}
return Opacity(opacity: 0.6, child: icon);
}
}
enum TabBarViewAction implements ActionCell {
rename,
changeIcon,
delete;
@override
@@ -269,6 +346,8 @@ enum TabBarViewAction implements ActionCell {
switch (this) {
case TabBarViewAction.rename:
return LocaleKeys.disclosureAction_rename.tr();
case TabBarViewAction.changeIcon:
return LocaleKeys.disclosureAction_changeIcon.tr();
case TabBarViewAction.delete:
return LocaleKeys.disclosureAction_delete.tr();
}
@@ -278,6 +357,8 @@ enum TabBarViewAction implements ActionCell {
switch (this) {
case TabBarViewAction.rename:
return const FlowySvg(FlowySvgs.edit_s);
case TabBarViewAction.changeIcon:
return const FlowySvg(FlowySvgs.change_icon_s);
case TabBarViewAction.delete:
return const FlowySvg(FlowySvgs.delete_s);
}
@@ -1,18 +1,17 @@
import 'package:appflowy/plugins/database/grid/presentation/layout/sizes.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:flutter/material.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/mobile/presentation/bottom_sheet/show_transition_bottom_sheet.dart';
import 'package:appflowy/mobile/presentation/database/view/database_view_list.dart';
import 'package:appflowy/plugins/database/application/tab_bar_bloc.dart';
import 'package:appflowy/plugins/database/grid/presentation/layout/sizes.dart';
import 'package:appflowy/plugins/database/widgets/setting/mobile_database_controls.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/workspace/application/view/view_bloc.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:collection/collection.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class MobileTabBarHeader extends StatelessWidget {
@@ -143,14 +142,16 @@ class _DatabaseViewSelectorButton extends StatelessWidget {
}
Widget _buildViewIconButton(BuildContext context, ViewPB view) {
return view.icon.value.isNotEmpty
? RawEmojiIconWidget(
emoji: view.icon.toEmojiIconData(),
emojiSize: 16.0,
)
: SizedBox.square(
dimension: 16.0,
child: view.defaultIcon(),
);
final iconData = view.icon.toEmojiIconData();
if (iconData.isEmpty || iconData.type != FlowyIconType.icon) {
return SizedBox.square(
dimension: 16.0,
child: view.defaultIcon(),
);
}
return RawEmojiIconWidget(
emoji: iconData,
emojiSize: 16,
);
}
}
@@ -288,7 +288,7 @@ class DatabasePluginWidgetBuilder extends PluginWidgetBuilder {
const HSpace(10),
ViewFavoriteButton(view: view),
const HSpace(4),
MoreViewActions(view: view, isDocument: false),
MoreViewActions(view: view),
],
),
);
@@ -1,4 +1,5 @@
import 'package:appflowy/plugins/database/application/row/related_row_detail_bloc.dart';
import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
@@ -26,10 +27,13 @@ class RelatedRowDetailPage extends StatelessWidget {
return state.when(
loading: () => const SizedBox.shrink(),
ready: (databaseController, rowController) {
return RowDetailPage(
databaseController: databaseController,
rowController: rowController,
allowOpenAsFullPage: false,
return BlocProvider.value(
value: context.read<UserWorkspaceBloc>(),
child: RowDetailPage(
databaseController: databaseController,
rowController: rowController,
allowOpenAsFullPage: false,
),
);
},
);
@@ -11,6 +11,7 @@ import 'package:appflowy/plugins/document/application/editor_transaction_adapter
import 'package:appflowy/plugins/trash/application/trash_service.dart';
import 'package:appflowy/shared/feature_flags.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/startup/tasks/app_widget.dart';
import 'package:appflowy/startup/tasks/device_info_task.dart';
import 'package:appflowy/user/application/auth/auth_service.dart';
import 'package:appflowy/util/color_generator/color_generator.dart';
@@ -18,6 +19,7 @@ import 'package:appflowy/util/color_to_hex_string.dart';
import 'package:appflowy/util/debounce.dart';
import 'package:appflowy/util/throttle.dart';
import 'package:appflowy/workspace/application/view/view_listener.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-document/entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-document/protobuf.dart';
@@ -25,11 +27,11 @@ import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:appflowy_editor/appflowy_editor.dart'
show
EditorState,
AppFlowyEditorLogLevel,
TransactionTime,
Selection,
EditorState,
Position,
Selection,
TransactionTime,
paragraphNode;
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter/foundation.dart';
@@ -38,6 +40,11 @@ import 'package:freezed_annotation/freezed_annotation.dart';
part 'document_bloc.freezed.dart';
/// Enable this flag to enable the internal log for
/// - document diff
/// - document integrity check
/// - document sync state
/// - document awareness states
bool enableDocumentInternalLog = false;
final Map<String, DocumentBloc> _documentBlocMap = {};
@@ -304,7 +311,7 @@ class DocumentBloc extends Bloc<DocumentEvent, DocumentState> {
..level = AppFlowyEditorLogLevel.all
..handler = (log) {
if (enableDocumentInternalLog) {
Log.info(log);
// Log.info(log);
}
};
}
@@ -363,6 +370,9 @@ class DocumentBloc extends Bloc<DocumentEvent, DocumentState> {
}
void _throttleSyncDoc(DocEventPB docEvent) {
if (enableDocumentInternalLog) {
Log.info('[DocumentBloc] throttle sync doc: ${docEvent.toProto3Json()}');
}
_syncThrottle.call(() {
_onDocumentStateUpdate(docEvent);
});
@@ -448,9 +458,17 @@ class DocumentBloc extends Bloc<DocumentEvent, DocumentState> {
if (!deepEqual) {
Log.error('document integrity check failed');
// Enable it to debug the document integrity check failed
// Log.error('cloud doc: $cloudJson');
// Log.error('local doc: $localJson');
assert(false, 'document integrity check failed');
Log.error('cloud doc: $cloudJson');
Log.error('local doc: $localJson');
final context = AppGlobals.rootNavKey.currentContext;
if (context != null && context.mounted) {
showToastNotification(
context,
message: 'document integrity check failed',
type: ToastificationType.error,
);
}
}
}
}
@@ -2,6 +2,7 @@ import 'dart:convert';
import 'package:appflowy/plugins/document/application/document_awareness_metadata.dart';
import 'package:appflowy/plugins/document/application/document_data_pb_extension.dart';
import 'package:appflowy/plugins/document/application/document_diff.dart';
import 'package:appflowy/plugins/document/application/prelude.dart';
import 'package:appflowy/shared/list_extension.dart';
import 'package:appflowy/startup/tasks/device_info_task.dart';
@@ -16,10 +17,14 @@ import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
class DocumentCollabAdapter {
DocumentCollabAdapter(this.editorState, this.docId);
DocumentCollabAdapter(
this.editorState,
this.docId,
);
final EditorState editorState;
final String docId;
final DocumentDiff diff = const DocumentDiff();
final _service = DocumentService();
@@ -75,13 +80,14 @@ class DocumentCollabAdapter {
return;
}
final ops = diffNodes(editorState.document.root, document.root);
final ops = diff.diffDocument(editorState.document, document);
if (ops.isEmpty) {
return;
}
// Use for debugging, DO NOT REMOVE
// prettyPrintJson(ops.map((op) => op.toJson()).toList());
if (enableDocumentInternalLog) {
prettyPrintJson(ops.map((op) => op.toJson()).toList());
}
final transaction = editorState.transaction;
for (final op in ops) {
@@ -89,18 +95,19 @@ class DocumentCollabAdapter {
}
await editorState.apply(transaction, isRemote: true);
// Use for debugging, DO NOT REMOVE
// assert(() {
// final local = editorState.document.root.toJson();
// final remote = document.root.toJson();
// if (!const DeepCollectionEquality().equals(local, remote)) {
// Log.error('Invalid diff status');
// Log.error('Local: $local');
// Log.error('Remote: $remote');
// return false;
// }
// return true;
// }());
if (enableDocumentInternalLog) {
assert(() {
final local = editorState.document.root.toJson();
final remote = document.root.toJson();
if (!const DeepCollectionEquality().equals(local, remote)) {
Log.error('Invalid diff status');
Log.error('Local: $local');
Log.error('Remote: $remote');
return false;
}
return true;
}());
}
}
Future<void> forceReload() async {
@@ -0,0 +1,172 @@
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:collection/collection.dart';
import 'package:flutter/foundation.dart';
/// DocumentDiff compares two document states and generates operations needed
/// to transform one state into another.
class DocumentDiff {
const DocumentDiff({
this.enableDebugLog = false,
});
final bool enableDebugLog;
// Using DeepCollectionEquality for deep comparison of collections
static const _equality = DeepCollectionEquality();
/// Generates operations needed to transform oldDocument into newDocument.
/// Returns a list of operations (Insert, Delete, Update) that can be applied sequentially.
List<Operation> diffDocument(Document oldDocument, Document newDocument) {
return diffNode(oldDocument.root, newDocument.root);
}
/// Compares two nodes and their children recursively to generate transformation operations.
/// Returns a list of operations that will transform oldNode into newNode.
List<Operation> diffNode(Node oldNode, Node newNode) {
final operations = <Operation>[];
// Compare and update node attributes if they're different.
// Using DeepCollectionEquality instead of == for deep comparison of collections
if (!_equality.equals(oldNode.attributes, newNode.attributes)) {
operations.add(
UpdateOperation(oldNode.path, newNode.attributes, oldNode.attributes),
);
}
final oldChildrenById = Map<String, Node>.fromEntries(
oldNode.children.map((child) => MapEntry(child.id, child)),
);
final newChildrenById = Map<String, Node>.fromEntries(
newNode.children.map((child) => MapEntry(child.id, child)),
);
// Insertion or Update
for (final newChild in newNode.children) {
final oldChild = oldChildrenById[newChild.id];
if (oldChild == null) {
// If the node doesn't exist in the old document, it's a new node.
operations.add(InsertOperation(newChild.path, [newChild]));
} else {
// If the node exists in the old document, recursively compare its children
operations.addAll(diffNode(oldChild, newChild));
}
}
// Deletion
for (final id in oldChildrenById.keys) {
// If the node doesn't exist in the new document, it's a deletion.
if (!newChildrenById.containsKey(id)) {
final oldChild = oldChildrenById[id]!;
operations.add(DeleteOperation(oldChild.path, [oldChild]));
}
}
// Optimize operations by merging consecutive inserts and deletes
return _optimizeOperations(operations);
}
/// Optimizes the list of operations by merging consecutive operations where possible.
/// This reduces the total number of operations that need to be applied.
List<Operation> _optimizeOperations(List<Operation> operations) {
// Optimize the insert operations first, then the delete operations
final optimizedOps = mergeDeleteOperations(
mergeInsertOperations(
operations,
),
);
return optimizedOps;
}
/// Merges consecutive insert operations to reduce the number of operations.
/// Operations are merged if they target consecutive paths in the document.
List<Operation> mergeInsertOperations(List<Operation> operations) {
if (enableDebugLog) {
_logOperations('mergeInsertOperations[before]', operations);
}
final copy = [...operations];
final insertOperations = operations
.whereType<InsertOperation>()
.sorted(_descendingCompareTo)
.toList();
_mergeConsecutiveOperations<InsertOperation>(
insertOperations,
(prev, current) => InsertOperation(
prev.path,
[...prev.nodes, ...current.nodes],
),
);
if (insertOperations.isNotEmpty) {
copy
..removeWhere((op) => op is InsertOperation)
..insertAll(0, insertOperations); // Insert ops must be at the start
}
if (enableDebugLog) {
_logOperations('mergeInsertOperations[after]', copy);
}
return copy;
}
/// Merges consecutive delete operations to reduce the number of operations.
/// Operations are merged if they target consecutive paths in the document.
List<Operation> mergeDeleteOperations(List<Operation> operations) {
if (enableDebugLog) {
_logOperations('mergeDeleteOperations[before]', operations);
}
final copy = [...operations];
final deleteOperations = operations
.whereType<DeleteOperation>()
.sorted(_descendingCompareTo)
.toList();
_mergeConsecutiveOperations<DeleteOperation>(
deleteOperations,
(prev, current) => DeleteOperation(
prev.path,
[...prev.nodes, ...current.nodes],
),
);
if (deleteOperations.isNotEmpty) {
copy
..removeWhere((op) => op is DeleteOperation)
..addAll(deleteOperations); // Delete ops must be at the end
}
if (enableDebugLog) {
_logOperations('mergeDeleteOperations[after]', copy);
}
return copy;
}
/// Merge consecutive operations of the same type
void _mergeConsecutiveOperations<T extends Operation>(
List<T> operations,
T Function(T prev, T current) merge,
) {
for (var i = operations.length - 1; i > 0; i--) {
final op = operations[i];
final previousOp = operations[i - 1];
if (op.path.equals(previousOp.path.next)) {
operations
..removeAt(i)
..[i - 1] = merge(previousOp, op);
}
}
}
void _logOperations(String prefix, List<Operation> operations) {
debugPrint('$prefix: ${operations.map((op) => op.toJson()).toList()}');
}
int _descendingCompareTo(Operation a, Operation b) {
return a.path > b.path ? 1 : -1;
}
}
@@ -4,7 +4,7 @@ import 'dart:convert';
import 'package:appflowy/plugins/document/application/document_bloc.dart';
import 'package:appflowy/plugins/document/application/document_data_pb_extension.dart';
import 'package:appflowy/plugins/document/application/document_service.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_block_component.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/ask_ai_block_component.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-document/protobuf.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
@@ -9,6 +9,7 @@ import 'package:appflowy/plugins/document/presentation/document_collaborators.da
import 'package:appflowy/plugins/shared/share/share_button.dart';
import 'package:appflowy/plugins/util.dart';
import 'package:appflowy/shared/feature_flags.dart';
import 'package:appflowy/shared/icon_emoji_picker/tab.dart';
import 'package:appflowy/startup/plugin/plugin.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy/workspace/application/view_info/view_info_bloc.dart';
@@ -107,6 +108,7 @@ class DocumentPluginWidgetBuilder extends PluginWidgetBuilder
final ViewInfoBloc bloc;
final ViewPluginNotifier notifier;
ViewPB get view => notifier.view;
int? deletedViewIndex;
final Selection? initialSelection;
@@ -130,6 +132,12 @@ class DocumentPluginWidgetBuilder extends PluginWidgetBuilder
final fixedTitle = data?[MobileDocumentScreen.viewFixedTitle];
final blockId = initialBlockId ?? data?[MobileDocumentScreen.viewBlockId];
final tabs = data?[MobileDocumentScreen.viewSelectTabs] ??
const [
PickerTabType.emoji,
PickerTabType.icon,
PickerTabType.custom,
];
return BlocProvider<ViewInfoBloc>.value(
value: bloc,
@@ -141,6 +149,7 @@ class DocumentPluginWidgetBuilder extends PluginWidgetBuilder
initialSelection: initialSelection,
initialBlockId: blockId,
fixedTitle: fixedTitle,
tabs: tabs,
),
),
);
@@ -10,6 +10,7 @@ import 'package:appflowy/plugins/document/presentation/editor_plugins/shared_con
import 'package:appflowy/plugins/document/presentation/editor_plugins/transaction_handler/editor_transaction_service.dart';
import 'package:appflowy/plugins/document/presentation/editor_style.dart';
import 'package:appflowy/shared/flowy_error_page.dart';
import 'package:appflowy/shared/icon_emoji_picker/tab.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/application/action_navigation/action_navigation_bloc.dart';
import 'package:appflowy/workspace/application/action_navigation/navigation_action.dart';
@@ -28,6 +29,7 @@ class DocumentPage extends StatefulWidget {
super.key,
required this.view,
required this.onDeleted,
required this.tabs,
this.initialSelection,
this.initialBlockId,
this.fixedTitle,
@@ -38,6 +40,7 @@ class DocumentPage extends StatefulWidget {
final Selection? initialSelection;
final String? initialBlockId;
final String? fixedTitle;
final List<PickerTabType> tabs;
@override
State<DocumentPage> createState() => _DocumentPageState();
@@ -178,7 +181,9 @@ class _DocumentPageState extends State<DocumentPage>
editorState: state.editorState!,
child: Column(
children: [
if (state.isDeleted) buildBanner(context),
// the banner only shows on desktop
if (state.isDeleted && UniversalPlatform.isDesktop)
buildBanner(context),
Expanded(child: child),
],
),
@@ -208,6 +213,7 @@ class _DocumentPageState extends State<DocumentPage>
return DocumentImmersiveCover(
fixedTitle: widget.fixedTitle,
view: widget.view,
tabs: widget.tabs,
userProfilePB: userProfilePB,
);
}
@@ -215,6 +221,7 @@ class _DocumentPageState extends State<DocumentPage>
final page = editorState.document.root;
return DocumentCoverWidget(
node: page,
tabs: widget.tabs,
editorState: editorState,
view: widget.view,
onIconChanged: (icon) async => ViewBackendService.updateViewIcon(
@@ -105,9 +105,16 @@ BlockComponentConfiguration _buildDefaultConfiguration(BuildContext context) {
return const EdgeInsets.symmetric(vertical: 5.0);
},
indentPadding: (node, textDirection) => textDirection == TextDirection.ltr
? const EdgeInsets.only(left: 26.0)
: const EdgeInsets.only(right: 26.0),
indentPadding: (node, textDirection) {
double padding = 26.0;
// only add indent padding for the top level node to align the children
if (UniversalPlatform.isMobile && node.path.length == 1) {
padding += EditorStyleCustomizer.nodeHorizontalPadding;
}
return textDirection == TextDirection.ltr
? EdgeInsets.only(left: padding)
: EdgeInsets.only(right: padding);
},
);
return configuration;
}
@@ -381,7 +388,10 @@ SimpleTableBlockComponentBuilder _buildSimpleTableBlockComponentBuilder(
}
},
);
return SimpleTableBlockComponentBuilder(configuration: copiedConfiguration);
return SimpleTableBlockComponentBuilder(
configuration: copiedConfiguration,
alwaysDistributeColumnWidths: alwaysDistributeColumnWidths,
);
}
SimpleTableRowBlockComponentBuilder _buildSimpleTableRowBlockComponentBuilder(
@@ -1,5 +1,5 @@
import 'package:appflowy/ai/appflowy_ai_service.dart';
import 'package:appflowy/ai/error.dart';
import 'package:appflowy/ai/service/appflowy_ai_service.dart';
import 'package:appflowy/ai/service/error.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/application/prelude.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/base/build_context_extension.dart';
@@ -15,11 +15,11 @@ import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:universal_platform/universal_platform.dart';
import 'ai_limit_dialog.dart';
import 'ai_writer_block_operations.dart';
import 'ai_writer_block_widgets.dart';
import 'discard_dialog.dart';
import 'barrier_dialog.dart';
import 'widgets/ai_limit_dialog.dart';
import 'widgets/ai_writer_block_operations.dart';
import 'widgets/ai_writer_block_widgets.dart';
import 'widgets/discard_dialog.dart';
import 'widgets/barrier_dialog.dart';
class AIWriterBlockKeys {
const AIWriterBlockKeys._();
@@ -1,13 +1,13 @@
import 'dart:async';
import 'package:appflowy/ai/service/appflowy_ai_service.dart';
import 'package:appflowy/ai/service/error.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/ai/ai_client.dart';
import 'package:appflowy/ai/error.dart';
import 'package:appflowy/ai/service/ai_client.dart';
import 'package:appflowy/plugins/document/application/document_bloc.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ai_limit_dialog.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action_bloc.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_block_widgets.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/widgets/ai_limit_dialog.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/widgets/ask_ai_action_bloc.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/widgets/ask_ai_block_widgets.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
@@ -167,7 +167,7 @@ class _AskAIBlockComponentWidgetState extends State<AskAIBlockComponentWidget> {
return BlocProvider.value(
// request the result when opening the popover
value: askAIBloc..add(const AskAIEvent.started()),
child: const AskAiInputContent(),
child: const AskAIInputContent(),
);
},
child: const SizedBox(
@@ -1,9 +1,8 @@
import 'package:appflowy/ai/service/appflowy_ai_service.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/application/document_bloc.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/util/ask_ai_node_extension.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_block_component.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/util/ask_ai_node_extension.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
@@ -12,6 +11,9 @@ import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'widgets/ask_ai_action.dart';
import 'ask_ai_block_component.dart';
const _kAskAIToolbarItemId = 'appflowy.editor.ask_ai';
final ToolbarItem askAIItem = ToolbarItem(
@@ -39,15 +41,14 @@ class AskAIActionList extends StatefulWidget {
}
class _AskAIActionListState extends State<AskAIActionList> {
bool isAIEnabled = true;
late bool isAIEnabled;
EditorState get editorState => widget.editorState;
@override
void initState() {
super.initState();
isAIEnabled = _isAIEnabled();
_updateIsAIEnabled();
}
@override
@@ -137,11 +138,9 @@ class _AskAIActionListState extends State<AskAIActionList> {
);
}
bool _isAIEnabled() {
void _updateIsAIEnabled() {
final documentContext = widget.editorState.document.root.context;
if (documentContext == null) {
return true;
}
return !documentContext.read<DocumentBloc>().isLocalMode;
isAIEnabled = documentContext == null ||
!documentContext.read<DocumentBloc>().isLocalMode;
}
}
@@ -1,4 +1,4 @@
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ai_writer_block_component.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/ai_writer_block_component.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
/// Notes: All the operation related to the AI writer block will be applied
@@ -0,0 +1,14 @@
import 'package:appflowy/ai/service/appflowy_ai_service.dart';
import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart';
import 'package:flutter/material.dart';
class AskAIActionWrapper extends ActionCell {
AskAIActionWrapper(this.inner);
final AskAIAction inner;
Widget? icon(Color iconColor) => null;
@override
String get name => inner.name;
}
@@ -1,11 +1,10 @@
import 'dart:async';
import 'package:appflowy/ai/ai_client.dart';
import 'package:appflowy/ai/error.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action.dart';
import 'package:appflowy/ai/service/ai_client.dart';
import 'package:appflowy/ai/service/error.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/shared/markdown_to_document.dart';
import 'package:appflowy/ai/appflowy_ai_service.dart';
import 'package:appflowy/ai/service/appflowy_ai_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
@@ -1,13 +1,13 @@
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/ai_chat/presentation/message/ai_markdown_text.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/openai/widgets/ask_ai_action_bloc.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/widgets/ask_ai_action_bloc.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class AskAiInputContent extends StatelessWidget {
const AskAiInputContent({super.key});
class AskAIInputContent extends StatelessWidget {
const AskAIInputContent({super.key});
@override
Widget build(BuildContext context) {
@@ -0,0 +1,20 @@
import 'package:flutter/material.dart';
class BarrierDialog {
BarrierDialog(this.context);
late BuildContext loadingContext;
final BuildContext context;
void show() => showDialog<void>(
context: context,
barrierDismissible: false,
barrierColor: Colors.transparent,
builder: (context) {
loadingContext = context;
return const SizedBox.shrink();
},
);
void dismiss() => Navigator.of(loadingContext).pop();
}
Loaded 100 of 185 files, more files were not shown because too many files have changed in this diff. Show more