A cross platform Audiobookshelf client for Android and iOS
Dart
Share duplicated sheet layout and duration formatting code
Barnabas0e01a05d3376
diff --git a/lib/screens/admin_podcasts_screen.dart b/lib/screens/admin_podcasts_screen.dartindex ef035e74..7c78921a 100644--- a/lib/screens/admin_podcasts_screen.dart+++ b/lib/screens/admin_podcasts_screen.dart@@ -6,6 +6,7 @@ import '../providers/auth_provider.dart';import '../widgets/absorb_page_header.dart';import '../widgets/html_description.dart';import '../l10n/app_localizations.dart';+import '../utils/duration_format.dart';class AdminPodcastsScreen extends StatefulWidget {final Map<String, dynamic> library;@@ -1287,7 +1288,7 @@ class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleTfinal epTitle = ep['title']?.toString() ?? l.adminPodcastsEpisodeFallback;final pubAt = ep['publishedAt'] as num?;final duration = ep['duration'];- final durStr = duration is num ? _fmtDur(duration.toDouble())+ final durStr = duration is num ? formatHm(duration.toDouble()): (duration is String ? _fmtDurFromStr(duration) : '');final selected = _selectedDownloadedIds.contains(epId);@@ -1944,14 +1945,11 @@ class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleTreturn '${m[dt.month - 1]} ${dt.day}, ${dt.year}';}- String _fmtDur(double s) { final h = (s / 3600).floor(); final m = ((s % 3600) / 60).floor();- return h > 0 ? '${h}h ${m}m' : '${m}m'; }-String _fmtDurFromStr(String s) {if (s.contains(':')) return s;final secs = double.tryParse(s) ?? 0;if (secs <= 0) return '';- return _fmtDur(secs);+ return formatHm(secs);}String _fmtDateTime(DateTime dt) {@@ -2110,9 +2108,7 @@ class _EpisodeDetailSheet extends StatelessWidget {String _fmtDurStr(String s) {final secs = double.tryParse(s) ?? 0;if (secs <= 0) return s;- final h = (secs / 3600).floor();- final m = ((secs % 3600) / 60).floor();- return h > 0 ? '${h}h ${m}m' : '${m}m';+ return formatHm(secs);}}@@ -2138,7 +2134,7 @@ class _DownloadedEpisodeDetailSheet extends StatelessWidget {final pubAt = episode['publishedAt'];final pubDate = pubAt is num ? pubAt : (num.tryParse(pubAt?.toString() ?? ''));final durRaw = episode['duration'];- final durStr = durRaw is num ? _fmtDur(durRaw.toDouble())+ final durStr = durRaw is num ? formatHm(durRaw.toDouble()): (durRaw is String && durRaw.isNotEmpty ? (durRaw.contains(':') ? durRaw : _fmtDurStr(durRaw)) : '');final season = episode['season']?.toString() ?? '';final episodeNum = episode['episode']?.toString() ?? '';@@ -2242,14 +2238,11 @@ class _DownloadedEpisodeDetailSheet extends StatelessWidget {return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(2)} GB';}- String _fmtDur(double s) { final h = (s / 3600).floor(); final m = ((s % 3600) / 60).floor();- return h > 0 ? '${h}h ${m}m' : '${m}m'; }-String _fmtDurStr(String s) {if (s.contains(':')) return s;final secs = double.tryParse(s) ?? 0;if (secs <= 0) return s;- return _fmtDur(secs);+ return formatHm(secs);}}diff --git a/lib/screens/admin_users_screen.dart b/lib/screens/admin_users_screen.dartindex e47ac6ab..b8e29858 100644--- a/lib/screens/admin_users_screen.dart+++ b/lib/screens/admin_users_screen.dart@@ -6,6 +6,7 @@ import '../providers/library_provider.dart';import '../widgets/absorb_page_header.dart';import '../widgets/absorb_wave_icon.dart';import '../l10n/app_localizations.dart';+import '../utils/duration_format.dart';class AdminUsersScreen extends StatefulWidget {final List<dynamic> users;@@ -639,7 +640,7 @@ class _UserDetailScreenState extends State<_UserDetailScreen> {]),const SizedBox(height: 3),Row(children: [- Text('${_fmtDur(currentTime.toDouble())} / ${_fmtDur(duration.toDouble())}',+ Text('${formatHm(currentTime.toDouble())} / ${formatHm(duration.toDouble())}',style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.2), fontSize: 9)),if (lastUpdateStr.isNotEmpty) ...[const Spacer(),@@ -704,7 +705,7 @@ class _UserDetailScreenState extends State<_UserDetailScreen> {])),const SizedBox(width: 8),Column(crossAxisAlignment: CrossAxisAlignment.end, children: [- Text(_fmtDur(duration), style: tt.labelSmall?.copyWith(+ Text(formatHm(duration), style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.4), fontWeight: FontWeight.w600, fontSize: 11)),if (updatedAt != null)Text(_relativeDate(updatedAt), style: TextStyle(color: cs.onSurface.withValues(alpha: 0.18), fontSize: 9)),@@ -773,12 +774,6 @@ class _UserDetailScreenState extends State<_UserDetailScreen> {return l.adminUsersMonthsAgo((d.inDays / 30).floor());}- String _fmtDur(double s) {- final h = (s / 3600).floor();- final m = ((s % 3600) / 60).floor();- if (h > 0) return '${h}h ${m}m';- return '${m}m';- }}// ═══════════════════════════════════════════════════════════════@@ -1053,10 +1048,7 @@ class _AdminSessionDetailsSheet extends StatelessWidget {}String _fmtDuration(double seconds) {- final h = (seconds / 3600).floor();- final m = ((seconds % 3600) / 60).floor();- if (h > 0) return '${h}h ${m}m';- if (m > 0) return '${m}m';+ if (seconds >= 60) return formatHm(seconds);if (seconds > 0) return '<1m';return '0m';}diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dartindex d4359b90..63102a61 100644--- a/lib/screens/home_screen.dart+++ b/lib/screens/home_screen.dart@@ -27,6 +27,7 @@ import '../widgets/scroll_reveal.dart';import '../widgets/section_labels.dart';import 'app_shell.dart';import '../l10n/app_localizations.dart';+import '../utils/duration_format.dart';class HomeScreen extends StatefulWidget {const HomeScreen({super.key});@@ -678,11 +679,8 @@ class _ContinueListeningCardState extends State<_ContinueListeningCard> {static String _fmtRemaining(double s) {if (s <= 0) return '';- final h = (s / 3600).floor();- final m = ((s % 3600) / 60).floor();- if (h > 0) return '${h}h ${m}m left';- if (m > 0) return '${m}m left';- return '<1m left';+ if (s < 60) return '<1m left';+ return '${formatHm(s)} left';}Widget _buildCoverImage(String? coverUrl, ColorScheme cs, Map<String, String> headers) {diff --git a/lib/services/rmab_service.dart b/lib/services/rmab_service.dartindex 80ad8510..e4268fbe 100644--- a/lib/services/rmab_service.dart+++ b/lib/services/rmab_service.dart@@ -3,6 +3,7 @@ import 'dart:convert';import 'dart:io';import 'package:flutter/foundation.dart';import 'package:http/http.dart' as http;+import '../l10n/app_localizations.dart';/// HTTP client for the ReadMeABook (RMAB) native API.///@@ -331,6 +332,19 @@ class RmabException implements Exception {final RmabErrorKind kind;final String message;+ /// User-facing message for this error. [genericPrefix] labels the+ /// fallback case (e.g. request vs search wording).+ String localizedMessage(AppLocalizations l, String genericPrefix) {+ switch (kind) {+ case RmabErrorKind.unauthorized:+ return l.rmabRequestErrorTokenRejected;+ case RmabErrorKind.network:+ return l.rmabConfigErrorNetwork;+ default:+ return '$genericPrefix: $message';+ }+ }+@overrideString toString() => 'RmabException($kind): $message';}diff --git a/lib/utils/duration_format.dart b/lib/utils/duration_format.dartnew file mode 100644index 00000000..be2c6730--- /dev/null+++ b/lib/utils/duration_format.dart@@ -0,0 +1,9 @@+/// The app's standard compact duration label: "3h 12m", or "42m" under+/// an hour. For the player-style padded "H:MM:SS" see fmtTime in+/// absorbing_shared.dart.+String formatHm(double seconds) {+ final h = (seconds / 3600).floor();+ final m = ((seconds % 3600) / 60).floor();+ if (h > 0) return '${h}h ${m}m';+ return '${m}m';+}diff --git a/lib/widgets/author_books_sheet.dart b/lib/widgets/author_books_sheet.dartindex e36933f4..3df91ef7 100644--- a/lib/widgets/author_books_sheet.dart+++ b/lib/widgets/author_books_sheet.dart@@ -8,14 +8,13 @@ import '../services/wording.dart';import '../providers/auth_provider.dart';import '../providers/library_provider.dart';import '../services/audio_player_service.dart';+import 'books_sheet_shared.dart';import 'edit_author_sheet.dart';import 'library_grid_tiles.dart';import 'library_search_results.dart';import 'series_books_sheet.dart';import 'stackable_sheet.dart';-enum _AuthorLayout { list, grid }-/// Show a bottom sheet with author info and books.void showAuthorDetailSheet(BuildContext context, {required String authorId,@@ -67,7 +66,7 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {String? _asin;late String _displayName;bool _descExpanded = false;- _AuthorLayout _layout = _AuthorLayout.list;+ bool _gridView = false;bool _groupBySeries = true;@override@@ -82,7 +81,7 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {final grid = await PlayerSettings.getSheetGridView();final collapse = await PlayerSettings.getSheetCollapseSeries();if (mounted) setState(() {- _layout = grid ? _AuthorLayout.grid : _AuthorLayout.list;+ _gridView = grid;_groupBySeries = collapse;});}@@ -113,17 +112,7 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {// libraryItems from the author endpoint include full metadata with series infofinal rawItems = authorData['libraryItems'] as List<dynamic>? ?? [];_books = rawItems.whereType<Map<String, dynamic>>().toList();- // Register updatedAt for cover cache busting- final lib = context.read<LibraryProvider>();- for (final book in _books) {- final id = book['id'] as String?;- final bts = book['updatedAt'] as num?;- if (id != null && bts != null) lib.registerUpdatedAt(id, bts.toInt());- if (id != null) {- final coverPath = (book['media'] as Map<String, dynamic>?)?['coverPath'] as String?;- lib.registerHasCover(id, coverPath != null && coverPath.isNotEmpty);- }- }+ registerBookCovers(context.read<LibraryProvider>(), _books);}_isLoading = false;});@@ -162,23 +151,13 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {];if (_books.isEmpty) {- 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(l.noBooksFound,- style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),- ),- ),- ],- );+ return sheetEmptyBooksList(context,+ controller: widget.scrollController,+ headerWidgets: headerWidgets,+ bottomPad: bottomPad);}- if (_layout == _AuthorLayout.list) {+ if (!_gridView) {return _buildListView(cs, tt, lib, sections, headerWidgets, bottomPad, l);}return _buildGridView(cs, tt, lib, sections, headerWidgets, bottomPad, l);@@ -284,36 +263,19 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {}Widget _buildViewModeBar(ColorScheme cs, AppLocalizations l) {- 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,+ return sheetViewModeBar(+ context,+ gridView: _gridView,+ onChanged: (grid) => setState(() => _gridView = grid),+ leading: IconButton(+ icon: Icon(Icons.collections_bookmark_rounded, size: 20,+ color: _groupBySeries ? cs.primary : cs.onSurfaceVariant),+ tooltip: l.authorBooksGroupBySeries,visualDensity: VisualDensity.compact,onPressed: () {- setState(() => _layout = mode);- PlayerSettings.setSheetGridView(mode == _AuthorLayout.grid);+ setState(() => _groupBySeries = !_groupBySeries);+ PlayerSettings.setSheetCollapseSeries(_groupBySeries);},- );- }- 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: l.authorBooksGroupBySeries,- visualDensity: VisualDensity.compact,- onPressed: () {- setState(() => _groupBySeries = !_groupBySeries);- PlayerSettings.setSheetCollapseSeries(_groupBySeries);- },- ),- const Spacer(),- layoutBtn(Icons.view_list_rounded, _AuthorLayout.list, l.authorBooksList),- layoutBtn(Icons.apps_rounded, _AuthorLayout.grid, l.authorBooksGrid),- ],),);}@@ -372,10 +334,7 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {SliverPadding(padding: EdgeInsets.fromLTRB(16, 0, 16, bottomPad),sliver: SliverGrid(- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(- crossAxisCount: (MediaQuery.of(context).size.width / 130).floor().clamp(3, 10),- mainAxisSpacing: 8, crossAxisSpacing: 8, childAspectRatio: 0.55,- ),+ gridDelegate: sheetBookGridDelegate(context),delegate: SliverChildBuilderDelegate((_, i) {final item = collapsed[i];if (item is _BookSection) {@@ -398,10 +357,7 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {SliverPadding(padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),sliver: SliverGrid(- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(- crossAxisCount: (MediaQuery.of(context).size.width / 130).floor().clamp(3, 10),- mainAxisSpacing: 8, crossAxisSpacing: 8, childAspectRatio: 0.55,- ),+ gridDelegate: sheetBookGridDelegate(context),delegate: SliverChildBuilderDelegate((_, i) => GridBookTile(item: section.books[i], sequenceBadge: _sequenceFor(section.books[i], section.label)?.replaceFirst('#', '')),childCount: section.books.length,@@ -551,56 +507,35 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {}Widget _buildHeader(ColorScheme cs, TextTheme tt, Map<String, String> headers, AppLocalizations l, {bool canEdit = false}) {- return Padding(- padding: const EdgeInsets.fromLTRB(24, 0, 24, 12),- child: Row(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Container(- width: 72,- height: 72,- decoration: BoxDecoration(- shape: BoxShape.circle,- color: cs.secondaryContainer,- ),- clipBehavior: Clip.antiAlias,- child: _imageUrl != null- ? CachedNetworkImage(- imageUrl: _imageUrl!,- fit: BoxFit.cover,- httpHeaders: headers,- placeholder: (_, __) => _avatarPlaceholder(cs),- errorWidget: (_, __, ___) => _avatarPlaceholder(cs),- )- : _avatarPlaceholder(cs),- ),- const SizedBox(width: 16),- Expanded(- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- const SizedBox(height: 4),- Text(_displayName,- style: tt.titleLarge?.copyWith(fontWeight: FontWeight.w600)),- if (_books.isNotEmpty)- Padding(- padding: const EdgeInsets.only(top: 4),- child: Text(- l.authorBooksBookCount(_books.length),- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),- ),- ),- ],- ),- ),- if (canEdit)- IconButton(+ return sheetPersonHeader(+ context,+ avatar: Container(+ width: 72,+ height: 72,+ decoration: BoxDecoration(+ shape: BoxShape.circle,+ color: cs.secondaryContainer,+ ),+ clipBehavior: Clip.antiAlias,+ child: _imageUrl != null+ ? CachedNetworkImage(+ imageUrl: _imageUrl!,+ fit: BoxFit.cover,+ httpHeaders: headers,+ placeholder: (_, __) => _avatarPlaceholder(cs),+ errorWidget: (_, __, ___) => _avatarPlaceholder(cs),+ )+ : _avatarPlaceholder(cs),+ ),+ title: _displayName,+ subtitle: _books.isNotEmpty ? l.authorBooksBookCount(_books.length) : null,+ trailing: canEdit+ ? IconButton(icon: Icon(Icons.edit_rounded, size: 20, color: cs.onSurfaceVariant),tooltip: l.editAuthor,onPressed: _openEditAuthor,- ),- ],- ),+ )+ : null,);}diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dartindex 8ec0cca8..66cc0103 100644--- a/lib/widgets/book_detail_sheet.dart+++ b/lib/widgets/book_detail_sheet.dart@@ -41,6 +41,7 @@ import 'playlist_picker_sheet.dart';import 'collection_picker_sheet.dart';import 'absorb_wave_icon.dart';import 'stackable_sheet.dart';+import '../utils/duration_format.dart';// ─── BOOK DETAIL BOTTOM SHEET ───────────────────────────────@@ -603,7 +604,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {const SizedBox(height: 16),Wrap(spacing: 8, runSpacing: 8, children: [if (year.isNotEmpty) _chip(Icons.calendar_today_rounded, year),- _chip(Icons.schedule_rounded, _fmtDur(duration)),+ _chip(Icons.schedule_rounded, formatHm(duration)),if (chapters.isNotEmpty) _chip(Icons.list_rounded, l.chaptersChip(chapters.length)),..._audioInfoChips(media),if (publisher.isNotEmpty) _chip(Icons.business_rounded, publisher),@@ -674,7 +675,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {child: Row(children: [SizedBox(width: 28, child: Text('${e.key + 1}', style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.3)))),Expanded(child: Text(ch['title'] as String? ?? l.chapterNumber(e.key + 1), maxLines: 1, overflow: TextOverflow.ellipsis, style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.6)))),- Text(_fmtDur(((ch['end'] as num?)?.toDouble() ?? 0) - ((ch['start'] as num?)?.toDouble() ?? 0)), style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.3))),+ Text(formatHm(((ch['end'] as num?)?.toDouble() ?? 0) - ((ch['start'] as num?)?.toDouble() ?? 0)), style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.3))),]));})]],if (_bookmarks.isNotEmpty) ...[const SizedBox(height: 16),@@ -1187,11 +1188,6 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {return '${months[d.month - 1]} ${d.day}, ${d.year}';}- String _fmtDur(double s) {- final h = (s / 3600).floor(); final m = ((s % 3600) / 60).floor();- if (h > 0) return '${h}h ${m}m';- return '${m}m';- }List<Widget> _buildStars(double rating, Color accent) {final cs = Theme.of(context).colorScheme;diff --git a/lib/widgets/books_sheet_shared.dart b/lib/widgets/books_sheet_shared.dartnew file mode 100644index 00000000..df484596--- /dev/null+++ b/lib/widgets/books_sheet_shared.dart@@ -0,0 +1,140 @@+import 'package:flutter/material.dart';+import '../l10n/app_localizations.dart';+import '../providers/library_provider.dart';+import '../services/audio_player_service.dart';++/// Helpers shared by the book-list sheets (author, narrator, series).++/// Register cover cache-busting and has-cover info for one book.+void registerBookCover(LibraryProvider lib, Map<String, dynamic> book) {+ final id = book['id'] as String?;+ if (id == null) return;+ final ts = book['updatedAt'] as num?;+ if (ts != null) lib.registerUpdatedAt(id, ts.toInt());+ final coverPath = (book['media'] as Map<String, dynamic>?)?['coverPath'] as String?;+ lib.registerHasCover(id, coverPath != null && coverPath.isNotEmpty);+}++void registerBookCovers(LibraryProvider lib, Iterable<Map<String, dynamic>> books) {+ for (final book in books) {+ registerBookCover(lib, book);+ }+}++/// Standard grid delegate for book grids inside sheets.+SliverGridDelegateWithFixedCrossAxisCount sheetBookGridDelegate(+ BuildContext context, {+ double childAspectRatio = 0.55,+}) {+ return SliverGridDelegateWithFixedCrossAxisCount(+ crossAxisCount: (MediaQuery.of(context).size.width / 130).floor().clamp(3, 10),+ mainAxisSpacing: 8,+ crossAxisSpacing: 8,+ childAspectRatio: childAspectRatio,+ );+}++/// List/grid toggle row shown under a sheet header. Persists the choice via+/// [PlayerSettings.setSheetGridView]; [leading] is an optional control pinned+/// to the left (e.g. a group-by-series toggle).+Widget sheetViewModeBar(+ BuildContext context, {+ required bool gridView,+ required ValueChanged<bool> onChanged,+ Widget? leading,+ EdgeInsetsGeometry padding = const EdgeInsets.fromLTRB(16, 0, 16, 4),+}) {+ final cs = Theme.of(context).colorScheme;+ final l = AppLocalizations.of(context)!;+ Widget layoutBtn(IconData icon, bool grid, String tooltip) {+ final active = gridView == grid;+ return IconButton(+ icon: Icon(icon, size: 20, color: active ? cs.primary : cs.onSurfaceVariant),+ tooltip: tooltip,+ visualDensity: VisualDensity.compact,+ onPressed: () {+ onChanged(grid);+ PlayerSettings.setSheetGridView(grid);+ },+ );+ }+ return Padding(+ padding: padding,+ child: Row(+ children: [+ if (leading != null) leading,+ const Spacer(),+ layoutBtn(Icons.view_list_rounded, false, l.authorBooksList),+ layoutBtn(Icons.apps_rounded, true, l.authorBooksGrid),+ ],+ ),+ );+}++/// Round-avatar header used by the author and narrator sheets:+/// 72px avatar, name, book count, optional trailing action.+Widget sheetPersonHeader(+ BuildContext context, {+ required Widget avatar,+ required String title,+ String? subtitle,+ Widget? trailing,+}) {+ final cs = Theme.of(context).colorScheme;+ final tt = Theme.of(context).textTheme;+ return Padding(+ padding: const EdgeInsets.fromLTRB(24, 0, 24, 12),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ avatar,+ const SizedBox(width: 16),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ const SizedBox(height: 4),+ Text(title,+ style: tt.titleLarge?.copyWith(fontWeight: FontWeight.w600)),+ if (subtitle != null)+ Padding(+ padding: const EdgeInsets.only(top: 4),+ child: Text(+ subtitle,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),+ ),+ ),+ ],+ ),+ ),+ if (trailing != null) trailing,+ ],+ ),+ );+}++/// Scrollable "no books" body that keeps the header widgets visible.+Widget sheetEmptyBooksList(+ BuildContext context, {+ required ScrollController controller,+ required List<Widget> headerWidgets,+ required double bottomPad,+}) {+ final cs = Theme.of(context).colorScheme;+ final tt = Theme.of(context).textTheme;+ final l = AppLocalizations.of(context)!;+ return ListView(+ controller: controller,+ padding: EdgeInsets.fromLTRB(0, 0, 0, bottomPad),+ children: [+ ...headerWidgets,+ Center(+ child: Padding(+ padding: const EdgeInsets.only(top: 48),+ child: Text(l.noBooksFound,+ style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),+ ),+ ),+ ],+ );+}diff --git a/lib/widgets/episode_detail_sheet.dart b/lib/widgets/episode_detail_sheet.dartindex 39773f24..fe4902ea 100644--- a/lib/widgets/episode_detail_sheet.dart+++ b/lib/widgets/episode_detail_sheet.dart@@ -18,6 +18,7 @@ import 'action_pill.dart';import '../main.dart' show rootNavigatorKey;import 'stackable_sheet.dart';import 'episode_list_sheet.dart';+import '../utils/duration_format.dart';class EpisodeDetailSheet extends StatefulWidget {final Map<String, dynamic> podcastItem;@@ -407,7 +408,7 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {child: Row(children: [SizedBox(width: 28, child: Text('${e.key + 1}', style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.3)))),Expanded(child: Text(ch['title'] as String? ?? l.chapterNumber(e.key + 1), maxLines: 1, overflow: TextOverflow.ellipsis, style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.6)))),- Text(_fmtDur(((ch['end'] as num?)?.toDouble() ?? 0) - ((ch['start'] as num?)?.toDouble() ?? 0)), style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.3))),+ Text(formatHm(((ch['end'] as num?)?.toDouble() ?? 0) - ((ch['start'] as num?)?.toDouble() ?? 0)), style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.3))),]));})]],@@ -697,12 +698,6 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {);}- String _fmtDur(double s) {- final h = (s / 3600).floor(); final m = ((s % 3600) / 60).floor();- if (h > 0) return '${h}h ${m}m';- return '${m}m';- }-Future<void> _resetProgress(BuildContext context) async {final l = AppLocalizations.of(context)!;final confirmed = await showDialog<bool>(diff --git a/lib/widgets/narrator_books_sheet.dart b/lib/widgets/narrator_books_sheet.dartindex 53f1724d..c95f8fa5 100644--- a/lib/widgets/narrator_books_sheet.dart+++ b/lib/widgets/narrator_books_sheet.dart@@ -4,12 +4,11 @@ import '../l10n/app_localizations.dart';import '../providers/auth_provider.dart';import '../providers/library_provider.dart';import '../services/audio_player_service.dart';+import 'books_sheet_shared.dart';import 'library_grid_tiles.dart';import 'library_search_results.dart';import 'stackable_sheet.dart';-enum _NarratorLayout { list, grid }-/// Show a stackable sheet listing books narrated by [narratorName].void showNarratorBooksSheet(BuildContext context, {required String narratorName,@@ -52,7 +51,7 @@ class NarratorBooksSheet extends StatefulWidget {class _NarratorBooksSheetState extends State<NarratorBooksSheet> {List<Map<String, dynamic>> _books = [];bool _isLoading = true;- _NarratorLayout _layout = _NarratorLayout.list;+ bool _gridView = false;@overridevoid initState() {@@ -63,9 +62,7 @@ class _NarratorBooksSheetState extends State<NarratorBooksSheet> {Future<void> _loadViewSettings() async {final grid = await PlayerSettings.getSheetGridView();- if (mounted) setState(() {- _layout = grid ? _NarratorLayout.grid : _NarratorLayout.list;- });+ if (mounted) setState(() => _gridView = grid);}Future<void> _loadBooks() async {@@ -79,17 +76,8 @@ class _NarratorBooksSheetState extends State<NarratorBooksSheet> {final raw = await api.getBooksByNarrator(widget.libraryId, widget.narratorName, limit: 200);if (!mounted) return;- final lib = context.read<LibraryProvider>();final books = raw.whereType<Map<String, dynamic>>().toList();- for (final book in books) {- final id = book['id'] as String?;- final bts = book['updatedAt'] as num?;- if (id != null && bts != null) lib.registerUpdatedAt(id, bts.toInt());- if (id != null) {- final coverPath = (book['media'] as Map<String, dynamic>?)?['coverPath'] as String?;- lib.registerHasCover(id, coverPath != null && coverPath.isNotEmpty);- }- }+ registerBookCovers(context.read<LibraryProvider>(), books);// Sort alphabetically by titlebooks.sort((a, b) {@@ -106,8 +94,6 @@ class _NarratorBooksSheetState extends State<NarratorBooksSheet> {@overrideWidget build(BuildContext context) {- final cs = Theme.of(context).colorScheme;- final tt = Theme.of(context).textTheme;final l = AppLocalizations.of(context)!;final bottomPad = 24 + MediaQuery.of(context).viewPadding.bottom;@@ -115,35 +101,28 @@ class _NarratorBooksSheetState extends State<NarratorBooksSheet> {return Column(crossAxisAlignment: CrossAxisAlignment.start,children: [- _buildHeader(cs, tt, l),+ _buildHeader(l),const Expanded(child: Center(child: CircularProgressIndicator())),],);}final headerWidgets = <Widget>[- _buildHeader(cs, tt, l),- if (_books.isNotEmpty) _buildViewModeBar(cs, l),+ _buildHeader(l),+ if (_books.isNotEmpty)+ sheetViewModeBar(context,+ gridView: _gridView,+ onChanged: (grid) => setState(() => _gridView = grid)),];if (_books.isEmpty) {- 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(l.noBooksFound,- style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),- ),- ),- ],- );+ return sheetEmptyBooksList(context,+ controller: widget.scrollController,+ headerWidgets: headerWidgets,+ bottomPad: bottomPad);}- if (_layout == _NarratorLayout.list) {+ if (!_gridView) {return ListView.builder(controller: widget.scrollController,padding: EdgeInsets.fromLTRB(0, 0, 0, bottomPad),@@ -170,12 +149,7 @@ class _NarratorBooksSheetState extends State<NarratorBooksSheet> {SliverPadding(padding: EdgeInsets.fromLTRB(16, 0, 16, bottomPad),sliver: SliverGrid(- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(- crossAxisCount: (MediaQuery.of(context).size.width / 130).floor().clamp(3, 10),- mainAxisSpacing: 8,- crossAxisSpacing: 8,- childAspectRatio: 0.55,- ),+ gridDelegate: sheetBookGridDelegate(context),delegate: SliverChildBuilderDelegate((_, i) => GridBookTile(item: _books[i]),childCount: _books.length,@@ -186,70 +160,24 @@ class _NarratorBooksSheetState extends State<NarratorBooksSheet> {);}- Widget _buildViewModeBar(ColorScheme cs, AppLocalizations l) {- Widget layoutBtn(IconData icon, _NarratorLayout 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 == _NarratorLayout.grid);- },- );- }- return Padding(- padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),- child: Row(- children: [- const Spacer(),- layoutBtn(Icons.view_list_rounded, _NarratorLayout.list, l.authorBooksList),- layoutBtn(Icons.apps_rounded, _NarratorLayout.grid, l.authorBooksGrid),- ],- ),- );- }-- Widget _buildHeader(ColorScheme cs, TextTheme tt, AppLocalizations l) {- return Padding(- padding: const EdgeInsets.fromLTRB(24, 0, 24, 12),- child: Row(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Container(- width: 72,- height: 72,- decoration: BoxDecoration(- shape: BoxShape.circle,- color: cs.tertiaryContainer,- ),- child: Center(- child: Icon(Icons.mic_rounded,- size: 36, color: cs.onTertiaryContainer.withValues(alpha: 0.7)),- ),- ),- const SizedBox(width: 16),- Expanded(- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- const SizedBox(height: 4),- Text(widget.narratorName,- style: tt.titleLarge?.copyWith(fontWeight: FontWeight.w600)),- if (_books.isNotEmpty)- Padding(- padding: const EdgeInsets.only(top: 4),- child: Text(- l.authorBooksBookCount(_books.length),- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),- ),- ),- ],- ),- ),- ],+ Widget _buildHeader(AppLocalizations l) {+ final cs = Theme.of(context).colorScheme;+ return sheetPersonHeader(+ context,+ avatar: Container(+ width: 72,+ height: 72,+ decoration: BoxDecoration(+ shape: BoxShape.circle,+ color: cs.tertiaryContainer,+ ),+ child: Center(+ child: Icon(Icons.mic_rounded,+ size: 36, color: cs.onTertiaryContainer.withValues(alpha: 0.7)),+ ),),+ title: widget.narratorName,+ subtitle: _books.isNotEmpty ? l.authorBooksBookCount(_books.length) : null,);}}diff --git a/lib/widgets/rmab_book_detail_sheet.dart b/lib/widgets/rmab_book_detail_sheet.dartindex 72e5766e..3cc06f47 100644--- a/lib/widgets/rmab_book_detail_sheet.dart+++ b/lib/widgets/rmab_book_detail_sheet.dart@@ -114,7 +114,7 @@ class _RmabBookDetailContentState extends State<_RmabBookDetailContent> {if (!mounted) return;debugPrint('[RMAB] detail submit exception: ${e.kind} ${e.message}');setState(() => _submitting = false);- _toast(_messageForException(e, l));+ _toast(e.localizedMessage(l, l.rmabRequestErrorGeneric));} catch (e) {if (!mounted) return;debugPrint('[RMAB] detail submit unexpected: $e');@@ -143,17 +143,6 @@ class _RmabBookDetailContentState extends State<_RmabBookDetailContent> {}}- String _messageForException(RmabException e, AppLocalizations l) {- switch (e.kind) {- case RmabErrorKind.unauthorized:- return l.rmabRequestErrorTokenRejected;- case RmabErrorKind.network:- return l.rmabConfigErrorNetwork;- default:- return '${l.rmabRequestErrorGeneric}: ${e.message}';- }- }-void _toast(String msg) {ScaffoldMessenger.of(context)..clearSnackBars()diff --git a/lib/widgets/rmab_search_results_sheet.dart b/lib/widgets/rmab_search_results_sheet.dartindex 0304291c..7cc79996 100644--- a/lib/widgets/rmab_search_results_sheet.dart+++ b/lib/widgets/rmab_search_results_sheet.dart@@ -139,9 +139,10 @@ class _RmabSearchSheetContentState extends State<_RmabSearchSheetContent> {} on RmabException catch (e) {if (!mounted) return;debugPrint('[RMAB] search sheet error: ${e.kind} ${e.message}');+ final l = AppLocalizations.of(context)!;setState(() {_searching = false;- _error = _errorTextFor(e);+ _error = e.localizedMessage(l, l.rmabSearchError);});} catch (e) {if (!mounted) return;@@ -153,18 +154,6 @@ class _RmabSearchSheetContentState extends State<_RmabSearchSheetContent> {}}- String _errorTextFor(RmabException e) {- final l = AppLocalizations.of(context)!;- switch (e.kind) {- case RmabErrorKind.unauthorized:- return l.rmabRequestErrorTokenRejected;- case RmabErrorKind.network:- return l.rmabConfigErrorNetwork;- default:- return '${l.rmabSearchError}: ${e.message}';- }- }-@overrideWidget build(BuildContext context) {final cs = Theme.of(context).colorScheme;diff --git a/lib/widgets/series_books_sheet.dart b/lib/widgets/series_books_sheet.dartindex e8a67337..641d5c4e 100644--- a/lib/widgets/series_books_sheet.dart+++ b/lib/widgets/series_books_sheet.dart@@ -16,7 +16,9 @@ import 'episode_list_sheet.dart';import 'stackable_sheet.dart';import 'audible_series_sheet.dart';import 'action_pill.dart';+import 'books_sheet_shared.dart';import '../services/api_service.dart';+import '../utils/duration_format.dart';/// Show a bottom sheet with all books in a series, sorted by sequence./// Can be called from any screen.@@ -176,23 +178,10 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {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'];- // Register updatedAt for cover cache busting- final id = item['id'] as String?;- final ts = item['updatedAt'] as num?;- if (id != null && ts != null && lib != null) lib.registerUpdatedAt(id, ts.toInt());- if (id != null && lib != null) {- final coverPath = (item['media'] as Map<String, dynamic>?)?['coverPath'] as String?;- lib.registerHasCover(id, coverPath != null && coverPath.isNotEmpty);- }+ if (lib != null) registerBookCover(lib, item);result.add(item);} else {- final id = b['id'] as String?;- final ts = b['updatedAt'] as num?;- if (id != null && ts != null && lib != null) lib.registerUpdatedAt(id, ts.toInt());- if (id != null && lib != null) {- final coverPath = (b['media'] as Map<String, dynamic>?)?['coverPath'] as String?;- lib.registerHasCover(id, coverPath != null && coverPath.isNotEmpty);- }+ if (lib != null) registerBookCover(lib, b);result.add(Map<String, dynamic>.from(b));}}@@ -402,15 +391,11 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {Widget _buildGroupedGrid(ColorScheme cs, TextTheme tt, LibraryProvider lib) {final parsed = _buildSubSeriesGroups();- final crossAxisCount = (MediaQuery.of(context).size.width / 130).floor().clamp(3, 10);return GridView.builder(controller: widget.scrollController,padding: EdgeInsets.fromLTRB(16, 0, 16, 24 + MediaQuery.of(context).viewPadding.bottom),- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(- crossAxisCount: crossAxisCount,- mainAxisSpacing: 8, crossAxisSpacing: 8, childAspectRatio: 0.65,- ),+ gridDelegate: sheetBookGridDelegate(context, childAspectRatio: 0.65),itemCount: parsed.subSeries.length + parsed.standalone.length,itemBuilder: (context, index) {if (index < parsed.subSeries.length) {@@ -922,7 +907,7 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {final bookCount = _totalBooks > 0 ? _totalBooks : _books.length;final base = l.booksInSeriesCount(bookCount);return displayDuration > 0- ? '$base · ${_formatDuration(displayDuration)}'+ ? '$base · ${formatHm(displayDuration)}': base;}(),),@@ -966,40 +951,26 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {),),if (_books.isNotEmpty)- Padding(+ sheetViewModeBar(+ context,+ gridView: _gridView,+ onChanged: (grid) => setState(() => _gridView = grid),padding: const EdgeInsets.symmetric(horizontal: 16),- child: Row(- children: [- IconButton(- icon: Icon(Icons.collections_bookmark_rounded, size: 20,- color: _collapseSeries ? cs.primary : cs.onSurfaceVariant),- visualDensity: VisualDensity.compact,- tooltip: _collapseSeries ? l.seriesBooksShowAllBooks : l.seriesBooksGroupBySubSeries,- onPressed: () {- setState(() {- _collapseSeries = !_collapseSeries;- if (_collapseSeries) {- _expandedSubSeries.clear();- if (!_subSeriesLoaded) _loadSubSeriesData();- }- });- PlayerSettings.setCollapseBookSeries(_collapseSeries);- },- ),- const Spacer(),- 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); },- ),- ],+ leading: IconButton(+ icon: Icon(Icons.collections_bookmark_rounded, size: 20,+ color: _collapseSeries ? cs.primary : cs.onSurfaceVariant),+ visualDensity: VisualDensity.compact,+ tooltip: _collapseSeries ? l.seriesBooksShowAllBooks : l.seriesBooksGroupBySubSeries,+ onPressed: () {+ setState(() {+ _collapseSeries = !_collapseSeries;+ if (_collapseSeries) {+ _expandedSubSeries.clear();+ if (!_subSeriesLoaded) _loadSubSeriesData();+ }+ });+ PlayerSettings.setCollapseBookSeries(_collapseSeries);+ },),),if (_isLoading && _books.isEmpty)@@ -1042,10 +1013,7 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {builder: (context, _) => GridView.builder(controller: widget.scrollController,padding: EdgeInsets.fromLTRB(16, 0, 16, 24 + MediaQuery.of(context).viewPadding.bottom),- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(- crossAxisCount: (MediaQuery.of(context).size.width / 130).floor().clamp(3, 10),- mainAxisSpacing: 8, crossAxisSpacing: 8, childAspectRatio: 0.65,- ),+ gridDelegate: sheetBookGridDelegate(context, childAspectRatio: 0.65),itemCount: _books.length,itemBuilder: (context, index) => GridBookTile(item: _books[index], sequenceBadge: _getSequenceString(_books[index])),),@@ -1216,7 +1184,7 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {if (duration > 0) ...[const SizedBox(height: 2),Row(children: [- Text(_formatDuration(duration), style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant)),+ Text(formatHm(duration), style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant)),if (progress > 0 && !isFinished) ...[const SizedBox(width: 8),Text('${(progress * 100).round()}%',@@ -1249,10 +1217,4 @@ class _SeriesBooksSheetState extends State<SeriesBooksSheet> {);}- 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';- }}