| 25 | * @return {Promise<void>} |
| 26 | */ |
| 27 | export function act(cb) { |
| 28 | if (++actDepth > 1) { |
| 29 | // If calls to `act` are nested, a flush happens only when the |
| 30 | // outermost call returns. In the inner call, we just execute the |
| 31 | // callback and return since the infrastructure for flushing has already |
| 32 | // been set up. |
| 33 | // |
| 34 | // If an exception occurs, the outermost `act` will handle cleanup. |
| 35 | try { |
| 36 | const result = cb(); |
| 37 | if (isThenable(result)) { |
| 38 | return result.then( |
| 39 | () => { |
| 40 | --actDepth; |
| 41 | }, |
| 42 | e => { |
| 43 | --actDepth; |
| 44 | throw e; |
| 45 | } |
| 46 | ); |
| 47 | } |
| 48 | } catch (e) { |
| 49 | --actDepth; |
| 50 | throw e; |
| 51 | } |
| 52 | --actDepth; |
| 53 | return Promise.resolve(); |
| 54 | } |
| 55 | |
| 56 | const previousRequestAnimationFrame = options.requestAnimationFrame; |
| 57 | const rerender = setupRerender(); |
| 58 | |
| 59 | /** @type {() => void} */ |
| 60 | let flushes = [], |
| 61 | toFlush; |
| 62 | |
| 63 | // Override requestAnimationFrame so we can flush pending hooks. |
| 64 | options.requestAnimationFrame = fc => flushes.push(fc); |
| 65 | |
| 66 | const finish = () => { |
| 67 | try { |
| 68 | rerender(); |
| 69 | while (flushes.length) { |
| 70 | toFlush = flushes; |
| 71 | flushes = []; |
| 72 | |
| 73 | toFlush.forEach(x => x()); |
| 74 | rerender(); |
| 75 | } |
| 76 | } catch (e) { |
| 77 | if (!err) { |
| 78 | err = e; |
| 79 | } |
| 80 | } finally { |
| 81 | teardown(); |
| 82 | } |
| 83 | |
| 84 | options.requestAnimationFrame = previousRequestAnimationFrame; |