toDetections method

List<Detection> toDetections({
  1. required TextStyle textStyle,
  2. required TextStyle detectedStyle,
  3. required RegExp detectionRegExp,
})

Implementation

List<Detection> toDetections({
  required TextStyle textStyle,
  required TextStyle detectedStyle,
  required RegExp detectionRegExp,
}) {
  var result = this;

  /// Text to change emoji into replacement text
  final fullWidthRegExp = RegExp(
    r"(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])",
  );

  final fullWidthRegExpMatches = fullWidthRegExp.allMatches(result).toList();
  final tokenRegExp = RegExp(
    r"[・ぁ-んーァ-ヶ一-龥\u1100-\u11FF\uAC00-\uD7A30-9a-zA-Z ]",
  );
  final emojiMatches = fullWidthRegExpMatches
      .where(
        (match) => !tokenRegExp.hasMatch(
          result.substring(match.start, match.end),
        ),
      )
      .toList();

  /// This is to avoid the error caused by 'regExp' which counts the emoji's length 1.
  emojiMatches.forEach((emojiMatch) {
    final emojiLength = emojiMatch.group(0)!.length;
    final replacementText = "a" * emojiLength;
    result = result.replaceRange(
      emojiMatch.start,
      emojiMatch.end,
      replacementText,
    );
  });

  final detections = detectionRegExp.allMatches(result).toList();
  if (detections.isEmpty) {
    return [];
  }

  final sourceDetections = _getSourceDetections(
    matches: detections,
    text: result,
    textStyle: textStyle,
    detectedStyle: detectedStyle,
    detectionRegExp: detectionRegExp,
  );

  final emojiFilteredResult = _getEmojiFilteredDetections(
    copiedText: result,
    emojiMatches: emojiMatches,
    source: sourceDetections,
    textStyle: textStyle,
    detectedStyle: detectedStyle,
    detectionRegExp: detectionRegExp,
  );

  return emojiFilteredResult;
}