fix: Update search

This commit is contained in:
Anton Stubenbord
2023-05-25 23:06:48 +02:00
parent 06611e0355
commit a36c96c7bb
6 changed files with 159 additions and 351 deletions
@@ -87,6 +87,10 @@ class DocumentSearchCubit extends Cubit<DocumentSearchState> with DocumentPaging
} }
Future<void> suggest(String query) async { Future<void> suggest(String query) async {
final normalizedQuery = query.trim();
if (normalizedQuery.isEmpty) {
return;
}
emit( emit(
state.copyWith( state.copyWith(
isLoading: true, isLoading: true,
@@ -96,10 +100,13 @@ class DocumentSearchCubit extends Cubit<DocumentSearchState> with DocumentPaging
), ),
); );
final suggestions = await api.autocomplete(query); final suggestions = await api.autocomplete(query);
emit(state.copyWith( print("Suggestions found: $suggestions");
suggestions: suggestions, emit(
isLoading: false, state.copyWith(
)); suggestions: suggestions,
isLoading: false,
),
);
} }
void reset() { void reset() {
@@ -1,18 +1,15 @@
import 'dart:async'; import 'package:animations/animations.dart';
import 'dart:math' as math;
import 'package:collection/collection.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:hive_flutter/adapters.dart'; import 'package:hive_flutter/adapters.dart';
import 'package:paperless_api/paperless_api.dart';
import 'package:paperless_mobile/core/config/hive/hive_config.dart'; import 'package:paperless_mobile/core/config/hive/hive_config.dart';
import 'package:paperless_mobile/core/database/tables/local_user_account.dart'; import 'package:paperless_mobile/core/database/tables/local_user_account.dart';
import 'package:paperless_mobile/core/navigation/push_routes.dart'; import 'package:paperless_mobile/core/database/tables/local_user_app_state.dart';
import 'package:paperless_mobile/extensions/flutter_extensions.dart'; import 'package:paperless_mobile/core/repository/label_repository.dart';
import 'package:paperless_mobile/core/repository/user_repository.dart';
import 'package:paperless_mobile/features/document_search/cubit/document_search_cubit.dart'; import 'package:paperless_mobile/features/document_search/cubit/document_search_cubit.dart';
import 'package:paperless_mobile/features/document_search/view/remove_history_entry_dialog.dart'; import 'package:paperless_mobile/features/document_search/view/document_search_page.dart';
import 'package:paperless_mobile/features/documents/view/widgets/adaptive_documents_view.dart';
import 'package:paperless_mobile/features/documents/view/widgets/selection/view_type_selection_widget.dart';
import 'package:paperless_mobile/features/home/view/model/api_version.dart'; import 'package:paperless_mobile/features/home/view/model/api_version.dart';
import 'package:paperless_mobile/features/settings/view/manage_accounts_page.dart'; import 'package:paperless_mobile/features/settings/view/manage_accounts_page.dart';
import 'package:paperless_mobile/features/settings/view/widgets/global_settings_builder.dart'; import 'package:paperless_mobile/features/settings/view/widgets/global_settings_builder.dart';
@@ -28,280 +25,113 @@ class DocumentSearchBar extends StatefulWidget {
} }
class _DocumentSearchBarState extends State<DocumentSearchBar> { class _DocumentSearchBarState extends State<DocumentSearchBar> {
Timer? _debounceTimer;
final _controller = SearchController();
@override
void initState() {
super.initState();
_controller.addListener(() {
_debounceTimer?.cancel();
_debounceTimer = Timer(const Duration(milliseconds: 500), () {
print("Searching for $query");
context.read<DocumentSearchCubit>().suggest(query);
});
});
}
String get query => _controller.text;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Theme( return OpenContainer(
data: Theme.of(context).copyWith( transitionType: ContainerTransitionType.fadeThrough,
inputDecorationTheme: const InputDecorationTheme(), closedElevation: 1,
middleColor: Theme.of(context).colorScheme.surfaceVariant,
openColor: Theme.of(context).colorScheme.background,
closedColor: Theme.of(context).colorScheme.surfaceVariant,
closedShape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(56),
), ),
child: BlocBuilder<DocumentSearchCubit, DocumentSearchState>( closedBuilder: (_, action) {
builder: (context, state) { return InkWell(
return Padding( child: ConstrainedBox(
padding: const EdgeInsets.only(top: 4), constraints: const BoxConstraints(
child: SearchAnchor( maxWidth: 720,
searchController: _controller, minWidth: 360,
viewHintText: S.of(context)!.searchDocuments, maxHeight: 56,
builder: (context, controller) { minHeight: 48,
return SearchBar( ),
focusNode: FocusNode(), child: Row(
controller: controller, mainAxisAlignment: MainAxisAlignment.spaceBetween,
leading: IconButton( children: [
icon: const Icon(Icons.menu), Flexible(
onPressed: Scaffold.of(context).openDrawer, child: Padding(
), padding: EdgeInsets.symmetric(horizontal: 8),
trailing: [ child: Row(
IconButton( children: [
icon: GlobalSettingsBuilder( IconButton(
builder: (context, settings) { icon: Icon(Icons.menu),
return ValueListenableBuilder( onPressed: Scaffold.of(context).openDrawer,
valueListenable: ),
Hive.box<LocalUserAccount>(HiveBoxes.localUserAccount).listenable(), Expanded(
builder: (context, box, _) { child: Hero(
final account = box.get(settings.currentLoggedInUser!)!; tag: "search_hero_tag",
return UserAvatar( child: TextField(
userId: settings.currentLoggedInUser!, enabled: false,
account: account, decoration: InputDecoration(
); border: InputBorder.none,
}, hintText: S.of(context)!.searchDocuments,
); hintStyle: TextStyle(
}, color: Theme.of(context).colorScheme.onSurfaceVariant,
), ),
onPressed: () { ),
final apiVersion = context.read<ApiVersion>(); ),
showDialog(
context: context,
builder: (context) => Provider.value(
value: apiVersion,
child: const ManageAccountsPage(),
), ),
); ),
}, ],
), ),
], ),
hintText: S.of(context)!.searchDocuments,
onTap: () {
controller.openView().then((value) => FocusScope.of(context).unfocus());
},
);
},
suggestionsBuilder: (context, controller) {
switch (state.view) {
case SearchView.suggestions:
return _buildSuggestionItems(state);
case SearchView.results:
return _buildResultsList(state);
}
},
),
);
return SearchAnchor.bar(
barPadding: MaterialStatePropertyAll(EdgeInsets.only(left: 8, right: 0)),
viewLeading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {
// FocusManager.instance.primaryFocus?.unfocus();
_controller.clear();
_controller.closeView(null);
Future.delayed(const Duration(milliseconds: 100), () {
FocusManager.instance.primaryFocus?.unfocus();
});
},
),
searchController: _controller,
barLeading: IconButton(
icon: const Icon(Icons.menu),
onPressed: Scaffold.of(context).openDrawer,
),
barHintText: S.of(context)!.searchDocuments,
barTrailing: [
IconButton(
icon: GlobalSettingsBuilder(
builder: (context, settings) {
return ValueListenableBuilder(
valueListenable:
Hive.box<LocalUserAccount>(HiveBoxes.localUserAccount).listenable(),
builder: (context, box, _) {
final account = box.get(settings.currentLoggedInUser!)!;
return UserAvatar(
userId: settings.currentLoggedInUser!,
account: account,
);
},
);
},
), ),
onPressed: () { _buildUserAvatar(context),
final apiVersion = context.read<ApiVersion>(); ],
showDialog( ),
context: context, ),
builder: (context) => Provider.value( );
value: apiVersion, },
child: const ManageAccountsPage(), openBuilder: (_, action) {
), return MultiProvider(
); providers: [
}, Provider.value(value: context.read<LabelRepository>()),
), Provider.value(value: context.read<PaperlessDocumentsApi>()),
], Provider.value(value: context.read<CacheManager>()),
suggestionsBuilder: (context, controller) { Provider.value(value: context.read<ApiVersion>()),
switch (state.view) { Provider.value(value: context.read<UserRepository>()),
case SearchView.suggestions: ],
return _buildSuggestionItems(state); child: Provider(
case SearchView.results: create: (_) => DocumentSearchCubit(
return _buildResultsList(state); context.read(),
} context.read(),
}, context.read(),
); Hive.box<LocalUserAppState>(HiveBoxes.localUserAppState)
}, .get(LocalUserAccount.current.id)!,
), ),
); builder: (_, __) => const DocumentSearchPage(),
} ),
Iterable<Widget> _buildSuggestionItems(DocumentSearchState state) sync* {
final suggestions =
state.suggestions.whereNot((element) => state.searchHistory.contains(element));
final historyMatches = state.searchHistory.where((element) => element.startsWith(query));
for (var match in historyMatches.take(5)) {
yield ListTile(
title: Text(match),
leading: const Icon(Icons.history),
onLongPress: () => _onDeleteHistoryEntry(match),
onTap: () => _selectSuggestion(match),
trailing: _buildInsertSuggestionButton(match),
);
}
for (var suggestion in suggestions) {
yield ListTile(
title: Text(suggestion),
leading: const Icon(Icons.search),
onTap: () => _selectSuggestion(suggestion),
trailing: _buildInsertSuggestionButton(suggestion),
);
}
}
void _onDeleteHistoryEntry(String entry) async {
final shouldRemove = await showDialog<bool>(
context: context,
builder: (context) => RemoveHistoryEntryDialog(entry: entry),
) ??
false;
if (shouldRemove) {
context.read<DocumentSearchCubit>().removeHistoryEntry(entry);
}
}
Widget _buildInsertSuggestionButton(String suggestion) {
return Transform(
alignment: Alignment.center,
transform: Matrix4.rotationY(math.pi),
child: IconButton(
icon: const Icon(Icons.arrow_outward),
onPressed: () {
_controller.text = '$suggestion ';
_controller.selection = TextSelection.fromPosition(
TextPosition(offset: _controller.text.length),
);
},
),
);
}
Iterable<Widget> _buildResultsList(DocumentSearchState state) sync* {
if (state.hasLoaded && !state.isLoading && state.documents.isEmpty) {
yield Center(
child: Text(S.of(context)!.noMatchesFound),
);
return;
}
yield DefaultAdaptiveDocumentsView(
viewType: state.viewType,
documents: state.documents,
hasInternetConnection: true,
isLabelClickable: false,
isLoading: state.isLoading,
hasLoaded: state.hasLoaded,
enableHeroAnimation: false,
onTap: (document) {
pushDocumentDetailsRoute(
context,
document: document,
isLabelClickable: false,
); );
}, },
); );
} }
Widget _buildResultsView(DocumentSearchState state) { IconButton _buildUserAvatar(BuildContext context) {
final header = Row( return IconButton(
mainAxisAlignment: MainAxisAlignment.spaceBetween, icon: GlobalSettingsBuilder(
children: [ builder: (context, settings) {
Text( return ValueListenableBuilder(
S.of(context)!.results, valueListenable: Hive.box<LocalUserAccount>(HiveBoxes.localUserAccount).listenable(),
style: Theme.of(context).textTheme.bodySmall, builder: (context, box, _) {
), final account = box.get(settings.currentLoggedInUser!)!;
BlocBuilder<DocumentSearchCubit, DocumentSearchState>( return UserAvatar(
builder: (context, state) { userId: settings.currentLoggedInUser!,
return ViewTypeSelectionWidget( account: account,
viewType: state.viewType,
onChanged: (type) => context.read<DocumentSearchCubit>().updateViewType(type),
);
},
)
],
).padded();
return CustomScrollView(
slivers: [
SliverToBoxAdapter(child: header),
if (state.hasLoaded && !state.isLoading && state.documents.isEmpty)
SliverToBoxAdapter(
child: Center(
child: Text(S.of(context)!.noMatchesFound),
),
)
else
SliverAdaptiveDocumentsView(
viewType: state.viewType,
documents: state.documents,
hasInternetConnection: true,
isLabelClickable: false,
isLoading: state.isLoading,
hasLoaded: state.hasLoaded,
enableHeroAnimation: false,
onTap: (document) {
pushDocumentDetailsRoute(
context,
document: document,
isLabelClickable: false,
); );
}, },
) );
], },
),
onPressed: () {
final apiVersion = context.read<ApiVersion>();
showDialog(
context: context,
builder: (context) => Provider.value(
value: apiVersion,
child: const ManageAccountsPage(),
),
);
},
); );
} }
void _selectSuggestion(String suggestion) {
_controller.text = suggestion;
context.read<DocumentSearchCubit>().search(suggestion);
FocusScope.of(context).unfocus();
}
} }
@@ -32,38 +32,38 @@ class _DocumentSearchPageState extends State<DocumentSearchPage> {
final theme = Theme.of(context); final theme = Theme.of(context);
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
backgroundColor: theme.colorScheme.surface, backgroundColor: theme.colorScheme.surfaceVariant,
toolbarHeight: 72, toolbarHeight: 72,
leading: BackButton( leading: BackButton(
color: theme.colorScheme.onSurface, color: theme.colorScheme.onSurfaceVariant,
), ),
title: TextField( title: Hero(
autofocus: true, tag: "search_hero_tag",
style: theme.textTheme.bodyLarge?.apply( child: TextField(
color: theme.colorScheme.onSurface, autofocus: true,
), // style: theme.textTheme.bodyLarge?.apply(
focusNode: _queryFocusNode, // color: theme.colorScheme.onSurface,
decoration: InputDecoration( // ),
contentPadding: EdgeInsets.zero, focusNode: _queryFocusNode,
hintStyle: theme.textTheme.bodyLarge?.apply( decoration: InputDecoration(
color: theme.colorScheme.onSurfaceVariant, contentPadding: EdgeInsets.zero,
hintText: S.of(context)!.searchDocuments,
border: InputBorder.none,
), ),
hintText: S.of(context)!.searchDocuments, controller: _queryController,
border: InputBorder.none, onChanged: (query) {
_debounceTimer?.cancel();
_debounceTimer = Timer(const Duration(milliseconds: 500), () {
context.read<DocumentSearchCubit>().suggest(query);
});
},
textInputAction: TextInputAction.search,
onSubmitted: (query) {
FocusScope.of(context).unfocus();
_debounceTimer?.cancel();
context.read<DocumentSearchCubit>().search(query);
},
), ),
controller: _queryController,
onChanged: (query) {
_debounceTimer?.cancel();
_debounceTimer = Timer(const Duration(milliseconds: 500), () {
context.read<DocumentSearchCubit>().suggest(query);
});
},
textInputAction: TextInputAction.search,
onSubmitted: (query) {
FocusScope.of(context).unfocus();
_debounceTimer?.cancel();
context.read<DocumentSearchCubit>().search(query);
},
), ),
actions: [ actions: [
IconButton( IconButton(
@@ -75,22 +75,22 @@ class _DocumentSearchPageState extends State<DocumentSearchPage> {
}, },
).padded(), ).padded(),
], ],
bottom: PreferredSize(
preferredSize: const Size.fromHeight(1),
child: Divider(
color: theme.colorScheme.outline,
),
),
), ),
body: BlocBuilder<DocumentSearchCubit, DocumentSearchState>( body: Column(
builder: (context, state) { children: [
switch (state.view) { Expanded(
case SearchView.suggestions: child: BlocBuilder<DocumentSearchCubit, DocumentSearchState>(
return _buildSuggestionsView(state); builder: (context, state) {
case SearchView.results: switch (state.view) {
return _buildResultsView(state); case SearchView.suggestions:
} return _buildSuggestionsView(state);
}, case SearchView.results:
return _buildResultsView(state);
}
},
),
),
],
), ),
); );
} }
@@ -134,7 +134,7 @@ class _DocumentSearchPageState extends State<DocumentSearchPage> {
), ),
childCount: suggestions.length, childCount: suggestions.length,
), ),
) ),
], ],
); );
} }
@@ -43,9 +43,7 @@ class DocumentPreview extends StatelessWidget {
fit: fit, fit: fit,
alignment: alignment, alignment: alignment,
cacheKey: "thumb_${document.id}", cacheKey: "thumb_${document.id}",
imageUrl: context imageUrl: context.read<PaperlessDocumentsApi>().getThumbnailUrl(document.id),
.read<PaperlessDocumentsApi>()
.getThumbnailUrl(document.id),
errorWidget: (ctxt, msg, __) => Text(msg), errorWidget: (ctxt, msg, __) => Text(msg),
placeholder: (context, value) => Shimmer.fromColors( placeholder: (context, value) => Shimmer.fromColors(
baseColor: Colors.grey[300]!, baseColor: Colors.grey[300]!,
@@ -1,19 +0,0 @@
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
class CameraView extends StatelessWidget {
const CameraView({super.key, required this.controller});
final CameraController controller;
@override
Widget build(BuildContext context) {
if (!controller.value.isInitialized) {
return Container();
}
return Center(
child: CameraPreview(controller),
);
}
}
@@ -5,7 +5,6 @@ import 'package:camera/camera.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:paperless_document_scanner/types/edge_detection_result.dart'; import 'package:paperless_document_scanner/types/edge_detection_result.dart';
import 'camera_view.dart';
import 'cropping_preview.dart'; import 'cropping_preview.dart';
import 'edge_detector.dart'; import 'edge_detector.dart';
import 'image_view.dart'; import 'image_view.dart';
@@ -65,10 +64,6 @@ class _ScanState extends State<Scan> {
return ImageView(imagePath: croppedImagePath!); return ImageView(imagePath: croppedImagePath!);
} }
if (imagePath == null && edgeDetectionResult == null) {
return CameraView(controller: controller);
}
return ImagePreview( return ImagePreview(
imagePath: imagePath!, imagePath: imagePath!,
edgeDetectionResult: edgeDetectionResult, edgeDetectionResult: edgeDetectionResult,
@@ -129,22 +124,19 @@ class _ScanState extends State<Scan> {
imagePath = filePath; imagePath = filePath;
}); });
EdgeDetectionResult result = EdgeDetectionResult result = await EdgeDetector().detectEdgesFromFile(filePath);
await EdgeDetector().detectEdgesFromFile(filePath);
setState(() { setState(() {
edgeDetectionResult = result; edgeDetectionResult = result;
}); });
} }
Future _processImage( Future _processImage(String filePath, EdgeDetectionResult edgeDetectionResult) async {
String filePath, EdgeDetectionResult edgeDetectionResult) async {
if (!mounted) { if (!mounted) {
return; return;
} }
bool result = await EdgeDetector() bool result = await EdgeDetector().processImageFromFile(filePath, edgeDetectionResult);
.processImageFromFile(filePath, edgeDetectionResult);
if (result == false) { if (result == false) {
return; return;