Files
eatvio_app/lib/features/feed/presentation/widgets/blog_post_widget.dart

462 lines
17 KiB
Dart

import 'dart:async';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:carousel_slider_plus/carousel_slider_plus.dart';
import 'package:dismissible_page/dismissible_page.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/enums/complained_content.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/utils/date_time_utils.dart';
import 'package:eatvio_app/core/widgets/custom_popup.dart';
import 'package:eatvio_app/core/widgets/feed_icon_button.dart';
import 'package:eatvio_app/core/widgets/markdown_html_widget.dart';
import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart';
import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart';
import 'package:eatvio_app/features/feed/models/post_feed_mapper.dart';
import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart';
import 'package:eatvio_app/features/feed/presentation/widgets/feed_video_player/feed_video_player_widget.dart';
import 'package:eatvio_app/features/feed/presentation/widgets/subscribe_button_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:go_router/go_router.dart';
import 'package:share_plus/share_plus.dart';
class BlogPostWidget extends StatefulWidget {
final FeedBlogPostModel post;
const BlogPostWidget({super.key, required this.post});
@override
State<BlogPostWidget> createState() => _BlogPostWidgetState();
}
class _BlogPostWidgetState extends State<BlogPostWidget> {
late bool isLiked;
late int totalLikes;
int currentGalleryIndex = 0;
FeedBlogPostModel get post => widget.post;
@override
void initState() {
super.initState();
isLiked = post.wasLikedByMe;
totalLikes = post.totalLikes;
}
@override
void didUpdateWidget(covariant BlogPostWidget oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.post.id != post.id) {
currentGalleryIndex = 0;
isLiked = post.wasLikedByMe;
totalLikes = post.totalLikes;
return;
}
if (oldWidget.post.wasLikedByMe != post.wasLikedByMe || oldWidget.post.totalLikes != post.totalLikes) {
isLiked = post.wasLikedByMe;
totalLikes = post.totalLikes;
}
}
void _openGallery(List<String> imageUrls, int index) {
context.pushTransparentRoute(rootNavigator: true, PhotoViewScreen(imageUrls: imageUrls, index: index));
}
Future<void> _toggleLike() async {
final nextLiked = !isLiked;
setState(() {
isLiked = nextLiked;
nextLiked ? totalLikes++ : totalLikes--;
});
context.read<FeedCubit>().updateFeedBlogPostList(post, nextLiked);
if (nextLiked) {
await context.read<FeedCubit>().likePost(post.id);
} else {
await context.read<FeedCubit>().unlikedPost(post.id);
}
}
@override
Widget build(BuildContext context) {
final imageUrl = PostFeedMapper.resolveMediaUrl(post.image);
final galleryUrls = post.images.map((e) => PostFeedMapper.resolveMediaUrl(e.url)).where((e) => e.isNotEmpty).toList();
final embedUrl = post.videoEmbedUrl?.trim();
return InkWell(
borderRadius: BorderRadius.circular(12),
onTap: () => GoRouter.of(context).pushNamed('blogPostScreen', extra: post.id),
child: Material(
borderRadius: BorderRadius.circular(12),
color: Colors.white,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 12),
_BlogPostHeader(post: post),
_BlogPostTextContent(post: post),
_BlogPostMediaContent(
galleryUrls: galleryUrls,
imageUrl: imageUrl,
videoEmbedUrl: embedUrl != null && embedUrl.isNotEmpty ? embedUrl : null,
videoUrlThumb: post.videoUrlThumb,
currentGalleryIndex: currentGalleryIndex,
onOpenGallery: _openGallery,
onGalleryChanged: (index) {
setState(() {
currentGalleryIndex = index;
});
},
),
const SizedBox(height: 12),
_BlogPostActionsRow(post: post, isLiked: isLiked, totalLikes: totalLikes, onToggleLike: _toggleLike),
const SizedBox(height: 8),
],
),
),
);
}
}
class _BlogPostHeader extends StatelessWidget {
const _BlogPostHeader({required this.post});
final FeedBlogPostModel post;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
GestureDetector(
onTap: () => GoRouter.of(context).pushNamed('profileScreen', extra: post.author.authorSlug),
child: CircleAvatar(
radius: 20,
backgroundColor: Colors.black12,
foregroundImage: post.author.authorProfileIcon.isNotEmpty ? NetworkImage(PostFeedMapper.resolveMediaUrl(post.author.authorProfileIcon)) : null,
backgroundImage: const AssetImage('assets/images/no_avatar.png'),
),
),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
post.author.authorName,
overflow: TextOverflow.ellipsis,
style: const TextStyle(height: 1, color: Colors.black87, fontWeight: FontWeight.w500, fontSize: 16),
),
const SizedBox(height: 4),
Text(
'${calculateDifference(post.createdAt)} в ${post.createdAt.hour.toString().padLeft(2, '0')}:${post.createdAt.minute.toString().padLeft(2, '0')}',
style: const TextStyle(height: 1, color: Colors.black45, fontSize: 14),
),
],
),
),
if (!(post.author.isEntitySubscribedByMe ?? false) && !post.author.authorIsMe)
Padding(
padding: const EdgeInsets.only(right: 8),
child: SubscribeButtonWidget(slug: post.author.authorSlug),
),
CustomPopup(
isAuthor: post.author.authorIsMe,
complainedContentType: ComplainedContent.posts,
path: 'blog_post/${post.id}',
id: post.id,
feedBlogPostModel: post,
userSlug: post.author.authorSlug,
),
],
),
);
}
}
class _BlogPostTextContent extends StatelessWidget {
const _BlogPostTextContent({required this.post});
final FeedBlogPostModel post;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (post.title.isNotEmpty) ...[
const SizedBox(height: 12),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Text(
post.title,
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: Colors.black87),
),
),
],
if (post.title.isEmpty) const SizedBox(height: 8),
if (post.title.isNotEmpty && post.description.isNotEmpty) const SizedBox(height: 8),
if (post.description.isNotEmpty)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: MarkdownHtmlWidget(markdownText: _truncateDescription(post.description)),
),
if (post.description.length > 200)
const Padding(
padding: EdgeInsets.symmetric(horizontal: 12),
child: Text(
'Показать ещё',
style: TextStyle(height: 1, color: Color(0xFF8B8B8B), fontSize: 14, fontWeight: FontWeight.w600),
),
),
if (post.title.isNotEmpty || post.description.isNotEmpty) const SizedBox(height: 8),
],
);
}
}
class _BlogPostMediaContent extends StatefulWidget {
const _BlogPostMediaContent({
required this.galleryUrls,
required this.imageUrl,
required this.videoEmbedUrl,
required this.currentGalleryIndex,
required this.onOpenGallery,
required this.onGalleryChanged,
required this.videoUrlThumb,
});
final List<String> galleryUrls;
final String imageUrl;
final String? videoEmbedUrl;
final String? videoUrlThumb;
final int currentGalleryIndex;
final void Function(List<String> urls, int index) onOpenGallery;
final ValueChanged<int> onGalleryChanged;
@override
State<_BlogPostMediaContent> createState() => _BlogPostMediaContentState();
}
class _BlogPostMediaContentState extends State<_BlogPostMediaContent> {
static const _counterDisplayDuration = Duration(seconds: 2);
bool _isCounterVisible = false;
Timer? _counterHideTimer;
@override
void dispose() {
_counterHideTimer?.cancel();
super.dispose();
}
bool _handleCarouselScroll(ScrollNotification notification) {
if (notification is ScrollStartNotification || notification is ScrollUpdateNotification) {
_counterHideTimer?.cancel();
if (!_isCounterVisible) {
setState(() => _isCounterVisible = true);
}
} else if (notification is ScrollEndNotification && _isCounterVisible) {
_counterHideTimer?.cancel();
_counterHideTimer = Timer(_counterDisplayDuration, () {
if (mounted) {
setState(() => _isCounterVisible = false);
}
});
}
return false;
}
@override
Widget build(BuildContext context) {
final mediaContentCount = widget.videoEmbedUrl != null ? widget.galleryUrls.length + 1 : widget.galleryUrls.length;
return Column(
children: [
if (widget.galleryUrls.length > 1) ...[
Stack(
children: [
NotificationListener<ScrollNotification>(
onNotification: _handleCarouselScroll,
child: CarouselSlider.builder(
itemCount: widget.galleryUrls.length + 1,
itemBuilder: (context, itemIndex, _) {
if (itemIndex == widget.galleryUrls.length) {
if (widget.videoEmbedUrl != null) {
return FeedVideoPlayer(embedUrl: widget.videoEmbedUrl!, videoUrlThumb: widget.videoUrlThumb);
}
return const SizedBox.shrink();
}
final itemUrl = widget.galleryUrls[itemIndex];
return GestureDetector(
onTap: () => widget.onOpenGallery(widget.galleryUrls, itemIndex),
child: CachedNetworkImage(
fit: BoxFit.cover,
width: MediaQuery.of(context).size.width,
imageUrl: itemUrl,
errorWidget: (context, str, object) => const SizedBox.shrink(),
),
);
},
options: CarouselOptions(
viewportFraction: 1,
height: 260,
enableInfiniteScroll: false,
onPageChanged: (index, _) => widget.onGalleryChanged(index),
),
),
),
Positioned(
top: 12,
right: 12,
child: IgnorePointer(
child: AnimatedOpacity(
opacity: _isCounterVisible ? 1 : 0,
duration: const Duration(milliseconds: 150),
child: _GalleryPhotoCounter(currentIndex: widget.currentGalleryIndex, total: mediaContentCount),
),
),
),
],
),
] else if (widget.galleryUrls.length == 1) ...[
GestureDetector(
onTap: () => widget.onOpenGallery(widget.galleryUrls, 0),
child: CachedNetworkImage(
fit: BoxFit.cover,
width: MediaQuery.of(context).size.width,
height: 260,
imageUrl: widget.galleryUrls.first,
errorWidget: (context, str, object) => const SizedBox.shrink(),
),
),
] else if (widget.imageUrl.isNotEmpty) ...[
GestureDetector(
onTap: () => widget.onOpenGallery([widget.imageUrl], 0),
child: Hero(
tag: widget.imageUrl,
child: CachedNetworkImage(
fit: BoxFit.fitWidth,
width: MediaQuery.of(context).size.width,
imageUrl: widget.imageUrl,
errorWidget: (context, str, object) => const SizedBox.shrink(),
),
),
),
],
],
);
}
}
class _GalleryPhotoCounter extends StatelessWidget {
const _GalleryPhotoCounter({required this.currentIndex, required this.total});
final int currentIndex;
final int total;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(color: Colors.black.withValues(alpha: 0.5), borderRadius: BorderRadius.circular(999)),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.photo_library_outlined, size: 14, color: Colors.white),
const SizedBox(width: 8),
Text(
'${currentIndex + 1} / $total',
style: const TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w500, height: 1.2),
),
],
),
);
}
}
class _BlogPostActionsRow extends StatelessWidget {
const _BlogPostActionsRow({required this.post, required this.isLiked, required this.totalLikes, required this.onToggleLike});
final FeedBlogPostModel post;
final bool isLiked;
final int totalLikes;
final Future<void> Function() onToggleLike;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Row(
children: [
FeedIconButton(
icon: isLiked ? Icons.favorite_rounded : Icons.favorite_border_rounded,
text: totalLikes.toString(),
iconColor: isLiked ? Colors.red.withValues(alpha: 0.8) : null,
backgroundColor: isLiked ? Colors.red.withValues(alpha: 0.1) : null,
textColor: isLiked ? Colors.red.withValues(alpha: 0.8) : null,
onTap: onToggleLike,
),
const SizedBox(width: 8),
FeedIconButton(
svgIcon: SvgPicture.asset('assets/icons/comment.svg', height: 20, width: 20, colorFilter: ColorFilter.mode(appTheme.gray600, BlendMode.srcIn)),
text: post.totalComments.toString(),
onTap: () => GoRouter.of(context).pushNamed('blogPostScreen', extra: post.id),
),
const SizedBox(width: 8),
FeedIconButton(
svgIcon: SvgPicture.asset(height: 15, width: 12, 'assets/icons/repost.svg', colorFilter: ColorFilter.mode(appTheme.gray600, BlendMode.srcIn)),
onTap: () {
final box = context.findRenderObject() as RenderBox?;
SharePlus.instance.share(
ShareParams(
uri: Uri.parse('${sl<AppConfig>().baseUrl}/ru/blog_post/${post.id}'),
sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
),
);
},
),
const Spacer(),
Icon(Icons.visibility_rounded, size: 16, color: appTheme.gray500),
const SizedBox(width: 4),
Text(
post.totalViews.toString(),
style: TextStyle(fontSize: 12, color: appTheme.gray500, fontWeight: FontWeight.w400),
),
],
),
);
}
}
String _truncateDescription(String description) {
final isLong = description.length > 200;
if (!isLong) return description;
var cutPoint = 200;
final preview = description.substring(0, cutPoint);
final boldOpen = (preview.split('**').length - 1) ~/ 2;
final boldClose = preview.split('**').length - 1 - boldOpen * 2;
final hasUnclosedBold = boldOpen > boldClose;
if (hasUnclosedBold) {
final searchEnd = (cutPoint + 100).clamp(0, description.length);
final boldClosePos = description.indexOf('**', cutPoint);
if (boldClosePos != -1 && boldClosePos < searchEnd) {
cutPoint = boldClosePos + 2;
} else {
cutPoint = description.lastIndexOf(' ', 200);
if (cutPoint == -1 || cutPoint < 150) cutPoint = 200;
}
} else {
cutPoint = description.lastIndexOf(' ', cutPoint);
if (cutPoint == -1 || cutPoint < 150) cutPoint = 200;
}
return description.substring(0, cutPoint);
}