createSidebar.js 2.1 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

D
DCloud_LXH 已提交
10
function parseBar(tab, file, options) {
D
DCloud_LXH 已提交
11 12 13 14 15
  const textName = options.text || 'text'
  const linkName = options.link || 'link'
  const contents = []

  new MarkdownIt()
D
DCloud_LXH 已提交
16
    .parse(fs.readFileSync(file, { encoding: 'utf-8' }).replace(/<!--([\s\S]*?)-->/g, ""))
D
DCloud_LXH 已提交
17 18
    .forEach(token => {
      if (token.type === 'inline') {
19 20 21 22 23 24
        let text
        let link
        let config = {}
        token.children.forEach(child => {
          switch (child.type) {
            case 'text':
D
DCloud_LXH 已提交
25
              text = text || child.content
26 27
              break;
            case 'link_open':
D
DCloud_LXH 已提交
28
              link = link || new Map(child.attrs).get('href')
29 30 31 32 33 34 35 36 37 38 39
              break;
            case 'code_inline':
              try {
                config = JSON.parse(child.content)
              } catch (error) { }
              break;

            default:
              break;
          }
        })
D
DCloud_LXH 已提交
40

D
DCloud_LXH 已提交
41
        if (link && !isExternal(link)) {
D
DCloud_LXH 已提交
42 43 44 45 46 47 48
          if (!link.startsWith('/')) {
            const linkFirstItem = link.split('/')[0]
            if (tab.indexOf(linkFirstItem) === -1) {
              link = `${tab}${link}`
            }
          }

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

D
DCloud_LXH 已提交
55
          links.push(link)
D
DCloud_LXH 已提交
56
        }
D
DCloud_LXH 已提交
57 58 59 60 61 62 63

        contents.push({
          level: token.level,
          [textName]: text,
          [linkName]: link,
          ...config
        })
D
DCloud_LXH 已提交
64 65 66 67 68 69 70 71
      }
    })

  return createMarkdownArray(contents, options.children)
}

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

D
DCloud_LXH 已提交
73
  tabs.forEach(tab => {
D
DCloud_LXH 已提交
74
    sidebar[tab] = parseBar(tab, path.join(__dirname, '../../', tab, '_sidebar.md'), {
D
DCloud_LXH 已提交
75 76 77 78
      text: 'title',
      link: 'path'
    })
  })
D
DCloud_LXH 已提交
79 80 81

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

D
DCloud_LXH 已提交
82 83
  return tabs.length ? sidebar : false
}