forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreact.js
64 lines (57 loc) · 1.51 KB
/
preact.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
import * as preact from /*OK*/ 'preact';
/**
* This file introduces a helper for draining Preact's queue of renders and effects.
* We use this as part of the afterEach() cleanup in unit tests, to ensure no effects are run
* in subsequent tests.
*
* There is still a test isolation issue in that an effect can asynchronously schedule work
* which cannot be guarded from at this layer. For that we'd likely need to refresh the window
* in between each test run.
*
* We should be able to remove this file if this feature lands in Preact.
* @fileoverview
*/
const rafs = [];
/**
* @param {(ts: (DOMHighResTimeStamp) => number)} cb
* @return {number}
*/
function flushableRaf(cb) {
rafs.push(cb);
return requestAnimationFrame(flushRaf);
}
function flushRaf(ts = performance.now()) {
for (const raf of rafs) {
raf(ts);
}
rafs.length = 0;
}
let pendingRender;
/**
* @param {() => void} process
* @return {Promise<void>}
*/
async function flushableRender(process) {
pendingRender = () => {
pendingRender = null;
return process();
};
await Promise.resolve().then(pendingRender);
}
/**
* Flushes Preact renders and effects.
*
* Effects may queue up further rerenders, etc. etc,
* so this function will loop until everything to resolves.
*
* @return {Promise<void>}
*/
export async function flush() {
flushRaf();
while (pendingRender) {
await pendingRender();
flushRaf();
}
}
preact.options.requestAnimationFrame = flushableRaf;
preact.options.debounceRendering = flushableRender;