A cross platform Audiobookshelf client for Android and iOS
Dart
Add progress info to continue listening cards and smooth sheet dismiss
Nathan Poulsond02c52ac35e3
diff --git a/lib/screens/admin_podcasts_screen.dart b/lib/screens/admin_podcasts_screen.dartindex 01d54587..1fe85f68 100644--- a/lib/screens/admin_podcasts_screen.dart+++ b/lib/screens/admin_podcasts_screen.dart@@ -250,7 +250,7 @@ class _PodcastSearchSheetState extends State<_PodcastSearchSheet> {),child: DraggableScrollableSheet(initialChildSize: 0.85,- minChildSize: 0.5,+ minChildSize: 0.05,maxChildSize: 0.95,expand: false,builder: (ctx, sc) {diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dartindex c1095875..a4c72ce8 100644--- a/lib/screens/home_screen.dart+++ b/lib/screens/home_screen.dart@@ -293,7 +293,7 @@ class _HomeScreenState extends State<HomeScreen> {child: Padding(padding: const EdgeInsets.only(top: 12),child: SizedBox(- height: 72,+ height: 92,child: ListView.separated(scrollDirection: Axis.horizontal,padding: const EdgeInsets.symmetric(horizontal: 20),@@ -443,6 +443,15 @@ class _ContinueListeningCard extends StatefulWidget {class _ContinueListeningCardState extends State<_ContinueListeningCard> {bool _isLoading = false;+ static String _fmtTime(double s) {+ if (s <= 0) return '0:00';+ final h = (s / 3600).floor();+ final m = ((s % 3600) / 60).floor();+ final sec = (s % 60).floor();+ if (h > 0) return '$h:${m.toString().padLeft(2, '0')}:${sec.toString().padLeft(2, '0')}';+ return '$m:${sec.toString().padLeft(2, '0')}';+ }+@overrideWidget build(BuildContext context) {final cs = Theme.of(context).colorScheme;@@ -472,6 +481,14 @@ class _ContinueListeningCardState extends State<_ContinueListeningCard> {final progress = episodeId != null? lib.getEpisodeProgress(itemId, episodeId): lib.getProgress(itemId);+ final progressData = episodeId != null+ ? lib.getEpisodeProgressData(itemId, episodeId)+ : lib.getProgressData(itemId);+ final currentTime = (progressData?['currentTime'] as num?)?.toDouble() ?? 0;+ final totalDuration = (progressData?['duration'] as num?)?.toDouble() ??+ (recentEpisode != null+ ? (recentEpisode['duration'] as num?)?.toDouble() ?? 0+ : (media['duration'] as num?)?.toDouble() ?? 0);final isCurrentItem = player.currentItemId == itemId;return GestureDetector(@@ -500,7 +517,7 @@ class _ContinueListeningCardState extends State<_ContinueListeningCard> {ClipRRect(borderRadius: BorderRadius.circular(8),child: SizedBox(- width: 48, height: 48,+ width: 52, height: 52,child: coverUrl != null? coverUrl.startsWith('/')? Image.file(File(coverUrl), fit: BoxFit.cover,@@ -532,6 +549,24 @@ class _ContinueListeningCardState extends State<_ContinueListeningCard> {style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant, fontSize: 11)),const SizedBox(height: 4),+ // Percentage + listened time+ Text.rich(+ TextSpan(children: [+ TextSpan(text: '${(progress * 100).round()}%',+ style: tt.labelSmall?.copyWith(+ fontSize: 10, fontWeight: FontWeight.w600,+ color: cs.primary)),+ if (totalDuration > 0) ...[+ TextSpan(text: ' · ',+ style: tt.labelSmall?.copyWith(+ fontSize: 10, color: cs.onSurfaceVariant.withValues(alpha: 0.5))),+ TextSpan(text: '${_fmtTime(currentTime)} / ${_fmtTime(totalDuration)}',+ style: tt.labelSmall?.copyWith(+ fontSize: 10, color: cs.onSurfaceVariant)),+ ],+ ]),+ ),+ const SizedBox(height: 4),// Thin progress barClipRRect(borderRadius: BorderRadius.circular(2),diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dartindex 5ca4f2b9..0004ebbf 100644--- a/lib/screens/settings_screen.dart+++ b/lib/screens/settings_screen.dart@@ -112,7 +112,7 @@ class _SettingsScreenState extends State<SettingsScreen> {context: context, isScrollControlled: true, useSafeArea: true,backgroundColor: Colors.transparent,builder: (ctx) => DraggableScrollableSheet(- expand: false, initialChildSize: 0.75, maxChildSize: 0.95,+ expand: false, initialChildSize: 0.75, minChildSize: 0.05, maxChildSize: 0.95,builder: (_, sc) => Container(decoration: BoxDecoration(color: cs.surface,@@ -1502,7 +1502,7 @@ class _SettingsScreenState extends State<SettingsScreen> {isScrollControlled: true,builder: (ctx) => DraggableScrollableSheet(initialChildSize: 0.5,- minChildSize: 0.3,+ minChildSize: 0.05,maxChildSize: 0.85,expand: false,builder: (ctx, scrollController) => Container(diff --git a/lib/widgets/absorbing_card.dart b/lib/widgets/absorbing_card.dartindex 284b8eda..6b835b1d 100644--- a/lib/widgets/absorbing_card.dart+++ b/lib/widgets/absorbing_card.dart@@ -776,7 +776,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClicontext: context, isScrollControlled: true, useSafeArea: true,backgroundColor: Colors.transparent,builder: (ctx) => DraggableScrollableSheet(- expand: false, initialChildSize: 0.6, maxChildSize: 0.9,+ expand: false, initialChildSize: 0.6, minChildSize: 0.05, maxChildSize: 0.9,builder: (_, sc) => Container(decoration: BoxDecoration(color: Theme.of(context).bottomSheetTheme.backgroundColor,@@ -830,7 +830,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClicontext: context, isScrollControlled: true, useSafeArea: true,backgroundColor: Colors.transparent,builder: (ctx) => DraggableScrollableSheet(- expand: false, initialChildSize: 0.6, maxChildSize: 0.9,+ expand: false, initialChildSize: 0.6, minChildSize: 0.05, maxChildSize: 0.9,builder: (_, sc) => Container(decoration: BoxDecoration(color: Theme.of(context).bottomSheetTheme.backgroundColor,diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dartindex e7f74650..c8a2f15b 100644--- a/lib/widgets/book_detail_sheet.dart+++ b/lib/widgets/book_detail_sheet.dart@@ -16,7 +16,7 @@ import '../services/download_service.dart';import '../services/progress_sync_service.dart';import '../services/metadata_override_service.dart';import '../screens/app_shell.dart';-import '../screens/library_screen.dart';+import 'series_books_sheet.dart';import 'absorbing_shared.dart';import 'metadata_lookup_sheet.dart';@@ -27,7 +27,7 @@ void showBookDetailSheet(BuildContext context, String itemId) {context: context, isScrollControlled: true, useSafeArea: true,backgroundColor: Colors.transparent,builder: (ctx) => DraggableScrollableSheet(- expand: false, initialChildSize: 0.85, minChildSize: 0.5, maxChildSize: 0.95,+ expand: false, initialChildSize: 0.85, minChildSize: 0.05, maxChildSize: 0.95,builder: (ctx, sc) => _BookDetailSheetContent(itemId: itemId, scrollController: sc),),);@@ -704,7 +704,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {builder: (_) => DraggableScrollableSheet(expand: false,initialChildSize: 0.85,- minChildSize: 0.5,+ minChildSize: 0.05,maxChildSize: 0.95,builder: (ctx, sc) => MetadataLookupSheet(itemId: widget.itemId,diff --git a/lib/widgets/card_buttons.dart b/lib/widgets/card_buttons.dartindex e6e83902..1d66d1d8 100644--- a/lib/widgets/card_buttons.dart+++ b/lib/widgets/card_buttons.dart@@ -248,7 +248,7 @@ class _CardBookmarkButtonInlineState extends State<CardBookmarkButtonInline> {showModalBottomSheet(context: context, backgroundColor: Colors.transparent, isScrollControlled: true, useSafeArea: true,builder: (ctx) => DraggableScrollableSheet(- initialChildSize: 0.6, minChildSize: 0.3, maxChildSize: 0.9, expand: false,+ initialChildSize: 0.6, minChildSize: 0.05, maxChildSize: 0.9, expand: false,builder: (ctx, sc) => SimpleBookmarkSheet(itemId: widget.itemId, player: widget.player, accent: widget.accent, scrollController: sc, onChanged: _loadCount),),);diff --git a/lib/widgets/episode_list_sheet.dart b/lib/widgets/episode_list_sheet.dartindex c344a735..b23cf897 100644--- a/lib/widgets/episode_list_sheet.dart+++ b/lib/widgets/episode_list_sheet.dart@@ -31,7 +31,7 @@ class EpisodeListSheet extends StatefulWidget {backgroundColor: Colors.transparent,builder: (_) => DraggableScrollableSheet(initialChildSize: 0.85,- minChildSize: 0.5,+ minChildSize: 0.05,maxChildSize: 0.95,expand: false,builder: (_, scrollController) => EpisodeListSheet._(@@ -457,7 +457,7 @@ class EpisodeDetailSheet extends StatefulWidget {backgroundColor: Colors.transparent,builder: (_) => DraggableScrollableSheet(initialChildSize: 0.75,- minChildSize: 0.4,+ minChildSize: 0.05,maxChildSize: 0.95,expand: false,builder: (_, scrollController) => EpisodeDetailSheet._(diff --git a/lib/widgets/equalizer_sheet.dart b/lib/widgets/equalizer_sheet.dartindex 6b4b4e9e..79273587 100644--- a/lib/widgets/equalizer_sheet.dart+++ b/lib/widgets/equalizer_sheet.dart@@ -11,7 +11,7 @@ void showEqualizerSheet(BuildContext context, Color accent) {builder: (ctx) => DraggableScrollableSheet(expand: false,initialChildSize: 0.75,- minChildSize: 0.5,+ minChildSize: 0.05,maxChildSize: 0.92,builder: (ctx, sc) => _EqualizerSheetContent(accent: accent, scrollController: sc),),diff --git a/lib/widgets/expanded_card.dart b/lib/widgets/expanded_card.dartindex 90fce799..645ec111 100644--- a/lib/widgets/expanded_card.dart+++ b/lib/widgets/expanded_card.dart@@ -919,7 +919,7 @@ class _ExpandedCardState extends State<ExpandedCard> {context: context, isScrollControlled: true, useSafeArea: true,backgroundColor: Colors.transparent,builder: (ctx) => DraggableScrollableSheet(- expand: false, initialChildSize: 0.6, maxChildSize: 0.9,+ expand: false, initialChildSize: 0.6, minChildSize: 0.05, maxChildSize: 0.9,builder: (_, sc) => Container(decoration: BoxDecoration(color: Theme.of(context).bottomSheetTheme.backgroundColor,@@ -972,7 +972,7 @@ class _ExpandedCardState extends State<ExpandedCard> {context: context, isScrollControlled: true, useSafeArea: true,backgroundColor: Colors.transparent,builder: (ctx) => DraggableScrollableSheet(- expand: false, initialChildSize: 0.6, maxChildSize: 0.9,+ expand: false, initialChildSize: 0.6, minChildSize: 0.05, maxChildSize: 0.9,builder: (_, sc) => Container(decoration: BoxDecoration(color: Theme.of(context).bottomSheetTheme.backgroundColor,diff --git a/lib/widgets/library_search_results.dart b/lib/widgets/library_search_results.dartnew file mode 100644index 00000000..25d9ea50--- /dev/null+++ b/lib/widgets/library_search_results.dart@@ -0,0 +1,337 @@+import 'package:flutter/material.dart';+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 'author_books_sheet.dart';+import 'book_detail_sheet.dart';+import 'episode_list_sheet.dart';+import 'series_books_sheet.dart';++class BookResultTile extends StatelessWidget {+ final Map<String, dynamic> item;+ final String? serverUrl;+ final String? token;++ const BookResultTile({+ super.key,+ required this.item,+ required this.serverUrl,+ required this.token,+ });++ @override+ Widget build(BuildContext context) {+ final cs = Theme.of(context).colorScheme;+ final tt = Theme.of(context).textTheme;++ final itemId = item['id'] as String?;+ final media = item['media'] as Map<String, dynamic>? ?? {};+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};+ final title = metadata['title'] as String? ?? 'Unknown';+ final authorName = metadata['authorName'] as String? ?? '';++ String? coverUrl;+ if (itemId != null && serverUrl != null && token != null) {+ final cleanUrl = serverUrl!.endsWith('/')+ ? serverUrl!.substring(0, serverUrl!.length - 1)+ : serverUrl!;+ coverUrl = '$cleanUrl/api/items/$itemId/cover?width=200&token=$token';+ }++ return Padding(+ padding: const EdgeInsets.only(bottom: 6),+ child: Card(+ elevation: 0,+ color: cs.surfaceContainerHigh,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: () {+ FocusManager.instance.primaryFocus?.unfocus();+ if (itemId != null) {+ final lib = context.read<LibraryProvider>();+ if (lib.isPodcastLibrary) {+ EpisodeListSheet.show(context, item);+ } else {+ showBookDetailSheet(context, itemId);+ }+ }+ },+ borderRadius: BorderRadius.circular(12),+ child: Row(+ children: [+ SizedBox(+ width: 56,+ height: 56,+ child: coverUrl != null+ ? CachedNetworkImage(+ imageUrl: coverUrl,+ fit: BoxFit.cover,+ httpHeaders: context.read<LibraryProvider>().mediaHeaders,+ placeholder: (_, __) => _ph(cs),+ errorWidget: (_, __, ___) => _ph(cs),+ )+ : _ph(cs),+ ),+ Expanded(+ child: Padding(+ padding:+ const EdgeInsets.symmetric(horizontal: 12, vertical: 8),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(title,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: tt.bodyMedium?.copyWith(+ fontWeight: FontWeight.w600,+ color: cs.onSurface)),+ if (authorName.isNotEmpty)+ Text(authorName,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: tt.bodySmall+ ?.copyWith(color: cs.onSurfaceVariant)),+ ],+ ),+ ),+ ),+ Padding(+ padding: const EdgeInsets.only(right: 8),+ child: Icon(Icons.chevron_right_rounded,+ color: cs.onSurfaceVariant, size: 20),+ ),+ ],+ ),+ ),+ ),+ );+ }++ Widget _ph(ColorScheme cs) {+ return Container(+ color: cs.surfaceContainerHighest,+ child: Icon(Icons.headphones_rounded,+ size: 20, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),+ );+ }+}++class SeriesResultCard extends StatelessWidget {+ final Map<String, dynamic> series;+ final List<dynamic> books;+ final String? serverUrl;+ final String? token;++ const SeriesResultCard({+ super.key,+ required this.series,+ required this.books,+ required this.serverUrl,+ required this.token,+ });++ @override+ Widget build(BuildContext context) {+ final cs = Theme.of(context).colorScheme;+ final tt = Theme.of(context).textTheme;+ final seriesName = series['name'] as String? ?? 'Unknown Series';++ return Padding(+ padding: const EdgeInsets.only(bottom: 6),+ child: Card(+ elevation: 0,+ color: cs.surfaceContainerHigh,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: () => _showSeriesBooks(context, seriesName),+ borderRadius: BorderRadius.circular(12),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),+ child: Row(+ children: [+ Container(+ width: 44,+ height: 44,+ decoration: BoxDecoration(+ color: cs.secondaryContainer,+ borderRadius: BorderRadius.circular(10),+ ),+ child: Center(+ child: Icon(Icons.auto_stories_rounded,+ size: 22, color: cs.onSecondaryContainer.withValues(alpha: 0.7)),+ ),+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(seriesName,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: tt.bodyMedium?.copyWith(+ fontWeight: FontWeight.w600,+ color: cs.onSurface)),+ Text(+ '${books.length} book${books.length != 1 ? 's' : ''}',+ style: tt.bodySmall+ ?.copyWith(color: cs.onSurfaceVariant)),+ ],+ ),+ ),+ Icon(Icons.chevron_right_rounded,+ color: cs.onSurfaceVariant, size: 20),+ ],+ ),+ ),+ ),+ ),+ );+ }++ void _showSeriesBooks(BuildContext context, String seriesName) {+ showSeriesBooksSheet(+ context,+ seriesName: seriesName,+ seriesId: series['id'] as String?,+ books: books,+ serverUrl: serverUrl,+ token: token,+ );+ }+}++class AuthorResultTile extends StatelessWidget {+ final Map<String, dynamic> author;+ final String? serverUrl;+ final String? token;++ const AuthorResultTile({+ super.key,+ required this.author,+ required this.serverUrl,+ required this.token,+ });++ @override+ Widget build(BuildContext context) {+ final cs = Theme.of(context).colorScheme;+ final tt = Theme.of(context).textTheme;++ final name = author['name'] as String? ?? 'Unknown';+ final authorId = author['id'] as String? ?? '';+ final numBooks = author['numBooks'] as int?;++ String? imageUrl;+ if (authorId.isNotEmpty && serverUrl != null && token != null) {+ final cleanUrl = serverUrl!.endsWith('/')+ ? serverUrl!.substring(0, serverUrl!.length - 1)+ : serverUrl!;+ imageUrl =+ '$cleanUrl/api/authors/$authorId/image?width=200&token=$token';+ }++ return Padding(+ padding: const EdgeInsets.only(bottom: 6),+ child: Card(+ elevation: 0,+ color: cs.surfaceContainerHigh,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: () => _showAuthorBooks(context, authorId, name),+ borderRadius: BorderRadius.circular(12),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),+ child: Row(+ children: [+ // Author avatar+ Container(+ width: 44,+ height: 44,+ decoration: BoxDecoration(+ shape: BoxShape.circle,+ color: cs.secondaryContainer,+ ),+ clipBehavior: Clip.antiAlias,+ child: imageUrl != null+ ? CachedNetworkImage(+ imageUrl: imageUrl,+ fit: BoxFit.cover,+ httpHeaders: context.read<LibraryProvider>().mediaHeaders,+ placeholder: (_, __) => _ph(cs),+ errorWidget: (_, __, ___) => _ph(cs),+ )+ : _ph(cs),+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: tt.bodyMedium?.copyWith(+ fontWeight: FontWeight.w600,+ color: cs.onSurface)),+ if (numBooks != null)+ Text(+ '$numBooks book${numBooks != 1 ? 's' : ''}',+ style: tt.bodySmall+ ?.copyWith(color: cs.onSurfaceVariant)),+ ],+ ),+ ),+ Icon(Icons.chevron_right_rounded,+ color: cs.onSurfaceVariant, size: 20),+ ],+ ),+ ),+ ),+ ),+ );+ }++ Widget _ph(ColorScheme cs) {+ return Center(+ child: Icon(Icons.person_rounded,+ size: 22, color: cs.onSecondaryContainer.withValues(alpha: 0.5)),+ );+ }++ void _showAuthorBooks(+ BuildContext context, String authorId, String authorName) {+ FocusManager.instance.primaryFocus?.unfocus();+ final auth = context.read<AuthProvider>();+ final lib = context.read<LibraryProvider>();+ final api = auth.apiService;+ if (api == null || lib.selectedLibraryId == null) return;++ showModalBottomSheet(+ context: context,+ isScrollControlled: true,+ showDragHandle: true,+ builder: (_) => DraggableScrollableSheet(+ initialChildSize: 0.7,+ minChildSize: 0.05,+ maxChildSize: 0.9,+ expand: false,+ builder: (ctx, scrollController) => AuthorBooksSheet(+ libraryId: lib.selectedLibraryId!,+ authorId: authorId,+ authorName: authorName,+ serverUrl: auth.serverUrl,+ token: auth.token,+ scrollController: scrollController,+ ),+ ),+ );+ }+}diff --git a/lib/widgets/series_books_sheet.dart b/lib/widgets/series_books_sheet.dartnew file mode 100644index 00000000..58248c9c--- /dev/null+++ b/lib/widgets/series_books_sheet.dart@@ -0,0 +1,508 @@+import 'package:flutter/material.dart';+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/download_service.dart';+import 'book_detail_sheet.dart';+import 'episode_list_sheet.dart';++/// Show a bottom sheet with all books in a series, sorted by sequence.+/// Can be called from any screen.+void showSeriesBooksSheet(BuildContext context, {+ required String seriesName,+ String? seriesId,+ List<dynamic> books = const [],+ String? serverUrl,+ String? token,+}) {+ FocusManager.instance.primaryFocus?.unfocus();+ showModalBottomSheet(+ context: context,+ isScrollControlled: true,+ showDragHandle: true,+ builder: (_) => DraggableScrollableSheet(+ initialChildSize: 0.7,+ minChildSize: 0.05,+ maxChildSize: 0.9,+ expand: false,+ builder: (ctx, scrollController) => SeriesBooksSheet(+ seriesName: seriesName,+ seriesId: seriesId,+ books: books,+ serverUrl: serverUrl,+ token: token,+ scrollController: scrollController,+ ),+ ),+ );+}++class SeriesBooksSheet extends StatefulWidget {+ final String seriesName;+ final String? seriesId;+ final List<dynamic> books;+ final String? serverUrl;+ final String? token;+ final ScrollController scrollController;++ const SeriesBooksSheet({+ super.key,+ required this.seriesName,+ this.seriesId,+ required this.books,+ required this.serverUrl,+ required this.token,+ required this.scrollController,+ });++ @override+ State<SeriesBooksSheet> createState() => _SeriesBooksSheetState();+}++class _SeriesBooksSheetState extends State<SeriesBooksSheet> {+ List<Map<String, dynamic>> _books = [];+ bool _isLoading = true;++ @override+ void initState() {+ super.initState();+ // Use passed books as initial data+ _books = _unwrapBooks(widget.books);+ _sortBooks();+ if (_books.isNotEmpty) _isLoading = false;+ // Fetch full data from API for proper sequence info+ _fetchFromApi();+ }++ /// Unwrap ABS format: { libraryItem: {...}, sequence: "1" }+ /// Move sequence to top level of the item for consistent access.+ List<Map<String, dynamic>> _unwrapBooks(List<dynamic> raw) {+ final result = <Map<String, dynamic>>[];+ for (final b in raw) {+ if (b is! Map<String, dynamic>) continue;+ if (b.containsKey('libraryItem') && b['libraryItem'] is Map<String, dynamic>) {+ final item = Map<String, dynamic>.from(b['libraryItem'] as Map<String, dynamic>);+ if (b['sequence'] != null) item['sequence'] = b['sequence'];+ result.add(item);+ } else {+ result.add(Map<String, dynamic>.from(b));+ }+ }+ return result;+ }++ void _sortBooks() {+ _books.sort((a, b) {+ final seqA = _getSequence(a);+ final seqB = _getSequence(b);+ if (seqA == null && seqB == null) return 0;+ if (seqA == null) return 1;+ if (seqB == null) return -1;+ return seqA.compareTo(seqB);+ });+ }++ double? _getSequence(Map<String, dynamic> book) {+ // Top-level sequence (from unwrapping)+ final seq = book['sequence'];+ if (seq != null) {+ final v = double.tryParse(seq.toString());+ if (v != null) return v;+ }+ // Nested in metadata.series+ final media = book['media'] as Map<String, dynamic>? ?? {};+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};+ final seriesRaw = metadata['series'];+ if (seriesRaw is List) {+ for (final s in seriesRaw) {+ if (s is Map<String, dynamic>) {+ final v = s['sequence'];+ if (v != null) {+ final d = double.tryParse(v.toString());+ if (d != null) return d;+ }+ }+ }+ } else if (seriesRaw is Map<String, dynamic>) {+ final v = seriesRaw['sequence'];+ if (v != null) {+ final d = double.tryParse(v.toString());+ if (d != null) return d;+ }+ }+ final fallback = metadata['seriesSequence'];+ if (fallback != null) return double.tryParse(fallback.toString());+ return null;+ }++ String? _getSequenceString(Map<String, dynamic> book) {+ final v = _getSequence(book);+ if (v == null) return null;+ // Show as int if whole number, otherwise decimal+ return v == v.roundToDouble() ? v.toInt().toString() : v.toString();+ }++ Future<void> _fetchFromApi() async {+ final seriesId = widget.seriesId;+ if (seriesId == null || seriesId.isEmpty) {+ if (mounted) setState(() => _isLoading = false);+ return;+ }+ final auth = context.read<AuthProvider>();+ final api = auth.apiService;+ if (api == null) {+ if (mounted) setState(() => _isLoading = false);+ return;+ }+ final lib = context.read<LibraryProvider>();+ final data = await api.getSeries(seriesId, libraryId: lib.selectedLibraryId);+ if (data != null && mounted) {+ final rawBooks = data['books'] ?? data['libraryItems'] ?? [];+ if (rawBooks is List && rawBooks.isNotEmpty) {+ final fetched = _unwrapBooks(rawBooks);+ setState(() {+ _books = fetched;+ _sortBooks();+ _isLoading = false;+ });+ return;+ }+ }+ if (mounted) setState(() => _isLoading = false);+ }++ @override+ Widget build(BuildContext context) {+ final cs = Theme.of(context).colorScheme;+ final tt = Theme.of(context).textTheme;+ final lib = context.watch<LibraryProvider>();++ // Calculate time-weighted series progress across all books+ double totalDuration = 0;+ double listenedDuration = 0;+ for (final book in _books) {+ final bookId = book['id'] as String? ?? '';+ final media = book['media'] as Map<String, dynamic>? ?? {};+ final dur = (media['duration'] is num) ? (media['duration'] as num).toDouble() : 0.0;+ final prog = lib.getProgress(bookId);+ totalDuration += dur;+ listenedDuration += dur * prog;+ }+ final seriesProgress = totalDuration > 0 ? (listenedDuration / totalDuration).clamp(0.0, 1.0) : 0.0;+ final seriesPercent = (seriesProgress * 100).round();++ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(24, 0, 24, 4),+ child: Row(+ children: [+ Icon(Icons.auto_stories_rounded, size: 20, color: cs.primary),+ const SizedBox(width: 8),+ Expanded(+ child: Text(widget.seriesName,+ style: tt.titleLarge+ ?.copyWith(fontWeight: FontWeight.w600)),+ ),+ ],+ ),+ ),+ Padding(+ padding: EdgeInsets.fromLTRB(24, 0, 24, seriesProgress > 0 ? 4 : 12),+ child: Text(+ '${_books.length} book${_books.length != 1 ? 's' : ''} in this series',+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),+ ),+ ),+ if (seriesProgress > 0)+ Padding(+ padding: const EdgeInsets.fromLTRB(24, 0, 24, 12),+ child: Row(+ children: [+ Expanded(+ child: ClipRRect(+ borderRadius: BorderRadius.circular(2),+ child: LinearProgressIndicator(+ value: seriesProgress,+ minHeight: 4,+ backgroundColor: cs.surfaceContainerHighest,+ valueColor: AlwaysStoppedAnimation(cs.primary),+ ),+ ),+ ),+ const SizedBox(width: 10),+ Text(+ '$seriesPercent% complete',+ style: tt.labelSmall?.copyWith(+ color: cs.primary,+ fontWeight: FontWeight.w600,+ ),+ ),+ ],+ ),+ ),+ if (_isLoading && _books.isEmpty)+ const Expanded(+ child: Center(child: CircularProgressIndicator()))+ else if (_books.isEmpty)+ Expanded(+ child: Center(+ child: Text('No books found',+ style: tt.bodyLarge+ ?.copyWith(color: cs.onSurfaceVariant)),+ ),+ )+ else+ Expanded(+ child: ListView.builder(+ controller: widget.scrollController,+ padding: EdgeInsets.fromLTRB(16, 0, 16, 24 + MediaQuery.of(context).viewPadding.bottom),+ itemCount: _books.length,+ itemBuilder: (context, index) {+ final book = _books[index];+ final bookId = book['id'] as String? ?? '';+ final media = book['media'] as Map<String, dynamic>? ?? {};+ final metadata =+ media['metadata'] as Map<String, dynamic>? ?? {};+ final bookTitle = metadata['title'] as String? ?? 'Unknown';+ final authorName = metadata['authorName'] as String? ?? '';+ final sequence = _getSequenceString(book);+ final duration = (media['duration'] is num)+ ? (media['duration'] as num).toDouble()+ : 0.0;++ final progress = lib.getProgress(bookId);+ final isFinished = lib.getProgressData(bookId)?['isFinished'] == true;+ final isDownloaded = DownloadService().isDownloaded(bookId);++ String? coverUrl;+ if (bookId.isNotEmpty &&+ widget.serverUrl != null &&+ widget.token != null) {+ final cleanUrl = widget.serverUrl!.endsWith('/')+ ? widget.serverUrl!+ .substring(0, widget.serverUrl!.length - 1)+ : widget.serverUrl!;+ coverUrl =+ '$cleanUrl/api/items/$bookId/cover?width=400&token=${widget.token}';+ }++ return Padding(+ padding: const EdgeInsets.only(bottom: 8),+ child: Card(+ elevation: 0,+ color: cs.surfaceContainerHigh,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(14)),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: () {+ if (bookId.isNotEmpty) {+ if (lib.isPodcastLibrary) {+ EpisodeListSheet.show(context, book);+ } else {+ showBookDetailSheet(context, bookId);+ }+ }+ },+ borderRadius: BorderRadius.circular(14),+ child: Row(+ children: [+ // Square cover with sequence badge + status badges+ SizedBox(+ width: 80,+ height: 80,+ child: Stack(+ children: [+ Positioned.fill(+ child: coverUrl != null+ ? CachedNetworkImage(+ imageUrl: coverUrl,+ fit: BoxFit.cover,+ httpHeaders: context.read<LibraryProvider>().mediaHeaders,+ placeholder: (_, __) =>+ _placeholder(cs),+ errorWidget: (_, __, ___) =>+ _placeholder(cs),+ )+ : _placeholder(cs),+ ),+ if (sequence != null && sequence.isNotEmpty)+ Positioned(+ top: 4,+ left: 4,+ child: Container(+ padding: const EdgeInsets.symmetric(+ horizontal: 6, vertical: 2),+ decoration: BoxDecoration(+ color: cs.primary,+ borderRadius:+ BorderRadius.circular(8),+ boxShadow: [+ BoxShadow(+ color: Colors.black+ .withValues(alpha: 0.3),+ blurRadius: 4)+ ],+ ),+ child: Text('#$sequence',+ style: TextStyle(+ color: cs.onPrimary,+ fontSize: 10,+ fontWeight: FontWeight.w800)),+ ),+ ),+ // Downloaded badge (top-right)+ if (isDownloaded)+ Positioned(+ top: 4,+ right: 4,+ child: Container(+ padding: const EdgeInsets.all(3),+ decoration: BoxDecoration(+ color: Colors.black54,+ borderRadius: BorderRadius.circular(6),+ ),+ child: Icon(Icons.download_done_rounded,+ size: 12, color: cs.primary),+ ),+ ),+ // Progress bar at bottom+ if (progress > 0 && !isFinished)+ Positioned(+ left: 0,+ right: 0,+ bottom: 0,+ child: LinearProgressIndicator(+ value: progress.clamp(0.0, 1.0),+ minHeight: 3,+ backgroundColor: Colors.black38,+ valueColor: AlwaysStoppedAnimation(cs.primary),+ ),+ ),+ // Finished overlay+ if (isFinished)+ Positioned(+ left: 0,+ right: 0,+ bottom: 0,+ child: Container(+ padding: const EdgeInsets.symmetric(+ horizontal: 4, vertical: 2),+ decoration: BoxDecoration(+ gradient: LinearGradient(+ begin: Alignment.bottomCenter,+ end: Alignment.topCenter,+ colors: [+ Colors.black.withValues(alpha: 0.85),+ Colors.black.withValues(alpha: 0.0),+ ],+ ),+ ),+ child: Row(+ mainAxisAlignment: MainAxisAlignment.center,+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(Icons.check_circle_rounded,+ size: 10, color: Theme.of(context).brightness == Brightness.dark ? Colors.greenAccent[400] : Colors.green.shade700),+ const SizedBox(width: 3),+ Text('Done',+ style: TextStyle(+ fontSize: 9,+ fontWeight: FontWeight.w600,+ color: Theme.of(context).brightness == Brightness.dark ? Colors.greenAccent[400] : Colors.green.shade700)),+ ],+ ),+ ),+ ),+ ],+ ),+ ),+ // Info+ Expanded(+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: 14, vertical: 10),+ child: Column(+ crossAxisAlignment:+ CrossAxisAlignment.start,+ mainAxisAlignment:+ MainAxisAlignment.center,+ children: [+ if (sequence != null &&+ sequence.isNotEmpty)+ Text('Book $sequence',+ style: tt.labelSmall?.copyWith(+ color: cs.primary,+ fontWeight: FontWeight.w600)),+ Text(bookTitle,+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: tt.titleSmall?.copyWith(+ fontWeight: FontWeight.w600,+ color: cs.onSurface)),+ if (authorName.isNotEmpty) ...[+ const SizedBox(height: 2),+ Text(authorName,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: tt.bodySmall?.copyWith(+ color: cs.onSurfaceVariant)),+ ],+ if (duration > 0) ...[+ const SizedBox(height: 2),+ Row(+ children: [+ Text(_formatDuration(duration),+ style: tt.labelSmall?.copyWith(+ color: cs.onSurfaceVariant)),+ if (progress > 0 && !isFinished) ...[+ const SizedBox(width: 8),+ Text('${(progress * 100).round()}%',+ style: tt.labelSmall?.copyWith(+ color: cs.primary,+ fontWeight: FontWeight.w600)),+ ],+ ],+ ),+ ],+ ],+ ),+ ),+ ),+ Padding(+ padding: const EdgeInsets.only(right: 12),+ child: Icon(Icons.chevron_right_rounded,+ color: cs.onSurfaceVariant),+ ),+ ],+ ),+ ),+ ),+ );+ },+ ),+ ),+ ],+ );+ }++ Widget _placeholder(ColorScheme cs) {+ return Container(+ color: cs.surfaceContainerHighest,+ child: Center(+ child: Icon(Icons.headphones_rounded,+ size: 24, color: cs.onSurfaceVariant.withValues(alpha: 0.4)),+ ),+ );+ }++ String _formatDuration(double seconds) {+ final h = (seconds / 3600).floor();+ final m = ((seconds % 3600) / 60).floor();+ if (h > 0) return '${h}h ${m}m';+ return '${m}m';+ }+}