1/**
2 * Imports code into a worklet. E.g.
3 *
4 * importWorklet(CSS.paintWorklet, {url: 'script.js'});
5 * importWorklet(CSS.paintWorklet, '(javascript string)');
6 *
7 * @param {Worklet} worklet
8 * @param {(Object|string)} code
9 */
10function importWorklet(worklet, code) {
11    let url;
12    if (typeof code === 'object') {
13      url = code.url;
14    } else {
15      const blob = new Blob([code], {type: 'text/javascript'});
16      url = URL.createObjectURL(blob);
17    }
18
19    return worklet.addModule(url);
20}
21
22/** @private */
23async function animationFrames(frames) {
24  for (let i = 0; i < frames; i++)
25    await new Promise(requestAnimationFrame);
26}
27
28/** @private */
29async function workletPainted() {
30    await animationFrames(2);
31}
32
33/**
34 * To make sure that we take the snapshot at the right time, we do double
35 * requestAnimationFrame. In the second frame, we take a screenshot, that makes
36 * sure that we already have a full frame.
37 *
38 * @param {Worklet} worklet
39 * @param {(Object|string)} code
40 */
41async function importWorkletAndTerminateTestAfterAsyncPaint(worklet, code) {
42    if (typeof worklet === 'undefined') {
43        takeScreenshot();
44        return;
45    }
46
47    await importWorklet(worklet, code);
48    await workletPainted();
49    takeScreenshot();
50}
51