/
gravatar-img.html
66 lines (63 loc) · 2.17 KB
/
gravatar-img.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
<script>
//gravatar-img.html
//v0.1.2
//Copyright 2014 Marcin Warpechowski (MIT license)
(function (global) {
function updateImg(host, img, hash) {
var width = host.offsetWidth;
var height = host.offsetHeight;
var desiredSize = Math.max(width, height);
if (!(desiredSize > 0)) {
desiredSize = 16;
img.style.minWidth = "16px";
img.style.minHeight = "16px";
}
if (!(width > 0)) {
img.style.minWidth = "16px";
}
if (!(height > 0)) {
img.style.minHeight = "16px";
}
img.style.backgroundImage = "url(//www.gravatar.com/avatar/" + (hash || "") + "?s=" + desiredSize + ")";
}
var GravatarImgElementPrototype = Object.create(HTMLElement.prototype);
GravatarImgElementPrototype.attributeChangedCallback = function (attributeName, oldVal, newVal) {
if (!this.shadowRoot) {
return;
}
if (attributeName == "email") {
updateImg(this, this.shadowRoot.querySelector('div'), SparkMD5.hash(newVal));
}
else if (attributeName == "hash") {
updateImg(this, this.shadowRoot.querySelector('div'), newVal);
}
};
GravatarImgElementPrototype.attachedCallback = function () {
var img = document.createElement("DIV");
var style = document.createElement("STYLE");
style.innerText = ":host{display: inline-flex;}";
img.style.display = "inline-block";
img.style.flex = "1 1 auto";
img.style.backgroundPosition = "center center";
img.style.backgroundRepeat = "no-repeat";
img.style.backgroundSize = "cover";
var that = this;
window.requestAnimationFrame(function() {
var email = that.getAttribute("email");
if (email) {
updateImg(that, img, SparkMD5.hash(email));
}
else {
var hash = that.getAttribute("hash");
updateImg(that, img, hash);
}
});
var shadowRoot = this.createShadowRoot();
shadowRoot.appendChild(style);
shadowRoot.appendChild(img);
};
global.GravatarImgElement = document.registerElement('gravatar-img', {
prototype: GravatarImgElementPrototype
});
})(window)
</script>