browser.js
2.27 KB
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
var parseAttributes = require('./parse-attribs')
var parseFromString = require('xml-parse-from-string')
//In some cases element.attribute.nodeName can return
//all lowercase values.. so we need to map them to the correct
//case
var NAME_MAP = {
scaleh: 'scaleH',
scalew: 'scaleW',
stretchh: 'stretchH',
lineheight: 'lineHeight',
alphachnl: 'alphaChnl',
redchnl: 'redChnl',
greenchnl: 'greenChnl',
bluechnl: 'blueChnl'
}
module.exports = function parse(data) {
data = data.toString()
var xmlRoot = parseFromString(data)
var output = {
pages: [],
chars: [],
kernings: []
}
//get config settings
;['info', 'common'].forEach(function(key) {
var element = xmlRoot.getElementsByTagName(key)[0]
if (element)
output[key] = parseAttributes(getAttribs(element))
})
//get page info
var pageRoot = xmlRoot.getElementsByTagName('pages')[0]
if (!pageRoot)
throw new Error('malformed file -- no <pages> element')
var pages = pageRoot.getElementsByTagName('page')
for (var i=0; i<pages.length; i++) {
var p = pages[i]
var id = parseInt(p.getAttribute('id'), 10)
var file = p.getAttribute('file')
if (isNaN(id))
throw new Error('malformed file -- page "id" attribute is NaN')
if (!file)
throw new Error('malformed file -- needs page "file" attribute')
output.pages[parseInt(id, 10)] = file
}
//get kernings / chars
;['chars', 'kernings'].forEach(function(key) {
var element = xmlRoot.getElementsByTagName(key)[0]
if (!element)
return
var childTag = key.substring(0, key.length-1)
var children = element.getElementsByTagName(childTag)
for (var i=0; i<children.length; i++) {
var child = children[i]
output[key].push(parseAttributes(getAttribs(child)))
}
})
return output
}
function getAttribs(element) {
var attribs = getAttribList(element)
return attribs.reduce(function(dict, attrib) {
var key = mapName(attrib.nodeName)
dict[key] = attrib.nodeValue
return dict
}, {})
}
function getAttribList(element) {
//IE8+ and modern browsers
var attribs = []
for (var i=0; i<element.attributes.length; i++)
attribs.push(element.attributes[i])
return attribs
}
function mapName(nodeName) {
return NAME_MAP[nodeName.toLowerCase()] || nodeName
}