scheduler.development.js 17 KB

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