createSidebar.js 2.1 KB
Newer Older
D
DCloud_LXH 已提交
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
const fs = require('fs')
const path = require('path')
const MarkdownIt = require('markdown-it');
const createMarkdownArray = require('./createMarkdownArray')
const { isExternal } = require('../utils')
const createSiteMap = require('./createSiteMap');

const links = []

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

  new MarkdownIt()
    .parse(fs.readFileSync(file, { encoding: 'utf-8' }).replace(/<!--([\s\S]*?)-->/g, ""))
    .forEach(token => {
      if (token.type === 'inline') {
        let text
        let link
        let config = {}
        token.children.forEach(child => {
          switch (child.type) {
            case 'text':
              text = text || child.content
              break;
            case 'link_open':
              link = link || new Map(child.attrs).get('href')
              break;
            case 'code_inline':
              try {
                config = JSON.parse(child.content)
              } catch (error) { }
              break;

            default:
              break;
          }
        })

        if (link && !isExternal(link)) {
          if (!link.startsWith('/')) {
            const linkFirstItem = link.split('/')[0]
            if (tab.indexOf(linkFirstItem) === -1) {
              link = path.join(tab, link).replace(/\\/g, '/')
            }
          }

D
DCloud_LXH 已提交
49 50 51 52 53
          link = path.join('/', link.replace(/\.md\b/, '')
            .replace(/\bREADME\b/, '')
            .replace(/\/index/, '/')
            .replace(/\?id=/, '#'))
            .replace(/\\/g, '/')
D
DCloud_LXH 已提交
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

          links.push(link)
        }

        contents.push({
          level: token.level,
          [textName]: text,
          [linkName]: link,
          ...config
        })
      }
    })

  return createMarkdownArray(contents, options.children)
}

module.exports = function (tabs = []) {
  const sidebar = {}

  tabs.forEach(tab => {
    sidebar[tab] = parseBar(tab, path.join(__dirname, '../../', tab, '_sidebar.md'), {
      text: 'title',
      link: 'path'
    })
  })

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

  return tabs.length ? sidebar : false
}