Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Fix startup freeze, add stream buffer, improve author links and UI

Nathan Poulsonefad783ca9c7
diff --git a/lib/screens/absorbing_screen.dart b/lib/screens/absorbing_screen.dart
index c584b497..74adf01c 100644
--- a/lib/screens/absorbing_screen.dart
+++ b/lib/screens/absorbing_screen.dart
@@ -473,8 +473,6 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
// ── Header ──
AbsorbPageHeader(
title: 'Absorbing',
- brandingColor: muted,
- titleColor: cs.onSurface,
padding: const EdgeInsets.fromLTRB(20, 12, 12, 0),
actions: [
// Offline mode toggle
diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dart
index 96fe6569..eadf11e6 100644
--- a/lib/screens/app_shell.dart
+++ b/lib/screens/app_shell.dart
@@ -462,18 +462,30 @@ class _AnimatedWaveIconState extends State<_AnimatedWaveIcon>
_ctrl = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 1400),
- )..repeat();
- _player.addListener(_rebuild);
+ );
+ _player.addListener(_onPlayerChanged);
+ _syncAnimation();
}
@override
void dispose() {
_ctrl.dispose();
- _player.removeListener(_rebuild);
+ _player.removeListener(_onPlayerChanged);
super.dispose();
}
- void _rebuild() { if (mounted) setState(() {}); }
+ void _onPlayerChanged() {
+ _syncAnimation();
+ if (mounted) setState(() {});
+ }
+
+ void _syncAnimation() {
+ if (_player.isPlaying) {
+ if (!_ctrl.isAnimating) _ctrl.repeat();
+ } else {
+ if (_ctrl.isAnimating) _ctrl.stop();
+ }
+ }
@override
Widget build(BuildContext context) {
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index ba2563e6..8c4e0d1f 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -221,6 +221,24 @@ class _SettingsScreenState extends State<SettingsScreen> {
});
}
+ Widget _infoIcon(String title, String content) {
+ final cs = Theme.of(context).colorScheme;
+ return GestureDetector(
+ onTap: () => showDialog(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: Text(title),
+ content: Text(content),
+ actions: [TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('Got it'))],
+ ),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.only(left: 4),
+ child: Icon(Icons.info_outline_rounded, size: 16, color: cs.onSurfaceVariant),
+ ),
+ );
+ }
+
Future<void> _saveRewind(AutoRewindSettings s) async {
setState(() => _rewindSettings = s);
await s.save();
@@ -643,7 +661,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
- Text('When absorbed', style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
+ Row(children: [
+ Text('When absorbed', style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
+ _infoIcon('When Absorbed', 'Controls what happens to an absorbing card when you finish a book or episode.\n\nShow Overlay: A completion overlay appears on the card, letting you choose what to do next.\n\nAuto-release: The finished card is automatically removed from your Absorbing screen.'),
+ ]),
const SizedBox(height: 4),
Text('What happens to the absorbing card when a book or episode finishes',
style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
@@ -663,7 +684,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
]),
),
SwitchListTile(
- title: const Text('Merge libraries'),
+ title: Row(children: [
+ const Text('Merge libraries'),
+ _infoIcon('Merge Libraries', 'When enabled, the Absorbing screen shows all your in-progress books and podcasts from every library in a single view. When disabled, only items from the library you currently have selected are shown.'),
+ ]),
subtitle: Text(
_mergeAbsorbingLibraries
? 'Absorbing page shows items from all libraries'
@@ -1179,7 +1203,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
),
const Divider(height: 1, indent: 16, endIndent: 16),
SwitchListTile(
- title: const Text('Auto download on Wi-Fi'),
+ title: Row(children: [
+ const Text('Auto download on Wi-Fi'),
+ _infoIcon('Auto Download on Wi-Fi', 'When you start streaming a book over Wi-Fi, it will automatically begin downloading the full book in the background. This way you\'ll have it available offline without having to manually start the download.'),
+ ]),
subtitle: Text(
_autoDownloadOnStream
? 'Books download in the background when you start streaming on Wi-Fi'
@@ -1231,7 +1258,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- Text('Keep next', style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
+ Row(children: [
+ Text('Keep next', style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
+ _infoIcon('Keep Next', 'The number of items to keep downloaded, including the one you\'re currently listening to. For example, "Keep next 3" means the current book plus the next 2 in the series or podcast will stay downloaded.'),
+ ]),
const SizedBox(height: 8),
SizedBox(width: double.infinity, child: SegmentedButton<int>(
segments: const [
@@ -1251,7 +1281,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
),
),
SwitchListTile(
- title: const Text('Delete absorbed downloads'),
+ title: Row(children: [
+ const Text('Delete absorbed downloads'),
+ _infoIcon('Delete Absorbed Downloads', 'When enabled, downloaded books or episodes are automatically deleted from your device after you finish listening to them. This helps free up storage space as you work through your library.'),
+ ]),
subtitle: Text(
_rollingDownloadDeleteFinished
? 'Finished items are removed to save space'
@@ -1305,7 +1338,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 12),
- Text('Streaming cache', style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
+ Row(children: [
+ Text('Streaming cache', style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
+ _infoIcon('Streaming Cache', 'Caches streamed audio to disk so it doesn\'t need to be re-downloaded if you seek back or re-listen to sections. The cache is automatically managed - oldest files are removed when the size limit is reached. This is separate from fully downloaded books.'),
+ ]),
const SizedBox(height: 4),
Text(
_streamingCacheSizeMb == 0
@@ -1570,7 +1606,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
onExpansionChanged: (v) => _onSectionExpanded('Advanced', v),
children: [
SwitchListTile(
- title: const Text('Local server'),
+ title: Row(children: [
+ const Text('Local server'),
+ _infoIcon('Local Server', 'If you run your Audiobookshelf server at home, you can set a local/LAN URL here. Absorb will automatically switch to the faster local connection when it detects you\'re on your home network, and fall back to your remote URL when you\'re away.'),
+ ]),
subtitle: Text(
_localServerEnabled
? (auth.useLocalServer
@@ -1661,7 +1700,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
],
const Divider(height: 1, indent: 16, endIndent: 16),
SwitchListTile(
- title: const Text('Disable audio focus'),
+ title: Row(children: [
+ const Text('Disable audio focus'),
+ _infoIcon('Audio Focus', 'By default, Android gives audio "focus" to one app at a time - when Absorb plays, other audio (music, videos) will pause. Disabling audio focus lets Absorb play alongside other apps. Phone calls will still pause playback regardless of this setting.'),
+ ]),
subtitle: Text(
_disableAudioFocus
? 'On - plays alongside other audio (still pauses for calls)'
diff --git a/lib/screens/stats_screen.dart b/lib/screens/stats_screen.dart
index 5cbc14f7..0f8aa15b 100644
--- a/lib/screens/stats_screen.dart
+++ b/lib/screens/stats_screen.dart
@@ -188,11 +188,11 @@ class _StatsScreenState extends State<StatsScreen>
final topItems = _topItems();
return ListView(
- padding: const EdgeInsets.fromLTRB(20, 8, 20, 32),
+ padding: const EdgeInsets.fromLTRB(20, 0, 20, 32),
children: [
const AbsorbPageHeader(
title: 'Your Stats',
- padding: EdgeInsets.only(top: 4),
+ padding: EdgeInsets.only(top: 12),
),
const SizedBox(height: 24),
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 839e2030..32263fdb 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -336,8 +336,11 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
handleInterruptions: false,
audioLoadConfiguration: const AudioLoadConfiguration(
androidLoadControl: AndroidLoadControl(
+ minBufferDuration: Duration(minutes: 5),
+ maxBufferDuration: Duration(minutes: 5),
bufferForPlaybackDuration: Duration(milliseconds: 500),
bufferForPlaybackAfterRebufferDuration: Duration(milliseconds: 2000),
+ backBufferDuration: Duration(minutes: 5),
),
),
);
@@ -356,13 +359,21 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
}
AudioPlayerHandler() {
- // Manually subscribe instead of .pipe() so we can handle errors.
- // Without onError, a stream error (e.g. network timeout during streaming)
- // would break the audio_service notification pipeline and crash the app.
+ _subscribePlaybackEvents();
+ }
+
+ /// Subscribe to the player's playback event stream and forward state to
+ /// the system MediaSession. If the stream errors (e.g. network timeout),
+ /// re-subscribe so system media controls stay alive.
+ void _subscribePlaybackEvents() {
_player.playbackEventStream.map(_transformEvent).listen(
playbackState.add,
onError: (Object e, StackTrace st) {
- debugPrint('[Player] playbackEvent error (suppressed): $e');
+ debugPrint('[Player] playbackEvent error - re-subscribing: $e');
+ // Push the last known good state so the notification doesn't go stale
+ refreshPlaybackState();
+ // Re-subscribe so future events still reach the MediaSession
+ _subscribePlaybackEvents();
},
);
}
@@ -1240,14 +1251,21 @@ class AudioPlayerService extends ChangeNotifier {
// Still pause when headphones/BT disconnect
_noisySub?.cancel();
_noisySub = session.becomingNoisyEventStream.listen((_) async {
- final service = _instance;
- debugPrint('[AudioSession] Becoming noisy - pausing');
- _noisyPause = true;
- service._wasPlayingBeforeInterrupt = false;
- _handler?.cancelPendingClick();
- if (service.isPlaying) {
- await service.pause();
+ try {
+ final service = _instance;
+ debugPrint('[AudioSession] Becoming noisy - pausing');
+ _noisyPause = true;
+ service._wasPlayingBeforeInterrupt = false;
+ _handler?.cancelPendingClick();
+ if (service.isPlaying) {
+ await service.pause();
+ }
+ } catch (e) {
+ debugPrint('[AudioSession] Noisy handler error: $e');
}
+ }, onError: (e) {
+ debugPrint('[AudioSession] Noisy stream error - re-subscribing: $e');
+ _configureAudioSession();
});
return;
}
@@ -1257,67 +1275,81 @@ class AudioPlayerService extends ChangeNotifier {
_interruptSub?.cancel();
_interruptSub = session.interruptionEventStream.listen((event) async {
- final service = _instance;
+ try {
+ final service = _instance;
- if (event.begin) {
- if (service.isPlaying) {
- debugPrint('[AudioSession] Interrupted (${event.type}) — pausing');
- _wasOnBluetooth = await _isBluetoothAudioConnected();
- debugPrint('[AudioSession] Was on BT: $_wasOnBluetooth');
- // Pause the underlying player directly — NOT service.pause() —
- // to keep the interruption lightweight. service.pause() saves progress,
- // syncs to server, clears _wasPlayingBeforeInterrupt, and sets
- // _lastPauseTime (triggering auto-rewind on resume). For transient
- // notification interruptions we just need to duck the audio briefly.
- await service._player?.pause();
- service._wasPlayingBeforeInterrupt = true;
- }
- } else {
- // Don't auto-resume if the pause was caused by BT/headphone disconnect.
- // Some devices fire interruption-end AFTER becoming-noisy, which would
- // resume playback on the phone speaker.
- if (_noisyPause) {
- debugPrint('[AudioSession] Interruption ended after noisy — skipping resume');
- service._wasPlayingBeforeInterrupt = false;
- return;
- }
- if (service._wasPlayingBeforeInterrupt) {
- service._wasPlayingBeforeInterrupt = false;
- await Future.delayed(const Duration(milliseconds: 600));
- // Re-check: another event (like becoming-noisy) might have fired
- // during the delay.
- if (_noisyPause) return;
- // If we were on BT when interrupted, check if BT is still connected.
- // Some car head units never send AUDIO_BECOMING_NOISY on disconnect,
- // so _noisyPause alone is not enough.
- if (_wasOnBluetooth) {
- final stillOnBt = await _isBluetoothAudioConnected();
- debugPrint('[AudioSession] Interruption ended — was BT, still BT: $stillOnBt');
- if (!stillOnBt) {
- debugPrint('[AudioSession] BT disconnected during interruption — skipping resume');
- _noisyPause = true;
- return;
+ if (event.begin) {
+ if (service.isPlaying) {
+ debugPrint('[AudioSession] Interrupted (${event.type}) — pausing');
+ _wasOnBluetooth = await _isBluetoothAudioConnected();
+ debugPrint('[AudioSession] Was on BT: $_wasOnBluetooth');
+ // Pause the underlying player directly — NOT service.pause() —
+ // to keep the interruption lightweight. service.pause() saves progress,
+ // syncs to server, clears _wasPlayingBeforeInterrupt, and sets
+ // _lastPauseTime (triggering auto-rewind on resume). For transient
+ // notification interruptions we just need to duck the audio briefly.
+ await service._player?.pause();
+ service._wasPlayingBeforeInterrupt = true;
+ }
+ } else {
+ // Don't auto-resume if the pause was caused by BT/headphone disconnect.
+ // Some devices fire interruption-end AFTER becoming-noisy, which would
+ // resume playback on the phone speaker.
+ if (_noisyPause) {
+ debugPrint('[AudioSession] Interruption ended after noisy — skipping resume');
+ service._wasPlayingBeforeInterrupt = false;
+ return;
+ }
+ if (service._wasPlayingBeforeInterrupt) {
+ service._wasPlayingBeforeInterrupt = false;
+ await Future.delayed(const Duration(milliseconds: 600));
+ // Re-check: another event (like becoming-noisy) might have fired
+ // during the delay.
+ if (_noisyPause) return;
+ // If we were on BT when interrupted, check if BT is still connected.
+ // Some car head units never send AUDIO_BECOMING_NOISY on disconnect,
+ // so _noisyPause alone is not enough.
+ if (_wasOnBluetooth) {
+ final stillOnBt = await _isBluetoothAudioConnected();
+ debugPrint('[AudioSession] Interruption ended — was BT, still BT: $stillOnBt');
+ if (!stillOnBt) {
+ debugPrint('[AudioSession] BT disconnected during interruption — skipping resume');
+ _noisyPause = true;
+ return;
+ }
}
+ debugPrint('[AudioSession] Interruption ended — resuming');
+ await service.play();
}
- debugPrint('[AudioSession] Interruption ended — resuming');
- await service.play();
}
+ } catch (e) {
+ debugPrint('[AudioSession] Interruption handler error: $e');
}
+ }, onError: (e) {
+ debugPrint('[AudioSession] Interruption stream error - re-subscribing: $e');
+ _configureAudioSession();
});
// Headphones unplugged / BT disconnected — pause, no auto-resume
_noisySub?.cancel();
_noisySub = session.becomingNoisyEventStream.listen((_) async {
- final service = _instance;
- debugPrint('[AudioSession] Becoming noisy — pausing');
- _noisyPause = true;
- service._wasPlayingBeforeInterrupt = false;
- // Cancel any pending media-button click from the BT disconnect so the
- // delayed click handler doesn't resume playback on the phone speaker.
- _handler?.cancelPendingClick();
- if (service.isPlaying) {
- await service.pause();
+ try {
+ final service = _instance;
+ debugPrint('[AudioSession] Becoming noisy — pausing');
+ _noisyPause = true;
+ service._wasPlayingBeforeInterrupt = false;
+ // Cancel any pending media-button click from the BT disconnect so the
+ // delayed click handler doesn't resume playback on the phone speaker.
+ _handler?.cancelPendingClick();
+ if (service.isPlaying) {
+ await service.pause();
+ }
+ } catch (e) {
+ debugPrint('[AudioSession] Noisy handler error: $e');
}
+ }, onError: (e) {
+ debugPrint('[AudioSession] Noisy stream error - re-subscribing: $e');
+ _configureAudioSession();
});
}
diff --git a/lib/services/download_service.dart b/lib/services/download_service.dart
index 901e0fa9..a80feb68 100644
--- a/lib/services/download_service.dart
+++ b/lib/services/download_service.dart
@@ -284,7 +284,6 @@ class DownloadService extends ChangeNotifier {
if (json != null) {
try {
final map = jsonDecode(json) as Map<String, dynamic>;
- final orphanIds = <String>[];
for (final entry in map.entries) {
final info =
DownloadInfo.fromJson(entry.value as Map<String, dynamic>);
@@ -293,37 +292,9 @@ class DownloadService extends ChangeNotifier {
'cover=${info.coverUrl != null ? "yes" : "null"} '
'sessionData=${info.sessionData != null ? "${info.sessionData!.length} chars" : "null"}');
if (info.status == DownloadStatus.downloaded) {
- bool allExist = true;
- for (final path in info.localPaths) {
- if (!await File(path).exists()) {
- allExist = false;
- break;
- }
- }
- if (allExist) {
- _downloads[entry.key] = info;
- } else {
- orphanIds.add(entry.key);
- }
+ _downloads[entry.key] = info;
} else {
- // Stale downloading/error entries from a previous crash
- orphanIds.add(entry.key);
- }
- }
- // Clean up partial/orphaned files on disk
- if (orphanIds.isNotEmpty) {
- final basePath = await downloadBasePath;
- final internalBase = await _internalBasePath;
- for (final id in orphanIds) {
- debugPrint('[Download] Cleaning up orphaned entry: $id');
- try {
- final dir = Directory('$basePath/$id');
- if (await dir.exists()) await dir.delete(recursive: true);
- } catch (_) {}
- try {
- final coverDir = Directory('$internalBase/$id');
- if (await coverDir.exists()) await coverDir.delete(recursive: true);
- } catch (_) {}
+ debugPrint('[Download] Skipping stale ${info.status} entry: ${entry.key}');
}
}
} catch (e) {
@@ -333,6 +304,53 @@ class DownloadService extends ChangeNotifier {
// Re-save to persist any metadata extracted from sessionData
if (_downloads.isNotEmpty) await _save();
notifyListeners();
+
+ // Validate files and clean up orphans in background after startup
+ _validateDownloads();
+ }
+
+ /// Validate that downloaded files still exist on disk and clean up orphans.
+ /// Runs in background so it doesn't block app startup.
+ Future<void> _validateDownloads() async {
+ try {
+ final orphanIds = <String>[];
+ final entries = Map<String, DownloadInfo>.from(_downloads);
+ for (final entry in entries.entries) {
+ if (entry.value.status != DownloadStatus.downloaded) continue;
+ bool allExist = true;
+ for (final path in entry.value.localPaths) {
+ if (!await File(path).exists()) {
+ allExist = false;
+ break;
+ }
+ }
+ if (!allExist) {
+ debugPrint('[Download] Files missing for ${entry.key}, removing');
+ _downloads.remove(entry.key);
+ orphanIds.add(entry.key);
+ }
+ }
+ if (orphanIds.isNotEmpty) {
+ await _save();
+ notifyListeners();
+ // Clean up partial/orphaned files on disk
+ final basePath = await downloadBasePath;
+ final internalBase = await _internalBasePath;
+ for (final id in orphanIds) {
+ debugPrint('[Download] Cleaning up orphaned entry: $id');
+ try {
+ final dir = Directory('$basePath/$id');
+ if (await dir.exists()) await dir.delete(recursive: true);
+ } catch (_) {}
+ try {
+ final coverDir = Directory('$internalBase/$id');
+ if (await coverDir.exists()) await coverDir.delete(recursive: true);
+ } catch (_) {}
+ }
+ }
+ } catch (e) {
+ debugPrint('[Download] Validation error: $e');
+ }
}
/// Try to fill in missing metadata from the API (for old downloads).
diff --git a/lib/widgets/absorb_page_header.dart b/lib/widgets/absorb_page_header.dart
index e772c897..6d15dbe6 100644
--- a/lib/widgets/absorb_page_header.dart
+++ b/lib/widgets/absorb_page_header.dart
@@ -26,7 +26,7 @@ class AbsorbPageHeader extends StatelessWidget {
Widget build(BuildContext context) {
final tt = Theme.of(context).textTheme;
final cs = Theme.of(context).colorScheme;
- final bColor = brandingColor ?? cs.onSurface.withValues(alpha: 0.3);
+ final bColor = brandingColor ?? cs.onSurfaceVariant;
final tColor = titleColor ?? cs.onSurface;
return Padding(
@@ -37,33 +37,36 @@ class AbsorbPageHeader extends StatelessWidget {
// Branding row — ABSORB + optional actions
LayoutBuilder(
builder: (ctx, lc) {
- return Row(
- children: [
- Text(
- 'A B S O R B',
- style: tt.labelSmall?.copyWith(
- color: bColor,
- letterSpacing: 4,
- fontWeight: FontWeight.w300,
- ),
- ),
- const Spacer(),
- if (actions != null)
- ConstrainedBox(
- constraints: BoxConstraints(
- maxWidth: (lc.maxWidth - 140).clamp(0.0, double.infinity),
+ return ConstrainedBox(
+ constraints: const BoxConstraints(minHeight: 32),
+ child: Row(
+ children: [
+ Text(
+ 'A B S O R B',
+ style: tt.labelSmall?.copyWith(
+ color: bColor,
+ letterSpacing: 4,
+ fontWeight: FontWeight.w300,
),
- child: FittedBox(
- fit: BoxFit.scaleDown,
- alignment: Alignment.centerRight,
- child: Row(
- mainAxisSize: MainAxisSize.min,
- spacing: 8,
- children: actions!,
+ ),
+ const Spacer(),
+ if (actions != null)
+ ConstrainedBox(
+ constraints: BoxConstraints(
+ maxWidth: (lc.maxWidth - 140).clamp(0.0, double.infinity),
+ ),
+ child: FittedBox(
+ fit: BoxFit.scaleDown,
+ alignment: Alignment.centerRight,
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ spacing: 8,
+ children: actions!,
+ ),
),
),
- ),
- ],
+ ],
+ ),
);
},
),
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index e9b76208..c8647161 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -58,6 +58,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
bool _hasLocalOverride = false;
bool _showGoodreads = false;
bool _ebookSaved = false;
+ bool _authorsExpanded = false;
@override void initState() {
super.initState();
@@ -227,14 +228,7 @@ 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),
- 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),
- )),
- ),
+ _buildAuthorLinks(context, metadata, cs, tt),
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) ─────────
@@ -683,26 +677,58 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
);
}
- void _openAuthor(BuildContext context, Map<String, dynamic> metadata) {
- // Get first author with an ID from the authors array
+ Widget _buildAuthorLinks(BuildContext context, Map<String, dynamic> metadata, ColorScheme cs, TextTheme tt) {
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;
- }
- }
+ // Fall back to authorName string if no structured authors array
+ if (authors.isEmpty) {
+ final name = metadata['authorName'] as String? ?? '';
+ if (name.isEmpty) return const SizedBox.shrink();
+ return Text(name, textAlign: TextAlign.center, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant));
}
- 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);
+
+ const int collapsedCount = 3;
+ final showAll = _authorsExpanded || authors.length <= collapsedCount;
+ final visible = showAll ? authors : authors.sublist(0, collapsedCount);
+ final remaining = authors.length - collapsedCount;
+
+ final linkStyle = tt.bodyMedium?.copyWith(
+ color: cs.primary,
+ decoration: TextDecoration.underline,
+ decorationColor: cs.primary.withValues(alpha: 0.4),
+ );
+ final commaStyle = tt.bodyMedium?.copyWith(color: cs.primary);
+
+ return Wrap(
+ alignment: WrapAlignment.center,
+ children: [
+ for (int i = 0; i < visible.length; i++) ...[
+ GestureDetector(
+ onTap: () {
+ final a = visible[i] as Map<String, dynamic>? ?? {};
+ final id = a['id'] as String? ?? '';
+ final name = a['name'] as String? ?? '';
+ if (id.isEmpty || name.isEmpty) return;
+ final nav = Navigator.of(context);
+ nav.pop();
+ showAuthorDetailSheet(nav.context, authorId: id, authorName: name);
+ },
+ child: Text(
+ (visible[i] as Map<String, dynamic>?)?['name'] as String? ?? '',
+ style: linkStyle,
+ ),
+ ),
+ if (i < visible.length - 1 || (!showAll && remaining > 0))
+ Text(', ', style: commaStyle),
+ ],
+ if (!showAll)
+ GestureDetector(
+ onTap: () => setState(() => _authorsExpanded = true),
+ child: Text('and $remaining more', style: tt.bodyMedium?.copyWith(
+ color: cs.primary.withValues(alpha: 0.7),
+ )),
+ ),
+ ],
+ );
}
Future<void> _openSeries(BuildContext context, String? seriesId, String seriesName) async {
diff --git a/lib/widgets/card_progress_bar.dart b/lib/widgets/card_progress_bar.dart
index 7a618c1a..2e895786 100644
--- a/lib/widgets/card_progress_bar.dart
+++ b/lib/widgets/card_progress_bar.dart
@@ -30,7 +30,6 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPr
double? _bookDragValue;
bool _showBookSlider = false;
bool _speedAdjustedTime = true;
- late AnimationController _waveController;
late AnimationController _smoothTicker;
// Smooth position tracking
@@ -45,8 +44,7 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPr
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
- _waveController = AnimationController(vsync: this, duration: const Duration(milliseconds: 2500))..repeat();
- _smoothTicker = AnimationController(vsync: this, duration: const Duration(days: 999))..repeat();
+ _smoothTicker = AnimationController(vsync: this, duration: const Duration(days: 999));
_loadSettings();
_subscribePosition();
PlayerSettings.settingsChanged.addListener(_loadSettings);
@@ -76,6 +74,14 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPr
if (old.isActive != widget.isActive) _subscribePosition();
}
+ void _syncTicker() {
+ if (_isPlaying && widget.isActive) {
+ if (!_smoothTicker.isAnimating) _smoothTicker.repeat();
+ } else {
+ if (_smoothTicker.isAnimating) _smoothTicker.stop();
+ }
+ }
+
void _subscribePosition() {
_posSub?.cancel();
final cast = ChromecastService();
@@ -86,12 +92,14 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPr
_lastPosTime = DateTime.now();
_currentSpeed = cast.castSpeed;
_isPlaying = cast.isPlaying;
+ _syncTicker();
_posSub = cast.castPositionStream?.listen((dur) {
final posSeconds = dur.inMilliseconds / 1000.0;
_lastKnownPos = posSeconds;
_lastPosTime = DateTime.now();
_currentSpeed = cast.castSpeed;
_isPlaying = cast.isPlaying;
+ _syncTicker();
});
} else if (widget.isActive) {
// Reset to the seed on a fresh subscription — clears stale position from a
@@ -114,6 +122,7 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPr
_lastPosTime = DateTime.now();
_currentSpeed = widget.player.speed;
_isPlaying = widget.player.isPlaying;
+ _syncTicker();
// Stream has caught up — clear the seek target so subsequent
// position updates flow through normally without filtering.
widget.player.clearSeekTarget();
@@ -132,9 +141,11 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPr
_lastPosTime = DateTime.now();
_currentSpeed = widget.player.speed;
_isPlaying = widget.player.isPlaying;
+ _syncTicker();
});
_currentSpeed = widget.player.speed;
_isPlaying = widget.player.isPlaying;
+ _syncTicker();
}
}
@@ -161,7 +172,6 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPr
PlayerSettings.settingsChanged.removeListener(_loadSettings);
ChromecastService().removeListener(_onCastChanged);
_posSub?.cancel();
- _waveController.dispose();
_smoothTicker.dispose();
super.dispose();
}