forked from nagaozen/markdown-it-toc-done-right
/
index.js
244 lines (207 loc) · 7.78 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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
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, '>');
}
function tocPlugin(md, options) {
options = Object.assign({}, {
placeholder: '(\\$\\{toc\\}|\\[\\[?_?toc_?\\]?\\]|\\$\\<toc(\\{[^}]*\\})\\>)',
slugify: slugify,
uniqueSlugStartIndex: 2,
containerClass: 'table-of-contents',
containerId: undefined,
listClass: undefined,
itemClass: undefined,
linkClass: undefined,
level: 6, // same as @gerhobbelt/markdown-it-anchor: **max** level or array of levels
listType: 'ol',
format: undefined,
callback: undefined/* function(html, ast, state) {} */
}, 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];
// use whitespace as a line tokenizer and extract the first token
// to test against the placeholder anchored pattern, rejecting if false
const lineFirstToken = state.src.slice(pos, max).split(' ')[0];
if (!pattern.test(lineFirstToken)) return false;
if (silent) return true;
const matches = pattern.exec(lineFirstToken);
let inlineOptions = {};
if (matches !== null && matches.length === 3) {
try {
inlineOptions = JSON.parse(matches[2]);
} catch (ex) {
// silently ignore inline options
}
}
state.line = startLine + 1;
token = state.push('tocOpen', 'nav', 1);
token.markup = '';
token.map = [ startLine, state.line ];
token.inlineOptions = inlineOptions;
token = state.push('tocBody', '', 0);
token.markup = '';
token.map = [ startLine, state.line ];
token.inlineOptions = inlineOptions;
token.children = [];
token = state.push('tocClose', 'nav', -1);
token.markup = '';
return true;
}
md.renderer.rules.tocOpen = function (tokens, idx/* , options, env, renderer */) {
const token = tokens[idx];
let _options = Object.assign({}, options, token.inlineOptions);
const id = _options.containerId ? ` id="${htmlencode(_options.containerId)}"` : '';
return `<nav${id} class="${htmlencode(_options.containerClass)}">`;
};
md.renderer.rules.tocClose = function (/* tokens, idx, options, env, renderer */) {
return '</nav>';
};
md.renderer.rules.tocBody = function (tokens, idx/* , options, env, renderer */) {
const token = tokens[idx];
let _options = Object.assign({}, options, token.inlineOptions);
const uniques = new Map();
function unique(slug, failOnNonUnique) {
// If first slug, return as is.
let key = slug;
let n = _options.uniqueSlugStartIndex;
while (uniques.has(key)) {
// Duplicate slug, add a `-2`, `-3`, etc. to keep ID unique.
key = `${slug}-${n++}`;
}
if (n > _options.uniqueSlugStartIndex && failOnNonUnique) {
throw new Error(`The ID attribute '${slug}' defined by user or other markdown-it plugin is not unique. Please fix it in your markdown to continue.`);
}
// Mark this slug as used in the environment.
uniques.set(key, true);
return key;
}
const isLevelSelectedNumber = selection => level => level <= selection;
const isLevelSelectedArray = selection => level => selection.includes(level);
const isLevelSelected = Array.isArray(_options.level)
? isLevelSelectedArray(_options.level)
: isLevelSelectedNumber(_options.level);
function ast2html(tree, level) {
const listClass = _options.listClass ? ` class="${htmlencode(_options.listClass)}"` : '';
const itemClass = _options.itemClass ? ` class="${htmlencode(_options.itemClass)}"` : '';
const linkClass = _options.linkClass ? ` class="${htmlencode(_options.linkClass)}"` : '';
if (tree.c.length === 0) return '';
let buffer = '';
if (tree.l === 0 || isLevelSelected(tree.l + 1)) {
buffer += `<${htmlencode(_options.listType) + listClass}>`;
}
tree.c.forEach(node => {
// first, check if the heading already has an ID attribute:
// if it has, use that one!
let slug = node.token.attrGet('id');
if (isLevelSelected(node.l)) {
if (slug == null) {
slug = unique(options.slugify(node.n), false);
// and register the ID for this heading,
// so it won't have to be re-generated by other plugins,
// resulting in consistent ID usage in the page:
node.token.attrSet('id', slug);
}
buffer += `<li${itemClass}><a${linkClass} href="#${slug}">${typeof _options.format === 'function' ? _options.format(node.n, htmlencode) : htmlencode(node.n)}</a>${ast2html(node, node.l)}</li>`;
} else {
buffer += ast2html(node, level + 1);
}
});
if (tree.l === 0 || isLevelSelected(tree.l + 1)) {
buffer += `</${htmlencode(_options.listType)}>`;
}
return buffer;
}
tokens
.filter(token => token.type === 'heading_open')
.forEach(token => {
// Before we do anything, we must collect all previously defined ID attributes to ensure we won't generate any duplicates:
let slug = token.attrGet('id');
if (slug != null) {
// mark existing slug/ID as unique, at least.
// IFF it collides, FAIL!
unique(slug, true);
}
});
return ast2html(ast, 1);
};
function headings2ast(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') {
let keyparts = [];
for (let j = i + 1; j < iK; j++) {
const token = tokens[j];
if (token.type === 'heading_close') { break; }
if (!token.children) { continue; }
const keypart = token.children
.filter((token) => token.type === 'text' || token.type === 'code_inline')
.reduce((acc, t) => acc + t.content, '')
.trim();
if (keypart.length > 0) {
keyparts.push(keypart);
}
}
const key = keyparts.join(' ');
const node = {
l: parseInt(token.tag.substr(1), 10),
n: key,
c: [],
token
};
if (node.l > stack[0].l) {
stack[0].c.push(node);
stack.unshift(node);
} else if (node.l === stack[0].l) {
stack[1].c.push(node);
stack[0] = node;
} else {
while (node.l <= stack[0].l) stack.shift();
stack[0].c.push(node);
stack.unshift(node);
}
}
}
return ast;
}
md.core.ruler.push('generateTocAst', function (state) {
const tokens = state.tokens;
ast = headings2ast(tokens);
if (typeof options.callback === 'function') {
for (let i = 0, iK = tokens.length; i < iK; i++) {
const token = tokens[i];
if (token.type === 'tocOpen') {
options.callback(
md.renderer.rules.tocOpen(tokens, i) + md.renderer.rules.tocBody(tokens, i) + md.renderer.rules.tocClose(),
ast,
state
);
}
}
}
});
md.block.ruler.before('heading', 'toc', toc, {
alt: [ 'paragraph', 'reference', 'blockquote' ]
});
}
export default tocPlugin;