setDraft method

  1. @override
Future<void> setDraft({
  1. ChatMessageText? text,
  2. List<Attachment> attachments = const [],
  3. List<ChatItem> repliesTo = const [],
  4. List<Donation> donations = const [],
})
override

Updates the draft with the provided text, attachments and repliesTo.

Resets it, if the specified fields are empty or null.

Implementation

@override
Future<void> setDraft({
  ChatMessageText? text,
  List<Attachment> attachments = const [],
  List<ChatItem> repliesTo = const [],
  List<Donation> donations = const [],
}) async {
  Log.debug(
    'setDraft($text, $attachments, $repliesTo, $donations)',
    '$runtimeType($id)',
  );

  await _draftGuard.protect(() async {
    ChatMessage? draft;

    try {
      draft = await _draftLocal.read(id);
    } catch (e) {
      Log.debug(
        'setDraft() -> `_draftLocal.read($id)` failed -> $e',
        '$runtimeType($id)',
      );

      // No-op?
    }

    if (text == null &&
        attachments.isEmpty &&
        repliesTo.isEmpty &&
        donations.isEmpty) {
      if (draft != null) {
        await _draftLocal.delete(id);
      }
    } else {
      final bool repliesEqual = const IterableEquality().equals(
        (draft?.repliesTo ?? []).map((e) => e.original?.id),
        repliesTo.map((e) => e.id),
      );

      final bool attachmentsEqual = const IterableEquality().equals(
        (draft?.attachments ?? []).map((e) => [e.id, e.runtimeType]),
        attachments.map((e) => [e.id, e.runtimeType]),
      );

      final bool donationsEqual = const IterableEquality().equals(
        (draft?.donations ?? []).map((e) => [e.amount.val, e.id]),
        donations.map((e) => [e.amount.val, e.id]),
      );

      if (draft?.text != text ||
          !repliesEqual ||
          !attachmentsEqual ||
          !donationsEqual) {
        draft = ChatMessage(
          ChatItemId.local(),
          id,
          User(me ?? const UserId('dummy'), UserNum('1234123412341234')),
          PreciseDateTime.now(),
          text: text,
          repliesTo: repliesTo.map((e) => ChatItemQuote.from(e)).toList(),
          attachments: attachments,
          donations: donations,
        );
        _draftLocal.upsert(id, draft);
      }
    }
  });
}