|
| 1 | +// reference: https://github.com/Oktavilla/markdown-it-table-of-contents |
| 2 | + |
| 3 | +const defaults = { |
| 4 | + includeLevel: [2, 3], |
| 5 | + containerClass: 'table-of-contents', |
| 6 | + markerPattern: /^\[\[toc\]\]/im, |
| 7 | + listType: 'ul', |
| 8 | + containerHeaderHtml: '', |
| 9 | + containerFooterHtml: '' |
| 10 | +} |
| 11 | + |
| 12 | +module.exports = (md, options) => { |
| 13 | + options = Object.assign({}, defaults, options) |
| 14 | + const tocRegexp = options.markerPattern |
| 15 | + |
| 16 | + function toc (state, silent) { |
| 17 | + var token |
| 18 | + var match |
| 19 | + |
| 20 | + // Reject if the token does not start with [ |
| 21 | + if (state.src.charCodeAt(state.pos) !== 0x5B /* [ */) { |
| 22 | + return false |
| 23 | + } |
| 24 | + // Don't run any pairs in validation mode |
| 25 | + if (silent) { |
| 26 | + return false |
| 27 | + } |
| 28 | + |
| 29 | + // Detect TOC markdown |
| 30 | + match = tocRegexp.exec(state.src) |
| 31 | + match = !match ? [] : match.filter(function (m) { return m }) |
| 32 | + if (match.length < 1) { |
| 33 | + return false |
| 34 | + } |
| 35 | + |
| 36 | + // Build content |
| 37 | + token = state.push('toc_open', 'toc', 1) |
| 38 | + token.markup = '[[toc]]' |
| 39 | + token = state.push('toc_body', '', 0) |
| 40 | + token = state.push('toc_close', 'toc', -1) |
| 41 | + |
| 42 | + // Update pos so the parser can continue |
| 43 | + var newline = state.src.indexOf('\n') |
| 44 | + if (newline !== -1) { |
| 45 | + state.pos = state.pos + newline |
| 46 | + } else { |
| 47 | + state.pos = state.pos + state.posMax + 1 |
| 48 | + } |
| 49 | + |
| 50 | + return true |
| 51 | + } |
| 52 | + |
| 53 | + md.renderer.rules.toc_open = function () { |
| 54 | + return vBindEscape`<TOC |
| 55 | + :class=${options.containerClass} |
| 56 | + :list-type=${options.listType} |
| 57 | + :include-level=${options.includeLevel} |
| 58 | + >` |
| 59 | + } |
| 60 | + |
| 61 | + md.renderer.rules.toc_body = function () { |
| 62 | + return `<template slot="header">${options.containerHeaderHtml}</template>` |
| 63 | + + `<template slot="footer">${options.containerFooterHtml}</template>` |
| 64 | + } |
| 65 | + |
| 66 | + md.renderer.rules.toc_close = function () { |
| 67 | + return `</TOC>` |
| 68 | + } |
| 69 | + |
| 70 | + // Insert TOC |
| 71 | + md.inline.ruler.after('emphasis', 'toc', toc) |
| 72 | +} |
| 73 | + |
| 74 | +/** escape double quotes in v-bind derivatives */ |
| 75 | +function vBindEscape (strs, ...args) { |
| 76 | + return strs.reduce((prev, curr, index) => { |
| 77 | + return prev + curr + (index >= args.length |
| 78 | + ? '' |
| 79 | + : `"${JSON.stringify(args[index]) |
| 80 | + .replace(/"/g, "'") |
| 81 | + .replace(/([^\\])(\\\\)*\\'/g, (_, char) => char + '\\u0022')}"`) |
| 82 | + }, '') |
| 83 | +} |
0 commit comments