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;
let i = 0;
const previousUpdatePriority = getCurrentUpdatePriority();
try {
const isSync = true;
const queue = syncQueue;
setCurrentUpdatePriority(DiscreteEventPriority);
for (; i < queue.length; i++) {
let callback: SchedulerCallback = queue[i];
do {
callback = callback(isSync);
} while (callback !== null);
}
syncQueue = null;
includesLegacySyncCallbacks = false;
} catch (error) {
if (syncQueue !== null) {
syncQueue = syncQueue.slice(i + 1);
}
scheduleCallback(ImmediatePriority, flushSyncCallbacks);
throw error;
} finally {
setCurrentUpdatePriority(previousUpdatePriority);
isFlushingSyncQueue = false;
}
}
return null;
}