editMessage method

void editMessage(
  1. ChatItem item
)

Starts the editing of the specified item, if allowed.

Implementation

void editMessage(ChatItem item) {
  if (!item.isEditable(chat!.chat.value, me!)) {
    MessagePopup.error('err_uneditable_message'.l10n);
    return;
  }

  if (item is ChatMessage) {
    edit.value ??= MessageFieldController(
      _chatService,
      _userService,
      _settingsRepository,
      text: item.text?.val,
      onSubmit: () async {
        final ChatMessage item = edit.value?.edited.value as ChatMessage;

        _stopTyping();

        if (edit.value!.field.text.trim().isNotEmpty ||
            edit.value!.attachments.isNotEmpty ||
            edit.value!.replied.isNotEmpty) {
          try {
            await _chatService.editChatMessage(
              item,
              text: ChatMessageTextInput(
                ChatMessageText(edit.value!.field.text),
              ),
              attachments: ChatMessageAttachmentsInput(
                edit.value!.attachments.map((e) => e.value).toList(),
              ),
              repliesTo: ChatMessageRepliesInput(
                edit.value!.replied.map((e) => e.value.id).toList(),
              ),
            );

            closeEditing();

            send.field.focus.requestFocus();
          } on EditChatMessageException catch (e) {
            if (e.code == EditChatMessageErrorCode.blocked) {
              _showBlockedPopup();
            } else {
              MessagePopup.error(e);
            }
          } catch (e) {
            MessagePopup.error(e);
            rethrow;
          }
        } else {
          MessagePopup.error('err_no_text_no_attachment_and_reply'.l10n);
        }
      },
      onChanged: () {
        if (edit.value?.edited.value == null) {
          closeEditing();
        }
      },
    );

    edit.value?.edited.value = item;
    edit.value?.field.focus.requestFocus();

    // Stop the [_typingSubscription] when the edit field loses its focus.
    edit.value?.field.focus.addListener(_stopTypingOnUnfocus);
  }
}