nifty-wallet/ui/lib/icon-factory.js

54 lines
1.4 KiB
JavaScript
Raw Normal View History

var iconFactory
2016-06-21 13:18:32 -07:00
module.exports = function (jazzicon) {
if (!iconFactory) {
iconFactory = new IconFactory(jazzicon)
}
return iconFactory
}
2016-06-21 13:18:32 -07:00
function IconFactory (jazzicon) {
this.jazzicon = jazzicon
this.cache = {}
}
2016-06-21 13:18:32 -07:00
IconFactory.prototype.iconForAddress = function (address, diameter) {
if (this.isCached(address, diameter)) {
return this.cache[address][diameter]
}
const dataUri = this.generateNewUri(address, diameter)
this.cacheIcon(address, diameter, dataUri)
return dataUri
}
2016-06-21 13:18:32 -07:00
IconFactory.prototype.generateNewUri = function (address, diameter) {
var numericRepresentation = jsNumberForAddress(address)
var identicon = this.jazzicon(diameter, numericRepresentation)
var identiconSrc = identicon.innerHTML
2016-06-21 13:18:32 -07:00
var dataUri = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(identiconSrc)
return dataUri
}
2016-06-21 13:18:32 -07:00
IconFactory.prototype.cacheIcon = function (address, diameter, icon) {
if (!(address in this.cache)) {
var sizeCache = {}
sizeCache[diameter] = icon
2016-06-21 13:56:04 -07:00
this.cache[address] = sizeCache
return sizeCache
} else {
2016-06-21 13:56:04 -07:00
this.cache[address][diameter] = icon
return icon
}
}
2016-06-21 13:18:32 -07:00
IconFactory.prototype.isCached = function (address, diameter) {
return address in this.cache && diameter in this.cache[address]
}
2016-06-21 13:18:32 -07:00
function jsNumberForAddress (address) {
var addr = address.slice(2, 10)
var seed = parseInt(addr, 16)
return seed
}