parseUserMentionText function

Future<void> parseUserMentionText(
  1. String htmlText,
  2. String roomId,
  3. dynamic controller,
  4. dynamic ref,
)

Implementation

Future<void> parseUserMentionText(
  String htmlText,
  String roomId,
  ActerTriggerAutoCompleteTextController controller,
  WidgetRef ref,
) async {
  final roomMentions = await ref.read(membersIdsProvider(roomId).future);
  final inputNotifier = ref.read(chatInputProvider.notifier);
  // Regular expression to match mention links
  final mentionRegex = RegExp(r'\[@([^\]]+)\]\(https://matrix\.to/#/([^)]+)\)');
  List<TaggedText> tags = [];
  String parsedText = htmlText;
  // Find all matches
  final matches = mentionRegex.allMatches(htmlText);

  int offset = 0;
  for (final match in matches) {
    final linkedName = match.group(1);
    final userId = match.group(2);

    String? displayName;
    bool isValidMention = false;

    if (linkedName != null && userId != null) {
      displayName = linkedName;
      isValidMention = roomMentions.any(
        (uId) => uId == userId,
      );
    }
    if (isValidMention && displayName != null) {
      final simpleMention = '@$displayName';
      final startIndex = match.start - offset;
      final endIndex = startIndex + simpleMention.length;
      // restore mention state of input
      inputNotifier.addMention(displayName, userId!);
      // restore tags
      tags.add(
        TaggedText(
          trigger: '@',
          displayText: simpleMention,
          start: startIndex,
          end: endIndex,
        ),
      );

      // Replace the mention in parsed text
      parsedText = parsedText.replaceRange(
        startIndex,
        match.end - offset,
        simpleMention,
      );
      offset += (match.end - match.start) - simpleMention.length;
    }
  }

  // Set the parsed text to the text controller
  controller.text = parsedText;

  // Apply the tags to the text controller
  for (var tag in tags) {
    controller.addTag(tag);
  }
}