This commit is contained in:
DelLevin-Home
2026-07-16 03:13:30 +08:00
parent a8842fe91d
commit 1aab6858a7
12 changed files with 1217 additions and 1306 deletions

View File

@@ -5,14 +5,23 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="index.css" /> <link rel="stylesheet" href="index.css" />
<style> <style>
html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; } html, body { margin: 0; padding: 0; min-height: 100%; overflow: hidden; }
#vditor { height: 100%; border: none !important; } #vditor { border: none !important; }
.vditor { border: none !important; } .vditor { border: none !important; }
.vditor-toolbar { display: none !important; } .vditor-toolbar { display: none !important; }
.vditor-ir, .vditor-ir,
.vditor-ir__marker--cursor, .vditor-ir__marker--cursor,
.vditor-content, .vditor-content,
.vditor-reset { background: transparent !important; } .vditor-reset { background: transparent !important; }
/* 正文字体小一些 */
.vditor-reset { font-size: 13px !important; line-height: 1.6 !important; }
/* 标题字体更大 */
.vditor-reset h1 { font-size: 22px !important; font-weight: 700 !important; }
.vditor-reset h2 { font-size: 18px !important; font-weight: 700 !important; }
.vditor-reset h3 { font-size: 16px !important; font-weight: 600 !important; }
.vditor-reset h4 { font-size: 15px !important; font-weight: 600 !important; }
.vditor-reset h5 { font-size: 14px !important; font-weight: 600 !important; }
.vditor-reset h6 { font-size: 13px !important; font-weight: 600 !important; }
/* 所有滚动条统一:极细极淡 */ /* 所有滚动条统一:极细极淡 */
*::-webkit-scrollbar { width: 4px; height: 4px; } *::-webkit-scrollbar { width: 4px; height: 4px; }
*::-webkit-scrollbar-track { background: transparent; } *::-webkit-scrollbar-track { background: transparent; }
@@ -26,17 +35,30 @@
<script src="index.min.js"></script> <script src="index.min.js"></script>
<script> <script>
let vditor = null; let vditor = null;
let _heightTimer = null;
let _contentTimer = null;
function initVditor(theme, placeholder) { function initVditor(theme, placeholder) {
// Android: 使用本地路径避免 CDN 请求Windows: 使用相对路径
var isAndroid = navigator.userAgent.indexOf('Android') > -1;
var themeBase = isAndroid
? 'file:///android_asset/flutter_assets/assets/vditor/dist'
: '.';
vditor = new Vditor('vditor', { vditor = new Vditor('vditor', {
height: '100%', height: 'auto',
mode: 'ir', mode: 'ir',
theme: theme, theme: theme === 'dark' ? 'dark' : 'light',
icon: 'ant', icon: 'ant',
placeholder: placeholder || '', placeholder: placeholder || '',
toolbar: false, toolbar: false,
cache: { enable: false }, cache: { enable: false },
preview: { theme: { current: theme } }, themePath: themeBase + '/css/content-theme',
preview: {
theme: {
current: theme === 'dark' ? 'dark' : 'light',
path: themeBase + '/css/content-theme',
},
},
upload: { upload: {
handler: function(files) { handler: function(files) {
for (let i = 0; i < files.length; i++) { for (let i = 0; i < files.length; i++) {
@@ -55,16 +77,38 @@
}, },
}, },
input: function(value) { input: function(value) {
window.flutter_inappwebview.callHandler('onContentChanged', value); // 防抖:避免每次按键都触发 JS Bridge
clearTimeout(_contentTimer);
_contentTimer = setTimeout(function() {
window.flutter_inappwebview.callHandler('onContentChanged', value);
}, 150);
// 高度通知也防抖
clearTimeout(_heightTimer);
_heightTimer = setTimeout(function() {
requestAnimationFrame(notifyHeight);
}, 200);
}, },
after: function() { after: function() {
window.flutter_inappwebview.callHandler('onVditorReady'); window.flutter_inappwebview.callHandler('onVditorReady');
// 初始化完成后通知高度
requestAnimationFrame(notifyHeight);
}, },
}); });
} }
function notifyHeight() {
const content = document.querySelector('.vditor-ir') || document.querySelector('.vditor-wysiwyg');
if (content) {
const h = content.scrollHeight;
window.flutter_inappwebview.callHandler('onHeightChanged', h);
}
}
function setValue(text) { function setValue(text) {
if (vditor) vditor.setValue(text); if (vditor) {
vditor.setValue(text);
setTimeout(() => requestAnimationFrame(notifyHeight), 100);
}
} }
function getValue() { function getValue() {
@@ -73,8 +117,9 @@
function setTheme(theme) { function setTheme(theme) {
if (vditor) { if (vditor) {
const codeTheme = theme === 'dark' ? 'dracula' : 'github'; var name = theme === 'dark' ? 'dark' : 'light';
vditor.setTheme(theme, theme, codeTheme); var codeTheme = theme === 'dark' ? 'dracula' : 'github';
vditor.setTheme(name, name, codeTheme);
} }
} }
@@ -85,12 +130,23 @@
} }
function insertValue(text) { function insertValue(text) {
if (vditor) vditor.insertValue(text); if (vditor) {
vditor.insertValue(text);
setTimeout(() => requestAnimationFrame(notifyHeight), 100);
}
} }
function destroy() { function destroy() {
if (vditor) { vditor.destroy(); vditor = null; } if (vditor) { vditor.destroy(); vditor = null; }
} }
function scrollToCursor() {
const cursor = document.querySelector('.vditor-ir__marker--cursor')
|| document.querySelector('.vditor-wysiwyg .vditor-cursor');
if (cursor) {
cursor.scrollIntoView({ block: 'center', behavior: 'smooth' });
}
}
</script> </script>
</body> </body>
</html> </html>

View File

@@ -1,13 +1,12 @@
import 'dart:io'; import 'dart:io';
import 'dart:ui';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart'; import 'package:file_picker/file_picker.dart';
import '../../data/epub/reader_dao.dart'; import '../../data/epub/reader_dao.dart';
import '../../services/epub/epub_service.dart'; import '../../services/epub/epub_service.dart';
import '../../utils/user_prefs.dart'; import '../../utils/user_prefs.dart';
import '../../utils/responsive.dart';
import '../../utils/toast_util.dart'; import '../../utils/toast_util.dart';
import 'epub_detail_page.dart'; import 'epub_detail_page.dart';
import 'widgets/book_grid_item.dart';
/// EPUB 书架页面 /// EPUB 书架页面
class EpubLibraryPage extends StatefulWidget { class EpubLibraryPage extends StatefulWidget {
@@ -25,9 +24,6 @@ class _EpubLibraryPageState extends State<EpubLibraryPage> {
bool _isLoading = true; bool _isLoading = true;
bool _isSearching = false; bool _isSearching = false;
final TextEditingController _searchCtrl = TextEditingController(); final TextEditingController _searchCtrl = TextEditingController();
ViewMode _viewMode = UserPrefs().epubViewMode == 1
? ViewMode.compact
: ViewMode.relaxed;
int _sortMode = UserPrefs().epubSortMode; int _sortMode = UserPrefs().epubSortMode;
@override @override
@@ -156,15 +152,9 @@ class _EpubLibraryPageState extends State<EpubLibraryPage> {
MaterialPageRoute( MaterialPageRoute(
builder: (_) => EpubDetailPage(bookId: book['id'], book: book), builder: (_) => EpubDetailPage(bookId: book['id'], book: book),
), ),
).then((_) => _loadBooks()); ).then((_) {
} if (mounted) _loadBooks();
void _toggleViewMode() {
setState(() {
_viewMode =
_viewMode == ViewMode.relaxed ? ViewMode.compact : ViewMode.relaxed;
}); });
UserPrefs().setEpubViewMode(_viewMode == ViewMode.compact ? 1 : 0);
} }
void _showSortMenu() { void _showSortMenu() {
@@ -215,6 +205,16 @@ class _EpubLibraryPageState extends State<EpubLibraryPage> {
); );
} }
/// 找到最近在读的书(进度 > 0 且 < 1按更新时间排序取第一本
Map<String, dynamic>? get _lastReadingBook {
final reading = _books.where((b) {
final p = (b['reading_percentage'] as num?)?.toDouble() ?? 0.0;
return p > 0.0 && p < 1.0;
}).toList();
if (reading.isEmpty) return null;
return reading.first;
}
@override @override
void dispose() { void dispose() {
_searchCtrl.dispose(); _searchCtrl.dispose();
@@ -280,11 +280,203 @@ class _EpubLibraryPageState extends State<EpubLibraryPage> {
? _buildEmpty(colors) ? _buildEmpty(colors)
: _filteredBooks.isEmpty : _filteredBooks.isEmpty
? Center(child: Text('无搜索结果', style: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.35)))) ? Center(child: Text('无搜索结果', style: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.35))))
: _buildGrid(colors)), : RefreshIndicator(
color: colors.primary,
onRefresh: _loadBooks,
child: _buildContent(colors),
)),
]), ]),
); );
} }
/// 主体内容:继续阅读横幅 + 书架列表
Widget _buildContent(ColorScheme colors) {
final lastBook = _lastReadingBook;
return CustomScrollView(
slivers: [
// 继续阅读横幅
if (lastBook != null && !_isSearching)
SliverToBoxAdapter(child: _buildContinueReading(colors, lastBook)),
// 书架列表
_buildSliverListView(colors),
],
);
}
/// 继续阅读横幅卡片 — 封面背景 + 毛玻璃
Widget _buildContinueReading(ColorScheme colors, Map<String, dynamic> book) {
final title = book['title'] as String? ?? '';
final author = book['author'] as String? ?? '';
final coverPath = book['cover_path'] as String?;
final progress = (book['reading_percentage'] as num?)?.toDouble() ?? 0.0;
final percentStr = '${(progress * 100).toInt()}%';
final hasCover = coverPath != null && coverPath.isNotEmpty && File(coverPath).existsSync();
return Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
GestureDetector(
onTap: () => _openBook(book),
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Stack(
fit: StackFit.passthrough,
children: [
// 底层:封面图做背景
if (hasCover)
SizedBox(
height: 140,
width: double.infinity,
child: Image.file(
File(coverPath!),
fit: BoxFit.cover,
errorBuilder: (_, __, ___) => Container(color: colors.primaryContainer),
),
),
// 毛玻璃遮罩层
ClipRRect(
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 16, sigmaY: 16),
child: Container(
height: 140,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: colors.surface.withValues(alpha: 0.35),
borderRadius: hasCover ? BorderRadius.zero : BorderRadius.circular(16),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 封面
Container(
width: 56,
height: 78,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: colors.outlineVariant,
boxShadow: [
BoxShadow(
color: colors.shadow.withValues(alpha: 0.2),
blurRadius: 8,
offset: const Offset(2, 3),
),
],
),
clipBehavior: Clip.antiAlias,
child: _buildCover(coverPath, colors),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w700,
color: colors.onSurface,
)),
if (author.isNotEmpty) ...[
const SizedBox(height: 3),
Text(author,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
color: colors.onSurface.withValues(alpha: 0.55),
)),
],
const Spacer(),
// 进度条 + 百分比
Row(
children: [
Expanded(
child: ClipRRect(
borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator(
value: progress,
minHeight: 6,
backgroundColor: colors.primary.withValues(alpha: 0.15),
valueColor: AlwaysStoppedAnimation<Color>(colors.primary),
),
),
),
const SizedBox(width: 10),
Text(percentStr,
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w700,
color: colors.primary,
)),
],
),
const SizedBox(height: 10),
// 继续阅读按钮
Align(
alignment: Alignment.centerRight,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 7),
decoration: BoxDecoration(
color: colors.primary,
borderRadius: BorderRadius.circular(20),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.play_arrow_rounded, size: 16, color: colors.onPrimary),
const SizedBox(width: 4),
Text('继续阅读',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: colors.onPrimary,
)),
],
),
),
),
],
),
),
],
),
),
),
),
],
),
),
),
// 书架分隔
Padding(
padding: const EdgeInsets.only(top: 20, left: 4, bottom: 4),
child: Row(
children: [
Text('书架',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
color: colors.onSurface.withValues(alpha: 0.45),
)),
const SizedBox(width: 8),
Expanded(
child: Container(
height: 0.5,
color: colors.outlineVariant,
),
),
],
),
),
],
),
);
}
List<Widget> _buildActions(ColorScheme colors) { List<Widget> _buildActions(ColorScheme colors) {
return [ return [
if (!_isSearching) if (!_isSearching)
@@ -292,16 +484,6 @@ class _EpubLibraryPageState extends State<EpubLibraryPage> {
icon: Icon(Icons.search, size: 20, color: colors.onSurface.withValues(alpha: 0.6)), icon: Icon(Icons.search, size: 20, color: colors.onSurface.withValues(alpha: 0.6)),
onPressed: _toggleSearch, onPressed: _toggleSearch,
), ),
IconButton(
icon: Icon(
_viewMode == ViewMode.relaxed
? Icons.view_compact_outlined
: Icons.view_agenda_outlined,
size: 20,
color: colors.onSurface.withValues(alpha: 0.6),
),
onPressed: _toggleViewMode,
),
IconButton( IconButton(
icon: Icon(Icons.sort, size: 20, color: colors.onSurface.withValues(alpha: 0.6)), icon: Icon(Icons.sort, size: 20, color: colors.onSurface.withValues(alpha: 0.6)),
onPressed: _showSortMenu, onPressed: _showSortMenu,
@@ -355,104 +537,90 @@ class _EpubLibraryPageState extends State<EpubLibraryPage> {
); );
} }
Widget _buildGrid(ColorScheme colors) { // ─── Sliver 书架 ────────────────────────────────────────────────────
final bool showList = _viewMode == ViewMode.compact;
if (showList) { Widget _buildSliverListView(ColorScheme colors) {
return _buildListView(colors); return SliverPadding(
} padding: const EdgeInsets.fromLTRB(12, 8, 12, 100),
return _buildGridView(colors); sliver: SliverList(
} delegate: SliverChildBuilderDelegate(
(context, index) => _buildListItem(colors, _filteredBooks[index]),
Widget _buildGridView(ColorScheme colors) { childCount: _filteredBooks.length,
return LayoutBuilder( ),
builder: (context, constraints) { ),
final count = responsiveCrossAxisCount(constraints.maxWidth, minItemWidth: 120);
return GridView.builder(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 100),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: count,
crossAxisSpacing: 12,
mainAxisSpacing: 16,
childAspectRatio: 0.55,
),
itemCount: _filteredBooks.length,
itemBuilder: (context, index) {
final book = _filteredBooks[index];
return BookGridItem(
book: book,
viewMode: ViewMode.relaxed,
onTap: () => _openBook(book),
onLongPress: () => _deleteBook(book),
);
},
);
},
); );
} }
Widget _buildListView(ColorScheme colors) { Widget _buildListItem(ColorScheme colors, Map<String, dynamic> book) {
return ListView.builder( final title = book['title'] as String? ?? '';
padding: const EdgeInsets.fromLTRB(12, 8, 12, 100), final author = book['author'] as String? ?? '';
itemCount: _filteredBooks.length, final coverPath = book['cover_path'] as String?;
itemBuilder: (context, index) { final progress = (book['reading_percentage'] as num?)?.toDouble() ?? 0.0;
final book = _filteredBooks[index]; final updatedAt = book['updated_at'] as String?;
final title = book['title'] as String? ?? '';
final author = book['author'] as String? ?? '';
final coverPath = book['cover_path'] as String?;
final progress = (book['reading_percentage'] as num?)?.toDouble() ?? 0.0;
// 阅读状态推断 // 阅读状态推断
final String statusLabel; final String statusLabel;
final Color statusColor; final Color statusColor;
if (progress >= 1.0) { if (progress >= 1.0) {
statusLabel = '已读'; statusLabel = '已读';
statusColor = const Color(0xFF16A34A); statusColor = const Color(0xFF16A34A);
} else if (progress > 0.0) { } else if (progress > 0.0) {
statusLabel = '在读'; statusLabel = '在读';
statusColor = colors.primary; statusColor = colors.primary;
} else { } else {
statusLabel = '未读'; statusLabel = '未读';
statusColor = const Color(0xFFDC2626); statusColor = const Color(0xFFDC2626);
} }
return GestureDetector( // 最后阅读时间
onTap: () => _openBook(book), String? lastReadText;
onLongPress: () => _deleteBook(book), if (updatedAt != null && updatedAt.isNotEmpty) {
child: Container( try {
margin: const EdgeInsets.only(bottom: 8), final dt = DateTime.parse(updatedAt);
padding: const EdgeInsets.all(12), lastReadText = _formatRelativeDate(dt);
decoration: BoxDecoration( } catch (_) {}
color: colors.surfaceContainerHigh, }
borderRadius: BorderRadius.circular(12),
return RepaintBoundary(
child: GestureDetector(
onTap: () => _openBook(book),
onLongPress: () => _deleteBook(book),
child: Container(
margin: const EdgeInsets.only(bottom: 8),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: colors.surfaceContainerHigh,
borderRadius: BorderRadius.circular(12),
),
child: Row(
children: [
// 封面
Container(
width: 48, height: 64,
decoration: BoxDecoration(
color: colors.outlineVariant,
borderRadius: BorderRadius.circular(6),
),
clipBehavior: Clip.antiAlias,
child: _buildCover(coverPath, colors),
), ),
child: Row( const SizedBox(width: 12),
children: [ // 信息
// 封面 Expanded(
Container( child: Column(
width: 48, height: 64, crossAxisAlignment: CrossAxisAlignment.start,
decoration: BoxDecoration( children: [
color: colors.outlineVariant, Text(title, maxLines: 1, overflow: TextOverflow.ellipsis,
borderRadius: BorderRadius.circular(6), style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: colors.onSurface)),
), if (author.isNotEmpty) ...[
clipBehavior: Clip.antiAlias, const SizedBox(height: 3),
child: _buildCover(coverPath, colors), Text(author, maxLines: 1, overflow: TextOverflow.ellipsis,
), style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.35))),
const SizedBox(width: 12), ],
// 信息 const SizedBox(height: 6),
Expanded( // 状态标签 + 最后阅读时间
child: Column( Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text(title, maxLines: 1, overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: colors.onSurface)),
if (author.isNotEmpty) ...[
const SizedBox(height: 3),
Text(author, maxLines: 1, overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.35))),
],
const SizedBox(height: 6),
// 状态标签
Container( Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration( decoration: BoxDecoration(
@@ -462,16 +630,51 @@ class _EpubLibraryPageState extends State<EpubLibraryPage> {
child: Text(statusLabel, child: Text(statusLabel,
style: TextStyle(fontSize: 11, fontWeight: FontWeight.w500, color: statusColor)), style: TextStyle(fontSize: 11, fontWeight: FontWeight.w500, color: statusColor)),
), ),
if (lastReadText != null) ...[
const SizedBox(width: 8),
Text(lastReadText,
style: TextStyle(
fontSize: 11,
color: colors.onSurface.withValues(alpha: 0.3),
)),
],
], ],
), ),
), // 进度条
const SizedBox(width: 8), if (progress > 0 && progress < 1.0) ...[
Icon(Icons.chevron_right, color: colors.onSurface.withValues(alpha: 0.2), size: 20), const SizedBox(height: 6),
], Row(
children: [
Expanded(
child: ClipRRect(
borderRadius: BorderRadius.circular(2),
child: LinearProgressIndicator(
value: progress,
minHeight: 3,
backgroundColor: colors.outlineVariant,
valueColor: AlwaysStoppedAnimation<Color>(colors.primary),
),
),
),
const SizedBox(width: 8),
Text('${(progress * 100).toInt()}%',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w500,
color: colors.primary,
)),
],
),
],
],
),
), ),
), const SizedBox(width: 8),
); Icon(Icons.chevron_right, color: colors.onSurface.withValues(alpha: 0.2), size: 20),
}, ],
),
),
),
); );
} }
@@ -479,8 +682,17 @@ class _EpubLibraryPageState extends State<EpubLibraryPage> {
if (path != null && path.isNotEmpty && File(path).existsSync()) { if (path != null && path.isNotEmpty && File(path).existsSync()) {
return ClipRRect( return ClipRRect(
borderRadius: BorderRadius.circular(6), borderRadius: BorderRadius.circular(6),
child: Image.file(File(path), fit: BoxFit.cover, child: Image.file(
width: double.infinity, height: double.infinity), File(path),
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity,
errorBuilder: (_, __, ___) => Container(
color: colors.outlineVariant,
child: Icon(Icons.auto_stories_outlined, size: 22,
color: colors.onSurface.withValues(alpha: 0.25)),
),
),
); );
} }
return Container( return Container(
@@ -493,4 +705,23 @@ class _EpubLibraryPageState extends State<EpubLibraryPage> {
); );
} }
/// 相对时间格式化
String _formatRelativeDate(DateTime date) {
final now = DateTime.now();
final diff = now.difference(date);
if (diff.isNegative) return '${date.month}${date.day}';
if (diff.inDays == 0) {
if (diff.inHours == 0) {
if (diff.inMinutes == 0) return '刚刚';
return '${diff.inMinutes}分钟前';
}
return '${diff.inHours}小时前';
} else if (diff.inDays < 7) {
return '${diff.inDays}天前';
} else if (diff.inDays < 30) {
return '${(diff.inDays / 7).floor()}周前';
} else {
return '${date.month}${date.day}';
}
}
} }

View File

@@ -24,13 +24,15 @@ class BookGridItem extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return GestureDetector( return RepaintBoundary(
child: GestureDetector(
onTap: onTap, onTap: onTap,
onLongPress: onLongPress, onLongPress: onLongPress,
child: switch (viewMode) { child: switch (viewMode) {
ViewMode.relaxed => _buildRelaxed(context), ViewMode.relaxed => _buildRelaxed(context),
ViewMode.compact => _buildCompact(context), ViewMode.compact => _buildCompact(context),
}, },
),
); );
} }
@@ -41,6 +43,7 @@ class BookGridItem extends StatelessWidget {
final colors = Theme.of(context).colorScheme; final colors = Theme.of(context).colorScheme;
final title = book['title'] as String? ?? ''; final title = book['title'] as String? ?? '';
final author = book['author'] as String? ?? ''; final author = book['author'] as String? ?? '';
final progress = _readingProgress;
return Column( return Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
@@ -59,8 +62,16 @@ class BookGridItem extends StatelessWidget {
), ),
clipBehavior: Clip.antiAlias, clipBehavior: Clip.antiAlias,
child: _buildCoverStack(context, fit: StackFit.expand, extras: [ child: _buildCoverStack(context, fit: StackFit.expand, extras: [
// 阅读状态角标 // 阅读状态圆点
_buildStatusBadge(context), _buildStatusDot(context),
// 底部进度条
if (progress > 0 && progress < 1.0)
Positioned(
bottom: 0,
left: 0,
right: 0,
child: _buildProgressBar(context, progress, height: 3),
),
]), ]),
), ),
), ),
@@ -95,13 +106,22 @@ class BookGridItem extends StatelessWidget {
Widget _buildCompact(BuildContext context) { Widget _buildCompact(BuildContext context) {
final title = book['title'] as String? ?? ''; final title = book['title'] as String? ?? '';
final author = book['author'] as String? ?? ''; final author = book['author'] as String? ?? '';
final progress = _readingProgress;
return _buildCoverStack( return _buildCoverStack(
context, context,
fit: StackFit.expand, fit: StackFit.expand,
extras: [ extras: [
// 阅读状态角标 // 阅读状态圆点
_buildStatusBadge(context), _buildStatusDot(context),
// 底部进度条
if (progress > 0 && progress < 1.0)
Positioned(
bottom: 0,
left: 0,
right: 0,
child: _buildProgressBar(context, progress, height: 3),
),
Positioned( Positioned(
bottom: 0, bottom: 0,
left: 0, left: 0,
@@ -193,23 +213,30 @@ class BookGridItem extends StatelessWidget {
} }
Widget _buildPlaceholder(BuildContext context) { Widget _buildPlaceholder(BuildContext context) {
final colors = Theme.of(context).colorScheme;
final title = book['title'] as String? ?? ''; final title = book['title'] as String? ?? '';
final initial = title.isNotEmpty ? title.substring(0, 1) : ''; final initial = title.isNotEmpty ? title.substring(0, 1) : '';
// 根据书名首字生成渐变色
final gradientColors = _generateGradientColors(initial);
return Container( return Container(
color: colors.surfaceContainerHighest, decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: gradientColors,
),
),
child: Center( child: Center(
child: initial.isNotEmpty child: initial.isNotEmpty
? Text(initial, ? Text(initial,
style: TextStyle( style: TextStyle(
fontSize: 32, fontSize: 32,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
color: colors.onSurface.withValues(alpha: 0.2), color: Colors.white.withValues(alpha: 0.85),
)) ))
: Icon( : Icon(
Icons.auto_stories_outlined, Icons.auto_stories_outlined,
size: 36, size: 36,
color: colors.onSurface.withValues(alpha: 0.2), color: Colors.white.withValues(alpha: 0.5),
), ),
), ),
); );
@@ -217,44 +244,76 @@ class BookGridItem extends StatelessWidget {
// ─── badge helpers ──────────────────────────────────────────────────────── // ─── badge helpers ────────────────────────────────────────────────────────
/// 阅读状态角标(左上角,含百分比 /// 阅读状态圆点(左上角,三色
Widget _buildStatusBadge(BuildContext context) { Widget _buildStatusDot(BuildContext context) {
final colors = Theme.of(context).colorScheme; final colors = Theme.of(context).colorScheme;
final progress = _readingProgress; final progress = _readingProgress;
final String label; final Color dotColor;
final Color color;
if (progress >= 1.0) { if (progress >= 1.0) {
label = '已读'; dotColor = const Color(0xFF16A34A);
color = const Color(0xFF16A34A);
} else if (progress > 0.0) { } else if (progress > 0.0) {
label = '在读 ${(progress * 100).toInt()}%'; dotColor = colors.primary;
color = colors.primary;
} else { } else {
label = '未读'; dotColor = const Color(0xFFDC2626);
color = const Color(0xFFDC2626);
} }
return Positioned( return Positioned(
top: 6, top: 6,
left: 6, left: 6,
child: Container( child: Container(
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2), width: 8,
height: 8,
decoration: BoxDecoration( decoration: BoxDecoration(
color: color.withValues(alpha: 0.85), color: dotColor,
borderRadius: BorderRadius.circular(4), shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: dotColor.withValues(alpha: 0.4),
blurRadius: 3,
offset: const Offset(0, 1),
),
],
), ),
child: Text(label,
style: const TextStyle(
color: Colors.white,
fontSize: 9,
fontWeight: FontWeight.w600,
)),
), ),
); );
} }
/// 底部进度条
Widget _buildProgressBar(BuildContext context, double progress, {double height = 3}) {
final colors = Theme.of(context).colorScheme;
return Column(
mainAxisSize: MainAxisSize.min,
children: [
LinearProgressIndicator(
value: progress,
minHeight: height,
backgroundColor: Colors.black26,
valueColor: AlwaysStoppedAnimation<Color>(colors.primary),
borderRadius: BorderRadius.zero,
),
],
);
}
// ─── helpers ────────────────────────────────────────────────────────────── // ─── helpers ──────────────────────────────────────────────────────────────
double get _readingProgress => double get _readingProgress =>
(book['reading_percentage'] as num?)?.toDouble() ?? 0.0; (book['reading_percentage'] as num?)?.toDouble() ?? 0.0;
/// 根据首字符生成渐变色
List<Color> _generateGradientColors(String initial) {
if (initial.isEmpty) return [const Color(0xFF6B7280), const Color(0xFF9CA3AF)];
final code = initial.codeUnitAt(0);
final palettes = [
[const Color(0xFF6366F1), const Color(0xFF8B5CF6)], // 靛蓝-紫
[const Color(0xFF3B82F6), const Color(0xFF06B6D4)], // 蓝-青
[const Color(0xFF10B981), const Color(0xFF34D399)], // 绿
[const Color(0xFFF59E0B), const Color(0xFFF97316)], // 琥珀-橙
[const Color(0xFFEF4444), const Color(0xFFF472B6)], // 红-粉
[const Color(0xFF8B5CF6), const Color(0xFFEC4899)], // 紫-粉
[const Color(0xFF14B8A6), const Color(0xFF3B82F6)], // 青-蓝
[const Color(0xFFF97316), const Color(0xFFEF4444)], // 橙-红
];
return palettes[code % palettes.length];
}
} }

View File

@@ -1,7 +1,5 @@
import 'dart:io'; import 'dart:io';
import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_markdown_plus/flutter_markdown_plus.dart'; import 'package:flutter_markdown_plus/flutter_markdown_plus.dart';
import 'package:image_picker/image_picker.dart'; import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as p; import 'package:path/path.dart' as p;
@@ -12,7 +10,6 @@ import '../../models/data_models.dart';
import '../../utils/toast_util.dart'; import '../../utils/toast_util.dart';
import '../../utils/image_path_helper.dart'; import '../../utils/image_path_helper.dart';
import '../../widgets/fade_in_local_image.dart'; import '../../widgets/fade_in_local_image.dart';
import '../../widgets/tag_side_panel.dart';
import '../../widgets/vditor_editor.dart'; import '../../widgets/vditor_editor.dart';
class NoteAddPage extends StatefulWidget { class NoteAddPage extends StatefulWidget {
@@ -125,20 +122,19 @@ class _NoteAddPageState extends State<NoteAddPage> {
} }
Widget _buildEditArea(ColorScheme colors) { Widget _buildEditArea(ColorScheme colors) {
final isWin = Platform.isWindows;
return Column(children: [ return Column(children: [
// 标题输入Windows: 更大更醒目) // 标题输入
Container( Container(
padding: EdgeInsets.symmetric(horizontal: isWin ? 48 : 16, vertical: isWin ? 16 : 8), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
decoration: BoxDecoration(border: Border(bottom: BorderSide(color: colors.outlineVariant, width: 0.5))), decoration: BoxDecoration(border: Border(bottom: BorderSide(color: colors.outlineVariant, width: 0.5))),
child: Center(child: ConstrainedBox(constraints: const BoxConstraints(maxWidth: 720), child: Center(child: ConstrainedBox(constraints: const BoxConstraints(maxWidth: 720),
child: TextField( child: TextField(
controller: _titleCtrl, controller: _titleCtrl,
maxLines: 1, maxLines: 1,
style: TextStyle(fontSize: isWin ? 22 : 16, fontWeight: FontWeight.w700, color: colors.onSurface, height: 1.4), style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: colors.onSurface, height: 1.4),
decoration: InputDecoration( decoration: InputDecoration(
hintText: '添加标题', hintText: '添加标题',
hintStyle: TextStyle(fontSize: isWin ? 22 : 16, fontWeight: FontWeight.w700, color: colors.onSurface.withValues(alpha: 0.2), height: 1.4), hintStyle: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: colors.onSurface.withValues(alpha: 0.2), height: 1.4),
border: InputBorder.none, enabledBorder: InputBorder.none, focusedBorder: InputBorder.none, border: InputBorder.none, enabledBorder: InputBorder.none, focusedBorder: InputBorder.none,
isDense: true, isDense: true,
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
@@ -147,163 +143,29 @@ class _NoteAddPageState extends State<NoteAddPage> {
), ),
)), )),
), ),
// Windows: 标签栏(彩色药丸样式) // 内容编辑
if (isWin)
Container(
padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 8),
child: Center(child: ConstrainedBox(constraints: const BoxConstraints(maxWidth: 720),
child: Align(
alignment: Alignment.centerLeft,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(mainAxisSize: MainAxisSize.min, children: [
for (int i = 0; i < _tags.length; i++)
Padding(
padding: const EdgeInsets.only(right: 6),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: colors.primaryContainer,
borderRadius: BorderRadius.circular(12),
),
child: Row(mainAxisSize: MainAxisSize.min, children: [
Text(_tags[i], style: TextStyle(fontSize: 12, color: colors.onPrimaryContainer, fontWeight: FontWeight.w500)),
const SizedBox(width: 4),
GestureDetector(
onTap: () => setState(() => _tags.removeAt(i)),
child: Icon(Icons.close, size: 12, color: colors.onPrimaryContainer.withValues(alpha: 0.6)),
),
]),
),
),
GestureDetector(
onTap: _showTagPanel,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 5),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
border: Border.all(color: colors.outline.withValues(alpha: 0.3), width: 1),
),
child: Row(mainAxisSize: MainAxisSize.min, children: [
Icon(Icons.add, size: 14, color: colors.onSurface.withValues(alpha: 0.4)),
const SizedBox(width: 3),
Text('标签', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
]),
),
),
]),
),
),
)),
),
// 内容编辑Windows: 限宽居中)
Expanded( Expanded(
child: isWin child: VditorEditor(
? Center(child: ConstrainedBox(constraints: const BoxConstraints(maxWidth: 720), key: _vditorKey,
child: VditorEditor( initialContent: _contentCtrl.text,
key: _vditorKey, noteId: _tempId,
initialContent: _contentCtrl.text, isDark: Theme.of(context).brightness == Brightness.dark,
noteId: _tempId, surfaceColor: colors.surface,
isDark: Theme.of(context).brightness == Brightness.dark, onContentChanged: (value) {
surfaceColor: colors.surface, _contentCtrl.text = value;
onContentChanged: (value) { setState(() {});
_contentCtrl.text = value; },
setState(() {}); ),
},
),
))
: 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, enabledBorder: InputBorder.none, focusedBorder: InputBorder.none,
contentPadding: const EdgeInsets.all(16),
),
onChanged: (_) => setState(() {}),
),
), ),
// 图片行 // 图片行
if (_images.isNotEmpty) _buildImageRow(colors), if (_images.isNotEmpty) _buildImageRow(colors),
// 底部标签 + 工具栏(仅非 Windows // 底部字数
if (!isWin) Container(
Container( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6), child: Row(mainAxisAlignment: MainAxisAlignment.end, children: [
decoration: BoxDecoration(border: Border(top: BorderSide(color: colors.outlineVariant, width: 0.5))), Text('${_contentCtrl.text.length}', style: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.3))),
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))),
]),
]),
),
// Windows: 底部字数(简洁)
if (isWin)
Container(
padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 8),
child: Center(child: ConstrainedBox(constraints: const BoxConstraints(maxWidth: 720),
child: Row(mainAxisAlignment: MainAxisAlignment.end, children: [
Text('${_contentCtrl.text.length}', style: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.3))),
]),
)),
),
]); ]);
} }
@@ -400,78 +262,6 @@ class _NoteAddPageState extends State<NoteAddPage> {
); );
} }
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<void> _pickImage() async { Future<void> _pickImage() async {
try { try {
final XFile? image = await _picker.pickImage(source: ImageSource.gallery, maxWidth: 1920, maxHeight: 1920, imageQuality: 85); final XFile? image = await _picker.pickImage(source: ImageSource.gallery, maxWidth: 1920, maxHeight: 1920, imageQuality: 85);
@@ -487,20 +277,6 @@ class _NoteAddPageState extends State<NoteAddPage> {
} }
} }
Future<void> _showTagPanel() async {
final provider = context.read<AppProvider>();
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) { MarkdownStyleSheet _buildMarkdownStyleSheet(ColorScheme colors) {
return MarkdownStyleSheet( return MarkdownStyleSheet(
h1: TextStyle(fontSize: 24, fontWeight: FontWeight.w600, color: colors.onSurface, height: 1.4), h1: TextStyle(fontSize: 24, fontWeight: FontWeight.w600, color: colors.onSurface, height: 1.4),
@@ -538,7 +314,7 @@ class _NoteAddPageState extends State<NoteAddPage> {
Future<void> _save() async { Future<void> _save() async {
final title = _titleCtrl.text.trim(); final title = _titleCtrl.text.trim();
String content; String content;
if (Platform.isWindows && _vditorKey.currentState != null && _vditorKey.currentState!.isReady) { if (_vditorKey.currentState != null && _vditorKey.currentState!.isReady) {
content = (await _vditorKey.currentState!.getValue()).trim(); content = (await _vditorKey.currentState!.getValue()).trim();
} else { } else {
content = _contentCtrl.text.trim(); content = _contentCtrl.text.trim();
@@ -587,9 +363,4 @@ class _NoteAddPageState extends State<NoteAddPage> {
} }
} }
static List<String> _collectUnique(List<List<String>> lists) {
final s = <String>{};
for (final l in lists) { s.addAll(l); }
return s.toList()..sort();
}
} }

View File

@@ -5,14 +5,12 @@ import 'package:flutter_markdown_plus/flutter_markdown_plus.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'package:image_picker/image_picker.dart'; import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as p; import 'package:path/path.dart' as p;
import 'package:uuid/uuid.dart';
import '../../providers/app_provider.dart'; import '../../providers/app_provider.dart';
import '../../widgets/fade_in_local_image.dart'; import '../../widgets/fade_in_local_image.dart';
import '../../models/data_models.dart'; import '../../models/data_models.dart';
import '../../utils/toast_util.dart'; import '../../utils/toast_util.dart';
import '../../utils/image_path_helper.dart'; import '../../utils/image_path_helper.dart';
import '../../utils/responsive.dart'; import '../../utils/responsive.dart';
import '../../widgets/tag_side_panel.dart';
import '../../widgets/vditor_editor.dart'; import '../../widgets/vditor_editor.dart';
import 'note_share_page.dart'; import 'note_share_page.dart';
@@ -79,7 +77,7 @@ class _NoteDetailPageState extends State<NoteDetailPage> {
Future<void> _autoSave() async { Future<void> _autoSave() async {
String content; String content;
if (Platform.isWindows && _vditorKey.currentState != null && _vditorKey.currentState!.isReady) { if (_vditorKey.currentState != null && _vditorKey.currentState!.isReady) {
content = (await _vditorKey.currentState!.getValue()).trim(); content = (await _vditorKey.currentState!.getValue()).trim();
} else { } else {
content = _contentCtrl.text.trim(); content = _contentCtrl.text.trim();
@@ -107,7 +105,7 @@ class _NoteDetailPageState extends State<NoteDetailPage> {
_autoSaveTimer?.cancel(); _autoSaveTimer?.cancel();
final title = _titleCtrl.text.trim(); final title = _titleCtrl.text.trim();
String content; String content;
if (Platform.isWindows && _vditorKey.currentState != null && _vditorKey.currentState!.isReady) { if (_vditorKey.currentState != null && _vditorKey.currentState!.isReady) {
content = (await _vditorKey.currentState!.getValue()).trim(); content = (await _vditorKey.currentState!.getValue()).trim();
} else { } else {
content = _contentCtrl.text.trim(); content = _contentCtrl.text.trim();
@@ -153,13 +151,9 @@ class _NoteDetailPageState extends State<NoteDetailPage> {
) )
: null, : null,
titleSpacing: 0, titleSpacing: 0,
title: Text( title: note.title.isNotEmpty
note.title.isNotEmpty ? Text(note.title, style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: colors.onSurface))
? note.title : null,
: _truncateContent(note.content),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
), ),
body: Stack( body: Stack(
children: [ children: [
@@ -215,16 +209,27 @@ class _NoteDetailPageState extends State<NoteDetailPage> {
), ),
Expanded( Expanded(
child: Markdown( child: ListView(
data: note.content,
styleSheet: _buildMarkdownStyleSheet(colors),
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
// ignore: deprecated_member_use children: [
imageBuilder: (uri, title, alt) => _buildMarkdownImage(uri, note), // Markdown 正文
Markdown(
data: note.content,
styleSheet: _buildMarkdownStyleSheet(colors),
padding: EdgeInsets.zero,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
// ignore: deprecated_member_use
imageBuilder: (uri, title, alt) => _buildMarkdownImage(uri, note),
),
// 附加图片(不在 markdown 中的独立图片)
if (note.images.isNotEmpty) ...[
const SizedBox(height: 16),
_buildInlineImageGrid(note.images),
],
],
), ),
), ),
if (note.images.isNotEmpty) _buildImageRow(note.images),
], ],
), ),
@@ -435,173 +440,55 @@ class _NoteDetailPageState extends State<NoteDetailPage> {
} }
Widget _buildEditArea(ColorScheme colors, Note note) { Widget _buildEditArea(ColorScheme colors, Note note) {
final isWin = Platform.isWindows;
return Column(children: [ return Column(children: [
// 标题输入Windows: 更大更醒目) // 标题输入
Container( Container(
padding: EdgeInsets.symmetric(horizontal: isWin ? 48 : 16, vertical: isWin ? 16 : 8), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
decoration: BoxDecoration(border: Border(bottom: BorderSide(color: colors.outlineVariant, width: 0.5))), decoration: BoxDecoration(border: Border(bottom: BorderSide(color: colors.outlineVariant, width: 0.5))),
child: Center(child: ConstrainedBox(constraints: const BoxConstraints(maxWidth: 720), child: Center(child: ConstrainedBox(constraints: const BoxConstraints(maxWidth: 720),
child: TextField(controller: _titleCtrl, maxLines: 1, child: TextField(controller: _titleCtrl, maxLines: 1,
style: TextStyle(fontSize: isWin ? 22 : 16, fontWeight: FontWeight.w700, color: colors.onSurface, height: 1.4), style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: colors.onSurface, height: 1.4),
decoration: InputDecoration(hintText: '添加标题', decoration: InputDecoration(hintText: '添加标题',
hintStyle: TextStyle(fontSize: isWin ? 22 : 16, fontWeight: FontWeight.w700, color: colors.onSurface.withValues(alpha: 0.2), height: 1.4), hintStyle: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: colors.onSurface.withValues(alpha: 0.2), height: 1.4),
border: InputBorder.none, enabledBorder: InputBorder.none, focusedBorder: InputBorder.none, isDense: true, contentPadding: EdgeInsets.zero), border: InputBorder.none, enabledBorder: InputBorder.none, focusedBorder: InputBorder.none, isDense: true, contentPadding: EdgeInsets.zero),
onChanged: (_) => setState(() {})), onChanged: (_) => setState(() {})),
)), )),
), ),
// Windows: 标签栏(彩色药丸样式) // 内容编辑
if (isWin)
Container(
padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 8),
child: Center(child: ConstrainedBox(constraints: const BoxConstraints(maxWidth: 720),
child: Align(
alignment: Alignment.centerLeft,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(mainAxisSize: MainAxisSize.min, children: [
for (int i = 0; i < _editTags.length; i++)
Padding(
padding: const EdgeInsets.only(right: 6),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: colors.primaryContainer,
borderRadius: BorderRadius.circular(12),
),
child: Row(mainAxisSize: MainAxisSize.min, children: [
Text(_editTags[i], style: TextStyle(fontSize: 12, color: colors.onPrimaryContainer, fontWeight: FontWeight.w500)),
const SizedBox(width: 4),
GestureDetector(
onTap: () => setState(() => _editTags.removeAt(i)),
child: Icon(Icons.close, size: 12, color: colors.onPrimaryContainer.withValues(alpha: 0.6)),
),
]),
),
),
GestureDetector(
onTap: _showEditTagPanel,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 5),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
border: Border.all(color: colors.outline.withValues(alpha: 0.3), width: 1),
),
child: Row(mainAxisSize: MainAxisSize.min, children: [
Icon(Icons.add, size: 14, color: colors.onSurface.withValues(alpha: 0.4)),
const SizedBox(width: 3),
Text('标签', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
]),
),
),
]),
),
),
)),
),
// 内容编辑Windows: 限宽居中)
Expanded( Expanded(
child: isWin child: VditorEditor(
? Center(child: ConstrainedBox(constraints: const BoxConstraints(maxWidth: 720), key: _vditorKey,
child: VditorEditor( initialContent: _contentCtrl.text,
key: _vditorKey, noteId: widget.note.id,
initialContent: _contentCtrl.text, isDark: Theme.of(context).brightness == Brightness.dark,
noteId: widget.note.id, surfaceColor: colors.surface,
isDark: Theme.of(context).brightness == Brightness.dark, onContentChanged: (value) {
surfaceColor: colors.surface, _contentCtrl.text = value;
onContentChanged: (value) { _onContentChanged();
_contentCtrl.text = value; },
_onContentChanged(); ),
},
),
))
: 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, enabledBorder: InputBorder.none, focusedBorder: InputBorder.none,
contentPadding: const EdgeInsets.all(16)),
onChanged: (_) => _onContentChanged()),
), ),
// 图片网格 // 图片网格
if (_editImages.isNotEmpty) _buildEditImageGrid(colors), if (_editImages.isNotEmpty) _buildEditImageGrid(colors),
// 底部标签 + 字数 + 工具栏(仅非 Windows // 底部字数
if (!isWin) Container(
Container( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6), child: Row(mainAxisAlignment: MainAxisAlignment.end, children: [
decoration: BoxDecoration(border: Border(top: BorderSide(color: colors.outlineVariant, width: 0.5))), Text('${_contentCtrl.text.length}', style: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.3))),
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))),
]),
]),
),
// Windows: 底部字数(简洁)
if (isWin)
Container(
padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 8),
child: Center(child: ConstrainedBox(constraints: const BoxConstraints(maxWidth: 720),
child: Row(mainAxisAlignment: MainAxisAlignment.end, children: [
Text('${_contentCtrl.text.length}', style: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.3))),
]),
)),
),
]); ]);
} }
Widget _buildPreviewArea(ColorScheme colors, Note note) { Widget _buildPreviewArea(ColorScheme colors, Note note) {
final isWin = Platform.isWindows;
return ListView( return ListView(
padding: EdgeInsets.symmetric(vertical: isWin ? 32 : 24), padding: const EdgeInsets.symmetric(vertical: 24),
children: [ children: [
Center(child: ConstrainedBox(constraints: const BoxConstraints(maxWidth: 720), Center(child: ConstrainedBox(constraints: const BoxConstraints(maxWidth: 720),
child: Padding(padding: EdgeInsets.symmetric(horizontal: isWin ? 48 : 24), child: Padding(padding: const EdgeInsets.symmetric(horizontal: 24),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
if (_titleCtrl.text.isNotEmpty) ...[ if (_titleCtrl.text.isNotEmpty) ...[
Text(_titleCtrl.text, style: TextStyle(fontSize: isWin ? 28 : 24, fontWeight: FontWeight.w700, color: colors.onSurface, height: 1.3)), Text(_titleCtrl.text, style: TextStyle(fontSize: 24, fontWeight: FontWeight.w700, color: colors.onSurface, height: 1.3)),
const SizedBox(height: 12), const SizedBox(height: 12),
], ],
// 标签 // 标签
@@ -640,64 +527,6 @@ class _NoteDetailPageState extends State<NoteDetailPage> {
); );
} }
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<void> _pickEditImage() async { Future<void> _pickEditImage() async {
try { try {
final XFile? image = await _picker.pickImage(source: ImageSource.gallery, maxWidth: 1920, maxHeight: 1920, imageQuality: 85); final XFile? image = await _picker.pickImage(source: ImageSource.gallery, maxWidth: 1920, maxHeight: 1920, imageQuality: 85);
@@ -714,17 +543,6 @@ class _NoteDetailPageState extends State<NoteDetailPage> {
} }
} }
Future<void> _showEditTagPanel() async {
final provider = context.read<AppProvider>();
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) { Widget _buildEditImageGrid(ColorScheme colors) {
return Container( return Container(
padding: const EdgeInsets.fromLTRB(16, 6, 16, 0), padding: const EdgeInsets.fromLTRB(16, 6, 16, 0),
@@ -783,6 +601,37 @@ class _NoteDetailPageState extends State<NoteDetailPage> {
); );
} }
/// 内嵌图片网格(移动端正文后展示)
Widget _buildInlineImageGrid(List<String> images) {
final colors = Theme.of(context).colorScheme;
return Wrap(
spacing: 8,
runSpacing: 8,
children: images.map((path) {
return GestureDetector(
onTap: () => _showImagePreview(images, images.indexOf(path)),
child: Container(
width: (MediaQuery.of(context).size.width - 48) / 3,
height: (MediaQuery.of(context).size.width - 48) / 3,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
border: Border.all(color: colors.outlineVariant, width: 0.5),
),
clipBehavior: Clip.antiAlias,
child: FadeInLocalImage(
path: path,
fit: BoxFit.cover,
errorWidget: Container(
color: colors.surfaceContainerHighest,
child: Icon(Icons.broken_image_outlined, size: 20, color: colors.onSurface.withValues(alpha: 0.25)),
),
),
),
);
}).toList(),
);
}
Widget _buildImageRow(List<String> images) { Widget _buildImageRow(List<String> images) {
final colors = Theme.of(context).colorScheme; final colors = Theme.of(context).colorScheme;
return Container( return Container(

View File

@@ -4,7 +4,6 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'package:image_picker/image_picker.dart'; import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as p; import 'package:path/path.dart' as p;
import 'package:flutter_markdown_plus/flutter_markdown_plus.dart';
import '../../providers/app_provider.dart'; import '../../providers/app_provider.dart';
import 'package:uuid/uuid.dart'; import 'package:uuid/uuid.dart';
import '../../models/data_models.dart'; import '../../models/data_models.dart';
@@ -12,6 +11,7 @@ import '../../utils/toast_util.dart';
import '../../utils/image_path_helper.dart'; import '../../utils/image_path_helper.dart';
import '../../widgets/fade_in_local_image.dart'; import '../../widgets/fade_in_local_image.dart';
import '../../widgets/tag_side_panel.dart'; import '../../widgets/tag_side_panel.dart';
import '../../widgets/vditor_editor.dart';
/// 添加/编辑笔记页面 - 极简书写界面 /// 添加/编辑笔记页面 - 极简书写界面
class NoteFormPage extends StatefulWidget { class NoteFormPage extends StatefulWidget {
@@ -32,11 +32,13 @@ class _NoteFormPageState extends State<NoteFormPage> {
bool _isEditing = false; bool _isEditing = false;
final ImagePicker _picker = ImagePicker(); final ImagePicker _picker = ImagePicker();
String? _tempNoteId; // 新建模式时使用的临时笔记ID String? _tempNoteId; // 新建模式时使用的临时笔记ID
String _editorMode = 'edit'; // 'edit' | 'preview'
Timer? _autoSaveTimer; Timer? _autoSaveTimer;
Timer? _saveStatusTimer; Timer? _saveStatusTimer;
String _saveStatus = ''; // '', 'saved' String _saveStatus = ''; // '', 'saved'
Note? _savedNote; // 新建模式首次自动保存后的笔记引用 Note? _savedNote; // 新建模式首次自动保存后的笔记引用
final _vditorKey = GlobalKey<VditorEditorState>();
final _scrollController = ScrollController();
bool _editorTouched = false;
static const _weekdays = ['', '', '', '', '', '', '']; static const _weekdays = ['', '', '', '', '', '', ''];
@@ -51,6 +53,9 @@ class _NoteFormPageState extends State<NoteFormPage> {
_tags = note != null ? List.from(note.tags) : []; _tags = note != null ? List.from(note.tags) : [];
_images = note != null ? List.from(note.images) : []; _images = note != null ? List.from(note.images) : [];
_isEditing = note != null; _isEditing = note != null;
if (!_isEditing) {
_tempNoteId = const Uuid().v4();
}
_titleController.addListener(_onTextChanged); _titleController.addListener(_onTextChanged);
_contentController.addListener(_onTextChanged); _contentController.addListener(_onTextChanged);
} }
@@ -72,7 +77,12 @@ class _NoteFormPageState extends State<NoteFormPage> {
} }
Future<void> _autoSave() async { Future<void> _autoSave() async {
final content = _contentController.text.trim(); String content;
if (_vditorKey.currentState != null && _vditorKey.currentState!.isReady) {
content = (await _vditorKey.currentState!.getValue()).trim();
} else {
content = _contentController.text.trim();
}
final title = _titleController.text.trim(); final title = _titleController.text.trim();
if (title.isEmpty && content.isEmpty) return; if (title.isEmpty && content.isEmpty) return;
@@ -157,13 +167,22 @@ class _NoteFormPageState extends State<NoteFormPage> {
// 可滚动内容 // 可滚动内容
Expanded( Expanded(
child: CustomScrollView( child: CustomScrollView(
controller: _scrollController,
physics: _editorTouched ? const NeverScrollableScrollPhysics() : null,
slivers: [ slivers: [
// 标题行(点击编辑) // 标题行(点击编辑)
SliverToBoxAdapter(child: _buildTitleInput(colors)), SliverToBoxAdapter(child: _buildTitleInput(colors)),
// 编辑区域 — 固定高度 // 编辑区域 — 高度随内容撑开,触摸时禁用外层滚动
SliverToBoxAdapter( SliverToBoxAdapter(
child: SizedBox(height: contentH, child: _buildContentArea()), child: ConstrainedBox(
constraints: BoxConstraints(minHeight: contentH),
child: GestureDetector(
onTapDown: (_) => setState(() => _editorTouched = true),
onTapUp: (_) => setState(() => _editorTouched = false),
onTapCancel: () => setState(() => _editorTouched = false),
child: _buildEditor(),
)),
), ),
// 图片 + 标签 + 字数 — 随内容撑开 // 图片 + 标签 + 字数 — 随内容撑开
@@ -256,31 +275,7 @@ class _NoteFormPageState extends State<NoteFormPage> {
); );
} }
/// 在光标处插入 Markdown 语法,光标自动放到正确位置 /// 底部浮动工具栏
void _insertMarkdown(String left, String right) {
final text = _contentController.text;
final selection = _contentController.selection;
final start = selection.start;
final end = selection.end;
String selectedText = '';
if (end > start) {
selectedText = text.substring(start, end);
}
final insertion = '$left$selectedText$right';
// 原子更新:一次性设置 text 和 selection避免分步操作导致光标跳动
_contentController.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,
),
);
}
/// 现代极简底部工具栏
Widget _buildFloatingToolbar() { Widget _buildFloatingToolbar() {
final colors = Theme.of(context).colorScheme; final colors = Theme.of(context).colorScheme;
return Container( return Container(
@@ -313,12 +308,15 @@ class _NoteFormPageState extends State<NoteFormPage> {
_toolGap(), _toolGap(),
_toolBtn(Icons.format_list_bulleted, '无序列表', () => _insertMarkdown('- ', '')), _toolBtn(Icons.format_list_bulleted, '无序列表', () => _insertMarkdown('- ', '')),
_toolBtn(Icons.format_list_numbered, '有序列表', () => _insertMarkdown('1. ', '')), _toolBtn(Icons.format_list_numbered, '有序列表', () => _insertMarkdown('1. ', '')),
_toolBtn(Icons.check_box_outlined, '待办', () => _insertMarkdown('- [ ] ', '')),
_toolBtn(Icons.format_quote, '引用', () => _insertMarkdown('> ', '')), _toolBtn(Icons.format_quote, '引用', () => _insertMarkdown('> ', '')),
_toolBtn(Icons.insert_link, '链接', () => _insertMarkdown('[', '](url)')), _toolBtn(Icons.insert_link, '链接', () => _insertMarkdown('[', '](url)')),
_toolGap(), _toolGap(),
_toolBtn(Icons.code, '行内代码', () => _insertMarkdown('`', '`')), _toolBtn(Icons.code, '行内代码', () => _insertMarkdown('`', '`')),
_toolBtn(Icons.data_object, '代码块', () => _insertMarkdown('```\n', '\n```')), _toolBtn(Icons.data_object, '代码块', () => _insertMarkdown('```\n', '\n```')),
_toolBtn(Icons.horizontal_rule, '分割线', () => _insertMarkdown('---\n', '')), _toolBtn(Icons.horizontal_rule, '分割线', () => _insertMarkdown('---\n', '')),
_toolGap(),
_toolBtn(Icons.add_photo_alternate_outlined, '图片', _pickImage),
], ],
), ),
), ),
@@ -357,194 +355,38 @@ class _NoteFormPageState extends State<NoteFormPage> {
); );
} }
Widget _modeSwitch(IconData icon, String mode) { /// 在光标处插入 Markdown 语法(通过 VditorEditor
final colors = Theme.of(context).colorScheme; void _insertMarkdown(String left, String right) {
final active = _editorMode == mode; final vditor = _vditorKey.currentState;
return Material( if (vditor != null && vditor.isReady) {
color: Colors.transparent, vditor.insertValue(left + right);
child: InkWell( }
onTap: () => setState(() => _editorMode = mode),
borderRadius: BorderRadius.circular(8),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 6),
decoration: BoxDecoration(
color: active ? colors.primary : Colors.transparent,
borderRadius: BorderRadius.circular(8),
),
child: Icon(
icon,
size: 18,
color: active ? colors.onPrimary : colors.onSurface.withValues(alpha: 0.35),
),
),
),
);
} }
/// 插入标题(在当前行首插入 # ,如果已有则升级 ## → ### → #### /// 插入标题(通过 VditorEditor
void _insertHeading() { void _insertHeading() {
final text = _contentController.text; final vditor = _vditorKey.currentState;
final selection = _contentController.selection; if (vditor != null && vditor.isReady) {
final start = selection.start; vditor.insertValue('# ');
// 找到当前行起始位置
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++;
String newPrefix;
int cursorOffset;
if (hashCount > 0 && hashCount < 6) {
// 升级标题级别
hashCount++;
newPrefix = '${'#' * hashCount} ';
cursorOffset = newPrefix.length;
// 替换旧前缀
_contentController.value = TextEditingValue(
text: text.substring(0, lineStart) + newPrefix + text.substring(pos),
selection: TextSelection.collapsed(offset: lineStart + cursorOffset),
);
} else if (hashCount >= 6) {
// 已经是 H6重置为普通文本
_contentController.value = TextEditingValue(
text: text.substring(0, lineStart) + text.substring(pos),
selection: TextSelection.collapsed(offset: lineStart),
);
} else {
// 没有 # 前缀,添加 H1
newPrefix = '# ';
_contentController.value = TextEditingValue(
text: text.substring(0, lineStart) + newPrefix + text.substring(lineStart),
selection: TextSelection.collapsed(offset: lineStart + 2),
);
} }
} }
/// 根据 _editorMode 构建内容区域 /// 编辑器 — 使用 VditorEditor 替代原来的 TextField
Widget _buildContentArea() {
switch (_editorMode) {
case 'preview':
return _buildPreview();
case 'edit':
default:
return _buildEditor();
}
}
/// 编辑器
Widget _buildEditor() { Widget _buildEditor() {
final colors = Theme.of(context).colorScheme; final colors = Theme.of(context).colorScheme;
return TextField( return VditorEditor(
controller: _contentController, key: _vditorKey,
maxLines: null, initialContent: _contentController.text,
expands: true, noteId: _isEditing && widget.note != null ? widget.note!.id : (_tempNoteId ?? ''),
textAlignVertical: TextAlignVertical.top, isDark: Theme.of(context).brightness == Brightness.dark,
strutStyle: const StrutStyle( surfaceColor: colors.surface,
forceStrutHeight: true, onContentChanged: (value) {
height: 1.6, _contentController.text = value;
fontSize: 14, _onTextChanged();
), },
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,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
contentPadding: const EdgeInsets.all(16),
),
); );
} }
/// 实时 Markdown 预览(点击回到编辑)
Widget _buildPreview() {
final colors = Theme.of(context).colorScheme;
final text = _contentController.text;
return GestureDetector(
onTap: () => setState(() => _editorMode = 'edit'),
behavior: HitTestBehavior.opaque,
child: Container(
color: colors.surfaceContainerHigh,
child: text.isEmpty
? Center(
child: Text(
'预览区域',
style: TextStyle(
fontSize: 14,
color: colors.onSurface.withValues(alpha: 0.25),
),
),
)
: Markdown(
data: text,
selectable: true,
padding: const EdgeInsets.all(16),
styleSheet: MarkdownStyleSheet(
h1: TextStyle(
fontSize: 22,
fontWeight: FontWeight.w600,
color: colors.onSurface,
height: 1.4,
),
h2: TextStyle(
fontSize: 19,
fontWeight: FontWeight.w600,
color: colors.onSurface,
height: 1.4,
),
h3: TextStyle(
fontSize: 17,
fontWeight: FontWeight.w600,
color: colors.onSurface,
height: 1.4,
),
p: TextStyle(
fontSize: 15,
color: colors.onSurface.withValues(alpha: 0.75),
height: 1.7,
),
code: TextStyle(
fontSize: 14,
color: colors.onSurface,
backgroundColor: colors.outlineVariant,
),
codeblockDecoration: BoxDecoration(
color: colors.outlineVariant,
borderRadius: BorderRadius.circular(6),
),
blockquote: TextStyle(
fontSize: 15,
color: colors.onSurface.withValues(alpha: 0.6),
),
blockquoteDecoration: BoxDecoration(
border: Border(
left: BorderSide(color: colors.onSurface.withValues(alpha: 0.25), width: 3),
),
),
),
),
));
}
/// 标签 chips 行(右侧展示) /// 标签 chips 行(右侧展示)
Widget _buildTagChips() { Widget _buildTagChips() {
return Wrap( return Wrap(
@@ -631,10 +473,10 @@ class _NoteFormPageState extends State<NoteFormPage> {
child: TextField( child: TextField(
controller: _titleController, controller: _titleController,
maxLines: 1, maxLines: 1,
style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: colors.onSurface), style: TextStyle(fontSize: 20, fontWeight: FontWeight.w700, color: colors.onSurface),
decoration: InputDecoration( decoration: InputDecoration(
hintText: '添加标题', hintText: '添加标题',
hintStyle: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: colors.onSurface.withValues(alpha: 0.2)), hintStyle: TextStyle(fontSize: 20, fontWeight: FontWeight.w700, color: colors.onSurface.withValues(alpha: 0.2)),
border: InputBorder.none, border: InputBorder.none,
enabledBorder: InputBorder.none, enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none, focusedBorder: InputBorder.none,
@@ -665,7 +507,12 @@ class _NoteFormPageState extends State<NoteFormPage> {
Future<void> _saveNote() async { Future<void> _saveNote() async {
_autoSaveTimer?.cancel(); _autoSaveTimer?.cancel();
final content = _contentController.text.trim(); String content;
if (_vditorKey.currentState != null && _vditorKey.currentState!.isReady) {
content = (await _vditorKey.currentState!.getValue()).trim();
} else {
content = _contentController.text.trim();
}
final title = _titleController.text.trim(); final title = _titleController.text.trim();
if (title.isEmpty && content.isEmpty) { if (title.isEmpty && content.isEmpty) {
@@ -679,7 +526,7 @@ class _NoteFormPageState extends State<NoteFormPage> {
if (_isEditing && widget.note != null) { if (_isEditing && widget.note != null) {
// 更新现有笔记(编辑已有笔记) // 更新现有笔记(编辑已有笔记)
final updatedNote = widget.note!.copyWith( final updatedNote = widget.note!.copyWith(
title: _titleController.text.trim(), title: title,
content: content, content: content,
tags: _tags, tags: _tags,
images: _images, images: _images,
@@ -689,7 +536,7 @@ class _NoteFormPageState extends State<NoteFormPage> {
} else if (_savedNote != null) { } else if (_savedNote != null) {
// 自动保存过的新笔记,更新它 // 自动保存过的新笔记,更新它
final updatedNote = _savedNote!.copyWith( final updatedNote = _savedNote!.copyWith(
title: _titleController.text.trim(), title: title,
content: content, content: content,
tags: _tags, tags: _tags,
images: _images, images: _images,
@@ -709,8 +556,6 @@ class _NoteFormPageState extends State<NoteFormPage> {
finalImages = await _moveImagesToNewId(oldNoteId, newNoteId); finalImages = await _moveImagesToNewId(oldNoteId, newNoteId);
} }
final title = _titleController.text.trim();
final newNote = Note( final newNote = Note(
id: noteId, id: noteId,
title: title, title: title,

View File

@@ -335,110 +335,105 @@ class _BookDetailPageState extends State<BookDetailPage> {
final pages = m['pagination']; final pages = m['pagination'];
final coverUrl = cover.toString().isNotEmpty ? _resolveCoverUrl(cover.toString()) : ''; final coverUrl = cover.toString().isNotEmpty ? _resolveCoverUrl(cover.toString()) : '';
return NestedScrollView( return Scaffold(
headerSliverBuilder: (context, _) => [ backgroundColor: colors.surface,
SliverToBoxAdapter( body: Column(children: [
child: Container( // 头部:返回按钮 + 封面信息
color: colors.surface, SafeArea(
child: SafeArea( bottom: false,
bottom: false, child: Column(children: [
child: Column(children: [ Padding(
Padding( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), child: Row(children: [
child: Row(children: [ GestureDetector(
GestureDetector( onTap: () => Navigator.pop(context),
onTap: () => Navigator.pop(context), child: Container(
child: Container( width: 36,
width: 36, height: 36,
height: 36, decoration: BoxDecoration(
decoration: BoxDecoration( color: colors.surfaceContainerHigh,
color: colors.surfaceContainerHigh, shape: BoxShape.circle),
shape: BoxShape.circle), child: Icon(Icons.arrow_back, size: 20, color: colors.onSurface)),
child: Icon(Icons.arrow_back, size: 20, color: colors.onSurface)), ),
]),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 16),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(10),
child: SizedBox(
width: 110,
height: 160,
child: coverUrl.isNotEmpty
? Image.network(coverUrl,
fit: BoxFit.cover,
errorBuilder: (_, __, ___) => _coverPlaceholder(colors))
: _coverPlaceholder(colors),
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title, style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: colors.onSurface)),
if (author.toString().isNotEmpty) ...[
const SizedBox(height: 8),
Text(author, style: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.6))),
],
if (press.toString().isNotEmpty) ...[
const SizedBox(height: 6),
Text(press, style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.45))),
],
if (year.toString().isNotEmpty) ...[
const SizedBox(height: 6),
Text('出版年份:$year', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
],
if (isbn.toString().isNotEmpty) ...[
const SizedBox(height: 4),
Text('ISBN$isbn', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
],
if (pages != null && pages != 0) ...[
const SizedBox(height: 4),
Text('页数:$pages', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
],
if (_localBook != null) ...[
const SizedBox(height: 10),
_buildLocalStatus(colors),
],
]),
), ),
]), ]),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 16),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(10),
child: SizedBox(
width: 110,
height: 160,
child: coverUrl.isNotEmpty
? Image.network(coverUrl,
fit: BoxFit.cover,
errorBuilder: (_, __, ___) => _coverPlaceholder(colors))
: _coverPlaceholder(colors),
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title, style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: colors.onSurface)),
if (author.toString().isNotEmpty) ...[
const SizedBox(height: 8),
Text(author, style: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.6))),
],
if (press.toString().isNotEmpty) ...[
const SizedBox(height: 6),
Text(press, style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.45))),
],
if (year.toString().isNotEmpty) ...[
const SizedBox(height: 6),
Text('出版年份:$year', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
],
if (isbn.toString().isNotEmpty) ...[
const SizedBox(height: 4),
Text('ISBN$isbn', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
],
if (pages != null && pages != 0) ...[
const SizedBox(height: 4),
Text('页数:$pages', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
],
if (_localBook != null) ...[
const SizedBox(height: 10),
_buildLocalStatus(colors),
],
]),
),
]),
),
]),
), ),
), ]),
), ),
// Tab 栏:吸顶 // Tab 栏
SliverPersistentHeader( Container(
pinned: true, decoration: BoxDecoration(
delegate: _StickyTabBarDelegate( color: colors.surface,
child: Container( border: Border(
decoration: BoxDecoration( bottom: BorderSide(color: colors.outlineVariant, width: 0.5))),
color: colors.surface, child: Row(children: [
border: Border( _buildTabButton('基础信息', 0),
bottom: BorderSide(color: colors.outlineVariant, width: 0.5))), _buildTabButton('国图信息', 1),
child: Row(children: [ _buildTabButton('网购地址', 2),
_buildTabButton('基础信息', 0), _buildTabButton('书籍目录', 3),
_buildTabButton('国图信息', 1), ]),
_buildTabButton('网购地址', 2),
_buildTabButton('书籍目录', 3),
]),
),
),
), ),
], // Tab 内容
body: _currentTab == 0 Expanded(
? _buildBasicInfo(colors) child: _currentTab == 0
: _currentTab == 1 ? _buildBasicInfo(colors)
? _buildOpacTab(colors) : _currentTab == 1
: _currentTab == 2 ? _buildOpacTab(colors)
? _buildOnlineTab(colors) : _currentTab == 2
: _buildCatalogTab(colors), ? _buildOnlineTab(colors)
: _buildCatalogTab(colors),
),
]),
); );
} }
@@ -758,20 +753,3 @@ class _BookDetailPageState extends State<BookDetailPage> {
]); ]);
} }
} }
class _StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
final Widget child;
_StickyTabBarDelegate({required this.child});
@override
Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) => child;
@override
double get minExtent => 44;
@override
double get maxExtent => 44;
@override
bool shouldRebuild(_StickyTabBarDelegate oldDelegate) => child != oldDelegate.child;
}

View File

@@ -329,137 +329,130 @@ class _MovieDetailPageState extends State<MovieDetailPage> {
final typeParts = final typeParts =
[typeName, classStr].where((s) => s.toString().isNotEmpty).join(' / '); [typeName, classStr].where((s) => s.toString().isNotEmpty).join(' / ');
return NestedScrollView( return Scaffold(
headerSliverBuilder: (context, _) => [ backgroundColor: colors.surface,
SliverToBoxAdapter( body: Column(children: [
child: Container( // 头部:返回按钮 + 海报信息
color: colors.surface, SafeArea(
child: SafeArea( bottom: false,
bottom: false, child: Column(children: [
child: Column(children: [ Padding(
// AppBar padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
Padding( child: Row(children: [
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), GestureDetector(
child: Row(children: [ onTap: () => Navigator.pop(context),
GestureDetector( child: Container(
onTap: () => Navigator.pop(context), width: 36,
child: Container( height: 36,
width: 36, decoration: BoxDecoration(
height: 36, color: colors.surfaceContainerHigh,
decoration: BoxDecoration( shape: BoxShape.circle),
color: colors.surfaceContainerHigh, child: Icon(Icons.arrow_back,
shape: BoxShape.circle), size: 20, color: colors.onSurface)),
child: Icon(Icons.arrow_back, ),
size: 20, color: colors.onSurface)), const Spacer(),
GestureDetector(
onTap: () => setState(() => _detailStyle = _detailStyle == 0 ? 1 : 0),
child: Container(
width: 36,
height: 36,
decoration: BoxDecoration(
color: colors.surfaceContainerHigh,
shape: BoxShape.circle),
child: Icon(
_detailStyle == 0
? Icons.crop_landscape_rounded
: Icons.grid_view_rounded,
size: 18,
color: colors.onSurface)),
),
]),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 16),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(10),
child: SizedBox(
width: 120,
height: 170,
child: pic.toString().isNotEmpty
? Image.network(pic,
fit: BoxFit.cover,
errorBuilder: (_, __, ___) =>
_posterPlaceholder(colors))
: _posterPlaceholder(colors),
),
), ),
const Spacer(), const SizedBox(width: 16),
GestureDetector( Expanded(
onTap: () => setState(() => _detailStyle = _detailStyle == 0 ? 1 : 0), child: Column(
child: Container( crossAxisAlignment: CrossAxisAlignment.start,
width: 36, children: [
height: 36, Text(name,
decoration: BoxDecoration( style: TextStyle(
color: colors.surfaceContainerHigh, fontSize: 18,
shape: BoxShape.circle), fontWeight: FontWeight.w700,
child: Icon( color: colors.onSurface)),
_detailStyle == 0 const SizedBox(height: 8),
? Icons.crop_landscape_rounded if (score.toString().isNotEmpty && score != '0.0') ...[
: Icons.grid_view_rounded, Row(children: [
size: 18, Icon(Icons.star_rounded, size: 16, color: const Color(0xFFF59E0B)),
color: colors.onSurface)), const SizedBox(width: 3),
Text('$score', style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: colors.onSurface)),
Text(' /10', style: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.3))),
]),
const SizedBox(height: 2),
Text('评分来源于网络资源收集,并非官方评分', style: TextStyle(fontSize: 10, color: colors.onSurface.withValues(alpha: 0.25))),
const SizedBox(height: 8),
],
_endTag(isEnd),
if (metaParts.isNotEmpty) ...[
const SizedBox(height: 8),
Text(metaParts,
style: TextStyle(
fontSize: 12,
color: colors.onSurface
.withValues(alpha: 0.5))),
],
if (typeParts.isNotEmpty) ...[
const SizedBox(height: 3),
Text(typeParts,
style: TextStyle(
fontSize: 11,
color: colors.onSurface
.withValues(alpha: 0.4)),
maxLines: 1,
overflow: TextOverflow.ellipsis),
],
if (_localMovie != null) ...[
const SizedBox(height: 10),
_buildLocalStatus(colors),
],
]),
), ),
]), ]),
),
// 海报 + 信息
Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 16),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(10),
child: SizedBox(
width: 120,
height: 170,
child: pic.toString().isNotEmpty
? Image.network(pic,
fit: BoxFit.cover,
errorBuilder: (_, __, ___) =>
_posterPlaceholder(colors))
: _posterPlaceholder(colors),
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(name,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w700,
color: colors.onSurface)),
const SizedBox(height: 8),
if (score.toString().isNotEmpty && score != '0.0') ...[
Row(children: [
Icon(Icons.star_rounded, size: 16, color: const Color(0xFFF59E0B)),
const SizedBox(width: 3),
Text('$score', style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: colors.onSurface)),
Text(' /10', style: TextStyle(fontSize: 11, color: colors.onSurface.withValues(alpha: 0.3))),
]),
const SizedBox(height: 2),
Text('评分来源于网络资源收集,并非官方评分', style: TextStyle(fontSize: 10, color: colors.onSurface.withValues(alpha: 0.25))),
const SizedBox(height: 8),
],
_endTag(isEnd),
if (metaParts.isNotEmpty) ...[
const SizedBox(height: 8),
Text(metaParts,
style: TextStyle(
fontSize: 12,
color: colors.onSurface
.withValues(alpha: 0.5))),
],
if (typeParts.isNotEmpty) ...[
const SizedBox(height: 3),
Text(typeParts,
style: TextStyle(
fontSize: 11,
color: colors.onSurface
.withValues(alpha: 0.4)),
maxLines: 1,
overflow: TextOverflow.ellipsis),
],
if (_localMovie != null) ...[
const SizedBox(height: 10),
_buildLocalStatus(colors),
],
]),
),
]),
),
]),
), ),
), ]),
), ),
// Tab 栏:吸顶 // Tab 栏
SliverPersistentHeader( Container(
pinned: true, decoration: BoxDecoration(
delegate: _StickyTabBarDelegate( color: colors.surface,
child: Container( border: Border(
decoration: BoxDecoration( bottom: BorderSide(color: colors.outlineVariant, width: 0.5))),
color: colors.surface, child: Row(children: [
border: Border( _buildTabButton('概要', 0),
bottom: BorderSide(color: colors.outlineVariant, width: 0.5))), _buildTabButton('演职人员', 1),
child: Row(children: [ ]),
_buildTabButton('概要', 0),
_buildTabButton('演职人员', 1),
]),
),
),
), ),
], // Tab 内容
body: _currentTab == 0 ? _buildOverview(colors) : _buildStaffTab(colors), Expanded(
child: _currentTab == 0 ? _buildOverview(colors) : _buildStaffTab(colors),
),
]),
); );
} }
@@ -478,114 +471,113 @@ class _MovieDetailPageState extends State<MovieDetailPage> {
final metaParts = [year, area].where((s) => s.toString().isNotEmpty).join(' · '); final metaParts = [year, area].where((s) => s.toString().isNotEmpty).join(' · ');
final typeParts = [typeName, classStr].where((s) => s.toString().isNotEmpty).join(' / '); final typeParts = [typeName, classStr].where((s) => s.toString().isNotEmpty).join(' / ');
return NestedScrollView( return Scaffold(
headerSliverBuilder: (context, _) => [ backgroundColor: colors.surface,
SliverToBoxAdapter( body: Column(children: [
child: Stack(children: [ // 沉浸式头部
SizedBox( Stack(children: [
width: double.infinity, SizedBox(
height: 320, width: double.infinity,
child: pic.toString().isNotEmpty height: 320,
? Image.network(pic, fit: BoxFit.cover, child: pic.toString().isNotEmpty
errorBuilder: (_, __, ___) => Container(color: colors.surfaceContainerHighest)) ? Image.network(pic, fit: BoxFit.cover,
: Container(color: colors.surfaceContainerHighest, errorBuilder: (_, __, ___) => Container(color: colors.surfaceContainerHighest))
child: Icon(Icons.movie_outlined, size: 64, color: colors.onSurface.withValues(alpha: 0.1))), : Container(color: colors.surfaceContainerHighest,
), child: Icon(Icons.movie_outlined, size: 64, color: colors.onSurface.withValues(alpha: 0.1))),
Positioned.fill( ),
child: DecoratedBox( Positioned.fill(
decoration: BoxDecoration( child: DecoratedBox(
gradient: LinearGradient( decoration: BoxDecoration(
begin: Alignment.topCenter, gradient: LinearGradient(
end: Alignment.bottomCenter, begin: Alignment.topCenter,
colors: [Colors.transparent, Colors.black.withValues(alpha: 0.8)], end: Alignment.bottomCenter,
stops: const [0.35, 1.0], colors: [Colors.transparent, Colors.black.withValues(alpha: 0.8)],
), stops: const [0.35, 1.0],
), ),
), ),
), ),
SafeArea( ),
bottom: false, SafeArea(
child: Padding( bottom: false,
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), child: Padding(
child: Row(children: [ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
GestureDetector(
onTap: () => Navigator.pop(context),
child: Container(
width: 36, height: 36,
decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.3), shape: BoxShape.circle),
child: const Icon(Icons.arrow_back, size: 20, color: Colors.white)),
),
const Spacer(),
GestureDetector(
onTap: () => setState(() => _detailStyle = 0),
child: Container(
width: 36, height: 36,
decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.3), shape: BoxShape.circle),
child: const Icon(Icons.grid_view_rounded, size: 18, color: Colors.white)),
),
]),
),
),
Positioned(
left: 16, right: 16, bottom: 18,
child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [
Text(name, maxLines: 2, overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 22, fontWeight: FontWeight.w700, color: Colors.white)),
const SizedBox(height: 8),
Row(children: [
if (score.toString().isNotEmpty && score != '0.0') ...[
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.3),
borderRadius: BorderRadius.circular(6),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.star_rounded, size: 18, color: Colors.amber.shade400),
const SizedBox(width: 3),
Text('$score', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: Colors.white)),
],
),
),
const SizedBox(width: 10),
],
_endTag(isEnd),
if (metaParts.isNotEmpty) ...[
const SizedBox(width: 8),
Text(metaParts, style: TextStyle(fontSize: 12, color: Colors.white.withValues(alpha: 0.7))),
],
]),
if (typeParts.isNotEmpty) ...[
const SizedBox(height: 4),
Text(typeParts, maxLines: 1, overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: Colors.white.withValues(alpha: 0.5))),
],
if (_localMovie != null) ...[
const SizedBox(height: 8),
_buildLocalStatus(colors),
],
]),
),
]),
),
SliverPersistentHeader(
pinned: true,
delegate: _StickyTabBarDelegate(
child: Container(
decoration: BoxDecoration(
color: colors.surface,
border: Border(bottom: BorderSide(color: colors.outlineVariant, width: 0.5))),
child: Row(children: [ child: Row(children: [
_buildTabButton('概要', 0), GestureDetector(
_buildTabButton('演职人员', 1), onTap: () => Navigator.pop(context),
child: Container(
width: 36, height: 36,
decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.3), shape: BoxShape.circle),
child: const Icon(Icons.arrow_back, size: 20, color: Colors.white)),
),
const Spacer(),
GestureDetector(
onTap: () => setState(() => _detailStyle = 0),
child: Container(
width: 36, height: 36,
decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.3), shape: BoxShape.circle),
child: const Icon(Icons.grid_view_rounded, size: 18, color: Colors.white)),
),
]), ]),
), ),
), ),
Positioned(
left: 16, right: 16, bottom: 18,
child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [
Text(name, maxLines: 2, overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 22, fontWeight: FontWeight.w700, color: Colors.white)),
const SizedBox(height: 8),
Row(children: [
if (score.toString().isNotEmpty && score != '0.0') ...[
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.3),
borderRadius: BorderRadius.circular(6),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.star_rounded, size: 18, color: Colors.amber.shade400),
const SizedBox(width: 3),
Text('$score', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: Colors.white)),
],
),
),
const SizedBox(width: 10),
],
_endTag(isEnd),
if (metaParts.isNotEmpty) ...[
const SizedBox(width: 8),
Text(metaParts, style: TextStyle(fontSize: 12, color: Colors.white.withValues(alpha: 0.7))),
],
]),
if (typeParts.isNotEmpty) ...[
const SizedBox(height: 4),
Text(typeParts, maxLines: 1, overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: Colors.white.withValues(alpha: 0.5))),
],
if (_localMovie != null) ...[
const SizedBox(height: 8),
_buildLocalStatus(colors),
],
]),
),
]),
// Tab 栏
Container(
decoration: BoxDecoration(
color: colors.surface,
border: Border(bottom: BorderSide(color: colors.outlineVariant, width: 0.5))),
child: Row(children: [
_buildTabButton('概要', 0),
_buildTabButton('演职人员', 1),
]),
), ),
], // Tab 内容
body: _currentTab == 0 ? _buildOverview(colors) : _buildStaffTab(colors), Expanded(
child: _currentTab == 0 ? _buildOverview(colors) : _buildStaffTab(colors),
),
]),
); );
} }
@@ -907,20 +899,3 @@ class _MovieDetailPageState extends State<MovieDetailPage> {
); );
} }
} }
class _StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
final Widget child;
_StickyTabBarDelegate({required this.child});
@override
Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) => child;
@override
double get minExtent => 44;
@override
double get maxExtent => 44;
@override
bool shouldRebuild(_StickyTabBarDelegate oldDelegate) => child != oldDelegate.child;
}

View File

@@ -235,13 +235,13 @@ class _SearchPageState extends State<SearchPage> {
return Padding( return Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
child: Row(children: [ child: Row(children: [
_filterChip('影视', Icons.movie_outlined, _showMovies, movieCount, () { setState(() { _showMovies = !_showMovies; _performSearch(); }); }), Expanded(child: _filterChip('影视', Icons.movie_outlined, _showMovies, movieCount, () { setState(() { _showMovies = !_showMovies; _performSearch(); }); })),
const SizedBox(width: 8), const SizedBox(width: 8),
_filterChip('书籍', Icons.menu_book_outlined, _showBooks, bookCount, () { setState(() { _showBooks = !_showBooks; _performSearch(); }); }), Expanded(child: _filterChip('书籍', Icons.menu_book_outlined, _showBooks, bookCount, () { setState(() { _showBooks = !_showBooks; _performSearch(); }); })),
const SizedBox(width: 8), const SizedBox(width: 8),
_filterChip('笔记', Icons.note_outlined, _showNotes, noteCount, () { setState(() { _showNotes = !_showNotes; _performSearch(); }); }), Expanded(child: _filterChip('笔记', Icons.note_outlined, _showNotes, noteCount, () { setState(() { _showNotes = !_showNotes; _performSearch(); }); })),
const SizedBox(width: 8), const SizedBox(width: 8),
_filterChip('游戏', Icons.sports_esports_outlined, _showGames, gameCount, () { setState(() { _showGames = !_showGames; _performSearch(); }); }), Expanded(child: _filterChip('游戏', Icons.sports_esports_outlined, _showGames, gameCount, () { setState(() { _showGames = !_showGames; _performSearch(); }); })),
]), ]),
); );
} }
@@ -253,16 +253,16 @@ class _SearchPageState extends State<SearchPage> {
onTap: onTap, onTap: onTap,
child: AnimatedContainer( child: AnimatedContainer(
duration: const Duration(milliseconds: 200), duration: const Duration(milliseconds: 200),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7), padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 7),
decoration: BoxDecoration( decoration: BoxDecoration(
color: selected ? colors.primary : colors.surfaceContainerHighest, color: selected ? colors.primary : colors.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8), borderRadius: BorderRadius.circular(8),
), ),
child: Row(mainAxisSize: MainAxisSize.min, children: [ child: Row(mainAxisSize: MainAxisSize.min, children: [
Icon(icon, size: 14, color: selected ? colors.onPrimary : colors.onSurface.withValues(alpha: 0.4)), Icon(icon, size: 14, color: selected ? colors.onPrimary : colors.onSurface.withValues(alpha: 0.4)),
const SizedBox(width: 5), const SizedBox(width: 4),
Text(label, style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: selected ? colors.onPrimary : colors.onSurface.withValues(alpha: 0.4))), Flexible(child: Text(label, style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: selected ? colors.onPrimary : colors.onSurface.withValues(alpha: 0.4)), overflow: TextOverflow.ellipsis)),
if (showCount) ...[const SizedBox(width: 4), Text('$count', style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: selected ? colors.onPrimary.withValues(alpha: 0.7) : colors.onSurface.withValues(alpha: 0.25)))], if (showCount) ...[const SizedBox(width: 3), Text('$count', style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: selected ? colors.onPrimary.withValues(alpha: 0.7) : colors.onSurface.withValues(alpha: 0.25)))],
]), ]),
), ),
); );

View File

@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import '../providers/app_provider.dart'; import '../providers/app_provider.dart';
import '../models/data_models.dart'; import '../models/data_models.dart';
import 'fade_in_local_image.dart';
/// 笔记列表项组件 - 卡片式设计,内容展示在卡片内 /// 笔记列表项组件 - 卡片式设计,内容展示在卡片内
class NoteListItem extends StatelessWidget { class NoteListItem extends StatelessWidget {
@@ -98,6 +99,54 @@ class _NoteListItemContent extends StatelessWidget {
), ),
], ],
// 图片预览
if (note.images.isNotEmpty) ...[
const SizedBox(height: 8),
SizedBox(
height: 48,
child: ListView.separated(
scrollDirection: Axis.horizontal,
itemCount: note.images.length > 4 ? 4 : note.images.length,
separatorBuilder: (_, __) => const SizedBox(width: 6),
itemBuilder: (context, index) {
if (index == 3 && note.images.length > 4) {
return Container(
width: 48,
height: 48,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
color: colors.surfaceContainerHighest,
),
child: Center(
child: Text(
'+${note.images.length - 3}',
style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.5)),
),
),
);
}
return Container(
width: 48,
height: 48,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
border: Border.all(color: colors.outlineVariant, width: 0.5),
),
clipBehavior: Clip.antiAlias,
child: FadeInLocalImage(
path: note.images[index],
fit: BoxFit.cover,
errorWidget: Container(
color: colors.surfaceContainerHighest,
child: Icon(Icons.broken_image_outlined, size: 16, color: colors.onSurface.withValues(alpha: 0.25)),
),
),
);
},
),
),
],
// 标签 // 标签
if (note.tags.isNotEmpty) ...[ if (note.tags.isNotEmpty) ...[
const SizedBox(height: 8), const SizedBox(height: 8),

View File

@@ -14,6 +14,7 @@ class VditorEditor extends StatefulWidget {
final bool isDark; final bool isDark;
final Color surfaceColor; final Color surfaceColor;
final ValueChanged<String>? onContentChanged; final ValueChanged<String>? onContentChanged;
final ValueChanged<double>? onHeightChanged;
final String placeholder; final String placeholder;
const VditorEditor({ const VditorEditor({
@@ -23,6 +24,7 @@ class VditorEditor extends StatefulWidget {
this.isDark = false, this.isDark = false,
this.surfaceColor = Colors.white, this.surfaceColor = Colors.white,
this.onContentChanged, this.onContentChanged,
this.onHeightChanged,
this.placeholder = '使用 Markdown 格式书写...', this.placeholder = '使用 Markdown 格式书写...',
}); });
@@ -34,8 +36,9 @@ class VditorEditorState extends State<VditorEditor> {
InAppWebViewController? _controller; InAppWebViewController? _controller;
bool _isReady = false; bool _isReady = false;
bool _loadFailed = false; bool _loadFailed = false;
bool _assetsReady = false; String? _distDir; // Windows: 文件系统路径
String? _distDir; double _contentHeight = 200; // WebView 内容高度,随内容撑开
double _lastKeyboardH = 0; // 上次键盘高度,用于检测键盘弹出
final Completer<void> _readyCompleter = Completer<void>(); final Completer<void> _readyCompleter = Completer<void>();
Timer? _fallbackTimer; Timer? _fallbackTimer;
@@ -46,7 +49,12 @@ class VditorEditorState extends State<VditorEditor> {
void initState() { void initState() {
super.initState(); super.initState();
_startFallbackTimer(); _startFallbackTimer();
_locateDistDir(); if (Platform.isWindows) {
_locateDistDir();
} else {
// Android/iOS: 直接从 asset 加载,无需定位文件系统路径
if (mounted) setState(() {});
}
} }
void _startFallbackTimer() { void _startFallbackTimer() {
@@ -60,13 +68,12 @@ class VditorEditorState extends State<VditorEditor> {
/// 定位 vditor_dist 目录Windows 构建时由 CMakeLists 复制到 data/ 下) /// 定位 vditor_dist 目录Windows 构建时由 CMakeLists 复制到 data/ 下)
Future<void> _locateDistDir() async { Future<void> _locateDistDir() async {
try { try {
// Windows: exe 同级 data/vditor_dist/
final exePath = Platform.resolvedExecutable; final exePath = Platform.resolvedExecutable;
final exeDir = p.dirname(exePath); final exeDir = p.dirname(exePath);
final candidate = p.join(exeDir, 'data', 'vditor_dist'); final candidate = p.join(exeDir, 'data', 'vditor_dist');
if (await File(p.join(candidate, 'vditor_editor.html')).exists()) { if (await File(p.join(candidate, 'vditor_editor.html')).exists()) {
_distDir = candidate; _distDir = candidate;
if (mounted) setState(() => _assetsReady = true); if (mounted) setState(() {});
return; return;
} }
debugPrint('[VditorEditor] vditor_dist not found at $candidate'); debugPrint('[VditorEditor] vditor_dist not found at $candidate');
@@ -112,7 +119,7 @@ class VditorEditorState extends State<VditorEditor> {
Future<void> setTheme(bool isDark) async { Future<void> setTheme(bool isDark) async {
if (_controller == null || !_isReady) return; if (_controller == null || !_isReady) return;
final theme = isDark ? 'dark' : 'classic'; final theme = isDark ? 'dark' : 'light';
try { try {
await _controller!.evaluateJavascript(source: 'setTheme("$theme")'); await _controller!.evaluateJavascript(source: 'setTheme("$theme")');
} catch (_) {} } catch (_) {}
@@ -134,16 +141,23 @@ class VditorEditorState extends State<VditorEditor> {
} catch (_) {} } catch (_) {}
} }
Future<void> _scrollToCursor() async {
if (_controller == null || !_isReady) return;
try {
// 延迟一帧让键盘动画完成
await Future.delayed(const Duration(milliseconds: 300));
await _controller!.evaluateJavascript(source: 'scrollToCursor()');
} catch (_) {}
}
void _onVditorReady() { void _onVditorReady() {
if (_isReady) return; if (_isReady) return;
_fallbackTimer?.cancel(); _fallbackTimer?.cancel();
_isReady = true; _isReady = true;
if (!_readyCompleter.isCompleted) _readyCompleter.complete(); if (!_readyCompleter.isCompleted) _readyCompleter.complete();
// 设置初始内容
if (widget.initialContent != null && widget.initialContent!.isNotEmpty) { if (widget.initialContent != null && widget.initialContent!.isNotEmpty) {
setValue(widget.initialContent!); setValue(widget.initialContent!);
} }
// 设置背景色
setBgColor(_colorToHex(widget.surfaceColor)); setBgColor(_colorToHex(widget.surfaceColor));
} }
@@ -202,83 +216,139 @@ class VditorEditorState extends State<VditorEditor> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme; final colors = Theme.of(context).colorScheme;
if (_loadFailed || !_assetsReady) { if (_loadFailed) {
if (_loadFailed) { return TextField(
// 离线降级:使用普通 TextField controller: TextEditingController(text: widget.initialContent ?? ''),
return TextField( maxLines: null,
controller: TextEditingController(text: widget.initialContent ?? ''), expands: true,
maxLines: null, textAlignVertical: TextAlignVertical.top,
expands: true, strutStyle: const StrutStyle(forceStrutHeight: true, height: 1.6, fontSize: 14),
textAlignVertical: TextAlignVertical.top, style: TextStyle(fontSize: 14, color: colors.onSurface, height: 1.6),
strutStyle: const StrutStyle(forceStrutHeight: true, height: 1.6, fontSize: 14), decoration: InputDecoration(
style: TextStyle(fontSize: 14, color: colors.onSurface, height: 1.6), hintText: widget.placeholder,
decoration: InputDecoration( hintStyle: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.25), height: 1.6),
hintText: widget.placeholder, border: InputBorder.none,
hintStyle: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.25), height: 1.6), enabledBorder: InputBorder.none,
border: InputBorder.none, focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none, contentPadding: const EdgeInsets.all(16),
focusedBorder: InputBorder.none, ),
contentPadding: const EdgeInsets.all(16), onChanged: widget.onContentChanged,
), );
onChanged: widget.onContentChanged, }
);
} // Windows: 等待 dist 目录定位完成
// 等待 assets 解压 if (Platform.isWindows && _distDir == null) {
return Center(child: CircularProgressIndicator(strokeWidth: 2, color: colors.primary)); return Center(child: CircularProgressIndicator(strokeWidth: 2, color: colors.primary));
} }
final htmlPath = p.join(_distDir!, 'vditor_editor.html'); final String initialUrl;
final fileUrl = 'file:///${htmlPath.replaceAll('\\', '/')}'; if (Platform.isWindows) {
debugPrint('[VditorEditor] loading: $fileUrl'); final htmlPath = p.join(_distDir!, 'vditor_editor.html');
initialUrl = 'file:///${htmlPath.replaceAll('\\', '/')}';
} else {
// Android: 直接访问 APK 内 asset相对路径自动解析
initialUrl = 'file:///android_asset/flutter_assets/assets/vditor/dist/vditor_editor.html';
}
debugPrint('[VditorEditor] loading: $initialUrl');
return Container( // 键盘弹出时,滚动到光标位置
color: colors.surface, final keyboardH = MediaQuery.of(context).viewInsets.bottom;
child: InAppWebView( if (keyboardH > 0 && _lastKeyboardH == 0 && _isReady) {
webViewEnvironment: windowsWebViewEnvironment, Future.microtask(() => _scrollToCursor());
initialUrlRequest: URLRequest(url: WebUri(fileUrl)), }
initialSettings: InAppWebViewSettings( _lastKeyboardH = keyboardH;
javaScriptEnabled: true,
transparentBackground: true, return SizedBox(
disableContextMenu: false, height: _contentHeight,
useHybridComposition: true, child: Stack(
), children: [
onWebViewCreated: (controller) { Container(
_controller = controller; color: colors.surface,
controller.addJavaScriptHandler( child: InAppWebView(
handlerName: 'onVditorReady', webViewEnvironment: Platform.isWindows ? windowsWebViewEnvironment : null,
callback: (_) => _onVditorReady(), initialUrlRequest: URLRequest(url: WebUri(initialUrl)),
); initialSettings: InAppWebViewSettings(
controller.addJavaScriptHandler( javaScriptEnabled: true,
handlerName: 'onContentChanged', transparentBackground: true,
callback: (args) { disableContextMenu: false,
if (args.isNotEmpty) { useHybridComposition: true,
widget.onContentChanged?.call(args[0].toString()); allowFileAccessFromFileURLs: true,
} allowUniversalAccessFromFileURLs: true,
}, ),
); onWebViewCreated: (controller) {
controller.addJavaScriptHandler( _controller = controller;
handlerName: 'onPickImage', controller.addJavaScriptHandler(
callback: (_) => _pickImage(), handlerName: 'onVditorReady',
); callback: (_) => _onVditorReady(),
controller.addJavaScriptHandler( );
handlerName: 'onImageUpload', controller.addJavaScriptHandler(
callback: (args) { handlerName: 'onContentChanged',
if (args.length >= 3) { callback: (args) {
_handleImageUpload(args[0].toString(), args[1].toString(), args[2].toString()); if (args.isNotEmpty) {
} widget.onContentChanged?.call(args[0].toString());
}, }
); },
}, );
onLoadStop: (controller, url) async { controller.addJavaScriptHandler(
final theme = widget.isDark ? 'dark' : 'classic'; handlerName: 'onPickImage',
final escapedPlaceholder = jsonEncode(widget.placeholder); callback: (_) => _pickImage(),
await controller.evaluateJavascript( );
source: 'initVditor("$theme", $escapedPlaceholder)', controller.addJavaScriptHandler(
); handlerName: 'onImageUpload',
}, callback: (args) {
onReceivedError: (controller, request, error) { if (args.length >= 3) {
debugPrint('[VditorEditor] load error: ${error.description}'); _handleImageUpload(args[0].toString(), args[1].toString(), args[2].toString());
}, }
},
);
controller.addJavaScriptHandler(
handlerName: 'onHeightChanged',
callback: (args) {
if (args.isNotEmpty) {
final h = double.tryParse(args[0].toString()) ?? _contentHeight;
if ((h - _contentHeight).abs() > 2 && h > 0) {
setState(() => _contentHeight = h);
widget.onHeightChanged?.call(h);
}
}
},
);
},
onLoadStop: (controller, url) async {
final theme = widget.isDark ? 'dark' : 'light';
final escapedPlaceholder = jsonEncode(widget.placeholder);
await controller.evaluateJavascript(
source: 'initVditor("$theme", $escapedPlaceholder)',
);
},
onReceivedError: (controller, request, error) {
debugPrint('[VditorEditor] load error: ${error.description}');
},
),
),
// 加载动画Vditor 就绪前显示
if (!_isReady)
Container(
color: colors.surface,
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(strokeWidth: 2, color: colors.primary),
),
const SizedBox(height: 10),
Text(
'编辑器加载中...',
style: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.4)),
),
],
),
),
),
],
), ),
); );
} }

View File

@@ -66,3 +66,31 @@ flutter:
- assets/images/ticket/ - assets/images/ticket/
- assets/images/imp_book/ - assets/images/imp_book/
- assets/vditor/ - assets/vditor/
- assets/vditor/dist/
- assets/vditor/dist/css/
- assets/vditor/dist/css/content-theme/
- assets/vditor/dist/images/
- assets/vditor/dist/images/emoji/
- assets/vditor/dist/js/abcjs/
- assets/vditor/dist/js/echarts/
- assets/vditor/dist/js/flowchart.js/
- assets/vditor/dist/js/graphviz/
- assets/vditor/dist/js/highlight.js/
- assets/vditor/dist/js/highlight.js/styles/
- assets/vditor/dist/js/i18n/
- assets/vditor/dist/js/icons/
- assets/vditor/dist/js/katex/
- assets/vditor/dist/js/katex/fonts/
- assets/vditor/dist/js/lute/
- assets/vditor/dist/js/markmap/
- assets/vditor/dist/js/mathjax/
- assets/vditor/dist/js/mathjax/a11y/
- assets/vditor/dist/js/mathjax/input/
- assets/vditor/dist/js/mathjax/input/mml/
- assets/vditor/dist/js/mathjax/input/tex/
- assets/vditor/dist/js/mathjax/input/tex/extensions/
- assets/vditor/dist/js/mathjax/sre/
- assets/vditor/dist/js/mathjax/sre/mathmaps/
- assets/vditor/dist/js/mermaid/
- assets/vditor/dist/js/plantuml/
- assets/vditor/dist/js/smiles-drawer/