Merge pull request #191 from astubenbord/feature/suggest-servers-on-login

Feature/suggest servers on login
This commit is contained in:
Anton Stubenbord
2023-06-03 15:58:20 +02:00
committed by GitHub
22 changed files with 758 additions and 463 deletions

View File

@@ -70,7 +70,7 @@ android {
} }
buildTypes { buildTypes {
release { release {
signingConfig signingConfigs.release signingConfig signingConfigs.debug
} }
} }

View File

@@ -20,6 +20,7 @@ class HiveBoxes {
static const localUserAccount = 'localUserAccount'; static const localUserAccount = 'localUserAccount';
static const localUserAppState = 'localUserAppState'; static const localUserAppState = 'localUserAppState';
static const localUserSettings = 'localUserSettings'; static const localUserSettings = 'localUserSettings';
static const hosts = 'hosts';
} }
class HiveTypeIds { class HiveTypeIds {

View File

@@ -10,21 +10,26 @@ class LabelRepository extends PersistentRepository<LabelRepositoryState> {
LabelRepository(this._api) : super(const LabelRepositoryState()); LabelRepository(this._api) : super(const LabelRepositoryState());
Future<void> initialize() { Future<void> initialize() async {
debugPrint("Initializing labels..."); debugPrint("[LabelRepository] initialize() called.");
return Future.wait([ try {
await Future.wait([
findAllCorrespondents(), findAllCorrespondents(),
findAllDocumentTypes(), findAllDocumentTypes(),
findAllStoragePaths(), findAllStoragePaths(),
findAllTags(), findAllTags(),
]).catchError((error) { ]);
debugPrint(error.toString()); } catch (error, stackTrace) {
}, test: (error) => false); debugPrint(
"[LabelRepository] An error occurred in initialize(): ${error.toString()}");
debugPrintStack(stackTrace: stackTrace);
}
} }
Future<Tag> createTag(Tag object) async { Future<Tag> createTag(Tag object) async {
final created = await _api.saveTag(object); final created = await _api.saveTag(object);
final updatedState = {...state.tags}..putIfAbsent(created.id!, () => created); final updatedState = {...state.tags}
..putIfAbsent(created.id!, () => created);
emit(state.copyWith(tags: updatedState)); emit(state.copyWith(tags: updatedState));
return created; return created;
} }
@@ -48,7 +53,8 @@ class LabelRepository extends PersistentRepository<LabelRepositoryState> {
Future<Iterable<Tag>> findAllTags([Iterable<int>? ids]) async { Future<Iterable<Tag>> findAllTags([Iterable<int>? ids]) async {
final tags = await _api.getTags(ids); final tags = await _api.getTags(ids);
final updatedState = {...state.tags}..addEntries(tags.map((e) => MapEntry(e.id!, e))); final updatedState = {...state.tags}
..addEntries(tags.map((e) => MapEntry(e.id!, e)));
emit(state.copyWith(tags: updatedState)); emit(state.copyWith(tags: updatedState));
return tags; return tags;
} }
@@ -62,14 +68,16 @@ class LabelRepository extends PersistentRepository<LabelRepositoryState> {
Future<Correspondent> createCorrespondent(Correspondent correspondent) async { Future<Correspondent> createCorrespondent(Correspondent correspondent) async {
final created = await _api.saveCorrespondent(correspondent); final created = await _api.saveCorrespondent(correspondent);
final updatedState = {...state.correspondents}..putIfAbsent(created.id!, () => created); final updatedState = {...state.correspondents}
..putIfAbsent(created.id!, () => created);
emit(state.copyWith(correspondents: updatedState)); emit(state.copyWith(correspondents: updatedState));
return created; return created;
} }
Future<int> deleteCorrespondent(Correspondent correspondent) async { Future<int> deleteCorrespondent(Correspondent correspondent) async {
await _api.deleteCorrespondent(correspondent); await _api.deleteCorrespondent(correspondent);
final updatedState = {...state.correspondents}..removeWhere((k, v) => k == correspondent.id); final updatedState = {...state.correspondents}
..removeWhere((k, v) => k == correspondent.id);
emit(state.copyWith(correspondents: updatedState)); emit(state.copyWith(correspondents: updatedState));
return correspondent.id!; return correspondent.id!;
@@ -86,22 +94,22 @@ class LabelRepository extends PersistentRepository<LabelRepositoryState> {
return null; return null;
} }
Future<Iterable<Correspondent>> findAllCorrespondents([Iterable<int>? ids]) async { Future<Iterable<Correspondent>> findAllCorrespondents(
[Iterable<int>? ids]) async {
debugPrint("Loading correspondents..."); debugPrint("Loading correspondents...");
final correspondents = await _api.getCorrespondents(ids); final correspondents = await _api.getCorrespondents(ids);
debugPrint("${correspondents.length} correspondents successfully loaded."); debugPrint("${correspondents.length} correspondents successfully loaded.");
final updatedState = { final updatedState = {
...state.correspondents, ...state.correspondents,
}..addAll({for (var element in correspondents) element.id!: element}); }..addAll({for (var element in correspondents) element.id!: element});
debugPrint("Pushing new correspondents state.");
emit(state.copyWith(correspondents: updatedState)); emit(state.copyWith(correspondents: updatedState));
debugPrint("New correspondents state pushed.");
return correspondents; return correspondents;
} }
Future<Correspondent> updateCorrespondent(Correspondent correspondent) async { Future<Correspondent> updateCorrespondent(Correspondent correspondent) async {
final updated = await _api.updateCorrespondent(correspondent); final updated = await _api.updateCorrespondent(correspondent);
final updatedState = {...state.correspondents}..update(updated.id!, (_) => updated); final updatedState = {...state.correspondents}
..update(updated.id!, (_) => updated);
emit(state.copyWith(correspondents: updatedState)); emit(state.copyWith(correspondents: updatedState));
return updated; return updated;
@@ -109,14 +117,16 @@ class LabelRepository extends PersistentRepository<LabelRepositoryState> {
Future<DocumentType> createDocumentType(DocumentType documentType) async { Future<DocumentType> createDocumentType(DocumentType documentType) async {
final created = await _api.saveDocumentType(documentType); final created = await _api.saveDocumentType(documentType);
final updatedState = {...state.documentTypes}..putIfAbsent(created.id!, () => created); final updatedState = {...state.documentTypes}
..putIfAbsent(created.id!, () => created);
emit(state.copyWith(documentTypes: updatedState)); emit(state.copyWith(documentTypes: updatedState));
return created; return created;
} }
Future<int> deleteDocumentType(DocumentType documentType) async { Future<int> deleteDocumentType(DocumentType documentType) async {
await _api.deleteDocumentType(documentType); await _api.deleteDocumentType(documentType);
final updatedState = {...state.documentTypes}..removeWhere((k, v) => k == documentType.id); final updatedState = {...state.documentTypes}
..removeWhere((k, v) => k == documentType.id);
emit(state.copyWith(documentTypes: updatedState)); emit(state.copyWith(documentTypes: updatedState));
return documentType.id!; return documentType.id!;
} }
@@ -131,7 +141,8 @@ class LabelRepository extends PersistentRepository<LabelRepositoryState> {
return null; return null;
} }
Future<Iterable<DocumentType>> findAllDocumentTypes([Iterable<int>? ids]) async { Future<Iterable<DocumentType>> findAllDocumentTypes(
[Iterable<int>? ids]) async {
final documentTypes = await _api.getDocumentTypes(ids); final documentTypes = await _api.getDocumentTypes(ids);
final updatedState = {...state.documentTypes} final updatedState = {...state.documentTypes}
..addEntries(documentTypes.map((e) => MapEntry(e.id!, e))); ..addEntries(documentTypes.map((e) => MapEntry(e.id!, e)));
@@ -141,21 +152,24 @@ class LabelRepository extends PersistentRepository<LabelRepositoryState> {
Future<DocumentType> updateDocumentType(DocumentType documentType) async { Future<DocumentType> updateDocumentType(DocumentType documentType) async {
final updated = await _api.updateDocumentType(documentType); final updated = await _api.updateDocumentType(documentType);
final updatedState = {...state.documentTypes}..update(updated.id!, (_) => updated); final updatedState = {...state.documentTypes}
..update(updated.id!, (_) => updated);
emit(state.copyWith(documentTypes: updatedState)); emit(state.copyWith(documentTypes: updatedState));
return updated; return updated;
} }
Future<StoragePath> createStoragePath(StoragePath storagePath) async { Future<StoragePath> createStoragePath(StoragePath storagePath) async {
final created = await _api.saveStoragePath(storagePath); final created = await _api.saveStoragePath(storagePath);
final updatedState = {...state.storagePaths}..putIfAbsent(created.id!, () => created); final updatedState = {...state.storagePaths}
..putIfAbsent(created.id!, () => created);
emit(state.copyWith(storagePaths: updatedState)); emit(state.copyWith(storagePaths: updatedState));
return created; return created;
} }
Future<int> deleteStoragePath(StoragePath storagePath) async { Future<int> deleteStoragePath(StoragePath storagePath) async {
await _api.deleteStoragePath(storagePath); await _api.deleteStoragePath(storagePath);
final updatedState = {...state.storagePaths}..removeWhere((k, v) => k == storagePath.id); final updatedState = {...state.storagePaths}
..removeWhere((k, v) => k == storagePath.id);
emit(state.copyWith(storagePaths: updatedState)); emit(state.copyWith(storagePaths: updatedState));
return storagePath.id!; return storagePath.id!;
} }
@@ -170,7 +184,8 @@ class LabelRepository extends PersistentRepository<LabelRepositoryState> {
return null; return null;
} }
Future<Iterable<StoragePath>> findAllStoragePaths([Iterable<int>? ids]) async { Future<Iterable<StoragePath>> findAllStoragePaths(
[Iterable<int>? ids]) async {
final storagePaths = await _api.getStoragePaths(ids); final storagePaths = await _api.getStoragePaths(ids);
final updatedState = {...state.storagePaths} final updatedState = {...state.storagePaths}
..addEntries(storagePaths.map((e) => MapEntry(e.id!, e))); ..addEntries(storagePaths.map((e) => MapEntry(e.id!, e)));
@@ -180,7 +195,8 @@ class LabelRepository extends PersistentRepository<LabelRepositoryState> {
Future<StoragePath> updateStoragePath(StoragePath storagePath) async { Future<StoragePath> updateStoragePath(StoragePath storagePath) async {
final updated = await _api.updateStoragePath(storagePath); final updated = await _api.updateStoragePath(storagePath);
final updatedState = {...state.storagePaths}..update(updated.id!, (_) => updated); final updatedState = {...state.storagePaths}
..update(updated.id!, (_) => updated);
emit(state.copyWith(storagePaths: updatedState)); emit(state.copyWith(storagePaths: updatedState));
return updated; return updated;
} }

View File

@@ -334,8 +334,7 @@ class FormBuilderTypeAhead<T> extends FormBuilderField<T> {
// TODO HACK to satisfy strictness // TODO HACK to satisfy strictness
suggestionsCallback: suggestionsCallback, suggestionsCallback: suggestionsCallback,
itemBuilder: itemBuilder, itemBuilder: itemBuilder,
transitionBuilder: (context, suggestionsBox, controller) => transitionBuilder: (context, suggestionsBox, controller) => suggestionsBox,
suggestionsBox,
onSuggestionSelected: (T suggestion) { onSuggestionSelected: (T suggestion) {
state.didChange(suggestion); state.didChange(suggestion);
onSuggestionSelected?.call(suggestion); onSuggestionSelected?.call(suggestion);
@@ -357,8 +356,7 @@ class FormBuilderTypeAhead<T> extends FormBuilderField<T> {
keepSuggestionsOnLoading: keepSuggestionsOnLoading, keepSuggestionsOnLoading: keepSuggestionsOnLoading,
autoFlipDirection: autoFlipDirection, autoFlipDirection: autoFlipDirection,
suggestionsBoxController: suggestionsBoxController, suggestionsBoxController: suggestionsBoxController,
keepSuggestionsOnSuggestionSelected: keepSuggestionsOnSuggestionSelected: keepSuggestionsOnSuggestionSelected,
keepSuggestionsOnSuggestionSelected,
hideKeyboard: hideKeyboard, hideKeyboard: hideKeyboard,
scrollController: scrollController, scrollController: scrollController,
); );
@@ -369,15 +367,14 @@ class FormBuilderTypeAhead<T> extends FormBuilderField<T> {
FormBuilderTypeAheadState<T> createState() => FormBuilderTypeAheadState<T>(); FormBuilderTypeAheadState<T> createState() => FormBuilderTypeAheadState<T>();
} }
class FormBuilderTypeAheadState<T> class FormBuilderTypeAheadState<T> extends FormBuilderFieldState<FormBuilderTypeAhead<T>, T> {
extends FormBuilderFieldState<FormBuilderTypeAhead<T>, T> {
late TextEditingController _typeAheadController; late TextEditingController _typeAheadController;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_typeAheadController = widget.controller ?? _typeAheadController =
TextEditingController(text: _getTextString(initialValue)); widget.controller ?? TextEditingController(text: _getTextString(initialValue));
// _typeAheadController.addListener(_handleControllerChanged); // _typeAheadController.addListener(_handleControllerChanged);
} }

View File

@@ -108,8 +108,9 @@ class _DocumentSearchPageState extends State<DocumentSearchPage> {
} }
Widget _buildSuggestionsView(DocumentSearchState state) { Widget _buildSuggestionsView(DocumentSearchState state) {
final suggestions = final suggestions = state.suggestions
state.suggestions.whereNot((element) => state.searchHistory.contains(element)).toList(); .whereNot((element) => state.searchHistory.contains(element))
.toList();
final historyMatches = state.searchHistory final historyMatches = state.searchHistory
.where( .where(
(element) => element.startsWith(query), (element) => element.startsWith(query),
@@ -140,7 +141,7 @@ class _DocumentSearchPageState extends State<DocumentSearchPage> {
childCount: suggestions.length, childCount: suggestions.length,
), ),
), ),
if (suggestions.isEmpty && historyMatches.isEmpty) if (suggestions.isEmpty && historyMatches.isEmpty && state.hasLoaded)
SliverPadding( SliverPadding(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
sliver: SliverToBoxAdapter( sliver: SliverToBoxAdapter(
@@ -191,7 +192,8 @@ class _DocumentSearchPageState extends State<DocumentSearchPage> {
builder: (context, state) { builder: (context, state) {
return ViewTypeSelectionWidget( return ViewTypeSelectionWidget(
viewType: state.viewType, viewType: state.viewType,
onChanged: (type) => context.read<DocumentSearchCubit>().updateViewType(type), onChanged: (type) =>
context.read<DocumentSearchCubit>().updateViewType(type),
); );
}, },
) )

View File

@@ -16,10 +16,13 @@ class SliverSearchBar extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final currentUser = final currentUser = Hive.box<GlobalSettings>(HiveBoxes.globalSettings)
Hive.box<GlobalSettings>(HiveBoxes.globalSettings).getValue()!.currentLoggedInUser; .getValue()!
.currentLoggedInUser;
return SliverPersistentHeader( return SliverPadding(
padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
sliver: SliverPersistentHeader(
floating: floating, floating: floating,
pinned: pinned, pinned: pinned,
delegate: CustomizableSliverPersistentHeaderDelegate( delegate: CustomizableSliverPersistentHeaderDelegate(
@@ -30,6 +33,7 @@ class SliverSearchBar extends StatelessWidget {
child: const DocumentSearchBar(), child: const DocumentSearchBar(),
), ),
), ),
),
); );
} }
} }

View File

@@ -42,9 +42,12 @@ class DocumentsPage extends StatefulWidget {
State<DocumentsPage> createState() => _DocumentsPageState(); State<DocumentsPage> createState() => _DocumentsPageState();
} }
class _DocumentsPageState extends State<DocumentsPage> with SingleTickerProviderStateMixin { class _DocumentsPageState extends State<DocumentsPage>
final SliverOverlapAbsorberHandle searchBarHandle = SliverOverlapAbsorberHandle(); with SingleTickerProviderStateMixin {
final SliverOverlapAbsorberHandle tabBarHandle = SliverOverlapAbsorberHandle(); final SliverOverlapAbsorberHandle searchBarHandle =
SliverOverlapAbsorberHandle();
final SliverOverlapAbsorberHandle tabBarHandle =
SliverOverlapAbsorberHandle();
late final TabController _tabController; late final TabController _tabController;
int _currentTab = 0; int _currentTab = 0;
@@ -81,7 +84,8 @@ class _DocumentsPageState extends State<DocumentsPage> with SingleTickerProvider
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BlocListener<TaskStatusCubit, TaskStatusState>( return BlocListener<TaskStatusCubit, TaskStatusState>(
listenWhen: (previous, current) => !previous.isSuccess && current.isSuccess, listenWhen: (previous, current) =>
!previous.isSuccess && current.isSuccess,
listener: (context, state) { listener: (context, state) {
showSnackBar( showSnackBar(
context, context,
@@ -98,7 +102,8 @@ class _DocumentsPageState extends State<DocumentsPage> with SingleTickerProvider
}, },
child: BlocConsumer<ConnectivityCubit, ConnectivityState>( child: BlocConsumer<ConnectivityCubit, ConnectivityState>(
listenWhen: (previous, current) => listenWhen: (previous, current) =>
previous != ConnectivityState.connected && current == ConnectivityState.connected, previous != ConnectivityState.connected &&
current == ConnectivityState.connected,
listener: (context, state) { listener: (context, state) {
try { try {
context.read<DocumentsCubit>().reload(); context.read<DocumentsCubit>().reload();
@@ -146,7 +151,11 @@ class _DocumentsPageState extends State<DocumentsPage> with SingleTickerProvider
resizeToAvoidBottomInset: true, resizeToAvoidBottomInset: true,
body: WillPopScope( body: WillPopScope(
onWillPop: () async { onWillPop: () async {
if (context.read<DocumentsCubit>().state.selection.isNotEmpty) { if (context
.read<DocumentsCubit>()
.state
.selection
.isNotEmpty) {
context.read<DocumentsCubit>().resetSelection(); context.read<DocumentsCubit>().resetSelection();
return false; return false;
} }
@@ -161,18 +170,13 @@ class _DocumentsPageState extends State<DocumentsPage> with SingleTickerProvider
handle: searchBarHandle, handle: searchBarHandle,
sliver: BlocBuilder<DocumentsCubit, DocumentsState>( sliver: BlocBuilder<DocumentsCubit, DocumentsState>(
builder: (context, state) { builder: (context, state) {
return AnimatedSwitcher( if (state.selection.isEmpty) {
layoutBuilder: SliverAnimatedSwitcher.defaultLayoutBuilder, return const SliverSearchBar(floating: true);
transitionBuilder: SliverAnimatedSwitcher.defaultTransitionBuilder, } else {
child: state.selection.isEmpty return DocumentSelectionSliverAppBar(
? const SliverSearchBar(floating: true)
: DocumentSelectionSliverAppBar(
state: state, state: state,
),
duration: const Duration(
milliseconds: 250,
),
); );
}
}, },
), ),
), ),
@@ -187,7 +191,8 @@ class _DocumentsPageState extends State<DocumentsPage> with SingleTickerProvider
} }
return SliverPersistentHeader( return SliverPersistentHeader(
pinned: true, pinned: true,
delegate: CustomizableSliverPersistentHeaderDelegate( delegate:
CustomizableSliverPersistentHeaderDelegate(
minExtent: kTextTabBarHeight, minExtent: kTextTabBarHeight,
maxExtent: kTextTabBarHeight, maxExtent: kTextTabBarHeight,
child: ColoredTabBar( child: ColoredTabBar(
@@ -211,15 +216,22 @@ class _DocumentsPageState extends State<DocumentsPage> with SingleTickerProvider
if (metrics.maxScrollExtent == 0) { if (metrics.maxScrollExtent == 0) {
return true; return true;
} }
final desiredTab = (metrics.pixels / metrics.maxScrollExtent).round(); final desiredTab =
if (metrics.axis == Axis.horizontal && _currentTab != desiredTab) { (metrics.pixels / metrics.maxScrollExtent)
.round();
if (metrics.axis == Axis.horizontal &&
_currentTab != desiredTab) {
setState(() => _currentTab = desiredTab); setState(() => _currentTab = desiredTab);
} }
return false; return false;
}, },
child: TabBarView( child: TabBarView(
controller: _tabController, controller: _tabController,
physics: context.watch<DocumentsCubit>().state.selection.isNotEmpty physics: context
.watch<DocumentsCubit>()
.state
.selection
.isNotEmpty
? const NeverScrollableScrollPhysics() ? const NeverScrollableScrollPhysics()
: null, : null,
children: [ children: [
@@ -287,13 +299,19 @@ class _DocumentsPageState extends State<DocumentsPage> with SingleTickerProvider
final currState = context.read<DocumentsCubit>().state; final currState = context.read<DocumentsCubit>().state;
final max = notification.metrics.maxScrollExtent; final max = notification.metrics.maxScrollExtent;
if (max == 0 || _currentTab != 0 || currState.isLoading || currState.isLastPageLoaded) { if (max == 0 ||
_currentTab != 0 ||
currState.isLoading ||
currState.isLastPageLoaded) {
return false; return false;
} }
final offset = notification.metrics.pixels; final offset = notification.metrics.pixels;
if (offset >= max * 0.7) { if (offset >= max * 0.7) {
context.read<DocumentsCubit>().loadMore().onError<PaperlessServerException>( context
.read<DocumentsCubit>()
.loadMore()
.onError<PaperlessServerException>(
(error, stackTrace) => showErrorMessage( (error, stackTrace) => showErrorMessage(
context, context,
error, error,
@@ -324,16 +342,20 @@ class _DocumentsPageState extends State<DocumentsPage> with SingleTickerProvider
), ),
); );
} }
final allowToggleFilter = state.selection.isEmpty;
return SliverAdaptiveDocumentsView( return SliverAdaptiveDocumentsView(
viewType: state.viewType, viewType: state.viewType,
onTap: _openDetails, onTap: _openDetails,
onSelected: context.read<DocumentsCubit>().toggleDocumentSelection, onSelected:
context.read<DocumentsCubit>().toggleDocumentSelection,
hasInternetConnection: connectivityState.isConnected, hasInternetConnection: connectivityState.isConnected,
onTagSelected: _addTagToFilter, onTagSelected: allowToggleFilter ? _addTagToFilter : null,
onCorrespondentSelected: _addCorrespondentToFilter, onCorrespondentSelected:
onDocumentTypeSelected: _addDocumentTypeToFilter, allowToggleFilter ? _addCorrespondentToFilter : null,
onStoragePathSelected: _addStoragePathToFilter, onDocumentTypeSelected:
allowToggleFilter ? _addDocumentTypeToFilter : null,
onStoragePathSelected:
allowToggleFilter ? _addStoragePathToFilter : null,
documents: state.documents, documents: state.documents,
hasLoaded: state.hasLoaded, hasLoaded: state.hasLoaded,
isLabelClickable: true, isLabelClickable: true,
@@ -401,7 +423,8 @@ class _DocumentsPageState extends State<DocumentsPage> with SingleTickerProvider
snapSizes: const [0.9, 1], snapSizes: const [0.9, 1],
initialChildSize: .9, initialChildSize: .9,
maxChildSize: 1, maxChildSize: 1,
builder: (context, controller) => BlocBuilder<DocumentsCubit, DocumentsState>( builder: (context, controller) =>
BlocBuilder<DocumentsCubit, DocumentsState>(
builder: (context, state) { builder: (context, state) {
return DocumentFilterPanel( return DocumentFilterPanel(
initialFilter: context.read<DocumentsCubit>().state.filter, initialFilter: context.read<DocumentsCubit>().state.filter,
@@ -422,7 +445,9 @@ class _DocumentsPageState extends State<DocumentsPage> with SingleTickerProvider
if (filterIntent.shouldReset) { if (filterIntent.shouldReset) {
await context.read<DocumentsCubit>().resetFilter(); await context.read<DocumentsCubit>().resetFilter();
} else { } else {
await context.read<DocumentsCubit>().updateFilter(filter: filterIntent.filter!); await context
.read<DocumentsCubit>()
.updateFilter(filter: filterIntent.filter!);
} }
} on PaperlessServerException catch (error, stackTrace) { } on PaperlessServerException catch (error, stackTrace) {
showErrorMessage(context, error, stackTrace); showErrorMessage(context, error, stackTrace);
@@ -439,7 +464,6 @@ class _DocumentsPageState extends State<DocumentsPage> with SingleTickerProvider
void _addTagToFilter(int tagId) { void _addTagToFilter(int tagId) {
final cubit = context.read<DocumentsCubit>(); final cubit = context.read<DocumentsCubit>();
try { try {
cubit.state.filter.tags.maybeMap( cubit.state.filter.tags.maybeMap(
ids: (state) { ids: (state) {
@@ -447,7 +471,9 @@ class _DocumentsPageState extends State<DocumentsPage> with SingleTickerProvider
cubit.updateCurrentFilter( cubit.updateCurrentFilter(
(filter) => filter.copyWith( (filter) => filter.copyWith(
tags: state.copyWith( tags: state.copyWith(
include: state.include.whereNot((element) => element == tagId).toList(), include: state.include
.whereNot((element) => element == tagId)
.toList(),
), ),
), ),
); );
@@ -455,7 +481,9 @@ class _DocumentsPageState extends State<DocumentsPage> with SingleTickerProvider
cubit.updateCurrentFilter( cubit.updateCurrentFilter(
(filter) => filter.copyWith( (filter) => filter.copyWith(
tags: state.copyWith( tags: state.copyWith(
exclude: state.exclude.whereNot((element) => element == tagId).toList(), exclude: state.exclude
.whereNot((element) => element == tagId)
.toList(),
), ),
), ),
); );
@@ -481,22 +509,26 @@ class _DocumentsPageState extends State<DocumentsPage> with SingleTickerProvider
void _addCorrespondentToFilter(int? correspondentId) { void _addCorrespondentToFilter(int? correspondentId) {
if (correspondentId == null) return; if (correspondentId == null) return;
final cubit = context.read<DocumentsCubit>(); final cubit = context.read<DocumentsCubit>();
try { try {
cubit.state.filter.correspondent.maybeWhen( cubit.state.filter.correspondent.maybeWhen(
fromId: (id) { fromId: (id) {
if (id == correspondentId) { if (id == correspondentId) {
cubit.updateCurrentFilter( cubit.updateCurrentFilter(
(filter) => filter.copyWith(correspondent: const IdQueryParameter.unset()), (filter) => filter.copyWith(
correspondent: const IdQueryParameter.unset()),
); );
} else { } else {
cubit.updateCurrentFilter( cubit.updateCurrentFilter(
(filter) => filter.copyWith(correspondent: IdQueryParameter.fromId(correspondentId)), (filter) => filter.copyWith(
correspondent: IdQueryParameter.fromId(correspondentId)),
); );
} }
}, },
orElse: () { orElse: () {
cubit.updateCurrentFilter( cubit.updateCurrentFilter(
(filter) => filter.copyWith(correspondent: IdQueryParameter.fromId(correspondentId)), (filter) => filter.copyWith(
correspondent: IdQueryParameter.fromId(correspondentId)),
); );
}, },
); );
@@ -508,22 +540,26 @@ class _DocumentsPageState extends State<DocumentsPage> with SingleTickerProvider
void _addDocumentTypeToFilter(int? documentTypeId) { void _addDocumentTypeToFilter(int? documentTypeId) {
if (documentTypeId == null) return; if (documentTypeId == null) return;
final cubit = context.read<DocumentsCubit>(); final cubit = context.read<DocumentsCubit>();
try { try {
cubit.state.filter.documentType.maybeWhen( cubit.state.filter.documentType.maybeWhen(
fromId: (id) { fromId: (id) {
if (id == documentTypeId) { if (id == documentTypeId) {
cubit.updateCurrentFilter( cubit.updateCurrentFilter(
(filter) => filter.copyWith(documentType: const IdQueryParameter.unset()), (filter) =>
filter.copyWith(documentType: const IdQueryParameter.unset()),
); );
} else { } else {
cubit.updateCurrentFilter( cubit.updateCurrentFilter(
(filter) => filter.copyWith(documentType: IdQueryParameter.fromId(documentTypeId)), (filter) => filter.copyWith(
documentType: IdQueryParameter.fromId(documentTypeId)),
); );
} }
}, },
orElse: () { orElse: () {
cubit.updateCurrentFilter( cubit.updateCurrentFilter(
(filter) => filter.copyWith(documentType: IdQueryParameter.fromId(documentTypeId)), (filter) => filter.copyWith(
documentType: IdQueryParameter.fromId(documentTypeId)),
); );
}, },
); );
@@ -535,22 +571,26 @@ class _DocumentsPageState extends State<DocumentsPage> with SingleTickerProvider
void _addStoragePathToFilter(int? pathId) { void _addStoragePathToFilter(int? pathId) {
if (pathId == null) return; if (pathId == null) return;
final cubit = context.read<DocumentsCubit>(); final cubit = context.read<DocumentsCubit>();
try { try {
cubit.state.filter.storagePath.maybeWhen( cubit.state.filter.storagePath.maybeWhen(
fromId: (id) { fromId: (id) {
if (id == pathId) { if (id == pathId) {
cubit.updateCurrentFilter( cubit.updateCurrentFilter(
(filter) => filter.copyWith(storagePath: const IdQueryParameter.unset()), (filter) =>
filter.copyWith(storagePath: const IdQueryParameter.unset()),
); );
} else { } else {
cubit.updateCurrentFilter( cubit.updateCurrentFilter(
(filter) => filter.copyWith(storagePath: IdQueryParameter.fromId(pathId)), (filter) =>
filter.copyWith(storagePath: IdQueryParameter.fromId(pathId)),
); );
} }
}, },
orElse: () { orElse: () {
cubit.updateCurrentFilter( cubit.updateCurrentFilter(
(filter) => filter.copyWith(storagePath: IdQueryParameter.fromId(pathId)), (filter) =>
filter.copyWith(storagePath: IdQueryParameter.fromId(pathId)),
); );
}, },
); );

View File

@@ -81,40 +81,25 @@ class DocumentListItem extends DocumentItem {
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
text: TextSpan( text: TextSpan(
text: DateFormat.yMMMd().format(document.created), text: DateFormat.yMMMd().format(document.created),
style: Theme.of(context).textTheme.labelSmall?.apply(color: Colors.grey), style: Theme.of(context)
.textTheme
.labelSmall
?.apply(color: Colors.grey),
children: document.documentType != null children: document.documentType != null
? [ ? [
const TextSpan(text: '\u30FB'), const TextSpan(text: '\u30FB'),
TextSpan( TextSpan(
text: labels.documentTypes[document.documentType]?.name, text: labels.documentTypes[document.documentType]?.name,
recognizer: TapGestureRecognizer() recognizer: onDocumentTypeSelected != null
..onTap = () => onDocumentTypeSelected?.call(document.documentType), ? (TapGestureRecognizer()
..onTap = () => onDocumentTypeSelected!(
document.documentType))
: null,
), ),
] ]
: null, : null,
), ),
), ),
// Row(
// children: [
// Text(
// DateFormat.yMMMd().format(document.created),
// style: Theme.of(context)
// .textTheme
// .bodySmall
// ?.apply(color: Colors.grey),
// ),
// if (document.documentType != null) ...[
// Text("\u30FB"),
// DocumentTypeWidget(
// documentTypeId: document.documentType,
// textStyle: Theme.of(context).textTheme.bodySmall?.apply(
// color: Colors.grey,
// overflow: TextOverflow.ellipsis,
// ),
// ),
// ],
// ],
// ),
), ),
isThreeLine: document.tags.isNotEmpty, isThreeLine: document.tags.isNotEmpty,
leading: AspectRatio( leading: AspectRatio(

View File

@@ -32,7 +32,8 @@ import 'package:responsive_builder/responsive_builder.dart';
/// Performs initialization logic. /// Performs initialization logic.
class HomePage extends StatefulWidget { class HomePage extends StatefulWidget {
final int paperlessApiVersion; final int paperlessApiVersion;
const HomePage({Key? key, required this.paperlessApiVersion}) : super(key: key); const HomePage({Key? key, required this.paperlessApiVersion})
: super(key: key);
@override @override
_HomePageState createState() => _HomePageState(); _HomePageState createState() => _HomePageState();
@@ -231,17 +232,38 @@ class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
listeners: [ listeners: [
BlocListener<ConnectivityCubit, ConnectivityState>( BlocListener<ConnectivityCubit, ConnectivityState>(
// If app was started offline, load data once it comes back online. // If app was started offline, load data once it comes back online.
listenWhen: (previous, current) => current == ConnectivityState.connected, listenWhen: (previous, current) =>
listener: (context, state) { previous != ConnectivityState.connected &&
context.read<LabelRepository>().initialize(); current == ConnectivityState.connected,
context.read<SavedViewRepository>().initialize(); listener: (context, state) async {
try {
debugPrint(
"[HomePage] BlocListener#listener: "
"Loading saved views and labels...",
);
await Future.wait([
context.read<LabelRepository>().initialize(),
context.read<SavedViewRepository>().initialize(),
]);
debugPrint("[HomePage] BlocListener#listener: "
"Saved views and labels successfully loaded.");
} catch (error, stackTrace) {
debugPrint(
'[HomePage] BlocListener.listener: '
'An error occurred while loading saved views and labels.\n'
'${error.toString()}',
);
debugPrintStack(stackTrace: stackTrace);
}
}, },
), ),
BlocListener<TaskStatusCubit, TaskStatusState>( BlocListener<TaskStatusCubit, TaskStatusState>(
listener: (context, state) { listener: (context, state) {
if (state.task != null) { if (state.task != null) {
// Handle local notifications on task change (only when app is running for now). // Handle local notifications on task change (only when app is running for now).
context.read<LocalNotificationService>().notifyTaskChanged(state.task!); context
.read<LocalNotificationService>()
.notifyTaskChanged(state.task!);
} }
}, },
), ),
@@ -254,7 +276,9 @@ class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
children: [ children: [
NavigationRail( NavigationRail(
labelType: NavigationRailLabelType.all, labelType: NavigationRailLabelType.all,
destinations: destinations.map((e) => e.toNavigationRailDestination()).toList(), destinations: destinations
.map((e) => e.toNavigationRailDestination())
.toList(),
selectedIndex: _currentIndex, selectedIndex: _currentIndex,
onDestinationSelected: _onNavigationChanged, onDestinationSelected: _onNavigationChanged,
), ),
@@ -272,7 +296,8 @@ class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
elevation: 4.0, elevation: 4.0,
selectedIndex: _currentIndex, selectedIndex: _currentIndex,
onDestinationSelected: _onNavigationChanged, onDestinationSelected: _onNavigationChanged,
destinations: destinations.map((e) => e.toNavigationDestination()).toList(), destinations:
destinations.map((e) => e.toNavigationDestination()).toList(),
), ),
body: routes[_currentIndex], body: routes[_currentIndex],
); );

View File

@@ -13,7 +13,8 @@ import 'package:paperless_mobile/features/paged_document_view/cubit/document_pag
part 'inbox_cubit.g.dart'; part 'inbox_cubit.g.dart';
part 'inbox_state.dart'; part 'inbox_state.dart';
class InboxCubit extends HydratedCubit<InboxState> with DocumentPagingBlocMixin { class InboxCubit extends HydratedCubit<InboxState>
with DocumentPagingBlocMixin {
final LabelRepository _labelRepository; final LabelRepository _labelRepository;
final PaperlessDocumentsApi _documentsApi; final PaperlessDocumentsApi _documentsApi;
@@ -38,7 +39,10 @@ class InboxCubit extends HydratedCubit<InboxState> with DocumentPagingBlocMixin
this, this,
onDeleted: remove, onDeleted: remove,
onUpdated: (document) { onUpdated: (document) {
if (document.tags.toSet().intersection(state.inboxTags.toSet()).isEmpty) { if (document.tags
.toSet()
.intersection(state.inboxTags.toSet())
.isEmpty) {
remove(document); remove(document);
emit(state.copyWith(itemsInInboxCount: state.itemsInInboxCount - 1)); emit(state.copyWith(itemsInInboxCount: state.itemsInInboxCount - 1));
} else { } else {
@@ -139,7 +143,8 @@ class InboxCubit extends HydratedCubit<InboxState> with DocumentPagingBlocMixin
/// from the inbox. /// from the inbox.
/// ///
Future<Iterable<int>> removeFromInbox(DocumentModel document) async { Future<Iterable<int>> removeFromInbox(DocumentModel document) async {
final tagsToRemove = document.tags.toSet().intersection(state.inboxTags.toSet()); final tagsToRemove =
document.tags.toSet().intersection(state.inboxTags.toSet());
final updatedTags = {...document.tags}..removeAll(tagsToRemove); final updatedTags = {...document.tags}..removeAll(tagsToRemove);
final updatedDocument = await api.update( final updatedDocument = await api.update(
@@ -193,8 +198,8 @@ class InboxCubit extends HydratedCubit<InboxState> with DocumentPagingBlocMixin
Future<void> assignAsn(DocumentModel document) async { Future<void> assignAsn(DocumentModel document) async {
if (document.archiveSerialNumber == null) { if (document.archiveSerialNumber == null) {
final int asn = await _documentsApi.findNextAsn(); final int asn = await _documentsApi.findNextAsn();
final updatedDocument = final updatedDocument = await _documentsApi
await _documentsApi.update(document.copyWith(archiveSerialNumber: () => asn)); .update(document.copyWith(archiveSerialNumber: () => asn));
replace(updatedDocument); replace(updatedDocument);
} }

View File

@@ -15,7 +15,6 @@ import 'package:paperless_mobile/features/document_search/view/sliver_search_bar
import 'package:paperless_mobile/features/inbox/cubit/inbox_cubit.dart'; import 'package:paperless_mobile/features/inbox/cubit/inbox_cubit.dart';
import 'package:paperless_mobile/features/inbox/view/widgets/inbox_empty_widget.dart'; import 'package:paperless_mobile/features/inbox/view/widgets/inbox_empty_widget.dart';
import 'package:paperless_mobile/features/inbox/view/widgets/inbox_item.dart'; import 'package:paperless_mobile/features/inbox/view/widgets/inbox_item.dart';
import 'package:paperless_mobile/features/inbox/view/widgets/inbox_list_loading_widget.dart';
import 'package:paperless_mobile/features/paged_document_view/view/document_paging_view_mixin.dart'; import 'package:paperless_mobile/features/paged_document_view/view/document_paging_view_mixin.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart'; import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
import 'package:paperless_mobile/helpers/message_helpers.dart'; import 'package:paperless_mobile/helpers/message_helpers.dart';
@@ -27,18 +26,15 @@ class InboxPage extends StatefulWidget {
State<InboxPage> createState() => _InboxPageState(); State<InboxPage> createState() => _InboxPageState();
} }
class _InboxPageState extends State<InboxPage> with DocumentPagingViewMixin<InboxPage, InboxCubit> { class _InboxPageState extends State<InboxPage>
final SliverOverlapAbsorberHandle searchBarHandle = SliverOverlapAbsorberHandle(); with DocumentPagingViewMixin<InboxPage, InboxCubit> {
final SliverOverlapAbsorberHandle searchBarHandle =
SliverOverlapAbsorberHandle();
@override @override
final pagingScrollController = ScrollController(); final pagingScrollController = ScrollController();
final _emptyStateRefreshIndicatorKey = GlobalKey<RefreshIndicatorState>(); final _emptyStateRefreshIndicatorKey = GlobalKey<RefreshIndicatorState>();
final _scrollController = ScrollController();
@override
void initState() {
super.initState();
context.read<InboxCubit>().reloadInbox();
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -63,9 +59,7 @@ class _InboxPageState extends State<InboxPage> with DocumentPagingViewMixin<Inbo
); );
}, },
), ),
body: BlocBuilder<InboxCubit, InboxState>( body: SafeArea(
builder: (context, state) {
return SafeArea(
top: true, top: true,
child: NestedScrollView( child: NestedScrollView(
headerSliverBuilder: (context, innerBoxIsScrolled) => [ headerSliverBuilder: (context, innerBoxIsScrolled) => [
@@ -74,16 +68,23 @@ class _InboxPageState extends State<InboxPage> with DocumentPagingViewMixin<Inbo
sliver: const SliverSearchBar(), sliver: const SliverSearchBar(),
) )
], ],
body: Builder( body: BlocBuilder<InboxCubit, InboxState>(
builder: (context) { builder: (_, state) {
if (!state.hasLoaded) { if (state.documents.isEmpty && state.hasLoaded) {
return const InboxListLoadingWidget();
} else if (state.documents.isEmpty) {
return Center( return Center(
child: InboxEmptyWidget( child: InboxEmptyWidget(
emptyStateRefreshIndicatorKey: _emptyStateRefreshIndicatorKey, emptyStateRefreshIndicatorKey:
_emptyStateRefreshIndicatorKey,
), ),
); );
} else if (state.isLoading) {
return ListView.builder(
padding: const EdgeInsets.only(top: 16, left: 16),
controller: _scrollController,
itemBuilder: (context, index) {
return const InboxItemPlaceholder();
},
);
} else { } else {
return RefreshIndicator( return RefreshIndicator(
onRefresh: context.read<InboxCubit>().reload, onRefresh: context.read<InboxCubit>().reload,
@@ -92,7 +93,8 @@ class _InboxPageState extends State<InboxPage> with DocumentPagingViewMixin<Inbo
SliverToBoxAdapter( SliverToBoxAdapter(
child: HintCard( child: HintCard(
show: !state.isHintAcknowledged, show: !state.isHintAcknowledged,
hintText: S.of(context)!.swipeLeftToMarkADocumentAsSeen, hintText:
S.of(context)!.swipeLeftToMarkADocumentAsSeen,
onHintAcknowledged: () => onHintAcknowledged: () =>
context.read<InboxCubit>().acknowledgeHint(), context.read<InboxCubit>().acknowledgeHint(),
), ),
@@ -110,7 +112,8 @@ class _InboxPageState extends State<InboxPage> with DocumentPagingViewMixin<Inbo
borderRadius: BorderRadius.circular(32.0), borderRadius: BorderRadius.circular(32.0),
child: Text( child: Text(
entry.key, entry.key,
style: Theme.of(context).textTheme.bodySmall, style:
Theme.of(context).textTheme.bodySmall,
textAlign: TextAlign.center, textAlign: TextAlign.center,
).padded(), ).padded(),
), ),
@@ -153,8 +156,6 @@ class _InboxPageState extends State<InboxPage> with DocumentPagingViewMixin<Inbo
}, },
), ),
), ),
);
},
), ),
); );
} }
@@ -239,7 +240,9 @@ class _InboxPageState extends State<InboxPage> with DocumentPagingViewMixin<Inbo
Iterable<int> removedTags, Iterable<int> removedTags,
) async { ) async {
try { try {
await context.read<InboxCubit>().undoRemoveFromInbox(document, removedTags); await context
.read<InboxCubit>()
.undoRemoveFromInbox(document, removedTags);
} on PaperlessServerException catch (error, stackTrace) { } on PaperlessServerException catch (error, stackTrace) {
showErrorMessage(context, error, stackTrace); showErrorMessage(context, error, stackTrace);
} }

View File

@@ -4,18 +4,130 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:paperless_api/paperless_api.dart'; import 'package:paperless_api/paperless_api.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/navigation/push_routes.dart';
import 'package:paperless_mobile/core/widgets/shimmer_placeholder.dart';
import 'package:paperless_mobile/core/workarounds/colored_chip.dart'; import 'package:paperless_mobile/core/workarounds/colored_chip.dart';
import 'package:paperless_mobile/extensions/flutter_extensions.dart'; import 'package:paperless_mobile/extensions/flutter_extensions.dart';
import 'package:paperless_mobile/features/documents/view/widgets/delete_document_confirmation_dialog.dart'; import 'package:paperless_mobile/features/documents/view/widgets/delete_document_confirmation_dialog.dart';
import 'package:paperless_mobile/features/documents/view/widgets/document_preview.dart'; import 'package:paperless_mobile/features/documents/view/widgets/document_preview.dart';
import 'package:paperless_mobile/features/documents/view/widgets/placeholder/tags_placeholder.dart';
import 'package:paperless_mobile/features/documents/view/widgets/placeholder/text_placeholder.dart';
import 'package:paperless_mobile/features/inbox/cubit/inbox_cubit.dart'; import 'package:paperless_mobile/features/inbox/cubit/inbox_cubit.dart';
import 'package:paperless_mobile/features/labels/tags/view/widgets/tags_widget.dart'; import 'package:paperless_mobile/features/labels/tags/view/widgets/tags_widget.dart';
import 'package:paperless_mobile/features/labels/view/widgets/label_text.dart'; import 'package:paperless_mobile/features/labels/view/widgets/label_text.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart'; import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
class InboxItemPlaceholder extends StatelessWidget {
const InboxItemPlaceholder({super.key});
@override
Widget build(BuildContext context) {
return ShimmerPlaceholder(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const TextPlaceholder(length: 150, fontSize: 12),
const SizedBox(
height: 16,
),
SizedBox(
height: 200,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 150,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
height: 120,
width: 90,
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: const ColoredBox(
color: Colors.white,
),
),
),
const SizedBox(width: 8),
const Flexible(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Spacer(),
TextPlaceholder(length: 200, fontSize: 14),
Spacer(),
TextPlaceholder(length: 120, fontSize: 14),
SizedBox(height: 8),
TextPlaceholder(length: 170, fontSize: 14),
Spacer(),
TagsPlaceholder(count: 3, dense: true),
Spacer(),
],
),
),
],
),
),
SizedBox(
height: 50,
child: IntrinsicHeight(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
physics: const NeverScrollableScrollPhysics(),
child: Row(
children: [
const SizedBox(
width: 50,
height: 40,
child: ColoredBox(
color: Colors.white,
),
).padded(),
const VerticalDivider(
indent: 12,
endIndent: 12,
),
SizedBox(
height: 40,
child: Row(
children: [
Container(
width: 150,
height: 48,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: Colors.white,
),
),
const SizedBox(width: 4),
Container(
width: 200,
height: 40,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: Colors.white,
),
),
],
),
),
],
),
),
),
),
],
),
),
],
),
);
}
}
class InboxItem extends StatefulWidget { class InboxItem extends StatefulWidget {
static const a4AspectRatio = 1 / 1.4142; static const a4AspectRatio = 1 / 1.4142;
final DocumentModel document; final DocumentModel document;
const InboxItem({ const InboxItem({
super.key, super.key,
@@ -70,10 +182,14 @@ class _InboxItemState extends State<InboxItem> {
_buildTextWithLeadingIcon( _buildTextWithLeadingIcon(
Icon( Icon(
Icons.person_outline, Icons.person_outline,
size: Theme.of(context).textTheme.bodyMedium?.fontSize, size: Theme.of(context)
.textTheme
.bodyMedium
?.fontSize,
), ),
LabelText<Correspondent>( LabelText<Correspondent>(
label: state.labels.correspondents[widget.document.correspondent], label: state.labels.correspondents[
widget.document.correspondent],
style: Theme.of(context).textTheme.bodyMedium, style: Theme.of(context).textTheme.bodyMedium,
placeholder: "-", placeholder: "-",
), ),
@@ -81,10 +197,14 @@ class _InboxItemState extends State<InboxItem> {
_buildTextWithLeadingIcon( _buildTextWithLeadingIcon(
Icon( Icon(
Icons.description_outlined, Icons.description_outlined,
size: Theme.of(context).textTheme.bodyMedium?.fontSize, size: Theme.of(context)
.textTheme
.bodyMedium
?.fontSize,
), ),
LabelText<DocumentType>( LabelText<DocumentType>(
label: state.labels.documentTypes[widget.document.documentType], label: state.labels.documentTypes[
widget.document.documentType],
style: Theme.of(context).textTheme.bodyMedium, style: Theme.of(context).textTheme.bodyMedium,
placeholder: "-", placeholder: "-",
), ),
@@ -139,8 +259,8 @@ class _InboxItemState extends State<InboxItem> {
onPressed: () async { onPressed: () async {
final shouldDelete = await showDialog<bool>( final shouldDelete = await showDialog<bool>(
context: context, context: context,
builder: (context) => builder: (context) => DeleteDocumentConfirmationDialog(
DeleteDocumentConfirmationDialog(document: widget.document), document: widget.document),
) ?? ) ??
false; false;
if (shouldDelete) { if (shouldDelete) {
@@ -217,7 +337,10 @@ class _InboxItemState extends State<InboxItem> {
_isAsnAssignLoading = true; _isAsnAssignLoading = true;
}); });
context.read<InboxCubit>().assignAsn(widget.document).whenComplete( context
.read<InboxCubit>()
.assignAsn(widget.document)
.whenComplete(
() => setState(() => _isAsnAssignLoading = false), () => setState(() => _isAsnAssignLoading = false),
); );
} }

View File

@@ -1,124 +0,0 @@
import 'package:flutter/material.dart';
import 'package:paperless_mobile/core/widgets/shimmer_placeholder.dart';
import 'package:paperless_mobile/extensions/flutter_extensions.dart';
import 'package:paperless_mobile/features/documents/view/widgets/placeholder/tags_placeholder.dart';
import 'package:paperless_mobile/features/documents/view/widgets/placeholder/text_placeholder.dart';
class InboxListLoadingWidget extends StatelessWidget {
const InboxListLoadingWidget({super.key});
@override
Widget build(BuildContext context) {
return ListView.separated(
itemCount: 20,
physics: const NeverScrollableScrollPhysics(),
itemBuilder: (context, index) => _buildInboxItem().padded(),
separatorBuilder: (context, index) => const SizedBox(height: 16),
).paddedOnly(top: 8);
}
Widget _buildInboxItem() {
return ShimmerPlaceholder(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const TextPlaceholder(length: 150, fontSize: 12),
const SizedBox(
height: 16,
),
SizedBox(
height: 200,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 150,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
height: 120,
width: 90,
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: const ColoredBox(
color: Colors.white,
),
),
),
const SizedBox(width: 8),
const Flexible(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Spacer(),
TextPlaceholder(length: 200, fontSize: 14),
Spacer(),
TextPlaceholder(length: 120, fontSize: 14),
SizedBox(height: 8),
TextPlaceholder(length: 170, fontSize: 14),
Spacer(),
TagsPlaceholder(count: 3, dense: true),
Spacer(),
],
),
),
],
),
),
SizedBox(
height: 50,
child: IntrinsicHeight(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
physics: const NeverScrollableScrollPhysics(),
child: Row(
children: [
const SizedBox(
width: 50,
height: 40,
child: ColoredBox(
color: Colors.white,
),
).padded(),
const VerticalDivider(
indent: 12,
endIndent: 12,
),
SizedBox(
height: 40,
child: Row(
children: [
Container(
width: 150,
height: 48,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: Colors.white,
),
),
const SizedBox(width: 4),
Container(
width: 200,
height: 40,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: Colors.white,
),
),
],
),
),
],
),
),
),
),
],
),
),
],
),
);
}
}

View File

@@ -29,9 +29,12 @@ class LabelsPage extends StatefulWidget {
State<LabelsPage> createState() => _LabelsPageState(); State<LabelsPage> createState() => _LabelsPageState();
} }
class _LabelsPageState extends State<LabelsPage> with SingleTickerProviderStateMixin { class _LabelsPageState extends State<LabelsPage>
final SliverOverlapAbsorberHandle searchBarHandle = SliverOverlapAbsorberHandle(); with SingleTickerProviderStateMixin {
final SliverOverlapAbsorberHandle tabBarHandle = SliverOverlapAbsorberHandle(); final SliverOverlapAbsorberHandle searchBarHandle =
SliverOverlapAbsorberHandle();
final SliverOverlapAbsorberHandle tabBarHandle =
SliverOverlapAbsorberHandle();
late final TabController _tabController; late final TabController _tabController;
int _currentIndex = 0; int _currentIndex = 0;
@@ -81,25 +84,33 @@ class _LabelsPageState extends State<LabelsPage> with SingleTickerProviderStateM
Tab( Tab(
icon: Icon( icon: Icon(
Icons.person_outline, Icons.person_outline,
color: Theme.of(context).colorScheme.onPrimaryContainer, color: Theme.of(context)
.colorScheme
.onPrimaryContainer,
), ),
), ),
Tab( Tab(
icon: Icon( icon: Icon(
Icons.description_outlined, Icons.description_outlined,
color: Theme.of(context).colorScheme.onPrimaryContainer, color: Theme.of(context)
.colorScheme
.onPrimaryContainer,
), ),
), ),
Tab( Tab(
icon: Icon( icon: Icon(
Icons.label_outline, Icons.label_outline,
color: Theme.of(context).colorScheme.onPrimaryContainer, color: Theme.of(context)
.colorScheme
.onPrimaryContainer,
), ),
), ),
Tab( Tab(
icon: Icon( icon: Icon(
Icons.folder_open, Icons.folder_open,
color: Theme.of(context).colorScheme.onPrimaryContainer, color: Theme.of(context)
.colorScheme
.onPrimaryContainer,
), ),
), ),
], ],
@@ -118,25 +129,44 @@ class _LabelsPageState extends State<LabelsPage> with SingleTickerProviderStateM
if (metrics.maxScrollExtent == 0) { if (metrics.maxScrollExtent == 0) {
return true; return true;
} }
final desiredTab = ((metrics.pixels / metrics.maxScrollExtent) * final desiredTab =
((metrics.pixels / metrics.maxScrollExtent) *
(_tabController.length - 1)) (_tabController.length - 1))
.round(); .round();
if (metrics.axis == Axis.horizontal && _currentIndex != desiredTab) { if (metrics.axis == Axis.horizontal &&
_currentIndex != desiredTab) {
setState(() => _currentIndex = desiredTab); setState(() => _currentIndex = desiredTab);
} }
return true; return true;
}, },
child: RefreshIndicator( child: RefreshIndicator(
edgeOffset: kTextTabBarHeight, edgeOffset: kTextTabBarHeight,
notificationPredicate: (notification) => connectedState.isConnected, notificationPredicate: (notification) =>
onRefresh: () => [ connectedState.isConnected,
onRefresh: () async {
try {
await [
context.read<LabelCubit>().reloadCorrespondents, context.read<LabelCubit>().reloadCorrespondents,
context.read<LabelCubit>().reloadDocumentTypes, context.read<LabelCubit>().reloadDocumentTypes,
context.read<LabelCubit>().reloadTags, context.read<LabelCubit>().reloadTags,
context.read<LabelCubit>().reloadStoragePaths, context.read<LabelCubit>().reloadStoragePaths,
][_currentIndex] ][_currentIndex]
.call(), .call();
} catch (error, stackTrace) {
debugPrint(
"[LabelsPage] RefreshIndicator.onRefresh "
"${[
"correspondents",
"document types",
"tags",
"storage paths"
][_currentIndex]}: "
"An error occurred (${error.toString()})",
);
debugPrintStack(stackTrace: stackTrace);
}
},
child: TabBarView( child: TabBarView(
controller: _tabController, controller: _tabController,
children: [ children: [
@@ -144,22 +174,29 @@ class _LabelsPageState extends State<LabelsPage> with SingleTickerProviderStateM
builder: (context) { builder: (context) {
return CustomScrollView( return CustomScrollView(
slivers: [ slivers: [
SliverOverlapInjector(handle: searchBarHandle), SliverOverlapInjector(
handle: searchBarHandle),
SliverOverlapInjector(handle: tabBarHandle), SliverOverlapInjector(handle: tabBarHandle),
LabelTabView<Correspondent>( LabelTabView<Correspondent>(
labels: state.correspondents, labels: state.correspondents,
filterBuilder: (label) => DocumentFilter( filterBuilder: (label) => DocumentFilter(
correspondent: IdQueryParameter.fromId(label.id!), correspondent:
IdQueryParameter.fromId(label.id!),
), ),
canEdit: LocalUserAccount.current.paperlessUser.hasPermission( canEdit: LocalUserAccount
PermissionAction.change, PermissionTarget.correspondent), .current.paperlessUser
canAddNew: LocalUserAccount.current.paperlessUser
.hasPermission( .hasPermission(
PermissionAction.add, PermissionTarget.correspondent), PermissionAction.change,
PermissionTarget.correspondent),
canAddNew: LocalUserAccount
.current.paperlessUser
.hasPermission(PermissionAction.add,
PermissionTarget.correspondent),
onEdit: _openEditCorrespondentPage, onEdit: _openEditCorrespondentPage,
emptyStateActionButtonLabel: emptyStateActionButtonLabel:
S.of(context)!.addNewCorrespondent, S.of(context)!.addNewCorrespondent,
emptyStateDescription: S.of(context)!.noCorrespondentsSetUp, emptyStateDescription:
S.of(context)!.noCorrespondentsSetUp,
onAddNew: _openAddCorrespondentPage, onAddNew: _openAddCorrespondentPage,
), ),
], ],
@@ -170,22 +207,29 @@ class _LabelsPageState extends State<LabelsPage> with SingleTickerProviderStateM
builder: (context) { builder: (context) {
return CustomScrollView( return CustomScrollView(
slivers: [ slivers: [
SliverOverlapInjector(handle: searchBarHandle), SliverOverlapInjector(
handle: searchBarHandle),
SliverOverlapInjector(handle: tabBarHandle), SliverOverlapInjector(handle: tabBarHandle),
LabelTabView<DocumentType>( LabelTabView<DocumentType>(
labels: state.documentTypes, labels: state.documentTypes,
filterBuilder: (label) => DocumentFilter( filterBuilder: (label) => DocumentFilter(
documentType: IdQueryParameter.fromId(label.id!), documentType:
IdQueryParameter.fromId(label.id!),
), ),
canEdit: LocalUserAccount.current.paperlessUser.hasPermission( canEdit: LocalUserAccount
PermissionAction.change, PermissionTarget.documentType), .current.paperlessUser
canAddNew: LocalUserAccount.current.paperlessUser
.hasPermission( .hasPermission(
PermissionAction.add, PermissionTarget.documentType), PermissionAction.change,
PermissionTarget.documentType),
canAddNew: LocalUserAccount
.current.paperlessUser
.hasPermission(PermissionAction.add,
PermissionTarget.documentType),
onEdit: _openEditDocumentTypePage, onEdit: _openEditDocumentTypePage,
emptyStateActionButtonLabel: emptyStateActionButtonLabel:
S.of(context)!.addNewDocumentType, S.of(context)!.addNewDocumentType,
emptyStateDescription: S.of(context)!.noDocumentTypesSetUp, emptyStateDescription:
S.of(context)!.noDocumentTypesSetUp,
onAddNew: _openAddDocumentTypePage, onAddNew: _openAddDocumentTypePage,
), ),
], ],
@@ -196,18 +240,24 @@ class _LabelsPageState extends State<LabelsPage> with SingleTickerProviderStateM
builder: (context) { builder: (context) {
return CustomScrollView( return CustomScrollView(
slivers: [ slivers: [
SliverOverlapInjector(handle: searchBarHandle), SliverOverlapInjector(
handle: searchBarHandle),
SliverOverlapInjector(handle: tabBarHandle), SliverOverlapInjector(handle: tabBarHandle),
LabelTabView<Tag>( LabelTabView<Tag>(
labels: state.tags, labels: state.tags,
filterBuilder: (label) => DocumentFilter( filterBuilder: (label) => DocumentFilter(
tags: TagsQuery.ids(include: [label.id!]), tags:
TagsQuery.ids(include: [label.id!]),
), ),
canEdit: LocalUserAccount.current.paperlessUser.hasPermission( canEdit: LocalUserAccount
PermissionAction.change, PermissionTarget.tag), .current.paperlessUser
canAddNew: LocalUserAccount.current.paperlessUser
.hasPermission( .hasPermission(
PermissionAction.add, PermissionTarget.tag), PermissionAction.change,
PermissionTarget.tag),
canAddNew: LocalUserAccount
.current.paperlessUser
.hasPermission(PermissionAction.add,
PermissionTarget.tag),
onEdit: _openEditTagPage, onEdit: _openEditTagPage,
leadingBuilder: (t) => CircleAvatar( leadingBuilder: (t) => CircleAvatar(
backgroundColor: t.color, backgroundColor: t.color,
@@ -218,8 +268,10 @@ class _LabelsPageState extends State<LabelsPage> with SingleTickerProviderStateM
) )
: null, : null,
), ),
emptyStateActionButtonLabel: S.of(context)!.addNewTag, emptyStateActionButtonLabel:
emptyStateDescription: S.of(context)!.noTagsSetUp, S.of(context)!.addNewTag,
emptyStateDescription:
S.of(context)!.noTagsSetUp,
onAddNew: _openAddTagPage, onAddNew: _openAddTagPage,
), ),
], ],
@@ -230,22 +282,30 @@ class _LabelsPageState extends State<LabelsPage> with SingleTickerProviderStateM
builder: (context) { builder: (context) {
return CustomScrollView( return CustomScrollView(
slivers: [ slivers: [
SliverOverlapInjector(handle: searchBarHandle), SliverOverlapInjector(
handle: searchBarHandle),
SliverOverlapInjector(handle: tabBarHandle), SliverOverlapInjector(handle: tabBarHandle),
LabelTabView<StoragePath>( LabelTabView<StoragePath>(
labels: state.storagePaths, labels: state.storagePaths,
onEdit: _openEditStoragePathPage, onEdit: _openEditStoragePathPage,
filterBuilder: (label) => DocumentFilter( filterBuilder: (label) => DocumentFilter(
storagePath: IdQueryParameter.fromId(label.id!), storagePath:
IdQueryParameter.fromId(label.id!),
), ),
canEdit: LocalUserAccount.current.paperlessUser.hasPermission( canEdit: LocalUserAccount
PermissionAction.change, PermissionTarget.storagePath), .current.paperlessUser
canAddNew: LocalUserAccount.current.paperlessUser
.hasPermission( .hasPermission(
PermissionAction.add, PermissionTarget.storagePath), PermissionAction.change,
PermissionTarget.storagePath),
canAddNew: LocalUserAccount
.current.paperlessUser
.hasPermission(PermissionAction.add,
PermissionTarget.storagePath),
contentBuilder: (path) => Text(path.path), contentBuilder: (path) => Text(path.path),
emptyStateActionButtonLabel: S.of(context)!.addNewStoragePath, emptyStateActionButtonLabel:
emptyStateDescription: S.of(context)!.noStoragePathsSetUp, S.of(context)!.addNewStoragePath,
emptyStateDescription:
S.of(context)!.noStoragePathsSetUp,
onAddNew: _openAddStoragePathPage, onAddNew: _openAddStoragePathPage,
), ),
], ],
@@ -331,8 +391,8 @@ class _LabelsPageState extends State<LabelsPage> with SingleTickerProviderStateM
Provider.value(value: context.read<LabelRepository>()), Provider.value(value: context.read<LabelRepository>()),
Provider.value(value: context.read<ApiVersion>()) Provider.value(value: context.read<ApiVersion>())
], ],
child: page child: page,
) ),
); );
} }
} }

View File

@@ -244,7 +244,7 @@ class AuthenticationCubit extends Cubit<AuthenticationState> {
final userStateBox = Hive.box<LocalUserAppState>(HiveBoxes.localUserAppState); final userStateBox = Hive.box<LocalUserAppState>(HiveBoxes.localUserAppState);
if (userAccountBox.containsKey(localUserId)) { if (userAccountBox.containsKey(localUserId)) {
throw Exception("User with id $localUserId already exists!"); throw Exception("User already exists!");
} }
final apiVersion = await _getApiVersion(sessionManager.client); final apiVersion = await _getApiVersion(sessionManager.client);
@@ -282,6 +282,10 @@ class AuthenticationCubit extends Cubit<AuthenticationState> {
), ),
); );
}); });
final hostsBox = Hive.box<String>(HiveBoxes.hosts);
if (!hostsBox.values.contains(serverUrl)) {
await hostsBox.add(serverUrl);
}
return serverUser.id; return serverUser.id;
} }

View File

@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart';
@@ -14,12 +16,13 @@ import 'package:paperless_mobile/features/login/view/widgets/form_fields/user_cr
import 'package:paperless_mobile/features/login/view/widgets/login_pages/server_connection_page.dart'; import 'package:paperless_mobile/features/login/view/widgets/login_pages/server_connection_page.dart';
import 'package:paperless_mobile/features/users/view/widgets/user_account_list_tile.dart'; import 'package:paperless_mobile/features/users/view/widgets/user_account_list_tile.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart'; import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
import 'package:paperless_mobile/helpers/message_helpers.dart';
import 'widgets/login_pages/server_login_page.dart'; import 'widgets/login_pages/server_login_page.dart';
import 'widgets/never_scrollable_scroll_behavior.dart'; import 'widgets/never_scrollable_scroll_behavior.dart';
class LoginPage extends StatefulWidget { class LoginPage extends StatefulWidget {
final void Function( final FutureOr<void> Function(
BuildContext context, BuildContext context,
String username, String username,
String password, String password,
@@ -131,13 +134,17 @@ class _LoginPageState extends State<LoginPage> {
); );
} }
final credentials = form[UserCredentialsFormField.fkCredentials] as LoginFormCredentials; final credentials = form[UserCredentialsFormField.fkCredentials] as LoginFormCredentials;
widget.onSubmit( try {
await widget.onSubmit(
context, context,
credentials.username!, credentials.username!,
credentials.password!, credentials.password!,
form[ServerAddressFormField.fkServerAddress], form[ServerAddressFormField.fkServerAddress],
clientCert, clientCert,
); );
} on Exception catch (error) {
showGenericError(context, error);
}
} }
} }
} }

View File

@@ -1,16 +1,18 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:hive_flutter/adapters.dart';
import 'package:paperless_mobile/core/config/hive/hive_config.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart'; import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
class ServerAddressFormField extends StatefulWidget { class ServerAddressFormField extends StatefulWidget {
static const String fkServerAddress = "serverAddress"; static const String fkServerAddress = "serverAddress";
final void Function(String? address) onDone; final void Function(String? address) onSubmit;
const ServerAddressFormField({ const ServerAddressFormField({
Key? key, Key? key,
required this.onDone, required this.onSubmit,
}) : super(key: key); }) : super(key: key);
@override @override
@@ -24,21 +26,18 @@ class _ServerAddressFormFieldState extends State<ServerAddressFormField> {
void initState() { void initState() {
super.initState(); super.initState();
_textEditingController.addListener(() { _textEditingController.addListener(() {
if (_textEditingController.text.isNotEmpty) {
setState(() { setState(() {
_canClear = true; _canClear = _textEditingController.text.isNotEmpty;
}); });
}
}); });
} }
final _focusNode = FocusNode();
final _textEditingController = TextEditingController(); final _textEditingController = TextEditingController();
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return FormBuilderTextField( return FormBuilderField<String>(
key: const ValueKey('login-server-address'),
controller: _textEditingController,
name: ServerAddressFormField.fkServerAddress, name: ServerAddressFormField.fkServerAddress,
autovalidateMode: AutovalidateMode.onUserInteraction, autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (value) { validator: (value) {
@@ -50,6 +49,28 @@ class _ServerAddressFormFieldState extends State<ServerAddressFormField> {
} }
return null; return null;
}, },
builder: (field) {
return RawAutocomplete<String>(
focusNode: _focusNode,
textEditingController: _textEditingController,
optionsViewBuilder: (context, onSelected, options) {
return _AutocompleteOptions(
onSelected: onSelected,
options: options,
maxOptionsHeight: 200.0,
);
},
key: const ValueKey('login-server-address'),
optionsBuilder: (textEditingValue) {
return Hive.box<String>(HiveBoxes.hosts)
.values
.where((element) => element.contains(textEditingValue.text));
},
onSelected: (option) => _formatInput(),
fieldViewBuilder: (context, textEditingController, focusNode, onFieldSubmitted) {
return TextField(
controller: textEditingController,
focusNode: focusNode,
decoration: InputDecoration( decoration: InputDecoration(
hintText: "http://192.168.1.50:8000", hintText: "http://192.168.1.50:8000",
labelText: S.of(context)!.serverAddress, labelText: S.of(context)!.serverAddress,
@@ -58,12 +79,30 @@ class _ServerAddressFormFieldState extends State<ServerAddressFormField> {
icon: const Icon(Icons.clear), icon: const Icon(Icons.clear),
color: Theme.of(context).iconTheme.color, color: Theme.of(context).iconTheme.color,
onPressed: () { onPressed: () {
_textEditingController.clear(); textEditingController.clear();
field.didChange(textEditingController.text);
widget.onSubmit(textEditingController.text);
}, },
) )
: null, : null,
), ),
onSubmitted: (_) => _formatInput(), autofocus: true,
onSubmitted: (_) {
onFieldSubmitted();
_formatInput();
},
keyboardType: TextInputType.url,
onChanged: (value) {
field.didChange(value);
},
onEditingComplete: () {
field.didChange(_textEditingController.text);
_focusNode.unfocus();
},
);
},
);
},
); );
} }
@@ -71,6 +110,59 @@ class _ServerAddressFormFieldState extends State<ServerAddressFormField> {
String address = _textEditingController.text.trim(); String address = _textEditingController.text.trim();
address = address.replaceAll(RegExp(r'^\/+|\/+$'), ''); address = address.replaceAll(RegExp(r'^\/+|\/+$'), '');
_textEditingController.text = address; _textEditingController.text = address;
widget.onDone(address); widget.onSubmit(address);
}
}
/// Taken from [Autocomplete]
class _AutocompleteOptions extends StatelessWidget {
const _AutocompleteOptions({
required this.onSelected,
required this.options,
required this.maxOptionsHeight,
});
final AutocompleteOnSelected<String> onSelected;
final Iterable<String> options;
final double maxOptionsHeight;
@override
Widget build(BuildContext context) {
return Align(
alignment: Alignment.topLeft,
child: Material(
elevation: 4.0,
child: ConstrainedBox(
constraints: BoxConstraints(maxHeight: maxOptionsHeight),
child: ListView.builder(
padding: EdgeInsets.zero,
shrinkWrap: true,
itemCount: options.length,
itemBuilder: (BuildContext context, int index) {
final option = options.elementAt(index);
return InkWell(
onTap: () {
onSelected(option);
},
child: Builder(builder: (BuildContext context) {
final bool highlight = AutocompleteHighlightedOption.of(context) == index;
if (highlight) {
SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) {
Scrollable.ensureVisible(context, alignment: 0.5);
});
}
return Container(
color: highlight ? Theme.of(context).focusColor : null,
padding: const EdgeInsets.all(16.0),
child: Text(option),
);
}),
);
},
),
),
),
);
} }
} }

View File

@@ -48,7 +48,7 @@ class _ServerConnectionPageState extends State<ServerConnectionPage> {
child: Column( child: Column(
children: [ children: [
ServerAddressFormField( ServerAddressFormField(
onDone: (address) { onSubmit: (address) {
_updateReachability(address); _updateReachability(address);
}, },
).padded(), ).padded(),

View File

@@ -9,7 +9,8 @@ import 'paged_documents_state.dart';
/// Mixin which can be used on cubits that handle documents. /// Mixin which can be used on cubits that handle documents.
/// This implements all paging and filtering logic. /// This implements all paging and filtering logic.
/// ///
mixin DocumentPagingBlocMixin<State extends DocumentPagingState> on BlocBase<State> { mixin DocumentPagingBlocMixin<State extends DocumentPagingState>
on BlocBase<State> {
PaperlessDocumentsApi get api; PaperlessDocumentsApi get api;
DocumentChangedNotifier get notifier; DocumentChangedNotifier get notifier;
@@ -74,7 +75,7 @@ mixin DocumentPagingBlocMixin<State extends DocumentPagingState> on BlocBase<Sta
} }
Future<void> reload() async { Future<void> reload() async {
emit(state.copyWithPaged(isLoading: true)); // emit(state.copyWithPaged(isLoading: true));
final filter = state.filter.copyWith(page: 1); final filter = state.filter.copyWith(page: 1);
try { try {
final result = await api.findAll(filter); final result = await api.findAll(filter);
@@ -128,7 +129,8 @@ mixin DocumentPagingBlocMixin<State extends DocumentPagingState> on BlocBase<Sta
if (index != -1) { if (index != -1) {
final foundPage = state.value[index]; final foundPage = state.value[index];
final replacementPage = foundPage.copyWith( final replacementPage = foundPage.copyWith(
results: foundPage.results..removeWhere((element) => element.id == document.id), results: foundPage.results
..removeWhere((element) => element.id == document.id),
); );
final newCount = foundPage.count - 1; final newCount = foundPage.count - 1;
emit( emit(
@@ -136,7 +138,8 @@ mixin DocumentPagingBlocMixin<State extends DocumentPagingState> on BlocBase<Sta
value: state.value value: state.value
.mapIndexed( .mapIndexed(
(currIndex, element) => (currIndex, element) =>
(currIndex == index ? replacementPage : element).copyWith(count: newCount), (currIndex == index ? replacementPage : element)
.copyWith(count: newCount),
) )
.toList(), .toList(),
), ),
@@ -159,11 +162,14 @@ mixin DocumentPagingBlocMixin<State extends DocumentPagingState> on BlocBase<Sta
if (pageIndex != -1) { if (pageIndex != -1) {
final foundPage = state.value[pageIndex]; final foundPage = state.value[pageIndex];
final replacementPage = foundPage.copyWith( final replacementPage = foundPage.copyWith(
results: foundPage.results.map((doc) => doc.id == document.id ? document : doc).toList(), results: foundPage.results
.map((doc) => doc.id == document.id ? document : doc)
.toList(),
); );
final newState = state.copyWithPaged( final newState = state.copyWithPaged(
value: state.value value: state.value
.mapIndexed((currIndex, element) => currIndex == pageIndex ? replacementPage : element) .mapIndexed((currIndex, element) =>
currIndex == pageIndex ? replacementPage : element)
.toList(), .toList(),
); );
emit(newState); emit(newState);

View File

@@ -64,6 +64,7 @@ Future<void> _initHive() async {
// await getApplicationDocumentsDirectory().then((value) => value.deleteSync(recursive: true)); // await getApplicationDocumentsDirectory().then((value) => value.deleteSync(recursive: true));
await Hive.openBox<LocalUserAccount>(HiveBoxes.localUserAccount); await Hive.openBox<LocalUserAccount>(HiveBoxes.localUserAccount);
await Hive.openBox<LocalUserAppState>(HiveBoxes.localUserAppState); await Hive.openBox<LocalUserAppState>(HiveBoxes.localUserAppState);
await Hive.openBox<String>(HiveBoxes.hosts);
final globalSettingsBox = await Hive.openBox<GlobalSettings>(HiveBoxes.globalSettings); final globalSettingsBox = await Hive.openBox<GlobalSettings>(HiveBoxes.globalSettings);
if (!globalSettingsBox.hasValue) { if (!globalSettingsBox.hasValue) {

View File

@@ -115,7 +115,9 @@ class DocumentFilter extends Equatable {
final queryParams = groupBy(params, (e) => e.key).map( final queryParams = groupBy(params, (e) => e.key).map(
(key, entries) => MapEntry( (key, entries) => MapEntry(
key, key,
entries.length == 1 ? entries.first.value : entries.map((e) => e.value).join(","), entries.length == 1
? entries.first.value
: entries.map((e) => e.value).join(","),
), ),
); );
return queryParams; return queryParams;
@@ -156,7 +158,8 @@ class DocumentFilter extends Equatable {
modified: modified ?? this.modified, modified: modified ?? this.modified,
moreLike: moreLike != null ? moreLike.call() : this.moreLike, moreLike: moreLike != null ? moreLike.call() : this.moreLike,
); );
if (query?.queryType != QueryType.extended && newFilter.forceExtendedQuery) { if (query?.queryType != QueryType.extended &&
newFilter.forceExtendedQuery) {
//Prevents infinite recursion //Prevents infinite recursion
return newFilter.copyWith( return newFilter.copyWith(
query: newFilter.query.copyWith(queryType: QueryType.extended), query: newFilter.query.copyWith(queryType: QueryType.extended),
@@ -212,7 +215,8 @@ class DocumentFilter extends Equatable {
query, query,
]; ];
factory DocumentFilter.fromJson(Map<String, dynamic> json) => _$DocumentFilterFromJson(json); factory DocumentFilter.fromJson(Map<String, dynamic> json) =>
_$DocumentFilterFromJson(json);
Map<String, dynamic> toJson() => _$DocumentFilterToJson(this); Map<String, dynamic> toJson() => _$DocumentFilterToJson(this);
} }

View File

@@ -0,0 +1,44 @@
# Uncomment this line to define a global platform for your project
# platform :ios, '11.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
project 'Runner', {
'Debug' => :debug,
'Profile' => :release,
'Release' => :release,
}
def flutter_root
generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
unless File.exist?(generated_xcode_build_settings_path)
raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
end
File.foreach(generated_xcode_build_settings_path) do |line|
matches = line.match(/FLUTTER_ROOT\=(.*)/)
return matches[1].strip if matches
end
raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end
require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
flutter_ios_podfile_setup
target 'Runner' do
use_frameworks!
use_modular_headers!
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
target 'RunnerTests' do
inherit! :search_paths
end
end
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
end
end