import { disableLegacyMode } from 'shared/ReactFeatureFlags';
import { DiscreteEventPriority } from 'react-reconciler/src/ReactEventPriorities';
import ReactSharedInternals from 'shared/ReactSharedInternals';
import ReactDOMSharedInternals from 'shared/ReactDOMSharedInternals';
function flushSyncImpl<R>(fn: () => R): R;
function flushSyncImpl(): void;
function flushSyncImpl<R>(fn?: () => R): R | undefined {
const previousTransition = ReactSharedInternals.T;
const previousUpdatePriority =
ReactDOMSharedInternals.p;
try {
ReactSharedInternals.T = null;
ReactDOMSharedInternals.p =
DiscreteEventPriority;
if (fn) {
return fn();
} else {
return undefined;
}
} finally {
ReactSharedInternals.T = previousTransition;
ReactDOMSharedInternals.p =
previousUpdatePriority;
const wasInRender =
ReactDOMSharedInternals.d
.f();
if (__DEV__) {
if (wasInRender) {
console.error(
'flushSync was called from inside a lifecycle method. React cannot ' +
'flush when React is already rendering. Consider moving this call to ' +
'a scheduler task or micro task.',
);
}
}
}
}
function flushSyncErrorInBuildsThatSupportLegacyMode<R>(fn: () => R): R;
function flushSyncErrorInBuildsThatSupportLegacyMode(): void;
function flushSyncErrorInBuildsThatSupportLegacyMode() {
throw new Error(
'Expected this build of React to not support legacy mode but it does. This is a bug in React.',
);
}
export const flushSync: typeof flushSyncImpl = disableLegacyMode
? flushSyncImpl
: flushSyncErrorInBuildsThatSupportLegacyMode;