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