/
spotify-coverart.html
94 lines (75 loc) · 2.79 KB
/
spotify-coverart.html
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
<link rel="import" href="../polymer/polymer.html">
<!--
Element to render the most suitable image depending on available size and pixel density.
##### Example
<spotify-coverart images='[{"height":640,"url":"large.jpg","width":480},{"height":300,"url":"medium.jpg","width":225},{"height":64,"url":"small.jpg","width":48}]'></spotify-coverart>
@element spotify-coverart
@blurb Element to render the most suitable image depending on available size and pixel density.
@status beta
@homepage https://github.com/JMPerez/spotify-coverart
-->
<polymer-element name="spotify-coverart" attributes="images, detectSizeChange">
<template>
<link rel="stylesheet" href="spotify-coverart.css"/>
<div class="square-placeholder">
<div class="image" style="background-size: cover; background-image:url({{ cover }})"></div>
</div>
</template>
<script>
var interval = null;
Polymer({
/**
* The `images` attribute specifies the set of images, sorted by descending size
* Each image is represented with a JSON object containing `width`, `height` and
* `url` of the image.
*
* @attribute images
* @type Array<{Object}>
* @default []
*/
/**
* `detectSizeChange` is a property that determines whether the
component will be listening for size changes once rendered.
*
* @property detectSizeChange
* @type bool
* @default true
*/
detectSizeChange: true,
ready: function () {
if (interval) {
clearInterval(interval);
interval = null;
}
if (this.images) {
try {
var images = JSON.parse(this.images);
// todo: once we have loaded a large one maybe it doesn't make sense to try to load
// a smaller one, since that incurs in an extra request and the quality won't be
// better than the one provided by the larger image
var findRightImage = function() {
var targetWidth = this.offsetWidth * window.devicePixelRatio,
targetHeight = this.offsetHeight * window.devicePixelRatio;
if (targetWidth === 0 || targetHeight === 0) {
return;
}
var cover = images[0].url;
for (var i=1; i<images.length; i++) {
if (images[i].width >= targetWidth && images[i].height >= targetHeight) {
cover = images[i].url;
}
}
this.cover = cover;
}.bind(this);
if (this.detectSizeChange) {
interval = setInterval(findRightImage, 200);
}
findRightImage();
} catch (e) {
console.error(e);
}
}
}
});
</script>
</polymer-element>