-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
format.b
50 lines (45 loc) · 1.13 KB
/
format.b
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
#!-- part of the html module
import iters
def split_head(str, sep) {
var idx = str.index_of(sep)
if idx == -1 return [str]
return [str[0, idx], str[idx + sep.length(),]]
}
def unquote(str) {
var car = str[0]
var end = str.length() - 1
var is_quote_start = car == '"' or car == "'"
if is_quote_start and car == str[end] {
return str[1, end]
}
return str
}
def format(nodes, options) {
return iters.map(nodes, @( node ) {
var type = node.type
var output_node = type == 'element' ? {
type,
name: node.name,
attributes: format_attributes(node.attributes),
children: format(node.children, options),
} : {
type,
content: node.content,
}
if options.get('with_position', false) {
output_node.position = node.position
}
return output_node
})
}
def format_attributes(attributes) {
return iters.map(attributes, @( attribute ) {
var parts = split_head(attribute.trim(), '=')
var name = parts[0]
var value
if parts.length() > 1 {
value = is_string(parts[1]) ? unquote(parts[1]) : nil
}
return {name, value}
})
}