Compare commits

..
Author SHA1 Message Date
Nathan 2d5946e75c chore: clippy 2025-04-14 10:31:05 +08:00
Nathan f28a299786 chore: exit anon mode 2025-04-14 10:16:20 +08:00
Nathan 4b0d61b534 chore: do not show logout button on mobile when current user is anon 2025-04-13 14:05:46 +08:00
Nathan cf8fb19976 chore: test 2025-04-13 13:19:10 +08:00
Nathan 1525a363f2 chore: remove unused code 2025-04-13 13:09:05 +08:00
Nathan 5a99da9a45 chore: anon login 2025-04-13 12:48:27 +08:00
Nathan 495226fa2c Merge branch 'main' into anon_user_mode 2025-04-13 12:15:24 +08:00
Lucas 2e295e6891 fix: unable to accept the response from 'mark longer' (#7725)
* fix: unable to accpet 'make it longer'

* fix: markdown text robot test
2025-04-11 14:25:19 +08:00
Richard Shiue 351c891a5a fix: adjust ghost icon hover color (#7723) 2025-04-11 10:21:02 +08:00
Richard Shiue bcb1e8e4f5 chore: adjust replace, insert below, discard selection behavior (#7719) 2025-04-11 09:57:41 +08:00
MornandLucas 4997ac99cf feat: revamp link preivew (#7692)
* feat: revamp link preivew

* feat: add convert to menu for link hover menu

* feat: add mention link

* feat: support convert preview to mention

* feat: add embed link preview

* fix: some test erros

* fix: test errors

* fix: some UI issues

* chore: add test for url

* chore: add test for mention

* chore: add test for bookmark

* chore: add test for embed

* chore: remove unuse import

* fix: some UI issues

* fix: remove text span overlay on mobile

* fix: code lint error

---------

Co-authored-by: Lucas <lucas.xu@appflowy.io>
2025-04-10 14:45:13 +08:00
Lucas e3bbabd63e feat: sign in with passcode (#7685)
* feat: sign in with password or passcode

* feat: add loading dialog

* chore: update translations

* feat: support otp on mobile
2025-04-10 14:06:08 +08:00
Morn 403c558f9b chore: update translation (#7675) 2025-04-10 13:45:22 +08:00
Nathan.fooo 31d2c1d603 Merge pull request #7718 from AppFlowy-IO/remove_path_to_lai
chore: remove local ai related path to lai repo
2025-04-09 21:56:40 +08:00
Nathan a7adeeadb1 chore: remove local ai related path to lai repo 2025-04-09 20:47:03 +08:00
Nathan.fooo f7d7141a59 Merge pull request #7717 from AppFlowy-IO/fix_local_ai_setting
chore: fix local ai setting
2025-04-09 20:43:36 +08:00
Nathan 2371d4691d chore: fix local ai setting 2025-04-09 20:07:06 +08:00
Nathan 9ec0437673 chore: remove enable sync log toggle 2025-04-09 14:15:48 +08:00
Richard Shiue 89525b7f7b chore: bump version (#7716) 2025-04-09 14:11:33 +08:00
Richard Shiue ad227bcf79 chore: toast message when theme folder doesn't have permission (#7715) 2025-04-09 13:45:07 +08:00
Lucas 8b82d532e0 fix: replace the selected text with ai response in the same line (#7708)
* fix: replace the selected text with ai response in the same line

* fix: replace the selected text with ai response in the multiple lines

* fix: integrate the replace function in the ai writer cubit

* fix: unit test and integration test
2025-04-09 13:21:19 +08:00
Morn f4af47728f fix: overwriting a selected text removes more than expected (#7714) 2025-04-09 12:57:58 +08:00
Richard Shiue b3a4a9ba04 fix: use normal underline for AI suggested text style (#7712) 2025-04-09 10:25:29 +08:00
Lucas 13028c6cfe fix: icon and emoji doesn't align in mention page menu (#7673) 2025-04-09 09:39:35 +08:00
Richard Shiue 7d0f6c9deb fix(mobile): edit mention page (#7698)
* fix(mobile): edit mention page

* chore: type check

* chore: replace usages

* chore: use MentionType instead
2025-04-09 09:38:42 +08:00
FakhriAzzouz 8d2901cc58 chore: arabic translations update (#7701)
* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦
2025-04-09 09:38:00 +08:00
Aniket Patil bbc7b6d172 feat(i18n): add initial Marathi (mr-IN) translations (#7667)
* feat(i18n): Add initial Marathi (mr-IN) translations

* fix(i18n): Force add mr-IN.json in assets folder for localization

* fix(i18n): Sync mr-IN.json from assets to resources

* fix(i18n): Final sync of full Marathi translation in assets

* feat(i18n): Force add Marathi translations to ignored directory

* feat(i18n): Complete Marathi translations
2025-04-09 09:37:21 +08:00
Lucas 145d1e5fdb feat: support white label on windows (#7706) 2025-04-09 09:36:53 +08:00
Nathan 7ffd459875 chore: anon mode 2025-04-08 21:22:16 +08:00
Nathan.fooo eae4e42dcc Merge pull request #7709 from AppFlowy-IO/refactor_path_name
chore: rename data path
2025-04-08 21:19:07 +08:00
Nathan 6886261692 chore: ensure path 2025-04-08 20:49:15 +08:00
Nathan 23f2d85e70 chore: clippy 2025-04-08 20:23:25 +08:00
Nathan d1d598940d chore: clippy 2025-04-08 16:08:28 +08:00
Nathan efb98d28ef chore: rename data path 2025-04-08 15:53:34 +08:00
Richard Shiue 462c822255 fix: translations (#7694) 2025-04-08 13:08:10 +08:00
Richard Shiue 9e30b1816f fix(flutter_desktop): grid bug (#7697)
* fix: field width doesn't persist

* test: add test

* test: fix test

* test: grid width integration test
2025-04-08 11:46:06 +08:00
Nathan.fooo d79929d1c9 Merge pull request #7700 from AppFlowy-IO/sync_log_enable_default
chore: enable sync log by default
2025-04-08 10:31:01 +08:00
Nathan 0286678286 chore: clippy 2025-04-08 10:30:48 +08:00
Nathan 4896d7c1be chore: enable sync log by default 2025-04-07 22:04:32 +08:00
Nathan.fooo b06a2337a0 Merge pull request #7699 from AppFlowy-IO/use_uuid
Chore: Use UUID instead of using String
2025-04-07 21:54:48 +08:00
Nathan 20bcdd1f90 chore: fmt 2025-04-07 21:28:48 +08:00
Nathan 24d57336a9 chore: bump collab id 2025-04-07 21:15:30 +08:00
Nathan 91397c963a chore: clippy 2025-04-07 19:34:26 +08:00
Nathan 995b773c74 chore: replace str with uuid 2025-04-07 19:24:58 +08:00
Richard Shiue c561abd9f8 fix: clear text field upon selection (#7695) 2025-04-07 14:52:44 +08:00
Lucas 10dd0fa438 feat: implement new color tokens design (#7684)
* fix: missing AFThemeExtensionV2 on mobile

* feat: add appflowy_ui package
2025-04-04 14:41:13 +08:00
207 changed files with 11370 additions and 1456 deletions

No files matched your search

+124 -124
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": "trace",
},
// 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]",
},
]
}
File diff suppressed because it is too large. Load diff
@@ -1,10 +1,12 @@
import 'dart:async';
import 'dart:io';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/block_menu/block_menu_button.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/clipboard_service.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/image/custom_image_block_component/custom_image_block_component.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/custom_link_preview.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/link_preview_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/paste_as/paste_as_menu.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart';
@@ -320,8 +322,14 @@ void main() {
(tester) async {
const url = 'https://appflowy.io';
await tester.pasteContent(plainText: url, (editorState) async {
final pasteAsMenu = find.byType(PasteAsMenu);
expect(pasteAsMenu, findsOneWidget);
final bookmarkButton = find.text(
LocaleKeys.document_plugins_linkPreview_typeSelection_bookmark.tr(),
);
await tester.tapButton(bookmarkButton);
// the second one is the paragraph node
expect(editorState.document.root.children.length, 2);
expect(editorState.document.root.children.length, 1);
final node = editorState.getNodeAtPath([0])!;
expect(node.type, LinkPreviewBlockKeys.type);
expect(node.attributes[LinkPreviewBlockKeys.url], url);
@@ -333,19 +341,19 @@ void main() {
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();
});
/// show menu
final menu = find.byType(CustomLinkPreviewMenu);
expect(menu, findsOneWidget);
await tester.tapButton(menu);
final convertToLinkButton = find.text(
LocaleKeys.document_plugins_linkPreview_linkPreviewMenu_toUrl.tr(),
);
expect(convertToLinkButton, findsOneWidget);
await tester.tap(convertToLinkButton);
await tester.pumpAndSettle();
await tester.tapButton(convertToLinkButton);
},
);
await tester.pumpAndSettle();
final editorState = tester.editor.getCurrentEditorState();
final textNode = editorState.getNodeAtPath([0])!;
expect(textNode.type, ParagraphBlockKeys.type);
@@ -363,14 +371,20 @@ void main() {
(tester) async {
const url = 'https://appflowy.io';
await tester.pasteContent(plainText: url, (editorState) async {
final pasteAsMenu = find.byType(PasteAsMenu);
expect(pasteAsMenu, findsOneWidget);
final bookmarkButton = find.text(
LocaleKeys.document_plugins_linkPreview_typeSelection_bookmark.tr(),
);
await tester.tapButton(bookmarkButton);
// the second one is the paragraph node
expect(editorState.document.root.children.length, 2);
expect(editorState.document.root.children.length, 1);
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:
@@ -521,7 +535,7 @@ void main() {
extension on WidgetTester {
Future<void> pasteContent(
void Function(EditorState editorState) test, {
FutureOr<void> Function(EditorState editorState) test, {
Future<void> Function(EditorState editorState)? beforeTest,
String? plainText,
String? html,
@@ -558,6 +572,6 @@ extension on WidgetTester {
);
await pumpAndSettle(const Duration(milliseconds: 1000));
test(editor.getCurrentEditorState());
await test(editor.getCurrentEditorState());
}
}
@@ -0,0 +1,452 @@
import 'dart:io';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/clipboard_service.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/link/link_hover_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_embed/link_embed_block_component.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/custom_link_preview_block_component.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/link_preview_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/paste_as/paste_as_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_block.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_link_block.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_link_error_preview.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_link_preview.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import '../../shared/util.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
const avaliableLink = 'https://appflowy.io/',
unavailableLink = 'www.thereIsNoting.com';
Future<void> preparePage(WidgetTester tester, {String? pageName}) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
await tester.createNewPageWithNameUnderParent(name: pageName);
await tester.editor.tapLineOfEditorAt(0);
}
Future<void> pasteLink(WidgetTester tester, String link) async {
await getIt<ClipboardService>()
.setData(ClipboardServiceData(plainText: link));
/// paste the link
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyV,
isControlPressed: Platform.isLinux || Platform.isWindows,
isMetaPressed: Platform.isMacOS,
);
await tester.pumpAndSettle(Duration(seconds: 1));
}
Future<void> pasteAs(
WidgetTester tester,
String link,
PasteMenuType type, {
Duration waitTime = const Duration(milliseconds: 500),
}) async {
await pasteLink(tester, link);
final convertToMentionButton = find.text(type.title);
await tester.tapButton(convertToMentionButton);
await tester.pumpAndSettle(waitTime);
}
void checkUrl(Node node, String link) {
expect(node.type, ParagraphBlockKeys.type);
expect(node.delta!.toJson(), [
{
'insert': link,
'attributes': {'href': link},
}
]);
}
void checkMention(Node node, String link) {
final delta = node.delta!;
final insert = (delta.first as TextInsert).text;
final attributes = delta.first.attributes;
expect(insert, MentionBlockKeys.mentionChar);
final mention =
attributes?[MentionBlockKeys.mention] as Map<String, dynamic>;
expect(mention[MentionBlockKeys.type], MentionType.externalLink.name);
expect(mention[MentionBlockKeys.url], avaliableLink);
}
void checkBookmark(Node node, String link) {
expect(node.type, LinkPreviewBlockKeys.type);
expect(node.attributes[LinkPreviewBlockKeys.url], link);
}
void checkEmbed(Node node, String link) {
expect(node.type, LinkPreviewBlockKeys.type);
expect(node.attributes[LinkEmbedKeys.previewType], LinkEmbedKeys.embed);
expect(node.attributes[LinkPreviewBlockKeys.url], link);
}
group('Paste as URL', () {
Future<void> pasteAndTurnInto(
WidgetTester tester,
String link,
String title,
) async {
await pasteLink(tester, link);
final convertToLinkButton = find
.text(LocaleKeys.document_plugins_linkPreview_typeSelection_URL.tr());
await tester.tapButton(convertToLinkButton);
/// hover link and turn into mention
await tester.hoverOnWidget(
find.byType(LinkHoverTrigger),
onHover: () async {
final turnintoButton = find.byFlowySvg(FlowySvgs.turninto_m);
await tester.tapButton(turnintoButton);
final convertToButton = find.text(title);
await tester.tapButton(convertToButton);
await tester.pumpAndSettle(Duration(seconds: 1));
},
);
}
testWidgets('paste a link', (tester) async {
final link = avaliableLink;
await preparePage(tester);
await pasteLink(tester, link);
final convertToLinkButton = find
.text(LocaleKeys.document_plugins_linkPreview_typeSelection_URL.tr());
await tester.tapButton(convertToLinkButton);
final node = tester.editor.getNodeAtPath([0]);
checkUrl(node, link);
});
testWidgets('paste a link and turn into mention', (tester) async {
final link = avaliableLink;
await preparePage(tester);
await pasteAndTurnInto(
tester,
link,
LinkConvertMenuCommand.toMention.title,
);
/// check metion values
final node = tester.editor.getNodeAtPath([0]);
checkMention(node, link);
});
testWidgets('paste a link and turn into bookmark', (tester) async {
final link = avaliableLink;
await preparePage(tester);
await pasteAndTurnInto(
tester,
link,
LinkConvertMenuCommand.toBookmark.title,
);
/// check metion values
final node = tester.editor.getNodeAtPath([0]);
checkBookmark(node, link);
});
testWidgets('paste a link and turn into embed', (tester) async {
final link = avaliableLink;
await preparePage(tester);
await pasteAndTurnInto(
tester,
link,
LinkConvertMenuCommand.toEmbed.title,
);
/// check metion values
final node = tester.editor.getNodeAtPath([0]);
checkEmbed(node, link);
});
});
group('Paste as Mention', () {
Future<void> pasteAsMention(WidgetTester tester, String link) =>
pasteAs(tester, link, PasteMenuType.mention);
String getMentionLink(Node node) {
final insert = node.delta?.first as TextInsert?;
final mention = insert?.attributes?[MentionBlockKeys.mention]
as Map<String, dynamic>?;
return mention?[MentionBlockKeys.url] ?? '';
}
Future<void> hoverMentionAndClick(
WidgetTester tester,
String command,
) async {
final mentionLink = find.byType(MentionLinkBlock);
expect(mentionLink, findsOneWidget);
await tester.hoverOnWidget(
mentionLink,
onHover: () async {
final errorPreview = find.byType(MentionLinkErrorPreview);
expect(errorPreview, findsOneWidget);
final convertButton = find.byFlowySvg(FlowySvgs.turninto_m);
await tester.tapButton(convertButton);
final menuButton = find.text(command);
await tester.tapButton(menuButton);
},
);
}
testWidgets('paste a link as mention', (tester) async {
final link = avaliableLink;
await preparePage(tester);
await pasteAsMention(tester, link);
final node = tester.editor.getNodeAtPath([0]);
checkMention(node, link);
});
testWidgets('paste as mention and copy link', (tester) async {
final link = avaliableLink;
await preparePage(tester);
await pasteAsMention(tester, link);
final mentionLink = find.byType(MentionLinkBlock);
expect(mentionLink, findsOneWidget);
await tester.hoverOnWidget(
mentionLink,
onHover: () async {
final preview = find.byType(MentionLinkPreview);
if (!preview.hasFound) {
final copyButton = find.byFlowySvg(FlowySvgs.toolbar_link_m);
await tester.tapButton(copyButton);
} else {
final moreOptionButton = find.byFlowySvg(FlowySvgs.toolbar_more_m);
await tester.tapButton(moreOptionButton);
final copyButton =
find.text(MentionLinktMenuCommand.copyLink.title);
await tester.tapButton(copyButton);
}
},
);
final clipboardContent = await getIt<ClipboardService>().getData();
expect(clipboardContent.plainText, link);
});
testWidgets('paste as error mention and turninto url', (tester) async {
String link = unavailableLink;
await preparePage(tester);
await pasteAsMention(tester, link);
Node node = tester.editor.getNodeAtPath([0]);
link = getMentionLink(node);
await hoverMentionAndClick(
tester,
MentionLinktErrorMenuCommand.toURL.title,
);
node = tester.editor.getNodeAtPath([0]);
checkUrl(node, link);
});
testWidgets('paste as error mention and turninto embed', (tester) async {
String link = unavailableLink;
await preparePage(tester);
await pasteAsMention(tester, link);
Node node = tester.editor.getNodeAtPath([0]);
link = getMentionLink(node);
await hoverMentionAndClick(
tester,
MentionLinktErrorMenuCommand.toEmbed.title,
);
node = tester.editor.getNodeAtPath([0]);
checkEmbed(node, link);
});
testWidgets('paste as error mention and turninto bookmark', (tester) async {
String link = unavailableLink;
await preparePage(tester);
await pasteAsMention(tester, link);
Node node = tester.editor.getNodeAtPath([0]);
link = getMentionLink(node);
await hoverMentionAndClick(
tester,
MentionLinktErrorMenuCommand.toBookmark.title,
);
node = tester.editor.getNodeAtPath([0]);
checkBookmark(node, link);
});
testWidgets('paste as error mention and remove link', (tester) async {
String link = unavailableLink;
await preparePage(tester);
await pasteAsMention(tester, link);
Node node = tester.editor.getNodeAtPath([0]);
link = getMentionLink(node);
await hoverMentionAndClick(
tester,
MentionLinktErrorMenuCommand.removeLink.title,
);
node = tester.editor.getNodeAtPath([0]);
expect(node.type, ParagraphBlockKeys.type);
expect(node.delta!.toJson(), [
{'insert': link},
]);
});
});
group('Paste as Bookmark', () {
Future<void> pasteAsBookmark(WidgetTester tester, String link) =>
pasteAs(tester, link, PasteMenuType.bookmark);
Future<void> hoverAndClick(
WidgetTester tester,
LinkPreviewMenuCommand command,
) async {
final bookmark = find.byType(CustomLinkPreviewBlockComponent);
expect(bookmark, findsOneWidget);
await tester.hoverOnWidget(
bookmark,
onHover: () async {
final menuButton = find.byFlowySvg(FlowySvgs.toolbar_more_m);
await tester.tapButton(menuButton);
final commandButton = find.text(command.title);
await tester.tapButton(commandButton);
},
);
}
testWidgets('paste a link as bookmark', (tester) async {
final link = avaliableLink;
await preparePage(tester);
await pasteAsBookmark(tester, link);
final node = tester.editor.getNodeAtPath([0]);
checkBookmark(node, link);
});
testWidgets('paste a link as bookmark and convert to mention',
(tester) async {
final link = avaliableLink;
await preparePage(tester);
await pasteAsBookmark(tester, link);
await hoverAndClick(tester, LinkPreviewMenuCommand.convertToMention);
final node = tester.editor.getNodeAtPath([0]);
checkMention(node, link);
});
testWidgets('paste a link as bookmark and convert to url', (tester) async {
final link = avaliableLink;
await preparePage(tester);
await pasteAsBookmark(tester, link);
await hoverAndClick(tester, LinkPreviewMenuCommand.convertToUrl);
final node = tester.editor.getNodeAtPath([0]);
checkUrl(node, link);
});
testWidgets('paste a link as bookmark and convert to embed',
(tester) async {
final link = avaliableLink;
await preparePage(tester);
await pasteAsBookmark(tester, link);
await hoverAndClick(tester, LinkPreviewMenuCommand.convertToEmbed);
final node = tester.editor.getNodeAtPath([0]);
checkEmbed(node, link);
});
testWidgets('paste a link as bookmark and copy link', (tester) async {
final link = avaliableLink;
await preparePage(tester);
await pasteAsBookmark(tester, link);
await hoverAndClick(tester, LinkPreviewMenuCommand.copyLink);
final clipboardContent = await getIt<ClipboardService>().getData();
expect(clipboardContent.plainText, link);
});
testWidgets('paste a link as bookmark and replace link', (tester) async {
final link = avaliableLink;
await preparePage(tester);
await pasteAsBookmark(tester, link);
await hoverAndClick(tester, LinkPreviewMenuCommand.replace);
await tester.simulateKeyEvent(
LogicalKeyboardKey.keyA,
isControlPressed: Platform.isLinux || Platform.isWindows,
isMetaPressed: Platform.isMacOS,
);
await tester.simulateKeyEvent(LogicalKeyboardKey.delete);
await tester.enterText(find.byType(TextFormField), unavailableLink);
await tester.tapButton(find.text(LocaleKeys.button_replace.tr()));
final node = tester.editor.getNodeAtPath([0]);
checkBookmark(node, unavailableLink);
});
testWidgets('paste a link as bookmark and remove link', (tester) async {
final link = avaliableLink;
await preparePage(tester);
await pasteAsBookmark(tester, link);
await hoverAndClick(tester, LinkPreviewMenuCommand.removeLink);
final node = tester.editor.getNodeAtPath([0]);
expect(node.type, ParagraphBlockKeys.type);
expect(node.delta!.toJson(), [
{'insert': link},
]);
});
});
group('Paste as Embed', () {
Future<void> pasteAsEmbed(WidgetTester tester, String link) =>
pasteAs(tester, link, PasteMenuType.embed);
Future<void> hoverAndConvert(
WidgetTester tester,
PasteMenuType command,
) async {
final embed = find.byType(LinkEmbedBlockComponent);
expect(embed, findsOneWidget);
await tester.hoverOnWidget(
embed,
onHover: () async {
final menuButton = find.byFlowySvg(FlowySvgs.turninto_m);
await tester.tapButton(menuButton);
final commandButton = find.text(command.title);
await tester.tapButton(commandButton);
},
);
}
testWidgets('paste a link as embed', (tester) async {
final link = avaliableLink;
await preparePage(tester);
await pasteAsEmbed(tester, link);
final node = tester.editor.getNodeAtPath([0]);
checkEmbed(node, link);
});
testWidgets('paste a link as bookmark and convert to mention',
(tester) async {
final link = avaliableLink;
await preparePage(tester);
await pasteAsEmbed(tester, link);
await hoverAndConvert(tester, PasteMenuType.mention);
final node = tester.editor.getNodeAtPath([0]);
checkMention(node, link);
});
testWidgets('paste a link as bookmark and convert to url', (tester) async {
final link = avaliableLink;
await preparePage(tester);
await pasteAsEmbed(tester, link);
await hoverAndConvert(tester, PasteMenuType.url);
final node = tester.editor.getNodeAtPath([0]);
checkUrl(node, link);
});
testWidgets('paste a link as bookmark and convert to bookmark',
(tester) async {
final link = avaliableLink;
await preparePage(tester);
await pasteAsEmbed(tester, link);
await hoverAndConvert(tester, PasteMenuType.bookmark);
final node = tester.editor.getNodeAtPath([0]);
checkBookmark(node, link);
});
});
}
@@ -13,6 +13,7 @@ import 'document_with_multi_image_block_test.dart'
as document_with_multi_image_block_test;
import 'document_with_simple_table_test.dart'
as document_with_simple_table_test;
import 'document_link_preview_test.dart' as document_link_preview_test;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
@@ -28,4 +29,5 @@ void main() {
document_find_menu_test.main();
document_toolbar_test.main();
document_with_simple_table_test.main();
document_link_preview_test.main();
}
@@ -43,7 +43,10 @@ void main() {
});
group('insert emoji by colon', () {
Future<void> createNewDocumentAndShowEmojiList(WidgetTester tester, {String? search}) async {
Future<void> createNewDocumentAndShowEmojiList(
WidgetTester tester, {
String? search,
}) async {
await tester.initializeAppFlowy();
await tester.tapAnonymousSignInButton();
await tester.createNewPageWithNameUnderParent();
@@ -54,8 +54,6 @@ extension AppFlowyTestBase on WidgetTester {
final rustEnvs = <String, String>{};
if (cloudType != null) {
switch (cloudType) {
case AuthenticatorType.local:
break;
case AuthenticatorType.appflowyCloudSelfHost:
rustEnvs["GOTRUE_ADMIN_EMAIL"] = "admin@example.com";
rustEnvs["GOTRUE_ADMIN_PASSWORD"] = "password";
@@ -71,9 +69,6 @@ extension AppFlowyTestBase on WidgetTester {
() async {
if (cloudType != null) {
switch (cloudType) {
case AuthenticatorType.local:
await useLocalServer();
break;
case AuthenticatorType.appflowyCloudSelfHost:
await useTestSelfHostedAppFlowyCloud();
getIt.unregister<AuthService>();
+23 -23
View File
@@ -181,37 +181,37 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/webview_flutter_wkwebview/darwin"
SPEC CHECKSUMS:
app_links: 3da4c36b46cac3bf24eb897f1a6ce80bda109874
appflowy_backend: 78f6a053f756e6bc29bcc5a2106cbe77b756e97a
connectivity_plus: 481668c94744c30c53b8895afb39159d1e619bdf
device_info_plus: 71ffc6ab7634ade6267c7a93088ed7e4f74e5896
app_links: e7a6750a915a9e161c58d91bc610e8cd1d4d0ad0
appflowy_backend: 144c20d8bfb298c4e10fa3fa6701a9f41bf98b88
connectivity_plus: bf0076dd84a130856aa636df1c71ccaff908fa1d
device_info_plus: 97af1d7e84681a90d0693e63169a5d50e0839a0d
DKImagePickerController: b512c28220a2b8ac7419f21c491fc8534b7601ac
DKPhotoGallery: fdfad5125a9fdda9cc57df834d49df790dbb4179
file_picker: 9b3292d7c8bc68c8a7bf8eb78f730e49c8efc517
flowy_infra_ui: 931b73a18b54a392ab6152eebe29a63a30751f53
file_picker: 09aa5ec1ab24135ccd7a1621c46c84134bfd6655
flowy_infra_ui: 0455e1fa8c51885aa1437848e361e99419f34ebc
Flutter: e0871f40cf51350855a761d2e70bf5af5b9b5de7
fluttertoast: 76fea30fcf04176325f6864c87306927bd7d2038
image_picker_ios: 7fe1ff8e34c1790d6fff70a32484959f563a928a
integration_test: 4a889634ef21a45d28d50d622cf412dc6d9f586e
irondash_engine_context: 8e58ca8e0212ee9d1c7dc6a42121849986c88486
keyboard_height_plugin: ef70a8181b29f27670e9e2450814ca6b6dc05b05
open_filex: 432f3cd11432da3e39f47fcc0df2b1603854eff1
package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
path_provider_foundation: 080d55be775b7414fd5a5ef3ac137b97b097e564
permission_handler_apple: 4ed2196e43d0651e8ff7ca3483a069d469701f2d
fluttertoast: e9a18c7be5413da53898f660530c56f35edfba9c
image_picker_ios: c560581cceedb403a6ff17f2f816d7fea1421fc1
integration_test: 252f60fa39af5e17c3aa9899d35d908a0721b573
irondash_engine_context: 3458bf979b90d616ffb8ae03a150bafe2e860cc9
keyboard_height_plugin: 43fa8bba20fd5c4fdeed5076466b8b9d43cc6b86
open_filex: 6e26e659846ec990262224a12ef1c528bb4edbe4
package_info_plus: c0502532a26c7662a62a356cebe2692ec5fe4ec4
path_provider_foundation: 2b6b4c569c0fb62ec74538f866245ac84301af46
permission_handler_apple: 9878588469a2b0d0fc1e048d9f43605f92e6cec2
ReachabilitySwift: 985039c6f7b23a1da463388634119492ff86c825
saver_gallery: af2d0c762dafda254e0ad025ef0dabd6506cd490
saver_gallery: 76172dc4bf6b40e66d694948ada9ff402304dd87
SDWebImage: b9a731e1d6307f44ca703b3976d18c24ca561e84
Sentry: 1fe34e9c2cbba1e347623610d26db121dcb569f1
sentry_flutter: e24b397f9a61fa5bbefd8279c3b2242ca86faa90
share_plus: 50da8cb520a8f0f65671c6c6a99b3617ed10a58a
shared_preferences_foundation: 9e1978ff2562383bd5676f64ec4e9aa8fa06a6f7
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
super_native_extensions: b763c02dc3a8fd078389f410bf15149179020cb4
sentry_flutter: a39c2a2d67d5e5b9cb0b94a4985c76dd5b3fc737
share_plus: 8b6f8b3447e494cca5317c8c3073de39b3600d1f
shared_preferences_foundation: fcdcbc04712aee1108ac7fda236f363274528f78
sqflite_darwin: 5a7236e3b501866c1c9befc6771dfd73ffb8702d
super_native_extensions: 4916b3c627a9c7fffdc48a23a9eca0b1ac228fa7
SwiftyGif: 6c3eafd0ce693cad58bb63d2b2fb9bacb8552780
Toast: 91b396c56ee72a5790816f40d3a94dd357abc196
url_launcher_ios: 694010445543906933d732453a59da0a173ae33d
webview_flutter_wkwebview: 44d4dee7d7056d5ad185d25b38404436d56c547c
url_launcher_ios: 5334b05cef931de560670eeae103fd3e431ac3fe
webview_flutter_wkwebview: 0982481e3d9c78fd5c6f62a002fcd24fc791f1e4
PODFILE CHECKSUM: d0d9b4ff572d8695c38eb3f9b490f55cdfc57eca
@@ -133,7 +133,6 @@ Future<bool> _afLaunchLocalUri(
};
if (context != null && context.mounted) {
showToastNotification(
context,
message: message,
type: result.type == ResultType.done
? ToastificationType.success
+2
View File
@@ -16,6 +16,7 @@ class AppFlowyConfiguration {
required this.platform,
required this.authenticator_type,
required this.appflowy_cloud_config,
required this.is_anon,
required this.envs,
});
@@ -28,6 +29,7 @@ class AppFlowyConfiguration {
final String origin_app_path;
final String device_id;
final String platform;
final bool is_anon;
final int authenticator_type;
final AppFlowyCloudConfiguration appflowy_cloud_config;
final Map<String, String> envs;
+1 -21
View File
@@ -23,9 +23,6 @@ import 'package:appflowy_backend/log.dart';
///
Future<void> _setAuthenticatorType(AuthenticatorType ty) async {
switch (ty) {
case AuthenticatorType.local:
await getIt<KeyValueStorage>().set(KVKeys.kCloudType, 0.toString());
break;
case AuthenticatorType.appflowyCloud:
await getIt<KeyValueStorage>().set(KVKeys.kCloudType, 2.toString());
break;
@@ -63,8 +60,6 @@ Future<AuthenticatorType> getAuthenticatorType() async {
}
switch (value ?? "0") {
case "0":
return AuthenticatorType.local;
case "2":
return AuthenticatorType.appflowyCloud;
case "3":
@@ -100,24 +95,17 @@ bool get isAuthEnabled {
return false;
}
bool get isLocalAuthEnabled {
return currentCloudType().isLocal;
}
/// Determines if AppFlowy Cloud is enabled.
bool get isAppFlowyCloudEnabled {
return currentCloudType().isAppFlowyCloudEnabled;
}
enum AuthenticatorType {
local,
appflowyCloud,
appflowyCloudSelfHost,
// The 'appflowyCloudDevelop' type is used for develop purposes only.
appflowyCloudDevelop;
bool get isLocal => this == AuthenticatorType.local;
bool get isAppFlowyCloudEnabled =>
this == AuthenticatorType.appflowyCloudSelfHost ||
this == AuthenticatorType.appflowyCloudDevelop ||
@@ -125,8 +113,6 @@ enum AuthenticatorType {
int get value {
switch (this) {
case AuthenticatorType.local:
return 0;
case AuthenticatorType.appflowyCloud:
return 2;
case AuthenticatorType.appflowyCloudSelfHost:
@@ -138,8 +124,6 @@ enum AuthenticatorType {
static AuthenticatorType fromValue(int value) {
switch (value) {
case 0:
return AuthenticatorType.local;
case 2:
return AuthenticatorType.appflowyCloud;
case 3:
@@ -147,7 +131,7 @@ enum AuthenticatorType {
case 4:
return AuthenticatorType.appflowyCloudDevelop;
default:
return AuthenticatorType.local;
return AuthenticatorType.appflowyCloud;
}
}
}
@@ -180,10 +164,6 @@ Future<void> useAppFlowyBetaCloudWithURL(
await _setAppFlowyCloudUrl(url);
}
Future<void> useLocalServer() async {
await _setAuthenticatorType(AuthenticatorType.local);
}
// Use getIt<AppFlowyCloudSharedEnv>() to get the shared environment.
class AppFlowyCloudSharedEnv {
AppFlowyCloudSharedEnv({
@@ -336,7 +336,6 @@ class _MobileViewPageState extends State<MobileViewPage> {
listener: (context, state) {
if (state.isLocked) {
showToastNotification(
context,
message: LocaleKeys.lockPage_pageLockedToast.tr(),
);
@@ -366,7 +365,6 @@ class _MobileViewPageState extends State<MobileViewPage> {
listener: (context, state) {
if (state.isLocked) {
showToastNotification(
context,
message: LocaleKeys.lockPage_pageLockedToast.tr(),
);
}
@@ -161,7 +161,6 @@ class MobileViewPageMoreBottomSheet extends StatelessWidget {
context.pop();
showToastNotification(
context,
message: LocaleKeys.button_duplicateSuccessfully.tr(),
);
}
@@ -170,7 +169,6 @@ class MobileViewPageMoreBottomSheet extends StatelessWidget {
_toggleFavorite(context);
showToastNotification(
context,
message: LocaleKeys.button_favoriteSuccessfully.tr(),
);
}
@@ -179,7 +177,6 @@ class MobileViewPageMoreBottomSheet extends StatelessWidget {
_toggleFavorite(context);
showToastNotification(
context,
message: LocaleKeys.button_unfavoriteSuccessfully.tr(),
);
}
@@ -202,8 +199,7 @@ class MobileViewPageMoreBottomSheet extends StatelessWidget {
),
);
showToastNotification(
context,
message: LocaleKeys.grid_url_copy.tr(),
message: LocaleKeys.message_copy_success.tr(),
);
}
}
@@ -234,12 +230,10 @@ class MobileViewPageMoreBottomSheet extends StatelessWidget {
),
);
showToastNotification(
context,
message: LocaleKeys.shareAction_copyLinkSuccess.tr(),
);
} else {
showToastNotification(
context,
message: LocaleKeys.shareAction_copyLinkToBlockFailed.tr(),
type: ToastificationType.error,
);
@@ -323,11 +317,9 @@ class MobileViewPageMoreBottomSheet extends StatelessWidget {
if (state.publishResult != null) {
state.publishResult!.fold(
(value) => showToastNotification(
context,
message: LocaleKeys.publish_publishSuccessfully.tr(),
),
(error) => showToastNotification(
context,
message: '${LocaleKeys.publish_publishFailed.tr()}: ${error.code}',
type: ToastificationType.error,
),
@@ -335,11 +327,9 @@ class MobileViewPageMoreBottomSheet extends StatelessWidget {
} else if (state.unpublishResult != null) {
state.unpublishResult!.fold(
(value) => showToastNotification(
context,
message: LocaleKeys.publish_unpublishSuccessfully.tr(),
),
(error) => showToastNotification(
context,
message: LocaleKeys.publish_unpublishFailed.tr(),
description: error.msg,
type: ToastificationType.error,
@@ -349,7 +339,6 @@ class MobileViewPageMoreBottomSheet extends StatelessWidget {
state.updatePathNameResult!.onSuccess(
(value) {
showToastNotification(
context,
message:
LocaleKeys.settings_sites_success_updatePathNameSuccess.tr(),
);
@@ -65,7 +65,6 @@ class _MobileViewItemBottomSheetState extends State<MobileViewItemBottomSheet> {
Navigator.pop(context);
context.read<ViewBloc>().add(const ViewEvent.duplicate());
showToastNotification(
context,
message: LocaleKeys.button_duplicateSuccessfully.tr(),
);
break;
@@ -84,7 +83,6 @@ class _MobileViewItemBottomSheetState extends State<MobileViewItemBottomSheet> {
.read<FavoriteBloc>()
.add(FavoriteEvent.toggle(widget.view));
showToastNotification(
context,
message: !widget.view.isFavorite
? LocaleKeys.button_favoriteSuccessfully.tr()
: LocaleKeys.button_unfavoriteSuccessfully.tr(),
@@ -146,7 +144,6 @@ class _MobileViewItemBottomSheetState extends State<MobileViewItemBottomSheet> {
Navigator.pop(context);
showToastNotification(
context,
message: LocaleKeys.sideBar_removeSuccess.tr(),
);
},
@@ -45,7 +45,6 @@ enum MobilePaneActionType {
size: 24.0,
onPressed: (context) {
showToastNotification(
context,
message: LocaleKeys.button_unfavoriteSuccessfully.tr(),
);
@@ -61,7 +60,6 @@ enum MobilePaneActionType {
size: 24.0,
onPressed: (context) {
showToastNotification(
context,
message: LocaleKeys.button_favoriteSuccessfully.tr(),
);
@@ -103,7 +103,7 @@ class _OpenRowPageButtonState extends State<OpenRowPageButton> {
Log.info('Open row page(${widget.documentId})');
if (view == null) {
showToastNotification(context, message: 'Failed to open row page');
showToastNotification(message: 'Failed to open row page');
// reload the view again
unawaited(_preloadView(context));
Log.error('Failed to open row page(${widget.documentId})');
@@ -329,7 +329,7 @@ class _HomePageState extends State<_HomePage> {
}
if (message != null) {
showToastNotification(context, message: message, type: toastType);
showToastNotification(message: message, type: toastType);
}
}
}
@@ -339,7 +339,6 @@ class _SpaceMenuItemTrailingState extends State<SpaceMenuItemTrailing> {
context.read<SpaceBloc>().add(const SpaceEvent.duplicate());
showToastNotification(
context,
message: LocaleKeys.space_success_duplicateSpace.tr(),
);
@@ -374,7 +373,6 @@ class _SpaceMenuItemTrailingState extends State<SpaceMenuItemTrailing> {
.add(SpaceEvent.rename(space: widget.space, name: name));
showToastNotification(
context,
message: LocaleKeys.space_success_renameSpace.tr(),
);
},
@@ -424,7 +422,6 @@ class _SpaceMenuItemTrailingState extends State<SpaceMenuItemTrailing> {
);
showToastNotification(
context,
message: LocaleKeys.space_success_updateSpace.tr(),
);
@@ -457,7 +454,6 @@ class _SpaceMenuItemTrailingState extends State<SpaceMenuItemTrailing> {
context.read<SpaceBloc>().add(SpaceEvent.delete(widget.space));
showToastNotification(
context,
message: LocaleKeys.space_success_deleteSpace.tr(),
);
@@ -102,7 +102,7 @@ class MobileInlineActionsWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final hasIcon = item.icon != null;
final hasIcon = item.iconBuilder != null;
return Container(
height: 36,
decoration: BoxDecoration(
@@ -119,7 +119,7 @@ class MobileInlineActionsWidget extends StatelessWidget {
child: Row(
children: [
if (hasIcon) ...[
item.icon!.call(isSelected),
item.iconBuilder!.call(isSelected),
SizedBox(width: 12),
],
Flexible(
@@ -332,7 +332,6 @@ class _NotificationNavigationBar extends StatelessWidget {
}
showToastNotification(
context,
message: LocaleKeys
.settings_notifications_markAsReadNotifications_allSuccess
.tr(),
@@ -350,7 +349,6 @@ class _NotificationNavigationBar extends StatelessWidget {
}
showToastNotification(
context,
message: LocaleKeys.settings_notifications_archiveNotifications_allSuccess
.tr(),
);
@@ -108,7 +108,6 @@ class NotificationSettingsPopupMenu extends StatelessWidget {
void _onMarkAllAsRead(BuildContext context) {
showToastNotification(
context,
message: LocaleKeys
.settings_notifications_markAsReadNotifications_allSuccess
.tr(),
@@ -119,7 +118,6 @@ class NotificationSettingsPopupMenu extends StatelessWidget {
void _onArchiveAll(BuildContext context) {
showToastNotification(
context,
message: LocaleKeys.settings_notifications_archiveNotifications_allSuccess
.tr(),
);
@@ -133,7 +131,6 @@ class NotificationSettingsPopupMenu extends StatelessWidget {
}
showToastNotification(
context,
message: 'Unarchive all success (Debug Mode)',
);
@@ -31,7 +31,6 @@ enum NotificationPaneActionType {
size: 24.0,
onPressed: (context) {
showToastNotification(
context,
message: LocaleKeys
.settings_notifications_markAsReadNotifications_success
.tr(),
@@ -55,7 +54,6 @@ enum NotificationPaneActionType {
size: 24.0,
onPressed: (context) {
showToastNotification(
context,
message: 'Unarchive notification success',
);
@@ -168,7 +166,6 @@ class _NotificationMoreActions extends StatelessWidget {
Navigator.of(context).pop();
showToastNotification(
context,
message: LocaleKeys.settings_notifications_markAsReadNotifications_success
.tr(),
);
@@ -191,7 +188,6 @@ class _NotificationMoreActions extends StatelessWidget {
void _onArchive(BuildContext context) {
showToastNotification(
context,
message: LocaleKeys.settings_notifications_archiveNotifications_success
.tr()
.tr(),
@@ -74,7 +74,6 @@ class _NotificationTabState extends State<NotificationTab>
if (context.mounted) {
showToastNotification(
context,
message: LocaleKeys.settings_notifications_refreshSuccess.tr(),
);
}
@@ -81,7 +81,6 @@ class SupportSettingGroup extends StatelessWidget {
);
if (context.mounted) {
showToastNotification(
context,
message: LocaleKeys.settings_files_clearCacheSuccess.tr(),
);
}
@@ -1,9 +1,7 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart';
import 'package:appflowy/mobile/presentation/widgets/show_flowy_mobile_confirm_dialog.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/user/application/auth/auth_service.dart';
import 'package:appflowy/user/application/sign_in_bloc.dart';
import 'package:appflowy/user/presentation/screens/sign_in_screen/widgets/widgets.dart';
import 'package:appflowy/workspace/presentation/settings/pages/account/account_deletion.dart';
@@ -32,12 +30,6 @@ class UserSessionSettingGroup extends StatelessWidget {
if (showThirdPartyLogin) _buildThirdPartySignInButtons(context),
const VSpace(8.0),
// logout button
MobileLogoutButton(
text: LocaleKeys.settings_menu_logout.tr(),
onPressed: () async => _showLogoutDialog(),
),
// delete account button
// only show the delete account button in cloud mode
if (userProfile.authenticator == AuthenticatorPB.AppFlowyCloud) ...[
@@ -79,31 +71,6 @@ class UserSessionSettingGroup extends StatelessWidget {
builder: (_) => const _DeleteAccountBottomSheet(),
);
}
Future<void> _showLogoutDialog() async {
return showFlowyCupertinoConfirmDialog(
title: LocaleKeys.settings_menu_logoutPrompt.tr(),
leftButton: FlowyText(
LocaleKeys.button_cancel.tr(),
fontSize: 17.0,
figmaLineHeight: 24.0,
fontWeight: FontWeight.w500,
color: const Color(0xFF007AFF),
),
rightButton: FlowyText(
LocaleKeys.button_logout.tr(),
fontSize: 17.0,
figmaLineHeight: 24.0,
fontWeight: FontWeight.w400,
color: const Color(0xFFFE0220),
),
onRightButtonPressed: (context) async {
Navigator.of(context).pop();
await getIt<AuthService>().signOut();
await runAppFlowy();
},
);
}
}
class _DeleteAccountBottomSheet extends StatefulWidget {
@@ -201,7 +201,6 @@ class _InviteMemberPageState extends State<_InviteMemberPage> {
result.fold(
(s) {
showToastNotification(
context,
message:
LocaleKeys.settings_appearance_members_addMemberSuccess.tr(),
bottomPadding: keyboardHeight,
@@ -218,7 +217,6 @@ class _InviteMemberPageState extends State<_InviteMemberPage> {
exceededLimit = f.code == ErrorCode.WorkspaceMemberLimitExceeded;
});
showToastNotification(
context,
type: ToastificationType.error,
bottomPadding: keyboardHeight,
message: message,
@@ -229,7 +227,6 @@ class _InviteMemberPageState extends State<_InviteMemberPage> {
result.fold(
(s) {
showToastNotification(
context,
message:
LocaleKeys.settings_appearance_members_inviteMemberSuccess.tr(),
bottomPadding: keyboardHeight,
@@ -247,7 +244,6 @@ class _InviteMemberPageState extends State<_InviteMemberPage> {
exceededLimit = f.code == ErrorCode.WorkspaceMemberLimitExceeded;
});
showToastNotification(
context,
type: ToastificationType.error,
message: message,
bottomPadding: keyboardHeight,
@@ -258,7 +254,6 @@ class _InviteMemberPageState extends State<_InviteMemberPage> {
result.fold(
(s) {
showToastNotification(
context,
message: LocaleKeys
.settings_appearance_members_removeFromWorkspaceSuccess
.tr(),
@@ -267,7 +262,6 @@ class _InviteMemberPageState extends State<_InviteMemberPage> {
},
(f) {
showToastNotification(
context,
type: ToastificationType.error,
message: LocaleKeys
.settings_appearance_members_removeFromWorkspaceFailed
@@ -283,7 +277,6 @@ class _InviteMemberPageState extends State<_InviteMemberPage> {
final email = emailController.text;
if (!isEmail(email)) {
showToastNotification(
context,
type: ToastificationType.error,
message: LocaleKeys.settings_appearance_members_emailInvalidError.tr(),
);
@@ -184,8 +184,7 @@ class CopyButton extends StatelessWidget {
);
if (context.mounted) {
showToastNotification(
context,
message: LocaleKeys.grid_url_copiedNotification.tr(),
message: LocaleKeys.message_copy_success.tr(),
);
}
},
@@ -376,8 +376,7 @@ class ChatAIMessagePopup extends StatelessWidget {
}
if (context.mounted) {
showToastNotification(
context,
message: LocaleKeys.grid_url_copiedNotification.tr(),
message: LocaleKeys.message_copy_success.tr(),
);
}
},
@@ -14,7 +14,6 @@ import 'package:universal_platform/universal_platform.dart';
void openPageFromMessage(BuildContext context, ViewPB? view) {
if (view == null) {
showToastNotification(
context,
message: LocaleKeys.chat_openPagePreviewFailedToast.tr(),
type: ToastificationType.error,
);
@@ -36,7 +35,6 @@ void showSaveMessageSuccessToast(BuildContext context, ViewPB? view) {
return;
}
showToastNotification(
context,
richMessage: TextSpan(
children: [
TextSpan(
@@ -241,6 +241,11 @@ class SelectOptionCellEditorBloc
} else if (!state.selectedOptions
.any((option) => option.id == focusedOptionId)) {
_selectOptionService.select(optionIds: [focusedOptionId]);
emit(
state.copyWith(
clearFilter: true,
),
);
}
}
@@ -203,7 +203,7 @@ class MobileURLEditor extends StatelessWidget {
ClipboardData(text: textEditingController.text),
);
Fluttertoast.showToast(
msg: LocaleKeys.grid_url_copiedNotification.tr(),
msg: LocaleKeys.message_copy_success.tr(),
gravity: ToastGravity.BOTTOM,
);
context.pop();
@@ -442,7 +442,6 @@ class DocumentBloc extends Bloc<DocumentEvent, DocumentState> {
final context = AppGlobals.rootNavKey.currentContext;
if (context != null && context.mounted) {
showToastNotification(
context,
message: 'document integrity check failed',
type: ToastificationType.error,
);
@@ -16,6 +16,7 @@ import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:universal_platform/universal_platform.dart';
import 'editor_plugins/link_preview/custom_link_preview_block_component.dart';
import 'editor_plugins/page_block/custom_page_block_component.dart';
/// A global configuration for the editor.
@@ -969,11 +970,11 @@ OutlineBlockComponentBuilder _buildOutlineBlockComponentBuilder(
);
}
LinkPreviewBlockComponentBuilder _buildLinkPreviewBlockComponentBuilder(
CustomLinkPreviewBlockComponentBuilder _buildLinkPreviewBlockComponentBuilder(
BuildContext context,
BlockComponentConfiguration configuration,
) {
return LinkPreviewBlockComponentBuilder(
return CustomLinkPreviewBlockComponentBuilder(
configuration: configuration.copyWith(
padding: (node) {
if (UniversalPlatform.isMobile) {
@@ -983,20 +984,6 @@ LinkPreviewBlockComponentBuilder _buildLinkPreviewBlockComponentBuilder(
},
),
cache: LinkPreviewDataCache(),
showMenu: true,
menuBuilder: (context, node, state) => Positioned(
top: 10,
right: 0,
child: LinkPreviewMenu(node: node, state: state),
),
builder: (_, node, url, title, description, imageUrl) =>
CustomLinkPreviewWidget(
node: node,
url: url,
title: title,
description: description,
imageUrl: imageUrl,
),
);
}
@@ -150,7 +150,6 @@ class _AiWriterToolbarActionListState extends State<AiWriterToolbarActionList> {
});
} else {
showToastNotification(
context,
message: LocaleKeys.document_plugins_appflowyAIEditDisabled.tr(),
);
}
@@ -196,7 +195,6 @@ class ImproveWritingButton extends StatelessWidget {
_insertAiNode(editorState, AiWriterCommand.improveWriting);
} else {
showToastNotification(
context,
message: LocaleKeys.document_plugins_appflowyAIEditDisabled.tr(),
);
}
@@ -57,8 +57,13 @@ class AiWriterCubit extends Cubit<AiWriterState> {
bool withDiscard = true,
bool withUnformat = true,
}) async {
if (aiWriterNode == null) {
return;
}
if (withDiscard) {
await _textRobot.discard();
await _textRobot.discard(
afterSelection: aiWriterNode!.aiWriterSelection,
);
}
_textRobot.clear();
_textRobot.reset();
@@ -232,6 +237,12 @@ class AiWriterCubit extends Cubit<AiWriterState> {
'trigger accept action, markdown text: $trimmedMarkdownText',
);
await formatSelection(
editorState,
selection,
ApplySuggestionFormatType.clear,
);
await _textRobot.deleteAINodes();
await _textRobot.replace(
@@ -40,6 +40,7 @@ class _AiWriterScrollWrapperState extends State<AiWriterScrollWrapper> {
onRemoveNode: () {
aiWriterRegistered = false;
widget.editorState.service.keyboardService?.enableShortcuts();
widget.editorState.service.keyboardService?.enable();
},
onAppendToDocument: onAppendToDocument,
);
@@ -70,13 +70,12 @@ extension InsertDatabase on EditorState {
node,
selection.end.offset,
0,
r'$',
attributes: {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.page.name,
MentionBlockKeys.pageId: view.id,
},
},
MentionBlockKeys.mentionChar,
attributes: MentionBlockKeys.buildMentionPageAttributes(
mentionType: MentionType.page,
pageId: view.id,
blockId: null,
),
);
}
@@ -118,7 +118,7 @@ class MarkdownTextRobot {
}
await _lock.synchronized(() async {
await _refresh(inMemoryUpdate: false);
await _refresh(inMemoryUpdate: false, updateSelection: true);
});
if (_enableDebug) {
@@ -156,7 +156,9 @@ class MarkdownTextRobot {
}
/// Discard the inserted content
Future<void> discard() async {
Future<void> discard({
Selection? afterSelection,
}) async {
final start = _insertPosition;
if (start == null) {
return;
@@ -165,6 +167,8 @@ class MarkdownTextRobot {
return;
}
afterSelection ??= Selection.collapsed(start);
// fallback to the calculated position if the selection is null.
final end = Position(
path: start.path.nextNPath(_insertedNodes.length - 1),
@@ -174,7 +178,7 @@ class MarkdownTextRobot {
);
final transaction = editorState.transaction
..deleteNodes(deletedNodes)
..afterSelection = Selection.collapsed(start);
..afterSelection = afterSelection;
await editorState.apply(
transaction,
@@ -47,7 +47,6 @@ class _CopyButton extends StatelessWidget {
if (context.mounted) {
showToastNotification(
context,
message: LocaleKeys.document_codeBlock_codeCopiedSnackbar.tr(),
);
}
@@ -16,6 +16,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:http/http.dart' as http;
import 'package:string_validator/string_validator.dart';
import 'package:universal_platform/universal_platform.dart';
/// - support
/// - desktop
@@ -162,6 +163,7 @@ Future<bool> _pasteAsLinkPreview(
EditorState editorState,
String? text,
) async {
final isMobile = UniversalPlatform.isMobile;
// the url should contain a protocol
if (text == null || !isURL(text, {'require_protocol': true})) {
return false;
@@ -193,6 +195,8 @@ Future<bool> _pasteAsLinkPreview(
return false;
}
if (!isMobile && !isImageUrl) return false;
// insert the text with link format
final textTransaction = editorState.transaction
..insertText(
@@ -250,6 +254,7 @@ Future<void> doPlainPaste(EditorState editorState) async {
}
Future<bool> _isImageUrl(String text) async {
if (isNotImageUrl(text)) return false;
final response = await http.head(Uri.parse(text));
if (response.statusCode == 200) {
@@ -43,13 +43,11 @@ extension PasteFromBlockLink on EditorState {
node,
selection.startIndex,
MentionBlockKeys.mentionChar,
attributes: {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.page.name,
MentionBlockKeys.blockId: blockId,
MentionBlockKeys.pageId: pageId,
},
},
attributes: MentionBlockKeys.buildMentionPageAttributes(
mentionType: MentionType.page,
pageId: pageId,
blockId: blockId,
),
);
await apply(transaction);
@@ -1,3 +1,4 @@
import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/paste_from_plain_text.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/shared/markdown_to_document.dart';
import 'package:appflowy/shared/patterns/common_patterns.dart';
@@ -13,6 +14,7 @@ extension PasteFromHtml on EditorState {
}
if (nodes.length == 1) {
await pasteSingleLineNode(nodes.first);
checkToShowPasteAsMenu(nodes.first);
} else {
await pasteMultiLineNodes(nodes.toList());
}
@@ -73,7 +73,6 @@ extension PasteFromImage on EditorState {
Log.info('unsupported format: $format');
if (UniversalPlatform.isMobile) {
showToastNotification(
context,
message: LocaleKeys.document_imageBlock_error_invalidImageFormat.tr(),
);
}
@@ -112,7 +111,6 @@ extension PasteFromImage on EditorState {
if (errorMessage != null && context.mounted) {
showToastNotification(
context,
message: errorMessage,
);
return false;
@@ -131,7 +129,6 @@ extension PasteFromImage on EditorState {
Log.error('cannot copy image file', e);
if (context.mounted) {
showToastNotification(
context,
message: LocaleKeys.document_imageBlock_error_invalidImage.tr(),
);
}
@@ -1,6 +1,8 @@
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/paste_as/paste_as_menu.dart';
import 'package:appflowy/shared/markdown_to_document.dart';
import 'package:appflowy/shared/patterns/common_patterns.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:universal_platform/universal_platform.dart';
extension PasteFromPlainText on EditorState {
Future<void> pastePlainText(String plainText) async {
@@ -41,6 +43,7 @@ extension PasteFromPlainText on EditorState {
}
if (nodes.length == 1) {
await pasteSingleLineNode(nodes.first);
checkToShowPasteAsMenu(nodes.first);
} else {
await pasteMultiLineNodes(nodes.toList());
}
@@ -65,6 +68,29 @@ extension PasteFromPlainText on EditorState {
AppFlowyRichTextKeys.href: plainText,
});
await apply(transaction);
checkToShowPasteAsMenu(node);
return true;
}
void checkToShowPasteAsMenu(Node node) {
if (selection == null || !selection!.isCollapsed) return;
if (UniversalPlatform.isMobile) return;
final href = _getLinkFromNode(node);
if (href != null) {
final context = document.root.context;
if (context != null && context.mounted) {
PasteAsMenuService(context: context, editorState: this).show(href);
}
}
}
String? _getLinkFromNode(Node node) {
final delta = node.delta;
if (delta == null) return null;
final inserts = delta.whereType<TextInsert>();
if (inserts.isEmpty || inserts.length > 1) return null;
final link = inserts.first.attributes?.href;
if (link != null) return inserts.first.text;
return null;
}
}
@@ -304,11 +304,14 @@ void showLinkCreateMenu(
return (left, top, right, bottom, alignment);
}
ShapeDecoration buildToolbarLinkDecoration(BuildContext context) =>
ShapeDecoration buildToolbarLinkDecoration(
BuildContext context, {
double radius = 12.0,
}) =>
ShapeDecoration(
color: Theme.of(context).cardColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
borderRadius: BorderRadius.circular(radius),
),
shadows: [
const BoxShadow(
@@ -6,6 +6,9 @@ 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/copy_and_paste/clipboard_service.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/desktop_floating_toolbar.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_embed/link_embed_block_component.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/shared.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_block.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/mention/mention_page_block.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/toolbar_item/custom_link_toolbar_item.dart';
import 'package:appflowy/startup/startup.dart';
@@ -14,6 +17,7 @@ import 'package:appflowy/workspace/application/view/view_service.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
@@ -139,6 +143,7 @@ class _LinkHoverTriggerState extends State<LinkHoverTrigger> {
isHoverMenuHovering = false;
tryToDismissLinkHoverMenu();
},
onConvertTo: (type) => convertLinkTo(editorState, selection, type),
onOpenLink: openLink,
onCopyLink: () => copyLink(context),
onEditLink: showLinkEditMenu,
@@ -236,15 +241,7 @@ class _LinkHoverTriggerState extends State<LinkHoverTrigger> {
Future<void> copyLink(BuildContext context) async {
final href = widget.attribute.href ?? '';
if (href.isEmpty) return;
await getIt<ClipboardService>()
.setData(ClipboardServiceData(plainText: href));
if (context.mounted) {
showToastNotification(
context,
message: LocaleKeys.shareAction_copyLinkSuccess.tr(),
);
}
await context.copyLink(href);
hoverMenuController.close();
}
@@ -271,6 +268,26 @@ class _LinkHoverTriggerState extends State<LinkHoverTrigger> {
editorState.apply(transaction);
}
Future<void> convertLinkTo(
EditorState editorState,
Selection selection,
LinkConvertMenuCommand type,
) async {
final url = widget.attribute.href ?? '';
if (type == LinkConvertMenuCommand.toBookmark) {
await convertUrlToLinkPreview(editorState, selection, url);
} else if (type == LinkConvertMenuCommand.toMention) {
await convertUrlToMention(editorState, selection);
} else if (type == LinkConvertMenuCommand.toEmbed) {
await convertUrlToLinkPreview(
editorState,
selection,
url,
previewType: LinkEmbedKeys.embed,
);
}
}
void onRemoveAndReplaceLink(
EditorState editorState,
Selection selection,
@@ -308,6 +325,7 @@ class LinkHoverMenu extends StatefulWidget {
required this.onOpenLink,
required this.onEditLink,
required this.onRemoveLink,
required this.onConvertTo,
});
final Attributes attribute;
@@ -318,6 +336,7 @@ class LinkHoverMenu extends StatefulWidget {
final VoidCallback onOpenLink;
final VoidCallback onEditLink;
final VoidCallback onRemoveLink;
final ValueChanged<LinkConvertMenuCommand> onConvertTo;
@override
State<LinkHoverMenu> createState() => _LinkHoverMenuState();
@@ -327,6 +346,8 @@ class _LinkHoverMenuState extends State<LinkHoverMenu> {
ViewPB? currentView;
late bool isPage = widget.attribute.isPage;
late String href = widget.attribute.href ?? '';
final popoverController = PopoverController();
bool isConvertButtonSelected = false;
@override
void initState() {
@@ -334,6 +355,12 @@ class _LinkHoverMenuState extends State<LinkHoverMenu> {
if (isPage) getPageView();
}
@override
void dispose() {
super.dispose();
popoverController.close();
}
@override
Widget build(BuildContext context) {
return Column(
@@ -365,6 +392,7 @@ class _LinkHoverMenuState extends State<LinkHoverMenu> {
FlowyIconButton(
icon: FlowySvg(FlowySvgs.toolbar_link_m),
tooltipText: LocaleKeys.editor_copyLink.tr(),
preferBelow: false,
width: 36,
height: 32,
onPressed: widget.onCopyLink,
@@ -372,13 +400,16 @@ class _LinkHoverMenuState extends State<LinkHoverMenu> {
FlowyIconButton(
icon: FlowySvg(FlowySvgs.toolbar_link_edit_m),
tooltipText: LocaleKeys.editor_editLink.tr(),
preferBelow: false,
width: 36,
height: 32,
onPressed: widget.onEditLink,
),
buildConvertButton(),
FlowyIconButton(
icon: FlowySvg(FlowySvgs.toolbar_link_unlink_m),
tooltipText: LocaleKeys.editor_removeLink.tr(),
preferBelow: false,
width: 36,
height: 32,
onPressed: widget.onRemoveLink,
@@ -445,6 +476,73 @@ class _LinkHoverMenuState extends State<LinkHoverMenu> {
),
);
}
Widget buildConvertButton() {
return AppFlowyPopover(
offset: Offset(44, 10.0),
direction: PopoverDirection.bottomWithRightAligned,
margin: EdgeInsets.zero,
controller: popoverController,
onOpen: () => keepEditorFocusNotifier.increase(),
onClose: () => keepEditorFocusNotifier.decrease(),
popupBuilder: (context) => buildConvertMenu(),
child: FlowyIconButton(
icon: FlowySvg(FlowySvgs.turninto_m),
isSelected: isConvertButtonSelected,
tooltipText: LocaleKeys.editor_convertTo.tr(),
preferBelow: false,
width: 36,
height: 32,
onPressed: () {
setState(() {
isConvertButtonSelected = true;
});
showConvertMenu();
},
),
);
}
Widget buildConvertMenu() {
return MouseRegion(
onEnter: widget.onEnter,
onExit: widget.onExit,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: SeparatedColumn(
mainAxisSize: MainAxisSize.min,
separatorBuilder: () => const VSpace(0.0),
children:
List.generate(LinkConvertMenuCommand.values.length, (index) {
final command = LinkConvertMenuCommand.values[index];
return SizedBox(
height: 36,
child: FlowyButton(
text: FlowyText(
command.title,
fontWeight: FontWeight.w400,
figmaLineHeight: 20,
),
onTap: () {
widget.onConvertTo(command);
closeConvertMenu();
},
),
);
}),
),
),
);
}
void showConvertMenu() {
keepEditorFocusNotifier.increase();
popoverController.show();
}
void closeConvertMenu() {
popoverController.close();
}
}
class HoverTriggerKey {
@@ -490,3 +588,48 @@ class LinkHoverTriggers {
callbacks.first.call();
}
}
enum LinkConvertMenuCommand {
toMention,
toBookmark,
toEmbed;
String get title {
switch (this) {
case toMention:
return LocaleKeys.document_plugins_linkPreview_linkPreviewMenu_toMetion
.tr();
case toBookmark:
return LocaleKeys
.document_plugins_linkPreview_linkPreviewMenu_toBookmark
.tr();
case toEmbed:
return LocaleKeys.document_plugins_linkPreview_linkPreviewMenu_toEmbed
.tr();
}
}
String get type {
switch (this) {
case toMention:
return MentionBlockKeys.type;
case toBookmark:
return LinkPreviewBlockKeys.type;
case toEmbed:
return LinkPreviewBlockKeys.type;
}
}
}
extension LinkExtension on BuildContext {
Future<void> copyLink(String link) async {
if (link.isEmpty) return;
await getIt<ClipboardService>()
.setData(ClipboardServiceData(plainText: link));
if (mounted) {
showToastNotification(
message: LocaleKeys.shareAction_copyLinkSuccess.tr(),
);
}
}
}
@@ -0,0 +1,184 @@
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/menu/menu_extension.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
// ignore: implementation_imports
import 'package:appflowy_editor/src/editor/util/link_util.dart';
import 'package:flutter/services.dart';
import 'link_create_menu.dart';
import 'link_styles.dart';
void showReplaceMenu({
required BuildContext context,
required EditorState editorState,
required Node node,
String? url,
required LTRB ltrb,
required ValueChanged<String> onReplace,
}) {
OverlayEntry? overlay;
void dismissOverlay() {
keepEditorFocusNotifier.decrease();
overlay?.remove();
overlay = null;
}
keepEditorFocusNotifier.increase();
overlay = FullScreenOverlayEntry(
top: ltrb.top,
bottom: ltrb.bottom,
left: ltrb.left,
right: ltrb.right,
dismissCallback: () => keepEditorFocusNotifier.decrease(),
builder: (context) {
return LinkReplaceMenu(
link: url ?? '',
onSubmitted: (link) async {
onReplace.call(link);
dismissOverlay();
},
onDismiss: dismissOverlay,
);
},
).build();
Overlay.of(context, rootOverlay: true).insert(overlay!);
}
class LinkReplaceMenu extends StatefulWidget {
const LinkReplaceMenu({
super.key,
required this.onSubmitted,
required this.link,
required this.onDismiss,
});
final ValueChanged<String> onSubmitted;
final VoidCallback onDismiss;
final String link;
@override
State<LinkReplaceMenu> createState() => _LinkReplaceMenuState();
}
class _LinkReplaceMenuState extends State<LinkReplaceMenu> {
bool showErrorText = false;
late FocusNode focusNode = FocusNode(onKeyEvent: onKeyEvent);
late TextEditingController textEditingController =
TextEditingController(text: widget.link);
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
focusNode.requestFocus();
});
}
@override
void dispose() {
focusNode.dispose();
textEditingController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
width: 330,
padding: EdgeInsets.all(8),
decoration: buildToolbarLinkDecoration(context),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: buildLinkField()),
HSpace(8),
buildReplaceButton(),
],
),
);
}
Widget buildLinkField() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
height: 32,
child: TextFormField(
autovalidateMode: AutovalidateMode.onUserInteraction,
autofocus: true,
focusNode: focusNode,
textAlign: TextAlign.left,
controller: textEditingController,
style: TextStyle(
fontSize: 14,
height: 20 / 14,
fontWeight: FontWeight.w400,
),
decoration: LinkStyle.buildLinkTextFieldInputDecoration(
LocaleKeys.document_plugins_linkPreview_linkPreviewMenu_pasteHint
.tr(),
context,
showErrorBorder: showErrorText,
),
),
),
if (showErrorText)
Padding(
padding: const EdgeInsets.only(top: 4),
child: FlowyText.regular(
LocaleKeys.document_plugins_file_networkUrlInvalid.tr(),
color: LinkStyle.textStatusError,
fontSize: 12,
figmaLineHeight: 16,
),
),
],
);
}
Widget buildReplaceButton() {
return FlowyTextButton(
LocaleKeys.button_replace.tr(),
padding: EdgeInsets.zero,
mainAxisAlignment: MainAxisAlignment.center,
constraints: BoxConstraints(maxWidth: 78, minHeight: 32),
fontSize: 14,
lineHeight: 20 / 14,
hoverColor: LinkStyle.fillThemeThick.withAlpha(200),
fontColor: Colors.white,
fillColor: LinkStyle.fillThemeThick,
fontWeight: FontWeight.w400,
onPressed: onSubmit,
);
}
void onSubmit() {
final link = textEditingController.text.trim();
if (link.isEmpty || !isUri(link)) {
setState(() {
showErrorText = true;
});
return;
}
widget.onSubmitted.call(link);
}
KeyEventResult onKeyEvent(FocusNode node, KeyEvent key) {
if (key is! KeyDownEvent) return KeyEventResult.ignored;
if (key.logicalKey == LogicalKeyboardKey.escape) {
widget.onDismiss.call();
return KeyEventResult.handled;
} else if (key.logicalKey == LogicalKeyboardKey.enter) {
onSubmit();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
}
@@ -154,7 +154,6 @@ class _ErrorBlockComponentWidgetState extends State<ErrorBlockComponentWidget>
void _copyBlockContent() {
showToastNotification(
context,
message: LocaleKeys.document_errorBlock_blockContentHasBeenCopied.tr(),
);
@@ -105,7 +105,6 @@ Future<void> downloadMediaFile(
} else {
if (userProfile == null) {
showToastNotification(
context,
message: LocaleKeys.grid_media_downloadFailedToken.tr(),
);
return;
@@ -129,14 +128,12 @@ Future<void> downloadMediaFile(
if (result != null && context.mounted) {
showToastNotification(
context,
type: ToastificationType.error,
message: LocaleKeys.grid_media_downloadSuccess.tr(),
);
}
} else if (context.mounted) {
showToastNotification(
context,
type: ToastificationType.error,
message: LocaleKeys.document_plugins_image_imageDownloadFailed.tr(),
);
@@ -160,13 +157,11 @@ Future<void> downloadMediaFile(
if (context.mounted) {
showToastNotification(
context,
message: LocaleKeys.grid_media_downloadSuccess.tr(),
);
}
} else if (context.mounted) {
showToastNotification(
context,
type: ToastificationType.error,
message: LocaleKeys.document_plugins_image_imageDownloadFailed.tr(),
);
@@ -8,6 +8,7 @@ import 'package:appflowy/shared/icon_emoji_picker/icon_picker.dart';
import 'package:appflowy/user/application/user_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pb.dart';
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flowy_svg/flowy_svg.dart';
import 'package:flutter/material.dart';
import 'package:string_validator/string_validator.dart';
@@ -113,24 +114,21 @@ class _RawEmojiIconWidgetState extends State<RawEmojiIconWidget> {
try {
switch (widget.emoji.type) {
case FlowyIconType.emoji:
return EmojiText(
emoji: widget.emoji.emoji,
return FlowyText.emoji(
widget.emoji.emoji,
fontSize: widget.emojiSize,
textAlign: TextAlign.justify,
lineHeight: widget.lineHeight,
);
case FlowyIconType.icon:
IconsData iconData =
IconsData.fromJson(jsonDecode(widget.emoji.emoji));
IconsData iconData = IconsData.fromJson(
jsonDecode(widget.emoji.emoji),
);
if (!widget.enableColor) {
iconData = iconData.noColor();
}
/// Under the same width conditions, icons on macOS seem to appear
/// larger than emojis, so 0.9 is used here to slightly reduce the
/// size of the icons
final iconSize =
Platform.isMacOS ? widget.emojiSize * 0.9 : widget.emojiSize;
final iconSize = widget.emojiSize;
return IconWidget(
iconsData: iconData,
size: iconSize,
@@ -378,7 +378,6 @@ class CustomImageBlockComponentState extends State<CustomImageBlockComponent>
onTap: () async {
context.pop();
showToastNotification(
context,
message: LocaleKeys.document_plugins_image_copiedToPasteBoard.tr(),
);
await getIt<ClipboardService>().setPlainText(url);
@@ -431,7 +430,6 @@ class CustomImageBlockComponentState extends State<CustomImageBlockComponent>
);
if (mounted) {
showToastNotification(
context,
message: result.isSuccess
? LocaleKeys.document_imageBlock_successToAddImageToGallery.tr()
: LocaleKeys.document_imageBlock_failedToAddImageToGallery.tr(),
@@ -117,14 +117,12 @@ class _ImageMenuState extends State<ImageMenu> {
if (mounted) {
showToastNotification(
context,
message: LocaleKeys.message_copy_success.tr(),
);
}
} catch (e) {
if (mounted) {
showToastNotification(
context,
message: LocaleKeys.message_copy_fail.tr(),
type: ToastificationType.error,
);
@@ -218,7 +218,6 @@ class _MultiImageMenuState extends State<MultiImageMenu> {
ClipboardData(text: images[widget.indexNotifier.value].url),
);
showToastNotification(
context,
message: LocaleKeys.document_plugins_image_copiedToPasteBoard.tr(),
);
}
@@ -0,0 +1,286 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/custom_link_parser.dart';
import 'package:appflowy/shared/appflowy_network_image.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart';
import 'package:appflowy_ui/appflowy_ui.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'link_embed_menu.dart';
class LinkEmbedKeys {
const LinkEmbedKeys._();
static const String previewType = 'preview_type';
static const String embed = 'embed';
static const String align = 'align';
}
Node linkEmbedNode({required String url}) => Node(
type: LinkPreviewBlockKeys.type,
attributes: {
LinkPreviewBlockKeys.url: url,
LinkEmbedKeys.previewType: LinkEmbedKeys.embed,
},
);
class LinkEmbedBlockComponent extends BlockComponentStatefulWidget {
const LinkEmbedBlockComponent({
super.key,
super.showActions,
super.actionBuilder,
super.configuration = const BlockComponentConfiguration(),
required super.node,
});
@override
State<LinkEmbedBlockComponent> createState() =>
LinkEmbedBlockComponentState();
}
class LinkEmbedBlockComponentState extends State<LinkEmbedBlockComponent>
with BlockComponentConfigurable {
@override
BlockComponentConfiguration get configuration => widget.configuration;
@override
Node get node => widget.node;
String get url => widget.node.attributes[LinkPreviewBlockKeys.url]!;
EmbedLoadingStatus status = EmbedLoadingStatus.loading;
final parser = LinkParser();
LinkInfo linkInfo = LinkInfo();
final showActionsNotifier = ValueNotifier<bool>(false);
bool isMenuShowing = false, isHovering = false;
@override
void initState() {
super.initState();
parser.addLinkInfoListener((v) {
if (mounted) {
setState(() {
if (v.isEmpty() && linkInfo.isEmpty()) {
status = EmbedLoadingStatus.error;
} else {
linkInfo = v;
status = EmbedLoadingStatus.idle;
}
});
}
});
parser.start(url);
}
@override
void dispose() {
parser.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
Widget result = MouseRegion(
onEnter: (_) {
isHovering = true;
showActionsNotifier.value = true;
},
onExit: (_) {
isHovering = false;
Future.delayed(const Duration(milliseconds: 200), () {
if (isMenuShowing || isHovering) return;
if (mounted) showActionsNotifier.value = false;
});
},
child: buildChild(context),
);
result = Padding(padding: padding, child: result);
if (widget.showActions && widget.actionBuilder != null) {
result = BlockComponentActionWrapper(
node: node,
actionBuilder: widget.actionBuilder!,
child: result,
);
}
return result;
}
Widget buildChild(BuildContext context) {
final theme = AppFlowyTheme.of(context),
fillSceme = theme.fillColorScheme,
borderScheme = theme.borderColorScheme;
Widget child;
final isIdle = status == EmbedLoadingStatus.idle;
if (isIdle) {
child = buildContent(context);
} else {
child = buildErrorLoadingWidget(context);
}
return Container(
height: 450,
decoration: BoxDecoration(
color: isIdle ? Theme.of(context).cardColor : fillSceme.tertiaryHover,
borderRadius: BorderRadius.all(Radius.circular(16)),
border: Border.all(color: borderScheme.greyTertiary),
),
child: Stack(
children: [
child,
buildMenu(context),
],
),
);
}
Widget buildMenu(BuildContext context) {
return Positioned(
top: 12,
right: 12,
child: ValueListenableBuilder<bool>(
valueListenable: showActionsNotifier,
builder: (context, showActions, child) {
if (!showActions) return SizedBox.shrink();
return LinkEmbedMenu(
editorState: context.read<EditorState>(),
node: node,
onReload: () {
setState(() {
status = EmbedLoadingStatus.loading;
});
Future.delayed(const Duration(milliseconds: 200), () {
if (mounted) parser.start(url);
});
},
onMenuShowed: () {
isMenuShowing = true;
},
onMenuHided: () {
isMenuShowing = false;
if (!isHovering && mounted) {
showActionsNotifier.value = false;
}
},
);
},
),
);
}
Widget buildContent(BuildContext context) {
final theme = AppFlowyTheme.of(context), textScheme = theme.textColorScheme;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: ClipRRect(
borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
child: FlowyNetworkImage(
url: linkInfo.imageUrl ?? '',
width: MediaQuery.of(context).size.width,
),
),
),
Container(
height: 64,
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 20),
child: Row(
children: [
SizedBox.square(
dimension: 40,
child: Center(
child: linkInfo.buildIconWidget(size: Size.square(32)),
),
),
HSpace(12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
FlowyText(
linkInfo.siteName ?? '',
color: textScheme.primary,
fontSize: 14,
figmaLineHeight: 20,
fontWeight: FontWeight.w600,
overflow: TextOverflow.ellipsis,
),
VSpace(4),
FlowyText.regular(
url,
color: textScheme.secondary,
fontSize: 12,
figmaLineHeight: 16,
overflow: TextOverflow.ellipsis,
),
],
),
),
],
),
),
],
);
}
Widget buildErrorLoadingWidget(BuildContext context) {
final theme = AppFlowyTheme.of(context), textSceme = theme.textColorScheme;
final isLoading = status == EmbedLoadingStatus.loading;
return isLoading
? Center(
child: SizedBox.square(
dimension: 64,
child: CircularProgressIndicator.adaptive(),
),
)
: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
SvgPicture.asset(
FlowySvgs.embed_error_xl.path,
),
VSpace(4),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: RichText(
maxLines: 1,
overflow: TextOverflow.ellipsis,
text: TextSpan(
children: [
TextSpan(
text: '$url ',
style: TextStyle(
color: textSceme.primary,
fontSize: 14,
height: 20 / 14,
fontWeight: FontWeight.w700,
),
),
TextSpan(
text: LocaleKeys
.document_plugins_linkPreview_linkPreviewMenu_refuseConnect
.tr(),
style: TextStyle(
color: textSceme.primary,
fontSize: 14,
height: 20 / 14,
fontWeight: FontWeight.w400,
),
),
],
),
),
),
],
),
);
}
}
enum EmbedLoadingStatus { loading, idle, error }
@@ -0,0 +1,332 @@
import 'package:appflowy/core/helpers/url_launcher.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/link/link_hover_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/link/link_replace_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/paste_as/paste_as_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/shared.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/menu/menu_extension.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart';
import 'package:appflowy_ui/appflowy_ui.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/widgets.dart';
import 'link_embed_block_component.dart';
class LinkEmbedMenu extends StatefulWidget {
const LinkEmbedMenu({
super.key,
required this.node,
required this.editorState,
required this.onMenuShowed,
required this.onMenuHided,
required this.onReload,
});
final Node node;
final EditorState editorState;
final VoidCallback onMenuShowed;
final VoidCallback onMenuHided;
final VoidCallback onReload;
@override
State<LinkEmbedMenu> createState() => _LinkEmbedMenuState();
}
class _LinkEmbedMenuState extends State<LinkEmbedMenu> {
final turnintoController = PopoverController();
final moreOptionController = PopoverController();
int turnintoMenuNum = 0, moreOptionNum = 0, alignMenuNum = 0;
final moreOptionButtonKey = GlobalKey();
bool get isTurnIntoShowing => turnintoMenuNum > 0;
bool get isMoreOptionShowing => moreOptionNum > 0;
bool get isAlignMenuShowing => alignMenuNum > 0;
Node get node => widget.node;
EditorState get editorState => widget.editorState;
String get url => node.attributes[LinkPreviewBlockKeys.url] ?? '';
@override
void dispose() {
super.dispose();
turnintoController.close();
moreOptionController.close();
widget.onMenuHided.call();
}
@override
Widget build(BuildContext context) {
return buildChild();
}
Widget buildChild() {
final theme = AppFlowyTheme.of(context),
iconScheme = theme.iconColorTheme,
fillScheme = theme.fillColorScheme;
return Container(
padding: EdgeInsets.all(4),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
color: fillScheme.primaryAlpha80,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
// FlowyIconButton(
// icon: FlowySvg(
// FlowySvgs.embed_fullscreen_m,
// color: iconScheme.tertiary,
// ),
// tooltipText: LocaleKeys.document_imageBlock_openFullScreen.tr(),
// preferBelow: false,
// onPressed: () {},
// ),
FlowyIconButton(
icon: FlowySvg(
FlowySvgs.toolbar_link_m,
color: iconScheme.tertiary,
),
tooltipText: LocaleKeys.editor_copyLink.tr(),
preferBelow: false,
onPressed: () => copyLink(context),
),
buildTurnIntoBotton(),
buildMoreOptionBotton(),
],
),
);
}
Widget buildTurnIntoBotton() {
final theme = AppFlowyTheme.of(context), iconScheme = theme.iconColorTheme;
return AppFlowyPopover(
offset: Offset(0, 6),
direction: PopoverDirection.bottomWithRightAligned,
margin: EdgeInsets.zero,
controller: turnintoController,
onOpen: () {
keepEditorFocusNotifier.increase();
turnintoMenuNum++;
},
onClose: () {
keepEditorFocusNotifier.decrease();
turnintoMenuNum--;
checkToHideMenu();
},
popupBuilder: (context) => buildTurnIntoMenu(),
child: FlowyIconButton(
icon: FlowySvg(
FlowySvgs.turninto_m,
color: iconScheme.tertiary,
),
tooltipText: LocaleKeys.document_toolbar_turnInto.tr(),
preferBelow: false,
onPressed: showTurnIntoMenu,
),
);
}
Widget buildTurnIntoMenu() {
final types =
PasteMenuType.values.where((e) => e != PasteMenuType.embed).toList();
return Padding(
padding: const EdgeInsets.all(8.0),
child: SeparatedColumn(
mainAxisSize: MainAxisSize.min,
separatorBuilder: () => const VSpace(0.0),
children: List.generate(types.length, (index) {
final command = types[index];
return SizedBox(
height: 36,
child: FlowyButton(
text: FlowyText(
command.title,
fontWeight: FontWeight.w400,
figmaLineHeight: 20,
),
onTap: () {
if (command == PasteMenuType.bookmark) {
final transaction = editorState.transaction;
transaction.updateNode(node, {
LinkPreviewBlockKeys.url: url,
LinkEmbedKeys.previewType: '',
});
editorState.apply(transaction);
} else if (command == PasteMenuType.mention) {
convertUrlPreviewNodeToMention(editorState, node);
} else if (command == PasteMenuType.url) {
convertUrlPreviewNodeToLink(editorState, node);
}
},
),
);
}),
),
);
}
Widget buildMoreOptionBotton() {
final theme = AppFlowyTheme.of(context), iconScheme = theme.iconColorTheme;
return AppFlowyPopover(
offset: Offset(0, 6),
direction: PopoverDirection.bottomWithRightAligned,
margin: EdgeInsets.zero,
controller: moreOptionController,
onOpen: () {
keepEditorFocusNotifier.increase();
moreOptionNum++;
},
onClose: () {
keepEditorFocusNotifier.decrease();
moreOptionNum--;
checkToHideMenu();
},
popupBuilder: (context) => buildMoreOptionMenu(),
child: FlowyIconButton(
key: moreOptionButtonKey,
icon: FlowySvg(
FlowySvgs.toolbar_more_m,
color: iconScheme.tertiary,
),
tooltipText: LocaleKeys.document_toolbar_moreOptions.tr(),
preferBelow: false,
onPressed: showMoreOptionMenu,
),
);
}
Widget buildMoreOptionMenu() {
final types = LinkEmbedMenuCommand.values;
return Padding(
padding: const EdgeInsets.all(8.0),
child: SeparatedColumn(
mainAxisSize: MainAxisSize.min,
separatorBuilder: () => const VSpace(0.0),
children: List.generate(types.length, (index) {
final command = types[index];
return SizedBox(
height: 36,
child: FlowyButton(
text: FlowyText(
command.title,
fontWeight: FontWeight.w400,
figmaLineHeight: 20,
),
onTap: () => onEmbedMenuCommand(command),
),
);
}),
),
);
}
void showTurnIntoMenu() {
keepEditorFocusNotifier.increase();
turnintoController.show();
checkToShowMenu();
turnintoMenuNum++;
if (isMoreOptionShowing) closeMoreOptionMenu();
}
void closeTurnIntoMenu() {
turnintoController.close();
checkToHideMenu();
}
void showMoreOptionMenu() {
keepEditorFocusNotifier.increase();
moreOptionController.show();
checkToShowMenu();
moreOptionNum++;
if (isTurnIntoShowing) closeTurnIntoMenu();
}
void closeMoreOptionMenu() {
moreOptionController.close();
checkToHideMenu();
}
void checkToHideMenu() {
Future.delayed(Duration(milliseconds: 200), () {
if (!mounted) return;
if (!isAlignMenuShowing && !isMoreOptionShowing && !isTurnIntoShowing) {
widget.onMenuHided.call();
}
});
}
void checkToShowMenu() {
if (!isAlignMenuShowing && !isMoreOptionShowing && !isTurnIntoShowing) {
widget.onMenuShowed.call();
}
}
Future<void> copyLink(BuildContext context) async {
await context.copyLink(url);
widget.onMenuHided.call();
}
void onEmbedMenuCommand(LinkEmbedMenuCommand command) {
switch (command) {
case LinkEmbedMenuCommand.openLink:
afLaunchUrlString(url, addingHttpSchemeWhenFailed: true);
break;
case LinkEmbedMenuCommand.replace:
final box = moreOptionButtonKey.currentContext?.findRenderObject()
as RenderBox?;
if (box == null) return;
final p = box.localToGlobal(Offset.zero);
showReplaceMenu(
context: context,
editorState: editorState,
node: node,
url: url,
ltrb: LTRB(left: p.dx - 330, top: p.dy),
onReplace: (url) async {
await convertLinkBlockToOtherLinkBlock(
editorState,
node,
node.type,
url: url,
);
},
);
break;
case LinkEmbedMenuCommand.reload:
widget.onReload.call();
break;
case LinkEmbedMenuCommand.removeLink:
removeUrlPreviewLink(editorState, node);
break;
}
closeMoreOptionMenu();
}
}
enum LinkEmbedMenuCommand {
openLink,
replace,
reload,
removeLink;
String get title {
switch (this) {
case openLink:
return LocaleKeys.editor_openLink.tr();
case replace:
return LocaleKeys.document_plugins_linkPreview_linkPreviewMenu_replace
.tr();
case reload:
return LocaleKeys.document_plugins_linkPreview_linkPreviewMenu_reload
.tr();
case removeLink:
return LocaleKeys
.document_plugins_linkPreview_linkPreviewMenu_removeLink
.tr();
}
}
}
@@ -0,0 +1,135 @@
import 'dart:convert';
import 'package:appflowy/core/config/kv.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/shared/appflowy_network_image.dart';
import 'package:appflowy/shared/appflowy_network_svg.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy_backend/log.dart';
import 'package:favicon/favicon.dart';
import 'package:flutter/material.dart';
// ignore: depend_on_referenced_packages
import 'package:flutter_link_previewer/flutter_link_previewer.dart' hide Size;
class LinkParser {
static final LinkInfoCache _cache = LinkInfoCache();
final Set<ValueChanged<LinkInfo>> _listeners = <ValueChanged<LinkInfo>>{};
Future<void> start(String url) async {
final data = await _cache.get(url);
if (data != null) {
refreshLinkInfo(data);
}
await _getLinkInfo(url);
}
Future<LinkInfo?> _getLinkInfo(String url) async {
try {
final previewData = await getPreviewData(url);
final favicon = await FaviconFinder.getBest(url);
final linkInfo = LinkInfo(
siteName: previewData.title,
description: previewData.description,
imageUrl: previewData.image?.url,
faviconUrl: favicon?.url,
);
if (!linkInfo.isEmpty()) await _cache.set(url, linkInfo);
refreshLinkInfo(linkInfo);
return linkInfo;
} catch (e, s) {
Log.error('get link info error: ', e, s);
refreshLinkInfo(LinkInfo());
return null;
}
}
void refreshLinkInfo(LinkInfo info) {
for (final listener in _listeners) {
listener(info);
}
}
void addLinkInfoListener(ValueChanged<LinkInfo> listener) {
_listeners.add(listener);
}
void dispose() {
_listeners.clear();
}
}
class LinkInfo {
factory LinkInfo.fromJson(Map<String, dynamic> json) => LinkInfo(
siteName: json['siteName'],
description: json['description'],
imageUrl: json['imageUrl'],
faviconUrl: json['faviconUrl'],
);
LinkInfo({
this.siteName,
this.description,
this.imageUrl,
this.faviconUrl,
});
final String? siteName;
final String? description;
final String? imageUrl;
final String? faviconUrl;
Map<String, dynamic> toJson() => {
'siteName': siteName,
'description': description,
'imageUrl': imageUrl,
'faviconUrl': faviconUrl,
};
bool isEmpty() {
return siteName == null ||
description == null ||
imageUrl == null ||
faviconUrl == null;
}
Widget buildIconWidget({Size size = const Size.square(20.0)}) {
final iconUrl = faviconUrl;
if (iconUrl == null) {
return FlowySvg(FlowySvgs.toolbar_link_earth_m, size: size);
}
if (iconUrl.endsWith('.svg')) {
return FlowyNetworkSvg(
iconUrl,
height: size.height,
width: size.width,
errorWidget: const FlowySvg(FlowySvgs.toolbar_link_earth_m),
);
}
return FlowyNetworkImage(
url: iconUrl,
fit: BoxFit.contain,
height: size.height,
width: size.width,
errorWidgetBuilder: (context, error, stackTrace) =>
const FlowySvg(FlowySvgs.toolbar_link_earth_m),
);
}
}
class LinkInfoCache {
final _linkInfoPrefix = 'link_info';
Future<LinkInfo?> get(String url) async {
final option = await getIt<KeyValueStorage>().getWithFormat<LinkInfo?>(
_linkInfoPrefix + url,
(value) => LinkInfo.fromJson(jsonDecode(value)),
);
return option;
}
Future<void> set(String url, LinkInfo data) async {
await getIt<KeyValueStorage>().set(
_linkInfoPrefix + url,
jsonEncode(data.toJson()),
);
}
}
@@ -12,6 +12,7 @@ import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:universal_platform/universal_platform.dart';
import 'package:appflowy_ui/appflowy_ui.dart';
class CustomLinkPreviewWidget extends StatelessWidget {
const CustomLinkPreviewWidget({
@@ -21,6 +22,8 @@ class CustomLinkPreviewWidget extends StatelessWidget {
this.title,
this.description,
this.imageUrl,
this.isHovering = false,
this.status = LinkPreviewStatus.loading,
});
final Node node;
@@ -28,9 +31,14 @@ class CustomLinkPreviewWidget extends StatelessWidget {
final String? description;
final String? imageUrl;
final String url;
final bool isHovering;
final LinkPreviewStatus status;
@override
Widget build(BuildContext context) {
final theme = AppFlowyTheme.of(context),
borderScheme = theme.borderColorScheme,
textScheme = theme.textColorScheme;
final documentFontSize = context
.read<EditorState>()
.editorStyle
@@ -39,69 +47,60 @@ class CustomLinkPreviewWidget extends StatelessWidget {
.fontSize ??
16.0;
final (fontSize, width) = UniversalPlatform.isDesktopOrWeb
? (documentFontSize, 180.0)
? (documentFontSize, 160.0)
: (documentFontSize - 2, 120.0);
final Widget child = Container(
clipBehavior: Clip.hardEdge,
decoration: BoxDecoration(
border: Border.all(
color: Theme.of(context).colorScheme.onSurface,
),
borderRadius: BorderRadius.circular(
6.0,
color: isHovering
? borderScheme.greyTertiaryHover
: borderScheme.greyTertiary,
),
borderRadius: BorderRadius.circular(16.0),
),
child: IntrinsicHeight(
child: SizedBox(
height: 96,
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (imageUrl != null)
ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(6.0),
bottomLeft: Radius.circular(6.0),
),
child: FlowyNetworkImage(
url: imageUrl!,
width: width,
),
),
buildImage(context),
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
padding: const EdgeInsets.fromLTRB(20, 12, 60, 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
buildLoadingOrErrorWidget(),
if (title != null)
Padding(
padding: const EdgeInsets.only(
bottom: 4.0,
right: 10.0,
),
padding: const EdgeInsets.only(bottom: 4.0),
child: FlowyText.medium(
title!,
maxLines: 2,
overflow: TextOverflow.ellipsis,
fontSize: fontSize,
color: textScheme.primary,
figmaLineHeight: 20,
),
),
if (description != null)
Padding(
padding: const EdgeInsets.only(bottom: 4.0),
padding: const EdgeInsets.only(bottom: 16.0),
child: FlowyText(
description!,
maxLines: 2,
overflow: TextOverflow.ellipsis,
fontSize: fontSize - 4,
figmaLineHeight: 16,
color: textScheme.primary,
),
),
FlowyText(
url.toString(),
overflow: TextOverflow.ellipsis,
maxLines: 2,
color: Theme.of(context).hintColor,
color: textScheme.secondary,
fontSize: fontSize - 4,
figmaLineHeight: 16,
),
],
),
@@ -150,4 +149,67 @@ class CustomLinkPreviewWidget extends StatelessWidget {
),
];
}
Widget buildImage(BuildContext context) {
final theme = AppFlowyTheme.of(context),
fillScheme = theme.fillColorScheme,
iconScheme = theme.iconColorTheme;
final width = UniversalPlatform.isDesktopOrWeb ? 160.0 : 120.0;
Widget child;
if (imageUrl != null) {
child = FlowyNetworkImage(
url: imageUrl!,
width: width,
);
} else {
child = Center(
child: FlowySvg(
FlowySvgs.toolbar_link_earth_m,
color: iconScheme.secondary,
size: Size.square(30),
),
);
}
return ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(16.0),
bottomLeft: Radius.circular(16.0),
),
child: Container(
width: width,
color: fillScheme.quaternary,
child: child,
),
);
}
Widget buildLoadingOrErrorWidget() {
if (status == LinkPreviewStatus.loading) {
return Expanded(
child: const Center(
child: SizedBox(
height: 16,
width: 16,
child: CircularProgressIndicator.adaptive(),
),
),
);
} else if (status == LinkPreviewStatus.error) {
return Expanded(
child: const Center(
child: SizedBox(
height: 16,
width: 16,
child: Icon(
Icons.error_outline,
color: Colors.red,
),
),
),
);
}
return SizedBox.shrink();
}
}
enum LinkPreviewStatus { loading, error, idle }
@@ -0,0 +1,204 @@
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_embed/link_embed_block_component.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart';
import 'package:flutter/material.dart';
import 'custom_link_preview.dart';
import 'link_preview_menu.dart';
class CustomLinkPreviewBlockComponentBuilder extends BlockComponentBuilder {
CustomLinkPreviewBlockComponentBuilder({
super.configuration,
this.cache,
});
final LinkPreviewDataCacheInterface? cache;
@override
BlockComponentWidget build(BlockComponentContext blockComponentContext) {
final node = blockComponentContext.node;
final isEmbed =
node.attributes[LinkEmbedKeys.previewType] == LinkEmbedKeys.embed;
if (isEmbed) {
return LinkEmbedBlockComponent(
key: node.key,
node: node,
configuration: configuration,
showActions: showActions(node),
actionBuilder: (_, state) =>
actionBuilder(blockComponentContext, state),
);
}
return CustomLinkPreviewBlockComponent(
key: node.key,
node: node,
configuration: configuration,
showActions: showActions(node),
actionBuilder: (_, state) => actionBuilder(blockComponentContext, state),
cache: cache,
);
}
@override
BlockComponentValidate get validate =>
(node) => node.attributes[LinkPreviewBlockKeys.url]!.isNotEmpty;
}
class CustomLinkPreviewBlockComponent extends BlockComponentStatefulWidget {
const CustomLinkPreviewBlockComponent({
super.key,
required super.node,
super.showActions,
super.actionBuilder,
super.configuration = const BlockComponentConfiguration(),
this.cache,
});
final LinkPreviewDataCacheInterface? cache;
@override
State<CustomLinkPreviewBlockComponent> createState() =>
CustomLinkPreviewBlockComponentState();
}
class CustomLinkPreviewBlockComponentState
extends State<CustomLinkPreviewBlockComponent>
with BlockComponentConfigurable {
@override
BlockComponentConfiguration get configuration => widget.configuration;
@override
Node get node => widget.node;
String get url => widget.node.attributes[LinkPreviewBlockKeys.url]!;
late final LinkPreviewParser parser;
late Future<void> future;
final showActionsNotifier = ValueNotifier<bool>(false);
bool isMenuShowing = false, isHovering = false;
@override
void initState() {
super.initState();
parser = LinkPreviewParser(url: url, cache: widget.cache);
future = parser.start();
}
@override
void didUpdateWidget(CustomLinkPreviewBlockComponent oldWidget) {
super.didUpdateWidget(oldWidget);
final url = widget.node.attributes[LinkPreviewBlockKeys.url]!;
final oldUrl = oldWidget.node.attributes[LinkPreviewBlockKeys.url]!;
if (url != oldUrl) {
parser = LinkPreviewParser(url: url, cache: widget.cache);
setState(() {
future = parser.start();
});
}
}
@override
Widget build(BuildContext context) {
return MouseRegion(
onEnter: (_) {
isHovering = true;
showActionsNotifier.value = true;
},
onExit: (_) {
isHovering = false;
Future.delayed(const Duration(milliseconds: 200), () {
if (isMenuShowing || isHovering) return;
if (mounted) showActionsNotifier.value = false;
});
},
hitTestBehavior: HitTestBehavior.opaque,
opaque: false,
child: ValueListenableBuilder<bool>(
valueListenable: showActionsNotifier,
builder: (context, showActions, child) {
return FutureBuilder(
future: future,
builder: (context, snapshot) {
Widget child;
if (snapshot.connectionState != ConnectionState.done) {
child = CustomLinkPreviewWidget(
node: node,
url: url,
isHovering: showActions,
);
} else {
final title = parser.getContent(LinkPreviewRegex.title);
final description =
parser.getContent(LinkPreviewRegex.description);
final image = parser.getContent(LinkPreviewRegex.image);
if (title == null && description == null && image == null) {
child = CustomLinkPreviewWidget(
node: node,
url: url,
isHovering: showActions,
status: LinkPreviewStatus.error,
);
} else {
child = CustomLinkPreviewWidget(
node: node,
url: url,
title: title,
description: description,
imageUrl: image,
isHovering: showActions,
status: LinkPreviewStatus.idle,
);
}
}
child = Padding(padding: padding, child: child);
if (widget.showActions && widget.actionBuilder != null) {
child = BlockComponentActionWrapper(
node: node,
actionBuilder: widget.actionBuilder!,
child: child,
);
}
child = Stack(
children: [
child,
if (showActions)
Positioned(
top: 16,
right: 16,
child: CustomLinkPreviewMenu(
onMenuShowed: () {
isMenuShowing = true;
},
onMenuHided: () {
isMenuShowing = false;
if (!isHovering && mounted) {
showActionsNotifier.value = false;
}
},
onReload: () {
if (mounted) {
setState(() {
future = parser.start();
});
}
},
node: node,
),
),
],
);
return child;
},
);
},
),
);
}
}
@@ -1,110 +1,207 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/block_menu/block_menu_button.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/link/link_hover_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/link/link_replace_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_embed/link_embed_block_component.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/shared.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/menu/menu_extension.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../image/custom_image_block_component/custom_image_block_component.dart';
class LinkPreviewMenu extends StatefulWidget {
const LinkPreviewMenu({
class CustomLinkPreviewMenu extends StatefulWidget {
const CustomLinkPreviewMenu({
super.key,
required this.onMenuShowed,
required this.onMenuHided,
required this.onReload,
required this.node,
required this.state,
});
final VoidCallback onMenuShowed;
final VoidCallback onMenuHided;
final VoidCallback onReload;
final Node node;
final LinkPreviewBlockComponentState state;
@override
State<LinkPreviewMenu> createState() => _LinkPreviewMenuState();
State<CustomLinkPreviewMenu> createState() => _CustomLinkPreviewMenuState();
}
class _LinkPreviewMenuState extends State<LinkPreviewMenu> {
class _CustomLinkPreviewMenuState extends State<CustomLinkPreviewMenu> {
final popoverController = PopoverController();
final buttonKey = GlobalKey();
bool closed = false;
bool selected = false;
@override
void dispose() {
super.dispose();
popoverController.close();
widget.onMenuHided.call();
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Container(
height: 32,
decoration: BoxDecoration(
color: theme.cardColor,
boxShadow: [
BoxShadow(
blurRadius: 5,
spreadRadius: 1,
color: Colors.black.withValues(alpha: 0.1),
),
],
borderRadius: BorderRadius.circular(4.0),
),
child: Row(
children: [
const HSpace(4),
MenuBlockButton(
tooltip: LocaleKeys.document_plugins_urlPreview_convertToLink.tr(),
iconData: FlowySvgs.m_toolbar_link_m,
onTap: () async => convertUrlPreviewNodeToLink(
context.read<EditorState>(),
widget.node,
),
),
const HSpace(4),
MenuBlockButton(
tooltip: LocaleKeys.editor_copyLink.tr(),
iconData: FlowySvgs.copy_s,
onTap: copyImageLink,
),
const _Divider(),
MenuBlockButton(
tooltip: LocaleKeys.button_delete.tr(),
iconData: FlowySvgs.trash_s,
onTap: deleteLinkPreviewNode,
),
const HSpace(4),
],
return AppFlowyPopover(
offset: Offset(0, 0.0),
direction: PopoverDirection.bottomWithRightAligned,
margin: EdgeInsets.zero,
controller: popoverController,
onOpen: () => keepEditorFocusNotifier.increase(),
onClose: () {
keepEditorFocusNotifier.decrease();
if (!closed) {
closed = true;
return;
} else {
closed = false;
widget.onMenuHided.call();
}
setState(() {
selected = false;
});
},
popupBuilder: (context) => buildMenu(),
child: FlowyIconButton(
key: buttonKey,
isSelected: selected,
icon: FlowySvg(FlowySvgs.toolbar_more_m),
onPressed: showPopover,
),
);
}
void copyImageLink() {
final url = widget.node.attributes[CustomImageBlockKeys.url];
if (url != null) {
Clipboard.setData(ClipboardData(text: url));
showToastNotification(
context,
message: LocaleKeys.document_plugins_urlPreview_copiedToPasteBoard.tr(),
);
Widget buildMenu() {
return MouseRegion(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: SeparatedColumn(
mainAxisSize: MainAxisSize.min,
separatorBuilder: () => const VSpace(0.0),
children:
List.generate(LinkPreviewMenuCommand.values.length, (index) {
final command = LinkPreviewMenuCommand.values[index];
return SizedBox(
height: 36,
child: FlowyButton(
text: FlowyText(
command.title,
fontWeight: FontWeight.w400,
figmaLineHeight: 20,
),
onTap: () => onTap(command),
),
);
}),
),
),
);
}
Future<void> onTap(LinkPreviewMenuCommand command) async {
final editorState = context.read<EditorState>();
final node = widget.node;
final url = node.attributes[LinkPreviewBlockKeys.url];
switch (command) {
case LinkPreviewMenuCommand.convertToMention:
await convertUrlPreviewNodeToMention(editorState, node);
break;
case LinkPreviewMenuCommand.convertToUrl:
await convertUrlPreviewNodeToLink(editorState, node);
break;
case LinkPreviewMenuCommand.convertToEmbed:
final transaction = editorState.transaction;
transaction.updateNode(node, {
LinkPreviewBlockKeys.url: url,
LinkEmbedKeys.previewType: LinkEmbedKeys.embed,
});
await editorState.apply(transaction);
break;
case LinkPreviewMenuCommand.copyLink:
if (url != null) {
await context.copyLink(url);
}
break;
case LinkPreviewMenuCommand.replace:
final box = buttonKey.currentContext?.findRenderObject() as RenderBox?;
if (box == null) return;
final p = box.localToGlobal(Offset.zero);
showReplaceMenu(
context: context,
editorState: editorState,
node: node,
url: url,
ltrb: LTRB(left: p.dx - 330, top: p.dy),
onReplace: (url) async {
await convertLinkBlockToOtherLinkBlock(
editorState,
node,
node.type,
url: url,
);
},
);
break;
case LinkPreviewMenuCommand.reload:
widget.onReload.call();
break;
case LinkPreviewMenuCommand.removeLink:
await removeUrlPreviewLink(editorState, node);
break;
}
closePopover();
}
void showPopover() {
widget.onMenuShowed.call();
keepEditorFocusNotifier.increase();
popoverController.show();
setState(() {
selected = true;
});
}
void closePopover() {
popoverController.close();
widget.onMenuHided.call();
}
}
enum LinkPreviewMenuCommand {
convertToMention,
convertToUrl,
convertToEmbed,
copyLink,
replace,
reload,
removeLink;
String get title {
switch (this) {
case convertToMention:
return LocaleKeys.document_plugins_linkPreview_linkPreviewMenu_toMetion
.tr();
case LinkPreviewMenuCommand.convertToUrl:
return LocaleKeys.document_plugins_linkPreview_linkPreviewMenu_toUrl
.tr();
case LinkPreviewMenuCommand.convertToEmbed:
return LocaleKeys.document_plugins_linkPreview_linkPreviewMenu_toEmbed
.tr();
case LinkPreviewMenuCommand.copyLink:
return LocaleKeys.document_plugins_linkPreview_linkPreviewMenu_copyLink
.tr();
case LinkPreviewMenuCommand.replace:
return LocaleKeys.document_plugins_linkPreview_linkPreviewMenu_replace
.tr();
case LinkPreviewMenuCommand.reload:
return LocaleKeys.document_plugins_linkPreview_linkPreviewMenu_reload
.tr();
case LinkPreviewMenuCommand.removeLink:
return LocaleKeys
.document_plugins_linkPreview_linkPreviewMenu_removeLink
.tr();
}
}
Future<void> deleteLinkPreviewNode() async {
final node = widget.node;
final editorState = context.read<EditorState>();
final transaction = editorState.transaction;
transaction.deleteNode(node);
transaction.afterSelection = null;
await editorState.apply(transaction);
}
}
class _Divider extends StatelessWidget {
const _Divider();
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8),
child: Container(
width: 1,
color: Colors.grey,
),
);
}
}
@@ -0,0 +1,253 @@
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_embed/link_embed_block_component.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/shared.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/menu/menu_extension.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/theme_extension_v2.dart';
import 'package:flowy_infra_ui/style_widget/button.dart';
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
const _menuHeighgt = 188.0, _menuWidth = 288.0;
class PasteAsMenuService {
PasteAsMenuService({
required this.context,
required this.editorState,
});
final BuildContext context;
final EditorState editorState;
OverlayEntry? _menuEntry;
void show(String href) {
WidgetsBinding.instance.addPostFrameCallback((_) => _show(href));
}
void dismiss() {
if (_menuEntry != null) {
editorState.service.keyboardService?.enable();
editorState.service.scrollService?.enable();
keepEditorFocusNotifier.decrease();
}
_menuEntry?.remove();
_menuEntry = null;
}
void _show(String href) {
final Size editorSize = editorState.renderBox?.size ?? Size.zero;
if (editorSize == Size.zero) return;
final menuPosition = editorState.calculateMenuOffset(
menuWidth: _menuWidth,
menuHeight: _menuHeighgt,
);
if (menuPosition == null) return;
final ltrb = menuPosition.ltrb;
_menuEntry = OverlayEntry(
builder: (context) => SizedBox(
height: editorSize.height,
width: editorSize.width,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: dismiss,
child: Stack(
children: [
ltrb.buildPositioned(
child: PasteAsMenu(
onSelect: (t) {
final selection = editorState.selection;
if (selection == null) return;
final end = selection.end;
final urlSelection = Selection(
start: end.copyWith(offset: end.offset - href.length),
end: end,
);
if (t == PasteMenuType.bookmark) {
convertUrlToLinkPreview(editorState, urlSelection, href);
} else if (t == PasteMenuType.mention) {
convertUrlToMention(editorState, urlSelection);
} else if (t == PasteMenuType.embed) {
convertUrlToLinkPreview(
editorState,
urlSelection,
href,
previewType: LinkEmbedKeys.embed,
);
}
dismiss();
},
onDismiss: dismiss,
),
),
],
),
),
),
);
Overlay.of(context).insert(_menuEntry!);
editorState.service.keyboardService?.disable(showCursor: true);
editorState.service.scrollService?.disable();
}
}
class PasteAsMenu extends StatefulWidget {
const PasteAsMenu({
super.key,
required this.onSelect,
required this.onDismiss,
});
final ValueChanged<PasteMenuType?> onSelect;
final VoidCallback onDismiss;
@override
State<PasteAsMenu> createState() => _PasteAsMenuState();
}
class _PasteAsMenuState extends State<PasteAsMenu> {
final focusNode = FocusNode(debugLabel: 'paste_as_menu');
final ValueNotifier<int> selectedIndexNotifier = ValueNotifier(0);
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback(
(_) => focusNode.requestFocus(),
);
}
@override
void dispose() {
focusNode.dispose();
selectedIndexNotifier.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final themeV2 = AFThemeExtensionV2.of(context);
return Focus(
focusNode: focusNode,
onKeyEvent: onKeyEvent,
child: Container(
width: _menuWidth,
height: _menuHeighgt,
padding: EdgeInsets.all(6),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Theme.of(context).cardColor,
boxShadow: [
BoxShadow(
offset: Offset(0, 4),
blurRadius: 16,
color: themeV2.shadow_medium,
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
height: 32,
padding: EdgeInsets.all(8),
child: FlowyText.semibold(
color: themeV2.text_tertiary,
LocaleKeys.document_plugins_linkPreview_typeSelection_pasteAs
.tr(),
),
),
...List.generate(
PasteMenuType.values.length,
(i) => buildItem(PasteMenuType.values[i], i),
),
],
),
),
);
}
Widget buildItem(PasteMenuType type, int i) {
return ValueListenableBuilder(
valueListenable: selectedIndexNotifier,
builder: (context, value, child) {
final isSelected = i == value;
return SizedBox(
height: 36,
child: FlowyButton(
isSelected: isSelected,
text: FlowyText(
type.title,
),
onTap: () => onSelect(type),
),
);
},
);
}
void changeIndex(int index) => selectedIndexNotifier.value = index;
KeyEventResult onKeyEvent(focus, KeyEvent event) {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
int index = selectedIndexNotifier.value,
length = PasteMenuType.values.length;
if (event.logicalKey == LogicalKeyboardKey.enter) {
onSelect(PasteMenuType.values[index]);
} else if (event.logicalKey == LogicalKeyboardKey.escape) {
dismiss();
} else if ([LogicalKeyboardKey.arrowUp, LogicalKeyboardKey.arrowLeft]
.contains(event.logicalKey)) {
if (index == 0) {
index = length - 1;
} else {
index--;
}
changeIndex(index);
} else if ([LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.arrowRight]
.contains(event.logicalKey)) {
if (index == length - 1) {
index = 0;
} else {
index++;
}
changeIndex(index);
}
return KeyEventResult.handled;
}
void onSelect(PasteMenuType type) => widget.onSelect.call(type);
void dismiss() => widget.onDismiss.call();
}
enum PasteMenuType {
mention,
url,
bookmark,
embed,
}
extension PasteMenuTypeExtension on PasteMenuType {
String get title {
switch (this) {
case PasteMenuType.mention:
return LocaleKeys.document_plugins_linkPreview_typeSelection_mention
.tr();
case PasteMenuType.url:
return LocaleKeys.document_plugins_linkPreview_typeSelection_URL.tr();
case PasteMenuType.bookmark:
return LocaleKeys.document_plugins_linkPreview_typeSelection_bookmark
.tr();
case PasteMenuType.embed:
return LocaleKeys.document_plugins_linkPreview_typeSelection_embed.tr();
}
}
}
@@ -1,3 +1,5 @@
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_embed/link_embed_block_component.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_editor_plugins/appflowy_editor_plugins.dart';
@@ -9,7 +11,7 @@ Future<void> convertUrlPreviewNodeToLink(
return;
}
final url = node.attributes[ImageBlockKeys.url];
final url = node.attributes[LinkPreviewBlockKeys.url];
final delta = Delta()
..insert(
url,
@@ -29,3 +31,172 @@ Future<void> convertUrlPreviewNodeToLink(
);
return editorState.apply(transaction);
}
Future<void> convertUrlPreviewNodeToMention(
EditorState editorState,
Node node,
) async {
if (node.type != LinkPreviewBlockKeys.type) {
return;
}
final url = node.attributes[LinkPreviewBlockKeys.url];
final delta = Delta()
..insert(
MentionBlockKeys.mentionChar,
attributes: {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.externalLink.name,
MentionBlockKeys.url: url,
},
},
);
final transaction = editorState.transaction;
transaction
..insertNode(node.path, paragraphNode(delta: delta))
..deleteNode(node);
transaction.afterSelection = Selection.collapsed(
Position(
path: node.path,
offset: url.length,
),
);
return editorState.apply(transaction);
}
Future<void> removeUrlPreviewLink(
EditorState editorState,
Node node,
) async {
if (node.type != LinkPreviewBlockKeys.type) {
return;
}
final url = node.attributes[LinkPreviewBlockKeys.url];
final delta = Delta()..insert(url);
final transaction = editorState.transaction;
transaction
..insertNode(node.path, paragraphNode(delta: delta))
..deleteNode(node);
transaction.afterSelection = Selection.collapsed(
Position(
path: node.path,
offset: url.length,
),
);
return editorState.apply(transaction);
}
Future<void> convertUrlToLinkPreview(
EditorState editorState,
Selection selection,
String url, {
String? previewType,
}) async {
final node = editorState.getNodeAtPath(selection.end.path);
if (node == null) {
return;
}
final delta = node.delta;
if (delta == null) return;
final List<TextInsert> beforeOperations = [], afterOperations = [];
int index = 0;
for (final insert in delta.whereType<TextInsert>()) {
if (index < selection.startIndex) {
beforeOperations.add(insert);
} else if (index >= selection.endIndex) {
afterOperations.add(insert);
}
index += insert.length;
}
final transaction = editorState.transaction;
transaction
..deleteNode(node)
..insertNodes(node.path.next, [
if (beforeOperations.isNotEmpty)
paragraphNode(delta: Delta(operations: beforeOperations)),
if (previewType == LinkEmbedKeys.embed)
linkEmbedNode(url: url)
else
linkPreviewNode(url: url),
if (afterOperations.isNotEmpty)
paragraphNode(delta: Delta(operations: afterOperations)),
]);
await editorState.apply(transaction);
}
Future<void> convertUrlToMention(
EditorState editorState,
Selection selection,
) async {
final node = editorState.getNodeAtPath(selection.end.path);
if (node == null) {
return;
}
final delta = node.delta;
if (delta == null) return;
String url = '';
int index = 0;
for (final insert in delta.whereType<TextInsert>()) {
if (index >= selection.startIndex && index < selection.endIndex) {
final href = insert.attributes?.href ?? '';
if (href.isNotEmpty) {
url = href;
break;
}
}
index += insert.length;
}
final transaction = editorState.transaction;
transaction.replaceText(
node,
selection.startIndex,
selection.length,
MentionBlockKeys.mentionChar,
attributes: {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.externalLink.name,
MentionBlockKeys.url: url,
},
},
);
await editorState.apply(transaction);
}
Future<void> convertLinkBlockToOtherLinkBlock(
EditorState editorState,
Node node,
String toType, {
String? url,
}) async {
final nodeType = node.type;
if (nodeType != LinkPreviewBlockKeys.type ||
(nodeType == toType && url == null)) {
return;
}
final insertedNode = <Node>[];
final afterUrl = url ?? node.attributes[LinkPreviewBlockKeys.url] ?? '';
final previewType = node.attributes[LinkEmbedKeys.previewType];
Node afterNode = node.copyWith(
type: toType,
attributes: {
LinkPreviewBlockKeys.url: afterUrl,
LinkEmbedKeys.previewType: previewType,
blockComponentBackgroundColor:
node.attributes[blockComponentBackgroundColor],
blockComponentTextDirection: node.attributes[blockComponentTextDirection],
blockComponentDelta: (node.delta ?? Delta()).toJson(),
},
);
afterNode = afterNode.copyWith(children: []);
insertedNode.add(afterNode);
insertedNode.addAll(node.children.map((e) => e.deepCopy()));
final transaction = editorState.transaction;
transaction.insertNodes(
node.path,
insertedNode,
);
transaction.deleteNodes([node]);
await editorState.apply(transaction);
}
@@ -100,7 +100,6 @@ class ChildPageTransactionHandler extends MentionTransactionHandler {
Log.error(error);
if (context.mounted) {
showToastNotification(
context,
message: LocaleKeys.document_plugins_subPage_errors_failedDeletePage
.tr(),
);
@@ -179,13 +178,6 @@ class ChildPageTransactionHandler extends MentionTransactionHandler {
await duplicatedViewOrFailure.fold(
(newView) async {
final newMentionAttributes = {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.childPage.name,
MentionBlockKeys.pageId: newView.id,
},
};
// The index is the index of the delta, to get the index of the mention character
// in all the text, we need to calculate it based on the deltas before the current delta.
int mentionIndex = 0;
@@ -202,7 +194,11 @@ class ChildPageTransactionHandler extends MentionTransactionHandler {
node,
mentionIndex,
MentionBlockKeys.mentionChar.length,
newMentionAttributes,
MentionBlockKeys.buildMentionPageAttributes(
mentionType: MentionType.childPage,
pageId: newView.id,
blockId: null,
),
);
await editorState.apply(
transaction,
@@ -192,15 +192,12 @@ class DateTransactionHandler extends MentionTransactionHandler {
),
);
final newMentionAttributes = {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.date.name,
MentionBlockKeys.date: dateTime.toIso8601String(),
MentionBlockKeys.reminderId: reminderId,
MentionBlockKeys.includeTime: data.includeTime,
MentionBlockKeys.reminderOption: data.reminderOption.name,
},
};
final newMentionAttributes = MentionBlockKeys.buildMentionDateAttributes(
date: dateTime.toIso8601String(),
reminderId: reminderId,
reminderOption: data.reminderOption.name,
includeTime: data.includeTime,
);
// The index is the index of the delta, to get the index of the mention character
// in all the text, we need to calculate it based on the deltas before the current delta.
@@ -6,14 +6,18 @@ import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'mention_link_block.dart';
enum MentionType {
page,
date,
externalLink,
childPage;
static MentionType fromString(String value) => switch (value) {
'page' => page,
'date' => date,
'externalLink' => externalLink,
'childPage' => childPage,
// Backwards compatibility
'reminder' => date,
@@ -27,12 +31,12 @@ Node dateMentionNode() {
operations: [
TextInsert(
MentionBlockKeys.mentionChar,
attributes: {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.date.name,
MentionBlockKeys.date: DateTime.now().toIso8601String(),
},
},
attributes: MentionBlockKeys.buildMentionDateAttributes(
date: DateTime.now().toIso8601String(),
reminderId: null,
reminderOption: null,
includeTime: false,
),
),
],
),
@@ -42,18 +46,52 @@ Node dateMentionNode() {
class MentionBlockKeys {
const MentionBlockKeys._();
static const reminderId = 'reminder_id'; // ReminderID
static const mention = 'mention';
static const type = 'type'; // MentionType, String
static const pageId = 'page_id';
static const blockId = 'block_id';
static const url = 'url';
// Related to Reminder and Date blocks
static const date = 'date'; // Start Date
static const includeTime = 'include_time';
static const reminderId = 'reminder_id'; // ReminderID
static const reminderOption = 'reminder_option';
static const mentionChar = '\$';
static Map<String, dynamic> buildMentionPageAttributes({
required MentionType mentionType,
required String pageId,
required String? blockId,
}) {
return {
MentionBlockKeys.mention: {
MentionBlockKeys.type: mentionType.name,
MentionBlockKeys.pageId: pageId,
if (blockId != null) MentionBlockKeys.blockId: blockId,
},
};
}
static Map<String, dynamic> buildMentionDateAttributes({
required String date,
required String? reminderId,
required String? reminderOption,
required bool includeTime,
}) {
return {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.date.name,
MentionBlockKeys.date: date,
MentionBlockKeys.includeTime: includeTime,
if (reminderId != null) MentionBlockKeys.reminderId: reminderId,
if (reminderOption != null)
MentionBlockKeys.reminderOption: reminderOption,
},
};
}
}
class MentionBlock extends StatelessWidget {
@@ -124,6 +162,17 @@ class MentionBlock extends StatelessWidget {
reminderOption: reminderOption ?? ReminderOption.none,
includeTime: mention[MentionBlockKeys.includeTime] ?? false,
);
case MentionType.externalLink:
final String? url = mention[MentionBlockKeys.url] as String?;
if (url == null) {
return const SizedBox.shrink();
}
return MentionLinkBlock(
url: url,
editorState: editorState,
node: node,
index: index,
);
}
}
}
@@ -201,16 +201,17 @@ class _MentionDateBlockState extends State<MentionDateBlock> {
(reminderOption == ReminderOption.none ? null : widget.reminderId);
final transaction = widget.editorState.transaction
..formatText(widget.node, widget.index, 1, {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.date.name,
MentionBlockKeys.date: date.toIso8601String(),
MentionBlockKeys.reminderId: rId,
MentionBlockKeys.includeTime: includeTime,
MentionBlockKeys.reminderOption:
reminderOption?.name ?? widget.reminderOption.name,
},
});
..formatText(
widget.node,
widget.index,
1,
MentionBlockKeys.buildMentionDateAttributes(
date: date.toIso8601String(),
reminderId: rId,
includeTime: includeTime,
reminderOption: reminderOption?.name ?? widget.reminderOption.name,
),
);
widget.editorState.apply(transaction, withUpdateSelection: false);
@@ -0,0 +1,337 @@
import 'dart:async';
import 'dart:math';
import 'package:appflowy/core/helpers/url_launcher.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/link/link_hover_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_embed/link_embed_block_component.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/custom_link_parser.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/paste_as/paste_as_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/shared.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_ui/appflowy_ui.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/style_widget/hover.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'mention_link_error_preview.dart';
import 'mention_link_preview.dart';
class MentionLinkBlock extends StatefulWidget {
const MentionLinkBlock({
super.key,
required this.url,
required this.editorState,
required this.node,
required this.index,
this.delayToShow = const Duration(milliseconds: 50),
this.delayToHide = const Duration(milliseconds: 300),
});
final String url;
final Duration delayToShow;
final Duration delayToHide;
final EditorState editorState;
final Node node;
final int index;
@override
State<MentionLinkBlock> createState() => _MentionLinkBlockState();
}
class _MentionLinkBlockState extends State<MentionLinkBlock> {
final parser = LinkParser();
_LoadingStatus status = _LoadingStatus.loading;
final previewController = PopoverController();
LinkInfo linkInfo = LinkInfo();
bool isHovering = false;
int previewFocusNum = 0;
bool isPreviewHovering = false;
bool showAtBottom = false;
final key = GlobalKey();
bool get isPreviewShowing => previewFocusNum > 0;
String get url => widget.url;
EditorState get editorState => widget.editorState;
Node get node => widget.node;
int get index => widget.index;
bool get readyForPreview =>
status == _LoadingStatus.idle && !linkInfo.isEmpty();
@override
void initState() {
super.initState();
parser.addLinkInfoListener((v) {
if (mounted) {
setState(() {
if (v.isEmpty() && linkInfo.isEmpty()) {
status = _LoadingStatus.error;
} else {
linkInfo = v;
status = _LoadingStatus.idle;
}
});
}
});
parser.start(url);
}
@override
void dispose() {
super.dispose();
parser.dispose();
previewController.close();
}
@override
Widget build(BuildContext context) {
return AppFlowyPopover(
key: ValueKey(showAtBottom),
controller: previewController,
direction: showAtBottom
? PopoverDirection.bottomWithLeftAligned
: PopoverDirection.topWithLeftAligned,
offset: Offset(0, showAtBottom ? -20 : 20),
onOpen: () {
keepEditorFocusNotifier.increase();
previewFocusNum++;
},
onClose: () {
keepEditorFocusNotifier.decrease();
previewFocusNum--;
},
decorationColor: Colors.transparent,
popoverDecoration: BoxDecoration(),
margin: EdgeInsets.zero,
constraints: getConstraints(),
borderRadius: BorderRadius.circular(16),
popupBuilder: (context) => readyForPreview
? MentionLinkPreview(
linkInfo: linkInfo,
showAtBottom: showAtBottom,
triggerSize: getSizeFromKey(),
onEnter: (e) {
isPreviewHovering = true;
},
onExit: (e) {
isPreviewHovering = false;
tryToDismissPreview();
},
onCopyLink: () => copyLink(context),
onConvertTo: (s) => convertTo(s),
onRemoveLink: removeLink,
onOpenLink: openLink,
)
: MentionLinkErrorPreview(
url: url,
triggerSize: getSizeFromKey(),
onEnter: (e) {
isPreviewHovering = true;
},
onExit: (e) {
isPreviewHovering = false;
tryToDismissPreview();
},
onCopyLink: () => copyLink(context),
onConvertTo: (s) => convertTo(s),
onRemoveLink: removeLink,
onOpenLink: openLink,
),
child: buildIconWithTitle(context),
);
}
Widget buildIconWithTitle(BuildContext context) {
final theme = AppFlowyTheme.of(context);
return MouseRegion(
cursor: SystemMouseCursors.click,
onEnter: onEnter,
onExit: onExit,
child: GestureDetector(
onTap: () async {
await afLaunchUrlString(url, addingHttpSchemeWhenFailed: true);
},
child: FlowyHoverContainer(
style:
HoverStyle(hoverColor: Theme.of(context).colorScheme.secondary),
applyStyle: isHovering,
child: Row(
mainAxisSize: MainAxisSize.min,
key: key,
children: [
HSpace(2),
buildIcon(),
HSpace(4),
Flexible(
child: FlowyText(
linkInfo.siteName ?? url,
color: theme.textColorScheme.primary,
fontSize: 14,
figmaLineHeight: 20,
overflow: TextOverflow.ellipsis,
),
),
HSpace(2),
],
),
),
),
);
}
Widget buildIcon() {
const defaultWidget = FlowySvg(FlowySvgs.toolbar_link_earth_m);
Widget icon = defaultWidget;
if (status == _LoadingStatus.loading) {
icon = Padding(
padding: const EdgeInsets.all(2.0),
child: const CircularProgressIndicator(strokeWidth: 1),
);
} else {
icon = linkInfo.buildIconWidget();
}
return SizedBox(
height: 20,
width: 20,
child: icon,
);
}
RenderBox? get box => key.currentContext?.findRenderObject() as RenderBox?;
Size getSizeFromKey() => box?.size ?? Size.zero;
Future<void> copyLink(BuildContext context) async {
await context.copyLink(url);
previewController.close();
}
Future<void> openLink() async {
await afLaunchUrlString(url, addingHttpSchemeWhenFailed: true);
}
Future<void> removeLink() async {
final transaction = editorState.transaction
..replaceText(widget.node, widget.index, 1, url, attributes: {});
await editorState.apply(transaction);
}
Future<void> convertTo(PasteMenuType type) async {
if (type == PasteMenuType.url) {
await toUrl();
} else if (type == PasteMenuType.bookmark) {
await toLinkPreview();
} else if (type == PasteMenuType.embed) {
await toLinkPreview(previewType: LinkEmbedKeys.embed);
}
}
Future<void> toUrl() async {
final transaction = editorState.transaction
..replaceText(
widget.node,
widget.index,
1,
url,
attributes: {
AppFlowyRichTextKeys.href: url,
},
);
await editorState.apply(transaction);
}
Future<void> toLinkPreview({String? previewType}) async {
final selection = Selection(
start: Position(path: node.path, offset: index),
end: Position(path: node.path, offset: index + 1),
);
await convertUrlToLinkPreview(
editorState,
selection,
url,
previewType: previewType,
);
}
void changeHovering(bool hovering) {
if (isHovering == hovering) return;
if (mounted) {
setState(() {
isHovering = hovering;
});
}
}
void changeShowAtBottom(bool bottom) {
if (showAtBottom == bottom) return;
if (mounted) {
setState(() {
showAtBottom = bottom;
});
}
}
void tryToDismissPreview() {
Future.delayed(widget.delayToHide, () {
if (isHovering || isPreviewHovering) {
return;
}
previewController.close();
});
}
void onEnter(PointerEnterEvent e) {
changeHovering(true);
final location = box?.localToGlobal(Offset.zero) ?? Offset.zero;
if (readyForPreview) {
if (location.dy < 300) {
changeShowAtBottom(true);
} else {
changeShowAtBottom(false);
}
}
Future.delayed(widget.delayToShow, () {
if (isHovering && !isPreviewShowing && status != _LoadingStatus.loading) {
showPreview();
}
});
}
void onExit(PointerExitEvent e) {
changeHovering(false);
tryToDismissPreview();
}
void showPreview() {
if (!mounted) return;
keepEditorFocusNotifier.increase();
previewController.show();
previewFocusNum++;
}
BoxConstraints getConstraints() {
final size = getSizeFromKey();
if (!readyForPreview) {
return BoxConstraints(
maxWidth: max(320, size.width),
maxHeight: 48 + size.height,
);
}
return BoxConstraints(
maxWidth: max(300, size.width),
maxHeight: 300,
);
}
}
enum _LoadingStatus {
loading,
idle,
error,
}
@@ -0,0 +1,232 @@
import 'dart:math';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/link/link_create_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/paste_as/paste_as_menu.dart';
import 'package:appflowy/util/theme_extension.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class MentionLinkErrorPreview extends StatefulWidget {
const MentionLinkErrorPreview({
super.key,
required this.url,
required this.onEnter,
required this.onExit,
required this.onCopyLink,
required this.onRemoveLink,
required this.onConvertTo,
required this.onOpenLink,
required this.triggerSize,
});
final String url;
final PointerEnterEventListener onEnter;
final PointerExitEventListener onExit;
final VoidCallback onCopyLink;
final VoidCallback onRemoveLink;
final VoidCallback onOpenLink;
final ValueChanged<PasteMenuType> onConvertTo;
final Size triggerSize;
@override
State<MentionLinkErrorPreview> createState() =>
_MentionLinkErrorPreviewState();
}
class _MentionLinkErrorPreviewState extends State<MentionLinkErrorPreview> {
final menuController = PopoverController();
bool isConvertButtonSelected = false;
@override
void dispose() {
super.dispose();
menuController.close();
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
MouseRegion(
onEnter: widget.onEnter,
onExit: widget.onExit,
child: SizedBox(
width: max(320, widget.triggerSize.width),
height: 48,
child: Align(
alignment: Alignment.centerLeft,
child: Container(
width: 320,
height: 48,
decoration: buildToolbarLinkDecoration(context),
padding: EdgeInsets.fromLTRB(12, 8, 8, 8),
child: Row(
children: [
Expanded(child: buildLinkWidget()),
Container(
height: 20,
width: 1,
color: Color(0xffE8ECF3)
.withAlpha(Theme.of(context).isLightMode ? 255 : 40),
margin: EdgeInsets.symmetric(horizontal: 6),
),
FlowyIconButton(
icon: FlowySvg(FlowySvgs.toolbar_link_m),
tooltipText: LocaleKeys.editor_copyLink.tr(),
preferBelow: false,
width: 36,
height: 32,
onPressed: widget.onCopyLink,
),
buildConvertButton(),
],
),
),
),
),
),
MouseRegion(
cursor: SystemMouseCursors.click,
onEnter: widget.onEnter,
onExit: widget.onExit,
child: GestureDetector(
onTap: widget.onOpenLink,
child: Container(
width: widget.triggerSize.width,
height: widget.triggerSize.height,
color: Colors.black.withAlpha(1),
),
),
),
],
);
}
Widget buildLinkWidget() {
final url = widget.url;
return FlowyTooltip(
message: url,
preferBelow: false,
child: FlowyText.regular(
url,
overflow: TextOverflow.ellipsis,
figmaLineHeight: 20,
fontSize: 14,
),
);
}
Widget buildConvertButton() {
return AppFlowyPopover(
offset: Offset(8, 10),
direction: PopoverDirection.bottomWithRightAligned,
margin: EdgeInsets.zero,
controller: menuController,
onOpen: () => keepEditorFocusNotifier.increase(),
onClose: () => keepEditorFocusNotifier.decrease(),
popupBuilder: (context) => buildConvertMenu(),
child: FlowyIconButton(
icon: FlowySvg(FlowySvgs.turninto_m),
isSelected: isConvertButtonSelected,
tooltipText: LocaleKeys.editor_convertTo.tr(),
preferBelow: false,
width: 36,
height: 32,
onPressed: () {
setState(() {
isConvertButtonSelected = true;
});
showPopover();
},
),
);
}
Widget buildConvertMenu() {
return MouseRegion(
onEnter: widget.onEnter,
onExit: widget.onExit,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: SeparatedColumn(
mainAxisSize: MainAxisSize.min,
separatorBuilder: () => const VSpace(0.0),
children: List.generate(MentionLinktErrorMenuCommand.values.length,
(index) {
final command = MentionLinktErrorMenuCommand.values[index];
return SizedBox(
height: 36,
child: FlowyButton(
text: FlowyText(
command.title,
fontWeight: FontWeight.w400,
figmaLineHeight: 20,
),
onTap: () => onTap(command),
),
);
}),
),
),
);
}
void showPopover() {
keepEditorFocusNotifier.increase();
menuController.show();
}
void closePopover() {
menuController.close();
}
void onTap(MentionLinktErrorMenuCommand command) {
switch (command) {
case MentionLinktErrorMenuCommand.toURL:
widget.onConvertTo(PasteMenuType.url);
break;
case MentionLinktErrorMenuCommand.toBookmark:
widget.onConvertTo(PasteMenuType.bookmark);
break;
case MentionLinktErrorMenuCommand.toEmbed:
widget.onConvertTo(PasteMenuType.embed);
break;
case MentionLinktErrorMenuCommand.removeLink:
widget.onRemoveLink();
break;
}
closePopover();
}
}
enum MentionLinktErrorMenuCommand {
toURL,
toBookmark,
toEmbed,
removeLink;
String get title {
switch (this) {
case toURL:
return LocaleKeys.document_plugins_linkPreview_linkPreviewMenu_toUrl
.tr();
case toBookmark:
return LocaleKeys
.document_plugins_linkPreview_linkPreviewMenu_toBookmark
.tr();
case toEmbed:
return LocaleKeys.document_plugins_linkPreview_linkPreviewMenu_toEmbed
.tr();
case removeLink:
return LocaleKeys
.document_plugins_linkPreview_linkPreviewMenu_removeLink
.tr();
}
}
}
@@ -0,0 +1,271 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/link/link_create_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/custom_link_parser.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/link_preview/paste_as/paste_as_menu.dart';
import 'package:appflowy/plugins/document/presentation/editor_style.dart';
import 'package:appflowy/shared/appflowy_network_image.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_ui/appflowy_ui.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class MentionLinkPreview extends StatefulWidget {
const MentionLinkPreview({
super.key,
required this.linkInfo,
required this.onEnter,
required this.onExit,
required this.onCopyLink,
required this.onRemoveLink,
required this.onConvertTo,
required this.onOpenLink,
required this.triggerSize,
required this.showAtBottom,
});
final LinkInfo linkInfo;
final PointerEnterEventListener onEnter;
final PointerExitEventListener onExit;
final VoidCallback onCopyLink;
final VoidCallback onRemoveLink;
final VoidCallback onOpenLink;
final ValueChanged<PasteMenuType> onConvertTo;
final Size triggerSize;
final bool showAtBottom;
@override
State<MentionLinkPreview> createState() => _MentionLinkPreviewState();
}
class _MentionLinkPreviewState extends State<MentionLinkPreview> {
final menuController = PopoverController();
bool isSelected = false;
LinkInfo get linkInfo => widget.linkInfo;
@override
void dispose() {
super.dispose();
menuController.close();
}
@override
Widget build(BuildContext context) {
final theme = AppFlowyTheme.of(context),
textColorScheme = theme.textColorScheme;
final card = MouseRegion(
onEnter: widget.onEnter,
onExit: widget.onExit,
child: Container(
decoration: buildToolbarLinkDecoration(context, radius: 16),
width: 280,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ClipRRect(
borderRadius:
const BorderRadius.vertical(top: Radius.circular(16)),
child: FlowyNetworkImage(
url: linkInfo.imageUrl ?? '',
width: 280,
height: 120,
),
),
VSpace(12),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: FlowyText.semibold(
linkInfo.siteName ?? '',
fontSize: 14,
figmaLineHeight: 20,
color: textColorScheme.primary,
overflow: TextOverflow.ellipsis,
),
),
VSpace(4),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: FlowyText(
linkInfo.description ?? '',
fontSize: 12,
figmaLineHeight: 16,
color: textColorScheme.secondary,
maxLines: 3,
overflow: TextOverflow.ellipsis,
),
),
VSpace(36),
Container(
margin: const EdgeInsets.symmetric(horizontal: 16),
height: 28,
child: Row(
children: [
linkInfo.buildIconWidget(size: Size.square(16)),
HSpace(6),
Expanded(
child: FlowyText(
linkInfo.description ?? '',
fontSize: 12,
figmaLineHeight: 16,
color: textColorScheme.primary,
overflow: TextOverflow.ellipsis,
fontWeight: FontWeight.w700,
),
),
buildMoreOptionButton(),
],
),
),
VSpace(12),
],
),
),
);
final clickPlaceHolder = MouseRegion(
cursor: SystemMouseCursors.click,
onEnter: widget.onEnter,
onExit: widget.onExit,
child: GestureDetector(
child: Container(
height: 20,
width: widget.triggerSize.width,
color: Colors.white.withAlpha(1),
),
onTap: () {
widget.onOpenLink.call();
closePopover();
},
),
);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: widget.showAtBottom
? [clickPlaceHolder, card]
: [card, clickPlaceHolder],
);
}
Widget buildMoreOptionButton() {
return AppFlowyPopover(
controller: menuController,
direction: PopoverDirection.topWithLeftAligned,
onOpen: () => keepEditorFocusNotifier.increase(),
onClose: () => keepEditorFocusNotifier.decrease(),
margin: EdgeInsets.zero,
borderRadius: BorderRadius.circular(12),
popupBuilder: (context) => buildConvertMenu(),
child: FlowyIconButton(
width: 28,
height: 28,
isSelected: isSelected,
hoverColor: EditorStyleCustomizer.toolbarHoverColor(context),
icon: FlowySvg(
FlowySvgs.toolbar_more_m,
size: Size.square(20),
),
onPressed: () {
setState(() {
isSelected = true;
});
showPopover();
},
),
);
}
Widget buildConvertMenu() {
return MouseRegion(
onEnter: widget.onEnter,
onExit: widget.onExit,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: SeparatedColumn(
mainAxisSize: MainAxisSize.min,
separatorBuilder: () => const VSpace(0.0),
children:
List.generate(MentionLinktMenuCommand.values.length, (index) {
final command = MentionLinktMenuCommand.values[index];
return SizedBox(
height: 36,
child: FlowyButton(
text: FlowyText(
command.title,
fontWeight: FontWeight.w400,
figmaLineHeight: 20,
),
onTap: () => onTap(command),
),
);
}),
),
),
);
}
void showPopover() {
keepEditorFocusNotifier.increase();
menuController.show();
}
void closePopover() {
menuController.close();
}
void onTap(MentionLinktMenuCommand command) {
switch (command) {
case MentionLinktMenuCommand.toURL:
widget.onConvertTo(PasteMenuType.url);
break;
case MentionLinktMenuCommand.toBookmark:
widget.onConvertTo(PasteMenuType.bookmark);
break;
case MentionLinktMenuCommand.toEmbed:
widget.onConvertTo(PasteMenuType.embed);
break;
case MentionLinktMenuCommand.copyLink:
widget.onCopyLink();
break;
case MentionLinktMenuCommand.removeLink:
widget.onRemoveLink();
break;
}
closePopover();
}
}
enum MentionLinktMenuCommand {
toURL,
toBookmark,
toEmbed,
copyLink,
removeLink;
String get title {
switch (this) {
case toURL:
return LocaleKeys.document_plugins_linkPreview_linkPreviewMenu_toUrl
.tr();
case toBookmark:
return LocaleKeys
.document_plugins_linkPreview_linkPreviewMenu_toBookmark
.tr();
case toEmbed:
return LocaleKeys.document_plugins_linkPreview_linkPreviewMenu_toEmbed
.tr();
case copyLink:
return LocaleKeys.document_plugins_linkPreview_linkPreviewMenu_copyLink
.tr();
case removeLink:
return LocaleKeys
.document_plugins_linkPreview_linkPreviewMenu_removeLink
.tr();
}
}
}
@@ -50,12 +50,11 @@ Node pageMentionNode(String viewId) {
operations: [
TextInsert(
MentionBlockKeys.mentionChar,
attributes: {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.page.name,
MentionBlockKeys.pageId: viewId,
},
},
attributes: MentionBlockKeys.buildMentionPageAttributes(
mentionType: MentionType.page,
pageId: viewId,
blockId: null,
),
),
],
),
@@ -284,12 +283,11 @@ class _MentionSubPageBlockState extends State<MentionSubPageBlock> {
widget.node,
widget.index,
MentionBlockKeys.mentionChar.length,
{
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.page.name,
MentionBlockKeys.pageId: widget.pageId,
},
},
MentionBlockKeys.buildMentionPageAttributes(
mentionType: MentionType.page,
pageId: widget.pageId,
blockId: null,
),
);
widget.editorState.apply(
@@ -383,25 +381,24 @@ Future<void> _handleDoubleTap(
}
final currentViewId = context.read<DocumentBloc>().documentId;
final newViewId = await showPageSelectorSheet(
final newView = await showPageSelectorSheet(
context,
currentViewId: currentViewId,
selectedViewId: viewId,
);
if (newViewId != null) {
if (newView != null) {
// Update this nodes pageId
final transaction = editorState.transaction
..formatText(
node,
index,
1,
{
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.page.name,
MentionBlockKeys.pageId: newViewId,
},
},
MentionBlockKeys.buildMentionPageAttributes(
mentionType: MentionType.page,
pageId: newView.id,
blockId: null,
),
);
await editorState.apply(transaction, withUpdateSelection: false);
@@ -0,0 +1,116 @@
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/material.dart';
extension MenuExtension on EditorState {
MenuPosition? calculateMenuOffset({
Rect? rect,
required double menuWidth,
required double menuHeight,
Offset menuOffset = const Offset(0, 10),
}) {
final selectionService = service.selectionService;
final selectionRects = selectionService.selectionRects;
late Rect startRect;
if (rect != null) {
startRect = rect;
} else {
if (selectionRects.isEmpty) return null;
startRect = selectionRects.first;
}
final editorOffset = renderBox?.localToGlobal(Offset.zero) ?? Offset.zero;
final editorHeight = renderBox!.size.height;
final editorWidth = renderBox!.size.width;
// show below default
Alignment alignment = Alignment.topLeft;
final bottomRight = startRect.bottomRight;
final topRight = startRect.topRight;
var startOffset = bottomRight + menuOffset;
Offset offset = Offset(
startOffset.dx,
startOffset.dy,
);
// show above
if (startOffset.dy + menuHeight >= editorOffset.dy + editorHeight) {
startOffset = topRight - menuOffset;
alignment = Alignment.bottomLeft;
offset = Offset(
startOffset.dx,
editorHeight + editorOffset.dy - startOffset.dy,
);
}
// show on right
if (offset.dx + menuWidth < editorOffset.dx + editorWidth) {
offset = Offset(
offset.dx,
offset.dy,
);
} else if (startOffset.dx - editorOffset.dx > menuWidth) {
// show on left
alignment = alignment == Alignment.topLeft
? Alignment.topRight
: Alignment.bottomRight;
offset = Offset(
editorWidth - offset.dx + editorOffset.dx,
offset.dy,
);
}
return MenuPosition(align: alignment, offset: offset);
}
}
class MenuPosition {
MenuPosition({
required this.align,
required this.offset,
});
final Alignment align;
final Offset offset;
LTRB get ltrb {
double? left, top, right, bottom;
switch (align) {
case Alignment.topLeft:
left = offset.dx;
top = offset.dy;
break;
case Alignment.bottomLeft:
left = offset.dx;
bottom = offset.dy;
break;
case Alignment.topRight:
right = offset.dx;
top = offset.dy;
break;
case Alignment.bottomRight:
right = offset.dx;
bottom = offset.dy;
break;
}
return LTRB(left: left, top: top, right: right, bottom: bottom);
}
}
class LTRB {
LTRB({this.left, this.top, this.right, this.bottom});
final double? left;
final double? top;
final double? right;
final double? bottom;
Positioned buildPositioned({required Widget child}) => Positioned(
left: left,
top: top,
right: right,
bottom: bottom,
child: child,
);
}
@@ -46,12 +46,12 @@ extension on EditorState {
selection.start.offset,
0,
MentionBlockKeys.mentionChar,
attributes: {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.date.name,
MentionBlockKeys.date: DateTime.now().toIso8601String(),
},
},
attributes: MentionBlockKeys.buildMentionDateAttributes(
date: DateTime.now().toIso8601String(),
reminderId: null,
reminderOption: null,
includeTime: false,
),
);
await apply(transaction);
@@ -58,6 +58,9 @@ class _HighlightColorPickerWidgetState
@override
Widget build(BuildContext context) {
if (editorState.selection == null) {
return const SizedBox.shrink();
}
final selectionRectList = editorState.selectionRects();
final top =
selectionRectList.isEmpty ? 0.0 : selectionRectList.first.height;
@@ -591,10 +591,9 @@ class EditorStyleCustomizer {
Node node,
SelectableMixin delegate,
) {
if (UniversalPlatform.isMobile) return [];
final delta = node.delta;
if (delta == null) {
return [];
}
if (delta == null) return [];
final widgets = <Widget>[];
final textInserts = delta.whereType<TextInsert>();
int index = 0;
@@ -299,7 +299,8 @@ class _EmojiHandlerState extends State<EmojiHandler> {
.getTextInSelection(
selection.copyWith(
start: selection.start.copyWith(offset: startOffset),
end: selection.start.copyWith(offset: startOffset + _search.length + 1),
end: selection.start
.copyWith(offset: startOffset + _search.length + 1),
),
)
.join();
@@ -24,7 +24,7 @@ class InlineChildPageService extends InlineActionsDelegate {
results.add(
InlineActionsMenuItem(
label: LocaleKeys.inlineActions_createPage.tr(args: [search]),
icon: (_) => const FlowySvg(FlowySvgs.add_s),
iconBuilder: (_) => const FlowySvg(FlowySvgs.add_s),
onSelected: (context, editorState, service, replacement) =>
_onSelected(context, editorState, service, replacement, search),
),
@@ -71,12 +71,11 @@ class InlineChildPageService extends InlineActionsDelegate {
replacement.$1,
replacement.$2,
MentionBlockKeys.mentionChar,
attributes: {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.childPage.name,
MentionBlockKeys.pageId: view.id,
},
},
attributes: MentionBlockKeys.buildMentionPageAttributes(
mentionType: MentionType.childPage,
pageId: view.id,
blockId: null,
),
);
await editorState.apply(transaction);
@@ -122,12 +122,12 @@ class DateReferenceService extends InlineActionsDelegate {
start,
end,
MentionBlockKeys.mentionChar,
attributes: {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.date.name,
MentionBlockKeys.date: date.toIso8601String(),
},
},
attributes: MentionBlockKeys.buildMentionDateAttributes(
date: date.toIso8601String(),
includeTime: false,
reminderId: null,
reminderOption: null,
),
);
await editorState.apply(transaction);
@@ -221,12 +221,11 @@ class InlinePageReferenceService extends InlineActionsDelegate {
replace.$1,
replace.$2,
MentionBlockKeys.mentionChar,
attributes: {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.page.name,
MentionBlockKeys.pageId: view.id,
},
},
attributes: MentionBlockKeys.buildMentionPageAttributes(
mentionType: MentionType.page,
pageId: view.id,
blockId: null,
),
);
await editorState.apply(transaction);
@@ -235,12 +234,19 @@ class InlinePageReferenceService extends InlineActionsDelegate {
InlineActionsMenuItem _fromView(ViewPB view) => InlineActionsMenuItem(
keywords: [view.nameOrDefault.toLowerCase()],
label: view.nameOrDefault,
icon: (onSelected) => view.icon.value.isNotEmpty
? RawEmojiIconWidget(
emoji: view.icon.toEmojiIconData(),
emojiSize: 14,
)
: view.defaultIcon(),
iconBuilder: (onSelected) {
final child = view.icon.value.isNotEmpty
? RawEmojiIconWidget(
emoji: view.icon.toEmojiIconData(),
emojiSize: 16.0,
lineHeight: 18.0 / 16.0,
)
: view.defaultIcon(size: const Size(16, 16));
return SizedBox(
width: 16,
child: child,
);
},
onSelected: (context, editorState, menu, replace) => insertPage
? _onInsertPageRef(view, context, editorState, replace)
: _onInsertLinkRef(view, context, editorState, menu, replace),
@@ -148,14 +148,12 @@ class ReminderReferenceService extends InlineActionsDelegate {
start,
end,
MentionBlockKeys.mentionChar,
attributes: {
MentionBlockKeys.mention: {
MentionBlockKeys.type: MentionType.date.name,
MentionBlockKeys.date: date.toIso8601String(),
MentionBlockKeys.reminderId: reminder.id,
MentionBlockKeys.reminderOption: ReminderOption.atTimeOfEvent.name,
},
},
attributes: MentionBlockKeys.buildMentionDateAttributes(
date: date.toIso8601String(),
reminderId: reminder.id,
reminderOption: ReminderOption.atTimeOfEvent.name,
includeTime: false,
),
);
await editorState.apply(transaction);
@@ -12,13 +12,13 @@ typedef SelectItemHandler = void Function(
class InlineActionsMenuItem {
InlineActionsMenuItem({
required this.label,
this.icon,
this.iconBuilder,
this.keywords,
this.onSelected,
});
final String label;
final Widget Function(bool onSelected)? icon;
final Widget Function(bool onSelected)? iconBuilder;
final List<String>? keywords;
final SelectItemHandler? onSelected;
}
@@ -92,8 +92,8 @@ class InlineActionsWidget extends StatefulWidget {
class _InlineActionsWidgetState extends State<InlineActionsWidget> {
@override
Widget build(BuildContext context) {
final icon = widget.item.icon;
final hasIcon = icon != null;
final iconBuilder = widget.item.iconBuilder;
final hasIcon = iconBuilder != null;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: SizedBox(
@@ -104,7 +104,7 @@ class _InlineActionsWidgetState extends State<InlineActionsWidget> {
text: Row(
children: [
if (hasIcon) ...[
icon.call(widget.isSelected),
iconBuilder.call(widget.isSelected),
SizedBox(width: 12),
],
Flexible(
@@ -174,11 +174,10 @@ class ExportTab extends StatelessWidget {
ClipboardServiceData(plainText: markdown),
);
showToastNotification(
context,
message: LocaleKeys.grid_url_copiedNotification.tr(),
message: LocaleKeys.message_copy_success.tr(),
);
},
(error) => showToastNotification(context, message: error.msg),
(error) => showToastNotification(message: error.msg),
);
}
}
@@ -85,11 +85,9 @@ class PublishTab extends StatelessWidget {
if (state.publishResult != null) {
state.publishResult!.fold(
(value) => showToastNotification(
context,
message: LocaleKeys.publish_publishSuccessfully.tr(),
),
(error) => showToastNotification(
context,
message: '${LocaleKeys.publish_publishFailed.tr()}: ${error.code}',
type: ToastificationType.error,
),
@@ -97,11 +95,9 @@ class PublishTab extends StatelessWidget {
} else if (state.unpublishResult != null) {
state.unpublishResult!.fold(
(value) => showToastNotification(
context,
message: LocaleKeys.publish_unpublishSuccessfully.tr(),
),
(error) => showToastNotification(
context,
message: LocaleKeys.publish_unpublishFailed.tr(),
description: error.msg,
type: ToastificationType.error,
@@ -110,14 +106,12 @@ class PublishTab extends StatelessWidget {
} else if (state.updatePathNameResult != null) {
state.updatePathNameResult!.fold(
(value) => showToastNotification(
context,
message: LocaleKeys.settings_sites_success_updatePathNameSuccess.tr(),
),
(error) {
Log.error('update path name failed: $error');
showToastNotification(
context,
message: LocaleKeys.settings_sites_error_updatePathNameFailed.tr(),
type: ToastificationType.error,
description: error.code.publishErrorMessage,
@@ -182,8 +176,7 @@ class _PublishedWidgetState extends State<_PublishedWidget> {
);
showToastNotification(
context,
message: LocaleKeys.grid_url_copy.tr(),
message: LocaleKeys.message_copy_success.tr(),
);
},
onSubmitted: (pathName) {
@@ -292,7 +285,6 @@ class _PublishWidgetState extends State<_PublishWidget> {
// check if any database is selected
if (_selectedViews.isEmpty) {
showToastNotification(
context,
message: LocaleKeys.publish_noDatabaseSelected.tr(),
);
return;
@@ -611,7 +603,6 @@ class _PublishDatabaseSelectorState extends State<_PublishDatabaseSelector> {
// unable to deselect the primary database
if (isPrimaryDatabase) {
showToastNotification(
context,
message:
LocaleKeys.publish_unableToDeselectPrimaryDatabase.tr(),
);
@@ -70,7 +70,6 @@ class ShareButton extends StatelessWidget {
case ShareType.html:
case ShareType.csv:
showToastNotification(
context,
message: LocaleKeys.settings_files_exportFileSuccess.tr(),
);
break;
@@ -81,7 +80,6 @@ class ShareButton extends StatelessWidget {
void _handleExportError(BuildContext context, FlowyError error) {
showToastNotification(
context,
message:
'${LocaleKeys.settings_files_exportFileFail.tr()}: ${error.code}',
);
@@ -117,8 +117,7 @@ class _ShareTabContent extends StatelessWidget {
);
showToastNotification(
context,
message: LocaleKeys.grid_url_copy.tr(),
message: LocaleKeys.message_copy_success.tr(),
);
}
}
@@ -1,14 +1,18 @@
import 'dart:io';
import 'package:appflowy/core/helpers/url_launcher.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_paste/clipboard_service.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/style_widget/button.dart';
import 'package:flowy_infra_ui/style_widget/hover.dart';
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flowy_infra_ui/widget/flowy_tooltip.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/style_widget/hover.dart';
import 'package:flowy_svg/flowy_svg.dart';
import 'package:url_launcher/url_launcher.dart';
class FlowyErrorPage extends StatelessWidget {
factory FlowyErrorPage.error(
@@ -86,7 +90,9 @@ class FlowyErrorPage extends StatelessWidget {
Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: (_) async {
await Clipboard.setData(ClipboardData(text: message));
await getIt<ClipboardService>().setData(
ClipboardServiceData(plainText: message),
);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
@@ -188,8 +194,8 @@ class StackTracePreview extends StatelessWidget {
"Copy",
),
useIntrinsicWidth: true,
onTap: () => Clipboard.setData(
ClipboardData(text: stackTrace),
onTap: () => getIt<ClipboardService>().setData(
ClipboardServiceData(plainText: stackTrace),
),
),
),
@@ -252,18 +258,14 @@ class GitHubRedirectButton extends StatelessWidget {
Widget build(BuildContext context) {
return FlowyButton(
leftIconSize: const Size.square(_height),
text: const FlowyText(
"AppFlowy",
),
text: FlowyText(LocaleKeys.appName.tr()),
useIntrinsicWidth: true,
leftIcon: const Padding(
padding: EdgeInsets.all(4.0),
child: FlowySvg(FlowySvgData('login/github-mark')),
),
onTap: () async {
if (await canLaunchUrl(_gitHubNewBugUri)) {
await launchUrl(_gitHubNewBugUri);
}
await afLaunchUri(_gitHubNewBugUri);
},
);
}
@@ -45,7 +45,6 @@ class _MobileSyncErrorPage extends StatelessWidget {
onTapUp: () {
getIt<ClipboardService>().setPlainText(error.toString());
showToastNotification(
context,
message: LocaleKeys.message_copy_success.tr(),
bottomPadding: 0,
);
@@ -101,7 +100,7 @@ class _DesktopSyncErrorPage extends StatelessWidget {
onTapUp: () {
getIt<ClipboardService>().setPlainText(error.toString());
showToastNotification(
context,
message: LocaleKeys.message_copy_success.tr(),
bottomPadding: 0,
);
@@ -99,13 +99,6 @@ void _resolveCommonService(
void _resolveUserDeps(GetIt getIt, IntegrationMode mode) {
switch (currentCloudType()) {
case AuthenticatorType.local:
getIt.registerFactory<AuthService>(
() => BackendAuthService(
AuthenticatorPB.Local,
),
);
break;
case AuthenticatorType.appflowyCloud:
case AuthenticatorType.appflowyCloudSelfHost:
case AuthenticatorType.appflowyCloudDevelop:
@@ -32,6 +32,21 @@ class FlowyRunnerContext {
final Directory applicationDataDirectory;
}
/// Launches AppFlowy application with optional anonymous mode.
///
/// [isAnon] When set to true, the application runs in anonymous mode where:
/// - No user authentication is required
/// - All data is stored locally in a separate anonymous directory
/// - The data is isolated from the main application storage
///
/// Example:
/// ```dart
/// // Launch in normal mode
/// await runAppFlowy();
///
/// // Launch in anonymous mode
/// await runAppFlowy(isAnon: true);
/// ```
Future<void> runAppFlowy({bool isAnon = false}) async {
Log.info('restart AppFlowy: isAnon: $isAnon');
@@ -129,7 +144,10 @@ class FlowyRunner {
// init the app window
InitAppWindowTask(),
// Init Rust SDK
InitRustSDKTask(customApplicationPath: applicationDataDirectory),
InitRustSDKTask(
customApplicationPath: applicationDataDirectory,
isAnon: isAnon,
),
// Load Plugins, like document, grid ...
const PluginLoadTask(),
const FileStorageTask(),
@@ -99,6 +99,7 @@ class InitAppWidgetTask extends LaunchTask {
Locale('zh', 'TW'),
Locale('fa'),
Locale('hin'),
Locale('mr', 'IN'),
],
path: 'assets/translations',
fallbackLocale: const Locale('en'),
@@ -225,16 +226,24 @@ class _ApplicationWidgetState extends State<ApplicationWidget> {
}
},
child: MaterialApp.router(
builder: (context, child) => MediaQuery(
// use the 1.0 as the textScaleFactor to avoid the text size
// affected by the system setting.
data: MediaQuery.of(context).copyWith(
textScaler: TextScaler.linear(state.textScaleFactor),
),
child: AppFlowyTheme(
data: Theme.of(context).brightness == Brightness.light
? AppFlowyThemeData.light()
: AppFlowyThemeData.dark(),
debugShowCheckedModeBanner: false,
theme: state.lightTheme,
darkTheme: state.darkTheme,
themeMode: state.themeMode,
localizationsDelegates: context.localizationDelegates,
supportedLocales: context.supportedLocales,
locale: state.locale,
routerConfig: routerConfig,
builder: (context, child) => AppFlowyTheme(
data: Theme.of(context).brightness == Brightness.light
? AppFlowyThemeData.light()
: AppFlowyThemeData.dark(),
child: MediaQuery(
// use the 1.0 as the textScaleFactor to avoid the text size
// affected by the system setting.
data: MediaQuery.of(context).copyWith(
textScaler: TextScaler.linear(state.textScaleFactor),
),
child: overlayManagerBuilder(
context,
!UniversalPlatform.isMobile && FeatureFlag.search.isOn
@@ -246,14 +255,6 @@ class _ApplicationWidgetState extends State<ApplicationWidget> {
),
),
),
debugShowCheckedModeBanner: false,
theme: state.lightTheme,
darkTheme: state.darkTheme,
themeMode: state.themeMode,
localizationsDelegates: context.localizationDelegates,
supportedLocales: context.supportedLocales,
locale: state.locale,
routerConfig: routerConfig,
),
),
),
@@ -8,15 +8,10 @@ import 'package:appflowy/startup/startup.dart';
class WindowSizeManager {
static const double minWindowHeight = 640.0;
static const double minWindowWidth = 640.0;
// Preventing failed assertion due to Texture Descriptor Validation
static const double maxWindowHeight = 8192.0;
static const double maxWindowWidth = 8192.0;
// Default windows size
static const double defaultWindowHeight = 960.0;
static const double defaultWindowWidth = 1280.0;
static const double maxScaleFactor = 2.0;
static const double minScaleFactor = 0.5;
@@ -41,8 +36,8 @@ class WindowSizeManager {
Future<Size> getSize() async {
final defaultWindowSize = jsonEncode(
{
WindowSizeManager.height: defaultWindowHeight,
WindowSizeManager.width: defaultWindowWidth,
WindowSizeManager.height: minWindowHeight,
WindowSizeManager.width: minWindowWidth,
},
);
final windowSize = await getIt<KeyValueStorage>().get(KVKeys.windowSize);
@@ -136,7 +136,7 @@ class AppFlowyCloudDeepLink {
final context = AppGlobals.rootNavKey.currentState?.context;
if (context != null) {
showToastNotification(
context,
message: err.msg,
);
}
@@ -120,18 +120,6 @@ GoRouter generateRouter(Widget child) {
);
},
),
GoRoute(
path: SignUpScreen.routeName,
pageBuilder: (context, state) {
return CustomTransitionPage(
child: SignUpScreen(
router: getIt<AuthRouter>(),
),
transitionsBuilder: _buildFadeTransition,
transitionDuration: _slowDuration,
);
},
),
],
);
}
@@ -12,11 +12,13 @@ import '../startup.dart';
class InitRustSDKTask extends LaunchTask {
const InitRustSDKTask({
this.customApplicationPath,
required this.isAnon,
required this.customApplicationPath,
});
// Customize the RustSDK initialization path
final Directory? customApplicationPath;
final bool isAnon;
@override
LaunchTaskType get type => LaunchTaskType.dataProcessing;
@@ -24,8 +26,16 @@ class InitRustSDKTask extends LaunchTask {
@override
Future<void> initialize(LaunchContext context) async {
final root = await getApplicationSupportDirectory();
final applicationPath = await appFlowyApplicationDataDirectory();
final dir = customApplicationPath ?? applicationPath;
// Only one anon user no matter what the cloud URL is
final applicationPath = isAnon
? await appFlowyAnonDirectory()
: await appFlowyApplicationDataDirectory();
final dir =
isAnon ? applicationPath : (customApplicationPath ?? applicationPath);
// Get device ID in parallel with path resolution
final deviceId = await getDeviceId();
// Pass the environment variables to the Rust SDK
@@ -35,6 +45,7 @@ class InitRustSDKTask extends LaunchTask {
dir.path,
applicationPath.path,
deviceId,
isAnon,
rustEnvs: context.config.rustEnvs,
);
await context.getIt<FlowySDK>().init(jsonEncode(env.toJson()));
@@ -49,7 +60,8 @@ AppFlowyConfiguration _makeAppFlowyConfiguration(
String appVersion,
String customAppPath,
String originAppPath,
String deviceId, {
String deviceId,
bool isAnon, {
required Map<String, String> rustEnvs,
}) {
final env = getIt<AppFlowyCloudSharedEnv>();
@@ -62,6 +74,7 @@ AppFlowyConfiguration _makeAppFlowyConfiguration(
platform: Platform.operatingSystem,
authenticator_type: env.authenticatorType.value,
appflowy_cloud_config: env.appflowyCloudConfig,
is_anon: isAnon,
envs: rustEnvs,
);
}
@@ -73,12 +86,19 @@ Future<Directory> appFlowyApplicationDataDirectory() async {
case IntegrationMode.develop:
final Directory documentsDir = await getApplicationSupportDirectory()
.then((directory) => directory.create());
return Directory(path.join(documentsDir.path, 'data_dev')).create();
return Directory(path.join(documentsDir.path, 'data_dev'));
case IntegrationMode.release:
final Directory documentsDir = await getApplicationSupportDirectory();
return Directory(path.join(documentsDir.path, 'data')).create();
return Directory(path.join(documentsDir.path, 'data'));
case IntegrationMode.unitTest:
case IntegrationMode.integrationTest:
return Directory(path.join(Directory.current.path, '.sandbox'));
}
}
/// The anon directory.
Future<Directory> appFlowyAnonDirectory() async {
final Directory documentsDir =
await getApplicationSupportDirectory().then((directory) => directory);
return Directory(path.join(documentsDir.path, 'anon'));
}
@@ -1,6 +1,4 @@
import 'package:appflowy/user/application/user_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/code.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
@@ -11,9 +9,7 @@ class AnonUserBloc extends Bloc<AnonUserEvent, AnonUserState> {
AnonUserBloc() : super(AnonUserState.initial()) {
on<AnonUserEvent>((event, emit) async {
await event.when(
initial: () async {
await _loadHistoricalUsers();
},
initial: () async {},
didLoadAnonUsers: (List<UserProfilePB> anonUsers) {
emit(state.copyWith(anonUsers: anonUsers));
},
@@ -24,20 +20,6 @@ class AnonUserBloc extends Bloc<AnonUserEvent, AnonUserState> {
);
});
}
Future<void> _loadHistoricalUsers() async {
final result = await UserBackendService.getAnonUser();
result.fold(
(anonUser) {
add(AnonUserEvent.didLoadAnonUsers([anonUser]));
},
(error) {
if (error.code != ErrorCode.RecordNotFound) {
Log.error(error);
}
},
);
}
}
@freezed
@@ -94,10 +94,10 @@ class AppFlowyCloudAuthService implements AuthService {
}
@override
Future<FlowyResult<UserProfilePB, FlowyError>> signUpAsGuest({
Future<void> signUpAsGuest({
Map<String, String> params = const {},
}) async {
return _backendAuthService.signUpAsGuest();
await _backendAuthService.signUpAsGuest();
}
@override
@@ -29,7 +29,16 @@ class AppFlowyCloudMockAuthService implements AuthService {
required String password,
Map<String, String> params = const {},
}) async {
throw UnimplementedError();
final request = SignUpPayloadPB.create()
..name = name
..email = email
..password = password
..authType = _appFlowyAuthService.authType
..deviceId = await getDeviceId();
final response = await UserEventSignUp(request).send().then(
(value) => value,
);
return response;
}
@override
@@ -89,10 +98,10 @@ class AppFlowyCloudMockAuthService implements AuthService {
}
@override
Future<FlowyResult<UserProfilePB, FlowyError>> signUpAsGuest({
Future<void> signUpAsGuest({
Map<String, String> params = const {},
}) async {
return _appFlowyAuthService.signUpAsGuest();
await _appFlowyAuthService.signUpAsGuest();
}
@override
@@ -61,7 +61,7 @@ abstract class AuthService {
/// - `params`: Additional parameters for guest registration (optional).
///
/// Returns a default [UserProfilePB].
Future<FlowyResult<UserProfilePB, FlowyError>> signUpAsGuest({
Future<void> signUpAsGuest({
Map<String, String> params,
});
@@ -1,3 +1,4 @@
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/user/application/auth/auth_service.dart';
import 'package:appflowy/user/application/user_service.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
@@ -5,12 +6,8 @@ import 'package:appflowy_backend/protobuf/flowy-error/code.pbenum.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/auth.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart'
show SignInPayloadPB, SignUpPayloadPB, UserProfilePB;
show SignInPayloadPB, UserProfilePB;
import 'package:appflowy_result/appflowy_result.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/uuid.dart';
import '../../../generated/locale_keys.g.dart';
import 'device_id.dart';
class BackendAuthService implements AuthService {
@@ -40,16 +37,17 @@ class BackendAuthService implements AuthService {
required String password,
Map<String, String> params = const {},
}) async {
final request = SignUpPayloadPB.create()
..name = name
..email = email
..password = password
..authType = authType
..deviceId = await getDeviceId();
final response = await UserEventSignUp(request).send().then(
(value) => value,
);
return response;
throw UnimplementedError();
// final request = SignUpPayloadPB.create()
// ..name = name
// ..email = email
// ..password = password
// ..authType = authType
// ..deviceId = await getDeviceId();
// final response = await UserEventSignUp(request).send().then(
// (value) => value,
// );
// return response;
}
@override
@@ -61,24 +59,10 @@ class BackendAuthService implements AuthService {
}
@override
Future<FlowyResult<UserProfilePB, FlowyError>> signUpAsGuest({
Future<void> signUpAsGuest({
Map<String, String> params = const {},
}) async {
const password = "Guest!@123456";
final uid = uuid();
final userEmail = "$uid@appflowy.io";
final request = SignUpPayloadPB.create()
..name = LocaleKeys.defaultUsername.tr()
..email = userEmail
..password = password
// When sign up as guest, the auth type is always local.
..authType = AuthenticatorPB.Local
..deviceId = await getDeviceId();
final response = await UserEventSignUp(request).send().then(
(value) => value,
);
return response;
await runAppFlowy(isAnon: true);
}
@override
@@ -251,16 +251,7 @@ class SignInBloc extends Bloc<SignInEvent, SignInState> {
),
);
final result = await authService.signUpAsGuest();
emit(
result.fold(
(userProfile) => state.copyWith(
isSubmitting: false,
successOrFail: FlowyResult.success(userProfile),
),
(error) => _stateFromCode(error),
),
);
await authService.signUpAsGuest();
}
SignInState _stateFromCode(FlowyError error) {
@@ -17,14 +17,14 @@ void handleOpenWorkspaceError(BuildContext context, FlowyError error) {
case ErrorCode.InvalidEncryptSecret:
case ErrorCode.NetworkError:
showToastNotification(
context,
message: error.msg,
type: ToastificationType.error,
);
break;
default:
showToastNotification(
context,
message: error.msg,
type: ToastificationType.error,
callbacks: ToastificationCallbacks(
Loaded 100 of 207 files, more files were not shown because too many files have changed in this diff. Show more