generate static method

RichTextBlock generate(
  1. String inText
)

Generates the tree of RichTextBlocks from inText

Implementation

static RichTextBlock generate(String inText) {
  RegExp open = RegExp(r"<(?<tag>([a-z]*))>");
  RegExp close = RegExp(r"<\/(?<tag>([a-z]*))>");

  Map<String, int> count = {};
  Map<String, int> closeCount = {};
  Set<String> closed = {};

  String text = inText;

  for (int i = 0; i < inText.length; i++) {
    String s = inText.substring(i);
    if (s.startsWith(open)) {
      RegExpMatch m = open.firstMatch(s)!;
      String t = m.namedGroup("tag")!;
      if (!count.containsKey(t)) {
        count[t] = 0;
        closeCount[t] = 0;
      }
      count[t] = count[t]! + 1;
      closeCount[t] = count[t]!;
      text = text.replaceFirst(open, "<$t:${count[t]}>",i);
    }
    if (s.startsWith(close)) {
      RegExpMatch m = close.firstMatch(s)!;
      String t = m.namedGroup("tag")!;
      if (closeCount.containsKey(t)) {

        while(closed.contains("$t:${closeCount[t]}")) {
          closeCount[t] = closeCount[t]! - 1;
        }
        text = text.replaceFirst(close, "</$t:${closeCount[t]}>",i);
        closed.add("$t:${closeCount[t]}");
      }
    }
  }

  return RichTextBlock._generate(text);
}