-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
vsync-impl.js
500 lines (456 loc) · 13.7 KB
/
vsync-impl.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
/**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {Deferred} from '../utils/promise';
import {JankMeter} from './jank-meter';
import {Pass} from '../pass';
import {Services} from '../services';
import {
addDocumentVisibilityChangeListener,
isDocumentHidden,
removeDocumentVisibilityChangeListener,
} from '../utils/document-visibility';
import {cancellation} from '../error';
import {dev, devAssert, rethrowAsync} from '../log';
import {getService, registerServiceBuilder} from '../service';
import {installTimerService} from './timer-impl';
/** @const {time} */
const FRAME_TIME = 16;
/**
* @typedef {!Object<string, *>}
*/
let VsyncStateDef;
/**
* @typedef {{
* measure: (function(!VsyncStateDef):undefined|undefined),
* mutate: (function(!VsyncStateDef):undefined|undefined)
* }}
*/
let VsyncTaskSpecDef;
/**
* Abstraction over requestAnimationFrame (rAF) that batches DOM read (measure)
* and write (mutate) tasks in a single frame, to eliminate layout thrashing.
*
* NOTE: If the document is invisible due to prerendering (this includes
* application-level prerendering where the doc is rendered in a hidden
* iframe or webview), then no frame will be scheduled.
* @package Visible for type.
* @implements {../service.Disposable}
*/
export class Vsync {
/**
* @param {!Window} win
*/
constructor(win) {
/** @const {!Window} */
this.win = win;
/** @private @const {!./ampdoc-impl.AmpDocService} */
this.ampdocService_ = Services.ampdocServiceFor(this.win);
/** @private @const {function(function())} */
this.raf_ = this.getRaf_();
/**
* Tasks to run in the next frame.
* @private {!Array<!VsyncTaskSpecDef>}
*/
this.tasks_ = [];
/**
* Double buffer for tasks.
* @private {!Array<!VsyncTaskSpecDef>}
*/
this.nextTasks_ = [];
/**
* States for tasks in the next frame in the same order.
* @private {!Array<!VsyncStateDef>}
*/
this.states_ = [];
/**
* Double buffer for states.
* @private {!Array<!VsyncStateDef>}
*/
this.nextStates_ = [];
/**
* Whether a new animation frame has been scheduled.
* @private {boolean}
*/
this.scheduled_ = false;
/** @private {?Promise} */
this.nextFramePromise_ = null;
/** @protected {?function()} */
this.nextFrameResolver_ = null;
/** @const {!Function} */
this.boundRunScheduledTasks_ = this.runScheduledTasks_.bind(this);
/**
* If the doc is invisible we use this instead of rAF because rAF
* does not run in that scenario.
* However, we only do this for non-animation tasks as running
* animations doesn't make sense when not visible.
* @const {!Pass}
*/
this.invisiblePass_ = new Pass(
this.win,
this.boundRunScheduledTasks_,
FRAME_TIME
);
/**
* Similar to this.invisiblePass_, but backing up a real rAF call. If we
* somehow failed to know that we are throttled we use a timer (which
* may also be throttled but at least runs eventually) to make sure
* we continue to get work done.
* @const {!Pass}
*/
this.backupPass_ = new Pass(
this.win,
this.boundRunScheduledTasks_,
// We cancel this when rAF fires and really only want it to fire
// if rAF doesn't work at all.
FRAME_TIME * 2.5
);
// When the document changes visibility, vsync has to reschedule the queue
// processing.
/** @private {function()} */
this.boundOnVisibilityChanged_ = this.onVisibilityChanged_.bind(this);
if (this.ampdocService_.isSingleDoc()) {
// In a single-doc mode, the visibility of the doc == global visibility.
// Thus, it's more efficient to only listen to it once.
this.ampdocService_
.getSingleDoc()
.onVisibilityChanged(this.boundOnVisibilityChanged_);
} else {
// In multi-doc mode, we track separately the global visibility and
// per-doc visibility when necessary.
addDocumentVisibilityChangeListener(
this.win.document,
this.boundOnVisibilityChanged_
);
}
/** @private {!JankMeter} */
this.jankMeter_ = new JankMeter(this.win);
}
/** @override */
dispose() {
removeDocumentVisibilityChangeListener(
this.win.document,
this.boundOnVisibilityChanged_
);
}
/** @private */
onVisibilityChanged_() {
if (this.scheduled_) {
this.forceSchedule_();
}
}
/**
* Runs vsync task: measure followed by mutate.
*
* If state is not provided, the value passed to the measure and mutate
* will be undefined.
*
* @param {!VsyncTaskSpecDef} task
* @param {!VsyncStateDef=} opt_state
*/
run(task, opt_state) {
this.tasks_.push(task);
this.states_.push(opt_state || undefined);
this.schedule_();
}
/**
* Runs vsync task: measure followed by mutate. Returns the promise that
* will be resolved as soon as the task has been completed.
*
* If state is not provided, the value passed to the measure and mutate
* will be undefined.
*
* @param {!VsyncTaskSpecDef} task
* @param {!VsyncStateDef=} opt_state
* @return {!Promise}
*/
runPromise(task, opt_state) {
this.run(task, opt_state);
if (this.nextFramePromise_) {
return this.nextFramePromise_;
}
const deferred = new Deferred();
this.nextFrameResolver_ = deferred.resolve;
return (this.nextFramePromise_ = deferred.promise);
}
/**
* Creates a function that will call {@link run} method.
* @param {!VsyncTaskSpecDef} task
* @return {function(!VsyncStateDef=)}
*/
createTask(task) {
return /** @type {function(!VsyncStateDef=)} */ ((opt_state) => {
this.run(task, opt_state);
});
}
/**
* Runs the mutate operation via vsync.
* @param {function():undefined} mutator
*/
mutate(mutator) {
this.run({
measure: undefined, // For uniform hidden class.
mutate: mutator,
});
}
/**
* Runs `mutate` wrapped in a promise.
* @param {function():undefined} mutator
* @return {!Promise}
*/
mutatePromise(mutator) {
return this.runPromise({
measure: undefined,
mutate: mutator,
});
}
/**
* Runs the measure operation via vsync.
* @param {function():undefined} measurer
*/
measure(measurer) {
this.run({
measure: measurer,
mutate: undefined, // For uniform hidden class.
});
}
/**
* Runs `measure` wrapped in a promise.
* @param {function():TYPE} measurer
* @return {!Promise<TYPE>}
* @template TYPE
*/
measurePromise(measurer) {
return new Promise((resolve) => {
this.measure(() => {
resolve(measurer());
});
});
}
/**
* Whether the runtime is allowed to animate at this time.
* @param {!Node} contextNode
* @return {boolean}
*/
canAnimate(contextNode) {
return this.canAnimate_(devAssert(contextNode));
}
/**
* @param {!Node=} opt_contextNode
* @return {boolean}
* @private
*/
canAnimate_(opt_contextNode) {
// Window level: animations allowed only when global window is visible.
if (isDocumentHidden(this.win.document)) {
return false;
}
// Single doc: animations allowed when single doc is visible.
if (this.ampdocService_.isSingleDoc()) {
return this.ampdocService_.getSingleDoc().isVisible();
}
// Multi-doc: animations depend on the state of the relevant doc.
if (opt_contextNode) {
const ampdoc = this.ampdocService_.getAmpDocIfAvailable(opt_contextNode);
return !ampdoc || ampdoc.isVisible();
}
return true;
}
/**
* Runs the animation vsync task. This operation can only run when animations
* are allowed. Otherwise, this method returns `false` and exits.
* @param {!Node} contextNode
* @param {!VsyncTaskSpecDef} task
* @param {!VsyncStateDef=} opt_state
* @return {boolean}
*/
runAnim(contextNode, task, opt_state) {
// Do not request animation frames when the document is not visible.
if (!this.canAnimate_(contextNode)) {
dev().warn(
'VSYNC',
'Did not schedule a vsync request, because document was invisible'
);
return false;
}
this.run(task, opt_state);
return true;
}
/**
* Creates an animation vsync task. This operation can only run when
* animations are allowed. Otherwise, this closure returns `false` and exits.
* @param {!Node} contextNode
* @param {!VsyncTaskSpecDef} task
* @return {function(!VsyncStateDef=):boolean}
*/
createAnimTask(contextNode, task) {
return /** @type {function(!VsyncStateDef=):boolean} */ ((opt_state) => {
return this.runAnim(contextNode, task, opt_state);
});
}
/**
* Runs the series of mutates until the mutator returns a false value.
* @param {!Node} contextNode
* @param {function(time, time, !VsyncStateDef):boolean} mutator The
* mutator callback. Only expected to do DOM writes, not reads. If the
* returned value is true, the vsync task will be repeated, otherwise it
* will be completed. The arguments are: timeSinceStart:time,
* timeSincePrev:time and state:VsyncStateDef.
* @param {number=} opt_timeout Optional timeout that will force the series
* to complete and reject the promise.
* @return {!Promise} Returns the promise that will either resolve on when
* the vsync series are completed or reject in case of failure, such as
* timeout.
*/
runAnimMutateSeries(contextNode, mutator, opt_timeout) {
if (!this.canAnimate_(contextNode)) {
return Promise.reject(cancellation());
}
return new Promise((resolve, reject) => {
const startTime = Date.now();
let prevTime = 0;
const task = this.createAnimTask(contextNode, {
mutate: (state) => {
const timeSinceStart = Date.now() - startTime;
const res = mutator(timeSinceStart, timeSinceStart - prevTime, state);
if (!res) {
resolve();
} else if (opt_timeout && timeSinceStart > opt_timeout) {
reject(new Error('timeout'));
} else {
prevTime = timeSinceStart;
task(state);
}
},
});
task({});
});
}
/** @private */
schedule_() {
if (this.scheduled_) {
return;
}
// Schedule actual animation frame and then run tasks.
this.scheduled_ = true;
this.jankMeter_.onScheduled();
this.forceSchedule_();
}
/** @private */
forceSchedule_() {
if (this.canAnimate_()) {
this.raf_(this.boundRunScheduledTasks_);
this.backupPass_.schedule();
} else {
this.invisiblePass_.schedule();
}
}
/**
* Runs all scheduled tasks. This is typically called in an RAF
* callback. Tests may call this method to force execution of
* tasks without waiting.
* @private
*/
runScheduledTasks_() {
this.backupPass_.cancel();
this.scheduled_ = false;
this.jankMeter_.onRun();
const {tasks_: tasks, states_: states, nextFrameResolver_: resolver} = this;
this.nextFrameResolver_ = null;
this.nextFramePromise_ = null;
// Double buffering
this.tasks_ = this.nextTasks_;
this.states_ = this.nextStates_;
for (let i = 0; i < tasks.length; i++) {
if (tasks[i].measure) {
if (!callTask_(tasks[i].measure, states[i])) {
// Ensure that the mutate is not executed when measure fails.
tasks[i].mutate = undefined;
}
}
}
for (let i = 0; i < tasks.length; i++) {
if (tasks[i].mutate) {
callTask_(tasks[i].mutate, states[i]);
}
}
// Swap last arrays into double buffer.
this.nextTasks_ = tasks;
this.nextStates_ = states;
this.nextTasks_.length = 0;
this.nextStates_.length = 0;
if (resolver) {
resolver();
}
}
/**
* @return {function(function())} requestAnimationFrame or polyfill.
*/
getRaf_() {
const raf =
this.win.requestAnimationFrame || this.win.webkitRequestAnimationFrame;
if (raf) {
return raf.bind(this.win);
}
let lastTime = 0;
return (fn) => {
const now = Date.now();
// By default we take 16ms between frames, but if the last frame is say
// 10ms ago, we only want to wait 6ms.
const timeToCall = Math.max(0, FRAME_TIME - (now - lastTime));
lastTime = now + timeToCall;
this.win.setTimeout(fn, timeToCall);
};
}
}
/**
* For optimization reasons to stop try/catch from blocking optimization.
* @param {function(!VsyncStateDef):undefined|undefined} callback
* @param {!VsyncStateDef} state
* @return {boolean}
* @noinline
*/
function callTask_(callback, state) {
devAssert(callback);
try {
const ret = callback(state);
if (ret !== undefined) {
dev().error(
'VSYNC',
'callback returned a value but vsync cannot propogate it: %s',
callback.toString()
);
}
} catch (e) {
rethrowAsync(e);
return false;
}
return true;
}
/**
* @param {!Window} window
* @return {!Vsync}
*/
export function vsyncForTesting(window) {
installVsyncService(window);
return getService(window, 'vsync');
}
/**
* @param {!Window} window
*/
export function installVsyncService(window) {
installTimerService(window);
registerServiceBuilder(window, 'vsync', Vsync);
}