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 ``
})
return `${linkTags.join(
'\n'
)}`
}
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('')
// 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 = ``
const titleReg = /(]*>)(.*?)(<\/n-h1>)/
mdContent = mdContent.replace(titleReg, `${githubButton}`)
}
return `
${mdContent}
${showAnchor ? `
${anchor}
` : ''}
`
}