import type {PriorityLevel} from '../SchedulerPriorities';
import {
enableSchedulerDebugging,
enableProfiling,
} from '../SchedulerFeatureFlags';
import {push, pop, peek} from '../SchedulerMinHeap';
import {
ImmediatePriority,
UserBlockingPriority,
NormalPriority,
LowPriority,
IdlePriority,
} from '../SchedulerPriorities';
import {
markTaskRun,
markTaskYield,
markTaskCompleted,
markTaskCanceled,
markTaskErrored,
markSchedulerSuspended,
markSchedulerUnsuspended,
markTaskStart,
stopLoggingProfilingEvents,
startLoggingProfilingEvents,
} from '../SchedulerProfiling';
type Callback = boolean => ?Callback;
type Task = {
id: number,
callback: Callback | null,
priorityLevel: PriorityLevel,
startTime: number,
expirationTime: number,
sortIndex: number,
isQueued?: boolean,
};
var maxSigned31BitInt = 1073741823;
var IMMEDIATE_PRIORITY_TIMEOUT = -1;
var USER_BLOCKING_PRIORITY_TIMEOUT = 250;
var NORMAL_PRIORITY_TIMEOUT = 5000;
var LOW_PRIORITY_TIMEOUT = 10000;
var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt;
var taskQueue: Array<Task> = [];
var timerQueue: Array<Task> = [];
var taskIdCounter = 1;
var isSchedulerPaused = false;
var currentTask = null;
var currentPriorityLevel = NormalPriority;
var isPerformingWork = false;
var isHostCallbackScheduled = false;
var isHostTimeoutScheduled = false;
let currentMockTime: number = 0;
let scheduledCallback:
| null
| ((
hasTimeRemaining: boolean,
initialTime: DOMHighResTimeStamp | number,
) => boolean) = null;
let scheduledTimeout: (number => void) | null = null;
let timeoutTime: number = -1;
let yieldedValues: Array<mixed> | null = null;
let expectedNumberOfYields: number = -1;
let didStop: boolean = false;
let isFlushing: boolean = false;
let needsPaint: boolean = false;
let shouldYieldForPaint: boolean = false;
var disableYieldValue = false;
function setDisableYieldValue(newValue: boolean) {
disableYieldValue = newValue;
}
function advanceTimers(currentTime: number) {
let timer = peek(timerQueue);
while (timer !== null) {
if (timer.callback === null) {
pop(timerQueue);
} else if (timer.startTime <= currentTime) {
pop(timerQueue);
timer.sortIndex = timer.expirationTime;
push(taskQueue, timer);
if (enableProfiling) {
markTaskStart(timer, currentTime);
timer.isQueued = true;
}
} else {
return;
}
timer = peek(timerQueue);
}
}
function handleTimeout(currentTime: number) {
isHostTimeoutScheduled = false;
advanceTimers(currentTime);
if (!isHostCallbackScheduled) {
if (peek(taskQueue) !== null) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
} else {
const firstTimer = peek(timerQueue);
if (firstTimer !== null) {
requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
}
}
}
}
function flushWork(hasTimeRemaining: boolean, initialTime: number) {
if (enableProfiling) {
markSchedulerUnsuspended(initialTime);
}
isHostCallbackScheduled = false;
if (isHostTimeoutScheduled) {
isHostTimeoutScheduled = false;
cancelHostTimeout();
}
isPerformingWork = true;
const previousPriorityLevel = currentPriorityLevel;
try {
if (enableProfiling) {
try {
return workLoop(hasTimeRemaining, initialTime);
} catch (error) {
if (currentTask !== null) {
const currentTime = getCurrentTime();
markTaskErrored(currentTask, currentTime);
currentTask.isQueued = false;
}
throw error;
}
} else {
return workLoop(hasTimeRemaining, initialTime);
}
} finally {
currentTask = null;
currentPriorityLevel = previousPriorityLevel;
isPerformingWork = false;
if (enableProfiling) {
const currentTime = getCurrentTime();
markSchedulerSuspended(currentTime);
}
}
}
function workLoop(hasTimeRemaining: boolean, initialTime: number): boolean {
let currentTime = initialTime;
advanceTimers(currentTime);
currentTask = peek(taskQueue);
while (
currentTask !== null &&
!(enableSchedulerDebugging && isSchedulerPaused)
) {
if (
currentTask.expirationTime > currentTime &&
(!hasTimeRemaining || shouldYieldToHost())
) {
break;
}
const callback = currentTask.callback;
if (typeof callback === 'function') {
currentTask.callback = null;
currentPriorityLevel = currentTask.priorityLevel;
const didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
if (enableProfiling) {
markTaskRun(currentTask, currentTime);
}
const continuationCallback = callback(didUserCallbackTimeout);
currentTime = getCurrentTime();
if (typeof continuationCallback === 'function') {
currentTask.callback = continuationCallback;
if (enableProfiling) {
markTaskYield(currentTask, currentTime);
}
advanceTimers(currentTime);
if (shouldYieldForPaint) {
needsPaint = true;
return true;
} else {
}
} else {
if (enableProfiling) {
markTaskCompleted(currentTask, currentTime);
currentTask.isQueued = false;
}
if (currentTask === peek(taskQueue)) {
pop(taskQueue);
}
advanceTimers(currentTime);
}
} else {
pop(taskQueue);
}
currentTask = peek(taskQueue);
}
if (currentTask !== null) {
return true;
} else {
const firstTimer = peek(timerQueue);
if (firstTimer !== null) {
requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
}
return false;
}
}
function unstable_runWithPriority<T>(
priorityLevel: PriorityLevel,
eventHandler: () => T,
): T {
switch (priorityLevel) {
case ImmediatePriority:
case UserBlockingPriority:
case NormalPriority:
case LowPriority:
case IdlePriority:
break;
default:
priorityLevel = NormalPriority;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
}
function unstable_next<T>(eventHandler: () => T): T {
var priorityLevel;
switch (currentPriorityLevel) {
case ImmediatePriority:
case UserBlockingPriority:
case NormalPriority:
priorityLevel = NormalPriority;
break;
default:
priorityLevel = currentPriorityLevel;
break;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
}
function unstable_wrapCallback<T: (...Array<mixed>) => mixed>(callback: T): T {
var parentPriorityLevel = currentPriorityLevel;
return function () {
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = parentPriorityLevel;
try {
return callback.apply(this, arguments);
} finally {
currentPriorityLevel = previousPriorityLevel;
}
};
}
function unstable_scheduleCallback(
priorityLevel: PriorityLevel,
callback: Callback,
options?: {delay: number},
): Task {
var currentTime = getCurrentTime();
var startTime;
if (typeof options === 'object' && options !== null) {
var delay = options.delay;
if (typeof delay === 'number' && delay > 0) {
startTime = currentTime + delay;
} else {
startTime = currentTime;
}
} else {
startTime = currentTime;
}
var timeout;
switch (priorityLevel) {
case ImmediatePriority:
timeout = IMMEDIATE_PRIORITY_TIMEOUT;
break;
case UserBlockingPriority:
timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
break;
case IdlePriority:
timeout = IDLE_PRIORITY_TIMEOUT;
break;
case LowPriority:
timeout = LOW_PRIORITY_TIMEOUT;
break;
case NormalPriority:
default:
timeout = NORMAL_PRIORITY_TIMEOUT;
break;
}
var expirationTime = startTime + timeout;
var newTask: Task = {
id: taskIdCounter++,
callback,
priorityLevel,
startTime,
expirationTime,
sortIndex: -1,
};
if (enableProfiling) {
newTask.isQueued = false;
}
if (startTime > currentTime) {
newTask.sortIndex = startTime;
push(timerQueue, newTask);
if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
if (isHostTimeoutScheduled) {
cancelHostTimeout();
} else {
isHostTimeoutScheduled = true;
}
requestHostTimeout(handleTimeout, startTime - currentTime);
}
} else {
newTask.sortIndex = expirationTime;
push(taskQueue, newTask);
if (enableProfiling) {
markTaskStart(newTask, currentTime);
newTask.isQueued = true;
}
if (!isHostCallbackScheduled && !isPerformingWork) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
}
}
return newTask;
}
function unstable_pauseExecution() {
isSchedulerPaused = true;
}
function unstable_continueExecution() {
isSchedulerPaused = false;
if (!isHostCallbackScheduled && !isPerformingWork) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
}
}
function unstable_getFirstCallbackNode(): Task | null {
return peek(taskQueue);
}
function unstable_cancelCallback(task: Task) {
if (enableProfiling) {
if (task.isQueued) {
const currentTime = getCurrentTime();
markTaskCanceled(task, currentTime);
task.isQueued = false;
}
}
task.callback = null;
}
function unstable_getCurrentPriorityLevel(): PriorityLevel {
return currentPriorityLevel;
}
function requestHostCallback(callback: (boolean, number) => boolean) {
scheduledCallback = callback;
}
function requestHostTimeout(callback: number => void, ms: number) {
scheduledTimeout = callback;
timeoutTime = currentMockTime + ms;
}
function cancelHostTimeout(): void {
scheduledTimeout = null;
timeoutTime = -1;
}
function shouldYieldToHost(): boolean {
if (
(expectedNumberOfYields === 0 && yieldedValues === null) ||
(expectedNumberOfYields !== -1 &&
yieldedValues !== null &&
yieldedValues.length >= expectedNumberOfYields) ||
(shouldYieldForPaint && needsPaint)
) {
didStop = true;
return true;
}
return false;
}
function getCurrentTime(): number {
return currentMockTime;
}
function forceFrameRate() {
}
function reset() {
if (isFlushing) {
throw new Error('Cannot reset while already flushing work.');
}
currentMockTime = 0;
scheduledCallback = null;
scheduledTimeout = null;
timeoutTime = -1;
yieldedValues = null;
expectedNumberOfYields = -1;
didStop = false;
isFlushing = false;
needsPaint = false;
}
function unstable_flushNumberOfYields(count: number): void {
if (isFlushing) {
throw new Error('Already flushing work.');
}
if (scheduledCallback !== null) {
const cb = scheduledCallback;
expectedNumberOfYields = count;
isFlushing = true;
try {
let hasMoreWork = true;
do {
hasMoreWork = cb(true, currentMockTime);
} while (hasMoreWork && !didStop);
if (!hasMoreWork) {
scheduledCallback = null;
}
} finally {
expectedNumberOfYields = -1;
didStop = false;
isFlushing = false;
}
}
}
function unstable_flushUntilNextPaint(): false {
if (isFlushing) {
throw new Error('Already flushing work.');
}
if (scheduledCallback !== null) {
const cb = scheduledCallback;
shouldYieldForPaint = true;
needsPaint = false;
isFlushing = true;
try {
let hasMoreWork = true;
do {
hasMoreWork = cb(true, currentMockTime);
} while (hasMoreWork && !didStop);
if (!hasMoreWork) {
scheduledCallback = null;
}
} finally {
shouldYieldForPaint = false;
didStop = false;
isFlushing = false;
}
}
return false;
}
function unstable_hasPendingWork(): boolean {
return scheduledCallback !== null;
}
function unstable_flushExpired() {
if (isFlushing) {
throw new Error('Already flushing work.');
}
if (scheduledCallback !== null) {
isFlushing = true;
try {
const hasMoreWork = scheduledCallback(false, currentMockTime);
if (!hasMoreWork) {
scheduledCallback = null;
}
} finally {
isFlushing = false;
}
}
}
function unstable_flushAllWithoutAsserting(): boolean {
if (isFlushing) {
throw new Error('Already flushing work.');
}
if (scheduledCallback !== null) {
const cb = scheduledCallback;
isFlushing = true;
try {
let hasMoreWork = true;
do {
hasMoreWork = cb(true, currentMockTime);
} while (hasMoreWork);
if (!hasMoreWork) {
scheduledCallback = null;
}
return true;
} finally {
isFlushing = false;
}
} else {
return false;
}
}
function unstable_clearLog(): Array<mixed> {
if (yieldedValues === null) {
return [];
}
const values = yieldedValues;
yieldedValues = null;
return values;
}
function unstable_flushAll(): void {
if (yieldedValues !== null) {
throw new Error(
'Log is not empty. Assert on the log of yielded values before ' +
'flushing additional work.',
);
}
unstable_flushAllWithoutAsserting();
if (yieldedValues !== null) {
throw new Error(
'While flushing work, something yielded a value. Use an ' +
'assertion helper to assert on the log of yielded values, e.g. ' +
'expect(Scheduler).toFlushAndYield([...])',
);
}
}
function log(value: mixed): void {
if (console.log.name === 'disabledLog' || disableYieldValue) {
return;
}
if (yieldedValues === null) {
yieldedValues = [value];
} else {
yieldedValues.push(value);
}
}
function unstable_advanceTime(ms: number) {
if (console.log.name === 'disabledLog' || disableYieldValue) {
return;
}
currentMockTime += ms;
if (scheduledTimeout !== null && timeoutTime <= currentMockTime) {
scheduledTimeout(currentMockTime);
timeoutTime = -1;
scheduledTimeout = null;
}
}
function requestPaint() {
needsPaint = true;
}
export {
ImmediatePriority as unstable_ImmediatePriority,
UserBlockingPriority as unstable_UserBlockingPriority,
NormalPriority as unstable_NormalPriority,
IdlePriority as unstable_IdlePriority,
LowPriority as unstable_LowPriority,
unstable_runWithPriority,
unstable_next,
unstable_scheduleCallback,
unstable_cancelCallback,
unstable_wrapCallback,
unstable_getCurrentPriorityLevel,
shouldYieldToHost as unstable_shouldYield,
requestPaint as unstable_requestPaint,
unstable_continueExecution,
unstable_pauseExecution,
unstable_getFirstCallbackNode,
getCurrentTime as unstable_now,
forceFrameRate as unstable_forceFrameRate,
unstable_flushAllWithoutAsserting,
unstable_flushNumberOfYields,
unstable_flushExpired,
unstable_clearLog,
unstable_flushUntilNextPaint,
unstable_hasPendingWork,
unstable_flushAll,
log,
unstable_advanceTime,
reset,
setDisableYieldValue as unstable_setDisableYieldValue,
};
export const unstable_Profiling: {
startLoggingProfilingEvents(): void,
stopLoggingProfilingEvents(): ArrayBuffer | null,
} | null = enableProfiling
? {
startLoggingProfilingEvents,
stopLoggingProfilingEvents,
}
: null;