Skip to content

Bring projects, wikis, and teams together with AI. AppFlowy is the AI collaborative workspace where you achieve more without losing control of your data. The leading open source Notion alternative.

feat: allow users to map fields while importing prompts from database (#7938)

Richard Shiuea7b795d3cc98
diff --git a/frontend/appflowy_flutter/lib/ai/service/ai_entities.dart b/frontend/appflowy_flutter/lib/ai/service/ai_entities.dart
index 8b3198cbd7..b5439cb558 100644
--- a/frontend/appflowy_flutter/lib/ai/service/ai_entities.dart
+++ b/frontend/appflowy_flutter/lib/ai/service/ai_entities.dart
@@ -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:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
+import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
@@ -235,3 +236,101 @@ class AiPrompt extends Equatable {
List<Object?> get props =>
[id, name, content, category, example, isFeatured, isCustom];
}
+
+class CustomPromptDatabaseConfig extends Equatable {
+ const CustomPromptDatabaseConfig({
+ required this.view,
+ required this.titleFieldId,
+ required this.contentFieldId,
+ required this.exampleFieldId,
+ required this.categoryFieldId,
+ });
+
+ factory CustomPromptDatabaseConfig.fromAiPB(
+ CustomPromptDatabaseConfigurationPB pb,
+ ViewPB view,
+ ) {
+ final config = CustomPromptDatabaseConfig(
+ view: view,
+ titleFieldId: pb.titleFieldId,
+ contentFieldId: pb.contentFieldId,
+ exampleFieldId: pb.hasExampleFieldId() ? pb.exampleFieldId : null,
+ categoryFieldId: pb.hasCategoryFieldId() ? pb.categoryFieldId : null,
+ );
+
+ return config;
+ }
+
+ factory CustomPromptDatabaseConfig.fromDbPB(
+ CustomPromptDatabaseConfigPB pb,
+ ViewPB view,
+ ) {
+ final config = CustomPromptDatabaseConfig(
+ view: view,
+ titleFieldId: pb.titleFieldId,
+ contentFieldId: pb.contentFieldId,
+ exampleFieldId: pb.hasExampleFieldId() ? pb.exampleFieldId : null,
+ categoryFieldId: pb.hasCategoryFieldId() ? pb.categoryFieldId : null,
+ );
+
+ return config;
+ }
+
+ final ViewPB view;
+ final String titleFieldId;
+ final String contentFieldId;
+ final String? exampleFieldId;
+ final String? categoryFieldId;
+
+ @override
+ List<Object?> get props =>
+ [view.id, titleFieldId, contentFieldId, exampleFieldId, categoryFieldId];
+
+ CustomPromptDatabaseConfig copyWith({
+ ViewPB? view,
+ String? titleFieldId,
+ String? contentFieldId,
+ String? exampleFieldId,
+ String? categoryFieldId,
+ }) {
+ return CustomPromptDatabaseConfig(
+ view: view ?? this.view,
+ titleFieldId: titleFieldId ?? this.titleFieldId,
+ contentFieldId: contentFieldId ?? this.contentFieldId,
+ exampleFieldId: exampleFieldId ?? this.exampleFieldId,
+ categoryFieldId: categoryFieldId ?? this.categoryFieldId,
+ );
+ }
+
+ CustomPromptDatabaseConfigurationPB toAiPB() {
+ final payload = CustomPromptDatabaseConfigurationPB.create()
+ ..viewId = view.id
+ ..titleFieldId = titleFieldId
+ ..contentFieldId = contentFieldId;
+
+ if (exampleFieldId != null) {
+ payload.exampleFieldId = exampleFieldId!;
+ }
+ if (categoryFieldId != null) {
+ payload.categoryFieldId = categoryFieldId!;
+ }
+
+ return payload;
+ }
+
+ CustomPromptDatabaseConfigPB toDbPB() {
+ final payload = CustomPromptDatabaseConfigPB.create()
+ ..viewId = view.id
+ ..titleFieldId = titleFieldId
+ ..contentFieldId = contentFieldId;
+
+ if (exampleFieldId != null) {
+ payload.exampleFieldId = exampleFieldId!;
+ }
+ if (categoryFieldId != null) {
+ payload.categoryFieldId = categoryFieldId!;
+ }
+
+ return payload;
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/ai/service/ai_prompt_database_selector_cubit.dart b/frontend/appflowy_flutter/lib/ai/service/ai_prompt_database_selector_cubit.dart
new file mode 100644
index 0000000000..0038ad0eb8
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/ai/service/ai_prompt_database_selector_cubit.dart
@@ -0,0 +1,161 @@
+import 'package:appflowy/ai/ai.dart';
+import 'package:appflowy/plugins/database/domain/field_service.dart';
+import 'package:appflowy_backend/dispatch/dispatch.dart';
+import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
+import 'package:appflowy_result/appflowy_result.dart';
+import 'package:bloc/bloc.dart';
+import 'package:freezed_annotation/freezed_annotation.dart';
+
+part 'ai_prompt_database_selector_cubit.freezed.dart';
+
+class AiPromptDatabaseSelectorCubit
+ extends Cubit<AiPromptDatabaseSelectorState> {
+ AiPromptDatabaseSelectorCubit({
+ required CustomPromptDatabaseConfig? configuration,
+ }) : super(AiPromptDatabaseSelectorState.loading()) {
+ _init(configuration);
+ }
+
+ void _init(CustomPromptDatabaseConfig? config) async {
+ if (config == null) {
+ emit(AiPromptDatabaseSelectorState.empty());
+ return;
+ }
+
+ final fields = await _getFields(config.view.id);
+
+ if (fields == null) {
+ emit(AiPromptDatabaseSelectorState.empty());
+ return;
+ }
+
+ emit(
+ AiPromptDatabaseSelectorState.selected(
+ config: config,
+ fields: fields,
+ ),
+ );
+ }
+
+ void selectDatabaseView(String viewId) async {
+ final configuration = await _testDatabase(viewId);
+
+ if (configuration == null) {
+ final stateCopy = state;
+ emit(AiPromptDatabaseSelectorState.invalidDatabase());
+ emit(stateCopy);
+ return;
+ }
+
+ final databaseView = await AiPromptSelectorCubit.getDatabaseView(viewId);
+ final fields = await _getFields(viewId);
+
+ if (databaseView == null || fields == null) {
+ final stateCopy = state;
+ emit(AiPromptDatabaseSelectorState.invalidDatabase());
+ emit(stateCopy);
+ return;
+ }
+
+ final config = CustomPromptDatabaseConfig.fromDbPB(
+ configuration,
+ databaseView,
+ );
+
+ emit(
+ AiPromptDatabaseSelectorState.selected(
+ config: config,
+ fields: fields,
+ ),
+ );
+ }
+
+ void selectContentField(String fieldId) {
+ final state = this.state;
+ if (state is! _Selected) {
+ return;
+ }
+
+ final config = state.config.copyWith(
+ contentFieldId: fieldId,
+ );
+
+ emit(
+ AiPromptDatabaseSelectorState.selected(
+ config: config,
+ fields: state.fields,
+ ),
+ );
+ }
+
+ void selectExampleField(String? fieldId) {
+ final state = this.state;
+ if (state is! _Selected) {
+ return;
+ }
+
+ final config = CustomPromptDatabaseConfig(
+ exampleFieldId: fieldId,
+ view: state.config.view,
+ titleFieldId: state.config.titleFieldId,
+ contentFieldId: state.config.contentFieldId,
+ categoryFieldId: state.config.categoryFieldId,
+ );
+
+ emit(
+ AiPromptDatabaseSelectorState.selected(
+ config: config,
+ fields: state.fields,
+ ),
+ );
+ }
+
+ void selectCategoryField(String? fieldId) {
+ final state = this.state;
+ if (state is! _Selected) {
+ return;
+ }
+
+ final config = CustomPromptDatabaseConfig(
+ categoryFieldId: fieldId,
+ view: state.config.view,
+ titleFieldId: state.config.titleFieldId,
+ contentFieldId: state.config.contentFieldId,
+ exampleFieldId: state.config.exampleFieldId,
+ );
+
+ emit(
+ AiPromptDatabaseSelectorState.selected(
+ config: config,
+ fields: state.fields,
+ ),
+ );
+ }
+
+ Future<List<FieldPB>?> _getFields(String viewId) {
+ return FieldBackendService.getFields(viewId: viewId).toNullable();
+ }
+
+ Future<CustomPromptDatabaseConfigPB?> _testDatabase(
+ String viewId,
+ ) {
+ return DatabaseEventTestCustomPromptDatabaseConfiguration(
+ DatabaseViewIdPB(value: viewId),
+ ).send().toNullable();
+ }
+}
+
+@freezed
+class AiPromptDatabaseSelectorState with _$AiPromptDatabaseSelectorState {
+ const factory AiPromptDatabaseSelectorState.loading() = _Loading;
+
+ const factory AiPromptDatabaseSelectorState.empty() = _Empty;
+
+ const factory AiPromptDatabaseSelectorState.selected({
+ required CustomPromptDatabaseConfig config,
+ required List<FieldPB> fields,
+ }) = _Selected;
+
+ const factory AiPromptDatabaseSelectorState.invalidDatabase() =
+ _InvalidDatabase;
+}
diff --git a/frontend/appflowy_flutter/lib/ai/service/ai_prompt_selector_cubit.dart b/frontend/appflowy_flutter/lib/ai/service/ai_prompt_selector_cubit.dart
index 3bc874fd4b..2679ad7598 100644
--- a/frontend/appflowy_flutter/lib/ai/service/ai_prompt_selector_cubit.dart
+++ b/frontend/appflowy_flutter/lib/ai/service/ai_prompt_selector_cubit.dart
@@ -1,12 +1,16 @@
+import 'dart:async';
+
+import 'package:appflowy/workspace/application/view/prelude.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart';
-import 'package:appflowy_backend/protobuf/flowy-ai/protobuf.dart';
+import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:bloc/bloc.dart';
import 'package:collection/collection.dart';
import 'package:flutter/widgets.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
+import '../../plugins/trash/application/trash_service.dart';
import 'ai_entities.dart';
import 'appflowy_ai_service.dart';
@@ -44,7 +48,7 @@ class AiPromptSelectorCubit extends Cubit<AiPromptSelectorState> {
isCustomPromptSectionSelected: false,
isFeaturedSectionSelected: true,
selectedPromptId: visiblePrompts.firstOrNull?.id,
- customPromptDatabaseViewId: null,
+ databaseConfig: null,
isLoadingCustomPrompts: true,
selectedCategory: null,
favoritePrompts: [],
@@ -61,14 +65,24 @@ class AiPromptSelectorCubit extends Cubit<AiPromptSelectorState> {
readyState.copyWith(isLoadingCustomPrompts: true),
);
- String? databaseViewId = readyState.customPromptDatabaseViewId;
- if (databaseViewId == null) {
- final result =
- await AIEventGetCustomPromptDatabaseViewId().send().toNullable();
- databaseViewId = result?.id;
+ CustomPromptDatabaseConfig? configuration = readyState.databaseConfig;
+ if (configuration == null) {
+ final configResult =
+ await AIEventGetCustomPromptDatabaseConfiguration()
+ .send()
+ .toNullable();
+ if (configResult != null) {
+ final view = await getDatabaseView(configResult.viewId);
+ if (view != null) {
+ configuration = CustomPromptDatabaseConfig.fromAiPB(
+ configResult,
+ view,
+ );
+ }
+ }
}
- if (databaseViewId == null) {
+ if (configuration == null) {
emit(
readyState.copyWith(isLoadingCustomPrompts: false),
);
@@ -78,7 +92,7 @@ class AiPromptSelectorCubit extends Cubit<AiPromptSelectorState> {
availablePrompts.removeWhere((prompt) => prompt.isCustom);
final customPrompts =
- await _aiService.getDatabasePrompts(databaseViewId);
+ await _aiService.getDatabasePrompts(configuration.toDbPB());
if (customPrompts == null) {
final prompts = availablePrompts.where((prompt) => prompt.isFeatured);
@@ -92,7 +106,7 @@ class AiPromptSelectorCubit extends Cubit<AiPromptSelectorState> {
readyState.copyWith(
visiblePrompts: visiblePrompts.toList(),
selectedPromptId: selectedPromptId,
- customPromptDatabaseViewId: databaseViewId,
+ databaseConfig: configuration,
isLoadingCustomPrompts: false,
isFeaturedSectionSelected: true,
isCustomPromptSectionSelected: false,
@@ -112,7 +126,7 @@ class AiPromptSelectorCubit extends Cubit<AiPromptSelectorState> {
emit(
readyState.copyWith(
visiblePrompts: visiblePrompts.toList(),
- customPromptDatabaseViewId: databaseViewId,
+ databaseConfig: configuration,
isLoadingCustomPrompts: false,
selectedPromptId: selectedPromptId,
),
@@ -240,58 +254,48 @@ class AiPromptSelectorCubit extends Cubit<AiPromptSelectorState> {
);
}
- void updateCustomPromptDatabaseViewId(String viewId) async {
- final stateCopy = state;
- final newState = state.maybeMap(
- ready: (readyState) {
- return readyState.customPromptDatabaseViewId == viewId
- ? null
- : readyState.copyWith(isLoadingCustomPrompts: true);
- },
- orElse: () => null,
- );
-
- if (newState == null) {
- return;
- }
- emit(newState);
-
- await Future.delayed(const Duration(seconds: 1));
+ void updateCustomPromptDatabaseConfiguration(
+ CustomPromptDatabaseConfig configuration,
+ ) async {
+ state.maybeMap(
+ ready: (readyState) async {
+ emit(
+ readyState.copyWith(isLoadingCustomPrompts: true),
+ );
- final customPrompts = await _aiService.getDatabasePrompts(viewId);
- if (customPrompts == null) {
- emit(AiPromptSelectorState.invalidDatabase());
- emit(stateCopy);
+ final customPrompts =
+ await _aiService.getDatabasePrompts(configuration.toDbPB());
- return;
- }
+ if (customPrompts == null) {
+ emit(AiPromptSelectorState.invalidDatabase());
+ emit(readyState);
+ return;
+ }
- availablePrompts
- ..removeWhere((prompt) => prompt.isCustom)
- ..addAll(customPrompts);
+ availablePrompts
+ ..removeWhere((prompt) => prompt.isCustom)
+ ..addAll(customPrompts);
- await AIEventSetCustomPromptDatabaseViewId(
- CustomPromptDatabaseViewIdPB()..id = viewId,
- ).send().onFailure(Log.error);
+ await AIEventSetCustomPromptDatabaseConfiguration(
+ configuration.toAiPB(),
+ ).send().onFailure(Log.error);
- emit(
- state.maybeMap(
- ready: (readyState) {
- final prompts = _getPromptsByCategory(readyState);
- final visiblePrompts = _getFilteredPrompts(prompts);
- final selectedPromptId = _getVisibleSelectedPrompt(
- visiblePrompts,
- readyState.selectedPromptId,
- );
- return readyState.copyWith(
+ final prompts = _getPromptsByCategory(readyState);
+ final visiblePrompts = _getFilteredPrompts(prompts);
+ final selectedPromptId = _getVisibleSelectedPrompt(
+ visiblePrompts,
+ readyState.selectedPromptId,
+ );
+ emit(
+ readyState.copyWith(
visiblePrompts: visiblePrompts.toList(),
selectedPromptId: selectedPromptId,
- customPromptDatabaseViewId: viewId,
+ databaseConfig: configuration,
isLoadingCustomPrompts: false,
- );
- },
- orElse: () => state,
- ),
+ ),
+ );
+ },
+ orElse: () => {},
);
}
@@ -352,6 +356,26 @@ class AiPromptSelectorCubit extends Cubit<AiPromptSelectorState> {
return visiblePrompts.firstOrNull?.id;
}
+
+ static Future<ViewPB?> getDatabaseView(String viewId) async {
+ final view = await ViewBackendService.getView(viewId).toNullable();
+
+ if (view != null) {
+ return view;
+ }
+
+ final trashViews = await TrashService().readTrash().toNullable();
+ final trashedItem =
+ trashViews?.items.firstWhereOrNull((element) => element.id == viewId);
+
+ if (trashedItem == null) {
+ return null;
+ }
+
+ return ViewPB()
+ ..id = trashedItem.id
+ ..name = trashedItem.name;
+ }
}
@freezed
@@ -371,7 +395,7 @@ class AiPromptSelectorState with _$AiPromptSelectorState {
required AiPromptCategory? selectedCategory,
required String? selectedPromptId,
required bool isLoadingCustomPrompts,
- required String? customPromptDatabaseViewId,
+ required CustomPromptDatabaseConfig? databaseConfig,
}) = _AiPromptSelectorReadyState;
bool get isLoading => this is _AiPromptSelectorLoadingState;
diff --git a/frontend/appflowy_flutter/lib/ai/service/appflowy_ai_service.dart b/frontend/appflowy_flutter/lib/ai/service/appflowy_ai_service.dart
index b846489d52..8d56b9d32c 100644
--- a/frontend/appflowy_flutter/lib/ai/service/appflowy_ai_service.dart
+++ b/frontend/appflowy_flutter/lib/ai/service/appflowy_ai_service.dart
@@ -8,7 +8,8 @@ import 'package:appflowy/plugins/document/presentation/editor_plugins/ai/operati
import 'package:appflowy/shared/list_extension.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart';
-import 'package:appflowy_backend/protobuf/flowy-ai/entities.pb.dart';
+import 'package:appflowy_backend/protobuf/flowy-ai/protobuf.dart'
+ hide CustomPromptDatabaseConfigurationPB;
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:easy_localization/easy_localization.dart';
@@ -42,7 +43,9 @@ abstract class AIRepository {
Future<List<AiPrompt>> getBuiltInPrompts();
- Future<List<AiPrompt>?> getDatabasePrompts(String databaseViewId);
+ Future<List<AiPrompt>?> getDatabasePrompts(
+ CustomPromptDatabaseConfigPB config,
+ );
void updateFavoritePrompts(List<String> promptIds);
}
@@ -122,14 +125,11 @@ class AppFlowyAIService implements AIRepository {
@override
Future<List<AiPrompt>?> getDatabasePrompts(
- String databaseViewId,
+ CustomPromptDatabaseConfigPB config,
) async {
- return DatabaseEventGetDatabaseCustomPrompts(
- DatabaseViewIdPB(value: databaseViewId),
- ).send().fold(
- (databasePromptsPB) {
- return databasePromptsPB.items.map(AiPrompt.fromPB).toList();
- },
+ return DatabaseEventGetDatabaseCustomPrompts(config).send().fold(
+ (databasePromptsPB) =>
+ databasePromptsPB.items.map(AiPrompt.fromPB).toList(),
(err) {
Log.error(err);
return null;
diff --git a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_database_modal.dart b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_database_modal.dart
new file mode 100644
index 0000000000..cb00ef74c5
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_database_modal.dart
@@ -0,0 +1,657 @@
+import 'package:appflowy/ai/ai.dart';
+import 'package:appflowy/ai/service/ai_prompt_database_selector_cubit.dart';
+import 'package:appflowy/generated/flowy_svgs.g.dart';
+import 'package:appflowy/generated/locale_keys.g.dart';
+import 'package:appflowy/workspace/application/sidebar/space/space_bloc.dart';
+import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart';
+import 'package:appflowy/workspace/application/view/view_ext.dart';
+import 'package:appflowy/workspace/presentation/home/menu/view/view_item.dart';
+import 'package:appflowy/workspace/presentation/widgets/dialog_v2.dart';
+import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
+import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
+import 'package:appflowy_ui/appflowy_ui.dart';
+import 'package:collection/collection.dart';
+import 'package:easy_localization/easy_localization.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';
+
+Future<CustomPromptDatabaseConfig?> changeCustomPromptDatabaseConfig(
+ BuildContext context, {
+ CustomPromptDatabaseConfig? config,
+}) async {
+ return showDialog<CustomPromptDatabaseConfig?>(
+ context: context,
+ builder: (_) {
+ return MultiBlocProvider(
+ providers: [
+ BlocProvider.value(
+ value: context.read<UserWorkspaceBloc>(),
+ ),
+ BlocProvider(
+ create: (context) => AiPromptDatabaseSelectorCubit(
+ configuration: config,
+ ),
+ ),
+ ],
+ child: const AiPromptDatabaseModal(),
+ );
+ },
+ );
+}
+
+class AiPromptDatabaseModal extends StatefulWidget {
+ const AiPromptDatabaseModal({
+ super.key,
+ });
+
+ @override
+ State<AiPromptDatabaseModal> createState() => _AiPromptDatabaseModalState();
+}
+
+class _AiPromptDatabaseModalState extends State<AiPromptDatabaseModal> {
+ final expandableController = ExpandableController(initialExpanded: false);
+
+ @override
+ void dispose() {
+ expandableController.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = AppFlowyTheme.of(context);
+
+ return BlocListener<AiPromptDatabaseSelectorCubit,
+ AiPromptDatabaseSelectorState>(
+ listener: (context, state) {
+ state.maybeMap(
+ invalidDatabase: (_) {
+ showSimpleAFDialog(
+ context: context,
+ title: LocaleKeys.ai_customPrompt_invalidDatabase.tr(),
+ content: LocaleKeys.ai_customPrompt_invalidDatabaseHelp.tr(),
+ primaryAction: (
+ LocaleKeys.button_ok.tr(),
+ (context) {},
+ ),
+ );
+ },
+ empty: (_) => expandableController.expanded = false,
+ selected: (_) => expandableController.expanded = true,
+ orElse: () {},
+ );
+ },
+ child: AFModal(
+ constraints: const BoxConstraints(
+ maxWidth: 450,
+ maxHeight: 400,
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ AFModalHeader(
+ leading: Text(
+ LocaleKeys.ai_customPrompt_configureDatabase.tr(),
+ style: theme.textStyle.heading4.prominent(
+ color: theme.textColorScheme.primary,
+ ),
+ ),
+ trailing: [
+ AFGhostButton.normal(
+ onTap: () => Navigator.of(context).pop(),
+ padding: EdgeInsets.all(theme.spacing.xs),
+ builder: (context, isHovering, disabled) {
+ return Center(
+ child: FlowySvg(
+ FlowySvgs.toast_close_s,
+ size: Size.square(20),
+ ),
+ );
+ },
+ ),
+ ],
+ ),
+ Flexible(
+ child: AFModalBody(
+ child: ExpandablePanel(
+ controller: expandableController,
+ theme: ExpandableThemeData(
+ tapBodyToCollapse: false,
+ hasIcon: false,
+ tapBodyToExpand: false,
+ tapHeaderToExpand: false,
+ ),
+ header: const _Header(),
+ collapsed: const SizedBox.shrink(),
+ expanded: const _Expanded(),
+ ),
+ ),
+ ),
+ AFModalFooter(
+ trailing: [
+ AFOutlinedButton.normal(
+ onTap: () => Navigator.of(context).pop(),
+ builder: (context, isHovering, disabled) {
+ return Text(
+ LocaleKeys.button_cancel.tr(),
+ style: theme.textStyle.body.standard(
+ color: theme.textColorScheme.primary,
+ ),
+ );
+ },
+ ),
+ AFFilledButton.primary(
+ onTap: () {
+ final config = context
+ .read<AiPromptDatabaseSelectorCubit>()
+ .state
+ .maybeMap(
+ selected: (state) => state.config,
+ orElse: () => null,
+ );
+ Navigator.of(context).pop(config);
+ },
+ builder: (context, isHovering, disabled) {
+ return Text(
+ LocaleKeys.button_done.tr(),
+ style: theme.textStyle.body.enhanced(
+ color: theme.textColorScheme.onFill,
+ ),
+ );
+ },
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class _Header extends StatefulWidget {
+ const _Header();
+
+ @override
+ State<_Header> createState() => _HeaderState();
+}
+
+class _HeaderState extends State<_Header> {
+ final popoverController = AFPopoverController();
+
+ @override
+ void dispose() {
+ popoverController.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = AppFlowyTheme.of(context);
+
+ return BlocBuilder<AiPromptDatabaseSelectorCubit,
+ AiPromptDatabaseSelectorState>(
+ builder: (context, state) {
+ bool showNothing = false;
+ String? viewName;
+ state.maybeMap(
+ empty: (_) {
+ showNothing = false;
+ viewName = null;
+ },
+ selected: (selectedState) {
+ showNothing = false;
+ viewName = selectedState.config.view.nameOrDefault;
+ },
+ orElse: () {
+ showNothing = true;
+ viewName = null;
+ },
+ );
+
+ if (showNothing) {
+ return SizedBox.shrink();
+ }
+
+ return Center(
+ child: ViewSelector(
+ viewSelectorCubit: BlocProvider(
+ create: (context) => ViewSelectorCubit(
+ getIgnoreViewType: getIgnoreViewType,
+ ),
+ ),
+ child: BlocSelector<SpaceBloc, SpaceState, (List<ViewPB>, ViewPB?)>(
+ selector: (state) => (state.spaces, state.currentSpace),
+ builder: (context, state) {
+ return Padding(
+ padding: EdgeInsets.symmetric(
+ vertical: theme.spacing.xl,
+ ),
+ child: AFPopover(
+ controller: popoverController,
+ decoration: BoxDecoration(
+ color: theme.surfaceColorScheme.primary,
+ borderRadius: BorderRadius.circular(theme.borderRadius.l),
+ border: Border.all(
+ color: theme.borderColorScheme.primary,
+ ),
+ boxShadow: theme.shadow.medium,
+ ),
+ anchor: AFAnchor(
+ childAlignment: Alignment.topCenter,
+ overlayAlignment: Alignment.bottomCenter,
+ offset: Offset(0, theme.spacing.xs),
+ ),
+ popover: (context) {
+ return _PopoverContent(
+ onSelectViewItem: (item) {
+ context
+ .read<AiPromptDatabaseSelectorCubit>()
+ .selectDatabaseView(item.view.id);
+ popoverController.hide();
+ },
+ );
+ },
+ child: AFOutlinedButton.normal(
+ onTap: () {
+ context
+ .read<ViewSelectorCubit>()
+ .refreshSources(state.$1, state.$2);
+ popoverController.toggle();
+ },
+ builder: (context, isHovering, disabled) {
+ return Row(
+ mainAxisSize: MainAxisSize.min,
+ spacing: theme.spacing.s,
+ children: [
+ Flexible(
+ child: Text(
+ viewName == null
+ ? LocaleKeys.ai_customPrompt_selectDatabase
+ .tr()
+ : viewName!,
+ style: theme.textStyle.body.enhanced(
+ color: theme.textColorScheme.primary,
+ ),
+ ),
+ ),
+ FlowySvg(
+ FlowySvgs.toolbar_arrow_down_m,
+ size: Size(12, 20),
+ ),
+ ],
+ );
+ },
+ ),
+ ),
+ );
+ },
+ ),
+ ),
+ );
+ },
+ );
+ }
+
+ IgnoreViewType getIgnoreViewType(ViewSelectorItem item) {
+ final layout = item.view.layout;
+
+ if (layout.isDatabaseView) {
+ return IgnoreViewType.none;
+ }
+ if (layout.isDocumentView) {
+ return hasDatabaseDescendent(item)
+ ? IgnoreViewType.none
+ : IgnoreViewType.hide;
+ }
+ return IgnoreViewType.hide;
+ }
+
+ bool hasDatabaseDescendent(ViewSelectorItem viewSelectorItem) {
+ final layout = viewSelectorItem.view.layout;
+
+ if (layout == ViewLayoutPB.Chat) {
+ return false;
+ }
+
+ if (layout.isDatabaseView) {
+ return true;
+ }
+
+ // document may have children
+ return viewSelectorItem.children.any(
+ (child) => hasDatabaseDescendent(child),
+ );
+ }
+}
+
+class _Expanded extends StatelessWidget {
+ const _Expanded();
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = AppFlowyTheme.of(context);
+
+ return BlocBuilder<AiPromptDatabaseSelectorCubit,
+ AiPromptDatabaseSelectorState>(
+ builder: (context, state) {
+ return state.maybeMap(
+ orElse: () => SizedBox.shrink(),
+ selected: (selectedState) {
+ return Container(
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(theme.borderRadius.l),
+ ),
+ padding: EdgeInsets.all(
+ theme.spacing.m,
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ spacing: theme.spacing.m,
+ children: [
+ FieldSelector(
+ title: LocaleKeys.ai_customPrompt_title.tr(),
+ currentFieldId: selectedState.config.titleFieldId,
+ isDisabled: true,
+ onSelect: (id) {},
+ ),
+ FieldSelector(
+ title: LocaleKeys.ai_customPrompt_content.tr(),
+ currentFieldId: selectedState.config.contentFieldId,
+ onSelect: (id) {
+ if (id != null) {
+ context
+ .read<AiPromptDatabaseSelectorCubit>()
+ .selectContentField(id);
+ }
+ },
+ ),
+ FieldSelector(
+ title: LocaleKeys.ai_customPrompt_example.tr(),
+ currentFieldId: selectedState.config.exampleFieldId,
+ isOptional: true,
+ onSelect: (id) {
+ context
+ .read<AiPromptDatabaseSelectorCubit>()
+ .selectExampleField(id);
+ },
+ ),
+ FieldSelector(
+ title: LocaleKeys.ai_customPrompt_category.tr(),
+ currentFieldId: selectedState.config.categoryFieldId,
+ isOptional: true,
+ onSelect: (id) {
+ context
+ .read<AiPromptDatabaseSelectorCubit>()
+ .selectCategoryField(id);
+ },
+ ),
+ ],
+ ),
+ );
+ },
+ );
+ },
+ );
+ }
+}
+
+class _PopoverContent extends StatefulWidget {
+ const _PopoverContent({
+ required this.onSelectViewItem,
+ });
+
+ final void Function(ViewSelectorItem item) onSelectViewItem;
+
+ @override
+ State<_PopoverContent> createState() => _PopoverContentState();
+}
+
+class _PopoverContentState extends State<_PopoverContent> {
+ final focusNode = FocusNode();
+
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ focusNode.requestFocus();
+ });
+ }
+
+ @override
+ void dispose() {
+ focusNode.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = AppFlowyTheme.of(context);
+
+ return ConstrainedBox(
+ constraints: const BoxConstraints.tightFor(
+ width: 300,
+ height: 400,
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ VSpace(
+ theme.spacing.m,
+ ),
+ Padding(
+ padding: EdgeInsets.symmetric(
+ horizontal: theme.spacing.m,
+ ),
+ child: AFTextField(
+ focusNode: focusNode,
+ size: AFTextFieldSize.m,
+ hintText: LocaleKeys.search_label.tr(),
+ controller:
+ context.read<ViewSelectorCubit>().filterTextController,
+ ),
+ ),
+ VSpace(
+ theme.spacing.m,
+ ),
+ AFDivider(),
+ Expanded(
+ child: BlocBuilder<ViewSelectorCubit, ViewSelectorState>(
+ builder: (context, state) {
+ return ListView(
+ shrinkWrap: true,
+ padding: const EdgeInsets.fromLTRB(8, 4, 8, 12),
+ children: _buildVisibleSources(context, state).toList(),
+ );
+ },
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Iterable<Widget> _buildVisibleSources(
+ BuildContext context,
+ ViewSelectorState state,
+ ) {
+ return state.visibleSources.map(
+ (e) => ViewSelectorTreeItem(
+ key: ValueKey(
+ 'custom_prompt_database_tree_item_${e.view.id}',
+ ),
+ viewSelectorItem: e,
+ level: 0,
+ isDescendentOfSpace: e.view.isSpace,
+ isSelectedSection: false,
+ showCheckbox: false,
+ onSelected: (item) {
+ if (item.view.isDocument || item.view.isSpace) {
+ context.read<ViewSelectorCubit>().toggleIsExpanded(item, false);
+ return;
+ }
+ widget.onSelectViewItem(item);
+ },
+ height: 30.0,
+ ),
+ );
+ }
+}
+
+class FieldSelector extends StatefulWidget {
+ const FieldSelector({
+ super.key,
+ required this.title,
+ required this.currentFieldId,
+ this.isDisabled = false,
+ this.isOptional = false,
+ required this.onSelect,
+ });
+
+ final String title;
+ final String? currentFieldId;
+ final bool isDisabled;
+ final bool isOptional;
+ final void Function(String? id)? onSelect;
+
+ @override
+ State<FieldSelector> createState() => _FieldSelectorState();
+}
+
+class _FieldSelectorState extends State<FieldSelector> {
+ final popoverController = AFPopoverController();
+
+ @override
+ void dispose() {
+ popoverController.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = AppFlowyTheme.of(context);
+
+ return BlocBuilder<AiPromptDatabaseSelectorCubit,
+ AiPromptDatabaseSelectorState>(
+ builder: (context, state) {
+ final fields = _getVisibleFields(state);
+ final selectedField = fields.firstWhereOrNull(
+ (field) => field.id == widget.currentFieldId,
+ );
+
+ return Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text(
+ widget.title,
+ style: theme.textStyle.body.standard(
+ color: theme.textColorScheme.secondary,
+ ),
+ ),
+ AFPopover(
+ controller: popoverController,
+ decoration: BoxDecoration(
+ color: theme.surfaceColorScheme.primary,
+ borderRadius: BorderRadius.circular(theme.borderRadius.l),
+ border: Border.all(
+ color: theme.borderColorScheme.primary,
+ ),
+ boxShadow: theme.shadow.medium,
+ ),
+ anchor: AFAnchor(
+ childAlignment: Alignment.topRight,
+ overlayAlignment: Alignment.bottomRight,
+ offset: Offset(0, theme.spacing.xs),
+ ),
+ popover: (context) {
+ return ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 240),
+ child: ListView.builder(
+ itemCount: fields.length + (widget.isOptional ? 1 : 0),
+ shrinkWrap: true,
+ padding: EdgeInsets.all(theme.spacing.m),
+ itemBuilder: (context, index) {
+ if (widget.isOptional && index == 0) {
+ return AFMenuItem(
+ title: LocaleKeys.ai_customPrompt_selectField.tr(),
+ onTap: () {
+ widget.onSelect?.call(null);
+ popoverController.hide();
+ },
+ trailing: selectedField == null
+ ? FlowySvg(
+ FlowySvgs.check_s,
+ size: const Size.square(20),
+ color: theme.fillColorScheme.themeThick,
+ )
+ : null,
+ );
+ }
+ final field = fields[index - (widget.isOptional ? 1 : 0)];
+ return AFMenuItem(
+ title: field.name,
+ trailing: field.id == selectedField?.id
+ ? FlowySvg(
+ FlowySvgs.check_s,
+ size: const Size.square(20),
+ color: theme.fillColorScheme.themeThick,
+ )
+ : null,
+ onTap: () {
+ widget.onSelect?.call(field.id);
+ popoverController.hide();
+ },
+ );
+ },
+ ),
+ );
+ },
+ child: AFOutlinedButton.normal(
+ disabled: widget.isDisabled,
+ builder: (context, isHovering, disabled) {
+ return Row(
+ children: [
+ Text(
+ selectedField?.name ??
+ LocaleKeys.ai_customPrompt_selectField.tr(),
+ style: theme.textStyle.body.enhanced(
+ color: disabled
+ ? theme.textColorScheme.tertiary
+ : selectedField == null
+ ? theme.textColorScheme.secondary
+ : theme.textColorScheme.primary,
+ ),
+ ),
+ HSpace(
+ theme.spacing.s,
+ ),
+ FlowySvg(
+ FlowySvgs.toolbar_arrow_down_m,
+ size: Size(12, 20),
+ ),
+ ],
+ );
+ },
+ onTap: () => popoverController.toggle(),
+ ),
+ ),
+ ],
+ );
+ },
+ );
+ }
+
+ List<FieldPB> _getVisibleFields(AiPromptDatabaseSelectorState state) {
+ return state.maybeMap(
+ orElse: () => [],
+ selected: (value) {
+ return value.fields
+ .where((field) => field.fieldType == FieldType.RichText)
+ .toList();
+ },
+ );
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_database_selector.dart b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_database_selector.dart
deleted file mode 100644
index a003e9d3aa..0000000000
--- a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_database_selector.dart
+++ /dev/null
@@ -1,346 +0,0 @@
-import 'package:appflowy/ai/ai.dart';
-import 'package:appflowy/generated/locale_keys.g.dart';
-import 'package:appflowy/plugins/trash/application/trash_service.dart';
-import 'package:appflowy/workspace/application/sidebar/space/space_bloc.dart';
-import 'package:appflowy/workspace/application/view/prelude.dart';
-import 'package:appflowy/workspace/application/view/view_ext.dart';
-import 'package:appflowy/workspace/presentation/home/menu/view/view_item.dart';
-import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
-import 'package:appflowy_result/appflowy_result.dart';
-import 'package:appflowy_ui/appflowy_ui.dart';
-import 'package:collection/collection.dart';
-import 'package:easy_localization/easy_localization.dart';
-import 'package:flowy_infra_ui/flowy_infra_ui.dart';
-import 'package:flutter/material.dart';
-import 'package:flutter_bloc/flutter_bloc.dart';
-
-class CustomPromptDatabaseSelector extends StatefulWidget {
- const CustomPromptDatabaseSelector({
- super.key,
- this.databaseViewId,
- this.isLoading = false,
- this.popoverDirection = PopoverDirection.bottomWithCenterAligned,
- required this.childBuilder,
- });
-
- final String? databaseViewId;
- final bool isLoading;
- final PopoverDirection popoverDirection;
- final Widget Function(VoidCallback) childBuilder;
-
- @override
- State<CustomPromptDatabaseSelector> createState() =>
- _CustomPromptDatabaseSelectorState();
-}
-
-class _CustomPromptDatabaseSelectorState
- extends State<CustomPromptDatabaseSelector> {
- final popoverController = PopoverController();
-
- @override
- Widget build(BuildContext context) {
- return ViewSelector(
- viewSelectorCubit: BlocProvider(
- create: (context) => ViewSelectorCubit(
- getIgnoreViewType: getIgnoreViewType,
- ),
- ),
- child: BlocSelector<SpaceBloc, SpaceState, (List<ViewPB>, ViewPB?)>(
- selector: (state) => (state.spaces, state.currentSpace),
- builder: (context, state) {
- return AppFlowyPopover(
- controller: popoverController,
- triggerActions: PopoverTriggerFlags.none,
- margin: EdgeInsets.zero,
- offset: const Offset(0, 4.0),
- direction: widget.popoverDirection,
- constraints: const BoxConstraints.tightFor(width: 300, height: 400),
- popupBuilder: (_) {
- return BlocProvider.value(
- value: context.read<ViewSelectorCubit>(),
- child: _PopoverContent(
- onSelectViewItem: (item) {
- final view = item.view;
- if (view.layout.isDatabaseView) {
- context
- .read<AiPromptSelectorCubit>()
- .updateCustomPromptDatabaseViewId(view.id);
- popoverController.close();
- } else if (!view.isSpace && view.layout.isDocumentView) {
- context.read<ViewSelectorCubit>().toggleIsExpanded(
- item,
- false,
- );
- }
- },
- ),
- );
- },
- child: widget.childBuilder(
- () {
- if (!widget.isLoading) {
- context
- .read<ViewSelectorCubit>()
- .refreshSources(state.$1, state.$2);
- popoverController.show();
- }
- },
- ),
- );
- },
- ),
- );
- }
-
- IgnoreViewType getIgnoreViewType(ViewSelectorItem item) {
- final layout = item.view.layout;
-
- if (layout.isDatabaseView) {
- return IgnoreViewType.none;
- }
- if (layout.isDocumentView) {
- return hasDatabaseDescendent(item)
- ? IgnoreViewType.none
- : IgnoreViewType.hide;
- }
- return IgnoreViewType.hide;
- }
-
- bool hasDatabaseDescendent(ViewSelectorItem viewSelectorItem) {
- final layout = viewSelectorItem.view.layout;
-
- if (layout == ViewLayoutPB.Chat) {
- return false;
- }
-
- if (layout.isDatabaseView) {
- return true;
- }
-
- // document may have children
- return viewSelectorItem.children.any(
- (child) => hasDatabaseDescendent(child),
- );
- }
-}
-
-class AiPromptDatabaseSelectorButton extends StatefulWidget {
- const AiPromptDatabaseSelectorButton({
- super.key,
- required this.selectedViewId,
- required this.isLoading,
- required this.onTap,
- });
-
- final String? selectedViewId;
- final bool isLoading;
- final VoidCallback onTap;
-
- @override
- State<AiPromptDatabaseSelectorButton> createState() =>
- _AiPromptDatabaseSelectorButtonState();
-}
-
-class _AiPromptDatabaseSelectorButtonState
- extends State<AiPromptDatabaseSelectorButton> {
- late Future<ViewPB?> viewFuture;
-
- @override
- void initState() {
- super.initState();
- viewFuture = getView();
- }
-
- @override
- void didUpdateWidget(covariant AiPromptDatabaseSelectorButton oldWidget) {
- super.didUpdateWidget(oldWidget);
- if (oldWidget.selectedViewId != widget.selectedViewId) {
- viewFuture = getView();
- }
- }
-
- @override
- Widget build(BuildContext context) {
- final theme = AppFlowyTheme.of(context);
-
- return FutureBuilder<ViewPB?>(
- future: viewFuture,
- builder: (context, snapshot) {
- String name = "";
-
- if (snapshot.hasData &&
- snapshot.connectionState == ConnectionState.done) {
- name = snapshot.data!.nameOrDefault;
- }
-
- return Row(
- spacing: theme.spacing.s,
- children: [
- Expanded(
- child: Text(
- "${LocaleKeys.ai_customPrompt_promptDatabase.tr()}: $name",
- maxLines: 1,
- style: theme.textStyle.body.standard(
- color: theme.textColorScheme.primary,
- ),
- overflow: TextOverflow.ellipsis,
- ),
- ),
- ConstrainedBox(
- constraints: const BoxConstraints(
- maxWidth: 150,
- ),
- child: AFOutlinedButton.normal(
- onTap: widget.onTap,
- builder: (context, isHovering, disabled) {
- return Row(
- spacing: theme.spacing.s,
- mainAxisSize: MainAxisSize.min,
- children: [
- if (widget.isLoading) buildLoadingIndicator(theme),
- Flexible(
- child: Text(
- widget.isLoading
- ? LocaleKeys.ai_customPrompt_loading.tr()
- : LocaleKeys.button_change.tr(),
- maxLines: 1,
- style: theme.textStyle.body.standard(
- color: theme.textColorScheme.primary,
- ),
- overflow: TextOverflow.ellipsis,
- ),
- ),
- ],
- );
- },
- ),
- ),
- ],
- );
- },
- );
- }
-
- Widget buildLoadingIndicator(AppFlowyThemeData theme) {
- return SizedBox.square(
- dimension: 20,
- child: Padding(
- padding: EdgeInsets.all(2.5),
- child: CircularProgressIndicator(
- color: theme.iconColorScheme.tertiary,
- strokeWidth: 2.0,
- ),
- ),
- );
- }
-
- Future<ViewPB?> getView() async {
- if (widget.selectedViewId == null) {
- return null;
- }
- final view =
- await ViewBackendService.getView(widget.selectedViewId!).toNullable();
-
- if (view != null) {
- return view;
- }
-
- final trashViews = await TrashService().readTrash().toNullable();
- final trashedItem = trashViews?.items
- .firstWhereOrNull((element) => element.id == widget.selectedViewId);
-
- if (trashedItem == null) {
- return null;
- }
-
- return ViewPB()
- ..id = trashedItem.id
- ..name = trashedItem.name;
- }
-}
-
-class _PopoverContent extends StatefulWidget {
- const _PopoverContent({
- required this.onSelectViewItem,
- });
-
- final void Function(ViewSelectorItem item) onSelectViewItem;
-
- @override
- State<_PopoverContent> createState() => _PopoverContentState();
-}
-
-class _PopoverContentState extends State<_PopoverContent> {
- final focusNode = FocusNode();
-
- @override
- void initState() {
- super.initState();
- WidgetsBinding.instance.addPostFrameCallback((_) {
- focusNode.requestFocus();
- });
- }
-
- @override
- void dispose() {
- focusNode.dispose();
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- final theme = AppFlowyTheme.of(context);
-
- return Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- VSpace(theme.spacing.m),
- Padding(
- padding: EdgeInsets.symmetric(
- horizontal: theme.spacing.m,
- ),
- child: AFTextField(
- focusNode: focusNode,
- size: AFTextFieldSize.m,
- hintText: LocaleKeys.search_label.tr(),
- controller: context.read<ViewSelectorCubit>().filterTextController,
- ),
- ),
- VSpace(theme.spacing.m),
- AFDivider(),
- Expanded(
- child: BlocBuilder<ViewSelectorCubit, ViewSelectorState>(
- builder: (context, state) {
- return ListView(
- shrinkWrap: true,
- padding: const EdgeInsets.fromLTRB(8, 4, 8, 12),
- children: _buildVisibleSources(context, state).toList(),
- );
- },
- ),
- ),
- ],
- );
- }
-
- Iterable<Widget> _buildVisibleSources(
- BuildContext context,
- ViewSelectorState state,
- ) {
- return state.visibleSources.map(
- (e) => ViewSelectorTreeItem(
- key: ValueKey(
- 'custom_prompt_database_tree_item_${e.view.id}',
- ),
- viewSelectorItem: e,
- level: 0,
- isDescendentOfSpace: e.view.isSpace,
- isSelectedSection: false,
- showCheckbox: false,
- onSelected: widget.onSelectViewItem,
- height: 30.0,
- ),
- );
- }
-}
diff --git a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_modal.dart b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_modal.dart
index aa97f446d8..7a31b4257b 100644
--- a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_modal.dart
+++ b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_modal.dart
@@ -102,7 +102,7 @@ class AiPromptModal extends StatelessWidget {
child: AiPromptCategoryList(),
),
if (readyState.isCustomPromptSectionSelected &&
- readyState.customPromptDatabaseViewId == null)
+ readyState.databaseConfig == null)
const Expanded(
flex: 5,
child: Center(
diff --git a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_onboarding.dart b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_onboarding.dart
index 145ea0f914..f61ea704ca 100644
--- a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_onboarding.dart
+++ b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_onboarding.dart
@@ -1,10 +1,12 @@
+import 'package:appflowy/ai/ai.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy_ui/appflowy_ui.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/widget/spacing.dart';
import 'package:flutter/widgets.dart';
+import 'package:flutter_bloc/flutter_bloc.dart';
-import 'ai_prompt_database_selector.dart';
+import 'ai_prompt_database_modal.dart';
class AiPromptOnboarding extends StatelessWidget {
const AiPromptOnboarding({super.key});
@@ -34,18 +36,24 @@ class AiPromptOnboarding extends StatelessWidget {
VSpace(
theme.spacing.xxl,
),
- CustomPromptDatabaseSelector(
- childBuilder: (onTap) => AFFilledButton.primary(
- onTap: onTap,
- builder: (context, isHovering, disabled) {
- return Text(
- LocaleKeys.ai_customPrompt_selectDatabase.tr(),
- style: theme.textStyle.body.enhanced(
- color: theme.textColorScheme.onFill,
- ),
- );
- },
- ),
+ AFFilledButton.primary(
+ onTap: () async {
+ final config = await changeCustomPromptDatabaseConfig(context);
+
+ if (config != null && context.mounted) {
+ context
+ .read<AiPromptSelectorCubit>()
+ .updateCustomPromptDatabaseConfiguration(config);
+ }
+ },
+ builder: (context, isHovering, disabled) {
+ return Text(
+ LocaleKeys.ai_customPrompt_selectDatabase.tr(),
+ style: theme.textStyle.body.enhanced(
+ color: theme.textColorScheme.onFill,
+ ),
+ );
+ },
),
],
);
diff --git a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_preview.dart b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_preview.dart
index c1a40f35d2..dc024195c8 100644
--- a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_preview.dart
+++ b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_preview.dart
@@ -70,7 +70,7 @@ class AiPromptPreview extends StatelessWidget {
if (prompt.example.isNotEmpty) ...[
SelectionContainer.disabled(
child: Text(
- LocaleKeys.ai_customPrompt_example.tr(),
+ LocaleKeys.ai_customPrompt_promptExample.tr(),
style: theme.textStyle.heading4.standard(
color: theme.textColorScheme.primary,
),
@@ -106,7 +106,7 @@ class _PromptContent extends StatelessWidget {
return Container(
padding: EdgeInsets.all(theme.spacing.l),
decoration: BoxDecoration(
- color: theme.fillColorScheme.primary,
+ color: theme.fillColorScheme.contentVisible,
borderRadius: BorderRadius.circular(theme.borderRadius.m),
),
child: Text.rich(
@@ -176,7 +176,7 @@ class _PromptExample extends StatelessWidget {
return Container(
padding: EdgeInsets.all(theme.spacing.l),
decoration: BoxDecoration(
- color: theme.fillColorScheme.primary,
+ color: theme.fillColorScheme.contentVisible,
borderRadius: BorderRadius.circular(theme.borderRadius.m),
),
child: AIMarkdownText(
diff --git a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_visible_list.dart b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_visible_list.dart
index 31e981c1fd..b904e792fe 100644
--- a/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_visible_list.dart
+++ b/frontend/appflowy_flutter/lib/ai/widgets/ai_prompt_modal/ai_prompt_visible_list.dart
@@ -4,6 +4,7 @@ import 'package:appflowy/ai/ai.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/util/theme_extension.dart';
+import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy_ui/appflowy_ui.dart';
import 'package:diffutil_dart/diffutil.dart';
import 'package:easy_localization/easy_localization.dart';
@@ -11,7 +12,7 @@ import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
-import 'ai_prompt_database_selector.dart';
+import 'ai_prompt_database_modal.dart';
const Duration _listItemAnimationDuration = Duration(milliseconds: 150);
@@ -57,89 +58,132 @@ class _AiPromptVisibleListState extends State<AiPromptVisibleList> {
Widget build(BuildContext context) {
final theme = AppFlowyTheme.of(context);
- return BlocListener<AiPromptSelectorCubit, AiPromptSelectorState>(
- listener: (context, state) {
- state.maybeMap(
- ready: (state) {
- handleVisiblePromptListChanged(state.visiblePrompts);
+ return Column(
+ children: [
+ Padding(
+ padding: EdgeInsets.symmetric(horizontal: theme.spacing.l),
+ child: buildSearchField(context),
+ ),
+ VSpace(
+ theme.spacing.s,
+ ),
+ BlocConsumer<AiPromptSelectorCubit, AiPromptSelectorState>(
+ listener: (context, state) {
+ state.maybeMap(
+ ready: (state) {
+ handleVisiblePromptListChanged(state.visiblePrompts);
+ },
+ orElse: () {},
+ );
},
- orElse: () {},
- );
- },
- child: Column(
- children: [
- Padding(
- padding: EdgeInsets.symmetric(horizontal: theme.spacing.l),
- child: buildSearchField(context),
- ),
- VSpace(
- theme.spacing.s,
- ),
- BlocBuilder<AiPromptSelectorCubit, AiPromptSelectorState>(
- buildWhen: (p, c) {
- return p.maybeMap(
- ready: (pr) => c.maybeMap(
- ready: (cr) =>
- pr.customPromptDatabaseViewId !=
- cr.customPromptDatabaseViewId ||
- pr.isLoadingCustomPrompts != cr.isLoadingCustomPrompts ||
- pr.isCustomPromptSectionSelected !=
- cr.isCustomPromptSectionSelected,
- orElse: () => false,
- ),
- orElse: () => true,
- );
- },
- builder: (context, state) {
- return state.maybeMap(
- ready: (readyState) {
- if (!readyState.isCustomPromptSectionSelected) {
- return const SizedBox.shrink();
- }
- return Padding(
- padding: EdgeInsets.only(
- left: theme.spacing.l,
- top: theme.spacing.s,
- right: theme.spacing.l,
- ),
- child: CustomPromptDatabaseSelector(
- databaseViewId: readyState.customPromptDatabaseViewId,
- isLoading: readyState.isLoadingCustomPrompts,
- popoverDirection: PopoverDirection.bottomWithRightAligned,
- childBuilder: (onTap) {
- return AiPromptDatabaseSelectorButton(
- selectedViewId: readyState.customPromptDatabaseViewId,
- isLoading: readyState.isLoadingCustomPrompts,
- onTap: onTap,
- );
- },
- ),
- );
- },
- orElse: () => const SizedBox.shrink(),
- );
- },
- ),
- Expanded(
- child: TextFieldTapRegion(
- groupId: "ai_prompt_category_list",
- child: BlocBuilder<AiPromptSelectorCubit, AiPromptSelectorState>(
- builder: (context, state) {
- return state.maybeMap(
- ready: (readyState) {
- if (readyState.visiblePrompts.isEmpty) {
- return buildEmptyPrompts();
- }
- return buildPromptList();
- },
- orElse: () => const SizedBox.shrink(),
- );
- },
+ buildWhen: (p, c) {
+ return p.maybeMap(
+ ready: (pr) => c.maybeMap(
+ ready: (cr) =>
+ pr.databaseConfig?.view.id != cr.databaseConfig?.view.id ||
+ pr.isLoadingCustomPrompts != cr.isLoadingCustomPrompts ||
+ pr.isCustomPromptSectionSelected !=
+ cr.isCustomPromptSectionSelected,
+ orElse: () => false,
),
+ orElse: () => true,
+ );
+ },
+ builder: (context, state) {
+ return state.maybeMap(
+ ready: (readyState) {
+ if (!readyState.isCustomPromptSectionSelected) {
+ return const SizedBox.shrink();
+ }
+ return Padding(
+ padding: EdgeInsets.only(
+ left: theme.spacing.l,
+ top: theme.spacing.s,
+ right: theme.spacing.l,
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ "${LocaleKeys.ai_customPrompt_promptDatabase.tr()}: ${readyState.databaseConfig?.view.nameOrDefault ?? ""}",
+ maxLines: 1,
+ style: theme.textStyle.body.standard(
+ color: theme.textColorScheme.primary,
+ ),
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ ConstrainedBox(
+ constraints: const BoxConstraints(
+ maxWidth: 150,
+ ),
+ child: AFOutlinedButton.normal(
+ builder: (context, isHovering, disabled) {
+ return Row(
+ spacing: theme.spacing.s,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (readyState.isLoadingCustomPrompts)
+ buildLoadingIndicator(theme),
+ Flexible(
+ child: Text(
+ readyState.isLoadingCustomPrompts
+ ? LocaleKeys.ai_customPrompt_loading
+ .tr()
+ : LocaleKeys.button_change.tr(),
+ maxLines: 1,
+ style: theme.textStyle.body.enhanced(
+ color: theme.textColorScheme.primary,
+ ),
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ ],
+ );
+ },
+ onTap: () async {
+ final newConfig =
+ await changeCustomPromptDatabaseConfig(
+ context,
+ config: readyState.databaseConfig,
+ );
+ if (newConfig != null && context.mounted) {
+ context
+ .read<AiPromptSelectorCubit>()
+ .updateCustomPromptDatabaseConfiguration(
+ newConfig,
+ );
+ }
+ },
+ ),
+ ),
+ ],
+ ),
+ );
+ },
+ orElse: () => const SizedBox.shrink(),
+ );
+ },
+ ),
+ Expanded(
+ child: TextFieldTapRegion(
+ groupId: "ai_prompt_category_list",
+ child: BlocBuilder<AiPromptSelectorCubit, AiPromptSelectorState>(
+ builder: (context, state) {
+ return state.maybeMap(
+ ready: (readyState) {
+ if (readyState.visiblePrompts.isEmpty) {
+ return buildEmptyPrompts();
+ }
+ return buildPromptList();
+ },
+ orElse: () => const SizedBox.shrink(),
+ );
+ },
),
),
- ],
- ),
+ ),
+ ],
);
}
@@ -240,6 +284,19 @@ class _AiPromptVisibleListState extends State<AiPromptVisibleList> {
);
}
+ Widget buildLoadingIndicator(AppFlowyThemeData theme) {
+ return SizedBox.square(
+ dimension: 20,
+ child: Padding(
+ padding: EdgeInsets.all(2.5),
+ child: CircularProgressIndicator(
+ color: theme.iconColorScheme.tertiary,
+ strokeWidth: 2.0,
+ ),
+ ),
+ );
+ }
+
void handleVisiblePromptListChanged(
List<AiPrompt> newList,
) {
diff --git a/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/select_sources_menu.dart b/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/select_sources_menu.dart
index 44439d9cf8..5ca6b7742d 100644
--- a/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/select_sources_menu.dart
+++ b/frontend/appflowy_flutter/lib/ai/widgets/prompt_input/select_sources_menu.dart
@@ -418,6 +418,8 @@ class ViewSelectorTreeItemInner extends StatelessWidget {
hoverColor: AFThemeExtension.of(context).lightGreyHover,
),
builder: (context, onHover) {
+ final theme = AppFlowyTheme.of(context);
+
final isSaveButtonVisible =
showSaveButton && !viewSelectorItem.view.isSpace;
final isAddButtonVisible = onAdd != null;
@@ -445,11 +447,12 @@ class ViewSelectorTreeItemInner extends StatelessWidget {
const HSpace(6.0),
// title
Expanded(
- child: FlowyText(
+ child: Text(
viewSelectorItem.view.nameOrDefault,
overflow: TextOverflow.ellipsis,
- fontSize: 14.0,
- figmaLineHeight: 18.0,
+ style: theme.textStyle.body.standard(
+ color: theme.textColorScheme.primary,
+ ),
),
),
if (onHover && (isSaveButtonVisible || isAddButtonVisible)) ...[
diff --git a/frontend/appflowy_flutter/lib/plugins/database/domain/field_service.dart b/frontend/appflowy_flutter/lib/plugins/database/domain/field_service.dart
index 66c941891d..97bfb34a60 100644
--- a/frontend/appflowy_flutter/lib/plugins/database/domain/field_service.dart
+++ b/frontend/appflowy_flutter/lib/plugins/database/domain/field_service.dart
@@ -145,6 +145,17 @@ class FieldBackendService {
return DatabaseEventUpdateFieldTypeOption(payload).send();
}
+ static Future<FlowyResult<List<FieldPB>, FlowyError>> getFields({
+ required String viewId,
+ }) {
+ final payload = GetFieldPayloadPB.create()..viewId = viewId;
+
+ return DatabaseEventGetFields(payload).send().fold(
+ (repeated) => FlowySuccess(repeated.items),
+ (error) => FlowyFailure(error),
+ );
+ }
+
/// Returns the primary field of the view.
static Future<FlowyResult<FieldPB, FlowyError>> getPrimaryField({
required String viewId,
diff --git a/frontend/appflowy_flutter/packages/appflowy_ui/lib/src/component/popover/popover.dart b/frontend/appflowy_flutter/packages/appflowy_ui/lib/src/component/popover/popover.dart
index cde698d69a..e47d53f86e 100644
--- a/frontend/appflowy_flutter/packages/appflowy_ui/lib/src/component/popover/popover.dart
+++ b/frontend/appflowy_flutter/packages/appflowy_ui/lib/src/component/popover/popover.dart
@@ -205,17 +205,17 @@ class _AFPopoverState extends State<AFPopover> {
Widget popover = ShadMouseArea(
groupId: widget.areaGroupId,
child: DecoratedBox(
- decoration: BoxDecoration(
- color: theme.surfaceColorScheme.primary,
- borderRadius: BorderRadius.circular(theme.borderRadius.m),
- ),
+ decoration: widget.decoration ??
+ BoxDecoration(
+ color: theme.surfaceColorScheme.primary,
+ borderRadius: BorderRadius.circular(theme.borderRadius.m),
+ ),
child: Padding(
padding: effectivePadding,
child: DefaultTextStyle(
style: TextStyle(
color: theme.textColorScheme.primary,
),
- textAlign: TextAlign.center,
child: Builder(
builder: widget.popover,
),
diff --git a/frontend/resources/translations/en-US.json b/frontend/resources/translations/en-US.json
index 6b512ddfe0..5c65fd37c2 100644
--- a/frontend/resources/translations/en-US.json
+++ b/frontend/resources/translations/en-US.json
@@ -3345,6 +3345,12 @@
"databasePrompts": "Load prompts from your own database",
"selectDatabase": "Select database",
"promptDatabase": "Prompt database",
+ "configureDatabase": "Configure Database",
+ "title": "Title",
+ "content": "Content",
+ "example": "Example",
+ "category": "Category",
+ "selectField": "Select field",
"loading": "Loading",
"invalidDatabase": "Invalid Database",
"invalidDatabaseHelp": "Ensure that the database has at least two text properties:\n ◦ One used for the prompt name\n ◦ One used for the prompt content\nYou can also optionally add properties for the prompt example and category.",
@@ -3358,7 +3364,7 @@
"travel": "Travel",
"others": "Other",
"prompt": "Prompt",
- "example": "Prompt Example",
+ "promptExample": "Prompt Example",
"sampleOutput": "Sample output",
"contentSeo": "Content/SEO",
"emailMarketing": "Email Marketing",
@@ -3405,4 +3411,4 @@
"rewrite": "Rewrite",
"insertBelow": "Insert below"
}
-}
\ No newline at end of file
+}
diff --git a/frontend/rust-lib/flowy-ai/src/ai_manager.rs b/frontend/rust-lib/flowy-ai/src/ai_manager.rs
index 7d2d7bc0a7..6d6fed960d 100644
--- a/frontend/rust-lib/flowy-ai/src/ai_manager.rs
+++ b/frontend/rust-lib/flowy-ai/src/ai_manager.rs
@@ -1,7 +1,8 @@
use crate::chat::Chat;
use crate::entities::{
- AIModelPB, ChatInfoPB, ChatMessageListPB, ChatMessagePB, ChatSettingsPB, FilePB,
- ModelSelectionPB, PredefinedFormatPB, RepeatedRelatedQuestionPB, StreamMessageParams,
+ AIModelPB, ChatInfoPB, ChatMessageListPB, ChatMessagePB, ChatSettingsPB,
+ CustomPromptDatabaseConfigurationPB, FilePB, ModelSelectionPB, PredefinedFormatPB,
+ RepeatedRelatedQuestionPB, StreamMessageParams,
};
use crate::local_ai::controller::{LocalAIController, LocalAISetting};
use crate::middleware::chat_service_mw::ChatServiceMiddleware;
@@ -720,21 +721,26 @@ impl AIManager {
Ok(())
}
- pub async fn get_custom_prompt_database_view_id(&self) -> FlowyResult<Option<String>> {
+ pub async fn get_custom_prompt_database_configuration(
+ &self,
+ ) -> FlowyResult<Option<CustomPromptDatabaseConfigurationPB>> {
let view_id = self
.store_preferences
- .get_object::<String>(CUSTOM_PROMPT_DATABASE_VIEW_ID_KEY);
+ .get_object::<CustomPromptDatabaseConfigurationPB>(CUSTOM_PROMPT_DATABASE_CONFIGURATION_KEY);
Ok(view_id)
}
- pub async fn set_custom_prompt_database_view_id(&self, view_id: String) -> FlowyResult<()> {
+ pub async fn set_custom_prompt_database_configuration(
+ &self,
+ config: CustomPromptDatabaseConfigurationPB,
+ ) -> FlowyResult<()> {
if let Err(err) = self
.store_preferences
- .set_object(CUSTOM_PROMPT_DATABASE_VIEW_ID_KEY, &view_id)
+ .set_object(CUSTOM_PROMPT_DATABASE_CONFIGURATION_KEY, &config)
{
error!(
- "failed to set custom prompt database view id settings: {}",
+ "failed to set custom prompt database configuration settings: {}",
err
);
}
@@ -804,4 +810,4 @@ fn setting_store_key(chat_id: &Uuid) -> String {
format!("chat_settings_{}", chat_id)
}
-const CUSTOM_PROMPT_DATABASE_VIEW_ID_KEY: &str = "custom_prompt_database_view_id";
+const CUSTOM_PROMPT_DATABASE_CONFIGURATION_KEY: &str = "custom_prompt_database_config";
diff --git a/frontend/rust-lib/flowy-ai/src/entities.rs b/frontend/rust-lib/flowy-ai/src/entities.rs
index 44dfeb25f3..af26f400d9 100644
--- a/frontend/rust-lib/flowy-ai/src/entities.rs
+++ b/frontend/rust-lib/flowy-ai/src/entities.rs
@@ -6,6 +6,7 @@ use flowy_ai_pub::cloud::{
};
use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
use lib_infra::validator_fn::required_not_empty_str;
+use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;
use validator::Validate;
@@ -739,3 +740,21 @@ pub struct CustomPromptDatabaseViewIdPB {
#[pb(index = 1)]
pub id: String,
}
+
+#[derive(Default, ProtoBuf, Clone, Debug, Serialize, Deserialize)]
+pub struct CustomPromptDatabaseConfigurationPB {
+ #[pb(index = 1)]
+ pub view_id: String,
+
+ #[pb(index = 2)]
+ pub title_field_id: String,
+
+ #[pb(index = 3)]
+ pub content_field_id: String,
+
+ #[pb(index = 4, one_of)]
+ pub example_field_id: Option<String>,
+
+ #[pb(index = 5, one_of)]
+ pub category_field_id: Option<String>,
+}
diff --git a/frontend/rust-lib/flowy-ai/src/event_handler.rs b/frontend/rust-lib/flowy-ai/src/event_handler.rs
index ff4e8dfe35..258d23d31c 100644
--- a/frontend/rust-lib/flowy-ai/src/event_handler.rs
+++ b/frontend/rust-lib/flowy-ai/src/event_handler.rs
@@ -364,33 +364,33 @@ pub(crate) async fn update_local_ai_setting_handler(
}
#[tracing::instrument(level = "debug", skip_all, err)]
-pub(crate) async fn get_custom_prompt_database_view_id_handler(
+pub(crate) async fn get_custom_prompt_database_configuration_handler(
ai_manager: AFPluginState<Weak<AIManager>>,
-) -> DataResult<CustomPromptDatabaseViewIdPB, FlowyError> {
+) -> DataResult<CustomPromptDatabaseConfigurationPB, FlowyError> {
let ai_manager = upgrade_ai_manager(ai_manager)?;
- let id = ai_manager
- .get_custom_prompt_database_view_id()
+ let configuration = ai_manager
+ .get_custom_prompt_database_configuration()
.await?
.ok_or_else(|| {
FlowyError::new(
ErrorCode::RecordNotFound,
- "Custom prompt database view id not found",
+ "Custom prompt configuration not found",
)
})?;
- data_result_ok(CustomPromptDatabaseViewIdPB { id })
+ data_result_ok(configuration)
}
#[tracing::instrument(level = "debug", skip_all, err)]
-pub(crate) async fn set_custom_prompt_database_view_id_handler(
- data: AFPluginData<CustomPromptDatabaseViewIdPB>,
+pub(crate) async fn set_custom_prompt_database_configuration_handler(
+ data: AFPluginData<CustomPromptDatabaseConfigurationPB>,
ai_manager: AFPluginState<Weak<AIManager>>,
) -> Result<(), FlowyError> {
let ai_manager = upgrade_ai_manager(ai_manager)?;
- let view_id = data.into_inner().id;
+ let config = data.into_inner();
ai_manager
- .set_custom_prompt_database_view_id(view_id)
+ .set_custom_prompt_database_configuration(config)
.await?;
Ok(())
diff --git a/frontend/rust-lib/flowy-ai/src/event_map.rs b/frontend/rust-lib/flowy-ai/src/event_map.rs
index eb72081467..c1345180f7 100644
--- a/frontend/rust-lib/flowy-ai/src/event_map.rs
+++ b/frontend/rust-lib/flowy-ai/src/event_map.rs
@@ -51,12 +51,12 @@ pub fn init(ai_manager: Weak<AIManager>) -> AFPlugin {
)
.event(AIEvent::UpdateSelectedModel, update_selected_model_handler)
.event(
- AIEvent::GetCustomPromptDatabaseViewId,
- get_custom_prompt_database_view_id_handler,
+ AIEvent::GetCustomPromptDatabaseConfiguration,
+ get_custom_prompt_database_configuration_handler,
)
.event(
- AIEvent::SetCustomPromptDatabaseViewId,
- set_custom_prompt_database_view_id_handler,
+ AIEvent::SetCustomPromptDatabaseConfiguration,
+ set_custom_prompt_database_configuration_handler,
)
}
@@ -137,9 +137,9 @@ pub enum AIEvent {
#[event(input = "ModelSourcePB", output = "ModelSelectionPB")]
GetSourceModelSelection = 34,
- #[event(output = "CustomPromptDatabaseViewIdPB")]
- GetCustomPromptDatabaseViewId = 35,
+ #[event(output = "CustomPromptDatabaseConfigurationPB")]
+ GetCustomPromptDatabaseConfiguration = 35,
- #[event(input = "CustomPromptDatabaseViewIdPB")]
- SetCustomPromptDatabaseViewId = 36,
+ #[event(input = "CustomPromptDatabaseConfigurationPB")]
+ SetCustomPromptDatabaseConfiguration = 36,
}
diff --git a/frontend/rust-lib/flowy-database2/src/entities/database_entities.rs b/frontend/rust-lib/flowy-database2/src/entities/database_entities.rs
index e2299fe8af..59b9e228ae 100644
--- a/frontend/rust-lib/flowy-database2/src/entities/database_entities.rs
+++ b/frontend/rust-lib/flowy-database2/src/entities/database_entities.rs
@@ -6,6 +6,7 @@ use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
use flowy_error::{ErrorCode, FlowyError};
use lib_infra::validator_fn::required_not_empty_str;
+use serde::{Deserialize, Serialize};
use validator::Validate;
use crate::entities::parser::NotEmptyStr;
@@ -373,3 +374,21 @@ pub struct CustomPromptPB {
#[pb(index = 5)]
pub category: String,
}
+
+#[derive(Default, ProtoBuf, Clone, Debug, Serialize, Deserialize, Validate)]
+pub struct CustomPromptDatabaseConfigPB {
+ #[pb(index = 1)]
+ pub view_id: String,
+
+ #[pb(index = 2)]
+ pub title_field_id: String,
+
+ #[pb(index = 3)]
+ pub content_field_id: String,
+
+ #[pb(index = 4, one_of)]
+ pub example_field_id: Option<String>,
+
+ #[pb(index = 5, one_of)]
+ pub category_field_id: Option<String>,
+}
diff --git a/frontend/rust-lib/flowy-database2/src/event_handler.rs b/frontend/rust-lib/flowy-database2/src/event_handler.rs
index 846065a0ef..596b4e613b 100644
--- a/frontend/rust-lib/flowy-database2/src/event_handler.rs
+++ b/frontend/rust-lib/flowy-database2/src/event_handler.rs
@@ -1416,19 +1416,35 @@ pub(crate) async fn rename_media_cell_file_handler(
#[tracing::instrument(level = "debug", skip(manager), err)]
pub(crate) async fn get_database_custom_prompts_handler(
- data: AFPluginData<DatabaseViewIdPB>,
+ data: AFPluginData<CustomPromptDatabaseConfigPB>,
manager: AFPluginState<Weak<DatabaseManager>>,
) -> DataResult<RepeatedCustomPromptPB, FlowyError> {
let manager = upgrade_manager(manager)?;
- let params: DatabaseViewIdPB = data.try_into_inner()?;
+ let params: CustomPromptDatabaseConfigPB = data.try_into_inner()?;
let database_editor = manager
- .get_database_editor_with_view_id(params.as_ref())
- .await?;
- let custom_prompts = database_editor
- .get_prompts_from_database(params.as_ref())
+ .get_database_editor_with_view_id(params.view_id.as_ref())
.await?;
+ let custom_prompts = database_editor.get_prompts_from_database(&params).await?;
data_result_ok(RepeatedCustomPromptPB {
items: custom_prompts,
})
}
+
+#[tracing::instrument(level = "debug", skip(manager), err)]
+pub(crate) async fn test_custom_prompt_database_configuration_handler(
+ data: AFPluginData<DatabaseViewIdPB>,
+ manager: AFPluginState<Weak<DatabaseManager>>,
+) -> DataResult<CustomPromptDatabaseConfigPB, FlowyError> {
+ let manager = upgrade_manager(manager)?;
+ let params: DatabaseViewIdPB = data.try_into_inner()?;
+ let database_editor = manager
+ .get_database_editor_with_view_id(params.as_ref())
+ .await?;
+
+ let configuration = database_editor
+ .test_custom_prompt_database_configuration(params.value.as_ref())
+ .await?;
+
+ data_result_ok(configuration)
+}
diff --git a/frontend/rust-lib/flowy-database2/src/event_map.rs b/frontend/rust-lib/flowy-database2/src/event_map.rs
index 1053d8d910..3a808b0bc3 100644
--- a/frontend/rust-lib/flowy-database2/src/event_map.rs
+++ b/frontend/rust-lib/flowy-database2/src/event_map.rs
@@ -98,10 +98,8 @@ pub fn init(database_manager: Weak<DatabaseManager>) -> AFPlugin {
// Media
.event(DatabaseEvent::UpdateMediaCell, update_media_cell_handler)
.event(DatabaseEvent::RenameMediaFile, rename_media_cell_file_handler)
- .event(
- DatabaseEvent::GetDatabaseCustomPrompts,
- get_database_custom_prompts_handler,
- )
+ .event(DatabaseEvent::GetDatabaseCustomPrompts, get_database_custom_prompts_handler)
+ .event(DatabaseEvent::TestCustomPromptDatabaseConfiguration, test_custom_prompt_database_configuration_handler)
}
/// [DatabaseEvent] defines events that are used to interact with the Grid. You could check [this](https://appflowy.gitbook.io/docs/essential-documentation/contribute-to-appflowy/architecture/backend/protobuf)
@@ -406,6 +404,12 @@ pub enum DatabaseEvent {
#[event(input = "RenameMediaChangesetPB")]
RenameMediaFile = 201,
- #[event(input = "DatabaseViewIdPB", output = "RepeatedCustomPromptPB")]
+ #[event(
+ input = "CustomPromptDatabaseConfigPB",
+ output = "RepeatedCustomPromptPB"
+ )]
GetDatabaseCustomPrompts = 500,
+
+ #[event(input = "DatabaseViewIdPB", output = "CustomPromptDatabaseConfigPB")]
+ TestCustomPromptDatabaseConfiguration = 501,
}
diff --git a/frontend/rust-lib/flowy-database2/src/services/database/database_editor.rs b/frontend/rust-lib/flowy-database2/src/services/database/database_editor.rs
index d92b33ef42..2c13af4665 100644
--- a/frontend/rust-lib/flowy-database2/src/services/database/database_editor.rs
+++ b/frontend/rust-lib/flowy-database2/src/services/database/database_editor.rs
@@ -1852,24 +1852,30 @@ impl DatabaseEditor {
pub async fn get_prompts_from_database(
&self,
- view_id: &str,
+ config: &CustomPromptDatabaseConfigPB,
) -> Result<Vec<CustomPromptPB>, FlowyError> {
- let fields = self.get_fields(view_id, None).await;
+ let fields = self.get_fields(&config.view_id, None).await;
+
let primary_field = fields
.iter()
- .find(|f| f.is_primary)
- .ok_or(FlowyError::internal().with_context("Cannot find primary field"))?;
+ .find(|field| field.id == config.title_field_id)
+ .ok_or_else(|| FlowyError::internal().with_context("Cannot find primary field"))?;
let content_field = fields
.iter()
- .find(|f| f.name.to_lowercase() == "content" && f.field_type == FieldType::RichText.value())
- .or_else(|| {
- fields
- .iter()
- .find(|f| !f.is_primary && f.field_type == FieldType::RichText.value())
+ .find(|field| {
+ field.id == config.content_field_id && field.field_type == FieldType::RichText.value()
})
- .ok_or(FlowyError::internal().with_context("Cannot find content field"))?;
- let example_field = fields.iter().find(|f| f.name.to_lowercase() == "example");
- let category_field = fields.iter().find(|f| f.name.to_lowercase() == "category");
+ .ok_or_else(|| FlowyError::internal().with_context("Cannot find content field"))?;
+ let example_field = config.example_field_id.as_ref().and_then(|id| {
+ fields
+ .iter()
+ .find(|field| field.id == *id && field.field_type == FieldType::RichText.value())
+ });
+ let category_field = config.category_field_id.as_ref().and_then(|id| {
+ fields
+ .iter()
+ .find(|field| field.id == *id && field.field_type == FieldType::RichText.value())
+ });
fn extract_cell_value(row: &Row, field: &Field) -> Option<String> {
row
@@ -1879,7 +1885,7 @@ impl DatabaseEditor {
}
let custom_prompts = self
- .get_all_rows(view_id)
+ .get_all_rows(&config.view_id)
.await?
.into_iter()
.filter_map(|row| {
@@ -1918,6 +1924,53 @@ impl DatabaseEditor {
Ok(custom_prompts)
}
+ pub async fn test_custom_prompt_database_configuration(
+ &self,
+ view_id: &str,
+ ) -> FlowyResult<CustomPromptDatabaseConfigPB> {
+ let mut fields = self.get_fields(view_id, None).await;
+ let view_id = view_id.to_string();
+
+ let title_field_position = fields
+ .iter()
+ .position(|f| f.is_primary)
+ .ok_or(FlowyError::internal().with_context("Cannot find primary field"))?;
+ let title_field_id = fields.remove(title_field_position).id;
+
+ let content_field_position = fields
+ .iter()
+ .position(|f| {
+ f.name.to_lowercase() == "content" && f.field_type == FieldType::RichText.value()
+ })
+ .or_else(|| {
+ fields
+ .iter()
+ .position(|f| f.field_type == FieldType::RichText.value())
+ })
+ .ok_or(FlowyError::internal().with_context("Cannot find content field"))?;
+ let content_field_id = fields.remove(content_field_position).id;
+
+ let example_field_id = fields
+ .iter()
+ .find(|f| f.name.to_lowercase() == "example" && f.field_type == FieldType::RichText.value())
+ .map(|f| f.id.clone());
+
+ let category_field_id = fields
+ .iter()
+ .find(|f| f.name.to_lowercase() == "category")
+ .map(|f| f.id.clone());
+
+ let configuration = CustomPromptDatabaseConfigPB {
+ view_id,
+ title_field_id,
+ content_field_id,
+ example_field_id,
+ category_field_id,
+ };
+
+ Ok(configuration)
+ }
+
async fn get_auto_updated_fields(&self, view_id: &str) -> Vec<Field> {
self
.database