From 78f9ad941bb749d820fbb734db140cc0b91b26d7 Mon Sep 17 00:00:00 2001 From: LittleSheep Date: Fri, 28 Jun 2024 00:59:11 +0800 Subject: [PATCH] :sparkles: Basic event based rendering --- lib/models/event.dart | 17 +- lib/providers/message/helper.dart | 32 ++- lib/screens/channel/channel_chat.dart | 26 +-- lib/translations.dart | 10 +- lib/widgets/chat/chat_event.dart | 139 ++++++++++++ ...age_action.dart => chat_event_action.dart} | 14 +- lib/widgets/chat/chat_event_action_log.dart | 43 ++++ ...deletion.dart => chat_event_deletion.dart} | 10 +- lib/widgets/chat/chat_event_message.dart | 93 ++++++++ lib/widgets/chat/chat_message.dart | 198 ------------------ lib/widgets/chat/chat_message_input.dart | 45 ++-- 11 files changed, 352 insertions(+), 275 deletions(-) create mode 100644 lib/widgets/chat/chat_event.dart rename lib/widgets/chat/{chat_message_action.dart => chat_event_action.dart} (90%) create mode 100644 lib/widgets/chat/chat_event_action_log.dart rename lib/widgets/chat/{chat_message_deletion.dart => chat_event_deletion.dart} (86%) create mode 100644 lib/widgets/chat/chat_event_message.dart delete mode 100644 lib/widgets/chat/chat_message.dart diff --git a/lib/models/event.dart b/lib/models/event.dart index b3c0812..f4cd331 100644 --- a/lib/models/event.dart +++ b/lib/models/event.dart @@ -9,15 +9,12 @@ class Event { DateTime? deletedAt; Map body; String type; - List? attachments; Channel? channel; Sender sender; - int? replyId; - Event? replyTo; int channelId; int senderId; - bool isSending = false; + bool isPending = false; Event({ required this.id, @@ -27,11 +24,8 @@ class Event { this.deletedAt, required this.body, required this.type, - this.attachments, this.channel, required this.sender, - required this.replyId, - required this.replyTo, required this.channelId, required this.senderId, }); @@ -44,15 +38,9 @@ class Event { deletedAt: json['deleted_at'], body: json['body'], type: json['type'], - attachments: json['attachments'] != null - ? List.from(json['attachments']) - : null, channel: json['channel'] != null ? Channel.fromJson(json['channel']) : null, sender: Sender.fromJson(json['sender']), - replyId: json['reply_id'], - replyTo: - json['reply_to'] != null ? Event.fromJson(json['reply_to']) : null, channelId: json['channel_id'], senderId: json['sender_id'], ); @@ -65,11 +53,8 @@ class Event { 'deleted_at': deletedAt, 'body': body, 'type': type, - 'attachments': attachments, 'channel': channel?.toJson(), 'sender': sender.toJson(), - 'reply_id': replyId, - 'reply_to': replyTo?.toJson(), 'channel_id': channelId, 'sender_id': senderId, }; diff --git a/lib/providers/message/helper.dart b/lib/providers/message/helper.dart index 5767854..af97d9b 100644 --- a/lib/providers/message/helper.dart +++ b/lib/providers/message/helper.dart @@ -18,7 +18,7 @@ Future createHistoryDb() async { } extension MessageHistoryHelper on MessageHistoryDb { - receiveEvent(Event remote) async { + Future receiveEvent(Event remote) async { final entry = LocalEvent( remote.id, remote, @@ -46,6 +46,17 @@ extension MessageHistoryHelper on MessageHistoryDb { return entry; } + Future getEvent(int id, Channel channel, + {String scope = 'global'}) async { + final localRecord = await localEvents.findById(id); + if (localRecord != null) return localRecord; + + final remoteRecord = await _getRemoteEvent(id, channel, scope); + if (remoteRecord == null) return null; + + return await receiveEvent(remoteRecord); + } + Future<(List, int)?> syncEvents(Channel channel, {String scope = 'global', depth = 10, offset = 0}) async { final lastOne = await localEvents.findLastByChannel(channel.id); @@ -70,6 +81,25 @@ extension MessageHistoryHelper on MessageHistoryDb { return data; } + Future _getRemoteEvent(int id, Channel channel, String scope) async { + final AuthProvider auth = Get.find(); + if (!await auth.isAuthorized) return null; + + final client = auth.configureClient('messaging'); + + final resp = await client.get( + '/api/channels/$scope/${channel.alias}/events/$id', + ); + + if (resp.statusCode == 404) { + return null; + } else if (resp.statusCode != 200) { + throw Exception(resp.bodyString); + } + + return Event.fromJson(resp.body); + } + Future<(List, int)?> _getRemoteEvents( Channel channel, String scope, { diff --git a/lib/screens/channel/channel_chat.dart b/lib/screens/channel/channel_chat.dart index bf61a95..cb19cee 100644 --- a/lib/screens/channel/channel_chat.dart +++ b/lib/screens/channel/channel_chat.dart @@ -20,8 +20,8 @@ import 'package:solian/theme.dart'; import 'package:solian/widgets/app_bar_title.dart'; import 'package:solian/widgets/chat/call/call_prejoin.dart'; import 'package:solian/widgets/chat/call/chat_call_action.dart'; -import 'package:solian/widgets/chat/chat_message.dart'; -import 'package:solian/widgets/chat/chat_message_action.dart'; +import 'package:solian/widgets/chat/chat_event.dart'; +import 'package:solian/widgets/chat/chat_event_action.dart'; import 'package:solian/widgets/chat/chat_message_input.dart'; import 'package:solian/widgets/current_state_action.dart'; @@ -125,7 +125,6 @@ class _ChannelChatScreenState extends State { } bool checkMessageMergeable(Event? a, Event? b) { - if (a?.replyTo != null) return false; if (a == null || b == null) return false; if (a.sender.account.id != b.sender.account.id) return false; return a.createdAt.difference(b.createdAt).inMinutes <= 3; @@ -146,24 +145,7 @@ class _ChannelChatScreenState extends State { Event? _messageToEditing; Widget buildHistoryBody(Event item, {bool isMerged = false}) { - if (item.replyTo != null) { - return Column( - children: [ - ChatMessage( - key: Key('m${item.replyTo!.uuid}'), - item: item.replyTo!, - isReply: true, - ).paddingOnly(left: 24, right: 4, bottom: 2), - ChatMessage( - key: Key('m${item.uuid}'), - item: item, - isMerged: isMerged, - ), - ], - ); - } - - return ChatMessage( + return ChatEvent( key: Key('m${item.uuid}'), item: item, isMerged: isMerged, @@ -198,7 +180,7 @@ class _ChannelChatScreenState extends State { showModalBottomSheet( useRootNavigator: true, context: context, - builder: (context) => ChatMessageAction( + builder: (context) => ChatEventAction( channel: _channel!, realm: _channel!.realm, item: item, diff --git a/lib/translations.dart b/lib/translations.dart index 52717fc..6d6badb 100644 --- a/lib/translations.dart +++ b/lib/translations.dart @@ -166,8 +166,9 @@ class SolianMessages extends Translations { 'channelNotifyLevelApplied': 'Your notification settings has been applied.', 'messageUnsync': 'Messages Un-synced', 'messageUnsyncCaption': '@count message(s) still in un-synced.', - 'messageDecoding': 'Decoding...', - 'messageDecodeFailed': 'Unable to decode: @message', + 'messageEditDesc': 'Edited message @id', + 'messageDeleteDesc': 'Deleted message @id', + 'messageTypeUnsupported': 'Unsupported Message: @type', 'messageInputPlaceholder': 'Message @channel', 'messageActionList': 'Actions of Message', 'messageDeletionConfirm': 'Confirm message deletion', @@ -382,8 +383,9 @@ class SolianMessages extends Translations { 'messageUnsync': '消息未同步', 'messageUnsyncCaption': '还有 @count 条消息未同步', 'messageDecoding': '解码信息中…', - 'messageDecodeFailed': '解码信息失败:@message', - 'messageInputPlaceholder': '在 @channel 发信息', + 'messageEditDesc': '修改了消息 @id', + 'messageDeleteDesc': '删除了消息 @id', + 'messageTypeUnsupported': '不支持的消息类型 @type', 'messageActionList': '消息的操作', 'messageDeletionConfirm': '确认删除消息', 'messageDeletionConfirmCaption': '你确定要删除消息 @id 吗?该操作不可撤销。', diff --git a/lib/widgets/chat/chat_event.dart b/lib/widgets/chat/chat_event.dart new file mode 100644 index 0000000..c6b7707 --- /dev/null +++ b/lib/widgets/chat/chat_event.dart @@ -0,0 +1,139 @@ +import 'package:flutter/material.dart'; +import 'package:font_awesome_flutter/font_awesome_flutter.dart'; +import 'package:get/get.dart'; +import 'package:solian/models/event.dart'; +import 'package:solian/widgets/account/account_avatar.dart'; +import 'package:solian/widgets/account/account_profile_popup.dart'; +import 'package:solian/widgets/chat/chat_event_action_log.dart'; +import 'package:solian/widgets/chat/chat_event_message.dart'; +import 'package:timeago/timeago.dart' show format; + +class ChatEvent extends StatelessWidget { + final Event item; + final bool isContentPreviewing; + final bool isQuote; + final bool isMerged; + final bool isHasMerged; + + const ChatEvent({ + super.key, + required this.item, + this.isContentPreviewing = false, + this.isMerged = false, + this.isHasMerged = false, + this.isQuote = false, + }); + + Widget buildContent() { + switch (item.type) { + case 'messages.new': + return ChatEventMessage( + item: item, + isContentPreviewing: isContentPreviewing, + isMerged: isMerged, + isHasMerged: isHasMerged, + isQuote: isQuote, + ); + case 'messages.edit': + return ChatEventMessageActionLog( + icon: const Icon(Icons.edit_note, size: 16), + text: 'messageEditDesc'.trParams({'id': '#${item.id}'}), + isMerged: isMerged, + isHasMerged: isHasMerged, + ); + case 'messages.delete': + return ChatEventMessageActionLog( + icon: const Icon(Icons.cancel_schedule_send, size: 16), + text: 'messageDeleteDesc'.trParams({'id': '#${item.id}'}), + isMerged: isMerged, + isHasMerged: isHasMerged, + ); + case 'system.changes': + return ChatEventMessageActionLog( + icon: const Icon(Icons.manage_history, size: 16), + text: item.body['text'], + isMerged: isMerged, + isHasMerged: isHasMerged, + ); + default: + return ChatEventMessageActionLog( + icon: const Icon(Icons.error, size: 16), + text: 'messageTypeUnsupported'.trParams({'type': item.type}), + isMerged: isMerged, + isHasMerged: isHasMerged, + ); + } + } + + Widget buildBody(BuildContext context) { + if (isContentPreviewing || isMerged) { + return buildContent(); + } else if (isQuote) { + return Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Transform.scale( + scaleX: -1, + child: const FaIcon(FontAwesomeIcons.reply, size: 14), + ), + const SizedBox(width: 12), + AccountAvatar(content: item.sender.account.avatar, radius: 8), + const SizedBox(width: 4), + Text( + item.sender.account.nick, + style: const TextStyle(fontWeight: FontWeight.bold), + ), + Expanded(child: buildContent()), + ], + ); + } else { + return Column( + key: Key('m${item.uuid}'), + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + GestureDetector( + child: AccountAvatar(content: item.sender.account.avatar), + onTap: () { + showModalBottomSheet( + useRootNavigator: true, + isScrollControlled: true, + backgroundColor: Theme.of(context).colorScheme.surface, + context: context, + builder: (context) => AccountProfilePopup( + account: item.sender.account, + ), + ); + }, + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text( + item.sender.account.nick, + style: const TextStyle(fontWeight: FontWeight.bold), + ), + const SizedBox(width: 4), + Text(format(item.createdAt, locale: 'en_short')) + ], + ).paddingSymmetric(horizontal: 12), + buildContent(), + ], + ), + ), + ], + ).paddingSymmetric(horizontal: 12), + ], + ); + } + } + + @override + Widget build(BuildContext context) { + return buildBody(context); + } +} diff --git a/lib/widgets/chat/chat_message_action.dart b/lib/widgets/chat/chat_event_action.dart similarity index 90% rename from lib/widgets/chat/chat_message_action.dart rename to lib/widgets/chat/chat_event_action.dart index 79e8a93..e095106 100644 --- a/lib/widgets/chat/chat_message_action.dart +++ b/lib/widgets/chat/chat_event_action.dart @@ -6,16 +6,16 @@ import 'package:solian/models/channel.dart'; import 'package:solian/models/event.dart'; import 'package:solian/models/realm.dart'; import 'package:solian/providers/auth.dart'; -import 'package:solian/widgets/chat/chat_message_deletion.dart'; +import 'package:solian/widgets/chat/chat_event_deletion.dart'; -class ChatMessageAction extends StatefulWidget { +class ChatEventAction extends StatefulWidget { final Channel channel; final Realm? realm; final Event item; final Function? onEdit; final Function? onReply; - const ChatMessageAction({ + const ChatEventAction({ super.key, required this.channel, required this.realm, @@ -25,14 +25,16 @@ class ChatMessageAction extends StatefulWidget { }); @override - State createState() => _ChatMessageActionState(); + State createState() => _ChatEventActionState(); } -class _ChatMessageActionState extends State { +class _ChatEventActionState extends State { bool _isBusy = false; bool _canModifyContent = false; void checkAbleToModifyContent() async { + if (!['messages.new'].contains(widget.item.type)) return; + final AuthProvider provider = Get.find(); if (!await provider.isAuthorized) return; @@ -106,7 +108,7 @@ class _ChatMessageActionState extends State { onTap: () async { final value = await showDialog( context: context, - builder: (context) => ChatMessageDeletionDialog( + builder: (context) => ChatEventDeletionDialog( channel: widget.channel, realm: widget.realm, item: widget.item, diff --git a/lib/widgets/chat/chat_event_action_log.dart b/lib/widgets/chat/chat_event_action_log.dart new file mode 100644 index 0000000..a82b583 --- /dev/null +++ b/lib/widgets/chat/chat_event_action_log.dart @@ -0,0 +1,43 @@ +import 'dart:math'; + +import 'package:flutter/material.dart'; +import 'package:flutter_markdown/flutter_markdown.dart'; +import 'package:get/get.dart'; +import 'package:solian/models/event.dart'; +import 'package:solian/widgets/attachments/attachment_list.dart'; +import 'package:timeago/timeago.dart' show format; +import 'package:url_launcher/url_launcher_string.dart'; + +class ChatEventMessageActionLog extends StatelessWidget { + final Widget icon; + final String text; + final bool isMerged; + final bool isHasMerged; + + const ChatEventMessageActionLog({ + super.key, + required this.icon, + required this.text, + this.isMerged = false, + this.isHasMerged = false, + }); + + @override + Widget build(BuildContext context) { + return Opacity( + opacity: 0.75, + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + icon, + const SizedBox(width: 4), + Text(text), + ], + ).paddingOnly( + left: isMerged ? 64 : 12, + top: 2, + bottom: isHasMerged ? 2 : 0, + ), + ); + } +} diff --git a/lib/widgets/chat/chat_message_deletion.dart b/lib/widgets/chat/chat_event_deletion.dart similarity index 86% rename from lib/widgets/chat/chat_message_deletion.dart rename to lib/widgets/chat/chat_event_deletion.dart index 92b8fa7..a17641d 100644 --- a/lib/widgets/chat/chat_message_deletion.dart +++ b/lib/widgets/chat/chat_event_deletion.dart @@ -6,12 +6,12 @@ import 'package:solian/models/event.dart'; import 'package:solian/models/realm.dart'; import 'package:solian/providers/auth.dart'; -class ChatMessageDeletionDialog extends StatefulWidget { +class ChatEventDeletionDialog extends StatefulWidget { final Channel channel; final Realm? realm; final Event item; - const ChatMessageDeletionDialog({ + const ChatEventDeletionDialog({ super.key, required this.channel, required this.realm, @@ -19,11 +19,11 @@ class ChatMessageDeletionDialog extends StatefulWidget { }); @override - State createState() => - _ChatMessageDeletionDialogState(); + State createState() => + _ChatEventDeletionDialogState(); } -class _ChatMessageDeletionDialogState extends State { +class _ChatEventDeletionDialogState extends State { bool _isBusy = false; void performAction() async { diff --git a/lib/widgets/chat/chat_event_message.dart b/lib/widgets/chat/chat_event_message.dart new file mode 100644 index 0000000..6866fed --- /dev/null +++ b/lib/widgets/chat/chat_event_message.dart @@ -0,0 +1,93 @@ +import 'dart:math'; + +import 'package:flutter/material.dart'; +import 'package:flutter_markdown/flutter_markdown.dart'; +import 'package:get/get.dart'; +import 'package:solian/models/event.dart'; +import 'package:solian/widgets/attachments/attachment_list.dart'; +import 'package:url_launcher/url_launcher_string.dart'; + +class ChatEventMessage extends StatelessWidget { + final Event item; + final bool isContentPreviewing; + final bool isQuote; + final bool isMerged; + final bool isHasMerged; + + const ChatEventMessage({ + super.key, + required this.item, + this.isContentPreviewing = false, + this.isMerged = false, + this.isHasMerged = false, + this.isQuote = false, + }); + + Widget buildContent() { + final body = EventMessageBody.fromJson(item.body); + final hasAttachment = body.attachments?.isNotEmpty ?? false; + + return Markdown( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + data: body.text, + selectable: true, + padding: const EdgeInsets.all(0), + onTapLink: (text, href, title) async { + if (href == null) return; + await launchUrlString( + href, + mode: LaunchMode.externalApplication, + ); + }, + ).paddingOnly( + left: 12, + right: 12, + top: 2, + bottom: hasAttachment ? 4 : (isHasMerged ? 2 : 0), + ); + } + + Widget buildBody(BuildContext context) { + final body = EventMessageBody.fromJson(item.body); + + if (isContentPreviewing || isQuote) { + return buildContent(); + } else if (isMerged) { + return Column( + children: [ + buildContent().paddingOnly(left: 52), + if (body.attachments?.isNotEmpty ?? false) + AttachmentList( + key: Key('m${item.uuid}attachments'), + parentId: item.uuid, + attachmentsId: body.attachments ?? List.empty(), + ).paddingSymmetric(vertical: 4), + ], + ); + } else { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + buildContent(), + if (body.attachments?.isNotEmpty ?? false) + SizedBox( + width: min(MediaQuery.of(context).size.width, 640), + child: AttachmentList( + key: Key('m${item.uuid}attachments'), + parentId: item.uuid, + attachmentsId: body.attachments ?? List.empty(), + divided: true, + viewport: 1, + ), + ), + ], + ); + } + } + + @override + Widget build(BuildContext context) { + return buildBody(context); + } +} diff --git a/lib/widgets/chat/chat_message.dart b/lib/widgets/chat/chat_message.dart deleted file mode 100644 index 6501f18..0000000 --- a/lib/widgets/chat/chat_message.dart +++ /dev/null @@ -1,198 +0,0 @@ -import 'dart:math'; - -import 'package:flutter/material.dart'; -import 'package:flutter_animate/flutter_animate.dart'; -import 'package:flutter_markdown/flutter_markdown.dart'; -import 'package:font_awesome_flutter/font_awesome_flutter.dart'; -import 'package:get/get.dart'; -import 'package:solian/models/event.dart'; -import 'package:solian/widgets/account/account_avatar.dart'; -import 'package:solian/widgets/account/account_profile_popup.dart'; -import 'package:solian/widgets/attachments/attachment_list.dart'; -import 'package:timeago/timeago.dart' show format; -import 'package:url_launcher/url_launcher_string.dart'; - -class ChatMessage extends StatelessWidget { - final Event item; - final bool isContentPreviewing; - final bool isReply; - final bool isMerged; - final bool isHasMerged; - - const ChatMessage({ - super.key, - required this.item, - this.isContentPreviewing = false, - this.isMerged = false, - this.isHasMerged = false, - this.isReply = false, - }); - - Future decodeContent(Map content) async { - String? text; - if (item.type == 'm.text') { - switch (content['algorithm']) { - case 'plain': - text = content['value']; - default: - throw Exception('Unsupported algorithm'); - } - } - - return text; - } - - Widget buildContent() { - final hasAttachment = item.attachments?.isNotEmpty ?? false; - - return FutureBuilder( - future: decodeContent(item.body), - builder: (context, snapshot) { - if (!snapshot.hasData) { - return Opacity( - opacity: 0.8, - child: Row( - children: [ - const Icon(Icons.more_horiz), - const SizedBox(width: 4), - Text('messageDecoding'.tr) - ], - ), - ).animate(onPlay: (c) => c.repeat()).fade(begin: 0, end: 1); - } else if (snapshot.hasError) { - return Opacity( - opacity: 0.9, - child: Row( - children: [ - const Icon(Icons.close), - const SizedBox(width: 4), - Text( - 'messageDecodeFailed' - .trParams({'message': snapshot.error.toString()}), - ) - ], - ), - ); - } - - if (snapshot.data?.isNotEmpty ?? false) { - return Markdown( - shrinkWrap: true, - physics: const NeverScrollableScrollPhysics(), - data: snapshot.data ?? '', - padding: const EdgeInsets.all(0), - onTapLink: (text, href, title) async { - if (href == null) return; - await launchUrlString( - href, - mode: LaunchMode.externalApplication, - ); - }, - ).paddingOnly( - left: 12, - right: 12, - top: 2, - bottom: hasAttachment ? 4 : 0, - ); - } else { - return const SizedBox(); - } - }, - ); - } - - Widget buildBody(BuildContext context) { - if (isContentPreviewing) { - return buildContent(); - } else if (isMerged) { - return Column( - children: [ - buildContent().paddingOnly(left: 52), - if (item.attachments?.isNotEmpty ?? false) - AttachmentList( - key: Key('m${item.uuid}attachments'), - parentId: item.uuid, - attachmentsId: item.attachments ?? List.empty(), - ).paddingSymmetric(vertical: 4), - ], - ); - } else if (isReply) { - return Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Transform.scale( - scaleX: -1, - child: const FaIcon(FontAwesomeIcons.reply, size: 14), - ), - const SizedBox(width: 12), - AccountAvatar(content: item.sender.account.avatar, radius: 8), - const SizedBox(width: 4), - Text( - item.sender.account.nick, - style: const TextStyle(fontWeight: FontWeight.bold), - ), - Expanded(child: buildContent()), - ], - ); - } else { - return Column( - key: Key('m${item.uuid}'), - children: [ - Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - GestureDetector( - child: AccountAvatar(content: item.sender.account.avatar), - onTap: () { - showModalBottomSheet( - useRootNavigator: true, - isScrollControlled: true, - backgroundColor: Theme.of(context).colorScheme.surface, - context: context, - builder: (context) => AccountProfilePopup( - account: item.sender.account, - ), - ); - }, - ), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Text( - item.sender.account.nick, - style: const TextStyle(fontWeight: FontWeight.bold), - ), - const SizedBox(width: 4), - Text(format(item.createdAt, locale: 'en_short')) - ], - ).paddingSymmetric(horizontal: 12), - buildContent(), - if (item.attachments?.isNotEmpty ?? false) - SizedBox( - width: min(MediaQuery.of(context).size.width, 640), - child: AttachmentList( - key: Key('m${item.uuid}attachments'), - parentId: item.uuid, - attachmentsId: item.attachments ?? List.empty(), - divided: true, - viewport: 1, - ), - ), - ], - ), - ), - ], - ).paddingSymmetric(horizontal: 12), - ], - ); - } - } - - @override - Widget build(BuildContext context) { - return buildBody(context); - } -} diff --git a/lib/widgets/chat/chat_message_input.dart b/lib/widgets/chat/chat_message_input.dart index 77001cf..fa31fc1 100644 --- a/lib/widgets/chat/chat_message_input.dart +++ b/lib/widgets/chat/chat_message_input.dart @@ -7,7 +7,7 @@ import 'package:solian/models/channel.dart'; import 'package:solian/models/event.dart'; import 'package:solian/providers/auth.dart'; import 'package:solian/widgets/attachments/attachment_publish.dart'; -import 'package:solian/widgets/chat/chat_message.dart'; +import 'package:solian/widgets/chat/chat_event.dart'; import 'package:uuid/uuid.dart'; class ChatMessageInput extends StatefulWidget { @@ -54,14 +54,6 @@ class _ChatMessageInputState extends State { ); } - Map encodeMessage(String content) { - return { - 'value': content.trim(), - 'keypair_id': null, - 'algorithm': 'plain', - }; - } - Future sendMessage() async { _focusNode.requestFocus(); @@ -71,15 +63,24 @@ class _ChatMessageInputState extends State { final client = auth.configureClient('messaging'); + // TODO Deal with the @ ping (query uid with username), and then add into related_user and replace the @ with internal link in body + final payload = { 'uuid': const Uuid().v4(), - 'type': 'm.text', - 'content': encodeMessage(_textController.value.text), - 'attachments': List.from(_attachments), - 'reply_to': _replyTo?.id, + 'type': _editTo == null ? 'messages.new' : 'messages.edit', + 'body': { + 'text': _textController.value.text, + 'algorithm': 'plain', + 'attachments': List.from(_attachments), + 'related_users': [ + if (_replyTo != null) _replyTo!.sender.accountId, + ], + if (_replyTo != null) 'quote_event': _replyTo!.id, + if (_editTo != null) 'related_event': _editTo!.id, + } }; - // The mock data + // The local mock data final sender = Sender( id: 0, createdAt: DateTime.now(), @@ -94,18 +95,15 @@ class _ChatMessageInputState extends State { uuid: payload['uuid'] as String, createdAt: DateTime.now(), updatedAt: DateTime.now(), - body: payload['content'] as Map, + body: payload['body'] as Map, type: payload['type'] as String, - attachments: _attachments, sender: sender, - replyId: _replyTo?.id, - replyTo: _replyTo, channelId: widget.channel.id, senderId: sender.id, ); if (_editTo == null) { - message.isSending = true; + message.isPending = true; widget.onSent(message); } @@ -139,9 +137,10 @@ class _ChatMessageInputState extends State { } void syncWidget() { - if (widget.edit != null) { + if (widget.edit != null && widget.edit!.type.startsWith('messages')) { + final body = EventMessageBody.fromJson(widget.edit!.body); _editTo = widget.edit!; - _textController.text = widget.edit!.body['value']; + _textController.text = body.text; } if (widget.reply != null) { _replyTo = widget.reply!; @@ -177,7 +176,7 @@ class _ChatMessageInputState extends State { .colorScheme .surfaceContainerHighest .withOpacity(0.5), - content: ChatMessage( + content: ChatEvent( item: _replyTo!, isContentPreviewing: true, ), @@ -192,7 +191,7 @@ class _ChatMessageInputState extends State { .colorScheme .surfaceContainerHighest .withOpacity(0.5), - content: ChatMessage( + content: ChatEvent( item: _editTo!, isContentPreviewing: true, ),