-
Notifications
You must be signed in to change notification settings - Fork 8
/
dom-scheduler.js
337 lines (277 loc) · 8.61 KB
/
dom-scheduler.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
(function(exports) {
'use strict';
var debug = false;
function log(str) {
if (!debug) {
return;
}
console.log('🎶 ', str);
}
// The naive mode just executes all blocks right away
// (useful for performance comparison).
var naive = false;
var naiveExec = function(block) {
block();
return Promise.resolve();
};
var directProtectionWindow = 360;
var Scheduler = function() {
this._directTracking = new Map();
this._ongoingTransitions = 0;
this._queuedTransitions = [];
this._flushing = false;
this._pendingMutations = [];
};
Scheduler.prototype = {
// *Direct* blocks should be used for direct manipulation use cases
// (touchevents, scrollevents...).
// They're exectuted in a requestAnimationFrame block and are protected
// from mutations. Request might be cancelled by subsequent direct blocks if
// the event loop gets too busy.
attachDirect: function(elm, evtType, block) {
var tracking = this._directTracking;
if (!tracking.get(elm)) {
tracking.set(elm, {});
}
var tElm = tracking.get(elm);
if (!(evtType in tElm)) {
tElm[evtType] = {
rafID: null,
protectionTimeout: null,
blocks: []
};
}
var tEvt = tElm[evtType];
if (!tEvt.blocks.length) {
elm.addEventListener(evtType, this);
}
tEvt.blocks.push(block);
},
detachDirect: function(elm, evtType, block) {
var tEvt = this._trackingFor(elm, evtType);
if (!tEvt) {
return;
}
if (tEvt.rafID) {
window.cancelAnimationFrame(tEvt.rafID);
}
if (tEvt.protectionTimeout) {
clearTimeout(tEvt.protectionTimeout);
tEvt.protectionTimeout = null;
this._stopProtectingDirect();
}
var toRemove = tEvt.blocks.indexOf(block);
if (toRemove === -1) {
log('wrong detach block');
return;
}
tEvt.blocks.splice(toRemove, 1);
if (!tEvt.blocks.length) {
elm.removeEventListener(evtType, this);
var tElm = this._directTracking.get(elm);
delete tElm[evtType];
if (Object.keys(tElm).length === 0) {
this._directTracking.delete(elm);
}
}
},
_trackingFor: function(elm, evtType) {
var tracking = this._directTracking;
if (!tracking.get(elm)) {
log('wrong detach element');
return;
}
var tElm = tracking.get(elm);
if (!(evtType in tElm)) {
log('wrong detach event');
return;
}
return tElm[evtType];
},
_shouldProtectDirect: function() {
var tracking = this._directTracking;
for (var elm of tracking.keys()) {
var tElm = tracking.get(elm);
for (var evtType in tElm) {
var tEvt = tElm[evtType];
if (tEvt.protectionTimeout !== null) {
return true;
}
}
}
return false;
},
_stopProtectingDirect: function() {
this._dequeueTransitions();
this._flushMutations();
if (debug) {
console.timeEnd('protecting');
}
},
handleEvent: function(evt) {
var tEvt = this._trackingFor(evt.currentTarget, evt.type);
if (!tEvt) {
return;
}
if (naive) {
tEvt.blocks.forEach(function(block) {
block(evt);
});
return;
}
if (tEvt.protectionTimeout) {
clearTimeout(tEvt.protectionTimeout);
} else {
if (debug) {
console.time('protecting');
}
}
tEvt.protectionTimeout = setTimeout((function() {
tEvt.protectionTimeout = null;
this._stopProtectingDirect();
}).bind(this), directProtectionWindow);
if (tEvt.rafID) {
window.cancelAnimationFrame(tEvt.rafID);
}
tEvt.rafID = window.requestAnimationFrame(function() {
tEvt.blocks.forEach(function(block) {
var startDate;
if (debug) {
startDate = performance.now();
}
block(evt);
if (debug) {
var blockDuration = performance.now() - startDate;
if (blockDuration > 16) {
log('Direct block took more than a frame (' +
blockDuration.toString() + 'ms)');
}
}
});
});
},
// *Feedbacks* blocks have a built in 'transitionend' wait mechanism.
// They're protected from mutation and will be delayed during a mutation
// flush.
// They have the same priority as `direct` blocks.
//
// -> Returns a promise fullfilled at the end of the transition for chaining
feedback: function(block, elm, evt, timeout) {
return this._transition(block, true, elm, evt, timeout);
},
// *Transitions* blocks have a built in 'transitionend' wait mechanism.
// They're protected from mutation and will be delayed during a mutation
// flush.
// They will also be delayed by `direct` blocks.
//
// -> Returns a promise fullfilled at the end of the transition for chaining
transition: function(block, elm, evt, timeout) {
return this._transition(block, false, elm, evt, timeout);
},
_transition: function(block, feedback, elm, evt, timeout) {
if (naive) {
return naiveExec(block);
}
timeout = timeout || 500;
return new Promise((function(resolve, reject) {
var content = (function() {
this._ongoingTransitions++;
block();
if (!elm || !evt) {
this._ongoingTransitions--;
resolve();
return;
}
if (debug) {
console.time('animating');
}
var finishTimeout;
var done = (function() {
clearTimeout(finishTimeout);
elm.removeEventListener(evt, done);
this._ongoingTransitions--;
if (debug) {
console.timeEnd('animating');
}
if (this._ongoingTransitions === 0) {
setTimeout(this._flushMutations.bind(this));
}
resolve();
}).bind(this);
elm.addEventListener(evt, done);
finishTimeout = setTimeout(function() {
done();
log('Transition block saved by a timeout of ' + timeout + ' ~ ' +
elm.style.transition);
}, timeout);
}).bind(this);
if (this._flushing || (this._shouldProtectDirect() && !feedback)) {
this._queuedTransitions.push(content);
} else {
content();
}
}).bind(this));
},
_dequeueTransitions: function() {
if (this._queuedTransitions.length === 0) {
return;
}
if (this._flushing || this._shouldProtectDirect()) {
return;
}
var transitions = this._queuedTransitions;
transitions.forEach(function(transition) {
transition();
});
this._queuedTransitions = [];
},
// *Mutations* blocks should be used to write to the DOM or perform
// actions requiring a reflow that are not direct manipulations.
// We shoud always aim for the document to be almost visually identical
// _before_ and _after_ a mutation block.
// Any big change in layout/size will cause a flash/jump.
//
// -> Returns a promise fullfilled after the reflow for chaining
mutation: function(block) {
if (naive) {
return naiveExec(block);
}
return new Promise((function(resolve, reject) {
if (this._shouldProtectDirect() || this._ongoingTransitions > 0) {
this._pendingMutations.push({
block: block,
resolve: resolve
});
} else {
Promise.resolve()
.then(block)
.then(resolve);
}
}).bind(this));
},
_flushMutations: function() {
if (this._pendingMutations.length === 0) {
return;
}
if (this._shouldProtectDirect() || this._ongoingTransitions > 0) {
return;
}
this._flushing = true;
var fulfilments =
this._pendingMutations
.map(function(obj) { return obj.resolve; });
var mutations = this._pendingMutations;
var results = mutations.map(function(mutation) {
return mutation.block();
});
this._pendingMutations = [];
this._flushing = false;
fulfilments.forEach(function(resolve, i) { resolve(results[i]); });
this._dequeueTransitions();
}
};
exports.DomScheduler = Scheduler;
// We only ever want there to be
// one instance of the scheduler
exports.scheduler = exports.scheduler || new Scheduler();
})(window);