UNPKG

1.87 kBJavaScriptView Raw
1'use strict';
2
3var _ = require('lodash');
4const SafeString = require('handlebars').SafeString;
5const common = require('./../lib/common');
6
7function helper(paper) {
8 paper.handlebars.registerHelper('getImage', function (image, presetName, defaultImageUrl) {
9 var sizeRegex = /^(\d+?)x(\d+?)$/g;
10 var settings = paper.themeSettings || {};
11 var presets = settings._images;
12 var size;
13 var width;
14 var height;
15
16 if (!_.isPlainObject(image) || !_.isString(image.data)
17 || !common.isValidURL(image.data) || image.data.indexOf('{:size}') === -1) {
18 // return empty string if not a valid image object
19 defaultImageUrl = defaultImageUrl ? defaultImageUrl : '';
20 return _.isString(image) ? image : defaultImageUrl;
21 }
22
23 if (_.isPlainObject(presets) && _.isPlainObject(presets[presetName])) {
24 // If preset is one of the given presets in _images
25 width = parseInt(presets[presetName].width, 10) || 5120;
26 height = parseInt(presets[presetName].height, 10) || 5120;
27 size = `${width}x${height}`;
28 } else if (sizeRegex.test(settings[presetName])) {
29 // If preset name is a setting and match the NNNxNNN format
30 size = settings[presetName];
31 width = parseInt(size.split('x')[0], 10);
32 height = parseInt(size.split('x')[1], 10);
33 } else {
34 // Use the original image size
35 size = 'original';
36 }
37
38 if (Number.isInteger(image.width) && Number.isInteger(image.height)
39 && Number.isInteger(width) && Number.isInteger(height)) {
40 size = `${Math.min(image.width, width)}x${Math.min(image.height, height)}`
41 }
42
43 return new SafeString(image.data.replace('{:size}', size));
44 });
45};
46
47module.exports = helper;