thedesk/app/node_modules/parse-bmfont-xml/lib/browser.js

85 lines
2.3 KiB
JavaScript
Raw Permalink Normal View History

2019-09-13 00:38:13 +10:00
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
}