A cross platform Audiobookshelf client for Android and iOS
Dart
Add a Lists tab to browse collections and playlists
Barnabas05e922238db9
diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dartindex 7cfc0cb3..cf9531e1 100644--- a/lib/screens/library_screen.dart+++ b/lib/screens/library_screen.dart@@ -20,6 +20,9 @@ import '../widgets/library_books_tab.dart';import '../widgets/library_series_tab.dart';import '../widgets/library_authors_tab.dart';import '../widgets/library_narrators_tab.dart';+import '../widgets/library_lists_tab.dart';+import '../widgets/collection_detail_sheet.dart';+import '../widgets/playlist_detail_sheet.dart';import 'admin_podcasts_screen.dart';import 'app_shell.dart';import 'upcoming_releases_screen.dart';@@ -152,13 +155,21 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMiString? _listsLoadedKey;Future<void>? _listsLoadFuture;String? _listsLoadingKey;- // When a collection/playlist is open the Library grid shows its items in- // place, like a filter. null = normal library.- String? _scopeId;- String? _scopeName;- bool _scopeIsPlaylist = false;- List<Map<String, dynamic>> _scopeItems = [];- bool get _isScoped => _scopeId != null;+ // Lists tab (collections/playlists). The tab is the 5th pill, only shown+ // when there's at least one list; re-tapping the active Lists pill flips+ // between collections and playlists.+ LibrarySort _listsSort = LibrarySort.alphabetical;+ bool _listsSortAsc = true;+ final _listsScrollController = ScrollController();+ // Remembered per library (persisted): once a library is known to have lists,+ // keep the Lists pill shown immediately on later opens and don't let it blink+ // out while the lists reload. Cleared only when a load confirms zero lists.+ bool _cachedHasLists = false;+ bool get _showLists =>+ _tabController != null &&+ (_collections.isNotEmpty || _playlists.isNotEmpty || _cachedHasLists);++ String _listsPresentKey(String libId) => 'lists_present_$libId';bool _isLoadingPage = false;bool _hasMore = true;@@ -258,7 +269,10 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMivoid _initTabController() {final lib = context.read<LibraryProvider>();if (!lib.isPodcastLibrary) {- _tabController = TabController(length: 4, vsync: this);+ // 5 = Library/Series/Authors/Narrators/Lists. The Lists pill is only+ // shown when lists exist; since the views are an IndexedStack (no swipe),+ // an unreachable 5th slot is harmless.+ _tabController = TabController(length: 5, vsync: this);_tabController!.addListener(_onTabChanged);}}@@ -278,6 +292,8 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi_loadAuthors();} else if (newTab == 3 && !_narratorsLoaded && !_isLoadingNarrators) {_loadNarrators();+ } else if (newTab == 4) {+ _loadLists();}}@@ -299,7 +315,7 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi_tabController?.removeListener(_onTabChanged);_tabController?.dispose();if (needsTabs) {- _tabController = TabController(length: 4, vsync: this);+ _tabController = TabController(length: 5, vsync: this);_tabController!.addListener(_onTabChanged);} else {_tabController = null;@@ -326,6 +342,9 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi_narrators.clear();_narratorsLoaded = false;_isLoadingNarrators = false;+ // Different library: drop the old Lists state; _fetchLists re-seeds the+ // pill from the new library's remembered flag.+ _cachedHasLists = false;_allNarratorsCache = null;_allNarratorsCacheLibraryId = null;_searchNarratorResults = [];@@ -386,6 +405,8 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMiPlayerSettings.getNarratorSortAsc(),PlayerSettings.getLibraryTagFilter(),PlayerSettings.getLibrarySeriesFilter(),+ PlayerSettings.getListsSort(),+ PlayerSettings.getListsSortAsc(),]);if (!mounted) return;final sortName = results[0] as String;@@ -403,7 +424,17 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMifinal narratorSortAsc = results[12] as bool;final tagFilter = results[13] as String;final seriesFilterName = results[14] as String;- final isPodcast = context.read<LibraryProvider>().isPodcastLibrary;+ final listsSortName = results[15] as String;+ final listsSortAsc = results[16] as bool;+ final lib = context.read<LibraryProvider>();+ final isPodcast = lib.isPodcastLibrary;+ // Read the remembered "has lists" flag so the Lists tab (and its pill) can+ // be restored immediately on cold start, before the lists finish loading.+ final libId = lib.selectedLibraryId;+ final hasListsRemembered = libId != null+ ? (await ScopedPrefs.getBool(_listsPresentKey(libId)) ?? false)+ : false;+ if (!mounted) return;setState(() {// Book library sort/filter_sort = LibrarySort.values.firstWhere(@@ -443,6 +474,11 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMiorElse: () => LibrarySort.alphabetical,);_narratorSortAsc = narratorSortAsc;+ _listsSort = LibrarySort.values.firstWhere(+ (s) => s.name == listsSortName,+ orElse: () => LibrarySort.alphabetical,+ );+ _listsSortAsc = listsSortAsc;// Podcast sort_podcastSort = LibrarySort.values.firstWhere((s) => s.name == podcastSortName,@@ -457,8 +493,13 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi_genreFilter = null;_tagFilter = null;}- // Restore last active tab (only for book libraries with tabs)- if (!isPodcast && savedTab > 0 && savedTab < 4) {+ // Seed the Lists pill from the remembered flag so it (and the restored+ // Lists tab) show right away, before the lists load.+ if (hasListsRemembered) _cachedHasLists = true;+ // Restore last active tab (only for book libraries with tabs). The Lists+ // tab (4) is only restorable if the library is known to have lists.+ final maxRestorableTab = hasListsRemembered ? 4 : 3;+ if (!isPodcast && savedTab > 0 && savedTab <= maxRestorableTab) {_currentTab = savedTab;_tabController?.animateTo(savedTab);}@@ -549,6 +590,7 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi_seriesScrollController.dispose();_authorsScrollController.dispose();_narratorsScrollController.dispose();+ _listsScrollController.dispose();_tabController?.removeListener(_onTabChanged);_tabController?.dispose();PlayerSettings.settingsChanged.removeListener(_onSettingsChanged);@@ -573,7 +615,6 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi// LIBRARY TAB - Load a page of items// ══════════════════════════════════════════════════════════════Future<void> _loadPage() async {- if (_isScoped) return;if (_isLoadingPage || !_hasMore) return;setState(() => _isLoadingPage = true);final gen = ++_loadGeneration;@@ -1035,6 +1076,7 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMiif (_currentTab == 1) { _changeSeriesSort(newSort); return; }if (_currentTab == 2) { _changeAuthorSort(newSort); return; }if (_currentTab == 3) { _changeNarratorSort(newSort); return; }+ if (_currentTab == 4) { _changeListsSort(newSort); return; }final isPodcast = context.read<LibraryProvider>().isPodcastLibrary;if (newSort == _sort) {@@ -1133,6 +1175,49 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMiif (_narratorsScrollController.hasClients) _narratorsScrollController.jumpTo(0);}+ void _changeListsSort(LibrarySort newSort) {+ if (newSort == _listsSort) {+ setState(() => _listsSortAsc = !_listsSortAsc);+ } else {+ setState(() {+ _listsSort = newSort;+ // A-Z ascending; date-added and item-count default to descending.+ _listsSortAsc = newSort == LibrarySort.alphabetical;+ });+ }+ PlayerSettings.setListsSort(_listsSort.name);+ PlayerSettings.setListsSortAsc(_listsSortAsc);+ if (_listsScrollController.hasClients) _listsScrollController.jumpTo(0);+ }++ /// All collections and playlists merged into one list, tagged with+ /// `_isPlaylist`, sorted by the current Lists sort.+ List<Map<String, dynamic>> _sortedLists() {+ final entries = <Map<String, dynamic>>[+ for (final c in _collections) {...c, '_isPlaylist': false},+ for (final p in _playlists) {...p, '_isPlaylist': true},+ ];+ int countOf(Map<String, dynamic> e) => e['_isPlaylist'] == true+ ? (e['items'] as List<dynamic>?)?.length ?? 0+ : (e['books'] as List<dynamic>?)?.length ?? 0;+ int asc(Map<String, dynamic> a, Map<String, dynamic> b) {+ switch (_listsSort) {+ case LibrarySort.recentlyAdded:+ final ca = (a['createdAt'] as num?)?.toDouble() ?? 0;+ final cb = (b['createdAt'] as num?)?.toDouble() ?? 0;+ return ca.compareTo(cb);+ case LibrarySort.totalDuration:+ return countOf(a).compareTo(countOf(b));+ default:+ return (a['name'] as String? ?? '')+ .toLowerCase()+ .compareTo((b['name'] as String? ?? '').toLowerCase());+ }+ }+ entries.sort((a, b) => _listsSortAsc ? asc(a, b) : asc(b, a));+ return entries;+ }+/// Switch to the Books sub-tab (if needed) and apply a tag filter. Used by/// AppShell.openLibraryWithTagFilterGlobal so a tag chip tapped from the/// book detail sheet drops the user into the matching library view.@@ -1229,16 +1314,16 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi}Future<void> _fetchLists(String key, ApiService api, String libId) async {- // New key (library/account changed) or first load: drop the previous- // lists + any open scope before fetching the new ones.+ // Seed the Lists pill from the remembered flag so it shows right away (and+ // doesn't blink out while reloading) before the network confirms.+ final remembered = await ScopedPrefs.getBool(_listsPresentKey(libId)) ?? false;+ if (!mounted || _listsLoadingKey != key) return;+ // New key (library/account changed) or first load: drop the previous lists+ // before fetching the new ones.setState(() {_collections = [];_playlists = [];- if (_isScoped) {- _scopeId = null;- _scopeName = null;- _scopeItems = [];- }+ _cachedHasLists = remembered;});try {final results = await Future.wait([@@ -1246,72 +1331,31 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMiapi.getLibraryPlaylists(libId),]);if (!mounted || _listsLoadingKey != key) return;+ final cols = results[0].whereType<Map<String, dynamic>>().toList();+ final pls = results[1].whereType<Map<String, dynamic>>().toList();+ final hasLists = cols.isNotEmpty || pls.isNotEmpty;setState(() {- _collections = results[0].whereType<Map<String, dynamic>>().toList();- _playlists = results[1].whereType<Map<String, dynamic>>().toList();+ _collections = cols;+ _playlists = pls;_listsLoadedKey = key;+ _cachedHasLists = hasLists;+ // Fall back to Library if the Lists tab is open but has nothing.+ if (_currentTab == 4 && !_showLists) {+ _currentTab = 0;+ _tabController?.animateTo(0);+ }});+ // Remember for next time so the pill is instant, and forget once a load+ // confirms the library genuinely has none.+ await ScopedPrefs.setBool(_listsPresentKey(libId), hasLists);} finally {if (_listsLoadingKey == key) _listsLoadFuture = null;}}- void _openCollection(Map<String, dynamic> c) {- final books = (c['books'] as List<dynamic>?)- ?.whereType<Map<String, dynamic>>()- .toList() ??- [];- setState(() {- _scopeId = c['id'] as String?;- _scopeName = c['name'] as String? ?? '';- _scopeIsPlaylist = false;- _scopeItems = books;- });- if (_scrollController.hasClients) _scrollController.jumpTo(0);- }-- void _openPlaylist(Map<String, dynamic> p) {- final books = <Map<String, dynamic>>[];- for (final it in (p['items'] as List<dynamic>?) ?? []) {- if (it is Map<String, dynamic>) {- final li = it['libraryItem'];- if (li is Map<String, dynamic>) books.add(li);- }- }- setState(() {- _scopeId = p['id'] as String?;- _scopeName = p['name'] as String? ?? '';- _scopeIsPlaylist = true;- _scopeItems = books;- });- if (_scrollController.hasClients) _scrollController.jumpTo(0);- }-- void _clearScope() {- setState(() {- _scopeId = null;- _scopeName = null;- _scopeItems = [];- });- if (_scrollController.hasClients) _scrollController.jumpTo(0);- }-- Future<void> _playScope() async {- final id = _scopeId;- if (id == null) return;- final lib = context.read<LibraryProvider>();- final isPlaylist = _scopeIsPlaylist;- final name = _scopeName ?? '';- // Jump to the player first - it shows its own loading state - so the tap- // gives instant feedback instead of a dead pause while the list loads.- AppShell.goToAbsorbingGlobal();- if (isPlaylist) {- await PlayerSettings.setQueueModePlaylist(id);- await lib.playPlaylistFromStart(id);- } else {- await PlayerSettings.setQueueModeCollection(id, name);- await lib.playCollectionFromStart(id);- }+ Future<void> _refreshLists() async {+ _listsLoadedKey = null;+ await _loadLists();}// ── Search ──@@ -1563,9 +1607,6 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi};Future<void> _showSortFilterSheet(BuildContext context, ColorScheme cs, TextTheme tt, {int initialTab = 0}) async {- // Await the load so the Lists tab appears on the first open, not after a reopen.- await _loadLists();- if (!mounted) return;final LibraryTab tab;final LibrarySort currentSort;final bool currentSortAsc;@@ -1585,6 +1626,11 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMicurrentSort = _narratorSort;currentSortAsc = _narratorSortAsc;break;+ case 4:+ tab = LibraryTab.lists;+ currentSort = _listsSort;+ currentSortAsc = _listsSortAsc;+ break;default:tab = LibraryTab.library;currentSort = _sort;@@ -1622,6 +1668,10 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMisetState(() { _narratorSortAsc = !_narratorSortAsc; _sortNarrators(); });PlayerSettings.setNarratorSortAsc(_narratorSortAsc);if (_narratorsScrollController.hasClients) _narratorsScrollController.jumpTo(0);+ } else if (_currentTab == 4) {+ setState(() => _listsSortAsc = !_listsSortAsc);+ PlayerSettings.setListsSortAsc(_listsSortAsc);+ if (_listsScrollController.hasClients) _listsScrollController.jumpTo(0);} else {setState(() { _sortAsc = !_sortAsc; _items.clear(); _page = 0; _hasMore = true; _isLoadingPage = false; });final isPodcast = context.read<LibraryProvider>().isPodcastLibrary;@@ -1656,10 +1706,6 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi_loadPage();},isPodcastLibrary: context.read<LibraryProvider>().isPodcastLibrary,- collections: tab == LibraryTab.library ? _collections : const [],- playlists: tab == LibraryTab.library ? _playlists : const [],- onOpenCollection: (c) { Navigator.pop(ctx); _openCollection(c); },- onOpenPlaylist: (p) { Navigator.pop(ctx); _openPlaylist(p); },onUpcomingReleases: tab == LibraryTab.series ? () {Navigator.pop(ctx);_openUpcomingReleases();@@ -1691,7 +1737,7 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMiif (libWatch.isOffline != _wasOffline) {_wasOffline = libWatch.isOffline;WidgetsBinding.instance.addPostFrameCallback((_) {- if (!mounted || _isScoped) return;+ if (!mounted) return;setState(() { _items.clear(); _page = 0; _hasMore = true; _isLoadingPage = false; });_loadPage();});@@ -1884,8 +1930,7 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMitoolbarHeight: _isInSearchMode? 156: ((_filter != LibraryFilter.none ||- _seriesFilter != SeriesFilter.none ||- _isScoped)+ _seriesFilter != SeriesFilter.none)? 196: 184),backgroundColor: scaffoldBg,@@ -2000,62 +2045,87 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMiWidget _buildFloatingTabBar(ColorScheme cs) {final l = AppLocalizations.of(context)!;- final labels = [l.libraryTabLibrary, l.libraryTabSeries, l.libraryTabAuthors, l.libraryTabNarrators];- 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(labels.length, (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: EdgeInsets.symmetric(horizontal: active ? 14 : 12, 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,+ final labels = [+ l.libraryTabLibrary,+ l.libraryTabSeries,+ l.libraryTabAuthors,+ l.libraryTabNarrators,+ if (_showLists) 'Lists',+ ];+ return Center(+ child: Padding(+ // Inset from the screen edges; the FittedBox below scales the whole+ // pill row down to fit this width so it never overflows on small or+ // zoomed/large-font screens.+ padding: const EdgeInsets.symmetric(horizontal: 16),+ 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: FittedBox(+ fit: BoxFit.scaleDown,+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: List.generate(labels.length, (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: EdgeInsets.symmetric(+ horizontal: active ? 14 : 12, 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],+ maxLines: 1,+ softWrap: false,+ style: TextStyle(+ fontSize: 13,+ fontWeight:+ active ? FontWeight.w700 : FontWeight.w500,+ color:+ active ? cs.primary : cs.onSurfaceVariant,+ ),+ ),+ if (active) ...[+ const SizedBox(width: 4),+ Icon(Icons.sort_rounded, size: 14, color: cs.primary),+ ],+ ],),),- if (active) ...[- const SizedBox(width: 4),- Icon(Icons.sort_rounded, size: 14, color: cs.primary),- ],- ],- ),+ );+ }),),- );- }),+ ),+ ),),),),- ));+ );}@@ -2147,10 +2217,14 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMicase 3:countText = l.libraryNarratorsCount(_narrators.length);break;+ case 4:+ final cCount = _collections.length, pCount = _playlists.length;+ countText = cCount > 0 && pCount > 0+ ? '$cCount collections, $pCount playlists'+ : (pCount > 0 ? '$pCount playlists' : '$cCount collections');+ break;default:- countText = _isScoped- ? l.libraryBooksCount(_scopeItems.length, _scopeItems.length)- : l.libraryBooksCount(_items.length, _totalItems);+ countText = l.libraryBooksCount(_items.length, _totalItems);break;}@@ -2158,50 +2232,7 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMipadding: const EdgeInsets.fromLTRB(16, 8, 16, 0),child: Row(children: [- if (_currentTab == 0 && _isScoped) ...[- GestureDetector(- onTap: _clearScope,- child: Container(- padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),- decoration: BoxDecoration(- color: cs.secondary.withValues(alpha: 0.12),- borderRadius: BorderRadius.circular(20),- ),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- Icon(_scopeIsPlaylist ? Icons.playlist_play_rounded : Icons.collections_bookmark_rounded,- size: 14, color: cs.secondary),- const SizedBox(width: 4),- ConstrainedBox(- constraints: const BoxConstraints(maxWidth: 150),- child: Text(_scopeName ?? '', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.secondary),- overflow: TextOverflow.ellipsis, maxLines: 1),- ),- const SizedBox(width: 4),- Icon(Icons.close_rounded, size: 14, color: cs.secondary),- ],- ),- ),- ),- const SizedBox(width: 8),- GestureDetector(- onTap: _playScope,- child: Container(- padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),- decoration: BoxDecoration(- color: cs.primary.withValues(alpha: 0.12),- borderRadius: BorderRadius.circular(20),- ),- child: Row(mainAxisSize: MainAxisSize.min, children: [- Icon(Icons.play_arrow_rounded, size: 14, color: cs.primary),- const SizedBox(width: 4),- Text(l.playlistPlayAction, style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.primary)),- ]),- ),- ),- ],- if (_currentTab == 0 && _filter != LibraryFilter.none && !_isScoped) ...[+ if (_currentTab == 0 && _filter != LibraryFilter.none) ...[GestureDetector(onTap: () => _changeFilter(LibraryFilter.none),child: Container(@@ -2262,19 +2293,44 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi// the SearchBar inside binds to the screen-level _focusNode. Inactive// tabs' SearchBars use their own internal focus, avoiding the multi-bind// bug that left the search bar unresponsive on first tap.+ // If we're somehow on the Lists tab without any lists, fall back to Library.+ final effectiveTab = (_currentTab == 4 && !_showLists) ? 0 : _currentTab;Widget headerFor(int i) =>- _buildHeaderSliver(context, useSharedFocus: i == _currentTab);+ _buildHeaderSliver(context, useSharedFocus: i == effectiveTab);return IndexedStack(- index: _currentTab,+ index: effectiveTab,children: [_buildGrid(headerFor(0)),_buildSeriesGrid(headerFor(1)),_buildAuthorsGrid(headerFor(2)),_buildNarratorsGrid(headerFor(3)),+ _buildListsGrid(headerFor(4)),],);}+ Widget _buildListsGrid(Widget headerSliver) {+ final entries = _sortedLists();+ return LibraryListsTab(+ entries: entries,+ // We expect lists (the remembered flag is set) but haven't loaded them+ // yet - show a spinner instead of flashing the empty state.+ isLoading: entries.isEmpty && _cachedHasLists,+ coverAspectRatio: _coverAspectRatio,+ onOpenCollection: (c) {+ final id = c['id'] as String?;+ if (id != null && id.isNotEmpty) CollectionDetailSheet.show(context, id);+ },+ onOpenPlaylist: (p) {+ final id = p['id'] as String?;+ if (id != null && id.isNotEmpty) PlaylistDetailSheet.show(context, id);+ },+ onRefresh: _refreshLists,+ headerSliver: headerSliver,+ scrollController: _listsScrollController,+ );+ }+// ── Pull-to-refresh ──Future<void> _refreshAll() async {final lib = context.read<LibraryProvider>();@@ -2314,9 +2370,9 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi// ═══════════════════════════════════════════════════════════════Widget _buildGrid(Widget headerSliver) {return LibraryBooksTab(- items: _isScoped ? _scopeItems : _items,- isLoadingPage: _isScoped ? false : _isLoadingPage,- hasMore: _isScoped ? false : _hasMore,+ items: _items,+ isLoadingPage: _isLoadingPage,+ hasMore: _hasMore,filter: _filter,genreFilter: _genreFilter,tagFilter: _tagFilter,diff --git a/lib/services/player_settings.dart b/lib/services/player_settings.dartindex d36d2033..59bc0787 100644--- a/lib/services/player_settings.dart+++ b/lib/services/player_settings.dart@@ -495,6 +495,12 @@ class PlayerSettings {static Future<bool> getSeriesSortAsc() => _get('seriesSortAsc', true);static Future<void> setSeriesSortAsc(bool value) => _set('seriesSortAsc', value);+ static Future<String> getListsSort() => _get('listsSort', 'alphabetical');+ static Future<void> setListsSort(String value) => _set('listsSort', value);++ static Future<bool> getListsSortAsc() => _get('listsSortAsc', true);+ static Future<void> setListsSortAsc(bool value) => _set('listsSortAsc', value);+static Future<String> getAuthorSort() => _get('authorSort', 'alphabetical');static Future<void> setAuthorSort(String value) => _set('authorSort', value);diff --git a/lib/widgets/library_grid_tiles.dart b/lib/widgets/library_grid_tiles.dartindex dbd18176..047ff39b 100644--- a/lib/widgets/library_grid_tiles.dart+++ b/lib/widgets/library_grid_tiles.dart@@ -625,6 +625,103 @@ class GridSeriesTileDirect extends StatelessWidget {}}+// ═══════════════════════════════════════════════════════════════+// Grid tile for a collection or playlist (stacked covers + name + count),+// styled like a series tile. Used by the library Lists tab.+// ═══════════════════════════════════════════════════════════════+class GridListTile extends StatelessWidget {+ final String name;+ final List<String> bookIds;+ final int count;+ final bool isPlaylist;+ final double coverAspectRatio;+ final VoidCallback onTap;++ const GridListTile({+ super.key,+ required this.name,+ required this.bookIds,+ required this.count,+ required this.isPlaylist,+ required this.onTap,+ this.coverAspectRatio = 1.0,+ });++ @override+ Widget build(BuildContext context) {+ final cs = Theme.of(context).colorScheme;+ final tt = Theme.of(context).textTheme;+ final l = AppLocalizations.of(context)!;+ final lib = context.watch<LibraryProvider>();++ final coverUrls = bookIds.take(4).map((id) => lib.getCoverUrl(id)).toList();++ double totalProgress = 0;+ int finished = 0;+ for (final id in bookIds) {+ final pd = lib.getProgressData(id);+ if (pd?['isFinished'] == true) {+ finished++;+ totalProgress += 1.0;+ } else {+ totalProgress += lib.getProgress(id);+ }+ }+ final progress = bookIds.isNotEmpty ? totalProgress / bookIds.length : 0.0;++ return GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: onTap,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ _StackedCovers(+ coverUrls: coverUrls.isEmpty ? const [null] : coverUrls,+ numBooks: count,+ mediaHeaders: lib.mediaHeaders,+ cs: cs,+ seriesProgress: progress,+ booksFinished: finished,+ coverAspectRatio: coverAspectRatio,+ ),+ const SizedBox(height: 5),+ Row(+ children: [+ Icon(+ isPlaylist+ ? Icons.playlist_play_rounded+ : Icons.collections_bookmark_rounded,+ size: 12,+ color: cs.onSurfaceVariant),+ const SizedBox(width: 3),+ Expanded(+ child: Text(+ name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: tt.labelSmall?.copyWith(+ fontWeight: FontWeight.w600,+ color: cs.onSurface,+ fontSize: 11,+ ),+ ),+ ),+ ],+ ),+ Text(+ isPlaylist+ ? l.playlistDetailItemCount(count)+ : l.collectionDetailBookCount(count),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant, fontSize: 10),+ ),+ ],+ ),+ );+ }+}+// ═══════════════════════════════════════════════════════════════// Grid author tile (circular avatar + name + book count)// ═══════════════════════════════════════════════════════════════diff --git a/lib/widgets/library_lists_tab.dart b/lib/widgets/library_lists_tab.dartnew file mode 100644index 00000000..484e62d1--- /dev/null+++ b/lib/widgets/library_lists_tab.dart@@ -0,0 +1,131 @@+import 'package:flutter/material.dart';+import '../screens/library_screen.dart';+import 'library_grid_tiles.dart';++/// Library "Lists" tab: a stacked-cover grid of all collections and playlists+/// together (sorted by the screen). Each [entry] carries an injected+/// `_isPlaylist` flag. Tapping a tile opens its detail sheet, like a series.+class LibraryListsTab extends StatelessWidget {+ final List<Map<String, dynamic>> entries;+ final bool isLoading;+ final double coverAspectRatio;+ final void Function(Map<String, dynamic>) onOpenCollection;+ final void Function(Map<String, dynamic>) onOpenPlaylist;+ final Future<void> Function() onRefresh;+ final Widget? headerSliver;+ final ScrollController? scrollController;++ const LibraryListsTab({+ super.key,+ required this.entries,+ required this.coverAspectRatio,+ required this.onOpenCollection,+ required this.onOpenPlaylist,+ required this.onRefresh,+ this.isLoading = false,+ this.headerSliver,+ this.scrollController,+ });++ static List<String> _collectionBookIds(Map<String, dynamic> c) =>+ ((c['books'] as List<dynamic>?) ?? [])+ .whereType<Map<String, dynamic>>()+ .map((b) => b['id'] as String? ?? '')+ .where((id) => id.isNotEmpty)+ .toList();++ static List<String> _playlistBookIds(Map<String, dynamic> p) {+ final ids = <String>[];+ for (final it in (p['items'] as List<dynamic>?) ?? []) {+ if (it is Map<String, dynamic>) {+ final li = it['libraryItem'];+ if (li is Map<String, dynamic>) {+ final id = li['id'] as String? ?? '';+ if (id.isNotEmpty) ids.add(id);+ }+ }+ }+ return ids;+ }++ @override+ Widget build(BuildContext context) {+ final cs = Theme.of(context).colorScheme;+ final tt = Theme.of(context).textTheme;+ final headers = <Widget>[if (headerSliver != null) headerSliver!];++ Widget body;+ if (entries.isEmpty) {+ body = CustomScrollView(+ controller: scrollController,+ physics: const AlwaysScrollableScrollPhysics(),+ slivers: [+ ...headers,+ SliverFillRemaining(+ hasScrollBody: false,+ child: Center(+ child: isLoading+ ? const CircularProgressIndicator()+ : 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 collections or playlists',+ style: tt.bodyLarge+ ?.copyWith(color: cs.onSurfaceVariant)),+ ],+ ),+ ),+ ),+ ],+ );+ } else {+ body = CustomScrollView(+ controller: scrollController,+ physics: const AlwaysScrollableScrollPhysics(),+ slivers: [+ ...headers,+ SliverPadding(+ padding: const EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding),+ sliver: SliverGrid(+ gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(+ crossAxisCount: responsiveGridCount(context),+ childAspectRatio: coverAspectRatio < 1 ? 0.48 : 0.68,+ crossAxisSpacing: 10,+ mainAxisSpacing: 10,+ ),+ delegate: SliverChildBuilderDelegate(+ (context, index) {+ final entry = entries[index];+ final isPlaylist = entry['_isPlaylist'] == true;+ final name = entry['name'] as String? ?? '';+ final ids = isPlaylist+ ? _playlistBookIds(entry)+ : _collectionBookIds(entry);+ final count = isPlaylist+ ? (entry['items'] as List<dynamic>?)?.length ?? ids.length+ : (entry['books'] as List<dynamic>?)?.length ?? ids.length;+ return GridListTile(+ name: name,+ bookIds: ids,+ count: count,+ isPlaylist: isPlaylist,+ coverAspectRatio: coverAspectRatio,+ onTap: () =>+ isPlaylist ? onOpenPlaylist(entry) : onOpenCollection(entry),+ );+ },+ childCount: entries.length,+ ),+ ),+ ),+ ],+ );+ }++ return RefreshIndicator(onRefresh: onRefresh, child: body);+ }+}diff --git a/lib/widgets/library_sort_filter_sheet.dart b/lib/widgets/library_sort_filter_sheet.dartindex 0d3fe5da..9572f8de 100644--- a/lib/widgets/library_sort_filter_sheet.dart+++ b/lib/widgets/library_sort_filter_sheet.dart@@ -4,7 +4,7 @@ import '../l10n/app_localizations.dart';import '../screens/library_screen.dart';/// Which library tab the sort/filter sheet is being shown for.-enum LibraryTab { library, series, authors, narrators }+enum LibraryTab { library, series, authors, narrators, lists }// ═══════════════════════════════════════════════════════════════// Sort & Filter bottom sheet with tabs@@ -33,12 +33,6 @@ class SortFilterSheet extends StatefulWidget {/// callers don't have to pass it; null = no filter active.final SeriesFilter currentSeriesFilter;final void Function(SeriesFilter)? onSeriesFilterChanged;- /// Collections + playlists for the Library tab's "Lists" tab. Tapping one- /// scopes the library page to that list's items (handled by the screen).- final List<Map<String, dynamic>> collections;- final List<Map<String, dynamic>> playlists;- final void Function(Map<String, dynamic>)? onOpenCollection;- final void Function(Map<String, dynamic>)? onOpenPlaylist;const SortFilterSheet({super.key,@@ -55,10 +49,6 @@ class SortFilterSheet extends StatefulWidget {this.onUpcomingReleases,this.currentSeriesFilter = SeriesFilter.none,this.onSeriesFilterChanged,- this.collections = const [],- this.playlists = const [],- this.onOpenCollection,- this.onOpenPlaylist,});@override@@ -80,17 +70,11 @@ class _SortFilterSheetState extends State<SortFilterSheet> with SingleTickerProvwidget.currentFilter != LibraryFilter.none ||widget.currentSeriesFilter != SeriesFilter.none;- bool get _showListsTab =>- widget.libraryTab == LibraryTab.library &&- (widget.collections.isNotEmpty || widget.playlists.isNotEmpty);-- int get _listsTabIndex => 1 + (_showFilterTab ? 1 : 0);-@overridevoid initState() {super.initState();_collapseSeries = widget.collapseSeries;- final tabCount = 1 + (_showFilterTab ? 1 : 0) + (_showListsTab ? 1 : 0);+ final tabCount = 1 + (_showFilterTab ? 1 : 0);_tabCtrl = TabController(length: tabCount, vsync: this,initialIndex: widget.initialTab.clamp(0, tabCount - 1),@@ -156,20 +140,14 @@ class _SortFilterSheetState extends State<SortFilterSheet> with SingleTickerProvTab(child: Row(mainAxisSize: MainAxisSize.min, children: [Icon(Icons.filter_list_rounded, size: 18), const SizedBox(width: 6),Text(_anyFilterActive ? l.filterActive : l.filter)])),- if (_showListsTab)- Tab(child: Row(mainAxisSize: MainAxisSize.min, children: [- Icon(Icons.collections_bookmark_rounded, size: 18), const SizedBox(width: 6),- const Text('Lists')])),];List<Widget> _buildViews(ColorScheme cs, AppLocalizations l) => [_buildSortTab(cs, l),if (_showFilterTab) _buildFilterTab(cs, l),- if (_showListsTab) _buildListsTab(cs, l),];double _calcHeight() {- if (_showListsTab && _tabCtrl.index == _listsTabIndex) return 440;if (widget.libraryTab == LibraryTab.series) {// Need extra room when the filter tab is showing on series.if (_showFilterTab && _tabCtrl.index == 1) return 280;@@ -177,6 +155,7 @@ class _SortFilterSheetState extends State<SortFilterSheet> with SingleTickerProv}if (widget.libraryTab == LibraryTab.authors) return 180;if (widget.libraryTab == LibraryTab.narrators) return 130;+ if (widget.libraryTab == LibraryTab.lists) return 230;if (_genreExpanded || _tagExpanded) return 420;return widget.isPodcastLibrary ? 200 : 440;}@@ -292,6 +271,12 @@ class _SortFilterSheetState extends State<SortFilterSheet> with SingleTickerProvreturn [(LibrarySort.alphabetical, l.name, Icons.sort_by_alpha_rounded),];+ case LibraryTab.lists:+ return [+ (LibrarySort.alphabetical, l.name, Icons.sort_by_alpha_rounded),+ (LibrarySort.recentlyAdded, l.dateAdded, Icons.schedule_rounded),+ (LibrarySort.totalDuration, l.numberOfBooks, Icons.format_list_numbered_rounded),+ ];case LibraryTab.library:if (widget.isPodcastLibrary) {return [@@ -450,42 +435,6 @@ class _SortFilterSheetState extends State<SortFilterSheet> with SingleTickerProv);}- Widget _buildListsTab(ColorScheme cs, AppLocalizations l) {- return ListView(- padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),- children: [- if (widget.collections.isNotEmpty) ...[- _listsHeader(cs, 'Collections'),- ...widget.collections.map((c) => SheetOption(- icon: Icons.collections_bookmark_rounded,- label: (c['name'] as String?) ?? '',- selected: false,- selectedColor: cs.secondary,- marquee: true,- onTap: () => widget.onOpenCollection?.call(c),- )),- ],- if (widget.playlists.isNotEmpty) ...[- _listsHeader(cs, 'Playlists'),- ...widget.playlists.map((p) => SheetOption(- icon: Icons.playlist_play_rounded,- label: (p['name'] as String?) ?? '',- selected: false,- selectedColor: cs.secondary,- marquee: true,- onTap: () => widget.onOpenPlaylist?.call(p),- )),- ],- ],- );- }-- Widget _listsHeader(ColorScheme cs, String text) => Padding(- padding: const EdgeInsets.fromLTRB(4, 8, 4, 6),- child: Text(text, style: TextStyle(- fontSize: 12, fontWeight: FontWeight.w700,- color: cs.onSurfaceVariant.withValues(alpha: 0.7), letterSpacing: 0.5)),- );}class SheetOption extends StatelessWidget {