Stackedit/public/res/extensions/yamlFrontMatterParser.js

49 lines
1.5 KiB
JavaScript
Raw Normal View History

define([
"underscore",
"classes/Extension",
2013-10-07 00:17:21 +00:00
"yaml-js",
], function(_, Extension, YAML) {
2013-10-06 14:34:01 +00:00
var yamlFrontMatterParser = new Extension("yamlFrontMatterParser", "YAML front matter");
2013-11-07 23:10:38 +00:00
var eventMgr;
yamlFrontMatterParser.onEventMgrCreated = function(eventMgrParameter) {
eventMgr = eventMgrParameter;
};
2013-11-07 23:10:38 +00:00
var fileDesc;
2013-10-06 14:34:01 +00:00
yamlFrontMatterParser.onFileSelected = function(fileDescParam) {
fileDesc = fileDescParam;
};
var regex = /^(\s*-{3}\s*\n([\w\W]+?)\n\s*-{3}\s*\n)?([\w\W]*)$/;
2014-03-19 00:33:57 +00:00
function parseFrontMatter(fileDesc) {
2014-03-17 02:01:46 +00:00
var text = fileDesc.content;
var results = regex.exec(text);
var yaml = results[2];
2014-03-17 02:01:46 +00:00
if (yaml && (!fileDesc.frontMatter || fileDesc.frontMatter._yaml != yaml)) {
fileDesc.frontMatter = undefined;
try {
fileDesc.frontMatter = YAML.parse(yaml);
if(!_.isObject(fileDesc.frontMatter)) {
fileDesc.frontMatter = undefined;
}
2014-03-17 02:01:46 +00:00
fileDesc.frontMatter._yaml = yaml;
fileDesc.frontMatter._frontMatter = results[1];
}
catch (e) {
eventMgr.onMarkdownTrim(0);
2014-03-19 00:33:57 +00:00
return;
}
2014-03-17 02:01:46 +00:00
}
eventMgr.onMarkdownTrim((results[1] || '').length);
2014-03-19 00:33:57 +00:00
}
yamlFrontMatterParser.onFileOpen = parseFrontMatter;
yamlFrontMatterParser.onContentChanged = parseFrontMatter;
return yamlFrontMatterParser;
2014-03-19 00:33:57 +00:00
});