-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
111 lines (107 loc) · 2.94 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
99
100
101
102
103
104
105
106
107
108
109
110
111
'use strict';
const YAML = require("js-yaml")
const Node = require("./node")
// this code is licenced under MIT
// https://github.com/CaliStyle/markdown-it-meta
function meta_parse(state, start, end) {
function get(state, line) {
const pos = state.bMarks[line]
const max = state.eMarks[line]
return state.src.substr(pos, max - pos)
}
var startLine = state.line
if (start !== 0 || state.blkIndent !== 0) {
return false
}
if (state.tShift[start] < 0) {
return false
}
if (!get(state, start).match(/^---$/)) {
return false
}
const data = []
let line = start
while (line < end) {
line++
const str = get(state, line)
if (str.match(/^---$/)) {
break
}
if (state.tShift[line] < 0) {
break
}
data.push(str)
}
var yaml = {}
try {
var yaml = YAML.load(data.join('\n'), {json: true})
} catch (_) {}
var token = state.push('meta', '', 0)
token.content = yaml
token.map = [startLine, state.line]
token.children = [];
state.line = line + 1
return true
}
function meta_render(tokens, idx) {
function make_table(data) {
var doc = new Node()
var isObject = function (o) {
return (o instanceof Object && !(o instanceof Array)) ? true : false;
};
if (isObject(data)) {
// 辞書だった場合
// key (theadに入れる)
var keys = doc.createElement("tr")
// value (tbodyに入れる)
var values = doc.createElement("tr")
for (const key in data) {
// key
var j = doc.createElement("th")
j.appendChild(make_table(key))
keys.appendChild(j)
// value
var k = doc.createElement("td")
k.appendChild(make_table(data[key]))
values.appendChild(k)
}
// テーブルを作る
var ret = doc.createElement("table")
// tbody
var thead = doc.createElement("thead")
thead.appendChild(keys)
ret.appendChild(thead)
// tbody
var tbody = doc.createElement("tbody")
tbody.appendChild(values)
ret.appendChild(tbody)
return ret
} else if (Array.isArray(data)) {
// 配列だった場合 -> tbodyのみ
var tbl = doc.createElement("tr")
for (const i of data) {
var j = doc.createElement("td")
j.appendChild(make_table(i))
tbl.appendChild(j)
}
// tbodyに入れる
var tbody = doc.createElement("tbody")
tbody.appendChild(tbl)
var ret = doc.createElement("table")
ret.appendChild(tbody)
return ret
} else if (data == undefined) {
// データが無いとき
return doc.createTextNode("")
} else {
// ただのデータ
return doc.createElement("td").appendChild(doc.createTextNode(data))
}
}
return make_table(tokens[idx].content).outerHTML
}
function MarkdownItMetaHeader(md) {
md.block.ruler.before('code', 'meta', meta_parse)
md.renderer.rules.meta = meta_render
}
module.exports = MarkdownItMetaHeader