Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add Library/Series/Authors tab navigation to library screen

Nathan Poulsona7c5d5237ba1
diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dart
index 08e5a85a..cc5d5049 100644
--- a/lib/screens/library_screen.dart
+++ b/lib/screens/library_screen.dart
@@ -14,7 +14,7 @@ import '../widgets/library_search_results.dart';
import '../widgets/library_sort_filter_sheet.dart';
// ─── Sort modes ──────────────────────────────────────────────
-enum LibrarySort { recentlyAdded, alphabetical, authorName, publishedYear, duration, random }
+enum LibrarySort { recentlyAdded, alphabetical, authorName, publishedYear, duration, random, totalDuration }
// ─── Filter modes ────────────────────────────────────────────
enum LibraryFilter { none, inProgress, finished, notStarted, downloaded, inASeries, hasEbook, genre }
@@ -26,7 +26,7 @@ class LibraryScreen extends StatefulWidget {
State<LibraryScreen> createState() => LibraryScreenState();
}
-class LibraryScreenState extends State<LibraryScreen> {
+class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMixin {
// ── Search state ──
final _searchController = TextEditingController();
final _focusNode = FocusNode();
@@ -49,14 +49,18 @@ class LibraryScreenState extends State<LibraryScreen> {
bool _hasSearched = false;
bool get _isInSearchMode => _searchController.text.trim().isNotEmpty;
- // ── Browse state ──
+ // ── Tab state ──
+ TabController? _tabController;
+ int _currentTab = 0;
+
+ // ── Browse state (Library tab) ──
+ bool _collapseSeries = false;
LibrarySort _sort = LibrarySort.recentlyAdded;
bool _sortAsc = false; // false = desc (newest/longest first), true = asc
LibraryFilter _filter = LibraryFilter.none;
String? _genreFilter;
List<String> _availableGenres = [];
bool _hideEbookOnly = false;
- bool _collapseSeries = false;
final List<Map<String, dynamic>> _items = [];
bool _isLoadingPage = false;
bool _hasMore = true;
@@ -68,6 +72,24 @@ class LibraryScreenState extends State<LibraryScreen> {
final _scrollController = ScrollController();
+ // ── Series tab state ──
+ final List<Map<String, dynamic>> _seriesItems = [];
+ bool _isLoadingSeriesPage = false;
+ bool _hasMoreSeries = true;
+ int _seriesPage = 0;
+ int _totalSeries = 0;
+ LibrarySort _seriesSort = LibrarySort.alphabetical;
+ bool _seriesSortAsc = true;
+ final _seriesScrollController = ScrollController();
+
+ // ── Authors tab state ──
+ List<Map<String, dynamic>> _authors = [];
+ bool _isLoadingAuthors = false;
+ bool _authorsLoaded = false;
+ LibrarySort _authorSort = LibrarySort.alphabetical;
+ bool _authorSortAsc = true;
+ final _authorsScrollController = ScrollController();
+
/// Called externally (e.g. from AppShell) to focus the search field.
void requestSearchFocus() {
_focusNode.requestFocus();
@@ -79,30 +101,80 @@ class LibraryScreenState extends State<LibraryScreen> {
void initState() {
super.initState();
_scrollController.addListener(_onScroll);
+ _seriesScrollController.addListener(_onSeriesScroll);
// Load initial page once the library is ready
WidgetsBinding.instance.addPostFrameCallback((_) {
+ _initTabController();
_tryInitialLoad();
});
}
+ void _initTabController() {
+ final lib = context.read<LibraryProvider>();
+ if (!lib.isPodcastLibrary) {
+ _tabController = TabController(length: 3, vsync: this);
+ _tabController!.addListener(_onTabChanged);
+ }
+ }
+
+ void _onTabChanged() {
+ if (_tabController == null || _tabController!.indexIsChanging) return;
+ final newTab = _tabController!.index;
+ if (newTab == _currentTab) return;
+ setState(() => _currentTab = newTab);
+ // Lazy load data for the tab
+ if (newTab == 1 && _seriesItems.isEmpty && !_isLoadingSeriesPage) {
+ _loadSeriesPage();
+ } else if (newTab == 2 && !_authorsLoaded && !_isLoadingAuthors) {
+ _loadAuthors();
+ }
+ }
+
void _onLibraryProviderChanged() {
final lib = context.read<LibraryProvider>();
if (lib.selectedLibraryId != _lastLibraryId && lib.selectedLibraryId != null) {
_lastLibraryId = lib.selectedLibraryId;
_loadGeneration++;
+
+ // Rebuild tab controller if library type changed
+ final needsTabs = !lib.isPodcastLibrary;
+ final hasTabs = _tabController != null;
+ if (needsTabs != hasTabs) {
+ _tabController?.removeListener(_onTabChanged);
+ _tabController?.dispose();
+ if (needsTabs) {
+ _tabController = TabController(length: 3, vsync: this);
+ _tabController!.addListener(_onTabChanged);
+ } else {
+ _tabController = null;
+ }
+ _currentTab = 0;
+ }
+
setState(() {
_items.clear();
_page = 0;
_hasMore = true;
_isLoadingPage = false;
_availableGenres = [];
- // Reset filter on library switch — genre filters don't carry across libraries
+ // Reset filter on library switch
_filter = LibraryFilter.none;
_genreFilter = null;
+ // Clear series and author data
+ _seriesItems.clear();
+ _seriesPage = 0;
+ _hasMoreSeries = true;
+ _isLoadingSeriesPage = false;
+ _totalSeries = 0;
+ _authors.clear();
+ _authorsLoaded = false;
+ _isLoadingAuthors = false;
});
PlayerSettings.setLibraryFilter('none');
PlayerSettings.setLibraryGenreFilter(null);
if (_scrollController.hasClients) _scrollController.jumpTo(0);
+ if (_seriesScrollController.hasClients) _seriesScrollController.jumpTo(0);
+ if (_authorsScrollController.hasClients) _authorsScrollController.jumpTo(0);
_loadPage();
_loadGenres();
}
@@ -136,12 +208,20 @@ class LibraryScreenState extends State<LibraryScreen> {
PlayerSettings.getLibrarySortAsc(),
PlayerSettings.getLibraryFilter(),
PlayerSettings.getLibraryGenreFilter(),
+ PlayerSettings.getSeriesSort(),
+ PlayerSettings.getSeriesSortAsc(),
+ PlayerSettings.getAuthorSort(),
+ PlayerSettings.getAuthorSortAsc(),
]);
if (!mounted) return;
final sortName = results[0] as String;
final sortAsc = results[1] as bool;
final filterName = results[2] as String;
final genreFilter = results[3] as String;
+ final seriesSortName = results[4] as String;
+ final seriesSortAsc = results[5] as bool;
+ final authorSortName = results[6] as String;
+ final authorSortAsc = results[7] as bool;
setState(() {
_sort = LibrarySort.values.firstWhere(
(s) => s.name == sortName,
@@ -154,6 +234,16 @@ class LibraryScreenState extends State<LibraryScreen> {
orElse: () => LibraryFilter.none,
);
_genreFilter = genreFilter.isNotEmpty ? genreFilter : null;
+ _seriesSort = LibrarySort.values.firstWhere(
+ (s) => s.name == seriesSortName,
+ orElse: () => LibrarySort.alphabetical,
+ );
+ _seriesSortAsc = seriesSortAsc;
+ _authorSort = LibrarySort.values.firstWhere(
+ (s) => s.name == authorSortName,
+ orElse: () => LibrarySort.alphabetical,
+ );
+ _authorSortAsc = authorSortAsc;
});
}
@@ -210,6 +300,10 @@ class LibraryScreenState extends State<LibraryScreen> {
_searchController.dispose();
_focusNode.dispose();
_scrollController.dispose();
+ _seriesScrollController.dispose();
+ _authorsScrollController.dispose();
+ _tabController?.removeListener(_onTabChanged);
+ _tabController?.dispose();
PlayerSettings.settingsChanged.removeListener(_onSettingsChanged);
try {
final lib = context.read<LibraryProvider>();
@@ -228,7 +322,16 @@ class LibraryScreenState extends State<LibraryScreen> {
}
}
- // ── Load a page of items ──
+ void _onSeriesScroll() {
+ if (_seriesScrollController.position.pixels >=
+ _seriesScrollController.position.maxScrollExtent - 400) {
+ _loadSeriesPage();
+ }
+ }
+
+ // ══════════════════════════════════════════════════════════════
+ // LIBRARY TAB - Load a page of items
+ // ══════════════════════════════════════════════════════════════
Future<void> _loadPage() async {
if (_isLoadingPage || !_hasMore) return;
setState(() => _isLoadingPage = true);
@@ -254,6 +357,7 @@ class LibraryScreenState extends State<LibraryScreen> {
case LibrarySort.publishedYear:
sort = 'media.metadata.publishedYear'; desc = _sortAsc ? 0 : 1; break;
case LibrarySort.duration:
+ case LibrarySort.totalDuration:
sort = 'media.duration'; desc = _sortAsc ? 0 : 1; break;
case LibrarySort.random:
sort = 'addedAt'; desc = 1; break;
@@ -274,8 +378,7 @@ class LibraryScreenState extends State<LibraryScreen> {
// Downloaded filter is client-side — handled after loading
final useClientFilter = _filter == LibraryFilter.downloaded;
- final seriesOnlyFilter = _filter == LibraryFilter.inASeries;
- final fetchAll = _sort == LibrarySort.random || useClientFilter || seriesOnlyFilter;
+ final fetchAll = _sort == LibrarySort.random || useClientFilter;
final limit = fetchAll ? 1000 : _pageSize;
final result = await api.getLibraryItems(
@@ -285,7 +388,7 @@ class LibraryScreenState extends State<LibraryScreen> {
sort: sort,
desc: desc,
filter: filter,
- collapseSeries: (_collapseSeries || seriesOnlyFilter) && !useClientFilter && !lib.isPodcastLibrary,
+ collapseSeries: _collapseSeries && !useClientFilter && !lib.isPodcastLibrary,
);
if (result != null && mounted && gen == _loadGeneration) {
@@ -304,9 +407,6 @@ class LibraryScreenState extends State<LibraryScreen> {
final id = r['id'] as String? ?? '';
if (!DownloadService().isDownloaded(id)) continue;
}
- if (seriesOnlyFilter) {
- if (r['collapsedSeries'] == null) continue;
- }
if (_hideEbookOnly && PlayerSettings.isEbookOnly(r)) continue;
_items.add(r);
}
@@ -314,7 +414,7 @@ class LibraryScreenState extends State<LibraryScreen> {
if (_sort == LibrarySort.random) {
_items.shuffle(Random(_randomSeed));
_hasMore = false;
- } else if (useClientFilter || seriesOnlyFilter) {
+ } else if (useClientFilter) {
_hasMore = false; // All loaded and filtered at once
} else {
_page++;
@@ -327,8 +427,104 @@ class LibraryScreenState extends State<LibraryScreen> {
}
}
+ // ══════════════════════════════════════════════════════════════
+ // SERIES TAB - Load a page of series
+ // ══════════════════════════════════════════════════════════════
+ Future<void> _loadSeriesPage() async {
+ if (_isLoadingSeriesPage || !_hasMoreSeries) return;
+ setState(() => _isLoadingSeriesPage = true);
+
+ final auth = context.read<AuthProvider>();
+ final lib = context.read<LibraryProvider>();
+ final api = auth.apiService;
+ if (api == null || lib.selectedLibraryId == null) {
+ setState(() => _isLoadingSeriesPage = false);
+ return;
+ }
+
+ String sort;
+ switch (_seriesSort) {
+ case LibrarySort.alphabetical:
+ sort = 'name'; break;
+ case LibrarySort.recentlyAdded:
+ sort = 'addedAt'; break;
+ case LibrarySort.totalDuration:
+ sort = 'numBooks'; break;
+ default:
+ sort = 'name'; break;
+ }
+
+ final result = await api.getLibrarySeries(
+ lib.selectedLibraryId!,
+ page: _seriesPage,
+ limit: 50,
+ sort: sort,
+ desc: _seriesSortAsc ? 0 : 1,
+ );
+
+ if (result != null && mounted) {
+ final results = (result['results'] as List<dynamic>?) ?? [];
+ final total = (result['total'] as int?) ?? 0;
+ setState(() {
+ _totalSeries = total;
+ for (final r in results) {
+ if (r is Map<String, dynamic>) {
+ _seriesItems.add(r);
+ }
+ }
+ _seriesPage++;
+ _hasMoreSeries = _seriesItems.length < total;
+ _isLoadingSeriesPage = false;
+ });
+ } else if (mounted) {
+ setState(() => _isLoadingSeriesPage = false);
+ }
+ }
+
+ // ══════════════════════════════════════════════════════════════
+ // AUTHORS TAB - Load all authors
+ // ══════════════════════════════════════════════════════════════
+ Future<void> _loadAuthors() async {
+ if (_isLoadingAuthors) return;
+ setState(() => _isLoadingAuthors = true);
+
+ final auth = context.read<AuthProvider>();
+ final lib = context.read<LibraryProvider>();
+ final api = auth.apiService;
+ if (api == null || lib.selectedLibraryId == null) {
+ setState(() { _isLoadingAuthors = false; _authorsLoaded = true; });
+ return;
+ }
+
+ final authors = await api.getLibraryAuthors(lib.selectedLibraryId!);
+ if (mounted) {
+ setState(() {
+ _authors = authors;
+ _sortAuthors();
+ _isLoadingAuthors = false;
+ _authorsLoaded = true;
+ });
+ }
+ }
+
+ void _sortAuthors() {
+ _authors.sort((a, b) {
+ if (_authorSort == LibrarySort.totalDuration) {
+ final aCount = a['numBooks'] as int? ?? 0;
+ final bCount = b['numBooks'] as int? ?? 0;
+ return _authorSortAsc ? aCount.compareTo(bCount) : bCount.compareTo(aCount);
+ }
+ final aName = (a['name'] as String? ?? '').toLowerCase();
+ final bName = (b['name'] as String? ?? '').toLowerCase();
+ return _authorSortAsc ? aName.compareTo(bName) : bName.compareTo(aName);
+ });
+ }
+
// ── Change sort and reload ──
void _changeSort(LibrarySort newSort) {
+ if (_currentTab == 1) { _changeSeriesSort(newSort); return; }
+ if (_currentTab == 2) { _changeAuthorSort(newSort); return; }
+
if (newSort == _sort) {
// Tapping the same sort toggles direction (except Random)
if (newSort == LibrarySort.random) return;
@@ -362,6 +558,42 @@ class LibraryScreenState extends State<LibraryScreen> {
_loadPage();
}
+ void _changeSeriesSort(LibrarySort newSort) {
+ if (newSort == _seriesSort) {
+ setState(() { _seriesSortAsc = !_seriesSortAsc; });
+ } else {
+ setState(() {
+ _seriesSort = newSort;
+ _seriesSortAsc = newSort == LibrarySort.alphabetical;
+ });
+ }
+ setState(() {
+ _seriesItems.clear();
+ _seriesPage = 0;
+ _hasMoreSeries = true;
+ _isLoadingSeriesPage = false;
+ });
+ PlayerSettings.setSeriesSort(_seriesSort.name);
+ PlayerSettings.setSeriesSortAsc(_seriesSortAsc);
+ if (_seriesScrollController.hasClients) _seriesScrollController.jumpTo(0);
+ _loadSeriesPage();
+ }
+
+ void _changeAuthorSort(LibrarySort newSort) {
+ if (newSort == _authorSort) {
+ setState(() { _authorSortAsc = !_authorSortAsc; });
+ } else {
+ setState(() {
+ _authorSort = newSort;
+ _authorSortAsc = newSort == LibrarySort.alphabetical;
+ });
+ }
+ PlayerSettings.setAuthorSort(_authorSort.name);
+ PlayerSettings.setAuthorSortAsc(_authorSortAsc);
+ setState(() => _sortAuthors());
+ if (_authorsScrollController.hasClients) _authorsScrollController.jumpTo(0);
+ }
+
// ── Change filter and reload ──
void _changeFilter(LibraryFilter newFilter, {String? genre}) {
final effective = (newFilter == _filter && genre == _genreFilter) ? LibraryFilter.none : newFilter;
@@ -544,15 +776,6 @@ class LibraryScreenState extends State<LibraryScreen> {
);
}
- String get _sortLabel => switch (_sort) {
- LibrarySort.recentlyAdded => 'Date Added',
- LibrarySort.alphabetical => 'Title',
- LibrarySort.authorName => 'Author',
- LibrarySort.publishedYear => 'Year',
- LibrarySort.duration => 'Duration',
- LibrarySort.random => 'Random',
- };
-
String get _filterLabel => switch (_filter) {
LibraryFilter.inProgress => 'In Progress',
LibraryFilter.finished => 'Finished',
@@ -565,32 +788,73 @@ class LibraryScreenState extends State<LibraryScreen> {
};
void _showSortFilterSheet(BuildContext context, ColorScheme cs, TextTheme tt, {int initialTab = 0}) {
+ final LibraryTab tab;
+ final LibrarySort currentSort;
+ final bool currentSortAsc;
+ switch (_currentTab) {
+ case 1:
+ tab = LibraryTab.series;
+ currentSort = _seriesSort;
+ currentSortAsc = _seriesSortAsc;
+ break;
+ case 2:
+ tab = LibraryTab.authors;
+ currentSort = _authorSort;
+ currentSortAsc = _authorSortAsc;
+ break;
+ default:
+ tab = LibraryTab.library;
+ currentSort = _sort;
+ currentSortAsc = _sortAsc;
+ break;
+ }
showModalBottomSheet(
context: context,
isScrollControlled: true,
useSafeArea: true,
backgroundColor: Colors.transparent,
builder: (ctx) => SortFilterSheet(
- currentSort: _sort,
- sortAsc: _sortAsc,
+ currentSort: currentSort,
+ sortAsc: currentSortAsc,
currentFilter: _filter,
genreFilter: _genreFilter,
availableGenres: _availableGenres,
initialTab: initialTab,
cs: cs, tt: tt,
+ libraryTab: tab,
onSortChanged: (sort) { Navigator.pop(ctx); _changeSort(sort); },
onSortDirectionToggled: () {
- setState(() { _sortAsc = !_sortAsc; _items.clear(); _page = 0; _hasMore = true; _isLoadingPage = false; });
- if (_scrollController.hasClients) _scrollController.jumpTo(0);
- _loadPage();
+ if (_currentTab == 1) {
+ setState(() { _seriesSortAsc = !_seriesSortAsc; _seriesItems.clear(); _seriesPage = 0; _hasMoreSeries = true; _isLoadingSeriesPage = false; });
+ PlayerSettings.setSeriesSortAsc(_seriesSortAsc);
+ if (_seriesScrollController.hasClients) _seriesScrollController.jumpTo(0);
+ _loadSeriesPage();
+ } else if (_currentTab == 2) {
+ setState(() { _authorSortAsc = !_authorSortAsc; _sortAuthors(); });
+ PlayerSettings.setAuthorSortAsc(_authorSortAsc);
+ if (_authorsScrollController.hasClients) _authorsScrollController.jumpTo(0);
+ } else {
+ setState(() { _sortAsc = !_sortAsc; _items.clear(); _page = 0; _hasMore = true; _isLoadingPage = false; });
+ if (_scrollController.hasClients) _scrollController.jumpTo(0);
+ _loadPage();
+ }
Navigator.pop(ctx);
},
onFilterChanged: (filter, {String? genre}) { Navigator.pop(ctx); _changeFilter(filter, genre: genre); },
onClearFilter: () { Navigator.pop(ctx); _changeFilter(LibraryFilter.none); },
collapseSeries: _collapseSeries,
onCollapseSeriesChanged: (value) {
- Navigator.pop(ctx);
+ _loadGeneration++;
+ setState(() {
+ _collapseSeries = value;
+ _items.clear();
+ _page = 0;
+ _hasMore = true;
+ _isLoadingPage = false;
+ });
PlayerSettings.setCollapseSeries(value);
+ if (_scrollController.hasClients) _scrollController.jumpTo(0);
+ _loadPage();
},
isPodcastLibrary: context.read<LibraryProvider>().isPodcastLibrary,
),
@@ -605,37 +869,9 @@ class LibraryScreenState extends State<LibraryScreen> {
final allLibraries = lib.libraries;
final hasMultipleLibraries = allLibraries.length > 1;
final libraryName = lib.selectedLibrary?['name'] as String? ?? 'Library';
+ final hasTabs = _tabController != null && !_isInSearchMode;
return Scaffold(
- floatingActionButton: _isInSearchMode ? null : ClipRRect(
- borderRadius: BorderRadius.circular(24),
- child: BackdropFilter(
- filter: ui.ImageFilter.blur(sigmaX: 20, sigmaY: 20),
- child: GestureDetector(
- onTap: () => _showSortFilterSheet(context, cs, tt),
- child: Container(
- padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
- decoration: BoxDecoration(
- color: cs.surface.withValues(alpha: 0.6),
- borderRadius: BorderRadius.circular(24),
- border: Border.all(color: cs.primary.withValues(alpha: 0.25)),
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(_filter != LibraryFilter.none ? Icons.filter_list_rounded : Icons.tune_rounded, size: 16, color: cs.primary),
- const SizedBox(width: 6),
- Text(
- _filter != LibraryFilter.none ? 'Sort & Filter ●' : 'Sort & Filter',
- style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: cs.primary),
- ),
- ],
- ),
- ),
- ),
- ),
- ),
- floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
body: SafeArea(
child: Column(
children: [
@@ -674,7 +910,7 @@ class LibraryScreenState extends State<LibraryScreen> {
child: SearchBar(
controller: _searchController,
focusNode: _focusNode,
- hintText: context.read<LibraryProvider>().isPodcastLibrary
+ hintText: lib.isPodcastLibrary
? 'Search shows and episodes...'
: 'Search books, series, and authors...',
leading: const Padding(
@@ -697,103 +933,156 @@ class LibraryScreenState extends State<LibraryScreen> {
),
),
+ // Item count + filter badge row
if (!_isInSearchMode)
- Padding(
- padding: const EdgeInsets.fromLTRB(16, 10, 16, 4),
- child: Row(
- children: [
- GestureDetector(
- onTap: () => _showSortFilterSheet(context, cs, tt, initialTab: 0),
- child: Container(
- padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
- decoration: BoxDecoration(
- color: cs.primary.withValues(alpha: 0.12),
- borderRadius: BorderRadius.circular(20),
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(Icons.sort_rounded, size: 14, color: cs.primary),
- const SizedBox(width: 4),
- Text(_sortLabel, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.primary)),
- const SizedBox(width: 2),
- if (_sort != LibrarySort.random)
- Icon(_sortAsc ? Icons.arrow_upward_rounded : Icons.arrow_downward_rounded, size: 12, color: cs.primary),
- ],
- ),
- ),
+ _buildInfoRow(cs, tt),
+
+ Expanded(
+ child: Stack(
+ children: [
+ _isInSearchMode
+ ? _buildSearchResults(cs, tt)
+ : hasTabs
+ ? _buildTabbedContent(cs, tt)
+ : _buildGrid(cs, tt),
+ // Floating tab bar at bottom (book libraries only, hidden during search)
+ if (hasTabs)
+ Positioned(
+ left: 0, right: 0,
+ bottom: 12,
+ child: _buildFloatingTabBar(cs),
),
- if (_filter != LibraryFilter.none) ...[
- const SizedBox(width: 8),
- Flexible(
- child: GestureDetector(
- onTap: () => _showSortFilterSheet(context, cs, tt, initialTab: 1),
- child: Container(
- padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
- decoration: BoxDecoration(
- color: cs.tertiary.withValues(alpha: 0.12),
- borderRadius: BorderRadius.circular(20),
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(Icons.filter_list_rounded, size: 14, color: cs.tertiary),
- const SizedBox(width: 4),
- Flexible(
- child: Text(_filterLabel, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.tertiary), overflow: TextOverflow.ellipsis, maxLines: 1),
- ),
- const SizedBox(width: 4),
- GestureDetector(
- onTap: () => _changeFilter(LibraryFilter.none),
- child: Icon(Icons.close_rounded, size: 14, color: cs.tertiary),
- ),
- ],
- ),
- ),
- ),
- ),
- ],
- if (_collapseSeries) ...[
- const SizedBox(width: 8),
- GestureDetector(
- onTap: () => PlayerSettings.setCollapseSeries(false),
- child: Container(
- padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
- decoration: BoxDecoration(
- color: cs.secondary.withValues(alpha: 0.12),
- borderRadius: BorderRadius.circular(20),
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(Icons.auto_stories_rounded, size: 14, color: cs.secondary),
- const SizedBox(width: 4),
- Text('Series Collapsed', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.secondary)),
- const SizedBox(width: 4),
- Icon(Icons.close_rounded, size: 14, color: cs.secondary),
- ],
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _buildFloatingTabBar(ColorScheme cs) {
+ const labels = ['Library', 'Series', 'Authors'];
+ return Center(
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(24),
+ child: BackdropFilter(
+ filter: ui.ImageFilter.blur(sigmaX: 20, sigmaY: 20),
+ child: Container(
+ padding: const EdgeInsets.all(4),
+ decoration: BoxDecoration(
+ color: cs.surface.withValues(alpha: 0.6),
+ borderRadius: BorderRadius.circular(24),
+ border: Border.all(color: cs.primary.withValues(alpha: 0.25)),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: List.generate(3, (i) {
+ final active = _currentTab == i;
+ return GestureDetector(
+ onTap: () {
+ if (active) {
+ _showSortFilterSheet(context, cs, Theme.of(context).textTheme);
+ } else {
+ _tabController?.animateTo(i);
+ }
+ },
+ child: AnimatedContainer(
+ duration: const Duration(milliseconds: 200),
+ curve: Curves.easeInOut,
+ padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 8),
+ decoration: BoxDecoration(
+ color: active ? cs.primary.withValues(alpha: 0.15) : Colors.transparent,
+ borderRadius: BorderRadius.circular(20),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ labels[i],
+ style: TextStyle(
+ fontSize: 13,
+ fontWeight: active ? FontWeight.w700 : FontWeight.w500,
+ color: active ? cs.primary : cs.onSurfaceVariant,
),
),
- ),
- ],
- const Spacer(),
- Text('${_items.length}${_totalItems > 0 ? '/$_totalItems' : ''} ${_collapseSeries ? 'items' : 'books'}',
- style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.6))),
+ if (active) ...[
+ const SizedBox(width: 4),
+ Icon(Icons.sort_rounded, size: 14, color: cs.primary),
+ ],
+ ],
+ ),
+ ),
+ );
+ }),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _buildInfoRow(ColorScheme cs, TextTheme tt) {
+ String countText;
+ switch (_currentTab) {
+ case 1:
+ countText = '$_totalSeries series';
+ break;
+ case 2:
+ countText = '${_authors.length} authors';
+ break;
+ default:
+ countText = '${_items.length}${_totalItems > 0 ? '/$_totalItems' : ''} books';
+ break;
+ }
+
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
+ child: Row(
+ children: [
+ if (_currentTab == 0 && _filter != LibraryFilter.none) ...[
+ GestureDetector(
+ onTap: () => _changeFilter(LibraryFilter.none),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
+ decoration: BoxDecoration(
+ color: cs.tertiary.withValues(alpha: 0.12),
+ borderRadius: BorderRadius.circular(20),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.filter_list_rounded, size: 14, color: cs.tertiary),
+ const SizedBox(width: 4),
+ Text(_filterLabel, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.tertiary),
+ overflow: TextOverflow.ellipsis, maxLines: 1),
+ const SizedBox(width: 4),
+ Icon(Icons.close_rounded, size: 14, color: cs.tertiary),
],
),
),
-
- Expanded(
- child: _isInSearchMode
- ? _buildSearchResults(cs, tt)
- : _buildGrid(cs, tt),
),
],
- ),
+ const Spacer(),
+ Text(countText,
+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.6))),
+ ],
),
);
}
+ Widget _buildTabbedContent(ColorScheme cs, TextTheme tt) {
+ // Use IndexedStack to preserve scroll positions across tabs
+ return IndexedStack(
+ index: _currentTab,
+ children: [
+ _buildGrid(cs, tt),
+ _buildSeriesGrid(cs, tt),
+ _buildAuthorsGrid(cs, tt),
+ ],
+ );
+ }
+
// ── Pull-to-refresh ──
Future<void> _refreshAll() async {
final lib = context.read<LibraryProvider>();
@@ -809,8 +1098,27 @@ class LibraryScreenState extends State<LibraryScreen> {
await _loadPage();
}
+ Future<void> _refreshSeries() async {
+ setState(() {
+ _seriesItems.clear();
+ _seriesPage = 0;
+ _hasMoreSeries = true;
+ _isLoadingSeriesPage = false;
+ });
+ await _loadSeriesPage();
+ }
+
+ Future<void> _refreshAuthors() async {
+ setState(() {
+ _authors.clear();
+ _authorsLoaded = false;
+ _isLoadingAuthors = false;
+ });
+ await _loadAuthors();
+ }
+
// ═══════════════════════════════════════════════════════════════
- // BROWSE GRID
+ // LIBRARY TAB - BROWSE GRID
// ═══════════════════════════════════════════════════════════════
Widget _buildGrid(ColorScheme cs, TextTheme tt) {
if (_items.isEmpty && _isLoadingPage) {
@@ -874,7 +1182,6 @@ class LibraryScreenState extends State<LibraryScreen> {
itemCount: _items.length + (_hasMore ? 1 : 0),
itemBuilder: (context, index) {
if (index >= _items.length) {
- // Loading indicator at the end
return const Center(
child: Padding(
padding: EdgeInsets.all(16),
@@ -892,6 +1199,118 @@ class LibraryScreenState extends State<LibraryScreen> {
);
}
+ // ═══════════════════════════════════════════════════════════════
+ // SERIES TAB - GRID
+ // ═══════════════════════════════════════════════════════════════
+ Widget _buildSeriesGrid(ColorScheme cs, TextTheme tt) {
+ if (_seriesItems.isEmpty && _isLoadingSeriesPage) {
+ return const Center(child: CircularProgressIndicator());
+ }
+ if (_seriesItems.isEmpty && !_isLoadingSeriesPage) {
+ return RefreshIndicator(
+ onRefresh: _refreshSeries,
+ child: CustomScrollView(
+ physics: const AlwaysScrollableScrollPhysics(),
+ slivers: [
+ SliverFillRemaining(
+ child: Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.collections_bookmark_outlined,
+ size: 56, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
+ const SizedBox(height: 12),
+ Text('No series found',
+ style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ return RefreshIndicator(
+ onRefresh: _refreshSeries,
+ child: GridView.builder(
+ controller: _seriesScrollController,
+ physics: const AlwaysScrollableScrollPhysics(),
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 100),
+ gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
+ crossAxisCount: 3,
+ childAspectRatio: 0.68,
+ crossAxisSpacing: 10,
+ mainAxisSpacing: 10,
+ ),
+ itemCount: _seriesItems.length + (_hasMoreSeries ? 1 : 0),
+ itemBuilder: (context, index) {
+ if (index >= _seriesItems.length) {
+ return const Center(
+ child: Padding(
+ padding: EdgeInsets.all(16),
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
+ );
+ }
+ return GridSeriesTileDirect(series: _seriesItems[index]);
+ },
+ ),
+ );
+ }
+
+ // ═══════════════════════════════════════════════════════════════
+ // AUTHORS TAB - GRID
+ // ═══════════════════════════════════════════════════════════════
+ Widget _buildAuthorsGrid(ColorScheme cs, TextTheme tt) {
+ if (_isLoadingAuthors) {
+ return const Center(child: CircularProgressIndicator());
+ }
+ if (_authors.isEmpty && _authorsLoaded) {
+ return RefreshIndicator(
+ onRefresh: _refreshAuthors,
+ child: CustomScrollView(
+ physics: const AlwaysScrollableScrollPhysics(),
+ slivers: [
+ SliverFillRemaining(
+ child: Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.people_outline_rounded,
+ size: 56, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
+ const SizedBox(height: 12),
+ Text('No authors found',
+ style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ return RefreshIndicator(
+ onRefresh: _refreshAuthors,
+ child: GridView.builder(
+ controller: _authorsScrollController,
+ physics: const AlwaysScrollableScrollPhysics(),
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 100),
+ gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
+ crossAxisCount: 3,
+ childAspectRatio: 0.68,
+ crossAxisSpacing: 10,
+ mainAxisSpacing: 10,
+ ),
+ itemCount: _authors.length,
+ itemBuilder: (context, index) {
+ return GridAuthorTile(author: _authors[index]);
+ },
+ ),
+ );
+ }
+
// ═══════════════════════════════════════════════════════════════
// SEARCH RESULTS
// ═══════════════════════════════════════════════════════════════
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index a3dc93f4..e242d67e 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -339,6 +339,44 @@ class ApiService {
return [];
}
+ /// Get all authors for a library.
+ Future<List<Map<String, dynamic>>> getLibraryAuthors(String libraryId) async {
+ try {
+ final response = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/authors'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+
+ if (response.statusCode == 200) {
+ final data = jsonDecode(response.body) as Map<String, dynamic>;
+ final authors = data['authors'] as List<dynamic>? ?? [];
+ return authors.cast<Map<String, dynamic>>();
+ }
+ } catch (e) {
+ debugPrint('[API] getLibraryAuthors error: $e');
+ }
+ return [];
+ }
+
+ /// Get full author details including description/bio.
+ Future<Map<String, dynamic>?> getAuthorById(String authorId, {String? libraryId}) async {
+ try {
+ var url = '$_cleanBaseUrl/api/authors/$authorId?include=items';
+ if (libraryId != null) url += '&library=$libraryId';
+ final response = await http.get(
+ Uri.parse(url),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+
+ if (response.statusCode == 200) {
+ return jsonDecode(response.body) as Map<String, dynamic>;
+ }
+ } catch (e) {
+ debugPrint('[API] getAuthorById error: $e');
+ }
+ return null;
+ }
+
/// Get books in a specific series using the filter API.
/// Filter format: series.<base64(seriesId)>
Future<List<dynamic>> getBooksBySeries(
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 85590589..e74e3372 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -191,6 +191,18 @@ class PlayerSettings {
static Future<String> getLibraryGenreFilter() => _get('libraryGenreFilter', '');
static Future<void> setLibraryGenreFilter(String? value) => _set('libraryGenreFilter', value ?? '');
+ static Future<String> getSeriesSort() => _get('seriesSort', 'alphabetical');
+ static Future<void> setSeriesSort(String value) => _set('seriesSort', value);
+
+ static Future<bool> getSeriesSortAsc() => _get('seriesSortAsc', true);
+ static Future<void> setSeriesSortAsc(bool value) => _set('seriesSortAsc', value);
+
+ static Future<String> getAuthorSort() => _get('authorSort', 'alphabetical');
+ static Future<void> setAuthorSort(String value) => _set('authorSort', value);
+
+ static Future<bool> getAuthorSortAsc() => _get('authorSortAsc', true);
+ static Future<void> setAuthorSortAsc(bool value) => _set('authorSortAsc', value);
+
static Future<bool> getShowGoodreadsButton() => _get('showGoodreadsButton', false);
static Future<void> setShowGoodreadsButton(bool value) => _set('showGoodreadsButton', value);
diff --git a/lib/widgets/author_books_sheet.dart b/lib/widgets/author_books_sheet.dart
index 81bed4df..7fa2cbe1 100644
--- a/lib/widgets/author_books_sheet.dart
+++ b/lib/widgets/author_books_sheet.dart
@@ -1,10 +1,41 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
+import 'package:cached_network_image/cached_network_image.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
+import '../providers/library_provider.dart';
import 'library_search_results.dart';
+/// Show a bottom sheet with author info and books.
+void showAuthorDetailSheet(BuildContext context, {
+ required String authorId,
+ required String authorName,
+}) {
+ FocusManager.instance.primaryFocus?.unfocus();
+ final auth = context.read<AuthProvider>();
+ final lib = context.read<LibraryProvider>();
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ showDragHandle: true,
+ builder: (_) => DraggableScrollableSheet(
+ initialChildSize: 0.7,
+ minChildSize: 0.05, snap: true,
+ maxChildSize: 0.9,
+ expand: false,
+ builder: (ctx, scrollController) => AuthorBooksSheet(
+ libraryId: lib.selectedLibraryId ?? '',
+ authorId: authorId,
+ authorName: authorName,
+ serverUrl: auth.serverUrl,
+ token: auth.token,
+ scrollController: scrollController,
+ ),
+ ),
+ );
+}
+
class AuthorBooksSheet extends StatefulWidget {
final String libraryId;
final String authorId;
@@ -30,14 +61,17 @@ class AuthorBooksSheet extends StatefulWidget {
class _AuthorBooksSheetState extends State<AuthorBooksSheet> {
List<Map<String, dynamic>> _books = [];
bool _isLoading = true;
+ String? _description;
+ String? _imageUrl;
+ bool _descExpanded = false;
@override
void initState() {
super.initState();
- _loadBooks();
+ _loadAuthorAndBooks();
}
- Future<void> _loadBooks() async {
+ Future<void> _loadAuthorAndBooks() async {
final auth = context.read<AuthProvider>();
final api = auth.apiService;
if (api == null) {
@@ -45,8 +79,30 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {
return;
}
+ // Fetch author details and books in parallel
+ final futures = await Future.wait([
+ api.getAuthorById(widget.authorId, libraryId: widget.libraryId),
+ _fetchBooks(auth),
+ ]);
+
+ final authorData = futures[0] as Map<String, dynamic>?;
+
+ if (mounted) {
+ setState(() {
+ if (authorData != null) {
+ _description = authorData['description'] as String?;
+ if (authorData['imagePath'] != null && (authorData['imagePath'] as String).isNotEmpty) {
+ final ts = (authorData['updatedAt'] as num?)?.toInt();
+ _imageUrl = api.getAuthorImageUrl(widget.authorId, updatedAt: ts);
+ }
+ }
+ _isLoading = false;
+ });
+ }
+ }
+
+ Future<List<Map<String, dynamic>>> _fetchBooks(AuthProvider auth) async {
try {
- // Use audiobookshelf filter: authors.<base64(authorId)>
final filterValue = base64Encode(utf8.encode(widget.authorId));
final cleanUrl = (auth.serverUrl ?? '').endsWith('/')
? auth.serverUrl!.substring(0, auth.serverUrl!.length - 1)
@@ -65,67 +121,151 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {
if (response.statusCode == 200 && mounted) {
final data = jsonDecode(response.body) as Map<String, dynamic>;
final results = (data['results'] as List<dynamic>?) ?? [];
- setState(() {
- _books = results.whereType<Map<String, dynamic>>().toList();
- _isLoading = false;
- });
- } else if (mounted) {
- setState(() => _isLoading = false);
+ final books = results.whereType<Map<String, dynamic>>().toList();
+ if (mounted) setState(() => _books = books);
+ return books;
}
- } catch (_) {
- if (mounted) setState(() => _isLoading = false);
- }
+ } catch (_) {}
+ return [];
}
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
final tt = Theme.of(context).textTheme;
+ final lib = context.read<LibraryProvider>();
+ final headers = lib.mediaHeaders;
- return Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Padding(
- padding: const EdgeInsets.fromLTRB(24, 0, 24, 12),
- child: Row(
- children: [
- Icon(Icons.person_rounded, size: 20, color: cs.primary),
- const SizedBox(width: 8),
- Expanded(
- child: Text(widget.authorName,
- style: tt.titleLarge
- ?.copyWith(fontWeight: FontWeight.w600)),
- ),
- ],
- ),
- ),
- if (_isLoading)
- const Expanded(
- child: Center(child: CircularProgressIndicator()))
- else if (_books.isEmpty)
- Expanded(
- child: Center(
+ if (_isLoading) {
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ _buildHeader(cs, tt, headers),
+ const Expanded(child: Center(child: CircularProgressIndicator())),
+ ],
+ );
+ }
+
+ // Single scrollable list: header + description + books
+ final bottomPad = 24 + MediaQuery.of(context).viewPadding.bottom;
+ final hasDesc = _description != null && _description!.isNotEmpty;
+ // header + optional description + books (or empty message)
+ final itemCount = 1 + (hasDesc ? 1 : 0) + (_books.isEmpty ? 1 : _books.length);
+ final descOffset = 1;
+ final booksOffset = 1 + (hasDesc ? 1 : 0);
+
+ return ListView.builder(
+ controller: widget.scrollController,
+ padding: EdgeInsets.fromLTRB(0, 0, 0, bottomPad),
+ itemCount: itemCount,
+ itemBuilder: (context, index) {
+ if (index == 0) return _buildHeader(cs, tt, headers);
+ if (hasDesc && index == descOffset) return _buildDescription(cs, tt);
+ if (_books.isEmpty) {
+ return Center(
+ child: Padding(
+ padding: const EdgeInsets.only(top: 48),
child: Text('No books found',
- style: tt.bodyLarge
- ?.copyWith(color: cs.onSurfaceVariant)),
+ style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
),
- )
- else
+ );
+ }
+ final bookIndex = index - booksOffset;
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: BookResultTile(
+ item: _books[bookIndex],
+ serverUrl: widget.serverUrl,
+ token: widget.token,
+ ),
+ );
+ },
+ );
+ }
+
+ Widget _buildHeader(ColorScheme cs, TextTheme tt, Map<String, String> headers) {
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(24, 0, 24, 12),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Container(
+ width: 72,
+ height: 72,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: cs.secondaryContainer,
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: _imageUrl != null
+ ? CachedNetworkImage(
+ imageUrl: _imageUrl!,
+ fit: BoxFit.cover,
+ httpHeaders: headers,
+ placeholder: (_, __) => _avatarPlaceholder(cs),
+ errorWidget: (_, __, ___) => _avatarPlaceholder(cs),
+ )
+ : _avatarPlaceholder(cs),
+ ),
+ const SizedBox(width: 16),
Expanded(
- child: ListView.builder(
- controller: widget.scrollController,
- padding: EdgeInsets.fromLTRB(16, 0, 16, 24 + MediaQuery.of(context).viewPadding.bottom),
- itemCount: _books.length,
- itemBuilder: (context, index) {
- return BookResultTile(
- item: _books[index],
- serverUrl: widget.serverUrl,
- token: widget.token,
- );
- },
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ const SizedBox(height: 4),
+ Text(widget.authorName,
+ style: tt.titleLarge?.copyWith(fontWeight: FontWeight.w600)),
+ if (_books.isNotEmpty)
+ Padding(
+ padding: const EdgeInsets.only(top: 4),
+ child: Text(
+ '${_books.length} ${_books.length == 1 ? 'book' : 'books'}',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ ),
+ ],
),
),
- ],
+ ],
+ ),
+ );
+ }
+
+ Widget _buildDescription(ColorScheme cs, TextTheme tt) {
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(24, 0, 24, 12),
+ child: GestureDetector(
+ onTap: () => setState(() => _descExpanded = !_descExpanded),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ _description!,
+ maxLines: _descExpanded ? null : 4,
+ overflow: _descExpanded ? null : TextOverflow.ellipsis,
+ style: tt.bodySmall?.copyWith(
+ color: cs.onSurface.withValues(alpha: 0.7),
+ height: 1.5,
+ ),
+ ),
+ const SizedBox(height: 4),
+ Text(
+ _descExpanded ? 'Show less' : 'Read more',
+ style: tt.labelSmall?.copyWith(
+ color: cs.primary,
+ fontWeight: FontWeight.w500,
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _avatarPlaceholder(ColorScheme cs) {
+ return Center(
+ child: Icon(Icons.person_rounded,
+ size: 32, color: cs.onSecondaryContainer.withValues(alpha: 0.5)),
);
}
}
diff --git a/lib/widgets/library_grid_tiles.dart b/lib/widgets/library_grid_tiles.dart
index 61bcbd66..520cf1cc 100644
--- a/lib/widgets/library_grid_tiles.dart
+++ b/lib/widgets/library_grid_tiles.dart
@@ -8,6 +8,7 @@ import '../services/download_service.dart';
import 'book_detail_sheet.dart';
import 'episode_list_sheet.dart';
import 'series_books_sheet.dart';
+import 'author_books_sheet.dart';
// ═══════════════════════════════════════════════════════════════
// Grid book tile (cover + title + author)
@@ -322,3 +323,232 @@ class GridSeriesTile extends StatelessWidget {
);
}
}
+
+// ═══════════════════════════════════════════════════════════════
+// Grid series tile for the series API format (series tab)
+// The series endpoint returns { id, name, books: [...] } instead
+// of the collapsedSeries format used by the library items endpoint.
+// ═══════════════════════════════════════════════════════════════
+class GridSeriesTileDirect extends StatelessWidget {
+ final Map<String, dynamic> series;
+ const GridSeriesTileDirect({super.key, required this.series});
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final lib = context.watch<LibraryProvider>();
+ final auth = context.read<AuthProvider>();
+
+ final seriesName = series['name'] as String? ?? 'Unknown Series';
+ final seriesId = series['id'] as String? ?? '';
+ final books = series['books'] as List<dynamic>? ?? [];
+ final numBooks = books.length;
+
+ // Get cover from first book in series
+ String? coverUrl;
+ String author = '';
+ if (books.isNotEmpty) {
+ final firstBook = books.first as Map<String, dynamic>? ?? {};
+ final bookId = firstBook['id'] as String? ?? '';
+ if (bookId.isNotEmpty) coverUrl = lib.getCoverUrl(bookId);
+ final media = firstBook['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ author = metadata['authorName'] as String? ?? '';
+ }
+
+ return GestureDetector(
+ onTap: () {
+ if (seriesId.isNotEmpty) {
+ showSeriesBooksSheet(
+ context,
+ seriesName: seriesName,
+ seriesId: seriesId,
+ books: const [],
+ serverUrl: auth.serverUrl,
+ token: auth.token,
+ );
+ }
+ },
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ AspectRatio(
+ aspectRatio: 1,
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(10),
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ coverUrl != null
+ ? coverUrl.startsWith('/')
+ ? Image.file(File(coverUrl), fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => _placeholder(cs))
+ : CachedNetworkImage(
+ imageUrl: coverUrl,
+ fit: BoxFit.cover,
+ httpHeaders: lib.mediaHeaders,
+ placeholder: (_, __) => _placeholder(cs),
+ errorWidget: (_, __, ___) => _placeholder(cs),
+ )
+ : _placeholder(cs),
+ Positioned(
+ top: 6,
+ right: 6,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 3),
+ decoration: BoxDecoration(
+ color: cs.primaryContainer,
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.auto_stories_rounded, size: 11, color: cs.onPrimaryContainer),
+ const SizedBox(width: 3),
+ Text('$numBooks',
+ style: TextStyle(fontSize: 10, fontWeight: FontWeight.w700,
+ color: cs.onPrimaryContainer)),
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(height: 5),
+ Text(
+ seriesName,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.onSurface,
+ fontSize: 11,
+ ),
+ ),
+ if (author.isNotEmpty)
+ Text(
+ author,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(
+ color: cs.onSurfaceVariant,
+ fontSize: 10,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _placeholder(ColorScheme cs) {
+ return Container(
+ color: cs.surfaceContainerHighest,
+ child: Center(
+ child: Icon(Icons.auto_stories_rounded,
+ size: 24, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
+ ),
+ );
+ }
+}
+
+// ═══════════════════════════════════════════════════════════════
+// Grid author tile (circular avatar + name + book count)
+// ═══════════════════════════════════════════════════════════════
+class GridAuthorTile extends StatelessWidget {
+ final Map<String, dynamic> author;
+ const GridAuthorTile({super.key, required this.author});
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final auth = context.read<AuthProvider>();
+ final lib = context.read<LibraryProvider>();
+
+ final name = author['name'] as String? ?? 'Unknown';
+ final authorId = author['id'] as String? ?? '';
+ final numBooks = author['numBooks'] as int? ?? 0;
+
+ String? imageUrl;
+ if (authorId.isNotEmpty && auth.apiService != null) {
+ final ts = (author['updatedAt'] as num?)?.toInt();
+ imageUrl = auth.apiService!.getAuthorImageUrl(authorId, updatedAt: ts);
+ }
+
+ final headers = lib.mediaHeaders;
+
+ return GestureDetector(
+ onTap: () {
+ if (authorId.isNotEmpty) {
+ showAuthorDetailSheet(context, authorId: authorId, authorName: name);
+ }
+ },
+ child: Column(
+ children: [
+ // Circular avatar
+ AspectRatio(
+ aspectRatio: 1,
+ child: Container(
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: cs.secondaryContainer,
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ imageUrl != null
+ ? CachedNetworkImage(
+ imageUrl: imageUrl,
+ fit: BoxFit.cover,
+ httpHeaders: headers,
+ placeholder: (_, __) => _placeholder(cs),
+ errorWidget: (_, __, ___) => _placeholder(cs),
+ )
+ : _placeholder(cs),
+ if (numBooks > 0)
+ Positioned(
+ bottom: 4,
+ right: 4,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
+ decoration: BoxDecoration(
+ color: cs.primaryContainer,
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Text('$numBooks',
+ style: TextStyle(fontSize: 10, fontWeight: FontWeight.w700,
+ color: cs.onPrimaryContainer)),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(height: 5),
+ Text(
+ name,
+ textAlign: TextAlign.center,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.onSurface,
+ fontSize: 11,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _placeholder(ColorScheme cs) {
+ return Center(
+ child: Icon(Icons.person_rounded,
+ size: 32, color: cs.onSecondaryContainer.withValues(alpha: 0.4)),
+ );
+ }
+}
diff --git a/lib/widgets/library_sort_filter_sheet.dart b/lib/widgets/library_sort_filter_sheet.dart
index 0a0587aa..e874d993 100644
--- a/lib/widgets/library_sort_filter_sheet.dart
+++ b/lib/widgets/library_sort_filter_sheet.dart
@@ -2,6 +2,9 @@ import 'dart:async';
import 'package:flutter/material.dart';
import '../screens/library_screen.dart';
+/// Which library tab the sort/filter sheet is being shown for.
+enum LibraryTab { library, series, authors }
+
// ═══════════════════════════════════════════════════════════════
// Sort & Filter bottom sheet with tabs
// ═══════════════════════════════════════════════════════════════
@@ -21,6 +24,7 @@ class SortFilterSheet extends StatefulWidget {
final bool collapseSeries;
final ValueChanged<bool> onCollapseSeriesChanged;
final bool isPodcastLibrary;
+ final LibraryTab libraryTab;
const SortFilterSheet({
super.key,
@@ -30,8 +34,9 @@ class SortFilterSheet extends StatefulWidget {
required this.cs, required this.tt,
required this.onSortChanged, required this.onSortDirectionToggled,
required this.onFilterChanged, required this.onClearFilter,
- required this.collapseSeries, required this.onCollapseSeriesChanged,
+ this.collapseSeries = false, required this.onCollapseSeriesChanged,
required this.isPodcastLibrary,
+ this.libraryTab = LibraryTab.library,
});
@override
@@ -41,11 +46,19 @@ class SortFilterSheet extends StatefulWidget {
class _SortFilterSheetState extends State<SortFilterSheet> with SingleTickerProviderStateMixin {
late TabController _tabCtrl;
bool _genreExpanded = false;
+ late bool _collapseSeries;
+
+ bool get _showFilterTab => widget.libraryTab == LibraryTab.library;
@override
void initState() {
super.initState();
- _tabCtrl = TabController(length: 2, vsync: this, initialIndex: widget.initialTab);
+ _collapseSeries = widget.collapseSeries;
+ final tabCount = _showFilterTab ? 2 : 1;
+ _tabCtrl = TabController(
+ length: tabCount, vsync: this,
+ initialIndex: _showFilterTab ? widget.initialTab.clamp(0, 1) : 0,
+ );
if (widget.currentFilter == LibraryFilter.genre) _genreExpanded = true;
}
@@ -67,23 +80,32 @@ class _SortFilterSheetState extends State<SortFilterSheet> with SingleTickerProv
Center(child: Container(width: 40, height: 4,
decoration: BoxDecoration(color: cs.onSurfaceVariant.withValues(alpha: 0.3), borderRadius: BorderRadius.circular(2)))),
const SizedBox(height: 16),
- TabBar(
- controller: _tabCtrl,
- labelColor: cs.primary, unselectedLabelColor: cs.onSurfaceVariant,
- indicatorColor: cs.primary, indicatorSize: TabBarIndicatorSize.label,
- dividerColor: Colors.transparent,
- tabs: [
- Tab(child: Row(mainAxisSize: MainAxisSize.min, children: [
- Icon(Icons.sort_rounded, size: 18), const SizedBox(width: 6), const Text('Sort')])),
- Tab(child: Row(mainAxisSize: MainAxisSize.min, children: [
- Icon(Icons.filter_list_rounded, size: 18), const SizedBox(width: 6),
- Text(widget.currentFilter != LibraryFilter.none ? 'Filter ●' : 'Filter')])),
- ],
- ),
+ if (_showFilterTab)
+ TabBar(
+ controller: _tabCtrl,
+ labelColor: cs.primary, unselectedLabelColor: cs.onSurfaceVariant,
+ indicatorColor: cs.primary, indicatorSize: TabBarIndicatorSize.label,
+ dividerColor: Colors.transparent,
+ tabs: [
+ Tab(child: Row(mainAxisSize: MainAxisSize.min, children: [
+ Icon(Icons.sort_rounded, size: 18), const SizedBox(width: 6), const Text('Sort')])),
+ Tab(child: Row(mainAxisSize: MainAxisSize.min, children: [
+ Icon(Icons.filter_list_rounded, size: 18), const SizedBox(width: 6),
+ Text(widget.currentFilter != LibraryFilter.none ? 'Filter \u25cf' : 'Filter')])),
+ ],
+ )
+ else
+ Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: Text('Sort', style: TextStyle(
+ fontSize: 16, fontWeight: FontWeight.w600, color: cs.primary)),
+ ),
SizedBox(
- height: _genreExpanded ? 420 : (widget.isPodcastLibrary ? 320 : 380),
- child: TabBarView(controller: _tabCtrl, children: [
- _buildSortTab(cs), _buildFilterTab(cs)]),
+ height: _calcHeight(),
+ child: _showFilterTab
+ ? TabBarView(controller: _tabCtrl, children: [
+ _buildSortTab(cs), _buildFilterTab(cs)])
+ : _buildSortTab(cs),
),
SizedBox(height: MediaQuery.of(context).viewPadding.bottom + 8),
],
@@ -91,15 +113,14 @@ class _SortFilterSheetState extends State<SortFilterSheet> with SingleTickerProv
);
}
+ double _calcHeight() {
+ if (widget.libraryTab == LibraryTab.series) return 230;
+ if (widget.libraryTab == LibraryTab.authors) return 180;
+ return _genreExpanded ? 420 : (widget.isPodcastLibrary ? 320 : 400);
+ }
+
Widget _buildSortTab(ColorScheme cs) {
- final sorts = <(LibrarySort, String, IconData)>[
- (LibrarySort.recentlyAdded, 'Date Added', Icons.schedule_rounded),
- (LibrarySort.alphabetical, 'Title', Icons.sort_by_alpha_rounded),
- (LibrarySort.authorName, 'Author', Icons.person_rounded),
- (LibrarySort.publishedYear, 'Published Year', Icons.calendar_today_rounded),
- (LibrarySort.duration, 'Duration', Icons.timelapse_rounded),
- (LibrarySort.random, 'Random', Icons.shuffle_rounded),
- ];
+ final sorts = _getSortOptions();
return ListView(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
children: [
@@ -124,49 +145,75 @@ class _SortFilterSheetState extends State<SortFilterSheet> with SingleTickerProv
onTap: () => widget.onSortChanged(sort),
);
}),
- if (!widget.isPodcastLibrary) ...[
- const SizedBox(height: 8),
- Divider(color: cs.outlineVariant.withValues(alpha: 0.3), height: 1),
- const SizedBox(height: 8),
+ if (widget.libraryTab == LibraryTab.library && !widget.isPodcastLibrary)
GestureDetector(
- onTap: () => widget.onCollapseSeriesChanged(!widget.collapseSeries),
+ onTap: () {
+ setState(() => _collapseSeries = !_collapseSeries);
+ widget.onCollapseSeriesChanged(_collapseSeries);
+ },
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
margin: const EdgeInsets.only(bottom: 4),
decoration: BoxDecoration(
- color: widget.collapseSeries ? cs.secondary.withValues(alpha: 0.12) : Colors.transparent,
+ color: _collapseSeries ? cs.secondary.withValues(alpha: 0.12) : Colors.transparent,
borderRadius: BorderRadius.circular(14),
),
child: Row(children: [
Icon(Icons.auto_stories_rounded, size: 20,
- color: widget.collapseSeries ? cs.secondary : cs.onSurfaceVariant),
+ color: _collapseSeries ? cs.secondary : cs.onSurfaceVariant),
const SizedBox(width: 12),
Expanded(
child: Text('Collapse Series', style: TextStyle(
fontSize: 14,
- fontWeight: widget.collapseSeries ? FontWeight.w600 : FontWeight.w400,
- color: widget.collapseSeries ? cs.secondary : cs.onSurface)),
+ fontWeight: _collapseSeries ? FontWeight.w600 : FontWeight.w400,
+ color: _collapseSeries ? cs.secondary : cs.onSurface)),
),
Switch(
- value: widget.collapseSeries,
- onChanged: widget.onCollapseSeriesChanged,
+ value: _collapseSeries,
+ onChanged: (v) {
+ setState(() => _collapseSeries = v);
+ widget.onCollapseSeriesChanged(v);
+ },
activeThumbColor: cs.secondary,
),
]),
),
),
- ],
],
);
}
+ List<(LibrarySort, String, IconData)> _getSortOptions() {
+ switch (widget.libraryTab) {
+ case LibraryTab.series:
+ return [
+ (LibrarySort.alphabetical, 'Name', Icons.sort_by_alpha_rounded),
+ (LibrarySort.recentlyAdded, 'Date Added', Icons.schedule_rounded),
+ (LibrarySort.totalDuration, 'Number of Books', Icons.auto_stories_rounded),
+ ];
+ case LibraryTab.authors:
+ return [
+ (LibrarySort.alphabetical, 'Name', Icons.sort_by_alpha_rounded),
+ (LibrarySort.totalDuration, 'Number of Books', Icons.auto_stories_rounded),
+ ];
+ case LibraryTab.library:
+ return [
+ (LibrarySort.recentlyAdded, 'Date Added', Icons.schedule_rounded),
+ (LibrarySort.alphabetical, 'Title', Icons.sort_by_alpha_rounded),
+ (LibrarySort.authorName, 'Author', Icons.person_rounded),
+ (LibrarySort.publishedYear, 'Published Year', Icons.calendar_today_rounded),
+ (LibrarySort.duration, 'Duration', Icons.timelapse_rounded),
+ (LibrarySort.random, 'Random', Icons.shuffle_rounded),
+ ];
+ }
+ }
+
Widget _buildFilterTab(ColorScheme cs) {
final filters = <(LibraryFilter, String, IconData)>[
(LibraryFilter.inProgress, 'In Progress', Icons.play_circle_outline_rounded),
(LibraryFilter.finished, 'Finished', Icons.check_circle_outline_rounded),
(LibraryFilter.notStarted, 'Not Started', Icons.circle_outlined),
(LibraryFilter.downloaded, 'Downloaded', Icons.download_done_rounded),
- (LibraryFilter.inASeries, 'Series', Icons.auto_stories_rounded),
(LibraryFilter.hasEbook, 'Has eBook', Icons.menu_book_rounded),
];
return ListView(