/
images.js
97 lines (86 loc) · 2.26 KB
/
images.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const FALLBACK_WIDTHS = [400, 600, 800, 1077, 1500, 2154]
const FALLBACK_WIDTH = 1077
const SIZES_PROFILES = {
full: [
'(min-width: 70rem) 67.34rem',
'calc(100vw - 2.66rem)'
]
}
const isNetlify = process.env.NETLIFY === 'true'
/**
* getSrcset
*
* take image name and array of widths to generte srcset
*
* @param {string} file
* @param {array} widths
* @param {boolean, number} ratio
*/
function getSrcset(file, widths, ratio = false) {
const widthsSet = widths || FALLBACK_WIDTHS
return widthsSet.map(width => {
return `${formatUrl(file, width, ratio)} ${width}w`
}).join(', ')
}
/**
* getSrc
*
* take image name and optional width, return URL for use with src
*
* @param {string} file
* @param {array} width
* @param {boolean, number} ratio
*/
function getSrc(file, width = FALLBACK_WIDTH, ratio = false) {
return formatUrl(file, width, ratio)
}
/**
* getSizes
*
* format sizes array as string for attribute
*
* @param {array, string} sizes
*/
function getSizes(sizes) {
if (typeof sizes === 'string') {
sizes = SIZES_PROFILES[sizes] || SIZES_PROFILES.full
}
return sizes.join(', ')
}
/**
* formatUrl
*
* with image name and image width generate url with image cdn
*
* @param {string} file
* @param {array} width
* @param {boolean, number} ratio
*/
function formatUrl(file, width, ratio) {
const params = {
org_if_sml: 1
}
// if width
if (width) {
params.w = width
}
// if aspect ratio has been set, add the height based on width
if (ratio && width) {
params.h = width * ratio
}
const paramStr = Object.keys(params).map(function(key) {
return key + '=' + params[key]
}).join('&')
// if this is production, use Netlify proxying for
if (isNetlify) {
return `/images/${file}?${paramStr}`
}
// in dev, use cloudimage with surge dev url
return `https://ahqwbmhykq.cloudimg.io/v7/_dev_/${file}?${paramStr}`
}
/* eslint-disable key-spacing */
module.exports = {
srcset: (file, widths, ratio) => getSrcset(file, widths, ratio),
src: (file, width, ratio) => getSrc(file, width, ratio),
sizes: (sizes) => getSizes(sizes)
}