Skip to content

基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。

feat(history): redesign watch history page

Predidit7ca223bbc498
diff --git a/lib/bean/card/bangumi_history_card.dart b/lib/bean/card/bangumi_history_card.dart
deleted file mode 100644
index e21a37b7..00000000
--- a/lib/bean/card/bangumi_history_card.dart
+++ /dev/null
@@ -1,265 +0,0 @@
-import 'package:flutter/material.dart';
-import 'package:flutter_mobx/flutter_mobx.dart';
-import 'package:flutter_modular/flutter_modular.dart';
-import 'package:kazumi/bean/card/network_img_layer.dart';
-import 'package:kazumi/bean/dialog/dialog_helper.dart';
-import 'package:kazumi/bean/widget/collect_button.dart';
-import 'package:kazumi/modules/history/history_module.dart';
-import 'package:kazumi/pages/collect/collect_controller.dart';
-import 'package:kazumi/services/player/history_playback_service.dart';
-import 'package:kazumi/services/plugin/rule_engine_models.dart'
- show RuleCancelToken;
-import 'package:kazumi/utils/device.dart';
-import 'package:kazumi/utils/date_time.dart';
-
-String _historySourceText(String entryKind) {
- return HistoryEntryKind.normalize(entryKind) == HistoryEntryKind.offline
- ? '缓存'
- : '在线';
-}
-
-class BangumiHistoryCardV extends StatefulWidget {
- const BangumiHistoryCardV({
- super.key,
- required this.historyItem,
- this.showDelete = false,
- this.onDeleted,
- });
-
- final History historyItem;
- final bool showDelete;
- final VoidCallback? onDeleted;
-
- @override
- State<BangumiHistoryCardV> createState() => _BangumiHistoryCardVState();
-}
-
-class _BangumiHistoryCardVState extends State<BangumiHistoryCardV> {
- final CollectController collectController = inject<CollectController>();
- final HistoryPlaybackService _playbackService =
- inject<HistoryPlaybackService>();
-
- RuleCancelToken? _queryRoadsCancelToken;
-
- @override
- void dispose() {
- _queryRoadsCancelToken?.cancel();
- super.dispose();
- }
-
- Future<void> _onTap() async {
- if (widget.showDelete) {
- KazumiDialog.showToast(message: '编辑模式');
- return;
- }
- _queryRoadsCancelToken?.cancel();
- final cancelToken = RuleCancelToken();
- _queryRoadsCancelToken = cancelToken;
- KazumiDialog.showLoading(
- msg: '获取中',
- barrierDismissible: isDesktop(),
- onDismiss: cancelToken.cancel,
- );
- final result = await _playbackService.open(
- widget.historyItem,
- cancelToken: cancelToken,
- );
- KazumiDialog.dismiss();
- if (!mounted) return;
- switch (result) {
- case HistoryPlaybackReady(:final args):
- context.pushNamed('/video/', arguments: args);
- case HistoryPlaybackUnavailable(:final reason):
- KazumiDialog.showToast(message: reason);
- }
- }
-
- @override
- Widget build(BuildContext context) {
- final theme = Theme.of(context);
- final colorScheme = theme.colorScheme;
- final double imageWidth = 80;
- final double imageHeight = 108;
- final String title = widget.historyItem.bangumiItem.nameCn == ''
- ? widget.historyItem.bangumiItem.name
- : widget.historyItem.bangumiItem.nameCn;
- final String episodeText = widget.historyItem.lastWatchEpisodeName.isEmpty
- ? '第${widget.historyItem.lastWatchEpisode}话'
- : widget.historyItem.lastWatchEpisodeName;
- final String sourceText = _historySourceText(widget.historyItem.entryKind);
-
- return Dismissible(
- key: ValueKey(widget.historyItem.key),
- direction: DismissDirection.endToStart,
- onDismissed: (_) {
- widget.onDeleted?.call();
- },
- background: Container(
- alignment: Alignment.centerRight,
- padding: const EdgeInsets.only(right: 24),
- margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
- decoration: BoxDecoration(
- color: colorScheme.errorContainer,
- borderRadius: BorderRadius.circular(16),
- ),
- child: Icon(
- Icons.delete_outline,
- color: colorScheme.onErrorContainer,
- ),
- ),
- child: Card(
- elevation: 0,
- margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(16),
- ),
- clipBehavior: Clip.antiAlias,
- color: colorScheme.surfaceContainerLow,
- child: InkWell(
- onTap: _onTap,
- child: Padding(
- padding: const EdgeInsets.all(12),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- ClipRRect(
- borderRadius: BorderRadius.circular(12),
- child: NetworkImgLayer(
- src: widget.historyItem.bangumiItem.images['large'] ?? '',
- width: imageWidth,
- height: imageHeight,
- ),
- ),
- const SizedBox(width: 12),
- Expanded(
- child: SizedBox(
- height: imageHeight,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- title,
- style: theme.textTheme.titleSmall?.copyWith(
- color: colorScheme.onSurface,
- fontWeight: FontWeight.w600,
- ),
- overflow: TextOverflow.ellipsis,
- maxLines: 1,
- ),
- const SizedBox(height: 6),
- Row(
- children: [
- Icon(
- Icons.play_circle_outline,
- size: 14,
- color: colorScheme.onSurfaceVariant,
- ),
- const SizedBox(width: 4),
- Flexible(
- child: Text(
- episodeText,
- style: theme.textTheme.bodySmall?.copyWith(
- color: colorScheme.onSurfaceVariant,
- ),
- overflow: TextOverflow.ellipsis,
- maxLines: 1,
- ),
- ),
- ],
- ),
- const SizedBox(height: 4),
- Row(
- children: [
- Icon(
- Icons.extension_outlined,
- size: 14,
- color: colorScheme.onSurfaceVariant,
- ),
- const SizedBox(width: 4),
- Flexible(
- child: Text(
- '$sourceText · ${widget.historyItem.adapterName}',
- style: theme.textTheme.bodySmall?.copyWith(
- color: colorScheme.onSurfaceVariant,
- ),
- overflow: TextOverflow.ellipsis,
- maxLines: 1,
- ),
- ),
- ],
- ),
- const Spacer(),
- Row(
- children: [
- Icon(
- Icons.access_time,
- size: 12,
- color: colorScheme.outline,
- ),
- const SizedBox(width: 4),
- Text(
- formatTimestampToRelativeTime(widget.historyItem
- .lastWatchTime.millisecondsSinceEpoch ~/
- 1000),
- style: theme.textTheme.labelSmall?.copyWith(
- color: colorScheme.outline,
- ),
- ),
- ],
- ),
- ],
- ),
- ),
- ),
- Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- if (!widget.showDelete) ...[
- Observer(
- builder: (context) {
- collectController.collectibles.length;
- return CollectButton(
- onClose: () {
- FocusScope.of(context).unfocus();
- },
- bangumiItem: widget.historyItem.bangumiItem,
- color: colorScheme.onSurfaceVariant,
- );
- },
- ),
- IconButton(
- icon: Icon(
- Icons.open_in_new,
- size: 20,
- color: colorScheme.onSurfaceVariant,
- ),
- tooltip: '番剧详情',
- onPressed: () {
- context.pushNamed(
- '/info/',
- arguments: widget.historyItem.bangumiItem,
- );
- },
- ),
- ],
- if (widget.showDelete)
- IconButton(
- icon: Icon(
- Icons.delete_outline,
- color: colorScheme.error,
- ),
- tooltip: '删除记录',
- onPressed: () {
- widget.onDeleted?.call();
- },
- ),
- ],
- ),
- ],
- ),
- ),
- ),
- ),
- );
- }
-}
diff --git a/lib/pages/history/history_list_query.dart b/lib/pages/history/history_list_query.dart
new file mode 100644
index 00000000..d797eba9
--- /dev/null
+++ b/lib/pages/history/history_list_query.dart
@@ -0,0 +1,62 @@
+import 'package:kazumi/modules/history/history_module.dart';
+
+enum HistorySourceFilter {
+ all('全部'),
+ online('在线'),
+ offline('缓存');
+
+ const HistorySourceFilter(this.label);
+
+ final String label;
+
+ bool _matches(History history) => switch (this) {
+ all => true,
+ online => HistoryEntryKind.normalize(history.entryKind) ==
+ HistoryEntryKind.online,
+ offline => HistoryEntryKind.normalize(history.entryKind) ==
+ HistoryEntryKind.offline,
+ };
+}
+
+class HistoryDateGroup {
+ HistoryDateGroup._(this.date, this.entries);
+
+ final DateTime date;
+ final List<History> entries;
+
+ String label(DateTime now) {
+ final localNow = now.toLocal();
+ final today = DateTime(localNow.year, localNow.month, localNow.day);
+ if (date == today) return '今天';
+ if (date == DateTime(today.year, today.month, today.day - 1)) return '昨天';
+ final prefix = date.year == today.year ? '' : '${date.year}年';
+ return '$prefix${date.month}月${date.day}日';
+ }
+}
+
+List<HistoryDateGroup> groupHistoryEntries(
+ Iterable<History> entries, {
+ String query = '',
+ HistorySourceFilter source = HistorySourceFilter.all,
+}) {
+ final keyword = query.trim().toLowerCase();
+ final filtered = entries.where((entry) {
+ if (!source._matches(entry)) return false;
+ final item = entry.bangumiItem;
+ return keyword.isEmpty ||
+ [item.name, item.nameCn, ...item.alias, entry.adapterName]
+ .any((value) => value.toLowerCase().contains(keyword));
+ }).toList()
+ ..sort((a, b) => b.lastWatchTime.compareTo(a.lastWatchTime));
+
+ final groups = <HistoryDateGroup>[];
+ for (final entry in filtered) {
+ final localTime = entry.lastWatchTime.toLocal();
+ final date = DateTime(localTime.year, localTime.month, localTime.day);
+ if (groups.isEmpty || groups.last.date != date) {
+ groups.add(HistoryDateGroup._(date, []));
+ }
+ groups.last.entries.add(entry);
+ }
+ return groups;
+}
diff --git a/lib/pages/history/history_list_view.dart b/lib/pages/history/history_list_view.dart
new file mode 100644
index 00000000..40da6fea
--- /dev/null
+++ b/lib/pages/history/history_list_view.dart
@@ -0,0 +1,328 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:kazumi/modules/history/history_module.dart';
+import 'package:kazumi/pages/history/history_list_query.dart';
+
+class HistoryListView extends StatefulWidget {
+ const HistoryListView({
+ super.key,
+ required this.entries,
+ required this.itemBuilder,
+ this.editing = false,
+ });
+
+ final List<History> entries;
+ final bool editing;
+ final Widget Function(History history, BorderRadius borderRadius) itemBuilder;
+
+ @override
+ State<HistoryListView> createState() => _HistoryListViewState();
+}
+
+class _HistoryListViewState extends State<HistoryListView> {
+ final _searchController = TextEditingController();
+ final _searchFocus = FocusNode();
+ final _scrollController = ScrollController();
+ HistorySourceFilter _source = HistorySourceFilter.all;
+ String _query = '';
+
+ @override
+ void dispose() {
+ _searchController.dispose();
+ _searchFocus.dispose();
+ _scrollController.dispose();
+ super.dispose();
+ }
+
+ void _updateFilters(VoidCallback update) {
+ setState(update);
+ if (_scrollController.hasClients) _scrollController.jumpTo(0);
+ }
+
+ void _clearSearch() {
+ _searchController.clear();
+ _updateFilters(() => _query = '');
+ }
+
+ void _resetFilters() {
+ _searchController.clear();
+ _updateFilters(() {
+ _query = '';
+ _source = HistorySourceFilter.all;
+ });
+ _searchFocus.unfocus();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final colors = theme.colorScheme;
+ final groups =
+ groupHistoryEntries(widget.entries, query: _query, source: _source);
+ final count =
+ groups.fold<int>(0, (total, group) => total + group.entries.length);
+ final filtered =
+ _query.trim().isNotEmpty || _source != HistorySourceFilter.all;
+ final now = DateTime.now();
+ const searchBorder = OutlineInputBorder(
+ borderRadius: BorderRadius.all(Radius.circular(28)),
+ borderSide: BorderSide.none,
+ );
+
+ return CallbackShortcuts(
+ bindings: {
+ const SingleActivator(LogicalKeyboardKey.keyF, control: true):
+ _searchFocus.requestFocus,
+ const SingleActivator(LogicalKeyboardKey.keyF, meta: true):
+ _searchFocus.requestFocus,
+ const SingleActivator(LogicalKeyboardKey.escape): () {
+ _clearSearch();
+ _searchFocus.unfocus();
+ },
+ },
+ child: Focus(
+ autofocus: true,
+ child: LayoutBuilder(builder: (context, constraints) {
+ final contentWidth = constraints.maxWidth.clamp(0.0, 960.0);
+ // Keep the viewport full-width for edge scrollbars and gutter scrolling.
+ final inset = (constraints.maxWidth - contentWidth) / 2 +
+ (constraints.maxWidth < 600 ? 16.0 : 24.0);
+ return Scrollbar(
+ controller: _scrollController,
+ child: CustomScrollView(
+ key: const PageStorageKey('history-list'),
+ controller: _scrollController,
+ scrollBehavior:
+ ScrollConfiguration.of(context).copyWith(scrollbars: false),
+ keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
+ slivers: [
+ SliverPadding(
+ padding: EdgeInsets.fromLTRB(inset, 8, inset, 0),
+ sliver: SliverToBoxAdapter(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ if (widget.entries.isNotEmpty || filtered) ...[
+ TextField(
+ controller: _searchController,
+ focusNode: _searchFocus,
+ textInputAction: TextInputAction.search,
+ decoration: InputDecoration(
+ hintText: '搜索番剧、别名或来源',
+ prefixIcon: const Icon(Icons.search_rounded),
+ suffixIcon: _query.isEmpty
+ ? null
+ : IconButton(
+ tooltip: '清除搜索',
+ onPressed: _clearSearch,
+ icon: const Icon(Icons.close_rounded),
+ ),
+ filled: true,
+ fillColor: colors.surfaceContainerHigh,
+ constraints: const BoxConstraints(minHeight: 56),
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 20, vertical: 16),
+ border: searchBorder,
+ enabledBorder: searchBorder,
+ focusedBorder: searchBorder.copyWith(
+ borderSide:
+ BorderSide(color: colors.primary, width: 2),
+ ),
+ ),
+ onChanged: (value) =>
+ _updateFilters(() => _query = value),
+ onSubmitted: (_) => _searchFocus.unfocus(),
+ ),
+ const SizedBox(height: 16),
+ Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ children: [
+ for (final source in HistorySourceFilter.values)
+ _filter(source),
+ ],
+ ),
+ const SizedBox(height: 20),
+ Semantics(
+ liveRegion: true,
+ child: Text(
+ widget.editing
+ ? '共 $count 条记录 · 点按删除按钮移除'
+ : filtered
+ ? '找到 $count 条记录 · 最近观看优先'
+ : '共 $count 条记录 · 最近观看优先',
+ style: theme.textTheme.bodyMedium
+ ?.copyWith(color: colors.onSurfaceVariant),
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ if (groups.isEmpty)
+ SliverFillRemaining(
+ hasScrollBody: false,
+ child: _emptyState(filtered),
+ ),
+ for (final group in groups) ...[
+ SliverPadding(
+ padding: EdgeInsets.fromLTRB(inset + 4, 24, inset + 4, 12),
+ sliver: SliverToBoxAdapter(
+ child: Semantics(
+ header: true,
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(group.label(now),
+ style: theme.textTheme.titleLarge
+ ?.copyWith(fontWeight: FontWeight.w700)),
+ ),
+ Text('${group.entries.length} 条',
+ style: theme.textTheme.labelLarge
+ ?.copyWith(color: colors.onSurfaceVariant)),
+ ],
+ ),
+ ),
+ ),
+ ),
+ SliverPadding(
+ padding: EdgeInsets.symmetric(horizontal: inset),
+ sliver: SliverList.builder(
+ itemCount: group.entries.length,
+ findChildIndexCallback: (key) {
+ if (key is! ValueKey<String>) return null;
+ final index = group.entries
+ .indexWhere((entry) => entry.key == key.value);
+ return index < 0 ? null : index;
+ },
+ itemBuilder: (context, index) {
+ final history = group.entries[index];
+ final shape = BorderRadius.vertical(
+ top: Radius.circular(index == 0 ? 24 : 4),
+ bottom: Radius.circular(
+ index == group.entries.length - 1 ? 24 : 4),
+ );
+ return Padding(
+ key: ValueKey(history.key),
+ padding: const EdgeInsets.only(bottom: 2),
+ child: widget.itemBuilder(history, shape),
+ );
+ },
+ ),
+ ),
+ ],
+ SliverPadding(
+ padding: EdgeInsets.only(
+ bottom: 24 + MediaQuery.paddingOf(context).bottom),
+ ),
+ ],
+ ),
+ );
+ }),
+ ),
+ );
+ }
+
+ Widget _filter(HistorySourceFilter source) {
+ final theme = Theme.of(context);
+ final selected = _source == source;
+ final colors = theme.colorScheme;
+ final shape = BorderRadius.circular(selected ? 20 : 12);
+ return Semantics(
+ button: true,
+ selected: selected,
+ child: AnimatedContainer(
+ duration: MediaQuery.disableAnimationsOf(context)
+ ? Duration.zero
+ : const Duration(milliseconds: 250),
+ curve: Curves.easeInOutCubicEmphasized,
+ decoration: BoxDecoration(
+ color:
+ selected ? colors.secondaryContainer : colors.surfaceContainerLow,
+ borderRadius: shape,
+ ),
+ child: Material(
+ color: Colors.transparent,
+ borderRadius: shape,
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ onTap: () => _updateFilters(() => _source = source),
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(minHeight: 48),
+ child: Padding(
+ padding:
+ const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (selected) ...[
+ Icon(Icons.check_rounded,
+ size: 18, color: colors.onSecondaryContainer),
+ const SizedBox(width: 8),
+ ],
+ Text(source.label,
+ style: theme.textTheme.labelLarge?.copyWith(
+ fontWeight:
+ selected ? FontWeight.w700 : FontWeight.w500,
+ color: selected
+ ? colors.onSecondaryContainer
+ : colors.onSurfaceVariant,
+ )),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _emptyState(bool filtered) {
+ final theme = Theme.of(context);
+ final colors = theme.colorScheme;
+ return Center(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 40),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Container(
+ width: 88,
+ height: 88,
+ decoration: BoxDecoration(
+ color: colors.secondaryContainer,
+ borderRadius: BorderRadius.circular(32),
+ ),
+ child: Icon(
+ filtered ? Icons.search_off_rounded : Icons.history_rounded,
+ size: 36,
+ color: colors.onSecondaryContainer,
+ ),
+ ),
+ const SizedBox(height: 24),
+ Text(filtered ? '没有找到相关记录' : '还没有观看记录',
+ textAlign: TextAlign.center,
+ style: theme.textTheme.titleLarge
+ ?.copyWith(fontWeight: FontWeight.w700)),
+ const SizedBox(height: 8),
+ Text(
+ filtered ? '试试其他关键词,或查看全部记录' : '看过的番剧会留在这里,随时接着看',
+ textAlign: TextAlign.center,
+ style: theme.textTheme.bodyMedium
+ ?.copyWith(color: colors.onSurfaceVariant),
+ ),
+ if (filtered) ...[
+ const SizedBox(height: 20),
+ FilledButton.tonal(
+ onPressed: _resetFilters,
+ child: const Text('查看全部记录'),
+ ),
+ ],
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/pages/history/history_page.dart b/lib/pages/history/history_page.dart
index 34f44337..14127e0d 100644
--- a/lib/pages/history/history_page.dart
+++ b/lib/pages/history/history_page.dart
@@ -1,17 +1,21 @@
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
+import 'package:flutter_modular/flutter_modular.dart';
import 'package:kazumi/bean/appbar/sys_app_bar.dart';
-import 'package:kazumi/bean/card/bangumi_history_card.dart';
import 'package:kazumi/bean/dialog/dialog_helper.dart';
-import 'package:kazumi/bean/widget/empty_state_widget.dart';
+import 'package:kazumi/modules/collect/collect_type.dart';
+import 'package:kazumi/modules/history/history_module.dart';
+import 'package:kazumi/pages/collect/collect_controller.dart';
import 'package:kazumi/pages/history/history_controller.dart';
-import 'package:kazumi/utils/constants.dart';
+import 'package:kazumi/pages/history/history_list_view.dart';
+import 'package:kazumi/pages/history/history_record_tile.dart';
+import 'package:kazumi/services/player/history_playback_service.dart';
+import 'package:kazumi/services/plugin/rule_engine_models.dart'
+ show RuleCancelToken;
+import 'package:kazumi/utils/device.dart';
class HistoryPage extends StatefulWidget {
- const HistoryPage({
- super.key,
- required this.controller,
- });
+ const HistoryPage({super.key, required this.controller});
final HistoryController controller;
@@ -20,150 +24,234 @@ class HistoryPage extends StatefulWidget {
}
class _HistoryPageState extends State<HistoryPage> {
- HistoryController get historyController => widget.controller;
-
- bool showDelete = false;
+ bool _editing = false;
+ bool _clearing = false;
+ final Set<String> _deleting = {};
@override
void initState() {
super.initState();
- historyController.init();
+ widget.controller.init();
}
- void onBackPressed(BuildContext context) {
- if (KazumiDialog.observer.hasKazumiDialog) {
- KazumiDialog.dismiss();
- return;
+ Future<void> _deleteHistory(History history) async {
+ if (_clearing || _deleting.contains(history.key)) return;
+ setState(() => _deleting.add(history.key));
+ try {
+ await widget.controller.deleteHistory(history);
+ if (mounted && widget.controller.histories.isEmpty) {
+ setState(() => _editing = false);
+ }
+ } catch (_) {
+ if (mounted) {
+ KazumiDialog.showToast(context: context, message: '删除失败,请稍后重试');
+ }
+ } finally {
+ if (mounted) setState(() => _deleting.remove(history.key));
}
}
- void showHistoryClearDialog() {
- KazumiDialog.show(
- builder: (context) {
- return AlertDialog(
- title: const Text('记录管理'),
- content: const Text('确认要清除所有历史记录吗?'),
- actions: [
- TextButton(
- onPressed: () {
- KazumiDialog.dismiss();
- },
- child: Text(
- '取消',
- style: TextStyle(color: Theme.of(context).colorScheme.outline),
- ),
- ),
- TextButton(
- onPressed: () {
- KazumiDialog.dismiss();
- try {
- historyController.clearAll();
- } catch (_) {}
- },
- child: const Text('确认'),
- ),
- ],
- );
- },
+ Future<void> _clearHistory() async {
+ if (_clearing || _deleting.isNotEmpty) return;
+ final confirmed = await KazumiDialog.show<bool>(
+ context: context,
+ builder: (context) => AlertDialog(
+ icon: const Icon(Icons.delete_sweep_outlined),
+ title: const Text('清空历史记录?'),
+ content: Text(
+ '将删除全部 ${widget.controller.histories.length} 条观看记录,包括在线和缓存记录。此操作无法撤销。'),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.of(context).pop(false),
+ child: const Text('取消'),
+ ),
+ FilledButton(
+ style: FilledButton.styleFrom(
+ backgroundColor: Theme.of(context).colorScheme.error,
+ foregroundColor: Theme.of(context).colorScheme.onError),
+ onPressed: () => Navigator.of(context).pop(true),
+ child: const Text('清空全部'),
+ ),
+ ],
+ ),
);
+ if (confirmed != true || !mounted) return;
+ setState(() => _clearing = true);
+ try {
+ await widget.controller.clearAll();
+ if (mounted) setState(() => _editing = false);
+ } catch (_) {
+ if (mounted) {
+ KazumiDialog.showToast(context: context, message: '清空失败,请稍后重试');
+ }
+ } finally {
+ if (mounted) setState(() => _clearing = false);
+ }
}
@override
Widget build(BuildContext context) {
return Observer(builder: (context) {
+ final entries = widget.controller.histories.toList();
return PopScope(
- canPop: true,
- onPopInvokedWithResult: (bool didPop, Object? result) async {
- onBackPressed(context);
+ canPop: !_editing,
+ onPopInvokedWithResult: (didPop, result) {
+ if (!didPop && _editing) {
+ setState(() => _editing = false);
+ }
},
child: Scaffold(
appBar: SysAppBar(
- title: const Text('历史记录'),
+ title: Text('历史记录',
+ style: Theme.of(context)
+ .textTheme
+ .headlineSmall
+ ?.copyWith(fontWeight: FontWeight.w700)),
actions: [
- if (historyController.histories.isNotEmpty) ...[
- IconButton(
- onPressed: () {
- setState(() {
- showDelete = !showDelete;
- });
- },
- icon: showDelete
- ? const Icon(Icons.edit_off_outlined)
- : const Icon(Icons.edit_outlined),
- tooltip: showDelete ? '退出编辑' : '编辑',
- ),
- IconButton(
- onPressed: () {
- showHistoryClearDialog();
- },
- icon: const Icon(Icons.delete_sweep_outlined),
- tooltip: '清除全部',
+ if (entries.isNotEmpty) ...[
+ Padding(
+ padding: const EdgeInsets.only(right: 8),
+ child: _editing
+ ? FilledButton.tonal(
+ onPressed: _clearing
+ ? null
+ : () => setState(() => _editing = false),
+ child: const Text('完成'),
+ )
+ : IconButton.filledTonal(
+ tooltip: '管理历史记录',
+ onPressed: () => setState(() => _editing = true),
+ icon: const Icon(Icons.edit_outlined),
+ ),
),
+ if (_editing)
+ IconButton(
+ tooltip: '清空全部历史记录',
+ onPressed: _clearing || _deleting.isNotEmpty
+ ? null
+ : _clearHistory,
+ icon: const Icon(Icons.delete_sweep_outlined),
+ ),
],
],
),
- body: SafeArea(bottom: false, child: renderBody),
+ body: SafeArea(
+ top: false,
+ bottom: false,
+ child: HistoryListView(
+ entries: entries,
+ editing: _editing,
+ itemBuilder: (history, borderRadius) => _HistoryCard(
+ history: history,
+ borderRadius: borderRadius,
+ editing: _editing,
+ busy: _clearing || _deleting.contains(history.key),
+ onDelete: () => _deleteHistory(history),
+ ),
+ ),
+ ),
),
);
});
}
+}
- Widget get renderBody {
- if (historyController.histories.isNotEmpty) {
- return contentGrid;
- } else {
- return const Center(
- child: GeneralEmptyState(
- icon: Icons.history_rounded,
- title: '暂无历史记录',
- ),
+class _HistoryCard extends StatefulWidget {
+ const _HistoryCard({
+ required this.history,
+ required this.onDelete,
+ required this.editing,
+ required this.busy,
+ required this.borderRadius,
+ });
+
+ final History history;
+ final bool editing;
+ final bool busy;
+ final Future<void> Function() onDelete;
+ final BorderRadius borderRadius;
+
+ @override
+ State<_HistoryCard> createState() => _HistoryCardState();
+}
+
+class _HistoryCardState extends State<_HistoryCard> {
+ final CollectController _collectController = inject<CollectController>();
+ final HistoryPlaybackService _playbackService =
+ inject<HistoryPlaybackService>();
+ RuleCancelToken? _playbackCancelToken;
+ bool _opening = false;
+ bool _updatingCollect = false;
+
+ @override
+ void dispose() {
+ _playbackCancelToken?.cancel();
+ super.dispose();
+ }
+
+ Future<void> _play() async {
+ if (widget.editing || widget.busy || _opening) return;
+ setState(() => _opening = true);
+ final cancelToken = RuleCancelToken();
+ _playbackCancelToken = cancelToken;
+ KazumiDialog.showLoading(
+ msg: '获取中',
+ barrierDismissible: isDesktop(),
+ onDismiss: cancelToken.cancel,
+ );
+ try {
+ final result = await _playbackService.open(
+ widget.history,
+ cancelToken: cancelToken,
);
+ if (!mounted || cancelToken.isCancelled) return;
+ KazumiDialog.dismiss();
+ switch (result) {
+ case HistoryPlaybackReady(:final args):
+ context.pushNamed('/video/', arguments: args);
+ case HistoryPlaybackUnavailable(:final reason):
+ KazumiDialog.showToast(message: reason);
+ }
+ } catch (_) {
+ if (!mounted || cancelToken.isCancelled) return;
+ KazumiDialog.dismiss();
+ KazumiDialog.showToast(message: '暂时无法继续播放,请稍后重试');
+ } finally {
+ if (mounted) setState(() => _opening = false);
}
}
- Widget get contentGrid {
- int crossCount = 1;
- if (MediaQuery.sizeOf(context).width > LayoutBreakpoint.compact['width']!) {
- crossCount = 2;
- }
- if (MediaQuery.sizeOf(context).width > LayoutBreakpoint.medium['width']!) {
- crossCount = 3;
+ Future<void> _changeCollect(CollectType type) async {
+ if (_updatingCollect) return;
+ setState(() => _updatingCollect = true);
+ try {
+ await _collectController.addCollect(widget.history.bangumiItem,
+ type: type.value);
+ } catch (_) {
+ KazumiDialog.showToast(message: '修改收藏状态失败,请稍后重试');
+ } finally {
+ if (mounted) setState(() => _updatingCollect = false);
}
+ }
- final double screenWidth = MediaQuery.sizeOf(context).width;
- final double maxContentWidth = 1000;
- final double horizontalPadding =
- screenWidth > maxContentWidth ? (screenWidth - maxContentWidth) / 2 : 0;
-
- return CustomScrollView(
- slivers: [
- const SliverPadding(padding: EdgeInsets.only(top: 4)),
- SliverPadding(
- padding: EdgeInsets.symmetric(horizontal: horizontalPadding),
- sliver: SliverGrid(
- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
- mainAxisSpacing: 2,
- crossAxisSpacing: StyleString.cardSpace,
- crossAxisCount: crossCount,
- mainAxisExtent: 136,
- ),
- delegate: SliverChildBuilderDelegate(
- (BuildContext context, int index) {
- return BangumiHistoryCardV(
- historyItem: historyController.histories[index],
- showDelete: showDelete,
- onDeleted: () {
- historyController
- .deleteHistory(historyController.histories[index]);
- },
- );
- },
- childCount: historyController.histories.length,
- ),
- ),
- ),
- const SliverPadding(padding: EdgeInsets.only(bottom: 16)),
- ],
- );
+ @override
+ Widget build(BuildContext context) {
+ return Observer(builder: (context) {
+ // getCollectType reads storage, so track the observable list explicitly.
+ _collectController.collectibles.length;
+ return HistoryRecordTile(
+ history: widget.history,
+ borderRadius: widget.borderRadius,
+ editing: widget.editing,
+ busy: widget.busy || _opening,
+ onPlay: _play,
+ onDelete: widget.onDelete,
+ onDetails: () =>
+ context.pushNamed('/info/', arguments: widget.history.bangumiItem),
+ collectType: CollectType.fromValue(
+ _collectController.getCollectType(widget.history.bangumiItem)),
+ onChangeCollect: _updatingCollect ? null : _changeCollect,
+ );
+ });
}
}
diff --git a/lib/pages/history/history_record_tile.dart b/lib/pages/history/history_record_tile.dart
new file mode 100644
index 00000000..1666ac7d
--- /dev/null
+++ b/lib/pages/history/history_record_tile.dart
@@ -0,0 +1,274 @@
+import 'package:flutter/material.dart';
+import 'package:kazumi/bean/card/network_img_layer.dart';
+import 'package:kazumi/bean/widget/loading_indicator.dart';
+import 'package:kazumi/modules/collect/collect_type.dart';
+import 'package:kazumi/modules/history/history_module.dart';
+
+class HistoryRecordTile extends StatelessWidget {
+ const HistoryRecordTile({
+ super.key,
+ required this.history,
+ required this.onPlay,
+ required this.onDetails,
+ required this.onDelete,
+ required this.collectType,
+ required this.onChangeCollect,
+ this.borderRadius = const BorderRadius.all(Radius.circular(24)),
+ this.editing = false,
+ this.busy = false,
+ });
+
+ final History history;
+ final VoidCallback onPlay;
+ final VoidCallback onDetails;
+ final Future<void> Function() onDelete;
+ final CollectType collectType;
+ final ValueChanged<CollectType>? onChangeCollect;
+ final BorderRadius borderRadius;
+ final bool editing;
+ final bool busy;
+
+ String get _position {
+ final progress = history.progresses[history.lastWatchEpisode]?.progress;
+ if (progress == null || progress.inSeconds <= 0) return '';
+ final seconds = (progress.inSeconds % 60).toString().padLeft(2, '0');
+ final minutes = (progress.inMinutes % 60).toString().padLeft(2, '0');
+ final position = progress.inHours > 0
+ ? '${progress.inHours}:$minutes:$seconds'
+ : '${progress.inMinutes}:$seconds';
+ return '看到 $position';
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final colors = theme.colorScheme;
+ final title = history.bangumiItem.nameCn.isEmpty
+ ? history.bangumiItem.name
+ : history.bangumiItem.nameCn;
+ final episode = history.lastWatchEpisodeName.isEmpty
+ ? '第 ${history.lastWatchEpisode} 话'
+ : history.lastWatchEpisodeName;
+ final source = HistoryEntryKind.normalize(history.entryKind) ==
+ HistoryEntryKind.offline
+ ? '缓存'
+ : '在线';
+ final time =
+ TimeOfDay.fromDateTime(history.lastWatchTime.toLocal()).format(context);
+ final image = history.bangumiItem.images['large'] ?? '';
+ final position = _position;
+
+ return Dismissible(
+ key: ValueKey(history.key),
+ direction:
+ busy || editing ? DismissDirection.none : DismissDirection.endToStart,
+ // The parent removes saved deletions; failed writes keep the row usable.
+ confirmDismiss: (_) async {
+ await onDelete();
+ return false;
+ },
+ background: Container(
+ alignment: Alignment.centerRight,
+ padding: const EdgeInsets.only(right: 24),
+ decoration: BoxDecoration(
+ color: colors.errorContainer, borderRadius: borderRadius),
+ child:
+ Icon(Icons.delete_outline_rounded, color: colors.onErrorContainer),
+ ),
+ child: Material(
+ color: colors.surfaceContainerLow,
+ borderRadius: borderRadius,
+ clipBehavior: Clip.antiAlias,
+ child: Stack(
+ children: [
+ // Keep menu focus outside the card's InkWell to prevent stuck highlights.
+ Positioned.fill(
+ child: Semantics(
+ button: !editing && !busy,
+ label: [
+ title,
+ episode,
+ position,
+ source,
+ history.adapterName,
+ time
+ ].where((text) => text.isNotEmpty).join(','),
+ child: InkWell(onTap: editing || busy ? null : onPlay),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.all(16),
+ child: LayoutBuilder(builder: (context, constraints) {
+ final wide = constraints.maxWidth >= 600;
+ final largeText =
+ MediaQuery.textScalerOf(context).scale(14) > 21;
+ final coverWidth = wide ? 72.0 : 60.0;
+ final content = Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(title,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: theme.textTheme.titleMedium
+ ?.copyWith(fontWeight: FontWeight.w700)),
+ const SizedBox(height: 6),
+ Text(episode,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: theme.textTheme.bodyMedium
+ ?.copyWith(color: colors.onSurfaceVariant)),
+ if (position.isNotEmpty) ...[
+ const SizedBox(height: 4),
+ Text(position,
+ style: theme.textTheme.labelMedium?.copyWith(
+ color: colors.primary,
+ fontWeight: FontWeight.w600)),
+ ],
+ const SizedBox(height: 8),
+ Text(
+ [
+ source,
+ if (history.adapterName.isNotEmpty) history.adapterName,
+ time
+ ].join(' · '),
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: theme.textTheme.bodySmall
+ ?.copyWith(color: colors.onSurfaceVariant),
+ ),
+ ],
+ );
+ final actions = _actions(context, wide: wide || largeText);
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ ExcludeSemantics(
+ child: IgnorePointer(
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(12),
+ child: image.isEmpty
+ ? Container(
+ width: coverWidth,
+ height: coverWidth * 1.4,
+ color: colors.surfaceContainerHighest,
+ child: Icon(Icons.movie_outlined,
+ color: colors.onSurfaceVariant),
+ )
+ : NetworkImgLayer(
+ src: image,
+ width: coverWidth,
+ height: coverWidth * 1.4,
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(width: 16),
+ Expanded(
+ child: ExcludeSemantics(
+ child: IgnorePointer(child: content),
+ ),
+ ),
+ if (!largeText) ...[
+ const SizedBox(width: 8),
+ actions,
+ ],
+ ],
+ ),
+ if (largeText) ...[
+ const SizedBox(height: 12),
+ Align(alignment: Alignment.centerRight, child: actions),
+ ],
+ ],
+ );
+ }),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _actions(BuildContext context, {required bool wide}) {
+ final colors = Theme.of(context).colorScheme;
+ if (busy) {
+ return const SizedBox(
+ width: 48,
+ height: 48,
+ child: Center(child: LoadingIndicator(size: 24)),
+ );
+ }
+ if (editing) {
+ return IconButton.filledTonal(
+ tooltip: '删除记录',
+ style: IconButton.styleFrom(
+ minimumSize: const Size(48, 48),
+ backgroundColor: colors.errorContainer,
+ foregroundColor: colors.onErrorContainer,
+ ),
+ onPressed: onDelete,
+ icon: const Icon(Icons.delete_outline_rounded),
+ );
+ }
+
+ final buttons = [
+ IconButton.filledTonal(
+ tooltip: '继续播放',
+ style: IconButton.styleFrom(
+ minimumSize: const Size(48, 48),
+ backgroundColor: colors.primaryContainer,
+ foregroundColor: colors.onPrimaryContainer,
+ ),
+ onPressed: onPlay,
+ icon: const Icon(Icons.play_arrow_rounded),
+ ),
+ MenuAnchor(
+ consumeOutsideTap: true,
+ menuChildren: [
+ MenuItemButton(
+ leadingIcon: const Icon(Icons.info_outline_rounded),
+ onPressed: onDetails,
+ child: const Text('番剧详情'),
+ ),
+ SubmenuButton(
+ leadingIcon: const Icon(Icons.bookmark_outline_rounded),
+ menuChildren: [
+ for (final type in CollectType.values)
+ MenuItemButton(
+ leadingIcon: Icon(collectType == type
+ ? Icons.radio_button_checked_rounded
+ : Icons.radio_button_unchecked_rounded),
+ onPressed: onChangeCollect == null
+ ? null
+ : () => onChangeCollect!(type),
+ child: Text(type.label),
+ ),
+ ],
+ child: Text('收藏 · ${collectType.label}'),
+ ),
+ const Divider(),
+ MenuItemButton(
+ leadingIcon:
+ Icon(Icons.delete_outline_rounded, color: colors.error),
+ onPressed: onDelete,
+ child: Text('删除记录', style: TextStyle(color: colors.error)),
+ ),
+ ],
+ builder: (context, controller, child) => IconButton(
+ tooltip: '更多操作',
+ constraints: const BoxConstraints(minWidth: 48, minHeight: 48),
+ onPressed: () =>
+ controller.isOpen ? controller.close() : controller.open(),
+ icon: const Icon(Icons.more_horiz_rounded),
+ ),
+ ),
+ ];
+ return wide
+ ? Row(mainAxisSize: MainAxisSize.min, children: buttons)
+ : Column(mainAxisSize: MainAxisSize.min, children: buttons);
+ }
+}