naive-ui/demo/loaders/NaiveUIMdLoader.js

56 lines
1.7 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-02-28 20:31:06 +08:00
return `<n-anchor ignore-gap :top="24" 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
}
2019-10-10 22:38:29 +08:00
module.exports = function (content) {
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')
2019-12-22 15:31:04 +08:00
return `<template>
<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-02-13 19:14:30 +08:00
${marked.parser(tokens, {
2019-12-23 21:40:45 +08:00
renderer
})}
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}
export default {
components: {
${components.join(',\n')}
}
}
</script>`
2019-10-10 22:38:29 +08:00
}