-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
103 lines (88 loc) · 2.08 KB
/
index.js
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
* Created by jufei on 2017/6/18.
*/
import getBlockType from './getBlockType';
import * as format from './format';
import './style/index.less';
/**
* script
* @type {RegExp}
* @private
*/
const _script = /<(script).*\/*>(.*<\/\1\s*>)?/gi;
/**
* empty
* @type {RegExp}
* @private
*/
const _empty = /^\s*$/;
/**
* toHTML
* @param value
* @return {*}
*/
export default function toHTML(value) {
// 验证value是否为String类型,如果不是抛出异常
if (Object.prototype.toString.call(value) !== '[object String]') {
throw 'toHTML arguments[0] must be string'
}
// 验证value是否为空
if (_empty.test(value)) {
throw 'argument[0] is empty'
}
value = value.replace(_script,'');
let chunks= value.split('\n'),
chunk = '',
valueLength = chunks.length,
index = 0,
result = '';
while (index < valueLength) {
chunk = chunks[index];
switch (getBlockType(chunk)){
// 空行
case 'empty':
index++;
break;
// 标题
case '_isTitle':
result += format.title(chunk);
index++;
break;
// 引用
case '_isQuote':
result += format.quote(chunk);
index++;
break;
// 代码
case '_isCode':
let codeChunks = [chunk];
while (index < valueLength - 1 && !/^```\s*$/.test(chunks[index+1])){
codeChunks.push(chunks[++index])
}
codeChunks.push(chunks[++index]);
result += format.code(codeChunks);
index++;
break;
// 分割线
case '_isHr':
result += '<hr/>';
index++;
break;
// 列表
case '_isListStart':
let items = [chunk];
while(index + 1 < valueLength && /^\s*([\-*+]|\d\.)\s/.test(chunks[index + 1])){
items.push(chunks[++index])
}
result += format.list(items);
index++;
break;
// 无特殊字符
case 'noBlockType':
result += format.normal(chunk);
index++;
break;
}
}
return `<div class="ju-markdown">${result}</div>`;
}