-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathswatch-renderer-mixin.js
114 lines (89 loc) · 3.56 KB
/
swatch-renderer-mixin.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
define([
'jquery',
'underscore'
], function ($, _) {
'use strict';
return function (swatchRenderer) {
$.widget('mage.SwatchRenderer', swatchRenderer, {
lastImageResponse: null,
imageSizes: [
'large',
'medium',
'small',
],
_init: function () {
if (_.isUndefined(this.options) || _.isEmpty(this.options))
return this._super();
if (_.isUndefined(this.options.jsonConfig) || _.isEmpty(this.options.jsonConfig))
return this._super();
if (_.isUndefined(this.options.jsonConfig.images) || _.isEmpty(this.options.jsonConfig.images))
return this._super();
let wdpr = window.devicePixelRatio;
_.each(this.options.jsonConfig.images, function (images) {
_.each(images, function (imageObject) {
if (_.isUndefined(imageObject.fastly_srcset))
return;
if (!_.has(imageObject.fastly_srcset, wdpr))
return;
imageObject.img = imageObject.fastly_srcset[wdpr];
});
});
return this._super();
},
_ProductMediaCallback: function ($this, response, isInProductView) {
this.lastImageResponse = response;
return this._super($this, response, isInProductView);
},
updateBaseImage: function (images, context, isInProductView) {
this._super(images, context, isInProductView);
if (isInProductView || !this.lastImageResponse) {
return;
}
var currentSrc = context.find('.product-image-photo').attr('src');
if (!currentSrc) {
return;
}
var srcset = this.findEquivalentSrcset(currentSrc);
if (srcset) {
context.find('.product-image-photo').attr('srcset', srcset);
}
},
findEquivalentSrcset: function (src) {
if (!this.lastImageResponse || !this.lastImageResponse.fastly_srcset) {
return null;
}
var srcset = this.findSrcsetInImageResponse(src, this.lastImageResponse);
if (srcset) {
return srcset;
}
var gallery = this.lastImageResponse.gallery;
if (!gallery) {
return null;
}
for (var i in gallery) {
if (!gallery.hasOwnProperty(i)) {
continue;
}
srcset = this.findSrcsetInImageResponse(src, gallery[i]);
if (srcset) {
return srcset;
}
}
return null;
},
findSrcsetInImageResponse: function (src, list) {
if (!list.fastly_srcset) {
return null;
}
for (var i = 0; i < this.imageSizes.length; i++) {
var size = this.imageSizes[i];
if (list[size] && list[size] === src) {
return list.fastly_srcset[size];
}
}
return null;
}
});
return $.mage.SwatchRenderer;
};
});