Skip to content

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

feat(collect): redesign library (#2534)

Predidit24690559c62b
diff --git a/lib/pages/collect/collect_library_card.dart b/lib/pages/collect/collect_library_card.dart
new file mode 100644
index 00000000..d24a8190
--- /dev/null
+++ b/lib/pages/collect/collect_library_card.dart
@@ -0,0 +1,170 @@
+part of 'collect_library_view.dart';
+
+class _CollectLibraryCard extends StatelessWidget {
+ const _CollectLibraryCard({
+ super.key,
+ required this.entry,
+ required this.onOpen,
+ required this.onChangeType,
+ });
+
+ final CollectedBangumi entry;
+ final VoidCallback onOpen;
+ final ValueChanged<CollectType>? onChangeType;
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final colors = theme.colorScheme;
+ final item = entry.bangumiItem;
+ final title = CollectLibraryQuery.titleOf(entry);
+ final type = CollectType.fromValue(entry.type);
+ final airDate = DateTime.tryParse(item.airDate);
+ final metadata = [
+ if (airDate != null) '${airDate.year} 年',
+ if (item.ratingScore > 0) '${item.ratingScore.toStringAsFixed(1)} 分',
+ ];
+
+ return Material(
+ color: colors.surfaceContainerLow,
+ borderRadius: BorderRadius.circular(24),
+ clipBehavior: Clip.antiAlias,
+ child: Stack(
+ children: [
+ // Keep the menu outside the card's focus and pointer subtree.
+ Positioned.fill(
+ child: Semantics(
+ button: true,
+ label: [title, ...metadata].join(','),
+ child: InkWell(onTap: onOpen),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(12, 12, 16, 8),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ ExcludeSemantics(
+ child: IgnorePointer(
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(16),
+ child: NetworkImgLayer(
+ src:
+ item.images['large'] ?? item.images['common'] ?? '',
+ width: 80,
+ height: 120,
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(width: 16),
+ Expanded(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ ExcludeSemantics(
+ child: IgnorePointer(
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(minHeight: 76),
+ child: Padding(
+ padding: const EdgeInsets.only(top: 4, bottom: 8),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ title,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style:
+ theme.textTheme.titleMedium?.copyWith(
+ fontWeight: FontWeight.w700,
+ height: 1.35,
+ ),
+ ),
+ if (metadata.isNotEmpty)
+ Padding(
+ padding: const EdgeInsets.only(top: 8),
+ child: Text(
+ metadata.join(' · '),
+ style:
+ theme.textTheme.bodySmall?.copyWith(
+ color: colors.onSurfaceVariant,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ _statusMenu(context, type, title),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _statusMenu(BuildContext context, CollectType type, String title) {
+ final colors = Theme.of(context).colorScheme;
+ const itemStyle = ButtonStyle(
+ visualDensity: VisualDensity.standard,
+ padding: WidgetStatePropertyAll(EdgeInsets.symmetric(horizontal: 16)),
+ minimumSize: WidgetStatePropertyAll(Size(192, 48)),
+ );
+
+ return MenuAnchor(
+ consumeOutsideTap: true,
+ style: MenuStyle(
+ shape: WidgetStatePropertyAll(
+ RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
+ ),
+ ),
+ menuChildren: [
+ for (final status
+ in CollectType.values.where((type) => type.isCollected))
+ MenuItemButton(
+ style: itemStyle,
+ trailingIcon:
+ status == type ? const Icon(Icons.check_rounded) : null,
+ onPressed: onChangeType == null || status == type
+ ? null
+ : () => onChangeType!(status),
+ child: Text(status.label),
+ ),
+ const Divider(indent: 16, endIndent: 16),
+ MenuItemButton(
+ style: itemStyle,
+ onPressed: onChangeType == null
+ ? null
+ : () => onChangeType!(CollectType.none),
+ child: Text('取消收藏', style: TextStyle(color: colors.error)),
+ ),
+ ],
+ builder: (context, controller, child) => Tooltip(
+ message: '调整《$title》的观看状态',
+ child: FilledButton.tonalIcon(
+ style: FilledButton.styleFrom(
+ visualDensity: VisualDensity.standard,
+ tapTargetSize: MaterialTapTargetSize.padded,
+ minimumSize: const Size(0, 40),
+ padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 12, 0),
+ ),
+ onPressed: onChangeType == null
+ ? null
+ : () =>
+ controller.isOpen ? controller.close() : controller.open(),
+ iconAlignment: IconAlignment.end,
+ icon: const Icon(Icons.expand_more_rounded, size: 18),
+ label: Text(type.label),
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/pages/collect/collect_library_query.dart b/lib/pages/collect/collect_library_query.dart
new file mode 100644
index 00000000..6f80fbd2
--- /dev/null
+++ b/lib/pages/collect/collect_library_query.dart
@@ -0,0 +1,66 @@
+import 'package:kazumi/modules/collect/collect_module.dart';
+import 'package:kazumi/modules/collect/collect_type.dart';
+
+enum CollectSort {
+ recentlyChanged('最近变更'),
+ title('番剧名称'),
+ rating('评分最高'),
+ airDate('开播时间');
+
+ const CollectSort(this.label);
+ final String label;
+}
+
+class CollectLibraryQuery {
+ CollectLibraryQuery(Iterable<CollectedBangumi> items, String query)
+ : _matches = _match(items, query);
+
+ final List<CollectedBangumi> _matches;
+
+ static List<CollectedBangumi> _match(
+ Iterable<CollectedBangumi> items, String query) {
+ final terms = query.trim().toLowerCase().split(RegExp(r'\s+'));
+ return items.where((entry) {
+ if (!CollectType.fromValue(entry.type).isCollected) return false;
+ final item = entry.bangumiItem;
+ final names =
+ [item.nameCn, item.name, ...item.alias].join('\n').toLowerCase();
+ return terms.every(names.contains);
+ }).toList();
+ }
+
+ int count(CollectType? type) => type == null
+ ? _matches.length
+ : _matches.where((entry) => entry.type == type.value).length;
+
+ List<CollectedBangumi> results(CollectType? type, CollectSort sort) {
+ final result = _matches
+ .where((entry) => type == null || entry.type == type.value)
+ .toList();
+ result.sort((a, b) {
+ final comparison = switch (sort) {
+ CollectSort.recentlyChanged => b.time.compareTo(a.time),
+ CollectSort.title => titleOf(a).toLowerCase().compareTo(
+ titleOf(b).toLowerCase(),
+ ),
+ CollectSort.rating =>
+ b.bangumiItem.ratingScore.compareTo(a.bangumiItem.ratingScore),
+ CollectSort.airDate => _airDate(b).compareTo(_airDate(a)),
+ };
+ if (comparison != 0) return comparison;
+ final byTime = b.time.compareTo(a.time);
+ return byTime != 0
+ ? byTime
+ : a.bangumiItem.id.compareTo(b.bangumiItem.id);
+ });
+ return result;
+ }
+
+ static String titleOf(CollectedBangumi entry) {
+ final item = entry.bangumiItem;
+ return item.nameCn.trim().isNotEmpty ? item.nameCn : item.name;
+ }
+
+ static DateTime _airDate(CollectedBangumi entry) =>
+ DateTime.tryParse(entry.bangumiItem.airDate) ?? DateTime(0);
+}
diff --git a/lib/pages/collect/collect_library_view.dart b/lib/pages/collect/collect_library_view.dart
new file mode 100644
index 00000000..6c8d7fea
--- /dev/null
+++ b/lib/pages/collect/collect_library_view.dart
@@ -0,0 +1,493 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:kazumi/bean/card/network_img_layer.dart';
+import 'package:kazumi/modules/bangumi/bangumi_item.dart';
+import 'package:kazumi/modules/collect/collect_module.dart';
+import 'package:kazumi/modules/collect/collect_type.dart';
+import 'package:kazumi/pages/collect/collect_library_query.dart';
+
+part 'collect_library_card.dart';
+
+class CollectLibraryView extends StatefulWidget {
+ const CollectLibraryView({
+ super.key,
+ required this.entries,
+ required this.onOpen,
+ required this.onChangeType,
+ required this.onDiscover,
+ required this.canEdit,
+ });
+
+ final List<CollectedBangumi> entries;
+ final ValueChanged<BangumiItem> onOpen;
+ final void Function(BangumiItem, CollectType) onChangeType;
+ final VoidCallback onDiscover;
+ final bool Function(BangumiItem) canEdit;
+
+ @override
+ State<CollectLibraryView> createState() => _CollectLibraryViewState();
+}
+
+class _CollectLibraryViewState extends State<CollectLibraryView> {
+ final _searchController = TextEditingController();
+ final _searchFocus = FocusNode();
+ final _scrollController = ScrollController();
+ CollectType? _selectedType = CollectType.watching;
+ CollectSort _sort = CollectSort.recentlyChanged;
+ String _query = '';
+
+ static const _categories = <CollectType?>[
+ null,
+ CollectType.watching,
+ CollectType.planToWatch,
+ CollectType.watched,
+ CollectType.onHold,
+ CollectType.abandoned,
+ ];
+
+ @override
+ void dispose() {
+ _searchController.dispose();
+ _searchFocus.dispose();
+ _scrollController.dispose();
+ super.dispose();
+ }
+
+ void _resetScroll() {
+ if (_scrollController.hasClients) _scrollController.jumpTo(0);
+ }
+
+ void _selectType(CollectType? type) {
+ setState(() => _selectedType = type);
+ _resetScroll();
+ }
+
+ void _search(String value) {
+ setState(() => _query = value);
+ _resetScroll();
+ }
+
+ void _clearSearch() {
+ _searchController.clear();
+ _search('');
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final query = CollectLibraryQuery(widget.entries, _query);
+ final entries = query.results(_selectedType, _sort);
+ final textScale = MediaQuery.textScalerOf(context).scale(14) / 14;
+
+ 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) {
+ // The outlet width excludes the app navigation rail.
+ final expanded = constraints.maxWidth >= 1000 && textScale <= 1.5;
+ final inset = constraints.maxWidth < 600 ? 16.0 : 24.0;
+ return Align(
+ alignment: Alignment.topCenter,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 1560),
+ child: Padding(
+ padding: EdgeInsets.fromLTRB(inset, 8, inset, 0),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ if (expanded) ...[
+ _sidebar(query),
+ const SizedBox(width: 28),
+ ],
+ Expanded(
+ child: Column(
+ children: [
+ _searchBar(),
+ Expanded(
+ child: _results(query, entries,
+ expanded: expanded, textScale: textScale),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }),
+ ),
+ );
+ }
+
+ Widget _sidebar(CollectLibraryQuery query) {
+ final theme = Theme.of(context);
+ return SizedBox(
+ key: const ValueKey('collect-sidebar'),
+ width: 224,
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.only(bottom: 24),
+ child: Material(
+ color: theme.colorScheme.surfaceContainerLow,
+ borderRadius: BorderRadius.circular(28),
+ child: Padding(
+ padding: const EdgeInsets.all(12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(12, 16, 12, 20),
+ child: Text('收藏分类',
+ style: theme.textTheme.titleSmall?.copyWith(
+ color: theme.colorScheme.onSurfaceVariant)),
+ ),
+ for (final type in _categories)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: _category(type, query, wide: true),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _searchBar() => SearchBar(
+ controller: _searchController,
+ focusNode: _searchFocus,
+ hintText: '搜索片单中的名称、别名',
+ leading: const Padding(
+ padding: EdgeInsets.only(left: 8),
+ child: Icon(Icons.search_rounded),
+ ),
+ trailing: [
+ if (_query.isNotEmpty)
+ IconButton(
+ tooltip: '清除搜索',
+ onPressed: _clearSearch,
+ icon: const Icon(Icons.close_rounded),
+ ),
+ ],
+ elevation: const WidgetStatePropertyAll(0),
+ backgroundColor: WidgetStatePropertyAll(
+ Theme.of(context).colorScheme.surfaceContainerHigh),
+ constraints: const BoxConstraints(minHeight: 56),
+ onChanged: _search,
+ onSubmitted: (_) => _searchFocus.unfocus(),
+ );
+
+ Widget _categoryStrip(CollectLibraryQuery query) => Padding(
+ padding: const EdgeInsets.only(top: 16),
+ child: SingleChildScrollView(
+ key: const ValueKey('collect-filter-strip'),
+ scrollDirection: Axis.horizontal,
+ child: Row(
+ children: [
+ for (final type in _categories)
+ Padding(
+ padding: const EdgeInsets.only(right: 8),
+ child: _category(type, query),
+ ),
+ ],
+ ),
+ ),
+ );
+
+ Widget _results(CollectLibraryQuery query, List<CollectedBangumi> entries,
+ {required bool expanded, required double textScale}) {
+ return LayoutBuilder(builder: (context, constraints) {
+ final columns = constraints.maxWidth >= 840 && textScale <= 1.3 ? 2 : 1;
+ return Scrollbar(
+ controller: _scrollController,
+ child: CustomScrollView(
+ key: const ValueKey('collect-results'),
+ controller: _scrollController,
+ keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
+ slivers: [
+ if (!expanded) SliverToBoxAdapter(child: _categoryStrip(query)),
+ SliverToBoxAdapter(
+ child: _heading(entries.length, expanded: expanded),
+ ),
+ if (entries.isEmpty)
+ SliverFillRemaining(
+ hasScrollBody: false,
+ child: _emptyState(query),
+ )
+ else
+ SliverPadding(
+ padding: EdgeInsets.only(
+ bottom: 24 + MediaQuery.paddingOf(context).bottom),
+ sliver: SliverList.builder(
+ itemCount: (entries.length + columns - 1) ~/ columns,
+ itemBuilder: (context, index) {
+ final first = index * columns;
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 10),
+ // Natural row heights accommodate enlarged text.
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Expanded(child: _card(entries[first])),
+ if (columns == 2) ...[
+ const SizedBox(width: 12),
+ Expanded(
+ child: first + 1 < entries.length
+ ? _card(entries[first + 1])
+ : const SizedBox(),
+ ),
+ ],
+ ],
+ ),
+ );
+ },
+ ),
+ ),
+ ],
+ ),
+ );
+ });
+ }
+
+ Widget _card(CollectedBangumi entry) => _CollectLibraryCard(
+ key: ValueKey('collect-${entry.bangumiItem.id}'),
+ entry: entry,
+ onOpen: () => widget.onOpen(entry.bangumiItem),
+ onChangeType: widget.canEdit(entry.bangumiItem)
+ ? (type) => widget.onChangeType(entry.bangumiItem, type)
+ : null,
+ );
+
+ Widget _category(CollectType? type, CollectLibraryQuery query,
+ {bool wide = false}) {
+ final theme = Theme.of(context);
+ final colors = theme.colorScheme;
+ final selected = type == _selectedType;
+ final label = type?.label ?? '全部';
+ final count = query.count(type);
+ final foreground =
+ selected ? colors.onPrimaryContainer : colors.onSurfaceVariant;
+
+ return Semantics(
+ selected: selected,
+ button: true,
+ label: '$label,$count 部',
+ excludeSemantics: true,
+ onTap: () => _selectType(type),
+ child: AnimatedContainer(
+ duration: MediaQuery.disableAnimationsOf(context)
+ ? Duration.zero
+ : const Duration(milliseconds: 250),
+ curve: Curves.easeInOutCubicEmphasized,
+ decoration: BoxDecoration(
+ color: selected
+ ? colors.primaryContainer
+ : wide
+ ? colors.surfaceContainerLow
+ : colors.surfaceContainer,
+ borderRadius: BorderRadius.circular(selected ? 20 : 12),
+ ),
+ child: Material(
+ color: Colors.transparent,
+ borderRadius: BorderRadius.circular(selected ? 20 : 12),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ key: ValueKey('collect-filter-${type?.value ?? 'all'}'),
+ onTap: () => _selectType(type),
+ child: ConstrainedBox(
+ constraints: BoxConstraints(minHeight: wide ? 56 : 48),
+ child: Padding(
+ padding:
+ const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+ child: Row(
+ mainAxisSize: wide ? MainAxisSize.max : MainAxisSize.min,
+ children: [
+ Icon(
+ switch (type) {
+ CollectType.watching =>
+ Icons.play_circle_outline_rounded,
+ CollectType.planToWatch =>
+ Icons.bookmark_border_rounded,
+ CollectType.onHold =>
+ Icons.pause_circle_outline_rounded,
+ CollectType.watched => Icons.task_alt_rounded,
+ CollectType.abandoned =>
+ Icons.remove_circle_outline_rounded,
+ _ => Icons.video_library_outlined,
+ },
+ size: 20,
+ color: foreground,
+ ),
+ const SizedBox(width: 10),
+ Text(label,
+ style: theme.textTheme.labelLarge?.copyWith(
+ color: foreground,
+ fontWeight:
+ selected ? FontWeight.w700 : FontWeight.w500)),
+ if (wide) const Spacer() else const SizedBox(width: 10),
+ Text('$count',
+ style: theme.textTheme.labelLarge?.copyWith(
+ color: foreground,
+ fontWeight: FontWeight.w700,
+ )),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _heading(int count, {required bool expanded}) {
+ final theme = Theme.of(context);
+ final colors = theme.colorScheme;
+ final searching = _query.trim().isNotEmpty;
+ return Padding(
+ padding: const EdgeInsets.only(top: 24, bottom: 20),
+ child: Wrap(
+ alignment: WrapAlignment.spaceBetween,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ spacing: 16,
+ runSpacing: 12,
+ children: [
+ Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ _selectedType?.label ?? '全部收藏',
+ style: (expanded
+ ? theme.textTheme.headlineLarge
+ : theme.textTheme.headlineMedium)
+ ?.copyWith(fontWeight: FontWeight.w700),
+ ),
+ const SizedBox(height: 6),
+ Semantics(
+ liveRegion: true,
+ child: Text(
+ searching ? '找到 $count 部番剧' : '共 $count 部番剧',
+ style: theme.textTheme.bodyMedium?.copyWith(
+ color: colors.onSurfaceVariant,
+ ),
+ ),
+ ),
+ ],
+ ),
+ MenuAnchor(
+ consumeOutsideTap: true,
+ menuChildren: [
+ for (final sort in CollectSort.values)
+ MenuItemButton(
+ trailingIcon:
+ _sort == sort ? const Icon(Icons.check_rounded) : null,
+ onPressed: () {
+ setState(() => _sort = sort);
+ _resetScroll();
+ },
+ child: Text(sort.label),
+ ),
+ ],
+ builder: (context, controller, child) => TextButton.icon(
+ style: TextButton.styleFrom(
+ foregroundColor: colors.onSurfaceVariant,
+ minimumSize: const Size(48, 48),
+ ),
+ onPressed: () =>
+ controller.isOpen ? controller.close() : controller.open(),
+ icon: const Icon(Icons.sort_rounded, size: 20),
+ label: Text(_sort.label),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _emptyState(CollectLibraryQuery query) {
+ final theme = Theme.of(context);
+ final colors = theme.colorScheme;
+ final searching = _query.trim().isNotEmpty;
+ final matchCount = query.count(null);
+ final String title;
+ final String description;
+ final String actionLabel;
+ final VoidCallback onAction;
+ var actionIcon = Icons.arrow_forward_rounded;
+
+ if (searching) {
+ title = '没有找到匹配的番剧';
+ if (matchCount > 0) {
+ description = '其他分类中有 $matchCount 部匹配的番剧。';
+ actionLabel = '在全部收藏中搜索';
+ onAction = () => _selectType(null);
+ } else {
+ description = '试试中文名、原名或别名,也可以缩短关键词。';
+ actionLabel = '清除搜索';
+ actionIcon = Icons.close_rounded;
+ onAction = _clearSearch;
+ }
+ } else if (matchCount == 0) {
+ title = '你的片单,从这里开始';
+ description = '收藏喜欢的番剧,在这里整理观看状态。';
+ actionLabel = '去发现番剧';
+ onAction = widget.onDiscover;
+ } else {
+ title = '还没有「${_selectedType!.label}」的番剧';
+ description = '可以从全部收藏中选择番剧,调整观看状态。';
+ actionLabel = '查看全部收藏';
+ onAction = () => _selectType(null);
+ }
+ return Center(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 32),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Container(
+ width: 88,
+ height: 88,
+ decoration: BoxDecoration(
+ color: colors.secondaryContainer,
+ borderRadius: BorderRadius.circular(32),
+ ),
+ child: Icon(
+ searching
+ ? Icons.search_off_rounded
+ : Icons.video_library_outlined,
+ size: 36,
+ color: colors.onSecondaryContainer,
+ ),
+ ),
+ const SizedBox(height: 24),
+ Text(title,
+ textAlign: TextAlign.center,
+ style: theme.textTheme.titleLarge
+ ?.copyWith(fontWeight: FontWeight.w700)),
+ const SizedBox(height: 10),
+ Text(description,
+ textAlign: TextAlign.center,
+ style: theme.textTheme.bodyMedium
+ ?.copyWith(color: colors.onSurfaceVariant)),
+ const SizedBox(height: 24),
+ FilledButton.tonalIcon(
+ onPressed: onAction,
+ icon: Icon(actionIcon),
+ label: Text(actionLabel),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/pages/collect/collect_page.dart b/lib/pages/collect/collect_page.dart
index b0b343ee..855eb7cb 100644
--- a/lib/pages/collect/collect_page.dart
+++ b/lib/pages/collect/collect_page.dart
@@ -2,20 +2,17 @@ import 'dart:async';
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_card.dart';
import 'package:kazumi/bean/dialog/dialog_helper.dart';
-import 'package:kazumi/bean/widget/collect_button.dart';
-import 'package:kazumi/bean/widget/empty_state_widget.dart';
import 'package:kazumi/bean/widget/loading_indicator.dart';
import 'package:kazumi/modules/bangumi/bangumi_item.dart';
-import 'package:kazumi/modules/collect/collect_module.dart';
import 'package:kazumi/modules/collect/collect_sync_plan.dart';
import 'package:kazumi/modules/collect/collect_type.dart';
import 'package:kazumi/pages/collect/collect_controller.dart';
+import 'package:kazumi/pages/collect/collect_library_view.dart';
import 'package:kazumi/services/storage/storage.dart';
-import 'package:kazumi/utils/constants.dart';
class CollectPage extends StatefulWidget {
const CollectPage({
@@ -29,73 +26,22 @@ class CollectPage extends StatefulWidget {
State<CollectPage> createState() => _CollectPageState();
}
-class _CollectPageState extends State<CollectPage>
- with SingleTickerProviderStateMixin {
+class _CollectPageState extends State<CollectPage> {
CollectController get collectController => widget.controller;
- TabController? tabController;
- bool showDelete = false;
- bool syncCollectiblesing = false;
+ bool _syncing = false;
+ final Set<int> _pendingIds = {};
- Future<bool> _syncBangumiWithProgress({
- required GlobalKey<_FullSyncProgressDialogState> progressDialogKey,
+ Future<void> _runFullSync({
+ required CollectSyncPlan plan,
}) async {
- progressDialogKey.currentState?.update('准备同步 Bangumi 收藏...', null);
-
- await Future<void>.delayed(const Duration(milliseconds: 80));
-
- return collectController.syncCollectiblesBangumi(
- showSuccessToast: false,
- onProgress: (message, current, total) {
- progressDialogKey.currentState?.update(
- total > 0 ? '$message ($current/$total)' : message,
- total > 0 ? (current / total).clamp(0.0, 1.0).toDouble() : null,
- );
- },
- );
- }
+ final progressDialogKey = GlobalKey<_FullSyncProgressDialogState>();
- void _showFullSyncProgressDialog({
- required GlobalKey<_FullSyncProgressDialogState> progressDialogKey,
- }) {
unawaited(KazumiDialog.show(
+ context: context,
clickMaskDismiss: false,
builder: (context) => _FullSyncProgressDialog(key: progressDialogKey),
));
- }
-
- String _buildFullSyncSummary({
- required CollectSyncPlan plan,
- required bool webDavSynced,
- required bool bangumiSynced,
- required bool webDavUploaded,
- }) {
- final List<String> states = [];
- if (plan.shouldSyncWebDavCollectibles) {
- states.add(webDavSynced ? 'WebDav 已同步' : 'WebDav 未完成');
- }
- if (plan.shouldSyncBangumi) {
- states.add(bangumiSynced ? 'Bangumi 已同步' : 'Bangumi 未完成');
- }
- if (plan.shouldSyncWebDavCollectibles &&
- plan.shouldSyncBangumi &&
- webDavSynced &&
- bangumiSynced) {
- states.add(webDavUploaded ? 'WebDav 已回传最新数据' : 'WebDav 未回传最新数据');
- }
- return states.join(',');
- }
-
- Future<void> _runFullSync({
- required CollectSyncPlan plan,
- }) async {
- final progressDialogKey = GlobalKey<_FullSyncProgressDialogState>();
-
- _showFullSyncProgressDialog(
- progressDialogKey: progressDialogKey,
- );
-
- await Future<void>.delayed(const Duration(milliseconds: 80));
-
+ await WidgetsBinding.instance.endOfFrame;
bool webDavSynced = false;
bool bangumiSynced = false;
bool webDavUploaded = false;
@@ -108,8 +54,15 @@ class _CollectPageState extends State<CollectPage>
}
if (plan.shouldSyncBangumi) {
- bangumiSynced = await _syncBangumiWithProgress(
- progressDialogKey: progressDialogKey,
+ progressDialogKey.currentState?.update('准备同步 Bangumi 收藏...', null);
+ bangumiSynced = await collectController.syncCollectiblesBangumi(
+ showSuccessToast: false,
+ onProgress: (message, current, total) {
+ progressDialogKey.currentState?.update(
+ total > 0 ? '$message ($current/$total)' : message,
+ total > 0 ? (current / total).clamp(0.0, 1.0).toDouble() : null,
+ );
+ },
);
}
@@ -123,268 +76,121 @@ class _CollectPageState extends State<CollectPage>
);
}
} finally {
- if (KazumiDialog.observer.hasKazumiDialog) {
- KazumiDialog.dismiss();
+ final dialogContext = progressDialogKey.currentContext;
+ if (dialogContext != null && dialogContext.mounted) {
+ final route = ModalRoute.of(dialogContext);
+ if (route != null) {
+ final navigator = Navigator.of(dialogContext);
+ if (route.isCurrent) {
+ navigator.pop();
+ } else {
+ navigator.removeRoute(route);
+ }
+ // The route observer clears stale snackbars at the end of the frame.
+ await WidgetsBinding.instance.endOfFrame;
+ }
}
}
- KazumiDialog.showToast(
- message: _buildFullSyncSummary(
- plan: plan,
+ final states = [
+ if (plan.shouldSyncWebDavCollectibles)
+ webDavSynced ? 'WebDav 已同步' : 'WebDav 未完成',
+ if (plan.shouldSyncBangumi) bangumiSynced ? 'Bangumi 已同步' : 'Bangumi 未完成',
+ if (plan.shouldUploadWebDavAfterBangumi(
webDavSynced: webDavSynced,
bangumiSynced: bangumiSynced,
- webDavUploaded: webDavUploaded,
- ),
- );
+ ))
+ webDavUploaded ? 'WebDav 已回传最新数据' : 'WebDav 未回传最新数据',
+ ];
+ KazumiDialog.showToast(message: states.join(','));
}
@override
void initState() {
super.initState();
collectController.loadCollectibles();
- tabController = TabController(vsync: this, length: _tabTypes.length);
}
- @override
- void dispose() {
- tabController?.dispose();
- super.dispose();
- }
-
- // CollectType values are one-based; tab indices are zero-based.
- static final List<CollectType> _tabTypes =
- CollectType.values.where((type) => type.isCollected).toList();
-
- static const double _countedTabMinWidth = 104;
-
- List<int> get _collectibleCounts {
- final List<int> counts = List<int>.filled(_tabTypes.length, 0);
- for (CollectedBangumi element in collectController.collectibles) {
- counts[element.type - 1]++;
+ Future<void> _changeType(BangumiItem item, CollectType type) async {
+ if (_syncing || _pendingIds.contains(item.id)) return;
+ setState(() => _pendingIds.add(item.id));
+ try {
+ await collectController.addCollect(item, type: type.value);
+ } catch (_) {
+ KazumiDialog.showToast(message: '修改收藏状态失败,请稍后重试');
+ } finally {
+ if (mounted) setState(() => _pendingIds.remove(item.id));
}
- return counts;
}
- Widget _buildTab(String label, int? count) {
- if (count == null) {
- return Tab(text: label);
- }
- final ThemeData theme = Theme.of(context);
- return Tab(
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(label),
- const SizedBox(width: 6),
- Container(
- padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
- decoration: BoxDecoration(
- color: theme.colorScheme.secondaryContainer,
- borderRadius: BorderRadius.circular(8),
- ),
- child: Text(
- '$count',
- style: theme.textTheme.labelSmall?.copyWith(
- color: theme.colorScheme.onSecondaryContainer,
- ),
- ),
- ),
- ],
- ),
+ Future<void> _sync() async {
+ if (_syncing || _pendingIds.isNotEmpty) return;
+ final plan = CollectSyncPlan(
+ webDavEnabled: GStorage.getSetting(SettingsKeys.webDavEnable),
+ webDavCollectiblesEnabled:
+ GStorage.getSetting(SettingsKeys.webDavEnableCollect),
+ bangumiEnabled: GStorage.getSetting(SettingsKeys.bangumiSyncEnable),
);
+ if (!plan.canSync) {
+ KazumiDialog.showToast(message: '同步功能不可用,请至少开启一个同步功能');
+ return;
+ }
+ setState(() => _syncing = true);
+ try {
+ await _runFullSync(plan: plan);
+ } catch (_) {
+ KazumiDialog.showToast(message: '同步未完成,请稍后重试');
+ } finally {
+ if (mounted) setState(() => _syncing = false);
+ }
}
@override
Widget build(BuildContext context) {
- final bool showAnimeCounter =
- GStorage.getSetting(SettingsKeys.showAnimeCounter);
+ final colors = Theme.of(context).colorScheme;
return Scaffold(
appBar: SysAppBar(
needTopOffset: false,
- toolbarHeight: 104,
- // App bar counts need their own Observer, outside the body observer.
- bottom: PreferredSize(
- preferredSize: const Size.fromHeight(kTextTabBarHeight),
- child: Observer(builder: (context) {
- final List<int>? counts =
- showAnimeCounter ? _collectibleCounts : null;
- return LayoutBuilder(builder: (context, constraints) {
- final bool scrollable = counts != null &&
- constraints.maxWidth <
- MediaQuery.textScalerOf(context)
- .scale(_countedTabMinWidth) *
- _tabTypes.length;
- return TabBar(
- controller: tabController,
- isScrollable: scrollable,
- tabAlignment:
- scrollable ? TabAlignment.start : TabAlignment.fill,
- tabs: [
- for (int i = 0; i < _tabTypes.length; i++)
- _buildTab(_tabTypes[i].label, counts?[i]),
- ],
- indicatorColor: Theme.of(context).colorScheme.primary,
- );
- });
- }),
+ toolbarHeight: 72,
+ title: Text(
+ '追番',
+ style: Theme.of(context)
+ .textTheme
+ .headlineSmall
+ ?.copyWith(fontWeight: FontWeight.w700),
),
- title: const Text('追番'),
actions: [
- IconButton(
- onPressed: () {
- setState(() {
- showDelete = !showDelete;
- });
- },
- icon: showDelete
- ? const Icon(Icons.edit_outlined)
- : const Icon(Icons.edit))
+ Padding(
+ padding: const EdgeInsets.only(right: 8),
+ child: IconButton.filledTonal(
+ tooltip: _syncing ? '正在同步收藏' : '同步收藏',
+ onPressed: _syncing || _pendingIds.isNotEmpty ? null : _sync,
+ icon: _syncing
+ ? LoadingIndicator(
+ size: 24,
+ color: colors.onSecondaryContainer,
+ semanticsLabel: '正在同步收藏',
+ )
+ : const Icon(Icons.sync_rounded),
+ ),
+ ),
],
),
- floatingActionButton: FloatingActionButton(
- onPressed: () async {
- bool webDavenable =
- await GStorage.getSetting(SettingsKeys.webDavEnable);
- bool webDavCollectEnable =
- GStorage.getSetting(SettingsKeys.webDavEnableCollect);
- bool bgmSyncEnable =
- GStorage.getSetting(SettingsKeys.bangumiSyncEnable);
- final syncPlan = CollectSyncPlan(
- webDavEnabled: webDavenable,
- webDavCollectiblesEnabled: webDavCollectEnable,
- bangumiEnabled: bgmSyncEnable,
- );
- if (!syncPlan.canSync) {
- KazumiDialog.showToast(message: '同步功能不可用,请至少开启一个同步功能');
- return;
- }
- if (showDelete) {
- KazumiDialog.showToast(message: '编辑模式无法执行同步');
- return;
- }
- if (syncCollectiblesing) {
- return;
- }
- setState(() {
- syncCollectiblesing = true;
- });
- try {
- await _runFullSync(
- plan: syncPlan,
- );
- } finally {
- if (mounted) {
- setState(() {
- syncCollectiblesing = false;
- });
- }
- }
- },
- child: syncCollectiblesing
- ? const SizedBox(width: 32, height: 32, child: LoadingIndicator())
- : const Icon(Icons.sync_rounded),
+ body: SafeArea(
+ top: false,
+ bottom: false,
+ child: Observer(
+ builder: (context) => CollectLibraryView(
+ entries: collectController.collectibles.toList(),
+ canEdit: (item) => !_syncing && !_pendingIds.contains(item.id),
+ onOpen: (item) => context.pushNamed('/info/', arguments: item),
+ onChangeType: (item, type) => unawaited(_changeType(item, type)),
+ onDiscover: () => context.pushNamed('/search/'),
+ ),
+ ),
),
- body: Observer(builder: (context) {
- return renderBody;
- }),
);
}
-
- Widget get renderBody {
- if (collectController.collectibles.isNotEmpty) {
- return TabBarView(
- controller: tabController,
- children: contentGrid(collectController.collectibles),
- );
- } else {
- return const Center(
- child: GeneralEmptyState(
- icon: Icons.favorite_border_rounded,
- title: '暂无追番内容',
- ),
- );
- }
- }
-
- List<Widget> contentGrid(List<CollectedBangumi> collectedBangumiList) {
- List<Widget> gridViewList = [];
- List<List<CollectedBangumi>> collectedBangumiRenderItemList =
- List.generate(_tabTypes.length, (_) => <CollectedBangumi>[]);
- for (CollectedBangumi element in collectedBangumiList) {
- collectedBangumiRenderItemList[element.type - 1].add(element);
- }
- for (List<CollectedBangumi> list in collectedBangumiRenderItemList) {
- list.sort((a, b) => b.time.millisecondsSinceEpoch
- .compareTo(a.time.millisecondsSinceEpoch));
- }
- int crossCount = 3;
- if (MediaQuery.sizeOf(context).width > LayoutBreakpoint.compact['width']!) {
- crossCount = 5;
- }
- if (MediaQuery.sizeOf(context).width > LayoutBreakpoint.medium['width']!) {
- crossCount = 6;
- }
- for (List<CollectedBangumi> collectedBangumiRenderItem
- in collectedBangumiRenderItemList) {
- gridViewList.add(
- CustomScrollView(
- slivers: [
- SliverPadding(
- padding: const EdgeInsets.fromLTRB(StyleString.cardSpace,
- StyleString.cardSpace, StyleString.cardSpace, 0),
- sliver: SliverGrid(
- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
- mainAxisSpacing: StyleString.cardSpace - 2,
- crossAxisSpacing: StyleString.cardSpace,
- crossAxisCount: crossCount,
- mainAxisExtent:
- MediaQuery.of(context).size.width / crossCount / 0.65 +
- MediaQuery.textScalerOf(context).scale(32.0),
- ),
- delegate: SliverChildBuilderDelegate(
- (BuildContext context, int index) {
- final BangumiItem bangumiItem =
- collectedBangumiRenderItem[index].bangumiItem;
- return Stack(
- children: [
- BangumiCardV(
- bangumiItem: bangumiItem,
- canTap: !showDelete,
- ),
- if (showDelete)
- Positioned(
- right: 5,
- bottom: 5,
- child: Container(
- width: 40,
- height: 40,
- decoration: BoxDecoration(
- color: Theme.of(context)
- .colorScheme
- .secondaryContainer,
- shape: BoxShape.circle,
- ),
- child: CollectButton(
- bangumiItem: bangumiItem,
- color: Theme.of(context)
- .colorScheme
- .onSecondaryContainer,
- ),
- ),
- ),
- ],
- );
- },
- childCount: collectedBangumiRenderItem.length,
- ),
- ),
- ),
- ],
- ),
- );
- }
- return gridViewList;
- }
}
class _FullSyncProgressDialog extends StatefulWidget {
diff --git a/lib/pages/settings/interface_settings.dart b/lib/pages/settings/interface_settings.dart
index 26899062..010addd8 100644
--- a/lib/pages/settings/interface_settings.dart
+++ b/lib/pages/settings/interface_settings.dart
@@ -12,7 +12,6 @@ class InterfaceSettingsPage extends StatefulWidget {
class _InterfaceSettingsPageState extends State<InterfaceSettingsPage> {
late bool showRating;
- late bool showAnimeCounter;
late String defaultPage;
final MenuController defaultPageMenuController = MenuController();
@@ -27,7 +26,6 @@ class _InterfaceSettingsPageState extends State<InterfaceSettingsPage> {
void initState() {
super.initState();
showRating = GStorage.getSetting(SettingsKeys.showRating);
- showAnimeCounter = GStorage.getSetting(SettingsKeys.showAnimeCounter);
defaultPage = GStorage.getSetting(SettingsKeys.defaultStartupPage);
}
@@ -101,18 +99,6 @@ class _InterfaceSettingsPageState extends State<InterfaceSettingsPage> {
description: Text('关闭后将在概览中隐藏评分信息'),
initialValue: showRating,
),
- SettingsTile.switchTile(
- leading: Icons.insights_rounded,
- onToggle: (value) async {
- showAnimeCounter = value ?? !showAnimeCounter;
- await GStorage.putSetting(
- SettingsKeys.showAnimeCounter, showAnimeCounter);
- setState(() {});
- },
- title: Text('显示追番统计'),
- description: Text('在追番页面的分类标签上显示数量'),
- initialValue: showAnimeCounter,
- ),
]),
],
),
diff --git a/lib/services/storage/settings_keys.dart b/lib/services/storage/settings_keys.dart
index 8872b7af..6cd69a6b 100644
--- a/lib/services/storage/settings_keys.dart
+++ b/lib/services/storage/settings_keys.dart
@@ -428,6 +428,7 @@ class SettingsKeys {
true,
group: SettingGroup.interface,
);
+ // Retained for legacy settings compatibility; no longer controls the UI.
static const showAnimeCounter = SettingKey<bool>(
_SettingBoxKey.showAnimeCounter,
false,