Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add author edit + quick match for admins

Barnabas9ec6377b6193
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index 0b27549b..30d59013 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -1652,5 +1652,22 @@
"tipsRestored": "Tips restored",
"resetSpeedPresets": "Reset speed presets",
"resetSpeedPresetsSubtitle": "Restore the default playback speed chips",
- "speedPresetsReset": "Speed presets reset"
+ "speedPresetsReset": "Speed presets reset",
+
+ "editAuthor": "Edit author",
+ "authorName": "Name",
+ "authorImage": "Author image",
+ "authorRemoveImage": "Remove image",
+ "authorRemoveImageTitle": "Remove author image?",
+ "authorRemoveImageConfirm": "This deletes the image on the server.",
+ "authorImageRemoved": "Image removed",
+ "authorImageFailed": "Couldn't update author image",
+ "authorUpdated": "Author updated",
+ "authorUpdateFailed": "Couldn't update author",
+ "authorMatched": "Author updated from match",
+ "authorNoMatchFound": "No match found",
+ "authorMergedInto": "Merged into {name}",
+ "@authorMergedInto": { "placeholders": { "name": { "type": "String" } } },
+ "authorQuickMatchHint": "Pull name, ASIN, description and image from Audible for the chosen region.",
+ "region": "Region"
}
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index dabfe6a5..22cc711a 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -8201,6 +8201,96 @@ abstract class AppLocalizations {
/// In en, this message translates to:
/// **'Speed presets reset'**
String get speedPresetsReset;
+
+ /// No description provided for @editAuthor.
+ ///
+ /// In en, this message translates to:
+ /// **'Edit author'**
+ String get editAuthor;
+
+ /// No description provided for @authorName.
+ ///
+ /// In en, this message translates to:
+ /// **'Name'**
+ String get authorName;
+
+ /// No description provided for @authorImage.
+ ///
+ /// In en, this message translates to:
+ /// **'Author image'**
+ String get authorImage;
+
+ /// No description provided for @authorRemoveImage.
+ ///
+ /// In en, this message translates to:
+ /// **'Remove image'**
+ String get authorRemoveImage;
+
+ /// No description provided for @authorRemoveImageTitle.
+ ///
+ /// In en, this message translates to:
+ /// **'Remove author image?'**
+ String get authorRemoveImageTitle;
+
+ /// No description provided for @authorRemoveImageConfirm.
+ ///
+ /// In en, this message translates to:
+ /// **'This deletes the image on the server.'**
+ String get authorRemoveImageConfirm;
+
+ /// No description provided for @authorImageRemoved.
+ ///
+ /// In en, this message translates to:
+ /// **'Image removed'**
+ String get authorImageRemoved;
+
+ /// No description provided for @authorImageFailed.
+ ///
+ /// In en, this message translates to:
+ /// **'Couldn\'t update author image'**
+ String get authorImageFailed;
+
+ /// No description provided for @authorUpdated.
+ ///
+ /// In en, this message translates to:
+ /// **'Author updated'**
+ String get authorUpdated;
+
+ /// No description provided for @authorUpdateFailed.
+ ///
+ /// In en, this message translates to:
+ /// **'Couldn\'t update author'**
+ String get authorUpdateFailed;
+
+ /// No description provided for @authorMatched.
+ ///
+ /// In en, this message translates to:
+ /// **'Author updated from match'**
+ String get authorMatched;
+
+ /// No description provided for @authorNoMatchFound.
+ ///
+ /// In en, this message translates to:
+ /// **'No match found'**
+ String get authorNoMatchFound;
+
+ /// No description provided for @authorMergedInto.
+ ///
+ /// In en, this message translates to:
+ /// **'Merged into {name}'**
+ String authorMergedInto(String name);
+
+ /// No description provided for @authorQuickMatchHint.
+ ///
+ /// In en, this message translates to:
+ /// **'Pull name, ASIN, description and image from Audible for the chosen region.'**
+ String get authorQuickMatchHint;
+
+ /// No description provided for @region.
+ ///
+ /// In en, this message translates to:
+ /// **'Region'**
+ String get region;
}
class _AppLocalizationsDelegate
diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart
index 68ed169d..3268c721 100644
--- a/lib/l10n/app_localizations_de.dart
+++ b/lib/l10n/app_localizations_de.dart
@@ -4805,4 +4805,53 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get speedPresetsReset =>
'Geschwindigkeits-Voreinstellungen zurückgesetzt';
+
+ @override
+ String get editAuthor => 'Edit author';
+
+ @override
+ String get authorName => 'Name';
+
+ @override
+ String get authorImage => 'Author image';
+
+ @override
+ String get authorRemoveImage => 'Remove image';
+
+ @override
+ String get authorRemoveImageTitle => 'Remove author image?';
+
+ @override
+ String get authorRemoveImageConfirm =>
+ 'This deletes the image on the server.';
+
+ @override
+ String get authorImageRemoved => 'Image removed';
+
+ @override
+ String get authorImageFailed => 'Couldn\'t update author image';
+
+ @override
+ String get authorUpdated => 'Author updated';
+
+ @override
+ String get authorUpdateFailed => 'Couldn\'t update author';
+
+ @override
+ String get authorMatched => 'Author updated from match';
+
+ @override
+ String get authorNoMatchFound => 'No match found';
+
+ @override
+ String authorMergedInto(String name) {
+ return 'Merged into $name';
+ }
+
+ @override
+ String get authorQuickMatchHint =>
+ 'Pull name, ASIN, description and image from Audible for the chosen region.';
+
+ @override
+ String get region => 'Region';
}
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index 94deb490..ec52aaf4 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -4746,4 +4746,53 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get speedPresetsReset => 'Speed presets reset';
+
+ @override
+ String get editAuthor => 'Edit author';
+
+ @override
+ String get authorName => 'Name';
+
+ @override
+ String get authorImage => 'Author image';
+
+ @override
+ String get authorRemoveImage => 'Remove image';
+
+ @override
+ String get authorRemoveImageTitle => 'Remove author image?';
+
+ @override
+ String get authorRemoveImageConfirm =>
+ 'This deletes the image on the server.';
+
+ @override
+ String get authorImageRemoved => 'Image removed';
+
+ @override
+ String get authorImageFailed => 'Couldn\'t update author image';
+
+ @override
+ String get authorUpdated => 'Author updated';
+
+ @override
+ String get authorUpdateFailed => 'Couldn\'t update author';
+
+ @override
+ String get authorMatched => 'Author updated from match';
+
+ @override
+ String get authorNoMatchFound => 'No match found';
+
+ @override
+ String authorMergedInto(String name) {
+ return 'Merged into $name';
+ }
+
+ @override
+ String get authorQuickMatchHint =>
+ 'Pull name, ASIN, description and image from Audible for the chosen region.';
+
+ @override
+ String get region => 'Region';
}
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index 9ddb23e4..bd1756ea 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -4667,4 +4667,53 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get speedPresetsReset => '速度预设已重置';
+
+ @override
+ String get editAuthor => 'Edit author';
+
+ @override
+ String get authorName => 'Name';
+
+ @override
+ String get authorImage => 'Author image';
+
+ @override
+ String get authorRemoveImage => 'Remove image';
+
+ @override
+ String get authorRemoveImageTitle => 'Remove author image?';
+
+ @override
+ String get authorRemoveImageConfirm =>
+ 'This deletes the image on the server.';
+
+ @override
+ String get authorImageRemoved => 'Image removed';
+
+ @override
+ String get authorImageFailed => 'Couldn\'t update author image';
+
+ @override
+ String get authorUpdated => 'Author updated';
+
+ @override
+ String get authorUpdateFailed => 'Couldn\'t update author';
+
+ @override
+ String get authorMatched => 'Author updated from match';
+
+ @override
+ String get authorNoMatchFound => 'No match found';
+
+ @override
+ String authorMergedInto(String name) {
+ return 'Merged into $name';
+ }
+
+ @override
+ String get authorQuickMatchHint =>
+ 'Pull name, ASIN, description and image from Audible for the chosen region.';
+
+ @override
+ String get region => 'Region';
}
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index 6f43c9b7..e0416a69 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -596,6 +596,94 @@ class ApiService {
return null;
}
+ /// Update an author's editable fields (admin/root only).
+ /// Returns one of:
+ /// { ok: true, author: {...} } - normal update succeeded
+ /// { ok: true, merged: { id, name } } - name matched another author, this one was merged
+ /// { ok: false } - request failed
+ /// PATCH /api/authors/:id
+ Future<Map<String, dynamic>> updateAuthor(
+ String authorId, {
+ String? name,
+ String? description,
+ String? asin,
+ String? imagePath,
+ }) async {
+ try {
+ final body = <String, dynamic>{};
+ if (name != null) body['name'] = name;
+ if (description != null) body['description'] = description;
+ if (asin != null) body['asin'] = asin;
+ if (imagePath != null) body['imagePath'] = imagePath;
+ final r = await _authPatch(
+ Uri.parse('$_cleanBaseUrl/api/authors/$authorId'),
+ body: jsonEncode(body),
+ );
+ debugPrint('[API] updateAuthor $authorId -> ${r.statusCode}: ${r.body}');
+ if (r.statusCode == 200) {
+ final data = jsonDecode(r.body) as Map<String, dynamic>;
+ if (data['merged'] != null) {
+ return {'ok': true, 'merged': data['merged']};
+ }
+ return {'ok': true, 'author': data['author'] ?? data};
+ }
+ } catch (e) { debugPrint('updateAuthor error: $e'); }
+ return {'ok': false};
+ }
+
+ /// Quick-match an author against the configured provider (Audible).
+ /// Server fetches name/asin/description/image, updates the author server-side,
+ /// and returns the updated author. Returns null if no match or on error.
+ /// GET /api/authors/:id/match?q=...&region=...
+ Future<Map<String, dynamic>?> matchAuthor(
+ String authorId, {
+ required String q,
+ String region = 'us',
+ }) async {
+ try {
+ final url = '$_cleanBaseUrl/api/authors/$authorId/match'
+ '?q=${Uri.encodeQueryComponent(q)}'
+ '&region=${Uri.encodeQueryComponent(region)}';
+ final r = await _authGet(Uri.parse(url));
+ debugPrint('[API] matchAuthor $authorId -> ${r.statusCode}: ${r.body}');
+ if (r.statusCode == 200) {
+ final data = jsonDecode(r.body) as Map<String, dynamic>;
+ // Server returns the updated author directly, or { author: {...} }
+ if (data['author'] is Map) return data['author'] as Map<String, dynamic>;
+ if (data.containsKey('updated')) return data;
+ return data;
+ }
+ } catch (e) { debugPrint('matchAuthor error: $e'); }
+ return null;
+ }
+
+ /// Set the author image from a remote URL.
+ /// POST /api/authors/:id/image body: { url }
+ Future<bool> updateAuthorImageFromUrl(String authorId, String url) async {
+ try {
+ final r = await _authPost(
+ Uri.parse('$_cleanBaseUrl/api/authors/$authorId/image'),
+ body: jsonEncode({'url': url}),
+ timeout: const Duration(seconds: 30),
+ );
+ debugPrint('[API] updateAuthorImageFromUrl $authorId -> ${r.statusCode}');
+ return r.statusCode == 200;
+ } catch (e) { debugPrint('updateAuthorImageFromUrl error: $e'); }
+ return false;
+ }
+
+ /// Remove the author's image.
+ /// DELETE /api/authors/:id/image
+ Future<bool> deleteAuthorImage(String authorId) async {
+ try {
+ final r = await _authDelete(
+ Uri.parse('$_cleanBaseUrl/api/authors/$authorId/image'),
+ );
+ return r.statusCode == 200;
+ } catch (e) { debugPrint('deleteAuthorImage error: $e'); }
+ return false;
+ }
+
/// Get books in a specific series using the filter API.
/// Filter format: series.<base64(seriesId)>
Future<List<dynamic>> getBooksBySeries(
diff --git a/lib/widgets/author_books_sheet.dart b/lib/widgets/author_books_sheet.dart
index 98e2a452..49a0df7b 100644
--- a/lib/widgets/author_books_sheet.dart
+++ b/lib/widgets/author_books_sheet.dart
@@ -7,6 +7,7 @@ import '../l10n/app_localizations.dart';
import '../providers/auth_provider.dart';
import '../providers/library_provider.dart';
import '../services/audio_player_service.dart';
+import 'edit_author_sheet.dart';
import 'library_grid_tiles.dart';
import 'library_search_results.dart';
import 'series_books_sheet.dart';
@@ -62,6 +63,8 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {
bool _isLoading = true;
String? _description;
String? _imageUrl;
+ String? _asin;
+ late String _displayName;
bool _descExpanded = false;
_AuthorLayout _layout = _AuthorLayout.list;
bool _groupBySeries = true;
@@ -69,6 +72,7 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {
@override
void initState() {
super.initState();
+ _displayName = widget.authorName;
_loadViewSettings();
_loadAuthorAndBooks();
}
@@ -96,9 +100,14 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {
setState(() {
if (authorData != null) {
_description = authorData['description'] as String?;
+ _asin = authorData['asin'] as String?;
+ final updatedName = authorData['name'] as String?;
+ if (updatedName != null && updatedName.isNotEmpty) _displayName = updatedName;
if (authorData['imagePath'] != null && (authorData['imagePath'] as String).isNotEmpty) {
final ts = (authorData['updatedAt'] as num?)?.toInt();
_imageUrl = api.getAuthorImageUrl(widget.authorId, updatedAt: ts);
+ } else {
+ _imageUrl = null;
}
// libraryItems from the author endpoint include full metadata with series info
final rawItems = authorData['libraryItems'] as List<dynamic>? ?? [];
@@ -126,13 +135,15 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {
final tt = Theme.of(context).textTheme;
final l = AppLocalizations.of(context)!;
final lib = context.read<LibraryProvider>();
+ final auth = context.watch<AuthProvider>();
final headers = lib.mediaHeaders;
+ final canEdit = auth.isRoot && !lib.isOffline;
if (_isLoading) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- _buildHeader(cs, tt, headers, l),
+ _buildHeader(cs, tt, headers, l, canEdit: canEdit),
const Expanded(child: Center(child: CircularProgressIndicator())),
],
);
@@ -144,7 +155,7 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {
// Header + description are always at the top
final headerWidgets = <Widget>[
- _buildHeader(cs, tt, headers, l),
+ _buildHeader(cs, tt, headers, l, canEdit: canEdit),
if (hasDesc) _buildDescription(cs, tt, l),
if (_books.isNotEmpty) _buildViewModeBar(cs, l),
];
@@ -538,7 +549,7 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {
);
}
- Widget _buildHeader(ColorScheme cs, TextTheme tt, Map<String, String> headers, AppLocalizations l) {
+ Widget _buildHeader(ColorScheme cs, TextTheme tt, Map<String, String> headers, AppLocalizations l, {bool canEdit = false}) {
return Padding(
padding: const EdgeInsets.fromLTRB(24, 0, 24, 12),
child: Row(
@@ -568,7 +579,7 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 4),
- Text(widget.authorName,
+ Text(_displayName,
style: tt.titleLarge?.copyWith(fontWeight: FontWeight.w600)),
if (_books.isNotEmpty)
Padding(
@@ -581,11 +592,45 @@ class _AuthorBooksSheetState extends State<AuthorBooksSheet> {
],
),
),
+ if (canEdit)
+ IconButton(
+ icon: Icon(Icons.edit_rounded, size: 20, color: cs.onSurfaceVariant),
+ tooltip: l.editAuthor,
+ onPressed: _openEditAuthor,
+ ),
],
),
);
}
+ void _openEditAuthor() {
+ showEditAuthorSheet(
+ context,
+ authorId: widget.authorId,
+ currentName: _displayName,
+ currentDescription: _description,
+ currentAsin: _asin,
+ currentImageUrl: _imageUrl,
+ onUpdated: () {
+ if (mounted) {
+ setState(() => _isLoading = true);
+ _loadAuthorAndBooks();
+ }
+ },
+ onMerged: (mergedIntoId, mergedIntoName) {
+ // The current author was merged into another; close this sheet.
+ if (!mounted) return;
+ final l = AppLocalizations.of(context)!;
+ Navigator.of(context).pop();
+ showOverlayToast(
+ context,
+ l.authorMergedInto(mergedIntoName),
+ icon: Icons.merge_type_rounded,
+ );
+ },
+ );
+ }
+
Widget _buildDescription(ColorScheme cs, TextTheme tt, AppLocalizations l) {
return Padding(
padding: const EdgeInsets.fromLTRB(24, 0, 24, 12),
diff --git a/lib/widgets/edit_author_sheet.dart b/lib/widgets/edit_author_sheet.dart
new file mode 100644
index 00000000..29409932
--- /dev/null
+++ b/lib/widgets/edit_author_sheet.dart
@@ -0,0 +1,507 @@
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+import 'package:cached_network_image/cached_network_image.dart';
+import '../l10n/app_localizations.dart';
+import '../providers/auth_provider.dart';
+
+/// Opens a full-screen editor for an author (root admin only).
+/// Two tabs:
+/// Quick Match - asks the server to pull name / asin / description / image
+/// from the configured provider (Audible) for the given region.
+/// Custom - manual editing of name / asin / description / image URL.
+///
+/// [onUpdated] is called after a successful save/match so the parent sheet can
+/// reload its data. [onMerged] is called when the server reports the author was
+/// merged into another author (because the new name matched an existing one);
+/// the parent should close itself since this author id no longer exists.
+void showEditAuthorSheet(
+ BuildContext context, {
+ required String authorId,
+ required String currentName,
+ String? currentDescription,
+ String? currentAsin,
+ String? currentImageUrl,
+ required VoidCallback onUpdated,
+ required void Function(String mergedIntoId, String mergedIntoName) onMerged,
+}) {
+ 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) => _EditAuthorContent(
+ authorId: authorId,
+ currentName: currentName,
+ currentDescription: currentDescription,
+ currentAsin: currentAsin,
+ currentImageUrl: currentImageUrl,
+ scrollController: sc,
+ onUpdated: onUpdated,
+ onMerged: onMerged,
+ ),
+ ),
+ );
+}
+
+class _EditAuthorContent extends StatefulWidget {
+ final String authorId;
+ final String currentName;
+ final String? currentDescription;
+ final String? currentAsin;
+ final String? currentImageUrl;
+ final ScrollController scrollController;
+ final VoidCallback onUpdated;
+ final void Function(String mergedIntoId, String mergedIntoName) onMerged;
+
+ const _EditAuthorContent({
+ required this.authorId,
+ required this.currentName,
+ required this.currentDescription,
+ required this.currentAsin,
+ required this.currentImageUrl,
+ required this.scrollController,
+ required this.onUpdated,
+ required this.onMerged,
+ });
+
+ @override
+ State<_EditAuthorContent> createState() => _EditAuthorContentState();
+}
+
+class _EditAuthorContentState extends State<_EditAuthorContent>
+ with SingleTickerProviderStateMixin {
+ late final TabController _tabCtrl;
+
+ // Custom edit controllers
+ late final TextEditingController _nameCtrl;
+ late final TextEditingController _asinCtrl;
+ late final TextEditingController _descCtrl;
+ late final TextEditingController _imageUrlCtrl;
+
+ // Quick match
+ late final TextEditingController _searchCtrl;
+ String _region = 'us';
+ bool _matching = false;
+ Map<String, dynamic>? _matchResult;
+ bool _matchEmpty = false;
+
+ bool _saving = false;
+
+ // Audible region codes - matches ABS web client
+ static const _regions = ['us', 'ca', 'uk', 'au', 'fr', 'de', 'jp', 'it', 'in', 'es'];
+
+ @override
+ void initState() {
+ super.initState();
+ _tabCtrl = TabController(length: 2, vsync: this);
+ _nameCtrl = TextEditingController(text: widget.currentName);
+ _asinCtrl = TextEditingController(text: widget.currentAsin ?? '');
+ _descCtrl = TextEditingController(text: widget.currentDescription ?? '');
+ _imageUrlCtrl = TextEditingController();
+ _searchCtrl = TextEditingController(text: widget.currentName);
+ }
+
+ @override
+ void dispose() {
+ _tabCtrl.dispose();
+ _nameCtrl.dispose();
+ _asinCtrl.dispose();
+ _descCtrl.dispose();
+ _imageUrlCtrl.dispose();
+ _searchCtrl.dispose();
+ super.dispose();
+ }
+
+ // ─── Quick Match ────────────────────────────────────────────
+
+ Future<void> _runMatch() async {
+ final q = _searchCtrl.text.trim();
+ if (q.isEmpty) return;
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) return;
+
+ setState(() { _matching = true; _matchResult = null; _matchEmpty = false; });
+
+ final result = await api.matchAuthor(widget.authorId, q: q, region: _region);
+
+ if (!mounted) return;
+ setState(() {
+ _matching = false;
+ if (result == null || result.isEmpty) {
+ _matchEmpty = true;
+ } else {
+ _matchResult = result;
+ }
+ });
+
+ if (result != null && result.isNotEmpty) {
+ // The match endpoint already updates the author server-side, so notify parent.
+ widget.onUpdated();
+ _showSnack(AppLocalizations.of(context)!.authorMatched);
+ } else {
+ _showSnack(AppLocalizations.of(context)!.authorNoMatchFound);
+ }
+ }
+
+ // ─── Custom Save ────────────────────────────────────────────
+
+ Future<void> _saveCustom() async {
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) return;
+
+ setState(() => _saving = true);
+
+ final name = _nameCtrl.text.trim();
+ final asin = _asinCtrl.text.trim();
+ final desc = _descCtrl.text.trim();
+ final imageUrl = _imageUrlCtrl.text.trim();
+
+ final result = await api.updateAuthor(
+ widget.authorId,
+ name: name,
+ asin: asin,
+ description: desc,
+ );
+
+ if (!mounted) return;
+
+ if (result['ok'] != true) {
+ setState(() => _saving = false);
+ _showSnack(AppLocalizations.of(context)!.authorUpdateFailed);
+ return;
+ }
+
+ // Handle "merged into another author" response
+ if (result['merged'] is Map) {
+ final merged = result['merged'] as Map<String, dynamic>;
+ setState(() => _saving = false);
+ final mergedId = merged['id'] as String? ?? '';
+ final mergedName = merged['name'] as String? ?? '';
+ if (mounted) Navigator.of(context).pop();
+ widget.onMerged(mergedId, mergedName);
+ return;
+ }
+
+ // If the user provided an image URL, upload it after the patch.
+ if (imageUrl.isNotEmpty) {
+ final imgOk = await api.updateAuthorImageFromUrl(widget.authorId, imageUrl);
+ if (!imgOk && mounted) {
+ setState(() => _saving = false);
+ _showSnack(AppLocalizations.of(context)!.authorImageFailed);
+ return;
+ }
+ }
+
+ widget.onUpdated();
+
+ if (mounted) {
+ setState(() => _saving = false);
+ Navigator.of(context).pop();
+ _showSnack(AppLocalizations.of(context)!.authorUpdated);
+ }
+ }
+
+ Future<void> _removeImage() async {
+ final api = context.read<AuthProvider>().apiService;
+ if (api == null) return;
+ final l = AppLocalizations.of(context)!;
+
+ final confirm = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: Text(l.authorRemoveImageTitle),
+ content: Text(l.authorRemoveImageConfirm),
+ actions: [
+ TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text(l.cancel)),
+ FilledButton(
+ onPressed: () => Navigator.pop(ctx, true),
+ style: FilledButton.styleFrom(backgroundColor: Colors.red.shade600),
+ child: Text(l.remove),
+ ),
+ ],
+ ),
+ );
+ if (confirm != true) return;
+
+ setState(() => _saving = true);
+ final ok = await api.deleteAuthorImage(widget.authorId);
+ if (!mounted) return;
+ setState(() => _saving = false);
+ if (ok) {
+ widget.onUpdated();
+ _showSnack(l.authorImageRemoved);
+ } else {
+ _showSnack(l.authorImageFailed);
+ }
+ }
+
+ void _showSnack(String text) {
+ ScaffoldMessenger.of(context)
+ ..clearSnackBars()
+ ..showSnackBar(SnackBar(
+ content: Text(text),
+ behavior: SnackBarBehavior.floating,
+ duration: const Duration(seconds: 2),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ ));
+ }
+
+ // ─── Build ──────────────────────────────────────────────────
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final l = AppLocalizations.of(context)!;
+
+ return Container(
+ decoration: BoxDecoration(
+ color: cs.surface,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ child: Column(children: [
+ 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(l.editAuthor, style: tt.titleLarge?.copyWith(fontWeight: FontWeight.w700)),
+ const Spacer(),
+ if (_saving || _matching)
+ const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2)),
+ ]),
+ ),
+ const SizedBox(height: 8),
+ TabBar(
+ controller: _tabCtrl,
+ labelColor: cs.primary,
+ unselectedLabelColor: cs.onSurfaceVariant,
+ indicatorColor: cs.primary,
+ tabs: [
+ Tab(text: l.quickMatch),
+ Tab(text: l.custom),
+ ],
+ ),
+ Expanded(
+ child: TabBarView(
+ controller: _tabCtrl,
+ children: [
+ _buildQuickMatchTab(cs, tt, l),
+ _buildCustomTab(cs, tt, l),
+ ],
+ ),
+ ),
+ ]),
+ );
+ }
+
+ // ─── Quick Match Tab ────────────────────────────────────────
+
+ Widget _buildQuickMatchTab(ColorScheme cs, TextTheme tt, AppLocalizations l) {
+ return ListView(
+ controller: widget.scrollController,
+ padding: EdgeInsets.fromLTRB(20, 16, 20, 32 + MediaQuery.of(context).viewInsets.bottom + MediaQuery.of(context).viewPadding.bottom),
+ children: [
+ Text(l.authorQuickMatchHint, style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ const SizedBox(height: 12),
+ _searchField(_searchCtrl, l.authorName, Icons.person_rounded, cs, tt),
+ const SizedBox(height: 10),
+ Row(children: [
+ Expanded(
+ child: Container(
+ height: 44,
+ 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: _region,
+ isExpanded: true,
+ dropdownColor: cs.surfaceContainerHigh,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),
+ icon: Icon(Icons.expand_more_rounded, size: 18, color: cs.onSurfaceVariant),
+ items: _regions.map((r) => DropdownMenuItem(
+ value: r,
+ child: Text('${l.region}: ${r.toUpperCase()}'),
+ )).toList(),
+ onChanged: (v) { if (v != null) setState(() => _region = v); },
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(width: 10),
+ SizedBox(
+ height: 44,
+ child: FilledButton.icon(
+ onPressed: _matching ? null : _runMatch,
+ icon: _matching
+ ? SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: cs.onPrimary))
+ : const Icon(Icons.search_rounded, size: 18),
+ label: Text(l.quickMatch),
+ style: FilledButton.styleFrom(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))),
+ ),
+ ),
+ ]),
+ const SizedBox(height: 20),
+ if (_matchResult != null) _matchResultCard(_matchResult!, cs, tt, l)
+ else if (_matchEmpty) Padding(
+ padding: const EdgeInsets.only(top: 24),
+ child: Center(child: Text(
+ l.authorNoMatchFound,
+ textAlign: TextAlign.center,
+ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.6)),
+ )),
+ ),
+ ],
+ );
+ }
+
+ Widget _matchResultCard(Map<String, dynamic> result, ColorScheme cs, TextTheme tt, AppLocalizations l) {
+ final name = result['name'] as String? ?? '';
+ final asin = result['asin'] as String? ?? '';
+ final desc = (result['description'] as String? ?? '').replaceAll(RegExp(r'<[^>]*>'), '').trim();
+ final imageUrl = result['imageUrl'] as String? ?? result['image'] as String? ?? '';
+
+ 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: Padding(
+ padding: const EdgeInsets.all(14),
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ if (imageUrl.isNotEmpty)
+ ClipOval(
+ child: SizedBox(
+ width: 60, height: 60,
+ child: CachedNetworkImage(imageUrl: imageUrl, fit: BoxFit.cover,
+ placeholder: (_, __) => Container(color: cs.surfaceContainerHighest),
+ errorWidget: (_, __, ___) => Container(color: cs.surfaceContainerHighest,
+ child: Icon(Icons.person_rounded, size: 28, color: cs.onSurfaceVariant)),
+ ),
+ ),
+ )
+ else
+ Container(
+ width: 60, height: 60,
+ decoration: BoxDecoration(shape: BoxShape.circle, color: cs.surfaceContainerHighest),
+ child: Icon(Icons.person_rounded, size: 28, color: cs.onSurfaceVariant),
+ ),
+ const SizedBox(width: 12),
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ if (name.isNotEmpty) Text(name, style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w600)),
+ if (asin.isNotEmpty) Padding(
+ padding: const EdgeInsets.only(top: 4),
+ child: Text('ASIN: $asin', style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant)),
+ ),
+ ])),
+ ]),
+ if (desc.isNotEmpty) ...[
+ const SizedBox(height: 10),
+ Text(desc, style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant, height: 1.4)),
+ ],
+ ]),
+ ),
+ );
+ }
+
+ Widget _searchField(TextEditingController ctrl, String label, IconData icon, ColorScheme cs, TextTheme tt) {
+ return SizedBox(
+ height: 44,
+ child: TextField(
+ controller: ctrl,
+ textInputAction: TextInputAction.search,
+ onSubmitted: (_) => _runMatch(),
+ 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))),
+ ),
+ ),
+ );
+ }
+
+ // ─── Custom Tab ─────────────────────────────────────────────
+
+ Widget _buildCustomTab(ColorScheme cs, TextTheme tt, AppLocalizations l) {
+ return Column(children: [
+ 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: Text(l.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(l.authorName, _nameCtrl, tt),
+ _field(l.asinLabel, _asinCtrl, tt),
+ _field(l.descriptionLabel, _descCtrl, tt, maxLines: 6),
+ const SizedBox(height: 12),
+ Text(l.authorImage, style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w600)),
+ const SizedBox(height: 8),
+ _field(l.coverUrlLabel, _imageUrlCtrl, tt, hint: l.coverUrlHint),
+ if (widget.currentImageUrl != null && widget.currentImageUrl!.isNotEmpty)
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TextButton.icon(
+ onPressed: _saving ? null : _removeImage,
+ icon: const Icon(Icons.delete_outline_rounded, size: 18),
+ label: Text(l.authorRemoveImage),
+ style: TextButton.styleFrom(foregroundColor: cs.error),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ]);
+ }
+
+ Widget _field(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,
+ 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,
+ ),
+ );
+ }
+}