import type {SchedulerCallback} from './Scheduler';
import {
DiscreteEventPriority,
getCurrentUpdatePriority,
setCurrentUpdatePriority,
} from './ReactEventPriorities';
import {ImmediatePriority, scheduleCallback} from './Scheduler';
let syncQueue: Array<SchedulerCallback> | null = null;
let includesLegacySyncCallbacks: boolean = false;
let isFlushingSyncQueue: boolean = false;
export function scheduleSyncCallback(callback: SchedulerCallback) {
if (syncQueue === null) {
syncQueue = [callback];
} else {
syncQueue.push(callback);
}
}
export function scheduleLegacySyncCallback(callback: SchedulerCallback) {
includesLegacySyncCallbacks = true;
scheduleSyncCallback(callback);
}
export function flushSyncCallbacksOnlyInLegacyMode() {
if (includesLegacySyncCallbacks) {
flushSyncCallbacks();
}
}
export function flushSyncCallbacks(): null {
if (!isFlushingSyncQueue && syncQueue !== null) {
isFlushingSyncQueue = true;
const previousUpdatePriority = getCurrentUpdatePriority();
setCurrentUpdatePriority(DiscreteEventPriority);
let errors: Array<mixed> | null = null;
const queue = syncQueue;
for (let i = 0; i < queue.length; i++) {
let callback: SchedulerCallback = queue[i];
try {
do {
const isSync = true;
callback = callback(isSync);
} while (callback !== null);
} catch (error) {
if (errors === null) {
errors = [error];
} else {
errors.push(error);
}
}
}
syncQueue = null;
includesLegacySyncCallbacks = false;
setCurrentUpdatePriority(previousUpdatePriority);
isFlushingSyncQueue = false;
if (errors !== null) {
if (errors.length > 1) {
if (typeof AggregateError === 'function') {
throw new AggregateError(errors);
} else {
for (let i = 1; i < errors.length; i++) {
scheduleCallback(
ImmediatePriority,
throwError.bind(null, errors[i]),
);
}
const firstError = errors[0];
throw firstError;
}
} else {
const error = errors[0];
throw error;
}
}
}
return null;
}
function throwError(error: mixed) {
throw error;
}