1
1
mirror of https://github.com/primer/css.git synced 2024-11-23 20:38:58 +03:00

refactor and clean up .md story loading

This commit is contained in:
Shawn Allen 2017-09-13 00:52:41 -07:00
parent 35ec6ba517
commit 310d7839a0

View File

@ -1,60 +1,46 @@
import remark from 'remark'
import parents from 'unist-util-parents'
import visit from 'unist-util-visit'
import select from 'unist-util-select'
import findBefore from 'unist-util-find-before'
import htmlToReact from 'html-to-react'
import {createParser} from 'parse-pairs'
import parsePairs from 'parse-pairs'
const htmlParser = new htmlToReact.Parser()
const parsePairs = (parse => {
return str => {
try {
return parse(str)
} catch (error) {
return {}
}
}
})(createParser())
const nodeToStory = (node, heading, file, index) => {
const nodeToStory = (node, file) => {
const html = node.value
const pairs = node.lang.replace(/^html\s+/, '')
const data = pairs ? parsePairs(pairs) : {}
const title = data.title || heading || `story #${index} (${file})`
const element = htmlParser.parse(html)
const pairs = node.lang.replace(/^html\s*/, '')
const attrs = pairs.length ? parsePairs(pairs) : {}
const title = attrs.title || getPreviousHeading(node) ||
`story @ ${file}:${node.position.start.line}`
return {
story: htmlParser.parse(html),
title,
story: () => element,
attrs,
html,
file,
node,
}
}
export default req => {
return req.keys()
.reduce((stories, file) => {
const content = req(file)
const ast = remark.parse(content)
let heading
visit(ast, node => {
switch (node.type) {
case 'heading':
heading = node.children
.map(child => child.value)
.join('')
break
case 'code':
if (node.lang && node.lang.match(/^html\b/)) {
stories.push(
nodeToStory(node, heading, file, stories.length + 1)
)
heading = undefined
}
break
}
})
return stories
}, [])
const getPreviousHeading = node => {
const heading = findBefore(node.parent, node, 'heading')
return (heading && !heading.used)
? (heading.used = true, heading.children.map(c => c.value).join(''))
: undefined
}
export default req => {
return req.keys().reduce((stories, file) => {
const content = req(file)
const ast = parents(remark.parse(content))
const path = file.replace(/^\.\//, '')
return stories.concat(
select(ast, 'code[lang^=html]')
.map(node => nodeToStory(node, path))
.filter(({attrs}) => attrs.story !== "false")
)
}, [])
}