Compare commits

...
Author SHA1 Message Date
Nathan 954aa48f52 chore: bump lai commit 2025-03-19 14:17:17 +08:00
Richard Shiue 461ac91b32 fix: continue writing empty text case (#7574) 2025-03-19 14:13:20 +08:00
Nathan.fooo 8a9cc278ec Merge pull request #7573 from AppFlowy-IO/rename_plugin
chore: rename the local ai plugin
2025-03-19 11:29:23 +08:00
Morn 9db87944f2 fix: toolbar tooltip message is incorrect on Windows (#7572)
* fix: some toolbar text display error

* chore: change string id to enum string id
2025-03-19 11:23:07 +08:00
Nathan 9230981e54 chore: remove test 2025-03-19 10:59:11 +08:00
Nathan 72b13dd941 chore: adjust UI 2025-03-19 10:48:30 +08:00
FakhriAzzouz e6b0c8ff05 chore: update Arabic translations (#7571)
* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦

* chore: update translations with Fink 🐦
2025-03-19 10:45:57 +08:00
Nathan f0d967f0e4 chore: rename the local ai plugin 2025-03-19 10:23:38 +08:00
Morn 85b9aab015 chore: update CHANGELOG.md (#7569) 2025-03-18 18:46:07 +08:00
Morn 69571f668c fix: some launch review issues (#7566)
* chore: adjust some toolbar text

* chore: change the icons in turn-into menu

* chore: change the icon in color menu

* fix: keep selection after doing some changes from toolbar

* fix: color menu displaying error

* fix: wrong filter logic in toolbar suggestion menu

* fix: some launch review issues

* fix: test errors
2025-03-18 18:45:31 +08:00
Lucas a89dd87c16 fix: optimize cover title position offset calculation (#7568)
* fix: optimize cover title position offset calculation

* feat: ingore shift+enter in callout/quote and fallback to system behavior
2025-03-18 17:53:21 +08:00
Richard Shiue 22b03eee29 chore: implement ai writer history (#7523)
* chore: implement ai writer history

* chore: pass hitosyr
2025-03-18 17:14:20 +08:00
Nathan.fooo e3ea3fcdfa Merge pull request #7570 from AppFlowy-IO/update_local_ai_translation
chore: update local ai translation
2025-03-18 16:43:39 +08:00
Nathan ccfbde9a92 chore: update local ai translation 2025-03-18 16:42:29 +08:00
Nathan.fooo 7358860bfc Merge pull request #7567 from AppFlowy-IO/fix_release_crash_2
chore: update commit
2025-03-18 16:07:25 +08:00
Nathan 17b355197c chore: update commit 2025-03-18 15:54:16 +08:00
Nathan.fooo aa7e50cc6c Merge pull request #7565 from AppFlowy-IO/update_translation
chore: update translation
2025-03-18 13:00:33 +08:00
Nathan 69ce105806 chore: update translation 2025-03-18 12:54:45 +08:00
Lucas cafdfcca51 feat: add download button in file block (#7562) 2025-03-18 11:31:18 +08:00
a8c5c9c34e chore(i18n): add and fine-tune ko-KR translations (#7548)
* feat(translations): reset hard Korean translation

Co-authored-by: NavyStack <navystack@askfront.com>
Co-authored-by: FVOCI <150913557+fvoci@users.noreply.github.com>

* i18n(ko-KR): Add new translations and fine-tune existing ones

Co-authored-by: NavyStack <navystack@askfront.com>
Co-authored-by: FVOCI <150913557+fvoci@users.noreply.github.com>

---------

Co-authored-by: fvoci <karl@hwan.dev>
Co-authored-by: FVOCI <150913557+fvoci@users.noreply.github.com>
2025-03-18 10:30:51 +08:00
Morn 6dd83675fc fix: toolbar launch review issues (#7532)
* fix: some launch review issues

* fix: some launch review issues

* fix: color picker position error

* fix: redesign the dropdown arrow and padding

* feat: implement toolbar button state

* fix: keep custom color not changed

* feat: revamp color icon in toolbar

* fix: correct toolbar position & add animation for toolbar

* fix: ajust toolbar animation parameters

* chore: adjust some UI values

* fix: keep selection after turn into

* fix: hover color on toolbar is wrong in dark mode

* fix: toolbar icon color in dark mode
2025-03-17 18:03:23 +08:00
Lucas b65fad6214 chore: update template link url (#7557) 2025-03-17 16:57:02 +08:00
Lucas 884046ba3f fix: first added cover might be invisible (#7555) 2025-03-17 15:41:54 +08:00
56 changed files with 4421 additions and 900 deletions

No files matched your search

+14
View File
@@ -1,4 +1,18 @@
# Release Notes
## Version 0.8.7 - 18/03/2025
### New Features
- Made local AI free and integrated with Ollama
- Supported nested lists within callout and quote blocks
- Revamped the document's floating toolbar and added Turn Into
- Enabled custom icons in callout blocks
### Bug Fixes
- Fixed occasional incorrect positioning of the slash menu
- Improved AI Chat and AI Writers with various bug fixes
- Adjusted the columns block to match the width of the editor
- Fixed a potential segfault caused by infinite recursion in the trash view
- Resolved an issue where the first added cover might be invisible
- Fixed adding cover images via Unsplash
## Version 0.8.6 - 06/03/2025
### Bug Fixes
- Fix the incorrect title positioning when adjusting the document width setting
@@ -76,13 +76,12 @@ void main() {
LocaleKeys.document_slashMenu_name_heading1.tr(): HeadingBlockKeys.type,
LocaleKeys.document_slashMenu_name_heading2.tr(): HeadingBlockKeys.type,
LocaleKeys.document_slashMenu_name_heading3.tr(): HeadingBlockKeys.type,
LocaleKeys.document_slashMenu_name_bulletedList.tr():
LocaleKeys.editor_bulletedListShortForm.tr():
BulletedListBlockKeys.type,
LocaleKeys.document_slashMenu_name_numberedList.tr():
LocaleKeys.editor_numberedListShortForm.tr():
NumberedListBlockKeys.type,
LocaleKeys.document_slashMenu_name_quote.tr(): QuoteBlockKeys.type,
LocaleKeys.document_slashMenu_name_todoList.tr():
TodoListBlockKeys.type,
LocaleKeys.editor_checkbox.tr(): TodoListBlockKeys.type,
LocaleKeys.document_slashMenu_name_callout.tr(): CalloutBlockKeys.type,
LocaleKeys.document_slashMenu_name_text.tr(): ParagraphBlockKeys.type,
};
@@ -117,13 +116,12 @@ void main() {
LocaleKeys.document_slashMenu_name_heading1.tr(): HeadingBlockKeys.type,
LocaleKeys.document_slashMenu_name_heading2.tr(): HeadingBlockKeys.type,
LocaleKeys.document_slashMenu_name_heading3.tr(): HeadingBlockKeys.type,
LocaleKeys.document_slashMenu_name_bulletedList.tr():
LocaleKeys.editor_bulletedListShortForm.tr():
BulletedListBlockKeys.type,
LocaleKeys.document_slashMenu_name_numberedList.tr():
LocaleKeys.editor_numberedListShortForm.tr():
NumberedListBlockKeys.type,
LocaleKeys.document_slashMenu_name_quote.tr(): QuoteBlockKeys.type,
LocaleKeys.document_slashMenu_name_todoList.tr():
TodoListBlockKeys.type,
LocaleKeys.editor_checkbox.tr(): TodoListBlockKeys.type,
LocaleKeys.document_slashMenu_name_callout.tr(): CalloutBlockKeys.type,
LocaleKeys.document_slashMenu_name_text.tr(): ParagraphBlockKeys.type,
};
@@ -42,7 +42,7 @@ void main() {
// tap the inline math equation button
final inlineMathEquationButton = find.text(
LocaleKeys.editor_mathEquationShortForm.tr(),
LocaleKeys.document_toolbar_equation.tr(),
);
await tester.tapButton(inlineMathEquationButton);
@@ -106,11 +106,6 @@ void main() {
);
await tester.tapButton(moreOptionButton);
// expect to the see the inline math equation button is highlighted
expect(
tester.widget<FlowySvg>(inlineMathEquationButton).color != null,
isTrue,
);
// cancel the format
await tester.tapButton(inlineMathEquationButton);
@@ -3,6 +3,7 @@ import 'dart:ffi';
import 'dart:isolate';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/operations/ai_writer_entities.dart';
import 'package:appflowy/shared/list_extension.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart';
@@ -19,6 +20,8 @@ abstract class AIRepository {
String? objectId,
required String text,
PredefinedFormat? format,
List<String> sourceIds = const [],
List<AiWriterRecord> history = const [],
required CompletionTypePB completionType,
required Future<void> Function() onStart,
required Future<void> Function(String text) onProcess,
@@ -34,6 +37,7 @@ class AppFlowyAIService implements AIRepository {
required String text,
PredefinedFormat? format,
List<String> sourceIds = const [],
List<AiWriterRecord> history = const [],
required CompletionTypePB completionType,
required Future<void> Function() onStart,
required Future<void> Function(String text) onProcess,
@@ -47,6 +51,8 @@ class AppFlowyAIService implements AIRepository {
onError: onError,
);
final records = history.map((record) => record.toPB()).toList();
final payload = CompleteTextPB(
text: text,
completionType: completionType,
@@ -57,6 +63,7 @@ class AppFlowyAIService implements AIRepository {
if (objectId != null) objectId,
...sourceIds,
].unique(),
history: records,
);
return AIEventCompleteText(payload).send().fold(
@@ -22,15 +22,16 @@ import 'package:appflowy/workspace/presentation/home/af_focus_manager.dart';
import 'package:appflowy_editor/appflowy_editor.dart' hide QuoteBlockKeys;
import 'package:collection/collection.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:universal_platform/universal_platform.dart';
import 'editor_plugins/desktop_toolbar/desktop_floating_toolbar.dart';
import 'editor_plugins/toolbar_item/custom_format_toolbar_items.dart';
import 'editor_plugins/toolbar_item/custom_hightlight_color_toolbar_item.dart';
import 'editor_plugins/toolbar_item/custom_link_toolbar_item.dart';
import 'editor_plugins/toolbar_item/custom_placeholder_toolbar_item.dart';
import 'editor_plugins/toolbar_item/custom_text_align_toolbar_item.dart';
import 'editor_plugins/toolbar_item/custom_text_color_toolbar_item.dart';
import 'editor_plugins/toolbar_item/more_option_toolbar_item.dart';
@@ -93,14 +94,22 @@ class _AppFlowyEditorPageState extends State<AppFlowyEditorPage>
final List<ToolbarItem> toolbarItems = [
improveWritingItem,
group0PaddingItem,
aiWriterItem,
customTextHeadingItem,
buildPaddingPlaceholderItem(
1,
isActive: onlyShowInSingleTextTypeSelectionAndExcludeTable,
),
...customMarkdownFormatItems,
group1PaddingItem,
customTextColorItem,
group1PaddingItem,
customHighlightColorItem,
customInlineCodeItem,
suggestionsItem,
customLinkItem,
group4PaddingItem,
customTextAlignItem,
moreOptionItem,
];
@@ -426,12 +435,19 @@ class _AppFlowyEditorPageState extends State<AppFlowyEditorPage>
padding: EdgeInsets.symmetric(horizontal: 6),
style: FloatingToolbarStyle(
backgroundColor: Theme.of(context).cardColor,
toolbarActiveColor: Color(0xffe0f8fd),
toolbarElevation: 10,
),
items: toolbarItems,
decoration: context.getPopoverDecoration(
borderRadius: BorderRadius.circular(6),
decoration: ShapeDecoration(
color: Theme.of(context).cardColor,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
),
toolbarBuilder: (context, child) => DesktopFloatingToolbar(
editorState: editorState,
child: child,
),
placeHolderBuilder: (_) => customPlaceholderItem,
editorState: editorState,
editorScrollController: editorScrollController,
textDirection: textDirection,
@@ -259,11 +259,13 @@ class BlockActionOptionCubit extends Cubit<BlockActionOptionState> {
emit(BlockActionOptionState()); // Emit a new state to trigger UI update
}
Future<bool> turnIntoBlock(
static Future<bool> turnIntoBlock(
String type,
Node node, {
Node node,
EditorState editorState, {
int? level,
String? currentViewId,
bool keepSelection = false,
}) async {
final selection = editorState.selection;
if (selection == null) {
@@ -287,6 +289,8 @@ class BlockActionOptionCubit extends Cubit<BlockActionOptionState> {
type: toType,
selectedNodes: selectedNodes,
level: level,
editorState: editorState,
afterSelection: keepSelection ? selection : null,
)) {
return true;
}
@@ -298,6 +302,7 @@ class BlockActionOptionCubit extends Cubit<BlockActionOptionState> {
selectedNodes: selectedNodes,
selection: selection,
currentViewId: currentViewId,
editorState: editorState,
)) {
return true;
}
@@ -344,6 +349,7 @@ class BlockActionOptionCubit extends Cubit<BlockActionOptionState> {
insertedNode,
);
transaction.deleteNodes(selectedNodes);
if (keepSelection) transaction.afterSelection = selection;
await editorState.apply(transaction);
return true;
@@ -353,7 +359,7 @@ class BlockActionOptionCubit extends Cubit<BlockActionOptionState> {
///
/// Returns the altered [Node] with the delta as the Views' name.
///
Future<Node> _handleSubPageNode(Node node, Node subPageNode) async {
static Future<Node> _handleSubPageNode(Node node, Node subPageNode) async {
if (subPageNode.type != SubPageBlockKeys.type) {
return node;
}
@@ -370,7 +376,7 @@ class BlockActionOptionCubit extends Cubit<BlockActionOptionState> {
/// Returns the [Delta] from a SubPage [Node], where the
/// [Delta] is the views' name.
///
Future<Delta?> _deltaFromSubPageNode(Node node) async {
static Future<Delta?> _deltaFromSubPageNode(Node node) async {
if (node.type != SubPageBlockKeys.type) {
return null;
}
@@ -400,9 +406,10 @@ class BlockActionOptionCubit extends Cubit<BlockActionOptionState> {
// - paragraph 1
// - paragraph 2
// when turning "Toggle Heading 1" into toggle heading, the bulleted items will be moved into the toggle heading
Future<bool> turnIntoSingleToggleHeading({
static Future<bool> turnIntoSingleToggleHeading({
required String type,
required List<Node> selectedNodes,
required EditorState editorState,
int? level,
Delta? delta,
Selection? afterSelection,
@@ -492,11 +499,12 @@ class BlockActionOptionCubit extends Cubit<BlockActionOptionState> {
return true;
}
Future<bool> turnIntoPage({
static Future<bool> turnIntoPage({
required String type,
required List<Node> selectedNodes,
required Selection selection,
required String currentViewId,
required EditorState editorState,
}) async {
if (type != SubPageBlockKeys.type || selectedNodes.isEmpty) {
return false;
@@ -552,7 +560,7 @@ class BlockActionOptionCubit extends Cubit<BlockActionOptionState> {
return true;
}
Future<String> _extractNameFromNodes(List<Node>? nodes) async {
static Future<String> _extractNameFromNodes(List<Node>? nodes) async {
if (nodes == null || nodes.isEmpty) {
return '';
}
@@ -602,7 +610,7 @@ class BlockActionOptionCubit extends Cubit<BlockActionOptionState> {
return name.substring(0, name.length > 30 ? 30 : name.length);
}
List<String> _extractChildViewIds(List<Node> nodes) {
static List<String> _extractChildViewIds(List<Node> nodes) {
final List<String> viewIds = [];
for (final node in nodes) {
if (node.type == SubPageBlockKeys.type) {
@@ -237,12 +237,13 @@ class _TurnInfoButton extends StatelessWidget {
leftIcon: FlowySvg(leftIcon),
rightIcon: rightIcon,
itemHeight: ActionListSizes.itemHeight,
onTap: () => context.read<BlockActionOptionCubit>().turnIntoBlock(
type,
node,
level: level,
currentViewId: getIt<MenuSharedState>().latestOpenView?.id,
),
onTap: () => BlockActionOptionCubit.turnIntoBlock(
type,
node,
context.read<BlockActionOptionCubit>().editorState,
level: level,
currentViewId: getIt<MenuSharedState>().latestOpenView?.id,
),
);
}
@@ -273,40 +274,40 @@ class _TurnInfoButton extends StatelessWidget {
FlowySvgData _buildLeftIcon(String type, {int? level}) {
if (type == ParagraphBlockKeys.type) {
return FlowySvgs.slash_menu_icon_text_s;
return FlowySvgs.type_text_m;
} else if (type == HeadingBlockKeys.type) {
switch (level) {
case 1:
return FlowySvgs.slash_menu_icon_h1_s;
return FlowySvgs.type_h1_m;
case 2:
return FlowySvgs.slash_menu_icon_h2_s;
return FlowySvgs.type_h2_m;
case 3:
return FlowySvgs.slash_menu_icon_h3_s;
return FlowySvgs.type_h3_m;
default:
return FlowySvgs.slash_menu_icon_text_s;
return FlowySvgs.type_text_m;
}
} else if (type == QuoteBlockKeys.type) {
return FlowySvgs.slash_menu_icon_quote_s;
return FlowySvgs.type_quote_m;
} else if (type == BulletedListBlockKeys.type) {
return FlowySvgs.slash_menu_icon_bulleted_list_s;
return FlowySvgs.type_bulleted_list_m;
} else if (type == NumberedListBlockKeys.type) {
return FlowySvgs.slash_menu_icon_numbered_list_s;
return FlowySvgs.type_numbered_list_m;
} else if (type == TodoListBlockKeys.type) {
return FlowySvgs.slash_menu_icon_checkbox_s;
return FlowySvgs.type_todo_m;
} else if (type == CalloutBlockKeys.type) {
return FlowySvgs.slash_menu_icon_callout_s;
return FlowySvgs.type_callout_m;
} else if (type == SubPageBlockKeys.type) {
return FlowySvgs.icon_document_s;
} else if (type == ToggleListBlockKeys.type) {
switch (level) {
case 1:
return FlowySvgs.toggle_heading1_s;
return FlowySvgs.type_toggle_h1_m;
case 2:
return FlowySvgs.toggle_heading2_s;
return FlowySvgs.type_toggle_h2_m;
case 3:
return FlowySvgs.toggle_heading3_s;
return FlowySvgs.type_toggle_h3_m;
default:
return FlowySvgs.slash_menu_icon_toggle_s;
return FlowySvgs.type_toggle_list_m;
}
}
@@ -334,11 +335,11 @@ class _TurnInfoButton extends StatelessWidget {
case QuoteBlockKeys.type:
return LocaleKeys.document_slashMenu_name_quote.tr();
case BulletedListBlockKeys.type:
return LocaleKeys.document_slashMenu_name_bulletedList.tr();
return LocaleKeys.editor_bulletedListShortForm.tr();
case NumberedListBlockKeys.type:
return LocaleKeys.document_slashMenu_name_numberedList.tr();
return LocaleKeys.editor_numberedListShortForm.tr();
case TodoListBlockKeys.type:
return LocaleKeys.document_slashMenu_name_todoList.tr();
return LocaleKeys.editor_checkbox.tr();
case CalloutBlockKeys.type:
return LocaleKeys.document_slashMenu_name_callout.tr();
case SubPageBlockKeys.type:
@@ -346,13 +347,13 @@ class _TurnInfoButton extends StatelessWidget {
case ToggleListBlockKeys.type:
switch (level) {
case 1:
return LocaleKeys.document_slashMenu_name_toggleHeading1.tr();
return LocaleKeys.editor_toggleHeading1ShortForm.tr();
case 2:
return LocaleKeys.document_slashMenu_name_toggleHeading2.tr();
return LocaleKeys.editor_toggleHeading2ShortForm.tr();
case 3:
return LocaleKeys.document_slashMenu_name_toggleHeading3.tr();
return LocaleKeys.editor_toggleHeading3ShortForm.tr();
default:
return LocaleKeys.document_slashMenu_name_toggleList.tr();
return LocaleKeys.editor_toggleListShortForm.tr();
}
}
@@ -61,7 +61,7 @@ class _AiWriterToolbarActionListState extends State<AiWriterToolbarActionList> {
return AppFlowyPopover(
controller: popoverController,
direction: PopoverDirection.bottomWithLeftAligned,
offset: const Offset(-8.0, 2.0),
offset: const Offset(0, 2.0),
onOpen: () => keepEditorFocusNotifier.increase(),
onClose: () {
setState(() {
@@ -120,7 +120,7 @@ class _AiWriterToolbarActionListState extends State<AiWriterToolbarActionList> {
Widget buildChild(BuildContext context) {
final iconColor = Theme.of(context).iconTheme.color;
final child = FlowyIconButton(
width: 52,
width: 48,
height: 32,
isSelected: isSelected,
hoverColor: EditorStyleCustomizer.toolbarHoverColor(context),
@@ -132,9 +132,10 @@ class _AiWriterToolbarActionListState extends State<AiWriterToolbarActionList> {
size: Size.square(20),
color: iconColor,
),
HSpace(4),
FlowySvg(
FlowySvgs.toolbar_arrow_down_m,
size: Size.square(20),
size: Size(12, 20),
color: iconColor,
),
],
@@ -44,6 +44,7 @@ class AiWriterCubit extends Cubit<AiWriterState> {
final AppFlowyAIService _aiService;
final MarkdownTextRobot _textRobot;
final List<AiWriterRecord> records = [];
final ValueNotifier<List<String>> selectedSourcesNotifier;
(String, PredefinedFormat?)? _previousPrompt;
bool acceptReplacesOriginal = false;
@@ -66,6 +67,7 @@ class AiWriterCubit extends Cubit<AiWriterState> {
) async {
final command = AiWriterCommand.userQuestion;
final node = getAiWriterNode();
_previousPrompt = (prompt, format);
final stream = await _aiService.streamCompletion(
@@ -74,6 +76,7 @@ class AiWriterCubit extends Cubit<AiWriterState> {
format: format,
sourceIds: selectedSourcesNotifier.value,
completionType: command.toCompletionType(),
history: records,
onStart: () async {
final transaction = editorState.transaction;
final position =
@@ -87,6 +90,9 @@ class AiWriterCubit extends Cubit<AiWriterState> {
),
);
_textRobot.start(position: position);
records.add(
AiWriterRecord.user(content: prompt),
);
},
onProcess: (text) async {
await _textRobot.appendMarkdownText(
@@ -99,9 +105,15 @@ class AiWriterCubit extends Cubit<AiWriterState> {
attributes: ApplySuggestionFormatType.replace.attributes,
);
emit(ReadyAiWriterState(command, isFirstRun: false));
records.add(
AiWriterRecord.ai(content: _textRobot.markdownText),
);
},
onError: (error) async {
emit(ErrorAiWriterState(state.command, error: error));
records.add(
AiWriterRecord.ai(content: _textRobot.markdownText),
);
},
);
@@ -306,7 +318,7 @@ class AiWriterCubit extends Cubit<AiWriterState> {
end: cursorPosition,
).normalized;
String text = await editorState.getMarkdownInSelection(selection);
String text = (await editorState.getMarkdownInSelection(selection)).trim();
if (text.isEmpty) {
if (state is! ReadyAiWriterState) {
return;
@@ -337,6 +349,7 @@ class AiWriterCubit extends Cubit<AiWriterState> {
objectId: documentId,
text: text,
completionType: command.toCompletionType(),
history: records,
onStart: () async {
final transaction = editorState.transaction;
final position =
@@ -364,9 +377,15 @@ class AiWriterCubit extends Cubit<AiWriterState> {
);
emit(ReadyAiWriterState(command, isFirstRun: false));
}
records.add(
AiWriterRecord.ai(content: _textRobot.markdownText),
);
},
onError: (error) async {
emit(ErrorAiWriterState(command, error: error));
records.add(
AiWriterRecord.ai(content: _textRobot.markdownText),
);
},
);
if (stream != null) {
@@ -392,6 +411,7 @@ class AiWriterCubit extends Cubit<AiWriterState> {
objectId: documentId,
text: await editorState.getMarkdownInSelection(selection),
completionType: command.toCompletionType(),
history: records,
onStart: () async {
final transaction = editorState.transaction;
formatSelection(
@@ -429,10 +449,16 @@ class AiWriterCubit extends Cubit<AiWriterState> {
isFirstRun: false,
),
);
records.add(
AiWriterRecord.ai(content: _textRobot.markdownText),
);
}
},
onError: (error) async {
emit(ErrorAiWriterState(command, error: error));
records.add(
AiWriterRecord.ai(content: _textRobot.markdownText),
);
},
);
if (stream != null) {
@@ -456,6 +482,7 @@ class AiWriterCubit extends Cubit<AiWriterState> {
objectId: documentId,
text: await editorState.getMarkdownInSelection(selection),
completionType: command.toCompletionType(),
history: records,
onStart: () async {},
onProcess: (text) async {
if (state case final GeneratingAiWriterState generatingState) {
@@ -477,9 +504,17 @@ class AiWriterCubit extends Cubit<AiWriterState> {
markdownText: generatingState.markdownText,
),
);
records.add(
AiWriterRecord.ai(content: generatingState.markdownText),
);
}
},
onError: (error) async {
if (state case final GeneratingAiWriterState generatingState) {
records.add(
AiWriterRecord.ai(content: generatingState.markdownText),
);
}
emit(ErrorAiWriterState(command, error: error));
},
);
@@ -2,6 +2,7 @@ import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy_backend/protobuf/flowy-ai/protobuf.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import '../ai_writer_block_component.dart';
@@ -90,7 +91,7 @@ enum AiWriterCommand {
FlowySvgData get icon => switch (this) {
userQuestion => FlowySvgs.ai_sparks_s,
explain => FlowySvgs.ai_explain_s,
explain => FlowySvgs.ai_explain_m,
// summarize => FlowySvgs.ai_summarize_s,
continueWriting || improveWriting => FlowySvgs.ai_improve_writing_s,
fixSpellingAndGrammar => FlowySvgs.ai_fix_spelling_grammar_s,
@@ -120,3 +121,40 @@ enum ApplySuggestionFormatType {
Map<String, dynamic> get attributes => {AiWriterBlockKeys.suggestion: value};
}
enum AiRole {
user,
system,
ai,
}
class AiWriterRecord extends Equatable {
const AiWriterRecord({
required this.role,
required this.content,
});
const AiWriterRecord.user({
required this.content,
}) : role = AiRole.user;
const AiWriterRecord.ai({
required this.content,
}) : role = AiRole.ai;
final AiRole role;
final String content;
@override
List<Object> get props => [role, content];
CompletionRecordPB toPB() {
return CompletionRecordPB(
content: content,
role: switch (role) {
AiRole.user => ChatMessageTypePB.User,
AiRole.system || AiRole.ai => ChatMessageTypePB.System,
},
);
}
}
@@ -30,6 +30,8 @@ class MarkdownTextRobot {
bool get hasAnyResult => _markdownText.isNotEmpty;
String get markdownText => _markdownText;
Selection? getInsertedSelection() {
final position = _insertPosition;
if (position == null) {
@@ -32,7 +32,8 @@ CharacterShortcutEventHandler _insertNewLineHandler = (editorState) async {
await editorState.deleteSelection(selection);
if (HardwareKeyboard.instance.isShiftPressed) {
await editorState.insertNewLine();
// ignore the shift+enter event, fallback to the default behavior
return false;
} else if (node.children.isEmpty) {
// insert a new paragraph within the callout block
final path = node.path.child(0);
@@ -1,6 +1,7 @@
import 'package:appflowy/mobile/application/page_style/document_page_style_bloc.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy/workspace/application/view/view_listener.dart';
import 'package:appflowy/workspace/application/view/view_service.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
@@ -19,9 +20,13 @@ class DocumentImmersiveCoverBloc
(event, emit) async {
await event.when(
initial: () async {
final latestView = await ViewBackendService.getView(view.id);
add(
DocumentImmersiveCoverEvent.updateCoverAndIcon(
view.cover,
latestView.fold(
(s) => s.cover,
(e) => view.cover,
),
EmojiIconData.fromViewIconPB(view.icon),
view.name,
),
@@ -0,0 +1,330 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
// ignore: implementation_imports
import 'package:appflowy_editor/src/editor/toolbar/desktop/items/utils/overlay_util.dart';
import 'package:flutter/material.dart';
class ColorPicker extends StatefulWidget {
const ColorPicker({
super.key,
required this.title,
required this.selectedColorHex,
required this.onSubmittedColorHex,
required this.colorOptions,
this.resetText,
this.customColorHex,
this.resetIconName,
this.showClearButton = false,
});
final String title;
final String? selectedColorHex;
final String? customColorHex;
final void Function(String? color, bool isCustomColor) onSubmittedColorHex;
final String? resetText;
final String? resetIconName;
final bool showClearButton;
final List<ColorOption> colorOptions;
@override
State<ColorPicker> createState() => _ColorPickerState();
}
class _ColorPickerState extends State<ColorPicker> {
final TextEditingController _colorHexController = TextEditingController();
final TextEditingController _colorOpacityController = TextEditingController();
@override
void initState() {
super.initState();
final selectedColorHex = widget.selectedColorHex,
customColorHex = widget.customColorHex;
_colorHexController.text =
_extractColorHex(customColorHex ?? selectedColorHex) ?? 'FFFFFF';
_colorOpacityController.text =
_convertHexToOpacity(customColorHex ?? selectedColorHex) ?? '100';
}
@override
Widget build(BuildContext context) {
return basicOverlay(
context,
width: 300,
height: 250,
children: [
EditorOverlayTitle(text: widget.title),
const SizedBox(height: 6),
widget.showClearButton &&
widget.resetText != null &&
widget.resetIconName != null
? ResetColorButton(
resetText: widget.resetText!,
resetIconName: widget.resetIconName!,
onPressed: (color) =>
widget.onSubmittedColorHex.call(color, false),
)
: const SizedBox.shrink(),
CustomColorItem(
colorController: _colorHexController,
opacityController: _colorOpacityController,
onSubmittedColorHex: (color) =>
widget.onSubmittedColorHex.call(color, true),
),
_buildColorItems(
widget.colorOptions,
widget.selectedColorHex,
),
],
);
}
Widget _buildColorItems(
List<ColorOption> options,
String? selectedColor,
) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: options
.map((e) => _buildColorItem(e, e.colorHex == selectedColor))
.toList(),
);
}
Widget _buildColorItem(ColorOption option, bool isChecked) {
return SizedBox(
height: 36,
child: TextButton.icon(
onPressed: () {
widget.onSubmittedColorHex(option.colorHex, false);
},
icon: SizedBox.square(
dimension: 12,
child: Container(
decoration: BoxDecoration(
color: option.colorHex.tryToColor(),
shape: BoxShape.circle,
),
),
),
style: buildOverlayButtonStyle(context),
label: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
option.name,
softWrap: false,
maxLines: 1,
overflow: TextOverflow.fade,
style: TextStyle(
color: Theme.of(context).textTheme.labelLarge?.color,
),
),
),
// checkbox
if (isChecked) const FlowySvg(FlowySvgs.toolbar_check_m),
],
),
),
);
}
String? _convertHexToOpacity(String? colorHex) {
if (colorHex == null) return null;
final opacityHex = colorHex.substring(2, 4);
final opacity = int.parse(opacityHex, radix: 16) / 2.55;
return opacity.toStringAsFixed(0);
}
String? _extractColorHex(String? colorHex) {
if (colorHex == null) return null;
return colorHex.substring(4);
}
}
class ResetColorButton extends StatelessWidget {
const ResetColorButton({
super.key,
required this.resetText,
required this.resetIconName,
required this.onPressed,
});
final Function(String? color) onPressed;
final String resetText;
final String resetIconName;
@override
Widget build(BuildContext context) {
return SizedBox(
width: double.infinity,
height: 32,
child: TextButton.icon(
onPressed: () => onPressed(null),
icon: EditorSvg(
name: resetIconName,
width: 13,
height: 13,
color: Theme.of(context).iconTheme.color,
),
label: Text(
resetText,
style: TextStyle(
color: Theme.of(context).hintColor,
),
textAlign: TextAlign.left,
),
style: ButtonStyle(
backgroundColor: WidgetStateProperty.resolveWith<Color>(
(Set<WidgetState> states) {
if (states.contains(WidgetState.hovered)) {
return Theme.of(context).hoverColor;
}
return Colors.transparent;
},
),
alignment: Alignment.centerLeft,
),
),
);
}
}
class CustomColorItem extends StatefulWidget {
const CustomColorItem({
super.key,
required this.colorController,
required this.opacityController,
required this.onSubmittedColorHex,
});
final TextEditingController colorController;
final TextEditingController opacityController;
final void Function(String color) onSubmittedColorHex;
@override
State<CustomColorItem> createState() => _CustomColorItemState();
}
class _CustomColorItemState extends State<CustomColorItem> {
@override
Widget build(BuildContext context) {
return ExpansionTile(
tilePadding: const EdgeInsets.only(left: 8),
shape: Border.all(
color: Colors.transparent,
), // remove the default border when it is expanded
title: Row(
children: [
// color sample box
SizedBox.square(
dimension: 12,
child: Container(
decoration: BoxDecoration(
color: Color(
int.tryParse(
_combineColorHexAndOpacity(
widget.colorController.text,
widget.opacityController.text,
),
) ??
0xFFFFFFFF,
),
shape: BoxShape.circle,
),
),
),
const SizedBox(width: 8),
Expanded(
child: Text(
AppFlowyEditorL10n.current.customColor,
style: Theme.of(context).textTheme.labelLarge,
// same style as TextButton.icon
),
),
],
),
children: [
const SizedBox(height: 6),
_customColorDetailsTextField(
labelText: AppFlowyEditorL10n.current.hexValue,
controller: widget.colorController,
// update the color sample box when the text changes
onChanged: (_) => setState(() {}),
onSubmitted: _submitCustomColorHex,
),
const SizedBox(height: 10),
_customColorDetailsTextField(
labelText: AppFlowyEditorL10n.current.opacity,
controller: widget.opacityController,
// update the color sample box when the text changes
onChanged: (_) => setState(() {}),
onSubmitted: _submitCustomColorHex,
),
const SizedBox(height: 6),
],
);
}
Widget _customColorDetailsTextField({
required String labelText,
required TextEditingController controller,
Function(String)? onChanged,
Function(String)? onSubmitted,
}) {
return Padding(
padding: const EdgeInsets.only(right: 3),
child: TextField(
controller: controller,
decoration: InputDecoration(
labelText: labelText,
border: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).colorScheme.outline,
),
),
),
style: Theme.of(context).textTheme.bodyMedium,
onChanged: onChanged,
onSubmitted: onSubmitted,
),
);
}
String _combineColorHexAndOpacity(String colorHex, String opacity) {
colorHex = _fixColorHex(colorHex);
opacity = _fixOpacity(opacity);
final opacityHex = (int.parse(opacity) * 2.55).round().toRadixString(16);
return '0x$opacityHex$colorHex';
}
String _fixColorHex(String colorHex) {
if (colorHex.length > 6) {
colorHex = colorHex.substring(0, 6);
}
if (int.tryParse(colorHex, radix: 16) == null) {
colorHex = 'FFFFFF';
}
return colorHex;
}
String _fixOpacity(String opacity) {
// if opacity is 0 - 99, return it
// otherwise return 100
final RegExp regex = RegExp('^(0|[1-9][0-9]?)');
if (regex.hasMatch(opacity)) {
return opacity;
} else {
return '100';
}
}
void _submitCustomColorHex(String value) {
final String color = _combineColorHexAndOpacity(
widget.colorController.text,
widget.opacityController.text,
);
widget.onSubmittedColorHex(color);
}
}
@@ -0,0 +1,79 @@
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/material.dart';
class DesktopFloatingToolbar extends StatefulWidget {
const DesktopFloatingToolbar({
super.key,
required this.editorState,
required this.child,
});
final EditorState editorState;
final Widget child;
@override
State<DesktopFloatingToolbar> createState() => _DesktopFloatingToolbarState();
}
class _DesktopFloatingToolbarState extends State<DesktopFloatingToolbar> {
EditorState get editorState => widget.editorState;
_Position? position;
@override
void initState() {
super.initState();
final selection = editorState.selection;
if (selection == null || selection.isCollapsed) {
return;
}
final selectionRect = editorState.selectionRects();
if (selectionRect.isEmpty) return;
position = calculateSelectionMenuOffset(selectionRect.first);
}
@override
Widget build(BuildContext context) {
if (position == null) return Container();
return Positioned(
left: position!.left,
top: position!.top,
right: position!.right,
child: widget.child,
);
}
_Position calculateSelectionMenuOffset(
Rect rect,
) {
const toolbarHeight = 40, topLimit = toolbarHeight + 8;
final bool isLongMenu = onlyShowInSingleSelectionAndTextType(editorState);
final menuWidth = isLongMenu ? 650.0 : 420.0;
final editorOffset =
editorState.renderBox?.localToGlobal(Offset.zero) ?? Offset.zero;
final editorSize = editorState.renderBox?.size ?? Size.zero;
final editorRect = editorOffset & editorSize;
final left = rect.left, leftStart = 50;
final top =
rect.top < topLimit ? rect.bottom + topLimit : rect.top - topLimit;
if (left + menuWidth > editorRect.right) {
return _Position(
editorRect.right - menuWidth,
top,
null,
);
} else if (rect.left - leftStart > 0) {
return _Position(rect.left - leftStart, top, null);
} else {
return _Position(rect.left, top, null);
}
}
}
class _Position {
_Position(this.left, this.top, this.right);
final double? left;
final double? top;
final double? right;
}
@@ -0,0 +1,87 @@
import 'package:flutter/material.dart';
class ToolbarAnimationWidget extends StatefulWidget {
const ToolbarAnimationWidget({
super.key,
required this.child,
this.duration = const Duration(milliseconds: 150),
this.beginOpacity = 0.0,
this.endOpacity = 1.0,
this.beginScaleFactor = 0.95,
this.endScaleFactor = 1.0,
});
final Widget child;
final Duration duration;
final double beginScaleFactor;
final double endScaleFactor;
final double beginOpacity;
final double endOpacity;
@override
State<ToolbarAnimationWidget> createState() => _ToolbarAnimationWidgetState();
}
class _ToolbarAnimationWidgetState extends State<ToolbarAnimationWidget>
with SingleTickerProviderStateMixin {
late AnimationController controller;
late Animation<double> fadeAnimation;
late Animation<double> scaleAnimation;
@override
void initState() {
super.initState();
controller = AnimationController(
vsync: this,
duration: widget.duration,
);
fadeAnimation = _buildFadeAnimation();
scaleAnimation = _buildScaleAnimation();
controller.forward();
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: controller,
builder: (_, child) => Opacity(
opacity: fadeAnimation.value,
child: Transform.scale(
scale: scaleAnimation.value,
child: child,
),
),
child: widget.child,
);
}
Animation<double> _buildFadeAnimation() {
return Tween<double>(
begin: widget.beginOpacity,
end: widget.endOpacity,
).animate(
CurvedAnimation(
parent: controller,
curve: Curves.easeInOut,
),
);
}
Animation<double> _buildScaleAnimation() {
return Tween<double>(
begin: widget.beginScaleFactor,
end: widget.endScaleFactor,
).animate(
CurvedAnimation(
parent: controller,
curve: Curves.easeInOut,
),
);
}
}
@@ -10,6 +10,7 @@ import 'package:appflowy/plugins/document/presentation/editor_plugins/copy_and_p
import 'package:appflowy/plugins/document/presentation/editor_plugins/file/file_util.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/presentation/home/toast.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/file_entities.pbenum.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:cross_file/cross_file.dart';
import 'package:desktop_drop/desktop_drop.dart';
@@ -95,6 +96,17 @@ enum FileUrlType {
return 2;
}
}
FileUploadTypePB toFileUploadTypePB() {
switch (this) {
case FileUrlType.local:
return FileUploadTypePB.LocalFile;
case FileUrlType.network:
return FileUploadTypePB.NetworkFile;
case FileUrlType.cloud:
return FileUploadTypePB.CloudFile;
}
}
}
Node fileNode({
@@ -1,15 +1,17 @@
import 'package:flutter/material.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/application/prelude.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/file/file_block.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/file/file_util.dart';
import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart';
import 'package:appflowy/workspace/application/settings/date_time/date_format_ext.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class FileBlockMenu extends StatefulWidget {
@@ -59,11 +61,37 @@ class _FileBlockMenuState extends State<FileBlockMenu> {
final dateFormat = context.read<AppearanceSettingsCubit>().state.dateFormat;
final urlType =
FileUrlType.fromIntValue(widget.node.attributes[FileBlockKeys.urlType]);
final fileUploadType = urlType.toFileUploadTypePB();
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
HoverButton(
itemHeight: 20,
leftIcon: const FlowySvg(FlowySvgs.download_s),
name: LocaleKeys.button_download.tr(),
onTap: () {
final userProfile = widget.editorState.document.root.context
?.read<DocumentBloc>()
.state
.userProfilePB;
final url = widget.node.attributes[FileBlockKeys.url];
final name = widget.node.attributes[FileBlockKeys.name];
if (url != null && name != null) {
final filePB = MediaFilePB(
url: url,
name: name,
uploadType: fileUploadType,
);
downloadMediaFile(
context,
filePB,
userProfile: userProfile,
);
}
},
),
const VSpace(4),
HoverButton(
itemHeight: 20,
leftIcon: const FlowySvg(FlowySvgs.edit_s),
@@ -188,49 +188,65 @@ class _DocumentCoverWidgetState extends State<DocumentCoverWidget> {
onChangeCover: (type, details) =>
_saveIconOrCover(cover: (type, details)),
),
_buildCoverIcon(
context,
constraints,
offset,
),
_buildAlignedCoverIcon(context),
],
),
Padding(
padding: EdgeInsets.fromLTRB(offset, 0, offset, 12),
child: MouseRegion(
onEnter: (event) => isCoverTitleHovered.value = true,
onExit: (event) => isCoverTitleHovered.value = false,
child: CoverTitle(
view: widget.view,
),
),
),
_buildAlignedTitle(context),
],
);
},
);
}
Widget _buildCoverIcon(
BuildContext context,
BoxConstraints constraints,
double offset,
) {
if (!hasIcon || offset == 0) {
Widget _buildAlignedTitle(BuildContext context) {
return Center(
child: Container(
constraints: BoxConstraints(
maxWidth: widget.editorState.editorStyle.maxWidth ?? double.infinity,
),
padding: widget.editorState.editorStyle.padding +
const EdgeInsets.symmetric(horizontal: 44),
child: MouseRegion(
onEnter: (event) => isCoverTitleHovered.value = true,
onExit: (event) => isCoverTitleHovered.value = false,
child: CoverTitle(
view: widget.view,
),
),
),
);
}
Widget _buildAlignedCoverIcon(BuildContext context) {
if (!hasIcon) {
return const SizedBox.shrink();
}
return Positioned(
// if hasCover, there shouldn't be icons present so the icon can
// be closer to the bottom.
left: offset,
bottom: hasCover ? kToolbarHeight - kIconHeight / 2 : kToolbarHeight,
child: DocumentIcon(
editorState: widget.editorState,
node: widget.node,
icon: viewIcon,
documentId: view.id,
onChangeIcon: (icon) => _saveIconOrCover(icon: icon),
left: 0,
right: 0,
child: Center(
child: Container(
constraints: BoxConstraints(
maxWidth:
widget.editorState.editorStyle.maxWidth ?? double.infinity,
),
padding: widget.editorState.editorStyle.padding +
const EdgeInsets.symmetric(horizontal: 44),
child: Row(
children: [
DocumentIcon(
editorState: widget.editorState,
node: widget.node,
icon: viewIcon,
documentId: view.id,
onChangeIcon: (icon) => _saveIconOrCover(icon: icon),
),
Spacer(),
],
),
),
),
);
}
@@ -30,8 +30,8 @@ CharacterShortcutEventHandler _insertNewLineHandler = (editorState) async {
await editorState.deleteSelection(selection);
if (HardwareKeyboard.instance.isShiftPressed) {
await editorState.insertNewLine();
return true;
// ignore the shift+enter event, fallback to the default behavior
return false;
} else if (node.children.isEmpty &&
selection.endIndex == node.delta?.length) {
// insert a new paragraph within the callout block
@@ -15,7 +15,7 @@ final _keywords = [
];
final todoListSlashMenuItem = SelectionMenuItem(
getName: () => LocaleKeys.document_slashMenu_name_todoList.tr(),
getName: () => LocaleKeys.editor_checkbox.tr(),
keywords: _keywords,
handler: (editorState, _, __) async => insertCheckboxAfterSelection(
editorState,
@@ -47,15 +47,12 @@ Future<void> _formatGreaterToToggleHeading(
delta = delta.compose(Delta()..delete(_greater.length));
// if the previous block is heading block, convert it to toggle heading block
if (type == HeadingBlockKeys.type && level != null) {
final cubit = BlockActionOptionCubit(
editorState: editorState,
blockComponentBuilder: {},
);
await cubit.turnIntoSingleToggleHeading(
await BlockActionOptionCubit.turnIntoSingleToggleHeading(
type: ToggleListBlockKeys.type,
selectedNodes: [node],
level: level,
delta: delta,
editorState: editorState,
afterSelection: afterSelection,
);
return;
@@ -98,7 +95,8 @@ CharacterShortcutEvent insertChildNodeInsideToggleList = CharacterShortcutEvent(
}
final slicedDelta = delta.slice(selection.start.offset);
final transaction = editorState.transaction;
final collapsed = node.attributes[ToggleListBlockKeys.collapsed] as bool;
final bool collapsed =
node.attributes[ToggleListBlockKeys.collapsed] ?? false;
if (collapsed) {
// if the delta is empty, clear the format
if (delta.isEmpty) {
@@ -1,32 +1,39 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_page.dart';
import 'package:appflowy/plugins/document/presentation/editor_style.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
// ignore: implementation_imports
import 'package:appflowy_editor/src/editor/toolbar/desktop/items/utils/tooltip_util.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/style_widget/icon_button.dart';
import 'package:flutter/material.dart';
import 'custom_placeholder_toolbar_item.dart';
import 'toolbar_id_enum.dart';
final List<ToolbarItem> customMarkdownFormatItems = [
_FormatToolbarItem(
id: 'bold',
id: ToolbarId.bold,
name: 'bold',
svg: FlowySvgs.toolbar_bold_m,
),
group1PaddingItem,
_FormatToolbarItem(
id: 'underline',
id: ToolbarId.underline,
name: 'underline',
svg: FlowySvgs.toolbar_underline_m,
),
group1PaddingItem,
_FormatToolbarItem(
id: 'italic',
id: ToolbarId.italic,
name: 'italic',
svg: FlowySvgs.toolbar_inline_italic_m,
),
];
final ToolbarItem customInlineCodeItem = _FormatToolbarItem(
id: 'code',
id: ToolbarId.code,
name: 'code',
svg: FlowySvgs.toolbar_inline_code_m,
group: 2,
@@ -34,12 +41,12 @@ final ToolbarItem customInlineCodeItem = _FormatToolbarItem(
class _FormatToolbarItem extends ToolbarItem {
_FormatToolbarItem({
required String id,
required ToolbarId id,
required String name,
required FlowySvgData svg,
super.group = 1,
}) : super(
id: 'editor.$id',
id: id.id,
isActive: showInAnyTextType,
builder: (
context,
@@ -57,29 +64,34 @@ class _FormatToolbarItem extends ToolbarItem {
delta.everyAttributes((attr) => attr[name] == true),
);
final hoverColor = Theme.of(context).brightness == Brightness.dark
? Theme.of(context).hoverColor
: AFThemeExtension.of(context).toolbarHoverColor;
final hoverColor = isHighlight
? highlightColor
: EditorStyleCustomizer.toolbarHoverColor(context);
final isDark = Theme.of(context).brightness == Brightness.dark;
final child = FlowyIconButton(
width: 36,
height: 32,
hoverColor: hoverColor,
isSelected: isHighlight,
icon: FlowySvg(
svg,
size: Size.square(20.0),
color: isHighlight
? highlightColor
color: (isDark && isHighlight)
? Color(0xFF282E3A)
: Theme.of(context).iconTheme.color,
),
onPressed: () => editorState.toggleAttribute(name),
onPressed: () => editorState.toggleAttribute(
name,
selection: selection,
),
);
if (tooltipBuilder != null) {
return tooltipBuilder(
context,
id,
getTooltipText(id),
id.id,
_getTooltipText(id),
child,
);
}
@@ -87,3 +99,34 @@ class _FormatToolbarItem extends ToolbarItem {
},
);
}
String _getTooltipText(ToolbarId id) {
switch (id) {
case ToolbarId.underline:
return '${LocaleKeys.toolbar_underline.tr()}${shortcutTooltips(
'⌘ + U',
'CTRL + U',
'CTRL + U',
)}';
case ToolbarId.bold:
return '${LocaleKeys.toolbar_bold.tr()}${shortcutTooltips(
'⌘ + B',
'CTRL + B',
'CTRL + B',
)}';
case ToolbarId.italic:
return '${LocaleKeys.toolbar_italic.tr()}${shortcutTooltips(
'⌘ + I',
'CTRL + I',
'CTRL + I',
)}';
case ToolbarId.code:
return '${LocaleKeys.document_toolbar_inlineCode.tr()}${shortcutTooltips(
'⌘ + E',
'CTRL + E',
'CTRL + E',
)}';
default:
return '';
}
}
@@ -1,18 +1,162 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_page.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/color_picker.dart';
import 'package:appflowy/plugins/document/presentation/editor_style.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flowy_infra_ui/style_widget/icon_button.dart';
import 'package:appflowy_editor/appflowy_editor.dart' hide ColorPicker;
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
const _kHighlightColorItemId = 'editor.highlightColor';
import 'toolbar_id_enum.dart';
String? _customHighlightColorHex;
final customHighlightColorItem = ToolbarItem(
id: _kHighlightColorItemId,
id: ToolbarId.highlightColor.id,
group: 1,
isActive: showInAnyTextType,
builder: (context, editorState, highlightColor, iconColor, tooltipBuilder) {
String? highlightColorHex;
builder: (context, editorState, highlightColor, iconColor, tooltipBuilder) =>
HighlightColorPickerWidget(
editorState: editorState,
tooltipBuilder: tooltipBuilder,
highlightColor: highlightColor,
),
);
class HighlightColorPickerWidget extends StatefulWidget {
const HighlightColorPickerWidget({
super.key,
required this.editorState,
this.tooltipBuilder,
required this.highlightColor,
});
final EditorState editorState;
final ToolbarTooltipBuilder? tooltipBuilder;
final Color highlightColor;
@override
State<HighlightColorPickerWidget> createState() =>
_HighlightColorPickerWidgetState();
}
class _HighlightColorPickerWidgetState
extends State<HighlightColorPickerWidget> {
final popoverController = PopoverController();
bool isSelected = false;
EditorState get editorState => widget.editorState;
Color get highlightColor => widget.highlightColor;
@override
void dispose() {
super.dispose();
popoverController.close();
}
@override
Widget build(BuildContext context) {
final selectionRectList = editorState.selectionRects();
final top =
selectionRectList.isEmpty ? 0.0 : selectionRectList.first.height;
return AppFlowyPopover(
controller: popoverController,
direction: PopoverDirection.bottomWithLeftAligned,
offset: Offset(0, top),
onOpen: () => keepEditorFocusNotifier.increase(),
onClose: () {
setState(() {
isSelected = false;
});
keepEditorFocusNotifier.decrease();
},
margin: EdgeInsets.zero,
popupBuilder: (context) => buildPopoverContent(),
child: buildChild(context),
);
}
Widget buildChild(BuildContext context) {
final iconColor = Theme.of(context).iconTheme.color;
final child = FlowyIconButton(
width: 36,
height: 32,
hoverColor: EditorStyleCustomizer.toolbarHoverColor(context),
icon: SizedBox(
width: 20,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
FlowySvg(
FlowySvgs.toolbar_text_highlight_m,
size: Size(20, 16),
color: iconColor,
),
buildColorfulDivider(iconColor),
],
),
),
onPressed: () {
setState(() {
isSelected = true;
});
showPopover();
},
);
return widget.tooltipBuilder?.call(
context,
ToolbarId.highlightColor.id,
AppFlowyEditorL10n.current.highlightColor,
child,
) ??
child;
}
Widget buildColorfulDivider(Color? iconColor) {
final List<String> colors = [];
final selection = editorState.selection!;
final nodes = editorState.getNodesInSelection(selection);
final isHighLight = nodes.allSatisfyInSelection(selection, (delta) {
if (delta.everyAttributes((attr) => attr.isEmpty)) {
return false;
}
return delta.everyAttributes((attr) {
final textColorHex = attr[AppFlowyRichTextKeys.backgroundColor];
if (textColorHex != null) colors.add(textColorHex);
return (textColorHex != null);
});
});
final colorLength = colors.length;
if (colors.isEmpty || !isHighLight) {
return Container(
width: 20,
height: 4,
color: iconColor,
);
}
return SizedBox(
width: 20,
height: 4,
child: Row(
children: List.generate(colorLength, (index) {
final currentColor = int.tryParse(colors[index]);
return Container(
width: 20 / colorLength,
height: 4,
color: currentColor == null ? iconColor : Color(currentColor),
);
}),
),
);
}
Widget buildPopoverContent() {
final List<String> colors = [];
final selection = editorState.selection!;
final nodes = editorState.getNodesInSelection(selection);
@@ -22,54 +166,57 @@ final customHighlightColorItem = ToolbarItem(
}
return delta.everyAttributes((attributes) {
highlightColorHex = attributes[AppFlowyRichTextKeys.backgroundColor];
final highlightColorHex =
attributes[AppFlowyRichTextKeys.backgroundColor];
if (highlightColorHex != null) colors.add(highlightColorHex);
return highlightColorHex != null;
});
});
final child = FlowyIconButton(
width: 36,
height: 32,
hoverColor: EditorStyleCustomizer.toolbarHoverColor(context),
icon: FlowySvg(
FlowySvgs.toolbar_text_highlight_m,
size: Size.square(20.0),
color: isHighlight ? highlightColor : Theme.of(context).iconTheme.color,
),
onPressed: () {
bool showClearButton = false;
nodes.allSatisfyInSelection(selection, (delta) {
if (!showClearButton) {
showClearButton = delta.whereType<TextInsert>().any(
(element) {
return element
.attributes?[AppFlowyRichTextKeys.backgroundColor] !=
null;
},
);
}
return true;
});
showColorMenu(
context,
editorState,
selection,
currentColorHex: highlightColorHex,
isTextColor: false,
showClearButton: showClearButton,
bool showClearButton = false;
nodes.allSatisfyInSelection(selection, (delta) {
if (!showClearButton) {
showClearButton = delta.whereType<TextInsert>().any(
(element) {
return element.attributes?[AppFlowyRichTextKeys.backgroundColor] !=
null;
},
);
},
}
return true;
});
return MouseRegion(
child: ColorPicker(
title: AppFlowyEditorL10n.current.highlightColor,
showClearButton: showClearButton,
selectedColorHex:
(colors.length == 1 && isHighlight) ? colors.first : null,
customColorHex: _customHighlightColorHex,
colorOptions: generateHighlightColorOptions(),
onSubmittedColorHex: (color, isCustomColor) {
if (isCustomColor) {
_customHighlightColorHex = color;
}
formatHighlightColor(
editorState,
editorState.selection,
color,
withUpdateSelection: true,
);
hidePopover();
},
resetText: AppFlowyEditorL10n.current.clearHighlightColor,
resetIconName: 'clear_highlight_color',
),
);
}
if (tooltipBuilder != null) {
return tooltipBuilder(
context,
_kHighlightColorItemId,
AppFlowyEditorL10n.current.highlightColor,
child,
);
}
void showPopover() {
keepEditorFocusNotifier.increase();
popoverController.show();
}
return child;
},
);
void hidePopover() {
popoverController.close();
keepEditorFocusNotifier.decrease();
}
}
@@ -4,10 +4,10 @@ import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flowy_infra_ui/style_widget/icon_button.dart';
import 'package:flutter/material.dart';
const _kLinkItemId = 'editor.link';
import 'toolbar_id_enum.dart';
final customLinkItem = ToolbarItem(
id: _kLinkItemId,
id: ToolbarId.link.id,
group: 4,
isActive: onlyShowInSingleSelectionAndTextType,
builder: (context, editorState, highlightColor, iconColor, tooltipBuilder) {
@@ -19,14 +19,19 @@ final customLinkItem = ToolbarItem(
);
});
final hoverColor = isHref
? highlightColor
: EditorStyleCustomizer.toolbarHoverColor(context);
final child = FlowyIconButton(
width: 36,
height: 32,
hoverColor: EditorStyleCustomizer.toolbarHoverColor(context),
hoverColor: hoverColor,
isSelected: isHref,
icon: FlowySvg(
FlowySvgs.toolbar_link_m,
size: Size.square(20.0),
color: isHref ? highlightColor : Theme.of(context).iconTheme.color,
color: Theme.of(context).iconTheme.color,
),
onPressed: () => showLinkMenu(context, editorState, selection, isHref),
);
@@ -34,7 +39,7 @@ final customLinkItem = ToolbarItem(
if (tooltipBuilder != null) {
return tooltipBuilder(
context,
_kLinkItemId,
ToolbarId.highlightColor.id,
AppFlowyEditorL10n.current.link,
child,
);
@@ -0,0 +1,47 @@
import 'package:appflowy/plugins/document/presentation/editor_page.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/ai_writer_toolbar_item.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'toolbar_id_enum.dart';
final ToolbarItem customPlaceholderItem = ToolbarItem(
id: ToolbarId.placeholder.id,
group: -1,
isActive: (editorState) => true,
builder: (context, __, ___, ____, _____) {
final isDark = Theme.of(context).brightness == Brightness.dark;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 5),
child: Container(
width: 1,
color: Color(0xffE8ECF3).withAlpha(isDark ? 40 : 255),
),
);
},
);
ToolbarItem buildPaddingPlaceholderItem(
int group, {
bool Function(EditorState editorState)? isActive,
}) =>
ToolbarItem(
id: ToolbarId.paddingPlaceHolder.id,
group: group,
isActive: isActive,
builder: (context, __, ___, ____, _____) => HSpace(4),
);
ToolbarItem group0PaddingItem = buildPaddingPlaceholderItem(
0,
isActive: onlyShowInTextTypeAndExcludeTable,
);
ToolbarItem group1PaddingItem =
buildPaddingPlaceholderItem(1, isActive: showInAnyTextType);
ToolbarItem group4PaddingItem = buildPaddingPlaceholderItem(
4,
isActive: onlyShowInSingleSelectionAndTextType,
);
@@ -6,10 +6,10 @@ import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
const _kTextAlignItemId = 'editor.text_align';
import 'toolbar_id_enum.dart';
final ToolbarItem customTextAlignItem = ToolbarItem(
id: _kTextAlignItemId,
id: ToolbarId.textAlign.id,
group: 4,
isActive: onlyShowInSingleSelectionAndTextType,
builder: (
@@ -63,7 +63,7 @@ class _TextAlignActionListState extends State<TextAlignActionList> {
return AppFlowyPopover(
controller: popoverController,
direction: PopoverDirection.bottomWithLeftAligned,
offset: const Offset(-8.0, 2.0),
offset: const Offset(0, 2.0),
onOpen: () => keepEditorFocusNotifier.increase(),
onClose: () {
setState(() {
@@ -84,7 +84,7 @@ class _TextAlignActionListState extends State<TextAlignActionList> {
Widget buildChild(BuildContext context) {
final iconColor = Theme.of(context).iconTheme.color;
final child = FlowyIconButton(
width: 52,
width: 48,
height: 32,
isSelected: isSelected,
hoverColor: EditorStyleCustomizer.toolbarHoverColor(context),
@@ -96,9 +96,10 @@ class _TextAlignActionListState extends State<TextAlignActionList> {
size: Size.square(20),
color: iconColor,
),
HSpace(4),
FlowySvg(
FlowySvgs.toolbar_arrow_down_m,
size: Size.square(20),
size: Size(12, 20),
color: iconColor,
),
],
@@ -113,7 +114,7 @@ class _TextAlignActionListState extends State<TextAlignActionList> {
return widget.tooltipBuilder?.call(
context,
_kTextAlignItemId,
ToolbarId.textAlign.id,
LocaleKeys.document_toolbar_textAlign.tr(),
child,
) ??
@@ -132,24 +133,20 @@ class _TextAlignActionListState extends State<TextAlignActionList> {
final isHighlight = nodes.every(
(n) => n.attributes[blockComponentAlign] == command.name,
);
final color =
isHighlight ? highlightColor : Theme.of(context).iconTheme.color;
return SizedBox(
height: 36,
child: FlowyButton(
leftIconSize: const Size.square(20),
leftIcon: FlowySvg(
command.svg,
color: color,
),
leftIcon: FlowySvg(command.svg),
iconPadding: 12,
text: FlowyText(
command.title,
fontWeight: FontWeight.w400,
figmaLineHeight: 20,
color: color,
),
rightIcon:
isHighlight ? FlowySvg(FlowySvgs.toolbar_check_m) : null,
onTap: () {
command.onAlignChanged(editorState);
popoverController.close();
@@ -193,6 +190,10 @@ enum TextAlignCommand {
blockComponentAlign: name,
},
),
selectionExtraInfo: {
selectionExtraInfoDoNotAttachTextService: true,
selectionExtraInfoDisableFloatingToolbar: true,
},
);
}
}
@@ -1,76 +1,221 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_page.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/desktop_toolbar/color_picker.dart';
import 'package:appflowy/plugins/document/presentation/editor_style.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flowy_infra_ui/style_widget/icon_button.dart';
import 'package:appflowy_editor/appflowy_editor.dart' hide ColorPicker;
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'toolbar_id_enum.dart';
const _kTextColorItemId = 'editor.textColor';
String? _customColorHex;
final customTextColorItem = ToolbarItem(
id: _kTextColorItemId,
id: ToolbarId.textColor.id,
group: 1,
isActive: showInAnyTextType,
builder: (context, editorState, highlightColor, iconColor, tooltipBuilder) {
String? textColorHex;
builder: (context, editorState, highlightColor, iconColor, tooltipBuilder) =>
TextColorPickerWidget(
editorState: editorState,
tooltipBuilder: tooltipBuilder,
highlightColor: highlightColor,
),
);
class TextColorPickerWidget extends StatefulWidget {
const TextColorPickerWidget({
super.key,
required this.editorState,
this.tooltipBuilder,
required this.highlightColor,
});
final EditorState editorState;
final ToolbarTooltipBuilder? tooltipBuilder;
final Color highlightColor;
@override
State<TextColorPickerWidget> createState() => _TextColorPickerWidgetState();
}
class _TextColorPickerWidgetState extends State<TextColorPickerWidget> {
final popoverController = PopoverController();
bool isSelected = false;
EditorState get editorState => widget.editorState;
Color get highlightColor => widget.highlightColor;
@override
void dispose() {
super.dispose();
popoverController.close();
}
@override
Widget build(BuildContext context) {
final selectionRectList = editorState.selectionRects();
final top =
selectionRectList.isEmpty ? 0.0 : selectionRectList.first.height;
return AppFlowyPopover(
controller: popoverController,
direction: PopoverDirection.bottomWithLeftAligned,
offset: Offset(0, top),
onOpen: () => keepEditorFocusNotifier.increase(),
onClose: () {
setState(() {
isSelected = false;
});
keepEditorFocusNotifier.decrease();
},
margin: EdgeInsets.zero,
popupBuilder: (context) => buildPopoverContent(),
child: buildChild(context),
);
}
Widget buildChild(BuildContext context) {
final iconColor = Theme.of(context).iconTheme.color;
final child = FlowyIconButton(
width: 36,
height: 32,
hoverColor: EditorStyleCustomizer.toolbarHoverColor(context),
icon: SizedBox(
width: 20,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
FlowySvg(
FlowySvgs.toolbar_text_color_m,
size: Size(20, 16),
color: iconColor,
),
buildColorfulDivider(iconColor),
],
),
),
onPressed: () {
setState(() {
isSelected = true;
});
showPopover();
},
);
return widget.tooltipBuilder?.call(
context,
ToolbarId.textColor.id,
LocaleKeys.document_toolbar_textColor.tr(),
child,
) ??
child;
}
Widget buildColorfulDivider(Color? iconColor) {
final List<String> colors = [];
final selection = editorState.selection!;
final nodes = editorState.getNodesInSelection(selection);
final isHighlight = nodes.allSatisfyInSelection(selection, (delta) {
final isHighLight = nodes.allSatisfyInSelection(selection, (delta) {
if (delta.everyAttributes((attr) => attr.isEmpty)) {
return false;
}
return delta.everyAttributes((attr) {
textColorHex = attr[AppFlowyRichTextKeys.textColor];
final textColorHex = attr[AppFlowyRichTextKeys.textColor];
if (textColorHex != null) colors.add(textColorHex);
return (textColorHex != null);
});
});
final child = FlowyIconButton(
width: 36,
height: 32,
hoverColor: EditorStyleCustomizer.toolbarHoverColor(context),
icon: FlowySvg(
FlowySvgs.toolbar_text_color_m,
size: Size.square(20.0),
color: isHighlight ? highlightColor : Theme.of(context).iconTheme.color,
),
onPressed: () {
bool showClearButton = false;
nodes.allSatisfyInSelection(
selection,
(delta) {
if (!showClearButton) {
showClearButton = delta.whereType<TextInsert>().any(
(element) {
return element.attributes?[AppFlowyRichTextKeys.textColor] !=
null;
},
);
}
return true;
},
);
showColorMenu(
context,
editorState,
selection,
currentColorHex: textColorHex,
isTextColor: true,
showClearButton: showClearButton,
);
},
);
if (tooltipBuilder != null) {
return tooltipBuilder(
context,
_kTextColorItemId,
AppFlowyEditorL10n.current.textColor,
child,
final colorLength = colors.length;
if (colors.isEmpty || !isHighLight) {
return Container(
width: 20,
height: 4,
color: iconColor,
);
}
return SizedBox(
width: 20,
height: 4,
child: Row(
children: List.generate(colorLength, (index) {
final currentColor = int.tryParse(colors[index]);
return Container(
width: 20 / colorLength,
height: 4,
color: currentColor == null ? iconColor : Color(currentColor),
);
}),
),
);
}
return child;
},
);
Widget buildPopoverContent() {
bool showClearButton = false;
final List<String> colors = [];
final selection = editorState.selection!;
final nodes = editorState.getNodesInSelection(selection);
final isHighLight = nodes.allSatisfyInSelection(selection, (delta) {
if (delta.everyAttributes((attr) => attr.isEmpty)) {
return false;
}
return delta.everyAttributes((attr) {
final textColorHex = attr[AppFlowyRichTextKeys.textColor];
if (textColorHex != null) colors.add(textColorHex);
return (textColorHex != null);
});
});
nodes.allSatisfyInSelection(
selection,
(delta) {
if (!showClearButton) {
showClearButton = delta.whereType<TextInsert>().any(
(element) {
return element.attributes?[AppFlowyRichTextKeys.textColor] !=
null;
},
);
}
return true;
},
);
return MouseRegion(
child: ColorPicker(
title: LocaleKeys.document_toolbar_textColor.tr(),
showClearButton: showClearButton,
selectedColorHex:
(colors.length == 1 && isHighLight) ? colors.first : null,
customColorHex: _customColorHex,
colorOptions: generateTextColorOptions(),
onSubmittedColorHex: (color, isCustomColor) {
if (isCustomColor) {
_customColorHex = color;
}
formatFontColor(
editorState,
editorState.selection,
color,
withUpdateSelection: true,
);
hidePopover();
},
resetText: AppFlowyEditorL10n.current.resetToDefaultColor,
resetIconName: 'reset_text_color',
),
);
}
void showPopover() {
keepEditorFocusNotifier.increase();
popoverController.show();
}
void hidePopover() {
popoverController.close();
keepEditorFocusNotifier.decrease();
}
}
@@ -1,15 +1,16 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_page.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/plugins/document/presentation/editor_style.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
// ignore: implementation_imports
import 'package:appflowy_editor/src/editor/toolbar/desktop/items/utils/tooltip_util.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import '../../editor_page.dart';
const _kMoreOptionItemId = 'editor.more_option';
const kFontToolbarItemId = 'editor.font';
@@ -73,7 +74,7 @@ class _MoreOptionActionListState extends State<MoreOptionActionList> {
return AppFlowyPopover(
controller: popoverController,
direction: PopoverDirection.bottomWithLeftAligned,
offset: const Offset(-8.0, 2.0),
offset: const Offset(0, 2.0),
onOpen: () => keepEditorFocusNotifier.increase(),
onClose: () {
setState(() {
@@ -152,6 +153,7 @@ class _MoreOptionActionListState extends State<MoreOptionActionList> {
Widget buildPopoverContent() {
final showFormula = onlyShowInSingleSelectionAndTextType(editorState);
const fontColor = Color(0xff99A1A8);
return MouseRegion(
child: SeparatedColumn(
mainAxisSize: MainAxisSize.min,
@@ -160,36 +162,55 @@ class _MoreOptionActionListState extends State<MoreOptionActionList> {
buildFontSelector(),
buildCommandItem(
MoreOptionCommand.strikethrough,
getStrikethroughColor(),
rightIcon: FlowyText(
shortcutTooltips(
'⌘⇧S',
'Ctrl⇧S',
'Ctrl⇧S',
).trim(),
color: fontColor,
fontSize: 12,
figmaLineHeight: 16,
fontWeight: FontWeight.w400,
),
),
if (showFormula)
buildCommandItem(
MoreOptionCommand.formula,
getFormulaColor(),
rightIcon: FlowyText(
shortcutTooltips(
'⌘⇧E',
'Ctrl⇧E',
'Ctrl⇧E',
).trim(),
color: fontColor,
fontSize: 12,
figmaLineHeight: 16,
fontWeight: FontWeight.w400,
),
),
],
),
);
}
Widget buildCommandItem(MoreOptionCommand command, Color? color) {
Widget buildCommandItem(
MoreOptionCommand command, {
Widget? rightIcon,
}) {
final isFontCommand = command == MoreOptionCommand.font;
return SizedBox(
height: 36,
child: FlowyButton(
key: command == MoreOptionCommand.font
? kFontFamilyToolbarItemKey
: null,
key: isFontCommand ? kFontFamilyToolbarItemKey : null,
leftIconSize: const Size.square(20),
leftIcon: FlowySvg(
command.svg,
color: color,
),
leftIcon: FlowySvg(command.svg),
rightIcon: rightIcon,
iconPadding: 12,
text: FlowyText(
command.title,
figmaLineHeight: 20,
fontWeight: FontWeight.w400,
color: color,
),
onTap: () {
command.onExecute(editorState);
@@ -228,7 +249,10 @@ class _MoreOptionActionListState extends State<MoreOptionActionList> {
await editorState
.formatDelta(selection, {AppFlowyRichTextKeys.fontFamily: null});
},
child: buildCommandItem(MoreOptionCommand.font, null),
child: buildCommandItem(
MoreOptionCommand.font,
rightIcon: FlowySvg(FlowySvgs.toolbar_arrow_right_m),
),
);
}
}
@@ -249,7 +273,7 @@ enum MoreOptionCommand {
case strikethrough:
return LocaleKeys.editor_strikethrough.tr();
case formula:
return LocaleKeys.editor_mathEquationShortForm.tr();
return LocaleKeys.document_toolbar_equation.tr();
}
}
@@ -1,5 +1,6 @@
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/block_action_option_cubit.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/plugins/document/presentation/editor_style.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
@@ -7,10 +8,10 @@ import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
const _kTextHeadingItemId = 'editor.text_heading';
import 'toolbar_id_enum.dart';
final ToolbarItem customTextHeadingItem = ToolbarItem(
id: _kTextHeadingItemId,
id: ToolbarId.textHeading.id,
group: 1,
isActive: onlyShowInSingleTextTypeSelectionAndExcludeTable,
builder: (
@@ -57,7 +58,7 @@ class _TextHeadingActionListState extends State<TextHeadingActionList> {
return AppFlowyPopover(
controller: popoverController,
direction: PopoverDirection.bottomWithLeftAligned,
offset: const Offset(-8.0, 2.0),
offset: const Offset(0, 2.0),
onOpen: () => keepEditorFocusNotifier.increase(),
onClose: () {
setState(() {
@@ -78,7 +79,7 @@ class _TextHeadingActionListState extends State<TextHeadingActionList> {
Widget buildChild(BuildContext context) {
final iconColor = Theme.of(context).iconTheme.color;
final child = FlowyIconButton(
width: 52,
width: 48,
height: 32,
isSelected: isSelected,
hoverColor: EditorStyleCustomizer.toolbarHoverColor(context),
@@ -90,9 +91,10 @@ class _TextHeadingActionListState extends State<TextHeadingActionList> {
size: Size.square(20),
color: iconColor,
),
HSpace(4),
FlowySvg(
FlowySvgs.toolbar_arrow_down_m,
size: Size.square(20),
size: Size(12, 20),
color: iconColor,
),
],
@@ -107,7 +109,7 @@ class _TextHeadingActionListState extends State<TextHeadingActionList> {
return widget.tooltipBuilder?.call(
context,
_kTextHeadingItemId,
ToolbarId.textHeading.id,
LocaleKeys.document_toolbar_textSize.tr(),
child,
) ??
@@ -115,6 +117,7 @@ class _TextHeadingActionListState extends State<TextHeadingActionList> {
}
Widget buildPopoverContent() {
final selectingCommand = getSelectingCommand();
return MouseRegion(
child: SeparatedColumn(
mainAxisSize: MainAxisSize.min,
@@ -132,7 +135,11 @@ class _TextHeadingActionListState extends State<TextHeadingActionList> {
fontWeight: FontWeight.w400,
figmaLineHeight: 20,
),
rightIcon: selectingCommand == command
? FlowySvg(FlowySvgs.toolbar_check_m)
: null,
onTap: () {
if (command == selectingCommand) return;
command.onExecute(widget.editorState);
popoverController.close();
},
@@ -142,6 +149,27 @@ class _TextHeadingActionListState extends State<TextHeadingActionList> {
),
);
}
TextHeadingCommand? getSelectingCommand() {
final editorState = widget.editorState;
final selection = editorState.selection;
if (selection == null || !selection.isSingle) {
return null;
}
final node = editorState.getNodeAtPath(selection.start.path);
if (node == null || node.delta == null) {
return null;
}
final nodeType = node.type;
if (nodeType == ParagraphBlockKeys.type) return TextHeadingCommand.text;
if (nodeType == HeadingBlockKeys.type) {
final level = node.attributes[HeadingBlockKeys.level] ?? 1;
if (level == 1) return TextHeadingCommand.h1;
if (level == 2) return TextHeadingCommand.h2;
if (level == 3) return TextHeadingCommand.h3;
}
return null;
}
}
enum TextHeadingCommand {
@@ -167,22 +195,34 @@ enum TextHeadingCommand {
}
}
void onExecute(EditorState editorState) {
void onExecute(EditorState state) {
switch (this) {
case text:
formatNodeToText(editorState);
formatNodeToText(state);
break;
case h1:
onHeadingLevelChanged(editorState, 1);
_turnInto(state, 1);
break;
case h2:
onHeadingLevelChanged(editorState, 2);
_turnInto(state, 2);
break;
case h3:
onHeadingLevelChanged(editorState, 3);
_turnInto(state, 3);
break;
}
}
Future<void> _turnInto(EditorState state, int level) async {
final selection = state.selection!;
final node = state.getNodeAtPath(selection.start.path)!;
await BlockActionOptionCubit.turnIntoBlock(
HeadingBlockKeys.type,
node,
state,
level: level,
keepSelection: true,
);
}
}
void formatNodeToText(EditorState editorState) {
@@ -203,111 +243,3 @@ void formatNodeToText(EditorState editorState) {
),
);
}
Future<void> onHeadingLevelChanged(
EditorState editorState,
int newLevel,
) async {
final selection = editorState.selection!;
final node = editorState.getNodeAtPath(selection.start.path)!;
final delta = (node.delta ?? Delta()).toJson();
final level = node.attributes[HeadingBlockKeys.level] ?? 1;
final originLevel = level;
final type = newLevel == originLevel && node.type == HeadingBlockKeys.type
? ParagraphBlockKeys.type
: HeadingBlockKeys.type;
if (type == HeadingBlockKeys.type) {
// from paragraph to heading
final newNode = node.copyWith(
type: type,
attributes: {
HeadingBlockKeys.level: newLevel,
blockComponentBackgroundColor:
node.attributes[blockComponentBackgroundColor],
blockComponentTextDirection:
node.attributes[blockComponentTextDirection],
blockComponentDelta: delta,
},
);
final children = node.children.map((child) => child.deepCopy());
final transaction = editorState.transaction;
transaction.insertNodes(
selection.start.path.next,
[newNode, ...children],
);
transaction.deleteNode(node);
await editorState.apply(transaction);
} else {
// from heading to paragraph
await editorState.formatNode(
selection,
(node) => node.copyWith(
type: type,
attributes: {
HeadingBlockKeys.level: newLevel,
blockComponentBackgroundColor:
node.attributes[blockComponentBackgroundColor],
blockComponentTextDirection:
node.attributes[blockComponentTextDirection],
blockComponentDelta: delta,
},
),
);
}
}
Future<void> onToggleLevelChanged(
EditorState editorState,
int? newLevel,
) async {
final selection = editorState.selection!;
final node = editorState.getNodeAtPath(selection.start.path)!;
final delta = (node.delta ?? Delta()).toJson();
final level = node.attributes[ToggleListBlockKeys.level];
final originLevel = level;
final type = newLevel == originLevel && node.type == ToggleListBlockKeys.type
? ParagraphBlockKeys.type
: ToggleListBlockKeys.type;
if (type == ToggleListBlockKeys.type) {
// from paragraph to heading
final newNode = node.copyWith(
type: type,
attributes: {
if (newLevel != null) ToggleListBlockKeys.level: newLevel,
blockComponentBackgroundColor:
node.attributes[blockComponentBackgroundColor],
blockComponentTextDirection:
node.attributes[blockComponentTextDirection],
blockComponentDelta: delta,
},
);
final children = node.children.map((child) => child.deepCopy());
final transaction = editorState.transaction;
transaction.insertNodes(
selection.start.path.next,
[newNode, ...children],
);
transaction.deleteNode(node);
await editorState.apply(transaction);
} else {
// from heading to paragraph
await editorState.formatNode(
selection,
(node) => node.copyWith(
type: type,
attributes: {
blockComponentBackgroundColor:
node.attributes[blockComponentBackgroundColor],
blockComponentTextDirection:
node.attributes[blockComponentTextDirection],
blockComponentDelta: delta,
},
),
);
}
}
@@ -2,6 +2,7 @@ import 'dart:collection';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/actions/block_action_option_cubit.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
import 'package:appflowy/plugins/document/presentation/editor_style.dart';
import 'package:appflowy_editor/appflowy_editor.dart'
@@ -13,8 +14,7 @@ import 'package:flowy_infra_ui/style_widget/hover.dart';
import 'package:flutter/material.dart';
import 'text_heading_toolbar_item.dart';
const _kSuggestionsItemId = 'editor.suggestions';
import 'toolbar_id_enum.dart';
@visibleForTesting
const kSuggestionsItemKey = ValueKey('SuggestionsItem');
@@ -23,7 +23,7 @@ const kSuggestionsItemKey = ValueKey('SuggestionsItem');
const kSuggestionsItemListKey = ValueKey('SuggestionsItemList');
final ToolbarItem suggestionsItem = ToolbarItem(
id: _kSuggestionsItemId,
id: ToolbarId.suggestions.id,
group: 3,
isActive: enableSuggestions,
builder: (
@@ -84,7 +84,7 @@ class _SuggestionsActionListState extends State<SuggestionsActionList> {
return AppFlowyPopover(
controller: popoverController,
direction: PopoverDirection.bottomWithLeftAligned,
offset: const Offset(-8.0, 2.0),
offset: const Offset(0, 2.0),
onOpen: () => keepEditorFocusNotifier.increase(),
onClose: () {
setState(() {
@@ -143,9 +143,10 @@ class _SuggestionsActionListState extends State<SuggestionsActionList> {
fontWeight: FontWeight.w400,
figmaLineHeight: 20,
),
HSpace(4),
FlowySvg(
FlowySvgs.toolbar_arrow_down_m,
size: Size.square(20),
size: Size(12, 20),
color: iconColor,
),
],
@@ -157,7 +158,7 @@ class _SuggestionsActionListState extends State<SuggestionsActionList> {
return widget.tooltipBuilder?.call(
context,
_kSuggestionsItemId,
ToolbarId.suggestions.id,
currentSuggestionItem.title,
child,
) ??
@@ -191,6 +192,7 @@ class _SuggestionsActionListState extends State<SuggestionsActionList> {
}
Widget buildItem(SuggestionItem item) {
final isSelected = item.type == currentSuggestionItem.type;
return SizedBox(
height: 36,
child: FlowyButton(
@@ -202,6 +204,7 @@ class _SuggestionsActionListState extends State<SuggestionsActionList> {
fontWeight: FontWeight.w400,
figmaLineHeight: 20,
),
rightIcon: isSelected ? FlowySvg(FlowySvgs.toolbar_check_m) : null,
onTap: () {
item.onTap(widget.editorState);
popoverController.close();
@@ -263,7 +266,8 @@ class _SuggestionsActionListState extends State<SuggestionsActionList> {
suggestionItems.clear();
turnIntoItems.clear();
for (final item in suggestions) {
if (item.type.group == suggestionType.group) {
if (item.type.group == suggestionType.group &&
item.type != suggestionType) {
suggestionItems.add(item);
} else {
turnIntoItems.add(item);
@@ -321,138 +325,98 @@ final h1SuggestionItem = SuggestionItem(
type: SuggestionType.h1,
title: LocaleKeys.document_toolbar_h1.tr(),
svg: FlowySvgs.type_h1_m,
onTap: (state) => onHeadingLevelChanged(state, 1),
onTap: (state) => _turnInto(state, HeadingBlockKeys.type, level: 1),
);
final h2SuggestionItem = SuggestionItem(
type: SuggestionType.h2,
title: LocaleKeys.document_toolbar_h2.tr(),
svg: FlowySvgs.type_h2_m,
onTap: (state) => onHeadingLevelChanged(state, 2),
onTap: (state) => _turnInto(state, HeadingBlockKeys.type, level: 2),
);
final h3SuggestionItem = SuggestionItem(
type: SuggestionType.h3,
title: LocaleKeys.document_toolbar_h3.tr(),
svg: FlowySvgs.type_h3_m,
onTap: (state) => onHeadingLevelChanged(state, 3),
onTap: (state) => _turnInto(state, HeadingBlockKeys.type, level: 3),
);
final checkboxSuggestionItem = SuggestionItem(
type: SuggestionType.checkbox,
title: LocaleKeys.editor_checkbox.tr(),
svg: FlowySvgs.type_todo_m,
onTap: (state) {
final selection = state.selection!;
final node = state.getNodeAtPath(selection.start.path)!;
final isHighlight = node.type == TodoListBlockKeys.type;
state.formatNode(
selection,
(node) => node.copyWith(
type: isHighlight ? ParagraphBlockKeys.type : TodoListBlockKeys.type,
),
);
},
onTap: (state) => _turnInto(state, TodoListBlockKeys.type),
);
final bulletedSuggestionItem = SuggestionItem(
type: SuggestionType.bulleted,
title: LocaleKeys.editor_bulletedListShortForm.tr(),
svg: FlowySvgs.type_bulleted_list_m,
onTap: (state) {
final selection = state.selection!;
final node = state.getNodeAtPath(selection.start.path)!;
final isHighlight = node.type == BulletedListBlockKeys.type;
state.formatNode(
selection,
(node) => node.copyWith(
type:
isHighlight ? ParagraphBlockKeys.type : BulletedListBlockKeys.type,
),
);
},
onTap: (state) => _turnInto(state, BulletedListBlockKeys.type),
);
final numberedSuggestionItem = SuggestionItem(
type: SuggestionType.numbered,
title: LocaleKeys.editor_numberedListShortForm.tr(),
svg: FlowySvgs.type_numbered_list_m,
onTap: (state) {
final selection = state.selection!;
final node = state.getNodeAtPath(selection.start.path)!;
final isHighlight = node.type == NumberedListBlockKeys.type;
state.formatNode(
selection,
(node) => node.copyWith(
type:
isHighlight ? ParagraphBlockKeys.type : NumberedListBlockKeys.type,
),
);
},
onTap: (state) => _turnInto(state, NumberedListBlockKeys.type),
);
final toggleSuggestionItem = SuggestionItem(
type: SuggestionType.toggle,
title: LocaleKeys.editor_toggleListShortForm.tr(),
svg: FlowySvgs.type_toggle_list_m,
onTap: (state) => onToggleLevelChanged(state, null),
onTap: (state) => _turnInto(state, ToggleListBlockKeys.type),
);
final toggleH1SuggestionItem = SuggestionItem(
type: SuggestionType.toggleH1,
title: LocaleKeys.editor_toggleHeading1ShortForm.tr(),
svg: FlowySvgs.type_toggle_h1_m,
onTap: (state) => onToggleLevelChanged(state, 1),
onTap: (state) => _turnInto(state, ToggleListBlockKeys.type, level: 1),
);
final toggleH2SuggestionItem = SuggestionItem(
type: SuggestionType.toggleH2,
title: LocaleKeys.editor_toggleHeading2ShortForm.tr(),
svg: FlowySvgs.type_toggle_h2_m,
onTap: (state) => onToggleLevelChanged(state, 2),
onTap: (state) => _turnInto(state, ToggleListBlockKeys.type, level: 2),
);
final toggleH3SuggestionItem = SuggestionItem(
type: SuggestionType.toggleH3,
title: LocaleKeys.editor_toggleHeading3ShortForm.tr(),
svg: FlowySvgs.type_toggle_h3_m,
onTap: (state) => onToggleLevelChanged(state, 3),
onTap: (state) => _turnInto(state, ToggleListBlockKeys.type, level: 3),
);
final callOutSuggestionItem = SuggestionItem(
type: SuggestionType.callOut,
title: LocaleKeys.document_plugins_callout.tr(),
svg: FlowySvgs.type_callout_m,
onTap: (state) {
final selection = state.selection!;
final node = state.getNodeAtPath(selection.start.path)!;
final isHighlight = node.type == CalloutBlockKeys.type;
state.formatNode(
selection,
(node) => node.copyWith(
type: isHighlight ? ParagraphBlockKeys.type : CalloutBlockKeys.type,
),
);
},
onTap: (state) => _turnInto(state, CalloutBlockKeys.type),
);
final quoteSuggestionItem = SuggestionItem(
type: SuggestionType.quote,
title: LocaleKeys.editor_quote.tr(),
svg: FlowySvgs.type_quote_m,
onTap: (state) {
final selection = state.selection!;
final node = state.getNodeAtPath(selection.start.path)!;
final isHighlight = node.type == QuoteBlockKeys.type;
state.formatNode(
selection,
(node) => node.copyWith(
type: isHighlight ? ParagraphBlockKeys.type : QuoteBlockKeys.type,
),
);
},
onTap: (state) => _turnInto(state, QuoteBlockKeys.type),
);
Future<void> _turnInto(EditorState state, String type, {int? level}) async {
final selection = state.selection!;
final node = state.getNodeAtPath(selection.start.path)!;
await BlockActionOptionCubit.turnIntoBlock(
type,
node,
state,
level: level,
keepSelection: true,
);
}
final suggestions = UnmodifiableListView([
textSuggestionItem,
h1SuggestionItem,
@@ -0,0 +1,19 @@
enum ToolbarId {
bold,
underline,
italic,
code,
highlightColor,
textColor,
link,
placeholder,
paddingPlaceHolder,
textAlign,
moreOption,
textHeading,
suggestions,
}
extension ToolbarIdExtension on ToolbarId {
String get id => 'editor.$name';
}
@@ -550,7 +550,7 @@ class EditorStyleCustomizer {
style: context.tooltipTextStyle(),
),
TextSpan(
text: (Platform.isMacOS ? '⌘+' : 'Ctrl+\\') + tooltip.$2,
text: (Platform.isMacOS ? '⌘+' : 'Ctrl+') + tooltip.$2,
style: context.tooltipTextStyle()?.copyWith(
color: Theme.of(context).hintColor,
),
@@ -60,7 +60,7 @@ class SidebarTemplateButton extends StatelessWidget {
FlowySvgs.icon_template_s,
),
text: LocaleKeys.template_label.tr(),
onTap: () => afLaunchUrlString('https://appflowy.io/templates'),
onTap: () => afLaunchUrlString('https://appflowy.com/templates'),
);
}
}
@@ -45,7 +45,7 @@ class LocalAISetting extends StatelessWidget {
collapsed: const SizedBox.shrink(),
expanded: Column(
children: [
const VSpace(6),
const VSpace(12),
DecoratedBox(
decoration: BoxDecoration(
color:
@@ -79,35 +79,46 @@ class LocalAISettingHeader extends StatelessWidget {
error: (error) => SizedBox.shrink(),
loading: () => const SizedBox.shrink(),
isEnabled: (isEnabled) {
return Row(
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FlowyText(
LocaleKeys.settings_aiPage_keys_localAIToggleTitle.tr(),
Row(
children: [
FlowyText(
LocaleKeys.settings_aiPage_keys_localAIToggleTitle.tr(),
),
const Spacer(),
Toggle(
value: isEnabled,
onChanged: (_) {
if (isEnabled) {
showConfirmDialog(
context: context,
title: LocaleKeys
.settings_aiPage_keys_disableLocalAITitle
.tr(),
description: LocaleKeys
.settings_aiPage_keys_disableLocalAIDescription
.tr(),
confirmLabel: LocaleKeys.button_confirm.tr(),
onConfirm: () => context
.read<LocalAIToggleBloc>()
.add(const LocalAIToggleEvent.toggle()),
);
} else {
context
.read<LocalAIToggleBloc>()
.add(const LocalAIToggleEvent.toggle());
}
},
),
],
),
const Spacer(),
Toggle(
value: isEnabled,
onChanged: (_) {
if (isEnabled) {
showConfirmDialog(
context: context,
title: LocaleKeys
.settings_aiPage_keys_disableLocalAITitle
.tr(),
description: LocaleKeys
.settings_aiPage_keys_disableLocalAIDescription
.tr(),
confirmLabel: LocaleKeys.button_confirm.tr(),
onConfirm: () => context
.read<LocalAIToggleBloc>()
.add(const LocalAIToggleEvent.toggle()),
);
} else {
context
.read<LocalAIToggleBloc>()
.add(const LocalAIToggleEvent.toggle());
}
},
const VSpace(4),
FlowyText(
LocaleKeys.settings_aiPage_keys_localAIToggleSubTitle.tr(),
maxLines: 3,
fontSize: 12,
),
],
);
@@ -1,6 +1,5 @@
import 'package:appflowy/workspace/application/settings/ai/local_ai_setting_panel_bloc.dart';
import 'package:appflowy/workspace/presentation/settings/pages/setting_ai_view/ollma_setting.dart';
import 'package:expandable/expandable.dart';
import 'package:flowy_infra_ui/widget/spacing.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
@@ -13,40 +12,19 @@ class LocalAISettingPanel extends StatelessWidget {
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => LocalAISettingPanelBloc(),
child: ExpandableNotifier(
initialExpanded: true,
child: ExpandablePanel(
theme: const ExpandableThemeData(
headerAlignment: ExpandablePanelHeaderAlignment.center,
tapBodyToCollapse: false,
hasIcon: false,
tapBodyToExpand: false,
tapHeaderToExpand: false,
),
header: const SizedBox.shrink(),
collapsed: const SizedBox.shrink(),
expanded: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child:
BlocBuilder<LocalAISettingPanelBloc, LocalAISettingPanelState>(
builder: (context, state) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// If the progress indicator is startLocalAIApp, then don't show the LLM model.
if (state.progressIndicator ==
const LocalAIProgress.downloadLocalAIApp())
const SizedBox.shrink()
else ...[
OllamaSettingPage(),
VSpace(6),
PluginStateIndicator(),
],
],
);
},
),
),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: BlocBuilder<LocalAISettingPanelBloc, LocalAISettingPanelState>(
builder: (context, state) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
OllamaSettingPage(),
VSpace(6),
PluginStateIndicator(),
],
);
},
),
),
);
+23 -23
View File
@@ -144,34 +144,34 @@ EXTERNAL SOURCES:
:path: Flutter/ephemeral/.symlinks/plugins/window_manager/macos
SPEC CHECKSUMS:
app_links: 9028728e32c83a0831d9db8cf91c526d16cc5468
appflowy_backend: 464aeb3e5c6966a41641a2111e5ead72ce2695f7
auto_updater_macos: 3a42f1a06be6981f1a18be37e6e7bf86aa732118
bitsdojo_window_macos: 7959fb0ca65a3ccda30095c181ecb856fae48ea9
connectivity_plus: e74b9f74717d2d99d45751750e266e55912baeb5
desktop_drop: e0b672a7d84c0a6cbc378595e82cdb15f2970a43
device_info_plus: a56e6e74dbbd2bb92f2da12c64ddd4f67a749041
file_selector_macos: 6280b52b459ae6c590af5d78fc35c7267a3c4b31
flowy_infra_ui: 8760ff42a789de40bf5007a5f176b454722a341e
app_links: 10e0a0ab602ffaf34d142cd4862f29d34b303b2a
appflowy_backend: 865496343de667fc8c600e04b9fd05234e130cf9
auto_updater_macos: 3e3462c418fe4e731917eacd8d28eef7af84086d
bitsdojo_window_macos: 44e3b8fe3dd463820e0321f6256c5b1c16bb6a00
connectivity_plus: 18d3c32514c886e046de60e9c13895109866c747
desktop_drop: 69eeff437544aa619c8db7f4481b3a65f7696898
device_info_plus: ce1b7762849d3ec103d0e0517299f2db7ad60720
file_selector_macos: cc3858c981fe6889f364731200d6232dac1d812d
flowy_infra_ui: 03301a39ad118771adbf051a664265c61c507f38
FlutterMacOS: 8f6f14fa908a6fb3fba0cd85dbd81ec4b251fb24
HotKey: 400beb7caa29054ea8d864c96f5ba7e5b4852277
hotkey_manager: b443f35f4d772162937aa73fd8995e579f8ac4e2
irondash_engine_context: 893c7d96d20ce361d7e996f39d360c4c2f9869ba
local_notifier: ebf072651e35ae5e47280ad52e2707375cb2ae4e
package_info_plus: f0052d280d17aa382b932f399edf32507174e870
path_provider_foundation: 080d55be775b7414fd5a5ef3ac137b97b097e564
hotkey_manager: c32bf0bfe8f934b7bc17ab4ad5c4c142960b023c
irondash_engine_context: da62996ee25616d2f01bbeb85dc115d813359478
local_notifier: e9506bc66fc70311e8bc7291fb70f743c081e4ff
package_info_plus: 12f1c5c2cfe8727ca46cbd0b26677728972d9a5b
path_provider_foundation: 2b6b4c569c0fb62ec74538f866245ac84301af46
ReachabilitySwift: 32793e867593cfc1177f5d16491e3a197d2fccda
screen_retriever_macos: 452e51764a9e1cdb74b3c541238795849f21557f
screen_retriever_macos: 776e0fa5d42c6163d2bf772d22478df4b302b161
Sentry: 1fe34e9c2cbba1e347623610d26db121dcb569f1
sentry_flutter: e24b397f9a61fa5bbefd8279c3b2242ca86faa90
share_plus: 510bf0af1a42cd602274b4629920c9649c52f4cc
shared_preferences_foundation: 9e1978ff2562383bd5676f64ec4e9aa8fa06a6f7
sentry_flutter: a39c2a2d67d5e5b9cb0b94a4985c76dd5b3fc737
share_plus: 1fa619de8392a4398bfaf176d441853922614e89
shared_preferences_foundation: fcdcbc04712aee1108ac7fda236f363274528f78
Sparkle: 5f8960a7a119aa7d45dacc0d5837017170bc5675
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
super_native_extensions: c2795d6d9aedf4a79fae25cb6160b71b50549189
url_launcher_macos: 0fba8ddabfc33ce0a9afe7c5fef5aab3d8d2d673
webview_flutter_wkwebview: 44d4dee7d7056d5ad185d25b38404436d56c547c
window_manager: 1d01fa7ac65a6e6f83b965471b1a7fdd3f06166c
sqflite_darwin: 5a7236e3b501866c1c9befc6771dfd73ffb8702d
super_native_extensions: 85efee3a7495b46b04befcfc86ed12069264ebf3
url_launcher_macos: c82c93949963e55b228a30115bd219499a6fe404
webview_flutter_wkwebview: 0982481e3d9c78fd5c6f62a002fcd24fc791f1e4
window_manager: 3a1844359a6295ab1e47659b1a777e36773cd6e8
PODFILE CHECKSUM: 0532f3f001ca3110b8be345d6491fff690e95823
@@ -23,6 +23,7 @@ class _MockAIRepository extends Mock implements AppFlowyAIService {
required String text,
PredefinedFormat? format,
List<String> sourceIds = const [],
List<AiWriterRecord> history = const [],
required CompletionTypePB completionType,
required Future<void> Function() onStart,
required Future<void> Function(String text) onProcess,
@@ -53,6 +54,7 @@ class _MockAIRepositoryLess extends Mock implements AppFlowyAIService {
required String text,
PredefinedFormat? format,
List<String> sourceIds = const [],
List<AiWriterRecord> history = const [],
required CompletionTypePB completionType,
required Future<void> Function() onStart,
required Future<void> Function(String text) onProcess,
@@ -79,6 +81,7 @@ class _MockAIRepositoryMore extends Mock implements AppFlowyAIService {
required String text,
PredefinedFormat? format,
List<String> sourceIds = const [],
List<AiWriterRecord> history = const [],
required CompletionTypePB completionType,
required Future<void> Function() onStart,
required Future<void> Function(String text) onProcess,
@@ -107,6 +110,7 @@ class _MockErrorRepository extends Mock implements AppFlowyAIService {
required String text,
PredefinedFormat? format,
List<String> sourceIds = const [],
List<AiWriterRecord> history = const [],
required CompletionTypePB completionType,
required Future<void> Function() onStart,
required Future<void> Function(String text) onProcess,
@@ -24,11 +24,6 @@ void main() {
void Function(EditorState editorState, Node node)? afterTurnInto,
}) async {
final editorState = EditorState(document: document);
final cubit = BlockActionOptionCubit(
editorState: editorState,
blockComponentBuilder: {},
);
final types = toType == null
? EditorOptionActionType.turnInto.supportTypes
: [toType];
@@ -43,7 +38,12 @@ void main() {
final node = editorState.getNodeAtPath([0])!;
expect(node.type, originalType);
final result = await cubit.turnIntoBlock(type, node, level: level);
final result = await BlockActionOptionCubit.turnIntoBlock(
type,
node,
editorState,
level: level,
);
expect(result, true);
final newNode = editorState.getNodeAtPath([0])!;
expect(newNode.type, type);
@@ -59,9 +59,10 @@ void main() {
Selection.collapsed(
Position(path: [0]),
);
await cubit.turnIntoBlock(
await BlockActionOptionCubit.turnIntoBlock(
originalType,
newNode,
editorState,
);
expect(result, true);
}
@@ -1,5 +0,0 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M1.75 8C1.75 9.6576 2.40848 11.2473 3.58058 12.4194C4.75268 13.5915 6.3424 14.25 8 14.25C9.6576 14.25 11.2473 13.5915 12.4194 12.4194C13.5915 11.2473 14.25 9.6576 14.25 8C14.25 6.3424 13.5915 4.75268 12.4194 3.58058C11.2473 2.40848 9.6576 1.75 8 1.75C6.3424 1.75 4.75268 2.40848 3.58058 3.58058C2.40848 4.75268 1.75 6.3424 1.75 8Z" stroke="black"/>
<path d="M6.82812 6.04688C6.82812 5.39967 7.35281 4.875 8 4.875C8.64719 4.875 9.17188 5.39967 9.17188 6.04688C9.17188 6.47653 8.94062 6.85219 8.59587 7.05619C8.29875 7.23194 8 7.49856 8 7.84375V8.625" stroke="black" stroke-linecap="round"/>
<path d="M7.375 10.5C7.375 10.6658 7.44085 10.8247 7.55806 10.9419C7.67527 11.0592 7.83424 11.125 8 11.125C8.16576 11.125 8.32473 11.0592 8.44194 10.9419C8.55915 10.8247 8.625 10.6658 8.625 10.5C8.625 10.3342 8.55915 10.1753 8.44194 10.0581C8.32473 9.94085 8.16576 9.875 8 9.875C7.83424 9.875 7.67527 9.94085 7.55806 10.0581C7.44085 10.1753 7.375 10.3342 7.375 10.5Z" fill="black"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

@@ -0,0 +1,4 @@
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M9.97294 13.8714C9.80435 13.8714 9.64266 13.8045 9.52344 13.6853C9.40423 13.566 9.33725 13.4043 9.33725 13.2358C9.33725 13.0672 9.40423 12.9055 9.52344 12.7863C9.64266 12.667 9.80435 12.6001 9.97294 12.6001C10.1415 12.6001 10.3032 12.667 10.4224 12.7863C10.5417 12.9055 10.6086 13.0672 10.6086 13.2358C10.6086 13.4043 10.5417 13.566 10.4224 13.6853C10.3032 13.8045 10.1415 13.8714 9.97294 13.8714ZM8.25444 8.86425C8.19161 8.8638 8.12958 8.85006 8.07243 8.82393C8.01529 8.79781 7.96431 8.75988 7.92287 8.71265C7.88142 8.66542 7.85044 8.60995 7.83196 8.5499C7.81348 8.48984 7.80791 8.42655 7.81563 8.36419C7.8445 8.117 7.89044 7.91488 7.95344 7.75782C8.06024 7.4975 8.22638 7.26573 8.43863 7.081C8.65412 6.88624 8.90661 6.73686 9.18107 6.64176C9.45925 6.54639 9.75149 6.49847 10.0456 6.50001C10.6581 6.50001 11.1678 6.68025 11.5755 7.04119C11.9833 7.40082 12.1876 7.88119 12.1876 8.48057C12.1876 8.75007 12.1351 8.99419 12.0301 9.21294C11.9259 9.43213 11.7037 9.70513 11.3638 10.0315C11.0229 10.3583 10.7981 10.5906 10.6865 10.7289C10.5709 10.8757 10.4853 11.0438 10.4345 11.2237C10.4039 11.3248 10.382 11.4442 10.3702 11.5816C10.3492 11.8134 10.1628 11.9972 9.93007 11.9972C9.86815 11.9968 9.807 11.9835 9.75051 11.9582C9.69402 11.9329 9.64343 11.896 9.60197 11.85C9.56052 11.8041 9.5291 11.7499 9.50974 11.6911C9.49037 11.6323 9.48348 11.5701 9.4895 11.5085C9.50481 11.3493 9.528 11.2106 9.56038 11.0924C9.62031 10.8671 9.71132 10.6703 9.83294 10.5018C9.95413 10.3329 10.1729 10.0853 10.4892 9.7585C10.8059 9.43213 11.0098 9.19413 11.1017 9.04669C11.1918 8.89838 11.2868 8.65732 11.2868 8.36419C11.2868 8.07107 11.1323 7.83263 10.9245 7.60688C10.7154 7.38113 10.4122 7.26782 10.0145 7.26782C9.23838 7.26782 8.79825 7.66725 8.695 8.46613C8.66569 8.691 8.48282 8.86425 8.25619 8.86425H8.25444Z" fill="#1F2329"/>
<circle cx="10" cy="10" r="6.5" stroke="#1F2329"/>
</svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

@@ -1,3 +1,3 @@
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M13 8.5L10 11.5L7 8.5" stroke="#99A1A8" stroke-linecap="round" stroke-linejoin="round"/>
<svg width="12" height="20" viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M9 8.5L6 11.5L3 8.5" stroke="#99A1A8" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 201 B

After

Width:  |  Height:  |  Size: 199 B

@@ -1,3 +1,3 @@
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5 13L6.66667 9.66666M6.66667 9.66666L9.46334 4.07331C9.68446 3.63108 10.3155 3.63108 10.5367 4.07331L13.3333 9.66666M6.66667 9.66666H13.3333M13.3333 9.66666L15 13M3 16H17" stroke="#1F2329" stroke-linecap="round"/>
<svg width="20" height="16" viewBox="0 0 20 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M4.55279 12.7764C4.42929 13.0234 4.5294 13.3237 4.77639 13.4472C5.02338 13.5707 5.32372 13.4706 5.44721 13.2236L4.55279 12.7764ZM10 3L10.4472 2.77639C10.3625 2.607 10.1894 2.5 10 2.5C9.81061 2.5 9.63748 2.607 9.55279 2.77639L10 3ZM14.5528 13.2236C14.6763 13.4706 14.9766 13.5707 15.2236 13.4472C15.4706 13.3237 15.5707 13.0234 15.4472 12.7764L14.5528 13.2236ZM5.44721 13.2236L7.11388 9.89027L6.21945 9.44306L4.55279 12.7764L5.44721 13.2236ZM7.11388 9.89027L10.4472 3.22361L9.55279 2.77639L6.21945 9.44306L7.11388 9.89027ZM9.55279 3.22361L12.8861 9.89027L13.7805 9.44306L10.4472 2.77639L9.55279 3.22361ZM12.8861 9.89027L14.5528 13.2236L15.4472 12.7764L13.7805 9.44306L12.8861 9.89027ZM6.66667 10.1667H13.3333V9.16667H6.66667V10.1667Z" fill="#1F2329"/>
</svg>

Before

Width:  |  Height:  |  Size: 327 B

After

Width:  |  Height:  |  Size: 863 B

@@ -1,3 +1,3 @@
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10 5C10.2367 6.60777 11.4697 7.83689 13 8M3 16H17M10.7911 3.86693L5.65847 9.10195C5.46467 9.30075 5.27712 9.69232 5.23961 9.96341L5.0083 11.9152C4.92702 12.6201 5.45217 13.102 6.17736 12.9815L8.19041 12.6502C8.47174 12.602 8.8656 12.4032 9.0594 12.1984L14.192 6.96336C15.0798 6.05974 15.4799 5.0296 14.0983 3.77054C12.7229 2.52354 11.6789 2.9633 10.7911 3.86693Z" stroke="#1F2329" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
<svg width="20" height="16" viewBox="0 0 20 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10 4.66667C10.2498 6.36375 11.5514 7.66117 13.1667 7.83333M10.7911 3.86693L5.65847 9.10195C5.46467 9.30075 5.27712 9.69232 5.23961 9.96341L5.0083 11.9152C4.92702 12.6201 5.45217 13.102 6.17736 12.9815L8.19041 12.6502C8.47174 12.602 8.8656 12.4032 9.0594 12.1984L14.192 6.96336C15.0798 6.05974 15.4799 5.0296 14.0983 3.77054C12.7229 2.52354 11.6789 2.9633 10.7911 3.86693Z" stroke="#1F2329" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 566 B

After

Width:  |  Height:  |  Size: 575 B

+47 -4
View File
@@ -155,7 +155,8 @@
"charCountLabel": "عدد الأحرف: ",
"createdAtLabel": "تم إنشاؤه: ",
"syncedAtLabel": "تم المزامنة: ",
"saveAsNewPage": "حفظ الرسائل في الصفحة"
"saveAsNewPage": "حفظ الرسائل في الصفحة",
"saveAsNewPageDisabled": "لا توجد رسائل متاحة"
},
"importPanel": {
"textAndMarkdown": "نص و Markdown",
@@ -260,7 +261,8 @@
"selectMessages": "حدد الرسائل",
"nSelected": "{} تم التحديد",
"allSelected": "جميعها محددة"
}
},
"stopTooltip": "توقف عن التوليد"
},
"trash": {
"text": "المهملات",
@@ -857,11 +859,13 @@
"localAIStopped": "تم إيقاف الذكاء الاصطناعي المحلي",
"localAIRunning": "الذكاء الاصطناعي المحلي قيد التشغيل",
"localAIInitializing": "يتم تهيئة الذكاء الاصطناعي المحلي وقد يستغرق الأمر بضع دقائق، حسب جهازك",
"localAINotReadyTextFieldPrompt": "لا يمكنك التحرير أثناء تحميل الذكاء الاصطناعي المحلي",
"failToLoadLocalAI": "فشل في بدء تشغيل الذكاء الاصطناعي المحلي",
"restartLocalAI": "إعادة تشغيل الذكاء الاصطناعي المحلي",
"disableLocalAITitle": "تعطيل الذكاء الاصطناعي المحلي",
"disableLocalAIDescription": "هل تريد تعطيل الذكاء الاصطناعي المحلي؟",
"localAIToggleTitle": "التبديل لتفعيل أو تعطيل الذكاء الاصطناعي المحلي",
"localAIToggleSubTitle": "قم بتشغيل نماذج الذكاء الاصطناعي المحلية الأكثر تقدمًا داخل AppFlowy للحصول على أقصى درجات الخصوصية والأمان",
"offlineAIInstruction1": "اتبع",
"offlineAIInstruction2": "تعليمات",
"offlineAIInstruction3": "لتفعيل الذكاء الاصطناعي دون اتصال بالإنترنت.",
@@ -2127,7 +2131,21 @@
"morePages": "المزيد من الصفحات"
},
"toolbar": {
"resetToDefaultFont": "إعادة تعيين إلى الافتراضي"
"resetToDefaultFont": "إعادة تعيين إلى الافتراضي",
"textSize": "حجم النص",
"h1": "العنوان 1",
"h2": "العنوان 2",
"h3": "العنوان 3",
"alignLeft": "محاذاة إلى اليسار",
"alignRight": "محاذاة إلى اليمين",
"alignCenter": "محاذاة إلى الوسط",
"link": "وصلة",
"textAlign": "محاذاة النص",
"moreOptions": "المزيد من الخيارات",
"font": "الخط",
"suggestions": "اقتراحات",
"turnInto": "تحول إلى",
"equation": "معادلة"
},
"errorBlock": {
"theBlockIsNotSupported": "الإصدار الحالي لا يدعم هذا الحقل.",
@@ -2774,6 +2792,7 @@
"moreOptions": "المزيد من الخيارات",
"collapse": "طي",
"signInAgreement": "بالنقر فوق \"متابعة\" أعلاه، فإنك توافق على شروط استخدام AppFlowy",
"signInLocalAgreement": "من خلال النقر على \"البدء\" أعلاه، فإنك توافق على شروط وأحكام AppFlowy",
"and": "و",
"termOfUse": "شروط",
"privacyPolicy": "سياسة الخصوصية",
@@ -3172,6 +3191,30 @@
},
"autoUpdate": {
"criticalUpdateTitle": "التحديث ضروري للمتابعة",
"criticalUpdateDescription": "لقد أجرينا تحسينات لتحسين تجربتك! يُرجى التحديث من {currentVersion} إلى {newVersion} لمواصلة استخدام التطبيق."
"criticalUpdateDescription": "لقد أجرينا تحسينات لتحسين تجربتك! يُرجى التحديث من {currentVersion} إلى {newVersion} لمواصلة استخدام التطبيق.",
"criticalUpdateButton": "تحديث",
"bannerUpdateTitle": "النسخة الجديدة متاحة!",
"bannerUpdateDescription": "احصل على أحدث الميزات والإصلاحات. انقر على \"تحديث\" للتثبيت الآن.",
"bannerUpdateButton": "تحديث",
"settingsUpdateTitle": "الإصدار الجديد ({newVersion}) متاح!",
"settingsUpdateDescription": "الإصدار الحالي: {currentVersion} (الإصدار الرسمي) → {newVersion}",
"settingsUpdateButton": "تحديث",
"settingsUpdateWhatsNew": "ما الجديد"
},
"lockPage": {
"lockPage": "مقفل",
"reLockPage": "إعادة القفل",
"lockTooltip": "تم قفل الصفحة لمنع التعديل غير المقصود. انقر لفتح القفل.",
"pageLockedToast": "الصفحة مقفلة. التعديل معطل حتى يفتحها أحد.",
"lockedOperationTooltip": "تم قفل الصفحة لمنع التعديل غير المقصود."
},
"suggestion": {
"accept": "يقبل",
"keep": "يحفظ",
"discard": "تجاهل",
"close": "يغلق",
"tryAgain": "حاول ثانية",
"rewrite": "إعادة كتابة",
"insertBelow": "أدخل أدناه"
}
}
+17 -13
View File
@@ -837,7 +837,7 @@
"menuLabel": "AI Settings",
"keys": {
"enableAISearchTitle": "AI Search",
"aiSettingsDescription": "Choose your preferred model to power AppFlowy AI. Now includes GPT 4-o, Claude 3,5, Llama 3.1, and Mistral 7B",
"aiSettingsDescription": "Choose your preferred model to power AppFlowy AI. Now includes GPT-4o, GPT-o3-mini, DeepSeek R1, Claude 3.5 Sonnet, and models available in Ollama",
"loginToEnableAIFeature": "AI features are only enabled after logging in with @:appName Cloud. If you don't have an @:appName account, go to 'My Account' to sign up",
"llmModel": "Language Model",
"llmModelType": "Language Model Type",
@@ -852,13 +852,14 @@
"localAILoading": "Local AI Chat Model is loading...",
"localAIStopped": "Local AI stopped",
"localAIRunning": "Local AI is running",
"localAIInitializing": "Local AI is loading and may take ßa few minutes, depending on your device",
"localAIInitializing": "Local AI is loading and may take a few minutes, depending on your device",
"localAINotReadyTextFieldPrompt": "You can not edit while Local AI is loading",
"failToLoadLocalAI": "Failed to start local AI",
"restartLocalAI": "Restart Local AI",
"disableLocalAITitle": "Disable local AI",
"disableLocalAIDescription": "Do you want to disable local AI?",
"localAIToggleTitle": "Toggle to enable or disable local AI",
"localAIToggleTitle": "AppFlowy Local AI (LAI)",
"localAIToggleSubTitle": "Run the most advanced local AI models within AppFlowy for ultimate privacy and security",
"offlineAIInstruction1": "Follow the",
"offlineAIInstruction2": "instruction",
"offlineAIInstruction3": "to enable offline AI.",
@@ -2104,19 +2105,22 @@
},
"toolbar": {
"resetToDefaultFont": "Reset to default",
"textSize": "Text Size",
"textSize": "Text size",
"textColor": "Text color",
"h1": "Heading 1",
"h2": "Heading 2",
"h3": "Heading 3",
"alignLeft": "Align Left",
"alignRight": "Align Right",
"alignCenter": "Align Center",
"alignLeft": "Align left",
"alignRight": "Align right",
"alignCenter": "Align center",
"link": "Link",
"textAlign": "Text Align",
"moreOptions": "More Options",
"textAlign": "Text align",
"moreOptions": "More options",
"font": "Font",
"inlineCode": "Inline code",
"suggestions": "Suggestions",
"turnInto": "Turn Into"
"turnInto": "Turn into",
"equation": "Equation"
},
"errorBlock": {
"theBlockIsNotSupported": "Unable to parse the block content",
@@ -2418,9 +2422,9 @@
"link": "Link",
"numberedList": "Numbered list",
"numberedListShortForm": "Numbered",
"toggleHeading1ShortForm": "Toggle h1",
"toggleHeading2ShortForm": "Toggle h2",
"toggleHeading3ShortForm": "Toggle h3",
"toggleHeading1ShortForm": "Toggle H1",
"toggleHeading2ShortForm": "Toggle H2",
"toggleHeading3ShortForm": "Toggle H3",
"quote": "Quote",
"strikethrough": "Strikethrough",
"text": "Text",
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -198,7 +198,7 @@ dependencies = [
[[package]]
name = "appflowy-local-ai"
version = "0.1.0"
source = "git+https://github.com/AppFlowy-IO/AppFlowy-LocalAI?rev=19f9ea7f9cc7c811eef3349ac3f1c5e6fce5c900#19f9ea7f9cc7c811eef3349ac3f1c5e6fce5c900"
source = "git+https://github.com/AppFlowy-IO/AppFlowy-LocalAI?rev=0136d80eeb4366913203db221b6a4aeae99dccd0#0136d80eeb4366913203db221b6a4aeae99dccd0"
dependencies = [
"anyhow",
"appflowy-plugin",
@@ -218,7 +218,7 @@ dependencies = [
[[package]]
name = "appflowy-plugin"
version = "0.1.0"
source = "git+https://github.com/AppFlowy-IO/AppFlowy-LocalAI?rev=19f9ea7f9cc7c811eef3349ac3f1c5e6fce5c900#19f9ea7f9cc7c811eef3349ac3f1c5e6fce5c900"
source = "git+https://github.com/AppFlowy-IO/AppFlowy-LocalAI?rev=0136d80eeb4366913203db221b6a4aeae99dccd0#0136d80eeb4366913203db221b6a4aeae99dccd0"
dependencies = [
"anyhow",
"cfg-if",
+2 -2
View File
@@ -152,5 +152,5 @@ collab-importer = { version = "0.1", git = "https://github.com/AppFlowy-IO/AppFl
# To update the commit ID, run:
# scripts/tool/update_local_ai_rev.sh new_rev_id
# ⚠️⚠️⚠️️
appflowy-local-ai = { version = "0.1", git = "https://github.com/AppFlowy-IO/AppFlowy-LocalAI", rev = "19f9ea7f9cc7c811eef3349ac3f1c5e6fce5c900" }
appflowy-plugin = { version = "0.1", git = "https://github.com/AppFlowy-IO/AppFlowy-LocalAI", rev = "19f9ea7f9cc7c811eef3349ac3f1c5e6fce5c900" }
appflowy-local-ai = { version = "0.1", git = "https://github.com/AppFlowy-IO/AppFlowy-LocalAI", rev = "0136d80eeb4366913203db221b6a4aeae99dccd0" }
appflowy-plugin = { version = "0.1", git = "https://github.com/AppFlowy-IO/AppFlowy-LocalAI", rev = "0136d80eeb4366913203db221b6a4aeae99dccd0" }
@@ -100,6 +100,7 @@ impl EventIntegrationTest {
object_id: "".to_string(),
rag_ids: vec![],
format: None,
history: vec![],
};
EventBuilder::new(self.clone())
.event(AIEvent::CompleteText)
+3 -3
View File
@@ -1,8 +1,8 @@
use bytes::Bytes;
pub use client_api::entity::ai_dto::{
AppFlowyOfflineAI, CompleteTextParams, CompletionMetadata, CompletionType, CreateChatContext,
LLMModel, LocalAIConfig, ModelInfo, ModelList, OutputContent, OutputLayout, RelatedQuestion,
RepeatedRelatedQuestion, ResponseFormat, StringOrMessage,
AppFlowyOfflineAI, CompleteTextParams, CompletionMetadata, CompletionRecord, CompletionType,
CreateChatContext, LLMModel, LocalAIConfig, ModelInfo, ModelList, OutputContent, OutputLayout,
RelatedQuestion, RepeatedRelatedQuestion, ResponseFormat, StringOrMessage,
};
pub use client_api::entity::billing_dto::SubscriptionPlan;
pub use client_api::entity::chat_dto::{
+4 -2
View File
@@ -98,6 +98,8 @@ impl CompletionTask {
};
let _ = sink.send("start:".to_string()).await;
let completion_history = Some(self.context.history.iter().map(Into::into).collect());
let format = self.context.format.map(Into::into).unwrap_or_default();
let params = CompleteTextParams {
text: self.context.text,
completion_type: Some(complete_type),
@@ -106,9 +108,9 @@ impl CompletionTask {
object_id: self.context.object_id,
workspace_id: Some(self.workspace_id.clone()),
rag_ids: Some(self.context.rag_ids),
completion_history: None,
completion_history,
}),
format: self.context.format.map(Into::into).unwrap_or_default(),
format,
};
info!("start completion: {:?}", params);
+27 -2
View File
@@ -4,8 +4,8 @@ use std::collections::HashMap;
use crate::local_ai::controller::LocalAISetting;
use crate::local_ai::resource::PendingResource;
use flowy_ai_pub::cloud::{
ChatMessage, ChatMessageMetadata, ChatMessageType, LLMModel, OutputContent, OutputLayout,
RelatedQuestion, RepeatedChatMessage, RepeatedRelatedQuestion, ResponseFormat,
ChatMessage, ChatMessageMetadata, ChatMessageType, CompletionRecord, LLMModel, OutputContent,
OutputLayout, RelatedQuestion, RepeatedChatMessage, RepeatedRelatedQuestion, ResponseFormat,
};
use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
use lib_infra::validator_fn::required_not_empty_str;
@@ -358,6 +358,9 @@ pub struct CompleteTextPB {
#[pb(index = 6)]
pub rag_ids: Vec<String>,
#[pb(index = 7)]
pub history: Vec<CompletionRecordPB>,
}
#[derive(Default, ProtoBuf, Clone, Debug)]
@@ -378,6 +381,28 @@ pub enum CompletionTypePB {
MakeLonger = 6,
}
#[derive(Default, ProtoBuf, Clone, Debug)]
pub struct CompletionRecordPB {
#[pb(index = 1)]
pub role: ChatMessageTypePB,
#[pb(index = 2)]
pub content: String,
}
impl From<&CompletionRecordPB> for CompletionRecord {
fn from(value: &CompletionRecordPB) -> Self {
CompletionRecord {
role: match value.role {
// Coerce ChatMessageTypePB::System to AI
ChatMessageTypePB::System => "ai".to_string(),
ChatMessageTypePB::User => "human".to_string(),
},
content: value.content.clone(),
}
}
}
#[derive(Default, ProtoBuf, Clone, Debug)]
pub struct ChatStatePB {
#[pb(index = 1)]
@@ -116,46 +116,3 @@ async fn make_request(
}
Ok(response)
}
#[cfg(test)]
mod test {
use super::*;
use std::env::temp_dir;
#[tokio::test]
async fn retrieve_gpt4all_model_test() {
for url in [
// "https://gpt4all.io/models/gguf/all-MiniLM-L6-v2-f16.gguf",
"https://huggingface.co/second-state/All-MiniLM-L6-v2-Embedding-GGUF/resolve/main/all-MiniLM-L6-v2-Q3_K_L.gguf?download=true",
// "https://huggingface.co/MaziyarPanahi/Mistral-7B-Instruct-v0.3-GGUF/resolve/main/Mistral-7B-Instruct-v0.3.Q4_K_M.gguf?download=true",
] {
let temp_dir = temp_dir().join("download_llm");
if !temp_dir.exists() {
fs::create_dir(&temp_dir).await.unwrap();
}
let file_name = "llm_model.gguf";
let cancel_token = CancellationToken::new();
let token = cancel_token.clone();
tokio::spawn(async move {
tokio::time::sleep(tokio::time::Duration::from_secs(120)).await;
token.cancel();
});
let download_file = download_model(
url,
&temp_dir,
file_name,
Some(Arc::new(|a, b| {
println!("{}/{}", a, b);
})),
Some(cancel_token),
).await.unwrap();
let file_path = temp_dir.join(file_name);
assert_eq!(download_file, file_path);
println!("File path: {:?}", file_path);
assert!(file_path.exists());
std::fs::remove_file(file_path).unwrap();
}
}
}
@@ -258,7 +258,7 @@ impl LocalAIResourceController {
let mut config = OllamaPluginConfig::new(
bin_path,
"ollama_ai_plugin".to_string(),
"af_ollama_plugin".to_string(),
llm_setting.chat_model_name.clone(),
llm_setting.embedding_model_name.clone(),
Some(llm_setting.ollama_server_url.clone()),
@@ -101,18 +101,18 @@ pub(crate) fn ollama_plugin_path() -> std::path::PathBuf {
// Use LOCALAPPDATA for a user-specific installation path on Windows.
let local_appdata =
std::env::var("LOCALAPPDATA").unwrap_or_else(|_| "C:\\Program Files".to_string());
std::path::PathBuf::from(local_appdata).join("Programs\\appflowy_plugin\\ollama_ai_plugin.exe")
std::path::PathBuf::from(local_appdata).join("Programs\\appflowy_plugin\\af_ollama_plugin.exe")
}
#[cfg(target_os = "macos")]
{
let offline_app = "ollama_ai_plugin";
let offline_app = "af_ollama_plugin";
std::path::PathBuf::from(format!("/usr/local/bin/{}", offline_app))
}
#[cfg(target_os = "linux")]
{
let offline_app = "ollama_ai_plugin";
let offline_app = "af_ollama_plugin";
std::path::PathBuf::from(format!("/usr/local/bin/{}", offline_app))
}
}
@@ -124,7 +124,7 @@ pub(crate) fn ollama_plugin_command_available() -> bool {
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x08000000;
let output = Command::new("cmd")
.args(&["/C", "where", "ollama_ai_plugin"])
.args(&["/C", "where", "af_ollama_plugin"])
.creation_flags(CREATE_NO_WINDOW)
.output();
if let Ok(output) = output {
@@ -135,7 +135,7 @@ pub(crate) fn ollama_plugin_command_available() -> bool {
// 2. Fallback: Check registry PATH for the executable
let path_dirs = get_windows_path_dirs();
let plugin_exe = "ollama_ai_plugin.exe"; // Adjust name if needed
let plugin_exe = "af_ollama_plugin.exe"; // Adjust name if needed
path_dirs.iter().any(|dir| {
let full_path = std::path::Path::new(dir).join(plugin_exe);
@@ -147,7 +147,7 @@ pub(crate) fn ollama_plugin_command_available() -> bool {
false
} else {
let output = Command::new("command")
.args(["-v", "ollama_ai_plugin"])
.args(["-v", "af_ollama_plugin"])
.output();
match output {
Ok(o) => !o.stdout.is_empty(),