diff --git a/lib/core/md_yaml_doc_codec.dart b/lib/core/md_yaml_doc_codec.dart index 3aac691d..22bb31cc 100644 --- a/lib/core/md_yaml_doc_codec.dart +++ b/lib/core/md_yaml_doc_codec.dart @@ -7,6 +7,10 @@ import 'package:gitjournal/utils/logger.dart'; import 'md_yaml_doc.dart'; class MarkdownYAMLCodec { + bool reverse; + + MarkdownYAMLCodec({this.reverse = false}); + MdYamlDoc decode(String str) { const startYamlStr = "---\n"; const endYamlStr = "\n---\n"; @@ -56,6 +60,23 @@ class MarkdownYAMLCodec { return MdYamlDoc(body, map); } + if (str.endsWith(endYamlStr)) { + var endYamlPos = str.length - endYamlStr.length; + var startYamlPos = str.lastIndexOf(startYamlStr, endYamlPos); + if (startYamlPos == -1) { + return MdYamlDoc(str); + } + + // FIXME: What if there is nothing afterwards? + var yamlText = + str.substring(startYamlPos + startYamlStr.length, endYamlPos); + var map = parseYamlText(yamlText); + var body = str.substring(0, startYamlPos); + + reverse = true; + return MdYamlDoc(body, map); + } + return MdYamlDoc(str, LinkedHashMap()); } @@ -85,9 +106,16 @@ class MarkdownYAMLCodec { return note.body; } - var str = toYamlHeader(note.props); - str += '\n'; - str += note.body; + var str = ""; + if (reverse) { + str += note.body.trimRight(); + str += '\n\n'; + str += toYamlHeader(note.props); + } else { + str += toYamlHeader(note.props); + str += '\n'; + str += note.body; + } return str; } diff --git a/test/md_yaml_codec_test.dart b/test/md_yaml_codec_test.dart index 64c91cb6..d01d321b 100644 --- a/test/md_yaml_codec_test.dart +++ b/test/md_yaml_codec_test.dart @@ -184,5 +184,29 @@ foo: bar var actualStr = serializer.encode(note); expect(actualStr, str + '\n'); }); + + test('YAML at the end of the doc', () { + var str = """Alright. + +--- +type: Journal +created: 2017-02-15T22:41:19+01:00 +foo: bar +--- +"""; + + var serializer = MarkdownYAMLCodec(reverse: true); + var doc = serializer.decode(str); + expect(doc.body, "Alright.\n\n"); + expect(doc.props.length, 3); + + var actualStr = serializer.encode(doc); + + expect(actualStr, str); + }); + + // FIXME: Add another test for yaml header at the bottom without a newline + // FIXME: Add another test for yaml header at the bottom with lots of new lines after + // FIXME: Add another test for yaml header at the bottom with lots of new lines with spaces after }); }