Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add playlists, collections, and customizable home screen

Nathan Poulson2bb2348c6b15
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 5bd96080..594b844f 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -52,6 +52,21 @@ class LibraryProvider extends ChangeNotifier {
'listen-again',
];
+ // Playlists
+ List<dynamic> _playlists = [];
+ bool _isLoadingPlaylists = false;
+ Future<void>? _playlistsInFlight;
+
+ // Collections
+ List<dynamic> _collections = [];
+ bool _isLoadingCollections = false;
+ Future<void>? _collectionsInFlight;
+
+ // Section customization
+ List<String> _sectionOrder = [];
+ Set<String> _hiddenSectionIds = {};
+ bool _applyDefaultPlaylistCollectionHiding = false;
+
// Per-series/show rolling download opt-in
Set<String> _rollingDownloadSeries = {};
@@ -178,9 +193,14 @@ class LibraryProvider extends ChangeNotifier {
/// Build home sections from downloaded books.
void _buildOfflineSections() {
- final downloads = DownloadService().downloadedItems;
+ final isPodcast = isPodcastLibrary;
+ // Only show downloads matching the current library type
+ final allDownloads = DownloadService().downloadedItems;
+ final downloads = allDownloads
+ .where((dl) => (dl.itemId.length > 36) == isPodcast)
+ .toList();
debugPrint(
- '[Library] Building offline sections: ${downloads.length} downloads');
+ '[Library] Building offline sections: ${downloads.length}/${allDownloads.length} downloads (${isPodcast ? "podcast" : "book"})');
if (downloads.isEmpty) {
_personalizedSections = [];
_errorMessage = null;
@@ -189,8 +209,11 @@ class LibraryProvider extends ChangeNotifier {
return;
}
- // Build fake entities from download metadata
- final entities = <Map<String, dynamic>>[];
+ // Build fake entities from download metadata.
+ // Split in-progress downloads into a continue-listening section so Home
+ // can show them as compact cards, while the rest go to downloaded-books.
+ final continueEntities = <Map<String, dynamic>>[];
+ final downloadedEntities = <Map<String, dynamic>>[];
for (final dl in downloads) {
// Try to extract duration from cached session data
double duration = 0;
@@ -208,10 +231,11 @@ class LibraryProvider extends ChangeNotifier {
// Podcast downloads use compound key "showId-episodeId"
final isCompound = dl.itemId.length > 36;
+ late final Map<String, dynamic> entity;
if (isCompound) {
final showId = dl.itemId.substring(0, 36);
final episodeId = dl.itemId.substring(37);
- entities.add({
+ entity = {
'id': showId,
'_absorbingKey': dl.itemId,
'recentEpisode': {
@@ -226,9 +250,9 @@ class LibraryProvider extends ChangeNotifier {
'duration': duration,
'chapters': chapters,
},
- });
+ };
} else {
- entities.add({
+ entity = {
'id': dl.itemId,
'media': {
'metadata': {
@@ -238,18 +262,39 @@ class LibraryProvider extends ChangeNotifier {
'duration': duration,
'chapters': chapters,
},
- });
+ };
+ }
+
+ final progress = _resetItems.contains(dl.itemId)
+ ? 0.0
+ : _localProgressOverrides[dl.itemId] ??
+ (_progressMap[dl.itemId]?['progress'] as num?)?.toDouble() ??
+ 0.0;
+ final isFinished =
+ _progressMap[dl.itemId]?['isFinished'] == true || progress >= 0.999;
+
+ if (progress > 0 && !isFinished) {
+ continueEntities.add(entity);
+ } else {
+ downloadedEntities.add(entity);
}
}
- final isPodcast = isPodcastLibrary;
_personalizedSections = [
- {
- 'id': 'downloaded-books',
- 'label': isPodcast ? 'Downloaded Episodes' : 'Downloaded Books',
- 'type': isPodcast ? 'podcast' : 'book',
- 'entities': entities,
- },
+ if (continueEntities.isNotEmpty)
+ {
+ 'id': 'continue-listening',
+ 'label': 'Continue Listening',
+ 'type': isPodcast ? 'podcast' : 'book',
+ 'entities': continueEntities,
+ },
+ if (downloadedEntities.isNotEmpty)
+ {
+ 'id': 'downloaded-books',
+ 'label': isPodcast ? 'Downloaded Episodes' : 'Downloaded Books',
+ 'type': isPodcast ? 'podcast' : 'book',
+ 'entities': downloadedEntities,
+ },
];
_errorMessage = null;
_isLoading = false;
@@ -266,6 +311,12 @@ class LibraryProvider extends ChangeNotifier {
bool get isLoading => _isLoading;
bool get isLoadingSeries => _isLoadingSeries;
String? get errorMessage => _errorMessage;
+ List<dynamic> get playlists => _playlists;
+ bool get isLoadingPlaylists => _isLoadingPlaylists;
+ List<dynamic> get collections => _collections;
+ bool get isLoadingCollections => _isLoadingCollections;
+ List<String> get sectionOrder => _sectionOrder;
+ Set<String> get hiddenSectionIds => _hiddenSectionIds;
/// Get progress (0.0–1.0) for a library item by ID.
/// Checks local progress first (freshest), falls back to server data.
@@ -729,6 +780,7 @@ class LibraryProvider extends ChangeNotifier {
/// Handle collection changes from socket.
void _onRemoteCollectionUpdated() {
loadPersonalizedView(force: true);
+ loadCollections();
}
/// Handle current user updated from socket.
@@ -813,6 +865,7 @@ class LibraryProvider extends ChangeNotifier {
? bookLibraries.first['id']
: _libraries.first['id'];
}
+ await _loadSectionPrefs();
await loadPersonalizedView(force: true);
}
} catch (e) {
@@ -836,7 +889,10 @@ class LibraryProvider extends ChangeNotifier {
Future<void> selectLibrary(String libraryId) async {
_selectedLibraryId = libraryId;
_series = [];
+ _playlists = [];
+ _collections = [];
await ScopedPrefs.setString('last_selected_library', libraryId);
+ await _loadSectionPrefs();
notifyListeners();
await loadPersonalizedView(force: true);
AndroidAutoService().refresh(force: true);
@@ -912,6 +968,10 @@ class LibraryProvider extends ChangeNotifier {
if (isPodcastLibrary) {
_hydrateRssFeedFieldsDeferred();
}
+
+ // Load playlists and collections alongside personalized view
+ loadPlaylists();
+ loadCollections();
} catch (e) {
if (_isLikelyNetworkError(e)) {
_goOffline();
@@ -1176,6 +1236,347 @@ class LibraryProvider extends ChangeNotifier {
notifyListeners();
}
+ // ── Playlists ──────────────────────────────────────────────────────────
+
+ Future<void> loadPlaylists({bool force = false}) async {
+ if (_api == null || _selectedLibraryId == null || isOffline) return;
+
+ final existing = _playlistsInFlight;
+ if (existing != null) {
+ await existing;
+ return;
+ }
+
+ final inFlight = _doLoadPlaylists();
+ _playlistsInFlight = inFlight;
+ try {
+ await inFlight;
+ } finally {
+ if (identical(_playlistsInFlight, inFlight)) {
+ _playlistsInFlight = null;
+ }
+ }
+ }
+
+ Future<void> _doLoadPlaylists() async {
+ _isLoadingPlaylists = true;
+ try {
+ _playlists = await _api!.getLibraryPlaylists(_selectedLibraryId!);
+ } catch (_) {}
+ _isLoadingPlaylists = false;
+ notifyListeners();
+ }
+
+ Future<Map<String, dynamic>?> createPlaylist(String name) async {
+ if (_api == null || _selectedLibraryId == null) return null;
+ final result = await _api!.createPlaylist(_selectedLibraryId!, name);
+ if (result != null) {
+ _playlists = [..._playlists, result];
+ notifyListeners();
+ }
+ return result;
+ }
+
+ Future<bool> addToPlaylist(
+ String playlistId,
+ String libraryItemId, {
+ String? episodeId,
+ }) async {
+ if (_api == null) return false;
+ final updated = await _api!.addItemToPlaylist(
+ playlistId, libraryItemId, episodeId: episodeId,
+ );
+ if (updated != null) {
+ // Reload full playlist data to get populated libraryItem fields
+ await _doLoadPlaylists();
+ return true;
+ }
+ return false;
+ }
+
+ Future<bool> removeFromPlaylist(
+ String playlistId,
+ String libraryItemId, {
+ String? episodeId,
+ }) async {
+ if (_api == null) return false;
+ final updated = await _api!.removeItemFromPlaylist(
+ playlistId, libraryItemId, episodeId: episodeId,
+ );
+ if (updated != null) {
+ await _doLoadPlaylists();
+ return true;
+ }
+ return false;
+ }
+
+ Future<bool> reorderPlaylistItems(
+ String playlistId,
+ List<Map<String, dynamic>> reorderedItems,
+ ) async {
+ if (_api == null) return false;
+ // Send just libraryItemId + episodeId for each item
+ final itemRefs = reorderedItems.map((item) {
+ final ref = <String, dynamic>{'libraryItemId': item['libraryItemId']};
+ final eid = item['episodeId'] as String?;
+ if (eid != null) ref['episodeId'] = eid;
+ return ref;
+ }).toList();
+ final updated = await _api!.updatePlaylist(playlistId, items: itemRefs);
+ if (updated != null) {
+ await _doLoadPlaylists();
+ return true;
+ }
+ return false;
+ }
+
+ Future<bool> deletePlaylist(String playlistId) async {
+ if (_api == null) return false;
+ final ok = await _api!.deletePlaylist(playlistId);
+ if (ok) {
+ _playlists = _playlists.where((p) => (p as Map)['id'] != playlistId).toList();
+ _hiddenSectionIds.remove('playlist:$playlistId');
+ _sectionOrder.remove('playlist:$playlistId');
+ await _saveSectionPrefs();
+ notifyListeners();
+ }
+ return ok;
+ }
+
+ // ── Collections ──────────────────────────────────────────────────────
+
+ Future<void> loadCollections({bool force = false}) async {
+ if (_api == null || _selectedLibraryId == null || isOffline) return;
+
+ final existing = _collectionsInFlight;
+ if (existing != null) {
+ await existing;
+ return;
+ }
+
+ final inFlight = _doLoadCollections();
+ _collectionsInFlight = inFlight;
+ try {
+ await inFlight;
+ } finally {
+ if (identical(_collectionsInFlight, inFlight)) {
+ _collectionsInFlight = null;
+ }
+ }
+ }
+
+ Future<void> _doLoadCollections() async {
+ _isLoadingCollections = true;
+ try {
+ _collections = await _api!.getLibraryCollections(_selectedLibraryId!);
+ } catch (_) {}
+ _isLoadingCollections = false;
+ notifyListeners();
+ }
+
+ Future<Map<String, dynamic>?> createCollection(String name, {List<String> books = const []}) async {
+ if (_api == null || _selectedLibraryId == null) return null;
+ final result = await _api!.createCollection(_selectedLibraryId!, name, books: books);
+ if (result != null) {
+ await _doLoadCollections();
+ }
+ return result;
+ }
+
+ Future<bool> addToCollection(String collectionId, String libraryItemId) async {
+ if (_api == null) return false;
+ final updated = await _api!.addBookToCollection(collectionId, libraryItemId);
+ if (updated != null) {
+ await _doLoadCollections();
+ return true;
+ }
+ return false;
+ }
+
+ Future<bool> removeFromCollection(String collectionId, String libraryItemId) async {
+ if (_api == null) return false;
+ final updated = await _api!.removeBookFromCollection(collectionId, libraryItemId);
+ if (updated != null) {
+ await _doLoadCollections();
+ return true;
+ }
+ return false;
+ }
+
+ Future<bool> reorderCollectionBooks(
+ String collectionId,
+ List<String> bookIds,
+ ) async {
+ if (_api == null) return false;
+ final updated = await _api!.updateCollection(collectionId, books: bookIds);
+ if (updated != null) {
+ await _doLoadCollections();
+ return true;
+ }
+ return false;
+ }
+
+ Future<bool> deleteCollection(String collectionId) async {
+ if (_api == null) return false;
+ final ok = await _api!.deleteCollection(collectionId);
+ if (ok) {
+ _collections = _collections.where((c) => (c as Map)['id'] != collectionId).toList();
+ _hiddenSectionIds.remove('collection:$collectionId');
+ _sectionOrder.remove('collection:$collectionId');
+ await _saveSectionPrefs();
+ notifyListeners();
+ }
+ return ok;
+ }
+
+ // ── Section Customization ─────────────────────────────────────────────
+
+ Future<void> _loadSectionPrefs() async {
+ final libId = _selectedLibraryId ?? '';
+ final orderJson = await ScopedPrefs.getStringList('home_section_order_$libId');
+ final hiddenJson = await ScopedPrefs.getStringList('home_hidden_sections_$libId');
+ _sectionOrder = orderJson.toList();
+ // If user has never customized (both order and hidden are empty),
+ // apply default hidden sections plus all playlists/collections
+ if (hiddenJson.isEmpty && orderJson.isEmpty) {
+ _hiddenSectionIds = Set<String>.from(_defaultHiddenSections);
+ _applyDefaultPlaylistCollectionHiding = true;
+ } else {
+ _hiddenSectionIds = hiddenJson.toSet();
+ _applyDefaultPlaylistCollectionHiding = false;
+ }
+ }
+
+ Future<void> _saveSectionPrefs() async {
+ final libId = _selectedLibraryId ?? '';
+ await ScopedPrefs.setStringList('home_section_order_$libId', _sectionOrder);
+ await ScopedPrefs.setStringList('home_hidden_sections_$libId', _hiddenSectionIds.toList());
+ }
+
+ Future<void> saveSectionOrder(List<String> order) async {
+ _sectionOrder = List<String>.from(order);
+ _applyDefaultPlaylistCollectionHiding = false;
+ await _saveSectionPrefs();
+ notifyListeners();
+ }
+
+ Future<void> toggleSectionVisibility(String sectionId) async {
+ final updated = Set<String>.from(_hiddenSectionIds);
+ if (updated.contains(sectionId)) {
+ updated.remove(sectionId);
+ } else {
+ updated.add(sectionId);
+ }
+ _hiddenSectionIds = updated;
+ await _saveSectionPrefs();
+ notifyListeners();
+ }
+
+ // Sections hidden by default (low-value ABS sections)
+ static const _defaultHiddenSections = {'newest-authors', 'recent-series'};
+
+ /// Merge server sections + playlist sections, apply user ordering and visibility.
+ List<Map<String, dynamic>> getOrderedHomeSections() {
+ // Collect all available section IDs
+ final allSections = <String, Map<String, dynamic>>{};
+
+ // Server sections
+ for (final s in _personalizedSections) {
+ final id = (s as Map)['id'] as String? ?? '';
+ if (id.isEmpty) continue;
+ allSections[id] = Map<String, dynamic>.from(s);
+ }
+
+ // Playlist sections
+ for (final p in _playlists) {
+ final pm = p as Map<String, dynamic>;
+ final id = 'playlist:${pm['id']}';
+ allSections[id] = {
+ 'id': id,
+ 'label': pm['name'] ?? 'Playlist',
+ 'type': 'playlist',
+ 'entities': (pm['items'] as List<dynamic>?) ?? [],
+ '_playlistId': pm['id'],
+ };
+ }
+
+ // Collection sections
+ for (final c in _collections) {
+ final cm = c as Map<String, dynamic>;
+ final id = 'collection:${cm['id']}';
+ allSections[id] = {
+ 'id': id,
+ 'label': 'Server Collection - ${cm['name'] ?? 'Collection'}',
+ 'type': 'collection',
+ 'entities': (cm['books'] as List<dynamic>?) ?? [],
+ '_collectionId': cm['id'],
+ };
+ }
+
+ // Filter hidden
+ allSections.removeWhere((id, _) => _hiddenSectionIds.contains(id));
+ // When user hasn't customized, hide playlists/collections by default
+ if (_applyDefaultPlaylistCollectionHiding) {
+ allSections.removeWhere((id, _) =>
+ id.startsWith('playlist:') || id.startsWith('collection:'));
+ }
+
+ // Order
+ if (_sectionOrder.isEmpty) {
+ // Default: server sections in their natural order, playlists/collections after
+ final result = <Map<String, dynamic>>[];
+ for (final s in _personalizedSections) {
+ final id = (s as Map)['id'] as String? ?? '';
+ if (allSections.containsKey(id)) result.add(allSections[id]!);
+ }
+ for (final p in _playlists) {
+ final id = 'playlist:${(p as Map)['id']}';
+ if (allSections.containsKey(id)) result.add(allSections[id]!);
+ }
+ for (final c in _collections) {
+ final id = 'collection:${(c as Map)['id']}';
+ if (allSections.containsKey(id)) result.add(allSections[id]!);
+ }
+ return result;
+ }
+
+ final result = <Map<String, dynamic>>[];
+ // Ordered items first
+ for (final id in _sectionOrder) {
+ if (allSections.containsKey(id)) {
+ result.add(allSections.remove(id)!);
+ }
+ }
+ // Remaining items (new sections not yet in order) at the end
+ result.addAll(allSections.values);
+ return result;
+ }
+
+ /// All available section IDs and labels (for customize sheet).
+ List<Map<String, String>> getAllSectionMeta() {
+ final result = <Map<String, String>>[];
+ for (final s in _personalizedSections) {
+ final id = (s as Map)['id'] as String? ?? '';
+ final label = s['label'] as String? ?? id;
+ if (id.isNotEmpty) result.add({'id': id, 'label': label});
+ }
+ for (final p in _playlists) {
+ final pm = p as Map<String, dynamic>;
+ result.add({
+ 'id': 'playlist:${pm['id']}',
+ 'label': pm['name'] as String? ?? 'Playlist',
+ });
+ }
+ for (final c in _collections) {
+ final cm = c as Map<String, dynamic>;
+ result.add({
+ 'id': 'collection:${cm['id']}',
+ 'label': 'Server Collection - ${cm['name'] as String? ?? 'Collection'}',
+ });
+ }
+ return result;
+ }
+
/// Register an item's updatedAt timestamp for cover cache-busting.
void registerUpdatedAt(String id, int ts) => _itemUpdatedAt[id] = ts;
diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart
index b41a9117..c48dbca8 100644
--- a/lib/screens/home_screen.dart
+++ b/lib/screens/home_screen.dart
@@ -13,6 +13,9 @@ import '../widgets/book_detail_sheet.dart';
import '../widgets/card_buttons.dart';
import '../widgets/episode_list_sheet.dart';
import '../main.dart' show oledNotifier;
+import '../widgets/home_customize_sheet.dart';
+import '../widgets/playlist_detail_sheet.dart';
+import '../widgets/collection_detail_sheet.dart';
import 'app_shell.dart';
class HomeScreen extends StatefulWidget {
@@ -27,9 +30,13 @@ class _HomeScreenState extends State<HomeScreen> {
bool _hideEbookOnly = false;
// Cached filtered sections — invalidated when source data or settings change.
- List<dynamic>? _cachedSections;
+ List<Map<String, dynamic>>? _cachedSections;
List<dynamic>? _cachedClItems;
List<dynamic>? _lastSectionsRef;
+ List<dynamic>? _lastPlaylistsRef;
+ List<dynamic>? _lastCollectionsRef;
+ List<String>? _lastSectionOrder;
+ Set<String>? _lastHiddenIds;
bool _lastHideEbook = false;
bool _lastIsPodcast = false;
@@ -78,14 +85,26 @@ class _HomeScreenState extends State<HomeScreen> {
/// Recompute cached filtered sections only when input data changes.
void _refreshFilteredCache(LibraryProvider lib) {
final sections = lib.personalizedSections;
+ final playlists = lib.playlists;
+ final collections = lib.collections;
final isPod = lib.isPodcastLibrary;
+ final sectionOrder = lib.sectionOrder;
+ final hiddenIds = lib.hiddenSectionIds;
if (identical(sections, _lastSectionsRef) &&
+ identical(playlists, _lastPlaylistsRef) &&
+ identical(collections, _lastCollectionsRef) &&
+ identical(sectionOrder, _lastSectionOrder) &&
+ identical(hiddenIds, _lastHiddenIds) &&
_hideEbookOnly == _lastHideEbook &&
isPod == _lastIsPodcast &&
_cachedSections != null) {
return; // cache is still valid
}
_lastSectionsRef = sections;
+ _lastPlaylistsRef = playlists;
+ _lastCollectionsRef = collections;
+ _lastSectionOrder = sectionOrder;
+ _lastHiddenIds = hiddenIds;
_lastHideEbook = _hideEbookOnly;
_lastIsPodcast = isPod;
@@ -106,7 +125,7 @@ class _HomeScreenState extends State<HomeScreen> {
}).toList();
}
_cachedClItems = clItems;
- _cachedSections = _sortSections(sections);
+ _cachedSections = lib.getOrderedHomeSections();
}
@override
@@ -212,17 +231,6 @@ class _HomeScreenState extends State<HomeScreen> {
);
}
- static const _prioritySections = [
- 'continue-listening',
- 'continue-series',
- 'episodes-recently-added',
- 'recently-added',
- 'discover',
- 'listen-again',
- ];
-
- static const _hiddenSections = {'newest-authors', 'recent-series'};
-
static const _sectionLabels = {
'continue-listening': 'Continue Listening',
'continue-series': 'Continue Series',
@@ -243,16 +251,6 @@ class _HomeScreenState extends State<HomeScreen> {
'downloaded-books': Icons.download_done_rounded,
};
- List<dynamic> _sortSections(List<dynamic> sections) {
- final sorted = List<dynamic>.from(sections);
- sorted.sort((a, b) {
- final aIdx = _prioritySections.indexOf(a['id'] ?? '');
- final bIdx = _prioritySections.indexOf(b['id'] ?? '');
- return (aIdx == -1 ? 999 : aIdx).compareTo(bIdx == -1 ? 999 : bIdx);
- });
- return sorted;
- }
-
String _titleCase(String s) {
return s
.replaceAll('-', ' ')
@@ -363,7 +361,7 @@ class _HomeScreenState extends State<HomeScreen> {
),
),
),
- if (!lib.isOffline && allLibraries.length > 1)
+ if (allLibraries.length > 1)
Material(
color: cs.onSurface.withValues(alpha: 0.06),
borderRadius: BorderRadius.circular(20),
@@ -410,68 +408,24 @@ class _HomeScreenState extends State<HomeScreen> {
),
),
),
+ if (!lib.isOffline)
+ GestureDetector(
+ onTap: () => HomeCustomizeSheet.show(context),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(20),
+ border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),
+ ),
+ child: Icon(Icons.tune_rounded, size: 14, color: cs.onSurfaceVariant),
+ ),
+ ),
],
),
),
- // ── Currently Absorbing section ──
- if (!lib.isLoading)
- ...() {
- final clItems = _cachedClItems ?? [];
- if (clItems.isEmpty) return <Widget>[];
- return <Widget>[
- SliverToBoxAdapter(
- child: Padding(
- padding: const EdgeInsets.fromLTRB(20, 24, 20, 0),
- child: Row(
- children: [
- Icon(Icons.play_circle_outline_rounded,
- size: 16,
- color: cs.primary.withValues(alpha: 0.7)),
- const SizedBox(width: 8),
- Text('Continue Listening',
- style: tt.titleSmall?.copyWith(
- fontWeight: FontWeight.w500,
- color: cs.onSurface.withValues(alpha: 0.8),
- letterSpacing: 0.3,
- )),
- const SizedBox(width: 12),
- Expanded(
- child: Container(
- height: 0.5,
- color: cs.outlineVariant
- .withValues(alpha: 0.2))),
- ],
- ),
- ),
- ),
- SliverToBoxAdapter(
- child: Padding(
- padding: const EdgeInsets.only(top: 12),
- child: SizedBox(
- height: 92,
- child: ListView.separated(
- scrollDirection: Axis.horizontal,
- padding:
- const EdgeInsets.symmetric(horizontal: 20),
- physics: const BouncingScrollPhysics(),
- itemCount: clItems.length,
- separatorBuilder: (_, __) =>
- const SizedBox(width: 10),
- itemBuilder: (context, i) {
- final item = clItems[i] as Map<String, dynamic>;
- return _ContinueListeningCard(
- item: item,
- lib: lib,
- player: _player,
- );
- },
- ),
- ),
- ),
- ),
- ];
- }(),
+ // (Continue Listening is now rendered in the generic sections loop below)
// ── Loading shimmer ──
if (lib.isLoading) ...[
@@ -547,31 +501,100 @@ class _HomeScreenState extends State<HomeScreen> {
),
),
- // ── Other sections ──
+ // ── All sections (including Continue Listening) ──
if (!lib.isLoading)
- ...(_cachedSections ?? []).map((section) {
- final id = section['id'] ?? '';
- if (id == 'continue-listening' ||
- _hiddenSections.contains(id)) {
- return const SliverToBoxAdapter();
+ ...(_cachedSections ?? []).expand((section) {
+ final id = section['id'] as String? ?? '';
+ final isPlaylist = id.startsWith('playlist:');
+ final isCollection = id.startsWith('collection:');
+
+ // Playlists/collections are server-only; hide when offline
+ if ((isPlaylist || isCollection) && lib.isOffline) return <Widget>[];
+
+ // Continue Listening gets its own compact card layout
+ if (id == 'continue-listening') {
+ final clItems = _cachedClItems ?? [];
+ if (clItems.isEmpty) return <Widget>[];
+ return <Widget>[
+ SliverToBoxAdapter(
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(20, 24, 20, 0),
+ child: Row(children: [
+ Icon(Icons.play_circle_outline_rounded,
+ size: 16, color: cs.primary.withValues(alpha: 0.7)),
+ const SizedBox(width: 8),
+ Text('Continue Listening',
+ style: tt.titleSmall?.copyWith(
+ fontWeight: FontWeight.w500,
+ color: cs.onSurface.withValues(alpha: 0.8),
+ letterSpacing: 0.3,
+ )),
+ const SizedBox(width: 12),
+ Expanded(child: Container(height: 0.5,
+ color: cs.outlineVariant.withValues(alpha: 0.2))),
+ ]),
+ ),
+ ),
+ SliverToBoxAdapter(
+ child: Padding(
+ padding: const EdgeInsets.only(top: 12),
+ child: SizedBox(
+ height: 92,
+ child: ListView.separated(
+ scrollDirection: Axis.horizontal,
+ padding: const EdgeInsets.symmetric(horizontal: 20),
+ physics: const BouncingScrollPhysics(),
+ itemCount: clItems.length,
+ separatorBuilder: (_, __) => const SizedBox(width: 10),
+ itemBuilder: (context, i) {
+ final item = clItems[i] as Map<String, dynamic>;
+ return _ContinueListeningCard(
+ item: item, lib: lib, player: _player,
+ );
+ },
+ ),
+ ),
+ ),
+ ),
+ ];
}
+
final label = section['label'] ??
_sectionLabels[id] ??
_titleCase(id);
final entities = _filterEbookOnly(
(section['entities'] as List<dynamic>?) ?? []);
- final type = section['type'] ?? 'book';
- if (entities.isEmpty) return const SliverToBoxAdapter();
-
- return SliverToBoxAdapter(
- child: HomeSection(
- title: label,
- icon: _sectionIcons[id] ?? Icons.album_outlined,
- entities: entities,
- sectionType: type,
- sectionId: id,
+ final type = isPlaylist ? 'playlist'
+ : isCollection ? 'collection'
+ : (section['type'] ?? 'book');
+ if (entities.isEmpty) return <Widget>[];
+
+ VoidCallback? titleTap;
+ IconData sectionIcon;
+ if (isPlaylist) {
+ titleTap = () => PlaylistDetailSheet.show(
+ context, section['_playlistId'] as String);
+ sectionIcon = Icons.playlist_play_rounded;
+ } else if (isCollection) {
+ titleTap = () => CollectionDetailSheet.show(
+ context, section['_collectionId'] as String);
+ sectionIcon = Icons.collections_bookmark_rounded;
+ } else {
+ sectionIcon = _sectionIcons[id] ?? Icons.album_outlined;
+ }
+
+ return <Widget>[
+ SliverToBoxAdapter(
+ child: HomeSection(
+ title: label,
+ icon: sectionIcon,
+ entities: entities,
+ sectionType: type,
+ sectionId: id,
+ onTitleTap: titleTap,
+ ),
),
- );
+ ];
}),
const SliverPadding(padding: EdgeInsets.only(bottom: 100)),
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index 3a50c9ce..d844bfec 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -1356,4 +1356,261 @@ class ApiService {
} catch (e) { debugPrint('deletePodcastEpisode error: $e'); }
return false;
}
+
+ // ── Playlists ──────────────────────────────────────────────────────────
+
+ /// GET /api/libraries/:libraryId/playlists
+ Future<List<dynamic>> getLibraryPlaylists(String libraryId) async {
+ try {
+ final resp = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/playlists'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+ if (resp.statusCode == 200) {
+ final data = jsonDecode(resp.body);
+ return (data['results'] as List<dynamic>?) ?? [];
+ }
+ } catch (_) {}
+ return [];
+ }
+
+ /// GET /api/playlists/:id
+ Future<Map<String, dynamic>?> getPlaylist(String playlistId) async {
+ try {
+ final resp = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/playlists/$playlistId'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 10));
+ if (resp.statusCode == 200) {
+ return jsonDecode(resp.body) as Map<String, dynamic>;
+ }
+ } catch (_) {}
+ return null;
+ }
+
+ /// POST /api/playlists
+ Future<Map<String, dynamic>?> createPlaylist(
+ String libraryId,
+ String name, {
+ List<Map<String, dynamic>> items = const [],
+ }) async {
+ try {
+ final resp = await http.post(
+ Uri.parse('$_cleanBaseUrl/api/playlists'),
+ headers: _headers,
+ body: jsonEncode({
+ 'libraryId': libraryId,
+ 'name': name,
+ 'items': items,
+ }),
+ ).timeout(const Duration(seconds: 10));
+ if (resp.statusCode == 200) {
+ return jsonDecode(resp.body) as Map<String, dynamic>;
+ }
+ } catch (_) {}
+ return null;
+ }
+
+ /// PATCH /api/playlists/:id
+ Future<Map<String, dynamic>?> updatePlaylist(
+ String playlistId, {
+ String? name,
+ List<Map<String, dynamic>>? items,
+ }) async {
+ try {
+ final body = <String, dynamic>{};
+ if (name != null) body['name'] = name;
+ if (items != null) body['items'] = items;
+ final resp = await http.patch(
+ Uri.parse('$_cleanBaseUrl/api/playlists/$playlistId'),
+ headers: _headers,
+ body: jsonEncode(body),
+ ).timeout(const Duration(seconds: 10));
+ if (resp.statusCode == 200) {
+ return jsonDecode(resp.body) as Map<String, dynamic>;
+ }
+ } catch (_) {}
+ return null;
+ }
+
+ /// DELETE /api/playlists/:id
+ Future<bool> deletePlaylist(String playlistId) async {
+ try {
+ final resp = await http.delete(
+ Uri.parse('$_cleanBaseUrl/api/playlists/$playlistId'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 10));
+ return resp.statusCode == 200;
+ } catch (_) {}
+ return false;
+ }
+
+ /// POST /api/playlists/:id/item
+ Future<Map<String, dynamic>?> addItemToPlaylist(
+ String playlistId,
+ String libraryItemId, {
+ String? episodeId,
+ }) async {
+ try {
+ final body = <String, dynamic>{'libraryItemId': libraryItemId};
+ if (episodeId != null) body['episodeId'] = episodeId;
+ final resp = await http.post(
+ Uri.parse('$_cleanBaseUrl/api/playlists/$playlistId/item'),
+ headers: _headers,
+ body: jsonEncode(body),
+ ).timeout(const Duration(seconds: 10));
+ if (resp.statusCode == 200) {
+ return jsonDecode(resp.body) as Map<String, dynamic>;
+ }
+ } catch (_) {}
+ return null;
+ }
+
+ /// DELETE /api/playlists/:id/item/:libraryItemId/:episodeId
+ Future<Map<String, dynamic>?> removeItemFromPlaylist(
+ String playlistId,
+ String libraryItemId, {
+ String? episodeId,
+ }) async {
+ try {
+ var path = '$_cleanBaseUrl/api/playlists/$playlistId/item/$libraryItemId';
+ if (episodeId != null) path += '/$episodeId';
+ final resp = await http.delete(
+ Uri.parse(path),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 10));
+ if (resp.statusCode == 200) {
+ return jsonDecode(resp.body) as Map<String, dynamic>;
+ }
+ } catch (_) {}
+ return null;
+ }
+
+ // ── Collections ────────────────────────────────────────────────────────
+
+ /// GET /api/libraries/:libraryId/collections
+ Future<List<dynamic>> getLibraryCollections(String libraryId) async {
+ try {
+ final resp = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/collections'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 15));
+ if (resp.statusCode == 200) {
+ final data = jsonDecode(resp.body);
+ return (data['results'] as List<dynamic>?) ?? [];
+ }
+ } catch (_) {}
+ return [];
+ }
+
+ /// GET /api/collections/:id
+ Future<Map<String, dynamic>?> getCollection(String collectionId) async {
+ try {
+ final resp = await http.get(
+ Uri.parse('$_cleanBaseUrl/api/collections/$collectionId'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 10));
+ if (resp.statusCode == 200) {
+ return jsonDecode(resp.body) as Map<String, dynamic>;
+ }
+ } catch (_) {}
+ return null;
+ }
+
+ /// POST /api/collections
+ Future<Map<String, dynamic>?> createCollection(
+ String libraryId,
+ String name, {
+ String? description,
+ List<String> books = const [],
+ }) async {
+ try {
+ final body = <String, dynamic>{
+ 'libraryId': libraryId,
+ 'name': name,
+ 'books': books,
+ };
+ if (description != null) body['description'] = description;
+ final resp = await http.post(
+ Uri.parse('$_cleanBaseUrl/api/collections'),
+ headers: _headers,
+ body: jsonEncode(body),
+ ).timeout(const Duration(seconds: 10));
+ if (resp.statusCode == 200) {
+ return jsonDecode(resp.body) as Map<String, dynamic>;
+ }
+ } catch (_) {}
+ return null;
+ }
+
+ /// PATCH /api/collections/:id
+ Future<Map<String, dynamic>?> updateCollection(
+ String collectionId, {
+ String? name,
+ String? description,
+ List<String>? books,
+ }) async {
+ try {
+ final body = <String, dynamic>{};
+ if (name != null) body['name'] = name;
+ if (description != null) body['description'] = description;
+ if (books != null) body['books'] = books;
+ final resp = await http.patch(
+ Uri.parse('$_cleanBaseUrl/api/collections/$collectionId'),
+ headers: _headers,
+ body: jsonEncode(body),
+ ).timeout(const Duration(seconds: 10));
+ if (resp.statusCode == 200) {
+ return jsonDecode(resp.body) as Map<String, dynamic>;
+ }
+ } catch (_) {}
+ return null;
+ }
+
+ /// DELETE /api/collections/:id
+ Future<bool> deleteCollection(String collectionId) async {
+ try {
+ final resp = await http.delete(
+ Uri.parse('$_cleanBaseUrl/api/collections/$collectionId'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 10));
+ return resp.statusCode == 200;
+ } catch (_) {}
+ return false;
+ }
+
+ /// POST /api/collections/:id/books
+ Future<Map<String, dynamic>?> addBookToCollection(
+ String collectionId,
+ String libraryItemId,
+ ) async {
+ try {
+ final resp = await http.post(
+ Uri.parse('$_cleanBaseUrl/api/collections/$collectionId/book'),
+ headers: _headers,
+ body: jsonEncode({'id': libraryItemId}),
+ ).timeout(const Duration(seconds: 10));
+ if (resp.statusCode == 200) {
+ return jsonDecode(resp.body) as Map<String, dynamic>;
+ }
+ } catch (_) {}
+ return null;
+ }
+
+ /// DELETE /api/collections/:id/books/:libraryItemId
+ Future<Map<String, dynamic>?> removeBookFromCollection(
+ String collectionId,
+ String libraryItemId,
+ ) async {
+ try {
+ final resp = await http.delete(
+ Uri.parse('$_cleanBaseUrl/api/collections/$collectionId/book/$libraryItemId'),
+ headers: _headers,
+ ).timeout(const Duration(seconds: 10));
+ if (resp.statusCode == 200) {
+ return jsonDecode(resp.body) as Map<String, dynamic>;
+ }
+ } catch (_) {}
+ return null;
+ }
}
diff --git a/lib/widgets/author_card.dart b/lib/widgets/author_card.dart
index 727440f4..38a298c0 100644
--- a/lib/widgets/author_card.dart
+++ b/lib/widgets/author_card.dart
@@ -3,6 +3,7 @@ import 'package:provider/provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../providers/auth_provider.dart';
import '../providers/library_provider.dart';
+import 'author_books_sheet.dart';
class AuthorCard extends StatelessWidget {
final Map<String, dynamic> author;
@@ -28,7 +29,11 @@ class AuthorCard extends StatelessWidget {
final headers = lib.mediaHeaders;
return InkWell(
- onTap: () {},
+ onTap: () {
+ if (authorId.isNotEmpty) {
+ showAuthorDetailSheet(context, authorId: authorId, authorName: name);
+ }
+ },
borderRadius: BorderRadius.circular(16),
child: Column(
mainAxisSize: MainAxisSize.min,
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index 9f9e1942..5bc8bb7f 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -26,6 +26,8 @@ import 'series_books_sheet.dart';
import 'absorbing_shared.dart';
import 'html_description.dart';
import 'metadata_lookup_sheet.dart';
+import 'playlist_picker_sheet.dart';
+import 'collection_picker_sheet.dart';
import 'absorb_wave_icon.dart';
import 'edit_metadata_sheet.dart';
@@ -129,11 +131,29 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
if (dl.sessionData != null) {
try {
final session = jsonDecode(dl.sessionData!) as Map<String, dynamic>;
+ // Prefer full libraryItem if it wasn't stripped
final localItem = session['libraryItem'] as Map<String, dynamic>?;
if (localItem != null && mounted) {
setState(() { _item = localItem; _isLoading = false; });
return;
}
+ // Build a synthetic item from session-level fields (mediaMetadata,
+ // chapters, duration) which survive the libraryItem strip.
+ final meta = session['mediaMetadata'] as Map<String, dynamic>?;
+ if (meta != null && mounted) {
+ setState(() {
+ _item = {
+ 'id': widget.itemId,
+ 'media': {
+ 'metadata': meta,
+ 'duration': session['duration'],
+ 'chapters': session['chapters'],
+ },
+ };
+ _isLoading = false;
+ });
+ return;
+ }
} catch (_) {}
}
// Minimal fallback from DownloadInfo metadata
@@ -490,6 +510,18 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
}
}
}),
+ if (!lib.isOffline)
+ _moreItem(cs, Icons.playlist_add_rounded, 'Add to Playlist',
+ onTap: () {
+ Navigator.pop(ctx);
+ PlaylistPickerSheet.show(context, widget.itemId);
+ }),
+ if (!lib.isOffline && !lib.isPodcastLibrary && auth.isRoot)
+ _moreItem(cs, Icons.collections_bookmark_rounded, 'Add to Collection',
+ onTap: () {
+ Navigator.pop(ctx);
+ CollectionPickerSheet.show(context, widget.itemId);
+ }),
if (ebookFile != null)
_moreItem(cs, _ebookSaved ? Icons.download_done_rounded : Icons.save_alt_rounded,
_ebookSaved ? 'Download eBook Again' : 'Download eBook',
diff --git a/lib/widgets/collection_detail_sheet.dart b/lib/widgets/collection_detail_sheet.dart
new file mode 100644
index 00000000..aba382f2
--- /dev/null
+++ b/lib/widgets/collection_detail_sheet.dart
@@ -0,0 +1,356 @@
+import 'dart:io';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:provider/provider.dart';
+import '../providers/auth_provider.dart';
+import '../providers/library_provider.dart';
+import 'book_detail_sheet.dart';
+
+class CollectionDetailSheet extends StatefulWidget {
+ final String collectionId;
+ final ScrollController? scrollController;
+
+ const CollectionDetailSheet({
+ super.key,
+ required this.collectionId,
+ this.scrollController,
+ });
+
+ static void show(BuildContext context, String collectionId) {
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (context) {
+ return GestureDetector(
+ onTap: () => Navigator.pop(context),
+ behavior: HitTestBehavior.opaque,
+ child: DraggableScrollableSheet(
+ initialChildSize: 0.7,
+ minChildSize: 0.4,
+ maxChildSize: 0.95,
+ builder: (context, scrollController) {
+ return GestureDetector(
+ onTap: () {},
+ child: Container(
+ decoration: BoxDecoration(
+ color: Theme.of(context).bottomSheetTheme.backgroundColor ??
+ Theme.of(context).colorScheme.surface,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ child: CollectionDetailSheet(
+ collectionId: collectionId,
+ scrollController: scrollController,
+ ),
+ ),
+ );
+ },
+ ),
+ );
+ },
+ );
+ }
+
+ @override
+ State<CollectionDetailSheet> createState() => _CollectionDetailSheetState();
+}
+
+class _CollectionDetailSheetState extends State<CollectionDetailSheet> {
+ bool _reordering = false;
+ List<Map<String, dynamic>>? _reorderItems;
+
+ Future<void> _removeItem(LibraryProvider lib, String libraryItemId) async {
+ await lib.removeFromCollection(widget.collectionId, libraryItemId);
+ }
+
+ Future<void> _deleteCollection(BuildContext context, LibraryProvider lib) async {
+ final confirmed = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: const Text('Delete Collection'),
+ content: const Text('Are you sure you want to delete this collection?'),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(ctx, false),
+ child: const Text('Cancel'),
+ ),
+ TextButton(
+ onPressed: () => Navigator.pop(ctx, true),
+ child: const Text('Delete'),
+ ),
+ ],
+ ),
+ );
+ if (confirmed == true && context.mounted) {
+ await lib.deleteCollection(widget.collectionId);
+ if (context.mounted) Navigator.pop(context);
+ }
+ }
+
+ void _startReorder(List<dynamic> books) {
+ setState(() {
+ _reordering = true;
+ _reorderItems = books
+ .map((b) => Map<String, dynamic>.from(b as Map))
+ .toList();
+ });
+ }
+
+ Future<void> _saveReorder(LibraryProvider lib) async {
+ if (_reorderItems != null) {
+ final bookIds = _reorderItems!
+ .map((b) => b['id'] as String? ?? '')
+ .where((id) => id.isNotEmpty)
+ .toList();
+ await lib.reorderCollectionBooks(widget.collectionId, bookIds);
+ }
+ if (mounted) Navigator.pop(context);
+ }
+
+ void _cancelReorder() {
+ setState(() {
+ _reordering = false;
+ _reorderItems = null;
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final lib = context.watch<LibraryProvider>();
+ final isRoot = context.read<AuthProvider>().isRoot;
+
+ final collection = lib.collections.cast<Map<String, dynamic>>().where(
+ (c) => c['id'] == widget.collectionId,
+ ).firstOrNull;
+
+ if (collection == null) {
+ return const Center(child: Text('Collection not found'));
+ }
+
+ final name = collection['name'] as String? ?? 'Collection';
+ final description = collection['description'] as String? ?? '';
+ final books = (collection['books'] as List<dynamic>?) ?? [];
+
+ return Column(children: [
+ // Grab handle + header
+ const SizedBox(height: 8),
+ Center(child: Container(
+ width: 40, height: 4,
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.24),
+ borderRadius: BorderRadius.circular(2),
+ ),
+ )),
+ const SizedBox(height: 16),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 20),
+ child: Row(children: [
+ if (_reordering) ...[
+ GestureDetector(
+ onTap: _cancelReorder,
+ child: Text('Cancel', style: tt.labelMedium?.copyWith(
+ color: cs.onSurfaceVariant, fontWeight: FontWeight.w500,
+ )),
+ ),
+ const Spacer(),
+ Text(name, style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.onSurface,
+ )),
+ const Spacer(),
+ GestureDetector(
+ onTap: () => _saveReorder(lib),
+ child: Text('Done', style: tt.labelMedium?.copyWith(
+ color: cs.primary, fontWeight: FontWeight.w600,
+ )),
+ ),
+ ] else ...[
+ if (isRoot) ...[
+ GestureDetector(
+ onTap: () => _deleteCollection(context, lib),
+ child: Icon(Icons.delete_outline_rounded, size: 20,
+ color: cs.onSurfaceVariant),
+ ),
+ const SizedBox(width: 12),
+ ],
+ Icon(Icons.collections_bookmark_rounded, size: 20, color: cs.primary),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(name, style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.onSurface,
+ )),
+ ),
+ Text('${books.length} book${books.length == 1 ? '' : 's'}',
+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ if (isRoot && books.length > 1) ...[
+ const SizedBox(width: 12),
+ GestureDetector(
+ onTap: () => _startReorder(books),
+ child: Icon(Icons.tune_rounded, size: 20,
+ color: cs.onSurfaceVariant),
+ ),
+ ],
+ ],
+ ]),
+ ),
+ if (!_reordering && description.isNotEmpty) ...[
+ const SizedBox(height: 4),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 20),
+ child: Text(description,
+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant),
+ maxLines: 2, overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ ],
+ const SizedBox(height: 12),
+ Divider(height: 1, color: cs.outlineVariant.withValues(alpha: 0.3),
+ indent: 20, endIndent: 20),
+ // Content
+ Expanded(
+ child: _reordering
+ ? _buildReorderList(cs, tt, lib)
+ : _buildItemList(cs, tt, lib, books, isRoot: isRoot),
+ ),
+ ]);
+ }
+
+ Widget _buildReorderList(ColorScheme cs, TextTheme tt, LibraryProvider lib) {
+ final items = _reorderItems!;
+ return ReorderableListView.builder(
+ padding: const EdgeInsets.symmetric(vertical: 8),
+ onReorderStart: (_) => HapticFeedback.mediumImpact(),
+ onReorder: (oldIndex, newIndex) {
+ setState(() {
+ if (newIndex > oldIndex) newIndex--;
+ final item = items.removeAt(oldIndex);
+ items.insert(newIndex, item);
+ });
+ },
+ itemCount: items.length,
+ itemBuilder: (context, index) {
+ final book = items[index];
+ final itemId = book['id'] as String? ?? '';
+ final media = book['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final title = metadata['title'] as String? ?? 'Unknown';
+ final coverUrl = lib.getCoverUrl(itemId);
+
+ return Container(
+ key: ValueKey(itemId),
+ margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 3),
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.05),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),
+ ),
+ child: ListTile(
+ dense: true,
+ leading: SizedBox(
+ width: 36, height: 36,
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(4),
+ child: coverUrl != null
+ ? (coverUrl.startsWith('/')
+ ? Image.file(File(coverUrl), fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => _placeholder(cs))
+ : Image.network(coverUrl, fit: BoxFit.cover,
+ headers: lib.mediaHeaders,
+ errorBuilder: (_, __, ___) => _placeholder(cs)))
+ : _placeholder(cs),
+ ),
+ ),
+ title: Text(
+ title,
+ maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500,
+ color: cs.onSurface),
+ ),
+ trailing: ReorderableDragStartListener(
+ index: index,
+ child: Padding(
+ padding: const EdgeInsets.all(8),
+ child: Icon(Icons.drag_handle_rounded, size: 18,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ ),
+ ),
+ ),
+ );
+ },
+ );
+ }
+
+ Widget _buildItemList(ColorScheme cs, TextTheme tt, LibraryProvider lib, List<dynamic> books, {required bool isRoot}) {
+ return ListView.builder(
+ controller: widget.scrollController,
+ padding: const EdgeInsets.only(bottom: 40),
+ itemCount: books.length,
+ itemBuilder: (context, index) {
+ final book = books[index] as Map<String, dynamic>;
+ final itemId = book['id'] as String? ?? '';
+ final media = book['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final title = metadata['title'] as String? ?? 'Unknown';
+ final author = metadata['authorName'] as String? ?? '';
+ final coverUrl = lib.getCoverUrl(itemId);
+
+ final tile = ListTile(
+ contentPadding: const EdgeInsets.symmetric(horizontal: 20),
+ leading: SizedBox(
+ width: 44, height: 44,
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(6),
+ child: coverUrl != null
+ ? (coverUrl.startsWith('/')
+ ? Image.file(File(coverUrl), fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => _placeholder(cs))
+ : Image.network(coverUrl, fit: BoxFit.cover,
+ headers: lib.mediaHeaders,
+ errorBuilder: (_, __, ___) => _placeholder(cs)))
+ : _placeholder(cs),
+ ),
+ ),
+ title: Text(
+ title,
+ maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w500, color: cs.onSurface,
+ ),
+ ),
+ subtitle: Text(
+ author,
+ maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ onTap: () => showBookDetailSheet(context, itemId),
+ );
+
+ if (!isRoot) return tile;
+
+ return Dismissible(
+ key: ValueKey(itemId),
+ direction: DismissDirection.endToStart,
+ onDismissed: (_) => _removeItem(lib, itemId),
+ background: Container(
+ alignment: Alignment.centerRight,
+ padding: const EdgeInsets.only(right: 20),
+ color: cs.error.withValues(alpha: 0.1),
+ child: Icon(Icons.delete_rounded, color: cs.error),
+ ),
+ child: tile,
+ );
+ },
+ );
+ }
+
+ Widget _placeholder(ColorScheme cs) {
+ return Container(
+ color: cs.surfaceContainerHigh,
+ child: Icon(Icons.book_rounded, size: 20,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
+ );
+ }
+}
diff --git a/lib/widgets/collection_picker_sheet.dart b/lib/widgets/collection_picker_sheet.dart
new file mode 100644
index 00000000..9afc0cb2
--- /dev/null
+++ b/lib/widgets/collection_picker_sheet.dart
@@ -0,0 +1,192 @@
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import '../providers/library_provider.dart';
+
+class CollectionPickerSheet extends StatefulWidget {
+ final String libraryItemId;
+
+ const CollectionPickerSheet({
+ super.key,
+ required this.libraryItemId,
+ });
+
+ static void show(BuildContext context, String libraryItemId) {
+ showModalBottomSheet(
+ context: context,
+ backgroundColor: Theme.of(context).bottomSheetTheme.backgroundColor,
+ shape: const RoundedRectangleBorder(
+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ isScrollControlled: true,
+ builder: (_) => CollectionPickerSheet(libraryItemId: libraryItemId),
+ );
+ }
+
+ @override
+ State<CollectionPickerSheet> createState() => _CollectionPickerSheetState();
+}
+
+class _CollectionPickerSheetState extends State<CollectionPickerSheet> {
+ bool _creatingNew = false;
+ final _nameController = TextEditingController();
+ bool _adding = false;
+
+ @override
+ void dispose() {
+ _nameController.dispose();
+ super.dispose();
+ }
+
+ Future<void> _createAndAdd(LibraryProvider lib) async {
+ final name = _nameController.text.trim();
+ if (name.isEmpty) return;
+ setState(() => _adding = true);
+ final collection = await lib.createCollection(name, books: [widget.libraryItemId]);
+ if (collection != null) {
+ if (mounted) {
+ Navigator.pop(context);
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ duration: const Duration(seconds: 3),
+ content: Text('Added to "$name"'),
+ behavior: SnackBarBehavior.floating,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ ));
+ }
+ } else {
+ setState(() => _adding = false);
+ }
+ }
+
+ Future<void> _addToExisting(LibraryProvider lib, Map<String, dynamic> collection) async {
+ setState(() => _adding = true);
+ final collectionId = collection['id'] as String;
+ final name = collection['name'] as String? ?? 'Collection';
+ final ok = await lib.addToCollection(collectionId, widget.libraryItemId);
+ if (mounted) {
+ Navigator.pop(context);
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ duration: const Duration(seconds: 3),
+ content: Text(ok ? 'Added to "$name"' : 'Failed to add'),
+ behavior: SnackBarBehavior.floating,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ ));
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final lib = context.watch<LibraryProvider>();
+ final collections = lib.collections;
+
+ return SafeArea(
+ child: Padding(
+ padding: EdgeInsets.fromLTRB(
+ 16, 8, 16, 16 + MediaQuery.of(context).viewInsets.bottom,
+ ),
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
+ // Grab handle
+ Center(child: Container(
+ width: 40, height: 4,
+ margin: const EdgeInsets.only(bottom: 16),
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.24),
+ borderRadius: BorderRadius.circular(2),
+ ),
+ )),
+ // Title
+ Text('Add to Collection', style: TextStyle(
+ color: cs.onSurface, fontSize: 16, fontWeight: FontWeight.w600,
+ )),
+ const SizedBox(height: 12),
+ // New collection
+ if (_creatingNew)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: Row(children: [
+ Expanded(child: TextField(
+ controller: _nameController,
+ autofocus: true,
+ style: TextStyle(color: cs.onSurface, fontSize: 14),
+ decoration: InputDecoration(
+ hintText: 'Collection name',
+ hintStyle: TextStyle(color: cs.onSurface.withValues(alpha: 0.4)),
+ isDense: true,
+ contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
+ enabledBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(12),
+ borderSide: BorderSide(color: cs.onSurface.withValues(alpha: 0.2)),
+ ),
+ ),
+ onSubmitted: (_) => _createAndAdd(lib),
+ )),
+ const SizedBox(width: 8),
+ _adding
+ ? const SizedBox(width: 36, height: 36,
+ child: Padding(
+ padding: EdgeInsets.all(8),
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ))
+ : IconButton(
+ icon: Icon(Icons.check_rounded, color: cs.primary),
+ onPressed: () => _createAndAdd(lib),
+ ),
+ ]),
+ )
+ else
+ _sheetItem(cs, Icons.add_rounded, 'New Collection',
+ onTap: () => setState(() => _creatingNew = true)),
+ // Existing collections
+ if (collections.isNotEmpty) ...[
+ const SizedBox(height: 4),
+ ...collections.map((c) {
+ final cm = c as Map<String, dynamic>;
+ final name = cm['name'] as String? ?? 'Collection';
+ final books = (cm['books'] as List<dynamic>?) ?? [];
+ // Check if item is already in this collection
+ final alreadyIn = books.any((book) {
+ final bm = book as Map<String, dynamic>;
+ return bm['id'] == widget.libraryItemId;
+ });
+ return _sheetItem(
+ cs,
+ alreadyIn ? Icons.check_rounded : Icons.collections_bookmark_rounded,
+ '$name (${books.length})',
+ enabled: !alreadyIn && !_adding,
+ onTap: () => _addToExisting(lib, cm),
+ );
+ }),
+ ],
+ ]),
+ ),
+ );
+ }
+
+ Widget _sheetItem(ColorScheme cs, IconData icon, String label,
+ {required VoidCallback onTap, bool enabled = true}) {
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: GestureDetector(
+ onTap: enabled ? onTap : null,
+ child: Container(
+ height: 44,
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: enabled ? 0.06 : 0.03),
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(color: cs.onSurface.withValues(alpha: 0.1)),
+ ),
+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ Icon(icon, size: 16,
+ color: enabled ? cs.onSurfaceVariant : cs.onSurfaceVariant.withValues(alpha: 0.4)),
+ const SizedBox(width: 8),
+ Text(label, style: TextStyle(
+ color: enabled ? cs.onSurfaceVariant : cs.onSurfaceVariant.withValues(alpha: 0.4),
+ fontSize: 13, fontWeight: FontWeight.w500,
+ )),
+ ]),
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/episode_list_sheet.dart b/lib/widgets/episode_list_sheet.dart
index 0d318ad8..3f30c1a5 100644
--- a/lib/widgets/episode_list_sheet.dart
+++ b/lib/widgets/episode_list_sheet.dart
@@ -11,6 +11,7 @@ import '../services/chromecast_service.dart';
import '../providers/auth_provider.dart';
import 'card_buttons.dart';
import 'html_description.dart';
+import 'playlist_picker_sheet.dart';
/// Bottom sheet that shows a podcast's episode list.
/// Mirrors the UX of [BookDetailSheet] but adapted for podcast shows.
@@ -1061,6 +1062,16 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {
}
}
}),
+ if (!lib.isOffline)
+ _moreItem(cs, Icons.playlist_add_rounded, 'Add to Playlist',
+ onTap: () {
+ Navigator.pop(ctx);
+ PlaylistPickerSheet.show(
+ context,
+ widget.podcastItem['id'] as String,
+ episodeId: widget.episode['id'] as String?,
+ );
+ }),
if (progress > 0 || isFinished)
_moreItem(cs, Icons.restart_alt_rounded, 'Reset Progress',
onTap: () { Navigator.pop(ctx); _resetProgress(context); }),
diff --git a/lib/widgets/home_customize_sheet.dart b/lib/widgets/home_customize_sheet.dart
new file mode 100644
index 00000000..fefb4398
--- /dev/null
+++ b/lib/widgets/home_customize_sheet.dart
@@ -0,0 +1,251 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:provider/provider.dart';
+import '../providers/library_provider.dart';
+
+class HomeCustomizeSheet extends StatefulWidget {
+ final ScrollController? scrollController;
+
+ const HomeCustomizeSheet({super.key, this.scrollController});
+
+ static void show(BuildContext context) {
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (context) {
+ return GestureDetector(
+ onTap: () => Navigator.pop(context),
+ behavior: HitTestBehavior.opaque,
+ child: DraggableScrollableSheet(
+ initialChildSize: 0.6,
+ minChildSize: 0.3,
+ maxChildSize: 0.85,
+ builder: (context, scrollController) {
+ return GestureDetector(
+ onTap: () {}, // absorb taps on the sheet itself
+ child: Container(
+ decoration: BoxDecoration(
+ color: Theme.of(context).bottomSheetTheme.backgroundColor ??
+ Theme.of(context).colorScheme.surface,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ child: HomeCustomizeSheet(scrollController: scrollController),
+ ),
+ );
+ },
+ ),
+ );
+ },
+ );
+ }
+
+ @override
+ State<HomeCustomizeSheet> createState() => _HomeCustomizeSheetState();
+}
+
+class _HomeCustomizeSheetState extends State<HomeCustomizeSheet> {
+ late List<Map<String, String>> _sections;
+ late Set<String> _hiddenIds;
+ bool _initialized = false;
+
+ static const _sectionIcons = {
+ 'continue-listening': Icons.play_circle_outline_rounded,
+ 'continue-series': Icons.auto_stories_rounded,
+ 'recently-added': Icons.new_releases_outlined,
+ 'listen-again': Icons.replay_rounded,
+ 'discover': Icons.explore_outlined,
+ 'episodes-recently-added': Icons.podcasts_rounded,
+ 'downloaded-books': Icons.download_done_rounded,
+ };
+
+ void _initSections(LibraryProvider lib) {
+ if (_initialized) return;
+ _initialized = true;
+
+ final allMeta = lib.getAllSectionMeta();
+ final order = lib.sectionOrder;
+ _hiddenIds = Set<String>.from(lib.hiddenSectionIds);
+
+ if (order.isNotEmpty) {
+ final ordered = <Map<String, String>>[];
+ for (final id in order) {
+ final meta = allMeta.where((m) => m['id'] == id).firstOrNull;
+ if (meta != null) ordered.add(meta);
+ }
+ for (final meta in allMeta) {
+ if (!order.contains(meta['id'])) ordered.add(meta);
+ }
+ _sections = ordered;
+ } else {
+ _sections = allMeta;
+ }
+ }
+
+ void _reset(LibraryProvider lib) {
+ setState(() {
+ _sections = lib.getAllSectionMeta();
+ _hiddenIds = {};
+ });
+ }
+
+ Future<void> _save(LibraryProvider lib) async {
+ await lib.saveSectionOrder(_sections.map((s) => s['id']!).toList());
+ // Sync hidden state: apply our local set to the provider
+ final currentHidden = lib.hiddenSectionIds;
+ // Unhide anything we removed
+ for (final id in currentHidden) {
+ if (!_hiddenIds.contains(id)) {
+ await lib.toggleSectionVisibility(id);
+ }
+ }
+ // Hide anything we added
+ for (final id in _hiddenIds) {
+ if (!lib.hiddenSectionIds.contains(id)) {
+ await lib.toggleSectionVisibility(id);
+ }
+ }
+ if (mounted) Navigator.pop(context);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final lib = context.read<LibraryProvider>();
+
+ _initSections(lib);
+
+ return Column(children: [
+ // Grab handle + header
+ const SizedBox(height: 8),
+ Center(child: Container(
+ width: 40, height: 4,
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.24),
+ borderRadius: BorderRadius.circular(2),
+ ),
+ )),
+ const SizedBox(height: 16),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 20),
+ child: Row(children: [
+ GestureDetector(
+ onTap: () => _reset(lib),
+ child: Text('Reset', style: tt.labelMedium?.copyWith(
+ color: cs.primary, fontWeight: FontWeight.w500,
+ )),
+ ),
+ const Spacer(),
+ Text('Customize Home', style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.onSurface,
+ )),
+ const Spacer(),
+ GestureDetector(
+ onTap: () => _save(lib),
+ child: Text('Done', style: tt.labelMedium?.copyWith(
+ color: cs.primary, fontWeight: FontWeight.w600,
+ )),
+ ),
+ ]),
+ ),
+ const SizedBox(height: 4),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 20),
+ child: Text(
+ 'Drag to reorder, tap eye to show/hide',
+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant),
+ textAlign: TextAlign.center,
+ ),
+ ),
+ const SizedBox(height: 12),
+ Divider(height: 1, color: cs.outlineVariant.withValues(alpha: 0.3),
+ indent: 20, endIndent: 20),
+ // Reorderable list
+ Expanded(
+ child: ReorderableListView.builder(
+ scrollController: widget.scrollController,
+ padding: const EdgeInsets.symmetric(vertical: 8),
+ itemCount: _sections.length,
+ onReorderStart: (_) => HapticFeedback.mediumImpact(),
+ onReorder: (oldIndex, newIndex) {
+ setState(() {
+ if (newIndex > oldIndex) newIndex--;
+ final item = _sections.removeAt(oldIndex);
+ _sections.insert(newIndex, item);
+ });
+ },
+ itemBuilder: (context, index) {
+ final section = _sections[index];
+ final id = section['id']!;
+ final label = section['label']!;
+ final isHidden = _hiddenIds.contains(id);
+ final isPlaylist = id.startsWith('playlist:');
+ final isCollection = id.startsWith('collection:');
+ final icon = isPlaylist
+ ? Icons.playlist_play_rounded
+ : isCollection
+ ? Icons.collections_bookmark_rounded
+ : (_sectionIcons[id] ?? Icons.album_outlined);
+
+ return Container(
+ key: ValueKey(id),
+ margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 3),
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: isHidden ? 0.02 : 0.05),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),
+ ),
+ child: ListTile(
+ dense: true,
+ leading: Icon(icon, size: 18,
+ color: isHidden
+ ? cs.onSurfaceVariant.withValues(alpha: 0.3)
+ : cs.onSurfaceVariant),
+ title: Text(label, style: TextStyle(
+ fontSize: 13, fontWeight: FontWeight.w500,
+ color: isHidden
+ ? cs.onSurface.withValues(alpha: 0.35)
+ : cs.onSurface,
+ )),
+ trailing: Row(mainAxisSize: MainAxisSize.min, children: [
+ GestureDetector(
+ onTap: () {
+ setState(() {
+ if (_hiddenIds.contains(id)) {
+ _hiddenIds.remove(id);
+ } else {
+ _hiddenIds.add(id);
+ }
+ });
+ },
+ child: Padding(
+ padding: const EdgeInsets.all(8),
+ child: Icon(
+ isHidden ? Icons.visibility_off_rounded : Icons.visibility_rounded,
+ size: 18,
+ color: isHidden
+ ? cs.onSurfaceVariant.withValues(alpha: 0.3)
+ : cs.onSurfaceVariant,
+ ),
+ ),
+ ),
+ ReorderableDragStartListener(
+ index: index,
+ child: Padding(
+ padding: const EdgeInsets.all(8),
+ child: Icon(Icons.drag_handle_rounded, size: 18,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ ),
+ ),
+ ]),
+ ),
+ );
+ },
+ ),
+ ),
+ ]);
+ }
+}
+
diff --git a/lib/widgets/home_section.dart b/lib/widgets/home_section.dart
index 625854ed..88e1cfe7 100644
--- a/lib/widgets/home_section.dart
+++ b/lib/widgets/home_section.dart
@@ -13,6 +13,7 @@ class HomeSection extends StatelessWidget {
final List<dynamic> entities;
final String sectionType;
final String sectionId;
+ final VoidCallback? onTitleTap;
const HomeSection({
super.key,
@@ -21,6 +22,7 @@ class HomeSection extends StatelessWidget {
required this.entities,
required this.sectionType,
required this.sectionId,
+ this.onTitleTap,
});
@override
@@ -29,6 +31,7 @@ class HomeSection extends StatelessWidget {
final tt = Theme.of(context).textTheme;
final isContinueListening = sectionId == 'continue-listening';
+ final isPlaylistSection = sectionType == 'playlist';
final isAuthorSection = sectionType == 'author' || sectionType == 'authors';
final isSeriesSection = sectionType == 'series';
final isEpisodeSection = sectionType == 'episode';
@@ -50,28 +53,37 @@ class HomeSection extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Section header
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 20),
- child: Row(
- children: [
- Icon(icon, size: 16, color: cs.primary.withValues(alpha: 0.7)),
- const SizedBox(width: 8),
- Text(
- title,
- style: tt.titleSmall?.copyWith(
- fontWeight: FontWeight.w500,
- color: cs.onSurface.withValues(alpha: 0.8),
- letterSpacing: 0.3,
+ GestureDetector(
+ onTap: onTitleTap,
+ behavior: onTitleTap != null ? HitTestBehavior.opaque : HitTestBehavior.deferToChild,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 20),
+ child: Row(
+ children: [
+ Icon(icon, size: 16, color: cs.primary.withValues(alpha: 0.7)),
+ const SizedBox(width: 8),
+ Text(
+ title,
+ style: tt.titleSmall?.copyWith(
+ fontWeight: FontWeight.w500,
+ color: cs.onSurface.withValues(alpha: 0.8),
+ letterSpacing: 0.3,
+ ),
),
- ),
- const SizedBox(width: 12),
- Expanded(
- child: Container(
- height: 0.5,
- color: cs.outlineVariant.withValues(alpha: 0.2),
+ if (onTitleTap != null) ...[
+ const SizedBox(width: 4),
+ Icon(Icons.chevron_right_rounded, size: 16,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.4)),
+ ],
+ const SizedBox(width: 12),
+ Expanded(
+ child: Container(
+ height: 0.5,
+ color: cs.outlineVariant.withValues(alpha: 0.2),
+ ),
),
- ),
- ],
+ ],
+ ),
),
),
const SizedBox(height: 12),
@@ -83,7 +95,26 @@ class HomeSection extends StatelessWidget {
cardWidth: cardWidth,
itemCount: entities.length,
itemBuilder: (context, index) {
- final entity = entities[index];
+ var entity = entities[index];
+
+ // Playlist items nest actual item under 'libraryItem'
+ if (isPlaylistSection && entity is Map<String, dynamic>) {
+ final inner = entity['libraryItem'] as Map<String, dynamic>?;
+ if (inner != null) {
+ // Merge episodeId into the item for episode detection
+ final episodeId = entity['episodeId'] as String?;
+ entity = Map<String, dynamic>.from(inner);
+ if (episodeId != null) {
+ // Find the matching episode from the podcast's episodes
+ final media = entity['media'] as Map<String, dynamic>? ?? {};
+ final episodes = media['episodes'] as List<dynamic>? ?? [];
+ final ep = episodes.cast<Map<String, dynamic>>().where(
+ (e) => e['id'] == episodeId,
+ ).firstOrNull;
+ if (ep != null) entity['recentEpisode'] = ep;
+ }
+ }
+ }
if (isAuthorSection) {
return SizedBox(
diff --git a/lib/widgets/playlist_detail_sheet.dart b/lib/widgets/playlist_detail_sheet.dart
new file mode 100644
index 00000000..be2e9cf8
--- /dev/null
+++ b/lib/widgets/playlist_detail_sheet.dart
@@ -0,0 +1,381 @@
+import 'dart:io';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:provider/provider.dart';
+import '../providers/library_provider.dart';
+import 'book_detail_sheet.dart';
+import 'episode_list_sheet.dart';
+
+class PlaylistDetailSheet extends StatefulWidget {
+ final String playlistId;
+ final ScrollController? scrollController;
+
+ const PlaylistDetailSheet({
+ super.key,
+ required this.playlistId,
+ this.scrollController,
+ });
+
+ static void show(BuildContext context, String playlistId) {
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (context) {
+ return GestureDetector(
+ onTap: () => Navigator.pop(context),
+ behavior: HitTestBehavior.opaque,
+ child: DraggableScrollableSheet(
+ initialChildSize: 0.7,
+ minChildSize: 0.4,
+ maxChildSize: 0.95,
+ builder: (context, scrollController) {
+ return GestureDetector(
+ onTap: () {},
+ child: Container(
+ decoration: BoxDecoration(
+ color: Theme.of(context).bottomSheetTheme.backgroundColor ??
+ Theme.of(context).colorScheme.surface,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ child: PlaylistDetailSheet(
+ playlistId: playlistId,
+ scrollController: scrollController,
+ ),
+ ),
+ );
+ },
+ ),
+ );
+ },
+ );
+ }
+
+ @override
+ State<PlaylistDetailSheet> createState() => _PlaylistDetailSheetState();
+}
+
+class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {
+ bool _reordering = false;
+ List<Map<String, dynamic>>? _reorderItems;
+
+ Future<void> _removeItem(
+ LibraryProvider lib,
+ String libraryItemId, {
+ String? episodeId,
+ }) async {
+ await lib.removeFromPlaylist(
+ widget.playlistId, libraryItemId, episodeId: episodeId,
+ );
+ }
+
+ Future<void> _deletePlaylist(BuildContext context, LibraryProvider lib) async {
+ final confirmed = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: const Text('Delete Playlist'),
+ content: const Text('Are you sure you want to delete this playlist?'),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(ctx, false),
+ child: const Text('Cancel'),
+ ),
+ TextButton(
+ onPressed: () => Navigator.pop(ctx, true),
+ child: const Text('Delete'),
+ ),
+ ],
+ ),
+ );
+ if (confirmed == true && context.mounted) {
+ await lib.deletePlaylist(widget.playlistId);
+ if (context.mounted) Navigator.pop(context);
+ }
+ }
+
+ void _startReorder(List<dynamic> items) {
+ setState(() {
+ _reordering = true;
+ _reorderItems = items
+ .map((i) => Map<String, dynamic>.from(i as Map))
+ .toList();
+ });
+ }
+
+ Future<void> _saveReorder(LibraryProvider lib) async {
+ if (_reorderItems != null) {
+ await lib.reorderPlaylistItems(widget.playlistId, _reorderItems!);
+ }
+ if (mounted) Navigator.pop(context);
+ }
+
+ void _cancelReorder() {
+ setState(() {
+ _reordering = false;
+ _reorderItems = null;
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final lib = context.watch<LibraryProvider>();
+
+ final playlist = lib.playlists.cast<Map<String, dynamic>>().where(
+ (p) => p['id'] == widget.playlistId,
+ ).firstOrNull;
+
+ if (playlist == null) {
+ return const Center(child: Text('Playlist not found'));
+ }
+
+ final name = playlist['name'] as String? ?? 'Playlist';
+ final items = (playlist['items'] as List<dynamic>?) ?? [];
+
+ return Column(children: [
+ // Grab handle + header
+ const SizedBox(height: 8),
+ Center(child: Container(
+ width: 40, height: 4,
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.24),
+ borderRadius: BorderRadius.circular(2),
+ ),
+ )),
+ const SizedBox(height: 16),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 20),
+ child: Row(children: [
+ if (_reordering) ...[
+ GestureDetector(
+ onTap: _cancelReorder,
+ child: Text('Cancel', style: tt.labelMedium?.copyWith(
+ color: cs.onSurfaceVariant, fontWeight: FontWeight.w500,
+ )),
+ ),
+ const Spacer(),
+ Text(name, style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.onSurface,
+ )),
+ const Spacer(),
+ GestureDetector(
+ onTap: () => _saveReorder(lib),
+ child: Text('Done', style: tt.labelMedium?.copyWith(
+ color: cs.primary, fontWeight: FontWeight.w600,
+ )),
+ ),
+ ] else ...[
+ GestureDetector(
+ onTap: () => _deletePlaylist(context, lib),
+ child: Icon(Icons.delete_outline_rounded, size: 20,
+ color: cs.onSurfaceVariant),
+ ),
+ const SizedBox(width: 12),
+ Icon(Icons.playlist_play_rounded, size: 20, color: cs.primary),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(name, style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.onSurface,
+ )),
+ ),
+ Text('${items.length} item${items.length == 1 ? '' : 's'}',
+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ if (items.length > 1) ...[
+ const SizedBox(width: 12),
+ GestureDetector(
+ onTap: () => _startReorder(items),
+ child: Icon(Icons.tune_rounded, size: 20,
+ color: cs.onSurfaceVariant),
+ ),
+ ],
+ ],
+ ]),
+ ),
+ const SizedBox(height: 12),
+ Divider(height: 1, color: cs.outlineVariant.withValues(alpha: 0.3),
+ indent: 20, endIndent: 20),
+ // Content
+ Expanded(
+ child: _reordering
+ ? _buildReorderList(cs, tt, lib)
+ : _buildItemList(cs, tt, lib, items),
+ ),
+ ]);
+ }
+
+ Widget _buildReorderList(ColorScheme cs, TextTheme tt, LibraryProvider lib) {
+ final items = _reorderItems!;
+ return ReorderableListView.builder(
+ padding: const EdgeInsets.symmetric(vertical: 8),
+ onReorderStart: (_) => HapticFeedback.mediumImpact(),
+ onReorder: (oldIndex, newIndex) {
+ setState(() {
+ if (newIndex > oldIndex) newIndex--;
+ final item = items.removeAt(oldIndex);
+ items.insert(newIndex, item);
+ });
+ },
+ itemCount: items.length,
+ itemBuilder: (context, index) {
+ final item = items[index];
+ final libraryItemId = item['libraryItemId'] as String? ?? '';
+ final episodeId = item['episodeId'] as String?;
+ final libraryItem = item['libraryItem'] as Map<String, dynamic>?;
+ if (libraryItem == null) {
+ return SizedBox.shrink(key: ValueKey('$libraryItemId-${episodeId ?? ''}-$index'));
+ }
+
+ final media = libraryItem['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final title = metadata['title'] as String? ?? 'Unknown';
+ final coverUrl = lib.getCoverUrl(libraryItemId);
+
+ String? episodeTitle;
+ if (episodeId != null) {
+ final episodes = media['episodes'] as List<dynamic>? ?? [];
+ final ep = episodes.cast<Map<String, dynamic>>().where(
+ (e) => e['id'] == episodeId,
+ ).firstOrNull;
+ episodeTitle = ep?['title'] as String?;
+ }
+
+ return Container(
+ key: ValueKey('$libraryItemId-${episodeId ?? ''}'),
+ margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 3),
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.05),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),
+ ),
+ child: ListTile(
+ dense: true,
+ leading: SizedBox(
+ width: 36, height: 36,
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(4),
+ child: coverUrl != null
+ ? (coverUrl.startsWith('/')
+ ? Image.file(File(coverUrl), fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => _placeholder(cs))
+ : Image.network(coverUrl, fit: BoxFit.cover,
+ headers: lib.mediaHeaders,
+ errorBuilder: (_, __, ___) => _placeholder(cs)))
+ : _placeholder(cs),
+ ),
+ ),
+ title: Text(
+ episodeTitle ?? title,
+ maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500,
+ color: cs.onSurface),
+ ),
+ trailing: ReorderableDragStartListener(
+ index: index,
+ child: Padding(
+ padding: const EdgeInsets.all(8),
+ child: Icon(Icons.drag_handle_rounded, size: 18,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ ),
+ ),
+ ),
+ );
+ },
+ );
+ }
+
+ Widget _buildItemList(ColorScheme cs, TextTheme tt, LibraryProvider lib, List<dynamic> items) {
+ return ListView.builder(
+ controller: widget.scrollController,
+ padding: const EdgeInsets.only(bottom: 40),
+ itemCount: items.length,
+ itemBuilder: (context, index) {
+ final item = items[index] as Map<String, dynamic>;
+ final libraryItemId = item['libraryItemId'] as String? ?? '';
+ final episodeId = item['episodeId'] as String?;
+ final libraryItem = item['libraryItem'] as Map<String, dynamic>?;
+
+ if (libraryItem == null) return const SizedBox.shrink();
+
+ final media = libraryItem['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final title = metadata['title'] as String? ?? 'Unknown';
+ final author = metadata['authorName'] as String? ?? '';
+ final coverUrl = lib.getCoverUrl(libraryItemId);
+
+ String? episodeTitle;
+ if (episodeId != null) {
+ final episodes = media['episodes'] as List<dynamic>? ?? [];
+ final ep = episodes.cast<Map<String, dynamic>>().where(
+ (e) => e['id'] == episodeId,
+ ).firstOrNull;
+ episodeTitle = ep?['title'] as String?;
+ }
+
+ return Dismissible(
+ key: ValueKey('$libraryItemId-${episodeId ?? ''}'),
+ direction: DismissDirection.endToStart,
+ onDismissed: (_) => _removeItem(lib, libraryItemId, episodeId: episodeId),
+ background: Container(
+ alignment: Alignment.centerRight,
+ padding: const EdgeInsets.only(right: 20),
+ color: cs.error.withValues(alpha: 0.1),
+ child: Icon(Icons.delete_rounded, color: cs.error),
+ ),
+ child: ListTile(
+ contentPadding: const EdgeInsets.symmetric(horizontal: 20),
+ leading: SizedBox(
+ width: 44, height: 44,
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(6),
+ child: coverUrl != null
+ ? (coverUrl.startsWith('/')
+ ? Image.file(File(coverUrl), fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => _placeholder(cs))
+ : Image.network(coverUrl, fit: BoxFit.cover,
+ headers: lib.mediaHeaders,
+ errorBuilder: (_, __, ___) => _placeholder(cs)))
+ : _placeholder(cs),
+ ),
+ ),
+ title: Text(
+ episodeTitle ?? title,
+ maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w500, color: cs.onSurface,
+ ),
+ ),
+ subtitle: Text(
+ episodeTitle != null ? title : author,
+ maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ onTap: () {
+ if (episodeId != null) {
+ final episodes = media['episodes'] as List<dynamic>? ?? [];
+ final ep = episodes.cast<Map<String, dynamic>>().where(
+ (e) => e['id'] == episodeId,
+ ).firstOrNull;
+ if (ep != null) {
+ EpisodeDetailSheet.show(context, libraryItem, ep);
+ }
+ } else {
+ showBookDetailSheet(context, libraryItemId);
+ }
+ },
+ ),
+ );
+ },
+ );
+ }
+
+ Widget _placeholder(ColorScheme cs) {
+ return Container(
+ color: cs.surfaceContainerHigh,
+ child: Icon(Icons.music_note_rounded, size: 20,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
+ );
+ }
+}
diff --git a/lib/widgets/playlist_picker_sheet.dart b/lib/widgets/playlist_picker_sheet.dart
new file mode 100644
index 00000000..bfb0192a
--- /dev/null
+++ b/lib/widgets/playlist_picker_sheet.dart
@@ -0,0 +1,206 @@
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import '../providers/library_provider.dart';
+
+class PlaylistPickerSheet extends StatefulWidget {
+ final String libraryItemId;
+ final String? episodeId;
+
+ const PlaylistPickerSheet({
+ super.key,
+ required this.libraryItemId,
+ this.episodeId,
+ });
+
+ static void show(BuildContext context, String libraryItemId, {String? episodeId}) {
+ showModalBottomSheet(
+ context: context,
+ backgroundColor: Theme.of(context).bottomSheetTheme.backgroundColor,
+ shape: const RoundedRectangleBorder(
+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ isScrollControlled: true,
+ builder: (_) => PlaylistPickerSheet(
+ libraryItemId: libraryItemId,
+ episodeId: episodeId,
+ ),
+ );
+ }
+
+ @override
+ State<PlaylistPickerSheet> createState() => _PlaylistPickerSheetState();
+}
+
+class _PlaylistPickerSheetState extends State<PlaylistPickerSheet> {
+ bool _creatingNew = false;
+ final _nameController = TextEditingController();
+ bool _adding = false;
+
+ @override
+ void dispose() {
+ _nameController.dispose();
+ super.dispose();
+ }
+
+ Future<void> _createAndAdd(LibraryProvider lib) async {
+ final name = _nameController.text.trim();
+ if (name.isEmpty) return;
+ setState(() => _adding = true);
+ final playlist = await lib.createPlaylist(name);
+ if (playlist != null) {
+ final playlistId = playlist['id'] as String;
+ await lib.addToPlaylist(
+ playlistId, widget.libraryItemId, episodeId: widget.episodeId,
+ );
+ if (mounted) {
+ Navigator.pop(context);
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ duration: const Duration(seconds: 3),
+ content: Text('Added to "$name"'),
+ behavior: SnackBarBehavior.floating,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ ));
+ }
+ } else {
+ setState(() => _adding = false);
+ }
+ }
+
+ Future<void> _addToExisting(LibraryProvider lib, Map<String, dynamic> playlist) async {
+ setState(() => _adding = true);
+ final playlistId = playlist['id'] as String;
+ final name = playlist['name'] as String? ?? 'Playlist';
+ final ok = await lib.addToPlaylist(
+ playlistId, widget.libraryItemId, episodeId: widget.episodeId,
+ );
+ if (mounted) {
+ Navigator.pop(context);
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ duration: const Duration(seconds: 3),
+ content: Text(ok ? 'Added to "$name"' : 'Failed to add'),
+ behavior: SnackBarBehavior.floating,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ ));
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final lib = context.watch<LibraryProvider>();
+ final playlists = lib.playlists;
+
+ return SafeArea(
+ child: Padding(
+ padding: EdgeInsets.fromLTRB(
+ 16, 8, 16, 16 + MediaQuery.of(context).viewInsets.bottom,
+ ),
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
+ // Grab handle
+ Center(child: Container(
+ width: 40, height: 4,
+ margin: const EdgeInsets.only(bottom: 16),
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.24),
+ borderRadius: BorderRadius.circular(2),
+ ),
+ )),
+ // Title
+ Text('Add to Playlist', style: TextStyle(
+ color: cs.onSurface, fontSize: 16, fontWeight: FontWeight.w600,
+ )),
+ const SizedBox(height: 12),
+ // New playlist
+ if (_creatingNew)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: Row(children: [
+ Expanded(child: TextField(
+ controller: _nameController,
+ autofocus: true,
+ style: TextStyle(color: cs.onSurface, fontSize: 14),
+ decoration: InputDecoration(
+ hintText: 'Playlist name',
+ hintStyle: TextStyle(color: cs.onSurface.withValues(alpha: 0.4)),
+ isDense: true,
+ contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
+ enabledBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(12),
+ borderSide: BorderSide(color: cs.onSurface.withValues(alpha: 0.2)),
+ ),
+ ),
+ onSubmitted: (_) => _createAndAdd(lib),
+ )),
+ const SizedBox(width: 8),
+ _adding
+ ? const SizedBox(width: 36, height: 36,
+ child: Padding(
+ padding: EdgeInsets.all(8),
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ))
+ : IconButton(
+ icon: Icon(Icons.check_rounded, color: cs.primary),
+ onPressed: () => _createAndAdd(lib),
+ ),
+ ]),
+ )
+ else
+ _sheetItem(cs, Icons.add_rounded, 'New Playlist',
+ onTap: () => setState(() => _creatingNew = true)),
+ // Existing playlists
+ if (playlists.isNotEmpty) ...[
+ const SizedBox(height: 4),
+ ...playlists.map((p) {
+ final pm = p as Map<String, dynamic>;
+ final name = pm['name'] as String? ?? 'Playlist';
+ final items = (pm['items'] as List<dynamic>?) ?? [];
+ // Check if item is already in this playlist
+ final alreadyIn = items.any((item) {
+ final im = item as Map<String, dynamic>;
+ final lid = im['libraryItemId'] as String?;
+ final eid = im['episodeId'] as String?;
+ return lid == widget.libraryItemId &&
+ (widget.episodeId == null ? eid == null : eid == widget.episodeId);
+ });
+ return _sheetItem(
+ cs,
+ alreadyIn ? Icons.check_rounded : Icons.playlist_play_rounded,
+ '$name (${items.length})',
+ enabled: !alreadyIn && !_adding,
+ onTap: () => _addToExisting(lib, pm),
+ );
+ }),
+ ],
+ ]),
+ ),
+ );
+ }
+
+ Widget _sheetItem(ColorScheme cs, IconData icon, String label,
+ {required VoidCallback onTap, bool enabled = true}) {
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: GestureDetector(
+ onTap: enabled ? onTap : null,
+ child: Container(
+ height: 44,
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: enabled ? 0.06 : 0.03),
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(color: cs.onSurface.withValues(alpha: 0.1)),
+ ),
+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ Icon(icon, size: 16,
+ color: enabled ? cs.onSurfaceVariant : cs.onSurfaceVariant.withValues(alpha: 0.4)),
+ const SizedBox(width: 8),
+ Text(label, style: TextStyle(
+ color: enabled ? cs.onSurfaceVariant : cs.onSurfaceVariant.withValues(alpha: 0.4),
+ fontSize: 13, fontWeight: FontWeight.w500,
+ )),
+ ]),
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/series_card.dart b/lib/widgets/series_card.dart
index 7fa7e57d..0cc60de3 100644
--- a/lib/widgets/series_card.dart
+++ b/lib/widgets/series_card.dart
@@ -1,4 +1,10 @@
+import 'dart:io';
import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import 'package:cached_network_image/cached_network_image.dart';
+import '../providers/auth_provider.dart';
+import '../providers/library_provider.dart';
+import 'series_books_sheet.dart';
class SeriesCard extends StatelessWidget {
final Map<String, dynamic> series;
@@ -9,91 +15,259 @@ class SeriesCard extends StatelessWidget {
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 name = series['name'] as String? ?? 'Unknown Series';
+ final seriesId = series['id'] as String? ?? '';
final books = series['books'] as List<dynamic>? ?? [];
final bookCount = books.length;
- return Card(
- elevation: 0,
- color: cs.tertiaryContainer.withValues(alpha: 0.4),
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
- clipBehavior: Clip.antiAlias,
- child: InkWell(
- onTap: () {},
- borderRadius: BorderRadius.circular(12),
- child: Stack(
- fit: StackFit.expand,
- children: [
- // Stacked book spines visual effect
- Column(
- children: [
- Expanded(
- child: Container(
- decoration: BoxDecoration(
- gradient: LinearGradient(
- begin: Alignment.topLeft,
- end: Alignment.bottomRight,
- colors: [
- cs.tertiaryContainer,
- cs.tertiaryContainer.withValues(alpha: 0.6),
- ],
+ // Gather up to 4 cover URLs
+ final coverUrls = books
+ .take(4)
+ .map((b) {
+ final bookId = (b as Map<String, dynamic>)['id'] as String? ?? '';
+ return bookId.isNotEmpty ? lib.getCoverUrl(bookId) : null;
+ })
+ .toList();
+
+ // Calculate series progress
+ double totalProgress = 0;
+ int finished = 0;
+ for (final b in books) {
+ final bookId = (b as Map<String, dynamic>)['id'] as String? ?? '';
+ if (bookId.isEmpty) continue;
+ final pd = lib.getProgressData(bookId);
+ if (pd?['isFinished'] == true) {
+ finished++;
+ totalProgress += 1.0;
+ } else {
+ totalProgress += lib.getProgress(bookId);
+ }
+ }
+ final seriesProgress = books.isNotEmpty ? totalProgress / books.length : 0.0;
+
+ return GestureDetector(
+ onTap: () {
+ if (seriesId.isNotEmpty) {
+ showSeriesBooksSheet(
+ context,
+ seriesName: name,
+ seriesId: seriesId,
+ books: const [],
+ serverUrl: auth.serverUrl,
+ token: auth.token,
+ );
+ }
+ },
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ // Stacked covers
+ AspectRatio(
+ aspectRatio: 1,
+ child: _StackedCovers(
+ coverUrls: coverUrls,
+ numBooks: bookCount,
+ mediaHeaders: lib.mediaHeaders,
+ cs: cs,
+ seriesProgress: seriesProgress,
+ booksFinished: finished,
+ ),
+ ),
+ const SizedBox(height: 5),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 2),
+ child: Text(
+ name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.onSurface,
+ fontSize: 11,
+ ),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 2),
+ child: Text(
+ '$bookCount book${bookCount != 1 ? 's' : ''}',
+ style: tt.labelSmall?.copyWith(
+ color: cs.onSurfaceVariant,
+ fontSize: 10,
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+/// Stacked cover art for series - shows up to 4 covers layered.
+class _StackedCovers extends StatelessWidget {
+ final List<String?> coverUrls;
+ final int numBooks;
+ final Map<String, String> mediaHeaders;
+ final ColorScheme cs;
+ final double seriesProgress;
+ final int booksFinished;
+
+ const _StackedCovers({
+ required this.coverUrls,
+ required this.numBooks,
+ required this.mediaHeaders,
+ required this.cs,
+ this.seriesProgress = 0,
+ this.booksFinished = 0,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final count = coverUrls.length.clamp(1, 4);
+ const inset = 5.0;
+ final totalOffset = count > 1 ? inset * (count - 1) : 0.0;
+
+ return Stack(
+ children: [
+ for (int i = count - 1; i > 0; i--)
+ Positioned(
+ top: (totalOffset - i * inset),
+ right: (totalOffset - i * inset),
+ left: i * inset,
+ bottom: i * inset,
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(10),
+ boxShadow: [
+ BoxShadow(
+ color: Colors.black.withValues(alpha: 0.15),
+ blurRadius: 2,
+ offset: const Offset(-1, 1),
+ ),
+ ],
+ ),
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(10),
+ child: _coverImage(coverUrls[i]),
+ ),
+ ),
+ ),
+ Positioned(
+ top: totalOffset,
+ right: totalOffset,
+ left: 0,
+ bottom: 0,
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(10),
+ boxShadow: count > 1
+ ? [BoxShadow(
+ color: Colors.black.withValues(alpha: 0.2),
+ blurRadius: 3,
+ offset: const Offset(-1, 1),
+ )]
+ : [],
+ ),
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(10),
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ _coverImage(coverUrls.isNotEmpty ? coverUrls[0] : null),
+ if (seriesProgress > 0 && booksFinished < numBooks)
+ Positioned(
+ left: 0, right: 0, bottom: 0,
+ child: LinearProgressIndicator(
+ value: seriesProgress.clamp(0.0, 1.0),
+ minHeight: 3,
+ backgroundColor: Colors.black38,
+ valueColor: AlwaysStoppedAnimation(cs.primary),
),
),
- child: Center(
- child: Icon(
- Icons.library_books_rounded,
- size: 40,
- color: cs.onTertiaryContainer.withValues(alpha: 0.5),
+ if (booksFinished > 0 && booksFinished >= numBooks)
+ Positioned(
+ left: 0, right: 0, bottom: 0,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3),
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.bottomCenter,
+ end: Alignment.topCenter,
+ colors: [
+ Colors.black.withValues(alpha: 0.7),
+ Colors.black.withValues(alpha: 0.0),
+ ],
+ ),
+ ),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Icon(Icons.check_circle_rounded, size: 10,
+ color: Colors.greenAccent),
+ const SizedBox(width: 3),
+ Text('Finished',
+ style: TextStyle(fontSize: 9, fontWeight: FontWeight.w600,
+ color: Colors.white.withValues(alpha: 0.9))),
+ ],
+ ),
),
),
- ),
- ),
- ],
- ),
- // Info overlay at bottom
- Positioned(
- left: 0,
- right: 0,
- bottom: 0,
- child: Container(
- padding: const EdgeInsets.all(10),
- decoration: BoxDecoration(
- gradient: LinearGradient(
- begin: Alignment.topCenter,
- end: Alignment.bottomCenter,
- colors: [
- Colors.transparent,
- cs.surface.withValues(alpha: 0.9),
- ],
- ),
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- name,
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
- style: tt.labelMedium?.copyWith(
- fontWeight: FontWeight.w600,
- color: cs.onSurface,
+ Positioned(
+ top: 4, right: 4,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
+ decoration: BoxDecoration(
+ color: cs.primaryContainer,
+ borderRadius: BorderRadius.circular(8),
),
- ),
- const SizedBox(height: 2),
- Text(
- '$bookCount book${bookCount != 1 ? 's' : ''}',
- style: tt.labelSmall?.copyWith(
- color: cs.onSurfaceVariant,
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.auto_stories_rounded, size: 9, color: cs.onPrimaryContainer),
+ const SizedBox(width: 2),
+ Text(booksFinished > 0 && booksFinished < numBooks
+ ? '$booksFinished/$numBooks'
+ : '$numBooks',
+ style: TextStyle(fontSize: 8, fontWeight: FontWeight.w700,
+ color: cs.onPrimaryContainer)),
+ ],
),
),
- ],
- ),
+ ),
+ ],
),
),
- ],
+ ),
),
+ ],
+ );
+ }
+
+ Widget _coverImage(String? url) {
+ if (url == null) return _placeholder();
+ if (url.startsWith('/')) {
+ return Image.file(File(url), fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => _placeholder());
+ }
+ return CachedNetworkImage(
+ imageUrl: url,
+ fit: BoxFit.cover,
+ httpHeaders: mediaHeaders,
+ placeholder: (_, __) => _placeholder(),
+ errorWidget: (_, __, ___) => _placeholder(),
+ );
+ }
+
+ Widget _placeholder() {
+ return Container(
+ color: cs.surfaceContainerHighest,
+ child: Center(
+ child: Icon(Icons.auto_stories_rounded,
+ size: 24, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
),
);
}