-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
72 lines (63 loc) · 2.29 KB
/
index.js
File metadata and controls
72 lines (63 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const codeBlocks = require('gfm-code-blocks');
const merge = require('lodash/merge');
const cryptoRandomString = require('crypto-random-string');
const PLUGIN_CONST = require('./lib/constants');
const renderers = require('./lib/renderers');
const utils = require('./lib/utils');
const defaultOpts = {
renderer: 'bootstrap3',
};
const getLine = (state, line) => {
const pos = state.bMarks[line] + state.blkIndent;
const max = state.eMarks[line];
return state.src.substr(pos, max - pos);
};
const createGroup = () => {
return (state, startLine, endLine) => {
if (getLine(state, startLine) === `[${PLUGIN_CONST.tokenName}]`) {
const startPgn = startLine + 1;
let nextLine = startPgn;
while (nextLine < endLine) {
if (getLine(state, nextLine) === `[/${PLUGIN_CONST.tokenName}]`) {
state.tokens.push({
type: PLUGIN_CONST.tokenName,
content: state.getLines(startPgn, nextLine, state.blkIndent, true),
block: true,
lines: [startLine, nextLine],
level: state.level,
});
state.line = nextLine + 1;
return true;
}
nextLine++;
}
}
return false;
};
};
const renderCodeGroup = (md, options, content, block) => {
const parsedCodeBlocks = codeBlocks(content);
parsedCodeBlocks.forEach((item, i) => {
const descriptor = item.lang;
item.tabId = `${descriptor.replace(PLUGIN_CONST.langSeperator, '-')}-${cryptoRandomString(10)}-${i}`;
item.tabName = utils.getTabName(descriptor);
item.langName = utils.getLangName(descriptor);
item.sanitizedBlock = item.block.replace(descriptor, item.langName);
item.render = md.render(item.sanitizedBlock);
});
return renderers[options.renderer](md, options, parsedCodeBlocks, content, block);
};
const getOpts = (options) => {
const builtOpts = merge({}, defaultOpts, options);
if (!renderers[builtOpts.renderer]) {
builtOpts.renderer = defaultOpts.renderer;
}
return builtOpts;
};
module.exports = (md, options) => {
const builtOpts = getOpts(options);
md.block.ruler.before('code', PLUGIN_CONST.tokenName, createGroup(md), { alt: [] });
md.renderer.rules.codegroup = function codegroupRender(tokens, idx) {
return renderCodeGroup(md, builtOpts, tokens[idx].content, tokens[idx].block);
};
};