A cross platform Audiobookshelf client for Android and iOS
Dart
Improve author sheet with series grouping, add author link in book details
Nathan Poulsonee33ba25eac6
diff --git a/lib/widgets/author_books_sheet.dart b/lib/widgets/author_books_sheet.dartindex 7fa2cbe1..e1addf30 100644--- a/lib/widgets/author_books_sheet.dart+++ b/lib/widgets/author_books_sheet.dart@@ -1,6 +1,4 @@-import 'dart:convert';import 'package:flutter/material.dart';-import 'package:http/http.dart' as http;import 'package:cached_network_image/cached_network_image.dart';import 'package:provider/provider.dart';import '../providers/auth_provider.dart';@@ -79,13 +77,7 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {return;}- // Fetch author details and books in parallel- final futures = await Future.wait([- api.getAuthorById(widget.authorId, libraryId: widget.libraryId),- _fetchBooks(auth),- ]);-- final authorData = futures[0] as Map<String, dynamic>?;+ final authorData = await api.getAuthorById(widget.authorId, libraryId: widget.libraryId);if (mounted) {setState(() {@@ -95,40 +87,15 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {final ts = (authorData['updatedAt'] as num?)?.toInt();_imageUrl = api.getAuthorImageUrl(widget.authorId, updatedAt: ts);}+ // libraryItems from the author endpoint include full metadata with series info+ final rawItems = authorData['libraryItems'] as List<dynamic>? ?? [];+ _books = rawItems.whereType<Map<String, dynamic>>().toList();}_isLoading = false;});}}- Future<List<Map<String, dynamic>>> _fetchBooks(AuthProvider auth) async {- try {- final filterValue = base64Encode(utf8.encode(widget.authorId));- final cleanUrl = (auth.serverUrl ?? '').endsWith('/')- ? auth.serverUrl!.substring(0, auth.serverUrl!.length - 1)- : auth.serverUrl!;- final url =- '$cleanUrl/api/libraries/${widget.libraryId}/items'- '?filter=authors.$filterValue&sort=media.metadata.title&limit=200&collapseseries=0';-- final response = await http.get(- Uri.parse(url),- headers: {- 'Authorization': 'Bearer ${auth.token}',- },- ).timeout(const Duration(seconds: 15));-- if (response.statusCode == 200 && mounted) {- final data = jsonDecode(response.body) as Map<String, dynamic>;- final results = (data['results'] as List<dynamic>?) ?? [];- final books = results.whereType<Map<String, dynamic>>().toList();- if (mounted) setState(() => _books = books);- return books;- }- } catch (_) {}- return [];- }-@overrideWidget build(BuildContext context) {final cs = Theme.of(context).colorScheme;@@ -146,43 +113,151 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {);}- // Single scrollable list: header + description + booksfinal bottomPad = 24 + MediaQuery.of(context).viewPadding.bottom;final hasDesc = _description != null && _description!.isNotEmpty;- // header + optional description + books (or empty message)- final itemCount = 1 + (hasDesc ? 1 : 0) + (_books.isEmpty ? 1 : _books.length);- final descOffset = 1;- final booksOffset = 1 + (hasDesc ? 1 : 0);+ final sections = _buildSections();++ // Flatten sections into list items: header, description, then section widgets+ final items = <Widget>[+ _buildHeader(cs, tt, headers),+ if (hasDesc) _buildDescription(cs, tt),+ ];++ 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) {+ items.add(Padding(+ padding: const EdgeInsets.symmetric(horizontal: 16),+ child: BookResultTile(+ item: book,+ serverUrl: widget.serverUrl,+ token: widget.token,+ popOnTap: true,+ subtitle: _sequenceFor(book, label),+ ),+ ));+ }+ }+ }return ListView.builder(controller: widget.scrollController,padding: EdgeInsets.fromLTRB(0, 0, 0, bottomPad),- itemCount: itemCount,- itemBuilder: (context, index) {- if (index == 0) return _buildHeader(cs, tt, headers);- if (hasDesc && index == descOffset) return _buildDescription(cs, tt);- if (_books.isEmpty) {- return Center(- child: Padding(- padding: const EdgeInsets.only(top: 48),- child: Text('No books found',- style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),- ),- );- }- final bookIndex = index - booksOffset;- return Padding(- padding: const EdgeInsets.symmetric(horizontal: 16),- child: BookResultTile(- item: _books[bookIndex],- serverUrl: widget.serverUrl,- token: widget.token,- ),- );- },+ itemCount: items.length,+ itemBuilder: (context, index) => items[index],);}+ List<_BookSection> _buildSections() {+ final seriesMap = <String, _BookSection>{};+ final standalones = <Map<String, dynamic>>[];++ for (final book in _books) {+ final media = book['media'] as Map<String, dynamic>? ?? {};+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};+ final seriesNameRaw = metadata['seriesName'] as String? ?? '';++ // Split comma-separated series entries like "Mistborn #3, Cosmere #6"+ final entries = seriesNameRaw.split(',').map((e) => e.trim()).where((e) => e.isNotEmpty).toList();+ bool addedToSeries = false;++ 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: []));+ seriesMap[name]!.books.add(book);+ addedToSeries = true;+ }++ if (!addedToSeries) {+ standalones.add(book);+ }+ }++ // Sort books within each series by their sequence in that specific series+ final seqPattern = RegExp(r'#\s*([\d.]+)$');+ for (final entry in seriesMap.entries) {+ final seriesName = entry.key;+ entry.value.books.sort((a, b) {+ final snA = ((a['media'] as Map<String, dynamic>?)?['metadata'] as Map<String, dynamic>?)?['seriesName'] as String? ?? '';+ final snB = ((b['media'] as Map<String, dynamic>?)?['metadata'] as Map<String, dynamic>?)?['seriesName'] as String? ?? '';+ final seqA = _extractSequenceFor(snA, seriesName, seqPattern);+ final seqB = _extractSequenceFor(snB, seriesName, seqPattern);+ return seqA.compareTo(seqB);+ });+ }++ // Series sections sorted alphabetically, then standalone group at the end+ final seriesSections = seriesMap.values.toList()+ ..sort((a, b) => a.label.toLowerCase().compareTo(b.label.toLowerCase()));++ // Sort standalones alphabetically by title+ standalones.sort((a, b) {+ final tA = ((a['media'] as Map<String, dynamic>?)?['metadata'] as Map<String, dynamic>?)?['title'] as String? ?? '';+ final tB = ((b['media'] as Map<String, dynamic>?)?['metadata'] as Map<String, dynamic>?)?['title'] as String? ?? '';+ return tA.toLowerCase().compareTo(tB.toLowerCase());+ });++ final allSections = <_BookSection>[...seriesSections];+ if (standalones.isNotEmpty) {+ allSections.add(_BookSection(label: 'Standalone', books: standalones));+ }+ return allSections;+ }++ /// Get just the "#N" for a book within a specific series.+ String? _sequenceFor(Map<String, dynamic> book, String seriesName) {+ final sn = ((book['media'] as Map<String, dynamic>?)?['metadata'] as Map<String, dynamic>?)?['seriesName'] as String? ?? '';+ final pattern = RegExp(r'#\s*([\d.]+)');+ for (final entry in sn.split(',').map((e) => e.trim())) {+ final name = entry.replaceFirst(RegExp(r'\s*#\s*[\d.]+$'), '').trim();+ if (name.toLowerCase() == seriesName.toLowerCase()) {+ final match = pattern.firstMatch(entry);+ if (match != null) return '#${match.group(1)}';+ }+ }+ return null;+ }++ /// Extract the sequence number for a specific series from the seriesName string.+ double _extractSequenceFor(String seriesNameRaw, String targetSeries, RegExp seqPattern) {+ final entries = seriesNameRaw.split(',').map((e) => e.trim()).where((e) => e.isNotEmpty);+ for (final entry in entries) {+ final name = entry.replaceFirst(seqPattern, '').trim();+ if (name.toLowerCase() == targetSeries.toLowerCase()) {+ final match = seqPattern.firstMatch(entry);+ if (match != null) return double.tryParse(match.group(1)!) ?? double.maxFinite;+ }+ }+ return double.maxFinite;+ }+Widget _buildHeader(ColorScheme cs, TextTheme tt, Map<String, String> headers) {return Padding(padding: const EdgeInsets.fromLTRB(24, 0, 24, 12),@@ -269,3 +344,9 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {);}}++class _BookSection {+ final String label;+ final List<Map<String, dynamic>> books;+ _BookSection({required this.label, required this.books});+}diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dartindex 06576ab3..9d43f7a2 100644--- a/lib/widgets/book_detail_sheet.dart+++ b/lib/widgets/book_detail_sheet.dart@@ -20,6 +20,7 @@ import '../services/progress_sync_service.dart';import '../services/metadata_override_service.dart';import '../services/scoped_prefs.dart';import '../screens/app_shell.dart';+import 'author_books_sheet.dart';import 'series_books_sheet.dart';import 'absorbing_shared.dart';import 'html_description.dart';@@ -225,7 +226,14 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {decoration: BoxDecoration(color: cs.onSurface.withValues(alpha: 0.24), borderRadius: BorderRadius.circular(2)))),Text(title, textAlign: TextAlign.center, style: tt.headlineSmall?.copyWith(fontWeight: FontWeight.w700, color: cs.onSurface)),const SizedBox(height: 4),- Text(authorName, textAlign: TextAlign.center, style: tt.bodyMedium?.copyWith(color: cs.onSurface.withValues(alpha: 0.6))),+ GestureDetector(+ onTap: () => _openAuthor(context, metadata),+ child: Text(authorName, textAlign: TextAlign.center, style: tt.bodyMedium?.copyWith(+ color: cs.primary,+ decoration: TextDecoration.underline,+ decorationColor: cs.primary.withValues(alpha: 0.4),+ )),+ ),if (narrator.isNotEmpty) ...[const SizedBox(height: 2),Text('Narrated by $narrator', textAlign: TextAlign.center, style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant))],// ─── AUDIBLE RATING (space always reserved) ─────────@@ -627,6 +635,28 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {);}+ void _openAuthor(BuildContext context, Map<String, dynamic> metadata) {+ // Get first author with an ID from the authors array+ final authors = metadata['authors'] as List<dynamic>? ?? [];+ String? authorId;+ String authorName = metadata['authorName'] as String? ?? '';+ for (final a in authors) {+ if (a is Map<String, dynamic>) {+ final id = a['id'] as String? ?? '';+ if (id.isNotEmpty) {+ authorId = id;+ authorName = a['name'] as String? ?? authorName;+ break;+ }+ }+ }+ if (authorId == null || authorName.isEmpty) return;+ // Close current sheet before opening author sheet+ final nav = Navigator.of(context);+ nav.pop();+ showAuthorDetailSheet(nav.context, authorId: authorId, authorName: authorName);+ }+Future<void> _openSeries(BuildContext context, String? seriesId, String seriesName) async {if (seriesId == null) return;final auth = context.read<AuthProvider>();@@ -933,19 +963,8 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {}void _openGoodreads(String title, String author) async {- final metadata = (_item?['media'] as Map<String, dynamic>?)?['metadata'] as Map<String, dynamic>? ?? {};- final isbn = metadata['isbn'] as String? ?? '';- final asin = metadata['asin'] as String? ?? '';- // ISBN goes directly to the book page; ASIN is a close second; search as fallback- final Uri uri;- if (isbn.isNotEmpty) {- uri = Uri.https('www.goodreads.com', '/book/isbn/$isbn');- } else if (asin.isNotEmpty) {- uri = Uri.https('www.goodreads.com', '/search', {'q': asin});- } else {- final q = author.isNotEmpty ? '$title $author' : title;- uri = Uri.https('www.goodreads.com', '/search', {'q': q});- }+ final q = author.isNotEmpty ? '$title $author' : title;+ final uri = Uri.https('www.goodreads.com', '/search', {'q': q});try {// Open in Goodreads app if installedif (!await launchUrl(uri, mode: LaunchMode.externalNonBrowserApplication)) {diff --git a/lib/widgets/library_grid_tiles.dart b/lib/widgets/library_grid_tiles.dartindex 520cf1cc..d924eb97 100644--- a/lib/widgets/library_grid_tiles.dart+++ b/lib/widgets/library_grid_tiles.dart@@ -491,16 +491,17 @@ class GridAuthorTile extends StatelessWidget {// Circular avatarAspectRatio(aspectRatio: 1,- child: Container(- decoration: BoxDecoration(- shape: BoxShape.circle,- color: cs.secondaryContainer,- ),- clipBehavior: Clip.antiAlias,- child: Stack(- fit: StackFit.expand,- children: [- imageUrl != null+ child: Stack(+ fit: StackFit.expand,+ clipBehavior: Clip.none,+ children: [+ Container(+ decoration: BoxDecoration(+ shape: BoxShape.circle,+ color: cs.secondaryContainer,+ ),+ clipBehavior: Clip.antiAlias,+ child: imageUrl != null? CachedNetworkImage(imageUrl: imageUrl,fit: BoxFit.cover,@@ -509,23 +510,30 @@ class GridAuthorTile extends StatelessWidget {errorWidget: (_, __, ___) => _placeholder(cs),): _placeholder(cs),- if (numBooks > 0)- Positioned(- bottom: 4,- right: 4,- child: Container(- padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),- decoration: BoxDecoration(- color: cs.primaryContainer,- borderRadius: BorderRadius.circular(10),- ),- child: Text('$numBooks',- style: TextStyle(fontSize: 10, fontWeight: FontWeight.w700,- color: cs.onPrimaryContainer)),+ ),+ if (numBooks > 0)+ Positioned(+ top: 0,+ right: 0,+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 3),+ decoration: BoxDecoration(+ color: cs.primaryContainer,+ borderRadius: BorderRadius.circular(10),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(Icons.auto_stories_rounded, size: 11, color: cs.onPrimaryContainer),+ const SizedBox(width: 3),+ Text('$numBooks',+ style: TextStyle(fontSize: 10, fontWeight: FontWeight.w700,+ color: cs.onPrimaryContainer)),+ ],),),- ],- ),+ ),+ ],),),const SizedBox(height: 5),diff --git a/lib/widgets/library_search_results.dart b/lib/widgets/library_search_results.dartindex 4f089346..5c93ca3c 100644--- a/lib/widgets/library_search_results.dart+++ b/lib/widgets/library_search_results.dart@@ -3,6 +3,7 @@ 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 'author_books_sheet.dart';import 'book_detail_sheet.dart';import 'episode_list_sheet.dart';@@ -12,12 +13,16 @@ class BookResultTile extends StatelessWidget {final Map<String, dynamic> item;final String? serverUrl;final String? token;+ final bool popOnTap;+ final String? subtitle;const BookResultTile({super.key,required this.item,required this.serverUrl,required this.token,+ this.popOnTap = false,+ this.subtitle,});@override@@ -30,6 +35,10 @@ class BookResultTile extends StatelessWidget {final metadata = media['metadata'] as Map<String, dynamic>? ?? {};final title = metadata['title'] as String? ?? 'Unknown';final authorName = metadata['authorName'] as String? ?? '';+ final lib = context.watch<LibraryProvider>();+ final isDownloaded = itemId != null && DownloadService().isDownloaded(itemId);+ final isFinished = itemId != null && lib.getProgressData(itemId)?['isFinished'] == true;+ final greenColor = Theme.of(context).brightness == Brightness.dark ? Colors.greenAccent[400]! : Colors.green.shade700;String? coverUrl;if (itemId != null && serverUrl != null && token != null) {@@ -52,11 +61,14 @@ class BookResultTile extends StatelessWidget {onTap: () {FocusManager.instance.primaryFocus?.unfocus();if (itemId != null) {- final lib = context.read<LibraryProvider>();+ final nav = Navigator.of(context);+ if (popOnTap) nav.pop();+ final ctx = popOnTap ? nav.context : context;+ final lib = ctx.read<LibraryProvider>();if (lib.isPodcastLibrary) {- EpisodeListSheet.show(context, item);+ EpisodeListSheet.show(ctx, item);} else {- showBookDetailSheet(context, itemId);+ showBookDetailSheet(ctx, itemId);}}},@@ -66,15 +78,51 @@ class BookResultTile extends StatelessWidget {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),+ child: Stack(+ fit: StackFit.expand,+ children: [+ coverUrl != null+ ? CachedNetworkImage(+ imageUrl: coverUrl,+ fit: BoxFit.cover,+ httpHeaders: lib.mediaHeaders,+ placeholder: (_, __) => _ph(cs),+ errorWidget: (_, __, ___) => _ph(cs),+ )+ : _ph(cs),+ if (isFinished || isDownloaded)+ 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: [+ if (isFinished) ...[+ Icon(Icons.check_circle_rounded, size: 8, color: greenColor),+ const SizedBox(width: 2),+ Text('Done', style: TextStyle(fontSize: 7, fontWeight: FontWeight.w600, color: greenColor)),+ ],+ if (isFinished && isDownloaded) const SizedBox(width: 4),+ if (isDownloaded) ...[+ Icon(Icons.download_done_rounded, size: 8, color: cs.primary),+ const SizedBox(width: 2),+ Text('Saved', style: TextStyle(fontSize: 7, fontWeight: FontWeight.w600, color: cs.primary)),+ ],+ ],+ ),+ ),+ ),+ ],+ ),),Expanded(child: Padding(@@ -90,6 +138,12 @@ class BookResultTile extends StatelessWidget {style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600,color: cs.onSurface)),+ if (subtitle != null)+ Text(subtitle!,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: tt.bodySmall?.copyWith(+ color: cs.primary, fontSize: 11)),if (authorName.isNotEmpty)Text(authorName,maxLines: 1,