diff --git a/lib/core/checklist.dart b/lib/core/checklist.dart index 85cc2a92..dcdf800b 100644 --- a/lib/core/checklist.dart +++ b/lib/core/checklist.dart @@ -105,10 +105,9 @@ class Checklist { } void addItem(ChecklistItem item) { + _insertNewLineIfRequired(nodes.length - 1); + items.add(item); - if (nodes.isNotEmpty && !nodes.last.textContent.endsWith('\n')) { - nodes.add(md.Text("\n")); - } nodes.add(item.element); } @@ -126,9 +125,22 @@ class Checklist { var prevItem = items[index]; var nodeIndex = nodes.indexOf(prevItem.element); + _insertNewLineIfRequired(nodeIndex); + nodes.insert(nodeIndex, item.element); items.insert(index, item); } + + void _insertNewLineIfRequired(int pos) { + if (nodes.isEmpty) return; + + var node = nodes[pos]; + if (node is md.Text) { + if (!node.text.endsWith('\n')) { + nodes.add(md.Text("\n")); + } + } + } } /// Copied from flutter-markdown - cannot be merged as we added xUpperCase and changed the regexp diff --git a/test/checklist_test.dart b/test/checklist_test.dart index 22ce5f28..001566ca 100644 --- a/test/checklist_test.dart +++ b/test/checklist_test.dart @@ -150,6 +150,26 @@ Booga Wooga expect(note.body, "Hi.\n[ ] item\n"); }); + test('Should not add \\n when adding after item', () async { + var content = "[ ] one"; + + var notePath = p.join(tempDir.path, "note13.md"); + await File(notePath).writeAsString(content); + + var parentFolder = NotesFolder(null, tempDir.path); + var note = Note(parentFolder, notePath); + await note.load(); + + var checklist = Checklist(note); + var items = checklist.items; + expect(items.length, equals(1)); + + checklist.addItem(checklist.buildItem(false, "item")); + + note = checklist.note; + expect(note.body, "[ ] one\n[ ] item\n"); + }); + test('insertItem works', () async { var content = "Hi.\n[ ] One\nTwo\n[ ] Three";