This repository has been archived by the owner on Jul 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathkernel.js
402 lines (332 loc) · 10.5 KB
/
kernel.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
////////////////////////////////////////////////////////////////////////////////
// Kernel RaiX 2014
////////////////////////////////////////////////////////////////////////////////
// Timed functions
var timedFunctions = [];
// General render engine
var renderFunctions = [];
// Functions that will be run when theres time for it
var deferedFunctions = [];
// Render loop global
Kernel = {};
// Max length of defered buffer
Kernel.maxDeferedLength = 100;
// Debug flag
Kernel.debug = false;
// DOMHighResTimeStamp - High resolution timestamp polyfil
var Time = (window.performance && window.performance.now) ?
window.performance : Date;
/**
* Return the current timestamp in high resolution
* @return {Number}
*/
Kernel.now = function() {
return Time.now();
};
/**
* Run render function
* @param {function} Function to run in frame
* @return {Kernel}
*/
Kernel.onRender = function onRender(f) {
renderFunctions.push(f);
return Kernel;
};
/**
* Run function when theres time for it in the render loop
* @param {function} Function to run in frame when time permits it
* @return {Kernel}
*/
Kernel.defer = function defer(f) {
deferedFunctions.push(f);
return Kernel;
};
/**
* Run a function at a fixed timestamp
* @param {function}
* @param {Number}
* @return {Kernel}
*/
Kernel.timed = function timed(f, runAt) {
timedFunctions.push({
f: f,
runAt: runAt
});
return Kernel;
};
var _nextTimerReferenceId = 0;
var _timerRunning = {};
var _initTimer = function() {
// Get id
var id = _nextTimerReferenceId++;
// Set the timer to run
_timerRunning[id] = true;
// Return id
return id;
};
/**
* Kernel.setTimeout
* @param {Function}
* @param {delay}
*/
Kernel.setTimeout = function(f, delay) {
// Initialize timer reference
var id = _initTimer();
Kernel.timed(function() {
if (_timerRunning[id]) {
// Run the function
f();
}
}, Kernel.now() + delay);
// Return clear id
return id;
};
Kernel.setInterval = function(f, interval) {
// Initialize timer reference
var id = _initTimer();
// Calc the next run
var nextRun = Kernel.now() + interval;
// The interval function
var intervalFunction = function intervalFunction() {
if (_timerRunning[id]) {
// Calc the next run
nextRun += interval;
// Add the next run to the queue
Kernel.timed(intervalFunction, nextRun);
// Run the function
f();
}
};
// Initial run
Kernel.timed(intervalFunction, nextRun);
// Return clear id
return id;
};
Kernel.clearTimeout = function clearTimer(id) {
// Remove the timeout
delete _timerRunning[id];
};
Kernel.clearInterval = Kernel.clearTimeout;
Kernel.debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
return function() {
context = this;
args = arguments;
timestamp = new Date();
var later = function() {
var last = (new Date()) - timestamp;
if (last < wait) {
timeout = Kernel.setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) result = func.apply(context, args);
}
};
var callNow = immediate && !timeout;
if (!timeout) {
timeout = Kernel.setTimeout(later, wait);
}
if (callNow) result = func.apply(context, args);
return result;
};
};
Kernel.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
options = options || {};
var later = function () {
previous = options.leading === false ? 0 : new Date();
timeout = null;
result = func.apply(context, args);
};
return function () {
var now = new Date();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
Kernel.clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout && options.trailing !== false) {
timeout = Kernel.setTimeout(later, remaining);
}
return result;
};
};
/**
* Create alias function for defer
* @type {[type]}
*/
Kernel.then = Kernel.defer;
/**
* Create alias for onRender as run
* @type {[type]}
*/
Kernel.run = Kernel.onRender;
Kernel.each = function KernelEach(items, f) {
// XXX: for now depend on underscore
_.each(items, function KernelEach_Item(item, key) {
// Let render loop run this when theres time
Kernel.defer(function KernelEachItem() {
// Run the function
f(item, key);
});
});
return Kernel;
};
/**
* Autorun when the
* @param f The function to autorun.
* @param [options]
* [options.debounce] Postpone the execution until after debounce
* milliseconds have elapsed since the last time it was invoked.
* [options.throttle] Only call the original function at most
* once per every wait milliseconds.
* @returns {Tracker.Computation}
*/
Kernel.autorun = function(f, options) {
var later = function(c) {
// Make sure not to run if computation have been stopped
if (!c.stopped) {
// Store current computation
var prev = Tracker.currentComputation;
// Set the new computation
Tracker.currentComputation = c;//thisComputation;
Tracker.active = !! Tracker.currentComputation;
// Call function
f.call(this, c);
// Switch back
Tracker.currentComputation = prev;
Tracker.active = !! Tracker.currentComputation;
}
};
if (options && options.debounce) {
later = Kernel.debounce(later, options.debounce);
}
else if (options && options.throttle) {
later = Kernel.throttle(later, options.throttle);
}
return Tracker.autorun(function KernelComputation(c) {
if (c.firstRun) {
// Let the first run be run normally
f.call(this, c);
} else {
// On reruns we defer via the kernel
Kernel.defer(function () {
later(c);
});
}
});
};
Blaze.View.prototype.autorun = function(f, _inViewScope) {
var self = this;
// Lets just have the Blaze autorun defered via the Kernel
// The restrictions on when View#autorun can be called are in order
// to avoid bad patterns, like creating a Blaze.View and immediately
// calling autorun on it. A freshly created View is not ready to
// have logic run on it; it doesn't have a parentView, for example.
// It's when the View is materialized or expanded that the onViewCreated
// handlers are fired and the View starts up.
//
// Letting the render() method call `this.autorun()` is problematic
// because of re-render. The best we can do is to stop the old
// autorun and start a new one for each render, but that's a pattern
// we try to avoid internally because it leads to helpers being
// called extra times, in the case where the autorun causes the
// view to re-render (and thus the autorun to be torn down and a
// new one established).
//
// We could lift these restrictions in various ways. One interesting
// idea is to allow you to call `view.autorun` after instantiating
// `view`, and automatically wrap it in `view.onViewCreated`, deferring
// the autorun so that it starts at an appropriate time. However,
// then we can't return the Computation object to the caller, because
// it doesn't exist yet.
if (! self.isCreated) {
throw new Error("View#autorun must be called from the created callback at the earliest");
}
if (this._isInRender) {
throw new Error("Can't call View#autorun from inside render(); try calling it from the created or rendered callback");
}
if (Tracker.active) {
throw new Error("Can't call View#autorun from a Tracker Computation; try calling it from the created or rendered callback");
}
var c = Kernel.autorun(function viewAutorun(c) {
Blaze._withCurrentView(_inViewScope || self, function () {
return f.call(self, c);
});
});
self.onViewDestroyed(function () { c.stop(); });
return c;
};
/**
* The frame rate limit is set matching 60 fps 1000/60
* @type {Number}
*/
Kernel.frameRateLimit = 0; // 1000 / 60;
Kernel.deferedTimeLimit = 10; // ms
Kernel.currentFrame = 0;
var lastTimeStamp = null;
Kernel.loop = function renderLoop() {
// Get timestamp
var timestamp = Kernel.now();
// Request animation frame at the beginning trying to maintain 60fps
window.requestAnimationFrame(Kernel.loop);
// Set initial value
if (!lastTimeStamp) lastTimeStamp = timestamp;
// Limit the cpu/gpu load constraint ourself to the frameRateLimit
if (Kernel.frameRateLimit && Kernel.frameRateLimit > timestamp - lastTimeStamp) return;
// Increase the frame counter
Kernel.currentFrame++;
// Set current timed functions
var currentTimedFunctions = timedFunctions;
// Reset timedFunctions
timedFunctions = [];
for (var i = 0; i < currentTimedFunctions.length; i++) {
var timedFunction = currentTimedFunctions[i];
if (timedFunction.runAt > timestamp) {
// not ready yet, maybe next tick
timedFunctions.push(timedFunction);
} else {
// Ready...
timedFunction.f(timedFunction.runAt, timestamp, lastTimeStamp, Kernel.currentFrame);
}
}
// Run all render functions
var renderLength = renderFunctions.length;
while (renderLength--) {
// Run normal function in frame
(renderFunctions.shift())(timestamp, lastTimeStamp, Kernel.currentFrame);
}
// Flags for limiting verbosity
var displayForcedDeferedCount = true;
var displayDeferedCount = true;
// Make sure we keep the Kernel.maxDeferedLength limit
while (Kernel.maxDeferedLength >= 0 && deferedFunctions.length - Kernel.maxDeferedLength > 0) {
// Display debug info
if (Kernel.debug && displayForcedDeferedCount) {
console.log('Kernel: force run of ' + (deferedFunctions.length - Kernel.maxDeferedLength) + ' defered functions');
displayForcedDeferedCount=false;
}
// Force defered function to run
(deferedFunctions.shift())(timestamp, lastTimeStamp, Kernel.currentFrame);
}
// Run defered functions - in the defered time frame
while (deferedFunctions.length && (Kernel.now() - timestamp) < Kernel.deferedTimeLimit) {
// Display debug info
if (Kernel.debug && displayDeferedCount) {
console.log('Kernel: current defered queue size', deferedFunctions.length);
displayDeferedCount=false;
}
// Run the defered function
(deferedFunctions.shift())(timestamp, lastTimeStamp, Kernel.currentFrame);
}
// Set last time stamp
lastTimeStamp = timestamp;
};
// Initialize render loop
window.requestAnimationFrame(Kernel.loop);