feat(markdown): Add table of contents support for Markdown mode (#645) · documentationjs/documentation@4c66fb1

11

var u = require('unist-builder'),

2+

remark = require('remark'),

3+

toc = require('remark-toc'),

24

hljs = require('highlight.js'),

35

GithubSlugger = require('github-slugger'),

46

createLinkerStack = require('./util/linker_stack'),

@@ -14,7 +16,7 @@ var u = require('unist-builder'),

1416

* @param {Function} callback called with AST

1517

* @returns {undefined} calls callback

1618

*/

17-

function commentsToAST(comments, options, callback) {

19+

function markdownAST(comments, options, callback) {

18201921

// Configure code highlighting

2022

var hljsOptions = (options || {}).hljs || {},

@@ -33,6 +35,10 @@ function commentsToAST(comments, options, callback) {

3335

u('html', '<!-- Generated by documentation.js. Update this documentation by updating the source code. -->')

3436

];

353738+

var tableOfContentsHeading = [

39+

u('heading', { depth: 3 }, [u('text', 'Table of Contents')])

40+

];

41+3642

/**

3743

* Generate an AST chunk for a comment at a given depth: this is

3844

* split from the main function to handle hierarchially nested comments

@@ -202,10 +208,20 @@ function commentsToAST(comments, options, callback) {

202208

.filter(Boolean);

203209

}

204210205-

return callback(null, rerouteLinks(linkerStack.link,

206-

u('root', generatorComment.concat(comments.reduce(function (memo, comment) {

207-

return memo.concat(generate(2, comment));

208-

}, [])))));

211+

var root = rerouteLinks(linkerStack.link,

212+

u('root', generatorComment

213+

.concat(options['no-markdown-toc'] ? [] : tableOfContentsHeading)

214+

.concat(comments.reduce(function (memo, comment) {

215+

return memo.concat(generate(2, comment));

216+

}, []))));

217+218+

if (!options['no-markdown-toc']) {

219+

return remark().use(toc, {

220+

tight: true

221+

}).run(root, callback);

222+

}

223+224+

return callback(null, root);

209225

}

210226211-

module.exports = commentsToAST;

227+

module.exports = markdownAST;