-
Notifications
You must be signed in to change notification settings - Fork 7
/
favloader-src.js
299 lines (294 loc) · 10.8 KB
/
favloader-src.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/**@license
*
* favloader v. {{VER}}
*
* Vanilla JavaScript library for loading animation in favicon
*
* Copyright (c) 2018-2019 Jakub T. Jankiewicz <https://jcubic.pl/me>
* Released under the MIT license
*
* Build: {{DATE}}
*/
/* global define, module, global, Worker, Blob, BlobBuilder, setTimeout, parseGIF */
(function(factory) {
var root = typeof window !== 'undefined' ? window : global;
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
// istanbul ignore next
define([], factory);
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = factory();
} else {
// Browser
// istanbul ignore next
root.favloader = factory();
}
})(function(undefined) {
// we use web worker to trigger interval since browser main thread is limited
// when tab is not active
function fworker(fn) {
// ref: https://stackoverflow.com/a/10372280/387194
var str = '(' + fn.toString() + ')()';
var URL = window.URL || window.webkitURL;
var blob;
try {
blob = new Blob([str], {type: 'application/javascript'});
} catch (e) { // Backwards-compatibility
window.BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder;
blob = new BlobBuilder();
blob.append(str);
blob = blob.getBlob();
}
return new Worker(URL.createObjectURL(blob));
}
// ----------------------------------------------------------------------------------
var interval = (function() {
var worker = fworker(function() {
// rAF polyfil without setTimeout, ref: https://gist.github.com/paulirish/1579671
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !self.requestAnimationFrame; ++x) {
self.requestAnimationFrame = self[vendors[x]+'RequestAnimationFrame'];
self.cancelAnimationFrame = self[vendors[x]+'CancelAnimationFrame']
|| self[vendors[x]+'CancelRequestAnimationFrame'];
}
var raf = {};
self.addEventListener('message', function(response) {
var data = response.data;
var id = data.id;
if (data.type !== 'RPC' || id === null) {
return;
}
if (data.method == 'setInterval') {
var interval_id = data.params[0];
if (typeof interval_id === 'number') {
raf[interval_id] = self.setInterval(function() {
self.postMessage({ type: 'interval', id: interval_id });
}, data.params[1]);
self.postMessage({ type: 'RPC', id: id, result: interval_id });
} else {
self.postMessage({
type: 'RPC',
id: id,
result: null,
error: 'Invalid Argument, expected number'
});
}
} else if (data.method == 'clearInterval') {
self.clearInterval(raf[data.params[0]]);
delete raf[data.params[0]];
}
});
});
var callbacks = {};
var rpc = (function() {
var id = 0;
return function rpc(method, params) {
var _id = ++id;
return new Promise(function(resolve, reject) {
worker.addEventListener('message', function handler(response) {
var data = response.data;
if (data && data.type === 'RPC' && data.id === _id) {
if (data.error) {
reject(data.error);
} else {
resolve(data.result);
}
worker.removeEventListener('message', handler);
}
});
worker.postMessage({ type: 'RPC', method: method, id: _id, params: params });
});
};
})();
worker.addEventListener('message', function(response) {
var data = response.data;
if (data && data.type === 'interval' && callbacks[data.id]) {
callbacks[data.id]();
}
});
return {
set: function(fn, interval) {
var interval_id = Date.now();
callbacks[interval_id] = fn;
rpc('setInterval', [interval_id, interval]);
return interval_id;
},
clear: function(id) {
delete callbacks[id];
return rpc('clearInterval', [id]);
}
};
})();
// ----------------------------------------------------------------------------------
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
hidden = "hidden";
visibilityChange = "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
// ----------------------------------------------------------------------------------
function warn(message) {
if (console && console.warn) {
console.warn(message);
} else {
setTimeout(function() {
throw new Error(message);
}, 0);
}
}
// ----------------------------------------------------------------------------------
var ctx,
c,
link,
icon,
id,
progress = 0,
duration,
initialized,
settings,
gif,
type,
initial_turns = -.25,
interval_id,
step;
// ----------------------------------------------------------------------------------
function init(options) {
if (document.readyState !== "complete") {
setTimeout(init.bind(this, options), 100);
return;
}
settings = Object.assign({
size: 16,
radius: 6,
thickness: 2,
color: '#0F60A8',
duration: 5000
}, options);
if (!link) {
link = document.querySelector('link[rel*="icon"]');
if (!link) {
link = document.createElement('link');
link.setAttribute('rel', 'icon');
document.head.appendChild(link);
warn("No default icon found, restore state will not work");
} else {
icon = link.getAttribute('href');
type = link.getAttribute('type');
}
}
clear();
if (settings.gif) {
if (typeof parseGIF === 'undefined') {
throw new Error('parseGIF not defined, please include parseGIF.js file');
}
parseGIF(settings.gif).then(function(data) {
gif = data;
});
} else {
if (!c) {
c = document.createElement('canvas');
}
c.width = c.height = settings.size;
ctx = c.getContext('2d');
ctx.lineCap = "round";
ctx.lineWidth = settings.thickness;
ctx.strokeStyle = settings.color;
duration = settings.duration;
}
initialized = true;
}
// ----------------------------------------------------------------------------------
function clear() {
if (interval_id) {
interval.clear(interval_id);
interval_id = null;
}
}
// ----------------------------------------------------------------------------------
function restore() {
if (icon) {
link.setAttribute('href', icon + '?' + Date.now());
link.setAttribute('type', type);
} else if (link) {
link.parentNode.removeChild(link);
}
clear();
}
// ----------------------------------------------------------------------------------
function animate() {
if (!initialized) {
setTimeout(animate, 100);
return;
}
if (interval_id) {
return;
}
progress = 0;
if (settings.gif && parseGIF) {
if (!gif) {
setTimeout(animate, 100);
return;
}
interval_id = interval.set(animateGIF, 20);
} else {
interval_id = interval.set(draw, 20);
}
}
// ----------------------------------------------------------------------------------
function turn(x) {
return (x + initial_turns) * 2 * Math.PI;
}
// ----------------------------------------------------------------------------------
function animateGIF() {
progress++;
if (progress >= gif.uris.length) {
progress = 0;
}
update(gif.uris[progress]);
}
// ----------------------------------------------------------------------------------
function arcStart(pos) {
return turn(pos + initial_turns) + turn(Math.max(0, pos * 2 - 1));
}
// ----------------------------------------------------------------------------------
function arcEnd(pos) {
return turn(pos + initial_turns) + turn(Math.min(1, pos * 2));
}
// ----------------------------------------------------------------------------------
function update(dataURI) {
var newIcon, icon = document.querySelector('link[rel*="icon"]');
(newIcon = icon.cloneNode(true)).setAttribute('href', dataURI);
icon.parentNode.replaceChild(newIcon, icon);
link = newIcon;
}
// ----------------------------------------------------------------------------------
function draw() {
ctx.clearRect(0, 0, settings.size, settings.size);
if (typeof settings.frame === 'function') {
settings.frame(ctx);
} else {
var position = progress % duration / duration;
ctx.beginPath();
var center = Math.round(settings.size / 2);
ctx.arc(center, center, settings.radius, arcStart(position), arcEnd(position));
ctx.stroke();
}
update(ctx.canvas.toDataURL());
progress += duration / 100;
}
// ----------------------------------------------------------------------------------
return {
init: init,
start: animate,
stop: restore,
version: '{{VER}}'
};
});