| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | * @flow |
| 7 | */ |
| 8 | |
| 9 | import type {ReactSyntheticEvent} from './ReactSyntheticEventType'; |
| 10 | import accumulateInto from './accumulateInto'; |
| 11 | import forEachAccumulated from './forEachAccumulated'; |
| 12 | import {executeDispatchesInOrder, rethrowCaughtError} from './EventPluginUtils'; |
| 13 | |
| 14 | /** |
| 15 | * Internal queue of events that have accumulated their dispatches and are |
| 16 | * waiting to have their dispatches executed. |
| 17 | */ |
| 18 | let eventQueue: ?(Array<ReactSyntheticEvent> | ReactSyntheticEvent) = null; |
| 19 | |
| 20 | /** |
| 21 | * Dispatches an event and releases it back into the pool, unless persistent. |
| 22 | * |
| 23 | * @param {?object} event Synthetic event to be dispatched. |
| 24 | * @private |
| 25 | */ |
| 26 | function executeDispatchesAndRelease(event: ReactSyntheticEvent) { |
| 27 | if (event) { |
| 28 | executeDispatchesInOrder(event); |
| 29 | |
| 30 | if (!event.isPersistent()) { |
| 31 | event.constructor.release(event); |
| 32 | } |
| 33 | } |
| 34 | } |
| 35 | // $FlowFixMe[missing-local-annot] |
| 36 | function executeDispatchesAndReleaseTopLevel(e) { |
| 37 | return executeDispatchesAndRelease(e); |
| 38 | } |
| 39 | |
| 40 | export function runEventsInBatch( |
| 41 | events: Array<ReactSyntheticEvent> | ReactSyntheticEvent | null, |
| 42 | ) { |
| 43 | if (events !== null) { |
| 44 | eventQueue = accumulateInto(eventQueue, events); |
| 45 | } |
| 46 | |
| 47 | // Set `eventQueue` to null before processing it so that we can tell if more |
| 48 | // events get enqueued while processing. |
| 49 | const processingEventQueue = eventQueue; |
| 50 | eventQueue = null; |
| 51 | |
| 52 | if (!processingEventQueue) { |
| 53 | return; |
| 54 | } |
| 55 | |
| 56 | forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); |
| 57 | |
| 58 | if (eventQueue) { |
| 59 | throw new Error( |
| 60 | 'processEventQueue(): Additional events were enqueued while processing ' + |
| 61 | 'an event queue. Support for this has not yet been implemented.', |
| 62 | ); |
| 63 | } |
| 64 | |
| 65 | // This would be a good time to rethrow if any of the event handlers threw. |
| 66 | rethrowCaughtError(); |
| 67 | } |