generated from dellevin/template
新增阅读器功能,待优化
This commit is contained in:
@@ -29,6 +29,7 @@ class _BookTabPageState extends State<BookTabPage> {
|
||||
DateTime? _lastUpdatedAt;
|
||||
late ScrollController _scrollController;
|
||||
AppProvider? _provider;
|
||||
int _lastScrollSignal = 0;
|
||||
|
||||
static const _statusMap = {0: 'read', 1: 'reading', 2: 'want_to_read'};
|
||||
|
||||
@@ -57,6 +58,15 @@ class _BookTabPageState extends State<BookTabPage> {
|
||||
void _onDataChanged() {
|
||||
if (!_initialized || !mounted) return;
|
||||
final provider = context.read<AppProvider>();
|
||||
|
||||
// 检查回到顶部信号
|
||||
if (provider.scrollToTopSignal != _lastScrollSignal && provider.scrollToTopSignal > 0) {
|
||||
_lastScrollSignal = provider.scrollToTopSignal;
|
||||
if (_scrollController.hasClients) {
|
||||
_scrollController.animateTo(0, duration: const Duration(milliseconds: 300), curve: Curves.easeOut);
|
||||
}
|
||||
}
|
||||
|
||||
final count = provider.books.length;
|
||||
final latest = provider.books.isNotEmpty ? provider.books.first.updatedAt : null;
|
||||
if (count != _lastDataCount || latest != _lastUpdatedAt) {
|
||||
|
||||
@@ -26,7 +26,7 @@ class _MainContentPageState extends State<MainContentPage> {
|
||||
bool _showNoteTab = true;
|
||||
|
||||
late PageController _pageController;
|
||||
bool _isTabTap = false; // 防止点击 Tab 和滑动互斥
|
||||
bool _isTabTap = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -82,6 +82,8 @@ class _MainContentPageState extends State<MainContentPage> {
|
||||
);
|
||||
}
|
||||
|
||||
// ─── AppBar ──────────────────────────────────────────
|
||||
|
||||
Widget _buildAppBar(BuildContext context) {
|
||||
return Consumer<AppProvider>(
|
||||
builder: (context, provider, child) {
|
||||
@@ -99,6 +101,17 @@ class _MainContentPageState extends State<MainContentPage> {
|
||||
);
|
||||
}
|
||||
|
||||
String _getAppBarTitle(AppProvider provider) {
|
||||
switch (provider.mainTabIndex) {
|
||||
case 0: return '影视';
|
||||
case 1: return '阅读';
|
||||
case 2: return '笔记';
|
||||
default: return 'MookNote';
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 云备份 ──────────────────────────────────────────
|
||||
|
||||
Widget _buildCloudSyncButton(BuildContext context) {
|
||||
return IconButton(
|
||||
icon: const Icon(Icons.cloud_sync_outlined),
|
||||
@@ -110,7 +123,6 @@ class _MainContentPageState extends State<MainContentPage> {
|
||||
void _showCloudSheet(BuildContext context) async {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
final hasConfig = (await WebDAVService.instance.getConfig()) != null;
|
||||
|
||||
if (!mounted) return;
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
@@ -220,18 +232,7 @@ class _MainContentPageState extends State<MainContentPage> {
|
||||
]),
|
||||
);
|
||||
|
||||
String _getAppBarTitle(AppProvider provider) {
|
||||
switch (provider.mainTabIndex) {
|
||||
case 0: return '影视';
|
||||
case 1: return '阅读';
|
||||
case 2: return '笔记';
|
||||
default: return 'MookNote';
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// Tab 栏 + 指示条(跟随 PageView 滑动)
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// ─── Tab 栏 + 指示条 ─────────────────────────────────
|
||||
|
||||
Widget _buildTabBar(BuildContext context) {
|
||||
return Consumer<AppProvider>(
|
||||
@@ -273,7 +274,6 @@ class _MainContentPageState extends State<MainContentPage> {
|
||||
}).toList(),
|
||||
),
|
||||
),
|
||||
// 指示条 — 跟随 PageView 滑动
|
||||
AnimatedBuilder(
|
||||
animation: _pageController,
|
||||
builder: (context, _) {
|
||||
@@ -302,9 +302,7 @@ class _MainContentPageState extends State<MainContentPage> {
|
||||
);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// PageView 内容区
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// ─── PageView 内容区 ─────────────────────────────────
|
||||
|
||||
Widget _buildTabContent() {
|
||||
return Consumer<AppProvider>(
|
||||
@@ -312,7 +310,6 @@ class _MainContentPageState extends State<MainContentPage> {
|
||||
final tabs = _enabledTabs;
|
||||
final safeIndex = _mapToEnabledTabIndex(provider.mainTabIndex).clamp(0, tabs.length - 1);
|
||||
|
||||
// 同步 provider → PageView(点击 Tab 触发)
|
||||
if (_isTabTap && _pageController.hasClients) {
|
||||
_pageController.animateToPage(safeIndex, duration: const Duration(milliseconds: 350), curve: Curves.easeInOut);
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ class _MovieTabPageState extends State<MovieTabPage> {
|
||||
DateTime? _lastUpdatedAt;
|
||||
late ScrollController _scrollController;
|
||||
AppProvider? _provider;
|
||||
int _lastScrollSignal = 0;
|
||||
|
||||
static const _statusMap = {0: 'watched', 1: 'watching', 2: 'want_to_watch'};
|
||||
|
||||
@@ -57,6 +58,15 @@ class _MovieTabPageState extends State<MovieTabPage> {
|
||||
void _onDataChanged() {
|
||||
if (!_initialized || !mounted) return;
|
||||
final provider = context.read<AppProvider>();
|
||||
|
||||
// 检查回到顶部信号
|
||||
if (provider.scrollToTopSignal != _lastScrollSignal && provider.scrollToTopSignal > 0) {
|
||||
_lastScrollSignal = provider.scrollToTopSignal;
|
||||
if (_scrollController.hasClients) {
|
||||
_scrollController.animateTo(0, duration: const Duration(milliseconds: 300), curve: Curves.easeOut);
|
||||
}
|
||||
}
|
||||
|
||||
final count = provider.movies.length;
|
||||
final latest = provider.movies.isNotEmpty ? provider.movies.first.updatedAt : null;
|
||||
if (count != _lastDataCount || latest != _lastUpdatedAt) {
|
||||
|
||||
@@ -26,6 +26,7 @@ class _NoteTabPageState extends State<NoteTabPage> {
|
||||
bool _initialized = false;
|
||||
int _lastDataCount = -1;
|
||||
DateTime? _lastUpdatedAt;
|
||||
int _lastScrollSignal = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -52,6 +53,15 @@ class _NoteTabPageState extends State<NoteTabPage> {
|
||||
void _onDataChanged() {
|
||||
if (!_initialized || !mounted) return;
|
||||
final provider = context.read<AppProvider>();
|
||||
|
||||
// 检查回到顶部信号
|
||||
if (provider.scrollToTopSignal != _lastScrollSignal && provider.scrollToTopSignal > 0) {
|
||||
_lastScrollSignal = provider.scrollToTopSignal;
|
||||
if (_scrollController.hasClients) {
|
||||
_scrollController.animateTo(0, duration: const Duration(milliseconds: 300), curve: Curves.easeOut);
|
||||
}
|
||||
}
|
||||
|
||||
final count = provider.notes.length;
|
||||
final latest = provider.notes.isNotEmpty ? provider.notes.first.updatedAt : null;
|
||||
if (count != _lastDataCount || latest != _lastUpdatedAt) {
|
||||
|
||||
182
lib/pages/reader/bookshelf_page.dart
Normal file
182
lib/pages/reader/bookshelf_page.dart
Normal file
@@ -0,0 +1,182 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../../models/reader_book.dart';
|
||||
import '../../providers/app_provider.dart';
|
||||
import '../../service/book_import_service.dart';
|
||||
import 'reader_book_detail_page.dart';
|
||||
|
||||
/// 书架页面 — 展示导入的阅读器书籍,支持网格/列表切换
|
||||
class BookshelfPage extends StatefulWidget {
|
||||
const BookshelfPage({super.key});
|
||||
|
||||
@override
|
||||
State<BookshelfPage> createState() => _BookshelfPageState();
|
||||
}
|
||||
|
||||
class _BookshelfPageState extends State<BookshelfPage> {
|
||||
bool _isGridView = true;
|
||||
|
||||
Future<void> _importBook() async {
|
||||
final provider = context.read<AppProvider>();
|
||||
await BookImportService.pickAndImportBook(context, provider);
|
||||
}
|
||||
|
||||
void _openBookDetail(ReaderBook book) {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (_) => ReaderBookDetailPage(book: book),
|
||||
),
|
||||
).then((_) {
|
||||
context.read<AppProvider>().loadReaderBooks();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: colors.surface,
|
||||
appBar: AppBar(
|
||||
title: const Text('阅读器'),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: Icon(_isGridView ? Icons.view_list : Icons.grid_view),
|
||||
tooltip: _isGridView ? '列表视图' : '网格视图',
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_isGridView = !_isGridView;
|
||||
});
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.add),
|
||||
tooltip: '导入书籍',
|
||||
onPressed: _importBook,
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Consumer<AppProvider>(
|
||||
builder: (context, provider, child) {
|
||||
final books = provider.readerBooks;
|
||||
|
||||
if (books.isEmpty) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.menu_book_outlined, size: 64, color: colors.onSurface.withValues(alpha: 0.15)),
|
||||
const SizedBox(height: 16),
|
||||
Text('点击右上角导入书籍',
|
||||
style: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.3))),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (_isGridView) {
|
||||
return GridView.builder(
|
||||
padding: const EdgeInsets.all(16),
|
||||
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: 3,
|
||||
mainAxisSpacing: 16,
|
||||
crossAxisSpacing: 12,
|
||||
childAspectRatio: 0.65,
|
||||
),
|
||||
itemCount: books.length,
|
||||
itemBuilder: (context, index) => _buildGridViewItem(books[index], colors),
|
||||
);
|
||||
}
|
||||
|
||||
return ListView.builder(
|
||||
padding: const EdgeInsets.all(16),
|
||||
itemCount: books.length,
|
||||
itemBuilder: (context, index) => _buildListViewItem(books[index], colors),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildGridViewItem(ReaderBook book, ColorScheme colors) {
|
||||
return GestureDetector(
|
||||
onTap: () => _openBookDetail(book),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Container(
|
||||
width: double.infinity,
|
||||
decoration: BoxDecoration(
|
||||
color: colors.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(color: colors.outlineVariant, width: 0.5),
|
||||
),
|
||||
child: Center(
|
||||
child: Icon(Icons.menu_book, size: 40, color: colors.onSurface.withValues(alpha: 0.2)),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(book.title,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(fontSize: 12, fontWeight: FontWeight.w500, color: colors.onSurface)),
|
||||
if (book.readingPercentage > 0)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 1),
|
||||
child: Text('${(book.readingPercentage * 100).toStringAsFixed(0)}%',
|
||||
style: TextStyle(fontSize: 10, color: colors.onSurface.withValues(alpha: 0.3))),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildListViewItem(ReaderBook book, ColorScheme colors) {
|
||||
return GestureDetector(
|
||||
onTap: () => _openBookDetail(book),
|
||||
child: Container(
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: colors.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 48,
|
||||
height: 64,
|
||||
decoration: BoxDecoration(
|
||||
color: colors.surface,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Icon(Icons.menu_book, size: 24, color: colors.onSurface.withValues(alpha: 0.2)),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(book.title,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500, color: colors.onSurface)),
|
||||
const SizedBox(height: 4),
|
||||
Text('.${book.fileExtension}',
|
||||
style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.3))),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (book.readingPercentage > 0)
|
||||
Text('${(book.readingPercentage * 100).toStringAsFixed(0)}%',
|
||||
style: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.4))),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
261
lib/pages/reader/epub_player.dart
Normal file
261
lib/pages/reader/epub_player.dart
Normal file
@@ -0,0 +1,261 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:wakelock_plus/wakelock_plus.dart';
|
||||
import '../../models/reader_book.dart';
|
||||
import '../../providers/app_provider.dart';
|
||||
import '../../service/book_server.dart';
|
||||
import '../../utils/book_file_helper.dart';
|
||||
import '../../utils/reader_url_generator.dart';
|
||||
|
||||
/// 目录条目
|
||||
class TocItem {
|
||||
final String href;
|
||||
final String title;
|
||||
|
||||
TocItem({required this.href, required this.title});
|
||||
|
||||
factory TocItem.fromJson(Map<String, dynamic> json) {
|
||||
return TocItem(
|
||||
href: json['href'] ?? '',
|
||||
title: json['title'] ?? '',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 核心电子书阅读组件 — 使用 InAppWebView 渲染 foliate-js 阅读器
|
||||
class EpubPlayer extends StatefulWidget {
|
||||
final ReaderBook book;
|
||||
final String? initialCfi;
|
||||
final VoidCallback showOrHideToolbar;
|
||||
final ValueChanged<List<TocItem>>? onTocReady;
|
||||
|
||||
const EpubPlayer({
|
||||
super.key,
|
||||
required this.book,
|
||||
this.initialCfi,
|
||||
required this.showOrHideToolbar,
|
||||
this.onTocReady,
|
||||
});
|
||||
|
||||
@override
|
||||
State<EpubPlayer> createState() => EpubPlayerState();
|
||||
}
|
||||
|
||||
class EpubPlayerState extends State<EpubPlayer> {
|
||||
late InAppWebViewController _controller;
|
||||
String cfi = '';
|
||||
double percentage = 0.0;
|
||||
String chapterTitle = '';
|
||||
int chapterCurrentPage = 0;
|
||||
int chapterTotalPages = 0;
|
||||
|
||||
Timer? _styleTimer;
|
||||
|
||||
InAppWebViewSettings get _settings => InAppWebViewSettings(
|
||||
supportZoom: false,
|
||||
transparentBackground: true,
|
||||
useHybridComposition: true,
|
||||
mixedContentMode: MixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW,
|
||||
);
|
||||
|
||||
// ─── 翻页方法 ───────────────────────────────────────
|
||||
|
||||
void prevPage() {
|
||||
_controller.evaluateJavascript(source: 'prevPage()');
|
||||
}
|
||||
|
||||
void nextPage() {
|
||||
_controller.evaluateJavascript(source: 'nextPage()');
|
||||
}
|
||||
|
||||
void prevChapter() {
|
||||
_controller.evaluateJavascript(source: 'prevSection()');
|
||||
}
|
||||
|
||||
void nextChapter() {
|
||||
_controller.evaluateJavascript(source: 'nextSection()');
|
||||
}
|
||||
|
||||
void goToPercentage(double value) {
|
||||
_controller.evaluateJavascript(source: 'goToPercent($value)');
|
||||
}
|
||||
|
||||
void goToHref(String href) {
|
||||
_controller.evaluateJavascript(source: "goToHref('$href')");
|
||||
}
|
||||
|
||||
void goToCfi(String cfi) {
|
||||
_controller.evaluateJavascript(source: "goToCfi('$cfi')");
|
||||
}
|
||||
|
||||
// ─── 样式方法 ───────────────────────────────────────
|
||||
|
||||
void changeStyle({
|
||||
double? fontSize,
|
||||
double? lineHeight,
|
||||
double? paragraphSpacing,
|
||||
String? fontColor,
|
||||
String? backgroundColor,
|
||||
}) {
|
||||
_styleTimer?.cancel();
|
||||
_styleTimer = Timer(const Duration(milliseconds: 200), () {
|
||||
if (!mounted) return;
|
||||
|
||||
final params = <String, dynamic>{};
|
||||
if (fontSize != null) params['fontSize'] = (fontSize * 100).round();
|
||||
if (lineHeight != null) params['spacing'] = lineHeight;
|
||||
if (paragraphSpacing != null) params['paragraphSpacing'] = paragraphSpacing;
|
||||
if (fontColor != null) params['fontColor'] = '#$fontColor';
|
||||
if (backgroundColor != null) params['backgroundColor'] = '#$backgroundColor';
|
||||
|
||||
if (params.isEmpty) return;
|
||||
|
||||
final jsonParams = jsonEncode(params);
|
||||
_controller.evaluateJavascript(source: 'changeStyle($jsonParams)');
|
||||
});
|
||||
}
|
||||
|
||||
void changeTheme(String bgColor, String textColor) {
|
||||
_controller.evaluateJavascript(source: '''
|
||||
changeStyle({
|
||||
backgroundColor: '#$bgColor',
|
||||
fontColor: '#$textColor',
|
||||
})
|
||||
''');
|
||||
}
|
||||
|
||||
// ─── 保存进度 ───────────────────────────────────────
|
||||
|
||||
Future<void> saveReadingProgress() async {
|
||||
if (cfi.isEmpty) return;
|
||||
final provider = context.read<AppProvider>();
|
||||
final updated = widget.book.copyWith(
|
||||
lastReadCfi: cfi,
|
||||
readingPercentage: percentage,
|
||||
updatedAt: DateTime.now(),
|
||||
);
|
||||
await provider.updateReaderBook(updated);
|
||||
}
|
||||
|
||||
// ─── WebView 回调 ───────────────────────────────────
|
||||
|
||||
Future<void> _onWebViewCreated(InAppWebViewController controller) async {
|
||||
_controller = controller;
|
||||
_setHandlers(controller);
|
||||
// 开启常亮
|
||||
WakelockPlus.enable();
|
||||
}
|
||||
|
||||
void _setHandlers(InAppWebViewController controller) {
|
||||
// 阅读位置变化
|
||||
controller.addJavaScriptHandler(
|
||||
handlerName: 'onRelocated',
|
||||
callback: (args) {
|
||||
final location = args[0] as Map<String, dynamic>;
|
||||
setState(() {
|
||||
cfi = location['cfi'] ?? '';
|
||||
percentage = double.tryParse(location['percentage']?.toString() ?? '0') ?? 0.0;
|
||||
chapterTitle = location['chapterTitle'] ?? '';
|
||||
chapterCurrentPage = location['chapterCurrentPage'] ?? 0;
|
||||
chapterTotalPages = location['chapterTotalPages'] ?? 0;
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// 点击事件(控制翻页和工具栏)
|
||||
controller.addJavaScriptHandler(
|
||||
handlerName: 'onClick',
|
||||
callback: (args) {
|
||||
final location = args[0] as Map<String, dynamic>;
|
||||
final x = location['x'] as num?;
|
||||
final y = location['y'] as num?;
|
||||
if (x == null || y == null) return;
|
||||
|
||||
final pageWidth = MediaQuery.of(context).size.width;
|
||||
final clickX = x.toDouble() * pageWidth;
|
||||
final oneThird = pageWidth / 3;
|
||||
final twoThird = pageWidth * 2 / 3;
|
||||
|
||||
if (clickX < oneThird) {
|
||||
prevPage();
|
||||
} else if (clickX > twoThird) {
|
||||
nextPage();
|
||||
} else {
|
||||
widget.showOrHideToolbar();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// 目录数据
|
||||
controller.addJavaScriptHandler(
|
||||
handlerName: 'onSetToc',
|
||||
callback: (args) {
|
||||
final List<dynamic> rawToc = args[0];
|
||||
final toc = rawToc.map((item) {
|
||||
if (item is Map) {
|
||||
return TocItem.fromJson(Map<String, dynamic>.from(item));
|
||||
}
|
||||
return TocItem(href: '', title: item.toString());
|
||||
}).toList();
|
||||
widget.onTocReady?.call(toc);
|
||||
},
|
||||
);
|
||||
|
||||
// 翻页上拉手势
|
||||
controller.addJavaScriptHandler(
|
||||
handlerName: 'onPullUp',
|
||||
callback: (args) {
|
||||
widget.showOrHideToolbar();
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_styleTimer?.cancel();
|
||||
saveReadingProgress();
|
||||
WakelockPlus.disable();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
|
||||
final fileAbsolute = BookFileHelper.instance.resolveAbsolutePath(widget.book.filePath);
|
||||
final fileExists = fileAbsolute.isNotEmpty && File(fileAbsolute).existsSync();
|
||||
final bookUrl = 'http://127.0.0.1:${Server().port}/book/${Uri.encodeComponent(fileAbsolute)}';
|
||||
final initialCfi = widget.initialCfi ?? widget.book.lastReadCfi;
|
||||
|
||||
final bgColor = isDark ? 'FF1A1A1A' : 'FFFFFFFF';
|
||||
final textColor = isDark ? 'FFE5E5E5' : 'FF1A1A1A';
|
||||
|
||||
final url = generateReaderUrl(
|
||||
fileUrl: bookUrl,
|
||||
cfi: initialCfi,
|
||||
backgroundColor: bgColor,
|
||||
textColor: textColor,
|
||||
isDarkMode: isDark,
|
||||
);
|
||||
|
||||
debugPrint('[EpubPlayer] port=${Server().port} running=${Server().isRunning}');
|
||||
debugPrint('[EpubPlayer] fileAbsolute=$fileAbsolute exists=$fileExists');
|
||||
|
||||
return InAppWebView(
|
||||
initialUrlRequest: URLRequest(url: WebUri(url)),
|
||||
initialSettings: _settings,
|
||||
onWebViewCreated: _onWebViewCreated,
|
||||
onReceivedError: (controller, request, error) {
|
||||
debugPrint('[EpubPlayer] WebView error: ${error.description}');
|
||||
},
|
||||
onConsoleMessage: (controller, msg) {
|
||||
debugPrint('[EpubPlayer] JS: ${msg.message}');
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
114
lib/pages/reader/progress_panel.dart
Normal file
114
lib/pages/reader/progress_panel.dart
Normal file
@@ -0,0 +1,114 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'epub_player.dart';
|
||||
|
||||
/// 进度控制面板 — 滑块跳转 + 章节信息
|
||||
class ProgressPanel extends StatefulWidget {
|
||||
final GlobalKey<EpubPlayerState> epubPlayerKey;
|
||||
|
||||
const ProgressPanel({super.key, required this.epubPlayerKey});
|
||||
|
||||
@override
|
||||
State<ProgressPanel> createState() => _ProgressPanelState();
|
||||
}
|
||||
|
||||
class _ProgressPanelState extends State<ProgressPanel> {
|
||||
double _sliderValue = 0.0;
|
||||
Timer? _debounceTimer;
|
||||
|
||||
EpubPlayerState? get _player => widget.epubPlayerKey.currentState;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_sliderValue = _player?.percentage ?? 0.0;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_debounceTimer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
final player = _player;
|
||||
final chapterTitle = player?.chapterTitle ?? '';
|
||||
final currentPage = player?.chapterCurrentPage ?? 0;
|
||||
final totalPages = player?.chapterTotalPages ?? 0;
|
||||
final percent = player?.percentage ?? 0.0;
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// 章节标题
|
||||
if (chapterTitle.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: Text(
|
||||
chapterTitle,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: colors.onSurface),
|
||||
),
|
||||
),
|
||||
// 滑块行
|
||||
Row(
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.skip_previous, size: 20),
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(minWidth: 36, minHeight: 36),
|
||||
onPressed: () => _player?.prevChapter(),
|
||||
),
|
||||
Expanded(
|
||||
child: Slider(
|
||||
value: _sliderValue.clamp(0.0, 1.0),
|
||||
onChanged: (value) {
|
||||
setState(() => _sliderValue = value);
|
||||
_debounceTimer?.cancel();
|
||||
_debounceTimer = Timer(const Duration(milliseconds: 100), () {
|
||||
_player?.goToPercentage(value);
|
||||
});
|
||||
},
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.skip_next, size: 20),
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(minWidth: 36, minHeight: 36),
|
||||
onPressed: () => _player?.nextChapter(),
|
||||
),
|
||||
],
|
||||
),
|
||||
// 页码和百分比
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 4),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||
children: [
|
||||
_infoItem('$currentPage', '当前页', colors),
|
||||
_infoItem('$totalPages', '总页数', colors),
|
||||
_infoItem('${(percent * 100).toStringAsFixed(1)}%', '进度', colors),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _infoItem(String value, String label, ColorScheme colors) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(value, style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: colors.onSurface)),
|
||||
const SizedBox(height: 2),
|
||||
Text(label, style: TextStyle(fontSize: 10, color: colors.onSurface.withValues(alpha: 0.4))),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
187
lib/pages/reader/reader_book_detail_page.dart
Normal file
187
lib/pages/reader/reader_book_detail_page.dart
Normal file
@@ -0,0 +1,187 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../../models/reader_book.dart';
|
||||
import '../../providers/app_provider.dart';
|
||||
import '../../utils/book_file_helper.dart';
|
||||
import 'reading_page.dart';
|
||||
|
||||
/// 阅读器书籍详情页
|
||||
class ReaderBookDetailPage extends StatefulWidget {
|
||||
final ReaderBook book;
|
||||
|
||||
const ReaderBookDetailPage({super.key, required this.book});
|
||||
|
||||
@override
|
||||
State<ReaderBookDetailPage> createState() => _ReaderBookDetailPageState();
|
||||
}
|
||||
|
||||
class _ReaderBookDetailPageState extends State<ReaderBookDetailPage> {
|
||||
late String _title;
|
||||
late ReaderBook _book;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_book = widget.book;
|
||||
_title = _book.title;
|
||||
}
|
||||
|
||||
Future<void> _startReading() async {
|
||||
// 确保获取最新的book数据
|
||||
final provider = context.read<AppProvider>();
|
||||
final latest = provider.readerBooks.firstWhere(
|
||||
(b) => b.id == _book.id,
|
||||
orElse: () => _book,
|
||||
);
|
||||
if (context.mounted) {
|
||||
await Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (_) => ReadingPage(book: latest),
|
||||
),
|
||||
);
|
||||
// 返回后刷新
|
||||
if (mounted) {
|
||||
await provider.loadReaderBooks();
|
||||
final updated = provider.readerBooks.firstWhere(
|
||||
(b) => b.id == _book.id,
|
||||
orElse: () => _book,
|
||||
);
|
||||
setState(() {
|
||||
_book = updated;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _deleteBook() async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('删除书籍'),
|
||||
content: Text('确定要删除「$_title」吗?\n此操作将同时删除书籍文件。'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx, false),
|
||||
child: const Text('取消'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
child: const Text('删除', style: TextStyle(color: Colors.red)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmed == true) {
|
||||
await BookFileHelper.instance.deleteBookFiles(_book.id);
|
||||
await context.read<AppProvider>().removeReaderBook(_book.id);
|
||||
if (mounted) {
|
||||
Navigator.pop(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: colors.surface,
|
||||
appBar: AppBar(
|
||||
title: const Text('书籍详情'),
|
||||
),
|
||||
body: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// 占位书封
|
||||
Center(
|
||||
child: Container(
|
||||
width: 140,
|
||||
height: 200,
|
||||
decoration: BoxDecoration(
|
||||
color: colors.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: colors.outlineVariant, width: 0.5),
|
||||
),
|
||||
child: Icon(Icons.menu_book, size: 64, color: colors.onSurface.withValues(alpha: 0.2)),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// 书名
|
||||
Text('书名', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
|
||||
const SizedBox(height: 4),
|
||||
Text(_title, style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600, color: colors.onSurface)),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 文件名
|
||||
Text('文件', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
|
||||
const SizedBox(height: 4),
|
||||
Text('${_book.fileName} (.${_book.fileExtension})',
|
||||
style: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.6))),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 阅读进度
|
||||
Text('阅读进度', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
child: LinearProgressIndicator(
|
||||
value: _book.readingPercentage,
|
||||
minHeight: 8,
|
||||
backgroundColor: colors.surfaceContainerHighest,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text('${(_book.readingPercentage * 100).toStringAsFixed(1)}%',
|
||||
style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: colors.onSurface)),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 导入时间
|
||||
Text('导入时间', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
|
||||
const SizedBox(height: 4),
|
||||
Text(_book.createdAt.toString().substring(0, 10),
|
||||
style: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.6))),
|
||||
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// 底部按钮
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: OutlinedButton(
|
||||
onPressed: _deleteBook,
|
||||
style: OutlinedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(vertical: 14),
|
||||
),
|
||||
child: const Text('删除'),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: FilledButton(
|
||||
onPressed: _startReading,
|
||||
style: FilledButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(vertical: 14),
|
||||
),
|
||||
child: const Text('阅读'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
243
lib/pages/reader/reading_page.dart
Normal file
243
lib/pages/reader/reading_page.dart
Normal file
@@ -0,0 +1,243 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:pointer_interceptor/pointer_interceptor.dart';
|
||||
import '../../models/reader_book.dart';
|
||||
import '../../service/book_server.dart';
|
||||
import '../../utils/book_file_helper.dart';
|
||||
import 'epub_player.dart';
|
||||
import 'toc_drawer.dart';
|
||||
import 'progress_panel.dart';
|
||||
import 'style_panel.dart';
|
||||
|
||||
/// 书籍阅读页面
|
||||
class ReadingPage extends StatefulWidget {
|
||||
final ReaderBook book;
|
||||
|
||||
const ReadingPage({super.key, required this.book});
|
||||
|
||||
@override
|
||||
State<ReadingPage> createState() => _ReadingPageState();
|
||||
}
|
||||
|
||||
class _ReadingPageState extends State<ReadingPage> {
|
||||
final GlobalKey<EpubPlayerState> _epubPlayerKey = GlobalKey<EpubPlayerState>();
|
||||
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
|
||||
|
||||
static const _empty = SizedBox.shrink();
|
||||
bool _toolbarOffstage = true; // true=隐藏, false=显示
|
||||
Widget _currentPage = const SizedBox.shrink();
|
||||
bool _serverReady = false;
|
||||
|
||||
List<TocItem> _toc = [];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_initServer();
|
||||
SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
|
||||
}
|
||||
|
||||
Future<void> _initServer() async {
|
||||
String _ = await BookFileHelper.instance.bookFileRoot;
|
||||
await Server().start(preferredPort: 0);
|
||||
if (mounted) setState(() => _serverReady = true);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_epubPlayerKey.currentState?.saveReadingProgress();
|
||||
Server().stop();
|
||||
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _showToolbar() {
|
||||
setState(() {
|
||||
_toolbarOffstage = false;
|
||||
});
|
||||
}
|
||||
|
||||
void _hideToolbar() {
|
||||
setState(() {
|
||||
_currentPage = _empty;
|
||||
_toolbarOffstage = true;
|
||||
});
|
||||
}
|
||||
|
||||
void _toggleToolbar() {
|
||||
if (_toolbarOffstage) {
|
||||
_showToolbar();
|
||||
} else {
|
||||
_hideToolbar();
|
||||
}
|
||||
}
|
||||
|
||||
void _onTocReady(List<TocItem> toc) {
|
||||
if (mounted) setState(() => _toc = toc);
|
||||
}
|
||||
|
||||
void _openTocDrawer() {
|
||||
_hideToolbar();
|
||||
_scaffoldKey.currentState?.openDrawer();
|
||||
}
|
||||
|
||||
// ─── 底部面板切换 ─────────────────────────────────────
|
||||
|
||||
void _onProgressPressed() {
|
||||
setState(() {
|
||||
_currentPage = ProgressPanel(epubPlayerKey: _epubPlayerKey);
|
||||
});
|
||||
}
|
||||
|
||||
void _onStylePressed() {
|
||||
setState(() {
|
||||
_currentPage = StylePanel(epubPlayerKey: _epubPlayerKey);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
|
||||
// ─── 工具栏覆盖层(照抄 anx-reader 的 Offstage + PointerInterceptor 模式)
|
||||
Offstage controller = Offstage(
|
||||
offstage: _toolbarOffstage,
|
||||
child: PointerInterceptor(
|
||||
child: Stack(
|
||||
children: [
|
||||
// 半透明背景,点击关闭工具栏
|
||||
Positioned.fill(
|
||||
child: GestureDetector(
|
||||
onTap: _hideToolbar,
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onVerticalDragUpdate: (details) {},
|
||||
onVerticalDragEnd: (details) {},
|
||||
child: Container(
|
||||
color: Colors.black.withValues(alpha: 0.15),
|
||||
),
|
||||
),
|
||||
),
|
||||
// 顶部 AppBar + 底部工具栏
|
||||
Column(
|
||||
children: [
|
||||
// 顶部 AppBar
|
||||
AppBar(
|
||||
backgroundColor: colors.surface.withValues(alpha: 0.94),
|
||||
title: Text(widget.book.title, overflow: TextOverflow.ellipsis),
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
// 底部面板 + 按钮行
|
||||
BottomSheet(
|
||||
onClosing: () {},
|
||||
enableDrag: false,
|
||||
builder: (context) => SafeArea(
|
||||
top: false,
|
||||
child: Container(
|
||||
constraints: const BoxConstraints(maxWidth: 600),
|
||||
child: StatefulBuilder(
|
||||
builder: (BuildContext context, StateSetter modalSetState) {
|
||||
final hasContent = !identical(_currentPage, _empty);
|
||||
return IntrinsicHeight(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// 面板内容区域
|
||||
if (hasContent)
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
child: _currentPage,
|
||||
),
|
||||
),
|
||||
// 按钮行
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.toc),
|
||||
tooltip: '目录',
|
||||
onPressed: _openTocDrawer,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.data_usage),
|
||||
tooltip: '进度',
|
||||
onPressed: () {
|
||||
modalSetState(() {
|
||||
_onProgressPressed();
|
||||
});
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.color_lens),
|
||||
tooltip: '样式',
|
||||
onPressed: () {
|
||||
modalSetState(() {
|
||||
_onStylePressed();
|
||||
});
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.skip_previous),
|
||||
tooltip: '上一章',
|
||||
onPressed: () {
|
||||
_epubPlayerKey.currentState?.prevChapter();
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.skip_next),
|
||||
tooltip: '下一章',
|
||||
onPressed: () {
|
||||
_epubPlayerKey.currentState?.nextChapter();
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return Scaffold(
|
||||
key: _scaffoldKey,
|
||||
backgroundColor: colors.surface,
|
||||
// TOC 目录抽屉
|
||||
drawer: PointerInterceptor(
|
||||
child: Drawer(
|
||||
width: MediaQuery.of(context).size.width * 0.75,
|
||||
child: TocDrawer(
|
||||
toc: _toc,
|
||||
epubPlayerKey: _epubPlayerKey,
|
||||
),
|
||||
),
|
||||
),
|
||||
body: _serverReady
|
||||
? Stack(
|
||||
children: [
|
||||
// 阅读内容(WebView)
|
||||
EpubPlayer(
|
||||
key: _epubPlayerKey,
|
||||
book: widget.book,
|
||||
showOrHideToolbar: _toggleToolbar,
|
||||
onTocReady: _onTocReady,
|
||||
),
|
||||
// 工具栏覆盖层
|
||||
controller,
|
||||
],
|
||||
)
|
||||
: const Center(child: CircularProgressIndicator()),
|
||||
);
|
||||
}
|
||||
}
|
||||
162
lib/pages/reader/style_panel.dart
Normal file
162
lib/pages/reader/style_panel.dart
Normal file
@@ -0,0 +1,162 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../utils/user_prefs.dart';
|
||||
import 'epub_player.dart';
|
||||
|
||||
/// 预设主题
|
||||
const _presetThemes = [
|
||||
{'bg': 'FFFFFFFF', 'fg': 'FF1A1A1A', 'name': '默认'},
|
||||
{'bg': 'FF1A1A1A', 'fg': 'FFE5E5E5', 'name': '暗黑'},
|
||||
{'bg': 'FFF8F0E3', 'fg': 'FF333333', 'name': '护眼'},
|
||||
{'bg': 'FF2B2B2B', 'fg': 'FFCCCCCC', 'name': '深灰'},
|
||||
{'bg': 'FF2D3E50', 'fg': 'FFD4D4D4', 'name': '蓝灰'},
|
||||
];
|
||||
|
||||
/// 样式设置面板 — 字号、行距、主题
|
||||
class StylePanel extends StatefulWidget {
|
||||
final GlobalKey<EpubPlayerState> epubPlayerKey;
|
||||
|
||||
const StylePanel({super.key, required this.epubPlayerKey});
|
||||
|
||||
@override
|
||||
State<StylePanel> createState() => _StylePanelState();
|
||||
}
|
||||
|
||||
class _StylePanelState extends State<StylePanel> {
|
||||
double _fontSize = 1.0;
|
||||
double _lineHeight = 1.6;
|
||||
int _selectedTheme = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadPrefs();
|
||||
}
|
||||
|
||||
void _loadPrefs() {
|
||||
final sp = UserPrefs().prefs;
|
||||
setState(() {
|
||||
_fontSize = sp.getDouble('reader_font_size') ?? 1.0;
|
||||
_lineHeight = sp.getDouble('reader_line_height') ?? 1.6;
|
||||
_selectedTheme = sp.getInt('reader_theme_index') ?? 0;
|
||||
});
|
||||
}
|
||||
|
||||
void _savePrefs() {
|
||||
final sp = UserPrefs().prefs;
|
||||
sp.setDouble('reader_font_size', _fontSize);
|
||||
sp.setDouble('reader_line_height', _lineHeight);
|
||||
sp.setInt('reader_theme_index', _selectedTheme);
|
||||
}
|
||||
|
||||
void _applyStyle() {
|
||||
widget.epubPlayerKey.currentState?.changeStyle(
|
||||
fontSize: _fontSize,
|
||||
lineHeight: _lineHeight,
|
||||
);
|
||||
_savePrefs();
|
||||
}
|
||||
|
||||
void _applyTheme(int index) {
|
||||
final theme = _presetThemes[index];
|
||||
final bg = theme['bg']!;
|
||||
final fg = theme['fg']!;
|
||||
widget.epubPlayerKey.currentState?.changeTheme(bg, fg);
|
||||
setState(() => _selectedTheme = index);
|
||||
_savePrefs();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// 字号
|
||||
Row(
|
||||
children: [
|
||||
Text('字号', style: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.6))),
|
||||
Expanded(
|
||||
child: Slider(
|
||||
value: _fontSize,
|
||||
min: 0.5,
|
||||
max: 3.0,
|
||||
divisions: 25,
|
||||
label: '${(_fontSize * 100).round()}%',
|
||||
onChanged: (value) {
|
||||
setState(() => _fontSize = value);
|
||||
_applyStyle();
|
||||
},
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: 44,
|
||||
child: Text('${(_fontSize * 100).round()}%',
|
||||
textAlign: TextAlign.end,
|
||||
style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.5))),
|
||||
),
|
||||
],
|
||||
),
|
||||
// 行距
|
||||
Row(
|
||||
children: [
|
||||
Text('行距', style: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.6))),
|
||||
Expanded(
|
||||
child: Slider(
|
||||
value: _lineHeight,
|
||||
min: 1.0,
|
||||
max: 3.0,
|
||||
divisions: 20,
|
||||
label: _lineHeight.toStringAsFixed(1),
|
||||
onChanged: (value) {
|
||||
setState(() => _lineHeight = value);
|
||||
_applyStyle();
|
||||
},
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: 44,
|
||||
child: Text(_lineHeight.toStringAsFixed(1),
|
||||
textAlign: TextAlign.end,
|
||||
style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.5))),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
// 主题色块
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: List.generate(_presetThemes.length, (index) {
|
||||
final theme = _presetThemes[index];
|
||||
final bg = Color(int.parse(theme['bg']!, radix: 16));
|
||||
final fg = Color(int.parse(theme['fg']!, radix: 16));
|
||||
final isSelected = index == _selectedTheme;
|
||||
|
||||
return GestureDetector(
|
||||
onTap: () => _applyTheme(index),
|
||||
child: Container(
|
||||
width: 42,
|
||||
height: 42,
|
||||
margin: const EdgeInsets.symmetric(horizontal: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: bg,
|
||||
borderRadius: BorderRadius.circular(21),
|
||||
border: Border.all(
|
||||
color: isSelected ? colors.primary : colors.outlineVariant,
|
||||
width: isSelected ? 2.5 : 1,
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: Text('A', style: TextStyle(color: fg, fontSize: 16, fontWeight: FontWeight.w500)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
77
lib/pages/reader/toc_drawer.dart
Normal file
77
lib/pages/reader/toc_drawer.dart
Normal file
@@ -0,0 +1,77 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'epub_player.dart';
|
||||
|
||||
/// 目录抽屉 — 显示书籍章节目录,点击跳转
|
||||
class TocDrawer extends StatelessWidget {
|
||||
final List<TocItem> toc;
|
||||
final GlobalKey<EpubPlayerState> epubPlayerKey;
|
||||
final VoidCallback? onClose;
|
||||
|
||||
const TocDrawer({
|
||||
super.key,
|
||||
required this.toc,
|
||||
required this.epubPlayerKey,
|
||||
this.onClose,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
|
||||
return Container(
|
||||
color: colors.surface,
|
||||
child: SafeArea(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.toc, size: 20, color: colors.onSurface.withValues(alpha: 0.6)),
|
||||
const SizedBox(width: 10),
|
||||
Text('目录', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: colors.onSurface)),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: onClose ?? () => Navigator.pop(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Divider(height: 1, color: colors.outlineVariant),
|
||||
Expanded(
|
||||
child: toc.isEmpty
|
||||
? Center(
|
||||
child: Text('暂无目录', style: TextStyle(color: colors.onSurface.withValues(alpha: 0.3))),
|
||||
)
|
||||
: ListView.builder(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
itemCount: toc.length,
|
||||
itemBuilder: (context, index) {
|
||||
final item = toc[index];
|
||||
return InkWell(
|
||||
onTap: () {
|
||||
epubPlayerKey.currentState?.goToHref(item.href);
|
||||
Navigator.pop(context);
|
||||
},
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
|
||||
child: Text(
|
||||
item.title,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: colors.onSurface.withValues(alpha: 0.8),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user