markdown-it-hashmention
Version:
Flowdock hashtag and mention parser for markdown-it
104 lines (82 loc) • 2.51 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _unicode = require('./unicode');
function not(group) {
return "[^" + group.slice(1);
}
function matcher(boundary, body, end) {
return new RegExp("(?:^|$|" + not(end) + ")((?:" + boundary + ")(?:" + body + ")*(?:" + end + ")+)", "g");
};
function split(currentToken, boundary, regex, Token, name) {
// find tokens matching regex
var text = currentToken.content;
var level = currentToken.level;
var matches = text.match(regex);
if (matches === null) {
return;
}
var nodes = [];
for (var m = 0; m < matches.length; m++) {
var start = matches[m].search(boundary);
var tagName = matches[m].slice(start + 1);
var pos = text.indexOf(matches[m]) + start;
if (pos > 0) {
var _token = new Token('text', '', 0);
_token.content = text.slice(0, pos);
_token.level = level;
nodes.push(_token);
}
var token = new Token(name, '', 0);
token.content = tagName;
token.markup = matches[m][start];
token.level = level;
nodes.push(token);
text = text.slice(pos + 1 + tagName.length);
}
if (text.length > 0) {
var token = new Token('text', '', 0);
token.content = text;
token.level = level;
nodes.push(token);
}
return nodes;
}
exports["default"] = function (md, name, boundary) {
var arrayReplaceAt = md.utils.arrayReplaceAt;
var regex = matcher(boundary.source, _unicode.tagCharacter, _unicode.tagEnd);
return function parser(state) {
var blockTokens = state.tokens;
var tokens;
// iterate over tokens
for (var j = 0; j < blockTokens.length; j++) {
if (blockTokens[j].type !== 'inline') {
continue;
}
tokens = blockTokens[j].children;
for (var i = tokens.length - 1; i >= 0; i--) {
var currentToken = tokens[i];
// skip content of links
if (currentToken.type === 'link_close') {
i--;
while (tokens[i].level !== currentToken.level && tokens[i].type !== 'link_open') {
i--;
}
continue;
}
// skip non-text tokens
if (currentToken.type !== 'text') {
continue;
}
// split text tokens
var nodes = split(currentToken, boundary, regex, state.Token, name);
if (nodes) {
blockTokens[j].children = tokens = arrayReplaceAt(tokens, i, nodes);
}
}
}
};
};
;
module.exports = exports["default"];