From be72fd128674f51d4b4ba004544c316a7f1ed106 Mon Sep 17 00:00:00 2001 From: DelLevin-Home Date: Mon, 13 Jul 2026 23:57:08 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E7=BC=96=E8=BE=91=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E7=95=8C=E9=9D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/main.dart | 19 + lib/pages/book/book_add_page.dart | 391 ++++++++++++ lib/pages/book/book_detail_page.dart | 457 ++++++++++++- lib/pages/book/book_tab_page.dart | 10 +- lib/pages/epub_reader/reader_renderer.dart | 52 +- lib/pages/epub_reader/reader_screen.dart | 14 +- lib/pages/epub_reader/reader_webview.dart | 21 + lib/pages/game/game_add_page.dart | 429 +++++++++++++ lib/pages/game/game_detail_page.dart | 670 +++++++++++++++++++- lib/pages/game/game_tab_page.dart | 10 +- lib/pages/home/home_page.dart | 18 +- lib/pages/movies/movie_add_page.dart | 398 ++++++++++++ lib/pages/movies/movie_detail_page.dart | 628 +++++++++++++++++- lib/pages/movies/movie_tab_page.dart | 10 +- lib/pages/note/note_add_page.dart | 510 +++++++++++++++ lib/pages/note/note_detail_page.dart | 390 +++++++++++- lib/pages/note/note_tab_page.dart | 10 +- lib/providers/app_provider.dart | 39 ++ lib/services/epub/epub_webview_handler.dart | 42 +- lib/services/epub/reader_scripts.dart | 41 +- lib/services/epub/web/reader_api.dart | 27 + lib/widgets/add_type_selector.dart | 100 +++ 22 files changed, 4241 insertions(+), 45 deletions(-) create mode 100644 lib/pages/book/book_add_page.dart create mode 100644 lib/pages/game/game_add_page.dart create mode 100644 lib/pages/movies/movie_add_page.dart create mode 100644 lib/pages/note/note_add_page.dart create mode 100644 lib/widgets/add_type_selector.dart diff --git a/lib/main.dart b/lib/main.dart index ded2644..79f5248 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -9,6 +9,7 @@ import 'package:dynamic_color/dynamic_color.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:package_info_plus/package_info_plus.dart'; import 'package:sqflite_common_ffi/sqflite_ffi.dart'; +import 'package:flutter_inappwebview/flutter_inappwebview.dart'; import 'pages/home/home_page.dart'; import 'utils/theme/app_theme.dart'; import 'utils/app_router.dart'; @@ -19,12 +20,30 @@ import 'providers/app_provider.dart'; final RouteObserver> routeObserver = RouteObserver>(); +/// Windows 桌面版 WebView2 环境,注册 epub:// 自定义协议 +WebViewEnvironment? windowsWebViewEnvironment; + void main() async { WidgetsFlutterBinding.ensureInitialized(); // Windows 桌面:使用 FFI 初始化 sqflite if (Platform.isWindows) { sqfliteFfiInit(); databaseFactory = databaseFactoryFfi; + // 注册 epub:// 自定义协议,使 WebView2 能拦截该协议的请求 + try { + windowsWebViewEnvironment = await WebViewEnvironment.create(settings: + WebViewEnvironmentSettings(customSchemeRegistrations: [ + CustomSchemeRegistration( + scheme: 'epub', + hasAuthorityComponent: true, + treatAsSecure: true, + ), + ]), + ); + debugPrint('[Startup] WebViewEnvironment created successfully'); + } catch (e) { + debugPrint('[Startup] WebViewEnvironment 初始化失败: $e'); + } } await UserPrefs.init(); final appProvider = AppProvider(); diff --git a/lib/pages/book/book_add_page.dart b/lib/pages/book/book_add_page.dart new file mode 100644 index 0000000..39cbdba --- /dev/null +++ b/lib/pages/book/book_add_page.dart @@ -0,0 +1,391 @@ +import 'dart:io'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:path/path.dart' as p; +import 'package:provider/provider.dart'; +import 'package:http/http.dart' as http; +import 'package:uuid/uuid.dart'; +import '../../widgets/fade_in_local_image.dart'; +import '../../providers/app_provider.dart'; +import '../../models/data_models.dart'; +import '../../utils/toast_util.dart'; +import '../../utils/image_path_helper.dart'; +import '../../widgets/genre_selector_page.dart'; + +class BookAddPage extends StatefulWidget { + final VoidCallback? onCancel; + final String? initialStatus; + const BookAddPage({super.key, this.onCancel, this.initialStatus}); + + @override + State createState() => _BookAddPageState(); +} + +class _BookAddPageState extends State { + final _formKey = GlobalKey(); + final ImagePicker _picker = ImagePicker(); + late TextEditingController _titleCtrl; + late TextEditingController _summaryCtrl; + late TextEditingController _ratingCtrl; + late TextEditingController _publisherCtrl; + late TextEditingController _isbnCtrl; + List _authors = []; + List _translators = []; + List _alternateTitles = []; + List _genres = []; + String? _coverPath; + String _status = 'want_to_read'; + DateTime? _publishDate; + DateTime? _startDate; + DateTime? _finishDate; + bool _isDownloading = false; + String? _tempId; + + @override + void initState() { + super.initState(); + _tempId = const Uuid().v4(); + _status = widget.initialStatus ?? 'want_to_read'; + _titleCtrl = TextEditingController(); + _summaryCtrl = TextEditingController(); + _ratingCtrl = TextEditingController(); + _publisherCtrl = TextEditingController(); + _isbnCtrl = TextEditingController(); + } + + @override + void dispose() { + _titleCtrl.dispose(); + _summaryCtrl.dispose(); + _ratingCtrl.dispose(); + _publisherCtrl.dispose(); + _isbnCtrl.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final colors = Theme.of(context).colorScheme; + final hasCover = _coverPath != null && _coverPath!.isNotEmpty; + return Scaffold( + backgroundColor: colors.surface, + body: Form( + key: _formKey, + child: Column( + children: [ + // 顶栏 + Container(height: 48, + decoration: BoxDecoration(color: colors.surface, + border: Border(bottom: BorderSide(color: colors.outlineVariant, width: 0.5))), + child: Row(children: [ + IconButton(icon: Icon(Icons.close, color: colors.onSurface, size: 18), + onPressed: () => widget.onCancel?.call()), + Expanded(child: Text('添加书籍', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: colors.onSurface))), + FilledButton.icon(onPressed: _save, + icon: const Icon(Icons.check, size: 16), label: const Text('保存'), + style: FilledButton.styleFrom(padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)))), + const SizedBox(width: 12), + ]), + ), + // 主体:左封面+右表单 + Expanded( + child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ + // 左侧 + Container(width: 240, padding: const EdgeInsets.all(20), child: Column(children: [ + GestureDetector(onTap: _showCoverOptions, child: Container( + width: 200, height: 280, + decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(12)), + clipBehavior: Clip.antiAlias, + child: Stack(alignment: Alignment.center, children: [ + hasCover ? FadeInLocalImage(path: _coverPath, fit: BoxFit.cover) + : Column(mainAxisAlignment: MainAxisAlignment.center, children: [ + Icon(Icons.image_outlined, size: 32, color: colors.onSurface.withValues(alpha: 0.25)), + const SizedBox(height: 8), + Text('点击添加封面', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.35))), + ]), + if (_isDownloading) Container(color: Colors.black.withValues(alpha: 0.4), + child: const CircularProgressIndicator(strokeWidth: 2, color: Colors.white)), + ]), + )), + if (hasCover) Padding(padding: const EdgeInsets.only(top: 8), + child: GestureDetector(onTap: () => setState(() => _coverPath = null), + child: Text('移除封面', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.5))))), + const SizedBox(height: 20), + _label('状态', colors), const SizedBox(height: 6), + Container(padding: const EdgeInsets.all(2), + decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(6)), + child: Wrap(spacing: 0, runSpacing: 4, children: [ + _statusChip('想读', 'want_to_read', colors), _statusChip('在读', 'reading', colors), + _statusChip('已读', 'read', colors), _statusChip('弃读', 'abandoned', colors), + ])), + const SizedBox(height: 16), + _label('评分', colors), const SizedBox(height: 6), + _buildRatingRow(colors), + ])), + // 右侧表单 + Expanded(child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(0, 20, 24, 80), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + _field('名称', _titleCtrl, hint: '书籍名称', required: true), const SizedBox(height: 16), + _chipField('别名', _alternateTitles, onTap: () async { + final r = await GenreSelectorPage.show(context: context, title: '添加别名', existingTags: [], initialSelected: _alternateTitles, hint: '输入别名'); + if (r != null) setState(() => _alternateTitles = r); + }), const SizedBox(height: 16), + _chipField('作者', _authors, onTap: () async { + final p = context.read(); final d = p.books.map((b) => b.authors).toList(); + final r = await GenreSelectorPage.show(context: context, title: '选择作者', existingTagsFuture: compute(_collectUnique, d), initialSelected: _authors, hint: '如:余华'); + if (r != null) setState(() => _authors = r); + }), const SizedBox(height: 16), + _chipField('译者', _translators, onTap: () async { + final p = context.read(); final d = p.books.map((b) => b.translators).toList(); + final r = await GenreSelectorPage.show(context: context, title: '选择译者', existingTagsFuture: compute(_collectUnique, d), initialSelected: _translators, hint: '如:李继宏'); + if (r != null) setState(() => _translators = r); + }), const SizedBox(height: 16), + _chipField('类型', _genres, onTap: () async { + final p = context.read(); + final tags = await p.getTags('book_genre', excludeHidden: true); + final names = tags.map((t) => t['name'] as String).toList(); + if (!mounted) return; + final r = await GenreSelectorPage.show(context: context, title: '选择类型', existingTags: names, initialSelected: _genres, hint: '如:小说、历史'); + if (r != null) setState(() => _genres = r); + }), const SizedBox(height: 16), + _field('出版社', _publisherCtrl, hint: '出版社名称'), const SizedBox(height: 16), + _field('ISBN', _isbnCtrl, hint: 'ISBN编号'), const SizedBox(height: 16), + Row(children: [ + Expanded(child: _dateField('出版日期', _publishDate, (d) => setState(() => _publishDate = d))), + const SizedBox(width: 12), + Expanded(child: _dateField('开始日期', _startDate, (d) => setState(() => _startDate = d), clearable: true)), + const SizedBox(width: 12), + Expanded(child: _dateField('读完日期', _finishDate, (d) => setState(() => _finishDate = d), clearable: true)), + ]), const SizedBox(height: 16), + _label('简介', colors), const SizedBox(height: 6), + Container(constraints: const BoxConstraints(minHeight: 120), + child: TextFormField(controller: _summaryCtrl, maxLines: null, + style: TextStyle(fontSize: 14, color: colors.onSurface, height: 1.6), + decoration: InputDecoration(hintText: '写下书籍简介...', hintStyle: TextStyle(color: colors.onSurface.withValues(alpha: 0.25)), + filled: true, fillColor: colors.surfaceContainerHighest.withValues(alpha: 0.5), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none), contentPadding: const EdgeInsets.all(12)))), + ]), + )), + ]), + ), + ], + ), + ), + ); + } + + Widget _label(String l, ColorScheme c) => Text(l, style: TextStyle(fontSize: 12, color: c.onSurface.withValues(alpha: 0.4))); + Widget _statusChip(String label, String value, ColorScheme c) { + final sel = _status == value; + return GestureDetector(onTap: () => setState(() => _status = value), + child: Container(padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6), + decoration: BoxDecoration(color: sel ? c.surface : Colors.transparent, borderRadius: BorderRadius.circular(6), + boxShadow: sel ? [BoxShadow(color: c.onSurface.withValues(alpha: 0.03), blurRadius: 4, offset: const Offset(0, 2))] : null), + child: Text(label, style: TextStyle(fontSize: 13, fontWeight: sel ? FontWeight.w500 : FontWeight.normal, + color: sel ? c.onSurface : c.onSurface.withValues(alpha: 0.4))))); + } + + Widget _buildRatingRow(ColorScheme colors) { + return Row(children: [ + ...List.generate(5, (i) { + final sv = i + 1; final cr = double.tryParse(_ratingCtrl.text) ?? 0; final sr = cr / 2; + final f = sv <= sr; final h = sv == sr.ceil() && sr % 1 != 0; + return GestureDetector(onTap: () => setState(() => _ratingCtrl.text = (sv * 2).toString()), + child: Padding(padding: const EdgeInsets.symmetric(horizontal: 1), + child: Icon(h ? Icons.star_half : (f ? Icons.star : Icons.star_border), size: 20, color: (f || h) ? const Color(0xFFFFB800) : colors.outline))); + }), + const SizedBox(width: 8), + Container(width: 48, height: 28, decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(6)), + child: TextFormField(controller: _ratingCtrl, keyboardType: const TextInputType.numberWithOptions(decimal: true), + textAlign: TextAlign.center, inputFormatters: [_RatingInputFormatter()], + style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: colors.onSurface), + decoration: InputDecoration(hintText: '0-10', hintStyle: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.25)), + border: InputBorder.none, contentPadding: const EdgeInsets.symmetric(vertical: 6), isDense: true), + onChanged: (_) => setState(() {}))), + if (_ratingCtrl.text.isNotEmpty) ...[ + const SizedBox(width: 4), + GestureDetector(onTap: () => setState(() => _ratingCtrl.clear()), + child: Icon(Icons.close, size: 14, color: colors.onSurface.withValues(alpha: 0.3))), + ], + ]); + } + + Widget _field(String label, TextEditingController ctrl, {String hint = '', bool required = false}) { + final c = Theme.of(context).colorScheme; + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(required ? '$label *' : label, style: TextStyle(fontSize: 12, color: c.onSurface.withValues(alpha: 0.4))), + const SizedBox(height: 6), + TextFormField(controller: ctrl, style: TextStyle(fontSize: 14, color: c.onSurface), + validator: required ? (v) => (v == null || v.trim().isEmpty) ? '请输入$label' : null : null, + decoration: InputDecoration(hintText: hint, hintStyle: TextStyle(color: c.onSurface.withValues(alpha: 0.25)), + filled: true, fillColor: c.surfaceContainerHighest.withValues(alpha: 0.5), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), isDense: true)), + ]); + } + + Widget _chipField(String label, List chips, {required VoidCallback onTap}) { + final c = Theme.of(context).colorScheme; + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(label, style: TextStyle(fontSize: 12, color: c.onSurface.withValues(alpha: 0.4))), + const SizedBox(height: 6), + GestureDetector(onTap: onTap, + child: Container(width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), + decoration: BoxDecoration(color: c.surfaceContainerHighest.withValues(alpha: 0.5), borderRadius: BorderRadius.circular(8)), + child: chips.isEmpty + ? Text('点击选择$label', style: TextStyle(fontSize: 14, color: c.onSurface.withValues(alpha: 0.25))) + : Wrap(spacing: 4, runSpacing: 4, children: chips.map((e) => Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration(color: c.surface, borderRadius: BorderRadius.circular(4)), + child: Text(e, style: TextStyle(fontSize: 12, color: c.onSurface)))).toList()))), + ]); + } + + Widget _dateField(String label, DateTime? date, ValueChanged onChanged, {bool clearable = false}) { + final c = Theme.of(context).colorScheme; final has = date != null; + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(label, style: TextStyle(fontSize: 12, color: c.onSurface.withValues(alpha: 0.4))), + const SizedBox(height: 6), + GestureDetector(onTap: () async { + final picked = await showDatePicker(context: context, initialDate: date ?? DateTime.now(), + firstDate: DateTime(1900), lastDate: DateTime.now().add(const Duration(days: 365 * 5))); + if (picked != null) onChanged(picked); + }, child: Container(width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: BoxDecoration(color: c.surfaceContainerHighest.withValues(alpha: 0.5), borderRadius: BorderRadius.circular(8)), + child: Row(children: [ + Icon(Icons.calendar_today_outlined, size: 14, color: c.onSurface.withValues(alpha: 0.4)), + const SizedBox(width: 8), + Text(has ? '${date!.year}.${date!.month.toString().padLeft(2, '0')}.${date!.day.toString().padLeft(2, '0')}' : '选择日期', + style: TextStyle(fontSize: 14, color: has ? c.onSurface : c.onSurface.withValues(alpha: 0.25))), + const Spacer(), + if (clearable && has) GestureDetector(onTap: () => onChanged(null), + child: Icon(Icons.close, size: 14, color: c.onSurface.withValues(alpha: 0.3))), + ]))), + ]); + } + + void _showCoverOptions() { + final c = Theme.of(context).colorScheme; + showModalBottomSheet(context: context, backgroundColor: c.surface, + shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(16))), + builder: (ctx) => SafeArea(child: Padding(padding: const EdgeInsets.symmetric(vertical: 16), + child: Column(mainAxisSize: MainAxisSize.min, children: [ + Container(width: 40, height: 4, decoration: BoxDecoration(color: c.outline, borderRadius: BorderRadius.circular(2))), + const SizedBox(height: 20), + Padding(padding: const EdgeInsets.symmetric(horizontal: 24), child: Align(alignment: Alignment.centerLeft, + child: Text('添加封面', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: c.onSurface)))), + const SizedBox(height: 16), + ListTile(leading: Icon(Icons.photo_library_outlined, color: c.onSurface.withValues(alpha: 0.6)), + title: Text('从相册选择'), onTap: () { Navigator.pop(ctx); _pickCover(); }), + ListTile(leading: Icon(Icons.link_outlined, color: c.onSurface.withValues(alpha: 0.6)), + title: Text('网络链接'), onTap: () { Navigator.pop(ctx); _pickCoverFromUrl(); }), + ])))); + } + + Future _pickCover() async { + try { + final XFile? picked = await _picker.pickImage(source: ImageSource.gallery, maxWidth: 800, maxHeight: 1200, imageQuality: 85); + if (picked == null) return; + final fileName = 'cover_${DateTime.now().millisecondsSinceEpoch}.jpg'; + final targetPath = await ImagePathHelper.instance.getBookCoverPath(_tempId!, fileName); + await ImagePathHelper.instance.ensureDirExists(p.dirname(targetPath)); + await File(picked.path).copy(targetPath); + if (mounted) setState(() => _coverPath = targetPath); + } catch (e) { if (mounted) ToastUtil.show(context, '选择封面失败: $e'); } + } + + Future _pickCoverFromUrl() async { + final ctrl = TextEditingController(); + final ok = await showDialog(context: context, builder: (ctx) { + final c = Theme.of(ctx).colorScheme; + return AlertDialog(backgroundColor: c.surface, elevation: 0, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + title: Text('添加网络图片', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: c.onSurface)), + content: TextField(controller: ctrl, keyboardType: TextInputType.url, style: TextStyle(fontSize: 14, color: c.onSurface), + decoration: InputDecoration(hintText: 'https://example.com/image.jpg', filled: true, fillColor: c.surfaceContainerHigh, + border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none))), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text('取消')), + ElevatedButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('确定')), + ]); + }); + final url = ctrl.text.trim(); ctrl.dispose(); + if (ok != true || url.isEmpty) return; + await _downloadCover(url); + } + + Future _downloadCover(String url) async { + setState(() => _isDownloading = true); + try { + final res = await http.get(Uri.parse(url), headers: { + 'User-Agent': 'Mozilla/5.0', 'Accept': 'image/*,*/*;q=0.8', 'Referer': Uri.parse(url).replace(path: '/').toString(), + }); + if (res.statusCode != 200) throw Exception('HTTP ${res.statusCode}'); + final fileName = 'cover_${DateTime.now().millisecondsSinceEpoch}.jpg'; + final targetPath = await ImagePathHelper.instance.getBookCoverPath(_tempId!, fileName); + await ImagePathHelper.instance.ensureDirExists(p.dirname(targetPath)); + await File(targetPath).writeAsBytes(res.bodyBytes); + if (mounted) setState(() => _coverPath = targetPath); + } catch (e) { if (mounted) ToastUtil.show(context, '下载失败: $e'); } + finally { if (mounted) setState(() => _isDownloading = false); } + } + + Future _save() async { + if (!_formKey.currentState!.validate()) return; + try { + final bookId = const Uuid().v4(); + // 移动封面到正式目录 + String? finalCoverPath; + if (_coverPath != null) { + final normalized = _coverPath!.replaceAll('\\', '/'); + if (!normalized.contains('/books/$bookId/')) { + final fileName = p.basename(_coverPath!); + final newPath = await ImagePathHelper.instance.getBookCoverPath(bookId, fileName); + await ImagePathHelper.instance.ensureDirExists(p.dirname(newPath)); + final src = File(_coverPath!); + if (await src.exists()) { await src.rename(newPath); finalCoverPath = newPath; } + // 清理临时目录 + final tempDir = Directory(p.dirname(_coverPath!)); + if (await tempDir.exists()) { try { await tempDir.delete(recursive: true); } catch (_) {} } + } else { finalCoverPath = _coverPath; } + } + final rating = _ratingCtrl.text.isNotEmpty ? double.tryParse(_ratingCtrl.text) : null; + final publisher = _publisherCtrl.text.trim().isEmpty ? null : _publisherCtrl.text.trim(); + final isbn = _isbnCtrl.text.trim().isEmpty ? null : _isbnCtrl.text.trim(); + final now = DateTime.now(); + final book = Book( + id: bookId, title: _titleCtrl.text.trim(), coverPath: finalCoverPath, + authors: _authors, translators: _translators, alternateTitles: _alternateTitles, + genres: _genres, publisher: publisher, isbn: isbn, + summary: _summaryCtrl.text.trim(), rating: rating, + status: _status, publishDate: _publishDate, startDate: _startDate, finishDate: _finishDate, + createdAt: now, updatedAt: now, + ); + await context.read().addBook(book); + await context.read().loadBooks(); + if (!mounted) return; + context.read().finishAdding(); + ToastUtil.show(context, '添加成功'); + } catch (e) { if (mounted) ToastUtil.show(context, '保存失败: $e'); } + } + + static List _collectUnique(List> lists) { + final s = {}; for (final l in lists) { s.addAll(l); } return s.toList()..sort(); + } +} + +class _RatingInputFormatter extends TextInputFormatter { + @override + TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { + final text = newValue.text; + if (text.isEmpty) return newValue; + if (!RegExp(r'^\d{0,2}\.?\d{0,1}$').hasMatch(text)) return oldValue; + final n = double.tryParse(text); + if (n != null && n > 10) return oldValue; + return newValue; + } +} diff --git a/lib/pages/book/book_detail_page.dart b/lib/pages/book/book_detail_page.dart index c836d29..0ca69e5 100644 --- a/lib/pages/book/book_detail_page.dart +++ b/lib/pages/book/book_detail_page.dart @@ -1,14 +1,20 @@ import 'dart:io'; import 'dart:ui' as ui; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:path/path.dart' as p; import 'package:provider/provider.dart'; +import 'package:http/http.dart' as http; import '../../widgets/fade_in_local_image.dart'; import '../../providers/app_provider.dart'; import '../../models/data_models.dart'; import '../../utils/toast_util.dart'; import '../../utils/user_prefs.dart'; +import '../../utils/image_path_helper.dart'; import '../../utils/responsive.dart'; +import '../../widgets/genre_selector_page.dart'; import 'book_reviews_page.dart'; import 'book_excerpts_page.dart'; import 'book_share_page.dart'; @@ -37,12 +43,37 @@ class _BookDetailPageState extends State { final ValueNotifier _showTitle = ValueNotifier(false); ScrollController? _overlayScrollController; + // ─── 编辑模式 ─── + bool _isEditing = false; + final _editFormKey = GlobalKey(); + late TextEditingController _titleCtrl; + late TextEditingController _summaryCtrl; + late TextEditingController _ratingCtrl; + late TextEditingController _publisherCtrl; + late TextEditingController _isbnCtrl; + List _editAuthors = []; + List _editTranslators = []; + List _editGenres = []; + List _editAlternateTitles = []; + String? _editCoverPath; + String _editStatus = 'want_to_read'; + DateTime? _editPublishDate; + DateTime? _editStartDate; + DateTime? _editFinishDate; + bool _editIsDownloading = false; + final ImagePicker _picker = ImagePicker(); + @override void dispose() { _coverOffset.dispose(); _draggingCover.dispose(); _showTitle.dispose(); _overlayScrollController?.dispose(); + _titleCtrl.dispose(); + _summaryCtrl.dispose(); + _ratingCtrl.dispose(); + _publisherCtrl.dispose(); + _isbnCtrl.dispose(); super.dispose(); } @@ -51,6 +82,45 @@ class _BookDetailPageState extends State { super.initState(); _detailStyle = UserPrefs().detailPageStyle; _coverOffset.value = UserPrefs().getCoverOffset(widget.book.id); + _initEditControllers(); + } + + void _initEditControllers() { + final b = widget.book; + _titleCtrl = TextEditingController(text: b.title); + _summaryCtrl = TextEditingController(text: b.summary ?? ''); + _ratingCtrl = TextEditingController(text: b.rating?.toString() ?? ''); + _publisherCtrl = TextEditingController(text: b.publisher ?? ''); + _isbnCtrl = TextEditingController(text: b.isbn ?? ''); + _editAuthors = List.from(b.authors); + _editTranslators = List.from(b.translators); + _editGenres = List.from(b.genres); + _editAlternateTitles = List.from(b.alternateTitles); + _editCoverPath = b.coverPath; + _editStatus = b.status; + _editPublishDate = b.publishDate; + _editStartDate = b.startDate; + _editFinishDate = b.finishDate; + } + + void _enterEditMode() { + final latest = context.read().books + .where((b) => b.id == widget.book.id).firstOrNull ?? widget.book; + _titleCtrl.text = latest.title; + _summaryCtrl.text = latest.summary ?? ''; + _ratingCtrl.text = latest.rating?.toString() ?? ''; + _publisherCtrl.text = latest.publisher ?? ''; + _isbnCtrl.text = latest.isbn ?? ''; + _editAuthors = List.from(latest.authors); + _editTranslators = List.from(latest.translators); + _editGenres = List.from(latest.genres); + _editAlternateTitles = List.from(latest.alternateTitles); + _editCoverPath = latest.coverPath; + _editStatus = latest.status; + _editPublishDate = latest.publishDate; + _editStartDate = latest.startDate; + _editFinishDate = latest.finishDate; + setState(() => _isEditing = true); } @override @@ -71,6 +141,7 @@ class _BookDetailPageState extends State { /// 桌面端左右分栏布局 Widget _buildDesktopStyle(Book book, ColorScheme colors) { + if (_isEditing) return _buildDesktopEditStyle(book, colors); final hasCover = book.coverPath != null && book.coverPath!.isNotEmpty; return Scaffold( backgroundColor: colors.surface, @@ -143,13 +214,12 @@ class _BookDetailPageState extends State { ], _buildEpubProgressBar(book), const SizedBox(height: 16), - Row(children: [ + Wrap(spacing: 6, runSpacing: 4, crossAxisAlignment: WrapCrossAlignment.center, children: [ if (book.rating != null) ...[ Icon(Icons.star, size: 20, color: colors.onSurface), const SizedBox(width: 4), Text(book.rating!.toStringAsFixed(1), style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: colors.onSurface)), - const SizedBox(width: 16), ], _buildStatusTag(book), ]), @@ -263,7 +333,7 @@ class _BookDetailPageState extends State { ), const SizedBox(width: 12), FilledButton.icon( - onPressed: () => _navigateToEdit(context), + onPressed: _enterEditMode, icon: const Icon(Icons.edit_outlined, size: 16), label: const Text('编辑'), style: FilledButton.styleFrom( @@ -278,6 +348,375 @@ class _BookDetailPageState extends State { ); } + // ─── 桌面端编辑模式 ────────────────────────────────────────── + + Widget _buildDesktopEditStyle(Book book, ColorScheme colors) { + final hasCover = _editCoverPath != null && _editCoverPath!.isNotEmpty; + return Scaffold( + backgroundColor: colors.surface, + body: Form( + key: _editFormKey, + child: Column( + children: [ + Container( + height: 48, + decoration: BoxDecoration(color: colors.surface, + border: Border(bottom: BorderSide(color: colors.outlineVariant, width: 0.5))), + child: Row(children: [ + IconButton(icon: Icon(Icons.close, color: colors.onSurface, size: 18), + onPressed: () => setState(() => _isEditing = false)), + Expanded(child: Text('编辑书籍', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: colors.onSurface))), + FilledButton.icon(onPressed: _saveEdit, + icon: const Icon(Icons.check, size: 16), label: const Text('保存'), + style: FilledButton.styleFrom(padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)))), + const SizedBox(width: 12), + ]), + ), + Expanded( + child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ + // 左侧:封面 + 状态/评分 + Container(width: 240, padding: const EdgeInsets.all(20), child: Column(children: [ + GestureDetector(onTap: _showEditCoverOptions, child: Container( + width: 200, height: 280, + decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(12)), + clipBehavior: Clip.antiAlias, + child: Stack(alignment: Alignment.center, children: [ + hasCover ? FadeInLocalImage(path: _editCoverPath, fit: BoxFit.cover) + : Column(mainAxisAlignment: MainAxisAlignment.center, children: [ + Icon(Icons.image_outlined, size: 32, color: colors.onSurface.withValues(alpha: 0.25)), + const SizedBox(height: 8), + Text('点击添加封面', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.35))), + ]), + if (_editIsDownloading) Container(color: Colors.black.withValues(alpha: 0.4), + child: const CircularProgressIndicator(strokeWidth: 2, color: Colors.white)), + ]), + )), + if (hasCover) Padding(padding: const EdgeInsets.only(top: 8), + child: GestureDetector(onTap: () => setState(() => _editCoverPath = null), + child: Text('移除封面', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.5))))), + const SizedBox(height: 20), + _buildEditSectionLabel('状态', colors), + const SizedBox(height: 6), + Container(padding: const EdgeInsets.all(2), + decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(6)), + child: Wrap(spacing: 0, runSpacing: 4, children: [ + _buildEditStatusChip('想读', 'want_to_read', colors), + _buildEditStatusChip('在读', 'reading', colors), + _buildEditStatusChip('已读', 'read', colors), + _buildEditStatusChip('弃读', 'abandoned', colors), + ])), + const SizedBox(height: 16), + _buildEditSectionLabel('评分', colors), + const SizedBox(height: 6), + Row(children: [ + ...List.generate(5, (i) { + final starVal = i + 1; + final currentRating = double.tryParse(_ratingCtrl.text) ?? 0; + final starRating = currentRating / 2; + final isFilled = starVal <= starRating; + final isHalf = starVal == starRating.ceil() && starRating % 1 != 0; + return GestureDetector(onTap: () => setState(() => _ratingCtrl.text = (starVal * 2).toString()), + child: Padding(padding: const EdgeInsets.symmetric(horizontal: 1), + child: Icon(isHalf ? Icons.star_half : (isFilled ? Icons.star : Icons.star_border), + size: 20, color: (isFilled || isHalf) ? const Color(0xFFFFB800) : colors.outline))); + }), + const SizedBox(width: 8), + Container(width: 48, height: 28, + decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(6)), + child: TextFormField(controller: _ratingCtrl, + keyboardType: const TextInputType.numberWithOptions(decimal: true), + textAlign: TextAlign.center, inputFormatters: [_RatingInputFormatter()], + style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: colors.onSurface), + decoration: InputDecoration(hintText: '0-10', hintStyle: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.25)), + border: InputBorder.none, contentPadding: const EdgeInsets.symmetric(vertical: 6), isDense: true), + onChanged: (_) => setState(() {}))), + if (_ratingCtrl.text.isNotEmpty) ...[ + const SizedBox(width: 4), + GestureDetector(onTap: () => setState(() => _ratingCtrl.clear()), + child: Icon(Icons.close, size: 14, color: colors.onSurface.withValues(alpha: 0.3))), + ], + ]), + ])), + // 右侧:可滚动表单 + Expanded(child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(0, 20, 24, 80), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + _buildEditField('名称', _titleCtrl, hint: '书籍名称', required: true), + const SizedBox(height: 16), + _buildEditChipField('作者', _editAuthors, onTap: () async { + final provider = context.read(); + final data = provider.books.map((b) => b.authors).toList(); + final result = await GenreSelectorPage.show(context: context, title: '选择作者', + existingTagsFuture: compute(_collectUnique, data), initialSelected: _editAuthors, hint: '如:余华、莫言'); + if (result != null) setState(() => _editAuthors = result); + }), + const SizedBox(height: 16), + _buildEditChipField('译者', _editTranslators, onTap: () async { + final provider = context.read(); + final data = provider.books.map((b) => b.translators).toList(); + final result = await GenreSelectorPage.show(context: context, title: '选择译者', + existingTagsFuture: compute(_collectUnique, data), initialSelected: _editTranslators, hint: '如:林少华'); + if (result != null) setState(() => _editTranslators = result); + }), + const SizedBox(height: 16), + _buildEditChipField('别名', _editAlternateTitles, onTap: () async { + final result = await GenreSelectorPage.show(context: context, title: '添加别名', + existingTags: [], initialSelected: _editAlternateTitles, hint: '输入别名'); + if (result != null) setState(() => _editAlternateTitles = result); + }), + const SizedBox(height: 16), + _buildEditChipField('类型', _editGenres, onTap: () async { + final provider = context.read(); + final tags = await provider.getTags('book_genre', excludeHidden: true); + final names = tags.map((t) => t['name'] as String).toList(); + if (!mounted) return; + final result = await GenreSelectorPage.show(context: context, title: '选择类型', + existingTags: names, initialSelected: _editGenres, hint: '如:小说、科幻'); + if (result != null) setState(() => _editGenres = result); + }), + const SizedBox(height: 16), + _buildEditField('出版社', _publisherCtrl, hint: '出版社名称'), + const SizedBox(height: 16), + _buildEditField('ISBN', _isbnCtrl, hint: 'ISBN编号'), + const SizedBox(height: 16), + Row(children: [ + Expanded(child: _buildEditDateField('出版时间', _editPublishDate, (d) => setState(() => _editPublishDate = d))), + const SizedBox(width: 12), + Expanded(child: _buildEditDateField('开始阅读', _editStartDate, (d) => setState(() => _editStartDate = d), clearable: true)), + ]), + const SizedBox(height: 16), + _buildEditDateField('读完日期', _editFinishDate, (d) => setState(() => _editFinishDate = d), clearable: true), + const SizedBox(height: 16), + _buildEditSectionLabel('简介', colors), + const SizedBox(height: 6), + Container(constraints: const BoxConstraints(minHeight: 120), + child: TextFormField(controller: _summaryCtrl, maxLines: null, + style: TextStyle(fontSize: 14, color: colors.onSurface, height: 1.6), + decoration: InputDecoration(hintText: '写下书籍简介...', + hintStyle: TextStyle(color: colors.onSurface.withValues(alpha: 0.25)), + filled: true, fillColor: colors.surfaceContainerHighest.withValues(alpha: 0.5), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none), + contentPadding: const EdgeInsets.all(12)))), + ]), + )), + ]), + ), + Container(height: 48, + decoration: BoxDecoration(color: colors.surface, + border: Border(top: BorderSide(color: colors.outlineVariant, width: 0.5))), + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Row(mainAxisAlignment: MainAxisAlignment.end, children: [ + OutlinedButton.icon(onPressed: () => _showDeleteDialog(context), + icon: Icon(Icons.delete_outline, size: 16, color: colors.error), + label: Text('删除', style: TextStyle(color: colors.error)), + style: OutlinedButton.styleFrom(side: BorderSide(color: colors.error.withValues(alpha: 0.3)), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)))), + ])), + ], + ), + ), + ); + } + + Widget _buildEditSectionLabel(String label, ColorScheme colors) { + return Text(label, style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))); + } + + Widget _buildEditStatusChip(String label, String value, ColorScheme colors) { + final selected = _editStatus == value; + return GestureDetector(onTap: () => setState(() => _editStatus = value), + child: Container(padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + decoration: BoxDecoration(color: selected ? colors.surface : Colors.transparent, + borderRadius: BorderRadius.circular(6), + boxShadow: selected ? [BoxShadow(color: colors.onSurface.withValues(alpha: 0.03), blurRadius: 4, offset: const Offset(0, 2))] : null), + child: Text(label, style: TextStyle(fontSize: 12, fontWeight: selected ? FontWeight.w500 : FontWeight.normal, + color: selected ? colors.onSurface : colors.onSurface.withValues(alpha: 0.4))))); + } + + Widget _buildEditField(String label, TextEditingController ctrl, {String hint = '', bool required = false}) { + final colors = Theme.of(context).colorScheme; + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(required ? '$label *' : label, style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))), + const SizedBox(height: 6), + TextFormField(controller: ctrl, style: TextStyle(fontSize: 14, color: colors.onSurface), + validator: required ? (v) => (v == null || v.trim().isEmpty) ? '请输入$label' : null : null, + decoration: InputDecoration(hintText: hint, hintStyle: TextStyle(color: colors.onSurface.withValues(alpha: 0.25)), + filled: true, fillColor: colors.surfaceContainerHighest.withValues(alpha: 0.5), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), isDense: true)), + ]); + } + + Widget _buildEditChipField(String label, List chips, {required VoidCallback onTap}) { + final colors = Theme.of(context).colorScheme; + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(label, style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))), + const SizedBox(height: 6), + GestureDetector(onTap: onTap, + child: Container(width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), + decoration: BoxDecoration(color: colors.surfaceContainerHighest.withValues(alpha: 0.5), borderRadius: BorderRadius.circular(8)), + child: chips.isEmpty + ? Text('点击选择$label', style: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.25))) + : Wrap(spacing: 4, runSpacing: 4, children: chips.map((c) => Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration(color: colors.surface, borderRadius: BorderRadius.circular(4)), + child: Text(c, style: TextStyle(fontSize: 12, color: colors.onSurface)))).toList()))), + ]); + } + + Widget _buildEditDateField(String label, DateTime? date, ValueChanged onChanged, {bool clearable = false}) { + final colors = Theme.of(context).colorScheme; + final hasDate = date != null; + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(label, style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))), + const SizedBox(height: 6), + GestureDetector(onTap: () async { + final picked = await showDatePicker(context: context, initialDate: date ?? DateTime.now(), + firstDate: DateTime(1900), lastDate: DateTime.now().add(const Duration(days: 365 * 5))); + if (picked != null) onChanged(picked); + }, + child: Container(width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: BoxDecoration(color: colors.surfaceContainerHighest.withValues(alpha: 0.5), borderRadius: BorderRadius.circular(8)), + child: Row(children: [ + Icon(Icons.calendar_today_outlined, size: 14, color: colors.onSurface.withValues(alpha: 0.4)), + const SizedBox(width: 8), + Text(hasDate ? '${date!.year}.${date!.month.toString().padLeft(2, '0')}.${date!.day.toString().padLeft(2, '0')}' : '选择日期', + style: TextStyle(fontSize: 14, color: hasDate ? colors.onSurface : colors.onSurface.withValues(alpha: 0.25))), + const Spacer(), + if (clearable && hasDate) GestureDetector(onTap: () => onChanged(null), + child: Icon(Icons.close, size: 14, color: colors.onSurface.withValues(alpha: 0.3))), + ]))), + ]); + } + + void _showEditCoverOptions() { + final colors = Theme.of(context).colorScheme; + showModalBottomSheet(context: context, backgroundColor: colors.surface, + shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(16))), + builder: (ctx) => SafeArea(child: Padding(padding: const EdgeInsets.symmetric(vertical: 16), + child: Column(mainAxisSize: MainAxisSize.min, children: [ + Container(width: 40, height: 4, decoration: BoxDecoration(color: colors.outline, borderRadius: BorderRadius.circular(2))), + const SizedBox(height: 20), + Padding(padding: const EdgeInsets.symmetric(horizontal: 24), child: Align(alignment: Alignment.centerLeft, + child: Text('添加封面', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: colors.onSurface)))), + const SizedBox(height: 16), + ListTile(leading: Icon(Icons.photo_library_outlined, color: colors.onSurface.withValues(alpha: 0.6)), + title: Text('从相册选择', style: TextStyle(color: colors.onSurface)), + onTap: () { Navigator.pop(ctx); _pickEditCover(); }), + ListTile(leading: Icon(Icons.link_outlined, color: colors.onSurface.withValues(alpha: 0.6)), + title: Text('网络链接', style: TextStyle(color: colors.onSurface)), + onTap: () { Navigator.pop(ctx); _pickEditCoverFromUrl(); }), + ])))); + } + + Future _pickEditCover() async { + try { + final XFile? picked = await _picker.pickImage(source: ImageSource.gallery, maxWidth: 800, maxHeight: 1200, imageQuality: 85); + if (picked == null) return; + final fileName = 'cover_${DateTime.now().millisecondsSinceEpoch}.jpg'; + final targetPath = await ImagePathHelper.instance.getBookCoverPath(widget.book.id, fileName); + await ImagePathHelper.instance.ensureDirExists(p.dirname(targetPath)); + await File(picked.path).copy(targetPath); + if (mounted) setState(() => _editCoverPath = targetPath); + } catch (e) { + if (mounted) ToastUtil.show(context, '选择封面失败: $e'); + } + } + + Future _pickEditCoverFromUrl() async { + final urlCtrl = TextEditingController(); + final confirmed = await showDialog(context: context, builder: (ctx) { + final colors = Theme.of(ctx).colorScheme; + return AlertDialog(backgroundColor: colors.surface, elevation: 0, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + title: Text('添加网络图片', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: colors.onSurface)), + content: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text('请输入图片链接地址', style: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.6))), + const SizedBox(height: 12), + TextField(controller: urlCtrl, keyboardType: TextInputType.url, style: TextStyle(fontSize: 14, color: colors.onSurface), + decoration: InputDecoration(hintText: 'https://example.com/image.jpg', + hintStyle: TextStyle(color: colors.onSurface.withValues(alpha: 0.25)), + filled: true, fillColor: colors.surfaceContainerHigh, + contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none), + enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none), + focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide(color: colors.primary, width: 1)))), + ]), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text('取消', style: TextStyle(color: colors.onSurface.withValues(alpha: 0.6)))), + ElevatedButton(onPressed: () => Navigator.pop(ctx, true), + style: ElevatedButton.styleFrom(backgroundColor: colors.primary, foregroundColor: colors.onPrimary, elevation: 0, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8)), + child: const Text('确定')), + ]); + }); + final url = urlCtrl.text.trim(); urlCtrl.dispose(); + if (confirmed != true || url.isEmpty) return; + await _downloadEditCoverFromUrl(url); + } + + Future _downloadEditCoverFromUrl(String url) async { + setState(() => _editIsDownloading = true); + try { + final response = await http.get(Uri.parse(url), headers: { + 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15', + 'Accept': 'image/avif,image/webp,image/apng,*/*;q=0.8', + 'Referer': Uri.parse(url).replace(path: '/').toString(), + }); + if (response.statusCode != 200) throw Exception('下载失败: HTTP ${response.statusCode}'); + final contentType = response.headers['content-type']; + if (contentType != null && !contentType.startsWith('image/')) throw Exception('链接返回的不是图片'); + if (response.bodyBytes.length > 10 * 1024 * 1024) throw Exception('图片太大'); + final fileName = 'cover_${DateTime.now().millisecondsSinceEpoch}.jpg'; + final targetPath = await ImagePathHelper.instance.getBookCoverPath(widget.book.id, fileName); + await ImagePathHelper.instance.ensureDirExists(p.dirname(targetPath)); + await File(targetPath).writeAsBytes(response.bodyBytes); + if (mounted) setState(() => _editCoverPath = targetPath); + } catch (e) { + if (mounted) ToastUtil.show(context, '下载失败: $e'); + } finally { + if (mounted) setState(() => _editIsDownloading = false); + } + } + + Future _saveEdit() async { + if (!_editFormKey.currentState!.validate()) return; + try { + final rating = _ratingCtrl.text.isNotEmpty ? double.tryParse(_ratingCtrl.text) : null; + final updated = widget.book.copyWith( + title: _titleCtrl.text.trim(), + coverPath: _editCoverPath, + authors: _editAuthors, + translators: _editTranslators, + alternateTitles: _editAlternateTitles, + genres: _editGenres, + publisher: _publisherCtrl.text.trim().isNotEmpty ? _publisherCtrl.text.trim() : null, + isbn: _isbnCtrl.text.trim().isNotEmpty ? _isbnCtrl.text.trim() : null, + summary: _summaryCtrl.text.trim(), + rating: rating, + status: _editStatus, + publishDate: _editPublishDate, + startDate: _editStartDate, + finishDate: _editFinishDate, + updatedAt: DateTime.now(), + ); + await context.read().updateBook(updated); + if (!mounted) return; + ToastUtil.show(context, '更新成功'); + setState(() => _isEditing = false); + } catch (e) { + if (mounted) ToastUtil.show(context, '保存失败: $e'); + } + } + + static List _collectUnique(List> lists) { + final s = {}; + for (final l in lists) { s.addAll(l); } + return s.toList()..sort(); + } + Widget _buildDesktopInfoRow(String label, String value, ColorScheme colors) { return Padding( padding: const EdgeInsets.symmetric(vertical: 6), @@ -1678,3 +2117,15 @@ class _BookDetailPageState extends State { ); } } + +class _RatingInputFormatter extends TextInputFormatter { + @override + TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { + final text = newValue.text; + if (text.isEmpty) return newValue; + if (!RegExp(r'^\d{0,2}\.?\d{0,1}$').hasMatch(text)) return oldValue; + final n = double.tryParse(text); + if (n != null && n > 10) return oldValue; + return newValue; + } +} diff --git a/lib/pages/book/book_tab_page.dart b/lib/pages/book/book_tab_page.dart index 89042b4..f7b90c2 100644 --- a/lib/pages/book/book_tab_page.dart +++ b/lib/pages/book/book_tab_page.dart @@ -12,6 +12,7 @@ import '../../widgets/fade_in_local_image.dart'; import '../../widgets/master_detail_scaffold.dart'; import '../../widgets/detail_placeholder.dart'; import 'book_detail_page.dart'; +import 'book_add_page.dart'; /// 阅读标签页(分页 + 触底加载) class BookTabPage extends StatefulWidget { @@ -157,11 +158,14 @@ class _BookTabPageState extends State { if (!isWideContent) return masterContent; final selectedBook = provider.selectedBook; + final detailWidget = provider.isAdding && provider.addingType == 1 + ? BookAddPage(onCancel: () => provider.cancelAdding()) + : selectedBook != null + ? BookDetailPage(book: selectedBook, embedded: true) + : const DetailPlaceholder(icon: Icons.menu_book_outlined, message: '选择一本书查看详情'); return MasterDetailScaffold( master: masterContent, - detail: selectedBook != null - ? BookDetailPage(book: selectedBook, embedded: true) - : const DetailPlaceholder(icon: Icons.menu_book_outlined, message: '选择一本书查看详情'), + detail: detailWidget, ); } diff --git a/lib/pages/epub_reader/reader_renderer.dart b/lib/pages/epub_reader/reader_renderer.dart index 3e3711f..93d37fe 100644 --- a/lib/pages/epub_reader/reader_renderer.dart +++ b/lib/pages/epub_reader/reader_renderer.dart @@ -77,11 +77,17 @@ class ReaderRendererController { .toList(); final propertiesParam = encodedPropertiesList.map((p) => '"$p"').join(','); final propertiesJson = '[$propertiesParam]'; + + if (Platform.isWindows) { + final result = await _rendererState?._readHtmlForUrl(url); + if (result != null) { + return await webViewController?.loadFrameSrcdoc( + 'curr', result.$1, result.$2, anchorsJson, propertiesJson, + ); + } + } return await webViewController?.loadFrame( - 'curr', - url, - anchorsJson, - propertiesJson, + 'curr', url, anchorsJson, propertiesJson, ); } @@ -98,11 +104,17 @@ class ReaderRendererController { .toList(); final propertiesParam = encodedPropertiesList.map((p) => '"$p"').join(','); final propertiesJson = '[$propertiesParam]'; + + if (Platform.isWindows) { + final result = await _rendererState?._readHtmlForUrl(url); + if (result != null) { + return await webViewController?.loadFrameSrcdoc( + 'next', result.$1, result.$2, anchorsJson, propertiesJson, + ); + } + } return await webViewController?.loadFrame( - 'next', - url, - anchorsJson, - propertiesJson, + 'next', url, anchorsJson, propertiesJson, ); } @@ -119,11 +131,17 @@ class ReaderRendererController { .toList(); final propertiesParam = encodedPropertiesList.map((p) => '"$p"').join(','); final propertiesJson = '[$propertiesParam]'; + + if (Platform.isWindows) { + final result = await _rendererState?._readHtmlForUrl(url); + if (result != null) { + return await webViewController?.loadFrameSrcdoc( + 'prev', result.$1, result.$2, anchorsJson, propertiesJson, + ); + } + } return await webViewController?.loadFrame( - 'prev', - url, - anchorsJson, - propertiesJson, + 'prev', url, anchorsJson, propertiesJson, ); } @@ -237,6 +255,16 @@ class _ReaderRendererState extends State ); } + /// Read HTML content from EPUB for a given virtual URL (Windows srcdoc approach). + /// Returns (htmlContent, baseUrl) or null. + Future<(String, String)?> _readHtmlForUrl(String url) async { + return await widget.webViewHandler.readHtmlContentWithBaseUrl( + epubPath: widget.bookSession.book['file_path'] as String, + fileHash: widget.fileHash, + url: url, + ); + } + @override void initState() { super.initState(); diff --git a/lib/pages/epub_reader/reader_screen.dart b/lib/pages/epub_reader/reader_screen.dart index 4755b75..7f6a2be 100644 --- a/lib/pages/epub_reader/reader_screen.dart +++ b/lib/pages/epub_reader/reader_screen.dart @@ -200,7 +200,18 @@ class _ReaderScreenState extends State final route = ModalRoute.of(context); if (route != null && route.animation != null) { routeAnimation = route.animation!; - routeAnimation?.addStatusListener(handleRouteAnimationStatus); + if (routeAnimation!.isCompleted) { + shouldShowWebView = true; + } else { + routeAnimation?.addStatusListener(handleRouteAnimationStatus); + // 安全超时:桌面端路由动画可能不触发 completed,500ms后强制显示 + Future.delayed(const Duration(milliseconds: 500), () { + if (mounted && !shouldShowWebView) { + debugPrint('[EPUB-Reader] animation timeout, forcing WebView visible'); + setState(() { shouldShowWebView = true; }); + } + }); + } } else { shouldShowWebView = true; } @@ -268,6 +279,7 @@ class _ReaderScreenState extends State } void handleRouteAnimationStatus(AnimationStatus status) { + debugPrint('[EPUB-Reader] animation status: $status'); if (status == AnimationStatus.completed) { setState(() { shouldShowWebView = true; diff --git a/lib/pages/epub_reader/reader_webview.dart b/lib/pages/epub_reader/reader_webview.dart index 547e1a2..05c5585 100644 --- a/lib/pages/epub_reader/reader_webview.dart +++ b/lib/pages/epub_reader/reader_webview.dart @@ -5,6 +5,7 @@ import 'dart:ui' as ui; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; +import '../../main.dart'; import '../../services/epub/epub_theme.dart'; import 'book_session.dart'; import '../../services/epub/epub_webview_handler.dart'; @@ -44,6 +45,16 @@ class ReaderWebViewController { return await _webViewState?._loadFrame(frame, url, anchors, properties); } + Future loadFrameSrcdoc( + String frame, + String htmlContent, + String baseUrl, + String anchors, + String properties, + ) async { + return await _webViewState?._loadFrameSrcdoc(frame, htmlContent, baseUrl, anchors, properties); + } + Future jumpToPage(int pageIndex) async { await _webViewState?._jumpToPage(pageIndex); } @@ -327,6 +338,7 @@ class _ReaderWebViewState extends State { if (_isHeadlessInitialized) return; _headlessWebView = HeadlessInAppWebView( + webViewEnvironment: windowsWebViewEnvironment, initialData: _generateInitialData(width, height), initialSettings: defaultSettings, shouldInterceptRequest: _shouldInterceptRequest, @@ -364,6 +376,14 @@ class _ReaderWebViewState extends State { String properties, ) => _api.loadFrame(frame, url, anchors, properties); + Future _loadFrameSrcdoc( + String frame, + String htmlContent, + String baseUrl, + String anchors, + String properties, + ) => _api.loadFrameSrcdoc(frame, htmlContent, baseUrl, anchors, properties); + Future _jumpToPage(int pageIndex) => _api.jumpToPage(pageIndex); Future _restoreScrollPosition(double ratio) => @@ -1113,6 +1133,7 @@ class _ReaderWebViewState extends State { child: AbsorbPointer( child: widget.shouldShowWebView ? InAppWebView( + webViewEnvironment: windowsWebViewEnvironment, headlessWebView: _headlessWebView, initialData: _generateInitialData(width, height), initialSettings: defaultSettings, diff --git a/lib/pages/game/game_add_page.dart b/lib/pages/game/game_add_page.dart new file mode 100644 index 0000000..bb9f0f9 --- /dev/null +++ b/lib/pages/game/game_add_page.dart @@ -0,0 +1,429 @@ +import 'dart:io'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:path/path.dart' as p; +import 'package:provider/provider.dart'; +import 'package:http/http.dart' as http; +import 'package:uuid/uuid.dart'; +import '../../widgets/fade_in_local_image.dart'; +import '../../providers/app_provider.dart'; +import '../../models/data_models.dart'; +import '../../utils/toast_util.dart'; +import '../../utils/image_path_helper.dart'; +import '../../widgets/genre_selector_page.dart'; + +class GameAddPage extends StatefulWidget { + final VoidCallback? onCancel; + final String? initialStatus; + const GameAddPage({super.key, this.onCancel, this.initialStatus}); + + @override + State createState() => _GameAddPageState(); +} + +class _GameAddPageState extends State { + final _formKey = GlobalKey(); + final ImagePicker _picker = ImagePicker(); + late TextEditingController _titleCtrl; + late TextEditingController _summaryCtrl; + late TextEditingController _ratingCtrl; + late TextEditingController _purchasePriceCtrl; + late TextEditingController _playTimeHoursCtrl; + late TextEditingController _playTimeMinutesCtrl; + List _platforms = []; + List _versions = []; + List _genres = []; + List _purchasePlatforms = []; + String? _coverPath; + String _status = 'want_to_play'; + String _category = 'digital'; + DateTime? _purchaseDate; + bool _isDownloading = false; + String? _tempId; + + static const _categories = [ + ('数字版', 'digital'), ('卡带版', 'cartridge'), ('光盘版', 'disc'), + ]; + + @override + void initState() { + super.initState(); + _tempId = const Uuid().v4(); + _status = widget.initialStatus ?? 'want_to_play'; + _titleCtrl = TextEditingController(); + _summaryCtrl = TextEditingController(); + _ratingCtrl = TextEditingController(); + _purchasePriceCtrl = TextEditingController(); + _playTimeHoursCtrl = TextEditingController(); + _playTimeMinutesCtrl = TextEditingController(); + } + + @override + void dispose() { + _titleCtrl.dispose(); + _summaryCtrl.dispose(); + _ratingCtrl.dispose(); + _purchasePriceCtrl.dispose(); + _playTimeHoursCtrl.dispose(); + _playTimeMinutesCtrl.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final colors = Theme.of(context).colorScheme; + final hasCover = _coverPath != null && _coverPath!.isNotEmpty; + return Scaffold( + backgroundColor: colors.surface, + body: Form( + key: _formKey, + child: Column( + children: [ + // 顶栏 + Container(height: 48, + decoration: BoxDecoration(color: colors.surface, + border: Border(bottom: BorderSide(color: colors.outlineVariant, width: 0.5))), + child: Row(children: [ + IconButton(icon: Icon(Icons.close, color: colors.onSurface, size: 18), + onPressed: () => widget.onCancel?.call()), + Expanded(child: Text('添加游戏', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: colors.onSurface))), + FilledButton.icon(onPressed: _save, + icon: const Icon(Icons.check, size: 16), label: const Text('保存'), + style: FilledButton.styleFrom(padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)))), + const SizedBox(width: 12), + ]), + ), + // 主体:左封面+右表单 + Expanded( + child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ + // 左侧 + Container(width: 240, padding: const EdgeInsets.all(20), child: Column(children: [ + GestureDetector(onTap: _showCoverOptions, child: Container( + width: 200, height: 280, + decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(12)), + clipBehavior: Clip.antiAlias, + child: Stack(alignment: Alignment.center, children: [ + hasCover ? FadeInLocalImage(path: _coverPath, fit: BoxFit.cover) + : Column(mainAxisAlignment: MainAxisAlignment.center, children: [ + Icon(Icons.image_outlined, size: 32, color: colors.onSurface.withValues(alpha: 0.25)), + const SizedBox(height: 8), + Text('点击添加封面', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.35))), + ]), + if (_isDownloading) Container(color: Colors.black.withValues(alpha: 0.4), + child: const CircularProgressIndicator(strokeWidth: 2, color: Colors.white)), + ]), + )), + if (hasCover) Padding(padding: const EdgeInsets.only(top: 8), + child: GestureDetector(onTap: () => setState(() => _coverPath = null), + child: Text('移除封面', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.5))))), + const SizedBox(height: 20), + _label('状态', colors), const SizedBox(height: 6), + Container(padding: const EdgeInsets.all(2), + decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(6)), + child: Wrap(spacing: 0, runSpacing: 4, children: [ + _statusChip('想玩', 'want_to_play', colors), _statusChip('在玩', 'playing', colors), + _statusChip('通关', 'completed', colors), _statusChip('弃游', 'abandoned', colors), + ])), + const SizedBox(height: 16), + _label('评分', colors), const SizedBox(height: 6), + _buildRatingRow(colors), + const SizedBox(height: 16), + _label('分类', colors), const SizedBox(height: 6), + Wrap(spacing: 4, runSpacing: 4, children: _categories.map((c) { + final sel = _category == c.$2; + return GestureDetector(onTap: () => setState(() => _category = c.$2), + child: Container(padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration(color: sel ? colors.primary : colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(4)), + child: Text(c.$1, style: TextStyle(fontSize: 11, fontWeight: sel ? FontWeight.w500 : FontWeight.normal, + color: sel ? colors.onPrimary : colors.onSurface.withValues(alpha: 0.5))))); + }).toList()), + ])), + // 右侧表单 + Expanded(child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(0, 20, 24, 80), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + _field('名称', _titleCtrl, hint: '游戏名称', required: true), const SizedBox(height: 16), + _chipField('平台', _platforms, onTap: () async { + final p = context.read(); final d = p.games.map((g) => g.platforms).toList(); + final r = await GenreSelectorPage.show(context: context, title: '选择平台', existingTagsFuture: compute(_collectUnique, d), initialSelected: _platforms, hint: '如:Switch、PS5'); + if (r != null) setState(() => _platforms = r); + }), const SizedBox(height: 16), + _chipField('版本', _versions, onTap: () async { + final p = context.read(); final d = p.games.map((g) => g.versions).toList(); + final r = await GenreSelectorPage.show(context: context, title: '选择版本', existingTagsFuture: compute(_collectUnique, d), initialSelected: _versions, hint: '如:标准版、豪华版'); + if (r != null) setState(() => _versions = r); + }), const SizedBox(height: 16), + _chipField('类型', _genres, onTap: () async { + final p = context.read(); + final tags = await p.getTags('game_genre', excludeHidden: true); + final names = tags.map((t) => t['name'] as String).toList(); + if (!mounted) return; + final r = await GenreSelectorPage.show(context: context, title: '选择类型', existingTags: names, initialSelected: _genres, hint: '如:RPG、动作'); + if (r != null) setState(() => _genres = r); + }), const SizedBox(height: 16), + _chipField('购买平台', _purchasePlatforms, onTap: () async { + final p = context.read(); final d = p.games.map((g) => g.purchasePlatforms).toList(); + final r = await GenreSelectorPage.show(context: context, title: '选择购买平台', existingTagsFuture: compute(_collectUnique, d), initialSelected: _purchasePlatforms, hint: '如:Steam、eShop'); + if (r != null) setState(() => _purchasePlatforms = r); + }), const SizedBox(height: 16), + _field('购买价格', _purchasePriceCtrl, hint: '如:298'), const SizedBox(height: 16), + _label('游玩时长', Theme.of(context).colorScheme), const SizedBox(height: 6), + Row(children: [ + SizedBox(width: 80, child: TextFormField(controller: _playTimeHoursCtrl, + keyboardType: TextInputType.number, + inputFormatters: [FilteringTextInputFormatter.digitsOnly], + textAlign: TextAlign.center, + style: TextStyle(fontSize: 14, color: colors.onSurface), + decoration: InputDecoration(hintText: '0', hintStyle: TextStyle(color: colors.onSurface.withValues(alpha: 0.25)), + filled: true, fillColor: colors.surfaceContainerHighest.withValues(alpha: 0.5), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), isDense: true))), + const SizedBox(width: 6), + Text('小时', style: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.5))), + const SizedBox(width: 12), + SizedBox(width: 80, child: TextFormField(controller: _playTimeMinutesCtrl, + keyboardType: TextInputType.number, + inputFormatters: [FilteringTextInputFormatter.digitsOnly], + textAlign: TextAlign.center, + style: TextStyle(fontSize: 14, color: colors.onSurface), + decoration: InputDecoration(hintText: '0', hintStyle: TextStyle(color: colors.onSurface.withValues(alpha: 0.25)), + filled: true, fillColor: colors.surfaceContainerHighest.withValues(alpha: 0.5), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), isDense: true))), + const SizedBox(width: 6), + Text('分钟', style: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.5))), + ]), const SizedBox(height: 16), + _dateField('购买日期', _purchaseDate, (d) => setState(() => _purchaseDate = d), clearable: true), const SizedBox(height: 16), + _label('简介', colors), const SizedBox(height: 6), + Container(constraints: const BoxConstraints(minHeight: 120), + child: TextFormField(controller: _summaryCtrl, maxLines: null, + style: TextStyle(fontSize: 14, color: colors.onSurface, height: 1.6), + decoration: InputDecoration(hintText: '写下游戏简介...', hintStyle: TextStyle(color: colors.onSurface.withValues(alpha: 0.25)), + filled: true, fillColor: colors.surfaceContainerHighest.withValues(alpha: 0.5), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none), contentPadding: const EdgeInsets.all(12)))), + ]), + )), + ]), + ), + ], + ), + ), + ); + } + + Widget _label(String l, ColorScheme c) => Text(l, style: TextStyle(fontSize: 12, color: c.onSurface.withValues(alpha: 0.4))); + Widget _statusChip(String label, String value, ColorScheme c) { + final sel = _status == value; + return GestureDetector(onTap: () => setState(() => _status = value), + child: Container(padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6), + decoration: BoxDecoration(color: sel ? c.surface : Colors.transparent, borderRadius: BorderRadius.circular(6), + boxShadow: sel ? [BoxShadow(color: c.onSurface.withValues(alpha: 0.03), blurRadius: 4, offset: const Offset(0, 2))] : null), + child: Text(label, style: TextStyle(fontSize: 13, fontWeight: sel ? FontWeight.w500 : FontWeight.normal, + color: sel ? c.onSurface : c.onSurface.withValues(alpha: 0.4))))); + } + + Widget _buildRatingRow(ColorScheme colors) { + return Row(children: [ + ...List.generate(5, (i) { + final sv = i + 1; final cr = double.tryParse(_ratingCtrl.text) ?? 0; final sr = cr / 2; + final f = sv <= sr; final h = sv == sr.ceil() && sr % 1 != 0; + return GestureDetector(onTap: () => setState(() => _ratingCtrl.text = (sv * 2).toString()), + child: Padding(padding: const EdgeInsets.symmetric(horizontal: 1), + child: Icon(h ? Icons.star_half : (f ? Icons.star : Icons.star_border), size: 20, color: (f || h) ? const Color(0xFFFFB800) : colors.outline))); + }), + const SizedBox(width: 8), + Container(width: 48, height: 28, decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(6)), + child: TextFormField(controller: _ratingCtrl, keyboardType: const TextInputType.numberWithOptions(decimal: true), + textAlign: TextAlign.center, inputFormatters: [_RatingInputFormatter()], + style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: colors.onSurface), + decoration: InputDecoration(hintText: '0-10', hintStyle: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.25)), + border: InputBorder.none, contentPadding: const EdgeInsets.symmetric(vertical: 6), isDense: true), + onChanged: (_) => setState(() {}))), + if (_ratingCtrl.text.isNotEmpty) ...[ + const SizedBox(width: 4), + GestureDetector(onTap: () => setState(() => _ratingCtrl.clear()), + child: Icon(Icons.close, size: 14, color: colors.onSurface.withValues(alpha: 0.3))), + ], + ]); + } + + Widget _field(String label, TextEditingController ctrl, {String hint = '', bool required = false}) { + final c = Theme.of(context).colorScheme; + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(required ? '$label *' : label, style: TextStyle(fontSize: 12, color: c.onSurface.withValues(alpha: 0.4))), + const SizedBox(height: 6), + TextFormField(controller: ctrl, style: TextStyle(fontSize: 14, color: c.onSurface), + validator: required ? (v) => (v == null || v.trim().isEmpty) ? '请输入$label' : null : null, + decoration: InputDecoration(hintText: hint, hintStyle: TextStyle(color: c.onSurface.withValues(alpha: 0.25)), + filled: true, fillColor: c.surfaceContainerHighest.withValues(alpha: 0.5), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), isDense: true)), + ]); + } + + Widget _chipField(String label, List chips, {required VoidCallback onTap}) { + final c = Theme.of(context).colorScheme; + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(label, style: TextStyle(fontSize: 12, color: c.onSurface.withValues(alpha: 0.4))), + const SizedBox(height: 6), + GestureDetector(onTap: onTap, + child: Container(width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), + decoration: BoxDecoration(color: c.surfaceContainerHighest.withValues(alpha: 0.5), borderRadius: BorderRadius.circular(8)), + child: chips.isEmpty + ? Text('点击选择$label', style: TextStyle(fontSize: 14, color: c.onSurface.withValues(alpha: 0.25))) + : Wrap(spacing: 4, runSpacing: 4, children: chips.map((e) => Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration(color: c.surface, borderRadius: BorderRadius.circular(4)), + child: Text(e, style: TextStyle(fontSize: 12, color: c.onSurface)))).toList()))), + ]); + } + + Widget _dateField(String label, DateTime? date, ValueChanged onChanged, {bool clearable = false}) { + final c = Theme.of(context).colorScheme; final has = date != null; + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(label, style: TextStyle(fontSize: 12, color: c.onSurface.withValues(alpha: 0.4))), + const SizedBox(height: 6), + GestureDetector(onTap: () async { + final picked = await showDatePicker(context: context, initialDate: date ?? DateTime.now(), + firstDate: DateTime(1900), lastDate: DateTime.now().add(const Duration(days: 365 * 5))); + if (picked != null) onChanged(picked); + }, child: Container(width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: BoxDecoration(color: c.surfaceContainerHighest.withValues(alpha: 0.5), borderRadius: BorderRadius.circular(8)), + child: Row(children: [ + Icon(Icons.calendar_today_outlined, size: 14, color: c.onSurface.withValues(alpha: 0.4)), + const SizedBox(width: 8), + Text(has ? '${date!.year}.${date!.month.toString().padLeft(2, '0')}.${date!.day.toString().padLeft(2, '0')}' : '选择日期', + style: TextStyle(fontSize: 14, color: has ? c.onSurface : c.onSurface.withValues(alpha: 0.25))), + const Spacer(), + if (clearable && has) GestureDetector(onTap: () => onChanged(null), + child: Icon(Icons.close, size: 14, color: c.onSurface.withValues(alpha: 0.3))), + ]))), + ]); + } + + void _showCoverOptions() { + final c = Theme.of(context).colorScheme; + showModalBottomSheet(context: context, backgroundColor: c.surface, + shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(16))), + builder: (ctx) => SafeArea(child: Padding(padding: const EdgeInsets.symmetric(vertical: 16), + child: Column(mainAxisSize: MainAxisSize.min, children: [ + Container(width: 40, height: 4, decoration: BoxDecoration(color: c.outline, borderRadius: BorderRadius.circular(2))), + const SizedBox(height: 20), + Padding(padding: const EdgeInsets.symmetric(horizontal: 24), child: Align(alignment: Alignment.centerLeft, + child: Text('添加封面', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: c.onSurface)))), + const SizedBox(height: 16), + ListTile(leading: Icon(Icons.photo_library_outlined, color: c.onSurface.withValues(alpha: 0.6)), + title: Text('从相册选择'), onTap: () { Navigator.pop(ctx); _pickCover(); }), + ListTile(leading: Icon(Icons.link_outlined, color: c.onSurface.withValues(alpha: 0.6)), + title: Text('网络链接'), onTap: () { Navigator.pop(ctx); _pickCoverFromUrl(); }), + ])))); + } + + Future _pickCover() async { + try { + final XFile? picked = await _picker.pickImage(source: ImageSource.gallery, maxWidth: 800, maxHeight: 1200, imageQuality: 85); + if (picked == null) return; + final fileName = 'cover_${DateTime.now().millisecondsSinceEpoch}.jpg'; + final targetPath = await ImagePathHelper.instance.getGameCoverPath(_tempId!, fileName); + await ImagePathHelper.instance.ensureDirExists(p.dirname(targetPath)); + await File(picked.path).copy(targetPath); + if (mounted) setState(() => _coverPath = targetPath); + } catch (e) { if (mounted) ToastUtil.show(context, '选择封面失败: $e'); } + } + + Future _pickCoverFromUrl() async { + final ctrl = TextEditingController(); + final ok = await showDialog(context: context, builder: (ctx) { + final c = Theme.of(ctx).colorScheme; + return AlertDialog(backgroundColor: c.surface, elevation: 0, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + title: Text('添加网络图片', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: c.onSurface)), + content: TextField(controller: ctrl, keyboardType: TextInputType.url, style: TextStyle(fontSize: 14, color: c.onSurface), + decoration: InputDecoration(hintText: 'https://example.com/image.jpg', filled: true, fillColor: c.surfaceContainerHigh, + border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none))), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text('取消')), + ElevatedButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('确定')), + ]); + }); + final url = ctrl.text.trim(); ctrl.dispose(); + if (ok != true || url.isEmpty) return; + await _downloadCover(url); + } + + Future _downloadCover(String url) async { + setState(() => _isDownloading = true); + try { + final res = await http.get(Uri.parse(url), headers: { + 'User-Agent': 'Mozilla/5.0', 'Accept': 'image/*,*/*;q=0.8', 'Referer': Uri.parse(url).replace(path: '/').toString(), + }); + if (res.statusCode != 200) throw Exception('HTTP ${res.statusCode}'); + final fileName = 'cover_${DateTime.now().millisecondsSinceEpoch}.jpg'; + final targetPath = await ImagePathHelper.instance.getGameCoverPath(_tempId!, fileName); + await ImagePathHelper.instance.ensureDirExists(p.dirname(targetPath)); + await File(targetPath).writeAsBytes(res.bodyBytes); + if (mounted) setState(() => _coverPath = targetPath); + } catch (e) { if (mounted) ToastUtil.show(context, '下载失败: $e'); } + finally { if (mounted) setState(() => _isDownloading = false); } + } + + Future _save() async { + if (!_formKey.currentState!.validate()) return; + try { + final gameId = const Uuid().v4(); + // 移动封面到正式目录 + String? finalCoverPath; + if (_coverPath != null) { + final normalized = _coverPath!.replaceAll('\\', '/'); + if (!normalized.contains('/games/$gameId/')) { + final fileName = p.basename(_coverPath!); + final newPath = await ImagePathHelper.instance.getGameCoverPath(gameId, fileName); + await ImagePathHelper.instance.ensureDirExists(p.dirname(newPath)); + final src = File(_coverPath!); + if (await src.exists()) { await src.rename(newPath); finalCoverPath = newPath; } + // 清理临时目录 + final tempDir = Directory(p.dirname(_coverPath!)); + if (await tempDir.exists()) { try { await tempDir.delete(recursive: true); } catch (_) {} } + } else { finalCoverPath = _coverPath; } + } + final rating = _ratingCtrl.text.isNotEmpty ? double.tryParse(_ratingCtrl.text) : null; + final purchasePrice = _purchasePriceCtrl.text.trim().isNotEmpty ? _purchasePriceCtrl.text.trim() : null; + final playTimeHours = int.tryParse(_playTimeHoursCtrl.text) ?? 0; + final playTimeMinutes = int.tryParse(_playTimeMinutesCtrl.text) ?? 0; + final now = DateTime.now(); + final game = Game( + id: gameId, title: _titleCtrl.text.trim(), coverPath: finalCoverPath, + platforms: _platforms, versions: _versions, genres: _genres, + purchasePlatforms: _purchasePlatforms, purchasePrice: purchasePrice, + playTimeHours: playTimeHours, playTimeMinutes: playTimeMinutes, + summary: _summaryCtrl.text.trim(), rating: rating, + status: _status, category: _category, purchaseDate: _purchaseDate, + createdAt: now, updatedAt: now, + ); + await context.read().addGame(game); + await context.read().loadGames(); + if (!mounted) return; + context.read().finishAdding(); + ToastUtil.show(context, '添加成功'); + } catch (e) { if (mounted) ToastUtil.show(context, '保存失败: $e'); } + } + + static List _collectUnique(List> lists) { + final s = {}; for (final l in lists) { s.addAll(l); } return s.toList()..sort(); + } +} + +class _RatingInputFormatter extends TextInputFormatter { + @override + TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { + final text = newValue.text; + if (text.isEmpty) return newValue; + if (!RegExp(r'^\d{0,2}\.?\d{0,1}$').hasMatch(text)) return oldValue; + final n = double.tryParse(text); + if (n != null && n > 10) return oldValue; + return newValue; + } +} diff --git a/lib/pages/game/game_detail_page.dart b/lib/pages/game/game_detail_page.dart index 9770889..e132df4 100644 --- a/lib/pages/game/game_detail_page.dart +++ b/lib/pages/game/game_detail_page.dart @@ -1,14 +1,20 @@ import 'dart:io'; import 'dart:ui'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:path/path.dart' as p; import 'package:provider/provider.dart'; +import 'package:http/http.dart' as http; import '../../widgets/fade_in_local_image.dart'; import '../../providers/app_provider.dart'; import '../../models/data_models.dart'; import '../../utils/user_prefs.dart'; import '../../utils/toast_util.dart'; +import '../../utils/image_path_helper.dart'; import '../../utils/responsive.dart'; +import '../../widgets/genre_selector_page.dart'; import 'game_reviews_page.dart'; import 'game_screenshots_page.dart'; import 'game_share_page.dart'; @@ -35,14 +41,74 @@ class _GameDetailPageState extends State { final ValueNotifier _showTitle = ValueNotifier(false); ScrollController? _overlayScrollController; + // ─── 编辑模式 ─── + bool _isEditing = false; + final _editFormKey = GlobalKey(); + late TextEditingController _titleCtrl; + late TextEditingController _summaryCtrl; + late TextEditingController _ratingCtrl; + late TextEditingController _purchasePriceCtrl; + late TextEditingController _playTimeHoursCtrl; + late TextEditingController _playTimeMinutesCtrl; + List _editPlatforms = []; + List _editVersions = []; + List _editGenres = []; + List _editPurchasePlatforms = []; + String? _editCoverPath; + String _editStatus = 'want_to_play'; + String _editCategory = 'digital'; + DateTime? _editPurchaseDate; + bool _editIsDownloading = false; + final ImagePicker _picker = ImagePicker(); + @override void initState() { super.initState(); _detailStyle = UserPrefs().detailPageStyle; _coverOffset.value = UserPrefs().getCoverOffset(widget.game.id); + _initEditControllers(); _detectCoverAspect(); } + void _initEditControllers() { + final g = widget.game; + _titleCtrl = TextEditingController(text: g.title); + _summaryCtrl = TextEditingController(text: g.summary ?? ''); + _ratingCtrl = TextEditingController(text: g.rating?.toString() ?? ''); + _purchasePriceCtrl = TextEditingController(text: g.purchasePrice ?? ''); + _playTimeHoursCtrl = TextEditingController(text: g.playTimeHours > 0 ? g.playTimeHours.toString() : ''); + _playTimeMinutesCtrl = TextEditingController(text: g.playTimeMinutes > 0 ? g.playTimeMinutes.toString() : ''); + _editPlatforms = List.from(g.platforms); + _editVersions = List.from(g.versions); + _editGenres = List.from(g.genres); + _editPurchasePlatforms = List.from(g.purchasePlatforms); + _editCoverPath = g.coverPath; + _editStatus = g.status; + _editCategory = g.category; + _editPurchaseDate = g.purchaseDate; + } + + void _enterEditMode() { + // 从 provider 获取最新数据 + final latest = context.read().games + .where((g) => g.id == widget.game.id).firstOrNull ?? widget.game; + _titleCtrl.text = latest.title; + _summaryCtrl.text = latest.summary ?? ''; + _ratingCtrl.text = latest.rating?.toString() ?? ''; + _purchasePriceCtrl.text = latest.purchasePrice ?? ''; + _playTimeHoursCtrl.text = latest.playTimeHours > 0 ? latest.playTimeHours.toString() : ''; + _playTimeMinutesCtrl.text = latest.playTimeMinutes > 0 ? latest.playTimeMinutes.toString() : ''; + _editPlatforms = List.from(latest.platforms); + _editVersions = List.from(latest.versions); + _editGenres = List.from(latest.genres); + _editPurchasePlatforms = List.from(latest.purchasePlatforms); + _editCoverPath = latest.coverPath; + _editStatus = latest.status; + _editCategory = latest.category; + _editPurchaseDate = latest.purchaseDate; + setState(() => _isEditing = true); + } + Future _detectCoverAspect() async { final path = widget.game.coverPath; if (path == null || path.isEmpty || path.startsWith('http')) return; @@ -64,6 +130,12 @@ class _GameDetailPageState extends State { void dispose() { _coverOffset.dispose(); _draggingCover.dispose(); + _titleCtrl.dispose(); + _summaryCtrl.dispose(); + _ratingCtrl.dispose(); + _purchasePriceCtrl.dispose(); + _playTimeHoursCtrl.dispose(); + _playTimeMinutesCtrl.dispose(); super.dispose(); } @@ -84,6 +156,7 @@ class _GameDetailPageState extends State { /// 桌面端左右分栏布局 Widget _buildDesktopStyle(Game game, ColorScheme colors) { + if (_isEditing) return _buildDesktopEditStyle(game, colors); final hasCover = game.coverPath != null && game.coverPath!.isNotEmpty; return Scaffold( backgroundColor: colors.surface, @@ -150,16 +223,14 @@ class _GameDetailPageState extends State { Text(game.title, style: TextStyle(fontSize: 24, fontWeight: FontWeight.w600, color: colors.onSurface, height: 1.3)), const SizedBox(height: 16), - Row(children: [ + Wrap(spacing: 6, runSpacing: 4, crossAxisAlignment: WrapCrossAlignment.center, children: [ if (game.rating != null) ...[ Icon(Icons.star, size: 20, color: colors.onSurface), const SizedBox(width: 4), Text(game.rating!.toStringAsFixed(1), style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: colors.onSurface)), - const SizedBox(width: 16), ], _buildStatusTag(game), - const SizedBox(width: 6), _buildCategoryTag(game), ]), Divider(height: 32, thickness: 0.5, color: colors.outline), @@ -252,7 +323,7 @@ class _GameDetailPageState extends State { ), const SizedBox(width: 12), FilledButton.icon( - onPressed: () => _navigateToEdit(context), + onPressed: _enterEditMode, icon: const Icon(Icons.edit_outlined, size: 16), label: const Text('编辑'), style: FilledButton.styleFrom( @@ -267,6 +338,584 @@ class _GameDetailPageState extends State { ); } + // ─── 桌面端编辑模式 ────────────────────────────────────────── + + static const _gameStatuses = [ + ('通关', 'completed'), ('在玩', 'playing'), ('想玩', 'want_to_play'), ('弃游', 'abandoned'), + ]; + + static const _gameCategories = [ + ('数字版', 'digital'), ('卡带版', 'cartridge'), ('光盘版', 'disc'), + ]; + + Widget _buildDesktopEditStyle(Game game, ColorScheme colors) { + final hasCover = _editCoverPath != null && _editCoverPath!.isNotEmpty; + return Scaffold( + backgroundColor: colors.surface, + body: Form( + key: _editFormKey, + child: Column( + children: [ + // 顶栏 + Container( + height: 48, + decoration: BoxDecoration( + color: colors.surface, + border: Border(bottom: BorderSide(color: colors.outlineVariant, width: 0.5)), + ), + child: Row(children: [ + IconButton( + icon: Icon(Icons.close, color: colors.onSurface, size: 18), + onPressed: () => setState(() => _isEditing = false), + ), + Expanded( + child: Text('编辑游戏', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: colors.onSurface)), + ), + FilledButton.icon( + onPressed: _saveEdit, + icon: const Icon(Icons.check, size: 16), + label: const Text('保存'), + style: FilledButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + const SizedBox(width: 12), + ]), + ), + // 主体:左封面+右表单 + Expanded( + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 左侧:封面 + 状态/评分/分类 + Container( + width: 240, + padding: const EdgeInsets.all(20), + child: Column( + children: [ + // 封面 + GestureDetector( + onTap: _showEditCoverOptions, + child: Container( + width: 200, height: 280, + decoration: BoxDecoration( + color: colors.surfaceContainerHighest, + borderRadius: BorderRadius.circular(12), + ), + clipBehavior: Clip.antiAlias, + child: Stack(alignment: Alignment.center, children: [ + hasCover + ? FadeInLocalImage(path: _editCoverPath, fit: BoxFit.cover) + : Column(mainAxisAlignment: MainAxisAlignment.center, children: [ + Icon(Icons.image_outlined, size: 32, color: colors.onSurface.withValues(alpha: 0.25)), + const SizedBox(height: 8), + Text('点击添加封面', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.35))), + ]), + if (_editIsDownloading) + Container(color: Colors.black.withValues(alpha: 0.4), + child: const CircularProgressIndicator(strokeWidth: 2, color: Colors.white)), + ]), + ), + ), + if (hasCover) + Padding( + padding: const EdgeInsets.only(top: 8), + child: GestureDetector( + onTap: () => setState(() => _editCoverPath = null), + child: Text('移除封面', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.5)))), + ), + const SizedBox(height: 20), + // 状态 + _buildEditSectionLabel('状态', colors), + const SizedBox(height: 6), + Container( + padding: const EdgeInsets.all(2), + decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(6)), + child: Wrap( + spacing: 0, runSpacing: 4, + children: _gameStatuses.map((s) => _buildEditStatusChip(s.$1, s.$2, colors)).toList(), + ), + ), + const SizedBox(height: 16), + // 评分 + _buildEditSectionLabel('评分', colors), + const SizedBox(height: 6), + Row(children: [ + ...List.generate(5, (i) { + final starVal = i + 1; + final currentRating = double.tryParse(_ratingCtrl.text) ?? 0; + final starRating = currentRating / 2; + final isFilled = starVal <= starRating; + final isHalf = starVal == starRating.ceil() && starRating % 1 != 0; + return GestureDetector( + onTap: () => setState(() => _ratingCtrl.text = (starVal * 2).toString()), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 1), + child: Icon( + isHalf ? Icons.star_half : (isFilled ? Icons.star : Icons.star_border), + size: 20, color: (isFilled || isHalf) ? const Color(0xFFFFB800) : colors.outline, + ), + ), + ); + }), + const SizedBox(width: 8), + Container( + width: 48, height: 28, + decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(6)), + child: TextFormField( + controller: _ratingCtrl, + keyboardType: const TextInputType.numberWithOptions(decimal: true), + textAlign: TextAlign.center, + inputFormatters: [_RatingInputFormatter()], + style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: colors.onSurface), + decoration: InputDecoration( + hintText: '0-10', hintStyle: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.25)), + border: InputBorder.none, contentPadding: const EdgeInsets.symmetric(vertical: 6), isDense: true, + ), + onChanged: (_) => setState(() {}), + ), + ), + if (_ratingCtrl.text.isNotEmpty) ...[ + const SizedBox(width: 4), + GestureDetector( + onTap: () => setState(() => _ratingCtrl.clear()), + child: Icon(Icons.close, size: 14, color: colors.onSurface.withValues(alpha: 0.3)), + ), + ], + ]), + const SizedBox(height: 16), + // 分类 + _buildEditSectionLabel('分类', colors), + const SizedBox(height: 6), + Wrap(spacing: 4, runSpacing: 4, children: _gameCategories.map((c) { + final selected = _editCategory == c.$2; + return GestureDetector( + onTap: () => setState(() => _editCategory = c.$2), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: selected ? colors.primary : colors.surfaceContainerHighest, + borderRadius: BorderRadius.circular(4), + ), + child: Text(c.$1, style: TextStyle( + fontSize: 11, fontWeight: selected ? FontWeight.w500 : FontWeight.normal, + color: selected ? colors.onPrimary : colors.onSurface.withValues(alpha: 0.5), + )), + ), + ); + }).toList()), + ], + ), + ), + // 右侧:可滚动表单 + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(0, 20, 24, 80), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 名称 + _buildEditField('名称', _titleCtrl, hint: '游戏名称', required: true), + const SizedBox(height: 16), + // 平台 + _buildEditChipField('平台', _editPlatforms, onTap: () async { + final provider = context.read(); + final data = provider.games.map((g) => g.platforms).toList(); + final result = await GenreSelectorPage.show( + context: context, title: '选择平台', + existingTagsFuture: compute(_collectUnique, data), + initialSelected: _editPlatforms, hint: '如:Switch、PS5、Steam', + ); + if (result != null) setState(() => _editPlatforms = result); + }), + const SizedBox(height: 16), + // 版本 + _buildEditChipField('版本', _editVersions, onTap: () async { + final provider = context.read(); + final data = provider.games.map((g) => g.versions).toList(); + final result = await GenreSelectorPage.show( + context: context, title: '选择版本', + existingTagsFuture: compute(_collectUnique, data), + initialSelected: _editVersions, hint: '如:标准版、豪华版', + ); + if (result != null) setState(() => _editVersions = result); + }), + const SizedBox(height: 16), + // 类型 + _buildEditChipField('类型', _editGenres, onTap: () async { + final provider = context.read(); + final tags = await provider.getTags('game_genre', excludeHidden: true); + final names = tags.map((t) => t['name'] as String).toList(); + if (!mounted) return; + final result = await GenreSelectorPage.show( + context: context, title: '选择类型', existingTags: names, + initialSelected: _editGenres, hint: '如:RPG、动作、冒险', + ); + if (result != null) setState(() => _editGenres = result); + }), + const SizedBox(height: 16), + // 购买平台 + _buildEditChipField('购买平台', _editPurchasePlatforms, onTap: () async { + final provider = context.read(); + final data = provider.games.map((g) => g.purchasePlatforms).toList(); + final result = await GenreSelectorPage.show( + context: context, title: '选择购买平台', + existingTagsFuture: compute(_collectUnique, data), + initialSelected: _editPurchasePlatforms, hint: '如:eShop、Steam、PS Store', + ); + if (result != null) setState(() => _editPurchasePlatforms = result); + }), + const SizedBox(height: 16), + // 购买价格 + _buildEditField('购买价格', _purchasePriceCtrl, hint: '如:298'), + const SizedBox(height: 16), + // 游玩时长 + _buildEditSectionLabel('游玩时长', colors), + const SizedBox(height: 6), + Row(children: [ + Container( + width: 80, + child: TextFormField( + controller: _playTimeHoursCtrl, + keyboardType: TextInputType.number, + inputFormatters: [FilteringTextInputFormatter.digitsOnly], + style: TextStyle(fontSize: 14, color: colors.onSurface), + decoration: InputDecoration( + hintText: '小时', hintStyle: TextStyle(color: colors.onSurface.withValues(alpha: 0.25)), + filled: true, fillColor: colors.surfaceContainerHighest.withValues(alpha: 0.5), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + isDense: true, + ), + ), + ), + const SizedBox(width: 8), + Text('小时', style: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.4))), + const SizedBox(width: 12), + Container( + width: 80, + child: TextFormField( + controller: _playTimeMinutesCtrl, + keyboardType: TextInputType.number, + inputFormatters: [FilteringTextInputFormatter.digitsOnly], + style: TextStyle(fontSize: 14, color: colors.onSurface), + decoration: InputDecoration( + hintText: '分钟', hintStyle: TextStyle(color: colors.onSurface.withValues(alpha: 0.25)), + filled: true, fillColor: colors.surfaceContainerHighest.withValues(alpha: 0.5), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + isDense: true, + ), + ), + ), + const SizedBox(width: 8), + Text('分钟', style: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.4))), + ]), + const SizedBox(height: 16), + // 购买日期 + _buildEditDateField('购买日期', _editPurchaseDate, (d) => setState(() => _editPurchaseDate = d), clearable: true), + const SizedBox(height: 16), + // 简介 + _buildEditSectionLabel('游戏简介', colors), + const SizedBox(height: 6), + Container( + constraints: const BoxConstraints(minHeight: 120), + child: TextFormField( + controller: _summaryCtrl, + maxLines: null, + style: TextStyle(fontSize: 14, color: colors.onSurface, height: 1.6), + decoration: InputDecoration( + hintText: '写下游戏简介...', + hintStyle: TextStyle(color: colors.onSurface.withValues(alpha: 0.25)), + filled: true, fillColor: colors.surfaceContainerHighest.withValues(alpha: 0.5), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none), + contentPadding: const EdgeInsets.all(12), + ), + ), + ), + ], + ), + ), + ), + ], + ), + ), + // 底部操作栏 + Container( + height: 48, + decoration: BoxDecoration( + color: colors.surface, + border: Border(top: BorderSide(color: colors.outlineVariant, width: 0.5)), + ), + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + OutlinedButton.icon( + onPressed: () => _showDeleteDialog(context), + icon: Icon(Icons.delete_outline, size: 16, color: colors.error), + label: Text('删除', style: TextStyle(color: colors.error)), + style: OutlinedButton.styleFrom( + side: BorderSide(color: colors.error.withValues(alpha: 0.3)), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ], + ), + ), + ], + ), + ), + ); + } + + Widget _buildEditSectionLabel(String label, ColorScheme colors) { + return Text(label, style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))); + } + + Widget _buildEditStatusChip(String label, String value, ColorScheme colors) { + final selected = _editStatus == value; + return GestureDetector( + onTap: () => setState(() => _editStatus = value), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6), + decoration: BoxDecoration( + color: selected ? colors.surface : Colors.transparent, + borderRadius: BorderRadius.circular(6), + boxShadow: selected ? [BoxShadow(color: colors.onSurface.withValues(alpha: 0.03), blurRadius: 4, offset: const Offset(0, 2))] : null, + ), + child: Text(label, style: TextStyle( + fontSize: 13, fontWeight: selected ? FontWeight.w500 : FontWeight.normal, + color: selected ? colors.onSurface : colors.onSurface.withValues(alpha: 0.4), + )), + ), + ); + } + + Widget _buildEditField(String label, TextEditingController ctrl, {String hint = '', bool required = false}) { + final colors = Theme.of(context).colorScheme; + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(required ? '$label *' : label, style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))), + const SizedBox(height: 6), + TextFormField( + controller: ctrl, + style: TextStyle(fontSize: 14, color: colors.onSurface), + validator: required ? (v) => (v == null || v.trim().isEmpty) ? '请输入$label' : null : null, + decoration: InputDecoration( + hintText: hint, hintStyle: TextStyle(color: colors.onSurface.withValues(alpha: 0.25)), + filled: true, fillColor: colors.surfaceContainerHighest.withValues(alpha: 0.5), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + isDense: true, + ), + ), + ]); + } + + Widget _buildEditChipField(String label, List chips, {required VoidCallback onTap}) { + final colors = Theme.of(context).colorScheme; + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(label, style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))), + const SizedBox(height: 6), + GestureDetector( + onTap: onTap, + child: Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), + decoration: BoxDecoration( + color: colors.surfaceContainerHighest.withValues(alpha: 0.5), + borderRadius: BorderRadius.circular(8), + ), + child: chips.isEmpty + ? Text('点击选择$label', style: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.25))) + : Wrap(spacing: 4, runSpacing: 4, children: chips.map((c) => Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration(color: colors.surface, borderRadius: BorderRadius.circular(4)), + child: Text(c, style: TextStyle(fontSize: 12, color: colors.onSurface)), + )).toList()), + ), + ), + ]); + } + + Widget _buildEditDateField(String label, DateTime? date, ValueChanged onChanged, {bool clearable = false}) { + final colors = Theme.of(context).colorScheme; + final hasDate = date != null; + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(label, style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))), + const SizedBox(height: 6), + GestureDetector( + onTap: () async { + final picked = await showDatePicker( + context: context, initialDate: date ?? DateTime.now(), + firstDate: DateTime(1900), lastDate: DateTime.now().add(const Duration(days: 365 * 5)), + ); + if (picked != null) onChanged(picked); + }, + child: Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: BoxDecoration( + color: colors.surfaceContainerHighest.withValues(alpha: 0.5), + borderRadius: BorderRadius.circular(8), + ), + child: Row(children: [ + Icon(Icons.calendar_today_outlined, size: 14, color: colors.onSurface.withValues(alpha: 0.4)), + const SizedBox(width: 8), + Text(hasDate ? '${date!.year}.${date!.month.toString().padLeft(2, '0')}.${date!.day.toString().padLeft(2, '0')}' : '选择日期', + style: TextStyle(fontSize: 14, color: hasDate ? colors.onSurface : colors.onSurface.withValues(alpha: 0.25))), + const Spacer(), + if (clearable && hasDate) + GestureDetector( + onTap: () => onChanged(null), + child: Icon(Icons.close, size: 14, color: colors.onSurface.withValues(alpha: 0.3)), + ), + ]), + ), + ), + ]); + } + + void _showEditCoverOptions() { + final colors = Theme.of(context).colorScheme; + showModalBottomSheet( + context: context, backgroundColor: colors.surface, + shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(16))), + builder: (ctx) => SafeArea( + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 16), + child: Column(mainAxisSize: MainAxisSize.min, children: [ + Container(width: 40, height: 4, decoration: BoxDecoration(color: colors.outline, borderRadius: BorderRadius.circular(2))), + const SizedBox(height: 20), + Padding(padding: const EdgeInsets.symmetric(horizontal: 24), child: Align(alignment: Alignment.centerLeft, + child: Text('添加封面', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: colors.onSurface)))), + const SizedBox(height: 16), + ListTile(leading: Icon(Icons.photo_library_outlined, color: colors.onSurface.withValues(alpha: 0.6)), + title: Text('从相册选择', style: TextStyle(color: colors.onSurface)), + onTap: () { Navigator.pop(ctx); _pickEditCover(); }), + ListTile(leading: Icon(Icons.link_outlined, color: colors.onSurface.withValues(alpha: 0.6)), + title: Text('网络链接', style: TextStyle(color: colors.onSurface)), + onTap: () { Navigator.pop(ctx); _pickEditCoverFromUrl(); }), + ]), + ), + ), + ); + } + + Future _pickEditCover() async { + try { + final XFile? picked = await _picker.pickImage(source: ImageSource.gallery, maxWidth: 800, maxHeight: 1200, imageQuality: 85); + if (picked == null) return; + final fileName = 'cover_${DateTime.now().millisecondsSinceEpoch}.jpg'; + final targetPath = await ImagePathHelper.instance.getGameCoverPath(widget.game.id, fileName); + await ImagePathHelper.instance.ensureDirExists(p.dirname(targetPath)); + await File(picked.path).copy(targetPath); + if (mounted) setState(() => _editCoverPath = targetPath); + } catch (e) { + if (mounted) ToastUtil.show(context, '选择封面失败: $e'); + } + } + + Future _pickEditCoverFromUrl() async { + final urlCtrl = TextEditingController(); + final confirmed = await showDialog(context: context, builder: (ctx) { + final colors = Theme.of(ctx).colorScheme; + return AlertDialog( + backgroundColor: colors.surface, elevation: 0, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + title: Text('添加网络图片', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: colors.onSurface)), + content: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text('请输入图片链接地址', style: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.6))), + const SizedBox(height: 12), + TextField(controller: urlCtrl, keyboardType: TextInputType.url, + style: TextStyle(fontSize: 14, color: colors.onSurface), + decoration: InputDecoration(hintText: 'https://example.com/image.jpg', + hintStyle: TextStyle(color: colors.onSurface.withValues(alpha: 0.25)), + filled: true, fillColor: colors.surfaceContainerHigh, + contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none), + enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none), + focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide(color: colors.primary, width: 1)), + )), + ]), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text('取消', style: TextStyle(color: colors.onSurface.withValues(alpha: 0.6)))), + ElevatedButton(onPressed: () => Navigator.pop(ctx, true), + style: ElevatedButton.styleFrom(backgroundColor: colors.primary, foregroundColor: colors.onPrimary, elevation: 0, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8)), + child: const Text('确定')), + ], + ); + }); + final url = urlCtrl.text.trim(); + urlCtrl.dispose(); + if (confirmed != true || url.isEmpty) return; + await _downloadEditCoverFromUrl(url); + } + + Future _downloadEditCoverFromUrl(String url) async { + setState(() => _editIsDownloading = true); + try { + final response = await http.get(Uri.parse(url), headers: { + 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15', + 'Accept': 'image/avif,image/webp,image/apng,*/*;q=0.8', + 'Referer': Uri.parse(url).replace(path: '/').toString(), + }); + if (response.statusCode != 200) throw Exception('下载失败: HTTP ${response.statusCode}'); + final contentType = response.headers['content-type']; + if (contentType != null && !contentType.startsWith('image/')) throw Exception('链接返回的不是图片'); + if (response.bodyBytes.length > 10 * 1024 * 1024) throw Exception('图片太大'); + final fileName = 'cover_${DateTime.now().millisecondsSinceEpoch}.jpg'; + final targetPath = await ImagePathHelper.instance.getGameCoverPath(widget.game.id, fileName); + await ImagePathHelper.instance.ensureDirExists(p.dirname(targetPath)); + await File(targetPath).writeAsBytes(response.bodyBytes); + if (mounted) setState(() => _editCoverPath = targetPath); + } catch (e) { + if (mounted) ToastUtil.show(context, '下载失败: $e'); + } finally { + if (mounted) setState(() => _editIsDownloading = false); + } + } + + Future _saveEdit() async { + if (!_editFormKey.currentState!.validate()) return; + try { + final rating = _ratingCtrl.text.isNotEmpty ? double.tryParse(_ratingCtrl.text) : null; + final updated = widget.game.copyWith( + title: _titleCtrl.text.trim(), + coverPath: _editCoverPath, + platforms: _editPlatforms, + versions: _editVersions, + genres: _editGenres, + purchasePlatforms: _editPurchasePlatforms, + purchasePrice: _purchasePriceCtrl.text.trim().isEmpty ? null : _purchasePriceCtrl.text.trim(), + playTimeHours: int.tryParse(_playTimeHoursCtrl.text) ?? 0, + playTimeMinutes: int.tryParse(_playTimeMinutesCtrl.text) ?? 0, + summary: _summaryCtrl.text.trim(), + rating: rating, + status: _editStatus, + category: _editCategory, + purchaseDate: _editPurchaseDate, + updatedAt: DateTime.now(), + ); + await context.read().updateGame(updated); + if (!mounted) return; + ToastUtil.show(context, '更新成功'); + setState(() => _isEditing = false); + } catch (e) { + if (mounted) ToastUtil.show(context, '保存失败: $e'); + } + } + + /// 从多值字段列表中提取去重排序的唯一值(供 compute 使用) + static List _collectUnique(List> lists) { + final s = {}; + for (final l in lists) { s.addAll(l); } + return s.toList()..sort(); + } + Widget _buildDesktopInfoRow(String label, String value, ColorScheme colors) { return Padding( padding: const EdgeInsets.symmetric(vertical: 6), @@ -1188,3 +1837,16 @@ class _GameDetailPageState extends State { ); } } + +/// 评分输入格式化器:只允许 0-10,最多1位小数 +class _RatingInputFormatter extends TextInputFormatter { + @override + TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { + final text = newValue.text; + if (text.isEmpty) return newValue; + if (!RegExp(r'^\d{0,2}\.?\d{0,1}$').hasMatch(text)) return oldValue; + final n = double.tryParse(text); + if (n != null && n > 10) return oldValue; + return newValue; + } +} diff --git a/lib/pages/game/game_tab_page.dart b/lib/pages/game/game_tab_page.dart index ae169c5..82e5ab0 100644 --- a/lib/pages/game/game_tab_page.dart +++ b/lib/pages/game/game_tab_page.dart @@ -12,6 +12,7 @@ import '../../utils/responsive.dart'; import '../../widgets/master_detail_scaffold.dart'; import '../../widgets/detail_placeholder.dart'; import 'game_detail_page.dart'; +import 'game_add_page.dart'; /// 游戏标签页(分页 + 触底加载) class GameTabPage extends StatefulWidget { @@ -180,11 +181,14 @@ class _GameTabPageState extends State { if (!isWideContent) return masterContent; final selectedGame = provider.selectedGame; + final detailWidget = provider.isAdding && provider.addingType == 3 + ? GameAddPage(onCancel: () => provider.cancelAdding()) + : selectedGame != null + ? GameDetailPage(game: selectedGame, embedded: true) + : const DetailPlaceholder(icon: Icons.sports_esports_outlined, message: '选择一款游戏查看详情'); return MasterDetailScaffold( master: masterContent, - detail: selectedGame != null - ? GameDetailPage(game: selectedGame, embedded: true) - : const DetailPlaceholder(icon: Icons.sports_esports_outlined, message: '选择一款游戏查看详情'), + detail: detailWidget, ); } diff --git a/lib/pages/home/home_page.dart b/lib/pages/home/home_page.dart index a4cf8ae..32de9d1 100644 --- a/lib/pages/home/home_page.dart +++ b/lib/pages/home/home_page.dart @@ -12,6 +12,7 @@ import '../../utils/toast_util.dart'; import '../../widgets/custom_drawer.dart'; import '../../widgets/bottom_nav_bar.dart'; import '../../widgets/add_sheet.dart'; +import '../../widgets/add_type_selector.dart'; import '../../widgets/fade_in_local_image.dart'; import '../../pages/epub_reader/epub_library_page.dart'; import '../../pages/movies/movie_detail_page.dart'; @@ -328,7 +329,16 @@ class _DesktopIconRail extends StatelessWidget { _buildProfileHeader(context), const SizedBox(height: 10), // 添加 + 搜索 - _IconRailItem(icon: Icons.add_circle_outline, activeIcon: Icons.add_circle, label: '添加', accentColor: colors.primary, selected: false, onTap: () => showAddSheet(context, context.read())), + _IconRailItem(icon: Icons.add_circle_outline, activeIcon: Icons.add_circle, label: '添加', accentColor: colors.primary, selected: false, onTap: () { + final provider = context.read(); + if (Breakpoint.isDesktop(context)) { + showAddTypeSelector(context).then((type) { + if (type != null) provider.startAddingType(type); + }); + } else { + showAddSheet(context, provider); + } + }), _IconRailItem(icon: Icons.search, activeIcon: Icons.search, label: '搜索', accentColor: colors.primary, selected: false, onTap: () => _showSearchDialog(context)), const SizedBox(height: 2), // 分类图标 @@ -3546,7 +3556,7 @@ class _SearchDialogState extends State<_SearchDialog> { Widget _toggleBtn(String label, bool selected, VoidCallback onTap, ColorScheme colors) { return Material( - color: selected ? colors.surface : Colors.transparent, + color: selected ? colors.onSurface : Colors.transparent, borderRadius: BorderRadius.circular(8), child: InkWell( onTap: onTap, @@ -3559,7 +3569,7 @@ class _SearchDialogState extends State<_SearchDialog> { Icon( selected ? Icons.search_rounded : Icons.search_outlined, size: 14, - color: selected ? colors.primary : colors.onSurface.withValues(alpha: 0.5), + color: selected ? colors.surface : colors.onSurface.withValues(alpha: 0.5), ), const SizedBox(width: 5), Text( @@ -3567,7 +3577,7 @@ class _SearchDialogState extends State<_SearchDialog> { style: TextStyle( fontSize: 12, fontWeight: selected ? FontWeight.w600 : FontWeight.w400, - color: selected ? colors.primary : colors.onSurface.withValues(alpha: 0.55), + color: selected ? colors.surface : colors.onSurface.withValues(alpha: 0.55), ), ), ], diff --git a/lib/pages/movies/movie_add_page.dart b/lib/pages/movies/movie_add_page.dart new file mode 100644 index 0000000..ba6d957 --- /dev/null +++ b/lib/pages/movies/movie_add_page.dart @@ -0,0 +1,398 @@ +import 'dart:io'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:path/path.dart' as p; +import 'package:provider/provider.dart'; +import 'package:http/http.dart' as http; +import 'package:uuid/uuid.dart'; +import '../../widgets/fade_in_local_image.dart'; +import '../../providers/app_provider.dart'; +import '../../models/data_models.dart'; +import '../../utils/toast_util.dart'; +import '../../utils/image_path_helper.dart'; +import '../../widgets/genre_selector_page.dart'; + +class MovieAddPage extends StatefulWidget { + final VoidCallback? onCancel; + final String? initialStatus; + const MovieAddPage({super.key, this.onCancel, this.initialStatus}); + + @override + State createState() => _MovieAddPageState(); +} + +class _MovieAddPageState extends State { + final _formKey = GlobalKey(); + final ImagePicker _picker = ImagePicker(); + late TextEditingController _titleCtrl; + late TextEditingController _summaryCtrl; + late TextEditingController _ratingCtrl; + List _directors = []; + List _writers = []; + List _actors = []; + List _genres = []; + List _alternateTitles = []; + String? _posterPath; + String _status = 'want_to_watch'; + String _category = 'movie'; + DateTime? _releaseDate; + DateTime? _watchDate; + bool _isDownloading = false; + String? _tempId; + + static const _categories = [ + ('电影', 'movie'), ('电视剧', 'tv'), ('动漫', 'anime'), + ('综艺', 'variety'), ('纪录片', 'documentary'), ('微短剧', 'short'), ('其他', 'other'), + ]; + + @override + void initState() { + super.initState(); + _tempId = const Uuid().v4(); + _status = widget.initialStatus ?? 'want_to_watch'; + _titleCtrl = TextEditingController(); + _summaryCtrl = TextEditingController(); + _ratingCtrl = TextEditingController(); + } + + @override + void dispose() { + _titleCtrl.dispose(); + _summaryCtrl.dispose(); + _ratingCtrl.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final colors = Theme.of(context).colorScheme; + final hasPoster = _posterPath != null && _posterPath!.isNotEmpty; + return Scaffold( + backgroundColor: colors.surface, + body: Form( + key: _formKey, + child: Column( + children: [ + // 顶栏 + Container(height: 48, + decoration: BoxDecoration(color: colors.surface, + border: Border(bottom: BorderSide(color: colors.outlineVariant, width: 0.5))), + child: Row(children: [ + IconButton(icon: Icon(Icons.close, color: colors.onSurface, size: 18), + onPressed: () => widget.onCancel?.call()), + Expanded(child: Text('添加影视', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: colors.onSurface))), + FilledButton.icon(onPressed: _save, + icon: const Icon(Icons.check, size: 16), label: const Text('保存'), + style: FilledButton.styleFrom(padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)))), + const SizedBox(width: 12), + ]), + ), + // 主体:左封面+右表单 + Expanded( + child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ + // 左侧 + Container(width: 240, padding: const EdgeInsets.all(20), child: Column(children: [ + GestureDetector(onTap: _showCoverOptions, child: Container( + width: 200, height: 280, + decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(12)), + clipBehavior: Clip.antiAlias, + child: Stack(alignment: Alignment.center, children: [ + hasPoster ? FadeInLocalImage(path: _posterPath, fit: BoxFit.cover) + : Column(mainAxisAlignment: MainAxisAlignment.center, children: [ + Icon(Icons.image_outlined, size: 32, color: colors.onSurface.withValues(alpha: 0.25)), + const SizedBox(height: 8), + Text('点击添加海报', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.35))), + ]), + if (_isDownloading) Container(color: Colors.black.withValues(alpha: 0.4), + child: const CircularProgressIndicator(strokeWidth: 2, color: Colors.white)), + ]), + )), + if (hasPoster) Padding(padding: const EdgeInsets.only(top: 8), + child: GestureDetector(onTap: () => setState(() => _posterPath = null), + child: Text('移除海报', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.5))))), + const SizedBox(height: 20), + _label('状态', colors), const SizedBox(height: 6), + Container(padding: const EdgeInsets.all(2), + decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(6)), + child: Wrap(spacing: 0, runSpacing: 4, children: [ + _statusChip('想看', 'want_to_watch', colors), _statusChip('在看', 'watching', colors), _statusChip('已看', 'watched', colors), + ])), + const SizedBox(height: 16), + _label('评分', colors), const SizedBox(height: 6), + _buildRatingRow(colors), + const SizedBox(height: 16), + _label('分类', colors), const SizedBox(height: 6), + Wrap(spacing: 4, runSpacing: 4, children: _categories.map((c) { + final sel = _category == c.$2; + return GestureDetector(onTap: () => setState(() => _category = c.$2), + child: Container(padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration(color: sel ? colors.primary : colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(4)), + child: Text(c.$1, style: TextStyle(fontSize: 11, fontWeight: sel ? FontWeight.w500 : FontWeight.normal, + color: sel ? colors.onPrimary : colors.onSurface.withValues(alpha: 0.5))))); + }).toList()), + ])), + // 右侧表单 + Expanded(child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(0, 20, 24, 80), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + _field('名称', _titleCtrl, hint: '影视名称', required: true), const SizedBox(height: 16), + _chipField('别名', _alternateTitles, onTap: () async { + final r = await GenreSelectorPage.show(context: context, title: '添加别名', existingTags: [], initialSelected: _alternateTitles, hint: '输入别名'); + if (r != null) setState(() => _alternateTitles = r); + }), const SizedBox(height: 16), + _chipField('导演', _directors, onTap: () async { + final p = context.read(); final d = p.movies.map((m) => m.directors).toList(); + final r = await GenreSelectorPage.show(context: context, title: '选择导演', existingTagsFuture: compute(_collectUnique, d), initialSelected: _directors, hint: '如:张艺谋'); + if (r != null) setState(() => _directors = r); + }), const SizedBox(height: 16), + _chipField('编剧', _writers, onTap: () async { + final p = context.read(); final d = p.movies.map((m) => m.writers).toList(); + final r = await GenreSelectorPage.show(context: context, title: '选择编剧', existingTagsFuture: compute(_collectUnique, d), initialSelected: _writers, hint: '如:刘慈欣'); + if (r != null) setState(() => _writers = r); + }), const SizedBox(height: 16), + _chipField('主演', _actors, onTap: () async { + final p = context.read(); final d = p.movies.map((m) => m.actors).toList(); + final r = await GenreSelectorPage.show(context: context, title: '选择主演', existingTagsFuture: compute(_collectUnique, d), initialSelected: _actors, hint: '如:梁朝伟'); + if (r != null) setState(() => _actors = r); + }), const SizedBox(height: 16), + _chipField('类型', _genres, onTap: () async { + final p = context.read(); + final tags = await p.getTags('movie_genre', excludeHidden: true); + final names = tags.map((t) => t['name'] as String).toList(); + if (!mounted) return; + final r = await GenreSelectorPage.show(context: context, title: '选择类型', existingTags: names, initialSelected: _genres, hint: '如:剧情、科幻'); + if (r != null) setState(() => _genres = r); + }), const SizedBox(height: 16), + Row(children: [ + Expanded(child: _dateField('上映日期', _releaseDate, (d) => setState(() => _releaseDate = d))), + const SizedBox(width: 12), + Expanded(child: _dateField('观看日期', _watchDate, (d) => setState(() => _watchDate = d), clearable: true)), + ]), const SizedBox(height: 16), + _label('剧情简介', colors), const SizedBox(height: 6), + Container(constraints: const BoxConstraints(minHeight: 120), + child: TextFormField(controller: _summaryCtrl, maxLines: null, + style: TextStyle(fontSize: 14, color: colors.onSurface, height: 1.6), + decoration: InputDecoration(hintText: '写下剧情简介...', hintStyle: TextStyle(color: colors.onSurface.withValues(alpha: 0.25)), + filled: true, fillColor: colors.surfaceContainerHighest.withValues(alpha: 0.5), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none), contentPadding: const EdgeInsets.all(12)))), + ]), + )), + ]), + ), + ], + ), + ), + ); + } + + Widget _label(String l, ColorScheme c) => Text(l, style: TextStyle(fontSize: 12, color: c.onSurface.withValues(alpha: 0.4))); + Widget _statusChip(String label, String value, ColorScheme c) { + final sel = _status == value; + return GestureDetector(onTap: () => setState(() => _status = value), + child: Container(padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6), + decoration: BoxDecoration(color: sel ? c.surface : Colors.transparent, borderRadius: BorderRadius.circular(6), + boxShadow: sel ? [BoxShadow(color: c.onSurface.withValues(alpha: 0.03), blurRadius: 4, offset: const Offset(0, 2))] : null), + child: Text(label, style: TextStyle(fontSize: 13, fontWeight: sel ? FontWeight.w500 : FontWeight.normal, + color: sel ? c.onSurface : c.onSurface.withValues(alpha: 0.4))))); + } + + Widget _buildRatingRow(ColorScheme colors) { + return Row(children: [ + ...List.generate(5, (i) { + final sv = i + 1; final cr = double.tryParse(_ratingCtrl.text) ?? 0; final sr = cr / 2; + final f = sv <= sr; final h = sv == sr.ceil() && sr % 1 != 0; + return GestureDetector(onTap: () => setState(() => _ratingCtrl.text = (sv * 2).toString()), + child: Padding(padding: const EdgeInsets.symmetric(horizontal: 1), + child: Icon(h ? Icons.star_half : (f ? Icons.star : Icons.star_border), size: 20, color: (f || h) ? const Color(0xFFFFB800) : colors.outline))); + }), + const SizedBox(width: 8), + Container(width: 48, height: 28, decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(6)), + child: TextFormField(controller: _ratingCtrl, keyboardType: const TextInputType.numberWithOptions(decimal: true), + textAlign: TextAlign.center, inputFormatters: [_RatingInputFormatter()], + style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: colors.onSurface), + decoration: InputDecoration(hintText: '0-10', hintStyle: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.25)), + border: InputBorder.none, contentPadding: const EdgeInsets.symmetric(vertical: 6), isDense: true), + onChanged: (_) => setState(() {}))), + if (_ratingCtrl.text.isNotEmpty) ...[ + const SizedBox(width: 4), + GestureDetector(onTap: () => setState(() => _ratingCtrl.clear()), + child: Icon(Icons.close, size: 14, color: colors.onSurface.withValues(alpha: 0.3))), + ], + ]); + } + + Widget _field(String label, TextEditingController ctrl, {String hint = '', bool required = false}) { + final c = Theme.of(context).colorScheme; + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(required ? '$label *' : label, style: TextStyle(fontSize: 12, color: c.onSurface.withValues(alpha: 0.4))), + const SizedBox(height: 6), + TextFormField(controller: ctrl, style: TextStyle(fontSize: 14, color: c.onSurface), + validator: required ? (v) => (v == null || v.trim().isEmpty) ? '请输入$label' : null : null, + decoration: InputDecoration(hintText: hint, hintStyle: TextStyle(color: c.onSurface.withValues(alpha: 0.25)), + filled: true, fillColor: c.surfaceContainerHighest.withValues(alpha: 0.5), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), isDense: true)), + ]); + } + + Widget _chipField(String label, List chips, {required VoidCallback onTap}) { + final c = Theme.of(context).colorScheme; + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(label, style: TextStyle(fontSize: 12, color: c.onSurface.withValues(alpha: 0.4))), + const SizedBox(height: 6), + GestureDetector(onTap: onTap, + child: Container(width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), + decoration: BoxDecoration(color: c.surfaceContainerHighest.withValues(alpha: 0.5), borderRadius: BorderRadius.circular(8)), + child: chips.isEmpty + ? Text('点击选择$label', style: TextStyle(fontSize: 14, color: c.onSurface.withValues(alpha: 0.25))) + : Wrap(spacing: 4, runSpacing: 4, children: chips.map((e) => Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration(color: c.surface, borderRadius: BorderRadius.circular(4)), + child: Text(e, style: TextStyle(fontSize: 12, color: c.onSurface)))).toList()))), + ]); + } + + Widget _dateField(String label, DateTime? date, ValueChanged onChanged, {bool clearable = false}) { + final c = Theme.of(context).colorScheme; final has = date != null; + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(label, style: TextStyle(fontSize: 12, color: c.onSurface.withValues(alpha: 0.4))), + const SizedBox(height: 6), + GestureDetector(onTap: () async { + final picked = await showDatePicker(context: context, initialDate: date ?? DateTime.now(), + firstDate: DateTime(1900), lastDate: DateTime.now().add(const Duration(days: 365 * 5))); + if (picked != null) onChanged(picked); + }, child: Container(width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: BoxDecoration(color: c.surfaceContainerHighest.withValues(alpha: 0.5), borderRadius: BorderRadius.circular(8)), + child: Row(children: [ + Icon(Icons.calendar_today_outlined, size: 14, color: c.onSurface.withValues(alpha: 0.4)), + const SizedBox(width: 8), + Text(has ? '${date!.year}.${date!.month.toString().padLeft(2, '0')}.${date!.day.toString().padLeft(2, '0')}' : '选择日期', + style: TextStyle(fontSize: 14, color: has ? c.onSurface : c.onSurface.withValues(alpha: 0.25))), + const Spacer(), + if (clearable && has) GestureDetector(onTap: () => onChanged(null), + child: Icon(Icons.close, size: 14, color: c.onSurface.withValues(alpha: 0.3))), + ]))), + ]); + } + + void _showCoverOptions() { + final c = Theme.of(context).colorScheme; + showModalBottomSheet(context: context, backgroundColor: c.surface, + shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(16))), + builder: (ctx) => SafeArea(child: Padding(padding: const EdgeInsets.symmetric(vertical: 16), + child: Column(mainAxisSize: MainAxisSize.min, children: [ + Container(width: 40, height: 4, decoration: BoxDecoration(color: c.outline, borderRadius: BorderRadius.circular(2))), + const SizedBox(height: 20), + Padding(padding: const EdgeInsets.symmetric(horizontal: 24), child: Align(alignment: Alignment.centerLeft, + child: Text('添加海报', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: c.onSurface)))), + const SizedBox(height: 16), + ListTile(leading: Icon(Icons.photo_library_outlined, color: c.onSurface.withValues(alpha: 0.6)), + title: Text('从相册选择'), onTap: () { Navigator.pop(ctx); _pickCover(); }), + ListTile(leading: Icon(Icons.link_outlined, color: c.onSurface.withValues(alpha: 0.6)), + title: Text('网络链接'), onTap: () { Navigator.pop(ctx); _pickCoverFromUrl(); }), + ])))); + } + + Future _pickCover() async { + try { + final XFile? picked = await _picker.pickImage(source: ImageSource.gallery, maxWidth: 800, maxHeight: 1200, imageQuality: 85); + if (picked == null) return; + final fileName = 'poster_${DateTime.now().millisecondsSinceEpoch}.jpg'; + final targetPath = await ImagePathHelper.instance.getMoviePosterPath(_tempId!, fileName); + await ImagePathHelper.instance.ensureDirExists(p.dirname(targetPath)); + await File(picked.path).copy(targetPath); + if (mounted) setState(() => _posterPath = targetPath); + } catch (e) { if (mounted) ToastUtil.show(context, '选择海报失败: $e'); } + } + + Future _pickCoverFromUrl() async { + final ctrl = TextEditingController(); + final ok = await showDialog(context: context, builder: (ctx) { + final c = Theme.of(ctx).colorScheme; + return AlertDialog(backgroundColor: c.surface, elevation: 0, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + title: Text('添加网络图片', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: c.onSurface)), + content: TextField(controller: ctrl, keyboardType: TextInputType.url, style: TextStyle(fontSize: 14, color: c.onSurface), + decoration: InputDecoration(hintText: 'https://example.com/image.jpg', filled: true, fillColor: c.surfaceContainerHigh, + border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none))), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text('取消')), + ElevatedButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('确定')), + ]); + }); + final url = ctrl.text.trim(); ctrl.dispose(); + if (ok != true || url.isEmpty) return; + await _downloadCover(url); + } + + Future _downloadCover(String url) async { + setState(() => _isDownloading = true); + try { + final res = await http.get(Uri.parse(url), headers: { + 'User-Agent': 'Mozilla/5.0', 'Accept': 'image/*,*/*;q=0.8', 'Referer': Uri.parse(url).replace(path: '/').toString(), + }); + if (res.statusCode != 200) throw Exception('HTTP ${res.statusCode}'); + final fileName = 'poster_${DateTime.now().millisecondsSinceEpoch}.jpg'; + final targetPath = await ImagePathHelper.instance.getMoviePosterPath(_tempId!, fileName); + await ImagePathHelper.instance.ensureDirExists(p.dirname(targetPath)); + await File(targetPath).writeAsBytes(res.bodyBytes); + if (mounted) setState(() => _posterPath = targetPath); + } catch (e) { if (mounted) ToastUtil.show(context, '下载失败: $e'); } + finally { if (mounted) setState(() => _isDownloading = false); } + } + + Future _save() async { + if (!_formKey.currentState!.validate()) return; + try { + final noteId = const Uuid().v4(); + // 移动封面到正式目录 + String? finalPosterPath; + if (_posterPath != null) { + final normalized = _posterPath!.replaceAll('\\', '/'); + if (!normalized.contains('/movies/$noteId/')) { + final fileName = p.basename(_posterPath!); + final newPath = await ImagePathHelper.instance.getMoviePosterPath(noteId, fileName); + await ImagePathHelper.instance.ensureDirExists(p.dirname(newPath)); + final src = File(_posterPath!); + if (await src.exists()) { await src.rename(newPath); finalPosterPath = newPath; } + // 清理临时目录 + final tempDir = Directory(p.dirname(_posterPath!)); + if (await tempDir.exists()) { try { await tempDir.delete(recursive: true); } catch (_) {} } + } else { finalPosterPath = _posterPath; } + } + final rating = _ratingCtrl.text.isNotEmpty ? double.tryParse(_ratingCtrl.text) : null; + final now = DateTime.now(); + final movie = Movie( + id: noteId, title: _titleCtrl.text.trim(), posterPath: finalPosterPath, + releaseDate: _releaseDate, directors: _directors, writers: _writers, actors: _actors, + genres: _genres, alternateTitles: _alternateTitles, summary: _summaryCtrl.text.trim(), + rating: rating, status: _status, category: _category, watchDate: _watchDate, + createdAt: now, updatedAt: now, + ); + await context.read().addMovie(movie); + await context.read().loadMovies(); + if (!mounted) return; + context.read().finishAdding(); + ToastUtil.show(context, '添加成功'); + } catch (e) { if (mounted) ToastUtil.show(context, '保存失败: $e'); } + } + + static List _collectUnique(List> lists) { + final s = {}; for (final l in lists) { s.addAll(l); } return s.toList()..sort(); + } +} + +class _RatingInputFormatter extends TextInputFormatter { + @override + TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { + final text = newValue.text; + if (text.isEmpty) return newValue; + if (!RegExp(r'^\d{0,2}\.?\d{0,1}$').hasMatch(text)) return oldValue; + final n = double.tryParse(text); + if (n != null && n > 10) return oldValue; + return newValue; + } +} diff --git a/lib/pages/movies/movie_detail_page.dart b/lib/pages/movies/movie_detail_page.dart index ac14e3e..88100f2 100644 --- a/lib/pages/movies/movie_detail_page.dart +++ b/lib/pages/movies/movie_detail_page.dart @@ -1,14 +1,20 @@ import 'dart:io'; import 'dart:ui' as ui; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:path/path.dart' as p; import 'package:provider/provider.dart'; +import 'package:http/http.dart' as http; import '../../widgets/fade_in_local_image.dart'; import '../../providers/app_provider.dart'; import '../../models/data_models.dart'; import '../../utils/user_prefs.dart'; import '../../utils/toast_util.dart'; +import '../../utils/image_path_helper.dart'; import '../../utils/responsive.dart'; +import '../../widgets/genre_selector_page.dart'; import 'movie_reviews_page.dart'; import 'movie_posters_page.dart'; import 'movie_share_page.dart'; @@ -35,12 +41,69 @@ class _MovieDetailPageState extends State { final ValueNotifier _showTitle = ValueNotifier(false); ScrollController? _overlayScrollController; + // ─── 编辑模式 ─── + bool _isEditing = false; + final _editFormKey = GlobalKey(); + late TextEditingController _titleCtrl; + late TextEditingController _summaryCtrl; + late TextEditingController _ratingCtrl; + List _editDirectors = []; + List _editWriters = []; + List _editActors = []; + List _editGenres = []; + List _editAlternateTitles = []; + String? _editPosterPath; + String _editStatus = 'want_to_watch'; + String _editCategory = 'movie'; + DateTime? _editReleaseDate; + DateTime? _editWatchDate; + bool _editIsDownloading = false; + final ImagePicker _picker = ImagePicker(); + @override void initState() { super.initState(); _showExactDate = UserPrefs().showExactReleaseDate; _detailStyle = UserPrefs().detailPageStyle; _posterOffset.value = UserPrefs().getCoverOffset(widget.movie.id); + _initEditControllers(); + } + + void _initEditControllers() { + final m = widget.movie; + _titleCtrl = TextEditingController(text: m.title); + _summaryCtrl = TextEditingController(text: m.summary ?? ''); + _ratingCtrl = TextEditingController(text: m.rating?.toString() ?? ''); + _editDirectors = List.from(m.directors); + _editWriters = List.from(m.writers); + _editActors = List.from(m.actors); + _editGenres = List.from(m.genres); + _editAlternateTitles = List.from(m.alternateTitles); + _editPosterPath = m.posterPath; + _editStatus = m.status; + _editCategory = m.category; + _editReleaseDate = m.releaseDate; + _editWatchDate = m.watchDate; + } + + void _enterEditMode() { + // 从 provider 获取最新数据 + final latest = context.read().movies + .where((m) => m.id == widget.movie.id).firstOrNull ?? widget.movie; + _titleCtrl.text = latest.title; + _summaryCtrl.text = latest.summary ?? ''; + _ratingCtrl.text = latest.rating?.toString() ?? ''; + _editDirectors = List.from(latest.directors); + _editWriters = List.from(latest.writers); + _editActors = List.from(latest.actors); + _editGenres = List.from(latest.genres); + _editAlternateTitles = List.from(latest.alternateTitles); + _editPosterPath = latest.posterPath; + _editStatus = latest.status; + _editCategory = latest.category; + _editReleaseDate = latest.releaseDate; + _editWatchDate = latest.watchDate; + setState(() => _isEditing = true); } @override @@ -49,6 +112,9 @@ class _MovieDetailPageState extends State { _draggingPoster.dispose(); _showTitle.dispose(); _overlayScrollController?.dispose(); + _titleCtrl.dispose(); + _summaryCtrl.dispose(); + _ratingCtrl.dispose(); super.dispose(); } @@ -74,6 +140,7 @@ class _MovieDetailPageState extends State { /// 桌面端左右分栏布局 Widget _buildDesktopStyle(Movie movie, ColorScheme colors) { + if (_isEditing) return _buildDesktopEditStyle(movie, colors); final hasPoster = movie.posterPath != null && movie.posterPath!.isNotEmpty; return Scaffold( backgroundColor: colors.surface, @@ -147,16 +214,14 @@ class _MovieDetailPageState extends State { ], const SizedBox(height: 16), // 评分 + 状态 + 分类 - Row(children: [ + Wrap(spacing: 6, runSpacing: 4, crossAxisAlignment: WrapCrossAlignment.center, children: [ if (movie.rating != null) ...[ Icon(Icons.star, size: 20, color: colors.onSurface), const SizedBox(width: 4), Text(movie.rating!.toStringAsFixed(1), style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: colors.onSurface)), - const SizedBox(width: 16), ], _buildStatusTag(movie), - const SizedBox(width: 6), _buildCategoryTag(movie), ]), const SizedBox(height: 8), @@ -261,7 +326,7 @@ class _MovieDetailPageState extends State { ), const SizedBox(width: 12), FilledButton.icon( - onPressed: () => _navigateToEdit(context), + onPressed: _enterEditMode, icon: const Icon(Icons.edit_outlined, size: 16), label: const Text('编辑'), style: FilledButton.styleFrom( @@ -276,6 +341,548 @@ class _MovieDetailPageState extends State { ); } + // ─── 桌面端编辑模式 ────────────────────────────────────────── + + static const _categories = [ + ('电影', 'movie'), ('电视剧', 'tv'), ('动漫', 'anime'), + ('综艺', 'variety'), ('纪录片', 'documentary'), ('微短剧', 'short'), ('其他', 'other'), + ]; + + Widget _buildDesktopEditStyle(Movie movie, ColorScheme colors) { + final hasPoster = _editPosterPath != null && _editPosterPath!.isNotEmpty; + return Scaffold( + backgroundColor: colors.surface, + body: Form( + key: _editFormKey, + child: Column( + children: [ + // 顶栏 + Container( + height: 48, + decoration: BoxDecoration( + color: colors.surface, + border: Border(bottom: BorderSide(color: colors.outlineVariant, width: 0.5)), + ), + child: Row(children: [ + IconButton( + icon: Icon(Icons.close, color: colors.onSurface, size: 18), + onPressed: () => setState(() => _isEditing = false), + ), + Expanded( + child: Text('编辑影视', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: colors.onSurface)), + ), + FilledButton.icon( + onPressed: _saveEdit, + icon: const Icon(Icons.check, size: 16), + label: const Text('保存'), + style: FilledButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + const SizedBox(width: 12), + ]), + ), + // 主体:左封面+右表单 + Expanded( + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 左侧:封面 + 状态/评分/分类 + Container( + width: 240, + padding: const EdgeInsets.all(20), + child: Column( + children: [ + // 封面 + GestureDetector( + onTap: _showEditCoverOptions, + child: Container( + width: 200, height: 280, + decoration: BoxDecoration( + color: colors.surfaceContainerHighest, + borderRadius: BorderRadius.circular(12), + ), + clipBehavior: Clip.antiAlias, + child: Stack(alignment: Alignment.center, children: [ + hasPoster + ? FadeInLocalImage(path: _editPosterPath, fit: BoxFit.cover) + : Column(mainAxisAlignment: MainAxisAlignment.center, children: [ + Icon(Icons.image_outlined, size: 32, color: colors.onSurface.withValues(alpha: 0.25)), + const SizedBox(height: 8), + Text('点击添加海报', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.35))), + ]), + if (_editIsDownloading) + Container(color: Colors.black.withValues(alpha: 0.4), + child: const CircularProgressIndicator(strokeWidth: 2, color: Colors.white)), + ]), + ), + ), + if (hasPoster) + Padding( + padding: const EdgeInsets.only(top: 8), + child: GestureDetector( + onTap: () => setState(() => _editPosterPath = null), + child: Text('移除海报', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.5)))), + ), + const SizedBox(height: 20), + // 状态 + _buildEditSectionLabel('状态', colors), + const SizedBox(height: 6), + Container( + padding: const EdgeInsets.all(2), + decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(6)), + child: Row(mainAxisSize: MainAxisSize.min, children: [ + _buildEditStatusChip('想看', 'want_to_watch', colors), + _buildEditStatusChip('在看', 'watching', colors), + _buildEditStatusChip('已看', 'watched', colors), + ]), + ), + const SizedBox(height: 16), + // 评分 + _buildEditSectionLabel('评分', colors), + const SizedBox(height: 6), + Row(children: [ + ...List.generate(5, (i) { + final starVal = i + 1; + final currentRating = double.tryParse(_ratingCtrl.text) ?? 0; + final starRating = currentRating / 2; + final isFilled = starVal <= starRating; + final isHalf = starVal == starRating.ceil() && starRating % 1 != 0; + return GestureDetector( + onTap: () => setState(() => _ratingCtrl.text = (starVal * 2).toString()), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 1), + child: Icon( + isHalf ? Icons.star_half : (isFilled ? Icons.star : Icons.star_border), + size: 20, color: (isFilled || isHalf) ? const Color(0xFFFFB800) : colors.outline, + ), + ), + ); + }), + const SizedBox(width: 8), + Container( + width: 48, height: 28, + decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(6)), + child: TextFormField( + controller: _ratingCtrl, + keyboardType: const TextInputType.numberWithOptions(decimal: true), + textAlign: TextAlign.center, + inputFormatters: [_RatingInputFormatter()], + style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: colors.onSurface), + decoration: InputDecoration( + hintText: '0-10', hintStyle: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.25)), + border: InputBorder.none, contentPadding: const EdgeInsets.symmetric(vertical: 6), isDense: true, + ), + onChanged: (_) => setState(() {}), + ), + ), + if (_ratingCtrl.text.isNotEmpty) ...[ + const SizedBox(width: 4), + GestureDetector( + onTap: () => setState(() => _ratingCtrl.clear()), + child: Icon(Icons.close, size: 14, color: colors.onSurface.withValues(alpha: 0.3)), + ), + ], + ]), + const SizedBox(height: 16), + // 分类 + _buildEditSectionLabel('分类', colors), + const SizedBox(height: 6), + Wrap(spacing: 4, runSpacing: 4, children: _categories.map((c) { + final selected = _editCategory == c.$2; + return GestureDetector( + onTap: () => setState(() => _editCategory = c.$2), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: selected ? colors.primary : colors.surfaceContainerHighest, + borderRadius: BorderRadius.circular(4), + ), + child: Text(c.$1, style: TextStyle( + fontSize: 11, fontWeight: selected ? FontWeight.w500 : FontWeight.normal, + color: selected ? colors.onPrimary : colors.onSurface.withValues(alpha: 0.5), + )), + ), + ); + }).toList()), + ], + ), + ), + // 右侧:可滚动表单 + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(0, 20, 24, 80), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 名称 + _buildEditField('名称', _titleCtrl, hint: '影视名称', required: true), + const SizedBox(height: 16), + // 别名 + _buildEditChipField('别名', _editAlternateTitles, onTap: () async { + final result = await GenreSelectorPage.show( + context: context, title: '添加别名', existingTags: [], + initialSelected: _editAlternateTitles, hint: '输入别名', + ); + if (result != null) setState(() => _editAlternateTitles = result); + }), + const SizedBox(height: 16), + // 导演 + _buildEditChipField('导演', _editDirectors, onTap: () async { + final provider = context.read(); + final data = provider.movies.map((m) => m.directors).toList(); + final result = await GenreSelectorPage.show( + context: context, title: '选择导演', + existingTagsFuture: compute(_collectUnique, data), + initialSelected: _editDirectors, hint: '如:张艺谋、李安', + ); + if (result != null) setState(() => _editDirectors = result); + }), + const SizedBox(height: 16), + // 编剧 + _buildEditChipField('编剧', _editWriters, onTap: () async { + final provider = context.read(); + final data = provider.movies.map((m) => m.writers).toList(); + final result = await GenreSelectorPage.show( + context: context, title: '选择编剧', + existingTagsFuture: compute(_collectUnique, data), + initialSelected: _editWriters, hint: '如:刘慈欣、王家卫', + ); + if (result != null) setState(() => _editWriters = result); + }), + const SizedBox(height: 16), + // 主演 + _buildEditChipField('主演', _editActors, onTap: () async { + final provider = context.read(); + final data = provider.movies.map((m) => m.actors).toList(); + final result = await GenreSelectorPage.show( + context: context, title: '选择主演', + existingTagsFuture: compute(_collectUnique, data), + initialSelected: _editActors, hint: '如:梁朝伟、周星驰', + ); + if (result != null) setState(() => _editActors = result); + }), + const SizedBox(height: 16), + // 类型 + _buildEditChipField('类型', _editGenres, onTap: () async { + final provider = context.read(); + final tags = await provider.getTags('movie_genre', excludeHidden: true); + final names = tags.map((t) => t['name'] as String).toList(); + if (!mounted) return; + final result = await GenreSelectorPage.show( + context: context, title: '选择类型', existingTags: names, + initialSelected: _editGenres, hint: '如:剧情、科幻、悬疑', + ); + if (result != null) setState(() => _editGenres = result); + }), + const SizedBox(height: 16), + // 日期行 + Row(children: [ + Expanded(child: _buildEditDateField('上映日期', _editReleaseDate, (d) => setState(() => _editReleaseDate = d))), + const SizedBox(width: 12), + Expanded(child: _buildEditDateField('观看日期', _editWatchDate, (d) => setState(() => _editWatchDate = d), clearable: true)), + ]), + const SizedBox(height: 16), + // 简介 + _buildEditSectionLabel('剧情简介', colors), + const SizedBox(height: 6), + Container( + constraints: const BoxConstraints(minHeight: 120), + child: TextFormField( + controller: _summaryCtrl, + maxLines: null, + style: TextStyle(fontSize: 14, color: colors.onSurface, height: 1.6), + decoration: InputDecoration( + hintText: '写下剧情简介...', + hintStyle: TextStyle(color: colors.onSurface.withValues(alpha: 0.25)), + filled: true, fillColor: colors.surfaceContainerHighest.withValues(alpha: 0.5), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none), + contentPadding: const EdgeInsets.all(12), + ), + ), + ), + ], + ), + ), + ), + ], + ), + ), + // 底部操作栏 + Container( + height: 48, + decoration: BoxDecoration( + color: colors.surface, + border: Border(top: BorderSide(color: colors.outlineVariant, width: 0.5)), + ), + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + OutlinedButton.icon( + onPressed: () => _showDeleteDialog(context), + icon: Icon(Icons.delete_outline, size: 16, color: colors.error), + label: Text('删除', style: TextStyle(color: colors.error)), + style: OutlinedButton.styleFrom( + side: BorderSide(color: colors.error.withValues(alpha: 0.3)), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + ], + ), + ), + ], + ), + ), + ); + } + + Widget _buildEditSectionLabel(String label, ColorScheme colors) { + return Text(label, style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))); + } + + Widget _buildEditStatusChip(String label, String value, ColorScheme colors) { + final selected = _editStatus == value; + return GestureDetector( + onTap: () => setState(() => _editStatus = value), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6), + decoration: BoxDecoration( + color: selected ? colors.surface : Colors.transparent, + borderRadius: BorderRadius.circular(6), + boxShadow: selected ? [BoxShadow(color: colors.onSurface.withValues(alpha: 0.03), blurRadius: 4, offset: const Offset(0, 2))] : null, + ), + child: Text(label, style: TextStyle( + fontSize: 13, fontWeight: selected ? FontWeight.w500 : FontWeight.normal, + color: selected ? colors.onSurface : colors.onSurface.withValues(alpha: 0.4), + )), + ), + ); + } + + Widget _buildEditField(String label, TextEditingController ctrl, {String hint = '', bool required = false}) { + final colors = Theme.of(context).colorScheme; + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(required ? '$label *' : label, style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))), + const SizedBox(height: 6), + TextFormField( + controller: ctrl, + style: TextStyle(fontSize: 14, color: colors.onSurface), + validator: required ? (v) => (v == null || v.trim().isEmpty) ? '请输入$label' : null : null, + decoration: InputDecoration( + hintText: hint, hintStyle: TextStyle(color: colors.onSurface.withValues(alpha: 0.25)), + filled: true, fillColor: colors.surfaceContainerHighest.withValues(alpha: 0.5), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + isDense: true, + ), + ), + ]); + } + + Widget _buildEditChipField(String label, List chips, {required VoidCallback onTap}) { + final colors = Theme.of(context).colorScheme; + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(label, style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))), + const SizedBox(height: 6), + GestureDetector( + onTap: onTap, + child: Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), + decoration: BoxDecoration( + color: colors.surfaceContainerHighest.withValues(alpha: 0.5), + borderRadius: BorderRadius.circular(8), + ), + child: chips.isEmpty + ? Text('点击选择$label', style: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.25))) + : Wrap(spacing: 4, runSpacing: 4, children: chips.map((c) => Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration(color: colors.surface, borderRadius: BorderRadius.circular(4)), + child: Text(c, style: TextStyle(fontSize: 12, color: colors.onSurface)), + )).toList()), + ), + ), + ]); + } + + Widget _buildEditDateField(String label, DateTime? date, ValueChanged onChanged, {bool clearable = false}) { + final colors = Theme.of(context).colorScheme; + final hasDate = date != null; + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(label, style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))), + const SizedBox(height: 6), + GestureDetector( + onTap: () async { + final picked = await showDatePicker( + context: context, initialDate: date ?? DateTime.now(), + firstDate: DateTime(1900), lastDate: DateTime.now().add(const Duration(days: 365 * 5)), + ); + if (picked != null) onChanged(picked); + }, + child: Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: BoxDecoration( + color: colors.surfaceContainerHighest.withValues(alpha: 0.5), + borderRadius: BorderRadius.circular(8), + ), + child: Row(children: [ + Icon(Icons.calendar_today_outlined, size: 14, color: colors.onSurface.withValues(alpha: 0.4)), + const SizedBox(width: 8), + Text(hasDate ? '${date!.year}.${date!.month.toString().padLeft(2, '0')}.${date!.day.toString().padLeft(2, '0')}' : '选择日期', + style: TextStyle(fontSize: 14, color: hasDate ? colors.onSurface : colors.onSurface.withValues(alpha: 0.25))), + const Spacer(), + if (clearable && hasDate) + GestureDetector( + onTap: () => onChanged(null), + child: Icon(Icons.close, size: 14, color: colors.onSurface.withValues(alpha: 0.3)), + ), + ]), + ), + ), + ]); + } + + void _showEditCoverOptions() { + final colors = Theme.of(context).colorScheme; + showModalBottomSheet( + context: context, backgroundColor: colors.surface, + shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(16))), + builder: (ctx) => SafeArea( + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 16), + child: Column(mainAxisSize: MainAxisSize.min, children: [ + Container(width: 40, height: 4, decoration: BoxDecoration(color: colors.outline, borderRadius: BorderRadius.circular(2))), + const SizedBox(height: 20), + Padding(padding: const EdgeInsets.symmetric(horizontal: 24), child: Align(alignment: Alignment.centerLeft, + child: Text('添加海报', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: colors.onSurface)))), + const SizedBox(height: 16), + ListTile(leading: Icon(Icons.photo_library_outlined, color: colors.onSurface.withValues(alpha: 0.6)), + title: Text('从相册选择', style: TextStyle(color: colors.onSurface)), + onTap: () { Navigator.pop(ctx); _pickEditCover(); }), + ListTile(leading: Icon(Icons.link_outlined, color: colors.onSurface.withValues(alpha: 0.6)), + title: Text('网络链接', style: TextStyle(color: colors.onSurface)), + onTap: () { Navigator.pop(ctx); _pickEditCoverFromUrl(); }), + ]), + ), + ), + ); + } + + Future _pickEditCover() async { + try { + final XFile? picked = await _picker.pickImage(source: ImageSource.gallery, maxWidth: 800, maxHeight: 1200, imageQuality: 85); + if (picked == null) return; + final fileName = 'poster_${DateTime.now().millisecondsSinceEpoch}.jpg'; + final targetPath = await ImagePathHelper.instance.getMoviePosterPath(widget.movie.id, fileName); + await ImagePathHelper.instance.ensureDirExists(p.dirname(targetPath)); + await File(picked.path).copy(targetPath); + if (mounted) setState(() => _editPosterPath = targetPath); + } catch (e) { + if (mounted) ToastUtil.show(context, '选择海报失败: $e'); + } + } + + Future _pickEditCoverFromUrl() async { + final urlCtrl = TextEditingController(); + final confirmed = await showDialog(context: context, builder: (ctx) { + final colors = Theme.of(ctx).colorScheme; + return AlertDialog( + backgroundColor: colors.surface, elevation: 0, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + title: Text('添加网络图片', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: colors.onSurface)), + content: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text('请输入图片链接地址', style: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.6))), + const SizedBox(height: 12), + TextField(controller: urlCtrl, keyboardType: TextInputType.url, + style: TextStyle(fontSize: 14, color: colors.onSurface), + decoration: InputDecoration(hintText: 'https://example.com/image.jpg', + hintStyle: TextStyle(color: colors.onSurface.withValues(alpha: 0.25)), + filled: true, fillColor: colors.surfaceContainerHigh, + contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none), + enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none), + focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide(color: colors.primary, width: 1)), + )), + ]), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text('取消', style: TextStyle(color: colors.onSurface.withValues(alpha: 0.6)))), + ElevatedButton(onPressed: () => Navigator.pop(ctx, true), + style: ElevatedButton.styleFrom(backgroundColor: colors.primary, foregroundColor: colors.onPrimary, elevation: 0, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8)), + child: const Text('确定')), + ], + ); + }); + final url = urlCtrl.text.trim(); + urlCtrl.dispose(); + if (confirmed != true || url.isEmpty) return; + await _downloadEditCoverFromUrl(url); + } + + Future _downloadEditCoverFromUrl(String url) async { + setState(() => _editIsDownloading = true); + try { + final response = await http.get(Uri.parse(url), headers: { + 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15', + 'Accept': 'image/avif,image/webp,image/apng,*/*;q=0.8', + 'Referer': Uri.parse(url).replace(path: '/').toString(), + }); + if (response.statusCode != 200) throw Exception('下载失败: HTTP ${response.statusCode}'); + final contentType = response.headers['content-type']; + if (contentType != null && !contentType.startsWith('image/')) throw Exception('链接返回的不是图片'); + if (response.bodyBytes.length > 10 * 1024 * 1024) throw Exception('图片太大'); + final fileName = 'poster_${DateTime.now().millisecondsSinceEpoch}.jpg'; + final targetPath = await ImagePathHelper.instance.getMoviePosterPath(widget.movie.id, fileName); + await ImagePathHelper.instance.ensureDirExists(p.dirname(targetPath)); + await File(targetPath).writeAsBytes(response.bodyBytes); + if (mounted) setState(() => _editPosterPath = targetPath); + } catch (e) { + if (mounted) ToastUtil.show(context, '下载失败: $e'); + } finally { + if (mounted) setState(() => _editIsDownloading = false); + } + } + + Future _saveEdit() async { + if (!_editFormKey.currentState!.validate()) return; + try { + final rating = _ratingCtrl.text.isNotEmpty ? double.tryParse(_ratingCtrl.text) : null; + final updated = widget.movie.copyWith( + title: _titleCtrl.text.trim(), + posterPath: _editPosterPath, + releaseDate: _editReleaseDate, + directors: _editDirectors, + writers: _editWriters, + actors: _editActors, + genres: _editGenres, + alternateTitles: _editAlternateTitles, + summary: _summaryCtrl.text.trim(), + rating: rating, + status: _editStatus, + category: _editCategory, + watchDate: _editWatchDate, + updatedAt: DateTime.now(), + ); + await context.read().updateMovie(updated); + if (!mounted) return; + ToastUtil.show(context, '更新成功'); + setState(() => _isEditing = false); + } catch (e) { + if (mounted) ToastUtil.show(context, '保存失败: $e'); + } + } + + /// 从多值字段列表中提取去重排序的唯一值(供 compute 使用) + static List _collectUnique(List> lists) { + final s = {}; + for (final l in lists) { s.addAll(l); } + return s.toList()..sort(); + } + Widget _buildDesktopInfoRow(String label, String value, ColorScheme colors) { return Padding( padding: const EdgeInsets.symmetric(vertical: 6), @@ -1451,3 +2058,16 @@ class _MovieDetailPageState extends State { ); } } + +/// 评分输入格式化器:只允许 0-10,最多1位小数 +class _RatingInputFormatter extends TextInputFormatter { + @override + TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { + final text = newValue.text; + if (text.isEmpty) return newValue; + if (!RegExp(r'^\d{0,2}\.?\d{0,1}$').hasMatch(text)) return oldValue; + final n = double.tryParse(text); + if (n != null && n > 10) return oldValue; + return newValue; + } +} diff --git a/lib/pages/movies/movie_tab_page.dart b/lib/pages/movies/movie_tab_page.dart index 8eab4cd..b33e80d 100644 --- a/lib/pages/movies/movie_tab_page.dart +++ b/lib/pages/movies/movie_tab_page.dart @@ -13,6 +13,7 @@ import '../../utils/responsive.dart'; import '../../widgets/master_detail_scaffold.dart'; import '../../widgets/detail_placeholder.dart'; import 'movie_detail_page.dart'; +import 'movie_add_page.dart'; /// 观影标签页(分页 + 触底加载) class MovieTabPage extends StatefulWidget { @@ -211,11 +212,14 @@ class _MovieTabPageState extends State { if (!isWideContent) return masterContent; final selectedMovie = provider.selectedMovie; + final detailWidget = provider.isAdding && provider.addingType == 0 + ? MovieAddPage(onCancel: () => provider.cancelAdding()) + : selectedMovie != null + ? MovieDetailPage(movie: selectedMovie, embedded: true) + : const DetailPlaceholder(icon: Icons.movie_outlined, message: '选择一部影片查看详情'); return MasterDetailScaffold( master: masterContent, - detail: selectedMovie != null - ? MovieDetailPage(movie: selectedMovie, embedded: true) - : const DetailPlaceholder(icon: Icons.movie_outlined, message: '选择一部影片查看详情'), + detail: detailWidget, ); } diff --git a/lib/pages/note/note_add_page.dart b/lib/pages/note/note_add_page.dart new file mode 100644 index 0000000..0661abd --- /dev/null +++ b/lib/pages/note/note_add_page.dart @@ -0,0 +1,510 @@ +import 'dart:io'; +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_markdown_plus/flutter_markdown_plus.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:path/path.dart' as p; +import 'package:provider/provider.dart'; +import 'package:uuid/uuid.dart'; +import '../../providers/app_provider.dart'; +import '../../models/data_models.dart'; +import '../../utils/toast_util.dart'; +import '../../utils/image_path_helper.dart'; +import '../../widgets/fade_in_local_image.dart'; +import '../../widgets/tag_side_panel.dart'; + +class NoteAddPage extends StatefulWidget { + final VoidCallback? onCancel; + const NoteAddPage({super.key, this.onCancel}); + + @override + State createState() => _NoteAddPageState(); +} + +class _NoteAddPageState extends State { + final ImagePicker _picker = ImagePicker(); + late TextEditingController _titleCtrl; + late TextEditingController _contentCtrl; + List _tags = []; + List _images = []; + String _editMode = 'edit'; // 'edit' | 'preview' + late String _tempId; + + @override + void initState() { + super.initState(); + _tempId = const Uuid().v4(); + _titleCtrl = TextEditingController(); + _contentCtrl = TextEditingController(); + } + + @override + void dispose() { + _titleCtrl.dispose(); + _contentCtrl.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final colors = Theme.of(context).colorScheme; + return Scaffold( + backgroundColor: colors.surface, + body: Column( + children: [ + // 顶栏 + Container( + height: 48, + decoration: BoxDecoration( + color: colors.surface, + border: Border(bottom: BorderSide(color: colors.outlineVariant, width: 0.5)), + ), + child: Row(children: [ + IconButton( + icon: Icon(Icons.close, color: colors.onSurface, size: 18), + onPressed: () => widget.onCancel?.call(), + ), + Expanded( + child: Text('添加笔记', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: colors.onSurface)), + ), + // 编辑/预览切换 + Container( + padding: const EdgeInsets.all(2), + decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(6)), + child: Row(mainAxisSize: MainAxisSize.min, children: [ + _editModeChip(Icons.edit_outlined, '编辑', 'edit', colors), + _editModeChip(Icons.visibility_outlined, '预览', 'preview', colors), + ]), + ), + const SizedBox(width: 8), + FilledButton.icon( + onPressed: _save, + icon: const Icon(Icons.check, size: 16), + label: const Text('保存'), + style: FilledButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + const SizedBox(width: 12), + ]), + ), + // 主体 + Expanded( + child: _editMode == 'edit' ? _buildEditArea(colors) : _buildPreviewArea(colors), + ), + ], + ), + ); + } + + Widget _editModeChip(IconData icon, String label, String mode, ColorScheme colors) { + final active = _editMode == mode; + return GestureDetector( + onTap: () => setState(() => _editMode = mode), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 5), + decoration: BoxDecoration( + color: active ? colors.surface : Colors.transparent, + borderRadius: BorderRadius.circular(4), + boxShadow: active ? [BoxShadow(color: colors.onSurface.withValues(alpha: 0.03), blurRadius: 2)] : null, + ), + child: Row(mainAxisSize: MainAxisSize.min, children: [ + Icon(icon, size: 14, color: active ? colors.onSurface : colors.onSurface.withValues(alpha: 0.4)), + const SizedBox(width: 4), + Text(label, style: TextStyle(fontSize: 12, fontWeight: active ? FontWeight.w500 : FontWeight.normal, + color: active ? colors.onSurface : colors.onSurface.withValues(alpha: 0.4))), + ]), + ), + ); + } + + Widget _buildEditArea(ColorScheme colors) { + return Column(children: [ + // 标题输入 + Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + decoration: BoxDecoration(border: Border(bottom: BorderSide(color: colors.outlineVariant, width: 0.5))), + child: TextField( + controller: _titleCtrl, + maxLines: 1, + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: colors.onSurface), + decoration: InputDecoration( + hintText: '添加标题', + hintStyle: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: colors.onSurface.withValues(alpha: 0.2)), + border: InputBorder.none, + isDense: true, + contentPadding: EdgeInsets.zero, + ), + onChanged: (_) => setState(() {}), + ), + ), + // 内容编辑 + Expanded( + child: TextField( + controller: _contentCtrl, + maxLines: null, + expands: true, + textAlignVertical: TextAlignVertical.top, + strutStyle: const StrutStyle(forceStrutHeight: true, height: 1.6, fontSize: 14), + style: TextStyle(fontSize: 14, color: colors.onSurface, height: 1.6), + decoration: InputDecoration( + hintText: '使用 Markdown 格式书写...', + hintStyle: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.25), height: 1.6), + border: InputBorder.none, + contentPadding: const EdgeInsets.all(16), + ), + onChanged: (_) => setState(() {}), + ), + ), + // 图片行 + if (_images.isNotEmpty) _buildImageRow(colors), + // 标签 + 工具栏 + Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6), + decoration: BoxDecoration(border: Border(top: BorderSide(color: colors.outlineVariant, width: 0.5))), + child: Column(children: [ + // 标签行 + Wrap(spacing: 6, runSpacing: 4, children: [ + for (int i = 0; i < _tags.length; i++) Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(6)), + child: Row(mainAxisSize: MainAxisSize.min, children: [ + Text(_tags[i], style: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.6))), + const SizedBox(width: 3), + GestureDetector( + onTap: () => setState(() => _tags.removeAt(i)), + child: Icon(Icons.close, size: 10, color: colors.onSurface.withValues(alpha: 0.3)), + ), + ]), + ), + GestureDetector( + onTap: _showTagPanel, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(6), + border: Border.all(color: colors.onSurface.withValues(alpha: 0.25), width: 1), + ), + child: Row(mainAxisSize: MainAxisSize.min, children: [ + Icon(Icons.add, size: 12, color: colors.onSurface.withValues(alpha: 0.35)), + const SizedBox(width: 2), + Text('标签', style: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.35))), + ]), + ), + ), + ]), + const SizedBox(height: 6), + // 工具栏 + Row(children: [ + Expanded( + child: SingleChildScrollView(scrollDirection: Axis.horizontal, child: Row(children: [ + _toolBtn(Icons.title, '标题', _insertHeading), + _toolBtn(Icons.format_bold, '粗体', () => _insertMarkdown('**', '**')), + _toolBtn(Icons.format_italic, '斜体', () => _insertMarkdown('*', '*')), + _toolBtn(Icons.format_strikethrough, '删除线', () => _insertMarkdown('~~', '~~')), + _toolGap(colors), + _toolBtn(Icons.format_list_bulleted, '无序列表', () => _insertMarkdown('- ', '')), + _toolBtn(Icons.format_list_numbered, '有序列表', () => _insertMarkdown('1. ', '')), + _toolBtn(Icons.format_quote, '引用', () => _insertMarkdown('> ', '')), + _toolBtn(Icons.insert_link, '链接', () => _insertMarkdown('[', '](url)')), + _toolGap(colors), + _toolBtn(Icons.code, '行内代码', () => _insertMarkdown('`', '`')), + _toolBtn(Icons.data_object, '代码块', () => _insertMarkdown('```\n', '\n```')), + _toolBtn(Icons.horizontal_rule, '分割线', () => _insertMarkdown('---\n', '')), + _toolGap(colors), + _toolBtn(Icons.add_photo_alternate_outlined, '图片', _pickImage), + ])), + ), + const SizedBox(width: 8), + Text('${_contentCtrl.text.length} 字', + style: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.3))), + ]), + ]), + ), + ]); + } + + Widget _buildPreviewArea(ColorScheme colors) { + return ListView( + padding: const EdgeInsets.all(24), + children: [ + if (_titleCtrl.text.isNotEmpty) ...[ + Text(_titleCtrl.text, + style: TextStyle(fontSize: 24, fontWeight: FontWeight.w600, color: colors.onSurface, height: 1.3)), + const SizedBox(height: 16), + ], + Markdown( + data: _contentCtrl.text, + styleSheet: _buildMarkdownStyleSheet(colors), + padding: EdgeInsets.zero, + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + ), + if (_images.isNotEmpty) ...[ + const SizedBox(height: 16), + _buildPreviewImageRow(colors), + ], + const SizedBox(height: 48), + ], + ); + } + + Widget _buildImageRow(ColorScheme colors) { + return Container( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 0), + height: 72, + child: ListView.separated( + scrollDirection: Axis.horizontal, + itemCount: _images.length + 1, + separatorBuilder: (_, __) => const SizedBox(width: 6), + itemBuilder: (ctx, i) { + if (i < _images.length) { + return Stack(children: [ + Container( + width: 56, height: 56, + decoration: BoxDecoration(borderRadius: BorderRadius.circular(6), border: Border.all(color: colors.outlineVariant, width: 0.5)), + clipBehavior: Clip.antiAlias, + child: FadeInLocalImage(path: _images[i], fit: BoxFit.cover), + ), + Positioned(top: -4, right: -4, + child: GestureDetector( + onTap: () => setState(() => _images.removeAt(i)), + child: Container(width: 16, height: 16, + decoration: BoxDecoration(color: colors.surface, shape: BoxShape.circle, border: Border.all(color: colors.outline)), + child: Icon(Icons.close, size: 10, color: colors.onSurface.withValues(alpha: 0.5))), + ), + ), + ]); + } + return InkWell( + onTap: _pickImage, + child: Container(width: 56, height: 56, + decoration: BoxDecoration(borderRadius: BorderRadius.circular(6), color: colors.surfaceContainerHighest, + border: Border.all(color: colors.outlineVariant)), + child: Icon(Icons.add_photo_alternate_outlined, size: 20, color: colors.onSurface.withValues(alpha: 0.3))), + ); + }, + ), + ); + } + + Widget _buildPreviewImageRow(ColorScheme colors) { + return SizedBox( + height: 80, + child: ListView.separated( + scrollDirection: Axis.horizontal, + itemCount: _images.length, + separatorBuilder: (_, __) => const SizedBox(width: 8), + itemBuilder: (context, index) { + return Container( + width: 64, height: 64, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(8), + border: Border.all(color: colors.outlineVariant, width: 0.5), + ), + clipBehavior: Clip.antiAlias, + child: FadeInLocalImage( + path: _images[index], + fit: BoxFit.cover, + errorWidget: Container( + color: colors.surfaceContainerHighest, + child: Icon(Icons.broken_image_outlined, size: 20, color: colors.onSurface.withValues(alpha: 0.25)), + ), + ), + ); + }, + ), + ); + } + + Widget _toolBtn(IconData icon, String tooltip, VoidCallback onTap) { + final colors = Theme.of(context).colorScheme; + return Material( + color: Colors.transparent, + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(6), + child: Tooltip( + message: tooltip, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2), + child: Icon(icon, size: 16, color: colors.onSurface.withValues(alpha: 0.6)), + ), + ), + ), + ); + } + + Widget _toolGap(ColorScheme colors) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 3), + child: SizedBox(height: 12, child: VerticalDivider(width: 0, thickness: 0.5, color: colors.outline)), + ); + } + + void _insertMarkdown(String left, String right) { + final text = _contentCtrl.text; + final selection = _contentCtrl.selection; + final start = selection.start; + final end = selection.end; + String selectedText = end > start ? text.substring(start, end) : ''; + final insertion = '$left$selectedText$right'; + _contentCtrl.value = TextEditingValue( + text: text.substring(0, start) + insertion + text.substring(end), + selection: TextSelection.collapsed( + offset: selectedText.isEmpty ? start + left.length : start + left.length + selectedText.length + right.length, + ), + ); + setState(() {}); + } + + void _insertHeading() { + final text = _contentCtrl.text; + final selection = _contentCtrl.selection; + final start = selection.start; + int lineStart = start; + while (lineStart > 0 && text[lineStart - 1] != '\n') lineStart--; + int hashCount = 0; + int pos = lineStart; + while (pos < text.length && text[pos] == '#') { hashCount++; pos++; } + if (pos < text.length && text[pos] == ' ') pos++; + if (hashCount > 0 && hashCount < 6) { + hashCount++; + final newPrefix = '${'#' * hashCount} '; + _contentCtrl.value = TextEditingValue( + text: text.substring(0, lineStart) + newPrefix + text.substring(pos), + selection: TextSelection.collapsed(offset: lineStart + newPrefix.length), + ); + } else if (hashCount >= 6) { + _contentCtrl.value = TextEditingValue( + text: text.substring(0, lineStart) + text.substring(pos), + selection: TextSelection.collapsed(offset: lineStart), + ); + } else { + _contentCtrl.value = TextEditingValue( + text: text.substring(0, lineStart) + '# ' + text.substring(lineStart), + selection: TextSelection.collapsed(offset: lineStart + 2), + ); + } + setState(() {}); + } + + Future _pickImage() async { + try { + final XFile? image = await _picker.pickImage(source: ImageSource.gallery, maxWidth: 1920, maxHeight: 1920, imageQuality: 85); + if (image == null) return; + final fileName = '${DateTime.now().millisecondsSinceEpoch}.jpg'; + final targetDir = await ImagePathHelper.instance.getNoteImagesDir(_tempId); + await ImagePathHelper.instance.ensureDirExists(targetDir); + final targetPath = p.join(targetDir, fileName); + await File(image.path).copy(targetPath); + if (mounted) setState(() => _images.add(targetPath)); + } catch (e) { + if (mounted) ToastUtil.show(context, '选择图片失败: $e'); + } + } + + Future _showTagPanel() async { + final provider = context.read(); + final tagRows = await provider.getTags('note_tag'); + final allTags = tagRows.map((t) => t['name'] as String).toSet(); + for (final note in provider.notes) { allTags.addAll(note.tags); } + if (!mounted) return; + TagSidePanel.show( + context: context, + selectedTags: List.from(_tags), + allAvailableTags: allTags.toList()..sort(), + onTagsChanged: (newTags) => setState(() => _tags = newTags), + ); + } + + MarkdownStyleSheet _buildMarkdownStyleSheet(ColorScheme colors) { + return MarkdownStyleSheet( + h1: TextStyle(fontSize: 24, fontWeight: FontWeight.w600, color: colors.onSurface, height: 1.4), + h2: TextStyle(fontSize: 20, fontWeight: FontWeight.w600, color: colors.onSurface, height: 1.4), + h3: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: colors.onSurface, height: 1.4), + h4: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: colors.onSurface, height: 1.4), + p: TextStyle(fontSize: 15, color: colors.onSurface.withValues(alpha: 0.75), height: 1.8), + code: TextStyle(fontSize: 14, color: colors.onSurface, backgroundColor: colors.surfaceContainerHighest, fontFamily: 'monospace'), + codeblockDecoration: BoxDecoration( + color: colors.surfaceContainerHigh, + border: Border.all(color: colors.outline), + borderRadius: BorderRadius.circular(6), + ), + codeblockPadding: const EdgeInsets.all(12), + blockquote: TextStyle(fontSize: 15, color: colors.onSurface.withValues(alpha: 0.6), fontStyle: FontStyle.italic, height: 1.8), + blockquoteDecoration: BoxDecoration( + border: Border(left: BorderSide(color: colors.onSurface.withValues(alpha: 0.4), width: 4)), + ), + blockquotePadding: const EdgeInsets.only(left: 12, top: 4, bottom: 4), + listBullet: TextStyle(fontSize: 15, color: colors.onSurface), + listIndent: 24, + a: const TextStyle(fontSize: 15, color: Color(0xFF4A90D9), decoration: TextDecoration.underline), + tableHead: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: colors.onSurface), + tableBody: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.75)), + tableBorder: TableBorder.all(color: colors.outline, width: 0.5), + tableColumnWidth: const FlexColumnWidth(), + tableCellsDecoration: BoxDecoration(color: colors.surface), + tablePadding: const EdgeInsets.all(8), + strong: TextStyle(fontWeight: FontWeight.w600, color: colors.onSurface), + em: TextStyle(fontStyle: FontStyle.italic, color: colors.onSurface.withValues(alpha: 0.75)), + del: TextStyle(decoration: TextDecoration.lineThrough, color: colors.onSurface.withValues(alpha: 0.4)), + ); + } + + Future _save() async { + final title = _titleCtrl.text.trim(); + final content = _contentCtrl.text.trim(); + if (title.isEmpty && content.isEmpty) { + ToastUtil.show(context, '标题或内容不能为空'); + return; + } + try { + final noteId = const Uuid().v4(); + // 移动图片从临时目录到正式目录 + List finalImages = []; + if (_images.isNotEmpty) { + final newDir = await ImagePathHelper.instance.getNoteImagesDir(noteId); + for (final imgPath in _images) { + final normalized = imgPath.replaceAll('\\', '/'); + if (normalized.contains('/notes/${_tempId}/')) { + final fileName = p.basename(imgPath); + final newPath = p.join(newDir, fileName); + await ImagePathHelper.instance.ensureDirExists(newDir); + final src = File(imgPath); + if (await src.exists()) { await src.rename(newPath); finalImages.add(newPath); } + } else { + finalImages.add(imgPath); + } + } + // 清理临时目录 + try { await ImagePathHelper.instance.deleteNoteImages(_tempId); } catch (_) {} + } + final note = Note( + id: noteId, + title: title, + content: content, + tags: _tags, + images: finalImages.isNotEmpty ? finalImages : _images, + createdAt: DateTime.now(), + updatedAt: DateTime.now(), + ); + await context.read().addNote(note); + await context.read().loadNotes(); + if (!mounted) return; + context.read().finishAdding(); + ToastUtil.show(context, '添加成功'); + } catch (e) { + if (mounted) ToastUtil.show(context, '保存失败: $e'); + } + } + + static List _collectUnique(List> lists) { + final s = {}; + for (final l in lists) { s.addAll(l); } + return s.toList()..sort(); + } +} diff --git a/lib/pages/note/note_detail_page.dart b/lib/pages/note/note_detail_page.dart index 133e798..6c76244 100644 --- a/lib/pages/note/note_detail_page.dart +++ b/lib/pages/note/note_detail_page.dart @@ -1,11 +1,18 @@ import 'dart:io'; +import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_markdown_plus/flutter_markdown_plus.dart'; import 'package:provider/provider.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:path/path.dart' as p; +import 'package:uuid/uuid.dart'; import '../../providers/app_provider.dart'; import '../../widgets/fade_in_local_image.dart'; import '../../models/data_models.dart'; +import '../../utils/toast_util.dart'; +import '../../utils/image_path_helper.dart'; import '../../utils/responsive.dart'; +import '../../widgets/tag_side_panel.dart'; import 'note_share_page.dart'; /// 笔记详情页 @@ -22,6 +29,97 @@ class NoteDetailPage extends StatefulWidget { class _NoteDetailPageState extends State { static const _weekdays = ['一', '二', '三', '四', '五', '六', '日']; + // ─── 编辑模式 ─── + bool _isEditing = false; + String _editMode = 'edit'; // 'edit' | 'preview' + late TextEditingController _titleCtrl; + late TextEditingController _contentCtrl; + List _editTags = []; + List _editImages = []; + Timer? _autoSaveTimer; + String _saveStatus = ''; + final ImagePicker _picker = ImagePicker(); + + @override + void initState() { + super.initState(); + _titleCtrl = TextEditingController(text: widget.note.title); + _contentCtrl = TextEditingController(text: widget.note.content); + _editTags = List.from(widget.note.tags); + _editImages = List.from(widget.note.images); + } + + @override + void dispose() { + _autoSaveTimer?.cancel(); + _titleCtrl.dispose(); + _contentCtrl.dispose(); + super.dispose(); + } + + void _enterEditMode() { + final latest = context.read().notes + .where((n) => n.id == widget.note.id).firstOrNull ?? widget.note; + _titleCtrl.text = latest.title; + _contentCtrl.text = latest.content; + _editTags = List.from(latest.tags); + _editImages = List.from(latest.images); + _saveStatus = ''; + setState(() => _isEditing = true); + } + + void _onContentChanged() { + _autoSaveTimer?.cancel(); + _autoSaveTimer = Timer(const Duration(seconds: 2), () { + if (mounted) _autoSave(); + }); + } + + Future _autoSave() async { + final content = _contentCtrl.text.trim(); + final title = _titleCtrl.text.trim(); + if (title.isEmpty && content.isEmpty) return; + try { + final latest = context.read().notes + .where((n) => n.id == widget.note.id).firstOrNull ?? widget.note; + final updated = latest.copyWith( + title: title, content: content, tags: _editTags, images: _editImages, + updatedAt: DateTime.now(), + ); + await context.read().updateNote(updated); + if (mounted) { + setState(() => _saveStatus = 'saved'); + Future.delayed(const Duration(seconds: 3), () { + if (mounted && _saveStatus == 'saved') setState(() => _saveStatus = ''); + }); + } + } catch (_) {} + } + + Future _saveEdit() async { + _autoSaveTimer?.cancel(); + final title = _titleCtrl.text.trim(); + final content = _contentCtrl.text.trim(); + if (title.isEmpty && content.isEmpty) { + ToastUtil.show(context, '标题或内容不能为空'); + return; + } + try { + final latest = context.read().notes + .where((n) => n.id == widget.note.id).firstOrNull ?? widget.note; + final updated = latest.copyWith( + title: title, content: content, tags: _editTags, images: _editImages, + updatedAt: DateTime.now(), + ); + await context.read().updateNote(updated); + if (!mounted) return; + ToastUtil.show(context, '保存成功'); + setState(() => _isEditing = false); + } catch (e) { + if (mounted) ToastUtil.show(context, '保存失败: $e'); + } + } + @override Widget build(BuildContext context) { final colors = Theme.of(context).colorScheme; @@ -130,6 +228,7 @@ class _NoteDetailPageState extends State { /// 桌面端布局 Widget _buildDesktopStyle(Note note, ColorScheme colors) { + if (_isEditing) return _buildDesktopEditStyle(note, colors); return Scaffold( backgroundColor: colors.surface, body: Column( @@ -219,7 +318,7 @@ class _NoteDetailPageState extends State { ), const SizedBox(width: 12), FilledButton.icon( - onPressed: () => _navigateToEdit(context), + onPressed: _enterEditMode, icon: const Icon(Icons.edit_outlined, size: 16), label: const Text('编辑'), style: FilledButton.styleFrom( @@ -234,6 +333,295 @@ class _NoteDetailPageState extends State { ); } + // ─── 桌面端编辑模式:左编辑 + 右预览 ──────────────────────────── + + Widget _buildDesktopEditStyle(Note note, ColorScheme colors) { + return Scaffold( + backgroundColor: colors.surface, + body: Column( + children: [ + // 顶栏 + Container( + height: 48, + decoration: BoxDecoration(color: colors.surface, + border: Border(bottom: BorderSide(color: colors.outlineVariant, width: 0.5))), + child: Row(children: [ + IconButton(icon: Icon(Icons.close, color: colors.onSurface, size: 18), + onPressed: () { _autoSaveTimer?.cancel(); if (_saveStatus == 'saved') _autoSave(); setState(() => _isEditing = false); }), + Expanded(child: Text(_titleCtrl.text.isNotEmpty ? _titleCtrl.text : '编辑笔记', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: colors.onSurface), + maxLines: 1, overflow: TextOverflow.ellipsis)), + // 编辑/预览切换 + Container( + padding: const EdgeInsets.all(2), + decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(6)), + child: Row(mainAxisSize: MainAxisSize.min, children: [ + _editModeChip(Icons.edit_outlined, '编辑', 'edit', colors), + _editModeChip(Icons.visibility_outlined, '预览', 'preview', colors), + ]), + ), + const SizedBox(width: 8), + if (_saveStatus == 'saved') + Padding(padding: const EdgeInsets.only(right: 8), + child: Row(mainAxisSize: MainAxisSize.min, children: [ + Container(width: 6, height: 6, decoration: const BoxDecoration(color: Colors.green, shape: BoxShape.circle)), + const SizedBox(width: 4), + Text('已保存', style: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.4))), + ])), + FilledButton.icon(onPressed: _saveEdit, + icon: const Icon(Icons.check, size: 16), label: const Text('保存'), + style: FilledButton.styleFrom(padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)))), + const SizedBox(width: 12), + ]), + ), + // 主体 + Expanded( + child: _editMode == 'edit' ? _buildEditArea(colors, note) : _buildPreviewArea(colors, note), + ), + ], + ), + ); + } + + Widget _editModeChip(IconData icon, String label, String mode, ColorScheme colors) { + final active = _editMode == mode; + return GestureDetector(onTap: () => setState(() => _editMode = mode), + child: Container(padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 5), + decoration: BoxDecoration( + color: active ? colors.surface : Colors.transparent, + borderRadius: BorderRadius.circular(4), + boxShadow: active ? [BoxShadow(color: colors.onSurface.withValues(alpha: 0.03), blurRadius: 2)] : null), + child: Row(mainAxisSize: MainAxisSize.min, children: [ + Icon(icon, size: 14, color: active ? colors.onSurface : colors.onSurface.withValues(alpha: 0.4)), + const SizedBox(width: 4), + Text(label, style: TextStyle(fontSize: 12, fontWeight: active ? FontWeight.w500 : FontWeight.normal, + color: active ? colors.onSurface : colors.onSurface.withValues(alpha: 0.4))), + ]))); + } + + Widget _buildEditArea(ColorScheme colors, Note note) { + return Column(children: [ + // 标题输入 + Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + decoration: BoxDecoration(border: Border(bottom: BorderSide(color: colors.outlineVariant, width: 0.5))), + child: TextField(controller: _titleCtrl, maxLines: 1, + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: colors.onSurface), + decoration: InputDecoration(hintText: '添加标题', + hintStyle: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: colors.onSurface.withValues(alpha: 0.2)), + border: InputBorder.none, isDense: true, contentPadding: EdgeInsets.zero), + onChanged: (_) => setState(() {})), + ), + // 内容编辑 + Expanded( + child: TextField(controller: _contentCtrl, maxLines: null, expands: true, + textAlignVertical: TextAlignVertical.top, + strutStyle: const StrutStyle(forceStrutHeight: true, height: 1.6, fontSize: 14), + style: TextStyle(fontSize: 14, color: colors.onSurface, height: 1.6), + decoration: InputDecoration(hintText: '使用 Markdown 格式书写...', + hintStyle: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.25), height: 1.6), + border: InputBorder.none, contentPadding: const EdgeInsets.all(16)), + onChanged: (_) => _onContentChanged()), + ), + // 图片网格 + if (_editImages.isNotEmpty) _buildEditImageGrid(colors), + // 标签 + 字数 + 工具栏 + Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6), + decoration: BoxDecoration(border: Border(top: BorderSide(color: colors.outlineVariant, width: 0.5))), + child: Column(children: [ + // 标签行 + Wrap(spacing: 6, runSpacing: 4, children: [ + for (int i = 0; i < _editTags.length; i++) Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration(color: colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(6)), + child: Row(mainAxisSize: MainAxisSize.min, children: [ + Text(_editTags[i], style: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.6))), + const SizedBox(width: 3), + GestureDetector(onTap: () => setState(() => _editTags.removeAt(i)), + child: Icon(Icons.close, size: 10, color: colors.onSurface.withValues(alpha: 0.3))), + ])), + GestureDetector(onTap: _showEditTagPanel, + child: Container(padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration(borderRadius: BorderRadius.circular(6), + border: Border.all(color: colors.onSurface.withValues(alpha: 0.25), width: 1)), + child: Row(mainAxisSize: MainAxisSize.min, children: [ + Icon(Icons.add, size: 12, color: colors.onSurface.withValues(alpha: 0.35)), + const SizedBox(width: 2), + Text('标签', style: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.35))), + ]))), + ]), + const SizedBox(height: 6), + // 工具栏 + Row(children: [ + Expanded(child: SingleChildScrollView(scrollDirection: Axis.horizontal, child: Row(children: [ + _editToolBtn(Icons.title, '标题', _insertHeading), + _editToolBtn(Icons.format_bold, '粗体', () => _insertMarkdown('**', '**')), + _editToolBtn(Icons.format_italic, '斜体', () => _insertMarkdown('*', '*')), + _editToolBtn(Icons.format_strikethrough, '删除线', () => _insertMarkdown('~~', '~~')), + _editToolGap(colors), + _editToolBtn(Icons.format_list_bulleted, '无序列表', () => _insertMarkdown('- ', '')), + _editToolBtn(Icons.format_list_numbered, '有序列表', () => _insertMarkdown('1. ', '')), + _editToolBtn(Icons.format_quote, '引用', () => _insertMarkdown('> ', '')), + _editToolBtn(Icons.insert_link, '链接', () => _insertMarkdown('[', '](url)')), + _editToolGap(colors), + _editToolBtn(Icons.code, '行内代码', () => _insertMarkdown('`', '`')), + _editToolBtn(Icons.data_object, '代码块', () => _insertMarkdown('```\n', '\n```')), + _editToolBtn(Icons.horizontal_rule, '分割线', () => _insertMarkdown('---\n', '')), + _editToolGap(colors), + _editToolBtn(Icons.add_photo_alternate_outlined, '图片', _pickEditImage), + ]))), + const SizedBox(width: 8), + Text('${_contentCtrl.text.length} 字', style: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.3))), + ]), + ]), + ), + ]); + } + + Widget _buildPreviewArea(ColorScheme colors, Note note) { + return ListView( + padding: const EdgeInsets.all(24), + children: [ + if (_titleCtrl.text.isNotEmpty) ...[ + Text(_titleCtrl.text, style: TextStyle(fontSize: 24, fontWeight: FontWeight.w600, color: colors.onSurface, height: 1.3)), + const SizedBox(height: 16), + ], + Markdown( + data: _contentCtrl.text, + styleSheet: _buildMarkdownStyleSheet(colors), + padding: EdgeInsets.zero, + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + // ignore: deprecated_member_use + imageBuilder: (uri, title, alt) => _buildMarkdownImage(uri, note), + ), + if (_editImages.isNotEmpty) ...[ + const SizedBox(height: 16), + _buildImageRow(_editImages), + ], + const SizedBox(height: 48), + ], + ); + } + + Widget _editToolBtn(IconData icon, String tooltip, VoidCallback onTap) { + final colors = Theme.of(context).colorScheme; + return Material(color: Colors.transparent, + child: InkWell(onTap: onTap, borderRadius: BorderRadius.circular(6), + child: Tooltip(message: tooltip, + child: Padding(padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2), + child: Icon(icon, size: 16, color: colors.onSurface.withValues(alpha: 0.6)))))); + } + + Widget _editToolGap(ColorScheme colors) { + return Padding(padding: const EdgeInsets.symmetric(horizontal: 3), + child: SizedBox(height: 12, child: VerticalDivider(width: 0, thickness: 0.5, color: colors.outline))); + } + + void _insertMarkdown(String left, String right) { + final text = _contentCtrl.text; + final selection = _contentCtrl.selection; + final start = selection.start; + final end = selection.end; + String selectedText = end > start ? text.substring(start, end) : ''; + final insertion = '$left$selectedText$right'; + _contentCtrl.value = TextEditingValue( + text: text.substring(0, start) + insertion + text.substring(end), + selection: TextSelection.collapsed( + offset: selectedText.isEmpty ? start + left.length : start + left.length + selectedText.length + right.length, + ), + ); + _onContentChanged(); + } + + void _insertHeading() { + final text = _contentCtrl.text; + final selection = _contentCtrl.selection; + final start = selection.start; + int lineStart = start; + while (lineStart > 0 && text[lineStart - 1] != '\n') lineStart--; + int hashCount = 0; + int pos = lineStart; + while (pos < text.length && text[pos] == '#') { hashCount++; pos++; } + if (pos < text.length && text[pos] == ' ') pos++; + if (hashCount > 0 && hashCount < 6) { + hashCount++; + final newPrefix = '${'#' * hashCount} '; + _contentCtrl.value = TextEditingValue( + text: text.substring(0, lineStart) + newPrefix + text.substring(pos), + selection: TextSelection.collapsed(offset: lineStart + newPrefix.length)); + } else if (hashCount >= 6) { + _contentCtrl.value = TextEditingValue( + text: text.substring(0, lineStart) + text.substring(pos), + selection: TextSelection.collapsed(offset: lineStart)); + } else { + _contentCtrl.value = TextEditingValue( + text: text.substring(0, lineStart) + '# ' + text.substring(lineStart), + selection: TextSelection.collapsed(offset: lineStart + 2)); + } + _onContentChanged(); + } + + Future _pickEditImage() async { + try { + final XFile? image = await _picker.pickImage(source: ImageSource.gallery, maxWidth: 1920, maxHeight: 1920, imageQuality: 85); + if (image == null) return; + final fileName = '${DateTime.now().millisecondsSinceEpoch}.jpg'; + final targetDir = await ImagePathHelper.instance.getNoteImagesDir(widget.note.id); + await ImagePathHelper.instance.ensureDirExists(targetDir); + final targetPath = p.join(targetDir, fileName); + await File(image.path).copy(targetPath); + if (mounted) setState(() => _editImages.add(targetPath)); + _onContentChanged(); + } catch (e) { + if (mounted) ToastUtil.show(context, '选择图片失败: $e'); + } + } + + Future _showEditTagPanel() async { + final provider = context.read(); + final tagRows = await provider.getTags('note_tag'); + final allTags = tagRows.map((t) => t['name'] as String).toSet(); + for (final note in provider.notes) { allTags.addAll(note.tags); } + if (!mounted) return; + TagSidePanel.show(context: context, selectedTags: List.from(_editTags), + allAvailableTags: allTags.toList()..sort(), + onTagsChanged: (newTags) => setState(() => _editTags = newTags)); + } + + Widget _buildEditImageGrid(ColorScheme colors) { + return Container( + padding: const EdgeInsets.fromLTRB(16, 6, 16, 0), + height: 72, + child: ListView.separated(scrollDirection: Axis.horizontal, + itemCount: _editImages.length + 1, + separatorBuilder: (_, __) => const SizedBox(width: 6), + itemBuilder: (ctx, i) { + if (i < _editImages.length) { + return Stack(children: [ + InkWell(onTap: () => _showImagePreview(_editImages, i), + child: Container(width: 56, height: 56, + decoration: BoxDecoration(borderRadius: BorderRadius.circular(6), border: Border.all(color: colors.outlineVariant, width: 0.5)), + clipBehavior: Clip.antiAlias, + child: FadeInLocalImage(path: _editImages[i], fit: BoxFit.cover))), + Positioned(top: -4, right: -4, + child: GestureDetector(onTap: () => setState(() => _editImages.removeAt(i)), + child: Container(width: 16, height: 16, + decoration: BoxDecoration(color: colors.surface, shape: BoxShape.circle, border: Border.all(color: colors.outline)), + child: Icon(Icons.close, size: 10, color: colors.onSurface.withValues(alpha: 0.5))))), + ]); + } + return InkWell(onTap: _pickEditImage, + child: Container(width: 56, height: 56, + decoration: BoxDecoration(borderRadius: BorderRadius.circular(6), color: colors.surfaceContainerHighest, + border: Border.all(color: colors.outlineVariant)), + child: Icon(Icons.add_photo_alternate_outlined, size: 20, color: colors.onSurface.withValues(alpha: 0.3)))); + }), + ); + } + Widget _buildTagRow(List tags) { final colors = Theme.of(context).colorScheme; return Container( diff --git a/lib/pages/note/note_tab_page.dart b/lib/pages/note/note_tab_page.dart index 72de466..e6d8316 100644 --- a/lib/pages/note/note_tab_page.dart +++ b/lib/pages/note/note_tab_page.dart @@ -10,6 +10,7 @@ import '../../utils/responsive.dart'; import '../../widgets/master_detail_scaffold.dart'; import '../../widgets/detail_placeholder.dart'; import 'note_detail_page.dart'; +import 'note_add_page.dart'; /// 笔记标签页(分页 + 触底加载) class NoteTabPage extends StatefulWidget { @@ -139,11 +140,14 @@ class _NoteTabPageState extends State { } final masterContent = _buildContent(isWideContent); if (!isWideContent) return masterContent; + final detailWidget = provider.isAdding && provider.addingType == 2 + ? NoteAddPage(onCancel: () => provider.cancelAdding()) + : provider.selectedNote != null + ? NoteDetailPage(note: provider.selectedNote!, embedded: true) + : const DetailPlaceholder(icon: Icons.note_outlined, message: '选择一条笔记查看详情'); return MasterDetailScaffold( master: masterContent, - detail: provider.selectedNote != null - ? NoteDetailPage(note: provider.selectedNote!, embedded: true) - : const DetailPlaceholder(icon: Icons.note_outlined, message: '选择一条笔记查看详情'), + detail: detailWidget, ); }); } diff --git a/lib/providers/app_provider.dart b/lib/providers/app_provider.dart index 19a2b95..bfaeac8 100644 --- a/lib/providers/app_provider.dart +++ b/lib/providers/app_provider.dart @@ -52,6 +52,8 @@ class AppProvider extends ChangeNotifier { Book? _selectedBook; Note? _selectedNote; Game? _selectedGame; + bool _isAdding = false; + int? _addingType; // 0=影视, 1=阅读, 2=笔记, 3=游戏, null=未选择类型 // 主题模式 ThemeMode _themeMode = ThemeMode.system; @@ -323,6 +325,43 @@ class AppProvider extends ChangeNotifier { notifyListeners(); } + bool get isAdding => _isAdding; + int? get addingType => _addingType; + + void startAdding() { + _isAdding = true; + _addingType = null; + // 清除选中项,避免同时显示详情和添加 + _selectedMovie = null; + _selectedBook = null; + _selectedNote = null; + _selectedGame = null; + notifyListeners(); + } + + void startAddingType(int type) { + _isAdding = true; + _addingType = type; + _selectedMovie = null; + _selectedBook = null; + _selectedNote = null; + _selectedGame = null; + _mainTabIndex = type; + notifyListeners(); + } + + void cancelAdding() { + _isAdding = false; + _addingType = null; + notifyListeners(); + } + + void finishAdding() { + _isAdding = false; + _addingType = null; + notifyListeners(); + } + void setBottomNavVisible(bool visible) { if (_bottomNavVisible != visible) { _bottomNavVisible = visible; diff --git a/lib/services/epub/epub_webview_handler.dart b/lib/services/epub/epub_webview_handler.dart index e398173..170bf28 100644 --- a/lib/services/epub/epub_webview_handler.dart +++ b/lib/services/epub/epub_webview_handler.dart @@ -1,5 +1,6 @@ import 'dart:io'; import 'dart:typed_data'; +import 'package:flutter/foundation.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; import 'epub_stream_service.dart'; import '../../utils/image_path_helper.dart'; @@ -99,6 +100,8 @@ class EpubWebViewHandler { required WebUri requestUrl, }) async { try { + debugPrint('[EPUB-Handler] customScheme: $requestUrl'); + // Serve user-imported fonts. if (isFontRequest(requestUrl)) { final fontResult = await _readFontFile(requestUrl); @@ -144,6 +147,7 @@ class EpubWebViewHandler { ) async { final prefix = "/book/$fileHash/"; if (!requestUrl.path.startsWith(prefix)) { + debugPrint('[EPUB-Handler] path mismatch: ${requestUrl.path} does not start with $prefix'); return null; } @@ -156,9 +160,13 @@ class EpubWebViewHandler { targetFilePath: fileRelativePath, ); - if (data == null) return null; + if (data == null) { + debugPrint('[EPUB-Handler] file not found in epub: $fileRelativePath'); + return null; + } final mimeType = _streamService.getMimeType(fileRelativePath); + debugPrint('[EPUB-Handler] serving: $fileRelativePath ($mimeType, ${data.length} bytes)'); return (data, mimeType); } @@ -195,6 +203,38 @@ class EpubWebViewHandler { 'woff2': 'font/woff2', }; + /// Read HTML content from EPUB for srcdoc injection (Windows WebView2). + /// [url] is the virtual epub:// URL; extracts the relative path and reads the file. + /// Returns (htmlContent, baseUrl) where baseUrl points to the file's directory + /// so that relative URLs in the HTML resolve correctly. + Future<(String, String)?> readHtmlContentWithBaseUrl({ + required String epubPath, + required String fileHash, + required String url, + }) async { + try { + final uri = Uri.parse(url); + final prefix = "/book/$fileHash/"; + if (!uri.path.startsWith(prefix)) return null; + final decodedPath = Uri.decodeFull(uri.path); + final relativePath = decodedPath.substring(prefix.length).split('#')[0]; + final data = await _streamService.readFileFromEpub( + epubPath: epubPath, + targetFilePath: relativePath, + ); + if (data == null) return null; + final htmlContent = String.fromCharCodes(data); + // Base URL should point to the directory containing the HTML file + final dirPath = relativePath.contains('/') + ? relativePath.substring(0, relativePath.lastIndexOf('/') + 1) + : ''; + final baseUrl = '$virtualScheme://$virtualDomain/book/$fileHash/$dirPath'; + return (htmlContent, baseUrl); + } catch (_) { + return null; + } + } + /// Generate base URL for a chapter. /// This URL should be used as the baseUrl parameter when loading HTML. static String getBaseUrl() { diff --git a/lib/services/epub/reader_scripts.dart b/lib/services/epub/reader_scripts.dart index 50daed4..fa43031 100644 --- a/lib/services/epub/reader_scripts.dart +++ b/lib/services/epub/reader_scripts.dart @@ -66,6 +66,41 @@ String generateSkeletonHtml( +