UNPKG

3.06 kBJavaScriptView Raw
1'use strict';
2const utils = require('handlebars-utils');
3const SafeString = require('handlebars').SafeString;
4const common = require('./../lib/common');
5
6function helper(paper) {
7 paper.handlebars.registerHelper('getImageSrcset', function(image, defaultImageUrl) {
8 // Regex to test size string is of the form 123x123 or 100w
9 const sizeRegex = /(^\d+w$)|(^(\d+?)x(\d+?)$)/;
10 // Regex to test to that srcset descriptor is of the form 1x 1.5x 2x OR 123w
11 const descriptorRegex = /(^\d+w$)|(^([0-9](\.[0-9]+)?)x)$/;
12
13 const options = arguments[arguments.length - 1];
14
15 if (utils.isUndefined(defaultImageUrl)) {
16 defaultImageUrl = '';
17 }
18
19 if (!utils.isObject(image) || !utils.isString (image.data)
20 || !common.isValidURL(image.data) || image.data.indexOf('{:size}') === -1) {
21 // return empty string if not a valid image object
22 defaultImageUrl = defaultImageUrl ? defaultImageUrl : '';
23 return utils.isString(image) ? image : defaultImageUrl;
24 }
25
26 let srcsets = {};
27
28 if (options.hash['use_default_sizes']) {
29 if (Number.isInteger(image.width) && Number.isInteger(image.height)){
30 /* If we know the image dimensions, don't generate srcset sizes larger than the image */
31 srcsets[`${image.width}w`] = `${image.width}w`;
32 const defaultSrcsetSizes = [2560, 1920, 1280, 960, 640, 320, 160, 80];
33 defaultSrcsetSizes.forEach(width => {
34 if (width < image.width) {
35 srcsets[`${width}w`] = `${width}w`;
36 }
37 });
38 } else {
39 /* If we DON'T know the image dimensions, generate a default set of srcsets
40 * This will upsize images */
41 srcsets = {
42 '2560w': '2560w',
43 '1920w': '1920w',
44 '1280w': '1280w',
45 '960w': '960w',
46 '640w': '640w',
47 '320w': '320w',
48 '160w': '160w',
49 '80w': '80w',
50 };
51 }
52 } else {
53 srcsets = options.hash;
54 if (!utils.isObject(srcsets) || Object.keys(srcsets).some(descriptor => {
55 return !(descriptorRegex.test(descriptor) && sizeRegex.test(srcsets[descriptor]));
56 })) {
57 // return empty string if not valid srcset object
58 return ''
59 }
60 }
61
62 // If there's only one argument, return a `src` only (also works for `srcset`)
63 if (Object.keys(srcsets).length === 1) {
64 return new SafeString((image.data.replace('{:size}', srcsets[Object.keys(srcsets)[0]])));
65 }
66
67 return new SafeString(Object.keys(srcsets).reverse().map(descriptor => {
68 return ([image.data.replace('{:size}', srcsets[descriptor]), descriptor].join(' '));
69 }).join(', '));
70 });
71}
72
73module.exports = helper;