A cross platform Audiobookshelf client for Android and iOS
Dart
Add metadata editing: server edit for root users, local override improvements
Nathan Poulsonbab7406195f7
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dartindex 2c35a402..3a50c9ce 100644--- a/lib/services/api_service.dart+++ b/lib/services/api_service.dart@@ -1144,6 +1144,50 @@ class ApiService {return false;}+ /// Update a library item's media metadata (admin/root only).+ /// Uses POST /api/items/:id/match which requires update permission.+ Future<bool> updateItemMedia(String itemId, Map<String, dynamic> media) async {+ try {+ final r = await http.patch(+ Uri.parse('$_cleanBaseUrl/api/items/$itemId/media'),+ headers: _headers,+ body: jsonEncode({'metadata': media}),+ ).timeout(const Duration(seconds: 15));+ debugPrint('[API] updateItemMedia $itemId -> ${r.statusCode}: ${r.body}');+ return r.statusCode == 200;+ } catch (e) { debugPrint('updateItemMedia error: $e'); }+ return false;+ }++ /// Upload a cover image URL for a library item (admin only)+ Future<bool> updateItemCoverUrl(String itemId, String url) async {+ try {+ final r = await http.post(+ Uri.parse('$_cleanBaseUrl/api/items/$itemId/cover'),+ headers: _headers,+ body: jsonEncode({'url': url}),+ ).timeout(const Duration(seconds: 30));+ debugPrint('[API] updateItemCoverUrl $itemId -> ${r.statusCode}: ${r.body}');+ return r.statusCode == 200;+ } catch (e) { debugPrint('updateItemCoverUrl error: $e'); }+ return false;+ }++ /// Upload a cover image file for a library item (admin only)+ Future<bool> uploadItemCover(String itemId, String filePath) async {+ try {+ final req = http.MultipartRequest(+ 'POST',+ Uri.parse('$_cleanBaseUrl/api/items/$itemId/cover'),+ );+ req.headers.addAll(_headers);+ req.files.add(await http.MultipartFile.fromPath('cover', filePath));+ final res = await req.send().timeout(const Duration(seconds: 60));+ return res.statusCode == 200;+ } catch (e) { debugPrint('uploadItemCover error: $e'); }+ return false;+ }+// ─── Podcast Endpoints ────────────────────────────────────/// Search for podcasts (uses iTunes)diff --git a/lib/services/metadata_override_service.dart b/lib/services/metadata_override_service.dartindex 9f668ae3..f3d0bf54 100644--- a/lib/services/metadata_override_service.dart+++ b/lib/services/metadata_override_service.dart@@ -46,49 +46,39 @@ class MetadataOverrideService {}/// Apply overrides to a server item map. Modifies in place and returns it.- /// Only fills in fields that are empty/missing on the server item.Map<String, dynamic> applyOverrides(Map<String, dynamic> item, Map<String, dynamic> override) {final media = item['media'] as Map<String, dynamic>? ?? {};final metadata =Map<String, dynamic>.from(media['metadata'] as Map<String, dynamic>? ?? {});- // Only override if the server field is empty- void fillIfEmpty(String metaKey, String overrideKey) {- final current = metadata[metaKey];+ // Apply override value (always replaces server value)+ void applyField(String metaKey, String overrideKey) {final replacement = override[overrideKey];- if (replacement != null &&- replacement.toString().isNotEmpty &&- (current == null || current.toString().trim().isEmpty)) {+ if (replacement != null && replacement.toString().isNotEmpty) {metadata[metaKey] = replacement;}}- fillIfEmpty('title', 'title');- fillIfEmpty('authorName', 'author');- fillIfEmpty('narratorName', 'narrator');- fillIfEmpty('description', 'description');- fillIfEmpty('publisher', 'publisher');- fillIfEmpty('publishedYear', 'publishedYear');- fillIfEmpty('asin', 'asin');- fillIfEmpty('isbn', 'isbn');+ applyField('title', 'title');+ applyField('authorName', 'author');+ applyField('narratorName', 'narrator');+ applyField('description', 'description');+ applyField('publisher', 'publisher');+ applyField('publishedYear', 'publishedYear');+ applyField('asin', 'asin');+ applyField('isbn', 'isbn');- // Genres: merge (add missing ones)+ // Genresfinal overrideGenres = override['genres'] as List<dynamic>?;if (overrideGenres != null && overrideGenres.isNotEmpty) {- final existing = (metadata['genres'] as List<dynamic>?)?.cast<String>() ?? [];- if (existing.isEmpty) {- metadata['genres'] = overrideGenres;- }+ metadata['genres'] = overrideGenres;}// Seriesfinal overrideSeries = override['series'] as List<dynamic>?;if (overrideSeries != null && overrideSeries.isNotEmpty) {- final existing = metadata['series'] as List<dynamic>? ?? [];- if (existing.isEmpty) {- metadata['series'] = overrideSeries;- }+ metadata['series'] = overrideSeries;}// Write backdiff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dartindex c8647161..9f9e1942 100644--- a/lib/widgets/book_detail_sheet.dart+++ b/lib/widgets/book_detail_sheet.dart@@ -27,6 +27,7 @@ import 'absorbing_shared.dart';import 'html_description.dart';import 'metadata_lookup_sheet.dart';import 'absorb_wave_icon.dart';+import 'edit_metadata_sheet.dart';// ─── BOOK DETAIL BOTTOM SHEET ───────────────────────────────@@ -498,7 +499,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {onTap: () { Navigator.pop(ctx); _resetProgress(context, auth, duration); }),if (auth.apiService != null && !lib.isOffline)_moreItem(cs, Icons.manage_search_rounded,- _hasLocalOverride ? 'Re-Lookup Metadata' : 'Lookup Metadata',+ _hasLocalOverride ? 'Re-Lookup Local Metadata' : 'Lookup Local Metadata',onTap: () { Navigator.pop(ctx); _openMetadataLookup(context, auth, title, authorName); }),if (_hasLocalOverride)_moreItem(cs, Icons.layers_clear_rounded, 'Clear Local Metadata',@@ -506,6 +507,14 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {if (_showGoodreads)_moreItem(cs, Icons.local_library_rounded, 'Search on Goodreads',onTap: () { Navigator.pop(ctx); _openGoodreads(title, authorName); }),+ if (auth.isRoot && !lib.isOffline)+ _moreItem(cs, Icons.edit_rounded, 'Edit Server Details',+ onTap: () {+ Navigator.pop(ctx);+ final media = _item!['media'] as Map<String, dynamic>? ?? {};+ final meta = media['metadata'] as Map<String, dynamic>? ?? {};+ showEditMetadataSheet(context, itemId: widget.itemId, metadata: meta);+ }),]),),);@@ -1067,6 +1076,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {api: api,initialTitle: title,initialAuthor: author,+ currentMetadata: (_item?['media'] as Map<String, dynamic>?)?['metadata'] as Map<String, dynamic>?,onApplied: () {// Reload the item to show the new override_loadItem();diff --git a/lib/widgets/edit_metadata_sheet.dart b/lib/widgets/edit_metadata_sheet.dartnew file mode 100644index 00000000..66713f0a--- /dev/null+++ b/lib/widgets/edit_metadata_sheet.dart@@ -0,0 +1,729 @@+import 'package:flutter/material.dart';+import 'package:provider/provider.dart';+import 'package:file_picker/file_picker.dart';+import 'package:cached_network_image/cached_network_image.dart';+import '../providers/auth_provider.dart';+import '../providers/library_provider.dart';++/// Opens a full-screen editor for a library item's metadata (admin only).+/// Has two tabs: Quick Match (search providers) and Custom (manual fields).+void showEditMetadataSheet(+ BuildContext context, {+ required String itemId,+ required Map<String, dynamic> metadata,+}) {+ showModalBottomSheet(+ context: context,+ isScrollControlled: true,+ useSafeArea: true,+ backgroundColor: Colors.transparent,+ builder: (ctx) => DraggableScrollableSheet(+ expand: false,+ initialChildSize: 0.85,+ minChildSize: 0.3,+ maxChildSize: 0.95,+ snap: true,+ builder: (ctx, sc) => _EditMetadataContent(+ itemId: itemId,+ metadata: metadata,+ scrollController: sc,+ ),+ ),+ );+}++class _EditMetadataContent extends StatefulWidget {+ final String itemId;+ final Map<String, dynamic> metadata;+ final ScrollController scrollController;++ const _EditMetadataContent({+ required this.itemId,+ required this.metadata,+ required this.scrollController,+ });++ @override+ State<_EditMetadataContent> createState() => _EditMetadataContentState();+}++class _EditMetadataContentState extends State<_EditMetadataContent>+ with SingleTickerProviderStateMixin {+ late final TabController _tabCtrl;++ // Custom edit controllers+ late final TextEditingController _titleCtrl;+ late final TextEditingController _subtitleCtrl;+ late final TextEditingController _authorCtrl;+ late final TextEditingController _narratorCtrl;+ late final TextEditingController _seriesCtrl;+ late final TextEditingController _seriesSeqCtrl;+ late final TextEditingController _descCtrl;+ late final TextEditingController _publisherCtrl;+ late final TextEditingController _yearCtrl;+ late final TextEditingController _genresCtrl;+ late final TextEditingController _asinCtrl;+ late final TextEditingController _isbnCtrl;+ late final TextEditingController _languageCtrl;+ late final TextEditingController _coverUrlCtrl;++ // Quick match+ late final TextEditingController _searchTitleCtrl;+ late final TextEditingController _searchAuthorCtrl;+ List<Map<String, dynamic>> _searchResults = [];+ bool _isSearching = false;+ bool _hasSearched = false;+ String _provider = 'audible';+ static const _providers = [+ ('audible', 'Audible'),+ ('itunes', 'iTunes'),+ ('openlibrary', 'Open Library'),+ ];++ String? _coverFilePath;+ bool _saving = false;++ @override+ void initState() {+ super.initState();+ _tabCtrl = TabController(length: 2, vsync: this);+ final m = widget.metadata;+ _titleCtrl = TextEditingController(text: m['title'] as String? ?? '');+ _subtitleCtrl = TextEditingController(text: m['subtitle'] as String? ?? '');+ _authorCtrl = TextEditingController(text: m['authorName'] as String? ?? '');+ _narratorCtrl = TextEditingController(text: m['narratorName'] as String? ?? '');+ _descCtrl = TextEditingController(text: m['description'] as String? ?? '');+ _publisherCtrl = TextEditingController(text: m['publisher'] as String? ?? '');+ _yearCtrl = TextEditingController(text: m['publishedYear'] as String? ?? '');+ _asinCtrl = TextEditingController(text: m['asin'] as String? ?? '');+ _isbnCtrl = TextEditingController(text: m['isbn'] as String? ?? '');+ _languageCtrl = TextEditingController(text: m['language'] as String? ?? '');+ _coverUrlCtrl = TextEditingController();++ final series = m['series'] as List<dynamic>? ?? [];+ if (series.isNotEmpty) {+ final first = series[0] as Map<String, dynamic>;+ _seriesCtrl = TextEditingController(text: first['name'] as String? ?? '');+ _seriesSeqCtrl = TextEditingController(text: first['sequence'] as String? ?? '');+ } else {+ _seriesCtrl = TextEditingController();+ _seriesSeqCtrl = TextEditingController();+ }++ final genres = (m['genres'] as List<dynamic>?)?.cast<String>() ?? [];+ _genresCtrl = TextEditingController(text: genres.join(', '));++ // Search fields default to current title/author+ _searchTitleCtrl = TextEditingController(text: m['title'] as String? ?? '');+ _searchAuthorCtrl = TextEditingController(text: m['authorName'] as String? ?? '');+ }++ @override+ void dispose() {+ _tabCtrl.dispose();+ _titleCtrl.dispose();+ _subtitleCtrl.dispose();+ _authorCtrl.dispose();+ _narratorCtrl.dispose();+ _seriesCtrl.dispose();+ _seriesSeqCtrl.dispose();+ _descCtrl.dispose();+ _publisherCtrl.dispose();+ _yearCtrl.dispose();+ _genresCtrl.dispose();+ _asinCtrl.dispose();+ _isbnCtrl.dispose();+ _languageCtrl.dispose();+ _coverUrlCtrl.dispose();+ _searchTitleCtrl.dispose();+ _searchAuthorCtrl.dispose();+ super.dispose();+ }++ // ─── Quick Match ────────────────────────────────────────────++ Future<void> _doSearch() async {+ final title = _searchTitleCtrl.text.trim();+ if (title.isEmpty) return;+ final api = context.read<AuthProvider>().apiService;+ if (api == null) return;++ setState(() { _isSearching = true; _hasSearched = true; });++ final results = await api.searchBooks(+ title: title,+ author: _searchAuthorCtrl.text.trim(),+ provider: _provider,+ );++ if (mounted) {+ setState(() { _searchResults = results; _isSearching = false; });+ }+ }++ Future<void> _applyMatch(Map<String, dynamic> result) async {+ final book = result['book'] as Map<String, dynamic>? ?? result;+ final api = context.read<AuthProvider>().apiService;+ if (api == null) return;++ final update = <String, dynamic>{};++ void add(String key, dynamic value) {+ final s = _safeString(value);+ if (s.isNotEmpty) update[key] = s;+ }++ add('title', book['title']);+ add('subtitle', book['subtitle']);+ add('description', book['description']);+ add('publisher', book['publisher']);+ add('publishedYear', book['publishedYear'] ?? book['publishedDate']);+ add('asin', book['asin']);+ add('isbn', book['isbn']);+ add('language', book['language']);++ // Authors/narrators are arrays in ABS+ final authorStr = _safeString(book['author']).isNotEmpty+ ? _safeString(book['author'])+ : _safeString(book['authorName']);+ if (authorStr.isNotEmpty) {+ update['authors'] = authorStr.split(',').map((a) => {'name': a.trim()}).where((a) => (a['name'] as String).isNotEmpty).toList();+ }++ final narratorStr = _safeString(book['narrator']).isNotEmpty+ ? _safeString(book['narrator'])+ : _safeString(book['narratorName']);+ if (narratorStr.isNotEmpty) {+ update['narrators'] = narratorStr.split(',').map((n) => {'name': n.trim()}).where((n) => (n['name'] as String).isNotEmpty).toList();+ }++ // Genres+ final genres = book['genres'] ?? book['tags'];+ if (genres is List && genres.isNotEmpty) {+ update['genres'] = genres.whereType<String>().toList();+ }++ // Series+ final series = book['series'];+ if (series is List && series.isNotEmpty) {+ update['series'] = series;+ } else if (series is String && series.isNotEmpty) {+ update['series'] = [+ {'name': series, 'sequence': _safeString(book['volumeNumber'] ?? book['sequence'])}+ ];+ }++ setState(() => _saving = true);++ bool ok = await api.updateItemMedia(widget.itemId, update);++ // Cover+ final coverUrl = _safeString(book['cover']).isNotEmpty+ ? _safeString(book['cover'])+ : _safeString(book['image']);+ if (ok && coverUrl.isNotEmpty) {+ await api.updateItemCoverUrl(widget.itemId, coverUrl);+ }++ if (!mounted) return;+ setState(() => _saving = false);++ if (ok) {+ context.read<LibraryProvider>().refresh();+ Navigator.pop(context);+ ScaffoldMessenger.of(context)+ ..clearSnackBars()+ ..showSnackBar(SnackBar(+ content: const Text('Metadata updated from match'),+ behavior: SnackBarBehavior.floating,+ duration: const Duration(seconds: 2),+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),+ ));+ } else {+ ScaffoldMessenger.of(context)+ ..clearSnackBars()+ ..showSnackBar(SnackBar(+ content: const Text('Failed to update metadata'),+ behavior: SnackBarBehavior.floating,+ duration: const Duration(seconds: 3),+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),+ ));+ }+ }++ void _confirmMatch(Map<String, dynamic> result) {+ final book = result['book'] as Map<String, dynamic>? ?? result;+ final title = _safeString(book['title']);+ final author = _safeString(book['author']).isNotEmpty+ ? _safeString(book['author'])+ : _safeString(book['authorName']);++ showDialog(+ context: context,+ builder: (ctx) => AlertDialog(+ title: const Text('Apply This Match?'),+ content: Text(+ 'This will update the server metadata for this book using:\n\n'+ '"$title"${author.isNotEmpty ? ' by $author' : ''}\n\n'+ 'All fields and the cover will be overwritten on the server.',+ ),+ actions: [+ TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('Cancel')),+ FilledButton(onPressed: () { Navigator.pop(ctx); _applyMatch(result); }, child: const Text('Apply')),+ ],+ ),+ );+ }++ // ─── Custom Save ────────────────────────────────────────────++ Future<void> _saveCustom() async {+ final api = context.read<AuthProvider>().apiService;+ if (api == null) return;++ setState(() => _saving = true);++ final update = <String, dynamic>{+ 'title': _titleCtrl.text.trim(),+ 'subtitle': _subtitleCtrl.text.trim(),+ 'description': _descCtrl.text.trim(),+ 'publisher': _publisherCtrl.text.trim(),+ 'publishedYear': _yearCtrl.text.trim(),+ 'asin': _asinCtrl.text.trim(),+ 'isbn': _isbnCtrl.text.trim(),+ 'language': _languageCtrl.text.trim(),+ };++ // Authors/narrators are arrays in ABS, not simple strings+ final authorText = _authorCtrl.text.trim();+ if (authorText.isNotEmpty) {+ update['authors'] = authorText.split(',').map((a) => {'name': a.trim()}).where((a) => (a['name'] as String).isNotEmpty).toList();+ } else {+ update['authors'] = <Map<String, dynamic>>[];+ }++ final narratorText = _narratorCtrl.text.trim();+ if (narratorText.isNotEmpty) {+ update['narrators'] = narratorText.split(',').map((n) => {'name': n.trim()}).where((n) => (n['name'] as String).isNotEmpty).toList();+ } else {+ update['narrators'] = <Map<String, dynamic>>[];+ }++ final genresText = _genresCtrl.text.trim();+ update['genres'] = genresText.isNotEmpty+ ? genresText.split(',').map((g) => g.trim()).where((g) => g.isNotEmpty).toList()+ : <String>[];++ final seriesName = _seriesCtrl.text.trim();+ update['series'] = seriesName.isNotEmpty+ ? [{'name': seriesName, 'sequence': _seriesSeqCtrl.text.trim()}]+ : <Map<String, dynamic>>[];++ bool ok = await api.updateItemMedia(widget.itemId, update);++ if (ok && _coverFilePath != null) {+ ok = await api.uploadItemCover(widget.itemId, _coverFilePath!);+ } else if (ok && _coverUrlCtrl.text.trim().isNotEmpty) {+ ok = await api.updateItemCoverUrl(widget.itemId, _coverUrlCtrl.text.trim());+ }++ if (!mounted) return;+ setState(() => _saving = false);++ if (ok) {+ context.read<LibraryProvider>().refresh();+ Navigator.pop(context);+ ScaffoldMessenger.of(context)+ ..clearSnackBars()+ ..showSnackBar(SnackBar(+ content: const Text('Metadata updated'),+ behavior: SnackBarBehavior.floating,+ duration: const Duration(seconds: 2),+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),+ ));+ } else {+ ScaffoldMessenger.of(context)+ ..clearSnackBars()+ ..showSnackBar(SnackBar(+ content: const Text('Failed to update metadata'),+ behavior: SnackBarBehavior.floating,+ duration: const Duration(seconds: 3),+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),+ ));+ }+ }++ Future<void> _pickCoverImage() async {+ final result = await FilePicker.platform.pickFiles(+ type: FileType.image,+ allowMultiple: false,+ );+ if (result != null && result.files.single.path != null) {+ setState(() {+ _coverFilePath = result.files.single.path;+ _coverUrlCtrl.clear();+ });+ }+ }++ String _safeString(dynamic value) {+ if (value == null) return '';+ if (value is String) return value;+ if (value is List) return value.whereType<String>().join(', ');+ return value.toString();+ }++ // ─── Build ──────────────────────────────────────────────────++ @override+ Widget build(BuildContext context) {+ final cs = Theme.of(context).colorScheme;+ final tt = Theme.of(context).textTheme;++ return Container(+ decoration: BoxDecoration(+ color: cs.surface,+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),+ ),+ child: Column(children: [+ // Drag pill+ Center(child: Container(width: 40, height: 4, margin: const EdgeInsets.only(top: 12, bottom: 8),+ decoration: BoxDecoration(color: cs.onSurface.withValues(alpha: 0.24), borderRadius: BorderRadius.circular(2)))),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 20),+ child: Row(children: [+ Text('Edit Details', style: tt.titleLarge?.copyWith(fontWeight: FontWeight.w700)),+ const Spacer(),+ if (_saving)+ const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2)),+ ]),+ ),+ const SizedBox(height: 8),++ // Tabs+ TabBar(+ controller: _tabCtrl,+ labelColor: cs.primary,+ unselectedLabelColor: cs.onSurfaceVariant,+ indicatorColor: cs.primary,+ tabs: const [+ Tab(text: 'Quick Match'),+ Tab(text: 'Custom'),+ ],+ ),++ // Tab content+ Expanded(+ child: TabBarView(+ controller: _tabCtrl,+ children: [+ _buildQuickMatchTab(cs, tt),+ _buildCustomTab(cs, tt),+ ],+ ),+ ),+ ]),+ );+ }++ // ─── Quick Match Tab ────────────────────────────────────────++ Widget _buildQuickMatchTab(ColorScheme cs, TextTheme tt) {+ return Column(children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 16, 20, 0),+ child: Column(children: [+ _searchField(_searchTitleCtrl, 'Title', Icons.book_rounded, cs, tt),+ const SizedBox(height: 8),+ _searchField(_searchAuthorCtrl, 'Author (optional)', Icons.person_rounded, cs, tt),+ const SizedBox(height: 10),+ Row(children: [+ Expanded(+ child: Container(+ height: 40,+ padding: const EdgeInsets.symmetric(horizontal: 12),+ decoration: BoxDecoration(+ color: cs.onSurface.withValues(alpha: 0.06),+ borderRadius: BorderRadius.circular(12),+ border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),+ ),+ child: DropdownButtonHideUnderline(+ child: DropdownButton<String>(+ value: _provider,+ isExpanded: true,+ dropdownColor: cs.surfaceContainerHigh,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),+ icon: Icon(Icons.expand_more_rounded, size: 18, color: cs.onSurfaceVariant),+ items: _providers.map((p) => DropdownMenuItem(value: p.$1, child: Text(p.$2))).toList(),+ onChanged: (v) { if (v != null) setState(() => _provider = v); },+ ),+ ),+ ),+ ),+ const SizedBox(width: 10),+ SizedBox(+ height: 40,+ child: FilledButton.icon(+ onPressed: _isSearching ? null : _doSearch,+ icon: _isSearching+ ? SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: cs.onPrimary))+ : const Icon(Icons.search_rounded, size: 18),+ label: const Text('Search'),+ style: FilledButton.styleFrom(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))),+ ),+ ),+ ]),+ ]),+ ),+ const SizedBox(height: 12),+ Divider(color: cs.onSurface.withValues(alpha: 0.08), height: 1),+ Expanded(+ child: _isSearching+ ? Center(child: CircularProgressIndicator(strokeWidth: 2, color: cs.onSurfaceVariant))+ : _searchResults.isEmpty+ ? Center(child: Text(+ _hasSearched ? 'No results found.\nTry adjusting your search or provider.' : 'Search for metadata above',+ textAlign: TextAlign.center,+ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.5)),+ ))+ : ListView.separated(+ padding: EdgeInsets.fromLTRB(16, 12, 16, 16 + MediaQuery.of(context).viewPadding.bottom),+ itemCount: _searchResults.length,+ separatorBuilder: (_, __) => const SizedBox(height: 8),+ itemBuilder: (_, i) => _buildResultCard(_searchResults[i], cs, tt),+ ),+ ),+ ]);+ }++ Widget _searchField(TextEditingController ctrl, String label, IconData icon, ColorScheme cs, TextTheme tt) {+ return SizedBox(+ height: 44,+ child: TextField(+ controller: ctrl,+ onSubmitted: (_) => _doSearch(),+ textInputAction: TextInputAction.search,+ style: tt.bodyMedium,+ decoration: InputDecoration(+ labelText: label,+ labelStyle: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),+ prefixIcon: Icon(icon, size: 18, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),+ filled: true,+ fillColor: cs.onSurface.withValues(alpha: 0.06),+ contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 0),+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: cs.onSurface.withValues(alpha: 0.08))),+ enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: cs.onSurface.withValues(alpha: 0.08))),+ focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: cs.primary.withValues(alpha: 0.5))),+ ),+ ),+ );+ }++ Widget _buildResultCard(Map<String, dynamic> result, ColorScheme cs, TextTheme tt) {+ final book = result['book'] as Map<String, dynamic>? ?? result;+ final title = _safeString(book['title']);+ final author = _safeString(book['author']).isNotEmpty ? _safeString(book['author']) : _safeString(book['authorName']);+ final narrator = _safeString(book['narrator']).isNotEmpty ? _safeString(book['narrator']) : _safeString(book['narratorName']);+ final desc = _safeString(book['description']).replaceAll(RegExp(r'<[^>]*>'), '').trim();+ final cover = _safeString(book['cover']).isNotEmpty ? _safeString(book['cover']) : _safeString(book['image']);+ final year = _safeString(book['publishedYear']).isNotEmpty ? _safeString(book['publishedYear']) : _safeString(book['publishedDate']);+ final publisher = _safeString(book['publisher']);+ final series = _safeString(book['series']);++ return Card(+ elevation: 0,+ color: cs.onSurface.withValues(alpha: 0.05),+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(14),+ side: BorderSide(color: cs.onSurface.withValues(alpha: 0.06)),+ ),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: () => _confirmMatch(result),+ borderRadius: BorderRadius.circular(14),+ child: Padding(+ padding: const EdgeInsets.all(12),+ child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [+ ClipRRect(+ borderRadius: BorderRadius.circular(8),+ child: SizedBox(+ width: 60, height: 60,+ child: cover.isNotEmpty+ ? CachedNetworkImage(imageUrl: cover, fit: BoxFit.cover,+ placeholder: (_, __) => _placeholder(cs),+ errorWidget: (_, __, ___) => _placeholder(cs))+ : _placeholder(cs),+ ),+ ),+ const SizedBox(width: 12),+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(title, maxLines: 2, overflow: TextOverflow.ellipsis,+ style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w600)),+ if (author.isNotEmpty) ...[+ const SizedBox(height: 2),+ Text(author, maxLines: 1, overflow: TextOverflow.ellipsis, style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ ],+ if (narrator.isNotEmpty) ...[+ const SizedBox(height: 1),+ Text('Narrated by $narrator', maxLines: 1, overflow: TextOverflow.ellipsis,+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.6))),+ ],+ const SizedBox(height: 4),+ Wrap(spacing: 6, runSpacing: 4, children: [+ if (year.isNotEmpty) _miniChip(cs, Icons.calendar_today_rounded, year),+ if (publisher.isNotEmpty) _miniChip(cs, Icons.business_rounded, publisher),+ if (series.isNotEmpty) _miniChip(cs, Icons.auto_stories_rounded, series),+ ]),+ if (desc.isNotEmpty) ...[+ const SizedBox(height: 4),+ Text(desc, maxLines: 2, overflow: TextOverflow.ellipsis,+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.5), height: 1.3)),+ ],+ ])),+ const SizedBox(width: 4),+ Icon(Icons.chevron_right_rounded, size: 20, color: cs.onSurfaceVariant.withValues(alpha: 0.4)),+ ]),+ ),+ ),+ );+ }++ Widget _placeholder(ColorScheme cs) {+ return Container(+ color: cs.surfaceContainerHighest,+ child: Center(child: Icon(Icons.headphones_rounded, size: 20, color: cs.onSurfaceVariant.withValues(alpha: 0.4))),+ );+ }++ Widget _miniChip(ColorScheme cs, IconData icon, String text) {+ return Container(+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),+ decoration: BoxDecoration(+ color: cs.onSurface.withValues(alpha: 0.06),+ borderRadius: BorderRadius.circular(8),+ ),+ child: Row(mainAxisSize: MainAxisSize.min, children: [+ Icon(icon, size: 10, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),+ const SizedBox(width: 3),+ Flexible(child: Text(text, overflow: TextOverflow.ellipsis, maxLines: 1,+ style: TextStyle(color: cs.onSurfaceVariant.withValues(alpha: 0.6), fontSize: 10))),+ ]),+ );+ }++ // ─── Custom Tab ─────────────────────────────────────────────++ Widget _buildCustomTab(ColorScheme cs, TextTheme tt) {+ return Column(children: [+ // Save button bar+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 8, 8, 0),+ child: Row(children: [+ const Spacer(),+ FilledButton.icon(+ onPressed: _saving ? null : _saveCustom,+ icon: _saving+ ? SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: cs.onPrimary))+ : const Icon(Icons.check_rounded, size: 18),+ label: const Text('Save'),+ style: FilledButton.styleFrom(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))),+ ),+ ]),+ ),+ const SizedBox(height: 8),+ Expanded(+ child: ListView(+ padding: EdgeInsets.fromLTRB(20, 0, 20, 32 + MediaQuery.of(context).viewInsets.bottom + MediaQuery.of(context).viewPadding.bottom),+ children: [+ _field('Title', _titleCtrl, tt),+ _field('Subtitle', _subtitleCtrl, tt),+ _field('Author', _authorCtrl, tt),+ _field('Narrator', _narratorCtrl, tt),+ Row(children: [+ Expanded(child: _field('Series', _seriesCtrl, tt)),+ const SizedBox(width: 12),+ SizedBox(width: 80, child: _field('#', _seriesSeqCtrl, tt)),+ ]),+ _field('Description', _descCtrl, tt, maxLines: 5),+ _field('Publisher', _publisherCtrl, tt),+ Row(children: [+ Expanded(child: _field('Year', _yearCtrl, tt, keyboardType: TextInputType.number)),+ const SizedBox(width: 12),+ Expanded(child: _field('Language', _languageCtrl, tt)),+ ]),+ _field('Genres', _genresCtrl, tt, hint: 'Comma separated'),+ Row(children: [+ Expanded(child: _field('ASIN', _asinCtrl, tt)),+ const SizedBox(width: 12),+ Expanded(child: _field('ISBN', _isbnCtrl, tt)),+ ]),++ const SizedBox(height: 20),+ Text('Cover Image', style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w600)),+ const SizedBox(height: 8),+ Row(children: [+ Expanded(+ child: TextField(+ controller: _coverUrlCtrl,+ decoration: InputDecoration(+ labelText: 'Cover URL',+ hintText: 'https://...',+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),+ contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),+ isDense: true,+ ),+ style: tt.bodyMedium,+ onChanged: (_) => setState(() => _coverFilePath = null),+ ),+ ),+ const SizedBox(width: 8),+ Text('or', style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ const SizedBox(width: 8),+ FilledButton.tonalIcon(+ onPressed: _pickCoverImage,+ icon: const Icon(Icons.image_rounded, size: 18),+ label: const Text('File'),+ ),+ ]),+ if (_coverFilePath != null)+ Padding(+ padding: const EdgeInsets.only(top: 6),+ child: Row(children: [+ Icon(Icons.check_circle_rounded, size: 14, color: cs.primary),+ const SizedBox(width: 6),+ Expanded(child: Text(+ _coverFilePath!.split('/').last.split('\\').last,+ style: tt.labelSmall?.copyWith(color: cs.primary),+ overflow: TextOverflow.ellipsis,+ )),+ GestureDetector(+ onTap: () => setState(() => _coverFilePath = null),+ child: Icon(Icons.close_rounded, size: 16, color: cs.onSurfaceVariant),+ ),+ ]),+ ),+ ],+ ),+ ),+ ]);+ }++ Widget _field(String label, TextEditingController ctrl, TextTheme tt, {int maxLines = 1, String? hint, TextInputType? keyboardType}) {+ return Padding(+ padding: const EdgeInsets.only(bottom: 12),+ child: TextField(+ controller: ctrl,+ maxLines: maxLines,+ keyboardType: keyboardType,+ decoration: InputDecoration(+ labelText: label,+ hintText: hint,+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),+ contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),+ isDense: true,+ ),+ style: tt.bodyMedium,+ ),+ );+ }+}diff --git a/lib/widgets/metadata_lookup_sheet.dart b/lib/widgets/metadata_lookup_sheet.dartindex 9b9811b1..4ee25bab 100644--- a/lib/widgets/metadata_lookup_sheet.dart+++ b/lib/widgets/metadata_lookup_sheet.dart@@ -5,13 +5,15 @@ import '../services/api_service.dart';import '../services/metadata_override_service.dart';/// Bottom sheet that lets users search for book metadata via the ABS server-/// and pick a result to store as a local override.+/// and pick a result to store as a local override, or manually edit fields.class MetadataLookupSheet extends StatefulWidget {final String itemId;final ApiService api;final String initialTitle;final String initialAuthor;final VoidCallback onApplied;+ /// Current metadata so the Custom tab can pre-fill fields.+ final Map<String, dynamic>? currentMetadata;const MetadataLookupSheet({super.key,@@ -20,13 +22,18 @@ class MetadataLookupSheet extends StatefulWidget {required this.initialTitle,required this.initialAuthor,required this.onApplied,+ this.currentMetadata,});@overrideState<MetadataLookupSheet> createState() => _MetadataLookupSheetState();}-class _MetadataLookupSheetState extends State<MetadataLookupSheet> {+class _MetadataLookupSheetState extends State<MetadataLookupSheet>+ with SingleTickerProviderStateMixin {+ late final TabController _tabCtrl;++ // Search tabfinal _titleController = TextEditingController();final _authorController = TextEditingController();List<Map<String, dynamic>> _results = [];@@ -35,6 +42,20 @@ class _MetadataLookupSheetState extends State<MetadataLookupSheet> {String _provider = 'audible';Timer? _debounce;+ // Custom tab+ late final TextEditingController _cTitleCtrl;+ late final TextEditingController _cAuthorCtrl;+ late final TextEditingController _cNarratorCtrl;+ late final TextEditingController _cDescCtrl;+ late final TextEditingController _cPublisherCtrl;+ late final TextEditingController _cYearCtrl;+ late final TextEditingController _cGenresCtrl;+ late final TextEditingController _cSeriesCtrl;+ late final TextEditingController _cSeriesSeqCtrl;+ late final TextEditingController _cAsinCtrl;+ late final TextEditingController _cIsbnCtrl;+ late final TextEditingController _cCoverUrlCtrl;+static const _providers = [('audible', 'Audible'),('itunes', 'iTunes'),@@ -44,8 +65,35 @@ class _MetadataLookupSheetState extends State<MetadataLookupSheet> {@overridevoid initState() {super.initState();+ _tabCtrl = TabController(length: 2, vsync: this);_titleController.text = widget.initialTitle;_authorController.text = widget.initialAuthor;++ // Pre-fill custom fields from current metadata+ final m = widget.currentMetadata ?? {};+ _cTitleCtrl = TextEditingController(text: m['title'] as String? ?? '');+ _cAuthorCtrl = TextEditingController(text: m['authorName'] as String? ?? '');+ _cNarratorCtrl = TextEditingController(text: m['narratorName'] as String? ?? '');+ _cDescCtrl = TextEditingController(text: m['description'] as String? ?? '');+ _cPublisherCtrl = TextEditingController(text: m['publisher'] as String? ?? '');+ _cYearCtrl = TextEditingController(text: m['publishedYear'] as String? ?? '');+ _cAsinCtrl = TextEditingController(text: m['asin'] as String? ?? '');+ _cIsbnCtrl = TextEditingController(text: m['isbn'] as String? ?? '');+ _cCoverUrlCtrl = TextEditingController();++ final series = m['series'] as List<dynamic>? ?? [];+ if (series.isNotEmpty) {+ final first = series[0] as Map<String, dynamic>;+ _cSeriesCtrl = TextEditingController(text: first['name'] as String? ?? '');+ _cSeriesSeqCtrl = TextEditingController(text: first['sequence'] as String? ?? '');+ } else {+ _cSeriesCtrl = TextEditingController();+ _cSeriesSeqCtrl = TextEditingController();+ }++ final genres = (m['genres'] as List<dynamic>?)?.cast<String>() ?? [];+ _cGenresCtrl = TextEditingController(text: genres.join(', '));+// Auto-search on openif (widget.initialTitle.isNotEmpty) {Future.delayed(const Duration(milliseconds: 300), _doSearch);@@ -54,20 +102,32 @@ class _MetadataLookupSheetState extends State<MetadataLookupSheet> {@overridevoid dispose() {+ _tabCtrl.dispose();_debounce?.cancel();_titleController.dispose();_authorController.dispose();+ _cTitleCtrl.dispose();+ _cAuthorCtrl.dispose();+ _cNarratorCtrl.dispose();+ _cDescCtrl.dispose();+ _cPublisherCtrl.dispose();+ _cYearCtrl.dispose();+ _cGenresCtrl.dispose();+ _cSeriesCtrl.dispose();+ _cSeriesSeqCtrl.dispose();+ _cAsinCtrl.dispose();+ _cIsbnCtrl.dispose();+ _cCoverUrlCtrl.dispose();super.dispose();}+ // ─── Search ─────────────────────────────────────────────────+Future<void> _doSearch() async {final title = _titleController.text.trim();if (title.isEmpty) return;- setState(() {- _isSearching = true;- _hasSearched = true;- });+ setState(() { _isSearching = true; _hasSearched = true; });final results = await widget.api.searchBooks(title: title,@@ -76,56 +136,204 @@ class _MetadataLookupSheetState extends State<MetadataLookupSheet> {);if (mounted) {- setState(() {- _results = results;- _isSearching = false;- });+ setState(() { _results = results; _isSearching = false; });}}- Future<void> _applyResult(Map<String, dynamic> result) async {+ // ─── Apply search result with field picker ──────────────────++ void _showFieldPicker(Map<String, dynamic> result) {final book = result['book'] as Map<String, dynamic>? ?? result;+ // Build available fields from the result+ final fields = <String, String>{};+ void tryAdd(String key, String label, dynamic value) {+ final s = _safeString(value);+ if (s.isNotEmpty) fields[key] = s;+ }++ tryAdd('title', 'Title', book['title']);+ tryAdd('author', 'Author', book['author'] ?? book['authorName']);+ tryAdd('narrator', 'Narrator', book['narrator'] ?? book['narratorName']);+ tryAdd('description', 'Description', book['description']);+ tryAdd('publisher', 'Publisher', book['publisher']);+ tryAdd('publishedYear', 'Year', book['publishedYear'] ?? book['publishedDate']);+ tryAdd('asin', 'ASIN', book['asin']);+ tryAdd('isbn', 'ISBN', book['isbn']);++ final coverUrl = _safeString(book['cover']).isNotEmpty+ ? _safeString(book['cover'])+ : _safeString(book['image']);+ if (coverUrl.isNotEmpty) fields['coverUrl'] = coverUrl;++ final genres = book['genres'] ?? book['tags'];+ if (genres is List && genres.isNotEmpty) {+ fields['genres'] = genres.whereType<String>().join(', ');+ }++ final series = book['series'];+ if (series is String && series.isNotEmpty) {+ fields['series'] = series;+ } else if (series is List && series.isNotEmpty) {+ final first = series[0];+ if (first is Map) fields['series'] = first['name']?.toString() ?? '';+ }++ // All fields selected by default+ final selected = Set<String>.from(fields.keys);++ final labels = {+ 'title': 'Title',+ 'author': 'Author',+ 'narrator': 'Narrator',+ 'description': 'Description',+ 'publisher': 'Publisher',+ 'publishedYear': 'Year',+ 'asin': 'ASIN',+ 'isbn': 'ISBN',+ 'coverUrl': 'Cover',+ 'genres': 'Genres',+ 'series': 'Series',+ };++ showDialog(+ context: context,+ builder: (ctx) {+ return StatefulBuilder(builder: (ctx, setDialogState) {+ final cs = Theme.of(ctx).colorScheme;+ final tt = Theme.of(ctx).textTheme;+ return AlertDialog(+ title: const Text('Choose Fields to Apply'),+ content: SizedBox(+ width: double.maxFinite,+ child: ListView(+ shrinkWrap: true,+ children: fields.entries.map((e) {+ final label = labels[e.key] ?? e.key;+ final preview = e.value.length > 60+ ? '${e.value.replaceAll(RegExp(r'<[^>]*>'), '').substring(0, 57)}...'+ : e.value.replaceAll(RegExp(r'<[^>]*>'), '');+ return CheckboxListTile(+ dense: true,+ contentPadding: EdgeInsets.zero,+ title: Text(label, style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600)),+ subtitle: Text(preview, maxLines: 1, overflow: TextOverflow.ellipsis,+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant)),+ value: selected.contains(e.key),+ onChanged: (v) => setDialogState(() {+ if (v == true) selected.add(e.key); else selected.remove(e.key);+ }),+ );+ }).toList(),+ ),+ ),+ actions: [+ TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('Cancel')),+ FilledButton(+ onPressed: selected.isEmpty ? null : () {+ Navigator.pop(ctx);+ _applySelectedFields(result, selected);+ },+ child: Text('Apply ${selected.length} field${selected.length == 1 ? '' : 's'}'),+ ),+ ],+ );+ });+ },+ );+ }++ Future<void> _applySelectedFields(Map<String, dynamic> result, Set<String> selected) async {+ final book = result['book'] as Map<String, dynamic>? ?? result;final override = <String, dynamic>{};- void addIfPresent(String overrideKey, dynamic value) {- final str = _safeString(value);- if (str.isNotEmpty) {- override[overrideKey] = str;+ void addIfSelected(String key, dynamic value) {+ if (!selected.contains(key)) return;+ final s = _safeString(value);+ if (s.isNotEmpty) override[key] = s;+ }++ addIfSelected('title', book['title']);+ addIfSelected('author', book['author'] ?? book['authorName']);+ addIfSelected('narrator', book['narrator'] ?? book['narratorName']);+ addIfSelected('description', book['description']);+ addIfSelected('publisher', book['publisher']);+ addIfSelected('publishedYear', book['publishedYear'] ?? book['publishedDate']);+ addIfSelected('asin', book['asin']);+ addIfSelected('isbn', book['isbn']);++ if (selected.contains('coverUrl')) {+ final coverRaw = book['cover'] ?? book['image'];+ if (coverRaw is String && coverRaw.isNotEmpty) {+ override['coverUrl'] = coverRaw;}}- addIfPresent('title', book['title']);- addIfPresent('author', book['author'] ?? book['authorName']);- addIfPresent('narrator', book['narrator'] ?? book['narratorName']);- addIfPresent('description', book['description']);- addIfPresent('publisher', book['publisher']);- addIfPresent('publishedYear', book['publishedYear'] ?? book['publishedDate']);- addIfPresent('asin', book['asin']);- addIfPresent('isbn', book['isbn']);-- // Cover — use raw string value- final coverRaw = book['cover'] ?? book['image'];- if (coverRaw is String && coverRaw.isNotEmpty) {- override['coverUrl'] = coverRaw;+ if (selected.contains('genres')) {+ final genres = book['genres'] ?? book['tags'];+ if (genres is List && genres.isNotEmpty) {+ override['genres'] = genres;+ }}- // Genres/tags- final genres = book['genres'] ?? book['tags'];- if (genres is List && genres.isNotEmpty) {- override['genres'] = genres;+ if (selected.contains('series')) {+ final series = book['series'];+ if (series is List && series.isNotEmpty) {+ override['series'] = series;+ } else if (series is String && series.isNotEmpty) {+ override['series'] = [+ {'name': series, 'sequence': _safeString(book['volumeNumber'] ?? book['sequence'])}+ ];+ }}- // Series — can be a String, List, or nested object- final series = book['series'];- if (series is List && series.isNotEmpty) {- override['series'] = series;- } else if (series is String && series.isNotEmpty) {+ await MetadataOverrideService().save(widget.itemId, override);++ if (mounted) {+ widget.onApplied();+ Navigator.pop(context);+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(+ content: Text('${selected.length} field${selected.length == 1 ? '' : 's'} saved locally'),+ behavior: SnackBarBehavior.floating,+ duration: const Duration(seconds: 2),+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),+ ));+ }+ }++ // ─── Custom save ────────────────────────────────────────────++ Future<void> _saveCustom() async {+ final override = <String, dynamic>{};++ void addIfNotEmpty(String key, String value) {+ if (value.isNotEmpty) override[key] = value;+ }++ addIfNotEmpty('title', _cTitleCtrl.text.trim());+ addIfNotEmpty('author', _cAuthorCtrl.text.trim());+ addIfNotEmpty('narrator', _cNarratorCtrl.text.trim());+ addIfNotEmpty('description', _cDescCtrl.text.trim());+ addIfNotEmpty('publisher', _cPublisherCtrl.text.trim());+ addIfNotEmpty('publishedYear', _cYearCtrl.text.trim());+ addIfNotEmpty('asin', _cAsinCtrl.text.trim());+ addIfNotEmpty('isbn', _cIsbnCtrl.text.trim());+ addIfNotEmpty('coverUrl', _cCoverUrlCtrl.text.trim());++ final genresText = _cGenresCtrl.text.trim();+ if (genresText.isNotEmpty) {+ override['genres'] = genresText.split(',').map((g) => g.trim()).where((g) => g.isNotEmpty).toList();+ }++ final seriesName = _cSeriesCtrl.text.trim();+ if (seriesName.isNotEmpty) {override['series'] = [- {'name': series, 'sequence': _safeString(book['volumeNumber'] ?? book['sequence'])}+ {'name': seriesName, 'sequence': _cSeriesSeqCtrl.text.trim()},];}+ if (override.isEmpty) return;+await MetadataOverrideService().save(widget.itemId, override);if (mounted) {@@ -140,6 +348,8 @@ class _MetadataLookupSheetState extends State<MetadataLookupSheet> {}}+ // ─── Build ──────────────────────────────────────────────────+@overrideWidget build(BuildContext context) {final cs = Theme.of(context).colorScheme;@@ -150,160 +360,192 @@ class _MetadataLookupSheetState extends State<MetadataLookupSheet> {color: Theme.of(context).bottomSheetTheme.backgroundColor,borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),),- child: Column(- children: [- // Drag handle- Center(- child: Container(- width: 40,- height: 4,- margin: const EdgeInsets.only(top: 12, bottom: 8),- decoration: BoxDecoration(- color: Colors.white24,- borderRadius: BorderRadius.circular(2),- ),- ),- ),+ child: Column(children: [+ // Drag handle+ Center(child: Container(width: 40, height: 4, margin: const EdgeInsets.only(top: 12, bottom: 8),+ decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(2)))),++ // Header+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 4, 20, 8),+ child: Row(children: [+ Icon(Icons.manage_search_rounded, size: 22, color: cs.primary),+ const SizedBox(width: 8),+ Text('Local Metadata', style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600, color: Colors.white)),+ ]),+ ),- // Header- Padding(- padding: const EdgeInsets.fromLTRB(20, 4, 20, 12),- child: Row(- children: [- Icon(Icons.manage_search_rounded, size: 22, color: cs.primary),- const SizedBox(width: 8),- Text('Lookup Metadata',- style: tt.titleMedium?.copyWith(- fontWeight: FontWeight.w600, color: Colors.white)),- ],- ),+ // Tabs+ TabBar(+ controller: _tabCtrl,+ labelColor: cs.primary,+ unselectedLabelColor: Colors.white54,+ indicatorColor: cs.primary,+ tabs: const [+ Tab(text: 'Quick Match'),+ Tab(text: 'Custom'),+ ],+ ),++ // Tab content+ Expanded(+ child: TabBarView(+ controller: _tabCtrl,+ children: [+ _buildSearchTab(cs, tt),+ _buildCustomTab(cs, tt),+ ],),+ ),+ ]),+ );+ }- // Search fields- Padding(- padding: const EdgeInsets.symmetric(horizontal: 20),- child: Column(- children: [- _buildField(- controller: _titleController,- label: 'Title',- icon: Icons.book_rounded,- cs: cs,- onSubmitted: (_) => _doSearch(),+ // ─── Search Tab ─────────────────────────────────────────────++ Widget _buildSearchTab(ColorScheme cs, TextTheme tt) {+ return Column(children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),+ child: Column(children: [+ _buildField(controller: _titleController, label: 'Title', icon: Icons.book_rounded, cs: cs, onSubmitted: (_) => _doSearch()),+ const SizedBox(height: 8),+ _buildField(controller: _authorController, label: 'Author (optional)', icon: Icons.person_rounded, cs: cs, onSubmitted: (_) => _doSearch()),+ const SizedBox(height: 10),+ Row(children: [+ Expanded(+ child: Container(+ height: 40,+ padding: const EdgeInsets.symmetric(horizontal: 12),+ decoration: BoxDecoration(+ color: Colors.white.withValues(alpha: 0.06),+ borderRadius: BorderRadius.circular(12),+ border: Border.all(color: Colors.white.withValues(alpha: 0.08)),),- const SizedBox(height: 8),- _buildField(- controller: _authorController,- label: 'Author (optional)',- icon: Icons.person_rounded,- cs: cs,- onSubmitted: (_) => _doSearch(),+ child: DropdownButtonHideUnderline(+ child: DropdownButton<String>(+ value: _provider,+ isExpanded: true,+ dropdownColor: cs.surfaceContainerHigh,+ style: tt.bodySmall?.copyWith(color: Colors.white70),+ icon: Icon(Icons.expand_more_rounded, size: 18, color: Colors.white38),+ items: _providers.map((p) => DropdownMenuItem(value: p.$1, child: Text(p.$2))).toList(),+ onChanged: (v) { if (v != null) setState(() => _provider = v); },+ ),),- const SizedBox(height: 10),- Row(- children: [- // Provider selector- Expanded(- child: Container(- height: 40,- padding: const EdgeInsets.symmetric(horizontal: 12),- decoration: BoxDecoration(- color: Colors.white.withValues(alpha: 0.06),- borderRadius: BorderRadius.circular(12),- border: Border.all(- color: Colors.white.withValues(alpha: 0.08)),- ),- child: DropdownButtonHideUnderline(- child: DropdownButton<String>(- value: _provider,- isExpanded: true,- dropdownColor: Theme.of(context).colorScheme.surfaceContainerHigh,- style: tt.bodySmall- ?.copyWith(color: Colors.white70),- icon: Icon(Icons.expand_more_rounded,- size: 18, color: Colors.white38),- items: _providers.map((p) {- return DropdownMenuItem(- value: p.$1,- child: Text(p.$2),- );- }).toList(),- onChanged: (v) {- if (v != null) setState(() => _provider = v);- },- ),- ),- ),- ),- const SizedBox(width: 10),- // Search button- SizedBox(- height: 40,- child: FilledButton.icon(- onPressed: _isSearching ? null : _doSearch,- icon: _isSearching- ? SizedBox(- width: 16,- height: 16,- child: CircularProgressIndicator(- strokeWidth: 2, color: cs.onPrimary),- )- : const Icon(Icons.search_rounded, size: 18),- label: const Text('Search'),- style: FilledButton.styleFrom(- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(12)),- ),- ),- ),- ],- ),- ],+ ),),+ const SizedBox(width: 10),+ SizedBox(+ height: 40,+ child: FilledButton.icon(+ onPressed: _isSearching ? null : _doSearch,+ icon: _isSearching+ ? SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: cs.onPrimary))+ : const Icon(Icons.search_rounded, size: 18),+ label: const Text('Search'),+ style: FilledButton.styleFrom(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))),+ ),+ ),+ ]),+ ]),+ ),+ const SizedBox(height: 12),+ Divider(color: Colors.white.withValues(alpha: 0.08), height: 1),++ Expanded(+ child: _isSearching+ ? const Center(child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white24))+ : _results.isEmpty+ ? Center(child: Text(+ _hasSearched ? 'No results found.\nTry adjusting your search or provider.' : 'Search for metadata above',+ textAlign: TextAlign.center,+ style: tt.bodyMedium?.copyWith(color: Colors.white38),+ ))+ : ListView.separated(+ padding: EdgeInsets.fromLTRB(16, 12, 16, 16 + MediaQuery.of(context).viewPadding.bottom),+ itemCount: _results.length,+ separatorBuilder: (_, __) => const SizedBox(height: 8),+ itemBuilder: (_, i) => _buildResultCard(_results[i], cs, tt),+ ),+ ),+ ]);+ }++ // ─── Custom Tab ─────────────────────────────────────────────++ Widget _buildCustomTab(ColorScheme cs, TextTheme tt) {+ return Column(children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 8, 8, 0),+ child: Row(children: [+ Text('Override local display', style: tt.labelSmall?.copyWith(color: Colors.white38)),+ const Spacer(),+ FilledButton.icon(+ onPressed: _saveCustom,+ icon: const Icon(Icons.check_rounded, size: 18),+ label: const Text('Save'),+ style: FilledButton.styleFrom(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))),),- const SizedBox(height: 12),- Divider(color: Colors.white.withValues(alpha: 0.08), height: 1),-- // Results- Expanded(- child: _isSearching- ? const Center(- child: CircularProgressIndicator(- strokeWidth: 2, color: Colors.white24))- : _results.isEmpty- ? Center(- child: Text(- _hasSearched- ? 'No results found.\nTry adjusting your search or provider.'- : 'Search for metadata above',- textAlign: TextAlign.center,- style: tt.bodyMedium- ?.copyWith(color: Colors.white38),- ),- )- : ListView.separated(- padding: EdgeInsets.fromLTRB(- 16,- 12,- 16,- 16 +- MediaQuery.of(context)- .viewPadding- .bottom),- itemCount: _results.length,- separatorBuilder: (_, __) =>- const SizedBox(height: 8),- itemBuilder: (context, index) {- return _buildResultCard(- _results[index], cs, tt);- },- ),- ),- ],+ ]),+ ),+ const SizedBox(height: 8),+ Expanded(+ child: ListView(+ padding: EdgeInsets.fromLTRB(20, 0, 20, 32 + MediaQuery.of(context).viewInsets.bottom + MediaQuery.of(context).viewPadding.bottom),+ children: [+ _customField('Title', _cTitleCtrl, tt),+ _customField('Author', _cAuthorCtrl, tt),+ _customField('Narrator', _cNarratorCtrl, tt),+ Row(children: [+ Expanded(child: _customField('Series', _cSeriesCtrl, tt)),+ const SizedBox(width: 12),+ SizedBox(width: 80, child: _customField('#', _cSeriesSeqCtrl, tt)),+ ]),+ _customField('Description', _cDescCtrl, tt, maxLines: 4),+ _customField('Publisher', _cPublisherCtrl, tt),+ Row(children: [+ Expanded(child: _customField('Year', _cYearCtrl, tt)),+ const SizedBox(width: 12),+ Expanded(child: _customField('ASIN', _cAsinCtrl, tt)),+ ]),+ Row(children: [+ Expanded(child: _customField('ISBN', _cIsbnCtrl, tt)),+ const SizedBox(width: 12),+ Expanded(child: _customField('Genres', _cGenresCtrl, tt, hint: 'Comma separated')),+ ]),+ _customField('Cover URL', _cCoverUrlCtrl, tt, hint: 'https://...'),+ ],+ ),+ ),+ ]);+ }++ Widget _customField(String label, TextEditingController ctrl, TextTheme tt, {int maxLines = 1, String? hint}) {+ return Padding(+ padding: const EdgeInsets.only(bottom: 12),+ child: TextField(+ controller: ctrl,+ maxLines: maxLines,+ style: const TextStyle(color: Colors.white, fontSize: 14),+ decoration: InputDecoration(+ labelText: label,+ hintText: hint,+ labelStyle: TextStyle(color: Colors.white38, fontSize: 13),+ hintStyle: TextStyle(color: Colors.white24, fontSize: 13),+ filled: true,+ fillColor: Colors.white.withValues(alpha: 0.06),+ contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: Colors.white.withValues(alpha: 0.08))),+ enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: Colors.white.withValues(alpha: 0.08))),+ focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.5))),+ ),),);}+ // ─── Shared widgets ─────────────────────────────────────────+Widget _buildField({required TextEditingController controller,required String label,@@ -320,34 +562,19 @@ class _MetadataLookupSheetState extends State<MetadataLookupSheet> {style: const TextStyle(color: Colors.white, fontSize: 14),decoration: InputDecoration(labelText: label,- labelStyle: TextStyle(- color: Colors.white38, fontSize: 13),+ labelStyle: TextStyle(color: Colors.white38, fontSize: 13),prefixIcon: Icon(icon, size: 18, color: Colors.white30),filled: true,fillColor: Colors.white.withValues(alpha: 0.06),- contentPadding:- const EdgeInsets.symmetric(horizontal: 12, vertical: 0),- border: OutlineInputBorder(- borderRadius: BorderRadius.circular(12),- borderSide: BorderSide(- color: Colors.white.withValues(alpha: 0.08)),- ),- enabledBorder: OutlineInputBorder(- borderRadius: BorderRadius.circular(12),- borderSide: BorderSide(- color: Colors.white.withValues(alpha: 0.08)),- ),- focusedBorder: OutlineInputBorder(- borderRadius: BorderRadius.circular(12),- borderSide:- BorderSide(color: cs.primary.withValues(alpha: 0.5)),- ),+ contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 0),+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: Colors.white.withValues(alpha: 0.08))),+ enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: Colors.white.withValues(alpha: 0.08))),+ focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: cs.primary.withValues(alpha: 0.5))),),),);}- /// Safely extract a string from a value that might be a String, List, or other type.String _safeString(dynamic value) {if (value == null) return '';if (value is String) return value;@@ -355,25 +582,14 @@ class _MetadataLookupSheetState extends State<MetadataLookupSheet> {return value.toString();}- Widget _buildResultCard(- Map<String, dynamic> result, ColorScheme cs, TextTheme tt) {+ Widget _buildResultCard(Map<String, dynamic> result, ColorScheme cs, TextTheme tt) {final book = result['book'] as Map<String, dynamic>? ?? result;final title = _safeString(book['title']);- final author = _safeString(book['author']).isNotEmpty- ? _safeString(book['author'])- : _safeString(book['authorName']);- final narrator = _safeString(book['narrator']).isNotEmpty- ? _safeString(book['narrator'])- : _safeString(book['narratorName']);- final desc = _safeString(book['description'])- .replaceAll(RegExp(r'<[^>]*>'), '')- .trim();- final cover = _safeString(book['cover']).isNotEmpty- ? _safeString(book['cover'])- : _safeString(book['image']);- final year = _safeString(book['publishedYear']).isNotEmpty- ? _safeString(book['publishedYear'])- : _safeString(book['publishedDate']);+ final author = _safeString(book['author']).isNotEmpty ? _safeString(book['author']) : _safeString(book['authorName']);+ final narrator = _safeString(book['narrator']).isNotEmpty ? _safeString(book['narrator']) : _safeString(book['narratorName']);+ final desc = _safeString(book['description']).replaceAll(RegExp(r'<[^>]*>'), '').trim();+ final cover = _safeString(book['cover']).isNotEmpty ? _safeString(book['cover']) : _safeString(book['image']);+ final year = _safeString(book['publishedYear']).isNotEmpty ? _safeString(book['publishedYear']) : _safeString(book['publishedDate']);final publisher = _safeString(book['publisher']);final series = _safeString(book['series']);@@ -386,130 +602,59 @@ class _MetadataLookupSheetState extends State<MetadataLookupSheet> {),clipBehavior: Clip.antiAlias,child: InkWell(- onTap: () => _showConfirmation(result, cs, tt),+ onTap: () => _showFieldPicker(result),borderRadius: BorderRadius.circular(14),child: Padding(padding: const EdgeInsets.all(12),- child: Row(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- // Cover thumbnail- ClipRRect(- borderRadius: BorderRadius.circular(8),- child: SizedBox(- width: 60,- height: 60,- child: cover.isNotEmpty- ? CachedNetworkImage(- imageUrl: cover,- fit: BoxFit.cover,- placeholder: (_, __) => _placeholder(cs),- errorWidget: (_, __, ___) => _placeholder(cs),- )- : _placeholder(cs),- ),- ),- const SizedBox(width: 12),- // Info- Expanded(- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(title,- maxLines: 2,- overflow: TextOverflow.ellipsis,- style: tt.titleSmall?.copyWith(- fontWeight: FontWeight.w600,- color: Colors.white)),- if (author.isNotEmpty) ...[- const SizedBox(height: 2),- Text(author,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: tt.bodySmall- ?.copyWith(color: Colors.white60)),- ],- if (narrator.isNotEmpty) ...[- const SizedBox(height: 1),- Text('Narrated by $narrator',- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: tt.labelSmall- ?.copyWith(color: Colors.white38)),- ],- const SizedBox(height: 4),- Wrap(- spacing: 6,- runSpacing: 4,- children: [- if (year.isNotEmpty)- _miniChip(Icons.calendar_today_rounded, year),- if (publisher.isNotEmpty)- _miniChip(Icons.business_rounded, publisher),- if (series.isNotEmpty)- _miniChip(Icons.auto_stories_rounded, series),- ],- ),- if (desc.isNotEmpty) ...[- const SizedBox(height: 4),- Text(desc,- maxLines: 2,- overflow: TextOverflow.ellipsis,- style: tt.labelSmall?.copyWith(- color: Colors.white30, height: 1.3)),- ],- ],- ),+ child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [+ ClipRRect(+ borderRadius: BorderRadius.circular(8),+ child: SizedBox(+ width: 60, height: 60,+ child: cover.isNotEmpty+ ? CachedNetworkImage(imageUrl: cover, fit: BoxFit.cover,+ placeholder: (_, __) => _placeholder(cs),+ errorWidget: (_, __, ___) => _placeholder(cs))+ : _placeholder(cs),),- const SizedBox(width: 4),- Icon(Icons.chevron_right_rounded,- size: 20, color: Colors.white24),- ],- ),+ ),+ const SizedBox(width: 12),+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(title, maxLines: 2, overflow: TextOverflow.ellipsis,+ style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w600, color: Colors.white)),+ if (author.isNotEmpty) ...[+ const SizedBox(height: 2),+ Text(author, maxLines: 1, overflow: TextOverflow.ellipsis, style: tt.bodySmall?.copyWith(color: Colors.white60)),+ ],+ if (narrator.isNotEmpty) ...[+ const SizedBox(height: 1),+ Text('Narrated by $narrator', maxLines: 1, overflow: TextOverflow.ellipsis,+ style: tt.labelSmall?.copyWith(color: Colors.white38)),+ ],+ const SizedBox(height: 4),+ Wrap(spacing: 6, runSpacing: 4, children: [+ if (year.isNotEmpty) _miniChip(Icons.calendar_today_rounded, year),+ if (publisher.isNotEmpty) _miniChip(Icons.business_rounded, publisher),+ if (series.isNotEmpty) _miniChip(Icons.auto_stories_rounded, series),+ ]),+ if (desc.isNotEmpty) ...[+ const SizedBox(height: 4),+ Text(desc, maxLines: 2, overflow: TextOverflow.ellipsis,+ style: tt.labelSmall?.copyWith(color: Colors.white30, height: 1.3)),+ ],+ ])),+ const SizedBox(width: 4),+ Icon(Icons.chevron_right_rounded, size: 20, color: Colors.white24),+ ]),),),);}- void _showConfirmation(- Map<String, dynamic> result, ColorScheme cs, TextTheme tt) {- final book = result['book'] as Map<String, dynamic>? ?? result;- final title = book['title'] as String? ?? 'Unknown';- final author =- book['author'] as String? ?? book['authorName'] as String? ?? '';-- showDialog(- context: context,- builder: (ctx) => AlertDialog(- title: const Text('Apply This Metadata?'),- content: Text(- 'This will fill in any missing metadata for this book using:\n\n'- '"$title"${author.isNotEmpty ? ' by $author' : ''}\n\n'- 'Only empty fields will be filled — existing server data won\'t be overwritten. '- 'This is stored locally on your device.'),- actions: [- TextButton(- onPressed: () => Navigator.pop(ctx),- child: const Text('Cancel')),- FilledButton(- onPressed: () {- Navigator.pop(ctx);- _applyResult(result);- },- child: const Text('Apply')),- ],- ),- );- }-Widget _placeholder(ColorScheme cs) {return Container(color: cs.surfaceContainerHighest,- child: Center(- child: Icon(Icons.headphones_rounded,- size: 20,- color: cs.onSurfaceVariant.withValues(alpha: 0.4)),- ),+ child: Center(child: Icon(Icons.headphones_rounded, size: 20, color: cs.onSurfaceVariant.withValues(alpha: 0.4))),);}@@ -520,20 +665,12 @@ class _MetadataLookupSheetState extends State<MetadataLookupSheet> {color: Colors.white.withValues(alpha: 0.06),borderRadius: BorderRadius.circular(8),),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- Icon(icon, size: 10, color: Colors.white30),- const SizedBox(width: 3),- Flexible(- child: Text(text,- overflow: TextOverflow.ellipsis,- maxLines: 1,- style: const TextStyle(- color: Colors.white38, fontSize: 10)),- ),- ],- ),+ child: Row(mainAxisSize: MainAxisSize.min, children: [+ Icon(icon, size: 10, color: Colors.white30),+ const SizedBox(width: 3),+ Flexible(child: Text(text, overflow: TextOverflow.ellipsis, maxLines: 1,+ style: const TextStyle(color: Colors.white38, fontSize: 10))),+ ]),);}}