|
| 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 | + * |
| 7 | + * @flow |
| 8 | + */ |
| 9 | + |
| 10 | +import type {BatchConfig} from 'react/src/ReactCurrentBatchConfig'; |
| 11 | + |
| 12 | +import {disableLegacyMode} from 'shared/ReactFeatureFlags'; |
| 13 | +import {DiscreteEventPriority} from 'react-reconciler/src/ReactEventPriorities'; |
| 14 | + |
| 15 | +import ReactSharedInternals from 'shared/ReactSharedInternals'; |
| 16 | +const ReactCurrentBatchConfig: BatchConfig = |
| 17 | + ReactSharedInternals.ReactCurrentBatchConfig; |
| 18 | + |
| 19 | +import ReactDOMSharedInternals from 'shared/ReactDOMSharedInternals'; |
| 20 | +const ReactDOMCurrentDispatcher = |
| 21 | + ReactDOMSharedInternals.ReactDOMCurrentDispatcher; |
| 22 | +const ReactDOMCurrentUpdatePriority = |
| 23 | + ReactDOMSharedInternals.ReactDOMCurrentUpdatePriority; |
| 24 | + |
| 25 | +declare function flushSyncImpl<R>(fn: () => R): R; |
| 26 | +declare function flushSyncImpl(void): void; |
| 27 | +function flushSyncImpl<R>(fn: (() => R) | void): R | void { |
| 28 | + const previousTransition = ReactCurrentBatchConfig.transition; |
| 29 | + const previousUpdatePriority = ReactDOMCurrentUpdatePriority.current; |
| 30 | + |
| 31 | + try { |
| 32 | + ReactCurrentBatchConfig.transition = null; |
| 33 | + ReactDOMCurrentUpdatePriority.current = DiscreteEventPriority; |
| 34 | + if (fn) { |
| 35 | + return fn(); |
| 36 | + } else { |
| 37 | + return undefined; |
| 38 | + } |
| 39 | + } finally { |
| 40 | + ReactCurrentBatchConfig.transition = previousTransition; |
| 41 | + ReactDOMCurrentUpdatePriority.current = previousUpdatePriority; |
| 42 | + const wasInRender = ReactDOMCurrentDispatcher.current.flushSyncWork(); |
| 43 | + if (__DEV__) { |
| 44 | + if (wasInRender) { |
| 45 | + console.error( |
| 46 | + 'flushSync was called from inside a lifecycle method. React cannot ' + |
| 47 | + 'flush when React is already rendering. Consider moving this call to ' + |
| 48 | + 'a scheduler task or micro task.', |
| 49 | + ); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +declare function flushSyncErrorInBuildsThatSupportLegacyMode<R>(fn: () => R): R; |
| 56 | +declare function flushSyncErrorInBuildsThatSupportLegacyMode(void): void; |
| 57 | +function flushSyncErrorInBuildsThatSupportLegacyMode() { |
| 58 | + // eslint-disable-next-line react-internal/prod-error-codes |
| 59 | + throw new Error( |
| 60 | + 'Expected this build of React to not support legacy mode but it does. This is a bug in React.', |
| 61 | + ); |
| 62 | +} |
| 63 | + |
| 64 | +export const flushSync: typeof flushSyncImpl = disableLegacyMode |
| 65 | + ? flushSyncImpl |
| 66 | + : flushSyncErrorInBuildsThatSupportLegacyMode; |
0 commit comments