UNPKG

2.88 kBJavaScriptView Raw
1const marked = require('./marked');
2const babel = require('babel-core');
3const renderer = new marked.Renderer();
4const yamlFront = require('yaml-front-matter')
5
6const highlightjs = require('highlight.js');
7
8
9let res;
10const id = 'comp' + Math.random();
11
12const oldCode = renderer.code;
13
14// marked.setOptions({
15// highlight: function (code) {
16// return require('highlight.js').highlightAuto(code).value;
17// }
18// });
19
20function escape(html, encode) {
21 return html
22 .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
23 .replace(/</g, '&lt;')
24 .replace(/>/g, '&gt;')
25 .replace(/"/g, '&quot;')
26 .replace(/'/g, '&#39;');
27}
28
29function unescape(html) {
30 // explicitly match decimal, hex, and named HTML entities
31 return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
32 n = n.toLowerCase();
33 if (n === 'colon') return ':';
34 if (n.charAt(0) === '#') {
35 return n.charAt(1) === 'x'
36 ? String.fromCharCode(parseInt(n.substring(2), 16))
37 : String.fromCharCode(+n.substring(1));
38 }
39 return '';
40 });
41}
42
43renderer.code = (code, language, escaped) => {
44 res = code;
45
46 const validLang = !!(language && highlightjs.getLanguage(language));
47 // Highlight only if the language is valid.
48 const highlighted = validLang ? highlightjs.highlight(language, code).value : code;
49 // Render the highlighted code with `hljs` class.
50 return `<pre><code class="hljs ${language}">${highlighted}</code></pre>`;
51
52 return `
53 <div>
54 <div id=${id}></div>
55 <pre><code>${escape(code)}</code></pre>
56 </div>`;
57}
58
59renderer.table = function (header, body) {
60 return '<table class="table table-striped">'+header+body+'</table>'
61}
62
63renderer.list = function(body, ordered) {
64 var type = ordered ? 'ol' : 'ul';
65 var styles = ordered ? 'upper-roman' : 'disc';
66 return '<' + type + ' style="padding-left:40px; list-style-type:'+ styles + ';" >\n' + body + '</' + type + '>\n';
67}
68
69function process(source) {
70 source = marked(source, {
71 renderer: renderer,
72 gfm: true,
73 tables: true,
74 breaks: true,
75 pedantic: false,
76 sanitize: true,
77 smartLists: true,
78 smartypants: false,
79 highlight: function (code) {
80 return require('highlight.js').highlightAuto(code).value;
81 }
82 });
83
84 const res = JSON.stringify(source);
85 return res;
86}
87
88
89module.exports = function(source, map){
90 this.cacheable && this.cacheable();
91
92 res = '';
93 const yaml = yamlFront.loadFront(source, 'content');
94 //对source进行解析
95 var md = process(yaml.content);
96 res += `\n export const md=${md}; \n export const id="${id}";`
97 console.log('----------------')
98 console.log(res);
99 console.log('--------------')
100
101 this.callback(null, res, map);
102 // return "module.exports = " + '{}';
103}
\No newline at end of file