49 lines
1.3 KiB
JavaScript
Raw Normal View History

export function remarkParseShortcodes({ plugins }) {
const Parser = this.Parser;
const tokenizers = Parser.prototype.blockTokenizers;
const methods = Parser.prototype.blockMethods;
2017-07-31 12:58:45 -04:00
tokenizers.shortcode = createShortcodeTokenizer({ plugins });
2017-07-31 12:58:45 -04:00
methods.unshift('shortcode');
}
2017-07-31 12:58:45 -04:00
function createShortcodeTokenizer({ plugins }) {
return function tokenizeShortcode(eat, value, silent) {
const potentialMatchValue = value.split('\n\n')[0];
let match;
const plugin = plugins.find(plugin => {
match = potentialMatchValue.trim().match(plugin.pattern);
return !!match;
});
2017-07-31 12:58:45 -04:00
if (match) {
if (silent) {
return true;
}
2017-07-31 12:58:45 -04:00
const shortcodeData = plugin.fromBlock(match);
2017-07-31 12:58:45 -04:00
return eat(match[0])({
type: 'shortcode',
data: { shortcode: plugin.id, shortcodeData },
2017-07-31 12:58:45 -04:00
});
}
};
}
2017-07-31 12:58:45 -04:00
export function createRemarkShortcodeStringifier({ plugins }) {
return function remarkStringifyShortcodes() {
const Compiler = this.Compiler;
const visitors = Compiler.prototype.visitors;
2017-07-31 12:58:45 -04:00
visitors.shortcode = shortcode;
2017-07-31 12:58:45 -04:00
function shortcode(node) {
const { data } = node;
const plugin = plugins.find(plugin => data.shortcode === plugin.id);
return plugin.toBlock(data.shortcodeData);
}
};
2017-07-31 12:58:45 -04:00
}