parseMarkdown function
Parses raw markdown text into a list of BlockNodes.
Supported blocks: Headers, Lists, Paragraphs, and Horizontal Rules.
Implementation
List<BlockNode> parseMarkdown(String text) {
List<String> lines = text.split('\n');
List<BlockNode> blocks = [];
int i = 0;
while (i < lines.length) {
String line = lines[i].trim();
if (line.isEmpty) {
i++;
continue;
}
if (line.startsWith('#')) {
int level = 0;
while (level < line.length && line[level] == '#') {
level++;
}
if (level < line.length && line[level] == ' ') {
String headerText = line.substring(level + 1).trim();
blocks.add(HeaderBlock(level, headerText));
i++;
continue;
}
}
if (line.startsWith('---')) {
blocks.add(HorizontalRuleBlock());
i++;
continue;
}
if (line.startsWith('- ')) {
List<String> items = [];
while (i < lines.length && lines[i].trim().startsWith('- ')) {
items.add(lines[i].trim().substring(2).trim());
i++;
}
blocks.add(ListBlock(items));
continue;
}
// Paragraph
String para = '';
while (i < lines.length && lines[i].trim().isNotEmpty) {
String currentLine = lines[i].trim();
// Stop if we hit a different block type
if (currentLine.startsWith('---')) break;
if (currentLine.startsWith('- ')) break;
if (currentLine.startsWith('#')) {
int level = 0;
while (level < currentLine.length && currentLine[level] == '#') level++;
if (level < currentLine.length && currentLine[level] == ' ') break;
}
para += (para.isEmpty ? '' : '\n') + lines[i];
i++;
}
if (para.isNotEmpty) {
blocks.add(ParagraphBlock(parseInlines(para)));
}
}
return blocks;
}