-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
index.js
131 lines (111 loc) · 2.69 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import unified from "unified"
import remarkMdx from "remark-mdx"
import remarkMdxjs from "remark-mdxjs"
import remarkParse from "remark-parse"
import remarkStringify from "remark-stringify"
import visit from "unist-util-visit"
import remove from "unist-util-remove"
import transformMdx from "../transform-recipe-mdx"
import { uuid } from "./util"
const IGNORED_COMPONENTS = [`RecipeIntroduction`, `RecipeStep`]
const asRoot = node => {
return {
type: `root`,
children: [node],
}
}
const pluckExports = tree => {
const exports = []
visit(tree, `export`, node => {
exports.push(node)
})
remove(tree, `export`)
return exports
}
const applyUuid = tree => {
visit(tree, `mdxBlockElement`, node => {
if (!IGNORED_COMPONENTS.includes(node.name)) {
node.attributes.push({
type: `mdxAttribute`,
name: `_uuid`,
value: uuid(),
})
node.attributes.push({
type: `mdxAttribute`,
name: `_type`,
value: node.name,
})
}
})
return tree
}
const u = unified()
.use(remarkParse)
.use(remarkStringify)
.use(remarkMdx)
.use(remarkMdxjs)
const partitionSteps = ast => {
const steps = []
let index = 0
ast.children.forEach(node => {
if (node.type === `thematicBreak`) {
index++
return undefined
}
steps[index] = steps[index] || []
steps[index].push(node)
return undefined
})
return steps
}
const toMdx = nodes => {
const stepAst = applyUuid(asRoot(nodes))
const mdxSrc = u.stringify(stepAst)
return mdxSrc
}
const parse = async src => {
const ast = u.parse(src)
const exportNodes = pluckExports(ast)
const [intro, ...resourceSteps] = partitionSteps(ast)
const wrappedIntroStep = {
type: `mdxBlockElement`,
name: `RecipeIntroduction`,
attributes: [],
children: intro,
}
const wrappedResourceSteps = resourceSteps.map((step, i) => {
return {
type: `mdxBlockElement`,
name: `RecipeStep`,
attributes: [
{
type: `mdxAttribute`,
name: `step`,
value: String(i + 1),
},
{
type: `mdxAttribute`,
name: `totalSteps`,
value: String(resourceSteps.length),
},
],
children: step,
}
})
const steps = [wrappedIntroStep, ...wrappedResourceSteps]
ast.children = [...exportNodes, ...ast.children]
const exportsAsMdx = exportNodes.map(toMdx)
const stepsAsMdx = steps.map(toMdx)
const stepsAsJS = stepsAsMdx.map(transformMdx)
return {
ast,
steps,
exports: exportNodes,
exportsAsMdx,
stepsAsMdx,
stepsAsJS,
recipe: exportsAsMdx.join(`\n`) + `\n\n` + stepsAsMdx.join(`\n`),
}
}
export default parse
export { parse, u }