Add back serializeDocumentToMarkdown

This commit is contained in:
Hillel Coren 2024-01-02 16:44:54 +02:00
parent 4b06e9cabe
commit 390a7b393f
1 changed files with 69 additions and 0 deletions

View File

@ -31,6 +31,75 @@ MutableDocument deserializeMarkdownToDocument(String markdown) {
return MutableDocument(nodes: nodeVisitor.content);
}
String serializeDocumentToMarkdown(Document doc) {
final StringBuffer buffer = StringBuffer();
bool isFirstLine = true;
for (int i = 0; i < doc.nodes.length; ++i) {
final node = doc.nodes[i];
if (!isFirstLine) {
// Create a new line to encode the given node.
buffer.writeln('');
} else {
isFirstLine = false;
}
if (node is ImageNode) {
buffer.write('![${node.altText}](${node.imageUrl})');
} else if (node is HorizontalRuleNode) {
buffer.write('---');
} else if (node is ListItemNode) {
final indent = List.generate(node.indent + 1, (index) => ' ').join('');
final symbol = node.type == ListItemType.unordered ? '*' : '1.';
buffer.write('$indent$symbol ${node.text.toMarkdown()}');
final nodeBelow = i < doc.nodes.length - 1 ? doc.nodes[i + 1] : null;
if (nodeBelow != null && (nodeBelow is! ListItemNode)) {
// This list item is the last item in the list. Add an extra
// blank line after it.
buffer.writeln('');
}
} else if (node is ParagraphNode) {
final Attribution blockType = node.getMetadataValue('blockType');
if (blockType == header1Attribution) {
buffer.write('# ${node.text.toMarkdown()}');
} else if (blockType == header2Attribution) {
buffer.write('## ${node.text.toMarkdown()}');
} else if (blockType == header3Attribution) {
buffer.write('### ${node.text.toMarkdown()}');
} else if (blockType == header4Attribution) {
buffer.write('#### ${node.text.toMarkdown()}');
} else if (blockType == header5Attribution) {
buffer.write('##### ${node.text.toMarkdown()}');
} else if (blockType == header6Attribution) {
buffer.write('###### ${node.text.toMarkdown()}');
} else if (blockType == blockquoteAttribution) {
// TODO: handle multiline
buffer.write('> ${node.text.toMarkdown()}');
} else if (blockType == codeAttribution) {
buffer //
..writeln('```') //
..writeln(node.text.toMarkdown()) //
..write('```');
} else {
buffer.write(node.text.toMarkdown());
}
// Separates paragraphs with blank lines.
// If we are at the last node we don't add a trailing
// blank line.
if (i != doc.nodes.length - 1) {
buffer.writeln();
}
}
}
return buffer.toString();
}
/// Converts structured markdown to a list of [DocumentNode]s.
///
/// To use [_MarkdownToDocument], obtain a series of markdown