createSidebar.js 1.4 KB
Newer Older
D
DCloud_LXH 已提交
1 2 3 4 5
const fs = require('fs')
const path = require('path')
const MarkdownIt = require('markdown-it');
const createMarkdownArray = require('./createMarkdownArray')
const { isExternal } = require('../utils')
D
DCloud_LXH 已提交
6 7 8
const createSiteMap = require('./createSiteMap');

const links = []
D
DCloud_LXH 已提交
9 10 11 12 13 14 15 16 17 18 19

function parseBar(file, options) {
  const textName = options.text || 'text'
  const linkName = options.link || 'link'
  const contents = []

  new MarkdownIt()
    .parse(fs.readFileSync(file, { encoding: 'utf-8' }))
    .forEach(token => {
      if (token.type === 'inline') {
        let [_, text, link] = token.content.match(/\[(.+?)\]\((.+?)\)/) || token.content.match(/(.+)/)
D
DCloud_LXH 已提交
20 21 22 23 24 25 26 27 28 29 30

        if (link && !isExternal(link)) {
          link = path.join('/', link.replace(/\.md\b/, '')
            .replace(/\bREADME\b/, '')
            .replace(/\/index/, '/')
            .replace(/\?id=/, '#'))
            .replace(/\\/g, '/')

          links.push(link)
        }

D
DCloud_LXH 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43
        contents.push({
          level: token.level,
          [textName]: text,
          [linkName]: link
        })
      }
    })

  return createMarkdownArray(contents, options.children)
}

module.exports = function (tabs = []) {
  const sidebar = {}
D
DCloud_LXH 已提交
44

D
DCloud_LXH 已提交
45 46 47 48 49 50
  tabs.forEach(tab => {
    sidebar[tab] = parseBar(path.join(__dirname, '../../', tab, '_sidebar.md'), {
      text: 'title',
      link: 'path'
    })
  })
D
DCloud_LXH 已提交
51 52 53

  createSiteMap(links, () => links.length = 0)

D
DCloud_LXH 已提交
54 55
  return tabs.length ? sidebar : false
}