forked from nagaozen/markdown-it-toc-done-right
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
157 lines (129 loc) · 4.51 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
"use strict"
function slugify(x) {
return encodeURIComponent(String(x).trim().toLowerCase().replace(/\s+/g, '-'));
}
function htmlencode(x) {
// safest, delegate task to native -- IMPORTANT: enabling this breaks both jest and runkit, but with browserify it's fine
/* if(document && document.createElement) {
const el = document.createElement("div");
el.innerText = x;
return el.innerHTML;
}*/
return String(x).replace(/&/g, "&")
.replace(/"/g, """)
.replace(/'/g, "'")
.replace(/</g, "<")
.replace(/>/g, ">");
}
module.exports = function toc_plugin(md, options) {
options = Object.assign({}, {
placeholder: "(\\$\\{toc\\}|\\[\\[?_?toc_?\\]?\\])",
slugify: slugify,
containerClass: "table-of-contents",
listClass: undefined,
itemClass: undefined,
linkClass: undefined,
level: 1,
listType: "ol",
format: undefined
}, options);
let ast;
const pattern = new RegExp("^" + options.placeholder + "$", "i");
function toc(state, startLine/*, endLine, silent*/) {
let token;
const pos = state.bMarks[startLine] + state.tShift[startLine];
const max = state.eMarks[startLine];
// if it's indented more than 3 spaces, it should be a code block
/*if(state.sCount[startLine] - state.blkIndent >= 4) return false;*/
// use whitespace as a line tokenizer and extract the first token
// to test against the placeholder anchored pattern, rejecting if false
const line_first_token = state.src.slice(pos, max).split(" ")[0];
if (!pattern.test(line_first_token)) return false;
// if(silent) return true;
state.line = startLine + 1;
token = state.push("toc_open", "nav", 1);
token.markup = "";
token.map = [ startLine, state.line ];
token = state.push("toc_body", "", 0);
token.markup = "";
token.map = [ startLine, state.line ];
token.children = [];
token = state.push("toc_close", "nav", -1);
token.markup = "";
return true;
}
md.renderer.rules.toc_open = function(/*tokens, idx, options, env, renderer*/) {
return `<nav class="${htmlencode(options.containerClass)}">`;
}
md.renderer.rules.toc_close = function(/*tokens, idx, options, env, renderer*/) {
return '</nav>';
}
md.renderer.rules.toc_body = function(/*tokens, idx, options, env, renderer*/) {
return ast_html(ast);
}
function ast_html(tree, uniques) {
uniques = uniques || {};
function unique(s) {
let u = s;
let i = 2;
while (uniques.hasOwnProperty(u)) u = `${s}-${i++}`;
uniques[u] = true;
return u;
}
const list_class = options.listClass
? ` class="${htmlencode(options.listClass)}"`
: "";
const item_class = options.itemClass
? ` class="${htmlencode(options.itemClass)}"`
: "";
const link_class = options.linkClass
? ` class="${htmlencode(options.linkClass)}"`
: "";
const keys = Object.keys(tree.c);
if ( keys.length === 0 ) return "";
let buffer = (`<${htmlencode(options.listType) + list_class}>`);
keys.forEach(function(key){
const node = tree.c[key];
buffer += (`<li${item_class}><a${link_class} href="#${unique(options.slugify(key))}">${typeof options.format === "function" ? options.format(key,htmlencode) : htmlencode(key)}</a>${ast_html(node, uniques)}</li>`);
});
buffer += (`</${htmlencode(options.listType)}>`);
return buffer;
}
function headings_ast(tokens) {
const ast = { l: 0, n: "", c: {} };
const stack = [ast];
for (let i = 0, iK = tokens.length; i < iK; i++) {
const token = tokens[i];
if(token.type === "heading_open") {
const node = {
l: parseInt(token.tag.substr(1), 10),
n: ( tokens[i+1].children
.filter(function(token){return token.type === "text" || token.type === "code_inline"})
.reduce(function(acc, t){return acc + t.content}, "") ),
c: {}
};
if (node.l >= options.level) {
if ( node.l > stack[0].l ) {
stack[0].c[node.n] = node;
stack.unshift(node);
} else if ( node.l === stack[0].l ) {
stack[1].c[node.n] = node;
stack[0] = node;
} else {
while( node.l <= stack[0].l ) stack.shift();
stack[0].c[node.n] = node;
stack.unshift(node);
}
}
}
}
return ast;
}
md.core.ruler.push("generate_toc_ast", function(state){
const tokens = state.tokens;
ast = headings_ast(tokens);
});
md.block.ruler.before("heading", "toc", toc, {
alt: [ "paragraph", "reference", "blockquote" ]
});
}