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.
Dart blogconfluence-alternativecontent-managementcontent-servicesdocumentationflutternote-takingnotion-alternativeproject-managementtask-managementteam-collaborationwiki
chore: adjust select sources (#7019)
Richard Shiue30131fd9e474
diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_select_sources_cubit.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_select_sources_cubit.dartindex ec6d536463..9fc1f9932d 100644--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_select_sources_cubit.dart+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/application/chat_select_sources_cubit.dart@@ -1,5 +1,6 @@import 'package:appflowy/workspace/application/view/view_ext.dart';import 'package:appflowy/workspace/application/view/view_service.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:bloc/bloc.dart';@@ -8,6 +9,8 @@ import 'package:freezed_annotation/freezed_annotation.dart';part 'chat_select_sources_cubit.freezed.dart';+const int _kMaxSelectedParentPageCount = 3;+enum SourceSelectedStatus {unselected,selected,@@ -25,17 +28,21 @@ class ChatSource {required this.children,required bool isExpanded,required SourceSelectedStatus selectedStatus,+ required IgnoreViewType ignoreStatus,}) : isExpandedNotifier = ValueNotifier(isExpanded),- selectedStatusNotifier = ValueNotifier(selectedStatus);+ selectedStatusNotifier = ValueNotifier(selectedStatus),+ ignoreStatusNotifier = ValueNotifier(ignoreStatus);final ViewPB view;final ViewPB? parentView;final List<ChatSource> children;final ValueNotifier<bool> isExpandedNotifier;final ValueNotifier<SourceSelectedStatus> selectedStatusNotifier;+ final ValueNotifier<IgnoreViewType> ignoreStatusNotifier;bool get isExpanded => isExpandedNotifier.value;SourceSelectedStatus get selectedStatus => selectedStatusNotifier.value;+ IgnoreViewType get ignoreStatus => ignoreStatusNotifier.value;void toggleIsExpanded() {isExpandedNotifier.value = !isExpanded;@@ -46,6 +53,7 @@ class ChatSource {view: view,parentView: parentView,children: children.map<ChatSource>((child) => child.copy()).toList(),+ ignoreStatus: ignoreStatus,isExpanded: isExpanded,selectedStatus: selectedStatus,);@@ -64,12 +72,30 @@ class ChatSource {return null;}+ void resetIgnoreViewTypeRecursive() {+ ignoreStatusNotifier.value = view.layout.isDocumentView+ ? IgnoreViewType.none+ : IgnoreViewType.disable;++ for (final child in children) {+ child.resetIgnoreViewTypeRecursive();+ }+ }++ void updateIgnoreViewTypeRecursive(IgnoreViewType newIgnoreViewType) {+ ignoreStatusNotifier.value = newIgnoreViewType;+ for (final child in children) {+ child.updateIgnoreViewTypeRecursive(newIgnoreViewType);+ }+ }+void dispose() {for (final child in children) {child.dispose();}isExpandedNotifier.dispose();selectedStatusNotifier.dispose();+ ignoreStatusNotifier.dispose();}}@@ -87,54 +113,12 @@ class ChatSettingsCubit extends Cubit<ChatSettingsState> {selectedSourceIds = [...newSelectedSourceIds];}- void updateSelectedStatus() {- if (source == null) {- return;- }- if (source != null) {- _recursiveUpdateSelectedStatus(source!);- }- for (final source in state.visibleSources) {- _recursiveUpdateSelectedStatus(source);- }- final selected = _buildSelectedSources(source!).toList();- emit(state.copyWith(selectedSources: selected));- selectedSources- ..forEach((e) => e.dispose())- ..clear()- ..addAll(selected.map((e) => e.copy()));- }-- SourceSelectedStatus _recursiveUpdateSelectedStatus(ChatSource chatSource) {- SourceSelectedStatus selectedStatus = SourceSelectedStatus.unselected;-- int selectedCount = 0;- for (final childSource in chatSource.children) {- final childStatus = _recursiveUpdateSelectedStatus(childSource);- if (childStatus.isSelected) {- selectedCount++;- }- }-- final isThisSourceSelected = selectedSourceIds.contains(chatSource.view.id);- final areAllChildrenSelectedOrNoChildren =- chatSource.children.length == selectedCount;- final isAnyChildNotUnselected =- chatSource.children.any((e) => !e.selectedStatus.isUnselected);-- if (isThisSourceSelected && areAllChildrenSelectedOrNoChildren) {- selectedStatus = SourceSelectedStatus.selected;- } else if (isThisSourceSelected || isAnyChildNotUnselected) {- selectedStatus = SourceSelectedStatus.partiallySelected;- }-- chatSource.selectedStatusNotifier.value = selectedStatus;- return selectedStatus;- }-void refreshSources(ViewPB view) async {filter = "";final newSource = await _recursiveBuild(view, null);++ _restrictSelectionIfNecessary(newSource.children);+final selected = _buildSelectedSources(newSource).toList();newSource.toggleIsExpanded();@@ -167,6 +151,9 @@ class ChatSettingsCubit extends Cubit<ChatSettingsState> {if (childrenViews != null) {for (final childView in childrenViews) {+ if (childView.layout == ViewLayoutPB.Chat) {+ continue;+ }final childChatSource = await _recursiveBuild(childView, view);if (childChatSource.selectedStatus.isSelected) {selectedCount++;@@ -192,11 +179,28 @@ class ChatSettingsCubit extends Cubit<ChatSettingsState> {view: view,parentView: parentView,children: children,+ ignoreStatus: view.layout.isDocumentView+ ? IgnoreViewType.none+ : IgnoreViewType.disable,isExpanded: false,selectedStatus: selectedStatus,);}+ void _restrictSelectionIfNecessary(List<ChatSource> sources) {+ for (final source in sources) {+ source.resetIgnoreViewTypeRecursive();+ }+ if (sources.where((e) => !e.selectedStatus.isUnselected).length >=+ _kMaxSelectedParentPageCount) {+ sources+ .where((e) => e.selectedStatus == SourceSelectedStatus.unselected)+ .forEach(+ (e) => e.updateIgnoreViewTypeRecursive(IgnoreViewType.disable),+ );+ }+ }+void updateFilter(String filter) {this.filter = filter;for (final source in state.visibleSources) {@@ -236,6 +240,7 @@ class ChatSettingsCubit extends Cubit<ChatSettingsState> {view: chatSource.view,parentView: chatSource.parentView,children: childrenResults,+ ignoreStatus: chatSource.ignoreStatus,isExpanded: chatSource.isExpanded,selectedStatus: chatSource.selectedStatus,)@@ -250,20 +255,24 @@ class ChatSettingsCubit extends Cubit<ChatSettingsState> {children.addAll(_buildSelectedSources(childSource));}- return chatSource.selectedStatus.isUnselected- ? children- : [+ return selectedSourceIds.contains(chatSource.view.id)+ ? [ChatSource(view: chatSource.view,parentView: chatSource.parentView,children: children,+ ignoreStatus: chatSource.ignoreStatus,selectedStatus: chatSource.selectedStatus,isExpanded: true,),- ];+ ]+ : children;}void toggleSelectedStatus(ChatSource chatSource) {+ if (chatSource.view.isSpace) {+ return;+ }final allIds = _recursiveGetSourceIds(chatSource);if (chatSource.selectedStatus.isUnselected ||@@ -281,28 +290,82 @@ class ChatSettingsCubit extends Cubit<ChatSettingsState> {}}}++ updateSelectedStatus();+ }++ List<String> _recursiveGetSourceIds(ChatSource chatSource) {+ return [+ if (chatSource.view.layout.isDocumentView) chatSource.view.id,+ for (final childSource in chatSource.children)+ ..._recursiveGetSourceIds(childSource),+ ];+ }++ void updateSelectedStatus() {+ if (source == null) {+ return;+ }+ _recursiveUpdateSelectedStatus(source!);+ _restrictSelectionIfNecessary(source!.children);+ for (final visibleSource in state.visibleSources) {+ visibleSource.dispose();+ }+ final visible = [_buildSearchResults(source!)].nonNulls.toList();++ selectedSources+ ..forEach((e) => e.dispose())+ ..clear()+ ..addAll(_buildSelectedSources(source!));+ emit(+ state.copyWith(+ visibleSources: visible,+ selectedSources:+ selectedSources.map(_buildSearchResults).nonNulls.toList(),+ ),+ );+ }++ SourceSelectedStatus _recursiveUpdateSelectedStatus(ChatSource chatSource) {+ SourceSelectedStatus selectedStatus = SourceSelectedStatus.unselected;++ int selectedCount = 0;+ for (final childSource in chatSource.children) {+ final childStatus = _recursiveUpdateSelectedStatus(childSource);+ if (childStatus.isSelected) {+ selectedCount++;+ }+ }++ final isThisSourceSelected = selectedSourceIds.contains(chatSource.view.id);+ final areAllChildrenSelectedOrNoChildren =+ chatSource.children.length == selectedCount;+ final isAnyChildNotUnselected =+ chatSource.children.any((e) => !e.selectedStatus.isUnselected);++ if (isThisSourceSelected && areAllChildrenSelectedOrNoChildren) {+ selectedStatus = SourceSelectedStatus.selected;+ } else if (isThisSourceSelected || isAnyChildNotUnselected) {+ selectedStatus = SourceSelectedStatus.partiallySelected;+ }++ chatSource.selectedStatusNotifier.value = selectedStatus;+ return selectedStatus;}void toggleIsExpanded(ChatSource chatSource, bool isSelectedSection) {chatSource.toggleIsExpanded();if (isSelectedSection) {- for (final source in selectedSources) {- source.findChildBySourceId(chatSource.view.id)?.toggleIsExpanded();+ for (final selectedSource in selectedSources) {+ selectedSource+ .findChildBySourceId(chatSource.view.id)+ ?.toggleIsExpanded();}} else {source?.findChildBySourceId(chatSource.view.id)?.toggleIsExpanded();}}- List<String> _recursiveGetSourceIds(ChatSource chatSource) {- return [- if (chatSource.view.layout.isDocumentView && !chatSource.view.isSpace)- chatSource.view.id,- for (final childSource in chatSource.children)- ..._recursiveGetSourceIds(childSource),- ];- }-@overrideFuture<void> close() {source?.dispose();diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/select_sources_bottom_sheet.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/select_sources_bottom_sheet.dartindex 3cc35c0c4a..78596c3ee9 100644--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/select_sources_bottom_sheet.dart+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/select_sources_bottom_sheet.dart@@ -98,13 +98,13 @@ class _PromptInputMobileSelectSourcesButtonState),],),- onTap: () {+ onTap: () async {if (spaceView != null) {context.read<ChatSettingsCubit>().refreshSources(spaceView);}- showMobileBottomSheet<void>(+ await showMobileBottomSheet<void>(context,backgroundColor: Theme.of(context).colorScheme.surface,maxChildSize: 0.98,@@ -115,14 +115,15 @@ class _PromptInputMobileSelectSourcesButtonStatevalue: cubit,child: _MobileSelectSourcesSheetBody(scrollController: scrollController,- onUpdateSelectedSources:- widget.onUpdateSelectedSources,),),);},builder: (context) => const SizedBox.shrink(),);+ if (context.mounted) {+ widget.onUpdateSelectedSources(cubit.selectedSourceIds);+ }},),);@@ -137,11 +138,9 @@ class _PromptInputMobileSelectSourcesButtonStateclass _MobileSelectSourcesSheetBody extends StatefulWidget {const _MobileSelectSourcesSheetBody({required this.scrollController,- required this.onUpdateSelectedSources,});final ScrollController scrollController;- final void Function(List<String>) onUpdateSelectedSources;@overrideState<_MobileSelectSourcesSheetBody> createState() =>@@ -205,32 +204,27 @@ class _MobileSelectSourcesSheetBodyState),BlocBuilder<ChatSettingsCubit, ChatSettingsState>(builder: (context, state) {+ final sources = state.visibleSources+ .where((e) => e.ignoreStatus != IgnoreViewType.hide);return SliverList(delegate: SliverChildBuilderDelegate(- childCount: state.visibleSources.length,+ childCount: sources.length,(context, index) {+ final source = sources.elementAt(index);return ChatSourceTreeItem(key: ValueKey(- 'visible_select_sources_tree_item_${state.visibleSources[index].view.id}',+ 'visible_select_sources_tree_item_${source.view.id}',),- chatSource: state.visibleSources[index],+ chatSource: source,level: 0,+ isDescendentOfSpace: source.view.isSpace,isSelectedSection: false,onSelected: (chatSource) {- final cubit = context.read<ChatSettingsCubit>();- cubit.toggleSelectedStatus(chatSource);- widget.onUpdateSelectedSources(cubit.selectedSourceIds);+ context+ .read<ChatSettingsCubit>()+ .toggleSelectedStatus(chatSource);},height: 40.0,- visibilityGetter: (view) {- if (view.id == context.read<ChatSettingsCubit>().chatId) {- return IgnoreViewType.hide;- }-- return view.layout.isDocumentView- ? IgnoreViewType.none- : IgnoreViewType.disable;- },);},),diff --git a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/select_sources_menu.dart b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/select_sources_menu.dartindex 34a426884e..f7a49074d2 100644--- a/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/select_sources_menu.dart+++ b/frontend/appflowy_flutter/lib/plugins/ai_chat/presentation/chat_input/select_sources_menu.dart@@ -1,3 +1,5 @@+import 'dart:math';+import 'package:appflowy/generated/flowy_svgs.g.dart';import 'package:appflowy/plugins/ai_chat/application/chat_bloc.dart';import 'package:appflowy/plugins/ai_chat/application/chat_select_sources_cubit.dart';@@ -91,6 +93,7 @@ class _PromptInputDesktopSelectSourcesButtonState}},onClose: () {+ widget.onUpdateSelectedSources(cubit.selectedSourceIds);if (spaceView != null) {context.read<ChatSettingsCubit>().refreshSources(spaceView);}@@ -98,9 +101,7 @@ class _PromptInputDesktopSelectSourcesButtonStatepopupBuilder: (_) {return BlocProvider.value(value: context.read<ChatSettingsCubit>(),- child: _PopoverContent(- onUpdateSelectedSources: widget.onUpdateSelectedSources,- ),+ child: const _PopoverContent(),);},child: _IndicatorButton(@@ -168,11 +169,7 @@ class _IndicatorButton extends StatelessWidget {}class _PopoverContent extends StatelessWidget {- const _PopoverContent({- required this.onUpdateSelectedSources,- });-- final void Function(List<String>) onUpdateSelectedSources;+ const _PopoverContent();@overrideWidget build(BuildContext context) {@@ -225,62 +222,50 @@ class _PopoverContent extends StatelessWidget {BuildContext context,ChatSettingsState state,) {- return state.selectedSources.map(- (e) => ChatSourceTreeItem(- key: ValueKey(- 'selected_select_sources_tree_item_${e.view.id}',- ),- chatSource: e,- level: 0,- isSelectedSection: true,- onSelected: (chatSource) {- final cubit = context.read<ChatSettingsCubit>();- cubit.toggleSelectedStatus(chatSource);- onUpdateSelectedSources(cubit.selectedSourceIds);- },- height: 30.0,- visibilityGetter: (view) {- if (view.id == context.read<ChatSettingsCubit>().chatId) {- return IgnoreViewType.hide;- }-- return view.layout.isDocumentView- ? IgnoreViewType.none- : IgnoreViewType.disable;- },- ),- );+ return state.selectedSources+ .where((e) => e.ignoreStatus != IgnoreViewType.hide)+ .map(+ (e) => ChatSourceTreeItem(+ key: ValueKey(+ 'selected_select_sources_tree_item_${e.view.id}',+ ),+ chatSource: e,+ level: 0,+ isDescendentOfSpace: e.view.isSpace,+ isSelectedSection: true,+ onSelected: (chatSource) {+ context+ .read<ChatSettingsCubit>()+ .toggleSelectedStatus(chatSource);+ },+ height: 30.0,+ ),+ );}Iterable<Widget> _buildVisibleSources(BuildContext context,ChatSettingsState state,) {- return state.visibleSources.map(- (e) => ChatSourceTreeItem(- key: ValueKey(- 'visible_select_sources_tree_item_${e.view.id}',- ),- chatSource: e,- level: 0,- isSelectedSection: false,- onSelected: (chatSource) {- final cubit = context.read<ChatSettingsCubit>();- cubit.toggleSelectedStatus(chatSource);- onUpdateSelectedSources(cubit.selectedSourceIds);- },- height: 30.0,- visibilityGetter: (view) {- if (view.id == context.read<ChatSettingsCubit>().chatId) {- return IgnoreViewType.hide;- }-- return view.layout.isDocumentView- ? IgnoreViewType.none- : IgnoreViewType.disable;- },- ),- );+ return state.visibleSources+ .where((e) => e.ignoreStatus != IgnoreViewType.hide)+ .map(+ (e) => ChatSourceTreeItem(+ key: ValueKey(+ 'visible_select_sources_tree_item_${e.view.id}',+ ),+ chatSource: e,+ level: 0,+ isDescendentOfSpace: e.view.isSpace,+ isSelectedSection: false,+ onSelected: (chatSource) {+ context+ .read<ChatSettingsCubit>()+ .toggleSelectedStatus(chatSource);+ },+ height: 30.0,+ ),+ );}}@@ -289,10 +274,10 @@ class ChatSourceTreeItem extends StatefulWidget {super.key,required this.chatSource,required this.level,+ required this.isDescendentOfSpace,required this.isSelectedSection,required this.onSelected,required this.height,- this.visibilityGetter,});final ChatSource chatSource;@@ -300,14 +285,14 @@ class ChatSourceTreeItem extends StatefulWidget {/// nested level of the view itemfinal int level;+ final bool isDescendentOfSpace;+final bool isSelectedSection;final void Function(ChatSource chatSource) onSelected;final double height;- final IgnoreViewType Function(ViewPB view)? visibilityGetter;-@overrideState<ChatSourceTreeItem> createState() => _ChatSourceTreeItemState();}@@ -320,35 +305,30 @@ class _ChatSourceTreeItemState extends State<ChatSourceTreeItem> {child: ChatSourceTreeItemInner(chatSource: widget.chatSource,level: widget.level,+ isDescendentOfSpace: widget.isDescendentOfSpace,isSelectedSection: widget.isSelectedSection,onSelected: widget.onSelected,),);- final viewVisibility =- widget.visibilityGetter?.call(widget.chatSource.view) ??- IgnoreViewType.none;-- final disabledEnabledChild = viewVisibility == IgnoreViewType.disable- ? Opacity(- opacity: 0.5,- child: MouseRegion(- cursor: SystemMouseCursors.forbidden,- child: IgnorePointer(child: child),- ),- )- : child;+ final disabledEnabledChild =+ widget.chatSource.ignoreStatus == IgnoreViewType.disable+ ? Opacity(+ opacity: 0.5,+ child: MouseRegion(+ cursor: SystemMouseCursors.forbidden,+ child: IgnorePointer(child: child),+ ),+ )+ : child;return ValueListenableBuilder(valueListenable: widget.chatSource.isExpandedNotifier,builder: (context, isExpanded, child) {// filter the child views that should be ignored- final childViews = [...widget.chatSource.children];- if (widget.visibilityGetter != null) {- childViews.retainWhere(- (v) => widget.visibilityGetter!(v.view) != IgnoreViewType.hide,- );- }+ final childViews = widget.chatSource.children+ .where((e) => e.ignoreStatus != IgnoreViewType.hide)+ .toList();if (!isExpanded || childViews.isEmpty) {return disabledEnabledChild;@@ -365,10 +345,10 @@ class _ChatSourceTreeItemState extends State<ChatSourceTreeItem> {),chatSource: childSource,level: widget.level + 1,+ isDescendentOfSpace: widget.isDescendentOfSpace,isSelectedSection: widget.isSelectedSection,onSelected: widget.onSelected,height: widget.height,- visibilityGetter: widget.visibilityGetter,),),],@@ -383,12 +363,14 @@ class ChatSourceTreeItemInner extends StatelessWidget {super.key,required this.chatSource,required this.level,+ required this.isDescendentOfSpace,required this.isSelectedSection,this.onSelected,});final ChatSource chatSource;final int level;+ final bool isDescendentOfSpace;final bool isSelectedSection;final void Function(ChatSource)? onSelected;@@ -404,7 +386,7 @@ class ChatSourceTreeItemInner extends StatelessWidget {child: Row(children: [const HSpace(4.0),- HSpace(20.0 * level),+ HSpace(max(20.0 * level - (isDescendentOfSpace ? 2 : 0), 0)),// builds the >, ^ or · buttonToggleIsExpandedButton(chatSource: chatSource,@@ -412,10 +394,12 @@ class ChatSourceTreeItemInner extends StatelessWidget {),const HSpace(2.0),// checkbox- SourceSelectedStatusCheckbox(- chatSource: chatSource,- ),- const HSpace(4.0),+ if (!chatSource.view.isSpace) ...[+ SourceSelectedStatusCheckbox(+ chatSource: chatSource,+ ),+ const HSpace(4.0),+ ],// iconMentionViewIcon(view: chatSource.view,diff --git a/frontend/rust-lib/flowy-ai/src/ai_manager.rs b/frontend/rust-lib/flowy-ai/src/ai_manager.rsindex 303aec2b40..6f2dc61a65 100644--- a/frontend/rust-lib/flowy-ai/src/ai_manager.rs+++ b/frontend/rust-lib/flowy-ai/src/ai_manager.rs@@ -365,28 +365,26 @@ impl AIManager {pub async fn update_rag_ids(&self, chat_id: &str, rag_ids: Vec<String>) -> FlowyResult<()> {info!("[Chat] update chat:{} rag ids: {:?}", chat_id, rag_ids);- if !rag_ids.is_empty() {- let workspace_id = self.user_service.workspace_id()?;- let update_setting = UpdateChatParams {- name: None,- metadata: None,- rag_ids: Some(rag_ids.clone()),- };- self- .cloud_service_wm- .update_chat_settings(&workspace_id, chat_id, update_setting)- .await?;-- let user_service = self.user_service.clone();- let external_service = self.external_service.clone();- tokio::spawn(async move {- if let Ok(workspace_id) = user_service.workspace_id() {- let _ = external_service- .sync_rag_documents(&workspace_id, rag_ids)- .await;- }- });- }+ let workspace_id = self.user_service.workspace_id()?;+ let update_setting = UpdateChatParams {+ name: None,+ metadata: None,+ rag_ids: Some(rag_ids.clone()),+ };+ self+ .cloud_service_wm+ .update_chat_settings(&workspace_id, chat_id, update_setting)+ .await?;++ let user_service = self.user_service.clone();+ let external_service = self.external_service.clone();+ tokio::spawn(async move {+ if let Ok(workspace_id) = user_service.workspace_id() {+ let _ = external_service+ .sync_rag_documents(&workspace_id, rag_ids)+ .await;+ }+ });Ok(())}}