From 1c7077225ebf11073a85bc7d91351e5706ae357a Mon Sep 17 00:00:00 2001 From: LittleSheep Date: Sun, 19 May 2024 20:30:50 +0800 Subject: [PATCH] :sparkles: Post reactions --- lib/main.dart | 10 +-- lib/models/post.dart | 105 ++++++++++++------------ lib/models/reaction.dart | 22 +++++ lib/screens/auth/signin.dart | 5 +- lib/screens/auth/signup.dart | 9 +-- lib/screens/posts/publish.dart | 5 +- lib/translations.dart | 8 ++ lib/widgets/posts/post_action.dart | 115 +++++++++++++++++++++++++++ lib/widgets/posts/post_item.dart | 36 +++++++-- lib/widgets/posts/post_reaction.dart | 53 ++++++++++++ 10 files changed, 290 insertions(+), 78 deletions(-) create mode 100644 lib/widgets/posts/post_action.dart create mode 100644 lib/widgets/posts/post_reaction.dart diff --git a/lib/main.dart b/lib/main.dart index d7c4a44..805f9fd 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -29,14 +29,8 @@ class SolianApp extends StatelessWidget { Get.lazyPut(() => AuthProvider()); }, builder: (context, child) { - return Overlay( - initialEntries: [ - OverlayEntry( - builder: (context) => ScaffoldMessenger( - child: child ?? Container(), - ), - ), - ], + return ScaffoldMessenger( + child: child ?? Container(), ); }, ); diff --git a/lib/models/post.dart b/lib/models/post.dart index 0d33da9..99cc706 100755 --- a/lib/models/post.dart +++ b/lib/models/post.dart @@ -24,7 +24,7 @@ class Post { Account author; int replyCount; int reactionCount; - dynamic reactionList; + Map reactionList; Post({ required this.id, @@ -53,54 +53,59 @@ class Post { }); factory Post.fromJson(Map json) => Post( - id: json["id"], - createdAt: DateTime.parse(json["created_at"]), - updatedAt: DateTime.parse(json["updated_at"]), - deletedAt: json["deleted_at"] != null ? DateTime.parse(json['deleted_at']) : null, - alias: json["alias"], - content: json["content"], - tags: json["tags"], - categories: json["categories"], - reactions: json["reactions"], - replies: json["replies"], - attachments: json["attachments"] != null ? List.from(json["attachments"]) : null, - replyId: json["reply_id"], - repostId: json["repost_id"], - realmId: json["realm_id"], - replyTo: json["reply_to"] == null ? null : Post.fromJson(json["reply_to"]), - repostTo: json["repost_to"], - realm: json["realm"], - publishedAt: json["published_at"], - authorId: json["author_id"], - author: Account.fromJson(json["author"]), - replyCount: json["reply_count"], - reactionCount: json["reaction_count"], - reactionList: json["reaction_list"], - ); + id: json["id"], + createdAt: DateTime.parse(json["created_at"]), + updatedAt: DateTime.parse(json["updated_at"]), + deletedAt: json["deleted_at"] != null ? DateTime.parse(json['deleted_at']) : null, + alias: json["alias"], + content: json["content"], + tags: json["tags"], + categories: json["categories"], + reactions: json["reactions"], + replies: json["replies"], + attachments: json["attachments"] != null ? List.from(json["attachments"]) : null, + replyId: json["reply_id"], + repostId: json["repost_id"], + realmId: json["realm_id"], + replyTo: json["reply_to"] == null ? null : Post.fromJson(json["reply_to"]), + repostTo: json["repost_to"], + realm: json["realm"], + publishedAt: json["published_at"], + authorId: json["author_id"], + author: Account.fromJson(json["author"]), + replyCount: json["reply_count"], + reactionCount: json["reaction_count"], + reactionList: json["reaction_list"] != null + ? json["reaction_list"] + .map((key, value) => + MapEntry(key, int.tryParse(value.toString()) ?? (value is double ? value.toInt() : null))) + .cast() + : {}, + ); Map toJson() => { - "id": id, - "created_at": createdAt.toIso8601String(), - "updated_at": updatedAt.toIso8601String(), - "deleted_at": deletedAt, - "alias": alias, - "content": content, - "tags": tags, - "categories": categories, - "reactions": reactions, - "replies": replies, - "attachments": attachments, - "reply_id": replyId, - "repost_id": repostId, - "realm_id": realmId, - "reply_to": replyTo?.toJson(), - "repost_to": repostTo, - "realm": realm, - "published_at": publishedAt, - "author_id": authorId, - "author": author.toJson(), - "reply_count": replyCount, - "reaction_count": reactionCount, - "reaction_list": reactionList, - }; -} \ No newline at end of file + "id": id, + "created_at": createdAt.toIso8601String(), + "updated_at": updatedAt.toIso8601String(), + "deleted_at": deletedAt, + "alias": alias, + "content": content, + "tags": tags, + "categories": categories, + "reactions": reactions, + "replies": replies, + "attachments": attachments, + "reply_id": replyId, + "repost_id": repostId, + "realm_id": realmId, + "reply_to": replyTo?.toJson(), + "repost_to": repostTo, + "realm": realm, + "published_at": publishedAt, + "author_id": authorId, + "author": author.toJson(), + "reply_count": replyCount, + "reaction_count": reactionCount, + "reaction_list": reactionList, + }; +} diff --git a/lib/models/reaction.dart b/lib/models/reaction.dart index 6725853..f47229d 100644 --- a/lib/models/reaction.dart +++ b/lib/models/reaction.dart @@ -13,4 +13,26 @@ final Map reactions = { 'confuse': ReactInfo(icon: '🧐', attitude: 0), 'retard': ReactInfo(icon: '🤪', attitude: 0), 'clap': ReactInfo(icon: '👏', attitude: 1), + 'heart': ReactInfo(icon: '❤️', attitude: 1), + 'laugh': ReactInfo(icon: '😂', attitude: 1), + 'angry': ReactInfo(icon: '😡', attitude: 2), + 'surprise': ReactInfo(icon: '😲', attitude: 0), + 'party': ReactInfo(icon: '🎉', attitude: 1), + 'wink': ReactInfo(icon: '😉', attitude: 1), + 'scream': ReactInfo(icon: '😱', attitude: 0), + 'sleep': ReactInfo(icon: '😴', attitude: 0), + 'thinking': ReactInfo(icon: '🤔', attitude: 0), + 'blush': ReactInfo(icon: '😊', attitude: 1), + 'cool': ReactInfo(icon: '😎', attitude: 1), + 'frown': ReactInfo(icon: '☹️', attitude: 2), + 'nauseated': ReactInfo(icon: '🤢', attitude: 2), + 'facepalm': ReactInfo(icon: '🤦', attitude: 0), + 'shrug': ReactInfo(icon: '🤷', attitude: 0), + 'joy': ReactInfo(icon: '🤣', attitude: 1), + 'relieved': ReactInfo(icon: '😌', attitude: 0), + 'disappointed': ReactInfo(icon: '😞', attitude: 2), + 'smirk': ReactInfo(icon: '😏', attitude: 1), + 'astonished': ReactInfo(icon: '😮', attitude: 0), + 'hug': ReactInfo(icon: '🤗', attitude: 1), + 'pray': ReactInfo(icon: '🙏', attitude: 1), }; diff --git a/lib/screens/auth/signin.dart b/lib/screens/auth/signin.dart index b7cf678..93f1d4c 100644 --- a/lib/screens/auth/signin.dart +++ b/lib/screens/auth/signin.dart @@ -29,10 +29,7 @@ class _SignInScreenState extends State { if (messages.last.contains('risk')) { final ticketId = RegExp(r'ticketId=(\d+)').firstMatch(messages.last); if (ticketId == null) { - Get.showSnackbar(GetSnackBar( - title: 'errorHappened'.tr, - message: 'requested to multi-factor authenticate, but the ticket id was not found', - )); + Get.snackbar('errorHappened'.tr, 'Requested to multi-factor authenticate, but the ticket id was not found'); } showDialog( context: context, diff --git a/lib/screens/auth/signup.dart b/lib/screens/auth/signup.dart index 2ab3806..fb8afde 100644 --- a/lib/screens/auth/signup.dart +++ b/lib/screens/auth/signup.dart @@ -28,14 +28,14 @@ class _SignUpScreenState extends State { final client = GetConnect(); client.httpClient.baseUrl = ServiceFinder.services['passport']; - final res = await client.post('/api/users', { + final resp = await client.post('/api/users', { 'name': username, 'nick': nickname, 'email': email, 'password': password, }); - if (res.statusCode == 200) { + if (resp.statusCode == 200) { showDialog( context: context, builder: (context) { @@ -54,10 +54,7 @@ class _SignUpScreenState extends State { AppRouter.instance.replaceNamed('auth.sign-in'); }); } else { - Get.showSnackbar(GetSnackBar( - title: 'errorHappened'.tr, - message: res.bodyString, - )); + Get.snackbar('errorHappened'.tr, resp.bodyString!); } } diff --git a/lib/screens/posts/publish.dart b/lib/screens/posts/publish.dart index a443da6..3962d06 100644 --- a/lib/screens/posts/publish.dart +++ b/lib/screens/posts/publish.dart @@ -34,10 +34,7 @@ class _PostPublishingScreenState extends State { 'content': _contentController.value.text, }); if (resp.statusCode != 200) { - Get.showSnackbar(GetSnackBar( - title: 'errorHappened'.tr, - message: resp.bodyString, - )); + Get.snackbar('errorHappened'.tr, resp.bodyString!); } else { AppRouter.instance.pop(resp.body); } diff --git a/lib/translations.dart b/lib/translations.dart index 48c304d..83b5e86 100644 --- a/lib/translations.dart +++ b/lib/translations.dart @@ -29,6 +29,10 @@ class SolianMessages extends Translations { 'postPublishing': 'Post a post', 'postIdentityNotify': 'You will post this post as', 'postContentPlaceholder': 'What\'s happened?!', + 'postReaction': 'Reactions of the Post', + 'reactAdd': 'React', + 'reactCompleted': 'Your reaction has been added', + 'reactUncompleted': 'Your reaction has been removed' }, 'zh_CN': { 'next': '下一步', @@ -55,6 +59,10 @@ class SolianMessages extends Translations { 'postPublishing': '发表帖子', 'postIdentityNotify': '你将会以本身份发表帖子', 'postContentPlaceholder': '发生什么事了?!', + 'postReaction': '帖子的反应', + 'reactAdd': '作出反应', + 'reactCompleted': '你的反应已被添加', + 'reactUncompleted': '你的反应已被移除' } }; } diff --git a/lib/widgets/posts/post_action.dart b/lib/widgets/posts/post_action.dart new file mode 100644 index 0000000..976b8d0 --- /dev/null +++ b/lib/widgets/posts/post_action.dart @@ -0,0 +1,115 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:get/get.dart'; +import 'package:solian/models/post.dart'; +import 'package:solian/models/reaction.dart'; +import 'package:solian/providers/auth.dart'; +import 'package:solian/services.dart'; +import 'package:solian/widgets/posts/post_reaction.dart'; + +class PostQuickAction extends StatefulWidget { + final Post item; + final void Function(String symbol, int num) onReact; + + const PostQuickAction({super.key, required this.item, required this.onReact}); + + @override + State createState() => _PostQuickActionState(); +} + +class _PostQuickActionState extends State { + bool _isSubmitting = false; + + void showReactMenu() { + showModalBottomSheet( + useRootNavigator: true, + isScrollControlled: true, + context: context, + builder: (context) => PostReactionPopup( + item: widget.item, + onReact: (key, value) { + doWidgetReact(key, value.attitude); + }, + ), + ); + } + + Future doWidgetReact(String symbol, int attitude) async { + final AuthProvider auth = Get.find(); + + if (_isSubmitting) return; + if (!await auth.isAuthorized) return; + + final client = GetConnect(); + client.httpClient.baseUrl = ServiceFinder.services['interactive']; + client.httpClient.addAuthenticator(auth.reqAuthenticator); + + setState(() => _isSubmitting = true); + + final resp = await client.post('/api/posts/${widget.item.alias}/react', { + 'symbol': symbol, + 'attitude': attitude, + }); + if (resp.statusCode == 201) { + widget.onReact(symbol, 1); + Get.snackbar('', 'reactCompleted'.tr); + } else if (resp.statusCode == 204) { + widget.onReact(symbol, -1); + Get.snackbar('', 'reactUncompleted'.tr); + } else { + Get.snackbar('errorHappened'.tr, resp.bodyString!); + } + + setState(() => _isSubmitting = false); + } + + @override + Widget build(BuildContext context) { + const density = VisualDensity(horizontal: -4, vertical: -3); + + return SizedBox( + height: 32, + width: double.infinity, + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + ActionChip( + avatar: const Icon(Icons.comment), + label: Text(widget.item.replyCount.toString()), + visualDensity: density, + onPressed: () {}, + ), + const VerticalDivider(thickness: 0.3, width: 0.3, indent: 8, endIndent: 8).paddingOnly(left: 8), + Expanded( + child: ListView( + shrinkWrap: true, + scrollDirection: Axis.horizontal, + children: [ + ...widget.item.reactionList.entries.map((x) { + final info = reactions[x.key]; + return Padding( + padding: const EdgeInsets.only(right: 8), + child: ActionChip( + avatar: Text(info!.icon), + label: Text(x.value.toString()), + tooltip: ':${x.key}:', + visualDensity: density, + onPressed: _isSubmitting ? null : () => doWidgetReact(x.key, info.attitude), + ), + ); + }), + ActionChip( + avatar: const Icon(Icons.add_reaction, color: Colors.teal), + label: Text('reactAdd'.tr), + visualDensity: density, + onPressed: () => showReactMenu(), + ), + ], + ).paddingOnly(left: 8), + ) + ], + ), + ); + } +} diff --git a/lib/widgets/posts/post_item.dart b/lib/widgets/posts/post_item.dart index 732630f..2ab31be 100644 --- a/lib/widgets/posts/post_item.dart +++ b/lib/widgets/posts/post_item.dart @@ -5,6 +5,7 @@ import 'package:get/get_utils/get_utils.dart'; import 'package:solian/models/post.dart'; import 'package:solian/widgets/account/account_avatar.dart'; import 'package:solian/widgets/attachments/attachment_list.dart'; +import 'package:solian/widgets/posts/post_action.dart'; import 'package:timeago/timeago.dart' show format; class PostItem extends StatefulWidget { @@ -17,30 +18,40 @@ class PostItem extends StatefulWidget { } class _PostItemState extends State { + late final Post item; + + @override + void initState() { + item = widget.item; + super.initState(); + } + @override Widget build(BuildContext context) { + final hasAttachment = item.attachments?.isNotEmpty ?? false; + return Column( children: [ Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ - AccountAvatar(content: widget.item.author.avatar), + AccountAvatar(content: item.author.avatar), Expanded( child: Column( children: [ Row( children: [ Text( - widget.item.author.nick, + item.author.nick, style: const TextStyle(fontWeight: FontWeight.bold), ).paddingOnly(left: 12), - Text(format(widget.item.createdAt, locale: 'en_short')).paddingOnly(left: 4), + Text(format(item.createdAt, locale: 'en_short')).paddingOnly(left: 4), ], ), Markdown( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), - data: widget.item.content, + data: item.content, padding: const EdgeInsets.all(0), ).paddingOnly(left: 12, right: 8), ], @@ -49,11 +60,24 @@ class _PostItemState extends State { ], ).paddingOnly( top: 18, - bottom: (widget.item.attachments?.isNotEmpty ?? false) ? 10 : 18, + bottom: hasAttachment ? 10 : 0, right: 16, left: 16, ), - AttachmentList(attachmentsId: widget.item.attachments ?? List.empty()), + AttachmentList(attachmentsId: item.attachments ?? List.empty()), + PostQuickAction( + item: widget.item, + onReact: (symbol, changes) { + setState(() { + item.reactionList[symbol] = (item.reactionList[symbol] ?? 0) + changes; + }); + }, + ).paddingOnly( + top: hasAttachment ? 10 : 6, + left: hasAttachment ? 16 : 60, + right: 16, + bottom: 10, + ), ], ); } diff --git a/lib/widgets/posts/post_reaction.dart b/lib/widgets/posts/post_reaction.dart new file mode 100644 index 0000000..5f29db5 --- /dev/null +++ b/lib/widgets/posts/post_reaction.dart @@ -0,0 +1,53 @@ +import 'package:flutter/material.dart'; +import 'package:get/get.dart'; +import 'package:solian/models/post.dart'; +import 'package:solian/models/reaction.dart'; + +class PostReactionPopup extends StatelessWidget { + final Post item; + final void Function(String key, ReactInfo info) onReact; + + const PostReactionPopup({super.key, required this.item, required this.onReact}); + + @override + Widget build(BuildContext context) { + return SizedBox( + height: MediaQuery.of(context).size.height * 0.85, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'postReaction'.tr, + style: Theme.of(context).textTheme.headlineSmall, + ).paddingOnly(left: 24, right: 24, top: 32, bottom: 16), + Expanded( + child: SingleChildScrollView( + child: Wrap( + runSpacing: 4.0, + spacing: 8.0, + children: reactions.entries.map((e) { + return ActionChip( + avatar: Text(e.value.icon), + label: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text(e.key, style: const TextStyle(fontFamily: 'monospace')), + const SizedBox(width: 6), + Text('x${item.reactionList[e.key]?.toString() ?? '0'}', + style: const TextStyle(fontWeight: FontWeight.bold)), + ], + ), + onPressed: () { + onReact(e.key, e.value); + Navigator.pop(context); + }, + ); + }).toList(), + ).paddingSymmetric(horizontal: 24), + ), + ), + ], + ), + ); + } +}