Checklist: Avoid extra \n

The markdown parser is weird.
This commit is contained in:
Vishesh Handa
2020-04-02 17:56:48 +02:00
parent 28ef551805
commit 26f641380d
2 changed files with 51 additions and 0 deletions

View File

@ -40,9 +40,39 @@ class Checklist {
);
nodes = doc.parseInline(_note.body);
_cleanupNodes(nodes);
items = ChecklistBuilder().build(nodes);
}
void _cleanupNodes(List<md.Node> nodes) {
if (nodes.length <= 1) {
return;
}
var last = nodes.last;
var secLast = nodes[nodes.length - 2];
if (last is! md.Text) {
return;
}
if (secLast is! md.Element) {
return;
}
var elem = secLast as md.Element;
if (elem.tag != 'input' || elem.attributes['type'] != 'checkbox') {
return;
}
// Some times we get an extra \n in the end, not sure why.
if (last.textContent == '\n') {
nodes.length = nodes.length - 1;
if (!elem.attributes["text"].endsWith('\n')) {
elem.attributes["text"] += '\n';
}
}
}
Note get note {
if (nodes.isEmpty) return _note;

View File

@ -205,5 +205,26 @@ Booga Wooga
note = checklist.note;
expect(note.body, "Hi.\n[ ] One\nTwo\n");
});
test('Does not add extra new line', () async {
var content = "[ ] One\n[ ]Two\n[ ] Three\n[ ] Four\n";
var notePath = p.join(tempDir.path, "note449.md");
await File(notePath).writeAsString(content);
var parentFolder = NotesFolderFS(null, tempDir.path);
var note = Note(parentFolder, notePath);
await note.load();
var checklist = Checklist(note);
/*
for (var node in checklist.nodes) {
print("node $node - '${node.textContent}'");
}*/
checklist.addItem(checklist.buildItem(false, "Five"));
note = checklist.note;
expect(note.body, "[ ] One\n[ ]Two\n[ ] Three\n[ ] Four\n[ ] Five\n");
});
});
}