Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Let you pick several books on home or in the library and quick match, mark, or delete them at once

Barnabas7957310ac396
diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart
index 1e947bdd..594b69ce 100644
--- a/lib/screens/home_screen.dart
+++ b/lib/screens/home_screen.dart
@@ -10,6 +10,7 @@ import '../providers/auth_provider.dart';
import '../providers/library_provider.dart';
import '../services/audio_player_service.dart';
import '../services/download_service.dart';
+import '../widgets/desktop_batch_actions.dart';
import '../widgets/home_section.dart';
import '../widgets/absorb_page_header.dart';
import '../widgets/library_picker_sheet.dart';
@@ -42,6 +43,122 @@ class HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateMi
bool _hideEbookOnly = false;
bool _rectangleCovers = false;
+ // ── Batch selection ──
+ bool _selectionMode = false;
+ bool _batchActionBusy = false;
+ final Set<String> _selectedItemIds = {};
+
+ void _resetSelectionState() {
+ _selectionMode = false;
+ _batchActionBusy = false;
+ _selectedItemIds.clear();
+ }
+
+ void _clearSelection() {
+ if (!_selectionMode && _selectedItemIds.isEmpty) return;
+ setState(_resetSelectionState);
+ }
+
+ void _toggleSelection(Map<String, dynamic> item) {
+ final itemId = item['id'] as String?;
+ if (itemId == null) return;
+ setState(() {
+ _selectionMode = true;
+ if (!_selectedItemIds.add(itemId)) _selectedItemIds.remove(itemId);
+ });
+ }
+
+ /// A shelf entity is only selectable when it resolves to a plain library
+ /// item: authors, series and episodes have no id the batch endpoints accept,
+ /// and a playlist row wraps the real item one level down.
+ Map<String, dynamic>? _selectableHomeItem(
+ dynamic entity, {
+ required String sectionType,
+ }) {
+ if (sectionType == 'author' ||
+ sectionType == 'authors' ||
+ sectionType == 'series' ||
+ sectionType == 'episode') {
+ return null;
+ }
+ if (entity is! Map<String, dynamic>) return null;
+ var item = entity;
+ if (sectionType == 'playlist') {
+ if (entity['episodeId'] != null) return null;
+ final nested = entity['libraryItem'];
+ if (nested is! Map<String, dynamic>) return null;
+ item = nested;
+ }
+ if (item['recentEpisode'] != null || item['id'] is! String) return null;
+ return item;
+ }
+
+ /// Every selectable item on screen, deduped: the same book can sit in
+ /// Continue Listening and in a shelf below it.
+ List<Map<String, dynamic>> _selectableHomeItems() {
+ final byId = <String, Map<String, dynamic>>{};
+ for (final item in _cachedClItems ?? const <dynamic>[]) {
+ final selectable = _selectableHomeItem(item, sectionType: 'book');
+ final id = selectable?['id'] as String?;
+ if (id != null) byId[id] = selectable!;
+ }
+ for (final section in _cachedSections ?? const <Map<String, dynamic>>[]) {
+ final id = section['id'] as String? ?? '';
+ if (id == 'continue-listening') continue;
+ final type = id.startsWith('playlist:')
+ ? 'playlist'
+ : id.startsWith('collection:')
+ ? 'collection'
+ : (section['type'] as String? ?? 'book');
+ final entities = _filterEbookOnly(
+ section['entities'] as List<dynamic>? ?? const [],
+ sectionType: section['type'] as String?,
+ );
+ for (final entity in entities) {
+ final selectable = _selectableHomeItem(entity, sectionType: type);
+ final itemId = selectable?['id'] as String?;
+ if (itemId != null) byId[itemId] = selectable!;
+ }
+ }
+ return byId.values.toList();
+ }
+
+ void _toggleSelectAll() {
+ final ids = _selectableHomeItems()
+ .map((item) => item['id'] as String)
+ .toSet();
+ setState(() {
+ _selectionMode = true;
+ if (ids.isNotEmpty && _selectedItemIds.containsAll(ids)) {
+ _selectedItemIds.removeAll(ids);
+ } else {
+ _selectedItemIds.addAll(ids);
+ }
+ });
+ }
+
+ Future<void> _runBatchAction(Future<bool?> Function() action) async {
+ if (_batchActionBusy) return;
+ final visibleIds = _selectableHomeItems()
+ .map((item) => item['id'] as String)
+ .toSet();
+ setState(() {
+ _selectedItemIds.retainAll(visibleIds);
+ if (_selectedItemIds.isEmpty) {
+ _resetSelectionState();
+ } else {
+ _batchActionBusy = true;
+ }
+ });
+ if (_selectedItemIds.isEmpty) return;
+ final success = await action();
+ if (!mounted) return;
+ setState(() {
+ _batchActionBusy = false;
+ if (success == true) _resetSelectionState();
+ });
+ }
+
// ── Scroll-to-hide bars ──
/// Continuous 0..1 reveal value the AppShell mirrors onto the bottom nav.
late final ScrollRevealDriver _revealDriver = ScrollRevealDriver(vsync: this);
@@ -243,8 +360,63 @@ class HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateMi
_refreshFilteredCache(lib);
}
+ final auth = context.watch<AuthProvider>();
+ final selectionAvailable = !lib.isOffline;
+ if (!selectionAvailable && _selectionMode) _resetSelectionState();
+ // Only walked while selecting: this crosses every shelf, and home rebuilds
+ // far too often to pay for that when there is nothing selected.
+ final selectableItems = selectionAvailable && _selectionMode
+ ? _selectableHomeItems()
+ : const <Map<String, dynamic>>[];
+ // Shelves reshuffle as progress changes, so drop anything that is no
+ // longer on screen rather than acting on a book the user can't see.
+ if (_selectionMode) {
+ _selectedItemIds.retainAll(
+ selectableItems.map((item) => item['id'] as String).toSet(),
+ );
+ }
+
return Scaffold(
backgroundColor: scaffoldBg,
+ floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
+ floatingActionButton: !(_selectionMode && selectionAvailable)
+ ? null
+ : DesktopBatchActionBar(
+ selectedCount: _selectedItemIds.length,
+ selectableCount: selectableItems.length,
+ busy: _batchActionBusy,
+ canQuickMatch: auth.isAdmin && !lib.isPodcastLibrary,
+ canMarkProgress: !lib.isPodcastLibrary,
+ canDelete: auth.canDelete,
+ onSelectAll: _toggleSelectAll,
+ onClear: _clearSelection,
+ onQuickMatch: () => _runBatchAction(
+ () => DesktopBatchActions.quickMatch(
+ context,
+ _selectedItemIds.toList(),
+ ),
+ ),
+ onMarkFinished: () => _runBatchAction(
+ () => DesktopBatchActions.setFinished(
+ context,
+ _selectedItemIds.toList(),
+ isFinished: true,
+ ),
+ ),
+ onMarkUnfinished: () => _runBatchAction(
+ () => DesktopBatchActions.setFinished(
+ context,
+ _selectedItemIds.toList(),
+ isFinished: false,
+ ),
+ ),
+ onDelete: () => _runBatchAction(
+ () => DesktopBatchActions.delete(
+ context,
+ _selectedItemIds.toList(),
+ ),
+ ),
+ ),
body: Container(
decoration: flatNotifier.value ? null : BoxDecoration(
gradient: LinearGradient(
@@ -292,6 +464,24 @@ class HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateMi
},
),
actions: [
+ if (selectionAvailable)
+ Tooltip(
+ message: _selectionMode
+ ? l.downloadsCancelSelection
+ : l.downloadsSelect,
+ child: IconButton(
+ onPressed: _batchActionBusy
+ ? null
+ : _selectionMode
+ ? _clearSelection
+ : () => setState(() => _selectionMode = true),
+ icon: Icon(
+ _selectionMode
+ ? Icons.close_rounded
+ : Icons.library_add_check_rounded,
+ ),
+ ),
+ ),
if (allLibraries.length > 1)
Material(
color: cs.onSurface.withValues(alpha: 0.06),
@@ -506,6 +696,14 @@ class HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateMi
return RepaintBoundary(child: _ContinueListeningCard(
item: item, lib: lib, player: _player,
rectangleCovers: _rectangleCovers,
+ selectionMode: selectionAvailable && _selectionMode,
+ selected: _selectedItemIds
+ .contains(item['id'] as String?),
+ onSelectionToggle: selectionAvailable &&
+ item['recentEpisode'] == null &&
+ item['id'] is String
+ ? () => _toggleSelection(item)
+ : null,
));
},
),
@@ -568,8 +766,13 @@ class HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateMi
entities: entities,
sectionType: type,
sectionId: id,
- onTitleTap: titleTap,
+ onTitleTap: _selectionMode ? null : titleTap,
coverAspectRatio: _rectangleCovers ? 2 / 3 : 1.0,
+ selectionMode: selectionAvailable && _selectionMode,
+ selectedItemIds: _selectedItemIds,
+ onSelectionToggle: selectionAvailable
+ ? _toggleSelection
+ : null,
),
),
];
@@ -600,12 +803,18 @@ class _ContinueListeningCard extends StatefulWidget {
final LibraryProvider lib;
final AudioPlayerService player;
final bool rectangleCovers;
+ final bool selectionMode;
+ final bool selected;
+ final VoidCallback? onSelectionToggle;
const _ContinueListeningCard({
required this.item,
required this.lib,
required this.player,
required this.rectangleCovers,
+ this.selectionMode = false,
+ this.selected = false,
+ this.onSelectionToggle,
});
@override
@@ -809,7 +1018,7 @@ class _ContinueListeningCardState extends State<_ContinueListeningCard> {
}
}
- return Material(
+ final card = Material(
color: Colors.transparent,
borderRadius: BorderRadius.circular(14),
clipBehavior: Clip.antiAlias,
@@ -823,8 +1032,8 @@ class _ContinueListeningCardState extends State<_ContinueListeningCard> {
),
),
child: InkWell(
- onTap: resume,
- onLongPress: openQuickActions,
+ onTap: widget.selectionMode ? widget.onSelectionToggle : resume,
+ onLongPress: widget.selectionMode ? null : openQuickActions,
borderRadius: BorderRadius.circular(14),
child: SizedBox(
width: 150,
@@ -947,6 +1156,49 @@ class _ContinueListeningCardState extends State<_ContinueListeningCard> {
),
),
);
+
+ if (!widget.selectionMode) return card;
+ return Stack(
+ children: [
+ card,
+ Positioned(
+ top: 6,
+ left: 6,
+ child: IgnorePointer(
+ child: Container(
+ width: 26,
+ height: 26,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: widget.selected
+ ? cs.primary
+ : Colors.black.withValues(alpha: 0.55),
+ border: Border.all(
+ color: widget.selected ? cs.primary : Colors.white70,
+ ),
+ ),
+ child: Icon(
+ widget.selected ? Icons.check_rounded : Icons.circle_outlined,
+ size: 17,
+ color: widget.selected ? cs.onPrimary : Colors.white70,
+ ),
+ ),
+ ),
+ ),
+ if (widget.selected)
+ Positioned.fill(
+ child: IgnorePointer(
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(color: cs.primary, width: 3),
+ color: cs.primary.withValues(alpha: 0.18),
+ ),
+ ),
+ ),
+ ),
+ ],
+ );
}
Future<void> _startBook(BuildContext context, String itemId) async {
diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dart
index 28bb78e0..37ec8469 100644
--- a/lib/screens/library_screen.dart
+++ b/lib/screens/library_screen.dart
@@ -19,6 +19,8 @@ import '../widgets/library_search_results.dart';
import '../widgets/podcast_episode_feed.dart';
import '../main.dart' show flatNotifier, gradientIntensityNotifier;
import '../widgets/library_sort_filter_sheet.dart';
+import '../widgets/desktop_batch_actions.dart';
+import '../widgets/overlay_toast.dart';
import '../widgets/library_books_tab.dart';
import '../widgets/library_series_tab.dart';
import '../widgets/library_authors_tab.dart';
@@ -332,6 +334,16 @@ class LibraryScreenState extends State<LibraryScreen>
bool _hasSearched = false;
bool get _isInSearchMode => _searchController.text.trim().isNotEmpty;
+ // ── Batch selection (books tab and authors tab) ──
+ bool _selectionMode = false;
+ bool _batchActionBusy = false;
+ bool _matchingAuthors = false;
+ String? _matchingAuthorId;
+ int _authorMatchPosition = 0;
+ int _authorMatchTotal = 0;
+ final Set<String> _selectedItemIds = {};
+ int? _lastSelectedVisibleIndex;
+
// ── Tab state ──
TabController? _tabController;
int _currentTab = 0;
@@ -2375,6 +2387,7 @@ class LibraryScreenState extends State<LibraryScreen>
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
setState(() {
+ _resetSelectionState();
_items.clear();
_page = 0;
_hasMore = true;
@@ -2384,9 +2397,94 @@ class LibraryScreenState extends State<LibraryScreen>
});
}
final hasTabs = _tabController != null && !_isInSearchMode;
+ final auth = context.watch<AuthProvider>();
+ final selectingAuthors = hasTabs && _currentTab == 2;
+ final authorSelectionAvailable =
+ selectingAuthors &&
+ !libWatch.isOffline &&
+ auth.canUpdateMetadata &&
+ !_matchingAuthors;
+ final bookSelectionAvailable =
+ !libWatch.isOffline &&
+ !_isInSearchMode &&
+ (hasTabs ? _currentTab == 0 : _podcastView == 0);
+ final selectionAvailable =
+ authorSelectionAvailable || bookSelectionAvailable;
+ if (!selectionAvailable && _selectionMode) _resetSelectionState();
+ final selectableItems = selectionAvailable && _selectionMode
+ ? _selectableVisibleItems()
+ : const <Map<String, dynamic>>[];
+ // Drop ids that scrolled out of the current filter so the count and the
+ // select-all state always describe what is on screen.
+ if (_selectionMode) {
+ _selectedItemIds.retainAll(
+ selectableItems.map((item) => item['id'] as String).toSet(),
+ );
+ }
+ final selectableCount = selectableItems.length;
return Scaffold(
backgroundColor: scaffoldBg,
+ floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
+ floatingActionButton: !_selectionMode
+ ? null
+ : authorSelectionAvailable
+ ? DesktopBatchActionBar(
+ selectedCount: _selectedItemIds.length,
+ selectableCount: selectableCount,
+ busy: _batchActionBusy,
+ busyLabel: _authorMatchTotal > 0
+ ? '$_authorMatchPosition/$_authorMatchTotal'
+ : null,
+ canQuickMatch: true,
+ canMarkProgress: false,
+ canDelete: false,
+ onSelectAll: _toggleSelectAll,
+ onClear: _clearSelection,
+ onQuickMatch: () =>
+ _runBatchAction(() => _quickMatchAuthors(_selectedAuthors())),
+ onMarkFinished: () {},
+ onMarkUnfinished: () {},
+ onDelete: () {},
+ )
+ : bookSelectionAvailable
+ ? DesktopBatchActionBar(
+ selectedCount: _selectedItemIds.length,
+ selectableCount: selectableCount,
+ busy: _batchActionBusy,
+ canQuickMatch: auth.isAdmin && !libWatch.isPodcastLibrary,
+ canMarkProgress: !libWatch.isPodcastLibrary,
+ canDelete: auth.canDelete,
+ onSelectAll: _toggleSelectAll,
+ onClear: _clearSelection,
+ onQuickMatch: () => _runBatchAction(
+ () => DesktopBatchActions.quickMatch(
+ context,
+ _selectedItemIds.toList(),
+ ),
+ ),
+ onMarkFinished: () => _runBatchAction(
+ () => DesktopBatchActions.setFinished(
+ context,
+ _selectedItemIds.toList(),
+ isFinished: true,
+ ),
+ ),
+ onMarkUnfinished: () => _runBatchAction(
+ () => DesktopBatchActions.setFinished(
+ context,
+ _selectedItemIds.toList(),
+ isFinished: false,
+ ),
+ ),
+ onDelete: () => _runBatchAction(
+ () => DesktopBatchActions.delete(
+ context,
+ _selectedItemIds.toList(),
+ ),
+ ),
+ )
+ : null,
body: Stack(
children: [
if (!flatNotifier.value)
@@ -2546,6 +2644,20 @@ class LibraryScreenState extends State<LibraryScreen>
final lib = context.watch<LibraryProvider>();
final allLibraries = lib.libraries;
final hasMultipleLibraries = allLibraries.length > 1;
+ // Batch selection is offered on the books grid and on the authors tab.
+ // Authors need metadata permission (quick match writes to the server);
+ // books only need to be online and out of search, where the visible list
+ // is stable enough for select-all to mean something.
+ final canSelectAuthors =
+ _tabController != null &&
+ _currentTab == 2 &&
+ context.read<AuthProvider>().canUpdateMetadata &&
+ !_matchingAuthors;
+ final canSelectItems =
+ !lib.isOffline &&
+ !_isInSearchMode &&
+ (canSelectAuthors ||
+ (_tabController == null ? _podcastView == 0 : _currentTab == 0));
final libraryName =
lib.selectedLibrary?['name'] as String? ?? l.libraryFallback;
final topInset = MediaQuery.of(context).padding.top;
@@ -2627,8 +2739,8 @@ class LibraryScreenState extends State<LibraryScreen>
}
},
),
- actions: hasMultipleLibraries
- ? [
+ actions: [
+ if (hasMultipleLibraries)
GestureDetector(
onTap: () => showLibraryPickerSheet(context, lib),
child: Container(
@@ -2682,8 +2794,25 @@ class LibraryScreenState extends State<LibraryScreen>
),
),
),
- ]
- : null,
+ if (canSelectItems)
+ Tooltip(
+ message: _selectionMode
+ ? l.downloadsCancelSelection
+ : l.downloadsSelect,
+ child: IconButton(
+ onPressed: _batchActionBusy
+ ? null
+ : _selectionMode
+ ? _clearSelection
+ : () => setState(() => _selectionMode = true),
+ icon: Icon(
+ _selectionMode
+ ? Icons.close_rounded
+ : Icons.library_add_check_rounded,
+ ),
+ ),
+ ),
+ ],
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
@@ -3067,6 +3196,29 @@ class LibraryScreenState extends State<LibraryScreen>
),
),
],
+ if (_currentTab == 2 &&
+ !_selectionMode &&
+ _authors.isNotEmpty &&
+ context.read<AuthProvider>().canUpdateMetadata &&
+ !context.read<LibraryProvider>().isOffline)
+ TextButton.icon(
+ onPressed: _matchingAuthors ? null : _quickMatchAllAuthors,
+ icon: _matchingAuthors
+ ? const SizedBox(
+ width: 16,
+ height: 16,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ )
+ : const Icon(Icons.auto_fix_high_rounded, size: 18),
+ label: Text(
+ _matchingAuthors && _authorMatchTotal > 0
+ ? '${l.adminMatching} '
+ '$_authorMatchPosition/$_authorMatchTotal'
+ : _matchingAuthors
+ ? l.adminMatching
+ : l.adminMatchAll,
+ ),
+ ),
const Spacer(),
Text(
countText,
@@ -3179,9 +3331,227 @@ class LibraryScreenState extends State<LibraryScreen>
headerSliver: headerSliver,
scrollController: _scrollController,
onLoadMore: _loadPage,
+ selectionMode: _selectionMode && (_tabController == null || _currentTab == 0),
+ selectedItemIds: _selectedItemIds,
+ onSelectionToggle: _toggleSelection,
);
}
+ // ═══════════════════════════════════════════════════════════════
+ // BATCH SELECTION
+ // ═══════════════════════════════════════════════════════════════
+ void _resetSelectionState() {
+ _selectionMode = false;
+ _batchActionBusy = false;
+ _selectedItemIds.clear();
+ _lastSelectedVisibleIndex = null;
+ }
+
+ void _clearSelection() {
+ if (!_selectionMode && _selectedItemIds.isEmpty) return;
+ setState(_resetSelectionState);
+ }
+
+ List<Map<String, dynamic>> _selectableVisibleItems() {
+ if (_tabController != null && _currentTab == 2) {
+ return _authors
+ .where((author) => author['id'] is String)
+ .toList(growable: false);
+ }
+ final lib = context.read<LibraryProvider>();
+ return _visibleLibraryItems(lib)
+ .where(
+ (item) =>
+ !item.containsKey('collapsedSeries') && item['id'] is String,
+ )
+ .toList();
+ }
+
+ void _toggleSelection(Map<String, dynamic> item, int visibleIndex) {
+ final itemId = item['id'] as String?;
+ if (itemId == null) return;
+ // Shift-click extends the run on a hardware keyboard; plain taps toggle.
+ final shiftPressed = HardwareKeyboard.instance.isShiftPressed;
+ setState(() {
+ _selectionMode = true;
+ if (shiftPressed && _lastSelectedVisibleIndex != null) {
+ final items = _selectableVisibleItems();
+ final start = min(_lastSelectedVisibleIndex!, visibleIndex);
+ final end = max(_lastSelectedVisibleIndex!, visibleIndex);
+ for (var index = start; index <= end && index < items.length; index++) {
+ final rangeItem = items[index];
+ if (rangeItem.containsKey('collapsedSeries')) continue;
+ final rangeId = rangeItem['id'] as String?;
+ if (rangeId != null) _selectedItemIds.add(rangeId);
+ }
+ } else if (!_selectedItemIds.add(itemId)) {
+ _selectedItemIds.remove(itemId);
+ }
+ _lastSelectedVisibleIndex = visibleIndex;
+ });
+ }
+
+ void _toggleSelectAll() {
+ final ids = _selectableVisibleItems()
+ .map((item) => item['id'] as String)
+ .toSet();
+ setState(() {
+ _selectionMode = true;
+ if (ids.isNotEmpty && _selectedItemIds.containsAll(ids)) {
+ _selectedItemIds.removeAll(ids);
+ } else {
+ _selectedItemIds.addAll(ids);
+ }
+ _lastSelectedVisibleIndex = null;
+ });
+ }
+
+ Future<void> _runBatchAction(Future<bool?> Function() action) async {
+ if (_batchActionBusy) return;
+ // Anything that scrolled out of the filter since it was ticked is dropped,
+ // so an action can never touch an item the user can no longer see.
+ final visibleIds = _selectableVisibleItems()
+ .map((item) => item['id'] as String)
+ .toSet();
+ setState(() {
+ _selectedItemIds.retainAll(visibleIds);
+ if (_selectedItemIds.isEmpty) {
+ _resetSelectionState();
+ } else {
+ _batchActionBusy = true;
+ }
+ });
+ if (_selectedItemIds.isEmpty) return;
+ final success = await action();
+ if (!mounted) return;
+ setState(() {
+ _batchActionBusy = false;
+ if (success == true) _resetSelectionState();
+ });
+ }
+
+ List<Map<String, dynamic>> _selectedAuthors() {
+ return _authors
+ .where((author) => _selectedItemIds.contains(author['id']))
+ .toList(growable: false);
+ }
+
+ String _authorQuickMatchRegion(LibraryProvider lib) {
+ final provider =
+ lib.selectedLibrary?['provider']?.toString().toLowerCase() ?? '';
+ if (!provider.startsWith('audible.')) return 'us';
+ final region = provider.split('.').last.trim();
+ return region.isEmpty ? 'us' : region;
+ }
+
+ /// Quick-match authors one at a time. There is no batch author endpoint, so
+ /// this walks the list and reports a tally at the end; the tile shows a
+ /// spinner on whichever author is in flight.
+ Future<bool> _quickMatchAuthors(
+ List<Map<String, dynamic>> authors, {
+ bool allAuthors = false,
+ }) async {
+ if (authors.isEmpty) return false;
+ final auth = context.read<AuthProvider>();
+ final lib = context.read<LibraryProvider>();
+ final api = auth.apiService;
+ final libraryId = lib.selectedLibraryId;
+ if (api == null || libraryId == null || !auth.canUpdateMetadata) {
+ return false;
+ }
+
+ final l = AppLocalizations.of(context)!;
+ setState(() {
+ _authorMatchPosition = 0;
+ _authorMatchTotal = authors.length;
+ _matchingAuthorId = null;
+ });
+ showOverlayToast(
+ context,
+ l.adminMatchingStarted(
+ allAuthors
+ ? l.libraryAuthorsCount(authors.length)
+ : l.selectedCount(authors.length),
+ ),
+ icon: Icons.auto_fix_high_rounded,
+ );
+
+ final region = _authorQuickMatchRegion(lib);
+ var found = 0;
+ var updated = 0;
+ var notFound = 0;
+ var failed = 0;
+ for (var index = 0; index < authors.length; index++) {
+ final author = authors[index];
+ final id = author['id']?.toString() ?? '';
+ final name = author['name']?.toString().trim() ?? '';
+ final asin = author['asin']?.toString().trim() ?? '';
+ if (mounted) {
+ setState(() {
+ _matchingAuthorId = id.isEmpty ? null : id;
+ _authorMatchPosition = index + 1;
+ });
+ }
+ if (id.isEmpty || (asin.isEmpty && name.isEmpty)) {
+ failed++;
+ continue;
+ }
+ final result = await api.quickMatchAuthor(
+ id,
+ asin: asin.isEmpty ? null : asin,
+ q: asin.isEmpty ? name : null,
+ region: region,
+ );
+ if (result.found) {
+ found++;
+ if (result.updated) updated++;
+ } else if (result.statusCode == 404) {
+ notFound++;
+ } else {
+ failed++;
+ }
+ }
+
+ if (!mounted) return failed < authors.length;
+ setState(() => _matchingAuthorId = null);
+ if (context.read<LibraryProvider>().selectedLibraryId == libraryId) {
+ await _refreshAuthors();
+ }
+ if (!mounted) return failed < authors.length;
+
+ final unchanged = found - updated;
+ final summary = <String>[
+ if (updated > 0) '${l.metadataUpdated} ($updated)',
+ if (unchanged > 0) '${l.quickMatchNoUpdates} ($unchanged)',
+ if (notFound > 0) '${l.authorNoMatchFound} ($notFound)',
+ if (failed > 0) '${l.failedToUpdateMetadata} ($failed)',
+ ];
+ showOverlayToast(
+ context,
+ summary.join(' - '),
+ icon: failed > 0
+ ? Icons.error_outline_rounded
+ : notFound > 0
+ ? Icons.search_off_rounded
+ : Icons.check_circle_outline_rounded,
+ );
+ return failed == 0 && notFound == 0;
+ }
+
+ Future<void> _quickMatchAllAuthors() async {
+ if (_matchingAuthors || _batchActionBusy || _authors.isEmpty) return;
+ final authors = List<Map<String, dynamic>>.from(_authors);
+ setState(() => _matchingAuthors = true);
+ await _quickMatchAuthors(authors, allAuthors: true);
+ if (mounted) {
+ setState(() {
+ _matchingAuthors = false;
+ _authorMatchPosition = 0;
+ _authorMatchTotal = 0;
+ });
+ }
+ }
+
List<Map<String, dynamic>> _visibleLibraryItems(LibraryProvider lib) {
if (_filter != LibraryFilter.subscribed) return _items;
return _items.where((item) {
@@ -3218,6 +3588,10 @@ class LibraryScreenState extends State<LibraryScreen>
onRefresh: _refreshAuthors,
headerSliver: headerSliver,
scrollController: _authorsScrollController,
+ selectionMode: _selectionMode && _currentTab == 2,
+ selectedAuthorIds: _selectedItemIds,
+ matchingAuthorId: _matchingAuthorId,
+ onSelectionToggle: _toggleSelection,
);
}
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index c0edba15..53279843 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -3818,6 +3818,77 @@ class ApiService {
return 0;
}
+ /// Delete several library items in one server operation.
+ /// Returns the HTTP status code so callers can distinguish a missing
+ /// `delete` permission (403) from other failures. Zero means no request was
+ /// made or the request threw.
+ Future<int> deleteLibraryItems(
+ List<String> itemIds, {
+ bool hard = false,
+ }) async {
+ if (itemIds.isEmpty) return 0;
+ try {
+ final response = await _authPost(
+ Uri.parse('$_cleanBaseUrl/api/items/batch/delete?hard=${hard ? 1 : 0}'),
+ body: jsonEncode({'libraryItemIds': itemIds}),
+ timeout: const Duration(seconds: 60),
+ );
+ return response.statusCode;
+ } catch (e) {
+ debugPrint('deleteLibraryItems error: $e');
+ return 0;
+ }
+ }
+
+ /// Quick-match several items using Audiobookshelf's native batch endpoint.
+ Future<bool> quickMatchLibraryItems(
+ List<String> itemIds, {
+ required String provider,
+ bool overrideCover = false,
+ bool overrideDetails = false,
+ }) async {
+ if (itemIds.isEmpty) return false;
+ try {
+ final response = await _authPost(
+ Uri.parse('$_cleanBaseUrl/api/items/batch/quickmatch'),
+ body: jsonEncode({
+ 'options': {
+ 'provider': provider,
+ 'overrideCover': overrideCover,
+ 'overrideDetails': overrideDetails,
+ },
+ 'libraryItemIds': itemIds,
+ }),
+ timeout: const Duration(seconds: 60),
+ );
+ return response.statusCode == 200;
+ } catch (e) {
+ debugPrint('quickMatchLibraryItems error: $e');
+ return false;
+ }
+ }
+
+ /// Mark several library items finished or unfinished in one request.
+ Future<bool> updateLibraryItemsFinished(
+ List<String> itemIds, {
+ required bool isFinished,
+ }) async {
+ if (itemIds.isEmpty) return false;
+ try {
+ final response = await _authPatch(
+ Uri.parse('$_cleanBaseUrl/api/me/progress/batch/update'),
+ body: jsonEncode([
+ for (final itemId in itemIds)
+ {'libraryItemId': itemId, 'isFinished': isFinished},
+ ]),
+ );
+ return response.statusCode == 200;
+ } catch (e) {
+ debugPrint('updateLibraryItemsFinished error: $e');
+ return false;
+ }
+ }
+
// ── Playlists ──────────────────────────────────────────────────────────
/// GET /api/libraries/:libraryId/playlists
diff --git a/lib/widgets/book_card.dart b/lib/widgets/book_card.dart
index e14aabeb..a4ca51b6 100644
--- a/lib/widgets/book_card.dart
+++ b/lib/widgets/book_card.dart
@@ -20,6 +20,9 @@ class BookCard extends StatelessWidget {
final String? sourcePlaylistEpisodeId;
final String? sourceCollectionId;
final String? sourceCollectionName;
+ final bool selectionMode;
+ final bool selected;
+ final VoidCallback? onSelectionToggle;
const BookCard({
super.key,
@@ -31,6 +34,9 @@ class BookCard extends StatelessWidget {
this.sourcePlaylistEpisodeId,
this.sourceCollectionId,
this.sourceCollectionName,
+ this.selectionMode = false,
+ this.selected = false,
+ this.onSelectionToggle,
});
@override
@@ -61,10 +67,59 @@ class BookCard extends StatelessWidget {
final headers = lib.mediaHeaders;
- if (isWide) {
- return _buildWideCard(context, cs, tt, l, title, authorName, coverUrl, progress, headers, isExplicit: isExplicit);
- }
- return _buildCompactCard(context, cs, tt, l, title, authorName, coverUrl, progress, headers, isFinished: isFinished, isDownloaded: isDownloaded, isExplicit: isExplicit, unfinishedCount: unfinishedCount);
+ final card = isWide
+ ? _buildWideCard(context, cs, tt, l, title, authorName, coverUrl, progress, headers, isExplicit: isExplicit)
+ : _buildCompactCard(context, cs, tt, l, title, authorName, coverUrl, progress, headers, isFinished: isFinished, isDownloaded: isDownloaded, isExplicit: isExplicit, unfinishedCount: unfinishedCount);
+ if (!selectionMode) return card;
+ // Selection sits on top of the finished card rather than inside both
+ // layouts: the overlay swallows the tap, so nothing below it can open a
+ // sheet while the shelf is being ticked through.
+ return Stack(
+ children: [
+ card,
+ Positioned.fill(
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onSelectionToggle,
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(12),
+ border: selected
+ ? Border.all(color: cs.primary, width: 3)
+ : null,
+ color: selected
+ ? cs.primary.withValues(alpha: 0.18)
+ : Colors.transparent,
+ ),
+ ),
+ ),
+ ),
+ Positioned(
+ top: 6,
+ left: 6,
+ child: IgnorePointer(
+ child: Container(
+ width: 26,
+ height: 26,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: selected
+ ? cs.primary
+ : Colors.black.withValues(alpha: 0.55),
+ border: Border.all(
+ color: selected ? cs.primary : Colors.white70,
+ ),
+ ),
+ child: Icon(
+ selected ? Icons.check_rounded : Icons.circle_outlined,
+ size: 17,
+ color: selected ? cs.onPrimary : Colors.white70,
+ ),
+ ),
+ ),
+ ),
+ ],
+ );
}
void _navigateToDetail(BuildContext context) {
diff --git a/lib/widgets/desktop_batch_actions.dart b/lib/widgets/desktop_batch_actions.dart
new file mode 100644
index 00000000..97bcebf0
--- /dev/null
+++ b/lib/widgets/desktop_batch_actions.dart
@@ -0,0 +1,367 @@
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+
+import '../l10n/app_localizations.dart';
+import '../providers/auth_provider.dart';
+import '../providers/library_provider.dart';
+import '../services/audio_player_service.dart';
+import 'delete_confirm_dialog.dart';
+import 'overlay_toast.dart';
+
+class DesktopQuickMatchOptions {
+ final String provider;
+ final bool overrideCover;
+ final bool overrideDetails;
+
+ const DesktopQuickMatchOptions({
+ required this.provider,
+ required this.overrideCover,
+ required this.overrideDetails,
+ });
+}
+
+Future<DesktopQuickMatchOptions?> showDesktopQuickMatchDialog(
+ BuildContext context, {
+ required List<String> providers,
+ required String initialProvider,
+}) {
+ final availableProviders = providers.isEmpty
+ ? <String>[initialProvider]
+ : providers.toSet().toList();
+ var provider = availableProviders.contains(initialProvider)
+ ? initialProvider
+ : availableProviders.first;
+ var overrideCover = true;
+ var overrideDetails = true;
+ final l = AppLocalizations.of(context)!;
+
+ return showDialog<DesktopQuickMatchOptions>(
+ context: context,
+ builder: (dialogContext) => StatefulBuilder(
+ builder: (context, setLocalState) => AlertDialog(
+ title: Text(l.quickMatch),
+ content: SizedBox(
+ width: 360,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ DropdownButtonFormField<String>(
+ initialValue: provider,
+ decoration: InputDecoration(labelText: l.libProvider),
+ items: [
+ for (final value in availableProviders)
+ DropdownMenuItem(value: value, child: Text(value)),
+ ],
+ onChanged: (value) {
+ if (value != null) {
+ setLocalState(() => provider = value);
+ }
+ },
+ ),
+ const SizedBox(height: 12),
+ CheckboxListTile(
+ contentPadding: EdgeInsets.zero,
+ title: const Text('Replace covers'),
+ value: overrideCover,
+ onChanged: (value) =>
+ setLocalState(() => overrideCover = value ?? false),
+ ),
+ CheckboxListTile(
+ contentPadding: EdgeInsets.zero,
+ title: const Text('Replace details'),
+ value: overrideDetails,
+ onChanged: (value) =>
+ setLocalState(() => overrideDetails = value ?? false),
+ ),
+ ],
+ ),
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(dialogContext),
+ child: Text(l.cancel),
+ ),
+ FilledButton(
+ onPressed: () => Navigator.pop(
+ dialogContext,
+ DesktopQuickMatchOptions(
+ provider: provider,
+ overrideCover: overrideCover,
+ overrideDetails: overrideDetails,
+ ),
+ ),
+ child: Text(l.quickMatch),
+ ),
+ ],
+ ),
+ ),
+ );
+}
+
+class DesktopBatchActions {
+ const DesktopBatchActions._();
+
+ static Future<bool?> quickMatch(
+ BuildContext context,
+ List<String> itemIds,
+ ) async {
+ if (itemIds.isEmpty) return null;
+ final auth = context.read<AuthProvider>();
+ final lib = context.read<LibraryProvider>();
+ final api = auth.apiService;
+ if (api == null) return false;
+
+ final libraryProvider =
+ lib.selectedLibrary?['provider']?.toString().trim() ?? '';
+ final providers = await api.getMetadataProviders();
+ if (!context.mounted) return null;
+ final initialProvider = libraryProvider.isNotEmpty
+ ? libraryProvider
+ : (providers.isNotEmpty ? providers.first : 'audible');
+ final options = await showDesktopQuickMatchDialog(
+ context,
+ providers: providers,
+ initialProvider: initialProvider,
+ );
+ if (options == null || !context.mounted) return null;
+
+ final success = await api.quickMatchLibraryItems(
+ itemIds,
+ provider: options.provider,
+ overrideCover: options.overrideCover,
+ overrideDetails: options.overrideDetails,
+ );
+ if (!context.mounted) return success;
+ final l = AppLocalizations.of(context)!;
+ showOverlayToast(
+ context,
+ success
+ ? l.adminMatchingStarted(l.selectedCount(itemIds.length))
+ : l.failedToUpdateMetadata,
+ icon: success
+ ? Icons.check_circle_outline_rounded
+ : Icons.error_outline_rounded,
+ );
+ return success;
+ }
+
+ static Future<bool> setFinished(
+ BuildContext context,
+ List<String> itemIds, {
+ required bool isFinished,
+ }) async {
+ if (itemIds.isEmpty) return false;
+ final auth = context.read<AuthProvider>();
+ final lib = context.read<LibraryProvider>();
+ final api = auth.apiService;
+ if (api == null) return false;
+ final success = await api.updateLibraryItemsFinished(
+ itemIds,
+ isFinished: isFinished,
+ );
+ if (!context.mounted) return success;
+ final l = AppLocalizations.of(context)!;
+ if (success) await lib.refresh();
+ if (!context.mounted) return success;
+ showOverlayToast(
+ context,
+ success
+ ? (isFinished
+ ? l.playlistDetailItemsMarkedFinished(itemIds.length)
+ : l.playlistDetailItemsMarkedUnfinished(itemIds.length))
+ : l.failedToUpdateCheckConnection,
+ icon: success
+ ? (isFinished
+ ? Icons.check_circle_outline_rounded
+ : Icons.radio_button_unchecked_rounded)
+ : Icons.error_outline_rounded,
+ );
+ return success;
+ }
+
+ static Future<bool?> delete(
+ BuildContext context,
+ List<String> itemIds,
+ ) async {
+ if (itemIds.isEmpty) return null;
+ final l = AppLocalizations.of(context)!;
+ final choice = await showDeleteConfirmDialog(
+ context,
+ title: l.deleteFromServerTitle,
+ message: l.selectedCount(itemIds.length),
+ );
+ if (choice == null || !context.mounted) return null;
+
+ final auth = context.read<AuthProvider>();
+ final lib = context.read<LibraryProvider>();
+ final api = auth.apiService;
+ if (api == null) return false;
+ final status = await api.deleteLibraryItems(
+ itemIds,
+ hard: choice.hardDelete,
+ );
+ if (!context.mounted) return status == 200;
+ if (status == 200) {
+ final player = AudioPlayerService();
+ if (itemIds.contains(player.currentItemId)) {
+ await player.stopWithoutSaving();
+ }
+ for (final itemId in itemIds) {
+ await lib.removeFromAbsorbing(itemId);
+ }
+ await lib.refresh();
+ if (!context.mounted) return true;
+ showOverlayToast(
+ context,
+ l.deletedFromServer(l.selectedCount(itemIds.length)),
+ icon: Icons.delete_outline_rounded,
+ );
+ return true;
+ }
+ showOverlayToast(
+ context,
+ status == 403 ? l.deletePermissionRequired : l.deleteFromServerFailed,
+ icon: status == 403
+ ? Icons.lock_outline_rounded
+ : Icons.error_outline_rounded,
+ );
+ return false;
+ }
+}
+
+class DesktopBatchActionBar extends StatelessWidget {
+ final int selectedCount;
+ final int selectableCount;
+ final bool busy;
+ final String? busyLabel;
+ final bool canQuickMatch;
+ final bool canMarkProgress;
+ final bool canDelete;
+ final VoidCallback onSelectAll;
+ final VoidCallback onClear;
+ final VoidCallback onQuickMatch;
+ final VoidCallback onMarkFinished;
+ final VoidCallback onMarkUnfinished;
+ final VoidCallback onDelete;
+
+ const DesktopBatchActionBar({
+ super.key,
+ required this.selectedCount,
+ required this.selectableCount,
+ required this.busy,
+ this.busyLabel,
+ required this.canQuickMatch,
+ this.canMarkProgress = true,
+ required this.canDelete,
+ required this.onSelectAll,
+ required this.onClear,
+ required this.onQuickMatch,
+ required this.onMarkFinished,
+ required this.onMarkUnfinished,
+ required this.onDelete,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final l = AppLocalizations.of(context)!;
+ final hasSelection = selectedCount > 0;
+ final allSelected = selectableCount > 0 && selectedCount >= selectableCount;
+
+ return Material(
+ elevation: 10,
+ color: cs.surfaceContainerHigh,
+ shadowColor: Colors.black.withValues(alpha: 0.35),
+ borderRadius: BorderRadius.circular(28),
+ clipBehavior: Clip.antiAlias,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(minHeight: 52),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (busy) ...[
+ const Padding(
+ padding: EdgeInsets.all(10),
+ child: SizedBox(
+ width: 20,
+ height: 20,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
+ ),
+ if (busyLabel != null && busyLabel!.isNotEmpty)
+ Padding(
+ padding: const EdgeInsets.only(right: 6),
+ child: Text(
+ busyLabel!,
+ style: const TextStyle(fontWeight: FontWeight.w700),
+ ),
+ ),
+ ] else
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 10),
+ child: Text(
+ l.selectedCount(selectedCount),
+ style: const TextStyle(fontWeight: FontWeight.w700),
+ ),
+ ),
+ Tooltip(
+ message: allSelected ? l.deselectAll : l.selectAll,
+ child: IconButton(
+ onPressed: busy || selectableCount == 0 ? null : onSelectAll,
+ icon: Icon(
+ allSelected
+ ? Icons.deselect_rounded
+ : Icons.select_all_rounded,
+ ),
+ ),
+ ),
+ if (canQuickMatch)
+ Tooltip(
+ message: l.quickMatch,
+ child: IconButton(
+ onPressed: busy || !hasSelection ? null : onQuickMatch,
+ icon: const Icon(Icons.auto_fix_high_rounded),
+ ),
+ ),
+ if (canMarkProgress) ...[
+ Tooltip(
+ message: l.markFinished,
+ child: IconButton(
+ onPressed: busy || !hasSelection ? null : onMarkFinished,
+ icon: const Icon(Icons.check_circle_outline_rounded),
+ ),
+ ),
+ Tooltip(
+ message: l.markUnfinished,
+ child: IconButton(
+ onPressed: busy || !hasSelection ? null : onMarkUnfinished,
+ icon: const Icon(Icons.radio_button_unchecked_rounded),
+ ),
+ ),
+ ],
+ if (canDelete)
+ Tooltip(
+ message: l.deleteFromServerAction,
+ child: IconButton(
+ onPressed: busy || !hasSelection ? null : onDelete,
+ color: cs.error,
+ icon: const Icon(Icons.delete_outline_rounded),
+ ),
+ ),
+ Tooltip(
+ message: l.downloadsCancelSelection,
+ child: IconButton(
+ onPressed: busy ? null : onClear,
+ icon: const Icon(Icons.close_rounded),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/home_section.dart b/lib/widgets/home_section.dart
index c7e85ee4..b8fe2390 100644
--- a/lib/widgets/home_section.dart
+++ b/lib/widgets/home_section.dart
@@ -18,6 +18,9 @@ class HomeSection extends StatelessWidget {
final String sectionId;
final VoidCallback? onTitleTap;
final double coverAspectRatio;
+ final bool selectionMode;
+ final Set<String> selectedItemIds;
+ final ValueChanged<Map<String, dynamic>>? onSelectionToggle;
const HomeSection({
super.key,
@@ -28,6 +31,9 @@ class HomeSection extends StatelessWidget {
required this.sectionId,
this.onTitleTap,
this.coverAspectRatio = 1.0,
+ this.selectionMode = false,
+ this.selectedItemIds = const {},
+ this.onSelectionToggle,
});
@override
@@ -177,6 +183,15 @@ class HomeSection extends StatelessWidget {
sourcePlaylistEpisodeId: sourcePlaylistEpisodeId,
sourceCollectionId: sourceCollectionId,
sourceCollectionName: sourceCollectionName,
+ selectionMode: selectionMode,
+ selected: entity is Map<String, dynamic> &&
+ selectedItemIds.contains(entity['id'] as String?),
+ onSelectionToggle:
+ entity is Map<String, dynamic> &&
+ entity['id'] is String &&
+ onSelectionToggle != null
+ ? () => onSelectionToggle!(entity as Map<String, dynamic>)
+ : null,
),
);
},
diff --git a/lib/widgets/library_authors_tab.dart b/lib/widgets/library_authors_tab.dart
index 8d6a2de9..10121df4 100644
--- a/lib/widgets/library_authors_tab.dart
+++ b/lib/widgets/library_authors_tab.dart
@@ -10,6 +10,11 @@ class LibraryAuthorsTab extends StatelessWidget {
final Future<void> Function() onRefresh;
final Widget? headerSliver;
final ScrollController? scrollController;
+ final bool selectionMode;
+ final Set<String> selectedAuthorIds;
+ final String? matchingAuthorId;
+ final void Function(Map<String, dynamic> author, int index)?
+ onSelectionToggle;
const LibraryAuthorsTab({
super.key,
@@ -19,6 +24,10 @@ class LibraryAuthorsTab extends StatelessWidget {
required this.onRefresh,
this.headerSliver,
this.scrollController,
+ this.selectionMode = false,
+ this.selectedAuthorIds = const {},
+ this.matchingAuthorId,
+ this.onSelectionToggle,
});
@override
@@ -81,7 +90,19 @@ class LibraryAuthorsTab extends StatelessWidget {
mainAxisSpacing: 10,
),
delegate: SliverChildBuilderDelegate(
- (context, index) => GridAuthorTile(author: authors[index]),
+ (context, index) {
+ final author = authors[index];
+ final authorId = author['id'] as String? ?? '';
+ return GridAuthorTile(
+ author: author,
+ selectionMode: selectionMode,
+ isSelected: selectedAuthorIds.contains(authorId),
+ isMatching: matchingAuthorId == authorId,
+ onSelectionToggle: onSelectionToggle == null
+ ? null
+ : () => onSelectionToggle!(author, index),
+ );
+ },
childCount: authors.length,
),
),
diff --git a/lib/widgets/library_books_tab.dart b/lib/widgets/library_books_tab.dart
index 6f1661ac..a474d431 100644
--- a/lib/widgets/library_books_tab.dart
+++ b/lib/widgets/library_books_tab.dart
@@ -30,6 +30,9 @@ class LibraryBooksTab extends StatelessWidget {
/// IndexedStack each one needs its own controller so scroll positions don't
/// collide on the PrimaryScrollController.
final ScrollController? scrollController;
+ final bool selectionMode;
+ final Set<String> selectedItemIds;
+ final void Function(Map<String, dynamic> item, int index)? onSelectionToggle;
const LibraryBooksTab({
super.key,
@@ -47,6 +50,9 @@ class LibraryBooksTab extends StatelessWidget {
required this.onLoadMore,
this.headerSliver,
this.scrollController,
+ this.selectionMode = false,
+ this.selectedItemIds = const {},
+ this.onSelectionToggle,
});
@override
@@ -162,7 +168,16 @@ class LibraryBooksTab extends StatelessWidget {
if (item.containsKey('collapsedSeries')) {
return GridSeriesTile(item: item, coverAspectRatio: coverAspectRatio);
}
- return GridBookTile(item: item, coverAspectRatio: coverAspectRatio);
+ final itemId = item['id'] as String?;
+ return GridBookTile(
+ item: item,
+ coverAspectRatio: coverAspectRatio,
+ selectionMode: selectionMode,
+ selected: itemId != null && selectedItemIds.contains(itemId),
+ onSelectionToggle: itemId == null || onSelectionToggle == null
+ ? null
+ : () => onSelectionToggle!(item, index),
+ );
},
childCount: items.length + (hasMore ? 1 : 0),
),
diff --git a/lib/widgets/library_grid_tiles.dart b/lib/widgets/library_grid_tiles.dart
index 047ff39b..4612d253 100644
--- a/lib/widgets/library_grid_tiles.dart
+++ b/lib/widgets/library_grid_tiles.dart
@@ -21,8 +21,19 @@ class GridBookTile extends StatefulWidget {
final Map<String, dynamic> item;
final double coverAspectRatio;
final String? sequenceBadge;
+ final bool selectionMode;
+ final bool selected;
+ final VoidCallback? onSelectionToggle;
- const GridBookTile({super.key, required this.item, this.coverAspectRatio = 1.0, this.sequenceBadge});
+ const GridBookTile({
+ super.key,
+ required this.item,
+ this.coverAspectRatio = 1.0,
+ this.sequenceBadge,
+ this.selectionMode = false,
+ this.selected = false,
+ this.onSelectionToggle,
+ });
@override
State<GridBookTile> createState() => _GridBookTileState();
@@ -75,6 +86,10 @@ class _GridBookTileState extends State<GridBookTile> {
// miss the Column's hit test and nothing happens.
behavior: HitTestBehavior.opaque,
onTap: () {
+ if (widget.selectionMode && widget.onSelectionToggle != null) {
+ widget.onSelectionToggle!();
+ return;
+ }
if (itemId.isNotEmpty) {
if (lib.isPodcastLibrary) {
EpisodeListSheet.show(context, widget.item);
@@ -84,7 +99,10 @@ class _GridBookTileState extends State<GridBookTile> {
}
},
// Long-press a book cover for the quick-actions sheet (podcasts skipped).
- onLongPress: (itemId.isNotEmpty && !lib.isPodcastLibrary)
+ // Selection mode owns the gesture instead, so a long-press can't fire a
+ // sheet over a grid the user is ticking through.
+ onLongPress:
+ (!widget.selectionMode && itemId.isNotEmpty && !lib.isPodcastLibrary)
? () => showQuickActionsSheet(context, itemId, initialItem: widget.item)
: null,
child: Column(
@@ -195,6 +213,44 @@ class _GridBookTileState extends State<GridBookTile> {
isFinished: isFinished,
),
),
+
+ // ── Batch selection ──
+ if (widget.selectionMode) ...[
+ if (widget.selected)
+ Positioned.fill(
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ border: Border.all(color: cs.primary, width: 3),
+ borderRadius: BorderRadius.circular(10),
+ color: cs.primary.withValues(alpha: 0.18),
+ ),
+ ),
+ ),
+ Positioned(
+ top: 4,
+ left: 4,
+ child: Container(
+ width: 26,
+ height: 26,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: widget.selected
+ ? cs.primary
+ : Colors.black.withValues(alpha: 0.55),
+ border: Border.all(
+ color: widget.selected ? cs.primary : Colors.white70,
+ ),
+ ),
+ child: Icon(
+ widget.selected
+ ? Icons.check_rounded
+ : Icons.circle_outlined,
+ size: 17,
+ color: widget.selected ? cs.onPrimary : Colors.white70,
+ ),
+ ),
+ ),
+ ],
],
),
),
@@ -727,7 +783,18 @@ class GridListTile extends StatelessWidget {
// ═══════════════════════════════════════════════════════════════
class GridAuthorTile extends StatelessWidget {
final Map<String, dynamic> author;
- const GridAuthorTile({super.key, required this.author});
+ final bool selectionMode;
+ final bool isSelected;
+ final bool isMatching;
+ final VoidCallback? onSelectionToggle;
+ const GridAuthorTile({
+ super.key,
+ required this.author,
+ this.selectionMode = false,
+ this.isSelected = false,
+ this.isMatching = false,
+ this.onSelectionToggle,
+ });
@override
Widget build(BuildContext context) {
@@ -749,13 +816,20 @@ class GridAuthorTile extends StatelessWidget {
final headers = lib.mediaHeaders;
- return GestureDetector(
+ return Semantics(
+ selected: selectionMode ? isSelected : null,
+ child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
+ if (selectionMode) {
+ onSelectionToggle?.call();
+ return;
+ }
if (authorId.isNotEmpty) {
showAuthorDetailSheet(context, authorId: authorId, authorName: name);
}
},
+ onLongPress: onSelectionToggle,
child: Column(
children: [
// Circular avatar
@@ -769,18 +843,47 @@ class GridAuthorTile extends StatelessWidget {
decoration: BoxDecoration(
shape: BoxShape.circle,
color: cs.secondaryContainer,
+ border: selectionMode && isSelected
+ ? Border.all(color: cs.primary, width: 3)
+ : null,
),
+ padding: selectionMode && isSelected
+ ? const EdgeInsets.all(3)
+ : EdgeInsets.zero,
clipBehavior: Clip.antiAlias,
child: imageUrl != null
- ? CachedNetworkImage(
- imageUrl: imageUrl,
- fit: BoxFit.cover,
- httpHeaders: headers,
- placeholder: (_, __) => _placeholder(cs),
- errorWidget: (_, __, ___) => _placeholder(cs),
+ ? ClipOval(
+ child: CachedNetworkImage(
+ imageUrl: imageUrl,
+ fit: BoxFit.cover,
+ httpHeaders: headers,
+ placeholder: (_, __) => _placeholder(cs),
+ errorWidget: (_, __, ___) => _placeholder(cs),
+ ),
)
- : _placeholder(cs),
+ : ClipOval(child: _placeholder(cs)),
),
+ if (selectionMode)
+ Positioned(
+ top: 0,
+ left: 0,
+ child: Container(
+ width: 28,
+ height: 28,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: isSelected ? cs.primary : cs.surfaceContainerHighest,
+ border: Border.all(
+ color: isSelected ? cs.primary : cs.outlineVariant,
+ ),
+ ),
+ child: Icon(
+ isSelected ? Icons.check_rounded : Icons.circle_outlined,
+ size: 18,
+ color: isSelected ? cs.onPrimary : cs.onSurfaceVariant,
+ ),
+ ),
+ ),
if (numBooks > 0)
Positioned(
top: 0,
@@ -803,6 +906,25 @@ class GridAuthorTile extends StatelessWidget {
),
),
),
+ if (isMatching)
+ Positioned.fill(
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: Colors.black.withValues(alpha: 0.55),
+ ),
+ child: const Center(
+ child: SizedBox(
+ width: 22,
+ height: 22,
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ color: Colors.white,
+ ),
+ ),
+ ),
+ ),
+ ),
],
),
),
@@ -820,6 +942,7 @@ class GridAuthorTile extends StatelessWidget {
),
],
),
+ ),
);
}