1 | 'use strict';
|
2 | const utils = require('handlebars-utils');
|
3 | const SafeString = require('handlebars').SafeString;
|
4 | const common = require('./../lib/common');
|
5 |
|
6 | function helper(paper) {
|
7 | paper.handlebars.registerHelper('getImageSrcset', function(image, defaultImageUrl) {
|
8 |
|
9 | const sizeRegex = /(^\d+w$)|(^(\d+?)x(\d+?)$)/;
|
10 |
|
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 |
|
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 |
|
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 | |
40 |
|
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 |
|
58 | return ''
|
59 | }
|
60 | }
|
61 |
|
62 |
|
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 |
|
73 | module.exports = helper;
|