|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +var R = require('ramda'); |
| 4 | +var Handlebars = require('handlebars'); |
| 5 | +var tinycolor = require('tinycolor2'); |
| 6 | + |
| 7 | +var source = '<svg xmlns="http://www.w3.org/2000/svg" width="{{width}}" height="{{height}}" viewBox="0 0 {{width}} {{height}}">' + |
| 8 | + '<rect fill="{{bg}}" width="100%" height="100%"/>' + |
| 9 | + '<text fill="{{fg}}" font-family="{{font}}" font-size="{{size}}" dy="{{dy}}" font-weight="{{weight}}" x="50%" y="50%" text-anchor="middle">{{{text}}}</text>' + |
| 10 | +'</svg>'; |
| 11 | + |
| 12 | +var template = Handlebars.compile(source); |
| 13 | + |
| 14 | +function encode (svgString) { |
| 15 | + // Thanks to: filamentgroup/directory-encoder |
| 16 | + return 'data:image/svg+xml;charset=US-ASCII,' + encodeURIComponent(svgString |
| 17 | + // strip newlines and tabs |
| 18 | + .replace(/[\n\r]/gmi, '') |
| 19 | + .replace(/\t/gmi, ' ') |
| 20 | + // strip comments |
| 21 | + .replace(/<\!\-\-(.*(?=\-\->))\-\->/gmi, '') |
| 22 | + // replace |
| 23 | + .replace(/'/gmi, '\\i')) |
| 24 | + // encode brackets |
| 25 | + .replace(/\(/g, '%28').replace(/\)/g, '%29'); |
| 26 | +} |
| 27 | + |
| 28 | +function create (width, height, options) { |
| 29 | + options = R.merge({ |
| 30 | + width: width, |
| 31 | + height: height, |
| 32 | + text: width + ' × ' + height, |
| 33 | + bg: '#ddd', |
| 34 | + size: Math.floor(height * 0.2), |
| 35 | + dy: Math.floor(height * 0.2 * 0.4), |
| 36 | + weight: 'bold', |
| 37 | + font: 'sans-serif' |
| 38 | + }, options || {}); |
| 39 | + |
| 40 | + if (R.isNil(options.fg)) { |
| 41 | + options.fg = (function (bg) { |
| 42 | + var color = tinycolor(bg); |
| 43 | + var method = color.isDark() ? 'lighten' : 'darken'; |
| 44 | + return color[method](50).toString(); |
| 45 | + })(options.bg); |
| 46 | + } |
| 47 | + |
| 48 | + return template(options); |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * Returns an escaped data URI for a placeholder image that can be used as the |
| 53 | + * src attribute of an img element. |
| 54 | + * |
| 55 | + * @since v0.3.0 |
| 56 | + * @param {Number} width |
| 57 | + * @param {Number} height |
| 58 | + * @param {Object} options |
| 59 | + * @return {String} |
| 60 | + * @example |
| 61 | + * |
| 62 | + * <img src="{{placeholder 150 50}}"> |
| 63 | + * |
| 64 | + * <img src="{{placeholder 150 50 text="foo"}}"> |
| 65 | + * |
| 66 | + * <img src="{{placeholder 150 50 bg="#000"}}"> |
| 67 | + * |
| 68 | + * <img src="{{placeholder 150 50 fg="pink"}}"> |
| 69 | + */ |
| 70 | + |
| 71 | +module.exports = function dummyImgSrc (width, height, options) { |
| 72 | + if (!R.is(Number, width) || !R.is(Number, height)) { |
| 73 | + throw new Error('The "dummyImgSrc" helper must be passed two numeric dimensions.'); |
| 74 | + } |
| 75 | + |
| 76 | + var result = encode(create(width, height, options.hash)); |
| 77 | + |
| 78 | + return new Handlebars.SafeString(result); |
| 79 | +}; |
0 commit comments