forked from commonform/commonform-markup-parse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
extract-directions.js
54 lines (52 loc) · 1.49 KB
/
extract-directions.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
// Given the AST produced by the parser, replace all blanks with
// `{blank:''}` and create directions that link blank identifiers to
// paths within the form.
module.exports = function (syntaxTree) {
return recurse(syntaxTree, [], [])
}
// Recurse the AST.
function recurse (syntaxTree, directions, path) {
var newContent = []
syntaxTree.content.forEach(function (element, index) {
var elementIsObject = typeof element === 'object'
var elementIsBlank = (
elementIsObject &&
element.hasOwnProperty('blank')
)
if (elementIsBlank) {
var identifier = element.blank
newContent.push(createBlank())
directions.push({
identifier: identifier,
path: path.concat('content', index)
})
} else {
var elementIsChild = (
elementIsObject &&
element.hasOwnProperty('form')
)
if (elementIsChild) {
var childPath = path.concat('content', index, 'form')
var result = recurse(element.form, directions, childPath)
var newChild = {form: result.form}
if (element.hasOwnProperty('heading')) {
newChild.heading = element.heading
}
newContent.push(newChild)
} else {
newContent.push(element)
}
}
})
var newForm = {content: newContent}
if (syntaxTree.hasOwnProperty('conspicuous')) {
newForm.conspicuous = syntaxTree.conspicuous
}
return {
form: newForm,
directions: directions
}
}
function createBlank () {
return {blank: ''}
}