diff --git a/lib/core/checklist.dart b/lib/core/checklist.dart index dcdf800b..93f484e8 100644 --- a/lib/core/checklist.dart +++ b/lib/core/checklist.dart @@ -40,9 +40,39 @@ class Checklist { ); nodes = doc.parseInline(_note.body); + _cleanupNodes(nodes); + items = ChecklistBuilder().build(nodes); } + void _cleanupNodes(List 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; diff --git a/test/checklist_test.dart b/test/checklist_test.dart index ed32fd9d..cc24b351 100644 --- a/test/checklist_test.dart +++ b/test/checklist_test.dart @@ -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"); + }); }); }