Skip to content

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

feat(collect): add responsive layouts and configurable default view

Predidit80e256ecb7dc
diff --git a/lib/bean/card/network_img_layer.dart b/lib/bean/card/network_img_layer.dart
index 506111bc..965576e3 100644
--- a/lib/bean/card/network_img_layer.dart
+++ b/lib/bean/card/network_img_layer.dart
@@ -18,6 +18,7 @@ class NetworkImgLayer extends StatelessWidget {
this.filterQuality = FilterQuality.high,
this.color,
this.colorBlendMode,
+ this.borderRadius,
});
final String? src;
@@ -31,6 +32,7 @@ class NetworkImgLayer extends StatelessWidget {
final FilterQuality filterQuality;
final Color? color;
final BlendMode? colorBlendMode;
+ final BorderRadius? borderRadius;
static Widget heroFlightShuttleBuilder(
BuildContext flightContext,
@@ -123,7 +125,9 @@ class NetworkImgLayer extends StatelessWidget {
}
}
- BorderRadius get _borderRadius => BorderRadius.circular(switch (type) {
+ BorderRadius get _borderRadius =>
+ borderRadius ??
+ BorderRadius.circular(switch (type) {
'avatar' => 50,
'emote' => 0,
_ => StyleString.imgRadius.x,
diff --git a/lib/modules/collect/collect_layout.dart b/lib/modules/collect/collect_layout.dart
new file mode 100644
index 00000000..749554c1
--- /dev/null
+++ b/lib/modules/collect/collect_layout.dart
@@ -0,0 +1,11 @@
+enum CollectLayout {
+ list('列表'),
+ cards('卡片');
+
+ const CollectLayout(this.label);
+
+ final String label;
+
+ static CollectLayout fromValue(String value) =>
+ value == cards.name ? cards : list;
+}
diff --git a/lib/pages/collect/collect_library_card.dart b/lib/pages/collect/collect_library_card.dart
index d3c4b733..2e230f6d 100644
--- a/lib/pages/collect/collect_library_card.dart
+++ b/lib/pages/collect/collect_library_card.dart
@@ -1,26 +1,236 @@
part of 'collect_library_view.dart';
-class _CollectLibraryCard extends StatelessWidget {
- const _CollectLibraryCard({
+class _CollectPosterCard extends StatelessWidget {
+ const _CollectPosterCard({
super.key,
required this.entry,
required this.showRating,
+ required this.showStatus,
required this.onOpen,
required this.onChangeType,
});
final CollectedBangumi entry;
final bool showRating;
+ final bool showStatus;
final VoidCallback onOpen;
final ValueChanged<CollectType>? onChangeType;
+ static const _coverRatio = 0.65;
+ static bool _isCompact(double width) => width < 160;
+ static double _titleHeight(TextScaler scaler, {bool compact = false}) =>
+ (scaler.scale(compact ? 13 : 14) * 2.7).ceilToDouble();
+ static double _detailsHeight(TextScaler scaler) =>
+ (scaler.scale(12) * 1.4).ceilToDouble();
+ static double _statusHeight(TextScaler scaler) =>
+ (scaler.scale(11) * 1.4).ceilToDouble();
+ static bool _stackCompactActions(double width, TextScaler scaler,
+ {required bool showRating, required bool showStatus}) =>
+ (showRating && scaler.scale(12) * 2.5 > width - 56) ||
+ (showStatus && scaler.scale(11) * 2 > width - 56);
+ static double _compactActionsHeight(double width, TextScaler scaler,
+ {required bool showRating, required bool showStatus}) {
+ final detailsHeight = (showRating ? _detailsHeight(scaler) : 0.0) +
+ (showStatus ? _statusHeight(scaler) : 0.0) +
+ (showRating && showStatus ? 2.0 : 0.0);
+ return _stackCompactActions(width, scaler,
+ showRating: showRating, showStatus: showStatus)
+ ? detailsHeight + 48
+ : detailsHeight.clamp(48.0, double.infinity);
+ }
+
+ static double extent(double width, TextScaler scaler,
+ {required bool showRating, required bool showStatus}) {
+ final footerHeight = _isCompact(width)
+ ? 12 +
+ _titleHeight(scaler, compact: true) +
+ _compactActionsHeight(width, scaler,
+ showRating: showRating, showStatus: showStatus)
+ : 16 +
+ (_titleHeight(scaler) +
+ (showRating || showStatus ? 4 + _detailsHeight(scaler) : 0))
+ .clamp(48.0, double.infinity);
+ return width / _coverRatio + footerHeight;
+ }
+
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colors = theme.colorScheme;
+ final scaler = MediaQuery.textScalerOf(context);
final item = entry.bangumiItem;
final title = CollectLibraryQuery.titleOf(entry);
+ final year = DateTime.tryParse(item.airDate)?.year;
final type = CollectType.fromValue(entry.type);
+ final hasRating = showRating && item.ratingScore > 0;
+ final showDetails = showStatus || showRating;
+
+ Widget detailLine(String value, {bool status = false}) => SizedBox(
+ height: status ? _statusHeight(scaler) : _detailsHeight(scaler),
+ child: Text(
+ value,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: theme.textTheme.bodySmall?.copyWith(
+ fontSize: status ? 11 : 12,
+ height: 1.4,
+ color: colors.onSurfaceVariant,
+ ),
+ ),
+ );
+
+ return LayoutBuilder(builder: (context, constraints) {
+ final compact = _isCompact(constraints.maxWidth);
+ final titleBlock = ExcludeSemantics(
+ child: SizedBox(
+ height: _titleHeight(scaler, compact: compact),
+ child: Text(
+ title,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: theme.textTheme.bodyMedium?.copyWith(
+ fontSize: compact ? 13 : 14,
+ height: 1.35,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ ),
+ );
+ final detailsBlock = ExcludeSemantics(
+ child: compact
+ ? Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ if (showRating)
+ detailLine(
+ hasRating ? item.ratingScore.toStringAsFixed(1) : ''),
+ if (showStatus) ...[
+ if (showRating) const SizedBox(height: 2),
+ detailLine(type.label, status: true),
+ ],
+ ],
+ )
+ : detailLine([
+ if (hasRating) '${item.ratingScore.toStringAsFixed(1)} 分',
+ if (showStatus) type.label,
+ ].join(' · ')),
+ );
+ final menu = _CollectEntryMenu(entry: entry, onChanged: onChangeType);
+ final footer = compact
+ ? Padding(
+ padding: const EdgeInsets.only(top: 8, bottom: 4),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8),
+ child: titleBlock,
+ ),
+ SizedBox(
+ height: _compactActionsHeight(constraints.maxWidth, scaler,
+ showRating: showRating, showStatus: showStatus),
+ child: _stackCompactActions(constraints.maxWidth, scaler,
+ showRating: showRating, showStatus: showStatus)
+ ? Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding:
+ const EdgeInsets.symmetric(horizontal: 8),
+ child: detailsBlock,
+ ),
+ Align(
+ alignment: AlignmentDirectional.centerEnd,
+ child: menu,
+ ),
+ ],
+ )
+ : Padding(
+ padding: const EdgeInsetsDirectional.only(start: 8),
+ child: Row(
+ children: [Expanded(child: detailsBlock), menu],
+ ),
+ ),
+ ),
+ ],
+ ),
+ )
+ : Padding(
+ padding: const EdgeInsetsDirectional.fromSTEB(12, 8, 0, 8),
+ child: Row(
+ children: [
+ Expanded(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ titleBlock,
+ if (showDetails) ...[
+ const SizedBox(height: 4),
+ detailsBlock,
+ ],
+ ],
+ ),
+ ),
+ menu,
+ ],
+ ),
+ );
+
+ return Material(
+ color: colors.surfaceContainerLow,
+ borderRadius: BorderRadius.circular(compact ? 16 : 20),
+ clipBehavior: Clip.antiAlias,
+ child: Semantics(
+ button: true,
+ label: [
+ title,
+ type.label,
+ if (year != null) '$year 年',
+ if (hasRating) '${item.ratingScore.toStringAsFixed(1)} 分',
+ ].join(','),
+ child: InkWell(
+ onTap: onOpen,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ ExcludeSemantics(
+ child: AspectRatio(
+ aspectRatio: _coverRatio,
+ child: _CollectCover(item: item),
+ ),
+ ),
+ Expanded(child: footer),
+ ],
+ ),
+ ),
+ ),
+ );
+ });
+ }
+}
+
+class _CollectListTile extends StatelessWidget {
+ const _CollectListTile({
+ super.key,
+ required this.entry,
+ required this.showRating,
+ required this.onOpen,
+ required this.onChangeType,
+ });
+
+ final CollectedBangumi entry;
+ final bool showRating;
+ 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 airDate = DateTime.tryParse(item.airDate);
final metadata = [
if (airDate != null) '${airDate.year} 年',
@@ -49,18 +259,12 @@ class _CollectLibraryCard extends StatelessWidget {
children: [
ExcludeSemantics(
child: IgnorePointer(
- child: Hero(
- tag: item.id,
- transitionOnUserGestures: true,
- child: ClipRRect(
+ child: SizedBox(
+ width: 80,
+ height: 120,
+ child: _CollectCover(
+ item: item,
borderRadius: BorderRadius.circular(16),
- child: NetworkImgLayer(
- src: item.images['large'] ??
- item.images['common'] ??
- '',
- width: 80,
- height: 120,
- ),
),
),
),
@@ -107,7 +311,11 @@ class _CollectLibraryCard extends StatelessWidget {
),
),
),
- _statusMenu(context, type, title),
+ _CollectEntryMenu(
+ entry: entry,
+ onChanged: onChangeType,
+ showStatusLabel: true,
+ ),
],
),
),
@@ -118,21 +326,58 @@ class _CollectLibraryCard extends StatelessWidget {
),
);
}
+}
+
+class _CollectCover extends StatelessWidget {
+ const _CollectCover({
+ required this.item,
+ this.borderRadius = BorderRadius.zero,
+ });
+ final BangumiItem item;
+ final BorderRadius borderRadius;
+
+ @override
+ Widget build(BuildContext context) => LayoutBuilder(
+ builder: (context, constraints) => Hero(
+ tag: item.id,
+ transitionOnUserGestures: true,
+ flightShuttleBuilder: NetworkImgLayer.heroFlightShuttleBuilder,
+ child: NetworkImgLayer(
+ src: item.images['large'] ?? item.images['common'] ?? '',
+ width: constraints.maxWidth,
+ height: constraints.maxHeight,
+ borderRadius: borderRadius,
+ ),
+ ),
+ );
+}
+
+class _CollectEntryMenu extends StatelessWidget {
+ const _CollectEntryMenu({
+ required this.entry,
+ required this.onChanged,
+ this.showStatusLabel = false,
+ });
+ final CollectedBangumi entry;
+ final ValueChanged<CollectType>? onChanged;
+ final bool showStatusLabel;
- Widget _statusMenu(BuildContext context, CollectType type, String title) {
+ @override
+ Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme;
+ final type = CollectType.fromValue(entry.type);
+ final title = CollectLibraryQuery.titleOf(entry);
const itemStyle = ButtonStyle(
visualDensity: VisualDensity.standard,
- padding: WidgetStatePropertyAll(EdgeInsets.symmetric(horizontal: 16)),
minimumSize: WidgetStatePropertyAll(Size(192, 48)),
+ padding: WidgetStatePropertyAll(EdgeInsets.symmetric(horizontal: 16)),
);
-
return MenuAnchor(
consumeOutsideTap: true,
style: MenuStyle(
- shape: WidgetStatePropertyAll(
- RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
- ),
+ shape: WidgetStatePropertyAll(RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(showStatusLabel ? 16 : 20),
+ )),
),
menuChildren: [
for (final status
@@ -141,38 +386,50 @@ class _CollectLibraryCard extends StatelessWidget {
style: itemStyle,
trailingIcon:
status == type ? const Icon(Icons.check_rounded) : null,
- onPressed: onChangeType == null || status == type
+ onPressed: onChanged == null || status == type
? null
- : () => onChangeType!(status),
+ : () => onChanged!(status),
child: Text(status.label),
),
const Divider(indent: 16, endIndent: 16),
MenuItemButton(
style: itemStyle,
- onPressed: onChangeType == null
- ? null
- : () => onChangeType!(CollectType.none),
+ onPressed:
+ onChanged == null ? null : () => onChanged!(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),
- ),
- ),
+ builder: (context, controller, child) {
+ final VoidCallback? toggle = onChanged == null
+ ? null
+ : () => controller.isOpen ? controller.close() : controller.open();
+ return showStatusLabel
+ ? 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: toggle,
+ iconAlignment: IconAlignment.end,
+ icon: const Icon(Icons.expand_more_rounded, size: 18),
+ label: Text(type.label),
+ ),
+ )
+ : IconButton(
+ tooltip: '管理《$title》 · ${type.label}',
+ onPressed: toggle,
+ style: IconButton.styleFrom(
+ foregroundColor: colors.onSurfaceVariant,
+ minimumSize: const Size(48, 48),
+ visualDensity: VisualDensity.standard,
+ ),
+ icon: const Icon(Icons.more_horiz_rounded, size: 20),
+ );
+ },
);
}
}
diff --git a/lib/pages/collect/collect_library_controls.dart b/lib/pages/collect/collect_library_controls.dart
new file mode 100644
index 00000000..55ad8f5f
--- /dev/null
+++ b/lib/pages/collect/collect_library_controls.dart
@@ -0,0 +1,274 @@
+part of 'collect_library_view.dart';
+
+const _collectCategories = <CollectType?>[
+ null,
+ CollectType.watching,
+ CollectType.planToWatch,
+ CollectType.watched,
+ CollectType.onHold,
+ CollectType.abandoned,
+];
+
+class _CollectCategoryPager extends StatefulWidget {
+ const _CollectCategoryPager({
+ required this.selectedIndex,
+ required this.onChanged,
+ required this.itemCount,
+ required this.itemBuilder,
+ });
+
+ final int selectedIndex;
+ final ValueChanged<int> onChanged;
+ final int itemCount;
+ final IndexedWidgetBuilder itemBuilder;
+
+ @override
+ State<_CollectCategoryPager> createState() => _CollectCategoryPagerState();
+}
+
+class _CollectCategoryPagerState extends State<_CollectCategoryPager> {
+ late final _controller = PageController(
+ initialPage: widget.selectedIndex,
+ keepPage: false,
+ );
+
+ @override
+ void didUpdateWidget(covariant _CollectCategoryPager oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (widget.selectedIndex != oldWidget.selectedIndex &&
+ _controller.hasClients &&
+ _controller.page?.round() != widget.selectedIndex) {
+ // Tab taps jump; swipe callbacks keep the current animation.
+ _controller.jumpToPage(widget.selectedIndex);
+ }
+ }
+
+ @override
+ void dispose() {
+ _controller.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) => PageView.builder(
+ key: const ValueKey('collect-category-pages'),
+ controller: _controller,
+ onPageChanged: widget.onChanged,
+ itemCount: widget.itemCount,
+ itemBuilder: widget.itemBuilder,
+ scrollBehavior:
+ ScrollConfiguration.of(context).copyWith(scrollbars: false),
+ );
+}
+
+class _CollectCategories extends StatefulWidget {
+ const _CollectCategories({
+ required this.selected,
+ required this.count,
+ required this.onSelected,
+ });
+
+ final CollectType? selected;
+ final int Function(CollectType?) count;
+ final ValueChanged<CollectType?> onSelected;
+
+ @override
+ State<_CollectCategories> createState() => _CollectCategoriesState();
+}
+
+class _CollectCategoriesState extends State<_CollectCategories> {
+ final _controller = ScrollController(keepScrollOffset: false);
+ final _keys = {for (final type in _collectCategories) type: GlobalKey()};
+
+ @override
+ void initState() {
+ super.initState();
+ _revealSelected();
+ }
+
+ @override
+ void didUpdateWidget(covariant _CollectCategories oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ _revealSelected();
+ }
+
+ void _revealSelected() {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted || !_controller.hasClients) return;
+ final target = _keys[widget.selected]?.currentContext?.findRenderObject();
+ if (target == null) return;
+ // Scroll only the tabs, never the enclosing collection viewport.
+ _controller.position.ensureVisible(
+ target,
+ alignment: 0.5,
+ duration: MediaQuery.disableAnimationsOf(context)
+ ? Duration.zero
+ : const Duration(milliseconds: 220),
+ curve: Curves.easeInOutCubicEmphasized,
+ );
+ });
+ }
+
+ @override
+ void dispose() {
+ _controller.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final colors = theme.colorScheme;
+ return SingleChildScrollView(
+ key: const ValueKey('collect-filter-strip'),
+ controller: _controller,
+ scrollDirection: Axis.horizontal,
+ child: Row(
+ spacing: 4,
+ children: [
+ for (final type in _collectCategories)
+ Semantics(
+ key: _keys[type],
+ selected: type == widget.selected,
+ inMutuallyExclusiveGroup: true,
+ button: true,
+ label: '${type?.label ?? '全部'},${widget.count(type)} 部',
+ excludeSemantics: true,
+ onTap: () => widget.onSelected(type),
+ child: TextButton(
+ key: ValueKey('collect-filter-${type?.value ?? 'all'}'),
+ onPressed: () => widget.onSelected(type),
+ style: TextButton.styleFrom(
+ minimumSize: const Size(64, 48),
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ backgroundColor: type == widget.selected
+ ? colors.primaryContainer
+ : Colors.transparent,
+ foregroundColor: type == widget.selected
+ ? colors.onPrimaryContainer
+ : colors.onSurfaceVariant,
+ textStyle: theme.textTheme.titleSmall?.copyWith(
+ fontWeight: type == widget.selected
+ ? FontWeight.w700
+ : FontWeight.w500,
+ ),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(24)),
+ ),
+ child: Text(type?.label ?? '全部'),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+class _CollectLayoutSwitch extends StatelessWidget {
+ const _CollectLayoutSwitch({required this.value, required this.onChanged});
+
+ final CollectLayout value;
+ final ValueChanged<CollectLayout> onChanged;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ return Row(
+ mainAxisSize: MainAxisSize.min,
+ spacing: 2,
+ children: [
+ for (final layout in [CollectLayout.cards, CollectLayout.list])
+ Semantics(
+ selected: value == layout,
+ inMutuallyExclusiveGroup: true,
+ child: IconButton.filledTonal(
+ tooltip: '${layout.label}布局',
+ isSelected: value == layout,
+ onPressed: () => onChanged(layout),
+ style: ButtonStyle(
+ minimumSize: const WidgetStatePropertyAll(Size(48, 48)),
+ visualDensity: VisualDensity.standard,
+ backgroundColor: WidgetStateProperty.resolveWith((states) =>
+ states.contains(WidgetState.selected)
+ ? colors.secondaryContainer
+ : colors.surfaceContainerLow),
+ foregroundColor: WidgetStateProperty.resolveWith((states) =>
+ states.contains(WidgetState.selected)
+ ? colors.onSecondaryContainer
+ : colors.onSurfaceVariant),
+ shape: WidgetStateProperty.resolveWith((states) =>
+ RoundedRectangleBorder(
+ borderRadius: states.contains(WidgetState.pressed)
+ ? BorderRadius.circular(12)
+ : states.contains(WidgetState.selected)
+ ? BorderRadius.circular(24)
+ : BorderRadiusDirectional.horizontal(
+ start: Radius.circular(
+ layout == CollectLayout.cards ? 24 : 8),
+ end: Radius.circular(
+ layout == CollectLayout.list ? 24 : 8),
+ ),
+ )),
+ animationDuration: MediaQuery.disableAnimationsOf(context)
+ ? Duration.zero
+ : const Duration(milliseconds: 200),
+ ),
+ icon: Icon(layout == CollectLayout.list
+ ? Icons.view_list_rounded
+ : Icons.grid_view_rounded),
+ ),
+ ),
+ ],
+ );
+ }
+}
+
+class _CollectSortMenu extends StatelessWidget {
+ const _CollectSortMenu({
+ required this.value,
+ required this.showLabel,
+ required this.onChanged,
+ });
+
+ final CollectSort value;
+ final bool showLabel;
+ final ValueChanged<CollectSort> onChanged;
+
+ @override
+ Widget build(BuildContext context) {
+ return MenuAnchor(
+ consumeOutsideTap: true,
+ menuChildren: [
+ for (final sort in CollectSort.values)
+ MenuItemButton(
+ trailingIcon:
+ value == sort ? const Icon(Icons.check_rounded) : null,
+ onPressed: () => onChanged(sort),
+ child: Text(sort.label),
+ ),
+ ],
+ builder: (context, controller, child) {
+ void toggle() =>
+ controller.isOpen ? controller.close() : controller.open();
+ return Tooltip(
+ message: '排序:${value.label}',
+ child: showLabel
+ ? TextButton.icon(
+ onPressed: toggle,
+ style: TextButton.styleFrom(
+ foregroundColor:
+ Theme.of(context).colorScheme.onSurfaceVariant,
+ minimumSize: const Size(48, 48),
+ ),
+ icon: const Icon(Icons.sort_rounded, size: 20),
+ label: Text(value.label),
+ )
+ : IconButton(
+ onPressed: toggle,
+ icon: const Icon(Icons.sort_rounded),
+ ),
+ );
+ },
+ );
+ }
+}
diff --git a/lib/pages/collect/collect_library_view.dart b/lib/pages/collect/collect_library_view.dart
index e7d207bc..5b0b8912 100644
--- a/lib/pages/collect/collect_library_view.dart
+++ b/lib/pages/collect/collect_library_view.dart
@@ -3,11 +3,13 @@ import 'package:flutter/services.dart';
import 'package:kazumi/bean/card/network_img_layer.dart';
import 'package:kazumi/bean/widget/empty_state_widget.dart';
import 'package:kazumi/modules/bangumi/bangumi_item.dart';
+import 'package:kazumi/modules/collect/collect_layout.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';
+part 'collect_library_controls.dart';
class CollectLibraryView extends StatefulWidget {
const CollectLibraryView({
@@ -17,6 +19,8 @@ class CollectLibraryView extends StatefulWidget {
required this.onOpen,
required this.onChangeType,
required this.canEdit,
+ required this.layout,
+ required this.onLayoutChanged,
});
final List<CollectedBangumi> entries;
@@ -24,6 +28,8 @@ class CollectLibraryView extends StatefulWidget {
final ValueChanged<BangumiItem> onOpen;
final void Function(BangumiItem, CollectType) onChangeType;
final bool Function(BangumiItem) canEdit;
+ final CollectLayout layout;
+ final ValueChanged<CollectLayout> onLayoutChanged;
@override
State<CollectLibraryView> createState() => _CollectLibraryViewState();
@@ -32,32 +38,27 @@ class CollectLibraryView extends StatefulWidget {
class _CollectLibraryViewState extends State<CollectLibraryView> {
final _searchController = TextEditingController();
final _searchFocus = FocusNode();
- final _categoryScrollController = ScrollController(keepScrollOffset: false);
- final _categoryKeys = {
- for (final type in _categories) type: GlobalKey(),
- };
+ final _libraryFocus = FocusNode();
final _scrollControllers = {
- for (final type in _categories) type: ScrollController(),
+ for (final type in _collectCategories) type: ScrollController(),
};
PageStorageBucket _resultsStorage = PageStorageBucket();
CollectType? _selectedType = CollectType.watching;
CollectSort _sort = CollectSort.recentlyChanged;
String _query = '';
+ bool _searchExpanded = false;
- static const _categories = <CollectType?>[
- null,
- CollectType.watching,
- CollectType.planToWatch,
- CollectType.watched,
- CollectType.onHold,
- CollectType.abandoned,
- ];
+ @override
+ void didUpdateWidget(covariant CollectLibraryView oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (oldWidget.layout != widget.layout) _resetResults();
+ }
@override
void dispose() {
_searchController.dispose();
_searchFocus.dispose();
- _categoryScrollController.dispose();
+ _libraryFocus.dispose();
for (final controller in _scrollControllers.values) {
controller.dispose();
}
@@ -65,7 +66,7 @@ class _CollectLibraryViewState extends State<CollectLibraryView> {
}
void _resetResults() {
- // Reset stored offsets for unmounted categories too.
+ // Unmounted categories must forget their previous layout's offsets too.
_resultsStorage = PageStorageBucket();
for (final controller in _scrollControllers.values) {
if (controller.hasClients) controller.jumpTo(0);
@@ -75,12 +76,20 @@ class _CollectLibraryViewState extends State<CollectLibraryView> {
void _focusSearch() {
final controller = _scrollControllers[_selectedType]!;
if (controller.hasClients) controller.jumpTo(0);
- _searchFocus.requestFocus();
+ setState(() => _searchExpanded = true);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _searchFocus.requestFocus();
+ });
}
- void _selectType(CollectType? type) {
- if (type == _selectedType) return;
- setState(() => _selectedType = type);
+ void _closeSearch() {
+ _libraryFocus.requestFocus();
+ _searchController.clear();
+ setState(() {
+ _searchExpanded = false;
+ _query = '';
+ _resetResults();
+ });
}
void _search(String value) {
@@ -90,15 +99,15 @@ class _CollectLibraryViewState extends State<CollectLibraryView> {
});
}
- void _clearSearch() {
- _searchController.clear();
- _search('');
+ void _selectType(CollectType? type) {
+ if (type == _selectedType) return;
+ _libraryFocus.requestFocus();
+ setState(() => _selectedType = type);
}
@override
Widget build(BuildContext context) {
final query = CollectLibraryQuery(widget.entries, _query);
- final textScale = MediaQuery.textScalerOf(context).scale(14) / 14;
final platform = Theme.of(context).platform;
final mobile =
platform == TargetPlatform.android || platform == TargetPlatform.iOS;
@@ -109,396 +118,291 @@ class _CollectLibraryViewState extends State<CollectLibraryView> {
_focusSearch,
const SingleActivator(LogicalKeyboardKey.keyF, meta: true):
_focusSearch,
- const SingleActivator(LogicalKeyboardKey.escape): () {
- _clearSearch();
- _searchFocus.unfocus();
- },
+ const SingleActivator(LogicalKeyboardKey.escape): _closeSearch,
},
child: Focus(
+ focusNode: _libraryFocus,
autofocus: true,
- child: PageStorage(
- bucket: _resultsStorage,
- child: LayoutBuilder(builder: (context, constraints) {
- final paged = mobile &&
- MediaQuery.orientationOf(context) == Orientation.portrait;
- final contentWidth = constraints.maxWidth.clamp(0.0, 1560.0);
- final inset = (constraints.maxWidth - contentWidth) / 2 +
- (constraints.maxWidth < 600 ? 16.0 : 24.0);
- if (paged) {
- return Padding(
- padding: EdgeInsets.symmetric(horizontal: inset),
- child: _pagedContent(query, textScale: textScale),
- );
- }
- final expanded = constraints.maxWidth >= 1000 && textScale <= 1.5;
- return Padding(
- padding: EdgeInsets.only(left: inset),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- if (expanded) ...[
- Padding(
- padding: const EdgeInsets.only(top: 8),
- child: _sidebar(query),
- ),
- const SizedBox(width: 28),
- ],
- Expanded(
- child: _scrollableContent(
- query,
- _selectedType,
- textScale: textScale,
- rightInset: inset,
- header: _header(query, expanded: expanded),
- ),
- ),
- ],
- ),
- );
- }),
- ),
- ),
- );
- }
-
- 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),
- ),
- ],
- ),
- ),
- ),
+ child: LayoutBuilder(builder: (context, constraints) {
+ final compact = constraints.maxWidth < 600;
+ final paged = mobile &&
+ MediaQuery.orientationOf(context) == Orientation.portrait &&
+ constraints.maxHeight > 320;
+ final width = constraints.maxWidth.clamp(0.0, 1560.0);
+ final inset =
+ (constraints.maxWidth - width) / 2 + (compact ? 16.0 : 32.0);
+ final header = _header(query, compact: compact);
+ return PageStorage(
+ bucket: _resultsStorage,
+ child: paged
+ ? Column(
+ children: [
+ Padding(
+ padding: EdgeInsets.symmetric(horizontal: inset),
+ child: header,
+ ),
+ Expanded(
+ child: _CollectCategoryPager(
+ selectedIndex:
+ _collectCategories.indexOf(_selectedType),
+ onChanged: (index) =>
+ _selectType(_collectCategories[index]),
+ itemCount: _collectCategories.length,
+ itemBuilder: (context, index) => HeroMode(
+ enabled: _collectCategories[index] == _selectedType,
+ child: _results(query, _collectCategories[index],
+ inset: inset),
+ ),
+ ),
+ ),
+ ],
+ )
+ : _results(query, _selectedType, inset: inset, header: header),
+ );
+ }),
),
);
}
- 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) {
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (!mounted || !_categoryScrollController.hasClients) return;
- final target =
- _categoryKeys[_selectedType]?.currentContext?.findRenderObject();
- if (target == null) return;
- // Avoid scrolling the enclosing results list.
- _categoryScrollController.position.ensureVisible(
- target,
- alignment: 0.5,
- duration: MediaQuery.disableAnimationsOf(context)
- ? Duration.zero
- : const Duration(milliseconds: 200),
- curve: Curves.easeOutCubic,
- );
- });
- return Padding(
- padding: const EdgeInsets.only(top: 16),
- child: SingleChildScrollView(
- key: const ValueKey('collect-filter-strip'),
- controller: _categoryScrollController,
- scrollDirection: Axis.horizontal,
- child: Row(
+ Widget _header(CollectLibraryQuery query, {required bool compact}) {
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
children: [
- for (final type in _categories)
+ Expanded(
+ child: _CollectCategories(
+ selected: _selectedType,
+ count: query.count,
+ onSelected: _selectType,
+ ),
+ ),
+ if (!compact)
Padding(
- key: _categoryKeys[type],
- padding: const EdgeInsets.only(right: 8),
- child: _category(type, query),
+ padding: const EdgeInsetsDirectional.only(start: 16),
+ child: Text(
+ '${query.count(_selectedType)} 部',
+ style: Theme.of(context).textTheme.labelLarge?.copyWith(
+ color: Theme.of(context).colorScheme.onSurfaceVariant,
+ ),
+ ),
),
],
),
- ),
- );
- }
-
- Widget _header(CollectLibraryQuery query, {required bool expanded}) => Column(
- children: [
- Padding(
- padding: const EdgeInsets.only(top: 8),
- child: Row(
- children: [
- Expanded(child: _searchBar()),
- const SizedBox(width: 8),
- _sortMenu(expanded: expanded),
- ],
+ const SizedBox(height: 12),
+ Row(
+ children: [
+ if (!compact)
+ Expanded(
+ child: Align(
+ alignment: AlignmentDirectional.centerStart,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 360),
+ child: _searchBar(),
+ ),
+ ),
+ )
+ else
+ Expanded(
+ child: Text(
+ '${query.count(_selectedType)} 部',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: Theme.of(context).textTheme.labelLarge?.copyWith(
+ color: Theme.of(context).colorScheme.onSurfaceVariant,
+ ),
+ ),
+ ),
+ const SizedBox(width: 12),
+ _CollectSortMenu(
+ value: _sort,
+ showLabel: !compact,
+ onChanged: (value) => setState(() {
+ _sort = value;
+ _resetResults();
+ }),
),
- ),
- if (!expanded) _categoryStrip(query),
- const SizedBox(height: 16),
- ],
- );
-
- Widget _pagedContent(CollectLibraryQuery query, {required double textScale}) {
- return Column(
- children: [
- _header(query, expanded: false),
- Expanded(
- child: _CollectCategoryPager(
- selectedIndex: _categories.indexOf(_selectedType),
- onChanged: (index) {
- _searchFocus.unfocus();
- _selectType(_categories[index]);
- },
- itemCount: _categories.length,
- itemBuilder: (context, index) => HeroMode(
- // Avoid duplicate Hero tags across collection categories.
- enabled: _categories[index] == _selectedType,
- child: _scrollableContent(
- query,
- _categories[index],
- textScale: textScale,
- rightInset: 0,
+ if (compact)
+ IconButton(
+ tooltip: _searchExpanded ? '收起搜索' : '搜索收藏',
+ isSelected: _searchExpanded,
+ selectedIcon: const Icon(Icons.search_off_rounded),
+ icon: const Icon(Icons.search_rounded),
+ onPressed: _searchExpanded ? _closeSearch : _focusSearch,
),
+ const SizedBox(width: 8),
+ _CollectLayoutSwitch(
+ value: widget.layout,
+ onChanged: widget.onLayoutChanged,
),
- ),
+ ],
),
+ if (compact && _searchExpanded) ...[
+ const SizedBox(height: 12),
+ _searchBar(),
+ ],
+ const SizedBox(height: 20),
],
);
}
- Widget _scrollableContent(
- CollectLibraryQuery query,
- CollectType? type, {
- required double textScale,
- required double rightInset,
- Widget? header,
- }) {
- final entries = query.results(type, _sort);
- final scrollController = _scrollControllers[type]!;
- return LayoutBuilder(builder: (context, constraints) {
- final contentWidth = constraints.maxWidth - rightInset;
- final columns = contentWidth >= 840 && textScale <= 1.3 ? 2 : 1;
- return CustomScrollView(
- key: PageStorageKey('collect-results-${type?.value ?? 'all'}'),
- controller: scrollController,
- keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
- slivers: [
- if (header != null) SliverToBoxAdapter(child: header),
- if (entries.isEmpty)
- SliverFillRemaining(
- hasScrollBody: false,
- child: _emptyState(query.count(null), type: type),
- )
- 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),
- 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 _searchBar() => Semantics(
+ label: '搜索收藏',
+ child: SearchBar(
+ controller: _searchController,
+ focusNode: _searchFocus,
+ leading: const Icon(Icons.search_rounded, size: 22),
+ trailing: [
+ if (_query.isNotEmpty)
+ IconButton(
+ tooltip: '清除搜索',
+ onPressed: () {
+ _searchController.clear();
+ _search('');
},
+ icon: const Icon(Icons.close_rounded),
),
- ),
- ]
- .map((sliver) => SliverPadding(
- padding: EdgeInsets.only(right: rightInset),
- sliver: sliver,
- ))
- .toList(),
- );
- });
- }
-
- Widget _card(CollectedBangumi entry) => _CollectLibraryCard(
- key: ValueKey('collect-${entry.bangumiItem.id}'),
- entry: entry,
- showRating: widget.showRating,
- onOpen: () => widget.onOpen(entry.bangumiItem),
- onChangeType: widget.canEdit(entry.bangumiItem)
- ? (type) => widget.onChangeType(entry.bangumiItem, type)
- : null,
+ ],
+ elevation: const WidgetStatePropertyAll(0),
+ backgroundColor: WidgetStatePropertyAll(
+ Theme.of(context).colorScheme.surfaceContainerLow),
+ padding: const WidgetStatePropertyAll(
+ EdgeInsets.symmetric(horizontal: 16)),
+ constraints: const BoxConstraints(minHeight: 48),
+ onChanged: _search,
+ onSubmitted: (_) => _libraryFocus.requestFocus(),
+ ),
);
- 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,
- liveRegion: 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 _results(CollectLibraryQuery query, CollectType? type,
+ {required double inset, Widget? header}) {
+ final entries = query.results(type, _sort);
+ return LayoutBuilder(builder: (context, constraints) {
+ final contentWidth = constraints.maxWidth - inset * 2;
+ // Keep the viewport full-width; only the slivers receive content insets.
+ return ScrollbarTheme(
+ data: ScrollbarTheme.of(context).copyWith(crossAxisMargin: 0),
+ child: CustomScrollView(
+ key: PageStorageKey('collect-results-${type?.value ?? 'all'}'),
+ controller: _scrollControllers[type],
+ semanticChildCount: entries.length,
+ keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
+ slivers: [
+ if (header != null)
+ SliverPadding(
+ padding: EdgeInsets.symmetric(horizontal: inset),
+ sliver: SliverToBoxAdapter(child: header),
+ ),
+ if (entries.isEmpty)
+ SliverFillRemaining(
+ hasScrollBody: false,
+ child: Padding(
+ padding: EdgeInsets.symmetric(horizontal: inset),
+ child: _emptyState(query.count(null), type: type),
),
+ )
+ else
+ SliverPadding(
+ padding: EdgeInsets.fromLTRB(
+ inset, 0, inset, 24 + MediaQuery.paddingOf(context).bottom),
+ sliver: widget.layout == CollectLayout.cards
+ ? _grid(entries, contentWidth, type: type)
+ : _list(entries, contentWidth),
),
- ),
- ),
+ ],
),
- ),
- );
+ );
+ });
}
- Widget _sortMenu({required bool expanded}) {
- final style = ButtonStyle(
- foregroundColor: WidgetStatePropertyAll(
- Theme.of(context).colorScheme.onSurfaceVariant),
- minimumSize: const WidgetStatePropertyAll(Size(48, 48)),
- );
- return MenuAnchor(
- consumeOutsideTap: true,
- menuChildren: [
- for (final sort in CollectSort.values)
- MenuItemButton(
- trailingIcon:
- _sort == sort ? const Icon(Icons.check_rounded) : null,
- onPressed: () {
- setState(() {
- _sort = sort;
- _resetResults();
- });
- },
- child: Text(sort.label),
+ Widget _list(List<CollectedBangumi> entries, double contentWidth) {
+ const spacing = 12.0;
+ final textScale = (MediaQuery.textScalerOf(context).scale(14) / 14)
+ .clamp(1.0, double.infinity);
+ final minWidth = 300 + 160 * (textScale - 1);
+ final preferredWidth = 400 + 160 * (textScale - 1);
+ final maxColumns =
+ ((contentWidth + spacing) / (minWidth + spacing)).floor().clamp(1, 12);
+ final columns = ((contentWidth + spacing) / (preferredWidth + spacing))
+ .ceil()
+ .clamp(1, maxColumns);
+
+ Widget tile(int index) => IndexedSemantics(
+ index: index,
+ child: _CollectListTile(
+ key: ValueKey('collect-${entries[index].bangumiItem.id}'),
+ entry: entries[index],
+ showRating: widget.showRating,
+ onOpen: () => widget.onOpen(entries[index].bangumiItem),
+ onChangeType: _changeTypeFor(entries[index]),
),
- ],
- builder: (context, controller, child) {
- void toggleMenu() =>
- controller.isOpen ? controller.close() : controller.open();
+ );
- return Tooltip(
- message: '排序:${_sort.label}',
- child: expanded
- ? TextButton.icon(
- style: style,
- onPressed: toggleMenu,
- icon: const Icon(Icons.sort_rounded, size: 20),
- label: Text(_sort.label),
- )
- : IconButton(
- style: style,
- onPressed: toggleMenu,
- icon: const Icon(Icons.sort_rounded, size: 20),
+ return SliverList.builder(
+ itemCount: (entries.length + columns - 1) ~/ columns,
+ addSemanticIndexes: false,
+ itemBuilder: (context, row) {
+ final first = row * columns;
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 10),
+ child: columns == 1
+ ? tile(first)
+ : IntrinsicHeight(
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ spacing: spacing,
+ children: [
+ for (var column = 0; column < columns; column++)
+ Expanded(
+ child: first + column < entries.length
+ ? tile(first + column)
+ : const SizedBox(),
+ ),
+ ],
+ ),
),
);
},
);
}
+ ValueChanged<CollectType>? _changeTypeFor(CollectedBangumi entry) =>
+ widget.canEdit(entry.bangumiItem)
+ ? (type) => widget.onChangeType(entry.bangumiItem, type)
+ : null;
+
+ Widget _grid(List<CollectedBangumi> entries, double contentWidth,
+ {required CollectType? type}) {
+ final portrait = MediaQuery.orientationOf(context) == Orientation.portrait;
+ final spacing = portrait ? (contentWidth < 600 ? 8.0 : 12.0) : 16.0;
+ final scaler = MediaQuery.textScalerOf(context);
+ final textScale = (scaler.scale(14) / 14).clamp(1.0, double.infinity);
+ final minWidth =
+ (contentWidth < 600 ? 136.0 : 172.0) + 32 * (textScale - 1);
+ final columns = portrait
+ ? 3
+ : ((contentWidth + spacing) / (minWidth + spacing)).floor().clamp(1, 6);
+ final width = (contentWidth - spacing * (columns - 1)) / columns;
+ return SliverGrid.builder(
+ gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
+ crossAxisCount: columns,
+ crossAxisSpacing: spacing,
+ mainAxisSpacing: portrait ? 12 : spacing,
+ mainAxisExtent: _CollectPosterCard.extent(width, scaler,
+ showRating: widget.showRating, showStatus: type == null),
+ ),
+ itemCount: entries.length,
+ itemBuilder: (context, index) => _CollectPosterCard(
+ key: ValueKey('collect-${entries[index].bangumiItem.id}'),
+ entry: entries[index],
+ showRating: widget.showRating,
+ showStatus: type == null,
+ onOpen: () => widget.onOpen(entries[index].bangumiItem),
+ onChangeType: _changeTypeFor(entries[index]),
+ ),
+ );
+ }
+
Widget _emptyState(int matchCount, {required CollectType? type}) {
final searching = _query.trim().isNotEmpty;
final String title;
@@ -523,55 +427,3 @@ class _CollectLibraryViewState extends State<CollectLibraryView> {
);
}
}
-
-class _CollectCategoryPager extends StatefulWidget {
- const _CollectCategoryPager({
- required this.selectedIndex,
- required this.onChanged,
- required this.itemCount,
- required this.itemBuilder,
- });
-
- final int selectedIndex;
- final ValueChanged<int> onChanged;
- final int itemCount;
- final IndexedWidgetBuilder itemBuilder;
-
- @override
- State<_CollectCategoryPager> createState() => _CollectCategoryPagerState();
-}
-
-class _CollectCategoryPagerState extends State<_CollectCategoryPager> {
- late final _controller = PageController(
- initialPage: widget.selectedIndex,
- keepPage: false,
- );
-
- @override
- void didUpdateWidget(covariant _CollectCategoryPager oldWidget) {
- super.didUpdateWidget(oldWidget);
- if (widget.selectedIndex != oldWidget.selectedIndex &&
- _controller.hasClients &&
- _controller.page?.round() != widget.selectedIndex) {
- // Tab taps jump; swipe callbacks keep the current animation.
- _controller.jumpToPage(widget.selectedIndex);
- }
- }
-
- @override
- void dispose() {
- _controller.dispose();
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) => PageView.builder(
- key: const ValueKey('collect-category-pages'),
- controller: _controller,
- onPageChanged: widget.onChanged,
- itemCount: widget.itemCount,
- itemBuilder: widget.itemBuilder,
- scrollBehavior:
- ScrollConfiguration.of(context).copyWith(scrollbars: false),
- );
-}
diff --git a/lib/pages/collect/collect_page.dart b/lib/pages/collect/collect_page.dart
index 8c28ce32..2383b2f4 100644
--- a/lib/pages/collect/collect_page.dart
+++ b/lib/pages/collect/collect_page.dart
@@ -9,6 +9,7 @@ import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:kazumi/bean/widget/state_presentation.dart';
import 'package:kazumi/modules/bangumi/bangumi_item.dart';
import 'package:kazumi/modules/bangumi/sync_priority.dart';
+import 'package:kazumi/modules/collect/collect_layout.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';
@@ -32,6 +33,7 @@ class _CollectPageState extends State<CollectPage> with KazumiDialogOwner {
CollectController get collectController => widget.controller;
bool get _syncDialogOpen => dialogs.isRunning;
final Set<int> _pendingIds = {};
+ late CollectLayout _layout;
Future<bool> _syncStep(
CollectSyncStep step, {
@@ -54,9 +56,18 @@ class _CollectPageState extends State<CollectPage> with KazumiDialogOwner {
@override
void initState() {
super.initState();
+ // Read once; page switches never change the saved default.
+ _layout = CollectLayout.fromValue(
+ GStorage.getSetting(SettingsKeys.defaultCollectLayout),
+ );
collectController.loadCollectibles();
}
+ void _changeLayout(CollectLayout layout) {
+ if (_layout == layout) return;
+ setState(() => _layout = layout);
+ }
+
Future<void> _changeType(BangumiItem item, CollectType type) async {
if (_syncDialogOpen || _pendingIds.contains(item.id)) return;
setState(() => _pendingIds.add(item.id));
@@ -129,6 +140,8 @@ class _CollectPageState extends State<CollectPage> with KazumiDialogOwner {
builder: (context) => CollectLibraryView(
entries: collectController.collectibles.toList(),
showRating: GStorage.getSetting(SettingsKeys.showRating),
+ layout: _layout,
+ onLayoutChanged: _changeLayout,
canEdit: (item) =>
!_syncDialogOpen && !_pendingIds.contains(item.id),
onOpen: (item) => context.pushNamed('/info/', arguments: item),
diff --git a/lib/pages/settings/interface_settings.dart b/lib/pages/settings/interface_settings.dart
index 12d9f8cd..ced10267 100644
--- a/lib/pages/settings/interface_settings.dart
+++ b/lib/pages/settings/interface_settings.dart
@@ -1,6 +1,8 @@
-import 'package:kazumi/bean/settings/settings_list.dart';
import 'package:flutter/material.dart';
+import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:kazumi/bean/settings/settings_detail_scaffold.dart';
+import 'package:kazumi/bean/settings/settings_list.dart';
+import 'package:kazumi/modules/collect/collect_layout.dart';
import 'package:kazumi/services/storage/storage.dart';
import 'package:kazumi/utils/device.dart';
@@ -14,6 +16,9 @@ class InterfaceSettingsPage extends StatefulWidget {
class _InterfaceSettingsPageState extends State<InterfaceSettingsPage> {
late bool showRating;
late String defaultPage;
+ late CollectLayout _defaultCollectLayout;
+ bool _savingCollectLayout = false;
+ final _collectLayoutMenuController = MenuController();
int _exitBehavior = GStorage.getSetting(SettingsKeys.exitBehavior);
static const _exitBehaviorTitles = ['退出 Kazumi', '最小化至托盘', '每次都询问'];
final MenuController defaultPageMenuController = MenuController();
@@ -30,6 +35,9 @@ class _InterfaceSettingsPageState extends State<InterfaceSettingsPage> {
super.initState();
showRating = GStorage.getSetting(SettingsKeys.showRating);
defaultPage = GStorage.getSetting(SettingsKeys.defaultStartupPage);
+ _defaultCollectLayout = CollectLayout.fromValue(
+ GStorage.getSetting(SettingsKeys.defaultCollectLayout),
+ );
}
void updateDefaultPage(String page) {
@@ -39,6 +47,40 @@ class _InterfaceSettingsPageState extends State<InterfaceSettingsPage> {
});
}
+ Future<void> _updateDefaultCollectLayout(CollectLayout layout) async {
+ if (_savingCollectLayout || layout == _defaultCollectLayout) return;
+ setState(() => _savingCollectLayout = true);
+ try {
+ await GStorage.putSetting(SettingsKeys.defaultCollectLayout, layout.name);
+ if (mounted) setState(() => _defaultCollectLayout = layout);
+ } catch (_) {
+ if (mounted) KazumiDialog.showToast(message: '追番默认布局保存失败,请重试');
+ } finally {
+ if (mounted) setState(() => _savingCollectLayout = false);
+ }
+ }
+
+ Widget _menuItem({
+ required String label,
+ required bool selected,
+ required VoidCallback? onPressed,
+ }) =>
+ MenuItemButton(
+ requestFocusOnHover: false,
+ onPressed: onPressed,
+ child: Container(
+ height: 48,
+ constraints: const BoxConstraints(minWidth: 112),
+ alignment: Alignment.centerLeft,
+ child: Text(
+ label,
+ style: TextStyle(
+ color: selected ? Theme.of(context).colorScheme.primary : null,
+ ),
+ ),
+ ),
+ );
+
@override
Widget build(BuildContext context) {
return SettingsDetailScaffold(
@@ -67,30 +109,40 @@ class _InterfaceSettingsPageState extends State<InterfaceSettingsPage> {
},
menuChildren: [
for (final entry in defaultPageMap.entries)
- MenuItemButton(
- requestFocusOnHover: false,
+ _menuItem(
+ label: entry.value,
+ selected: entry.key == defaultPage,
onPressed: () => updateDefaultPage(entry.key),
- child: Container(
- height: 48,
- constraints: BoxConstraints(minWidth: 112),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Text(
- entry.value,
- style: TextStyle(
- color: entry.key == defaultPage
- ? Theme.of(context).colorScheme.primary
- : null,
- ),
- ),
- ),
- ),
),
],
),
),
]),
SettingsSection(title: Text('展示信息'), tiles: [
+ SettingsTile(
+ leading: Icons.view_agenda_rounded,
+ title: const Text('追番默认布局'),
+ description: const Text('下次打开追番页时使用,页面内切换不会改变此设置'),
+ enabled: !_savingCollectLayout,
+ onPressed: (_) => _collectLayoutMenuController.isOpen
+ ? _collectLayoutMenuController.close()
+ : _collectLayoutMenuController.open(),
+ value: MenuAnchor(
+ controller: _collectLayoutMenuController,
+ consumeOutsideTap: true,
+ menuChildren: [
+ for (final layout in CollectLayout.values)
+ _menuItem(
+ label: layout.label,
+ selected: layout == _defaultCollectLayout,
+ onPressed: _savingCollectLayout
+ ? null
+ : () => _updateDefaultCollectLayout(layout),
+ ),
+ ],
+ builder: (_, __, ___) => Text(_defaultCollectLayout.label),
+ ),
+ ),
SettingsTile.switchTile(
leading: Icons.star_rounded,
onToggle: (value) async {
diff --git a/lib/services/storage/settings_keys.dart b/lib/services/storage/settings_keys.dart
index acdbcd38..755b617c 100644
--- a/lib/services/storage/settings_keys.dart
+++ b/lib/services/storage/settings_keys.dart
@@ -449,10 +449,9 @@ class SettingsKeys {
true,
group: SettingGroup.interface,
);
- // Retained for legacy settings compatibility; no longer controls the UI.
- static const showAnimeCounter = SettingKey<bool>(
- _SettingBoxKey.showAnimeCounter,
- false,
+ static const defaultCollectLayout = SettingKey<String>(
+ 'defaultCollectLayout',
+ 'list',
group: SettingGroup.interface,
);
static const downloadParallelEpisodes = SettingKey<int>(
@@ -625,7 +624,7 @@ class SettingsKeys {
proxyUrl,
proxyTestUrl,
showRating,
- showAnimeCounter,
+ defaultCollectLayout,
downloadParallelEpisodes,
downloadParallelSegments,
downloadDanmaku,
@@ -734,7 +733,6 @@ class _SettingBoxKey {
proxyUrl = 'proxyUrl',
proxyTestUrl = 'proxyTestUrl',
showRating = 'showRating',
- showAnimeCounter = 'showAnimeCounter',
downloadParallelEpisodes = 'downloadParallelEpisodes',
downloadParallelSegments = 'downloadParallelSegments',
downloadDanmaku = 'downloadDanmaku',