naive-ui/demo/loaders/NaiveUIMdLoader.js

79 lines
2.2 KiB
JavaScript
Raw Normal View History

2019-10-10 22:38:29 +08:00
const marked = require('marked')
2019-12-22 23:19:08 +08:00
const createRenderer = require('./mdRenderer')
const renderer = createRenderer()
2019-10-10 22:38:29 +08:00
2020-02-13 19:14:30 +08:00
function parseMdAsAnchor (tokens) {
2019-12-22 15:31:04 +08:00
const titles = tokens.filter(token => token.type === 'heading' && token.depth === 2).map(token => token.text)
const linkTags = titles.map(title => {
const href = title.replace(/ /g, '-')
return `<n-anchor-link title="${title}" href="#${href}"/>`
})
2020-03-05 22:31:20 +08:00
return `<n-anchor ignore-gap :top="32" position="absolute" affix style="width: 144px;">${linkTags.join('\n')}</n-anchor>`
2019-10-10 22:38:29 +08:00
}
2020-02-13 19:14:30 +08:00
function parseComponents (tokens) {
const componentsIndex = tokens.findIndex(token => token.type === 'code' && token.lang === 'component')
let components = []
if (~componentsIndex) {
components = tokens[componentsIndex].text
components = components.split('\n').map(component => component.trim()).filter(component => component.length)
tokens.splice(componentsIndex, 1)
}
return components
}
2020-03-16 13:01:13 +08:00
module.exports = function (content, titleReg, gheUrl, gheButton) {
2020-02-13 19:14:30 +08:00
const tokens = marked.lexer(content)
const anchor = parseMdAsAnchor(tokens)
const components = parseComponents(tokens)
const importStatements = components
.map(component => `import ${component} from './${component}'`)
.join('\n')
2020-03-16 13:01:13 +08:00
const mdContent = marked.parser(tokens, { renderer })
const documentationContent = mdContent.replace(titleReg, `$1$2${gheButton}$3`)
return `<i18n>
{
"zh-CN": {
"editOnGithub": "在 Github 上编辑"
},
"en-US": {
"editOnGithub": "Edit on Github"
}
}
</i18n>
<template>
2019-12-22 15:31:04 +08:00
<component-documentation>
<div style="display: flex; flex-wrap: nowrap;">
2020-02-22 20:25:10 +08:00
<div style="width: calc(100% - 180px); margin-right: 36px;">
2020-03-16 13:01:13 +08:00
${documentationContent}
2019-12-22 15:31:04 +08:00
</div>
2020-02-22 20:25:10 +08:00
<div style="width: 144px;">
2020-02-13 19:14:30 +08:00
${anchor}
2019-12-22 15:31:04 +08:00
</div>
</div>
</component-documentation>
2020-02-13 19:14:30 +08:00
</template>
<script>
${importStatements}
2020-03-16 13:01:13 +08:00
import createOutline from 'naive-ui/lib/icons/create-outline'
2020-02-13 19:14:30 +08:00
export default {
components: {
2020-03-16 13:01:13 +08:00
createOutline,
2020-02-13 19:14:30 +08:00
${components.join(',\n')}
2020-03-16 13:01:13 +08:00
},
data () {
return {
gheUrl: ${JSON.stringify(gheUrl)}
}
},
methods: {
handleEditOnGithubClick () {
window.open(this.gheUrl, '_blank')
2020-03-17 18:54:21 +08:00
return false
2020-03-16 13:01:13 +08:00
},
2020-02-13 19:14:30 +08:00
}
}
</script>`
2019-10-10 22:38:29 +08:00
}