@diplodoc/transform
Version:
A simple transformer of text in YFM (Yandex Flavored Markdown) to HTML
53 lines • 2.18 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderTokens = exports.replaceTokens = exports.TOKEN_NAME = void 0;
const pattern = /^{%[^\S\r\n]*anchor[^\S\r\n]+([\w-]+)[^\S\r\n]*%}/;
exports.TOKEN_NAME = 'anchor';
function isParagraph(tokens, i) {
return (tokens[i].type === 'paragraph_open' &&
tokens[i + 1].type === 'inline' &&
tokens[i + 2].type === 'paragraph_close');
}
function hasSingleChildWithText(tokens, i) {
var _a, _b;
return ((_a = tokens[i + 1].children) === null || _a === void 0 ? void 0 : _a.length) === 1 && ((_b = tokens[i + 1].children) === null || _b === void 0 ? void 0 : _b[0].type) === 'text';
}
function matchOpenToken(tokens, i) {
var _a;
return (isParagraph(tokens, i) &&
hasSingleChildWithText(tokens, i) &&
pattern.exec((_a = tokens[i + 1].children) === null || _a === void 0 ? void 0 : _a[0].content));
}
function createAnchorToken(state, anchorId, position) {
const token = new state.Token(exports.TOKEN_NAME, '', 0);
token.map = state.tokens[position].map;
token.markup = state.tokens[position].markup;
token.content = anchorId;
return token;
}
function replaceTokens(state) {
const blockTokens = state.tokens;
// I hate the idea of splicing the array while we're iterating over it
// so first lets find all the places where we will need to splice it and then actually do the splicing
const splicePointsMap = new Map();
for (let i = 0; i < blockTokens.length; i++) {
const match = matchOpenToken(blockTokens, i);
if (!match) {
continue;
}
splicePointsMap.set(i, match[1]);
}
Array.from(splicePointsMap)
.sort(([keyA], [keyB]) => keyB - keyA)
.forEach(([position, anchorId]) => {
blockTokens.splice(position, 3, createAnchorToken(state, anchorId, position));
});
}
exports.replaceTokens = replaceTokens;
function renderTokens(tokens, idx) {
const token = tokens[idx];
const id = token.content;
return `<hr id=${id} class="visually-hidden"/>`;
}
exports.renderTokens = renderTokens;
//# sourceMappingURL=block-anchor.js.map