build: unify doc loader & md loader

This commit is contained in:
07akioni 2021-04-05 14:38:39 +08:00
parent 321aa08b23
commit 257233398d
7 changed files with 155 additions and 247 deletions

View File

@ -25,7 +25,7 @@
## 2.3.0
## Breaking Changes
### Breaking Changes
- Collapsing won't work for `n-layout-sider` with `position="absolute"`.
- For `n-layout` contains `n-layout-sider` as a direct child `has-sider` must be set.
@ -78,7 +78,7 @@
## 2.1.0
## Breaking Changes
### Breaking Changes
- `n-popover` default `duration` is set to `100`.
- `n-popover` default `delay` is set to `100`.

View File

@ -25,7 +25,7 @@
## 2.3.0
## Breaking Changes
### Breaking Changes
- 折叠对于 `position="absolute"``n-layout-sider` 不再生效
- 对于包含 `n-layout-sider``n-layout` 必须设定 `has-sider`
@ -78,7 +78,7 @@
## 2.1.0
## Breaking Changes
### Breaking Changes
- `n-popover` 默认 `duration` 设为 `100`
- `n-popover` 默认 `delay` 设为 `100`

View File

@ -1,96 +1,123 @@
const path = require('path')
const fse = require('fs-extra')
const marked = require('marked')
const camelCase = require('lodash/camelCase')
const mdLoader = require('./naive-ui-md-loader')
const createRenderer = require('./md-renderer')
const projectPath = require('./project-path')
const mdRenderer = createRenderer()
function template (demos, demosLiteral, isSingleColumn = false) {
// return `<component-demos :single-column="${isSingleColumn}">
// ${demos}
// <template #anchor>
// ${parseDemosAsAnchor(demosLiteral)}
// </template>
// </component-demos>`
return `<component-demos :single-column="${isSingleColumn}">
${demos}
</component-demos>`
async function resolveDemoTitle (fileName, demoEntryPath) {
const demoStr = await fse.readFile(
path.resolve(projectPath, demoEntryPath, '..', fileName),
'utf-8'
)
return demoStr.match(/# ([^\n]+)/)[1]
}
function parseDemos (demosLiteral, env) {
const demoFileNames = demosLiteral
async function resolveDemoInfos (literal, url, env) {
const ids = literal
.split('\n')
.map((demoFileName) => demoFileName.trim())
.filter((demoFileName) => {
if (env === 'production') {
return (
demoFileName.length &&
demoFileName.indexOf('debug') < 0 &&
demoFileName.indexOf('Debug') < 0
)
}
return demoFileName.length
.map((line) => line.trim())
.filter((id) => id.length)
const infos = []
for (const id of ids) {
if (
env === 'production' &&
(id.includes('debug') || id.includes('Debug'))
) {
continue
}
const fileName = `${id}.demo.md`
const variable = `${camelCase(id)}Demo`
infos.push({
id,
variable,
fileName,
title: await resolveDemoTitle(fileName, url),
tag: `<${variable} />`
})
const demoTags = demoFileNames.map(
(demoFileName) =>
`<${demoFileName}Demo id="${demoFileName}" demo-id="${demoFileName}"/>`
)
return demoTags.join('\n')
}
return infos
}
function parseDemosAsAnchor (demosLiteral) {
const demoFileNames = demosLiteral
.split('\n')
.map((demoFileName) => demoFileName.trim())
.filter((demoFileName) => demoFileName.length)
const linkTags = demoFileNames.map(
(demoFileName) =>
`
<n-anchor-link
v-if="anchorLinkMap.has('${demoFileName}')"
:title="anchorLinkMap.get('${demoFileName}')"
href="#${demoFileName}"
/>`
)
return `<n-anchor :top="32" :bound="16" position="absolute" affix style="width: 144px;">${linkTags.join(
'\n'
)}</n-anchor>`
function genDemosTemplate (demoInfos, colSpan) {
return `<component-demos :span="${colSpan}">${demoInfos
.map(({ tag }) => tag)
.join('\n')}</component-demos>`
}
function generateScript (demosLiteral, components = [], url) {
const demoFileNames = demosLiteral
.split('\n')
.map((demoFileName) => demoFileName.trim())
.filter((demoFileName) => demoFileName.length)
const importStatements = demoFileNames
.map(
(demoFileName) =>
`import ${camelCase(demoFileName)}Demo from './${demoFileName}.demo.md'`
)
function genAnchorTemplate (children, options = {}) {
return `<n-anchor :top="32" :bound="16" position="absolute" affix style="width: 144px;" :ignore-gap="${options.ignoreGap}">${children}</n-anchor>`
}
function genDemosAnchorTemplate (demoInfos) {
const links = demoInfos.map(
({ id, title }) => `<n-anchor-link
v-if="true"
title="${title}"
href="#${id}"
/>`
)
return genAnchorTemplate(links.join('\n'))
}
function genPageAnchorTemplate (tokens) {
const titles = tokens
.filter((token) => token.type === 'heading' && token.depth === 2)
.map((token) => token.text)
const links = titles.map((title) => {
const href = title.replace(/ /g, '-')
return `<n-anchor-link title="${title}" href="#${href}"/>`
})
return genAnchorTemplate(links.join('\n'), { ignoreGap: true })
}
function genScript (demoInfos, components = [], url, forceShowAnchor) {
const showAnchor = !!(demoInfos.length || forceShowAnchor)
const importStmts = demoInfos
.map(({ variable, fileName }) => `import ${variable} from './${fileName}'`)
.concat(
components.map(
(component) => `import ${camelCase(component)} from './${component}'`
)
)
.join('\n')
const componentStatements = demoFileNames
.map((demoFileName) => camelCase(demoFileName) + 'Demo')
const componentStmts = demoInfos
.map(({ variable }) => variable)
.concat(components)
.join(', ')
.join(',\n')
const script = `<script>
${importStatements}
${importStmts}
import { computed } from 'vue'
import { useBreakpoint, useMemo } from 'vooks'
export default {
components: {
${componentStatements}
${componentStmts}
},
provide () {
setup () {
const breakpointRef = useBreakpoint()
const isMobileRef = useMemo(() => {
return breakpointRef.value === 'xs'
})
const showAnchorRef = computed(() => {
if (isMobileRef.value) {
return false
}
return ${showAnchor}
})
return {
NDocumentation: this
}
},
data () {
return {
anchorLinkMap: new Map(),
showAnchor: showAnchorRef,
wrapperStyle: computed(() => {
return !isMobileRef.value
? 'display: flex; flex-wrap: nowrap; padding: 32px 24px 24px 56px;'
: 'padding: 16px;'
}),
contentStyle: computed(() => {
return !isMobileRef.value
? 'width: calc(100% - 180px); margin-right: 36px;'
: 'width: 100%';
}),
url: ${JSON.stringify(url)}
}
}
@ -99,13 +126,15 @@ export default {
return script
}
function convertMd2ComponentDocumentation (text, env = 'development', url) {
const isNoDemo = !!~text.search('<!--no-demo-->')
if (isNoDemo) {
return mdLoader(text, url)
}
const isSingleColumn = !!~text.search('<!--single-column-->')
async function convertMd2ComponentDocumentation (
text,
url,
env = 'development'
) {
const forceShowAnchor = !!~text.search('<!--anchor:on-->')
const colSpan = ~text.search('<!--single-column-->') ? 1 : 2
const tokens = marked.lexer(text)
// resolve external components
const componentsIndex = tokens.findIndex(
(token) => token.type === 'code' && token.lang === 'component'
)
@ -118,97 +147,57 @@ function convertMd2ComponentDocumentation (text, env = 'development', url) {
.filter((component) => component.length)
tokens.splice(componentsIndex, 1)
}
const demosIndex = tokens.findIndex(
(token) => token.type === 'code' && token.lang === 'demo'
)
let demos = { text: '' }
let demosLiteral = ''
let headerPart = tokens
let footerPart = []
// console.log(tokens)
if (~demosIndex) {
headerPart = tokens.slice(0, demosIndex)
footerPart = tokens.slice(demosIndex + 1)
demos = tokens[demosIndex]
demosLiteral = demos.text
tokens.splice(demosIndex, 1, {
type: 'html',
pre: false,
text: '<!--demos-->\n'
})
}
headerPart.links = {}
footerPart.links = {}
const documentationHTML =
`${marked.parser(headerPart, {
gfm: true,
renderer: mdRenderer
})}\n` +
'<!--demos-->\n' +
`${marked.parser(footerPart, {
gfm: true,
renderer: mdRenderer
})}\n`
// console.log(documentationHTML)
// const classedDocumentationHTML = addClassToHTML(documentationHTML, 'markdown')
const demosReg = /<!--demos-->/
const demoTags = parseDemos(demosLiteral, env)
let documentationContent = documentationHTML.replace(
demosReg,
template(demoTags, demosLiteral, isSingleColumn)
)
// add edit on github button on title
const titleIndex = tokens.findIndex(
(token) => token.type === 'heading' && token.depth === 1
)
if (titleIndex > -1) {
const titleText = JSON.stringify(tokens[titleIndex].text)
const githubButton = `<edit-on-github-header relative-url="${url}" text=${titleText}></edit-on-github-header>`
const titleReg = /(<n-h1[^>]*>)(.*?)(<\/n-h1>)/
documentationContent = documentationContent.replace(
titleReg,
`${githubButton}`
)
const btnTemplate = `<edit-on-github-header relative-url="${url}" text=${titleText}></edit-on-github-header>`
tokens.splice(titleIndex, 1, {
type: 'html',
pre: false,
text: btnTemplate
})
}
const documentationTemplate = `
// resolve demos, debug demos are removed from production build
const demosIndex = tokens.findIndex(
(token) => token.type === 'code' && token.lang === 'demo'
)
let demoInfos = []
if (~demosIndex) {
demoInfos = await resolveDemoInfos(tokens[demosIndex].text, url, env)
tokens.splice(demosIndex, 1, {
type: 'html',
pre: false,
text: genDemosTemplate(demoInfos, colSpan)
})
}
const docMainTemplate = marked.parser(tokens, {
gfm: true,
renderer: mdRenderer
})
// generate page
const docTemplate = `
<template>
<component-documentation>
<div style="display: flex; flex-wrap: nowrap;">
<div style="width: calc(100% - 180px); margin-right: 36px;">
${documentationContent}
</div>
<div style="width: 144px;">
${parseDemosAsAnchor(demosLiteral)}
</div>
<div
class="n-documentation"
:style="wrapperStyle"
>
<div :style="contentStyle">
${docMainTemplate}
</div>
</component-documentation>
<div style="width: 144px;" v-if="showAnchor">
${
demoInfos.length
? genDemosAnchorTemplate(demoInfos)
: genPageAnchorTemplate(tokens)
}
</div>
</div>
</template>`
const documentationScript = generateScript(demosLiteral, components, url)
// if (components.length) console.log(`${documentationTemplate}\n\n${documentationScript}`)
return `${documentationTemplate}\n\n${documentationScript}`
// console.log(vueComponent)
// return vueComponent
// console.log(marked.parser(tokens))
// const parts = getPartsOfDemo(tokens)
// const mergedParts = mergeParts(parts)
// const vueComponent = genVueComponent(mergedParts)
// console.log(vueComponent)
// return vueComponent
const docScript = await genScript(demoInfos, components, url, forceShowAnchor)
return `${docTemplate}\n\n${docScript}`
}
// function addClassToHTML (html, className) {
// const classReg = /<[^!/][^>]*>/g
// return html.replace(classReg, (openTag) => {
// return openTag.replace(/>/, ` class="${className}">`)
// })
// }
module.exports = convertMd2ComponentDocumentation
// const startTime = new Date()
// for (let i = 0; i < 100; ++i) {
// const fs = require('fs')
// const md = fs.readFileSync('./marked/component.md').toString()
// console.log(convertMd2ComponentDocumentation(md))
// }
// const endTime = new Date()
// console.log(endTime - startTime)

View File

@ -7,12 +7,13 @@ function createRenderer (wrapCodeWithCard = true) {
table (header, body) {
if (body) body = '<tbody class="n-table__tbody">' + body + '</tbody>'
return (
'<n-table single-column class="md-table">\n' +
'<div class="md-table-wrapper"><n-table single-column class="md-table">\n' +
'<thead class="n-table__thead">\n' +
header +
'</thead>\n' +
body +
'</n-table>\n'
'</n-table>\n' +
'</div>'
)
},

View File

@ -1,8 +1,8 @@
const convertMd2Doc = require('./convert-md-to-doc')
const projectPath = require('./project-path')
module.exports = function (content, path) {
module.exports = async function (content, path) {
const env = process.env.NODE_ENV
const relativeUrl = path.replace(projectPath + '/', '')
return convertMd2Doc(content, env, relativeUrl)
return convertMd2Doc(content, relativeUrl, env)
}

View File

@ -1,78 +0,0 @@
const marked = require('marked')
const createRenderer = require('./md-renderer')
const renderer = createRenderer()
const projectPath = require('./project-path')
function parseMdAsAnchor (tokens) {
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}"/>`
})
return `<n-anchor ignore-gap :top="32" position="absolute" affix style="width: 144px;">${linkTags.join(
'\n'
)}</n-anchor>`
}
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
}
module.exports = function (content, path) {
const relativeURL = path.replace(projectPath + '/', '')
const showAnchor = !!~content.search('<!--anchor:on-->')
// for marked bug https://github.com/markedjs/marked/issues/1047
content = content.replace(/\n#/g, '\n\n#')
const tokens = marked.lexer(content)
const titleIndex = tokens.findIndex(
(token) => token.type === 'heading' && token.depth === 1
)
const titleText =
titleIndex > -1 ? JSON.stringify(tokens[titleIndex].text) : null
const anchor = parseMdAsAnchor(tokens)
const components = parseComponents(tokens)
const importStatements = components
.map((component) => `import ${component} from './${component}'`)
.join('\n')
let mdContent = marked.parser(tokens, { renderer })
if (titleText) {
const githubButton = `<edit-on-github-header relative-url="${relativeURL}" text=${titleText}></edit-on-github-header>`
const titleReg = /(<n-h1[^>]*>)(.*?)(<\/n-h1>)/
mdContent = mdContent.replace(titleReg, `${githubButton}`)
}
return `
<template>
<component-documentation>
<div style="display: flex; flex-wrap: nowrap;">
<div style="width: calc(100% - 180px); margin-right: 36px;">
${mdContent}
</div>
${showAnchor ? `<div style="width: 144px;">${anchor}</div>` : ''}
</div>
</component-documentation>
</template>
<script>
${importStatements}
export default {
components: {
${components.join(',\n')}
}
}
</script>`
}

View File

@ -1,18 +1,14 @@
const fs = require('fs').promises
const fs = require('fs-extra')
const demoLoader = require('../loaders/naive-ui-demo-loader')
const docLoader = require('../loaders/naive-ui-doc-loader')
const mdLoader = require('../loaders/naive-ui-md-loader')
module.exports = async function getTransformedVueSrc (path) {
if (path.endsWith('.demo.md')) {
const code = await fs.readFile(path, 'utf-8')
return demoLoader(code, path)
} else if (path.endsWith('.demo-entry.md')) {
const code = await fs.readFile(path, 'utf-8')
return docLoader(code, path)
} else if (path.endsWith('.md')) {
const code = await fs.readFile(path, 'utf-8')
return mdLoader(code, path)
return docLoader(code, path)
}
}