diff --git a/badge.js b/badge.js index 956bde4..1d7cb73 100644 --- a/badge.js +++ b/badge.js @@ -14,7 +14,51 @@ templateFiles.forEach(function(filename) { path.join(__dirname, 'templates', filename)).toString(); var extension = path.extname(filename).slice(1); var style = filename.slice(0, -(('-template.' + extension).length)); + // Compile the template. Necessary to always have a working template. templates[style + '-' + extension] = dot.template(templateData); + if (extension === 'svg') { + // Substitute dot code. + var mapping = new Map(); + var mappingIndex = 1; + var untemplatedSvg = templateData.replace(/{{.*?}}/g, function(match) { + // Weird substitution that currently works for all templates. + var mapKey = '99999990' + mappingIndex + '.1'; + mappingIndex++; + mapping.set(mapKey, match); + return mapKey; + }); + compressSvg(untemplatedSvg, function(object) { + if (object.error !== undefined) { + console.error('Template ' + filename + ': ' + object.error + '\n' + + ' Generated untemplated SVG:\n' + + '---\n' + untemplatedSvg + '---\n'); + return; + } + // Substitute dot code back. + var svg = object.data; + var unmappedKeys = []; + mapping.forEach(function(value, key) { + var keySubstituted = false; + svg = svg.replace(RegExp(key, 'g'), function() { + keySubstituted = true; + return value; + }); + if (!keySubstituted) { + unmappedKeys.push(key); + } + }); + if (unmappedKeys.length > 0) { + console.error('Template ' + filename + ' has unmapped keys ' + + unmappedKeys.join(', ') + '.\n' + + ' Generated untemplated SVG:\n' + + '---\n' + untemplatedSvg + '\n---\n' + + ' Generated template:\n' + + '---\n' + svg + '\n---\n'); + return; + } + templates[style + '-' + extension] = dot.template(svg); + }); + } }); function escapeXml(s) { @@ -34,7 +78,7 @@ function addEscapers(data) { var colorscheme = require(path.join(__dirname, 'colorscheme.json')); -function optimize(string, callback) { +function compressSvg(string, callback) { var svgo = new SVGO(); svgo.optimize(string, callback); } @@ -95,12 +139,7 @@ function makeImage(data, cb) { return; } - if (data.format === 'json') { - cb(result); - } else { - // Run the SVG through SVGO. - optimize(result, function(object) { cb(object.data); }); - } + cb(result); } module.exports = makeImage; diff --git a/templates/social-template.svg b/templates/social-template.svg index 386236e..96cef0d 100644 --- a/templates/social-template.svg +++ b/templates/social-template.svg @@ -1,5 +1,5 @@ -{{it.widths[1]-=4;}} + {{it.widths[1]-=4;}}