scheduler.development.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. /**
  2. * @license React
  3. * scheduler.development.js
  4. *
  5. * Copyright (c) Facebook, Inc. and its affiliates.
  6. *
  7. * This source code is licensed under the MIT license found in the
  8. * LICENSE file in the root directory of this source tree.
  9. */
  10. 'use strict';
  11. if (process.env.NODE_ENV !== "production") {
  12. (function() {
  13. 'use strict';
  14. /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
  15. if (
  16. typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
  17. typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===
  18. 'function'
  19. ) {
  20. __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
  21. }
  22. var enableSchedulerDebugging = false;
  23. var enableProfiling = false;
  24. var frameYieldMs = 5;
  25. function push(heap, node) {
  26. var index = heap.length;
  27. heap.push(node);
  28. siftUp(heap, node, index);
  29. }
  30. function peek(heap) {
  31. return heap.length === 0 ? null : heap[0];
  32. }
  33. function pop(heap) {
  34. if (heap.length === 0) {
  35. return null;
  36. }
  37. var first = heap[0];
  38. var last = heap.pop();
  39. if (last !== first) {
  40. heap[0] = last;
  41. siftDown(heap, last, 0);
  42. }
  43. return first;
  44. }
  45. function siftUp(heap, node, i) {
  46. var index = i;
  47. while (index > 0) {
  48. var parentIndex = index - 1 >>> 1;
  49. var parent = heap[parentIndex];
  50. if (compare(parent, node) > 0) {
  51. // The parent is larger. Swap positions.
  52. heap[parentIndex] = node;
  53. heap[index] = parent;
  54. index = parentIndex;
  55. } else {
  56. // The parent is smaller. Exit.
  57. return;
  58. }
  59. }
  60. }
  61. function siftDown(heap, node, i) {
  62. var index = i;
  63. var length = heap.length;
  64. var halfLength = length >>> 1;
  65. while (index < halfLength) {
  66. var leftIndex = (index + 1) * 2 - 1;
  67. var left = heap[leftIndex];
  68. var rightIndex = leftIndex + 1;
  69. var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those.
  70. if (compare(left, node) < 0) {
  71. if (rightIndex < length && compare(right, left) < 0) {
  72. heap[index] = right;
  73. heap[rightIndex] = node;
  74. index = rightIndex;
  75. } else {
  76. heap[index] = left;
  77. heap[leftIndex] = node;
  78. index = leftIndex;
  79. }
  80. } else if (rightIndex < length && compare(right, node) < 0) {
  81. heap[index] = right;
  82. heap[rightIndex] = node;
  83. index = rightIndex;
  84. } else {
  85. // Neither child is smaller. Exit.
  86. return;
  87. }
  88. }
  89. }
  90. function compare(a, b) {
  91. // Compare sort index first, then task id.
  92. var diff = a.sortIndex - b.sortIndex;
  93. return diff !== 0 ? diff : a.id - b.id;
  94. }
  95. // TODO: Use symbols?
  96. var ImmediatePriority = 1;
  97. var UserBlockingPriority = 2;
  98. var NormalPriority = 3;
  99. var LowPriority = 4;
  100. var IdlePriority = 5;
  101. function markTaskErrored(task, ms) {
  102. }
  103. /* eslint-disable no-var */
  104. var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function';
  105. if (hasPerformanceNow) {
  106. var localPerformance = performance;
  107. exports.unstable_now = function () {
  108. return localPerformance.now();
  109. };
  110. } else {
  111. var localDate = Date;
  112. var initialTime = localDate.now();
  113. exports.unstable_now = function () {
  114. return localDate.now() - initialTime;
  115. };
  116. } // Max 31 bit integer. The max integer size in V8 for 32-bit systems.
  117. // Math.pow(2, 30) - 1
  118. // 0b111111111111111111111111111111
  119. var maxSigned31BitInt = 1073741823; // Times out immediately
  120. var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out
  121. var USER_BLOCKING_PRIORITY_TIMEOUT = 250;
  122. var NORMAL_PRIORITY_TIMEOUT = 5000;
  123. var LOW_PRIORITY_TIMEOUT = 10000; // Never times out
  124. var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap
  125. var taskQueue = [];
  126. var timerQueue = []; // Incrementing id counter. Used to maintain insertion order.
  127. var taskIdCounter = 1; // Pausing the scheduler is useful for debugging.
  128. var currentTask = null;
  129. var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance.
  130. var isPerformingWork = false;
  131. var isHostCallbackScheduled = false;
  132. var isHostTimeoutScheduled = false; // Capture local references to native APIs, in case a polyfill overrides them.
  133. var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null;
  134. var localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : null;
  135. var localSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom
  136. var isInputPending = typeof navigator !== 'undefined' && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null;
  137. function advanceTimers(currentTime) {
  138. // Check for tasks that are no longer delayed and add them to the queue.
  139. var timer = peek(timerQueue);
  140. while (timer !== null) {
  141. if (timer.callback === null) {
  142. // Timer was cancelled.
  143. pop(timerQueue);
  144. } else if (timer.startTime <= currentTime) {
  145. // Timer fired. Transfer to the task queue.
  146. pop(timerQueue);
  147. timer.sortIndex = timer.expirationTime;
  148. push(taskQueue, timer);
  149. } else {
  150. // Remaining timers are pending.
  151. return;
  152. }
  153. timer = peek(timerQueue);
  154. }
  155. }
  156. function handleTimeout(currentTime) {
  157. isHostTimeoutScheduled = false;
  158. advanceTimers(currentTime);
  159. if (!isHostCallbackScheduled) {
  160. if (peek(taskQueue) !== null) {
  161. isHostCallbackScheduled = true;
  162. requestHostCallback(flushWork);
  163. } else {
  164. var firstTimer = peek(timerQueue);
  165. if (firstTimer !== null) {
  166. requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
  167. }
  168. }
  169. }
  170. }
  171. function flushWork(hasTimeRemaining, initialTime) {
  172. isHostCallbackScheduled = false;
  173. if (isHostTimeoutScheduled) {
  174. // We scheduled a timeout but it's no longer needed. Cancel it.
  175. isHostTimeoutScheduled = false;
  176. cancelHostTimeout();
  177. }
  178. isPerformingWork = true;
  179. var previousPriorityLevel = currentPriorityLevel;
  180. try {
  181. if (enableProfiling) {
  182. try {
  183. return workLoop(hasTimeRemaining, initialTime);
  184. } catch (error) {
  185. if (currentTask !== null) {
  186. var currentTime = exports.unstable_now();
  187. markTaskErrored(currentTask, currentTime);
  188. currentTask.isQueued = false;
  189. }
  190. throw error;
  191. }
  192. } else {
  193. // No catch in prod code path.
  194. return workLoop(hasTimeRemaining, initialTime);
  195. }
  196. } finally {
  197. currentTask = null;
  198. currentPriorityLevel = previousPriorityLevel;
  199. isPerformingWork = false;
  200. }
  201. }
  202. function workLoop(hasTimeRemaining, initialTime) {
  203. var currentTime = initialTime;
  204. advanceTimers(currentTime);
  205. currentTask = peek(taskQueue);
  206. while (currentTask !== null && !(enableSchedulerDebugging )) {
  207. if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {
  208. // This currentTask hasn't expired, and we've reached the deadline.
  209. break;
  210. }
  211. var callback = currentTask.callback;
  212. if (typeof callback === 'function') {
  213. currentTask.callback = null;
  214. currentPriorityLevel = currentTask.priorityLevel;
  215. var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
  216. var continuationCallback = callback(didUserCallbackTimeout);
  217. currentTime = exports.unstable_now();
  218. if (typeof continuationCallback === 'function') {
  219. currentTask.callback = continuationCallback;
  220. } else {
  221. if (currentTask === peek(taskQueue)) {
  222. pop(taskQueue);
  223. }
  224. }
  225. advanceTimers(currentTime);
  226. } else {
  227. pop(taskQueue);
  228. }
  229. currentTask = peek(taskQueue);
  230. } // Return whether there's additional work
  231. if (currentTask !== null) {
  232. return true;
  233. } else {
  234. var firstTimer = peek(timerQueue);
  235. if (firstTimer !== null) {
  236. requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
  237. }
  238. return false;
  239. }
  240. }
  241. function unstable_runWithPriority(priorityLevel, eventHandler) {
  242. switch (priorityLevel) {
  243. case ImmediatePriority:
  244. case UserBlockingPriority:
  245. case NormalPriority:
  246. case LowPriority:
  247. case IdlePriority:
  248. break;
  249. default:
  250. priorityLevel = NormalPriority;
  251. }
  252. var previousPriorityLevel = currentPriorityLevel;
  253. currentPriorityLevel = priorityLevel;
  254. try {
  255. return eventHandler();
  256. } finally {
  257. currentPriorityLevel = previousPriorityLevel;
  258. }
  259. }
  260. function unstable_next(eventHandler) {
  261. var priorityLevel;
  262. switch (currentPriorityLevel) {
  263. case ImmediatePriority:
  264. case UserBlockingPriority:
  265. case NormalPriority:
  266. // Shift down to normal priority
  267. priorityLevel = NormalPriority;
  268. break;
  269. default:
  270. // Anything lower than normal priority should remain at the current level.
  271. priorityLevel = currentPriorityLevel;
  272. break;
  273. }
  274. var previousPriorityLevel = currentPriorityLevel;
  275. currentPriorityLevel = priorityLevel;
  276. try {
  277. return eventHandler();
  278. } finally {
  279. currentPriorityLevel = previousPriorityLevel;
  280. }
  281. }
  282. function unstable_wrapCallback(callback) {
  283. var parentPriorityLevel = currentPriorityLevel;
  284. return function () {
  285. // This is a fork of runWithPriority, inlined for performance.
  286. var previousPriorityLevel = currentPriorityLevel;
  287. currentPriorityLevel = parentPriorityLevel;
  288. try {
  289. return callback.apply(this, arguments);
  290. } finally {
  291. currentPriorityLevel = previousPriorityLevel;
  292. }
  293. };
  294. }
  295. function unstable_scheduleCallback(priorityLevel, callback, options) {
  296. var currentTime = exports.unstable_now();
  297. var startTime;
  298. if (typeof options === 'object' && options !== null) {
  299. var delay = options.delay;
  300. if (typeof delay === 'number' && delay > 0) {
  301. startTime = currentTime + delay;
  302. } else {
  303. startTime = currentTime;
  304. }
  305. } else {
  306. startTime = currentTime;
  307. }
  308. var timeout;
  309. switch (priorityLevel) {
  310. case ImmediatePriority:
  311. timeout = IMMEDIATE_PRIORITY_TIMEOUT;
  312. break;
  313. case UserBlockingPriority:
  314. timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
  315. break;
  316. case IdlePriority:
  317. timeout = IDLE_PRIORITY_TIMEOUT;
  318. break;
  319. case LowPriority:
  320. timeout = LOW_PRIORITY_TIMEOUT;
  321. break;
  322. case NormalPriority:
  323. default:
  324. timeout = NORMAL_PRIORITY_TIMEOUT;
  325. break;
  326. }
  327. var expirationTime = startTime + timeout;
  328. var newTask = {
  329. id: taskIdCounter++,
  330. callback: callback,
  331. priorityLevel: priorityLevel,
  332. startTime: startTime,
  333. expirationTime: expirationTime,
  334. sortIndex: -1
  335. };
  336. if (startTime > currentTime) {
  337. // This is a delayed task.
  338. newTask.sortIndex = startTime;
  339. push(timerQueue, newTask);
  340. if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
  341. // All tasks are delayed, and this is the task with the earliest delay.
  342. if (isHostTimeoutScheduled) {
  343. // Cancel an existing timeout.
  344. cancelHostTimeout();
  345. } else {
  346. isHostTimeoutScheduled = true;
  347. } // Schedule a timeout.
  348. requestHostTimeout(handleTimeout, startTime - currentTime);
  349. }
  350. } else {
  351. newTask.sortIndex = expirationTime;
  352. push(taskQueue, newTask);
  353. // wait until the next time we yield.
  354. if (!isHostCallbackScheduled && !isPerformingWork) {
  355. isHostCallbackScheduled = true;
  356. requestHostCallback(flushWork);
  357. }
  358. }
  359. return newTask;
  360. }
  361. function unstable_pauseExecution() {
  362. }
  363. function unstable_continueExecution() {
  364. if (!isHostCallbackScheduled && !isPerformingWork) {
  365. isHostCallbackScheduled = true;
  366. requestHostCallback(flushWork);
  367. }
  368. }
  369. function unstable_getFirstCallbackNode() {
  370. return peek(taskQueue);
  371. }
  372. function unstable_cancelCallback(task) {
  373. // remove from the queue because you can't remove arbitrary nodes from an
  374. // array based heap, only the first one.)
  375. task.callback = null;
  376. }
  377. function unstable_getCurrentPriorityLevel() {
  378. return currentPriorityLevel;
  379. }
  380. var isMessageLoopRunning = false;
  381. var scheduledHostCallback = null;
  382. var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main
  383. // thread, like user events. By default, it yields multiple times per frame.
  384. // It does not attempt to align with frame boundaries, since most tasks don't
  385. // need to be frame aligned; for those that do, use requestAnimationFrame.
  386. var frameInterval = frameYieldMs;
  387. var startTime = -1;
  388. function shouldYieldToHost() {
  389. var timeElapsed = exports.unstable_now() - startTime;
  390. if (timeElapsed < frameInterval) {
  391. // The main thread has only been blocked for a really short amount of time;
  392. // smaller than a single frame. Don't yield yet.
  393. return false;
  394. } // The main thread has been blocked for a non-negligible amount of time. We
  395. return true;
  396. }
  397. function requestPaint() {
  398. }
  399. function forceFrameRate(fps) {
  400. if (fps < 0 || fps > 125) {
  401. // Using console['error'] to evade Babel and ESLint
  402. console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported');
  403. return;
  404. }
  405. if (fps > 0) {
  406. frameInterval = Math.floor(1000 / fps);
  407. } else {
  408. // reset the framerate
  409. frameInterval = frameYieldMs;
  410. }
  411. }
  412. var performWorkUntilDeadline = function () {
  413. if (scheduledHostCallback !== null) {
  414. var currentTime = exports.unstable_now(); // Keep track of the start time so we can measure how long the main thread
  415. // has been blocked.
  416. startTime = currentTime;
  417. var hasTimeRemaining = true; // If a scheduler task throws, exit the current browser task so the
  418. // error can be observed.
  419. //
  420. // Intentionally not using a try-catch, since that makes some debugging
  421. // techniques harder. Instead, if `scheduledHostCallback` errors, then
  422. // `hasMoreWork` will remain true, and we'll continue the work loop.
  423. var hasMoreWork = true;
  424. try {
  425. hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
  426. } finally {
  427. if (hasMoreWork) {
  428. // If there's more work, schedule the next message event at the end
  429. // of the preceding one.
  430. schedulePerformWorkUntilDeadline();
  431. } else {
  432. isMessageLoopRunning = false;
  433. scheduledHostCallback = null;
  434. }
  435. }
  436. } else {
  437. isMessageLoopRunning = false;
  438. } // Yielding to the browser will give it a chance to paint, so we can
  439. };
  440. var schedulePerformWorkUntilDeadline;
  441. if (typeof localSetImmediate === 'function') {
  442. // Node.js and old IE.
  443. // There's a few reasons for why we prefer setImmediate.
  444. //
  445. // Unlike MessageChannel, it doesn't prevent a Node.js process from exiting.
  446. // (Even though this is a DOM fork of the Scheduler, you could get here
  447. // with a mix of Node.js 15+, which has a MessageChannel, and jsdom.)
  448. // https://github.com/facebook/react/issues/20756
  449. //
  450. // But also, it runs earlier which is the semantic we want.
  451. // If other browsers ever implement it, it's better to use it.
  452. // Although both of these would be inferior to native scheduling.
  453. schedulePerformWorkUntilDeadline = function () {
  454. localSetImmediate(performWorkUntilDeadline);
  455. };
  456. } else if (typeof MessageChannel !== 'undefined') {
  457. // DOM and Worker environments.
  458. // We prefer MessageChannel because of the 4ms setTimeout clamping.
  459. var channel = new MessageChannel();
  460. var port = channel.port2;
  461. channel.port1.onmessage = performWorkUntilDeadline;
  462. schedulePerformWorkUntilDeadline = function () {
  463. port.postMessage(null);
  464. };
  465. } else {
  466. // We should only fallback here in non-browser environments.
  467. schedulePerformWorkUntilDeadline = function () {
  468. localSetTimeout(performWorkUntilDeadline, 0);
  469. };
  470. }
  471. function requestHostCallback(callback) {
  472. scheduledHostCallback = callback;
  473. if (!isMessageLoopRunning) {
  474. isMessageLoopRunning = true;
  475. schedulePerformWorkUntilDeadline();
  476. }
  477. }
  478. function requestHostTimeout(callback, ms) {
  479. taskTimeoutID = localSetTimeout(function () {
  480. callback(exports.unstable_now());
  481. }, ms);
  482. }
  483. function cancelHostTimeout() {
  484. localClearTimeout(taskTimeoutID);
  485. taskTimeoutID = -1;
  486. }
  487. var unstable_requestPaint = requestPaint;
  488. var unstable_Profiling = null;
  489. exports.unstable_IdlePriority = IdlePriority;
  490. exports.unstable_ImmediatePriority = ImmediatePriority;
  491. exports.unstable_LowPriority = LowPriority;
  492. exports.unstable_NormalPriority = NormalPriority;
  493. exports.unstable_Profiling = unstable_Profiling;
  494. exports.unstable_UserBlockingPriority = UserBlockingPriority;
  495. exports.unstable_cancelCallback = unstable_cancelCallback;
  496. exports.unstable_continueExecution = unstable_continueExecution;
  497. exports.unstable_forceFrameRate = forceFrameRate;
  498. exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
  499. exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode;
  500. exports.unstable_next = unstable_next;
  501. exports.unstable_pauseExecution = unstable_pauseExecution;
  502. exports.unstable_requestPaint = unstable_requestPaint;
  503. exports.unstable_runWithPriority = unstable_runWithPriority;
  504. exports.unstable_scheduleCallback = unstable_scheduleCallback;
  505. exports.unstable_shouldYield = shouldYieldToHost;
  506. exports.unstable_wrapCallback = unstable_wrapCallback;
  507. /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
  508. if (
  509. typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
  510. typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
  511. 'function'
  512. ) {
  513. __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
  514. }
  515. })();
  516. }