Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add playlist queue mode

Barnabasac7b6d5cdcd4
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index 76188bd1..6a5668c3 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -308,6 +308,17 @@
"queueModeOff": "Off",
"queueModeManual": "Manual",
"queueModeAuto": "Auto",
+ "queueModePlaylist": "Playlist",
+ "queueModeInfoPlaylist": "Playlist Queue",
+ "queueModeInfoPlaylistDesc": "Plays items in order from a chosen playlist, skipping anything already finished. Stops at the end of the list.",
+ "queuePlaylistPickerTitle": "Choose a playlist",
+ "queuePlaylistNone": "No playlist selected",
+ "queuePlaylistActiveLabel": "Playlist: {name}",
+ "@queuePlaylistActiveLabel": { "placeholders": { "name": { "type": "String" } } },
+ "queueModePlaylistHint": "Start a playlist queue by opening a playlist on the home page.",
+ "exit": "Exit",
+ "playlistPlayAction": "Play playlist",
+ "playlistAllFinished": "All finished",
"queueModeBooks": "Books",
"queueModePodcasts": "Podcasts",
"autoDownloadQueue": "Auto-download queue",
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index 5c13af7f..de00341e 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -1744,6 +1744,66 @@ abstract class AppLocalizations {
/// **'Auto'**
String get queueModeAuto;
+ /// No description provided for @queueModePlaylist.
+ ///
+ /// In en, this message translates to:
+ /// **'Playlist'**
+ String get queueModePlaylist;
+
+ /// No description provided for @queueModeInfoPlaylist.
+ ///
+ /// In en, this message translates to:
+ /// **'Playlist Queue'**
+ String get queueModeInfoPlaylist;
+
+ /// No description provided for @queueModeInfoPlaylistDesc.
+ ///
+ /// In en, this message translates to:
+ /// **'Plays items in order from a chosen playlist, skipping anything already finished. Stops at the end of the list.'**
+ String get queueModeInfoPlaylistDesc;
+
+ /// No description provided for @queuePlaylistPickerTitle.
+ ///
+ /// In en, this message translates to:
+ /// **'Choose a playlist'**
+ String get queuePlaylistPickerTitle;
+
+ /// No description provided for @queuePlaylistNone.
+ ///
+ /// In en, this message translates to:
+ /// **'No playlist selected'**
+ String get queuePlaylistNone;
+
+ /// No description provided for @queuePlaylistActiveLabel.
+ ///
+ /// In en, this message translates to:
+ /// **'Playlist: {name}'**
+ String queuePlaylistActiveLabel(String name);
+
+ /// No description provided for @queueModePlaylistHint.
+ ///
+ /// In en, this message translates to:
+ /// **'Start a playlist queue by opening a playlist on the home page.'**
+ String get queueModePlaylistHint;
+
+ /// No description provided for @exit.
+ ///
+ /// In en, this message translates to:
+ /// **'Exit'**
+ String get exit;
+
+ /// No description provided for @playlistPlayAction.
+ ///
+ /// In en, this message translates to:
+ /// **'Play playlist'**
+ String get playlistPlayAction;
+
+ /// No description provided for @playlistAllFinished.
+ ///
+ /// In en, this message translates to:
+ /// **'All finished'**
+ String get playlistAllFinished;
+
/// No description provided for @queueModeBooks.
///
/// In en, this message translates to:
diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart
index 81255dc9..de49a3f3 100644
--- a/lib/l10n/app_localizations_de.dart
+++ b/lib/l10n/app_localizations_de.dart
@@ -907,6 +907,40 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get queueModeAuto => 'Auto';
+ @override
+ String get queueModePlaylist => 'Playlist';
+
+ @override
+ String get queueModeInfoPlaylist => 'Playlist Queue';
+
+ @override
+ String get queueModeInfoPlaylistDesc =>
+ 'Plays items in order from a chosen playlist, skipping anything already finished. Stops at the end of the list.';
+
+ @override
+ String get queuePlaylistPickerTitle => 'Choose a playlist';
+
+ @override
+ String get queuePlaylistNone => 'No playlist selected';
+
+ @override
+ String queuePlaylistActiveLabel(String name) {
+ return 'Playlist: $name';
+ }
+
+ @override
+ String get queueModePlaylistHint =>
+ 'Start a playlist queue by opening a playlist on the home page.';
+
+ @override
+ String get exit => 'Exit';
+
+ @override
+ String get playlistPlayAction => 'Play playlist';
+
+ @override
+ String get playlistAllFinished => 'All finished';
+
@override
String get queueModeBooks => 'Bücher';
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index 47050a1d..cd8fd64f 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -899,6 +899,40 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get queueModeAuto => 'Auto';
+ @override
+ String get queueModePlaylist => 'Playlist';
+
+ @override
+ String get queueModeInfoPlaylist => 'Playlist Queue';
+
+ @override
+ String get queueModeInfoPlaylistDesc =>
+ 'Plays items in order from a chosen playlist, skipping anything already finished. Stops at the end of the list.';
+
+ @override
+ String get queuePlaylistPickerTitle => 'Choose a playlist';
+
+ @override
+ String get queuePlaylistNone => 'No playlist selected';
+
+ @override
+ String queuePlaylistActiveLabel(String name) {
+ return 'Playlist: $name';
+ }
+
+ @override
+ String get queueModePlaylistHint =>
+ 'Start a playlist queue by opening a playlist on the home page.';
+
+ @override
+ String get exit => 'Exit';
+
+ @override
+ String get playlistPlayAction => 'Play playlist';
+
+ @override
+ String get playlistAllFinished => 'All finished';
+
@override
String get queueModeBooks => 'Books';
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index cef0f672..f0cfc1c4 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -875,6 +875,40 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get queueModeAuto => '自动';
+ @override
+ String get queueModePlaylist => 'Playlist';
+
+ @override
+ String get queueModeInfoPlaylist => 'Playlist Queue';
+
+ @override
+ String get queueModeInfoPlaylistDesc =>
+ 'Plays items in order from a chosen playlist, skipping anything already finished. Stops at the end of the list.';
+
+ @override
+ String get queuePlaylistPickerTitle => 'Choose a playlist';
+
+ @override
+ String get queuePlaylistNone => 'No playlist selected';
+
+ @override
+ String queuePlaylistActiveLabel(String name) {
+ return 'Playlist: $name';
+ }
+
+ @override
+ String get queueModePlaylistHint =>
+ 'Start a playlist queue by opening a playlist on the home page.';
+
+ @override
+ String get exit => 'Exit';
+
+ @override
+ String get playlistPlayAction => 'Play playlist';
+
+ @override
+ String get playlistAllFinished => 'All finished';
+
@override
String get queueModeBooks => '书籍';
diff --git a/lib/providers/_lp_absorbing.dart b/lib/providers/_lp_absorbing.dart
index e6bbbbee..acd60913 100644
--- a/lib/providers/_lp_absorbing.dart
+++ b/lib/providers/_lp_absorbing.dart
@@ -433,6 +433,8 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
_manualQueueAdvance(itemId);
} else if (mode == 'auto_next') {
_autoAdvanceOffline(itemId);
+ } else if (mode == 'playlist') {
+ _advanceInPlaylist(itemId);
}
});
}
@@ -921,4 +923,162 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {
);
});
}
+
+ // ── Playlist queue mode ──────────────────────────────────────────────
+
+ String _playlistItemKey(Map<String, dynamic> item) {
+ final lid = item['libraryItemId'] as String? ?? '';
+ final eid = item['episodeId'] as String?;
+ return eid != null ? '$lid-$eid' : lid;
+ }
+
+ /// Index of the first playlist item that isn't marked finished. Returns -1
+ /// if every item is finished or the list is empty.
+ int firstUnfinishedPlaylistIndex(List<dynamic> items) {
+ final self = this as LibraryProvider;
+ for (var i = 0; i < items.length; i++) {
+ final m = items[i];
+ if (m is! Map<String, dynamic>) continue;
+ final key = _playlistItemKey(m);
+ if (key.isEmpty) continue;
+ if (!self.isItemFinishedByKey(key)) return i;
+ }
+ return -1;
+ }
+
+ Future<Map<String, dynamic>?> _getPlaylistById(String playlistId) async {
+ final cached = _playlists.cast<Map<String, dynamic>>().where(
+ (p) => p['id'] == playlistId,
+ ).firstOrNull;
+ if (cached != null) return cached;
+ if (_api == null) return null;
+ try {
+ return await _api!.getPlaylist(playlistId);
+ } catch (e) {
+ debugPrint('[Playlist] getPlaylist($playlistId) failed: $e');
+ return null;
+ }
+ }
+
+ Future<bool> _playPlaylistItem(Map<String, dynamic> playlistItem) async {
+ final api = _api;
+ if (api == null) return false;
+ final libraryItemId = playlistItem['libraryItemId'] as String? ?? '';
+ if (libraryItemId.isEmpty) return false;
+ final episodeId = playlistItem['episodeId'] as String?;
+ final libraryItem =
+ playlistItem['libraryItem'] as Map<String, dynamic>? ?? const {};
+ final media = libraryItem['media'] as Map<String, dynamic>? ?? const {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? const {};
+
+ if (episodeId != null) {
+ Map<String, dynamic>? episode =
+ playlistItem['episode'] as Map<String, dynamic>?;
+ episode ??= (media['episodes'] as List<dynamic>? ?? const [])
+ .cast<Map<String, dynamic>>()
+ .where((e) => e['id'] == episodeId)
+ .firstOrNull;
+ final epDuration = (episode?['duration'] as num?)?.toDouble() ??
+ ((episode?['audioFile'] as Map<String, dynamic>?)?['duration']
+ as num?)
+ ?.toDouble() ??
+ 0.0;
+ await AudioPlayerService().playItem(
+ api: api,
+ itemId: libraryItemId,
+ title: metadata['title'] as String? ?? '',
+ author: metadata['author'] as String? ??
+ metadata['authorName'] as String? ??
+ '',
+ coverUrl: getCoverUrl(libraryItemId),
+ totalDuration: epDuration,
+ chapters: const [],
+ episodeId: episodeId,
+ episodeTitle: episode?['title'] as String?,
+ );
+ } else {
+ final duration = (media['duration'] as num?)?.toDouble() ?? 0;
+ final chapters = media['chapters'] as List<dynamic>? ?? const [];
+ await AudioPlayerService().playItem(
+ api: api,
+ itemId: libraryItemId,
+ title: metadata['title'] as String? ?? '',
+ author: metadata['authorName'] as String? ?? '',
+ coverUrl: getCoverUrl(libraryItemId),
+ totalDuration: duration,
+ chapters: chapters,
+ );
+ }
+ return true;
+ }
+
+ /// Start playing the first unfinished item in [playlistId]. Returns true if
+ /// playback started. Used by the "Play playlist" entry point.
+ Future<bool> playPlaylistFromStart(String playlistId) async {
+ final pl = await _getPlaylistById(playlistId);
+ if (pl == null) return false;
+ final items = (pl['items'] as List<dynamic>?) ?? const [];
+ final idx = firstUnfinishedPlaylistIndex(items);
+ if (idx < 0) return false;
+ final item = items[idx] as Map<String, dynamic>? ?? const {};
+ return _playPlaylistItem(item);
+ }
+
+ /// Returns true if [libraryItemId] (+ optional [episodeId]) appears in the
+ /// active queue playlist's items. Used to decide whether playing a given
+ /// item should keep playlist mode active or kick the user out of it.
+ Future<bool> isInActiveQueuePlaylist(String libraryItemId,
+ {String? episodeId}) async {
+ final playlistId = await PlayerSettings.getQueuePlaylistId();
+ if (playlistId == null) return false;
+ final pl = await _getPlaylistById(playlistId);
+ if (pl == null) return false;
+ final items = (pl['items'] as List<dynamic>?) ?? const [];
+ final target =
+ episodeId != null ? '$libraryItemId-$episodeId' : libraryItemId;
+ for (final m in items) {
+ if (m is! Map<String, dynamic>) continue;
+ if (_playlistItemKey(m) == target) return true;
+ }
+ return false;
+ }
+
+ Future<void> _advanceInPlaylist(String finishedKey) async {
+ final playlistId = await PlayerSettings.getQueuePlaylistId();
+ if (playlistId == null) {
+ debugPrint('[AutoAdvance] Playlist mode but no queuePlaylistId; no-op');
+ return;
+ }
+ final pl = await _getPlaylistById(playlistId);
+ if (pl == null) {
+ debugPrint('[AutoAdvance] Playlist $playlistId missing; exiting playlist queue mode');
+ await PlayerSettings.clearQueueModePlaylist();
+ return;
+ }
+ final items = (pl['items'] as List<dynamic>?) ?? const [];
+ int idx = -1;
+ for (var i = 0; i < items.length; i++) {
+ final m = items[i];
+ if (m is! Map<String, dynamic>) continue;
+ if (_playlistItemKey(m) == finishedKey) { idx = i; break; }
+ }
+ if (idx < 0) {
+ debugPrint('[AutoAdvance] Finished item $finishedKey not in playlist $playlistId');
+ return;
+ }
+ final self = this as LibraryProvider;
+ for (var i = idx + 1; i < items.length; i++) {
+ final m = items[i];
+ if (m is! Map<String, dynamic>) continue;
+ final key = _playlistItemKey(m);
+ if (key.isEmpty) continue;
+ if (self.isItemFinishedByKey(key)) continue;
+ final ok = await _playPlaylistItem(m);
+ if (ok) {
+ debugPrint('[AutoAdvance] Playlist advanced to $key (index $i)');
+ return;
+ }
+ }
+ debugPrint('[AutoAdvance] Playlist $playlistId exhausted after $finishedKey');
+ }
}
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 8d883b02..2f543871 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -33,6 +33,10 @@ class LibraryProvider extends ChangeNotifier
// where updateAuth may not run until much later).
AudioPlayerService.setOnBookFinishedCallback(markFinishedLocally);
AudioPlayerService.setOnPlayStartedCallback((key) {
+ // If a non-playlist item is being played while playlist mode is active,
+ // exit playlist mode. Lets users escape the queue by just tapping any
+ // other book/episode (matches "Auto-switch mode to off" UX choice).
+ _checkPlaylistModeOnPlay(key);
Future.delayed(const Duration(seconds: 30), () {
final stillPlaying = AudioPlayerService().isPlaying;
if (!stillPlaying) return;
@@ -380,4 +384,27 @@ class LibraryProvider extends ChangeNotifier
}
return getProgressData(key)?['isFinished'] == true;
}
+
+ /// If queue mode is 'playlist' and [progressKey] is not in the active
+ /// playlist, clear playlist mode (modes back to 'off'). Fire-and-forget.
+ Future<void> _checkPlaylistModeOnPlay(String progressKey) async {
+ try {
+ final mode = await PlayerSettings.getBookQueueMode();
+ if (mode != 'playlist') return;
+ final libraryItemId =
+ progressKey.length > 36 ? progressKey.substring(0, 36) : progressKey;
+ final episodeId =
+ progressKey.length > 36 ? progressKey.substring(37) : null;
+ final inPlaylist = await isInActiveQueuePlaylist(
+ libraryItemId,
+ episodeId: episodeId,
+ );
+ if (!inPlaylist) {
+ debugPrint('[Playlist] Off-queue play; clearing playlist queue mode');
+ await PlayerSettings.clearQueueModePlaylist();
+ }
+ } catch (e) {
+ debugPrint('[Playlist] _checkPlaylistModeOnPlay error: $e');
+ }
+ }
}
diff --git a/lib/screens/absorbing_screen.dart b/lib/screens/absorbing_screen.dart
index a0137deb..c81129c9 100644
--- a/lib/screens/absorbing_screen.dart
+++ b/lib/screens/absorbing_screen.dart
@@ -10,6 +10,7 @@ import '../services/scoped_prefs.dart';
import '../widgets/absorb_page_header.dart';
import '../main.dart' show oledNotifier;
import '../widgets/absorbing_card.dart';
+import '../widgets/feature_hint.dart';
import '../widgets/offline_status_icon.dart';
import '../l10n/app_localizations.dart';
import '../services/wording.dart';
@@ -54,6 +55,7 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
final _cast = ChromecastService();
String _queueMode = 'off';
+ String? _queuePlaylistId;
@override
void initState() {
@@ -62,6 +64,7 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
_lastSeenIsPlaying = _player.isPlaying;
_player.addListener(_rebuild);
_cast.addListener(_rebuild);
+ PlayerSettings.settingsChanged.addListener(_loadQueueMode);
_restoreLastFinished();
_loadMergeLibraries();
_loadQueueMode();
@@ -79,30 +82,48 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
if (mounted && v != _mergeLibraries) setState(() => _mergeLibraries = v);
}
+ String _activePlaylistChipLabel(LibraryProvider lib, AppLocalizations l) {
+ final id = _queuePlaylistId;
+ if (id == null) return l.queueModePlaylist;
+ final match = lib.playlists.cast<Map<String, dynamic>>().where(
+ (p) => p['id'] == id,
+ ).firstOrNull;
+ final n = match?['name'] as String?;
+ if (n == null || n.isEmpty) return l.queueModePlaylist;
+ return n.length > 24 ? '${n.substring(0, 23)}…' : n;
+ }
+
Future<void> _loadQueueMode() async {
final lib = context.read<LibraryProvider>();
String mode;
- if (_mergeLibraries) {
+ final bm = await PlayerSettings.getBookQueueMode();
+ final pm = await PlayerSettings.getPodcastQueueMode();
+ if (bm == 'playlist' || pm == 'playlist') {
+ mode = 'playlist';
+ } else if (_mergeLibraries) {
// When merged, use the more restrictive of the two modes
// (matches Settings screen's _mergedQueueMode logic)
- final bm = await PlayerSettings.getBookQueueMode();
- final pm = await PlayerSettings.getPodcastQueueMode();
const order = ['off', 'manual', 'auto_next'];
final bi = order.indexOf(bm);
final pi = order.indexOf(pm);
mode = order[(bi < pi ? bi : pi).clamp(0, 2)];
} else {
- mode = lib.isPodcastLibrary
- ? await PlayerSettings.getPodcastQueueMode()
- : await PlayerSettings.getBookQueueMode();
+ mode = lib.isPodcastLibrary ? pm : bm;
+ }
+ final qpId = await PlayerSettings.getQueuePlaylistId();
+ if (mounted) {
+ setState(() {
+ _queueMode = mode;
+ _queuePlaylistId = qpId;
+ });
}
- if (mounted && mode != _queueMode) setState(() => _queueMode = mode);
}
@override
void dispose() {
_player.removeListener(_rebuild);
_cast.removeListener(_rebuild);
+ PlayerSettings.settingsChanged.removeListener(_loadQueueMode);
_pageController.dispose();
super.dispose();
}
@@ -642,9 +663,11 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
if (_queueMode != 'off') ...[
const SizedBox(width: 4),
Text(
- _queueMode == 'auto_next'
- ? (_mergeLibraries ? l.queueModeAuto : lib.isPodcastLibrary ? l.queueModeShowLabel : l.queueModeSeriesLabel)
- : l.queueModeManual,
+ _queueMode == 'playlist'
+ ? _activePlaylistChipLabel(lib, l)
+ : _queueMode == 'auto_next'
+ ? (_mergeLibraries ? l.queueModeAuto : lib.isPodcastLibrary ? l.queueModeShowLabel : l.queueModeSeriesLabel)
+ : l.queueModeManual,
style: TextStyle(fontSize: 10, fontWeight: FontWeight.w600, color: cs.primary),
),
],
@@ -834,11 +857,14 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
isMerged: _mergeLibraries,
isPodcast: lib.isPodcastLibrary,
onQueueModeChanged: (mode) async {
- setState(() => _queueMode = mode);
- if (_mergeLibraries) {
- // Merged view: keep both types in sync
+ final wasPlaylist = _queueMode == 'playlist';
+ if (_mergeLibraries || wasPlaylist) {
+ // Merged view OR leaving playlist mode: keep both types in sync
await PlayerSettings.setBookQueueMode(mode);
await PlayerSettings.setPodcastQueueMode(mode);
+ if (wasPlaylist) {
+ await PlayerSettings.setQueuePlaylistId(null);
+ }
} else {
final isPod = lib.isPodcastLibrary;
if (isPod) {
@@ -951,6 +977,30 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
for (final b in widget.books) widget.absorbingKeyFn(b): b,
};
_queueMode = widget.queueMode;
+ PlayerSettings.settingsChanged.addListener(_refreshMode);
+ }
+
+ @override
+ void dispose() {
+ PlayerSettings.settingsChanged.removeListener(_refreshMode);
+ super.dispose();
+ }
+
+ Future<void> _refreshMode() async {
+ final bm = await PlayerSettings.getBookQueueMode();
+ final pm = await PlayerSettings.getPodcastQueueMode();
+ String mode;
+ if (bm == 'playlist' || pm == 'playlist') {
+ mode = 'playlist';
+ } else if (widget.isMerged) {
+ const order = ['off', 'manual', 'auto_next'];
+ final bi = order.indexOf(bm);
+ final pi = order.indexOf(pm);
+ mode = order[(bi < pi ? bi : pi).clamp(0, 2)];
+ } else {
+ mode = widget.isPodcast ? pm : bm;
+ }
+ if (mounted && mode != _queueMode) setState(() => _queueMode = mode);
}
@override
@@ -990,20 +1040,64 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
),
]),
),
+ if (_queueMode == 'playlist')
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
+ child: Container(
+ padding: const EdgeInsets.fromLTRB(10, 4, 4, 4),
+ decoration: BoxDecoration(
+ color: cs.primaryContainer.withValues(alpha: 0.45),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: cs.primary.withValues(alpha: 0.25), width: 0.5),
+ ),
+ child: Row(children: [
+ Icon(Icons.playlist_play_rounded, size: 16, color: cs.primary),
+ const SizedBox(width: 8),
+ Expanded(child: FutureBuilder<String?>(
+ future: PlayerSettings.getQueuePlaylistId(),
+ builder: (context, snap) {
+ String name = l.queuePlaylistNone;
+ final id = snap.data;
+ if (id != null) {
+ final match = widget.lib.playlists.cast<Map<String, dynamic>>().where(
+ (p) => p['id'] == id,
+ ).firstOrNull;
+ final n = match?['name'] as String?;
+ if (n != null && n.isNotEmpty) name = n;
+ }
+ return Text(
+ name,
+ style: tt.bodySmall?.copyWith(color: cs.onPrimaryContainer, fontWeight: FontWeight.w600),
+ maxLines: 1, overflow: TextOverflow.ellipsis,
+ );
+ },
+ )),
+ IconButton(
+ icon: const Icon(Icons.close_rounded, size: 16),
+ color: cs.onPrimaryContainer.withValues(alpha: 0.7),
+ padding: EdgeInsets.zero,
+ constraints: const BoxConstraints(minWidth: 32, minHeight: 32),
+ visualDensity: VisualDensity.compact,
+ tooltip: l.exit,
+ onPressed: () => PlayerSettings.clearQueueModePlaylist(),
+ ),
+ ]),
+ ),
+ ),
// Queue mode toggle
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
child: SegmentedButton<String>(
+ emptySelectionAllowed: true,
segments: [
ButtonSegment(value: 'off', icon: const Icon(Icons.stop_rounded, size: 16), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeOff, maxLines: 1))),
ButtonSegment(value: 'manual', icon: const Icon(Icons.queue_music_rounded, size: 16), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeManual, maxLines: 1))),
ButtonSegment(value: 'auto_next', icon: const Icon(Icons.skip_next_rounded, size: 16),
label: FittedBox(fit: BoxFit.scaleDown, child: Text(widget.isMerged ? l.queueModeAuto : widget.isPodcast ? l.queueModeShowLabel : l.queueModeSeriesLabel, maxLines: 1))),
],
- selected: {_queueMode},
+ selected: _queueMode == 'playlist' ? const <String>{} : {_queueMode},
onSelectionChanged: (v) {
- setState(() => _queueMode = v.first);
- widget.onQueueModeChanged(v.first);
+ if (v.isNotEmpty) widget.onQueueModeChanged(v.first);
},
style: ButtonStyle(
visualDensity: VisualDensity.compact,
@@ -1011,6 +1105,12 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {
),
),
),
+ FeatureHint(
+ prefKey: 'hint_playlist_queue_mode',
+ message: l.queueModePlaylistHint,
+ icon: Icons.playlist_play_rounded,
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
+ ),
Expanded(
child: ReorderableListView.builder(
buildDefaultDragHandles: false,
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index bb1236f4..cc4142c7 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -33,6 +33,7 @@ import '../widgets/tips_sheet.dart';
import '../widgets/feature_hint.dart';
import '../widgets/welcome_sheet.dart';
import '../widgets/rmab_config_sheet.dart';
+import '../widgets/queue_playlist_picker_sheet.dart';
import '../l10n/app_localizations.dart';
class SettingsScreen extends StatefulWidget {
@@ -67,9 +68,15 @@ class _SettingsScreenState extends State<SettingsScreen> {
String _shakeSensitivity = 'medium';
String _bookQueueMode = 'off';
String _podcastQueueMode = 'off';
+ String? _queuePlaylistId;
// Returns the more restrictive of the two modes so the merged control
- // never shows 'Auto' if one type is still 'off' or 'manual'.
+ // never shows 'Auto' if one type is still 'off' or 'manual'. Playlist
+ // mode is set atomically on both, so if either is 'playlist' the merged
+ // value is 'playlist'.
String get _mergedQueueMode {
+ if (_bookQueueMode == 'playlist' || _podcastQueueMode == 'playlist') {
+ return 'playlist';
+ }
const order = ['off', 'manual', 'auto_next'];
final bi = order.indexOf(_bookQueueMode);
final pi = order.indexOf(_podcastQueueMode);
@@ -151,14 +158,136 @@ class _SettingsScreenState extends State<SettingsScreen> {
void _onExternalSettingsChange() async {
final bookMode = await PlayerSettings.getBookQueueMode();
final podMode = await PlayerSettings.getPodcastQueueMode();
+ final qpId = await PlayerSettings.getQueuePlaylistId();
if (mounted) {
setState(() {
_bookQueueMode = bookMode;
_podcastQueueMode = podMode;
+ _queuePlaylistId = qpId;
});
}
}
+ Future<String?> _pickQueuePlaylist() async {
+ if (!mounted) return null;
+ return await QueuePlaylistPickerSheet.show(context);
+ }
+
+ Future<void> _enterPlaylistMode() async {
+ String? id = _queuePlaylistId;
+ if (id == null) {
+ id = await _pickQueuePlaylist();
+ if (id == null || !mounted) return;
+ }
+ await PlayerSettings.setQueueModePlaylist(id);
+ if (!mounted) return;
+ setState(() {
+ _bookQueueMode = 'playlist';
+ _podcastQueueMode = 'playlist';
+ _queuePlaylistId = id;
+ });
+ }
+
+ Future<void> _setBookQueueMode(String mode) async {
+ if (mode == 'playlist') return _enterPlaylistMode();
+ final wasPlaylist =
+ _bookQueueMode == 'playlist' || _podcastQueueMode == 'playlist';
+ await PlayerSettings.setBookQueueMode(mode);
+ if (wasPlaylist) {
+ await PlayerSettings.setPodcastQueueMode(mode);
+ await PlayerSettings.setQueuePlaylistId(null);
+ }
+ if (!mounted) return;
+ setState(() {
+ _bookQueueMode = mode;
+ if (wasPlaylist) {
+ _podcastQueueMode = mode;
+ _queuePlaylistId = null;
+ }
+ });
+ PlayerSettings.notifySettingsChanged();
+ }
+
+ Future<void> _setPodcastQueueMode(String mode) async {
+ if (mode == 'playlist') return _enterPlaylistMode();
+ final wasPlaylist =
+ _bookQueueMode == 'playlist' || _podcastQueueMode == 'playlist';
+ await PlayerSettings.setPodcastQueueMode(mode);
+ if (wasPlaylist) {
+ await PlayerSettings.setBookQueueMode(mode);
+ await PlayerSettings.setQueuePlaylistId(null);
+ }
+ if (!mounted) return;
+ setState(() {
+ _podcastQueueMode = mode;
+ if (wasPlaylist) {
+ _bookQueueMode = mode;
+ _queuePlaylistId = null;
+ }
+ });
+ PlayerSettings.notifySettingsChanged();
+ }
+
+ Widget _buildActivePlaylistRow(
+ ColorScheme cs,
+ TextTheme tt,
+ LibraryProvider lib,
+ AppLocalizations l,
+ ) {
+ String name = l.queuePlaylistNone;
+ if (_queuePlaylistId != null) {
+ final match = lib.playlists.cast<Map<String, dynamic>>().where(
+ (p) => p['id'] == _queuePlaylistId,
+ ).firstOrNull;
+ final n = match?['name'] as String?;
+ if (n != null && n.isNotEmpty) name = n;
+ }
+ return Container(
+ padding: const EdgeInsets.fromLTRB(10, 4, 4, 4),
+ decoration: BoxDecoration(
+ color: cs.primaryContainer.withValues(alpha: 0.45),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: cs.primary.withValues(alpha: 0.25), width: 0.5),
+ ),
+ child: Row(children: [
+ Icon(Icons.playlist_play_rounded, size: 16, color: cs.primary),
+ const SizedBox(width: 8),
+ Expanded(child: Text(
+ name,
+ style: tt.bodySmall?.copyWith(color: cs.onPrimaryContainer, fontWeight: FontWeight.w600),
+ maxLines: 1, overflow: TextOverflow.ellipsis,
+ )),
+ IconButton(
+ icon: const Icon(Icons.close_rounded, size: 16),
+ color: cs.onPrimaryContainer.withValues(alpha: 0.7),
+ padding: EdgeInsets.zero,
+ constraints: const BoxConstraints(minWidth: 32, minHeight: 32),
+ visualDensity: VisualDensity.compact,
+ tooltip: l.exit,
+ onPressed: () => PlayerSettings.clearQueueModePlaylist(),
+ ),
+ ]),
+ );
+ }
+
+ Future<void> _setMergedQueueMode(String mode) async {
+ if (mode == 'playlist') return _enterPlaylistMode();
+ final wasPlaylist =
+ _bookQueueMode == 'playlist' || _podcastQueueMode == 'playlist';
+ await PlayerSettings.setBookQueueMode(mode);
+ await PlayerSettings.setPodcastQueueMode(mode);
+ if (wasPlaylist) {
+ await PlayerSettings.setQueuePlaylistId(null);
+ }
+ if (!mounted) return;
+ setState(() {
+ _bookQueueMode = mode;
+ _podcastQueueMode = mode;
+ if (wasPlaylist) _queuePlaylistId = null;
+ });
+ PlayerSettings.notifySettingsChanged();
+ }
+
Future<void> _loadSettings() async {
final results = await Future.wait([
AutoRewindSettings.load(), // 0
@@ -209,6 +338,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
PlayerSettings.getShakeSensitivity(), // 48
PlayerSettings.getLanguage(), // 49
PlayerSettings.getClassicWording(), // 50
+ PlayerSettings.getQueuePlaylistId(), // 51
]);
final s = results[0] as AutoRewindSettings;
final speed = results[1] as double;
@@ -258,6 +388,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
final shakeSens = results[45] as String;
final language = results[46] as String;
final classicWording = results[47] as bool;
+ final qpId = results[48] as String?;
final rmabBaseUrl = await ScopedPrefs.getString(kRmabBaseUrlKey);
final rmabApiToken = await ScopedPrefs.getString(kRmabApiTokenKey);
if (mounted) setState(() {
@@ -280,6 +411,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
_shakeAddMinutes = shakeMins;
_bookQueueMode = bookQueueMode;
_podcastQueueMode = podcastQueueMode;
+ _queuePlaylistId = qpId;
_queueAutoDownload = queueAutoDl;
_mergeAbsorbingLibraries = mergeLibs;
_maxConcurrentDownloads = maxConc;
@@ -858,6 +990,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
Text(l.queueModeInfoSeries, style: const TextStyle(fontWeight: FontWeight.w600)),
const SizedBox(height: 4),
Text(l.queueModeInfoSeriesDesc),
+ const SizedBox(height: 12),
+ Text(l.queueModeInfoPlaylist, style: const TextStyle(fontWeight: FontWeight.w600)),
+ const SizedBox(height: 4),
+ Text(l.queueModeInfoPlaylistDesc),
],
),
actions: [TextButton(onPressed: () => Navigator.pop(ctx), child: Text(l.gotIt))],
@@ -874,21 +1010,16 @@ class _SettingsScreenState extends State<SettingsScreen> {
const SizedBox(height: 8),
SizedBox(width: double.infinity, child: SegmentedButton<String>(
showSelectedIcon: false,
+ emptySelectionAllowed: true,
segments: [
ButtonSegment(value: 'off', icon: const Icon(Icons.stop_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeOff))),
ButtonSegment(value: 'manual', icon: const Icon(Icons.queue_music_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeManual))),
ButtonSegment(value: 'auto_next', icon: const Icon(Icons.skip_next_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeAuto))),
],
- selected: {_mergedQueueMode},
- onSelectionChanged: _loaded ? (s) {
- setState(() {
- _bookQueueMode = s.first;
- _podcastQueueMode = s.first;
- });
- PlayerSettings.setBookQueueMode(s.first);
- PlayerSettings.setPodcastQueueMode(s.first);
- PlayerSettings.notifySettingsChanged();
- } : null,
+ selected: _mergedQueueMode == 'playlist' ? const <String>{} : {_mergedQueueMode},
+ onSelectionChanged: _loaded
+ ? (s) { if (s.isNotEmpty) _setMergedQueueMode(s.first); }
+ : null,
style: const ButtonStyle(visualDensity: VisualDensity.compact),
)),
] else ...[
@@ -897,17 +1028,16 @@ class _SettingsScreenState extends State<SettingsScreen> {
const SizedBox(height: 4),
SizedBox(width: double.infinity, child: SegmentedButton<String>(
showSelectedIcon: false,
+ emptySelectionAllowed: true,
segments: [
ButtonSegment(value: 'off', icon: const Icon(Icons.stop_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeOff))),
ButtonSegment(value: 'manual', icon: const Icon(Icons.queue_music_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeManual))),
ButtonSegment(value: 'auto_next', icon: const Icon(Icons.skip_next_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeSeriesLabel))),
],
- selected: {_bookQueueMode},
- onSelectionChanged: _loaded ? (s) {
- setState(() => _bookQueueMode = s.first);
- PlayerSettings.setBookQueueMode(s.first);
- PlayerSettings.notifySettingsChanged();
- } : null,
+ selected: _bookQueueMode == 'playlist' ? const <String>{} : {_bookQueueMode},
+ onSelectionChanged: _loaded
+ ? (s) { if (s.isNotEmpty) _setBookQueueMode(s.first); }
+ : null,
style: const ButtonStyle(visualDensity: VisualDensity.compact),
)),
if (lib.libraries.any((lib) => lib['mediaType'] == 'podcast')) ...[
@@ -916,21 +1046,24 @@ class _SettingsScreenState extends State<SettingsScreen> {
const SizedBox(height: 4),
SizedBox(width: double.infinity, child: SegmentedButton<String>(
showSelectedIcon: false,
+ emptySelectionAllowed: true,
segments: [
ButtonSegment(value: 'off', icon: const Icon(Icons.stop_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeOff))),
ButtonSegment(value: 'manual', icon: const Icon(Icons.queue_music_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeManual))),
ButtonSegment(value: 'auto_next', icon: const Icon(Icons.skip_next_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeShowLabel))),
],
- selected: {_podcastQueueMode},
- onSelectionChanged: _loaded ? (s) {
- setState(() => _podcastQueueMode = s.first);
- PlayerSettings.setPodcastQueueMode(s.first);
- PlayerSettings.notifySettingsChanged();
- } : null,
+ selected: _podcastQueueMode == 'playlist' ? const <String>{} : {_podcastQueueMode},
+ onSelectionChanged: _loaded
+ ? (s) { if (s.isNotEmpty) _setPodcastQueueMode(s.first); }
+ : null,
style: const ButtonStyle(visualDensity: VisualDensity.compact),
)),
],
],
+ if (_mergedQueueMode == 'playlist') ...[
+ const SizedBox(height: 8),
+ _buildActivePlaylistRow(cs, tt, lib, l),
+ ],
if (_bookQueueMode == 'manual' || _podcastQueueMode == 'manual') ...[
const SizedBox(height: 4),
SwitchListTile(
diff --git a/lib/services/player_settings.dart b/lib/services/player_settings.dart
index aba69b9a..4960df83 100644
--- a/lib/services/player_settings.dart
+++ b/lib/services/player_settings.dart
@@ -148,7 +148,7 @@ class PlayerSettings {
static Future<void> setMaxConcurrentDownloads(int value) => _set('maxConcurrentDownloads', value);
// ── Queue mode (replaces autoPlayNextBook + autoPlayNextPodcast) ──
- // Values: 'off', 'manual', 'auto_next'
+ // Values: 'off', 'manual', 'auto_next', 'playlist'
static Future<String> getQueueMode() => _get('queueMode', 'off');
static Future<void> setQueueMode(String value) => _set('queueMode', value);
@@ -156,13 +156,45 @@ class PlayerSettings {
final value = await ScopedPrefs.getString('bookQueueMode');
return value ?? await getQueueMode();
}
- static Future<void> setBookQueueMode(String value) => _set('bookQueueMode', value);
+ static Future<void> setBookQueueMode(String value) => _set('bookQueueMode', value, notify: true);
static Future<String> getPodcastQueueMode() async {
final value = await ScopedPrefs.getString('podcastQueueMode');
return value ?? await getQueueMode();
}
- static Future<void> setPodcastQueueMode(String value) => _set('podcastQueueMode', value);
+ static Future<void> setPodcastQueueMode(String value) => _set('podcastQueueMode', value, notify: true);
+
+ /// Active playlist ID for playlist queue mode. Null when no playlist is selected.
+ static Future<String?> getQueuePlaylistId() async {
+ final s = await ScopedPrefs.getString('queuePlaylistId');
+ return (s == null || s.isEmpty) ? null : s;
+ }
+ static Future<void> setQueuePlaylistId(String? id) async {
+ if (id == null || id.isEmpty) {
+ await ScopedPrefs.remove('queuePlaylistId');
+ } else {
+ await ScopedPrefs.setString('queuePlaylistId', id);
+ }
+ _notify();
+ }
+
+ /// Enter playlist queue mode atomically: both book and podcast modes flip to
+ /// 'playlist' and the active playlist is set. Playlists can mix book and
+ /// podcast items, so the two modes always agree when in playlist mode.
+ static Future<void> setQueueModePlaylist(String playlistId) async {
+ await ScopedPrefs.setString('bookQueueMode', 'playlist');
+ await ScopedPrefs.setString('podcastQueueMode', 'playlist');
+ await ScopedPrefs.setString('queuePlaylistId', playlistId);
+ _notify();
+ }
+
+ /// Exit playlist queue mode: both modes back to 'off' and active playlist cleared.
+ static Future<void> clearQueueModePlaylist() async {
+ await ScopedPrefs.setString('bookQueueMode', 'off');
+ await ScopedPrefs.setString('podcastQueueMode', 'off');
+ await ScopedPrefs.remove('queuePlaylistId');
+ _notify();
+ }
/// One-time migration from the old boolean auto-play settings to queueMode.
static Future<void> migrateQueueMode() async {
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index 29743157..4768cb72 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -27,6 +27,7 @@ import '../services/download_service.dart';
import '../services/progress_sync_service.dart';
import '../services/metadata_override_service.dart';
import '../services/scoped_prefs.dart';
+import '../main.dart' show rootNavigatorKey;
import '../screens/app_shell.dart';
import 'author_books_sheet.dart';
import 'narrator_books_sheet.dart';
@@ -1242,22 +1243,21 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
final api = auth.apiService;
if (api == null) return;
- // Start playback
- final error = await player.playItem(api: api, itemId: widget.itemId, title: title, author: author, coverUrl: coverUrl, totalDuration: duration, chapters: chapters);
- if (error != null && context.mounted) showErrorSnackBar(context, error);
-
- // Refresh library so the absorbing screen picks up the new book
- if (context.mounted) {
- final lib = context.read<LibraryProvider>();
- lib.refreshLocalProgress();
- lib.refresh();
- }
+ final lib = context.mounted ? context.read<LibraryProvider>() : null;
- // Close all sheets and navigate
+ // Pop sheets and switch tab BEFORE starting playback. Otherwise the
+ // auto-expand triggered by playItem pushes the expanded player on top
+ // of the sheet, and the popUntil below kills the expanded player too.
rootNav.popUntil((route) => route.isFirst);
- Future.delayed(const Duration(milliseconds: 100), () {
- AppShell.goToAbsorbingGlobal();
- });
+ AppShell.goToAbsorbingGlobal();
+
+ final error = await player.playItem(api: api, itemId: widget.itemId, title: title, author: author, coverUrl: coverUrl, totalDuration: duration, chapters: chapters);
+ if (error != null) {
+ final ctx = rootNavigatorKey.currentContext;
+ if (ctx != null) showErrorSnackBar(ctx, error);
+ }
+ lib?.refreshLocalProgress();
+ lib?.refresh();
}
Future<void> _markFinished(BuildContext context, AuthProvider auth, double duration) async {
diff --git a/lib/widgets/collection_picker_sheet.dart b/lib/widgets/collection_picker_sheet.dart
index 5a5a49e1..15285931 100644
--- a/lib/widgets/collection_picker_sheet.dart
+++ b/lib/widgets/collection_picker_sheet.dart
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../l10n/app_localizations.dart';
import '../providers/library_provider.dart';
+import 'overlay_toast.dart';
class CollectionPickerSheet extends StatefulWidget {
final String libraryItemId;
@@ -46,13 +47,8 @@ class _CollectionPickerSheetState extends State<CollectionPickerSheet> {
if (collection != null) {
if (mounted) {
final l = AppLocalizations.of(context)!;
+ showOverlayToast(context, l.addedToName(name), icon: Icons.bookmark_added_rounded);
Navigator.pop(context);
- ScaffoldMessenger.of(context).showSnackBar(SnackBar(
- duration: const Duration(seconds: 3),
- content: Text(l.addedToName(name)),
- behavior: SnackBarBehavior.floating,
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
- ));
}
} else {
setState(() => _adding = false);
@@ -66,13 +62,12 @@ class _CollectionPickerSheetState extends State<CollectionPickerSheet> {
final name = collection['name'] as String? ?? l.collectionPickerCollectionFallback;
final ok = await lib.addToCollection(collectionId, widget.libraryItemId);
if (mounted) {
+ showOverlayToast(
+ context,
+ ok ? l.addedToName(name) : l.failedToAdd,
+ icon: ok ? Icons.bookmark_added_rounded : Icons.error_outline_rounded,
+ );
Navigator.pop(context);
- ScaffoldMessenger.of(context).showSnackBar(SnackBar(
- duration: const Duration(seconds: 3),
- content: Text(ok ? l.addedToName(name) : l.failedToAdd),
- behavior: SnackBarBehavior.floating,
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
- ));
}
}
diff --git a/lib/widgets/playlist_detail_sheet.dart b/lib/widgets/playlist_detail_sheet.dart
index 8f905f6e..8f20cf86 100644
--- a/lib/widgets/playlist_detail_sheet.dart
+++ b/lib/widgets/playlist_detail_sheet.dart
@@ -144,14 +144,13 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {
_selectMode = false;
_selectedKeys.clear();
});
- ScaffoldMessenger.of(context).showSnackBar(SnackBar(
- content: Text(finished
+ showOverlayToast(
+ context,
+ finished
? l.playlistDetailItemsMarkedFinished(count)
- : l.playlistDetailItemsMarkedUnfinished(count)),
- behavior: SnackBarBehavior.floating,
- duration: const Duration(seconds: 2),
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
- ));
+ : l.playlistDetailItemsMarkedUnfinished(count),
+ icon: finished ? Icons.check_circle_rounded : Icons.undo_rounded,
+ );
}
}
@@ -182,12 +181,11 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {
_selectMode = false;
_selectedKeys.clear();
});
- ScaffoldMessenger.of(context).showSnackBar(SnackBar(
- content: Text(l.playlistDetailItemsRemoved(count)),
- behavior: SnackBarBehavior.floating,
- duration: const Duration(seconds: 2),
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
- ));
+ showOverlayToast(
+ context,
+ l.playlistDetailItemsRemoved(count),
+ icon: Icons.playlist_remove_rounded,
+ );
}
}
@@ -366,6 +364,8 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {
const SizedBox(height: 12),
Divider(height: 1, color: cs.outlineVariant.withValues(alpha: 0.3),
indent: 20, endIndent: 20),
+ if (!_reordering && !_selectMode)
+ _buildPlayButton(cs, lib, items, l),
// Content
Expanded(
child: _reordering
@@ -415,6 +415,40 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {
]);
}
+ Widget _buildPlayButton(
+ ColorScheme cs,
+ LibraryProvider lib,
+ List<dynamic> items,
+ AppLocalizations l,
+ ) {
+ final firstIdx = lib.firstUnfinishedPlaylistIndex(items);
+ final allFinished = items.isNotEmpty && firstIdx < 0;
+ final enabled = items.isNotEmpty && firstIdx >= 0;
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(20, 12, 20, 4),
+ child: SizedBox(
+ width: double.infinity,
+ child: FilledButton.icon(
+ onPressed: enabled
+ ? () async {
+ HapticFeedback.selectionClick();
+ // Pop the sheet first; otherwise auto-expand pushes the
+ // expanded player on top of us and our pop closes it.
+ final playlistId = widget.playlistId;
+ Navigator.pop(context);
+ await PlayerSettings.setQueueModePlaylist(playlistId);
+ await lib.playPlaylistFromStart(playlistId);
+ }
+ : null,
+ icon: Icon(allFinished
+ ? Icons.check_circle_outline_rounded
+ : Icons.play_arrow_rounded),
+ label: Text(allFinished ? l.playlistAllFinished : l.playlistPlayAction),
+ ),
+ ),
+ );
+ }
+
Widget _buildReorderList(ColorScheme cs, TextTheme tt, LibraryProvider lib, AppLocalizations l) {
final items = _reorderItems!;
return ReorderableListView.builder(
diff --git a/lib/widgets/playlist_picker_sheet.dart b/lib/widgets/playlist_picker_sheet.dart
index 52bb77e8..c59c2042 100644
--- a/lib/widgets/playlist_picker_sheet.dart
+++ b/lib/widgets/playlist_picker_sheet.dart
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../l10n/app_localizations.dart';
import '../providers/library_provider.dart';
+import 'overlay_toast.dart';
class PlaylistPickerSheet extends StatefulWidget {
final String libraryItemId;
@@ -55,13 +56,8 @@ class _PlaylistPickerSheetState extends State<PlaylistPickerSheet> {
);
if (mounted) {
final l = AppLocalizations.of(context)!;
+ showOverlayToast(context, l.addedToName(name), icon: Icons.playlist_add_check_rounded);
Navigator.pop(context);
- ScaffoldMessenger.of(context).showSnackBar(SnackBar(
- duration: const Duration(seconds: 3),
- content: Text(l.addedToName(name)),
- behavior: SnackBarBehavior.floating,
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
- ));
}
} else {
setState(() => _adding = false);
@@ -77,13 +73,12 @@ class _PlaylistPickerSheetState extends State<PlaylistPickerSheet> {
playlistId, widget.libraryItemId, episodeId: widget.episodeId,
);
if (mounted) {
+ showOverlayToast(
+ context,
+ ok ? l.addedToName(name) : l.failedToAdd,
+ icon: ok ? Icons.playlist_add_check_rounded : Icons.error_outline_rounded,
+ );
Navigator.pop(context);
- ScaffoldMessenger.of(context).showSnackBar(SnackBar(
- duration: const Duration(seconds: 3),
- content: Text(ok ? l.addedToName(name) : l.failedToAdd),
- behavior: SnackBarBehavior.floating,
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
- ));
}
}
diff --git a/lib/widgets/queue_playlist_picker_sheet.dart b/lib/widgets/queue_playlist_picker_sheet.dart
new file mode 100644
index 00000000..2966cd61
--- /dev/null
+++ b/lib/widgets/queue_playlist_picker_sheet.dart
@@ -0,0 +1,153 @@
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import '../l10n/app_localizations.dart';
+import '../providers/library_provider.dart';
+import '../services/audio_player_service.dart';
+
+/// Bottom sheet that lets the user pick which playlist drives the playlist
+/// queue mode. Writes the choice via [PlayerSettings.setQueuePlaylistId];
+/// callers are responsible for flipping `bookQueueMode`/`podcastQueueMode`
+/// to `'playlist'` if they want to *enter* playlist mode at the same time.
+class QueuePlaylistPickerSheet extends StatefulWidget {
+ const QueuePlaylistPickerSheet({super.key});
+
+ static Future<String?> show(BuildContext context) {
+ return showModalBottomSheet<String?>(
+ context: context,
+ backgroundColor: Theme.of(context).bottomSheetTheme.backgroundColor,
+ shape: const RoundedRectangleBorder(
+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ isScrollControlled: true,
+ builder: (_) => const QueuePlaylistPickerSheet(),
+ );
+ }
+
+ @override
+ State<QueuePlaylistPickerSheet> createState() => _QueuePlaylistPickerSheetState();
+}
+
+class _QueuePlaylistPickerSheetState extends State<QueuePlaylistPickerSheet> {
+ String? _activeId;
+ bool _loadedActive = false;
+
+ @override
+ void initState() {
+ super.initState();
+ _loadActive();
+ // Make sure the playlist list is current.
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) context.read<LibraryProvider>().loadPlaylists();
+ });
+ }
+
+ Future<void> _loadActive() async {
+ final id = await PlayerSettings.getQueuePlaylistId();
+ if (mounted) setState(() {
+ _activeId = id;
+ _loadedActive = true;
+ });
+ }
+
+ Future<void> _choose(String id) async {
+ await PlayerSettings.setQueuePlaylistId(id);
+ if (mounted) Navigator.pop(context, id);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final l = AppLocalizations.of(context)!;
+ final lib = context.watch<LibraryProvider>();
+ final playlists = lib.playlists;
+
+ return SafeArea(
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
+ Center(child: Container(
+ width: 40, height: 4,
+ margin: const EdgeInsets.only(bottom: 16),
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.24),
+ borderRadius: BorderRadius.circular(2),
+ ),
+ )),
+ Text(l.queuePlaylistPickerTitle, style: tt.titleMedium?.copyWith(
+ color: cs.onSurface, fontWeight: FontWeight.w600,
+ )),
+ const SizedBox(height: 12),
+ if (lib.isLoadingPlaylists && playlists.isEmpty)
+ const Padding(
+ padding: EdgeInsets.symmetric(vertical: 32),
+ child: CircularProgressIndicator(strokeWidth: 2),
+ )
+ else if (playlists.isEmpty)
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 32),
+ child: Text(l.queuePlaylistNone, style: tt.bodyMedium?.copyWith(
+ color: cs.onSurfaceVariant,
+ )),
+ )
+ else
+ ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: MediaQuery.of(context).size.height * 0.6,
+ ),
+ child: ListView.builder(
+ shrinkWrap: true,
+ itemCount: playlists.length,
+ itemBuilder: (_, i) {
+ final p = playlists[i] as Map<String, dynamic>;
+ final id = p['id'] as String? ?? '';
+ final name = p['name'] as String? ?? l.playlistPickerPlaylistFallback;
+ final items = (p['items'] as List<dynamic>?) ?? const [];
+ final active = _loadedActive && id == _activeId;
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: GestureDetector(
+ onTap: id.isEmpty ? null : () => _choose(id),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: active ? 0.10 : 0.06),
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(
+ color: active
+ ? cs.primary.withValues(alpha: 0.5)
+ : cs.onSurface.withValues(alpha: 0.1),
+ ),
+ ),
+ child: Row(children: [
+ Icon(
+ active ? Icons.check_circle_rounded : Icons.playlist_play_rounded,
+ size: 18,
+ color: active ? cs.primary : cs.onSurfaceVariant,
+ ),
+ const SizedBox(width: 10),
+ Expanded(child: Text(
+ name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.bodyMedium?.copyWith(
+ color: cs.onSurface,
+ fontWeight: active ? FontWeight.w600 : FontWeight.w500,
+ ),
+ )),
+ Text(
+ l.playlistDetailItemCount(items.length),
+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ ]),
+ ),
+ ),
+ );
+ },
+ ),
+ ),
+ ]),
+ ),
+ );
+ }
+}