diff --git a/src/lib/generate-jdenticon.js b/src/lib/generate-jdenticon.js new file mode 100644 index 0000000..101f1d6 --- /dev/null +++ b/src/lib/generate-jdenticon.js @@ -0,0 +1,49 @@ +"use strict"; + +const jdenticon = require("jdenticon"); +const defaultValue = require("default-value"); + +module.exports = function generateJdenticon(name) { + function setConfig() { + /* NOTE: This is a hack to ensure that any other code using the `jdenticon` library can't mess with our config, since it's set globally. This function gets called prior to *every* jdenticon-generating operation. */ + jdenticon.config = { + lightness: { + color: [0.58, 0.66], + grayscale: [0.30, 0.90] + }, + saturation: { + color: 0.66, + grayscale: 0.00 + }, + backColor: "#00000000" + }; + } + + return { + toSvg: function (size) { + setConfig(); + + return jdenticon.toSvg(name, size); + }, + primaryColor: function () { + let svg = this.toSvg(); + + let color = svg.match(/#([a-f0-9]{6})/g).find((candidate) => { + let r = candidate.substr(1, 2); + let g = candidate.substr(3, 2); + let b = candidate.substr(5, 2); + + let isGrayScale = (r === g && g === b); + + return !isGrayScale; + }); + + return defaultValue(color, "#ff0000"); + }, + update: function (element) { + setConfig(); + + jdenticon.update(element, name); + } + } +};