-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
81 lines (72 loc) · 2.72 KB
/
index.js
File metadata and controls
81 lines (72 loc) · 2.72 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
73
74
75
76
77
78
79
80
81
import container from 'markdown-it-container/dist/markdown-it-container.min';
import Replacer from './lib/index';
import reactBlockRule from './lib/react_block';
import { react_inline } from './lib/react_inline';
import { getWrapperId } from './lib/func';
export function renderSimpleComponent(replacer,content,env) {
let wrapperId = getWrapperId();
if (env && typeof env === 'object') {
replacer.sandbox = {
...replacer.sandbox,
...env
};
}
const code = `return (${content})`;
try {
return `<span style="opacity: 0" id="${wrapperId}">${replacer.getHtml(wrapperId, code,env)}</span>`;
} catch (e) {
console.error(e);
return `<span style="opacity: 0" id="${wrapperId}"></span>`;
}
}
export const SupportReactComponent = (md, options) => {
md.use(...createContainer('rc', options, '`'));
md.use(...createContainer('mixin-react', options, '`'));
const replacer = new Replacer(options);
md['md-it-rc-replacer'] = replacer;
// // react_block
md.block.ruler.before('html_block','react_block',reactBlockRule,[ 'paragraph', 'reference', 'blockquote' ]);
md.renderer.rules.react_block = function (tokens, idx,options, env) {
return renderSimpleComponent(replacer,tokens[idx].content,env);
};
// // react_inline
md.inline.ruler.before('html_inline','react_inline',react_inline);
md.renderer.rules.react_inline = function (tokens, idx,options, env) {
return renderSimpleComponent(replacer,tokens[idx].content,env);
};
function createContainer (klass, options, marker = ':') {
return [container, klass, {
render (tokens, idx,_options,env) {
const token = tokens[idx];
// const info = token.info.trim().slice(klass.length).trim();
if (token.nesting === 1) {
if (env && typeof env === 'object') {
replacer.sandbox = {
...replacer.sandbox,
...env
};
}
let wrapperId = getWrapperId();
try {
const offset = tokens.slice(idx).findIndex(token => token.type === `container_${klass}_close`);
let str = tokens.slice(idx,idx + offset).reduce((pre,cur)=>{
const str = pre + '\n' + cur.content;
// reset token
cur.content = '';
cur.children = [];
return str;
},'');
const html = replacer.getHtml(wrapperId, str,env);
return `<div class="${klass}" style="opacity: 0" id="${wrapperId}">${html}`;
} catch (e) {
if (options && options.allowErrorLog) console.log(e);
return `<div class="${klass}" style="opacity: 0" id="${wrapperId}">`;
}
} else {
return '</div>\n';
}
},
marker
}];
}
};