splitColorTags function
Implementation
List<ColoredText> splitColorTags(String text) {
final startTagIndexes =
RegExp(r"<color=(\w+)>").allMatches(text).map((tag) => tag.start);
final endTagIndexes =
RegExp(r"</color>").allMatches(text).map((tag) => tag.end);
final tagMatches = <List<int>>[];
for (int startIndex in startTagIndexes) {
final lastIndex = tagMatches.lastOrNull?.lastOrNull;
if (lastIndex != null && startIndex < lastIndex) {
continue;
}
final endIndex = endTagIndexes.firstWhereOrNull((i) => i > startIndex);
if (endIndex == null) {
continue;
}
tagMatches.add([startIndex, endIndex]);
}
final coloredTextStart = tagMatches.map((e) => e.first);
final normalTextStart = tagMatches.map((e) => e.last + 1).toList();
if (coloredTextStart.firstOrNull != 0) {
normalTextStart.insert(0, 0);
}
if (normalTextStart.lastOrNull != null &&
normalTextStart.last > text.length) {
normalTextStart.removeLast();
}
int pointer = 0;
final coloredTexts = <ColoredText>[];
tagMatches.forEach((tagMatch) {
if (pointer < tagMatch.first) {
coloredTexts
.add(ColoredText.deligate(text.substring(pointer, tagMatch.first)));
pointer = tagMatch.first;
}
final coloredText =
ColoredText.generate(text.substring(pointer, tagMatch.last));
if (coloredText != null) {
coloredTexts.add(coloredText);
pointer = tagMatch.last;
}
});
if (pointer != text.length) {
coloredTexts
.add(ColoredText.deligate(text.substring(pointer, text.length)));
}
return coloredTexts;
}