Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Sort authors by date added and narrators by number of books

Barnabas90f60ff7b219
diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dart
index 67c363da..fb0adfcb 100644
--- a/lib/screens/library_screen.dart
+++ b/lib/screens/library_screen.dart
@@ -460,6 +460,9 @@ class LibraryScreenState extends State<LibraryScreen>
// ── Narrators tab state ──
List<String> _narrators = [];
+ // Book count per narrator, from the narrators endpoint; empty until it
+ // answers. Drives the "number of books" sort and the count on each row.
+ Map<String, int> _narratorCounts = {};
bool _isLoadingNarrators = false;
bool _narratorsLoaded = false;
LibrarySort _narratorSort = LibrarySort.alphabetical;
@@ -646,6 +649,7 @@ class LibraryScreenState extends State<LibraryScreen>
_totalAuthors = 0;
_authorsGen++;
_narrators.clear();
+ _narratorCounts = {};
_narratorsLoaded = false;
_isLoadingNarrators = false;
_listsFailed = false;
@@ -1575,8 +1579,11 @@ class LibraryScreenState extends State<LibraryScreen>
// ══════════════════════════════════════════════════════════════
// AUTHORS TAB - Load all authors
// ══════════════════════════════════════════════════════════════
- String get _authorServerSort =>
- _authorSort == LibrarySort.totalDuration ? 'numBooks' : 'name';
+ String get _authorServerSort => switch (_authorSort) {
+ LibrarySort.totalDuration => 'numBooks',
+ LibrarySort.recentlyAdded => 'addedAt',
+ _ => 'name',
+ };
List<Map<String, dynamic>> _authorPageResults(Map<String, dynamic>? result) =>
((result?['results'] ?? result?['authors']) as List<dynamic>? ?? const [])
@@ -1649,6 +1656,13 @@ class LibraryScreenState extends State<LibraryScreen>
? aCount.compareTo(bCount)
: bCount.compareTo(aCount);
}
+ if (_authorSort == LibrarySort.recentlyAdded) {
+ final aAdded = (a['addedAt'] as num?)?.toInt() ?? 0;
+ final bAdded = (b['addedAt'] as num?)?.toInt() ?? 0;
+ return _authorSortAsc
+ ? aAdded.compareTo(bAdded)
+ : bAdded.compareTo(aAdded);
+ }
final aName = (a['name'] as String? ?? '').toLowerCase();
final bName = (b['name'] as String? ?? '').toLowerCase();
return _authorSortAsc ? aName.compareTo(bName) : bName.compareTo(aName);
@@ -1670,21 +1684,39 @@ class LibraryScreenState extends State<LibraryScreen>
return;
}
- final narrators = await api.getLibraryNarrators(lib.selectedLibraryId!);
- if (mounted) {
- setState(() {
- _narrators = narrators;
- _sortNarrators();
- _isLoadingNarrators = false;
- _narratorsLoaded = true;
- });
- }
+ final libId = lib.selectedLibraryId!;
+ final narrators = await api.getLibraryNarrators(libId);
+ if (!mounted) return;
+ setState(() {
+ _narrators = narrators;
+ _sortNarrators();
+ _isLoadingNarrators = false;
+ _narratorsLoaded = true;
+ });
+ // Book counts come from a separate endpoint that walks every book with a
+ // narrator, so they land after the names and re-sort the list then.
+ final counts = await api.getLibraryNarratorCounts(libId);
+ if (!mounted || counts.isEmpty || lib.selectedLibraryId != libId) return;
+ setState(() {
+ _narratorCounts = counts;
+ _sortNarrators();
+ });
}
void _sortNarrators() {
_narrators.sort((a, b) {
final aLower = a.toLowerCase();
final bLower = b.toLowerCase();
+ if (_narratorSort == LibrarySort.totalDuration) {
+ final aCount = _narratorCounts[a] ?? 0;
+ final bCount = _narratorCounts[b] ?? 0;
+ if (aCount != bCount) {
+ return _narratorSortAsc
+ ? aCount.compareTo(bCount)
+ : bCount.compareTo(aCount);
+ }
+ return aLower.compareTo(bLower);
+ }
return _narratorSortAsc
? aLower.compareTo(bLower)
: bLower.compareTo(aLower);
@@ -1816,7 +1848,7 @@ class LibraryScreenState extends State<LibraryScreen>
} else {
setState(() {
_narratorSort = newSort;
- _narratorSortAsc = true;
+ _narratorSortAsc = newSort == LibrarySort.alphabetical;
});
}
PlayerSettings.setNarratorSort(_narratorSort.name);
@@ -3768,6 +3800,7 @@ class LibraryScreenState extends State<LibraryScreen>
Future<void> _refreshNarrators() async {
setState(() {
_narrators.clear();
+ _narratorCounts = {};
_narratorsLoaded = false;
_isLoadingNarrators = false;
});
@@ -3777,6 +3810,7 @@ class LibraryScreenState extends State<LibraryScreen>
Widget _buildNarratorsGrid(Widget headerSliver) {
return LibraryNarratorsTab(
narrators: _narrators,
+ narratorCounts: _narratorCounts,
isLoading: _isLoadingNarrators,
loaded: _narratorsLoaded,
onRefresh: _refreshNarrators,
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index a3f736ef..aac9f6cc 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -1522,6 +1522,35 @@ class ApiService {
return [];
}
+ /// Book count per narrator name. The narrators endpoint walks every book
+ /// with a narrator server-side, so it is slower than filterdata; callers
+ /// fetch it after the names and treat an empty map as "not available".
+ Future<Map<String, int>> getLibraryNarratorCounts(String libraryId) async {
+ try {
+ final response = await _authGet(
+ Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/narrators'),
+ timeout: const Duration(seconds: 30),
+ );
+ if (response.statusCode == 200) {
+ final data = jsonDecode(response.body) as Map<String, dynamic>;
+ final counts = <String, int>{};
+ for (final n in data['narrators'] as List<dynamic>? ?? const []) {
+ if (n is! Map<String, dynamic>) continue;
+ final name = n['name'] as String?;
+ final count = (n['numBooks'] as num?)?.toInt();
+ if (name != null && name.isNotEmpty && count != null) {
+ counts[name] = count;
+ }
+ }
+ return counts;
+ }
+ debugPrint('[API] getLibraryNarratorCounts: HTTP ${response.statusCode}');
+ } catch (e) {
+ debugPrint('[API] getLibraryNarratorCounts failed: $e');
+ }
+ return const {};
+ }
+
/// Get books narrated by a specific person.
/// Filter format: narrators.<base64(name)>
Future<List<dynamic>> getBooksByNarrator(
diff --git a/lib/widgets/library_narrators_tab.dart b/lib/widgets/library_narrators_tab.dart
index 80dc7a57..9e5d7e30 100644
--- a/lib/widgets/library_narrators_tab.dart
+++ b/lib/widgets/library_narrators_tab.dart
@@ -5,6 +5,10 @@ import 'narrator_books_sheet.dart';
class LibraryNarratorsTab extends StatelessWidget {
final List<String> narrators;
+
+ /// Book count per narrator, when the server has answered; rows without an
+ /// entry show no count.
+ final Map<String, int> narratorCounts;
final bool isLoading;
final bool loaded;
final Future<void> Function() onRefresh;
@@ -14,6 +18,7 @@ class LibraryNarratorsTab extends StatelessWidget {
const LibraryNarratorsTab({
super.key,
required this.narrators,
+ this.narratorCounts = const {},
required this.isLoading,
required this.loaded,
required this.onRefresh,
@@ -103,6 +108,15 @@ class LibraryNarratorsTab extends StatelessWidget {
overflow: TextOverflow.ellipsis,
),
),
+ if (narratorCounts[name] case final count?) ...[
+ Text(
+ l.seriesBooksBookCount(count),
+ style: tt.bodySmall?.copyWith(
+ color: cs.onSurfaceVariant.withValues(alpha: 0.7),
+ ),
+ ),
+ const SizedBox(width: 8),
+ ],
Icon(Icons.chevron_right_rounded,
size: 18, color: cs.onSurfaceVariant.withValues(alpha: 0.4)),
],
diff --git a/lib/widgets/library_sort_filter_sheet.dart b/lib/widgets/library_sort_filter_sheet.dart
index 8a29e83b..def23792 100644
--- a/lib/widgets/library_sort_filter_sheet.dart
+++ b/lib/widgets/library_sort_filter_sheet.dart
@@ -202,8 +202,8 @@ class _SortFilterSheetState extends State<SortFilterSheet> with SingleTickerProv
if (_showFilterTab && _tabCtrl.index == 1) return 280;
return widget.onUpcomingReleases != null ? 330 : 230;
}
- if (widget.libraryTab == LibraryTab.authors) return 180;
- if (widget.libraryTab == LibraryTab.narrators) return 130;
+ if (widget.libraryTab == LibraryTab.authors) return 230;
+ if (widget.libraryTab == LibraryTab.narrators) return 180;
if (widget.libraryTab == LibraryTab.lists) return 230;
if (_genreExpanded ||
_tagExpanded ||
@@ -324,11 +324,13 @@ class _SortFilterSheetState extends State<SortFilterSheet> with SingleTickerProv
case LibraryTab.authors:
return [
(LibrarySort.alphabetical, l.name, Icons.sort_by_alpha_rounded),
+ (LibrarySort.recentlyAdded, l.dateAdded, Icons.schedule_rounded),
(LibrarySort.totalDuration, l.numberOfBooks, Icons.auto_stories_rounded),
];
case LibraryTab.narrators:
return [
(LibrarySort.alphabetical, l.name, Icons.sort_by_alpha_rounded),
+ (LibrarySort.totalDuration, l.numberOfBooks, Icons.auto_stories_rounded),
];
case LibraryTab.lists:
return [