Compare commits

...

2 Commits

Author SHA1 Message Date
lixi f873acf9a3 新增:帖子详情页真实数据整页替换——四态/真九宫格大图/评论区/关注双态,Feed 导航与互动全接线,demo 详情退役(T3-15/16)
CI / flutter-gates (push) Failing after 20s
- post_detail_page 整页重写:内存副本先渲染 + getPost 拉新、四态
 (loading/error+重试/ready/40403 提示后返回 Feed 并刷新);媒体全量
  ——单图原比例(高度钳制 [0.75w,1.33w])、多图真九宫格(D11 轮播
  弃用,本单裁定)+ InteractiveViewer 全屏大图(03 号拍板 E)
- 评论区:游标列表触底补页 + 底部输入条创建(幂等键在数据层)+
  仅本人评论渲染删除入口(40301/40404 服务端兜底);成败埋点对
 (durationMs 取输入会话起点、attemptSeq 会话内递增);CommentTile
  升共享组件(@ 回复前缀呈现、降级作者「宠友」占位)
- 关注双态钮(tonal +关注 / Outlined 已关注 + 取关确认)乐观翻转、
  回滚零动画 + SnackBar,user_followed/unfollowed(post_detail) 挂接;
  本人帖不渲染
- Feed 接通:整卡与评论钮导航详情(T3-14 占位提示移除)、点赞/收藏
  接共享 ToggleSync(详情与卡片同一实例跨页一致)、toggleError
  一次性 SnackBar 消费
- 主壳/装配:openPost 按 postId push;create demo 流不再导航已退役的
  demo 详情(发布页真实化留 T3-17);AppState 在 post_detail/Feed 面
  消费清零
- compose 冒烟(env 门控默认跳过):真链路发帖/点赞幂等/收藏/评论/
  删评一轮 + 断网点赞回滚(生产 ApiClient 异常链)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-09-09 13:39:10 +08:00
lixi 92524da8e2 新增:互动埋点与乐观更新视觉基建——字典 v3 互动八事件封装 + ToggleSync 成功上报与触点归因 + LikeButton 三层闪烁抑制动画(T3-16)
- community_interaction_analytics:post_liked/unliked、post_favorited/unfavorited、
  comment_create_succeeded/failed、user_followed/unfollowed 强类型封装(22 号
  白名单键集逐一对齐;textLengthBucket 分桶、httpStatus 由五位码推导、
  会话失效不上报);comment_create_started 锁死 unknown 不封装
- CommunityController:toggleLike/toggleBookmark 增 source 触点归因
 (feed / post_detail),成功响应后经注入的 interactionAnalytics 上报
 (乐观翻转与失败不报);adjustCommentCount 评论计数同源写入
 (详情副本与 Feed 卡片一并更新)
- LikeButton 升 Stateful:点按激活 240ms 弹性缩放 + 120ms 图标淡入、
  取消仅颜色渐出;回滚/对账零动画直接跳变、计数与状态成对更新、
  激活动画未播完等播完再跳(05 号 §3.5/§4);减弱动态设置降级瞬变

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-09-09 13:38:50 +08:00
15 changed files with 2749 additions and 265 deletions
+8 -1
View File
@@ -13,6 +13,7 @@ import 'package:patbond_flutter/features/auth/login_page.dart';
import 'package:patbond_flutter/features/auth/session_manager.dart'; import 'package:patbond_flutter/features/auth/session_manager.dart';
import 'package:patbond_flutter/features/auth/splash_page.dart'; import 'package:patbond_flutter/features/auth/splash_page.dart';
import 'package:patbond_flutter/features/community/community_controller.dart'; import 'package:patbond_flutter/features/community/community_controller.dart';
import 'package:patbond_flutter/features/community/community_interaction_analytics.dart';
import 'package:patbond_flutter/features/community/community_repository.dart'; import 'package:patbond_flutter/features/community/community_repository.dart';
import 'package:patbond_flutter/features/community/feed_analytics.dart'; import 'package:patbond_flutter/features/community/feed_analytics.dart';
import 'package:patbond_flutter/features/main/main_shell_page.dart'; import 'package:patbond_flutter/features/main/main_shell_page.dart';
@@ -50,6 +51,7 @@ class _AppState extends State<App> {
late final PetAnalytics petAnalytics; late final PetAnalytics petAnalytics;
late final HealthRecordAnalytics healthRecordAnalytics; late final HealthRecordAnalytics healthRecordAnalytics;
late final FeedAnalytics feedAnalytics; late final FeedAnalytics feedAnalytics;
late final CommunityInteractionAnalytics interactionAnalytics;
late final SessionTracker _sessionTracker; late final SessionTracker _sessionTracker;
late final AnalyticsService _analytics; late final AnalyticsService _analytics;
late final PageViewTracker _pageViewTracker; late final PageViewTracker _pageViewTracker;
@@ -95,9 +97,12 @@ class _AppState extends State<App> {
petsController = PetsController( petsController = PetsController(
repository: widget.petsRepository ?? _buildPetsRepository(), repository: widget.petsRepository ?? _buildPetsRepository(),
); );
// T3-14Feed segment 接线主壳(数据层 T3-12 就位) // T3-14Feed segment 接线主壳(数据层 T3-12 就位)T3-16 起
// 点赞/收藏成功埋点经 interactionAnalytics 在 controller 内上报。
interactionAnalytics = CommunityInteractionAnalytics(_analytics.trackEvent);
communityController = CommunityController( communityController = CommunityController(
repository: widget.communityRepository ?? _buildCommunityRepository(), repository: widget.communityRepository ?? _buildCommunityRepository(),
interactionAnalytics: interactionAnalytics,
); );
petAnalytics = PetAnalytics(_analytics.trackEvent); petAnalytics = PetAnalytics(_analytics.trackEvent);
healthRecordAnalytics = HealthRecordAnalytics(_analytics.trackEvent); healthRecordAnalytics = HealthRecordAnalytics(_analytics.trackEvent);
@@ -235,9 +240,11 @@ class _AppState extends State<App> {
appState: appState, appState: appState,
petsController: petsController, petsController: petsController,
communityController: communityController, communityController: communityController,
currentUserId: sessionManager.userId,
petAnalytics: petAnalytics, petAnalytics: petAnalytics,
healthRecordAnalytics: healthRecordAnalytics, healthRecordAnalytics: healthRecordAnalytics,
feedAnalytics: feedAnalytics, feedAnalytics: feedAnalytics,
interactionAnalytics: interactionAnalytics,
pageViewTracker: _pageViewTracker, pageViewTracker: _pageViewTracker,
onLogout: authRepository.logout, onLogout: authRepository.logout,
); );
+141
View File
@@ -0,0 +1,141 @@
import 'package:flutter/material.dart';
import 'package:patbond_flutter/core/theme/app_theme.dart';
import 'package:patbond_flutter/core/widgets/pet_avatar.dart';
import 'package:patbond_flutter/features/community/community_display.dart';
import 'package:patbond_flutter/features/community/community_models.dart';
/// 评论条目(05 号规范 §3.4,demo 气泡形态升共享):
/// `PetAvatar sm32` + 10 + 气泡(`surface` 底、`border` 1px、圆角 16、
/// padding 12)——作者名 13/w700 → 4 → 内容 bodyMedium → 6 → 底行
/// (时间 11 `inkSoft` + 仅本人评论的「删除」入口)。
///
/// - @ 回复(单层平铺,契约 replyToUser)以「回复 @昵称:」前缀呈现;
/// 降级作者统一「宠友」占位(isDegraded 一个判定口)。
/// - [onDelete] 非 null 才渲染删除入口——**权限判定在调用方**(17 号
/// 后端语义:仅评论作者可删,他人可见评论 403/40301);[deleting]
/// 期间入口替换为 14 转圈防重复提交。
/// - 评论点赞(§3.4 底行右端)无契约端点,M3 不渲染。
class CommentTile extends StatelessWidget {
const CommentTile({
required this.comment,
super.key,
this.onDelete,
this.deleting = false,
this.now,
});
final PostComment comment;
/// 删除回调;null = 非本人评论,不渲染删除入口。
final VoidCallback? onDelete;
/// 删除请求在途(入口转圈锁定)。
final bool deleting;
/// 相对时间的参考时钟(测试注入;缺省取当前时间)。
final DateTime? now;
@override
Widget build(BuildContext context) {
final replyTo = comment.replyToUser;
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
PetAvatar(size: PetAvatarSize.sm, url: comment.author.avatarUrl),
const SizedBox(width: 10),
Expanded(
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: AppColors.surface,
border: Border.all(color: AppColors.border),
borderRadius: BorderRadius.circular(16),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
authorDisplayName(comment.author),
style: const TextStyle(
color: AppColors.ink,
fontSize: 13,
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 4),
Text.rich(
TextSpan(
children: [
if (replyTo != null)
TextSpan(
text: '回复 @${authorDisplayName(replyTo)}',
style: const TextStyle(
color: AppColors.inkSoft,
fontWeight: FontWeight.w600,
),
),
TextSpan(text: comment.content),
],
),
style: Theme.of(context).textTheme.bodyMedium,
),
const SizedBox(height: 6),
Row(
children: [
Text(
feedRelativeTime(comment.createdAt, now: now),
style: const TextStyle(
color: AppColors.inkSoft,
fontSize: 11,
),
),
const Spacer(),
if (onDelete != null)
deleting
? const Padding(
padding: EdgeInsets.all(4),
child: SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(
strokeWidth: 2,
color: AppColors.inkSoft,
),
),
)
: Semantics(
label: '删除评论',
button: true,
child: InkWell(
onTap: onDelete,
borderRadius: BorderRadius.circular(
AppRadius.pill,
),
// 视觉 11 字,触控由 padding 撑到 ≥32
//(气泡内行高受限,不足 44 以热区扩展补偿)。
child: const Padding(
padding: EdgeInsets.symmetric(
horizontal: 10,
vertical: 8,
),
child: Text(
'删除',
style: TextStyle(
color: AppColors.inkSoft,
fontSize: 11,
fontWeight: FontWeight.w600,
),
),
),
),
),
],
),
],
),
),
),
],
);
}
}
+123 -13
View File
@@ -31,12 +31,21 @@ enum LikeButtonVariant {
final Color activeCountColor; final Color activeCountColor;
} }
/// 点赞/收藏交互钮(05 号规范 §3.5 静态规格):图标 20 + 计数 13/w600 /// 点赞/收藏交互钮(05 号规范 §3.5):图标 20 + 计数 13/w600未激活
/// 未激活一律 `inkSoft`6.59:1)。触控 44×44 由 padding 撑足。 /// 一律 `inkSoft`6.59:1)。触控 44×44 由 padding 撑足。
/// ///
/// T3-14 只做展示([onPressed] 传 null 即禁用态,仍按正常色渲染计数与 /// 乐观更新视觉(§3.5/§4 三层闪烁抑制的 UI 半边,状态本体由持有方经
/// 状态);乐观更新动画与 ToggleSync 接线属 T3-15/16。 /// ToggleSync 驱动):
class LikeButton extends StatelessWidget { ///
/// - **点按驱动**的状态变化:激活播 240ms 弹性缩放(1→1.25→1+ 图标
/// 120ms 淡入;取消仅 120ms 颜色渐出、无缩放。
/// - **非点按驱动**的状态变化(失败回滚 / 服务端对账):零动画直接跳变;
/// 若激活动画未播完,等播完再跳(避免动画中途反转的抖动,§4.3a)。
/// - 计数变化一律直接替换,不做滚动动画(回滚时无二次滚动)。
/// - 系统「减弱动态效果」开启时全部降级为瞬变。
///
/// [onPressed] 传 null 即纯展示禁用态(仍按正常色渲染计数与状态)。
class LikeButton extends StatefulWidget {
const LikeButton({ const LikeButton({
required this.variant, required this.variant,
required this.active, required this.active,
@@ -52,15 +61,106 @@ class LikeButton extends StatelessWidget {
final VoidCallback? onPressed; final VoidCallback? onPressed;
final String? semanticLabel; final String? semanticLabel;
@override
State<LikeButton> createState() => _LikeButtonState();
}
class _LikeButtonState extends State<LikeButton>
with SingleTickerProviderStateMixin {
late final AnimationController _scaleController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 240),
);
late final Animation<double> _scale = TweenSequence<double>([
TweenSequenceItem(
tween: Tween<double>(
begin: 1,
end: 1.25,
).chain(CurveTween(curve: Curves.easeOut)),
weight: 40,
),
TweenSequenceItem(
tween: Tween<double>(
begin: 1.25,
end: 1,
).chain(CurveTween(curve: Curves.easeOutBack)),
weight: 60,
),
]).animate(_scaleController);
/// 当前展示态(回滚等待动画播完期间可短暂落后于 widget.active)。
late bool _displayActive = widget.active;
/// 展示计数与状态成对更新(§4.3c:回滚不出现「心已灭计数未减」中间帧)。
late int _displayCount = widget.count;
/// 最近一次点按的期望目标态;didUpdateWidget 以此区分「点按驱动」
/// (播动画)与「回滚/对账」(零动画跳变)。
bool? _expectedTarget;
/// 图标切换是否走 120ms 淡入淡出(点按驱动);回滚跳变置 false。
bool _fadeSwap = false;
bool get _reduceMotion =>
MediaQuery.maybeOf(context)?.disableAnimations ?? false;
@override
void didUpdateWidget(LikeButton oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.active == widget.active) {
// 状态未变的计数变化 = 服务端对账:静默替换、不播动画(§4.4)。
_displayCount = widget.count;
return;
}
final tapDriven = _expectedTarget == widget.active;
_expectedTarget = null;
if (tapDriven && !_reduceMotion) {
_fadeSwap = true;
_displayActive = widget.active;
_displayCount = widget.count;
if (widget.active) _scaleController.forward(from: 0);
return;
}
// 回滚 / 对账:零动画、计数与状态成对跳变。激活动画未播完则等
// 播完再跳(§4.3a,避免动画中途反转的抖动)。
_fadeSwap = false;
if (_scaleController.isAnimating) {
_scaleController.forward().whenComplete(() {
if (mounted) {
setState(() {
_displayActive = widget.active;
_displayCount = widget.count;
});
}
});
} else {
_displayActive = widget.active;
_displayCount = widget.count;
}
}
void _handleTap() {
_expectedTarget = !widget.active;
widget.onPressed!();
}
@override
void dispose() {
_scaleController.dispose();
super.dispose();
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final variant = widget.variant;
final active = _displayActive;
final iconColor = active ? variant.activeIconColor : AppColors.inkSoft; final iconColor = active ? variant.activeIconColor : AppColors.inkSoft;
final countColor = active ? variant.activeCountColor : AppColors.inkSoft; final countColor = active ? variant.activeCountColor : AppColors.inkSoft;
return Semantics( return Semantics(
label: semanticLabel, label: widget.semanticLabel,
button: onPressed != null, button: widget.onPressed != null,
child: InkWell( child: InkWell(
onTap: onPressed, onTap: widget.onPressed == null ? null : _handleTap,
borderRadius: BorderRadius.circular(AppRadius.pill), borderRadius: BorderRadius.circular(AppRadius.pill),
child: ConstrainedBox( child: ConstrainedBox(
constraints: const BoxConstraints(minWidth: 44, minHeight: 44), constraints: const BoxConstraints(minWidth: 44, minHeight: 44),
@@ -69,14 +169,24 @@ class LikeButton extends StatelessWidget {
child: Row( child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Icon( ScaleTransition(
active ? variant.activeIcon : variant.inactiveIcon, scale: _scale,
size: 20, child: AnimatedSwitcher(
color: iconColor, duration: _fadeSwap
? const Duration(milliseconds: 120)
: Duration.zero,
child: Icon(
active ? variant.activeIcon : variant.inactiveIcon,
key: ValueKey(active),
size: 20,
color: iconColor,
),
),
), ),
const SizedBox(width: 4), const SizedBox(width: 4),
// 计数直接替换(§3.5:不做滚动动画,避免回滚二次滚动)。
Text( Text(
'$count', '$_displayCount',
style: TextStyle( style: TextStyle(
color: countColor, color: countColor,
fontSize: 13, fontSize: 13,
@@ -1,5 +1,6 @@
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:patbond_flutter/core/network/api_exception.dart'; import 'package:patbond_flutter/core/network/api_exception.dart';
import 'package:patbond_flutter/features/community/community_interaction_analytics.dart';
import 'package:patbond_flutter/features/community/community_models.dart'; import 'package:patbond_flutter/features/community/community_models.dart';
import 'package:patbond_flutter/features/community/community_repository.dart'; import 'package:patbond_flutter/features/community/community_repository.dart';
import 'package:patbond_flutter/features/community/toggle_sync.dart'; import 'package:patbond_flutter/features/community/toggle_sync.dart';
@@ -18,7 +19,7 @@ enum LoadMorePhase { idle, loading, error }
/// 评论列表只属详情页,按「页面级状态按页自建」纪律经 [repository] /// 评论列表只属详情页,按「页面级状态按页自建」纪律经 [repository]
/// 自取,不膨胀本控制器。服务端是唯一事实来源,内存副本仅作展示缓存。 /// 自取,不膨胀本控制器。服务端是唯一事实来源,内存副本仅作展示缓存。
class CommunityController extends ChangeNotifier { class CommunityController extends ChangeNotifier {
CommunityController({required this._repository}) { CommunityController({required this._repository, this._interactionAnalytics}) {
_likeSync = ToggleSync( _likeSync = ToggleSync(
read: (id) { read: (id) {
final post = _postCache[id]; final post = _postCache[id];
@@ -35,6 +36,11 @@ class CommunityController extends ChangeNotifier {
final state = target final state = target
? await _repository.likePost(id) ? await _repository.likePost(id)
: await _repository.unlikePost(id); : await _repository.unlikePost(id);
// 成功响应后上报(06 §1.4 口径;乐观翻转与失败均不报)。
final source = _likeSources[id] ?? InteractionSource.feed;
target
? _interactionAnalytics?.postLiked(source: source)
: _interactionAnalytics?.postUnliked(source: source);
return ToggleOutcome(active: state.liked, count: state.likeCount); return ToggleOutcome(active: state.liked, count: state.likeCount);
}, },
generation: () => _generation, generation: () => _generation,
@@ -62,6 +68,10 @@ class CommunityController extends ChangeNotifier {
final state = target final state = target
? await _repository.bookmarkPost(id) ? await _repository.bookmarkPost(id)
: await _repository.unbookmarkPost(id); : await _repository.unbookmarkPost(id);
final source = _bookmarkSources[id] ?? InteractionSource.feed;
target
? _interactionAnalytics?.postFavorited(source: source)
: _interactionAnalytics?.postUnfavorited(source: source);
return ToggleOutcome( return ToggleOutcome(
active: state.bookmarked, active: state.bookmarked,
count: state.bookmarkCount, count: state.bookmarkCount,
@@ -73,6 +83,12 @@ class CommunityController extends ChangeNotifier {
} }
final CommunityRepository _repository; final CommunityRepository _repository;
final CommunityInteractionAnalytics? _interactionAnalytics;
/// 各帖最近一次 toggle 的触点来源(Feed 卡片 / 详情页共享同一实例,
/// 成功响应上报时按发起触点归因)。
final Map<String, InteractionSource> _likeSources = {};
final Map<String, InteractionSource> _bookmarkSources = {};
/// 页面级状态(评论列表、我的帖子、收藏页等)按页直接经仓库取数。 /// 页面级状态(评论列表、我的帖子、收藏页等)按页直接经仓库取数。
CommunityRepository get repository => _repository; CommunityRepository get repository => _repository;
@@ -193,10 +209,34 @@ class CommunityController extends ChangeNotifier {
} }
/// 点赞/取消点赞(乐观翻转,终态由 [ToggleSync] 对账收敛,不外抛)。 /// 点赞/取消点赞(乐观翻转,终态由 [ToggleSync] 对账收敛,不外抛)。
void toggleLike(String postId) => _likeSync.toggle(postId); /// [source] 为触点来源(埋点归因),Feed 卡片缺省 feed、详情页传
/// post_detail。
void toggleLike(
String postId, {
InteractionSource source = InteractionSource.feed,
}) {
_likeSources[postId] = source;
_likeSync.toggle(postId);
}
/// 收藏/取消收藏(与点赞同构)。 /// 收藏/取消收藏(与点赞同构)。
void toggleBookmark(String postId) => _bookmarkSync.toggle(postId); void toggleBookmark(
String postId, {
InteractionSource source = InteractionSource.feed,
}) {
_bookmarkSources[postId] = source;
_bookmarkSync.toggle(postId);
}
/// 评论创建/删除后的计数调整(详情页与 Feed 卡片同源写入,
/// 服务端 comment_count 由写侧同事务维护,本地只做展示对齐)。
void adjustCommentCount(String postId, int delta) {
final current =
_postCache[postId]?.commentCount ?? _cardOrNull(postId)?.commentCount;
if (current == null) return;
final next = current + delta;
_writeInteraction(postId, commentCount: next < 0 ? 0 : next);
}
/// 消费一次性 toggle 错误(SnackBar 展示后清除)。 /// 消费一次性 toggle 错误(SnackBar 展示后清除)。
void clearToggleError() => _toggleError = null; void clearToggleError() => _toggleError = null;
@@ -215,6 +255,8 @@ class CommunityController extends ChangeNotifier {
_loadMoreError = null; _loadMoreError = null;
_toggleError = null; _toggleError = null;
_postCache.clear(); _postCache.clear();
_likeSources.clear();
_bookmarkSources.clear();
_likeSync.reset(); _likeSync.reset();
_bookmarkSync.reset(); _bookmarkSync.reset();
_notify(); _notify();
@@ -234,6 +276,7 @@ class CommunityController extends ChangeNotifier {
int? likeCount, int? likeCount,
bool? bookmarkedByMe, bool? bookmarkedByMe,
int? bookmarkCount, int? bookmarkCount,
int? commentCount,
}) { }) {
final post = _postCache[postId]; final post = _postCache[postId];
if (post != null) { if (post != null) {
@@ -242,6 +285,7 @@ class CommunityController extends ChangeNotifier {
likeCount: likeCount, likeCount: likeCount,
bookmarkedByMe: bookmarkedByMe, bookmarkedByMe: bookmarkedByMe,
bookmarkCount: bookmarkCount, bookmarkCount: bookmarkCount,
commentCount: commentCount,
); );
} }
final index = _feed.indexWhere((card) => card.id == postId); final index = _feed.indexWhere((card) => card.id == postId);
@@ -252,6 +296,7 @@ class CommunityController extends ChangeNotifier {
likeCount: likeCount, likeCount: likeCount,
bookmarkedByMe: bookmarkedByMe, bookmarkedByMe: bookmarkedByMe,
bookmarkCount: bookmarkCount, bookmarkCount: bookmarkCount,
commentCount: commentCount,
); );
} }
if (post != null || index != -1) _notify(); if (post != null || index != -1) _notify();
@@ -0,0 +1,137 @@
import 'package:patbond_flutter/analytics/page_view_tracker.dart';
import 'package:patbond_flutter/core/network/api_exception.dart';
/// 互动域埋点强类型封装(06 号规划 §1.4 字典 v3 互动八事件;后端白名单
/// 已随 api dev@8089c06 就绪,22 号报告 §1)。沿 pet/feed 域惯例:枚举
/// 编译期锁死,业务代码禁止手拼事件名与属性;只记行为不记内容
/// (隐私红线:postId/commentId 等内容 ID 一律不进 props)。
///
/// 点赞/收藏/关注**不埋失败**(06 §1.4 取舍:幂等写入单点交互,失败率
/// 靠服务端错误率观测);`comment_create_started` 被字典锁死 unknown
/// 不得上报(22 号 §1 末段)。
/// 互动触点来源(06 §1.4 source 枚举)。M3 接 feed / post_detail
/// user_profile / follow_list 随后续页面启用。
enum InteractionSource {
feed('feed'),
postDetail('post_detail'),
userProfile('user_profile'),
followList('follow_list');
const InteractionSource(this.value);
final String value;
}
/// 评论创建失败原因(06 §1.4 失败枚举基底)。网络归并口径同 pet/feed 域:
/// 断网/超时/5xx 均并入 network_errorserver_error 保留兜底。
enum CommentCreateFailureReason {
validationError('validation_error'),
notFound('not_found'),
rateLimited('rate_limited'),
networkError('network_error'),
serverError('server_error');
const CommentCreateFailureReason(this.value);
final String value;
}
/// 类型化异常 → 评论失败原因;会话失效返回 null(应用即将回登录页,
/// 不作为评论失败上报,feed 域同款口径)。
CommentCreateFailureReason? commentCreateFailureReasonOf(ApiException error) =>
switch (error) {
ApiNetworkException _ => CommentCreateFailureReason.networkError,
ApiRateLimitException _ => CommentCreateFailureReason.rateLimited,
SessionExpiredException _ => null,
ApiBusinessException(:final code) => switch (code) {
ApiCodes.paramError => CommentCreateFailureReason.validationError,
ApiCodes.postNotFound ||
ApiCodes.commentNotFound ||
ApiCodes.communityUserNotFound => CommentCreateFailureReason.notFound,
_ => CommentCreateFailureReason.serverError,
},
};
/// 正文规模分桶(06 §1.3 隐私红线 1:不报精确字数)。
/// empty / short(≤50) / medium(51500) / long(>500)。
String textLengthBucketOf(int length) {
if (length <= 0) return 'empty';
if (length <= 50) return 'short';
if (length <= 500) return 'medium';
return 'long';
}
class CommunityInteractionAnalytics {
CommunityInteractionAnalytics(this._track);
/// 生产传 `AnalyticsService.trackEvent`,测试传录制桩。
final TrackEventFn _track;
/// 点赞成功响应后(乐观翻转本身不报;单飞合并链每个实际抵达服务端
/// 并成功的状态变更各报一条,与「成功响应后」的字典口径一致)。
void postLiked({required InteractionSource source}) {
_track('post_liked', {'source': source.value});
}
/// 取消点赞成功响应后。
void postUnliked({required InteractionSource source}) {
_track('post_unliked', {'source': source.value});
}
/// 收藏成功响应后。
void postFavorited({required InteractionSource source}) {
_track('post_favorited', {'source': source.value});
}
/// 取消收藏成功响应后。
void postUnfavorited({required InteractionSource source}) {
_track('post_unfavorited', {'source': source.value});
}
/// 评论提交成功响应后。
///
/// [durationMs]:本次输入会话(首个字符输入)→ 成功响应的耗时
/// (评论不设 started 事件,时长随成功事件带出);
/// [textLength] 经 [textLengthBucketOf] 分桶后上报,精确字数不出端。
void commentCreateSucceeded({
required int durationMs,
required bool isReply,
required int textLength,
}) {
_track('comment_create_succeeded', {
'durationMs': durationMs,
'isReply': isReply,
'textLengthBucket': textLengthBucketOf(textLength),
});
}
/// 评论提交失败。
///
/// [errorCode] 为业务错误码(网络错误时缺席);[httpStatus] 由五位
/// 业务码推导(`code ~/ 100`pet 域同款口径);[attemptSeq] 为本次
/// 输入会话内第几次提交尝试(从 1 起,成功或清空输入后重置)。
void commentCreateFailed({
required CommentCreateFailureReason reason,
required int attemptSeq,
int? errorCode,
}) {
_track('comment_create_failed', {
'failureReason': reason.value,
'attemptSeq': attemptSeq,
'errorCode': ?errorCode,
if (errorCode != null && errorCode >= 10000)
'httpStatus': errorCode ~/ 100,
});
}
/// 关注成功响应后。
void userFollowed({required InteractionSource source}) {
_track('user_followed', {'source': source.value});
}
/// 取关成功响应后。
void userUnfollowed({required InteractionSource source}) {
_track('user_unfollowed', {'source': source.value});
}
}
+24 -9
View File
@@ -26,6 +26,7 @@ class HomePage extends StatefulWidget {
required this.onOpenServices, required this.onOpenServices,
required this.onOpenCreate, required this.onOpenCreate,
super.key, super.key,
this.onOpenPost,
this.feedAnalytics, this.feedAnalytics,
this.isActive = true, this.isActive = true,
}); });
@@ -38,6 +39,9 @@ class HomePage extends StatefulWidget {
final ValueChanged<bool> onOpenServices; final ValueChanged<bool> onOpenServices;
final VoidCallback onOpenCreate; final VoidCallback onOpenCreate;
/// 帖子详情导航(T3-15 接通;主壳 push PostDetailPage)。
final ValueChanged<String>? onOpenPost;
/// feed 域埋点(feed_viewed 聚合曝光 + feed_load_failed)。 /// feed 域埋点(feed_viewed 聚合曝光 + feed_load_failed)。
final FeedAnalytics? feedAnalytics; final FeedAnalytics? feedAnalytics;
@@ -231,14 +235,6 @@ class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
} }
} }
/// T3-14 取舍:详情页数据层重写属 T3-15,demo 详情页无法按服务端
/// postId 渲染真实帖,故整卡点按先提示、互动按钮为纯展示禁用态。
void _showDetailPending() {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(const SnackBar(content: Text('帖子详情正在接入真实数据,敬请期待')));
}
/// 搜索词过滤(demo 交互保留:只过滤已加载的多页缓存,不发检索请求; /// 搜索词过滤(demo 交互保留:只过滤已加载的多页缓存,不发检索请求;
/// 契约 v1.3.0 无搜索端点)。 /// 契约 v1.3.0 无搜索端点)。
List<FeedCard> get _visibleCards { List<FeedCard> get _visibleCards {
@@ -309,6 +305,17 @@ class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
return ListenableBuilder( return ListenableBuilder(
listenable: _feed, listenable: _feed,
builder: (context, _) { builder: (context, _) {
// 点赞/收藏对账失败的一次性 SnackBar(§3.5 回滚提示;与详情页
// 共用 controller 的 toggleError 消费口,先消费者清空)。
if (_feed.toggleError != null) {
_feed.clearToggleError();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('操作失败,请重试')));
});
}
// ready 后(含翻页追加)补一次可见性扫描:无滚动也能记首屏曝光。 // ready 后(含翻页追加)补一次可见性扫描:无滚动也能记首屏曝光。
if (_viewSegment != null && _feed.phase == FeedPhase.ready) { if (_viewSegment != null && _feed.phase == FeedPhase.ready) {
_scheduleVisibilityScan(); _scheduleVisibilityScan();
@@ -467,7 +474,15 @@ class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
padding: const EdgeInsets.only(bottom: 16), padding: const EdgeInsets.only(bottom: 16),
child: KeyedSubtree( child: KeyedSubtree(
key: _cardKeys.putIfAbsent(card.id, GlobalKey.new), key: _cardKeys.putIfAbsent(card.id, GlobalKey.new),
child: PostCard(card: card, onTap: _showDetailPending), // 点赞/收藏经共享 ToggleSyncsource=feed 缺省);整卡与
// 评论钮进详情(T3-15 导航接通,T3-14 的占位提示移除)。
child: PostCard(
card: card,
onTap: () => widget.onOpenPost?.call(card.id),
onCommentTap: () => widget.onOpenPost?.call(card.id),
onLikeTap: () => _feed.toggleLike(card.id),
onBookmarkTap: () => _feed.toggleBookmark(card.id),
),
), ),
), ),
// 搜索过滤中不渲染尾部(过滤只作用于已加载页,翻页语义混淆)。 // 搜索过滤中不渲染尾部(过滤只作用于已加载页,翻页语义混淆)。
+22 -10
View File
@@ -3,6 +3,7 @@ import 'package:patbond_flutter/analytics/analytics_page_name.dart';
import 'package:patbond_flutter/analytics/page_view_tracker.dart'; import 'package:patbond_flutter/analytics/page_view_tracker.dart';
import 'package:patbond_flutter/core/theme/app_theme.dart'; import 'package:patbond_flutter/core/theme/app_theme.dart';
import 'package:patbond_flutter/features/community/community_controller.dart'; import 'package:patbond_flutter/features/community/community_controller.dart';
import 'package:patbond_flutter/features/community/community_interaction_analytics.dart';
import 'package:patbond_flutter/features/community/feed_analytics.dart'; import 'package:patbond_flutter/features/community/feed_analytics.dart';
import 'package:patbond_flutter/features/create/create_page.dart'; import 'package:patbond_flutter/features/create/create_page.dart';
import 'package:patbond_flutter/features/home/home_page.dart'; import 'package:patbond_flutter/features/home/home_page.dart';
@@ -13,7 +14,6 @@ import 'package:patbond_flutter/features/pets/pets_page.dart';
import 'package:patbond_flutter/features/post/post_detail_page.dart'; import 'package:patbond_flutter/features/post/post_detail_page.dart';
import 'package:patbond_flutter/features/profile/profile_page.dart'; import 'package:patbond_flutter/features/profile/profile_page.dart';
import 'package:patbond_flutter/features/services/services_page.dart'; import 'package:patbond_flutter/features/services/services_page.dart';
import 'package:patbond_flutter/models/models.dart';
import 'package:patbond_flutter/state/app_state.dart'; import 'package:patbond_flutter/state/app_state.dart';
import 'package:patbond_flutter/widgets/common.dart'; import 'package:patbond_flutter/widgets/common.dart';
@@ -23,9 +23,11 @@ class MainShellPage extends StatefulWidget {
required this.petsController, required this.petsController,
required this.communityController, required this.communityController,
super.key, super.key,
this.currentUserId,
this.petAnalytics, this.petAnalytics,
this.healthRecordAnalytics, this.healthRecordAnalytics,
this.feedAnalytics, this.feedAnalytics,
this.interactionAnalytics,
this.pageViewTracker, this.pageViewTracker,
this.onLogout, this.onLogout,
}); });
@@ -38,6 +40,9 @@ class MainShellPage extends StatefulWidget {
/// 社区状态(T3-12 数据层;首页 Feed segment 数据源,T3-14 接线)。 /// 社区状态(T3-12 数据层;首页 Feed segment 数据源,T3-14 接线)。
final CommunityController communityController; final CommunityController communityController;
/// 当前登录用户 id(详情页评论删除入口 / 关注钮自见性的 UI 判定)。
final String? currentUserId;
/// pet 域埋点强类型封装(建宠漏斗三事件)。 /// pet 域埋点强类型封装(建宠漏斗三事件)。
final PetAnalytics? petAnalytics; final PetAnalytics? petAnalytics;
@@ -47,6 +52,9 @@ class MainShellPage extends StatefulWidget {
/// feed 域埋点(T3-14 聚合曝光 + 加载失败)。 /// feed 域埋点(T3-14 聚合曝光 + 加载失败)。
final FeedAnalytics? feedAnalytics; final FeedAnalytics? feedAnalytics;
/// 互动域埋点(T3-16 评论成败对 + 关注对;详情页消费)。
final CommunityInteractionAnalytics? interactionAnalytics;
/// Tab 曝光补点(IndexedStack 切换不产生路由事件,03 号评估 §3.2)。 /// Tab 曝光补点(IndexedStack 切换不产生路由事件,03 号评估 §3.2)。
final PageViewTracker? pageViewTracker; final PageViewTracker? pageViewTracker;
@@ -93,12 +101,18 @@ class _MainShellPageState extends State<MainShellPage> {
widget.pageViewTracker?.reportTab(_tabPages[3]); widget.pageViewTracker?.reportTab(_tabPages[3]);
} }
void openPost(PostModel post) { /// 帖子详情(T3-15:真实数据整页;Feed 卡片与详情共享
/// communityController,互动状态跨页一致)。
void openPost(String postId) {
Navigator.of(context).push( Navigator.of(context).push(
MaterialPageRoute<void>( MaterialPageRoute<void>(
settings: RouteSettings(name: AnalyticsPageName.postDetail.pageName), settings: RouteSettings(name: AnalyticsPageName.postDetail.pageName),
builder: (context) => builder: (context) => PostDetailPage(
PostDetailPage(appState: widget.appState, postId: post.id), controller: widget.communityController,
postId: postId,
currentUserId: widget.currentUserId,
analytics: widget.interactionAnalytics,
),
), ),
); );
} }
@@ -122,15 +136,13 @@ class _MainShellPageState extends State<MainShellPage> {
isActive: currentIndex == 0, isActive: currentIndex == 0,
onOpenServices: openServices, onOpenServices: openServices,
onOpenCreate: () => selectTab(1), onOpenCreate: () => selectTab(1),
onOpenPost: openPost,
), ),
CreatePage( CreatePage(
appState: widget.appState, appState: widget.appState,
onPublished: (post) { // demo 详情页已退役(T3-15):demo 发布流不再导航详情,
selectTab(0); // 回首页 Feed;发布页真实化随 T3-17 收编。
WidgetsBinding.instance.addPostFrameCallback( onPublished: (_) => selectTab(0),
(_) => openPost(post),
);
},
), ),
PetsPage( PetsPage(
controller: widget.petsController, controller: widget.petsController,
File diff suppressed because it is too large Load Diff
+75
View File
@@ -0,0 +1,75 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:patbond_flutter/core/theme/app_theme.dart';
import 'package:patbond_flutter/core/widgets/comment_tile.dart';
import '../../helpers/community_test_helpers.dart';
void main() {
final now = DateTime.parse('2026-09-08T13:00:00.000Z');
Widget wrap(Widget child) => MaterialApp(
theme: buildAppTheme(),
home: Scaffold(body: Center(child: child)),
);
testWidgets('渲染作者名 / 内容 / 相对时间;无 onDelete 不显删除', (tester) async {
await tester.pumpWidget(
wrap(CommentTile(comment: sampleComment(), now: now)),
);
expect(find.text('毛毛的铲屎官'), findsOneWidget);
expect(find.text('好可爱!', findRichText: true), findsOneWidget);
expect(find.text('2 小时前'), findsOneWidget);
expect(find.text('删除'), findsNothing);
});
testWidgets('@ 回复以「回复 @昵称:」前缀呈现;降级作者「宠友」占位', (tester) async {
await tester.pumpWidget(
wrap(
CommentTile(
comment: sampleComment(
author: sampleAuthorJson(nickname: null, avatarUrl: null),
replyToUser: sampleAuthorJson(userId: 'u-2', nickname: '豆豆麻麻'),
),
now: now,
),
),
);
expect(find.text('宠友'), findsOneWidget);
expect(
find.textContaining('回复 @豆豆麻麻:', findRichText: true),
findsOneWidget,
);
});
testWidgets('onDelete 提供时显删除入口并回调;deleting 期间转圈锁定', (tester) async {
var deleted = 0;
await tester.pumpWidget(
wrap(
CommentTile(
comment: sampleComment(),
now: now,
onDelete: () => deleted++,
),
),
);
await tester.tap(find.text('删除'));
expect(deleted, 1);
await tester.pumpWidget(
wrap(
CommentTile(
comment: sampleComment(),
now: now,
deleting: true,
onDelete: () => deleted++,
),
),
);
expect(find.text('删除'), findsNothing);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
});
}
+155
View File
@@ -0,0 +1,155 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:patbond_flutter/core/theme/app_theme.dart';
import 'package:patbond_flutter/core/widgets/like_button.dart';
/// 宿主:模拟持有方(controller)的状态翻转——点按经 [onTap] 乐观翻转,
/// 外部(回滚/对账)经 [setActive] 直接改。
class _Host extends StatefulWidget {
const _Host({required this.initialActive, required this.initialCount});
final bool initialActive;
final int initialCount;
@override
State<_Host> createState() => _HostState();
}
class _HostState extends State<_Host> {
late bool active = widget.initialActive;
late int count = widget.initialCount;
void setExternal({required bool active, required int count}) {
setState(() {
this.active = active;
this.count = count;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: buildAppTheme(),
home: Scaffold(
body: Center(
child: LikeButton(
variant: LikeButtonVariant.like,
active: active,
count: count,
onPressed: () => setState(() {
active = !active;
count += active ? 1 : -1;
}),
semanticLabel: '点赞',
),
),
),
);
}
}
void main() {
double scaleOf(WidgetTester tester) => tester
.widget<ScaleTransition>(
find.descendant(
of: find.byType(LikeButton),
matching: find.byType(ScaleTransition),
),
)
.scale
.value;
testWidgets('点按激活:240ms 弹性缩放动画(中途 >1,播完归位)', (tester) async {
await tester.pumpWidget(const _Host(initialActive: false, initialCount: 6));
await tester.tap(find.byIcon(Icons.favorite_border));
await tester.pump();
await tester.pump(const Duration(milliseconds: 90));
expect(scaleOf(tester), greaterThan(1.0));
expect(find.byIcon(Icons.favorite), findsOneWidget);
expect(find.text('7'), findsOneWidget);
await tester.pumpAndSettle();
expect(scaleOf(tester), 1.0);
});
testWidgets('点按取消:仅颜色切换,无缩放动画', (tester) async {
await tester.pumpWidget(const _Host(initialActive: true, initialCount: 7));
await tester.tap(find.byIcon(Icons.favorite));
await tester.pump();
await tester.pump(const Duration(milliseconds: 90));
expect(scaleOf(tester), 1.0);
expect(find.byIcon(Icons.favorite_border), findsOneWidget);
expect(find.text('6'), findsOneWidget);
await tester.pumpAndSettle();
});
testWidgets('外部回滚:零动画直接跳变,计数与状态成对恢复', (tester) async {
await tester.pumpWidget(const _Host(initialActive: false, initialCount: 6));
// 点按激活并播完动画(在途请求随后失败的场景)。
await tester.tap(find.byIcon(Icons.favorite_border));
await tester.pumpAndSettle();
expect(find.byIcon(Icons.favorite), findsOneWidget);
// 外部(非点按)回滚:下一帧即恢复,无过渡动画。
tester
.state<_HostState>(find.byType(_Host))
.setExternal(active: false, count: 6);
await tester.pump();
expect(find.byIcon(Icons.favorite_border), findsOneWidget);
expect(find.text('6'), findsOneWidget);
expect(scaleOf(tester), 1.0);
});
testWidgets('激活动画未播完时回滚:等播完再成对跳变(§4.3a 抖动抑制)', (tester) async {
await tester.pumpWidget(const _Host(initialActive: false, initialCount: 6));
await tester.tap(find.byIcon(Icons.favorite_border));
await tester.pump();
await tester.pump(const Duration(milliseconds: 60));
expect(find.byIcon(Icons.favorite), findsOneWidget);
// 动画中途回滚:本帧仍显示激活视觉(等待播完),计数同持。
tester
.state<_HostState>(find.byType(_Host))
.setExternal(active: false, count: 6);
await tester.pump();
expect(find.byIcon(Icons.favorite), findsOneWidget);
expect(find.text('7'), findsOneWidget);
// 播完后成对跳回。
await tester.pumpAndSettle();
expect(find.byIcon(Icons.favorite_border), findsOneWidget);
expect(find.text('6'), findsOneWidget);
});
testWidgets('对账静默:状态不变的计数变化直接替换,无动画', (tester) async {
await tester.pumpWidget(const _Host(initialActive: true, initialCount: 7));
tester
.state<_HostState>(find.byType(_Host))
.setExternal(active: true, count: 9);
await tester.pump();
expect(find.text('9'), findsOneWidget);
expect(scaleOf(tester), 1.0);
});
testWidgets('onPressed 为 null 时禁用但照常渲染激活态', (tester) async {
await tester.pumpWidget(
MaterialApp(
theme: buildAppTheme(),
home: const Scaffold(
body: LikeButton(
variant: LikeButtonVariant.bookmark,
active: true,
count: 2,
),
),
),
);
expect(find.byIcon(Icons.bookmark), findsOneWidget);
expect(find.text('2'), findsOneWidget);
});
}
@@ -0,0 +1,126 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:patbond_flutter/core/network/api_exception.dart';
import 'package:patbond_flutter/features/community/community_interaction_analytics.dart';
void main() {
late List<(String, Map<String, dynamic>?)> events;
late CommunityInteractionAnalytics analytics;
setUp(() {
events = [];
analytics = CommunityInteractionAnalytics(
(name, [props]) async => events.add((name, props)),
);
});
List<String> names() => events.map((e) => e.$1).toList();
List<Map<String, dynamic>?> props() => events.map((e) => e.$2).toList();
test('互动四事件:source 逐字段(22 号白名单键集)', () {
analytics.postLiked(source: InteractionSource.feed);
analytics.postUnliked(source: InteractionSource.postDetail);
analytics.postFavorited(source: InteractionSource.postDetail);
analytics.postUnfavorited(source: InteractionSource.feed);
expect(names(), [
'post_liked',
'post_unliked',
'post_favorited',
'post_unfavorited',
]);
expect(props(), [
{'source': 'feed'},
{'source': 'post_detail'},
{'source': 'post_detail'},
{'source': 'feed'},
]);
});
test('comment_create_succeededdurationMs/isReply/textLengthBucket', () {
analytics.commentCreateSucceeded(
durationMs: 4200,
isReply: false,
textLength: 12,
);
expect(names(), ['comment_create_succeeded']);
expect(props().single, {
'durationMs': 4200,
'isReply': false,
'textLengthBucket': 'short',
});
});
test('comment_create_failedhttpStatus 由五位业务码推导,网络错误缺席', () {
analytics.commentCreateFailed(
reason: CommentCreateFailureReason.validationError,
attemptSeq: 2,
errorCode: 40000,
);
analytics.commentCreateFailed(
reason: CommentCreateFailureReason.networkError,
attemptSeq: 3,
);
expect(names(), ['comment_create_failed', 'comment_create_failed']);
expect(props(), [
{
'failureReason': 'validation_error',
'attemptSeq': 2,
'errorCode': 40000,
'httpStatus': 400,
},
{'failureReason': 'network_error', 'attemptSeq': 3},
]);
});
test('关注对:user_followed / user_unfollowed', () {
analytics.userFollowed(source: InteractionSource.postDetail);
analytics.userUnfollowed(source: InteractionSource.postDetail);
expect(names(), ['user_followed', 'user_unfollowed']);
expect(props(), [
{'source': 'post_detail'},
{'source': 'post_detail'},
]);
});
test('textLengthBucketOf 分桶边界(06 §1.3 红线:不报精确字数)', () {
expect(textLengthBucketOf(0), 'empty');
expect(textLengthBucketOf(1), 'short');
expect(textLengthBucketOf(50), 'short');
expect(textLengthBucketOf(51), 'medium');
expect(textLengthBucketOf(500), 'medium');
expect(textLengthBucketOf(501), 'long');
});
test('失败原因映射:网络归并口径 + 防枚举族归 not_found + 会话失效 null', () {
expect(
commentCreateFailureReasonOf(const ApiNetworkException()),
CommentCreateFailureReason.networkError,
);
expect(
commentCreateFailureReasonOf(const ApiRateLimitException()),
CommentCreateFailureReason.rateLimited,
);
expect(
commentCreateFailureReasonOf(
const ApiBusinessException(code: ApiCodes.paramError, message: 'x'),
),
CommentCreateFailureReason.validationError,
);
expect(
commentCreateFailureReasonOf(
const ApiBusinessException(code: ApiCodes.postNotFound, message: 'x'),
),
CommentCreateFailureReason.notFound,
);
expect(
commentCreateFailureReasonOf(
const ApiBusinessException(code: 50000, message: 'x'),
),
CommentCreateFailureReason.serverError,
);
expect(
commentCreateFailureReasonOf(const SessionExpiredException()),
isNull,
);
});
}
+77 -3
View File
@@ -8,6 +8,7 @@ import 'package:patbond_flutter/core/widgets/feed_skeleton.dart';
import 'package:patbond_flutter/core/widgets/inline_error_banner.dart'; import 'package:patbond_flutter/core/widgets/inline_error_banner.dart';
import 'package:patbond_flutter/core/widgets/post_card.dart'; import 'package:patbond_flutter/core/widgets/post_card.dart';
import 'package:patbond_flutter/features/community/community_controller.dart'; import 'package:patbond_flutter/features/community/community_controller.dart';
import 'package:patbond_flutter/features/community/community_interaction_analytics.dart';
import 'package:patbond_flutter/features/community/community_models.dart'; import 'package:patbond_flutter/features/community/community_models.dart';
import 'package:patbond_flutter/features/community/feed_analytics.dart'; import 'package:patbond_flutter/features/community/feed_analytics.dart';
import 'package:patbond_flutter/features/home/home_page.dart'; import 'package:patbond_flutter/features/home/home_page.dart';
@@ -39,15 +40,22 @@ void main() {
late List<(String, Map<String, dynamic>?)> events; late List<(String, Map<String, dynamic>?)> events;
late FeedAnalytics analytics; late FeedAnalytics analytics;
late int createTaps; late int createTaps;
late List<String> openedPosts;
setUp(() { setUp(() {
repository = FakeCommunityRepository(); repository = FakeCommunityRepository();
controller = CommunityController(repository: repository);
events = []; events = [];
controller = CommunityController(
repository: repository,
interactionAnalytics: CommunityInteractionAnalytics(
(name, [props]) async => events.add((name, props)),
),
);
analytics = FeedAnalytics( analytics = FeedAnalytics(
(name, [props]) async => events.add((name, props)), (name, [props]) async => events.add((name, props)),
); );
createTaps = 0; createTaps = 0;
openedPosts = [];
}); });
List<Map<String, dynamic>?> eventsNamed(String name) => List<Map<String, dynamic>?> eventsNamed(String name) =>
@@ -65,6 +73,7 @@ void main() {
isActive: isActive, isActive: isActive,
onOpenServices: (_) {}, onOpenServices: (_) {},
onOpenCreate: () => createTaps++, onOpenCreate: () => createTaps++,
onOpenPost: openedPosts.add,
), ),
), ),
), ),
@@ -361,7 +370,7 @@ void main() {
expect(eventsNamed('feed_viewed'), hasLength(2)); expect(eventsNamed('feed_viewed'), hasLength(2));
}); });
testWidgets('T3-14 取舍:整卡点按提示详情接入中(不导航 demo 详情', (tester) async { testWidgets('T3-15 导航接通:整卡与评论钮点按回调 onOpenPost(占位提示移除', (tester) async {
repository.onFeed = (_, _) async => feedPage([textCard('p-1')]); repository.onFeed = (_, _) async => feedPage([textCard('p-1')]);
await pumpHome(tester); await pumpHome(tester);
@@ -371,7 +380,72 @@ void main() {
await tester.tap(find.text('动态内容 p-1')); await tester.tap(find.text('动态内容 p-1'));
await tester.pump(); await tester.pump();
expect(find.text('帖子详情正在接入真实数据,敬请期待'), findsOneWidget); expect(find.text('帖子详情正在接入真实数据,敬请期待'), findsNothing);
expect(openedPosts, ['p-1']);
await tester.tap(find.byIcon(Icons.chat_bubble_outline));
await tester.pump();
expect(openedPosts, ['p-1', 'p-1']);
});
testWidgets('T3-16 互动接线:点赞乐观翻转即时显示,成功报 post_liked(source=feed)', (
tester,
) async {
repository.onFeed = (_, _) async => feedPage([
FeedCard.fromJson({
...sampleFeedCardJson(likeCount: 6),
'coverImage': null,
'mediaCount': 0,
}),
]);
final like = Completer<LikeState>();
repository.onLikeToggle = (_, _) => like.future;
await pumpHome(tester);
await tester.pumpAndSettle();
await tester.drag(list(), const Offset(0, -800));
await tester.pumpAndSettle();
await tester.tap(find.byIcon(Icons.favorite_border));
await tester.pump();
// 乐观翻转:请求未回已 +1(同帧反馈)。
expect(find.text('7'), findsOneWidget);
expect(repository.calls, contains('like:p-1'));
like.complete(const LikeState(liked: true, likeCount: 7));
await tester.pumpAndSettle();
expect(eventsNamed('post_liked'), [
{'source': 'feed'},
]);
expect(find.text('7'), findsOneWidget);
});
testWidgets('T3-16 互动接线:点赞失败回滚 + SnackBar「操作失败,请重试」', (tester) async {
repository.onFeed = (_, _) async => feedPage([
FeedCard.fromJson({
...sampleFeedCardJson(likeCount: 6),
'coverImage': null,
'mediaCount': 0,
}),
]);
final like = Completer<LikeState>();
repository.onLikeToggle = (_, _) => like.future;
await pumpHome(tester);
await tester.pumpAndSettle();
await tester.drag(list(), const Offset(0, -800));
await tester.pumpAndSettle();
await tester.tap(find.byIcon(Icons.favorite_border));
await tester.pump();
expect(find.text('7'), findsOneWidget);
like.completeError(const ApiNetworkException());
await tester.pumpAndSettle();
// 回滚成对恢复 + SnackBar;不报 post_liked。
expect(find.text('6'), findsOneWidget);
expect(find.text('操作失败,请重试'), findsOneWidget);
expect(eventsNamed('post_liked'), isEmpty);
}); });
testWidgets('搜索词过滤已加载卡片;无命中显搜索空态', (tester) async { testWidgets('搜索词过滤已加载卡片;无命中显搜索空态', (tester) async {
@@ -0,0 +1,551 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:patbond_flutter/core/network/api_exception.dart';
import 'package:patbond_flutter/core/theme/app_theme.dart';
import 'package:patbond_flutter/core/widgets/comment_tile.dart';
import 'package:patbond_flutter/core/widgets/inline_error_banner.dart';
import 'package:patbond_flutter/core/widgets/post_media_grid.dart';
import 'package:patbond_flutter/features/community/community_controller.dart';
import 'package:patbond_flutter/features/community/community_exceptions.dart';
import 'package:patbond_flutter/features/community/community_interaction_analytics.dart';
import 'package:patbond_flutter/features/community/community_models.dart';
import 'package:patbond_flutter/features/post/post_detail_page.dart';
import '../../helpers/community_test_helpers.dart';
void main() {
late FakeCommunityRepository repository;
late CommunityController controller;
late List<(String, Map<String, dynamic>?)> events;
late CommunityInteractionAnalytics analytics;
/// 无媒体帖(避免测试环境网络图噪音;媒体形态单测另立)。
Post textPost({
String id = 'p-1',
bool likedByMe = false,
int likeCount = 6,
int commentCount = 3,
}) => Post.fromJson({
...samplePostJson(id: id, likedByMe: likedByMe, likeCount: likeCount),
'media': <Object>[],
'commentCount': commentCount,
});
setUp(() {
repository = FakeCommunityRepository();
events = [];
analytics = CommunityInteractionAnalytics(
(name, [props]) async => events.add((name, props)),
);
controller = CommunityController(
repository: repository,
interactionAnalytics: analytics,
);
// 缺省行为:正常帖 + 空评论 + 未关注(各测试按需覆盖)。
repository.onGetPost = (_) async => textPost();
repository.onListComments = (_, _) async => commentPage(const []);
repository.onGetFollowStats = (_) async => const FollowStats(
followerCount: 1,
followingCount: 2,
followedByMe: false,
);
});
List<Map<String, dynamic>?> eventsNamed(String name) =>
events.where((e) => e.$1 == name).map((e) => e.$2).toList();
Widget detailApp({String? currentUserId = 'me'}) => MaterialApp(
theme: buildAppTheme(),
home: PostDetailPage(
controller: controller,
postId: 'p-1',
currentUserId: currentUserId,
analytics: analytics,
),
);
/// 经启动页 push 详情(40403 返回 Feed 的 pop 断言用)。
Widget launcherApp({String? currentUserId = 'me'}) => MaterialApp(
theme: buildAppTheme(),
home: Builder(
builder: (context) => Scaffold(
body: Center(
child: TextButton(
onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => PostDetailPage(
controller: controller,
postId: 'p-1',
currentUserId: currentUserId,
analytics: analytics,
),
),
),
child: const Text('打开详情'),
),
),
),
),
);
group('详情四态', () {
testWidgets('loading:请求未回渲染转圈', (tester) async {
final post = Completer<Post>();
repository.onGetPost = (_) => post.future;
await tester.pumpWidget(detailApp());
await tester.pump();
expect(find.byType(CircularProgressIndicator), findsOneWidget);
post.complete(textPost());
await tester.pumpAndSettle();
expect(find.text('晒了一下午太阳。'), findsOneWidget);
});
testWidgets('ready:正文/作者/求助标/评论标题齐全', (tester) async {
await tester.pumpWidget(detailApp());
await tester.pumpAndSettle();
expect(find.text('今天的豆豆'), findsOneWidget);
expect(find.text('晒了一下午太阳。'), findsOneWidget);
expect(find.text('毛毛的铲屎官'), findsOneWidget);
expect(find.text('评论 (3)'), findsOneWidget);
expect(find.text('还没有评论,来抢沙发'), findsOneWidget);
});
testWidgets('error:横幅 + 重试恢复 ready', (tester) async {
var attempts = 0;
repository.onGetPost = (_) async {
attempts += 1;
if (attempts == 1) throw const ApiNetworkException();
return textPost();
};
await tester.pumpWidget(detailApp());
await tester.pumpAndSettle();
expect(find.byType(InlineErrorBanner), findsOneWidget);
expect(find.text('网络异常,请检查网络后重试'), findsOneWidget);
await tester.tap(find.text('重试'));
await tester.pumpAndSettle();
expect(find.byType(InlineErrorBanner), findsNothing);
expect(find.text('晒了一下午太阳。'), findsOneWidget);
});
testWidgets('40403 不存在态:SnackBar + 返回 Feed 并触发刷新', (tester) async {
repository.onGetPost = (_) async =>
throw const PostNotFoundException(message: 'gone');
repository.onFeed = (_, _) async => feedPage(const []);
await tester.pumpWidget(launcherApp());
await tester.tap(find.text('打开详情'));
await tester.pumpAndSettle();
// 已弹回启动页 + 提示 + Feed 整体刷新(失效帖剔除)。
expect(find.text('打开详情'), findsOneWidget);
expect(find.text('帖子不存在或已被删除'), findsOneWidget);
expect(repository.calls, contains('feed:cursor=null'));
});
testWidgets('内存副本先渲染:进入即展示缓存,后台拉新不阻塞', (tester) async {
await controller.getPost('p-1'); // 预热详情副本。
final refresh = Completer<Post>();
repository.onGetPost = (_) => refresh.future;
await tester.pumpWidget(detailApp());
await tester.pump();
// 拉新未回已渲染缓存内容,无全页转圈。
expect(find.text('晒了一下午太阳。'), findsOneWidget);
refresh.complete(textPost(likeCount: 9));
await tester.pumpAndSettle();
expect(find.text('9'), findsOneWidget);
});
});
group('媒体', () {
testWidgets('多图渲染真九宫格,点格进全屏大图(页码 + 关闭)', (tester) async {
repository.onGetPost = (_) async => Post.fromJson({
...samplePostJson(),
'media': [
for (var i = 0; i < 5; i++)
samplePostMediaItemJson(
assetId: 'a-$i',
position: i,
isCover: i == 0,
),
],
});
await tester.pumpWidget(detailApp());
await tester.pumpAndSettle();
expect(find.byType(PostMediaGrid), findsOneWidget);
await tester.tap(
find
.descendant(
of: find.byType(PostMediaGrid),
matching: find.byType(InkWell),
)
.first,
);
await tester.pumpAndSettle();
expect(find.text('1/5'), findsOneWidget);
await tester.tap(find.byIcon(Icons.close));
await tester.pumpAndSettle();
expect(find.byType(PostMediaGrid), findsOneWidget);
});
});
group('评论区', () {
testWidgets('游标列表:首页渲染 + 触底携游标补页', (tester) async {
repository.onListComments = (_, cursor) async {
if (cursor == null) {
return commentPage(
[
sampleComment(id: 'c-1', content: '第一条'),
sampleComment(id: 'c-2', content: '第二条'),
],
nextCursor: 'cc1',
hasMore: true,
);
}
return commentPage([sampleComment(id: 'c-3', content: '第三条')]);
};
await tester.pumpWidget(detailApp());
await tester.pumpAndSettle();
expect(find.text('第一条'), findsOneWidget);
await tester.drag(find.byType(ListView), const Offset(0, -800));
await tester.pumpAndSettle();
expect(
repository.calls.where((c) => c.startsWith('comments:')).toList(),
['comments:p-1:cursor=null', 'comments:p-1:cursor=cc1'],
);
expect(find.text('第三条'), findsOneWidget);
});
testWidgets('列表失败:话术 + 点按重试恢复', (tester) async {
var attempts = 0;
repository.onListComments = (_, _) async {
attempts += 1;
if (attempts == 1) throw const ApiNetworkException();
return commentPage([sampleComment(content: '恢复后的评论')]);
};
await tester.pumpWidget(detailApp());
await tester.pumpAndSettle();
expect(find.text('加载失败,点此重试'), findsOneWidget);
await tester.tap(find.text('加载失败,点此重试'));
await tester.pumpAndSettle();
expect(find.text('恢复后的评论'), findsOneWidget);
});
testWidgets('创建成功:插入列表头 + 计数 +1 + comment_create_succeeded + 清空输入', (
tester,
) async {
repository.onCreateComment = (_, request) async =>
sampleComment(id: 'c-new', content: request.content);
await tester.pumpWidget(detailApp());
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), '沙发!');
await tester.pump();
await tester.tap(find.byIcon(Icons.send_rounded));
await tester.pumpAndSettle();
expect(repository.calls, contains('createComment:p-1:沙发!'));
expect(find.text('沙发!'), findsOneWidget); // 列表中的新评论。
expect(find.text('评论 (4)'), findsOneWidget);
expect(
tester.widget<TextField>(find.byType(TextField)).controller?.text,
'',
);
final succeeded = eventsNamed('comment_create_succeeded').single!;
expect(succeeded['isReply'], false);
expect(succeeded['textLengthBucket'], 'short');
expect(succeeded['durationMs'], greaterThanOrEqualTo(0));
// Feed 卡片同源计数(跨页一致的另一半在 like 测试)。
expect(controller.cachedPost('p-1')!.commentCount, 4);
});
testWidgets('创建失败:SnackBar + comment_create_failedattemptSeq 递增', (
tester,
) async {
repository.onCreateComment = (_, _) async =>
throw const ApiBusinessException(code: 40000, message: 'bad');
await tester.pumpWidget(detailApp());
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), '不合规内容');
await tester.pump();
await tester.tap(find.byIcon(Icons.send_rounded));
await tester.pumpAndSettle();
expect(find.text('评论内容不合规,请修改后重试'), findsOneWidget);
// 等 SnackBar 退场(遮挡底部发送钮)后重试第二次。
await tester.pump(const Duration(seconds: 5));
await tester.pumpAndSettle();
await tester.tap(find.byIcon(Icons.send_rounded));
await tester.pumpAndSettle();
expect(eventsNamed('comment_create_failed'), [
{
'failureReason': 'validation_error',
'attemptSeq': 1,
'errorCode': 40000,
'httpStatus': 400,
},
{
'failureReason': 'validation_error',
'attemptSeq': 2,
'errorCode': 40000,
'httpStatus': 400,
},
]);
// 失败不清空输入、不入列表、不动计数。
expect(find.text('评论 (3)'), findsOneWidget);
});
testWidgets('删除权限呈现:仅本人评论有「删除」;确认后删除 + 计数 -1', (tester) async {
repository.onListComments = (_, _) async => commentPage([
sampleComment(
id: 'c-mine',
author: sampleAuthorJson(userId: 'me', nickname: '我自己'),
content: '我的评论',
),
sampleComment(id: 'c-other', content: '别人的评论'),
]);
repository.onDeleteComment = (_) async {};
await tester.pumpWidget(detailApp());
await tester.pumpAndSettle();
await tester.drag(find.byType(ListView), const Offset(0, -400));
await tester.pump();
// 两条评论,删除入口恰一个(本人条目)。
expect(find.byType(CommentTile), findsNWidgets(2));
expect(find.text('删除'), findsOneWidget);
await tester.tap(find.text('删除'));
await tester.pumpAndSettle();
expect(find.text('删除这条评论?'), findsOneWidget);
await tester.tap(find.widgetWithText(FilledButton, '删除'));
await tester.pumpAndSettle();
expect(repository.calls, contains('deleteComment:c-mine'));
expect(find.text('我的评论'), findsNothing);
expect(find.text('别人的评论'), findsOneWidget);
expect(find.text('评论 (2)'), findsOneWidget);
});
testWidgets('删除失败:40301 提示无权限,条目保留', (tester) async {
repository.onListComments = (_, _) async => commentPage([
sampleComment(
id: 'c-mine',
author: sampleAuthorJson(userId: 'me', nickname: '我自己'),
content: '我的评论',
),
]);
repository.onDeleteComment = (_) async =>
throw const PostAccessDeniedException(message: 'denied');
await tester.pumpWidget(detailApp());
await tester.pumpAndSettle();
await tester.drag(find.byType(ListView), const Offset(0, -400));
await tester.pump();
await tester.tap(find.text('删除'));
await tester.pumpAndSettle();
await tester.tap(find.widgetWithText(FilledButton, '删除'));
await tester.pumpAndSettle();
expect(find.text('没有权限删除这条评论'), findsOneWidget);
expect(find.text('我的评论'), findsOneWidget);
expect(find.text('评论 (3)'), findsOneWidget);
});
});
group('互动(ToggleSync UI 层)', () {
testWidgets('点赞乐观翻转即时 +1,成功报 post_liked(source=post_detail)', (
tester,
) async {
final like = Completer<LikeState>();
repository.onLikeToggle = (_, _) => like.future;
await tester.pumpWidget(detailApp());
await tester.pumpAndSettle();
await tester.tap(find.byIcon(Icons.favorite_border));
await tester.pump();
expect(find.text('7'), findsOneWidget);
expect(find.byIcon(Icons.favorite), findsOneWidget);
like.complete(const LikeState(liked: true, likeCount: 7));
await tester.pumpAndSettle();
expect(eventsNamed('post_liked'), [
{'source': 'post_detail'},
]);
});
testWidgets('点赞失败:零动画回滚成对恢复 + SnackBar,不报事件', (tester) async {
final like = Completer<LikeState>();
repository.onLikeToggle = (_, _) => like.future;
await tester.pumpWidget(detailApp());
await tester.pumpAndSettle();
await tester.tap(find.byIcon(Icons.favorite_border));
await tester.pump();
expect(find.text('7'), findsOneWidget);
like.completeError(const ApiNetworkException());
await tester.pumpAndSettle();
expect(find.text('6'), findsOneWidget);
expect(find.byIcon(Icons.favorite_border), findsOneWidget);
expect(find.text('操作失败,请重试'), findsOneWidget);
expect(eventsNamed('post_liked'), isEmpty);
});
testWidgets('收藏接线:成功报 post_favorited(source=post_detail)', (tester) async {
repository.onBookmarkToggle = (_, target) async =>
BookmarkState(bookmarked: target, bookmarkCount: target ? 3 : 2);
await tester.pumpWidget(detailApp());
await tester.pumpAndSettle();
await tester.tap(find.byIcon(Icons.bookmark_border));
await tester.pumpAndSettle();
expect(find.byIcon(Icons.bookmark), findsOneWidget);
expect(eventsNamed('post_favorited'), [
{'source': 'post_detail'},
]);
});
testWidgets('跨页一致:详情页点赞,Feed 卡片同帖同帧更新(共享同一实例)', (tester) async {
repository.onFeed = (_, _) async =>
feedPage([sampleFeedCard(likeCount: 6)]);
await controller.refresh();
repository.onLikeToggle = (_, target) async =>
LikeState(liked: target, likeCount: target ? 7 : 6);
await tester.pumpWidget(
MaterialApp(
theme: buildAppTheme(),
home: Column(
children: [
// 模拟 Feed 侧对同一 controller 的消费。
ListenableBuilder(
listenable: controller,
builder: (context, _) {
final card = controller.feed.single;
return Text('card:${card.likedByMe}:${card.likeCount}');
},
),
Expanded(
child: PostDetailPage(
controller: controller,
postId: 'p-1',
currentUserId: 'me',
analytics: analytics,
),
),
],
),
),
);
await tester.pumpAndSettle();
expect(find.text('card:false:6'), findsOneWidget);
await tester.tap(find.byIcon(Icons.favorite_border));
await tester.pump();
// 乐观写入即同源:卡片副本同帧翻转。
expect(find.text('card:true:7'), findsOneWidget);
await tester.pumpAndSettle();
expect(find.text('card:true:7'), findsOneWidget);
});
});
group('关注', () {
testWidgets('未关注 → 关注:乐观翻转 + user_followed(post_detail)', (tester) async {
repository.onFollowToggle = (_, target) async =>
FollowState(following: target, followerCount: target ? 2 : 1);
await tester.pumpWidget(detailApp());
await tester.pumpAndSettle();
expect(find.text(' 关注'), findsOneWidget);
await tester.tap(find.text(' 关注'));
await tester.pump();
expect(find.text('已关注'), findsOneWidget);
await tester.pumpAndSettle();
expect(repository.calls, contains('follow:u-1'));
expect(eventsNamed('user_followed'), [
{'source': 'post_detail'},
]);
});
testWidgets('已关注 → 取关:确认弹窗 + user_unfollowed', (tester) async {
repository.onGetFollowStats = (_) async => const FollowStats(
followerCount: 2,
followingCount: 2,
followedByMe: true,
);
repository.onFollowToggle = (_, target) async =>
FollowState(following: target, followerCount: target ? 2 : 1);
await tester.pumpWidget(detailApp());
await tester.pumpAndSettle();
expect(find.text('已关注'), findsOneWidget);
await tester.tap(find.text('已关注'));
await tester.pumpAndSettle();
expect(find.text('不再关注 TA'), findsOneWidget);
await tester.tap(find.widgetWithText(FilledButton, '不再关注'));
await tester.pumpAndSettle();
expect(find.text(' 关注'), findsOneWidget);
expect(repository.calls, contains('unfollow:u-1'));
expect(eventsNamed('user_unfollowed'), [
{'source': 'post_detail'},
]);
});
testWidgets('关注失败:回滚直接跳变 + SnackBar', (tester) async {
final follow = Completer<FollowState>();
repository.onFollowToggle = (_, _) => follow.future;
await tester.pumpWidget(detailApp());
await tester.pumpAndSettle();
await tester.tap(find.text(' 关注'));
await tester.pump();
expect(find.text('已关注'), findsOneWidget);
follow.completeError(const ApiNetworkException());
await tester.pumpAndSettle();
expect(find.text(' 关注'), findsOneWidget);
expect(find.text('操作失败,请重试'), findsOneWidget);
expect(eventsNamed('user_followed'), isEmpty);
});
testWidgets('本人帖:不渲染关注钮、不拉 follow-stats', (tester) async {
await tester.pumpWidget(detailApp(currentUserId: 'u-1'));
await tester.pumpAndSettle();
expect(find.text(' 关注'), findsNothing);
expect(find.text('已关注'), findsNothing);
expect(
repository.calls.where((c) => c.startsWith('followStats:')),
isEmpty,
);
});
});
}
+77 -15
View File
@@ -76,13 +76,15 @@ Map<String, dynamic> sampleFeedCardJson({
Map<String, dynamic> sampleCommentJson({ Map<String, dynamic> sampleCommentJson({
String id = 'c-1', String id = 'c-1',
Map<String, dynamic>? author,
Map<String, dynamic>? replyToUser, Map<String, dynamic>? replyToUser,
String content = '好可爱!',
}) => { }) => {
'id': id, 'id': id,
'postId': 'p-1', 'postId': 'p-1',
'author': sampleAuthorJson(), 'author': author ?? sampleAuthorJson(),
'replyToUser': replyToUser, 'replyToUser': replyToUser,
'content': '好可爱!', 'content': content,
'createdAt': '2026-09-08T11:00:00.000Z', 'createdAt': '2026-09-08T11:00:00.000Z',
}; };
@@ -131,6 +133,42 @@ CursorPage<FeedCard> feedPage(
bool hasMore = false, bool hasMore = false,
}) => CursorPage(items: items, nextCursor: nextCursor, hasMore: hasMore); }) => CursorPage(items: items, nextCursor: nextCursor, hasMore: hasMore);
Post samplePost({
String id = 'p-1',
bool likedByMe = false,
int likeCount = 6,
bool bookmarkedByMe = false,
int bookmarkCount = 2,
}) => Post.fromJson(
samplePostJson(
id: id,
likedByMe: likedByMe,
likeCount: likeCount,
bookmarkedByMe: bookmarkedByMe,
bookmarkCount: bookmarkCount,
),
);
PostComment sampleComment({
String id = 'c-1',
Map<String, dynamic>? author,
Map<String, dynamic>? replyToUser,
String content = '好可爱!',
}) => PostComment.fromJson(
sampleCommentJson(
id: id,
author: author,
replyToUser: replyToUser,
content: content,
),
);
CursorPage<PostComment> commentPage(
List<PostComment> items, {
String? nextCursor,
bool hasMore = false,
}) => CursorPage(items: items, nextCursor: nextCursor, hasMore: hasMore);
/// 假仓库:controller 测试注入行为并记录调用(Completer 控时序)。 /// 假仓库:controller 测试注入行为并记录调用(Completer 控时序)。
/// 未注入 handler 的方法一律 UnimplementedError(误触发即测试失败)。 /// 未注入 handler 的方法一律 UnimplementedError(误触发即测试失败)。
class FakeCommunityRepository implements CommunityRepository { class FakeCommunityRepository implements CommunityRepository {
@@ -141,6 +179,13 @@ class FakeCommunityRepository implements CommunityRepository {
Future<LikeState> Function(String postId, bool target)? onLikeToggle; Future<LikeState> Function(String postId, bool target)? onLikeToggle;
Future<BookmarkState> Function(String postId, bool target)? onBookmarkToggle; Future<BookmarkState> Function(String postId, bool target)? onBookmarkToggle;
Future<Post> Function(String postId)? onGetPost; Future<Post> Function(String postId)? onGetPost;
Future<CursorPage<PostComment>> Function(String postId, String? cursor)?
onListComments;
Future<PostComment> Function(String postId, CreateCommentRequest request)?
onCreateComment;
Future<void> Function(String commentId)? onDeleteComment;
Future<FollowState> Function(String userId, bool target)? onFollowToggle;
Future<FollowStats> Function(String userId)? onGetFollowStats;
Future<MediaUploadCredentials> Function(CreateMediaUploadRequest request)? Future<MediaUploadCredentials> Function(CreateMediaUploadRequest request)?
onCreateMediaUpload; onCreateMediaUpload;
Future<MediaAsset> Function(String assetId)? onCompleteMediaUpload; Future<MediaAsset> Function(String assetId)? onCompleteMediaUpload;
@@ -218,28 +263,45 @@ class FakeCommunityRepository implements CommunityRepository {
String postId, { String postId, {
int? limit, int? limit,
String? cursor, String? cursor,
}) => throw UnimplementedError(); }) {
calls.add('comments:$postId:cursor=$cursor');
return onListComments!(postId, cursor);
}
@override @override
Future<PostComment> createComment( Future<PostComment> createComment(
String postId, String postId,
CreateCommentRequest request, CreateCommentRequest request,
) => throw UnimplementedError(); ) {
calls.add('createComment:$postId:${request.content}');
return onCreateComment!(postId, request);
}
@override @override
Future<void> deleteComment(String commentId) => throw UnimplementedError(); Future<void> deleteComment(String commentId) {
calls.add('deleteComment:$commentId');
return onDeleteComment!(commentId);
}
@override
Future<FollowState> followUser(String userId) {
calls.add('follow:$userId');
return onFollowToggle!(userId, true);
}
@override
Future<FollowState> unfollowUser(String userId) {
calls.add('unfollow:$userId');
return onFollowToggle!(userId, false);
}
@override
Future<FollowStats> getFollowStats(String userId) {
calls.add('followStats:$userId');
return onGetFollowStats!(userId);
}
@override @override
Future<CursorPage<FeedCard>> listMyBookmarks({int? limit, String? cursor}) => Future<CursorPage<FeedCard>> listMyBookmarks({int? limit, String? cursor}) =>
throw UnimplementedError(); throw UnimplementedError();
@override
Future<FollowState> followUser(String userId) => throw UnimplementedError();
@override
Future<FollowState> unfollowUser(String userId) => throw UnimplementedError();
@override
Future<FollowStats> getFollowStats(String userId) =>
throw UnimplementedError();
} }
@@ -0,0 +1,265 @@
import 'dart:async';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:patbond_flutter/core/network/api_client.dart';
import 'package:patbond_flutter/core/network/api_exception.dart';
import 'package:patbond_flutter/core/network/token_refresher.dart';
import 'package:patbond_flutter/features/auth/auth_models.dart';
import 'package:patbond_flutter/features/auth/session_manager.dart';
import 'package:patbond_flutter/features/community/community_controller.dart';
import 'package:patbond_flutter/features/community/community_models.dart';
import 'package:patbond_flutter/features/community/community_repository.dart';
import 'package:uuid/uuid.dart';
import '../helpers/auth_test_helpers.dart';
/// T3-15/16 compose
///
/// ```bash
/// # patbond-api
/// # ./deploy/init-secrets.sh
/// # JAVA_HOME=<JDK17> ./mvnw -DskipTests package && docker compose up -d --build
/// PATBOND_DETAIL_SMOKE=1 flutter test test/smoke/detail_interactions_smoke_test.dart
/// ```
///
/// /
/// Idempotency-Key
/// ****[CommunityController]/ToggleSync +
/// ApiClient community
/// ApiNetworkException
///
void main() {
final enabled = Platform.environment['PATBOND_DETAIL_SMOKE'] == '1';
final env = Platform.environment;
final authBase = env['PATBOND_SMOKE_AUTH_BASE'] ?? 'http://127.0.0.1:8081';
final communityBase =
env['PATBOND_SMOKE_COMMUNITY_BASE'] ?? 'http://127.0.0.1:8084';
test(
'点赞/收藏/评论/删评真链路一轮 + 断网点赞回滚',
() async {
// ---- ----
final dio = Dio(BaseOptions(validateStatus: (_) => true));
final seed = DateTime.now().millisecondsSinceEpoch;
final register = await dio.post<Map<String, dynamic>>(
'$authBase/api/v1/auth/register',
data: {
'username': 'ismoke$seed',
'phone': '+86138${(seed % 100000000).toString().padLeft(8, '0')}',
'password': 'Smoke1234!$seed',
},
options: Options(
headers: {
'Idempotency-Key': const Uuid().v4(),
'X-Device-Id': const Uuid().v4(),
},
),
);
expect(register.data?['code'], 0, reason: '注册失败:${register.data}');
final session = SessionManager(store: InMemoryTokenStore());
await session.updateTokens(
AuthTokens.fromJson(register.data!['data'] as Map<String, dynamic>),
);
final refresher = TokenRefresher(
dio: buildPatbondDio(session: session, baseUrl: authBase),
session: session,
);
final live = ApiCommunityRepository(
api: ApiClient(
dio: buildPatbondDio(session: session, baseUrl: communityBase),
session: session,
refresher: refresher,
),
);
// community
// ApiClient ApiNetworkException
final dead = ApiCommunityRepository(
api: ApiClient(
dio: buildPatbondDio(session: session, baseUrl: 'http://127.0.0.1:9'),
session: session,
refresher: refresher,
),
);
final switchable = _SwitchableRepository(live);
// ---- published----
final post = await live.createPost(
CreatePostRequest(
content: 'T3-15/16 互动冒烟 $seed',
status: PostStatus.published,
),
);
expect(post.likeCount, 0);
expect(post.commentCount, 0);
// ---- / ----
var like = await live.likePost(post.id);
expect(like.liked, true);
expect(like.likeCount, 1);
like = await live.likePost(post.id);
expect(like.likeCount, 1, reason: '重复 PUT 不重复计数');
// ---- / ----
var bookmark = await live.bookmarkPost(post.id);
expect(bookmark.bookmarked, true);
expect(bookmark.bookmarkCount, 1);
bookmark = await live.unbookmarkPost(post.id);
expect(bookmark.bookmarked, false);
expect(bookmark.bookmarkCount, 0);
// ---- Idempotency-Key +1 ----
final comment = await live.createComment(
post.id,
const CreateCommentRequest(content: '冒烟评论:真链路一轮'),
);
expect(comment.content, '冒烟评论:真链路一轮');
var fresh = await live.getPost(post.id);
expect(fresh.commentCount, 1);
// ---- -1 ----
await live.deleteComment(comment.id);
fresh = await live.getPost(post.id);
expect(fresh.commentCount, 0);
final comments = await live.listComments(post.id);
expect(comments.items, isEmpty);
// ---- CommunityController + ToggleSync----
final controller = CommunityController(repository: switchable);
await controller.refresh();
FeedCard card() => controller.feed.firstWhere((c) => c.id == post.id);
expect(card().likedByMe, true);
expect(card().likeCount, 1);
switchable.target = dead; // 线
final errored = Completer<void>();
controller.addListener(() {
if (controller.toggleError != null && !errored.isCompleted) {
errored.complete();
}
});
controller.toggleLike(post.id);
//
expect(card().likedByMe, false);
expect(card().likeCount, 0);
await errored.future.timeout(const Duration(seconds: 30));
// + SnackBar
expect(card().likedByMe, true);
expect(card().likeCount, 1);
expect(controller.toggleError, isA<ApiNetworkException>());
controller.clearToggleError();
// ---- ----
switchable.target = live;
controller.toggleLike(post.id);
expect(card().likedByMe, false); //
//
final deadline = DateTime.now().add(const Duration(seconds: 15));
Post settled = await live.getPost(post.id);
while (settled.likedByMe) {
expect(DateTime.now().isBefore(deadline), true, reason: '收敛超时');
await Future<void>.delayed(const Duration(milliseconds: 300));
settled = await live.getPost(post.id);
}
expect(settled.likedByMe, false);
expect(settled.likeCount, 0);
expect(controller.toggleError, isNull);
expect(card().likedByMe, false);
controller.dispose();
},
skip: enabled
? false
: '设 PATBOND_DETAIL_SMOKE=1 且后端六容器在本机运行时才执行',
timeout: const Timeout(Duration(minutes: 3)),
);
}
/// live dead
class _SwitchableRepository implements CommunityRepository {
_SwitchableRepository(this.target);
CommunityRepository target;
@override
Future<MediaUploadCredentials> createMediaUpload(
CreateMediaUploadRequest request,
) => target.createMediaUpload(request);
@override
Future<MediaAsset> completeMediaUpload(String assetId) =>
target.completeMediaUpload(assetId);
@override
Future<Post> createPost(CreatePostRequest request) =>
target.createPost(request);
@override
Future<Post> getPost(String postId) => target.getPost(postId);
@override
Future<Post> updatePost(String postId, UpdatePostRequest request) =>
target.updatePost(postId, request);
@override
Future<void> deletePost(String postId) => target.deletePost(postId);
@override
Future<CursorPage<Post>> listMyPosts({
int? limit,
String? cursor,
PostStatus? status,
}) => target.listMyPosts(limit: limit, cursor: cursor, status: status);
@override
Future<CursorPage<FeedCard>> getFeed({int? limit, String? cursor}) =>
target.getFeed(limit: limit, cursor: cursor);
@override
Future<CursorPage<PostComment>> listComments(
String postId, {
int? limit,
String? cursor,
}) => target.listComments(postId, limit: limit, cursor: cursor);
@override
Future<PostComment> createComment(
String postId,
CreateCommentRequest request,
) => target.createComment(postId, request);
@override
Future<void> deleteComment(String commentId) =>
target.deleteComment(commentId);
@override
Future<LikeState> likePost(String postId) => target.likePost(postId);
@override
Future<LikeState> unlikePost(String postId) => target.unlikePost(postId);
@override
Future<BookmarkState> bookmarkPost(String postId) =>
target.bookmarkPost(postId);
@override
Future<BookmarkState> unbookmarkPost(String postId) =>
target.unbookmarkPost(postId);
@override
Future<CursorPage<FeedCard>> listMyBookmarks({int? limit, String? cursor}) =>
target.listMyBookmarks(limit: limit, cursor: cursor);
@override
Future<FollowState> followUser(String userId) => target.followUser(userId);
@override
Future<FollowState> unfollowUser(String userId) =>
target.unfollowUser(userId);
@override
Future<FollowStats> getFollowStats(String userId) =>
target.getFollowStats(userId);
}