Skip to content

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

feat(comments): unify episode and character cards

Prediditb677940041f0
diff --git a/lib/bbcode/bbcode_widget.dart b/lib/bbcode/bbcode_widget.dart
index 5140c915..a7ea423e 100644
--- a/lib/bbcode/bbcode_widget.dart
+++ b/lib/bbcode/bbcode_widget.dart
@@ -11,9 +11,14 @@ import 'generated/BBCodeParser.dart';
import 'generated/BBCodeLexer.dart';
class BBCodeWidget extends StatefulWidget {
- const BBCodeWidget({super.key, required this.bbcode});
+ const BBCodeWidget({
+ super.key,
+ required this.bbcode,
+ this.textScaler = TextScaler.noScaling,
+ });
final String bbcode;
+ final TextScaler textScaler;
@override
State<StatefulWidget> createState() => _BBCodeWidgetState();
@@ -22,15 +27,6 @@ class BBCodeWidget extends StatefulWidget {
class _BBCodeWidgetState extends State<BBCodeWidget> {
bool _isVisible = false;
- /// color 可以为三种表现形式
- ///
- /// `ARGB: #FFFFFFFF`
- ///
- /// `RGB: #FFFFFF`
- ///
- /// `NAME: red`
- ///
- /// 若全部解析失败则返回 null 使用默认颜色
Color? _parseColor(String hex) {
if (hex.startsWith('#')) {
hex = hex.replaceFirst('#', '');
@@ -59,7 +55,6 @@ class _BBCodeWidgetState extends State<BBCodeWidget> {
@override
Widget build(BuildContext context) {
- BBCodeParser.checkVersion();
BBCodeParser.checkVersion();
final input = InputStream.fromString(widget.bbcode);
final lexer = BBCodeLexer(input);
@@ -79,6 +74,7 @@ class _BBCodeWidgetState extends State<BBCodeWidget> {
return Wrap(
children: [
RichText(
+ textScaler: widget.textScaler,
text: TextSpan(
style: DefaultTextStyle.of(context).style,
children: bbcodeBaseListener.bbcode.map((e) {
@@ -127,7 +123,8 @@ class _BBCodeWidgetState extends State<BBCodeWidget> {
);
} else if (e is BBCodeImg) {
final currentIndex = imageIndex++;
- final heroTag = ImageViewer.heroTagFor(e.imageUrl, currentIndex);
+ final heroTag =
+ ImageViewer.heroTagFor(e.imageUrl, currentIndex);
return WidgetSpan(
child: GestureDetector(
onTap: () => ImageViewer.show(
@@ -197,7 +194,6 @@ class _BBCodeWidgetState extends State<BBCodeWidget> {
),
);
} else {
- // e is Icon
return WidgetSpan(
child: Icon(
(e as Icon).icon,
diff --git a/lib/bean/card/user_comments_card.dart b/lib/bean/card/user_comments_card.dart
index 37a24ac0..7ff49b31 100644
--- a/lib/bean/card/user_comments_card.dart
+++ b/lib/bean/card/user_comments_card.dart
@@ -5,159 +5,135 @@ import 'package:kazumi/modules/comments/comment_item.dart';
import 'package:kazumi/utils/date_time.dart';
import 'package:skeletonizer/skeletonizer.dart';
-// 16 and 12 are M3 `large` and a 4dp-grid step; the replies block nested inside
-// takes the concentric radius `outer - padding` so both sets of corners stay
-// parallel.
-const double _cardRadius = 16;
-const double _cardPadding = 12;
-const double _repliesRadius = _cardRadius - _cardPadding;
-
-const double _avatarGap = 12;
-const double _replyAvatarRadius = 16;
-
-/// Renders one Bangumi comment and its replies. Episode and character comments
-/// are distinct models of the same shape, so each gets a constructor.
-class UserCommentsCard extends StatelessWidget {
+class UserCommentsCard extends StatefulWidget {
UserCommentsCard.episode(EpisodeCommentItem item, {super.key})
- : _comment = _fromEpisode(item.comment),
+ : _source = item,
+ _comment = _fromEpisode(item.comment),
_replies = item.replies.map(_fromEpisode).toList();
UserCommentsCard.character(CharacterCommentItem item, {super.key})
- : _comment = _fromCharacter(item.comment),
+ : _source = item,
+ _comment = _fromCharacter(item.comment),
_replies = item.replies.map(_fromCharacter).toList();
- final _CommentView _comment;
- final List<_CommentView> _replies;
-
- static _CommentView _fromEpisode(EpisodeComment comment) => _CommentView(
- nickname: comment.user.nickname,
- avatarUrl: comment.user.avatar.large,
- createdAt: comment.createdAt,
- content: comment.comment,
- );
-
- static _CommentView _fromCharacter(CharacterComment comment) => _CommentView(
- nickname: comment.user.nickname,
- avatarUrl: comment.user.avatar.large,
- createdAt: comment.createdAt,
- content: comment.comment,
- );
+ final Object _source;
+ final _CommentData _comment;
+ final List<_CommentData> _replies;
@override
- Widget build(BuildContext context) {
- return Padding(
- padding: const EdgeInsets.only(bottom: 8),
- child: Material(
- color: Theme.of(context).colorScheme.surfaceContainerLow,
- borderRadius: BorderRadius.circular(_cardRadius),
- clipBehavior: Clip.antiAlias,
- child: Padding(
- padding: const EdgeInsets.all(_cardPadding),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- _CommentAuthor(comment: _comment, avatarRadius: 20),
- const SizedBox(height: 8),
- _CommentBody(content: _comment.content),
- if (_replies.isNotEmpty) ...[
- const SizedBox(height: 12),
- _RepliesContainer(replies: _replies),
- ],
- ],
- ),
- ),
- ),
- );
- }
+ State<UserCommentsCard> createState() => _UserCommentsCardState();
}
-/// Loading placeholder for [UserCommentsCard], sharing its chrome and metrics.
-class UserCommentsCardBone extends StatelessWidget {
- const UserCommentsCardBone({super.key});
+class _UserCommentsCardState extends State<UserCommentsCard> {
+ static const _previewCount = 2;
+ bool _expanded = false;
@override
- Widget build(BuildContext context) {
- return Padding(
- padding: const EdgeInsets.only(bottom: 8),
- child: Material(
- color: Theme.of(context).colorScheme.surfaceContainerLow,
- borderRadius: BorderRadius.circular(_cardRadius),
- clipBehavior: Clip.antiAlias,
- child: const Padding(
- padding: EdgeInsets.all(_cardPadding),
- child: Skeletonizer.zone(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Row(
- children: [
- Bone.circle(size: 40),
- SizedBox(width: _avatarGap),
- Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Bone.text(width: 96),
- SizedBox(height: 6),
- Bone.text(width: 64, fontSize: 11),
- ],
- ),
- ],
- ),
- SizedBox(height: 12),
- Bone.multiText(lines: 2),
- ],
- ),
- ),
- ),
- ),
- );
+ void didUpdateWidget(covariant UserCommentsCard oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (oldWidget._source != widget._source) _expanded = false;
}
-}
-
-class _CommentView {
- const _CommentView({
- required this.nickname,
- required this.avatarUrl,
- required this.createdAt,
- required this.content,
- });
-
- final String nickname;
- final String avatarUrl;
- final int createdAt;
- final String content;
-}
-
-class _RepliesContainer extends StatelessWidget {
- const _RepliesContainer({required this.replies});
-
- final List<_CommentView> replies;
@override
Widget build(BuildContext context) {
- return Container(
- width: double.infinity,
- padding: const EdgeInsets.all(_cardPadding),
- decoration: BoxDecoration(
- color: Theme.of(context).colorScheme.surfaceContainer,
- borderRadius: BorderRadius.circular(_repliesRadius),
- ),
+ final colors = Theme.of(context).colorScheme;
+ final type = Theme.of(context).textTheme;
+ final replies = widget._replies;
+ final visibleCount = _expanded || replies.length <= _previewCount
+ ? replies.length
+ : _previewCount;
+ final disableAnimations = MediaQuery.disableAnimationsOf(context);
+
+ return _CommentSurface(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- for (var index = 0; index < replies.length; index++) ...[
- if (index > 0) const SizedBox(height: 12),
- _CommentAuthor(
- comment: replies[index],
- avatarRadius: _replyAvatarRadius,
- ),
- const SizedBox(height: 6),
+ _CommentAuthor(comment: widget._comment),
+ const SizedBox(height: 16),
+ _CommentBody(content: widget._comment.content),
+ if (replies.isNotEmpty) ...[
+ const SizedBox(height: 20),
Padding(
- padding: const EdgeInsets.only(
- left: _replyAvatarRadius * 2 + _avatarGap,
+ padding: const EdgeInsets.only(left: 4, bottom: 10),
+ child: Row(
+ children: [
+ Icon(Icons.forum_outlined, size: 16, color: colors.primary),
+ const SizedBox(width: 8),
+ Text('${replies.length} 条回复',
+ style: type.labelLarge?.copyWith(color: colors.primary)),
+ ],
),
- child: _CommentBody(content: replies[index].content),
),
+ AnimatedSize(
+ duration: disableAnimations
+ ? Duration.zero
+ : const Duration(milliseconds: 300),
+ curve: Curves.easeInOutCubicEmphasized,
+ alignment: Alignment.topCenter,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ for (var index = 0; index < visibleCount; index++)
+ Padding(
+ padding: EdgeInsets.only(top: index == 0 ? 0 : 3),
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ color: colors.surfaceContainerHighest,
+ borderRadius: BorderRadius.vertical(
+ top: Radius.circular(index == 0 ? 16 : 4),
+ bottom: Radius.circular(
+ index == visibleCount - 1 ? 16 : 4),
+ ),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.all(12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ _CommentAuthor(
+ comment: replies[index],
+ compact: true,
+ ),
+ const SizedBox(height: 10),
+ _CommentBody(content: replies[index].content),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (replies.length > _previewCount) ...[
+ const SizedBox(height: 8),
+ Semantics(
+ expanded: _expanded,
+ child: SizedBox(
+ width: double.infinity,
+ child: TextButton.icon(
+ onPressed: () => setState(() => _expanded = !_expanded),
+ style: TextButton.styleFrom(
+ minimumSize: const Size(48, 48),
+ backgroundColor: colors.secondaryContainer,
+ foregroundColor: colors.onSecondaryContainer,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(16),
+ ),
+ ),
+ icon: AnimatedRotation(
+ turns: _expanded ? .5 : 0,
+ duration: disableAnimations
+ ? Duration.zero
+ : const Duration(milliseconds: 200),
+ child: const Icon(Icons.expand_more_rounded, size: 20),
+ ),
+ label: Text(_expanded
+ ? '收起回复'
+ : '展开其余 ${replies.length - _previewCount} 条回复'),
+ ),
+ ),
+ ),
+ ],
],
],
),
@@ -165,62 +141,44 @@ class _RepliesContainer extends StatelessWidget {
}
}
-class _CommentBody extends StatelessWidget {
- const _CommentBody({required this.content});
-
- final String content;
-
- @override
- Widget build(BuildContext context) {
- if (content.isEmpty) {
- final theme = Theme.of(context);
- return Text(
- '该评论已被删除',
- style: theme.textTheme.bodyMedium?.copyWith(
- color: theme.colorScheme.onSurfaceVariant,
- fontStyle: FontStyle.italic,
- ),
- );
- }
- return BBCodeWidget(bbcode: content);
- }
-}
-
class _CommentAuthor extends StatelessWidget {
- const _CommentAuthor({
- required this.comment,
- required this.avatarRadius,
- });
+ const _CommentAuthor({required this.comment, this.compact = false});
- final _CommentView comment;
- final double avatarRadius;
+ final _CommentData comment;
+ final bool compact;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
- final colorScheme = theme.colorScheme;
-
return Row(
children: [
- BangumiAvatar(radius: avatarRadius, imageUrl: comment.avatarUrl),
- const SizedBox(width: _avatarGap),
+ ExcludeSemantics(
+ child: BangumiAvatar(
+ radius: compact ? 16 : 22,
+ imageUrl: comment.user.avatar.large,
+ ),
+ ),
+ const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
- comment.nickname,
- maxLines: 1,
+ comment.user.nickname.isNotEmpty
+ ? comment.user.nickname
+ : comment.user.username,
+ maxLines: 2,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.titleSmall?.copyWith(
- color: colorScheme.onSurface,
- fontWeight: FontWeight.w600,
+ color: theme.colorScheme.onSurface,
+ fontWeight: FontWeight.w700,
),
),
+ const SizedBox(height: 2),
Text(
dateFormat(comment.createdAt),
style: theme.textTheme.labelSmall?.copyWith(
- color: colorScheme.onSurfaceVariant,
+ color: theme.colorScheme.onSurfaceVariant,
),
),
],
@@ -230,3 +188,91 @@ class _CommentAuthor extends StatelessWidget {
);
}
}
+
+class _CommentBody extends StatelessWidget {
+ const _CommentBody({required this.content});
+
+ final String content;
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ return DefaultTextStyle.merge(
+ style: theme.textTheme.bodyMedium?.copyWith(
+ color: theme.colorScheme.onSurface,
+ height: 1.65,
+ ),
+ child: content.isEmpty
+ ? Text('该评论已被删除',
+ style: TextStyle(color: theme.colorScheme.onSurfaceVariant))
+ : BBCodeWidget(
+ bbcode: content,
+ textScaler: MediaQuery.textScalerOf(context),
+ ),
+ );
+ }
+}
+
+class UserCommentsCardBone extends StatelessWidget {
+ const UserCommentsCardBone({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ return const _CommentSurface(
+ child: Skeletonizer.zone(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(children: [
+ Bone.circle(size: 44),
+ SizedBox(width: 12),
+ Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Bone.text(width: 96),
+ SizedBox(height: 2),
+ Bone.text(width: 64, fontSize: 11),
+ ],
+ ),
+ ]),
+ SizedBox(height: 16),
+ Bone.multiText(lines: 2),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class _CommentSurface extends StatelessWidget {
+ const _CommentSurface({required this.child});
+
+ final Widget child;
+
+ @override
+ Widget build(BuildContext context) {
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 12),
+ child: Material(
+ color: Theme.of(context).colorScheme.surfaceContainerLow,
+ borderRadius: BorderRadius.circular(24),
+ clipBehavior: Clip.antiAlias,
+ child: Padding(padding: const EdgeInsets.all(16), child: child),
+ ),
+ );
+ }
+}
+
+typedef _CommentData = ({User user, String content, int createdAt});
+
+_CommentData _fromEpisode(EpisodeComment comment) => (
+ user: comment.user,
+ content: comment.comment,
+ createdAt: comment.createdAt,
+ );
+
+_CommentData _fromCharacter(CharacterComment comment) => (
+ user: comment.user,
+ content: comment.comment,
+ createdAt: comment.createdAt,
+ );
diff --git a/lib/pages/player/episode_comments_picker.dart b/lib/pages/player/episode_comments_picker.dart
new file mode 100644
index 00000000..22c269b5
--- /dev/null
+++ b/lib/pages/player/episode_comments_picker.dart
@@ -0,0 +1,116 @@
+import 'package:flutter/material.dart';
+import 'package:kazumi/modules/bangumi/episode_item.dart';
+
+class EpisodeCommentsPicker extends StatelessWidget {
+ const EpisodeCommentsPicker({
+ super.key,
+ required this.episodes,
+ required this.selectedEpisode,
+ });
+
+ final List<EpisodeInfo> episodes;
+ final int selectedEpisode;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ final type = Theme.of(context).textTheme;
+ return Dialog(
+ insetPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 24),
+ backgroundColor: colors.surfaceContainerLow,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)),
+ clipBehavior: Clip.antiAlias,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 480, maxHeight: 600),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(24, 24, 24, 20),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text('选择讨论分集',
+ style: type.headlineSmall
+ ?.copyWith(fontWeight: FontWeight.w700)),
+ const SizedBox(height: 8),
+ Text('切换想看的讨论,视频会继续播放。',
+ style: type.bodyMedium
+ ?.copyWith(color: colors.onSurfaceVariant)),
+ ],
+ ),
+ ),
+ Flexible(
+ child: ListView.separated(
+ shrinkWrap: true,
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ itemCount: episodes.length,
+ separatorBuilder: (context, index) => const SizedBox(height: 3),
+ itemBuilder: (context, index) {
+ final info = episodes[index];
+ final title =
+ info.nameCn.isNotEmpty ? info.nameCn : info.name;
+ final selected = index + 1 == selectedEpisode;
+ return Material(
+ color: selected
+ ? colors.primaryContainer
+ : colors.surfaceContainerHighest,
+ borderRadius: BorderRadius.vertical(
+ top: Radius.circular(index == 0 ? 20 : 4),
+ bottom: Radius.circular(
+ index == episodes.length - 1 ? 20 : 4),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: ListTile(
+ selected: selected,
+ selectedColor: colors.onPrimaryContainer,
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 16, vertical: 8),
+ title: Text(
+ '${info.readType().toUpperCase()} ${info.episode}'
+ .trim(),
+ style: type.labelLarge?.copyWith(
+ color: selected
+ ? colors.onPrimaryContainer
+ : colors.primary,
+ ),
+ ),
+ subtitle: title.isEmpty
+ ? null
+ : Text(title,
+ style: type.bodyLarge?.copyWith(
+ color: selected
+ ? colors.onPrimaryContainer
+ : colors.onSurface,
+ )),
+ trailing: Icon(
+ selected
+ ? Icons.check_circle_rounded
+ : Icons.chevron_right_rounded,
+ color:
+ selected ? colors.primary : colors.onSurfaceVariant,
+ ),
+ onTap: () => Navigator.pop(context, index + 1),
+ ),
+ );
+ },
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.all(12),
+ child: Align(
+ alignment: Alignment.centerRight,
+ child: TextButton(
+ onPressed: () => Navigator.pop(context),
+ style: TextButton.styleFrom(minimumSize: const Size(64, 48)),
+ child: const Text('取消'),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/pages/player/episode_comments_sheet.dart b/lib/pages/player/episode_comments_sheet.dart
index 0aeeceff..291de231 100644
--- a/lib/pages/player/episode_comments_sheet.dart
+++ b/lib/pages/player/episode_comments_sheet.dart
@@ -1,10 +1,11 @@
-import 'dart:ui';
+import 'dart:async';
+
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:kazumi/bean/dialog/dialog_helper.dart';
-import 'package:kazumi/bean/card/user_comments_card.dart';
-import 'package:kazumi/bean/widget/error_widget.dart';
import 'package:kazumi/modules/bangumi/episode_item.dart';
+import 'package:kazumi/pages/player/episode_comments_picker.dart';
+import 'package:kazumi/pages/player/episode_comments_view.dart';
import 'package:kazumi/pages/video/video_controller.dart';
import 'package:kazumi/request/apis/bangumi_api.dart';
@@ -25,43 +26,13 @@ class EpisodeCommentsSheet extends StatefulWidget {
}
class _EpisodeCommentsSheetState extends State<EpisodeCommentsSheet> {
- VideoPageController get videoPageController => widget.videoPageController;
- bool commentsQueryTimeout = false;
- bool commentsIsEmpty = false;
- final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
- GlobalKey<RefreshIndicatorState>();
-
- int ep = 0;
-
- Future<void> loadComments(int episode) async {
- commentsQueryTimeout = false;
- commentsIsEmpty = false;
- try {
- final applied = await videoPageController.queryBangumiEpisodeCommentsByID(
- videoPageController.bangumiItem.id, episode);
- if (!mounted || !applied) {
- return;
- }
- if (videoPageController.episodeCommentsList.isEmpty && mounted) {
- setState(() {
- commentsIsEmpty = true;
- });
- }
- } catch (e) {
- if (mounted) {
- setState(() {
- commentsQueryTimeout = true;
- });
- }
- }
- if (mounted) {
- setState(() {});
- }
- }
-
- void toggleSortOrder() {
- videoPageController.toggleSortOrder();
- }
+ VideoPageController get _controller => widget.videoPageController;
+ late int _selectedEpisode;
+ bool _isLoading = false;
+ bool _hasError = false;
+ bool _isSelectingEpisode = false;
+ int _requestVersion = 0;
+ final Map<int, EpisodeInfo> _episodeInfoByIndex = {};
@override
void initState() {
@@ -72,250 +43,129 @@ class _EpisodeCommentsSheetState extends State<EpisodeCommentsSheet> {
@override
void didUpdateWidget(covariant EpisodeCommentsSheet oldWidget) {
super.didUpdateWidget(oldWidget);
- if (oldWidget.episode != widget.episode ||
- oldWidget.selection != widget.selection) {
+ final controllerChanged =
+ oldWidget.videoPageController != widget.videoPageController;
+ if (controllerChanged) {
+ _episodeInfoByIndex.clear();
+ }
+ if (oldWidget.selection != widget.selection ||
+ controllerChanged ||
+ (oldWidget.episode != widget.episode &&
+ widget.episode != _selectedEpisode)) {
_resetAndScheduleRefresh();
}
}
void _resetAndScheduleRefresh() {
- ep = 0;
- commentsQueryTimeout = false;
- commentsIsEmpty = false;
- final targetEpisode = widget.episode;
- final targetSelection = widget.selection;
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (!mounted ||
- widget.episode != targetEpisode ||
- widget.selection != targetSelection) {
- return;
- }
- if (videoPageController.episodeCommentsList.isEmpty) {
- _refreshIndicatorKey.currentState?.show();
- }
- });
+ final version = ++_requestVersion;
+ _selectedEpisode = widget.episode;
+ _hasError = false;
+ _isLoading = _controller.commentsEpisode != _selectedEpisode ||
+ _controller.episodeCommentsList.isEmpty;
+ if (_isLoading) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && version == _requestVersion) {
+ unawaited(_loadComments());
+ }
+ });
+ }
}
- Widget get episodeCommentsBody {
- return CustomScrollView(
- scrollBehavior: const ScrollBehavior().copyWith(
- scrollbars: false,
- dragDevices: {
- PointerDeviceKind.mouse,
- PointerDeviceKind.touch,
- PointerDeviceKind.trackpad
- },
- ),
- slivers: [
- SliverPadding(
- padding: const EdgeInsets.fromLTRB(12, 8, 12, 8),
- sliver: Observer(builder: (context) {
- if (commentsQueryTimeout) {
- return SliverFillRemaining(
- child: GeneralErrorWidget(
- errMsg: '评论获取失败',
- actions: [
- GeneralErrorButton(
- onPressed: () {
- _refreshIndicatorKey.currentState?.show();
- },
- text: '重试',
- ),
- ],
- ),
- );
- }
- if (commentsIsEmpty) {
- return const SliverFillRemaining(
- child: Center(
- child: Text('什么都没有找到 (´;ω;`)'),
- ),
- );
- }
- return SliverList(
- delegate: SliverChildBuilderDelegate(
- (context, index) {
- // Keep loaded image cards alive to avoid scroll jumps when
- // network images report their final size.
- return KeepAlive(
- keepAlive: true,
- child: IndexedSemantics(
- index: index,
- child: UserCommentsCard.episode(
- videoPageController.episodeCommentsList[index],
- ),
- ),
- );
- },
- childCount: videoPageController.episodeCommentsList.length,
- addAutomaticKeepAlives: false,
- addRepaintBoundaries: false,
- addSemanticIndexes: false,
- ),
- );
- }),
- ),
- ],
- );
+ Future<void> _loadComments() async {
+ final version = ++_requestVersion;
+ setState(() {
+ _isLoading = true;
+ _hasError = false;
+ });
+ try {
+ final applied = await _controller.queryBangumiEpisodeCommentsByID(
+ _controller.bangumiItem.id, _selectedEpisode);
+ if (!mounted || version != _requestVersion || !applied) return;
+ if (_controller.episodeInfo.id != 0) {
+ _rememberEpisodeInfo(_selectedEpisode, _controller.episodeInfo);
+ }
+ setState(() => _isLoading = false);
+ } catch (_) {
+ if (!mounted || version != _requestVersion) return;
+ setState(() {
+ _isLoading = false;
+ _hasError = true;
+ });
+ }
}
- Widget get commentsInfo {
- return Padding(
- padding: const EdgeInsets.all(8),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- const Text(' 本集标题 '),
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- '${videoPageController.episodeInfo.readType()}.${videoPageController.episodeInfo.episode} ${videoPageController.episodeInfo.name}',
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: 12,
- color: Theme.of(context).colorScheme.outline)),
- Text(
- (videoPageController.episodeInfo.nameCn != '')
- ? '${videoPageController.episodeInfo.readType()}.${videoPageController.episodeInfo.episode} ${videoPageController.episodeInfo.nameCn}'
- : '${videoPageController.episodeInfo.readType()}.${videoPageController.episodeInfo.episode} ${videoPageController.episodeInfo.name}',
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: 12,
- color: Theme.of(context).colorScheme.outline)),
- ],
- ),
- ),
- const SizedBox(width: 10),
- SizedBox(
- height: 34,
- child: TextButton(
- style: ButtonStyle(
- padding: WidgetStateProperty.all(
- const EdgeInsets.only(left: 4.0, right: 4.0)),
- ),
- onPressed: () {
- showEpisodeSelection();
- },
- child: const Text(
- '手动切换',
- style: TextStyle(fontSize: 13),
- ),
- ),
- ),
- SizedBox(
- height: 34,
- child: TextButton(
- style: ButtonStyle(
- padding: WidgetStateProperty.all(
- const EdgeInsets.symmetric(horizontal: 4.0)),
- ),
- onPressed: toggleSortOrder,
- child: Observer(builder: (context) {
- return Text(
- videoPageController.isCommentsAscending ? '倒序' : '正序',
- style: const TextStyle(fontSize: 13),
- );
- }),
- ),
- ),
- ],
- ),
+ void _rememberEpisodeInfo(int index, EpisodeInfo info) {
+ // Playback resets the controller's EpisodeInfo in place when switching.
+ _episodeInfoByIndex[index] = EpisodeInfo(
+ id: info.id,
+ episode: info.episode,
+ type: info.type,
+ name: info.name,
+ nameCn: info.nameCn,
);
}
- void showEpisodeSelection() async {
- final int selectedEpisode = ep == 0 ? widget.episode : ep;
+ Future<void> _showEpisodeSelection() async {
+ if (_isSelectingEpisode) return;
+ _isSelectingEpisode = true;
+ final controller = _controller;
+ final selection = widget.selection;
KazumiDialog.showLoading(msg: '分集列表加载中');
- final List<EpisodeInfo> episodeList =
- await BangumiApi.getBangumiEpisodesByID(
- videoPageController.bangumiItem.id);
- KazumiDialog.dismiss();
- if (!mounted) {
- return;
- }
- if (episodeList.isEmpty) {
- KazumiDialog.showToast(message: '未找到分集列表');
- return;
+ try {
+ final episodes =
+ await BangumiApi.getBangumiEpisodesByID(controller.bangumiItem.id);
+ KazumiDialog.dismiss();
+ if (!mounted ||
+ controller != _controller ||
+ selection != widget.selection) {
+ return;
+ }
+ if (episodes.isEmpty) {
+ KazumiDialog.showToast(message: '未找到分集列表');
+ return;
+ }
+ for (var index = 0; index < episodes.length; index++) {
+ _rememberEpisodeInfo(index + 1, episodes[index]);
+ }
+ final selected = await KazumiDialog.show<int>(
+ context: context,
+ builder: (context) => EpisodeCommentsPicker(
+ episodes: episodes,
+ selectedEpisode: _selectedEpisode,
+ ),
+ );
+ if (!mounted ||
+ controller != _controller ||
+ selection != widget.selection ||
+ selected == null ||
+ selected == _selectedEpisode) {
+ return;
+ }
+ _selectedEpisode = selected;
+ unawaited(_loadComments());
+ } finally {
+ _isSelectingEpisode = false;
}
- KazumiDialog.show(
- builder: (context) {
- return Dialog(
- child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 560, maxHeight: 520),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- const Padding(
- padding: EdgeInsets.fromLTRB(24, 20, 24, 8),
- child: Text('分集列表', style: TextStyle(fontSize: 20)),
- ),
- Flexible(
- child: ListView.builder(
- shrinkWrap: true,
- itemCount: episodeList.length,
- itemBuilder: (context, index) {
- final episode = episodeList[index];
- final episodeTitle = episode.nameCn.isNotEmpty
- ? episode.nameCn
- : episode.name;
- final episodeText =
- '${episode.readType()}.${episode.episode}';
- final bool selected = index + 1 == selectedEpisode;
- return ListTile(
- selected: selected,
- title: Text(
- episodeTitle.isEmpty
- ? episodeText
- : '$episodeText $episodeTitle',
- overflow: TextOverflow.ellipsis,
- ),
- onTap: () {
- ep = index + 1;
- _refreshIndicatorKey.currentState?.show();
- KazumiDialog.dismiss();
- },
- );
- },
- ),
- ),
- Align(
- alignment: Alignment.centerRight,
- child: Padding(
- padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
- child: TextButton(
- onPressed: () => KazumiDialog.dismiss(),
- child: Text(
- '取消',
- style: TextStyle(
- color: Theme.of(context).colorScheme.outline),
- ),
- ),
- ),
- ),
- ],
- ),
- ),
- );
- },
- );
}
@override
Widget build(BuildContext context) {
- return Scaffold(
- body: RefreshIndicator(
- key: _refreshIndicatorKey,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [commentsInfo, Expanded(child: episodeCommentsBody)],
- ),
- onRefresh: () async {
- await loadComments(ep == 0 ? widget.episode : ep);
- },
- ),
- );
+ return Observer(builder: (context) {
+ final matchesEpisode = _controller.commentsEpisode == _selectedEpisode;
+ final comments = _controller.episodeCommentsList.toList();
+ return EpisodeCommentsView(
+ episode: _selectedEpisode,
+ episodeInfo: matchesEpisode && _controller.episodeInfo.id != 0
+ ? _controller.episodeInfo
+ : _episodeInfoByIndex[_selectedEpisode],
+ comments: matchesEpisode ? comments : [],
+ isLoading: _isLoading,
+ hasError: _hasError,
+ isAscending: _controller.isCommentsAscending,
+ onToggleSort: _controller.toggleSortOrder,
+ onSelectEpisode: _showEpisodeSelection,
+ onRefresh: _loadComments,
+ );
+ });
}
}
diff --git a/lib/pages/player/episode_comments_view.dart b/lib/pages/player/episode_comments_view.dart
new file mode 100644
index 00000000..ca7694e5
--- /dev/null
+++ b/lib/pages/player/episode_comments_view.dart
@@ -0,0 +1,376 @@
+import 'dart:ui';
+
+import 'package:flutter/material.dart';
+import 'package:kazumi/bean/card/user_comments_card.dart';
+import 'package:kazumi/bean/widget/loading_indicator.dart';
+import 'package:kazumi/modules/bangumi/episode_item.dart';
+import 'package:kazumi/modules/comments/comment_item.dart';
+
+class EpisodeCommentsView extends StatelessWidget {
+ const EpisodeCommentsView({
+ super.key,
+ required this.episode,
+ required this.episodeInfo,
+ required this.comments,
+ required this.isLoading,
+ required this.hasError,
+ required this.isAscending,
+ required this.onToggleSort,
+ required this.onSelectEpisode,
+ required this.onRefresh,
+ });
+
+ final int episode;
+ final EpisodeInfo? episodeInfo;
+ final List<EpisodeCommentItem> comments;
+ final bool isLoading;
+ final bool hasError;
+ final bool isAscending;
+ final VoidCallback onToggleSort;
+ final VoidCallback onSelectEpisode;
+ final VoidCallback onRefresh;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ return ColoredBox(
+ color: colors.surface,
+ child: LayoutBuilder(builder: (context, constraints) {
+ final gutter = constraints.maxWidth > 760
+ ? (constraints.maxWidth - 728) / 2
+ : 16.0;
+ return CustomScrollView(
+ key: ValueKey(episode),
+ scrollBehavior: const ScrollBehavior().copyWith(
+ scrollbars: false,
+ dragDevices: {
+ PointerDeviceKind.mouse,
+ PointerDeviceKind.touch,
+ PointerDeviceKind.trackpad,
+ },
+ ),
+ slivers: [
+ SliverPadding(
+ padding: EdgeInsets.fromLTRB(gutter, 16, gutter, 0),
+ sliver: SliverToBoxAdapter(
+ child: _EpisodeHeader(
+ episode: episode,
+ info: episodeInfo,
+ onSelectEpisode: onSelectEpisode,
+ ),
+ ),
+ ),
+ SliverPadding(
+ padding: EdgeInsets.fromLTRB(gutter + 4, 16, gutter, 12),
+ sliver: SliverToBoxAdapter(child: _buildToolbar(context)),
+ ),
+ if (!isLoading && hasError && comments.isEmpty)
+ SliverToBoxAdapter(
+ child: _DiscussionState(
+ icon: Icons.cloud_off_rounded,
+ title: '评论暂时未能加载',
+ description: '请检查网络后重试,或切换分集查看讨论。',
+ action: FilledButton.icon(
+ onPressed: onRefresh,
+ icon: const Icon(Icons.refresh_rounded, size: 20),
+ label: const Text('重新加载'),
+ ),
+ ),
+ )
+ else if (!isLoading && comments.isEmpty)
+ SliverToBoxAdapter(
+ child: _DiscussionState(
+ icon: Icons.chat_bubble_outline_rounded,
+ title: '本集还没有讨论',
+ description: '换一集看看,或稍后回来刷新。',
+ action: FilledButton.tonalIcon(
+ onPressed: onSelectEpisode,
+ icon: const Icon(Icons.video_library_outlined, size: 20),
+ label: const Text('切换分集'),
+ ),
+ ),
+ )
+ else if (comments.isNotEmpty) ...[
+ if (hasError)
+ SliverPadding(
+ padding: EdgeInsets.fromLTRB(gutter, 0, gutter, 12),
+ sliver: SliverToBoxAdapter(
+ child: Material(
+ color: colors.errorContainer,
+ borderRadius: BorderRadius.circular(16),
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 4, 8, 4),
+ child: Row(children: [
+ Expanded(
+ child: Text('刷新失败,已保留现有讨论',
+ style:
+ TextStyle(color: colors.onErrorContainer)),
+ ),
+ TextButton(
+ onPressed: onRefresh,
+ style: TextButton.styleFrom(
+ foregroundColor: colors.onErrorContainer),
+ child: const Text('重试'),
+ ),
+ ]),
+ ),
+ ),
+ ),
+ ),
+ SliverPadding(
+ padding: EdgeInsets.symmetric(horizontal: gutter),
+ sliver: SliverList(
+ delegate: SliverChildBuilderDelegate(
+ (context, index) => KeepAlive(
+ // Retain BBCode image geometry and expanded discussions.
+ key: ObjectKey(comments[index]),
+ keepAlive: true,
+ child: IndexedSemantics(
+ index: index,
+ child: UserCommentsCard.episode(comments[index]),
+ ),
+ ),
+ childCount: comments.length,
+ findChildIndexCallback: (key) {
+ final index = comments.indexOf(
+ (key as ObjectKey).value as EpisodeCommentItem);
+ return index < 0 ? null : index;
+ },
+ addAutomaticKeepAlives: false,
+ addRepaintBoundaries: false,
+ addSemanticIndexes: false,
+ ),
+ ),
+ ),
+ SliverToBoxAdapter(
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
+ child: Text('已显示全部 ${comments.length} 条讨论 · 来自 Bangumi',
+ textAlign: TextAlign.center,
+ style: Theme.of(context)
+ .textTheme
+ .labelMedium
+ ?.copyWith(color: colors.onSurfaceVariant)),
+ ),
+ ),
+ ],
+ SliverToBoxAdapter(
+ child: SizedBox(height: MediaQuery.paddingOf(context).bottom),
+ ),
+ ],
+ );
+ }),
+ );
+ }
+
+ Widget _buildToolbar(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ final type = Theme.of(context).textTheme;
+ return LayoutBuilder(builder: (context, constraints) {
+ final title = Row(mainAxisSize: MainAxisSize.min, children: [
+ Text('讨论',
+ style: type.titleMedium?.copyWith(fontWeight: FontWeight.w700)),
+ if ((!isLoading && !hasError) || comments.isNotEmpty) ...[
+ const SizedBox(width: 8),
+ Container(
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
+ decoration: BoxDecoration(
+ color: colors.secondaryContainer,
+ borderRadius: BorderRadius.circular(20),
+ ),
+ child: Text('${comments.length}',
+ style: type.labelLarge
+ ?.copyWith(color: colors.onSecondaryContainer)),
+ ),
+ ],
+ ]);
+ final actions = Row(mainAxisSize: MainAxisSize.min, children: [
+ TextButton.icon(
+ onPressed: comments.length > 1 ? onToggleSort : null,
+ style: TextButton.styleFrom(minimumSize: const Size(48, 48)),
+ icon: Icon(
+ isAscending
+ ? Icons.arrow_upward_rounded
+ : Icons.arrow_downward_rounded,
+ size: 18),
+ label: Text(isAscending ? '最早优先' : '最新优先'),
+ ),
+ const SizedBox(width: 4),
+ SizedBox.square(
+ dimension: 48,
+ child: IconButton.filledTonal(
+ tooltip: isLoading ? '正在加载评论' : '刷新评论',
+ onPressed: isLoading ? null : onRefresh,
+ style: IconButton.styleFrom(
+ backgroundColor: colors.secondaryContainer,
+ disabledBackgroundColor: colors.secondaryContainer,
+ foregroundColor: colors.onSecondaryContainer,
+ disabledForegroundColor: colors.onSecondaryContainer,
+ ),
+ icon: isLoading
+ ? LoadingIndicator(
+ size: 24,
+ color: colors.onSecondaryContainer,
+ semanticsLabel: '正在加载评论',
+ )
+ : const Icon(Icons.refresh_rounded, size: 24),
+ ),
+ ),
+ ]);
+ if (constraints.maxWidth < 310 ||
+ MediaQuery.textScalerOf(context).scale(14) > 19) {
+ return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ title,
+ const SizedBox(height: 4),
+ Align(alignment: Alignment.centerRight, child: actions),
+ ]);
+ }
+ return Row(children: [title, const Spacer(), actions]);
+ });
+ }
+}
+
+class _EpisodeHeader extends StatelessWidget {
+ const _EpisodeHeader({
+ required this.episode,
+ required this.info,
+ required this.onSelectEpisode,
+ });
+
+ final int episode;
+ final EpisodeInfo? info;
+ final VoidCallback onSelectEpisode;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ final type = Theme.of(context).textTheme;
+ final number = info?.episode ?? episode;
+ final translatedTitle = info?.nameCn ?? '';
+ final originalTitle = info?.name ?? '';
+ final title = translatedTitle.isNotEmpty
+ ? translatedTitle
+ : originalTitle.isNotEmpty
+ ? originalTitle
+ : '第 $number 集';
+ final subtitle = originalTitle.isNotEmpty && originalTitle != title
+ ? originalTitle
+ : 'Bangumi 分集讨论';
+ final episodeType = info?.readType().toUpperCase() ?? 'EP';
+
+ return Material(
+ color: colors.primaryContainer,
+ borderRadius: BorderRadius.circular(28),
+ clipBehavior: Clip.antiAlias,
+ child: Padding(
+ padding: const EdgeInsets.all(20),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ SizedBox(
+ width: double.infinity,
+ child: Wrap(
+ alignment: WrapAlignment.spaceBetween,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ spacing: 12,
+ runSpacing: 12,
+ children: [
+ Container(
+ padding:
+ const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
+ decoration: BoxDecoration(
+ color: colors.primary,
+ borderRadius: BorderRadius.circular(12),
+ ),
+ child: Text('$episodeType $number'.trim(),
+ style: type.titleSmall?.copyWith(
+ color: colors.onPrimary,
+ fontWeight: FontWeight.w700)),
+ ),
+ FilledButton.icon(
+ onPressed: onSelectEpisode,
+ style: FilledButton.styleFrom(
+ minimumSize: const Size(48, 48),
+ backgroundColor: colors.surface,
+ foregroundColor: colors.primary,
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ ),
+ icon: const Icon(Icons.video_library_outlined, size: 18),
+ label: const Text('切换分集'),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(height: 16),
+ Semantics(
+ header: true,
+ child: Text(title,
+ style: type.titleLarge?.copyWith(
+ color: colors.onPrimaryContainer,
+ fontWeight: FontWeight.w700,
+ height: 1.3,
+ )),
+ ),
+ const SizedBox(height: 6),
+ // Reserve one line to prevent jumps when metadata arrives.
+ Tooltip(
+ message: subtitle,
+ child: Text(subtitle,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: type.bodySmall?.copyWith(
+ color: colors.onPrimaryContainer, height: 1.5)),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class _DiscussionState extends StatelessWidget {
+ const _DiscussionState({
+ required this.title,
+ required this.description,
+ required this.icon,
+ required this.action,
+ });
+
+ final String title;
+ final String description;
+ final IconData icon;
+ final Widget action;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ final type = Theme.of(context).textTheme;
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 32),
+ child: Column(children: [
+ Container(
+ width: 80,
+ height: 80,
+ decoration: BoxDecoration(
+ color: colors.secondaryContainer,
+ borderRadius: BorderRadius.circular(28),
+ ),
+ child: Center(
+ child: Icon(icon, size: 32, color: colors.onSecondaryContainer),
+ ),
+ ),
+ const SizedBox(height: 20),
+ Text(title,
+ textAlign: TextAlign.center,
+ style: type.titleMedium?.copyWith(fontWeight: FontWeight.w700)),
+ const SizedBox(height: 8),
+ Text(description,
+ textAlign: TextAlign.center,
+ style: type.bodyMedium
+ ?.copyWith(color: colors.onSurfaceVariant, height: 1.6)),
+ const SizedBox(height: 20),
+ action,
+ ]),
+ );
+ }
+}