Skip to content

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

feat(ui): redesign timeline and simplify collection empty states

Predidit02f4b3071237
diff --git a/lib/bean/card/bangumi_timeline_card.dart b/lib/bean/card/bangumi_timeline_card.dart
index febfbc84..8973f9c6 100644
--- a/lib/bean/card/bangumi_timeline_card.dart
+++ b/lib/bean/card/bangumi_timeline_card.dart
@@ -1,80 +1,136 @@
import 'package:flutter/material.dart';
-import 'package:flutter_modular/flutter_modular.dart';
-import 'package:kazumi/modules/bangumi/bangumi_item.dart';
import 'package:kazumi/bean/card/network_img_layer.dart';
-import 'package:kazumi/utils/device.dart';
+import 'package:kazumi/modules/bangumi/bangumi_item.dart';
-/// 时间线番剧卡片
class BangumiTimelineCard extends StatelessWidget {
const BangumiTimelineCard({
super.key,
required this.bangumiItem,
required this.showRating,
- this.onTap,
- this.cardHeight = 120,
- this.cardWidth,
- this.enableHero = true,
+ required this.onTap,
+ this.isWatching = false,
+ this.compact = false,
});
final BangumiItem bangumiItem;
final bool showRating;
- final VoidCallback? onTap;
- final bool enableHero;
- final double cardHeight;
- final double? cardWidth;
+ final bool isWatching;
+ final bool compact;
+ final VoidCallback onTap;
+
+ static final _episodePattern =
+ RegExp(r'^\s*([1-9]\d*)\s*[话話集](?=\s*(?:[//]|$))');
+
+ static double heightFor(TextScaler scaler, {bool compact = false}) =>
+ (compact ? 48 : 64) +
+ scaler.scale(22) * 2 +
+ scaler.scale(18) +
+ scaler.scale(20);
+
+ String _supportingText(String title) {
+ // Calendar subjects provide episodes in `info`, but no separate air date.
+ final episodes = _episodePattern.firstMatch(bangumiItem.info);
+ final metadata = <String>[
+ if (episodes != null) '${episodes.group(1)} 话',
+ ...(bangumiItem.metaTags.isNotEmpty
+ ? bangumiItem.metaTags
+ : bangumiItem.tags.map((tag) => tag.name))
+ .map((name) => name.trim())
+ .where((name) => name.isNotEmpty)
+ .toSet(),
+ ];
+ if (metadata.isNotEmpty) return metadata.take(3).join(' · ');
+ final originalName = bangumiItem.name.trim();
+ return originalName != title ? originalName : '';
+ }
@override
Widget build(BuildContext context) {
- final desktopLayout = isDesktop();
- final tabletLayout = isTablet();
final theme = Theme.of(context);
- final textScaler = MediaQuery.textScalerOf(context);
- final colorScheme = theme.colorScheme;
- const double borderRadius = 16;
- const double horizontalPadding = 12;
- const double verticalPadding = 10;
- final double contentHeight = cardHeight > verticalPadding * 2
- ? cardHeight - (verticalPadding * 2)
- : cardHeight;
- final double imageWidth = contentHeight * 0.7;
+ final colors = theme.colorScheme;
+ final translatedName = bangumiItem.nameCn.trim();
+ final title =
+ translatedName.isNotEmpty ? translatedName : bangumiItem.name.trim();
+ final supportingText = _supportingText(title);
+ final radius = BorderRadius.all(Radius.circular(compact ? 20 : 24));
- return Card(
- elevation: 0,
- margin: const EdgeInsets.symmetric(vertical: 4),
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(borderRadius),
- ),
- clipBehavior: Clip.antiAlias,
- color: colorScheme.surfaceContainerLow,
- child: InkWell(
- borderRadius: BorderRadius.circular(borderRadius),
- onTap: onTap ??
- () {
- context.pushNamed('/info/', arguments: bangumiItem);
- },
- child: SizedBox(
- height: cardHeight,
- width: cardWidth,
- child: Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: horizontalPadding,
- vertical: verticalPadding,
- ),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- buildImage(
- context,
- bangumiItem.images['large'] ?? '',
- imageWidth,
- contentHeight,
- ),
- const SizedBox(width: 12),
- Expanded(
- child: buildInfo(
- context, textScaler, desktopLayout, tabletLayout),
- ),
- ],
+ return Semantics(
+ button: true,
+ child: Card(
+ elevation: 0,
+ margin: EdgeInsets.zero,
+ color: colors.surfaceContainerLow,
+ shape: RoundedRectangleBorder(borderRadius: radius),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ onTap: onTap,
+ child: SizedBox(
+ height:
+ heightFor(MediaQuery.textScalerOf(context), compact: compact),
+ child: Padding(
+ padding: const EdgeInsets.all(12),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ _buildCover(context),
+ SizedBox(width: compact ? 12 : 16),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ title,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: theme.textTheme.titleMedium?.copyWith(
+ color: colors.onSurface,
+ fontWeight: FontWeight.w600,
+ height: 1.375,
+ ),
+ ),
+ const Spacer(),
+ if (supportingText.isNotEmpty) ...[
+ Text(
+ supportingText,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: theme.textTheme.bodySmall?.copyWith(
+ color: colors.onSurfaceVariant,
+ ),
+ ),
+ const SizedBox(height: 8),
+ ],
+ Row(
+ children: [
+ if (showRating)
+ Expanded(
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: _buildRating(context),
+ ),
+ )
+ else
+ const Spacer(),
+ if (isWatching) ...[
+ if (showRating) const SizedBox(width: 8),
+ Tooltip(
+ message: '正在追',
+ child: Icon(Icons.bookmark_rounded,
+ size: 20,
+ color: colors.primary,
+ semanticLabel: '正在追'),
+ ),
+ ],
+ const SizedBox(width: 8),
+ Icon(Icons.chevron_right_rounded,
+ size: 20, color: colors.onSurfaceVariant),
+ ],
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
),
),
),
@@ -82,143 +138,71 @@ class BangumiTimelineCard extends StatelessWidget {
);
}
- Widget buildImage(
- BuildContext context, String imageUrl, double width, double height) {
- final borderRadius = BorderRadius.circular(12);
- Widget img = NetworkImgLayer(
- src: imageUrl,
- width: width,
- height: height,
+ Widget _buildCover(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ final imageUrl = bangumiItem.images['large'] ?? '';
+ final width = compact ? 68.0 : 80.0;
+ final height = compact ? 96.0 : 112.0;
+ final cover = ClipRRect(
+ borderRadius: BorderRadius.circular(16),
+ child: imageUrl.isEmpty
+ ? ColoredBox(
+ color: colors.surfaceContainerHighest,
+ child: SizedBox(
+ width: width,
+ height: height,
+ child:
+ Icon(Icons.movie_outlined, color: colors.onSurfaceVariant),
+ ),
+ )
+ : NetworkImgLayer(src: imageUrl, width: width, height: height),
);
- if (enableHero) {
- img = Hero(
+ return ExcludeSemantics(
+ child: Hero(
tag: bangumiItem.id,
transitionOnUserGestures: true,
- child: ClipRRect(
- borderRadius: borderRadius,
- child: img,
- ),
- );
- } else {
- img = ClipRRect(
- borderRadius: borderRadius,
- child: img,
- );
- }
- return img;
+ child: cover,
+ ),
+ );
}
- Widget buildInfo(BuildContext context, TextScaler textScaler, bool isDesktop,
- bool isTablet) {
+ Widget _buildRating(BuildContext context) {
final theme = Theme.of(context);
- final colorScheme = theme.colorScheme;
- final title =
- bangumiItem.nameCn.isNotEmpty ? bangumiItem.nameCn : bangumiItem.name;
- final supportingText = bangumiItem.info.trim().isNotEmpty
- ? bangumiItem.info.trim()
- : bangumiItem.summary.trim();
- final bool useWideLayout = isDesktop || isTablet;
- final int supportingLines = useWideLayout ? 3 : 2;
- final nameStyle = theme.textTheme.titleSmall?.copyWith(
- color: colorScheme.onSurface,
- fontWeight: FontWeight.w600,
- height: 1.2,
- );
- final subStyle = theme.textTheme.bodySmall?.copyWith(
- color: colorScheme.onSurfaceVariant,
- height: 1.2,
- );
- return Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- title,
- style: nameStyle,
- maxLines: useWideLayout ? 2 : 1,
+ final colors = theme.colorScheme;
+ if (bangumiItem.ratingScore <= 0) {
+ return Text('暂无评分',
+ maxLines: 1,
overflow: TextOverflow.ellipsis,
- textScaler:
- textScaler.clamp(maxScaleFactor: useWideLayout ? 1.2 : 1.1),
+ style: theme.textTheme.labelMedium
+ ?.copyWith(color: colors.onSurfaceVariant));
+ }
+ final score = bangumiItem.ratingScore.toStringAsFixed(1);
+ return Semantics(
+ label: '评分 $score',
+ excludeSemantics: true,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
+ decoration: BoxDecoration(
+ color: colors.secondaryContainer,
+ borderRadius: BorderRadius.circular(8),
),
- Expanded(
- child: Padding(
- padding: EdgeInsets.only(top: supportingText.isNotEmpty ? 6 : 0),
- child: supportingText.isNotEmpty
- ? Text(
- supportingText,
- style: subStyle,
- maxLines: supportingLines,
- overflow: TextOverflow.ellipsis,
- textScaler: textScaler.clamp(maxScaleFactor: 1.0),
- )
- : const SizedBox.shrink(),
- ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.star_rounded,
+ size: 14, color: colors.onSecondaryContainer),
+ const SizedBox(width: 4),
+ Flexible(
+ child: Text(score,
+ maxLines: 1,
+ style: theme.textTheme.labelMedium?.copyWith(
+ color: colors.onSecondaryContainer,
+ fontWeight: FontWeight.w700,
+ )),
+ ),
+ ],
),
- const SizedBox(height: 8),
- buildFooter(context),
- ],
- );
- }
-
- Widget buildFooter(BuildContext context) {
- final theme = Theme.of(context);
- final colorScheme = theme.colorScheme;
- final metricStyle = theme.textTheme.labelMedium?.copyWith(
- color: colorScheme.onSurface,
- fontWeight: FontWeight.w600,
- );
- final showScore = showRating ? bangumiItem.ratingScore > 0 : true;
- final showRank = showRating ? bangumiItem.rank > 0 : true;
- final showVotes = showRating ? bangumiItem.votes > 0 : true;
- final rankText = showRating ? '#${bangumiItem.rank}' : '#***';
- final votesText = showRating ? bangumiItem.votes.toString() : '***';
-
- return Wrap(
- spacing: 8,
- runSpacing: 4,
- children: [
- if (showScore)
- buildMetric(
- context,
- icon: Icons.star_rounded,
- iconColor: colorScheme.primary,
- label:
- showRating ? bangumiItem.ratingScore.toStringAsFixed(1) : '***',
- textStyle: metricStyle,
- ),
- if (showRank)
- buildMetric(
- context,
- icon: Icons.leaderboard_outlined,
- iconColor: colorScheme.secondary,
- label: rankText,
- textStyle: metricStyle,
- ),
- if (showVotes)
- buildMetric(
- context,
- icon: Icons.how_to_vote_outlined,
- iconColor: colorScheme.onSurfaceVariant,
- label: votesText,
- textStyle: metricStyle,
- ),
- ],
- );
- }
-
- Widget buildMetric(
- BuildContext context, {
- required IconData icon,
- required Color iconColor,
- required String label,
- required TextStyle? textStyle,
- }) {
- return Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(icon, size: 15, color: iconColor),
- const SizedBox(width: 4),
- Text(label, style: textStyle),
- ],
+ ),
);
}
}
diff --git a/lib/modules/bangumi/bangumi_item.dart b/lib/modules/bangumi/bangumi_item.dart
index 53aa3f67..5e15ae7b 100644
--- a/lib/modules/bangumi/bangumi_item.dart
+++ b/lib/modules/bangumi/bangumi_item.dart
@@ -37,6 +37,8 @@ class BangumiItem {
List<int> votesCount;
@HiveField(14, defaultValue: '')
String info;
+ // Calendar metadata is separate from counted user tags and is not persisted.
+ final List<String> metaTags;
BangumiInterest? interest;
BangumiItem({
@@ -55,6 +57,7 @@ class BangumiItem {
required this.votes,
required this.votesCount,
required this.info,
+ this.metaTags = const [],
this.interest,
});
@@ -93,11 +96,9 @@ class BangumiItem {
return [];
}
final json = jsonData['rating']['count'];
- // For api.bgm.tv
if (json is Map<String, dynamic>) {
return List<int>.generate(10, (i) => json['${i + 1}'] as int);
}
- // For next.bgm.tv
if (json is List<dynamic>) {
return json.map((e) => e as int).toList();
}
@@ -110,10 +111,9 @@ class BangumiItem {
final s = v.toString().trim();
return s.isEmpty ? null : s;
}
- // For api.bgm.tv date
+
final fromTop = nonEmpty(jsonData['date']);
if (fromTop != null) return fromTop;
- // For next.bgm.tv date
final airtime = jsonData['airtime'];
if (airtime is Map) {
final fromAir = nonEmpty(airtime['date']);
@@ -124,16 +124,16 @@ class BangumiItem {
final String airDateStr = resolveAirDateString(json);
- List list = json['tags'] ?? [];
- List<String> bangumiAlias = parseBangumiAliases(json);
- List<BangumiTag> tagList = list.map((i) => BangumiTag.fromJson(i)).toList();
- List<int> voteList = parseBangumiVoteCount(json);
+ final rawTags = json['tags'] as List? ?? [];
+ final tagList = rawTags.map((tag) => BangumiTag.fromJson(tag)).toList();
+ final rawMetaTags = json['metaTags'];
BangumiInterest? interest;
final interestRaw = json['interest'];
if (interestRaw is Map<String, dynamic>) {
- interest = BangumiInterest.fromJson(json['interest']);
+ interest = BangumiInterest.fromJson(interestRaw);
} else if (interestRaw is Map) {
- interest = BangumiInterest.fromJson(Map<String, dynamic>.from(interestRaw));
+ interest =
+ BangumiInterest.fromJson(Map<String, dynamic>.from(interestRaw));
}
return BangumiItem(
id: json['id'],
@@ -144,7 +144,8 @@ class BangumiItem {
: json['name_cn'],
summary: json['summary'] ?? '',
airDate: airDateStr,
- airWeekday: dateStringToWeekday(airDateStr.isEmpty ? '2000-11-11' : airDateStr),
+ airWeekday:
+ dateStringToWeekday(airDateStr.isEmpty ? '2000-11-11' : airDateStr),
rank: json['rating']['rank'] ?? 0,
images: Map<String, String>.from(
json['images'] ??
@@ -157,12 +158,20 @@ class BangumiItem {
},
),
tags: tagList,
- alias: bangumiAlias,
+ alias: parseBangumiAliases(json),
ratingScore: double.parse(
(json['rating']['score'] ?? 0.0).toDouble().toStringAsFixed(1)),
votes: json['rating']['total'] ?? 0,
- votesCount: voteList,
+ votesCount: parseBangumiVoteCount(json),
info: json['info'] ?? '',
+ metaTags: rawMetaTags is List
+ ? rawMetaTags
+ .whereType<String>()
+ .map((name) => name.trim())
+ .where((name) => name.isNotEmpty)
+ .toSet()
+ .toList()
+ : const [],
interest: interest,
);
}
diff --git a/lib/pages/collect/collect_library_view.dart b/lib/pages/collect/collect_library_view.dart
index 6c8d7fea..486f8af5 100644
--- a/lib/pages/collect/collect_library_view.dart
+++ b/lib/pages/collect/collect_library_view.dart
@@ -14,14 +14,12 @@ class CollectLibraryView extends StatefulWidget {
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
@@ -92,7 +90,6 @@ class _CollectLibraryViewState extends State<CollectLibraryView> {
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(
@@ -166,7 +163,7 @@ class _CollectLibraryViewState extends State<CollectLibraryView> {
Widget _searchBar() => SearchBar(
controller: _searchController,
focusNode: _searchFocus,
- hintText: '搜索片单中的名称、别名',
+ hintText: '搜索收藏番剧的名称、别名',
leading: const Padding(
padding: EdgeInsets.only(left: 8),
child: Icon(Icons.search_rounded),
@@ -222,7 +219,7 @@ class _CollectLibraryViewState extends State<CollectLibraryView> {
if (entries.isEmpty)
SliverFillRemaining(
hasScrollBody: false,
- child: _emptyState(query),
+ child: _emptyState(query.count(null)),
)
else
SliverPadding(
@@ -234,7 +231,6 @@ class _CollectLibraryViewState extends State<CollectLibraryView> {
final first = index * columns;
return Padding(
padding: const EdgeInsets.only(bottom: 10),
- // Natural row heights accommodate enlarged text.
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
@@ -414,39 +410,25 @@ class _CollectLibraryViewState extends State<CollectLibraryView> {
);
}
- Widget _emptyState(CollectLibraryQuery query) {
+ Widget _emptyState(int matchCount) {
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;
- }
+ title = matchCount > 0 ? '当前分类没有匹配的番剧' : '没有找到匹配的番剧';
} else if (matchCount == 0) {
- title = '你的片单,从这里开始';
- description = '收藏喜欢的番剧,在这里整理观看状态。';
- actionLabel = '去发现番剧';
- onAction = widget.onDiscover;
+ title = '还没有收藏的番剧';
} else {
- title = '还没有「${_selectedType!.label}」的番剧';
- description = '可以从全部收藏中选择番剧,调整观看状态。';
- actionLabel = '查看全部收藏';
- onAction = () => _selectType(null);
+ title = switch (_selectedType) {
+ CollectType.watching => '还没有在追的番剧',
+ CollectType.planToWatch => '还没有想看的番剧',
+ CollectType.watched => '还没有看过的番剧',
+ CollectType.onHold => '没有搁置的番剧',
+ CollectType.abandoned => '没有弃追的番剧',
+ _ => '还没有收藏的番剧',
+ };
}
return Center(
child: Padding(
@@ -474,17 +456,6 @@ class _CollectLibraryViewState extends State<CollectLibraryView> {
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 855eb7cb..b4320c03 100644
--- a/lib/pages/collect/collect_page.dart
+++ b/lib/pages/collect/collect_page.dart
@@ -185,7 +185,6 @@ class _CollectPageState extends State<CollectPage> {
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/'),
),
),
),
diff --git a/lib/pages/timeline/timeline_controller.dart b/lib/pages/timeline/timeline_controller.dart
index 8173b640..a801a07a 100644
--- a/lib/pages/timeline/timeline_controller.dart
+++ b/lib/pages/timeline/timeline_controller.dart
@@ -4,10 +4,13 @@ import 'package:kazumi/utils/anime_season.dart';
import 'package:kazumi/repositories/collect_repository.dart';
import 'package:kazumi/modules/collect/collect_type.dart';
import 'package:kazumi/services/storage/storage.dart';
+import 'package:kazumi/services/logging/logger.dart';
import 'package:mobx/mobx.dart';
part 'timeline_controller.g.dart';
+enum TimelineSort { popularity, rating, defaultOrder }
+
class TimelineController = _TimelineController with _$TimelineController;
abstract class _TimelineController with Store {
@@ -19,8 +22,8 @@ abstract class _TimelineController with Store {
ObservableList<List<BangumiItem>> bangumiCalendar =
ObservableList<List<BangumiItem>>();
- @observable
- String seasonString = '';
+ @readonly
+ DateTime _selectedDate = DateTime.now();
@observable
bool isLoading = false;
@@ -40,109 +43,72 @@ abstract class _TimelineController with Store {
late bool onlyShowWatchingBangumis =
_collectRepository.getTimelineOnlyShowWatchingBangumis();
- int _sortType = 3;
- int get sortType => _sortType;
-
- late DateTime _selectedDate;
- DateTime get selectedDate => _selectedDate;
+ @readonly
+ TimelineSort _sort = TimelineSort.popularity;
bool get _bangumiMirrorEnabled =>
GStorage.getSetting(SettingsKeys.enableBangumiProxy);
- void init() {
- _selectedDate = DateTime.now();
- seasonString = AnimeSeason(_selectedDate).toString();
- getSchedules();
- }
-
- // Async actions commit each segment between awaits as one transaction, so
- // clear+addAll never shows observers an intermediate empty list.
@action
- Future<void> getSchedules() async {
+ Future<void> loadSeason(DateTime date) async {
+ if (isLoading) return;
isLoading = true;
isTimeOut = false;
- bangumiCalendar.clear();
- final resBangumiCalendar = await BangumiApi.getCalendar();
- bangumiCalendar.clear();
- bangumiCalendar.addAll(resBangumiCalendar);
- changeSortType(sortType);
- isLoading = false;
- isTimeOut = bangumiCalendar.isEmpty;
+ try {
+ _selectedDate = date;
+ bangumiCalendar.clear();
+ if (isSameSeason(date, DateTime.now())) {
+ bangumiCalendar.addAll(await BangumiApi.getCalendar());
+ isTimeOut = bangumiCalendar.isEmpty;
+ } else {
+ await _getSchedulesBySeason(date);
+ isTimeOut = bangumiCalendar.every((day) => day.isEmpty);
+ }
+ if (!isTimeOut) changeSort(_sort);
+ } catch (error, stackTrace) {
+ isTimeOut = true;
+ KazumiLogger().e('Timeline: loading season failed',
+ error: error, stackTrace: stackTrace);
+ } finally {
+ isLoading = false;
+ }
}
+ // MobX batches clear/addAll between awaits so observers never see a partial update.
@action
- Future<void> getSchedulesBySeason() async {
+ Future<void> _getSchedulesBySeason(DateTime date) async {
+ final dateRange = AnimeSeason(date).toSeasonStartAndEnd();
if (_bangumiMirrorEnabled) {
- isLoading = true;
- isTimeOut = false;
- bangumiCalendar.clear();
- final resBangumiCalendar =
- await BangumiApi.getBangumiMirrorSeasonCalendar(
- AnimeSeason(selectedDate).toSeasonStartAndEnd());
- bangumiCalendar.clear();
- bangumiCalendar.addAll(resBangumiCalendar);
- isLoading = false;
- isTimeOut = bangumiCalendar.every((innerList) => innerList.isEmpty);
- if (!isTimeOut) {
- changeSortType(sortType);
- }
+ bangumiCalendar
+ .addAll(await BangumiApi.getBangumiMirrorSeasonCalendar(dateRange));
return;
}
- isLoading = true;
- isTimeOut = false;
- bangumiCalendar.clear();
- var time = 0;
- const maxTime = 4;
+ const pageCount = 4;
const limit = 20;
- var resBangumiCalendar = List.generate(7, (_) => <BangumiItem>[]);
- for (time = 0; time < maxTime; time++) {
- final offset = time * limit;
- var newList = await BangumiApi.getCalendarBySearch(
- AnimeSeason(selectedDate).toSeasonStartAndEnd(), limit, offset);
+ final resBangumiCalendar = List.generate(7, (_) => <BangumiItem>[]);
+ for (var page = 0; page < pageCount; page++) {
+ final newList =
+ await BangumiApi.getCalendarBySearch(dateRange, limit, page * limit);
for (int i = 0; i < resBangumiCalendar.length; ++i) {
resBangumiCalendar[i].addAll(newList[i]);
}
bangumiCalendar.clear();
bangumiCalendar.addAll(resBangumiCalendar);
}
- isLoading = false;
- if (bangumiCalendar.isEmpty) {
- isTimeOut = true;
- } else {
- isTimeOut = bangumiCalendar.every((innerList) => innerList.isEmpty);
- }
- if (!isTimeOut) {
- changeSortType(sortType);
- }
}
- void tryEnterSeason(DateTime date) {
- _selectedDate = date;
- seasonString = "加载中 ٩(◦`꒳´◦)۶";
- }
-
- /// Sort type: 1 = default (id), 2 = score, 3 = heat (votes).
@action
- void changeSortType(int type) {
- if (type < 1 || type > 3) {
- return;
- }
- _sortType = type;
- var resBangumiCalendar = bangumiCalendar.toList();
- for (var dayList in resBangumiCalendar) {
- switch (_sortType) {
- case 1:
- dayList.sort((a, b) => a.id.compareTo(b.id));
- break;
- case 2:
- dayList.sort((a, b) => (b.ratingScore).compareTo(a.ratingScore));
- break;
- case 3:
- dayList.sort((a, b) => (b.votes).compareTo(a.votes));
- break;
- default:
- }
+ void changeSort(TimelineSort sort) {
+ _sort = sort;
+ final Comparator<BangumiItem> compare = switch (sort) {
+ TimelineSort.popularity => (a, b) => b.votes.compareTo(a.votes),
+ TimelineSort.rating => (a, b) => b.ratingScore.compareTo(a.ratingScore),
+ TimelineSort.defaultOrder => (a, b) => a.id.compareTo(b.id),
+ };
+ final resBangumiCalendar = bangumiCalendar.toList();
+ for (final dayList in resBangumiCalendar) {
+ dayList.sort(compare);
}
bangumiCalendar.clear();
bangumiCalendar.addAll(resBangumiCalendar);
@@ -160,14 +126,6 @@ abstract class _TimelineController with Store {
await _collectRepository.updateTimelineNotShowWatchedBangumis(value);
}
- Set<int> loadAbandonedBangumiIds() {
- return _collectRepository.getBangumiIdsByType(CollectType.abandoned);
- }
-
- Set<int> loadWatchedBangumiIds() {
- return _collectRepository.getBangumiIdsByType(CollectType.watched);
- }
-
@action
Future<void> setOnlyShowWatchingBangumis(bool value) async {
onlyShowWatchingBangumis = value;
@@ -177,4 +135,38 @@ abstract class _TimelineController with Store {
Set<int> loadWatchingBangumiIds() {
return _collectRepository.getBangumiIdsByType(CollectType.watching);
}
+
+ int get activeFilterCount => [
+ onlyShowWatchingBangumis,
+ notShowWatchedBangumis,
+ notShowAbandonedBangumis,
+ ].where((enabled) => enabled).length;
+
+ List<List<BangumiItem>> filterCalendar(Set<int> watchingIds) {
+ final abandonedIds = notShowAbandonedBangumis
+ ? _collectRepository.getBangumiIdsByType(CollectType.abandoned)
+ : <int>{};
+ final watchedIds = notShowWatchedBangumis
+ ? _collectRepository.getBangumiIdsByType(CollectType.watched)
+ : <int>{};
+ final onlyWatching = onlyShowWatchingBangumis;
+ return List.generate(7, (day) {
+ if (day >= bangumiCalendar.length) return <BangumiItem>[];
+ return bangumiCalendar[day]
+ .where((item) =>
+ !abandonedIds.contains(item.id) &&
+ !watchedIds.contains(item.id) &&
+ (!onlyWatching || watchingIds.contains(item.id)))
+ .toList();
+ });
+ }
+
+ @action
+ Future<void> clearFilters() async {
+ await Future.wait([
+ setNotShowAbandonedBangumis(false),
+ setNotShowWatchedBangumis(false),
+ setOnlyShowWatchingBangumis(false),
+ ]);
+ }
}
diff --git a/lib/pages/timeline/timeline_controller.g.dart b/lib/pages/timeline/timeline_controller.g.dart
index ee3e2e88..d361a500 100644
--- a/lib/pages/timeline/timeline_controller.g.dart
+++ b/lib/pages/timeline/timeline_controller.g.dart
@@ -25,19 +25,21 @@ mixin _$TimelineController on _TimelineController, Store {
});
}
- late final _$seasonStringAtom =
- Atom(name: '_TimelineController.seasonString', context: context);
+ late final _$_selectedDateAtom =
+ Atom(name: '_TimelineController._selectedDate', context: context);
- @override
- String get seasonString {
- _$seasonStringAtom.reportRead();
- return super.seasonString;
+ DateTime get selectedDate {
+ _$_selectedDateAtom.reportRead();
+ return super._selectedDate;
}
@override
- set seasonString(String value) {
- _$seasonStringAtom.reportWrite(value, super.seasonString, () {
- super.seasonString = value;
+ DateTime get _selectedDate => selectedDate;
+
+ @override
+ set _selectedDate(DateTime value) {
+ _$_selectedDateAtom.reportWrite(value, super._selectedDate, () {
+ super._selectedDate = value;
});
}
@@ -142,21 +144,40 @@ mixin _$TimelineController on _TimelineController, Store {
});
}
- late final _$getSchedulesAsyncAction =
- AsyncAction('_TimelineController.getSchedules', context: context);
+ late final _$_sortAtom =
+ Atom(name: '_TimelineController._sort', context: context);
+
+ TimelineSort get sort {
+ _$_sortAtom.reportRead();
+ return super._sort;
+ }
@override
- Future<void> getSchedules() {
- return _$getSchedulesAsyncAction.run(() => super.getSchedules());
+ TimelineSort get _sort => sort;
+
+ @override
+ set _sort(TimelineSort value) {
+ _$_sortAtom.reportWrite(value, super._sort, () {
+ super._sort = value;
+ });
}
- late final _$getSchedulesBySeasonAsyncAction =
- AsyncAction('_TimelineController.getSchedulesBySeason', context: context);
+ late final _$loadSeasonAsyncAction =
+ AsyncAction('_TimelineController.loadSeason', context: context);
@override
- Future<void> getSchedulesBySeason() {
- return _$getSchedulesBySeasonAsyncAction
- .run(() => super.getSchedulesBySeason());
+ Future<void> loadSeason(DateTime date) {
+ return _$loadSeasonAsyncAction.run(() => super.loadSeason(date));
+ }
+
+ late final _$_getSchedulesBySeasonAsyncAction = AsyncAction(
+ '_TimelineController._getSchedulesBySeason',
+ context: context);
+
+ @override
+ Future<void> _getSchedulesBySeason(DateTime date) {
+ return _$_getSchedulesBySeasonAsyncAction
+ .run(() => super._getSchedulesBySeason(date));
}
late final _$setNotShowAbandonedBangumisAsyncAction = AsyncAction(
@@ -189,15 +210,23 @@ mixin _$TimelineController on _TimelineController, Store {
.run(() => super.setOnlyShowWatchingBangumis(value));
}
+ late final _$clearFiltersAsyncAction =
+ AsyncAction('_TimelineController.clearFilters', context: context);
+
+ @override
+ Future<void> clearFilters() {
+ return _$clearFiltersAsyncAction.run(() => super.clearFilters());
+ }
+
late final _$_TimelineControllerActionController =
ActionController(name: '_TimelineController', context: context);
@override
- void changeSortType(int type) {
+ void changeSort(TimelineSort sort) {
final _$actionInfo = _$_TimelineControllerActionController.startAction(
- name: '_TimelineController.changeSortType');
+ name: '_TimelineController.changeSort');
try {
- return super.changeSortType(type);
+ return super.changeSort(sort);
} finally {
_$_TimelineControllerActionController.endAction(_$actionInfo);
}
@@ -207,7 +236,6 @@ mixin _$TimelineController on _TimelineController, Store {
String toString() {
return '''
bangumiCalendar: ${bangumiCalendar},
-seasonString: ${seasonString},
isLoading: ${isLoading},
isTimeOut: ${isTimeOut},
notShowAbandonedBangumis: ${notShowAbandonedBangumis},
diff --git a/lib/pages/timeline/timeline_page.dart b/lib/pages/timeline/timeline_page.dart
index c5339a7c..5b33e4b9 100644
--- a/lib/pages/timeline/timeline_page.dart
+++ b/lib/pages/timeline/timeline_page.dart
@@ -1,5 +1,6 @@
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_timeline_card.dart';
@@ -12,8 +13,16 @@ import 'package:kazumi/modules/bangumi/bangumi_item.dart';
import 'package:kazumi/pages/timeline/timeline_controller.dart';
import 'package:kazumi/services/storage/storage.dart';
import 'package:kazumi/utils/anime_season.dart';
-import 'package:kazumi/utils/constants.dart';
-import 'package:kazumi/utils/device.dart';
+
+part 'timeline_week_selector.dart';
+
+extension _TimelineSortLabel on TimelineSort {
+ String get label => switch (this) {
+ TimelineSort.popularity => '热度优先',
+ TimelineSort.rating => '评分优先',
+ TimelineSort.defaultOrder => '默认顺序',
+ };
+}
class TimelinePage extends StatefulWidget {
const TimelinePage({
@@ -27,57 +36,21 @@ class TimelinePage extends StatefulWidget {
State<TimelinePage> createState() => _TimelinePageState();
}
-class _TimelinePageState extends State<TimelinePage>
- with SingleTickerProviderStateMixin {
- TimelineController get timelineController => widget.controller;
- TabController? tabController;
- late bool showRating;
+class _TimelinePageState extends State<TimelinePage> {
+ TimelineController get _controller => widget.controller;
+ late final bool _showRating;
@override
void initState() {
super.initState();
- int weekday = DateTime.now().weekday - 1;
- tabController =
- TabController(vsync: this, length: tabs.length, initialIndex: weekday);
- showRating = GStorage.getSetting(SettingsKeys.showRating);
- if (timelineController.bangumiCalendar.isEmpty) {
- timelineController.init();
+ _showRating = GStorage.getSetting(SettingsKeys.showRating);
+ if (_controller.bangumiCalendar.isEmpty) {
+ _controller.loadSeason(_controller.selectedDate);
}
}
- @override
- void dispose() {
- tabController?.dispose();
- super.dispose();
- }
-
- DateTime _generateDateTime(int year, String season) {
- switch (season) {
- case '冬':
- return DateTime(year, 1, 1);
- case '春':
- return DateTime(year, 4, 1);
- case '夏':
- return DateTime(year, 7, 1);
- case '秋':
- return DateTime(year, 10, 1);
- default:
- return DateTime.now();
- }
- }
-
- final List<Tab> tabs = const <Tab>[
- Tab(text: '一'),
- Tab(text: '二'),
- Tab(text: '三'),
- Tab(text: '四'),
- Tab(text: '五'),
- Tab(text: '六'),
- Tab(text: '日'),
- ];
-
- String _getStringByDateTime(DateTime d) {
- return d.year.toString() + getSeasonStringByMonth(d.month);
+ String _seasonLabel(DateTime date) {
+ return '${date.year}年${getSeasonStringByMonth(date.month)}季';
}
void _showSeasonBottomSheet(BuildContext context) {
@@ -91,8 +64,7 @@ class _TimelinePageState extends State<TimelinePage>
children: [
MaterialBottomSheetHeader(
title: '放送季度',
- description:
- '正在查看 ${_getStringByDateTime(timelineController.selectedDate)}',
+ description: '正在查看 ${_seasonLabel(_controller.selectedDate)}',
onClose: () => Navigator.of(context).pop(),
),
Expanded(
@@ -112,12 +84,12 @@ class _TimelinePageState extends State<TimelinePage>
spacing: 4,
runSpacing: 4,
children: [
- for (final season in ['冬', '春', '夏', '秋'])
+ for (final month in [1, 4, 7, 10])
SizedBox(
width: (constraints.maxWidth - 4 * (columns - 1)) /
columns,
child: _seasonButton(
- context, _generateDateTime(year, season), now),
+ context, DateTime(year, month), now),
),
],
);
@@ -132,7 +104,7 @@ class _TimelinePageState extends State<TimelinePage>
}
Widget _seasonButton(BuildContext context, DateTime date, DateTime now) {
- final selected = isSameSeason(timelineController.selectedDate, date);
+ final selected = isSameSeason(_controller.selectedDate, date);
final colors = Theme.of(context).colorScheme;
return TextButton(
style: TextButton.styleFrom(
@@ -143,37 +115,23 @@ class _TimelinePageState extends State<TimelinePage>
foregroundColor:
selected ? colors.onSecondaryContainer : colors.onSurface,
),
- onPressed: now.isAfter(date)
+ onPressed: !date.isAfter(now)
? () {
Navigator.of(context).pop();
- _onSeasonSelected(date);
+ _controller.loadSeason(date);
}
: null,
child: Text('${getSeasonStringByMonth(date.month)}季'),
);
}
- void _onSeasonSelected(DateTime date) async {
- final currDate = DateTime.now();
- timelineController.tryEnterSeason(date);
-
- if (isSameSeason(timelineController.selectedDate, currDate)) {
- await timelineController.getSchedules();
- } else {
- await timelineController.getSchedulesBySeason();
- }
-
- timelineController.seasonString =
- AnimeSeason(timelineController.selectedDate).toString();
- }
-
Widget _buildTimelineOptionsSheet(BuildContext context) {
- return StatefulBuilder(builder: (context, updateSheet) {
+ return Observer(builder: (context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
MaterialBottomSheetHeader(
- title: '时间线选项',
+ title: '排序与筛选',
onClose: () => Navigator.of(context).pop(),
),
Flexible(
@@ -187,44 +145,36 @@ class _TimelinePageState extends State<TimelinePage>
spacing: 8,
runSpacing: 8,
children: [
- for (final option in [(3, '热度'), (2, '评分'), (1, '播出时间')])
+ for (final option in TimelineSort.values)
ChoiceChip(
- label: Text(option.$2),
- selected: timelineController.sortType == option.$1,
- onSelected: (_) => updateSheet(() {
- timelineController.changeSortType(option.$1);
- }),
+ label: Text(option.label),
+ selected: _controller.sort == option,
+ onSelected: (_) => _controller.changeSort(option),
),
],
),
),
const SizedBox(height: 24),
- Observer(
- builder: (context) => ContentSection.group(
- title: '显示范围',
- children: [
- SwitchListTile(
- title: const Text('隐藏看过的番剧'),
- value: timelineController.notShowWatchedBangumis,
- onChanged:
- timelineController.setNotShowWatchedBangumis,
- ),
- SwitchListTile(
- title: const Text('隐藏抛弃的番剧'),
- value:
- timelineController.notShowAbandonedBangumis,
- onChanged: timelineController
- .setNotShowAbandonedBangumis,
- ),
- SwitchListTile(
- title: const Text('只看正在追的番剧'),
- value:
- timelineController.onlyShowWatchingBangumis,
- onChanged: timelineController
- .setOnlyShowWatchingBangumis,
- ),
- ],
- )),
+ ContentSection.group(
+ title: '显示范围',
+ children: [
+ SwitchListTile(
+ title: const Text('隐藏看过的番剧'),
+ value: _controller.notShowWatchedBangumis,
+ onChanged: _controller.setNotShowWatchedBangumis,
+ ),
+ SwitchListTile(
+ title: const Text('隐藏抛弃的番剧'),
+ value: _controller.notShowAbandonedBangumis,
+ onChanged: _controller.setNotShowAbandonedBangumis,
+ ),
+ SwitchListTile(
+ title: const Text('只看正在追的番剧'),
+ value: _controller.onlyShowWatchingBangumis,
+ onChanged: _controller.setOnlyShowWatchingBangumis,
+ ),
+ ],
+ ),
],
),
),
@@ -233,141 +183,439 @@ class _TimelinePageState extends State<TimelinePage>
});
}
+ void _showOptions() {
+ showAdaptiveBottomSheet<void>(
+ context: context,
+ useRootNavigator: true,
+ maxHeightFactor: .8,
+ compactLandscapeMaxHeightFactor: 1,
+ builder: _buildTimelineOptionsSheet,
+ );
+ }
+
@override
Widget build(BuildContext context) {
- return Scaffold(
- appBar: SysAppBar(
- needTopOffset: false,
- toolbarHeight: 104,
- bottom: TabBar(
- controller: tabController,
- tabs: tabs,
- indicatorColor: Theme.of(context).colorScheme.primary,
- ),
- title: InkWell(
- borderRadius: BorderRadius.circular(8),
- child: Observer(builder: (context) {
- return Text(timelineController.seasonString);
- }),
- onTap: () {
- _showSeasonBottomSheet(context);
- },
- ),
- ),
- floatingActionButton: FloatingActionButton(
- onPressed: () {
- showAdaptiveBottomSheet<void>(
- useRootNavigator: true,
- maxHeightFactor: MediaQuery.sizeOf(context).height >=
- LayoutBreakpoint.compact['height']!
- ? 2 / 3
- : 1,
- compactLandscapeMaxHeightFactor: 1,
- context: context,
- builder: (context) {
- return _buildTimelineOptionsSheet(context);
- },
- );
- },
- child: const Icon(Icons.tune),
- ),
- body: Observer(builder: (context) {
- if (timelineController.isLoading &&
- timelineController.bangumiCalendar.isEmpty) {
- return const Center(
- child: LoadingIndicator(),
- );
- }
- if (timelineController.isTimeOut) {
- return Center(
- child: SizedBox(
- height: 400,
- child: BangumiMirrorErrorWidget(
- onRetry: () {
- _onSeasonSelected(timelineController.selectedDate);
- },
- onSettingsReturned: () {
- if (mounted) {
- setState(() {});
- }
- },
+ return DefaultTabController(
+ length: 7,
+ initialIndex: DateTime.now().weekday - 1,
+ animationDuration:
+ MediaQuery.disableAnimationsOf(context) ? Duration.zero : null,
+ child: _buildContent(context),
+ );
+ }
+
+ Widget _buildContent(BuildContext context) {
+ final theme = Theme.of(context);
+ final scaler = MediaQuery.textScalerOf(context);
+ return LayoutBuilder(builder: (context, constraints) {
+ final narrowPortrait = constraints.maxWidth < 600 &&
+ constraints.maxHeight > constraints.maxWidth;
+ final sidePadding = constraints.maxWidth < 600 ? 16.0 : 24.0;
+ final contentWidth =
+ (constraints.maxWidth - sidePadding * 2).clamp(0.0, 1280.0);
+ final inset = (constraints.maxWidth - contentWidth) / 2;
+ final minCardWidth = scaler.scale(16) > 24 ? 440.0 : 340.0;
+ final columns =
+ ((contentWidth + 12) / (minCardWidth + 12)).floor().clamp(1, 3);
+ return Observer(builder: (context) {
+ final loading = _controller.isLoading;
+ final failed = _controller.isTimeOut;
+ final watchingIds = _controller.loadWatchingBangumiIds();
+ final calendar = _controller.filterCalendar(watchingIds);
+ final filters = _controller.activeFilterCount;
+ final today = DateTime.now();
+ final currentSeason = isSameSeason(_controller.selectedDate, today);
+ final header = narrowPortrait
+ ? null
+ : _buildHeader(context,
+ loading: loading,
+ compact: constraints.maxHeight < 500,
+ horizontal: contentWidth >= scaler.scale(16) * 40);
+ final weekHeight = _TimelineWeekSelector.heightFor(scaler) + 16;
+ final weekSelector = Padding(
+ padding: EdgeInsets.fromLTRB(inset, 0, inset, 16),
+ child: _TimelineWeekSelector(
+ counts: calendar.map((day) => day.length).toList(),
+ todayIndex: currentSeason ? today.weekday - 1 : null,
+ isLoading: loading || failed,
+ ),
+ );
+ return Scaffold(
+ appBar: SysAppBar(
+ needTopOffset: false,
+ toolbarHeight: narrowPortrait
+ ? (scaler.scale(20) + 24).clamp(56.0, double.infinity)
+ : null,
+ title: narrowPortrait
+ ? _buildSeasonPicker(context, loading: loading, inAppBar: true)
+ : const Text('时间表'),
+ actions: [
+ Padding(
+ padding: const EdgeInsets.only(right: 12),
+ child: IconButton.filledTonal(
+ tooltip: '排序与筛选',
+ onPressed: _showOptions,
+ icon: Badge(
+ isLabelVisible: filters > 0,
+ label: Text('$filters'),
+ child: const Icon(Icons.tune_rounded),
+ ),
+ ),
),
- ),
- );
- }
- return TabBarView(
- controller: tabController,
- children: contentGrid(timelineController.bangumiCalendar),
+ ],
+ ),
+ body: SafeArea(
+ top: false,
+ child: LayoutBuilder(
+ builder: (context, viewport) => NestedScrollView(
+ headerSliverBuilder: (context, innerBoxIsScrolled) => [
+ if (header != null)
+ SliverToBoxAdapter(
+ child: Padding(
+ padding: EdgeInsets.fromLTRB(inset, 8, inset, 20),
+ child: header,
+ ),
+ ),
+ SliverOverlapAbsorber(
+ handle:
+ NestedScrollView.sliverOverlapAbsorberHandleFor(
+ context),
+ sliver: SliverPersistentHeader(
+ pinned: true,
+ delegate: _WeekHeaderDelegate(
+ height: weekHeight,
+ color: theme.scaffoldBackgroundColor,
+ child: weekSelector,
+ ),
+ ),
+ ),
+ ],
+ body: loading && calendar.every((day) => day.isEmpty)
+ ? _buildLoading(viewport.maxHeight, weekHeight)
+ : failed
+ ? _TimelineScrollView(
+ slivers: [
+ SliverPadding(
+ padding: const EdgeInsets.all(24),
+ sliver: SliverToBoxAdapter(
+ child: BangumiMirrorErrorWidget(
+ onRetry: () => _controller.loadSeason(
+ _controller.selectedDate),
+ onSettingsReturned: () {
+ if (mounted) setState(() {});
+ },
+ ),
+ ),
+ ),
+ ],
+ )
+ : TabBarView(
+ children: [
+ for (var day = 0; day < 7; day++)
+ _buildDay(
+ context,
+ day: day,
+ items: calendar[day],
+ watchingIds: watchingIds,
+ columns: columns,
+ inset: inset,
+ compact: narrowPortrait,
+ loading: loading,
+ ),
+ ],
+ ),
+ )),
+ ),
);
- }),
+ });
+ });
+ }
+
+ Widget _buildLoading(double viewportHeight, double overlapHeight) {
+ return LayoutBuilder(builder: (context, constraints) {
+ // The injector prevents overlap; this offset centers loading in the whole page.
+ final contentHeight =
+ (constraints.maxHeight - overlapHeight).clamp(0.0, double.infinity);
+ final headerHeight = viewportHeight - contentHeight;
+ final bottomInset = headerHeight.clamp(
+ 0.0, (contentHeight - 48).clamp(0.0, double.infinity));
+ return _TimelineScrollView(
+ slivers: [
+ SliverFillRemaining(
+ hasScrollBody: false,
+ child: Padding(
+ padding: EdgeInsets.only(bottom: bottomInset),
+ child: const Center(child: LoadingIndicator()),
+ ),
+ ),
+ ],
+ );
+ });
+ }
+
+ Widget _buildSeasonPicker(BuildContext context,
+ {required bool loading, bool compact = false, bool inAppBar = false}) {
+ final theme = Theme.of(context);
+ final colors = theme.colorScheme;
+ final label = _seasonLabel(_controller.selectedDate);
+ final style = inAppBar
+ ? theme.textTheme.titleMedium
+ : compact || MediaQuery.textScalerOf(context).scale(16) > 24
+ ? theme.textTheme.titleLarge
+ : theme.textTheme.headlineMedium;
+ return Semantics(
+ label: '切换放送季度,$label',
+ button: true,
+ enabled: !loading,
+ onTap: loading ? null : () => _showSeasonBottomSheet(context),
+ excludeSemantics: true,
+ child: Tooltip(
+ message: '切换放送季度',
+ child: InkWell(
+ onTap: loading ? null : () => _showSeasonBottomSheet(context),
+ borderRadius: BorderRadius.circular(20),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: 8),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Flexible(
+ child: Text(label,
+ maxLines: inAppBar ? 1 : null,
+ overflow: inAppBar ? TextOverflow.ellipsis : null,
+ style: style?.copyWith(
+ color: colors.onSurface,
+ fontWeight: FontWeight.w700)),
+ ),
+ SizedBox(width: inAppBar ? 4 : 12),
+ if (inAppBar)
+ const Icon(Icons.expand_more_rounded, size: 20)
+ else
+ CircleAvatar(
+ radius: 18,
+ backgroundColor: colors.secondaryContainer,
+ foregroundColor: colors.onSecondaryContainer,
+ child: const Icon(Icons.expand_more_rounded, size: 24),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
);
}
- List<Widget> contentGrid(List<List<BangumiItem>> bangumiCalendar) {
- List<Widget> gridViewList = [];
- int crossCount = 1;
- if (MediaQuery.sizeOf(context).width > LayoutBreakpoint.compact['width']!) {
- crossCount = 2;
- }
- if (MediaQuery.sizeOf(context).width > LayoutBreakpoint.medium['width']!) {
- crossCount = 3;
+ Widget _buildHeader(BuildContext context,
+ {required bool loading,
+ required bool compact,
+ required bool horizontal}) {
+ final theme = Theme.of(context);
+ final colors = theme.colorScheme;
+ final date = _controller.selectedDate;
+ final startMonth = ((date.month - 1) ~/ 3) * 3 + 1;
+ final seasonPicker = Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ _buildSeasonPicker(context, loading: loading, compact: compact),
+ if (!compact)
+ Text(
+ loading ? '正在加载放送时间表…' : '$startMonth — ${startMonth + 2} 月 · 每周放送',
+ style: theme.textTheme.bodyMedium
+ ?.copyWith(color: colors.onSurfaceVariant),
+ ),
+ ],
+ );
+ final filters = Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: [
+ FilterChip(
+ avatar: _controller.onlyShowWatchingBangumis
+ ? null
+ : const Icon(Icons.bookmark_border_rounded, size: 18),
+ label: const Text('只看在追'),
+ selected: _controller.onlyShowWatchingBangumis,
+ onSelected: _controller.setOnlyShowWatchingBangumis,
+ ),
+ ActionChip(
+ avatar: const Icon(Icons.sort_rounded, size: 18),
+ label: Text(_controller.sort.label),
+ onPressed: _showOptions,
+ ),
+ if (_controller.notShowWatchedBangumis)
+ InputChip(
+ label: const Text('隐藏看过'),
+ onDeleted: () => _controller.setNotShowWatchedBangumis(false),
+ deleteButtonTooltipMessage: '显示看过的番剧',
+ ),
+ if (_controller.notShowAbandonedBangumis)
+ InputChip(
+ label: const Text('隐藏抛弃'),
+ onDeleted: () => _controller.setNotShowAbandonedBangumis(false),
+ deleteButtonTooltipMessage: '显示抛弃的番剧',
+ ),
+ ],
+ );
+ if (horizontal) {
+ return Row(
+ children: [
+ Expanded(child: seasonPicker),
+ const SizedBox(width: 24),
+ Flexible(
+ child: Align(alignment: Alignment.centerRight, child: filters),
+ ),
+ ],
+ );
}
- double cardHeight = isDesktop() ? 160 : (isTablet() ? 140 : 120);
- for (var bangumiList in bangumiCalendar) {
- var filteredList = bangumiList;
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [seasonPicker, SizedBox(height: compact ? 8 : 16), filters],
+ );
+ }
- if (timelineController.notShowAbandonedBangumis) {
- final abandonedBangumiIds =
- timelineController.loadAbandonedBangumiIds();
- filteredList = filteredList
- .where((item) => !abandonedBangumiIds.contains(item.id))
- .toList();
- }
+ Widget _buildDay(
+ BuildContext context, {
+ required int day,
+ required List<BangumiItem> items,
+ required Set<int> watchingIds,
+ required int columns,
+ required double inset,
+ required bool compact,
+ required bool loading,
+ }) {
+ final theme = Theme.of(context);
+ final colors = theme.colorScheme;
+ final cardHeight = BangumiTimelineCard.heightFor(
+ MediaQuery.textScalerOf(context),
+ compact: compact);
+ final rawCalendar = _controller.bangumiCalendar;
+ final filteredOut = day < rawCalendar.length && rawCalendar[day].isNotEmpty;
+ return _TimelineScrollView(
+ key: PageStorageKey('timeline-day-$day'),
+ slivers: [
+ if (loading)
+ SliverToBoxAdapter(
+ child: Padding(
+ padding: EdgeInsets.fromLTRB(inset, 0, inset, 12),
+ child: const LinearProgressIndicator(),
+ ),
+ ),
+ if (items.isEmpty)
+ SliverToBoxAdapter(
+ child: Padding(
+ padding: EdgeInsets.fromLTRB(inset + 16, 40, inset + 16, 40),
+ child: Column(
+ children: [
+ Container(
+ padding: const EdgeInsets.all(24),
+ decoration: BoxDecoration(
+ color: colors.secondaryContainer,
+ borderRadius: BorderRadius.circular(28),
+ ),
+ child: Icon(
+ filteredOut
+ ? Icons.filter_alt_off_outlined
+ : Icons.event_available_outlined,
+ size: 32,
+ color: colors.onSecondaryContainer,
+ ),
+ ),
+ const SizedBox(height: 20),
+ Text(filteredOut ? '没有符合筛选的番剧' : '这一天暂无放送',
+ textAlign: TextAlign.center,
+ style: theme.textTheme.titleMedium),
+ const SizedBox(height: 8),
+ Text(
+ filteredOut ? '调整筛选条件,看看其他作品吧' : '切换其他星期,发现更多番剧',
+ textAlign: TextAlign.center,
+ style: theme.textTheme.bodyMedium
+ ?.copyWith(color: colors.onSurfaceVariant),
+ ),
+ if (filteredOut) ...[
+ const SizedBox(height: 20),
+ FilledButton.tonal(
+ onPressed: _controller.clearFilters,
+ child: const Text('清除筛选')),
+ ],
+ ],
+ ),
+ ),
+ )
+ else
+ SliverPadding(
+ padding: EdgeInsets.fromLTRB(inset, 0, inset, 24),
+ sliver: SliverGrid(
+ gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
+ crossAxisCount: columns,
+ mainAxisSpacing: 12,
+ crossAxisSpacing: 12,
+ mainAxisExtent: cardHeight,
+ ),
+ delegate: SliverChildBuilderDelegate(
+ (context, index) {
+ final item = items[index];
+ return BangumiTimelineCard(
+ key: ValueKey(item.id),
+ bangumiItem: item,
+ compact: compact,
+ showRating: _showRating,
+ isWatching: watchingIds.contains(item.id),
+ onTap: () => context.pushNamed('/info/', arguments: item),
+ );
+ },
+ childCount: items.length,
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+}
- if (timelineController.notShowWatchedBangumis) {
- final watchedBangumiIds = timelineController.loadWatchedBangumiIds();
- filteredList = filteredList
- .where((item) => !watchedBangumiIds.contains(item.id))
- .toList();
- }
+class _TimelineScrollView extends StatelessWidget {
+ const _TimelineScrollView({super.key, required this.slivers});
- if (timelineController.onlyShowWatchingBangumis) {
- final watchingBangumiIds = timelineController.loadWatchingBangumiIds();
- filteredList = filteredList
- .where((item) => watchingBangumiIds.contains(item.id))
- .toList();
- }
+ final List<Widget> slivers;
- gridViewList.add(
- CustomScrollView(
- slivers: [
- SliverPadding(
- padding: const EdgeInsets.symmetric(horizontal: 8),
- sliver: SliverGrid(
- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
- mainAxisSpacing: StyleString.cardSpace - 2,
- crossAxisSpacing: StyleString.cardSpace,
- crossAxisCount: crossCount,
- mainAxisExtent: cardHeight + 12,
- ),
- delegate: SliverChildBuilderDelegate(
- (BuildContext context, int index) {
- if (filteredList.isEmpty) return null;
- final item = filteredList[index];
- return BangumiTimelineCard(
- bangumiItem: item,
- cardHeight: cardHeight,
- showRating: showRating);
- },
- childCount:
- filteredList.isNotEmpty ? filteredList.length : 10,
- ),
- ),
- ),
- ],
+ @override
+ Widget build(BuildContext context) {
+ return CustomScrollView(
+ slivers: [
+ SliverOverlapInjector(
+ handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
),
- );
- }
- return gridViewList;
+ ...slivers,
+ ],
+ );
}
}
+
+class _WeekHeaderDelegate extends SliverPersistentHeaderDelegate {
+ const _WeekHeaderDelegate({
+ required this.height,
+ required this.color,
+ required this.child,
+ });
+
+ final double height;
+ final Color color;
+ final Widget child;
+
+ @override
+ double get minExtent => height;
+
+ @override
+ double get maxExtent => height;
+
+ @override
+ Widget build(
+ BuildContext context, double shrinkOffset, bool overlapsContent) =>
+ ColoredBox(color: color, child: child);
+
+ @override
+ bool shouldRebuild(covariant _WeekHeaderDelegate oldDelegate) =>
+ oldDelegate.height != height ||
+ oldDelegate.color != color ||
+ oldDelegate.child != child;
+}
diff --git a/lib/pages/timeline/timeline_week_selector.dart b/lib/pages/timeline/timeline_week_selector.dart
new file mode 100644
index 00000000..512f8c61
--- /dev/null
+++ b/lib/pages/timeline/timeline_week_selector.dart
@@ -0,0 +1,89 @@
+part of 'timeline_page.dart';
+
+class _TimelineWeekSelector extends StatelessWidget {
+ const _TimelineWeekSelector({
+ required this.counts,
+ this.todayIndex,
+ this.isLoading = false,
+ });
+
+ final List<int> counts;
+ final int? todayIndex;
+ final bool isLoading;
+
+ static const _weekdays = ['一', '二', '三', '四', '五', '六', '日'];
+
+ static double heightFor(TextScaler scaler) =>
+ 40 + scaler.scale(20) + scaler.scale(16);
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final colors = theme.colorScheme;
+ final scaler = MediaQuery.textScalerOf(context);
+ return LayoutBuilder(builder: (context, constraints) {
+ final minTabWidth = (scaler.scale(14) * 2 + 16).clamp(48.0, 112.0);
+ final scrollable = constraints.maxWidth - 8 < minTabWidth * 7;
+ return DecoratedBox(
+ decoration: BoxDecoration(
+ color: colors.surfaceContainerLow,
+ borderRadius: BorderRadius.circular(28),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.all(4),
+ child: TabBar(
+ isScrollable: scrollable,
+ tabAlignment: scrollable ? TabAlignment.start : TabAlignment.fill,
+ dividerHeight: 0,
+ indicatorSize: TabBarIndicatorSize.tab,
+ indicator: BoxDecoration(
+ color: colors.primary,
+ borderRadius: BorderRadius.circular(24),
+ ),
+ indicatorAnimation: TabIndicatorAnimation.elastic,
+ labelColor: colors.onPrimary,
+ unselectedLabelColor: colors.onSurfaceVariant,
+ labelPadding: const EdgeInsets.symmetric(horizontal: 4),
+ labelStyle: theme.textTheme.labelLarge
+ ?.copyWith(fontWeight: FontWeight.w700),
+ overlayColor: WidgetStateProperty.resolveWith((states) =>
+ states.contains(WidgetState.hovered) ||
+ states.contains(WidgetState.focused)
+ ? colors.primary.withValues(alpha: .08)
+ : null),
+ splashBorderRadius: BorderRadius.circular(24),
+ tabs: [
+ for (var day = 0; day < 7; day++)
+ Tab(
+ height: heightFor(scaler) - 8,
+ child: Semantics(
+ label: '星期${_weekdays[day]}'
+ '${day == todayIndex ? ',今天' : ''}'
+ '${isLoading ? ',加载中' : ',${counts[day]}部'}',
+ excludeSemantics: true,
+ child: SizedBox(
+ width: scrollable ? minTabWidth : null,
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Text(day == todayIndex ? '今天' : '周${_weekdays[day]}'),
+ const SizedBox(height: 4),
+ Text(
+ isLoading ? '—' : '${counts[day]}',
+ style: TextStyle(
+ fontSize: theme.textTheme.labelSmall?.fontSize,
+ fontWeight: FontWeight.w500,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ });
+ }
+}