1
1
mirror of https://github.com/primer/css.git synced 2024-12-25 07:03:35 +03:00
css/.storybook/lib/storiesFromMarkdown.js

46 lines
1.3 KiB
JavaScript
Raw Normal View History

2017-09-13 02:43:34 +03:00
import remark from 'remark'
import parents from 'unist-util-parents'
2017-09-13 02:43:34 +03:00
import select from 'unist-util-select'
import findBefore from 'unist-util-find-before'
2017-09-13 02:43:34 +03:00
import htmlToReact from 'html-to-react'
import parsePairs from 'parse-pairs'
const htmlParser = new htmlToReact.Parser()
const nodeToStory = (node, file) => {
const html = node.value
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 {
title,
story: () => element,
attrs,
html,
file,
node,
}
}
2017-09-13 02:43:34 +03:00
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")
)
}, [])
2017-09-13 02:43:34 +03:00
}