Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
refactor and clean up .md story loading
  • Loading branch information
shawnbot committed Sep 13, 2017
commit 310d7839a073a340700778794e65f6ca2e09503b
70 changes: 28 additions & 42 deletions .storybook/lib/storiesFromMarkdown.js
Original file line number Diff line number Diff line change
@@ -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
}
})
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
}

return stories
}, [])
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")
)
}, [])
}