Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Sleep rewind slider, ETag caching, series/author view modes, grid badges, inactive card buttons, accurate card time, create user fix, large series improvements

Nathan Poulsond0d7064ff2f0
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 340b632d..beed0069 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -67,6 +67,20 @@ class LibraryProvider extends ChangeNotifier {
Set<String> _hiddenSectionIds = {};
bool _applyDefaultPlaylistCollectionHiding = false;
+ // Series books cache — keyed by seriesId, holds fetched books + total
+ final Map<String, Map<String, dynamic>> _seriesBooksCache = {};
+ Map<String, dynamic>? getSeriesBooksCache(String seriesId) => _seriesBooksCache[seriesId];
+ void setSeriesBooksCache(String seriesId, List<dynamic> books, int total) {
+ _seriesBooksCache[seriesId] = {'books': books, 'total': total};
+ }
+
+ // Series tab cache — keyed by "libraryId:sort:desc", holds series list + total
+ final Map<String, Map<String, dynamic>> _seriesTabCache = {};
+ Map<String, dynamic>? getSeriesTabCache(String key) => _seriesTabCache[key];
+ void setSeriesTabCache(String key, List<Map<String, dynamic>> items, int total) {
+ _seriesTabCache[key] = {'items': items, 'total': total};
+ }
+
// Per-series/show rolling download opt-in
Set<String> _rollingDownloadSeries = {};
@@ -541,6 +555,8 @@ class LibraryProvider extends ChangeNotifier {
_absorbingItemCache.clear();
_rollingDownloadSeries.clear();
_itemUpdatedAt.clear();
+ _seriesBooksCache.clear();
+ _seriesTabCache.clear();
_personalizedInFlight = null;
_lastPersonalizedFetchAt = null;
_lastPersonalizedFetchLibraryId = null;
diff --git a/lib/screens/admin_users_screen.dart b/lib/screens/admin_users_screen.dart
index 9e671960..606406ee 100644
--- a/lib/screens/admin_users_screen.dart
+++ b/lib/screens/admin_users_screen.dart
@@ -617,7 +617,8 @@ class _UserEditorSheetState extends State<_UserEditorSheet> {
bool ok;
if (_isNew) {
final r = await api.createUser(username: username, password: _passwordCtrl.text, type: _type,
- permissions: perms, librariesAccessible: _accessAllLibraries ? [] : _selectedLibraries.toList());
+ permissions: perms, librariesAccessible: _accessAllLibraries ? [] : _selectedLibraries.toList(),
+ isActive: _isActive);
ok = r != null;
} else {
final up = <String, dynamic>{'type': _type, 'isActive': _isActive, 'isLocked': _isLocked,
diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dart
index fdfefad2..02b09d5c 100644
--- a/lib/screens/library_screen.dart
+++ b/lib/screens/library_screen.dart
@@ -6,6 +6,7 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
import '../providers/library_provider.dart';
+import '../services/api_service.dart';
import '../services/download_service.dart';
import '../services/audio_player_service.dart';
import '../widgets/absorb_page_header.dart';
@@ -517,6 +518,30 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
sort = 'name'; break;
}
+ // For large libraries (250+ series), serve cached data on first load
+ final cacheKey = '${lib.selectedLibraryId}:$sort:${_seriesSortAsc ? 0 : 1}';
+ if (_seriesPage == 0 && _seriesItems.isEmpty) {
+ final cached = lib.getSeriesTabCache(cacheKey);
+ if (cached != null) {
+ final cachedTotal = (cached['total'] as int?) ?? 0;
+ if (cachedTotal >= 250) {
+ final items = (cached['items'] as List<Map<String, dynamic>>?) ?? [];
+ if (items.isNotEmpty && mounted) {
+ setState(() {
+ _seriesItems.addAll(items);
+ _totalSeries = cachedTotal;
+ _seriesPage = (items.length / 50).ceil();
+ _hasMoreSeries = items.length < cachedTotal;
+ _isLoadingSeriesPage = false;
+ });
+ // Refresh in background
+ _refreshSeriesInBackground(api, lib, sort, cacheKey);
+ return;
+ }
+ }
+ }
+ }
+
final result = await api.getLibrarySeries(
lib.selectedLibraryId!,
page: _seriesPage,
@@ -539,11 +564,48 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
_hasMoreSeries = _seriesItems.length < total;
_isLoadingSeriesPage = false;
});
+ // Update cache
+ if (total >= 250) {
+ lib.setSeriesTabCache(cacheKey, List<Map<String, dynamic>>.from(_seriesItems), total);
+ }
} else if (mounted) {
setState(() => _isLoadingSeriesPage = false);
}
}
+ Future<void> _refreshSeriesInBackground(ApiService api, LibraryProvider lib, String sort, String cacheKey) async {
+ final allItems = <Map<String, dynamic>>[];
+ int page = 0;
+ int total = 0;
+ while (true) {
+ final result = await api.getLibrarySeries(
+ lib.selectedLibraryId!,
+ page: page,
+ limit: 50,
+ sort: sort,
+ desc: _seriesSortAsc ? 0 : 1,
+ );
+ if (result == null) break;
+ final results = (result['results'] as List<dynamic>?) ?? [];
+ total = (result['total'] as int?) ?? 0;
+ for (final r in results) {
+ if (r is Map<String, dynamic>) allItems.add(r);
+ }
+ if (allItems.length >= total || results.isEmpty) break;
+ page++;
+ }
+ if (allItems.isNotEmpty && mounted) {
+ lib.setSeriesTabCache(cacheKey, allItems, total);
+ setState(() {
+ _seriesItems.clear();
+ _seriesItems.addAll(allItems);
+ _totalSeries = total;
+ _seriesPage = (allItems.length / 50).ceil();
+ _hasMoreSeries = allItems.length < total;
+ });
+ }
+ }
+
// ══════════════════════════════════════════════════════════════
// AUTHORS TAB - Load all authors
// ══════════════════════════════════════════════════════════════
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index 0c9ddd46..8c9e0764 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -47,6 +47,38 @@ class ApiService {
ApiService({required this.baseUrl, required this.token, this.customHeaders = const {}});
+ // ── HTTP ETag cache ──
+ // Stores ETag and response body per URL path so we can send If-None-Match
+ // and get 304 Not Modified on unchanged data (avoids re-serializing on server).
+ static final Map<String, String> _etagCache = {};
+ static final Map<String, String> _etagBodyCache = {};
+
+ /// GET with ETag support. Returns cached body on 304.
+ Future<http.Response> _cachedGet(Uri url, {Duration timeout = const Duration(seconds: 15)}) async {
+ final key = url.toString();
+ final headers = Map<String, String>.from(_headers);
+ final etag = _etagCache[key];
+ if (etag != null && _etagBodyCache.containsKey(key)) {
+ headers['If-None-Match'] = etag;
+ }
+ final resp = await http.get(url, headers: headers).timeout(timeout);
+ if (resp.statusCode == 304 && _etagBodyCache.containsKey(key)) {
+ return http.Response(_etagBodyCache[key]!, 200, headers: resp.headers);
+ }
+ // If 304 but no cached body, retry without If-None-Match
+ if (resp.statusCode == 304) {
+ debugPrint('[API] Got 304 without cached body, retrying: $key');
+ _etagCache.remove(key);
+ return http.get(url, headers: _headers).timeout(timeout);
+ }
+ final newEtag = resp.headers['etag'];
+ if (newEtag != null && resp.statusCode == 200) {
+ _etagCache[key] = newEtag;
+ _etagBodyCache[key] = resp.body;
+ }
+ return resp;
+ }
+
Map<String, String> get _headers => {
...customHeaders,
'Authorization': 'Bearer $token',
@@ -156,11 +188,11 @@ class ApiService {
}
if (limit != null) query['limit'] = '$limit';
- final response = await http.get(
+ final response = await _cachedGet(
Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/personalized')
.replace(queryParameters: query.isEmpty ? null : query),
- headers: _headers,
- ).timeout(const Duration(seconds: 15));
+ timeout: const Duration(seconds: 15),
+ );
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
@@ -195,10 +227,10 @@ class ApiService {
if (filter != null) url += '&filter=$filter';
if (expanded) url += '&minified=0';
if (collapseSeries) url += '&collapseseries=1';
- final response = await http.get(
+ final response = await _cachedGet(
Uri.parse(url),
- headers: _headers,
- ).timeout(const Duration(seconds: 15));
+ timeout: const Duration(seconds: 15),
+ );
if (response.statusCode == 200) {
return jsonDecode(response.body) as Map<String, dynamic>;
@@ -271,13 +303,13 @@ class ApiService {
int desc = 1,
}) async {
try {
- final response = await http.get(
+ final response = await _cachedGet(
Uri.parse(
'$_cleanBaseUrl/api/libraries/$libraryId/series'
'?page=$page&limit=$limit&sort=$sort&desc=$desc',
),
- headers: _headers,
- ).timeout(const Duration(seconds: 15));
+ timeout: const Duration(seconds: 30),
+ );
if (response.statusCode == 200) {
return jsonDecode(response.body) as Map<String, dynamic>;
@@ -780,7 +812,9 @@ class ApiService {
}
/// Get a single series with its books (paginated).
- Future<Map<String, dynamic>?> getSeries(String seriesId, {String? libraryId}) async {
+ /// If [onPageLoaded] is provided, it's called after each page with the
+ /// cumulative results and total so the UI can show books as they arrive.
+ Future<Map<String, dynamic>?> getSeries(String seriesId, {String? libraryId, void Function(List<dynamic> books, int total, {double? totalDuration})? onPageLoaded}) async {
try {
Map<String, dynamic>? seriesMeta;
@@ -789,7 +823,7 @@ class ApiService {
final metaResp = await http.get(
Uri.parse('$_cleanBaseUrl/api/libraries/$libraryId/series/$seriesId'),
headers: _headers,
- ).timeout(const Duration(seconds: 15));
+ ).timeout(const Duration(seconds: 30));
if (metaResp.statusCode == 200) {
seriesMeta = jsonDecode(metaResp.body) as Map<String, dynamic>;
}
@@ -799,7 +833,7 @@ class ApiService {
// ABS filter format: series.<base64(seriesId)>
if (libraryId != null) {
final filterValue = base64Encode(utf8.encode(seriesId));
- const pageSize = 500;
+ const pageSize = 100;
final allResults = <dynamic>[];
int total = 0;
int page = 0;
@@ -808,12 +842,16 @@ class ApiService {
final itemsResp = await http.get(
Uri.parse(url),
headers: _headers,
- ).timeout(const Duration(seconds: 15));
- if (itemsResp.statusCode != 200) break;
+ ).timeout(const Duration(seconds: 30));
+ if (itemsResp.statusCode != 200) {
+ debugPrint('[API] getSeries items page $page failed: ${itemsResp.statusCode}');
+ break;
+ }
final data = jsonDecode(itemsResp.body) as Map<String, dynamic>;
final results = data['results'] as List<dynamic>? ?? [];
total = (data['total'] as num?)?.toInt() ?? results.length;
allResults.addAll(results);
+ onPageLoaded?.call(allResults, total, totalDuration: (seriesMeta?['totalDuration'] as num?)?.toDouble());
if (allResults.length >= total || results.isEmpty) break;
page++;
}
@@ -823,6 +861,7 @@ class ApiService {
'name': seriesMeta?['name'] ?? '',
'books': allResults,
'total': total,
+ if (seriesMeta != null) 'totalDuration': seriesMeta['totalDuration'],
};
}
}
@@ -1102,12 +1141,14 @@ class ApiService {
required String type,
Map<String, dynamic>? permissions,
List<String>? librariesAccessible,
+ bool isActive = true,
}) async {
try {
final body = <String, dynamic>{
'username': username,
'password': password,
'type': type,
+ 'isActive': isActive,
};
if (permissions != null) body['permissions'] = permissions;
if (librariesAccessible != null) body['librariesAccessible'] = librariesAccessible;
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 1ef6f9a5..2373209f 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -209,6 +209,11 @@ class PlayerSettings {
static Future<int> getSleepTimerTab() => _get('sleepTimerTab', 0);
static Future<void> setSleepTimerTab(int tab) => _set('sleepTimerTab', tab);
+ static Future<bool> getSheetGridView() => _get('sheetGridView', false);
+ static Future<void> setSheetGridView(bool value) => _set('sheetGridView', value);
+ static Future<bool> getSheetCollapseSeries() => _get('sheetCollapseSeries', true);
+ static Future<void> setSheetCollapseSeries(bool value) => _set('sheetCollapseSeries', value);
+
static Future<bool> getHideEbookOnly() => _get('hideEbookOnly', false);
static Future<void> setHideEbookOnly(bool value) => _set('hideEbookOnly', value, notify: true);
diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dart
index 88c4f02a..a0556994 100644
--- a/lib/services/backup_service.dart
+++ b/lib/services/backup_service.dart
@@ -69,6 +69,11 @@ class BackupService {
'cardButtonLayout': await PlayerSettings.getCardButtonLayout(),
'rectangleCovers': await PlayerSettings.getRectangleCovers(),
'coverPlayButton': await PlayerSettings.getCoverPlayButton(),
+ 'whenFinished': await PlayerSettings.getWhenFinished(),
+ 'sleepRewindSeconds': await PlayerSettings.getSleepRewindSeconds(),
+ 'sleepTimerTab': await PlayerSettings.getSleepTimerTab(),
+ 'sheetGridView': await PlayerSettings.getSheetGridView(),
+ 'sheetCollapseSeries': await PlayerSettings.getSheetCollapseSeries(),
};
// AutoRewind (scoped)
@@ -252,6 +257,10 @@ class BackupService {
if (s['cardButtonLayout'] != null) PlayerSettings.setCardButtonLayout(s['cardButtonLayout'] as String);
if (s['rectangleCovers'] != null) PlayerSettings.setRectangleCovers(s['rectangleCovers'] as bool);
if (s['coverPlayButton'] != null) PlayerSettings.setCoverPlayButton(s['coverPlayButton'] as bool);
+ if (s['sleepRewindSeconds'] != null) PlayerSettings.setSleepRewindSeconds(s['sleepRewindSeconds'] as int);
+ if (s['sleepTimerTab'] != null) PlayerSettings.setSleepTimerTab(s['sleepTimerTab'] as int);
+ if (s['sheetGridView'] != null) PlayerSettings.setSheetGridView(s['sheetGridView'] as bool);
+ if (s['sheetCollapseSeries'] != null) PlayerSettings.setSheetCollapseSeries(s['sheetCollapseSeries'] as bool);
// AutoRewind (scoped via save())
final r = data['autoRewind'] as Map<String, dynamic>?;
diff --git a/lib/widgets/absorbing_card.dart b/lib/widgets/absorbing_card.dart
index fc5c237b..54047f3b 100644
--- a/lib/widgets/absorbing_card.dart
+++ b/lib/widgets/absorbing_card.dart
@@ -477,9 +477,18 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
child: StreamBuilder<Duration>(
stream: widget.player.absolutePositionStream,
builder: (_, snap) {
- final pos = _isActive
- ? (snap.data?.inMilliseconds ?? 0) / 1000.0
- : bookProgress * _effectiveDuration;
+ final double pos;
+ if (_isActive) {
+ pos = (snap.data?.inMilliseconds ?? 0) / 1000.0;
+ } else {
+ // Use exact currentTime from server progress if available,
+ // otherwise fall back to progress ratio * duration.
+ final pd = _episodeId != null
+ ? lib.getEpisodeProgressData(_itemId, _episodeId!)
+ : lib.getProgressData(_itemId);
+ final ct = (pd?['currentTime'] as num?)?.toDouble();
+ pos = (ct != null && ct > 0) ? ct : bookProgress * _effectiveDuration;
+ }
final speed = _speedAdjustedTime && _isActive ? widget.player.speed : 1.0;
final elapsed = pos / speed;
final remaining = (_effectiveDuration - pos) / speed;
@@ -930,8 +939,8 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
case 'chapters':
return CardWideButton(
icon: Icons.list_rounded, label: 'Chapters',
- accent: accent, isActive: _isPlaybackActive, large: large, compact: compact,
- onTap: () => _showChapters(context, accent, tt),
+ accent: accent, isActive: true, alwaysEnabled: true, large: large, compact: compact,
+ onTap: _chapters.isNotEmpty ? () => _showChapters(context, accent, tt) : null,
);
case 'speed':
return CardWideButton(
@@ -942,8 +951,8 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
case 'sleep':
return CardWideButton(
icon: Icons.bedtime_outlined, label: short ? 'Sleep' : 'Sleep Timer',
- accent: accent, isActive: _isPlaybackActive, large: large, compact: compact,
- child: CardSleepButtonInline(accent: accent, isActive: _isPlaybackActive, large: large, compact: compact),
+ accent: accent, isActive: true, alwaysEnabled: true, large: large, compact: compact,
+ child: CardSleepButtonInline(accent: accent, isActive: true, large: large, compact: compact),
);
case 'bookmarks':
return CardWideButton(
@@ -1003,7 +1012,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
case 'history':
return CardWideButton(
icon: Icons.history_rounded, label: (compact || short) ? 'History' : 'Playback History',
- accent: accent, isActive: _isActive, large: large, compact: compact,
+ accent: accent, isActive: true, alwaysEnabled: true, large: large, compact: compact,
onTap: () => _showHistory(context, accent, tt),
);
case 'remove':
@@ -1034,7 +1043,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
case 'chapters':
return MoreMenuItem(
icon: Icons.list_rounded, label: 'Chapters', accent: accent,
- enabled: _isPlaybackActive,
+ enabled: _chapters.isNotEmpty,
onTap: () { Navigator.pop(ctx); _showChapters(context, accent, tt); },
);
case 'speed':
@@ -1050,7 +1059,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
case 'sleep':
return MoreMenuItem(
icon: Icons.bedtime_outlined, label: 'Sleep Timer', accent: accent,
- enabled: _isPlaybackActive,
+ enabled: true,
onTap: () {
Navigator.pop(ctx);
showSleepTimerSheet(context, accent);
@@ -1117,7 +1126,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
case 'history':
return MoreMenuItem(
icon: Icons.history_rounded, label: 'Playback History', accent: accent,
- enabled: _isActive,
+ enabled: true,
onTap: () { Navigator.pop(ctx); _showHistory(context, accent, tt); },
);
case 'remove':
@@ -1202,10 +1211,20 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
// Find current chapter index for auto-scroll
int currentIdx = -1;
- if (_isPlaybackActive) {
- final pos = _isCastingThis
- ? cast.castPosition.inMilliseconds / 1000.0
- : widget.player.position.inMilliseconds / 1000.0;
+ {
+ double pos = 0;
+ if (_isCastingThis) {
+ pos = cast.castPosition.inMilliseconds / 1000.0;
+ } else if (_isActive) {
+ pos = widget.player.position.inMilliseconds / 1000.0;
+ } else {
+ // Use server progress currentTime when inactive
+ final lib = context.read<LibraryProvider>();
+ final pd = _episodeId != null
+ ? lib.getEpisodeProgressData(_itemId, _episodeId!)
+ : lib.getProgressData(_itemId);
+ pos = (pd?['currentTime'] as num?)?.toDouble() ?? 0;
+ }
for (int i = 0; i < chapters.length; i++) {
final ch = chapters[i] as Map<String, dynamic>;
final start = (ch['start'] as num?)?.toDouble() ?? 0;
diff --git a/lib/widgets/author_books_sheet.dart b/lib/widgets/author_books_sheet.dart
index 91e2951b..a4ff07d2 100644
--- a/lib/widgets/author_books_sheet.dart
+++ b/lib/widgets/author_books_sheet.dart
@@ -3,7 +3,12 @@ import 'package:cached_network_image/cached_network_image.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
import '../providers/library_provider.dart';
+import '../services/audio_player_service.dart';
+import 'library_grid_tiles.dart';
import 'library_search_results.dart';
+import 'series_books_sheet.dart';
+
+enum _AuthorLayout { list, grid }
/// Show a bottom sheet with author info and books.
void showAuthorDetailSheet(BuildContext context, {
@@ -62,13 +67,25 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {
String? _description;
String? _imageUrl;
bool _descExpanded = false;
+ _AuthorLayout _layout = _AuthorLayout.list;
+ bool _groupBySeries = true;
@override
void initState() {
super.initState();
+ _loadViewSettings();
_loadAuthorAndBooks();
}
+ Future<void> _loadViewSettings() async {
+ final grid = await PlayerSettings.getSheetGridView();
+ final collapse = await PlayerSettings.getSheetCollapseSeries();
+ if (mounted) setState(() {
+ _layout = grid ? _AuthorLayout.grid : _AuthorLayout.list;
+ _groupBySeries = collapse;
+ });
+ }
+
Future<void> _loadAuthorAndBooks() async {
final auth = context.read<AuthProvider>();
final api = auth.apiService;
@@ -117,90 +134,34 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {
final hasDesc = _description != null && _description!.isNotEmpty;
final sections = _buildSections();
- // Flatten sections into list items: header, description, then section widgets
- final items = <Widget>[
+ // Header + description are always at the top
+ final headerWidgets = <Widget>[
_buildHeader(cs, tt, headers),
if (hasDesc) _buildDescription(cs, tt),
+ if (_books.isNotEmpty) _buildViewModeBar(cs),
];
if (_books.isEmpty) {
- items.add(Center(
- child: Padding(
- padding: const EdgeInsets.only(top: 48),
- child: Text('No books found',
- style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
- ),
- ));
- } else {
- for (final section in sections) {
- final label = section.label;
- final books = section.books;
- // Section header with divider
- items.add(Padding(
- padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
- child: Row(children: [
- Expanded(child: Divider(color: cs.outlineVariant)),
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 12),
- child: Text(label,
- style: tt.labelMedium?.copyWith(
- color: cs.onSurfaceVariant,
- fontWeight: FontWeight.w600,
- )),
- ),
- Expanded(child: Divider(color: cs.outlineVariant)),
- ]),
- ));
- for (final book in books) {
- final bookId = book['id'] as String? ?? '';
- final bookTitle = (book['media'] as Map<String, dynamic>?)?['metadata']?['title'] as String? ?? 'Unknown';
- final isOnAbsorbing = lib.isOnAbsorbingList(bookId);
- items.add(Padding(
- padding: const EdgeInsets.symmetric(horizontal: 16),
- child: Dismissible(
- key: ValueKey('absorb-$bookId'),
- direction: isOnAbsorbing ? DismissDirection.none : DismissDirection.startToEnd,
- confirmDismiss: (_) async {
- await lib.addToAbsorbingQueue(bookId);
- lib.absorbingItemCache[bookId] = Map<String, dynamic>.from(book);
- if (context.mounted) {
- ScaffoldMessenger.of(context).showSnackBar(SnackBar(
- content: Text('Added "$bookTitle" to Absorbing'),
- behavior: SnackBarBehavior.floating,
- duration: const Duration(seconds: 2),
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
- ));
- }
- return false;
- },
- background: Container(
- alignment: Alignment.centerLeft,
- padding: const EdgeInsets.only(left: 20),
- decoration: BoxDecoration(
- color: cs.primary.withValues(alpha: 0.15),
- borderRadius: BorderRadius.circular(14),
- ),
- child: Icon(Icons.add_circle_outline_rounded, color: cs.primary),
- ),
- child: BookResultTile(
- item: book,
- serverUrl: widget.serverUrl,
- token: widget.token,
- popOnTap: true,
- subtitle: _sequenceFor(book, label),
- ),
+ return ListView(
+ controller: widget.scrollController,
+ padding: EdgeInsets.fromLTRB(0, 0, 0, bottomPad),
+ children: [
+ ...headerWidgets,
+ Center(
+ child: Padding(
+ padding: const EdgeInsets.only(top: 48),
+ child: Text('No books found',
+ style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
),
- ));
- }
- }
+ ),
+ ],
+ );
}
- return ListView.builder(
- controller: widget.scrollController,
- padding: EdgeInsets.fromLTRB(0, 0, 0, bottomPad),
- itemCount: items.length,
- itemBuilder: (context, index) => items[index],
- );
+ if (_layout == _AuthorLayout.list) {
+ return _buildListView(cs, tt, lib, sections, headerWidgets, bottomPad);
+ }
+ return _buildGridView(cs, tt, lib, sections, headerWidgets, bottomPad);
}
List<_BookSection> _buildSections() {
@@ -216,10 +177,25 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {
final entries = seriesNameRaw.split(',').map((e) => e.trim()).where((e) => e.isNotEmpty).toList();
bool addedToSeries = false;
+ // Also try to get series ID from the structured series list
+ final seriesList = metadata['series'] as List<dynamic>? ?? [];
+
for (final entry in entries) {
final name = entry.replaceFirst(RegExp(r'\s*#\s*[\d.]+$'), '').trim();
if (name.isEmpty) continue;
- seriesMap.putIfAbsent(name, () => _BookSection(label: name, books: []));
+ // Try to find the series ID from the structured data
+ String? sid;
+ for (final s in seriesList) {
+ if (s is Map<String, dynamic> && (s['name'] as String? ?? '').toLowerCase() == name.toLowerCase()) {
+ sid = s['id'] as String?;
+ break;
+ }
+ }
+ seriesMap.putIfAbsent(name, () => _BookSection(label: name, seriesId: sid, books: []));
+ // Update seriesId if we found one and the section didn't have one
+ if (sid != null && seriesMap[name]!.seriesId == null) {
+ seriesMap[name] = _BookSection(label: name, seriesId: sid, books: seriesMap[name]!.books);
+ }
seriesMap[name]!.books.add(book);
addedToSeries = true;
}
@@ -287,6 +263,278 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {
return double.maxFinite;
}
+ Widget _buildViewModeBar(ColorScheme cs) {
+ Widget layoutBtn(IconData icon, _AuthorLayout mode, String tooltip) {
+ final active = _layout == mode;
+ return IconButton(
+ icon: Icon(icon, size: 20, color: active ? cs.primary : cs.onSurfaceVariant),
+ tooltip: tooltip,
+ visualDensity: VisualDensity.compact,
+ onPressed: () {
+ setState(() => _layout = mode);
+ PlayerSettings.setSheetGridView(mode == _AuthorLayout.grid);
+ },
+ );
+ }
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),
+ child: Row(
+ children: [
+ IconButton(
+ icon: Icon(Icons.collections_bookmark_rounded, size: 20,
+ color: _groupBySeries ? cs.primary : cs.onSurfaceVariant),
+ tooltip: 'Group by series',
+ visualDensity: VisualDensity.compact,
+ onPressed: () {
+ setState(() => _groupBySeries = !_groupBySeries);
+ PlayerSettings.setSheetCollapseSeries(_groupBySeries);
+ },
+ ),
+ const Spacer(),
+ layoutBtn(Icons.view_list_rounded, _AuthorLayout.list, 'List'),
+ layoutBtn(Icons.apps_rounded, _AuthorLayout.grid, 'Grid'),
+ ],
+ ),
+ );
+ }
+
+ /// Build a flat list of items mixing collapsed series tiles and standalone books.
+ List<dynamic> _buildCollapsedItems(List<_BookSection> sections) {
+ final items = <dynamic>[];
+ for (final section in sections) {
+ if (section.label == 'Standalone') {
+ items.addAll(section.books);
+ } else {
+ items.add(section); // collapsed series
+ }
+ }
+ return items;
+ }
+
+ Widget _buildListView(ColorScheme cs, TextTheme tt, LibraryProvider lib,
+ List<_BookSection> sections, List<Widget> headerWidgets, double bottomPad) {
+ final items = <Widget>[...headerWidgets];
+ if (_groupBySeries) {
+ // Collapsed: series as tappable rows, standalones as book tiles
+ final collapsed = _buildCollapsedItems(sections);
+ for (final item in collapsed) {
+ if (item is _BookSection) {
+ items.add(_collapsedSeriesTile(cs, tt, lib, item));
+ } else if (item is Map<String, dynamic>) {
+ items.add(_dismissibleBookTile(lib, cs, item, 'Standalone'));
+ }
+ }
+ } else {
+ for (final section in sections) {
+ items.add(_sectionDivider(cs, tt, section.label));
+ for (final book in section.books) {
+ items.add(_dismissibleBookTile(lib, cs, book, section.label));
+ }
+ }
+ }
+ return ListView.builder(
+ controller: widget.scrollController,
+ padding: EdgeInsets.fromLTRB(0, 0, 0, bottomPad),
+ itemCount: items.length,
+ itemBuilder: (context, index) => items[index],
+ );
+ }
+
+ Widget _buildGridView(ColorScheme cs, TextTheme tt, LibraryProvider lib,
+ List<_BookSection> sections, List<Widget> headerWidgets, double bottomPad) {
+ if (_groupBySeries) {
+ // Collapsed: mix series tiles and standalone book tiles in a grid
+ final collapsed = _buildCollapsedItems(sections);
+ return CustomScrollView(
+ controller: widget.scrollController,
+ slivers: [
+ SliverList(delegate: SliverChildListDelegate(headerWidgets)),
+ SliverPadding(
+ padding: EdgeInsets.fromLTRB(16, 0, 16, bottomPad),
+ sliver: SliverGrid(
+ gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
+ crossAxisCount: 3, mainAxisSpacing: 8, crossAxisSpacing: 8, childAspectRatio: 0.55,
+ ),
+ delegate: SliverChildBuilderDelegate((_, i) {
+ final item = collapsed[i];
+ if (item is _BookSection) {
+ return _collapsedSeriesGridTile(cs, tt, lib, item);
+ }
+ return GridBookTile(item: item as Map<String, dynamic>);
+ }, childCount: collapsed.length),
+ ),
+ ),
+ ],
+ );
+ }
+ // Non-collapsed grid with series dividers
+ return CustomScrollView(
+ controller: widget.scrollController,
+ slivers: [
+ SliverList(delegate: SliverChildListDelegate(headerWidgets)),
+ for (final section in sections) ...[
+ SliverToBoxAdapter(child: _sectionDivider(cs, tt, section.label)),
+ SliverPadding(
+ padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),
+ sliver: SliverGrid(
+ gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
+ crossAxisCount: 3, mainAxisSpacing: 8, crossAxisSpacing: 8, childAspectRatio: 0.55,
+ ),
+ delegate: SliverChildBuilderDelegate(
+ (_, i) => GridBookTile(item: section.books[i], sequenceBadge: _sequenceFor(section.books[i], section.label)?.replaceFirst('#', '')),
+ childCount: section.books.length,
+ ),
+ ),
+ ),
+ ],
+ SliverPadding(padding: EdgeInsets.only(bottom: bottomPad)),
+ ],
+ );
+ }
+
+ Widget _collapsedSeriesTile(ColorScheme cs, TextTheme tt, LibraryProvider lib, _BookSection section) {
+ final bookCount = section.books.length;
+ final headers = lib.mediaHeaders;
+ final coverUrls = section.books.take(3).map((b) {
+ final id = b['id'] as String? ?? '';
+ return id.isNotEmpty ? lib.getCoverUrl(id) : null;
+ }).toList();
+ final coverCount = coverUrls.length.clamp(1, 3);
+ final stackWidth = 40.0 + (coverCount - 1) * 8.0;
+
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
+ child: Material(
+ color: Colors.transparent,
+ child: InkWell(
+ borderRadius: BorderRadius.circular(12),
+ onTap: () => _openSeriesSheet(section),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 10),
+ child: Row(children: [
+ SizedBox(
+ width: stackWidth, height: 40,
+ child: Stack(children: [
+ for (int i = coverCount - 1; i >= 0; i--)
+ Positioned(
+ left: i * 8.0,
+ child: Container(
+ width: 40, height: 40,
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(6),
+ boxShadow: i > 0 ? [BoxShadow(color: Colors.black.withValues(alpha: 0.15), blurRadius: 2, offset: const Offset(-1, 1))] : [],
+ ),
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(6),
+ child: coverUrls[i] != null
+ ? CachedNetworkImage(imageUrl: coverUrls[i]!, fit: BoxFit.cover, httpHeaders: headers, width: 40, height: 40,
+ errorWidget: (_, __, ___) => Container(color: cs.surfaceContainerHighest,
+ child: Icon(Icons.auto_stories_rounded, size: 18, color: cs.onSurfaceVariant)))
+ : Container(color: cs.surfaceContainerHighest,
+ child: Icon(Icons.auto_stories_rounded, size: 18, color: cs.onSurfaceVariant)),
+ ),
+ ),
+ ),
+ ]),
+ ),
+ const SizedBox(width: 12),
+ Expanded(child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(section.label, style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600),
+ maxLines: 1, overflow: TextOverflow.ellipsis),
+ Text('$bookCount ${bookCount == 1 ? 'book' : 'books'}',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ ],
+ )),
+ Icon(Icons.chevron_right_rounded, size: 20, color: cs.onSurfaceVariant),
+ ]),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _collapsedSeriesGridTile(ColorScheme cs, TextTheme tt, LibraryProvider lib, _BookSection section) {
+ return GridSeriesTileDirect(series: {
+ 'name': section.label,
+ 'id': section.seriesId ?? '',
+ 'books': section.books,
+ });
+ }
+
+
+ void _openSeriesSheet(_BookSection section) {
+ if (section.seriesId != null) {
+ showSeriesBooksSheet(context,
+ seriesName: section.label,
+ seriesId: section.seriesId,
+ books: section.books,
+ serverUrl: widget.serverUrl,
+ token: widget.token,
+ libraryId: widget.libraryId,
+ );
+ }
+ }
+
+ Widget _sectionDivider(ColorScheme cs, TextTheme tt, String label) {
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
+ child: Row(children: [
+ Expanded(child: Divider(color: cs.outlineVariant)),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ child: Text(label, style: tt.labelMedium?.copyWith(
+ color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),
+ ),
+ Expanded(child: Divider(color: cs.outlineVariant)),
+ ]),
+ );
+ }
+
+ Widget _dismissibleBookTile(LibraryProvider lib, ColorScheme cs, Map<String, dynamic> book, String sectionLabel) {
+ final bookId = book['id'] as String? ?? '';
+ final bookTitle = (book['media'] as Map<String, dynamic>?)?['metadata']?['title'] as String? ?? 'Unknown';
+ final isOnAbsorbing = lib.isOnAbsorbingList(bookId);
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Dismissible(
+ key: ValueKey('absorb-$bookId'),
+ direction: isOnAbsorbing ? DismissDirection.none : DismissDirection.startToEnd,
+ confirmDismiss: (_) async {
+ await lib.addToAbsorbingQueue(bookId);
+ lib.absorbingItemCache[bookId] = Map<String, dynamic>.from(book);
+ if (context.mounted) {
+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(
+ content: Text('Added "$bookTitle" to Absorbing'),
+ behavior: SnackBarBehavior.floating,
+ duration: const Duration(seconds: 2),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ ));
+ }
+ return false;
+ },
+ background: Container(
+ alignment: Alignment.centerLeft,
+ padding: const EdgeInsets.only(left: 20),
+ decoration: BoxDecoration(
+ color: cs.primary.withValues(alpha: 0.15),
+ borderRadius: BorderRadius.circular(14),
+ ),
+ child: Icon(Icons.add_circle_outline_rounded, color: cs.primary),
+ ),
+ child: BookResultTile(
+ item: book,
+ serverUrl: widget.serverUrl,
+ token: widget.token,
+ popOnTap: true,
+ subtitle: _sequenceFor(book, sectionLabel),
+ sequenceBadge: _sequenceFor(book, sectionLabel)?.replaceFirst('#', ''),
+ ),
+ ),
+ );
+ }
+
Widget _buildHeader(ColorScheme cs, TextTheme tt, Map<String, String> headers) {
return Padding(
padding: const EdgeInsets.fromLTRB(24, 0, 24, 12),
@@ -376,6 +624,7 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {
class _BookSection {
final String label;
+ final String? seriesId;
final List<Map<String, dynamic>> books;
- _BookSection({required this.label, required this.books});
+ _BookSection({required this.label, this.seriesId, required this.books});
}
diff --git a/lib/widgets/expanded_card.dart b/lib/widgets/expanded_card.dart
index 6d73e11e..81cb3c66 100644
--- a/lib/widgets/expanded_card.dart
+++ b/lib/widgets/expanded_card.dart
@@ -994,8 +994,8 @@ class _ExpandedCardState extends State<ExpandedCard> {
case 'chapters':
return CardWideButton(
icon: Icons.list_rounded, label: 'Chapters',
- accent: accent, isActive: _isPlaybackActive, large: large, compact: compact,
- onTap: () => _showChapters(context, accent, tt),
+ accent: accent, isActive: true, alwaysEnabled: true, large: large, compact: compact,
+ onTap: _chapters.isNotEmpty ? () => _showChapters(context, accent, tt) : null,
);
case 'speed':
return CardWideButton(
@@ -1006,8 +1006,8 @@ class _ExpandedCardState extends State<ExpandedCard> {
case 'sleep':
return CardWideButton(
icon: Icons.bedtime_outlined, label: short ? 'Sleep' : 'Sleep Timer',
- accent: accent, isActive: _isPlaybackActive, large: large, compact: compact,
- child: CardSleepButtonInline(accent: accent, isActive: _isPlaybackActive, large: large, compact: compact),
+ accent: accent, isActive: true, alwaysEnabled: true, large: large, compact: compact,
+ child: CardSleepButtonInline(accent: accent, isActive: true, large: large, compact: compact),
);
case 'bookmarks':
return CardWideButton(
@@ -1067,7 +1067,7 @@ class _ExpandedCardState extends State<ExpandedCard> {
case 'history':
return CardWideButton(
icon: Icons.history_rounded, label: (compact || short) ? 'History' : 'Playback History',
- accent: accent, isActive: _isActive, large: large, compact: compact,
+ accent: accent, isActive: true, alwaysEnabled: true, large: large, compact: compact,
onTap: () => _showHistory(context, accent, tt),
);
case 'remove':
@@ -1098,7 +1098,7 @@ class _ExpandedCardState extends State<ExpandedCard> {
case 'chapters':
return MoreMenuItem(
icon: Icons.list_rounded, label: 'Chapters', accent: accent,
- enabled: _isPlaybackActive,
+ enabled: _chapters.isNotEmpty,
onTap: () { Navigator.pop(ctx); _showChapters(context, accent, tt); },
);
case 'speed':
@@ -1114,7 +1114,7 @@ class _ExpandedCardState extends State<ExpandedCard> {
case 'sleep':
return MoreMenuItem(
icon: Icons.bedtime_outlined, label: 'Sleep Timer', accent: accent,
- enabled: _isPlaybackActive,
+ enabled: true,
onTap: () {
Navigator.pop(ctx);
showSleepTimerSheet(context, accent);
@@ -1181,7 +1181,7 @@ class _ExpandedCardState extends State<ExpandedCard> {
case 'history':
return MoreMenuItem(
icon: Icons.history_rounded, label: 'Playback History', accent: accent,
- enabled: _isActive,
+ enabled: true,
onTap: () { Navigator.pop(ctx); _showHistory(context, accent, tt); },
);
case 'remove':
@@ -1268,10 +1268,17 @@ class _ExpandedCardState extends State<ExpandedCard> {
// Find current chapter index for auto-scroll
int currentIdx = -1;
- if (_isPlaybackActive) {
- final pos = _isCastingThis
- ? cast.castPosition.inMilliseconds / 1000.0
- : widget.player.position.inMilliseconds / 1000.0;
+ {
+ double pos = 0;
+ if (_isCastingThis) {
+ pos = cast.castPosition.inMilliseconds / 1000.0;
+ } else if (_isActive) {
+ pos = widget.player.position.inMilliseconds / 1000.0;
+ } else {
+ final lib = context.read<LibraryProvider>();
+ final pd = lib.getProgressData(_itemId);
+ pos = (pd?['currentTime'] as num?)?.toDouble() ?? 0;
+ }
for (int i = 0; i < chapters.length; i++) {
final ch = chapters[i] as Map<String, dynamic>;
final start = (ch['start'] as num?)?.toDouble() ?? 0;
diff --git a/lib/widgets/library_grid_tiles.dart b/lib/widgets/library_grid_tiles.dart
index b12919eb..a058a15c 100644
--- a/lib/widgets/library_grid_tiles.dart
+++ b/lib/widgets/library_grid_tiles.dart
@@ -16,8 +16,9 @@ import 'author_books_sheet.dart';
class GridBookTile extends StatefulWidget {
final Map<String, dynamic> item;
final double coverAspectRatio;
+ final String? sequenceBadge;
- const GridBookTile({super.key, required this.item, this.coverAspectRatio = 1.0});
+ const GridBookTile({super.key, required this.item, this.coverAspectRatio = 1.0, this.sequenceBadge});
@override
State<GridBookTile> createState() => _GridBookTileState();
@@ -124,6 +125,21 @@ class _GridBookTileState extends State<GridBookTile> {
),
),
+ // Sequence badge
+ if (widget.sequenceBadge != null)
+ Positioned(
+ top: 4, left: 4,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
+ decoration: BoxDecoration(
+ color: Colors.black.withValues(alpha: 0.7),
+ borderRadius: BorderRadius.circular(6),
+ ),
+ child: Text('#${widget.sequenceBadge}',
+ style: const TextStyle(color: Colors.white, fontSize: 9, fontWeight: FontWeight.w600)),
+ ),
+ ),
+
// ── Banners ──
if (isFinished || isDownloaded)
Positioned(
diff --git a/lib/widgets/library_search_results.dart b/lib/widgets/library_search_results.dart
index 5c93ca3c..dd2b9dac 100644
--- a/lib/widgets/library_search_results.dart
+++ b/lib/widgets/library_search_results.dart
@@ -15,6 +15,7 @@ class BookResultTile extends StatelessWidget {
final String? token;
final bool popOnTap;
final String? subtitle;
+ final String? sequenceBadge;
const BookResultTile({
super.key,
@@ -23,6 +24,7 @@ class BookResultTile extends StatelessWidget {
required this.token,
this.popOnTap = false,
this.subtitle,
+ this.sequenceBadge,
});
@override
@@ -90,6 +92,19 @@ class BookResultTile extends StatelessWidget {
errorWidget: (_, __, ___) => _ph(cs),
)
: _ph(cs),
+ if (sequenceBadge != null)
+ Positioned(
+ top: 3, left: 3,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
+ decoration: BoxDecoration(
+ color: Colors.black.withValues(alpha: 0.7),
+ borderRadius: BorderRadius.circular(4),
+ ),
+ child: Text('#$sequenceBadge',
+ style: const TextStyle(color: Colors.white, fontSize: 8, fontWeight: FontWeight.w600)),
+ ),
+ ),
if (isFinished || isDownloaded)
Positioned(
left: 0, right: 0, bottom: 0,
diff --git a/lib/widgets/series_books_sheet.dart b/lib/widgets/series_books_sheet.dart
index a3e20b73..272cdf56 100644
--- a/lib/widgets/series_books_sheet.dart
+++ b/lib/widgets/series_books_sheet.dart
@@ -3,8 +3,10 @@ import 'package:cached_network_image/cached_network_image.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
import '../providers/library_provider.dart';
+import '../services/audio_player_service.dart';
import '../services/download_service.dart';
import 'book_detail_sheet.dart';
+import 'library_grid_tiles.dart';
import 'episode_list_sheet.dart';
/// Show a bottom sheet with all books in a series, sorted by sequence.
@@ -72,8 +74,11 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
bool _autoDownloadEnabled = false;
bool _didAutoScroll = false;
+ LibraryProvider? _lib;
int _totalBooks = 0;
+ double _seriesDuration = 0; // from metadata, available before all books load
+ bool _gridView = false;
@override
void initState() {
@@ -88,18 +93,24 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
// Fetch full data from API for proper sequence info
_fetchFromApi();
_loadAutoDownloadState();
- context.read<LibraryProvider>().addListener(_onLibraryChanged);
+ PlayerSettings.getSheetGridView().then((v) {
+ if (mounted && v != _gridView) setState(() => _gridView = v);
+ });
+ _lib = context.read<LibraryProvider>();
+ _lib!.addListener(_onLibraryChanged);
}
@override
void dispose() {
- context.read<LibraryProvider>().removeListener(_onLibraryChanged);
+ _lib?.removeListener(_onLibraryChanged);
super.dispose();
}
void _onLibraryChanged() {
- // Re-fetch to pick up cover changes, metadata updates, etc.
- _fetchFromApi();
+ // Just rebuild to pick up progress/cover changes — don't re-fetch
+ if (mounted) {
+ try { setState(() {}); } catch (_) {}
+ }
}
void _scrollToUpNext() {
@@ -222,23 +233,47 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
return;
}
final lib = context.read<LibraryProvider>();
- final data = await api.getSeries(seriesId, libraryId: widget.libraryId ?? lib.selectedLibraryId);
- if (data != null && mounted) {
- final rawBooks = data['books'] ?? data['libraryItems'] ?? [];
- final total = (data['total'] as num?)?.toInt() ?? 0;
- if (rawBooks is List && rawBooks.isNotEmpty) {
- final fetched = _unwrapBooks(rawBooks);
+ final libraryId = widget.libraryId ?? lib.selectedLibraryId;
+
+ // For large series (100+ books), serve cached data instantly
+ // then refresh in background. Small series always fetch fresh.
+ final cached = lib.getSeriesBooksCache(seriesId);
+ if (cached != null) {
+ final cachedTotal = (cached['total'] as num?)?.toInt() ?? 0;
+ if (cachedTotal >= 100) {
+ final fetched = _unwrapBooks(cached['books'] as List<dynamic>);
+ if (fetched.isNotEmpty && mounted) {
+ setState(() {
+ _books = fetched;
+ _sortBooks();
+ _isLoading = false;
+ _totalBooks = cachedTotal;
+ });
+ _scrollToUpNext();
+ }
+ }
+ }
+
+ // Fetch fresh data (updates cache as pages arrive)
+ final data = await api.getSeries(seriesId, libraryId: libraryId,
+ onPageLoaded: (books, total, {double? totalDuration}) {
+ if (!mounted) return;
+ final fetched = _unwrapBooks(books);
setState(() {
_books = fetched;
_sortBooks();
_isLoading = false;
_totalBooks = total;
+ if (totalDuration != null && totalDuration > 0) _seriesDuration = totalDuration;
});
- _scrollToUpNext();
- return;
- }
- }
- if (mounted) setState(() => _isLoading = false);
+ if (!_didAutoScroll) _scrollToUpNext();
+ // Update cache - re-read lib safely, only cache non-empty results
+ if (mounted && books.isNotEmpty) {
+ try { context.read<LibraryProvider>().setSeriesBooksCache(seriesId, books, total); } catch (_) {}
+ }
+ },
+ );
+ if (data == null && mounted) setState(() => _isLoading = false);
}
@@ -513,8 +548,12 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
TextSpan(
children: [
TextSpan(
- text: '${_totalBooks > 0 ? _totalBooks : _books.length} book${(_totalBooks > 0 ? _totalBooks : _books.length) != 1 ? 's' : ''} in this series'
- '${totalDuration > 0 ? ' · ${_formatDuration(totalDuration)}' : ''}',
+ text: () {
+ final displayDuration = _seriesDuration > totalDuration ? _seriesDuration : totalDuration;
+ final bookCount = _totalBooks > 0 ? _totalBooks : _books.length;
+ return '$bookCount book${bookCount != 1 ? 's' : ''} in this series'
+ '${displayDuration > 0 ? ' · ${_formatDuration(displayDuration)}' : ''}';
+ }(),
),
if (_autoDownloadEnabled) ...[
const TextSpan(text: ' · '),
@@ -555,6 +594,27 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
],
),
),
+ if (_books.isNotEmpty)
+ Padding(
+ padding: const EdgeInsets.only(right: 16),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.end,
+ children: [
+ IconButton(
+ icon: Icon(Icons.view_list_rounded, size: 20,
+ color: !_gridView ? cs.primary : cs.onSurfaceVariant),
+ visualDensity: VisualDensity.compact,
+ onPressed: () { setState(() => _gridView = false); PlayerSettings.setSheetGridView(false); },
+ ),
+ IconButton(
+ icon: Icon(Icons.apps_rounded, size: 20,
+ color: _gridView ? cs.primary : cs.onSurfaceVariant),
+ visualDensity: VisualDensity.compact,
+ onPressed: () { setState(() => _gridView = true); PlayerSettings.setSheetGridView(true); },
+ ),
+ ],
+ ),
+ ),
if (_isLoading && _books.isEmpty)
const Expanded(
child: Center(child: CircularProgressIndicator()))
@@ -566,6 +626,20 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
?.copyWith(color: cs.onSurfaceVariant)),
),
)
+ else if (_gridView)
+ Expanded(
+ child: ListenableBuilder(
+ listenable: DownloadService(),
+ builder: (context, _) => GridView.builder(
+ controller: widget.scrollController,
+ padding: EdgeInsets.fromLTRB(16, 0, 16, 24 + MediaQuery.of(context).viewPadding.bottom),
+ gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
+ crossAxisCount: 3, mainAxisSpacing: 8, crossAxisSpacing: 8, childAspectRatio: 0.55,
+ ),
+ itemCount: _books.length,
+ itemBuilder: (context, index) => GridBookTile(item: _books[index], sequenceBadge: _getSequenceString(_books[index])),
+ ),
+ ))
else
Expanded(
child: ListenableBuilder(
@@ -684,23 +758,17 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {
left: 4,
child: Container(
padding: const EdgeInsets.symmetric(
- horizontal: 6, vertical: 2),
+ horizontal: 5, vertical: 2),
decoration: BoxDecoration(
- color: cs.primary,
+ color: Colors.black.withValues(alpha: 0.7),
borderRadius:
- BorderRadius.circular(8),
- boxShadow: [
- BoxShadow(
- color: Colors.black
- .withValues(alpha: 0.3),
- blurRadius: 4)
- ],
+ BorderRadius.circular(6),
),
child: Text('#$sequence',
- style: TextStyle(
- color: cs.onPrimary,
- fontSize: 10,
- fontWeight: FontWeight.w800)),
+ style: const TextStyle(
+ color: Colors.white,
+ fontSize: 9,
+ fontWeight: FontWeight.w600)),
),
),
if (!isDownloaded && isDownloading)
diff --git a/lib/widgets/sleep_timer_sheet.dart b/lib/widgets/sleep_timer_sheet.dart
index 9876a182..51765261 100644
--- a/lib/widgets/sleep_timer_sheet.dart
+++ b/lib/widgets/sleep_timer_sheet.dart
@@ -26,8 +26,7 @@ class _SleepTimerSheetState extends State<SleepTimerSheet> {
int _shakeAddMinutes = 5;
int _sleepRewindSeconds = 0;
- // Rewind presets in seconds - filtered by timer duration at build time
- static const _rewindStops = [0, 15, 30, 60, 120, 300, 600, 900, 1200, 1800];
+ static const _maxRewindMinutes = 60;
@override
void initState() {
@@ -343,39 +342,43 @@ class _SleepTimerSheetState extends State<SleepTimerSheet> {
Widget _buildRewindSection(Color accent, TextTheme tt) {
final cs = Theme.of(context).colorScheme;
final isEnabled = _sleepRewindSeconds > 0;
-
- // Filter stops to those <= 2/3 of the timer duration (in seconds)
- final timerSeconds = _tabIndex == 0
- ? (_customMinutes * 60).round()
- : _customChapters * 600; // rough estimate: ~10 min per chapter
- final maxRewind = (timerSeconds * 2 ~/ 3).clamp(15, 1800);
- final stops = _rewindStops.where((s) => s == 0 || s <= maxRewind).toList();
-
- // Snap current value to nearest valid stop
- if (_sleepRewindSeconds > 0 && !stops.contains(_sleepRewindSeconds)) {
- final nearest = stops.where((s) => s > 0).reduce((a, b) =>
- (a - _sleepRewindSeconds).abs() <= (b - _sleepRewindSeconds).abs() ? a : b);
- _sleepRewindSeconds = nearest;
- }
+ final rewindMinutes = (_sleepRewindSeconds / 60).clamp(0.0, _maxRewindMinutes.toDouble());
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Row(children: [
Icon(Icons.replay_rounded, size: 18, color: isEnabled ? accent : cs.onSurface.withValues(alpha: 0.24)),
const SizedBox(width: 10),
- Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
- Text('Rewind on sleep', style: TextStyle(color: isEnabled ? cs.onSurface.withValues(alpha: 0.7) : cs.onSurfaceVariant, fontSize: 13, fontWeight: FontWeight.w500)),
- Text(isEnabled ? 'Rewinds ${_rewindLabel(_sleepRewindSeconds)} when timer stops' : 'Disabled',
- style: TextStyle(color: cs.onSurface.withValues(alpha: 0.3), fontSize: 11)),
- ])),
- ]),
- const SizedBox(height: 10),
- Wrap(spacing: 8, runSpacing: 8, alignment: WrapAlignment.center, children: [
- for (final s in stops)
- _presetChip(accent, _rewindLabel(s), _sleepRewindSeconds == s, () {
- setState(() => _sleepRewindSeconds = s);
- PlayerSettings.setSleepRewindSeconds(s);
- }),
+ Expanded(child: Text('Rewind on sleep',
+ style: TextStyle(color: isEnabled ? cs.onSurface.withValues(alpha: 0.7) : cs.onSurfaceVariant, fontSize: 13, fontWeight: FontWeight.w500))),
+ Text(isEnabled ? _rewindLabel(_sleepRewindSeconds) : 'Off',
+ style: TextStyle(color: isEnabled ? accent : cs.onSurface.withValues(alpha: 0.3), fontSize: 13, fontWeight: FontWeight.w600)),
]),
+ const SizedBox(height: 4),
+ SliderTheme(
+ data: SliderThemeData(
+ activeTrackColor: accent,
+ inactiveTrackColor: cs.onSurface.withValues(alpha: 0.1),
+ thumbColor: accent,
+ overlayColor: accent.withValues(alpha: 0.1),
+ trackHeight: 4,
+ ),
+ child: Slider(
+ value: rewindMinutes,
+ min: 0, max: _maxRewindMinutes.toDouble(), divisions: _maxRewindMinutes,
+ onChanged: (v) {
+ final seconds = (v * 60).round();
+ setState(() => _sleepRewindSeconds = seconds);
+ PlayerSettings.setSleepRewindSeconds(seconds);
+ },
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
+ Text('Off', style: TextStyle(color: cs.onSurface.withValues(alpha: 0.3), fontSize: 11)),
+ Text('60m', style: TextStyle(color: cs.onSurface.withValues(alpha: 0.3), fontSize: 11)),
+ ]),
+ ),
]);
}