mirror of
https://github.com/primer/css.git
synced 2024-11-14 03:54:54 +03:00
parse titles from nearest heading or fence lang
This commit is contained in:
parent
85ca818998
commit
1b6c2bdc9b
@ -1,16 +1,60 @@
|
|||||||
import remark from 'remark'
|
import remark from 'remark'
|
||||||
|
import visit from 'unist-util-visit'
|
||||||
import select from 'unist-util-select'
|
import select from 'unist-util-select'
|
||||||
import htmlToReact from 'html-to-react'
|
import htmlToReact from 'html-to-react'
|
||||||
|
import {createParser} 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 html = node.value
|
||||||
|
const pairs = node.lang.replace(/^html\s+/, '')
|
||||||
|
const data = pairs ? parsePairs(pairs) : {}
|
||||||
|
const title = data.title || heading || `story #${index} (${file})`
|
||||||
|
return {
|
||||||
|
story: htmlParser.parse(html),
|
||||||
|
title,
|
||||||
|
html,
|
||||||
|
file,
|
||||||
|
node,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export default req => {
|
export default req => {
|
||||||
const parser = new htmlToReact.Parser()
|
|
||||||
return req.keys()
|
return req.keys()
|
||||||
.reduce((stories, file) => {
|
.reduce((stories, file) => {
|
||||||
const content = req(file)
|
const content = req(file)
|
||||||
const ast = remark.parse(content)
|
const ast = remark.parse(content)
|
||||||
return stories.concat(
|
let heading
|
||||||
select(ast, 'code[lang^=html]')
|
|
||||||
.map(node => parser.parse(node.value))
|
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
|
||||||
}, [])
|
}, [])
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user