UNPKG

595 kBJavaScriptView Raw
1/** @license React v16.9.0-alpha.0
2 * react-test-renderer.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
10'use strict';
11
12(function (global, factory) {
13 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react'), require('scheduler/unstable_mock'), require('scheduler')) :
14 typeof define === 'function' && define.amd ? define(['react', 'scheduler/unstable_mock', 'scheduler'], factory) :
15 (global.ReactTestRenderer = factory(global.React,global.SchedulerMock,global.Scheduler));
16}(this, (function (React,Scheduler,Scheduler$1) { 'use strict';
17
18// Do not require this module directly! Use a normal error constructor with
19// template literal strings. The messages will be converted to ReactError during
20// build, and in production they will be minified.
21
22// Do not require this module directly! Use a normal error constructor with
23// template literal strings. The messages will be converted to ReactError during
24// build, and in production they will be minified.
25
26function ReactError(message) {
27 var error = new Error(message);
28 error.name = 'Invariant Violation';
29 return error;
30}
31
32var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
33
34var _assign = ReactInternals.assign;
35
36/**
37 * Use invariant() to assert state which your program assumes to be true.
38 *
39 * Provide sprintf-style format (only %s is supported) and arguments
40 * to provide information about what broke and what you were
41 * expecting.
42 *
43 * The invariant message will be stripped in production, but the invariant
44 * will remain to ensure logic does not differ in production.
45 */
46
47/**
48 * Similar to invariant but only logs a warning if the condition is not met.
49 * This can be used to log issues in development environments in critical
50 * paths. Removing the logging code for production environments will keep the
51 * same logic and follow the same code paths.
52 */
53
54var warningWithoutStack = function () {};
55
56{
57 warningWithoutStack = function (condition, format) {
58 for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
59 args[_key - 2] = arguments[_key];
60 }
61
62 if (format === undefined) {
63 throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
64 }
65 if (args.length > 8) {
66 // Check before the condition to catch violations early.
67 throw new Error('warningWithoutStack() currently supports at most 8 arguments.');
68 }
69 if (condition) {
70 return;
71 }
72 if (typeof console !== 'undefined') {
73 var argsWithFormat = args.map(function (item) {
74 return '' + item;
75 });
76 argsWithFormat.unshift('Warning: ' + format);
77
78 // We intentionally don't use spread (or .apply) directly because it
79 // breaks IE9: https://github.com/facebook/react/issues/13610
80 Function.prototype.apply.call(console.error, console, argsWithFormat);
81 }
82 try {
83 // --- Welcome to debugging React ---
84 // This error was thrown as a convenience so that you can use this stack
85 // to find the callsite that caused this warning to fire.
86 var argIndex = 0;
87 var message = 'Warning: ' + format.replace(/%s/g, function () {
88 return args[argIndex++];
89 });
90 throw new Error(message);
91 } catch (x) {}
92 };
93}
94
95var warningWithoutStack$1 = warningWithoutStack;
96
97/**
98 * `ReactInstanceMap` maintains a mapping from a public facing stateful
99 * instance (key) and the internal representation (value). This allows public
100 * methods to accept the user facing instance as an argument and map them back
101 * to internal methods.
102 *
103 * Note that this module is currently shared and assumed to be stateless.
104 * If this becomes an actual Map, that will break.
105 */
106
107/**
108 * This API should be called `delete` but we'd have to make sure to always
109 * transform these to strings for IE support. When this transform is fully
110 * supported we can rename it.
111 */
112
113
114function get(key) {
115 return key._reactInternalFiber;
116}
117
118
119
120function set(key, value) {
121 key._reactInternalFiber = value;
122}
123
124var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
125
126// Prevent newer renderers from RTE when used with older react package versions.
127// Current owner and dispatcher used to share the same ref,
128// but PR #14548 split them out to better support the react-debug-tools package.
129if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {
130 ReactSharedInternals.ReactCurrentDispatcher = {
131 current: null
132 };
133}
134
135// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
136// nor polyfill, then a plain number is used for performance.
137var hasSymbol = typeof Symbol === 'function' && Symbol.for;
138
139var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
140var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
141var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
142var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
143var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
144var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
145var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
146
147var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
148var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
149var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
150var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
151var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
152var REACT_EVENT_COMPONENT_TYPE = hasSymbol ? Symbol.for('react.event_component') : 0xead5;
153var REACT_EVENT_TARGET_TYPE = hasSymbol ? Symbol.for('react.event_target') : 0xead6;
154
155// React event targets
156var REACT_EVENT_TARGET_TOUCH_HIT = hasSymbol ? Symbol.for('react.event_target.touch_hit') : 0xead7;
157
158var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
159var FAUX_ITERATOR_SYMBOL = '@@iterator';
160
161function getIteratorFn(maybeIterable) {
162 if (maybeIterable === null || typeof maybeIterable !== 'object') {
163 return null;
164 }
165 var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
166 if (typeof maybeIterator === 'function') {
167 return maybeIterator;
168 }
169 return null;
170}
171
172var Pending = 0;
173var Resolved = 1;
174var Rejected = 2;
175
176function refineResolvedLazyComponent(lazyComponent) {
177 return lazyComponent._status === Resolved ? lazyComponent._result : null;
178}
179
180function getWrappedName(outerType, innerType, wrapperName) {
181 var functionName = innerType.displayName || innerType.name || '';
182 return outerType.displayName || (functionName !== '' ? wrapperName + '(' + functionName + ')' : wrapperName);
183}
184
185function getComponentName(type) {
186 if (type == null) {
187 // Host root, text node or just invalid type.
188 return null;
189 }
190 {
191 if (typeof type.tag === 'number') {
192 warningWithoutStack$1(false, 'Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
193 }
194 }
195 if (typeof type === 'function') {
196 return type.displayName || type.name || null;
197 }
198 if (typeof type === 'string') {
199 return type;
200 }
201 switch (type) {
202 case REACT_CONCURRENT_MODE_TYPE:
203 return 'ConcurrentMode';
204 case REACT_FRAGMENT_TYPE:
205 return 'Fragment';
206 case REACT_PORTAL_TYPE:
207 return 'Portal';
208 case REACT_PROFILER_TYPE:
209 return 'Profiler';
210 case REACT_STRICT_MODE_TYPE:
211 return 'StrictMode';
212 case REACT_SUSPENSE_TYPE:
213 return 'Suspense';
214 }
215 if (typeof type === 'object') {
216 switch (type.$$typeof) {
217 case REACT_CONTEXT_TYPE:
218 return 'Context.Consumer';
219 case REACT_PROVIDER_TYPE:
220 return 'Context.Provider';
221 case REACT_FORWARD_REF_TYPE:
222 return getWrappedName(type, type.render, 'ForwardRef');
223 case REACT_MEMO_TYPE:
224 return getComponentName(type.type);
225 case REACT_LAZY_TYPE:
226 {
227 var thenable = type;
228 var resolvedThenable = refineResolvedLazyComponent(thenable);
229 if (resolvedThenable) {
230 return getComponentName(resolvedThenable);
231 }
232 break;
233 }
234 case REACT_EVENT_COMPONENT_TYPE:
235 {
236 var eventComponent = type;
237 var displayName = eventComponent.displayName;
238 if (displayName !== undefined) {
239 return displayName;
240 }
241 break;
242 }
243 case REACT_EVENT_TARGET_TYPE:
244 {
245 var eventTarget = type;
246 if (eventTarget.type === REACT_EVENT_TARGET_TOUCH_HIT) {
247 return 'TouchHitTarget';
248 }
249 var _displayName = eventTarget.displayName;
250 if (_displayName !== undefined) {
251 return _displayName;
252 }
253 }
254 }
255 }
256 return null;
257}
258
259var FunctionComponent = 0;
260var ClassComponent = 1;
261var IndeterminateComponent = 2; // Before we know whether it is function or class
262var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
263var HostPortal = 4; // A subtree. Could be an entry point to a different renderer.
264var HostComponent = 5;
265var HostText = 6;
266var Fragment = 7;
267var Mode = 8;
268var ContextConsumer = 9;
269var ContextProvider = 10;
270var ForwardRef = 11;
271var Profiler = 12;
272var SuspenseComponent = 13;
273var MemoComponent = 14;
274var SimpleMemoComponent = 15;
275var LazyComponent = 16;
276var IncompleteClassComponent = 17;
277var DehydratedSuspenseComponent = 18;
278var EventComponent = 19;
279var EventTarget = 20;
280
281// Don't change these two values. They're used by React Dev Tools.
282var NoEffect = /* */0;
283var PerformedWork = /* */1;
284
285// You can change the rest (and add more).
286var Placement = /* */2;
287var Update = /* */4;
288var PlacementAndUpdate = /* */6;
289var Deletion = /* */8;
290var ContentReset = /* */16;
291var Callback = /* */32;
292var DidCapture = /* */64;
293var Ref = /* */128;
294var Snapshot = /* */256;
295var Passive = /* */512;
296
297// Passive & Update & Callback & Ref & Snapshot
298var LifecycleEffectMask = /* */932;
299
300// Union of all host effects
301var HostEffectMask = /* */1023;
302
303var Incomplete = /* */1024;
304var ShouldCapture = /* */2048;
305
306var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
307
308var MOUNTING = 1;
309var MOUNTED = 2;
310var UNMOUNTED = 3;
311
312function isFiberMountedImpl(fiber) {
313 var node = fiber;
314 if (!fiber.alternate) {
315 // If there is no alternate, this might be a new tree that isn't inserted
316 // yet. If it is, then it will have a pending insertion effect on it.
317 if ((node.effectTag & Placement) !== NoEffect) {
318 return MOUNTING;
319 }
320 while (node.return) {
321 node = node.return;
322 if ((node.effectTag & Placement) !== NoEffect) {
323 return MOUNTING;
324 }
325 }
326 } else {
327 while (node.return) {
328 node = node.return;
329 }
330 }
331 if (node.tag === HostRoot) {
332 // TODO: Check if this was a nested HostRoot when used with
333 // renderContainerIntoSubtree.
334 return MOUNTED;
335 }
336 // If we didn't hit the root, that means that we're in an disconnected tree
337 // that has been unmounted.
338 return UNMOUNTED;
339}
340
341function isFiberMounted(fiber) {
342 return isFiberMountedImpl(fiber) === MOUNTED;
343}
344
345function isMounted(component) {
346 {
347 var owner = ReactCurrentOwner.current;
348 if (owner !== null && owner.tag === ClassComponent) {
349 var ownerFiber = owner;
350 var instance = ownerFiber.stateNode;
351 !instance._warnedAboutRefsInRender ? warningWithoutStack$1(false, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(ownerFiber.type) || 'A component') : void 0;
352 instance._warnedAboutRefsInRender = true;
353 }
354 }
355
356 var fiber = get(component);
357 if (!fiber) {
358 return false;
359 }
360 return isFiberMountedImpl(fiber) === MOUNTED;
361}
362
363function assertIsMounted(fiber) {
364 (function () {
365 if (!(isFiberMountedImpl(fiber) === MOUNTED)) {
366 {
367 throw ReactError('Unable to find node on an unmounted component.');
368 }
369 }
370 })();
371}
372
373function findCurrentFiberUsingSlowPath(fiber) {
374 var alternate = fiber.alternate;
375 if (!alternate) {
376 // If there is no alternate, then we only need to check if it is mounted.
377 var state = isFiberMountedImpl(fiber);
378 (function () {
379 if (!(state !== UNMOUNTED)) {
380 {
381 throw ReactError('Unable to find node on an unmounted component.');
382 }
383 }
384 })();
385 if (state === MOUNTING) {
386 return null;
387 }
388 return fiber;
389 }
390 // If we have two possible branches, we'll walk backwards up to the root
391 // to see what path the root points to. On the way we may hit one of the
392 // special cases and we'll deal with them.
393 var a = fiber;
394 var b = alternate;
395 while (true) {
396 var parentA = a.return;
397 var parentB = parentA ? parentA.alternate : null;
398 if (!parentA || !parentB) {
399 // We're at the root.
400 break;
401 }
402
403 // If both copies of the parent fiber point to the same child, we can
404 // assume that the child is current. This happens when we bailout on low
405 // priority: the bailed out fiber's child reuses the current child.
406 if (parentA.child === parentB.child) {
407 var child = parentA.child;
408 while (child) {
409 if (child === a) {
410 // We've determined that A is the current branch.
411 assertIsMounted(parentA);
412 return fiber;
413 }
414 if (child === b) {
415 // We've determined that B is the current branch.
416 assertIsMounted(parentA);
417 return alternate;
418 }
419 child = child.sibling;
420 }
421 // We should never have an alternate for any mounting node. So the only
422 // way this could possibly happen is if this was unmounted, if at all.
423 (function () {
424 {
425 {
426 throw ReactError('Unable to find node on an unmounted component.');
427 }
428 }
429 })();
430 }
431
432 if (a.return !== b.return) {
433 // The return pointer of A and the return pointer of B point to different
434 // fibers. We assume that return pointers never criss-cross, so A must
435 // belong to the child set of A.return, and B must belong to the child
436 // set of B.return.
437 a = parentA;
438 b = parentB;
439 } else {
440 // The return pointers point to the same fiber. We'll have to use the
441 // default, slow path: scan the child sets of each parent alternate to see
442 // which child belongs to which set.
443 //
444 // Search parent A's child set
445 var didFindChild = false;
446 var _child = parentA.child;
447 while (_child) {
448 if (_child === a) {
449 didFindChild = true;
450 a = parentA;
451 b = parentB;
452 break;
453 }
454 if (_child === b) {
455 didFindChild = true;
456 b = parentA;
457 a = parentB;
458 break;
459 }
460 _child = _child.sibling;
461 }
462 if (!didFindChild) {
463 // Search parent B's child set
464 _child = parentB.child;
465 while (_child) {
466 if (_child === a) {
467 didFindChild = true;
468 a = parentB;
469 b = parentA;
470 break;
471 }
472 if (_child === b) {
473 didFindChild = true;
474 b = parentB;
475 a = parentA;
476 break;
477 }
478 _child = _child.sibling;
479 }
480 (function () {
481 if (!didFindChild) {
482 {
483 throw ReactError('Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.');
484 }
485 }
486 })();
487 }
488 }
489
490 (function () {
491 if (!(a.alternate === b)) {
492 {
493 throw ReactError('Return fibers should always be each others\' alternates. This error is likely caused by a bug in React. Please file an issue.');
494 }
495 }
496 })();
497 }
498 // If the root is not a host container, we're in a disconnected tree. I.e.
499 // unmounted.
500 (function () {
501 if (!(a.tag === HostRoot)) {
502 {
503 throw ReactError('Unable to find node on an unmounted component.');
504 }
505 }
506 })();
507 if (a.stateNode.current === a) {
508 // We've determined that A is the current branch.
509 return fiber;
510 }
511 // Otherwise B has to be current branch.
512 return alternate;
513}
514
515function findCurrentHostFiber(parent) {
516 var currentParent = findCurrentFiberUsingSlowPath(parent);
517 if (!currentParent) {
518 return null;
519 }
520
521 // Next we'll drill down this component to find the first HostComponent/Text.
522 var node = currentParent;
523 while (true) {
524 if (node.tag === HostComponent || node.tag === HostText) {
525 return node;
526 } else if (node.child) {
527 node.child.return = node;
528 node = node.child;
529 continue;
530 }
531 if (node === currentParent) {
532 return null;
533 }
534 while (!node.sibling) {
535 if (!node.return || node.return === currentParent) {
536 return null;
537 }
538 node = node.return;
539 }
540 node.sibling.return = node.return;
541 node = node.sibling;
542 }
543 // Flow needs the return null here, but ESLint complains about it.
544 // eslint-disable-next-line no-unreachable
545 return null;
546}
547
548/**
549 * Similar to invariant but only logs a warning if the condition is not met.
550 * This can be used to log issues in development environments in critical
551 * paths. Removing the logging code for production environments will keep the
552 * same logic and follow the same code paths.
553 */
554
555var warning = warningWithoutStack$1;
556
557{
558 warning = function (condition, format) {
559 if (condition) {
560 return;
561 }
562 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
563 var stack = ReactDebugCurrentFrame.getStackAddendum();
564 // eslint-disable-next-line react-internal/warning-and-invariant-args
565
566 for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
567 args[_key - 2] = arguments[_key];
568 }
569
570 warningWithoutStack$1.apply(undefined, [false, format + '%s'].concat(args, [stack]));
571 };
572}
573
574var warning$1 = warning;
575
576var debugRenderPhaseSideEffects = false;
577var debugRenderPhaseSideEffectsForStrictMode = false;
578var enableUserTimingAPI = true;
579var warnAboutDeprecatedLifecycles = false;
580var replayFailedUnitOfWorkWithInvokeGuardedCallback = false;
581var enableProfilerTimer = false;
582var enableSchedulerTracing = false;
583var enableSuspenseServerRenderer = false;
584
585var disableYielding = false;
586
587
588
589
590
591var enableEventAPI = false;
592var enableNewScheduler = false;
593
594// Only used in www builds.
595
596// Renderers that don't support persistence
597// can re-export everything from this module.
598
599function shim() {
600 (function () {
601 {
602 {
603 throw ReactError('The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue.');
604 }
605 }
606 })();
607}
608
609// Persistence (when unsupported)
610var supportsPersistence = false;
611var cloneInstance = shim;
612var createContainerChildSet = shim;
613var appendChildToContainerChildSet = shim;
614var finalizeContainerChildren = shim;
615var replaceContainerChildren = shim;
616var cloneHiddenInstance = shim;
617var cloneHiddenTextInstance = shim;
618
619// Renderers that don't support hydration
620// can re-export everything from this module.
621
622function shim$1() {
623 (function () {
624 {
625 {
626 throw ReactError('The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue.');
627 }
628 }
629 })();
630}
631
632// Hydration (when unsupported)
633
634var supportsHydration = false;
635var canHydrateInstance = shim$1;
636var canHydrateTextInstance = shim$1;
637var canHydrateSuspenseInstance = shim$1;
638var isSuspenseInstancePending = shim$1;
639var isSuspenseInstanceFallback = shim$1;
640var registerSuspenseInstanceRetry = shim$1;
641var getNextHydratableSibling = shim$1;
642var getFirstHydratableChild = shim$1;
643var hydrateInstance = shim$1;
644var hydrateTextInstance = shim$1;
645var getNextHydratableInstanceAfterSuspenseInstance = shim$1;
646var clearSuspenseBoundary = shim$1;
647var clearSuspenseBoundaryFromContainer = shim$1;
648var didNotMatchHydratedContainerTextInstance = shim$1;
649var didNotMatchHydratedTextInstance = shim$1;
650var didNotHydrateContainerInstance = shim$1;
651var didNotHydrateInstance = shim$1;
652var didNotFindHydratableContainerInstance = shim$1;
653var didNotFindHydratableContainerTextInstance = shim$1;
654var didNotFindHydratableContainerSuspenseInstance = shim$1;
655var didNotFindHydratableInstance = shim$1;
656var didNotFindHydratableTextInstance = shim$1;
657var didNotFindHydratableSuspenseInstance = shim$1;
658
659var EVENT_COMPONENT_CONTEXT = {};
660var EVENT_TARGET_CONTEXT = {};
661var EVENT_TOUCH_HIT_TARGET_CONTEXT = {};
662var NO_CONTEXT = {};
663var UPDATE_SIGNAL = {};
664{
665 Object.freeze(NO_CONTEXT);
666 Object.freeze(UPDATE_SIGNAL);
667}
668
669function getPublicInstance(inst) {
670 switch (inst.tag) {
671 case 'INSTANCE':
672 var _createNodeMock = inst.rootContainerInstance.createNodeMock;
673 return _createNodeMock({
674 type: inst.type,
675 props: inst.props
676 });
677 default:
678 return inst;
679 }
680}
681
682function appendChild(parentInstance, child) {
683 {
684 !Array.isArray(parentInstance.children) ? warning$1(false, 'An invalid container has been provided. ' + 'This may indicate that another renderer is being used in addition to the test renderer. ' + '(For example, ReactDOM.createPortal inside of a ReactTestRenderer tree.) ' + 'This is not supported.') : void 0;
685 }
686 var index = parentInstance.children.indexOf(child);
687 if (index !== -1) {
688 parentInstance.children.splice(index, 1);
689 }
690 parentInstance.children.push(child);
691}
692
693function insertBefore(parentInstance, child, beforeChild) {
694 var index = parentInstance.children.indexOf(child);
695 if (index !== -1) {
696 parentInstance.children.splice(index, 1);
697 }
698 var beforeIndex = parentInstance.children.indexOf(beforeChild);
699 parentInstance.children.splice(beforeIndex, 0, child);
700}
701
702function removeChild(parentInstance, child) {
703 var index = parentInstance.children.indexOf(child);
704 parentInstance.children.splice(index, 1);
705}
706
707function getRootHostContext(rootContainerInstance) {
708 return NO_CONTEXT;
709}
710
711function getChildHostContext(parentHostContext, type, rootContainerInstance) {
712 return NO_CONTEXT;
713}
714
715function getChildHostContextForEventComponent(parentHostContext) {
716 if (true && enableEventAPI) {
717 !(parentHostContext !== EVENT_TARGET_CONTEXT && parentHostContext !== EVENT_TOUCH_HIT_TARGET_CONTEXT) ? warning$1(false, 'validateDOMNesting: React event targets must not have event components as children.') : void 0;
718 return EVENT_COMPONENT_CONTEXT;
719 }
720 return NO_CONTEXT;
721}
722
723function getChildHostContextForEventTarget(parentHostContext, type) {
724 if (true && enableEventAPI) {
725 if (type === REACT_EVENT_TARGET_TOUCH_HIT) {
726 !(parentHostContext !== EVENT_COMPONENT_CONTEXT) ? warning$1(false, 'validateDOMNesting: <TouchHitTarget> cannot not be a direct child of an event component. ' + 'Ensure <TouchHitTarget> is a direct child of a DOM element.') : void 0;
727 return EVENT_TOUCH_HIT_TARGET_CONTEXT;
728 }
729 return EVENT_TARGET_CONTEXT;
730 }
731 return NO_CONTEXT;
732}
733
734function prepareForCommit(containerInfo) {
735 // noop
736}
737
738function resetAfterCommit(containerInfo) {
739 // noop
740}
741
742function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
743 if (true && enableEventAPI) {
744 !(hostContext !== EVENT_TOUCH_HIT_TARGET_CONTEXT) ? warning$1(false, 'validateDOMNesting: <TouchHitTarget> must not have any children.') : void 0;
745 }
746 return {
747 type: type,
748 props: props,
749 isHidden: false,
750 children: [],
751 rootContainerInstance: rootContainerInstance,
752 tag: 'INSTANCE'
753 };
754}
755
756function appendInitialChild(parentInstance, child) {
757 var index = parentInstance.children.indexOf(child);
758 if (index !== -1) {
759 parentInstance.children.splice(index, 1);
760 }
761 parentInstance.children.push(child);
762}
763
764function finalizeInitialChildren(testElement, type, props, rootContainerInstance, hostContext) {
765 return false;
766}
767
768function prepareUpdate(testElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
769 return UPDATE_SIGNAL;
770}
771
772function shouldSetTextContent(type, props) {
773 return false;
774}
775
776function shouldDeprioritizeSubtree(type, props) {
777 return false;
778}
779
780function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
781 if (true && enableEventAPI) {
782 !(hostContext !== EVENT_TOUCH_HIT_TARGET_CONTEXT) ? warning$1(false, 'validateDOMNesting: <TouchHitTarget> must not have any children.') : void 0;
783 !(hostContext !== EVENT_COMPONENT_CONTEXT) ? warning$1(false, 'validateDOMNesting: React event components cannot have text DOM nodes as children. ' + 'Wrap the child text "%s" in an element.', text) : void 0;
784 !(hostContext !== EVENT_TARGET_CONTEXT) ? warning$1(false, 'validateDOMNesting: React event targets cannot have text DOM nodes as children. ' + 'Wrap the child text "%s" in an element.', text) : void 0;
785 }
786 return {
787 text: text,
788 isHidden: false,
789 tag: 'TEXT'
790 };
791}
792
793var isPrimaryRenderer = false;
794
795var scheduleTimeout = setTimeout;
796var cancelTimeout = clearTimeout;
797var noTimeout = -1;
798
799// -------------------
800// Mutation
801// -------------------
802
803var supportsMutation = true;
804
805function commitUpdate(instance, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
806 instance.type = type;
807 instance.props = newProps;
808}
809
810
811
812function commitTextUpdate(textInstance, oldText, newText) {
813 textInstance.text = newText;
814}
815
816function resetTextContent(testElement) {
817 // noop
818}
819
820var appendChildToContainer = appendChild;
821var insertInContainerBefore = insertBefore;
822var removeChildFromContainer = removeChild;
823
824function hideInstance(instance) {
825 instance.isHidden = true;
826}
827
828function hideTextInstance(textInstance) {
829 textInstance.isHidden = true;
830}
831
832function unhideInstance(instance, props) {
833 instance.isHidden = false;
834}
835
836function unhideTextInstance(textInstance, text) {
837 textInstance.isHidden = false;
838}
839
840/**
841 * Copyright (c) 2013-present, Facebook, Inc.
842 *
843 * This source code is licensed under the MIT license found in the
844 * LICENSE file in the root directory of this source tree.
845 */
846
847
848
849var ReactPropTypesSecret$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
850
851var ReactPropTypesSecret_1 = ReactPropTypesSecret$1;
852
853/**
854 * Copyright (c) 2013-present, Facebook, Inc.
855 *
856 * This source code is licensed under the MIT license found in the
857 * LICENSE file in the root directory of this source tree.
858 */
859
860
861
862var printWarning = function() {};
863
864{
865 var ReactPropTypesSecret = ReactPropTypesSecret_1;
866 var loggedTypeFailures = {};
867
868 printWarning = function(text) {
869 var message = 'Warning: ' + text;
870 if (typeof console !== 'undefined') {
871 console.error(message);
872 }
873 try {
874 // --- Welcome to debugging React ---
875 // This error was thrown as a convenience so that you can use this stack
876 // to find the callsite that caused this warning to fire.
877 throw new Error(message);
878 } catch (x) {}
879 };
880}
881
882/**
883 * Assert that the values match with the type specs.
884 * Error messages are memorized and will only be shown once.
885 *
886 * @param {object} typeSpecs Map of name to a ReactPropType
887 * @param {object} values Runtime values that need to be type-checked
888 * @param {string} location e.g. "prop", "context", "child context"
889 * @param {string} componentName Name of the component for error messages.
890 * @param {?Function} getStack Returns the component stack.
891 * @private
892 */
893function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
894 {
895 for (var typeSpecName in typeSpecs) {
896 if (typeSpecs.hasOwnProperty(typeSpecName)) {
897 var error;
898 // Prop type validation may throw. In case they do, we don't want to
899 // fail the render phase where it didn't fail before. So we log it.
900 // After these have been cleaned up, we'll let them throw.
901 try {
902 // This is intentionally an invariant that gets caught. It's the same
903 // behavior as without this statement except with a better message.
904 if (typeof typeSpecs[typeSpecName] !== 'function') {
905 var err = Error(
906 (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
907 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
908 );
909 err.name = 'Invariant Violation';
910 throw err;
911 }
912 error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
913 } catch (ex) {
914 error = ex;
915 }
916 if (error && !(error instanceof Error)) {
917 printWarning(
918 (componentName || 'React class') + ': type specification of ' +
919 location + ' `' + typeSpecName + '` is invalid; the type checker ' +
920 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
921 'You may have forgotten to pass an argument to the type checker ' +
922 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
923 'shape all require an argument).'
924 );
925
926 }
927 if (error instanceof Error && !(error.message in loggedTypeFailures)) {
928 // Only monitor this failure once because there tends to be a lot of the
929 // same error.
930 loggedTypeFailures[error.message] = true;
931
932 var stack = getStack ? getStack() : '';
933
934 printWarning(
935 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
936 );
937 }
938 }
939 }
940 }
941}
942
943var checkPropTypes_1 = checkPropTypes;
944
945var BEFORE_SLASH_RE = /^(.*)[\\\/]/;
946
947var describeComponentFrame = function (name, source, ownerName) {
948 var sourceInfo = '';
949 if (source) {
950 var path = source.fileName;
951 var fileName = path.replace(BEFORE_SLASH_RE, '');
952 {
953 // In DEV, include code for a common special case:
954 // prefer "folder/index.js" instead of just "index.js".
955 if (/^index\./.test(fileName)) {
956 var match = path.match(BEFORE_SLASH_RE);
957 if (match) {
958 var pathBeforeSlash = match[1];
959 if (pathBeforeSlash) {
960 var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
961 fileName = folderName + '/' + fileName;
962 }
963 }
964 }
965 }
966 sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
967 } else if (ownerName) {
968 sourceInfo = ' (created by ' + ownerName + ')';
969 }
970 return '\n in ' + (name || 'Unknown') + sourceInfo;
971};
972
973var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
974
975function describeFiber(fiber) {
976 switch (fiber.tag) {
977 case HostRoot:
978 case HostPortal:
979 case HostText:
980 case Fragment:
981 case ContextProvider:
982 case ContextConsumer:
983 return '';
984 default:
985 var owner = fiber._debugOwner;
986 var source = fiber._debugSource;
987 var name = getComponentName(fiber.type);
988 var ownerName = null;
989 if (owner) {
990 ownerName = getComponentName(owner.type);
991 }
992 return describeComponentFrame(name, source, ownerName);
993 }
994}
995
996function getStackByFiberInDevAndProd(workInProgress) {
997 var info = '';
998 var node = workInProgress;
999 do {
1000 info += describeFiber(node);
1001 node = node.return;
1002 } while (node);
1003 return info;
1004}
1005
1006var current = null;
1007var phase = null;
1008
1009function getCurrentFiberOwnerNameInDevOrNull() {
1010 {
1011 if (current === null) {
1012 return null;
1013 }
1014 var owner = current._debugOwner;
1015 if (owner !== null && typeof owner !== 'undefined') {
1016 return getComponentName(owner.type);
1017 }
1018 }
1019 return null;
1020}
1021
1022function getCurrentFiberStackInDev() {
1023 {
1024 if (current === null) {
1025 return '';
1026 }
1027 // Safe because if current fiber exists, we are reconciling,
1028 // and it is guaranteed to be the work-in-progress version.
1029 return getStackByFiberInDevAndProd(current);
1030 }
1031 return '';
1032}
1033
1034function resetCurrentFiber() {
1035 {
1036 ReactDebugCurrentFrame.getCurrentStack = null;
1037 current = null;
1038 phase = null;
1039 }
1040}
1041
1042function setCurrentFiber(fiber) {
1043 {
1044 ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev;
1045 current = fiber;
1046 phase = null;
1047 }
1048}
1049
1050function setCurrentPhase(lifeCyclePhase) {
1051 {
1052 phase = lifeCyclePhase;
1053 }
1054}
1055
1056// Prefix measurements so that it's possible to filter them.
1057// Longer prefixes are hard to read in DevTools.
1058var reactEmoji = '\u269B';
1059var warningEmoji = '\u26D4';
1060var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function';
1061
1062// Keep track of current fiber so that we know the path to unwind on pause.
1063// TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them?
1064var currentFiber = null;
1065// If we're in the middle of user code, which fiber and method is it?
1066// Reusing `currentFiber` would be confusing for this because user code fiber
1067// can change during commit phase too, but we don't need to unwind it (since
1068// lifecycles in the commit phase don't resemble a tree).
1069var currentPhase = null;
1070var currentPhaseFiber = null;
1071// Did lifecycle hook schedule an update? This is often a performance problem,
1072// so we will keep track of it, and include it in the report.
1073// Track commits caused by cascading updates.
1074var isCommitting = false;
1075var hasScheduledUpdateInCurrentCommit = false;
1076var hasScheduledUpdateInCurrentPhase = false;
1077var commitCountInCurrentWorkLoop = 0;
1078var effectCountInCurrentCommit = 0;
1079var isWaitingForCallback = false;
1080// During commits, we only show a measurement once per method name
1081// to avoid stretch the commit phase with measurement overhead.
1082var labelsInCurrentCommit = new Set();
1083
1084var formatMarkName = function (markName) {
1085 return reactEmoji + ' ' + markName;
1086};
1087
1088var formatLabel = function (label, warning) {
1089 var prefix = warning ? warningEmoji + ' ' : reactEmoji + ' ';
1090 var suffix = warning ? ' Warning: ' + warning : '';
1091 return '' + prefix + label + suffix;
1092};
1093
1094var beginMark = function (markName) {
1095 performance.mark(formatMarkName(markName));
1096};
1097
1098var clearMark = function (markName) {
1099 performance.clearMarks(formatMarkName(markName));
1100};
1101
1102var endMark = function (label, markName, warning) {
1103 var formattedMarkName = formatMarkName(markName);
1104 var formattedLabel = formatLabel(label, warning);
1105 try {
1106 performance.measure(formattedLabel, formattedMarkName);
1107 } catch (err) {}
1108 // If previous mark was missing for some reason, this will throw.
1109 // This could only happen if React crashed in an unexpected place earlier.
1110 // Don't pile on with more errors.
1111
1112 // Clear marks immediately to avoid growing buffer.
1113 performance.clearMarks(formattedMarkName);
1114 performance.clearMeasures(formattedLabel);
1115};
1116
1117var getFiberMarkName = function (label, debugID) {
1118 return label + ' (#' + debugID + ')';
1119};
1120
1121var getFiberLabel = function (componentName, isMounted, phase) {
1122 if (phase === null) {
1123 // These are composite component total time measurements.
1124 return componentName + ' [' + (isMounted ? 'update' : 'mount') + ']';
1125 } else {
1126 // Composite component methods.
1127 return componentName + '.' + phase;
1128 }
1129};
1130
1131var beginFiberMark = function (fiber, phase) {
1132 var componentName = getComponentName(fiber.type) || 'Unknown';
1133 var debugID = fiber._debugID;
1134 var isMounted = fiber.alternate !== null;
1135 var label = getFiberLabel(componentName, isMounted, phase);
1136
1137 if (isCommitting && labelsInCurrentCommit.has(label)) {
1138 // During the commit phase, we don't show duplicate labels because
1139 // there is a fixed overhead for every measurement, and we don't
1140 // want to stretch the commit phase beyond necessary.
1141 return false;
1142 }
1143 labelsInCurrentCommit.add(label);
1144
1145 var markName = getFiberMarkName(label, debugID);
1146 beginMark(markName);
1147 return true;
1148};
1149
1150var clearFiberMark = function (fiber, phase) {
1151 var componentName = getComponentName(fiber.type) || 'Unknown';
1152 var debugID = fiber._debugID;
1153 var isMounted = fiber.alternate !== null;
1154 var label = getFiberLabel(componentName, isMounted, phase);
1155 var markName = getFiberMarkName(label, debugID);
1156 clearMark(markName);
1157};
1158
1159var endFiberMark = function (fiber, phase, warning) {
1160 var componentName = getComponentName(fiber.type) || 'Unknown';
1161 var debugID = fiber._debugID;
1162 var isMounted = fiber.alternate !== null;
1163 var label = getFiberLabel(componentName, isMounted, phase);
1164 var markName = getFiberMarkName(label, debugID);
1165 endMark(label, markName, warning);
1166};
1167
1168var shouldIgnoreFiber = function (fiber) {
1169 // Host components should be skipped in the timeline.
1170 // We could check typeof fiber.type, but does this work with RN?
1171 switch (fiber.tag) {
1172 case HostRoot:
1173 case HostComponent:
1174 case HostText:
1175 case HostPortal:
1176 case Fragment:
1177 case ContextProvider:
1178 case ContextConsumer:
1179 case Mode:
1180 return true;
1181 default:
1182 return false;
1183 }
1184};
1185
1186var clearPendingPhaseMeasurement = function () {
1187 if (currentPhase !== null && currentPhaseFiber !== null) {
1188 clearFiberMark(currentPhaseFiber, currentPhase);
1189 }
1190 currentPhaseFiber = null;
1191 currentPhase = null;
1192 hasScheduledUpdateInCurrentPhase = false;
1193};
1194
1195var pauseTimers = function () {
1196 // Stops all currently active measurements so that they can be resumed
1197 // if we continue in a later deferred loop from the same unit of work.
1198 var fiber = currentFiber;
1199 while (fiber) {
1200 if (fiber._debugIsCurrentlyTiming) {
1201 endFiberMark(fiber, null, null);
1202 }
1203 fiber = fiber.return;
1204 }
1205};
1206
1207var resumeTimersRecursively = function (fiber) {
1208 if (fiber.return !== null) {
1209 resumeTimersRecursively(fiber.return);
1210 }
1211 if (fiber._debugIsCurrentlyTiming) {
1212 beginFiberMark(fiber, null);
1213 }
1214};
1215
1216var resumeTimers = function () {
1217 // Resumes all measurements that were active during the last deferred loop.
1218 if (currentFiber !== null) {
1219 resumeTimersRecursively(currentFiber);
1220 }
1221};
1222
1223function recordEffect() {
1224 if (enableUserTimingAPI) {
1225 effectCountInCurrentCommit++;
1226 }
1227}
1228
1229function recordScheduleUpdate() {
1230 if (enableUserTimingAPI) {
1231 if (isCommitting) {
1232 hasScheduledUpdateInCurrentCommit = true;
1233 }
1234 if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') {
1235 hasScheduledUpdateInCurrentPhase = true;
1236 }
1237 }
1238}
1239
1240function startRequestCallbackTimer() {
1241 if (enableUserTimingAPI) {
1242 if (supportsUserTiming && !isWaitingForCallback) {
1243 isWaitingForCallback = true;
1244 beginMark('(Waiting for async callback...)');
1245 }
1246 }
1247}
1248
1249function stopRequestCallbackTimer(didExpire, expirationTime) {
1250 if (enableUserTimingAPI) {
1251 if (supportsUserTiming) {
1252 isWaitingForCallback = false;
1253 var warning = didExpire ? 'React was blocked by main thread' : null;
1254 endMark('(Waiting for async callback... will force flush in ' + expirationTime + ' ms)', '(Waiting for async callback...)', warning);
1255 }
1256 }
1257}
1258
1259function startWorkTimer(fiber) {
1260 if (enableUserTimingAPI) {
1261 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
1262 return;
1263 }
1264 // If we pause, this is the fiber to unwind from.
1265 currentFiber = fiber;
1266 if (!beginFiberMark(fiber, null)) {
1267 return;
1268 }
1269 fiber._debugIsCurrentlyTiming = true;
1270 }
1271}
1272
1273function cancelWorkTimer(fiber) {
1274 if (enableUserTimingAPI) {
1275 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
1276 return;
1277 }
1278 // Remember we shouldn't complete measurement for this fiber.
1279 // Otherwise flamechart will be deep even for small updates.
1280 fiber._debugIsCurrentlyTiming = false;
1281 clearFiberMark(fiber, null);
1282 }
1283}
1284
1285function stopWorkTimer(fiber) {
1286 if (enableUserTimingAPI) {
1287 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
1288 return;
1289 }
1290 // If we pause, its parent is the fiber to unwind from.
1291 currentFiber = fiber.return;
1292 if (!fiber._debugIsCurrentlyTiming) {
1293 return;
1294 }
1295 fiber._debugIsCurrentlyTiming = false;
1296 endFiberMark(fiber, null, null);
1297 }
1298}
1299
1300function stopFailedWorkTimer(fiber) {
1301 if (enableUserTimingAPI) {
1302 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
1303 return;
1304 }
1305 // If we pause, its parent is the fiber to unwind from.
1306 currentFiber = fiber.return;
1307 if (!fiber._debugIsCurrentlyTiming) {
1308 return;
1309 }
1310 fiber._debugIsCurrentlyTiming = false;
1311 var warning = fiber.tag === SuspenseComponent || fiber.tag === DehydratedSuspenseComponent ? 'Rendering was suspended' : 'An error was thrown inside this error boundary';
1312 endFiberMark(fiber, null, warning);
1313 }
1314}
1315
1316function startPhaseTimer(fiber, phase) {
1317 if (enableUserTimingAPI) {
1318 if (!supportsUserTiming) {
1319 return;
1320 }
1321 clearPendingPhaseMeasurement();
1322 if (!beginFiberMark(fiber, phase)) {
1323 return;
1324 }
1325 currentPhaseFiber = fiber;
1326 currentPhase = phase;
1327 }
1328}
1329
1330function stopPhaseTimer() {
1331 if (enableUserTimingAPI) {
1332 if (!supportsUserTiming) {
1333 return;
1334 }
1335 if (currentPhase !== null && currentPhaseFiber !== null) {
1336 var warning = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null;
1337 endFiberMark(currentPhaseFiber, currentPhase, warning);
1338 }
1339 currentPhase = null;
1340 currentPhaseFiber = null;
1341 }
1342}
1343
1344function startWorkLoopTimer(nextUnitOfWork) {
1345 if (enableUserTimingAPI) {
1346 currentFiber = nextUnitOfWork;
1347 if (!supportsUserTiming) {
1348 return;
1349 }
1350 commitCountInCurrentWorkLoop = 0;
1351 // This is top level call.
1352 // Any other measurements are performed within.
1353 beginMark('(React Tree Reconciliation)');
1354 // Resume any measurements that were in progress during the last loop.
1355 resumeTimers();
1356 }
1357}
1358
1359function stopWorkLoopTimer(interruptedBy, didCompleteRoot) {
1360 if (enableUserTimingAPI) {
1361 if (!supportsUserTiming) {
1362 return;
1363 }
1364 var warning = null;
1365 if (interruptedBy !== null) {
1366 if (interruptedBy.tag === HostRoot) {
1367 warning = 'A top-level update interrupted the previous render';
1368 } else {
1369 var componentName = getComponentName(interruptedBy.type) || 'Unknown';
1370 warning = 'An update to ' + componentName + ' interrupted the previous render';
1371 }
1372 } else if (commitCountInCurrentWorkLoop > 1) {
1373 warning = 'There were cascading updates';
1374 }
1375 commitCountInCurrentWorkLoop = 0;
1376 var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)';
1377 // Pause any measurements until the next loop.
1378 pauseTimers();
1379 endMark(label, '(React Tree Reconciliation)', warning);
1380 }
1381}
1382
1383function startCommitTimer() {
1384 if (enableUserTimingAPI) {
1385 if (!supportsUserTiming) {
1386 return;
1387 }
1388 isCommitting = true;
1389 hasScheduledUpdateInCurrentCommit = false;
1390 labelsInCurrentCommit.clear();
1391 beginMark('(Committing Changes)');
1392 }
1393}
1394
1395function stopCommitTimer() {
1396 if (enableUserTimingAPI) {
1397 if (!supportsUserTiming) {
1398 return;
1399 }
1400
1401 var warning = null;
1402 if (hasScheduledUpdateInCurrentCommit) {
1403 warning = 'Lifecycle hook scheduled a cascading update';
1404 } else if (commitCountInCurrentWorkLoop > 0) {
1405 warning = 'Caused by a cascading update in earlier commit';
1406 }
1407 hasScheduledUpdateInCurrentCommit = false;
1408 commitCountInCurrentWorkLoop++;
1409 isCommitting = false;
1410 labelsInCurrentCommit.clear();
1411
1412 endMark('(Committing Changes)', '(Committing Changes)', warning);
1413 }
1414}
1415
1416function startCommitSnapshotEffectsTimer() {
1417 if (enableUserTimingAPI) {
1418 if (!supportsUserTiming) {
1419 return;
1420 }
1421 effectCountInCurrentCommit = 0;
1422 beginMark('(Committing Snapshot Effects)');
1423 }
1424}
1425
1426function stopCommitSnapshotEffectsTimer() {
1427 if (enableUserTimingAPI) {
1428 if (!supportsUserTiming) {
1429 return;
1430 }
1431 var count = effectCountInCurrentCommit;
1432 effectCountInCurrentCommit = 0;
1433 endMark('(Committing Snapshot Effects: ' + count + ' Total)', '(Committing Snapshot Effects)', null);
1434 }
1435}
1436
1437function startCommitHostEffectsTimer() {
1438 if (enableUserTimingAPI) {
1439 if (!supportsUserTiming) {
1440 return;
1441 }
1442 effectCountInCurrentCommit = 0;
1443 beginMark('(Committing Host Effects)');
1444 }
1445}
1446
1447function stopCommitHostEffectsTimer() {
1448 if (enableUserTimingAPI) {
1449 if (!supportsUserTiming) {
1450 return;
1451 }
1452 var count = effectCountInCurrentCommit;
1453 effectCountInCurrentCommit = 0;
1454 endMark('(Committing Host Effects: ' + count + ' Total)', '(Committing Host Effects)', null);
1455 }
1456}
1457
1458function startCommitLifeCyclesTimer() {
1459 if (enableUserTimingAPI) {
1460 if (!supportsUserTiming) {
1461 return;
1462 }
1463 effectCountInCurrentCommit = 0;
1464 beginMark('(Calling Lifecycle Methods)');
1465 }
1466}
1467
1468function stopCommitLifeCyclesTimer() {
1469 if (enableUserTimingAPI) {
1470 if (!supportsUserTiming) {
1471 return;
1472 }
1473 var count = effectCountInCurrentCommit;
1474 effectCountInCurrentCommit = 0;
1475 endMark('(Calling Lifecycle Methods: ' + count + ' Total)', '(Calling Lifecycle Methods)', null);
1476 }
1477}
1478
1479var valueStack = [];
1480
1481var fiberStack = void 0;
1482
1483{
1484 fiberStack = [];
1485}
1486
1487var index = -1;
1488
1489function createCursor(defaultValue) {
1490 return {
1491 current: defaultValue
1492 };
1493}
1494
1495function pop(cursor, fiber) {
1496 if (index < 0) {
1497 {
1498 warningWithoutStack$1(false, 'Unexpected pop.');
1499 }
1500 return;
1501 }
1502
1503 {
1504 if (fiber !== fiberStack[index]) {
1505 warningWithoutStack$1(false, 'Unexpected Fiber popped.');
1506 }
1507 }
1508
1509 cursor.current = valueStack[index];
1510
1511 valueStack[index] = null;
1512
1513 {
1514 fiberStack[index] = null;
1515 }
1516
1517 index--;
1518}
1519
1520function push(cursor, value, fiber) {
1521 index++;
1522
1523 valueStack[index] = cursor.current;
1524
1525 {
1526 fiberStack[index] = fiber;
1527 }
1528
1529 cursor.current = value;
1530}
1531
1532function checkThatStackIsEmpty() {
1533 {
1534 if (index !== -1) {
1535 warningWithoutStack$1(false, 'Expected an empty stack. Something was not reset properly.');
1536 }
1537 }
1538}
1539
1540function resetStackAfterFatalErrorInDev() {
1541 {
1542 index = -1;
1543 valueStack.length = 0;
1544 fiberStack.length = 0;
1545 }
1546}
1547
1548var warnedAboutMissingGetChildContext = void 0;
1549
1550{
1551 warnedAboutMissingGetChildContext = {};
1552}
1553
1554var emptyContextObject = {};
1555{
1556 Object.freeze(emptyContextObject);
1557}
1558
1559// A cursor to the current merged context object on the stack.
1560var contextStackCursor = createCursor(emptyContextObject);
1561// A cursor to a boolean indicating whether the context has changed.
1562var didPerformWorkStackCursor = createCursor(false);
1563// Keep track of the previous context object that was on the stack.
1564// We use this to get access to the parent context after we have already
1565// pushed the next context provider, and now need to merge their contexts.
1566var previousContext = emptyContextObject;
1567
1568function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
1569 if (didPushOwnContextIfProvider && isContextProvider(Component)) {
1570 // If the fiber is a context provider itself, when we read its context
1571 // we may have already pushed its own child context on the stack. A context
1572 // provider should not "see" its own child context. Therefore we read the
1573 // previous (parent) context instead for a context provider.
1574 return previousContext;
1575 }
1576 return contextStackCursor.current;
1577}
1578
1579function cacheContext(workInProgress, unmaskedContext, maskedContext) {
1580 var instance = workInProgress.stateNode;
1581 instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
1582 instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
1583}
1584
1585function getMaskedContext(workInProgress, unmaskedContext) {
1586 var type = workInProgress.type;
1587 var contextTypes = type.contextTypes;
1588 if (!contextTypes) {
1589 return emptyContextObject;
1590 }
1591
1592 // Avoid recreating masked context unless unmasked context has changed.
1593 // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
1594 // This may trigger infinite loops if componentWillReceiveProps calls setState.
1595 var instance = workInProgress.stateNode;
1596 if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
1597 return instance.__reactInternalMemoizedMaskedChildContext;
1598 }
1599
1600 var context = {};
1601 for (var key in contextTypes) {
1602 context[key] = unmaskedContext[key];
1603 }
1604
1605 {
1606 var name = getComponentName(type) || 'Unknown';
1607 checkPropTypes_1(contextTypes, context, 'context', name, getCurrentFiberStackInDev);
1608 }
1609
1610 // Cache unmasked context so we can avoid recreating masked context unless necessary.
1611 // Context is created before the class component is instantiated so check for instance.
1612 if (instance) {
1613 cacheContext(workInProgress, unmaskedContext, context);
1614 }
1615
1616 return context;
1617}
1618
1619function hasContextChanged() {
1620 return didPerformWorkStackCursor.current;
1621}
1622
1623function isContextProvider(type) {
1624 var childContextTypes = type.childContextTypes;
1625 return childContextTypes !== null && childContextTypes !== undefined;
1626}
1627
1628function popContext(fiber) {
1629 pop(didPerformWorkStackCursor, fiber);
1630 pop(contextStackCursor, fiber);
1631}
1632
1633function popTopLevelContextObject(fiber) {
1634 pop(didPerformWorkStackCursor, fiber);
1635 pop(contextStackCursor, fiber);
1636}
1637
1638function pushTopLevelContextObject(fiber, context, didChange) {
1639 (function () {
1640 if (!(contextStackCursor.current === emptyContextObject)) {
1641 {
1642 throw ReactError('Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue.');
1643 }
1644 }
1645 })();
1646
1647 push(contextStackCursor, context, fiber);
1648 push(didPerformWorkStackCursor, didChange, fiber);
1649}
1650
1651function processChildContext(fiber, type, parentContext) {
1652 var instance = fiber.stateNode;
1653 var childContextTypes = type.childContextTypes;
1654
1655 // TODO (bvaughn) Replace this behavior with an invariant() in the future.
1656 // It has only been added in Fiber to match the (unintentional) behavior in Stack.
1657 if (typeof instance.getChildContext !== 'function') {
1658 {
1659 var componentName = getComponentName(type) || 'Unknown';
1660
1661 if (!warnedAboutMissingGetChildContext[componentName]) {
1662 warnedAboutMissingGetChildContext[componentName] = true;
1663 warningWithoutStack$1(false, '%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);
1664 }
1665 }
1666 return parentContext;
1667 }
1668
1669 var childContext = void 0;
1670 {
1671 setCurrentPhase('getChildContext');
1672 }
1673 startPhaseTimer(fiber, 'getChildContext');
1674 childContext = instance.getChildContext();
1675 stopPhaseTimer();
1676 {
1677 setCurrentPhase(null);
1678 }
1679 for (var contextKey in childContext) {
1680 (function () {
1681 if (!(contextKey in childContextTypes)) {
1682 {
1683 throw ReactError((getComponentName(type) || 'Unknown') + '.getChildContext(): key "' + contextKey + '" is not defined in childContextTypes.');
1684 }
1685 }
1686 })();
1687 }
1688 {
1689 var name = getComponentName(type) || 'Unknown';
1690 checkPropTypes_1(childContextTypes, childContext, 'child context', name,
1691 // In practice, there is one case in which we won't get a stack. It's when
1692 // somebody calls unstable_renderSubtreeIntoContainer() and we process
1693 // context from the parent component instance. The stack will be missing
1694 // because it's outside of the reconciliation, and so the pointer has not
1695 // been set. This is rare and doesn't matter. We'll also remove that API.
1696 getCurrentFiberStackInDev);
1697 }
1698
1699 return _assign({}, parentContext, childContext);
1700}
1701
1702function pushContextProvider(workInProgress) {
1703 var instance = workInProgress.stateNode;
1704 // We push the context as early as possible to ensure stack integrity.
1705 // If the instance does not exist yet, we will push null at first,
1706 // and replace it on the stack later when invalidating the context.
1707 var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject;
1708
1709 // Remember the parent context so we can merge with it later.
1710 // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
1711 previousContext = contextStackCursor.current;
1712 push(contextStackCursor, memoizedMergedChildContext, workInProgress);
1713 push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
1714
1715 return true;
1716}
1717
1718function invalidateContextProvider(workInProgress, type, didChange) {
1719 var instance = workInProgress.stateNode;
1720 (function () {
1721 if (!instance) {
1722 {
1723 throw ReactError('Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue.');
1724 }
1725 }
1726 })();
1727
1728 if (didChange) {
1729 // Merge parent and own context.
1730 // Skip this if we're not updating due to sCU.
1731 // This avoids unnecessarily recomputing memoized values.
1732 var mergedContext = processChildContext(workInProgress, type, previousContext);
1733 instance.__reactInternalMemoizedMergedChildContext = mergedContext;
1734
1735 // Replace the old (or empty) context with the new one.
1736 // It is important to unwind the context in the reverse order.
1737 pop(didPerformWorkStackCursor, workInProgress);
1738 pop(contextStackCursor, workInProgress);
1739 // Now push the new context and mark that it has changed.
1740 push(contextStackCursor, mergedContext, workInProgress);
1741 push(didPerformWorkStackCursor, didChange, workInProgress);
1742 } else {
1743 pop(didPerformWorkStackCursor, workInProgress);
1744 push(didPerformWorkStackCursor, didChange, workInProgress);
1745 }
1746}
1747
1748function findCurrentUnmaskedContext(fiber) {
1749 // Currently this is only used with renderSubtreeIntoContainer; not sure if it
1750 // makes sense elsewhere
1751 (function () {
1752 if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) {
1753 {
1754 throw ReactError('Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue.');
1755 }
1756 }
1757 })();
1758
1759 var node = fiber;
1760 do {
1761 switch (node.tag) {
1762 case HostRoot:
1763 return node.stateNode.context;
1764 case ClassComponent:
1765 {
1766 var Component = node.type;
1767 if (isContextProvider(Component)) {
1768 return node.stateNode.__reactInternalMemoizedMergedChildContext;
1769 }
1770 break;
1771 }
1772 }
1773 node = node.return;
1774 } while (node !== null);
1775 (function () {
1776 {
1777 {
1778 throw ReactError('Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.');
1779 }
1780 }
1781 })();
1782}
1783
1784var onCommitFiberRoot = null;
1785var onCommitFiberUnmount = null;
1786var hasLoggedError = false;
1787
1788function catchErrors(fn) {
1789 return function (arg) {
1790 try {
1791 return fn(arg);
1792 } catch (err) {
1793 if (true && !hasLoggedError) {
1794 hasLoggedError = true;
1795 warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err);
1796 }
1797 }
1798 };
1799}
1800
1801var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
1802
1803function injectInternals(internals) {
1804 if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
1805 // No DevTools
1806 return false;
1807 }
1808 var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
1809 if (hook.isDisabled) {
1810 // This isn't a real property on the hook, but it can be set to opt out
1811 // of DevTools integration and associated warnings and logs.
1812 // https://github.com/facebook/react/issues/3877
1813 return true;
1814 }
1815 if (!hook.supportsFiber) {
1816 {
1817 warningWithoutStack$1(false, 'The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://fb.me/react-devtools');
1818 }
1819 // DevTools exists, even though it doesn't support Fiber.
1820 return true;
1821 }
1822 try {
1823 var rendererID = hook.inject(internals);
1824 // We have successfully injected, so now it is safe to set up hooks.
1825 onCommitFiberRoot = catchErrors(function (root) {
1826 return hook.onCommitFiberRoot(rendererID, root);
1827 });
1828 onCommitFiberUnmount = catchErrors(function (fiber) {
1829 return hook.onCommitFiberUnmount(rendererID, fiber);
1830 });
1831 } catch (err) {
1832 // Catch all errors because it is unsafe to throw during initialization.
1833 {
1834 warningWithoutStack$1(false, 'React DevTools encountered an error: %s.', err);
1835 }
1836 }
1837 // DevTools exists
1838 return true;
1839}
1840
1841function onCommitRoot(root) {
1842 if (typeof onCommitFiberRoot === 'function') {
1843 onCommitFiberRoot(root);
1844 }
1845}
1846
1847function onCommitUnmount(fiber) {
1848 if (typeof onCommitFiberUnmount === 'function') {
1849 onCommitFiberUnmount(fiber);
1850 }
1851}
1852
1853// Max 31 bit integer. The max integer size in V8 for 32-bit systems.
1854// Math.pow(2, 30) - 1
1855// 0b111111111111111111111111111111
1856var maxSigned31BitInt = 1073741823;
1857
1858// Intentionally not named imports because Rollup would use dynamic dispatch for
1859// CommonJS interop named imports.
1860var Scheduler_runWithPriority = Scheduler$1.unstable_runWithPriority;
1861var Scheduler_scheduleCallback = Scheduler$1.unstable_scheduleCallback;
1862var Scheduler_cancelCallback = Scheduler$1.unstable_cancelCallback;
1863var Scheduler_shouldYield = Scheduler$1.unstable_shouldYield;
1864var Scheduler_now = Scheduler$1.unstable_now;
1865var Scheduler_getCurrentPriorityLevel = Scheduler$1.unstable_getCurrentPriorityLevel;
1866var Scheduler_ImmediatePriority = Scheduler$1.unstable_ImmediatePriority;
1867var Scheduler_UserBlockingPriority = Scheduler$1.unstable_UserBlockingPriority;
1868var Scheduler_NormalPriority = Scheduler$1.unstable_NormalPriority;
1869var Scheduler_LowPriority = Scheduler$1.unstable_LowPriority;
1870var Scheduler_IdlePriority = Scheduler$1.unstable_IdlePriority;
1871
1872
1873var fakeCallbackNode = {};
1874
1875// Except for NoPriority, these correspond to Scheduler priorities. We use
1876// ascending numbers so we can compare them like numbers. They start at 90 to
1877// avoid clashing with Scheduler's priorities.
1878var ImmediatePriority = 99;
1879var UserBlockingPriority = 98;
1880var NormalPriority = 97;
1881var LowPriority = 96;
1882var IdlePriority = 95;
1883// NoPriority is the absence of priority. Also React-only.
1884
1885
1886var now = Scheduler_now;
1887var shouldYield = disableYielding ? function () {
1888 return false;
1889} // Never yield when `disableYielding` is on
1890: Scheduler_shouldYield;
1891
1892var immediateQueue = null;
1893var immediateQueueCallbackNode = null;
1894var isFlushingImmediate = false;
1895
1896function getCurrentPriorityLevel() {
1897 switch (Scheduler_getCurrentPriorityLevel()) {
1898 case Scheduler_ImmediatePriority:
1899 return ImmediatePriority;
1900 case Scheduler_UserBlockingPriority:
1901 return UserBlockingPriority;
1902 case Scheduler_NormalPriority:
1903 return NormalPriority;
1904 case Scheduler_LowPriority:
1905 return LowPriority;
1906 case Scheduler_IdlePriority:
1907 return IdlePriority;
1908 default:
1909 (function () {
1910 {
1911 {
1912 throw ReactError('Unknown priority level.');
1913 }
1914 }
1915 })();
1916 }
1917}
1918
1919function reactPriorityToSchedulerPriority(reactPriorityLevel) {
1920 switch (reactPriorityLevel) {
1921 case ImmediatePriority:
1922 return Scheduler_ImmediatePriority;
1923 case UserBlockingPriority:
1924 return Scheduler_UserBlockingPriority;
1925 case NormalPriority:
1926 return Scheduler_NormalPriority;
1927 case LowPriority:
1928 return Scheduler_LowPriority;
1929 case IdlePriority:
1930 return Scheduler_IdlePriority;
1931 default:
1932 (function () {
1933 {
1934 {
1935 throw ReactError('Unknown priority level.');
1936 }
1937 }
1938 })();
1939 }
1940}
1941
1942function runWithPriority(reactPriorityLevel, fn) {
1943 var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
1944 return Scheduler_runWithPriority(priorityLevel, fn);
1945}
1946
1947function scheduleCallback(reactPriorityLevel, callback, options) {
1948 if (reactPriorityLevel === ImmediatePriority) {
1949 // Push this callback into an internal queue. We'll flush these either in
1950 // the next tick, or earlier if something calls `flushImmediateQueue`.
1951 if (immediateQueue === null) {
1952 immediateQueue = [callback];
1953 // Flush the queue in the next tick, at the earliest.
1954 immediateQueueCallbackNode = Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushImmediateQueueImpl);
1955 } else {
1956 // Push onto existing queue. Don't need to schedule a callback because
1957 // we already scheduled one when we created the queue.
1958 immediateQueue.push(callback);
1959 }
1960 return fakeCallbackNode;
1961 }
1962 // Otherwise pass through to Scheduler.
1963 var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
1964 return Scheduler_scheduleCallback(priorityLevel, callback, options);
1965}
1966
1967function cancelCallback(callbackNode) {
1968 if (callbackNode !== fakeCallbackNode) {
1969 Scheduler_cancelCallback(callbackNode);
1970 }
1971}
1972
1973function flushImmediateQueue() {
1974 if (immediateQueueCallbackNode !== null) {
1975 Scheduler_cancelCallback(immediateQueueCallbackNode);
1976 }
1977 flushImmediateQueueImpl();
1978}
1979
1980function flushImmediateQueueImpl() {
1981 if (!isFlushingImmediate && immediateQueue !== null) {
1982 // Prevent re-entrancy.
1983 isFlushingImmediate = true;
1984 var i = 0;
1985 try {
1986 var _isSync = true;
1987 for (; i < immediateQueue.length; i++) {
1988 var callback = immediateQueue[i];
1989 do {
1990 callback = callback(_isSync);
1991 } while (callback !== null);
1992 }
1993 immediateQueue = null;
1994 } catch (error) {
1995 // If something throws, leave the remaining callbacks on the queue.
1996 if (immediateQueue !== null) {
1997 immediateQueue = immediateQueue.slice(i + 1);
1998 }
1999 // Resume flushing in the next tick
2000 Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushImmediateQueue);
2001 throw error;
2002 } finally {
2003 isFlushingImmediate = false;
2004 }
2005 }
2006}
2007
2008var NoWork = 0;
2009var Never = 1;
2010var Sync = maxSigned31BitInt;
2011
2012var UNIT_SIZE = 10;
2013var MAGIC_NUMBER_OFFSET = maxSigned31BitInt - 1;
2014
2015// 1 unit of expiration time represents 10ms.
2016function msToExpirationTime(ms) {
2017 // Always add an offset so that we don't clash with the magic number for NoWork.
2018 return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);
2019}
2020
2021function expirationTimeToMs(expirationTime) {
2022 return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE;
2023}
2024
2025function ceiling(num, precision) {
2026 return ((num / precision | 0) + 1) * precision;
2027}
2028
2029function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) {
2030 return MAGIC_NUMBER_OFFSET - ceiling(MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE);
2031}
2032
2033// TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update
2034// the names to reflect.
2035var LOW_PRIORITY_EXPIRATION = 5000;
2036var LOW_PRIORITY_BATCH_SIZE = 250;
2037
2038function computeAsyncExpiration(currentTime) {
2039 return computeExpirationBucket(currentTime, LOW_PRIORITY_EXPIRATION, LOW_PRIORITY_BATCH_SIZE);
2040}
2041
2042// We intentionally set a higher expiration time for interactive updates in
2043// dev than in production.
2044//
2045// If the main thread is being blocked so long that you hit the expiration,
2046// it's a problem that could be solved with better scheduling.
2047//
2048// People will be more likely to notice this and fix it with the long
2049// expiration time in development.
2050//
2051// In production we opt for better UX at the risk of masking scheduling
2052// problems, by expiring fast.
2053var HIGH_PRIORITY_EXPIRATION = 500;
2054var HIGH_PRIORITY_BATCH_SIZE = 100;
2055
2056function computeInteractiveExpiration(currentTime) {
2057 return computeExpirationBucket(currentTime, HIGH_PRIORITY_EXPIRATION, HIGH_PRIORITY_BATCH_SIZE);
2058}
2059
2060function inferPriorityFromExpirationTime(currentTime, expirationTime) {
2061 if (expirationTime === Sync) {
2062 return ImmediatePriority;
2063 }
2064 if (expirationTime === Never) {
2065 return IdlePriority;
2066 }
2067 var msUntil = msToExpirationTime(expirationTime) - msToExpirationTime(currentTime);
2068 if (msUntil <= 0) {
2069 return ImmediatePriority;
2070 }
2071 if (msUntil <= HIGH_PRIORITY_EXPIRATION) {
2072 return UserBlockingPriority;
2073 }
2074 if (msUntil <= LOW_PRIORITY_EXPIRATION) {
2075 return NormalPriority;
2076 }
2077
2078 // TODO: Handle LowPriority
2079
2080 // Assume anything lower has idle priority
2081 return IdlePriority;
2082}
2083
2084var NoContext = 0;
2085var ConcurrentMode = 1;
2086var StrictMode = 2;
2087var ProfileMode = 4;
2088
2089var hasBadMapPolyfill = void 0;
2090
2091{
2092 hasBadMapPolyfill = false;
2093 try {
2094 var nonExtensibleObject = Object.preventExtensions({});
2095 var testMap = new Map([[nonExtensibleObject, null]]);
2096 var testSet = new Set([nonExtensibleObject]);
2097 // This is necessary for Rollup to not consider these unused.
2098 // https://github.com/rollup/rollup/issues/1771
2099 // TODO: we can remove these if Rollup fixes the bug.
2100 testMap.set(0, 0);
2101 testSet.add(0);
2102 } catch (e) {
2103 // TODO: Consider warning about bad polyfills
2104 hasBadMapPolyfill = true;
2105 }
2106}
2107
2108// A Fiber is work on a Component that needs to be done or was done. There can
2109// be more than one per component.
2110
2111
2112var debugCounter = void 0;
2113
2114{
2115 debugCounter = 1;
2116}
2117
2118function FiberNode(tag, pendingProps, key, mode) {
2119 // Instance
2120 this.tag = tag;
2121 this.key = key;
2122 this.elementType = null;
2123 this.type = null;
2124 this.stateNode = null;
2125
2126 // Fiber
2127 this.return = null;
2128 this.child = null;
2129 this.sibling = null;
2130 this.index = 0;
2131
2132 this.ref = null;
2133
2134 this.pendingProps = pendingProps;
2135 this.memoizedProps = null;
2136 this.updateQueue = null;
2137 this.memoizedState = null;
2138 this.contextDependencies = null;
2139
2140 this.mode = mode;
2141
2142 // Effects
2143 this.effectTag = NoEffect;
2144 this.nextEffect = null;
2145
2146 this.firstEffect = null;
2147 this.lastEffect = null;
2148
2149 this.expirationTime = NoWork;
2150 this.childExpirationTime = NoWork;
2151
2152 this.alternate = null;
2153
2154 if (enableProfilerTimer) {
2155 // Note: The following is done to avoid a v8 performance cliff.
2156 //
2157 // Initializing the fields below to smis and later updating them with
2158 // double values will cause Fibers to end up having separate shapes.
2159 // This behavior/bug has something to do with Object.preventExtension().
2160 // Fortunately this only impacts DEV builds.
2161 // Unfortunately it makes React unusably slow for some applications.
2162 // To work around this, initialize the fields below with doubles.
2163 //
2164 // Learn more about this here:
2165 // https://github.com/facebook/react/issues/14365
2166 // https://bugs.chromium.org/p/v8/issues/detail?id=8538
2167 this.actualDuration = Number.NaN;
2168 this.actualStartTime = Number.NaN;
2169 this.selfBaseDuration = Number.NaN;
2170 this.treeBaseDuration = Number.NaN;
2171
2172 // It's okay to replace the initial doubles with smis after initialization.
2173 // This won't trigger the performance cliff mentioned above,
2174 // and it simplifies other profiler code (including DevTools).
2175 this.actualDuration = 0;
2176 this.actualStartTime = -1;
2177 this.selfBaseDuration = 0;
2178 this.treeBaseDuration = 0;
2179 }
2180
2181 {
2182 this._debugID = debugCounter++;
2183 this._debugSource = null;
2184 this._debugOwner = null;
2185 this._debugIsCurrentlyTiming = false;
2186 this._debugHookTypes = null;
2187 if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
2188 Object.preventExtensions(this);
2189 }
2190 }
2191}
2192
2193// This is a constructor function, rather than a POJO constructor, still
2194// please ensure we do the following:
2195// 1) Nobody should add any instance methods on this. Instance methods can be
2196// more difficult to predict when they get optimized and they are almost
2197// never inlined properly in static compilers.
2198// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
2199// always know when it is a fiber.
2200// 3) We might want to experiment with using numeric keys since they are easier
2201// to optimize in a non-JIT environment.
2202// 4) We can easily go from a constructor to a createFiber object literal if that
2203// is faster.
2204// 5) It should be easy to port this to a C struct and keep a C implementation
2205// compatible.
2206var createFiber = function (tag, pendingProps, key, mode) {
2207 // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
2208 return new FiberNode(tag, pendingProps, key, mode);
2209};
2210
2211function shouldConstruct(Component) {
2212 var prototype = Component.prototype;
2213 return !!(prototype && prototype.isReactComponent);
2214}
2215
2216function isSimpleFunctionComponent(type) {
2217 return typeof type === 'function' && !shouldConstruct(type) && type.defaultProps === undefined;
2218}
2219
2220function resolveLazyComponentTag(Component) {
2221 if (typeof Component === 'function') {
2222 return shouldConstruct(Component) ? ClassComponent : FunctionComponent;
2223 } else if (Component !== undefined && Component !== null) {
2224 var $$typeof = Component.$$typeof;
2225 if ($$typeof === REACT_FORWARD_REF_TYPE) {
2226 return ForwardRef;
2227 }
2228 if ($$typeof === REACT_MEMO_TYPE) {
2229 return MemoComponent;
2230 }
2231 }
2232 return IndeterminateComponent;
2233}
2234
2235// This is used to create an alternate fiber to do work on.
2236function createWorkInProgress(current, pendingProps, expirationTime) {
2237 var workInProgress = current.alternate;
2238 if (workInProgress === null) {
2239 // We use a double buffering pooling technique because we know that we'll
2240 // only ever need at most two versions of a tree. We pool the "other" unused
2241 // node that we're free to reuse. This is lazily created to avoid allocating
2242 // extra objects for things that are never updated. It also allow us to
2243 // reclaim the extra memory if needed.
2244 workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
2245 workInProgress.elementType = current.elementType;
2246 workInProgress.type = current.type;
2247 workInProgress.stateNode = current.stateNode;
2248
2249 {
2250 // DEV-only fields
2251 workInProgress._debugID = current._debugID;
2252 workInProgress._debugSource = current._debugSource;
2253 workInProgress._debugOwner = current._debugOwner;
2254 workInProgress._debugHookTypes = current._debugHookTypes;
2255 }
2256
2257 workInProgress.alternate = current;
2258 current.alternate = workInProgress;
2259 } else {
2260 workInProgress.pendingProps = pendingProps;
2261
2262 // We already have an alternate.
2263 // Reset the effect tag.
2264 workInProgress.effectTag = NoEffect;
2265
2266 // The effect list is no longer valid.
2267 workInProgress.nextEffect = null;
2268 workInProgress.firstEffect = null;
2269 workInProgress.lastEffect = null;
2270
2271 if (enableProfilerTimer) {
2272 // We intentionally reset, rather than copy, actualDuration & actualStartTime.
2273 // This prevents time from endlessly accumulating in new commits.
2274 // This has the downside of resetting values for different priority renders,
2275 // But works for yielding (the common case) and should support resuming.
2276 workInProgress.actualDuration = 0;
2277 workInProgress.actualStartTime = -1;
2278 }
2279 }
2280
2281 workInProgress.childExpirationTime = current.childExpirationTime;
2282 workInProgress.expirationTime = current.expirationTime;
2283
2284 workInProgress.child = current.child;
2285 workInProgress.memoizedProps = current.memoizedProps;
2286 workInProgress.memoizedState = current.memoizedState;
2287 workInProgress.updateQueue = current.updateQueue;
2288 workInProgress.contextDependencies = current.contextDependencies;
2289
2290 // These will be overridden during the parent's reconciliation
2291 workInProgress.sibling = current.sibling;
2292 workInProgress.index = current.index;
2293 workInProgress.ref = current.ref;
2294
2295 if (enableProfilerTimer) {
2296 workInProgress.selfBaseDuration = current.selfBaseDuration;
2297 workInProgress.treeBaseDuration = current.treeBaseDuration;
2298 }
2299
2300 return workInProgress;
2301}
2302
2303function createHostRootFiber(isConcurrent) {
2304 var mode = isConcurrent ? ConcurrentMode | StrictMode : NoContext;
2305
2306 if (enableProfilerTimer && isDevToolsPresent) {
2307 // Always collect profile timings when DevTools are present.
2308 // This enables DevTools to start capturing timing at any point–
2309 // Without some nodes in the tree having empty base times.
2310 mode |= ProfileMode;
2311 }
2312
2313 return createFiber(HostRoot, null, null, mode);
2314}
2315
2316function createFiberFromTypeAndProps(type, // React$ElementType
2317key, pendingProps, owner, mode, expirationTime) {
2318 var fiber = void 0;
2319
2320 var fiberTag = IndeterminateComponent;
2321 // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
2322 var resolvedType = type;
2323 if (typeof type === 'function') {
2324 if (shouldConstruct(type)) {
2325 fiberTag = ClassComponent;
2326 }
2327 } else if (typeof type === 'string') {
2328 fiberTag = HostComponent;
2329 } else {
2330 getTag: switch (type) {
2331 case REACT_FRAGMENT_TYPE:
2332 return createFiberFromFragment(pendingProps.children, mode, expirationTime, key);
2333 case REACT_CONCURRENT_MODE_TYPE:
2334 return createFiberFromMode(pendingProps, mode | ConcurrentMode | StrictMode, expirationTime, key);
2335 case REACT_STRICT_MODE_TYPE:
2336 return createFiberFromMode(pendingProps, mode | StrictMode, expirationTime, key);
2337 case REACT_PROFILER_TYPE:
2338 return createFiberFromProfiler(pendingProps, mode, expirationTime, key);
2339 case REACT_SUSPENSE_TYPE:
2340 return createFiberFromSuspense(pendingProps, mode, expirationTime, key);
2341 default:
2342 {
2343 if (typeof type === 'object' && type !== null) {
2344 switch (type.$$typeof) {
2345 case REACT_PROVIDER_TYPE:
2346 fiberTag = ContextProvider;
2347 break getTag;
2348 case REACT_CONTEXT_TYPE:
2349 // This is a consumer
2350 fiberTag = ContextConsumer;
2351 break getTag;
2352 case REACT_FORWARD_REF_TYPE:
2353 fiberTag = ForwardRef;
2354 break getTag;
2355 case REACT_MEMO_TYPE:
2356 fiberTag = MemoComponent;
2357 break getTag;
2358 case REACT_LAZY_TYPE:
2359 fiberTag = LazyComponent;
2360 resolvedType = null;
2361 break getTag;
2362 case REACT_EVENT_COMPONENT_TYPE:
2363 if (enableEventAPI) {
2364 return createFiberFromEventComponent(type, pendingProps, mode, expirationTime, key);
2365 }
2366 break;
2367 case REACT_EVENT_TARGET_TYPE:
2368 if (enableEventAPI) {
2369 return createFiberFromEventTarget(type, pendingProps, mode, expirationTime, key);
2370 }
2371 break;
2372 }
2373 }
2374 var info = '';
2375 {
2376 if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
2377 info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.';
2378 }
2379 var ownerName = owner ? getComponentName(owner.type) : null;
2380 if (ownerName) {
2381 info += '\n\nCheck the render method of `' + ownerName + '`.';
2382 }
2383 }
2384 (function () {
2385 {
2386 {
2387 throw ReactError('Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: ' + (type == null ? type : typeof type) + '.' + info);
2388 }
2389 }
2390 })();
2391 }
2392 }
2393 }
2394
2395 fiber = createFiber(fiberTag, pendingProps, key, mode);
2396 fiber.elementType = type;
2397 fiber.type = resolvedType;
2398 fiber.expirationTime = expirationTime;
2399
2400 return fiber;
2401}
2402
2403function createFiberFromElement(element, mode, expirationTime) {
2404 var owner = null;
2405 {
2406 owner = element._owner;
2407 }
2408 var type = element.type;
2409 var key = element.key;
2410 var pendingProps = element.props;
2411 var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, expirationTime);
2412 {
2413 fiber._debugSource = element._source;
2414 fiber._debugOwner = element._owner;
2415 }
2416 return fiber;
2417}
2418
2419function createFiberFromFragment(elements, mode, expirationTime, key) {
2420 var fiber = createFiber(Fragment, elements, key, mode);
2421 fiber.expirationTime = expirationTime;
2422 return fiber;
2423}
2424
2425function createFiberFromEventComponent(eventComponent, pendingProps, mode, expirationTime, key) {
2426 var fiber = createFiber(EventComponent, pendingProps, key, mode);
2427 fiber.elementType = eventComponent;
2428 fiber.type = eventComponent;
2429 fiber.stateNode = {
2430 props: pendingProps,
2431 state: null
2432 };
2433 fiber.expirationTime = expirationTime;
2434 return fiber;
2435}
2436
2437function createFiberFromEventTarget(eventTarget, pendingProps, mode, expirationTime, key) {
2438 var fiber = createFiber(EventTarget, pendingProps, key, mode);
2439 fiber.elementType = eventTarget;
2440 fiber.type = eventTarget;
2441 fiber.expirationTime = expirationTime;
2442 return fiber;
2443}
2444
2445function createFiberFromProfiler(pendingProps, mode, expirationTime, key) {
2446 {
2447 if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') {
2448 warningWithoutStack$1(false, 'Profiler must specify an "id" string and "onRender" function as props');
2449 }
2450 }
2451
2452 var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode);
2453 // TODO: The Profiler fiber shouldn't have a type. It has a tag.
2454 fiber.elementType = REACT_PROFILER_TYPE;
2455 fiber.type = REACT_PROFILER_TYPE;
2456 fiber.expirationTime = expirationTime;
2457
2458 return fiber;
2459}
2460
2461function createFiberFromMode(pendingProps, mode, expirationTime, key) {
2462 var fiber = createFiber(Mode, pendingProps, key, mode);
2463
2464 // TODO: The Mode fiber shouldn't have a type. It has a tag.
2465 var type = (mode & ConcurrentMode) === NoContext ? REACT_STRICT_MODE_TYPE : REACT_CONCURRENT_MODE_TYPE;
2466 fiber.elementType = type;
2467 fiber.type = type;
2468
2469 fiber.expirationTime = expirationTime;
2470 return fiber;
2471}
2472
2473function createFiberFromSuspense(pendingProps, mode, expirationTime, key) {
2474 var fiber = createFiber(SuspenseComponent, pendingProps, key, mode);
2475
2476 // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
2477 var type = REACT_SUSPENSE_TYPE;
2478 fiber.elementType = type;
2479 fiber.type = type;
2480
2481 fiber.expirationTime = expirationTime;
2482 return fiber;
2483}
2484
2485function createFiberFromText(content, mode, expirationTime) {
2486 var fiber = createFiber(HostText, content, null, mode);
2487 fiber.expirationTime = expirationTime;
2488 return fiber;
2489}
2490
2491function createFiberFromHostInstanceForDeletion() {
2492 var fiber = createFiber(HostComponent, null, null, NoContext);
2493 // TODO: These should not need a type.
2494 fiber.elementType = 'DELETED';
2495 fiber.type = 'DELETED';
2496 return fiber;
2497}
2498
2499function createFiberFromPortal(portal, mode, expirationTime) {
2500 var pendingProps = portal.children !== null ? portal.children : [];
2501 var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
2502 fiber.expirationTime = expirationTime;
2503 fiber.stateNode = {
2504 containerInfo: portal.containerInfo,
2505 pendingChildren: null, // Used by persistent updates
2506 implementation: portal.implementation
2507 };
2508 return fiber;
2509}
2510
2511// Used for stashing WIP properties to replay failed work in DEV.
2512function assignFiberPropertiesInDEV(target, source) {
2513 if (target === null) {
2514 // This Fiber's initial properties will always be overwritten.
2515 // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
2516 target = createFiber(IndeterminateComponent, null, null, NoContext);
2517 }
2518
2519 // This is intentionally written as a list of all properties.
2520 // We tried to use Object.assign() instead but this is called in
2521 // the hottest path, and Object.assign() was too slow:
2522 // https://github.com/facebook/react/issues/12502
2523 // This code is DEV-only so size is not a concern.
2524
2525 target.tag = source.tag;
2526 target.key = source.key;
2527 target.elementType = source.elementType;
2528 target.type = source.type;
2529 target.stateNode = source.stateNode;
2530 target.return = source.return;
2531 target.child = source.child;
2532 target.sibling = source.sibling;
2533 target.index = source.index;
2534 target.ref = source.ref;
2535 target.pendingProps = source.pendingProps;
2536 target.memoizedProps = source.memoizedProps;
2537 target.updateQueue = source.updateQueue;
2538 target.memoizedState = source.memoizedState;
2539 target.contextDependencies = source.contextDependencies;
2540 target.mode = source.mode;
2541 target.effectTag = source.effectTag;
2542 target.nextEffect = source.nextEffect;
2543 target.firstEffect = source.firstEffect;
2544 target.lastEffect = source.lastEffect;
2545 target.expirationTime = source.expirationTime;
2546 target.childExpirationTime = source.childExpirationTime;
2547 target.alternate = source.alternate;
2548 if (enableProfilerTimer) {
2549 target.actualDuration = source.actualDuration;
2550 target.actualStartTime = source.actualStartTime;
2551 target.selfBaseDuration = source.selfBaseDuration;
2552 target.treeBaseDuration = source.treeBaseDuration;
2553 }
2554 target._debugID = source._debugID;
2555 target._debugSource = source._debugSource;
2556 target._debugOwner = source._debugOwner;
2557 target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
2558 target._debugHookTypes = source._debugHookTypes;
2559 return target;
2560}
2561
2562var ReactInternals$1 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
2563
2564var _ReactInternals$Sched = ReactInternals$1.SchedulerTracing;
2565var __interactionsRef = _ReactInternals$Sched.__interactionsRef;
2566var __subscriberRef = _ReactInternals$Sched.__subscriberRef;
2567var unstable_clear = _ReactInternals$Sched.unstable_clear;
2568var unstable_getCurrent = _ReactInternals$Sched.unstable_getCurrent;
2569var unstable_getThreadID = _ReactInternals$Sched.unstable_getThreadID;
2570var unstable_subscribe = _ReactInternals$Sched.unstable_subscribe;
2571var unstable_trace = _ReactInternals$Sched.unstable_trace;
2572var unstable_unsubscribe = _ReactInternals$Sched.unstable_unsubscribe;
2573var unstable_wrap = _ReactInternals$Sched.unstable_wrap;
2574
2575// TODO: This should be lifted into the renderer.
2576
2577
2578// The following attributes are only used by interaction tracing builds.
2579// They enable interactions to be associated with their async work,
2580// And expose interaction metadata to the React DevTools Profiler plugin.
2581// Note that these attributes are only defined when the enableSchedulerTracing flag is enabled.
2582
2583
2584// Exported FiberRoot type includes all properties,
2585// To avoid requiring potentially error-prone :any casts throughout the project.
2586// Profiling properties are only safe to access in profiling builds (when enableSchedulerTracing is true).
2587// The types are defined separately within this file to ensure they stay in sync.
2588// (We don't have to use an inline :any cast when enableSchedulerTracing is disabled.)
2589
2590
2591function FiberRootNode(containerInfo, hydrate) {
2592 this.current = null;
2593 this.containerInfo = containerInfo;
2594 this.pendingChildren = null;
2595 this.pingCache = null;
2596 this.pendingCommitExpirationTime = NoWork;
2597 this.finishedWork = null;
2598 this.timeoutHandle = noTimeout;
2599 this.context = null;
2600 this.pendingContext = null;
2601 this.hydrate = hydrate;
2602 this.firstBatch = null;
2603
2604 if (enableNewScheduler) {
2605 this.callbackNode = null;
2606 this.callbackExpirationTime = NoWork;
2607 this.firstPendingTime = NoWork;
2608 this.lastPendingTime = NoWork;
2609 this.pingTime = NoWork;
2610 } else {
2611 this.earliestPendingTime = NoWork;
2612 this.latestPendingTime = NoWork;
2613 this.earliestSuspendedTime = NoWork;
2614 this.latestSuspendedTime = NoWork;
2615 this.latestPingedTime = NoWork;
2616 this.didError = false;
2617 this.nextExpirationTimeToWorkOn = NoWork;
2618 this.expirationTime = NoWork;
2619 this.nextScheduledRoot = null;
2620 }
2621
2622 if (enableSchedulerTracing) {
2623 this.interactionThreadID = unstable_getThreadID();
2624 this.memoizedInteractions = new Set();
2625 this.pendingInteractionMap = new Map();
2626 }
2627}
2628
2629function createFiberRoot(containerInfo, isConcurrent, hydrate) {
2630 var root = new FiberRootNode(containerInfo, hydrate);
2631
2632 // Cyclic construction. This cheats the type system right now because
2633 // stateNode is any.
2634 var uninitializedFiber = createHostRootFiber(isConcurrent);
2635 root.current = uninitializedFiber;
2636 uninitializedFiber.stateNode = root;
2637
2638 return root;
2639}
2640
2641var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) {
2642 var funcArgs = Array.prototype.slice.call(arguments, 3);
2643 try {
2644 func.apply(context, funcArgs);
2645 } catch (error) {
2646 this.onError(error);
2647 }
2648};
2649
2650{
2651 // In DEV mode, we swap out invokeGuardedCallback for a special version
2652 // that plays more nicely with the browser's DevTools. The idea is to preserve
2653 // "Pause on exceptions" behavior. Because React wraps all user-provided
2654 // functions in invokeGuardedCallback, and the production version of
2655 // invokeGuardedCallback uses a try-catch, all user exceptions are treated
2656 // like caught exceptions, and the DevTools won't pause unless the developer
2657 // takes the extra step of enabling pause on caught exceptions. This is
2658 // unintuitive, though, because even though React has caught the error, from
2659 // the developer's perspective, the error is uncaught.
2660 //
2661 // To preserve the expected "Pause on exceptions" behavior, we don't use a
2662 // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
2663 // DOM node, and call the user-provided callback from inside an event handler
2664 // for that fake event. If the callback throws, the error is "captured" using
2665 // a global event handler. But because the error happens in a different
2666 // event loop context, it does not interrupt the normal program flow.
2667 // Effectively, this gives us try-catch behavior without actually using
2668 // try-catch. Neat!
2669
2670 // Check that the browser supports the APIs we need to implement our special
2671 // DEV version of invokeGuardedCallback
2672 if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
2673 var fakeNode = document.createElement('react');
2674
2675 var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) {
2676 // If document doesn't exist we know for sure we will crash in this method
2677 // when we call document.createEvent(). However this can cause confusing
2678 // errors: https://github.com/facebookincubator/create-react-app/issues/3482
2679 // So we preemptively throw with a better message instead.
2680 (function () {
2681 if (!(typeof document !== 'undefined')) {
2682 {
2683 throw ReactError('The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous.');
2684 }
2685 }
2686 })();
2687 var evt = document.createEvent('Event');
2688
2689 // Keeps track of whether the user-provided callback threw an error. We
2690 // set this to true at the beginning, then set it to false right after
2691 // calling the function. If the function errors, `didError` will never be
2692 // set to false. This strategy works even if the browser is flaky and
2693 // fails to call our global error handler, because it doesn't rely on
2694 // the error event at all.
2695 var didError = true;
2696
2697 // Keeps track of the value of window.event so that we can reset it
2698 // during the callback to let user code access window.event in the
2699 // browsers that support it.
2700 var windowEvent = window.event;
2701
2702 // Keeps track of the descriptor of window.event to restore it after event
2703 // dispatching: https://github.com/facebook/react/issues/13688
2704 var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event');
2705
2706 // Create an event handler for our fake event. We will synchronously
2707 // dispatch our fake event using `dispatchEvent`. Inside the handler, we
2708 // call the user-provided callback.
2709 var funcArgs = Array.prototype.slice.call(arguments, 3);
2710 function callCallback() {
2711 // We immediately remove the callback from event listeners so that
2712 // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
2713 // nested call would trigger the fake event handlers of any call higher
2714 // in the stack.
2715 fakeNode.removeEventListener(evtType, callCallback, false);
2716
2717 // We check for window.hasOwnProperty('event') to prevent the
2718 // window.event assignment in both IE <= 10 as they throw an error
2719 // "Member not found" in strict mode, and in Firefox which does not
2720 // support window.event.
2721 if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
2722 window.event = windowEvent;
2723 }
2724
2725 func.apply(context, funcArgs);
2726 didError = false;
2727 }
2728
2729 // Create a global error event handler. We use this to capture the value
2730 // that was thrown. It's possible that this error handler will fire more
2731 // than once; for example, if non-React code also calls `dispatchEvent`
2732 // and a handler for that event throws. We should be resilient to most of
2733 // those cases. Even if our error event handler fires more than once, the
2734 // last error event is always used. If the callback actually does error,
2735 // we know that the last error event is the correct one, because it's not
2736 // possible for anything else to have happened in between our callback
2737 // erroring and the code that follows the `dispatchEvent` call below. If
2738 // the callback doesn't error, but the error event was fired, we know to
2739 // ignore it because `didError` will be false, as described above.
2740 var error = void 0;
2741 // Use this to track whether the error event is ever called.
2742 var didSetError = false;
2743 var isCrossOriginError = false;
2744
2745 function handleWindowError(event) {
2746 error = event.error;
2747 didSetError = true;
2748 if (error === null && event.colno === 0 && event.lineno === 0) {
2749 isCrossOriginError = true;
2750 }
2751 if (event.defaultPrevented) {
2752 // Some other error handler has prevented default.
2753 // Browsers silence the error report if this happens.
2754 // We'll remember this to later decide whether to log it or not.
2755 if (error != null && typeof error === 'object') {
2756 try {
2757 error._suppressLogging = true;
2758 } catch (inner) {
2759 // Ignore.
2760 }
2761 }
2762 }
2763 }
2764
2765 // Create a fake event type.
2766 var evtType = 'react-' + (name ? name : 'invokeguardedcallback');
2767
2768 // Attach our event handlers
2769 window.addEventListener('error', handleWindowError);
2770 fakeNode.addEventListener(evtType, callCallback, false);
2771
2772 // Synchronously dispatch our fake event. If the user-provided function
2773 // errors, it will trigger our global error handler.
2774 evt.initEvent(evtType, false, false);
2775 fakeNode.dispatchEvent(evt);
2776
2777 if (windowEventDescriptor) {
2778 Object.defineProperty(window, 'event', windowEventDescriptor);
2779 }
2780
2781 if (didError) {
2782 if (!didSetError) {
2783 // The callback errored, but the error event never fired.
2784 error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.');
2785 } else if (isCrossOriginError) {
2786 error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://fb.me/react-crossorigin-error for more information.');
2787 }
2788 this.onError(error);
2789 }
2790
2791 // Remove our event listeners
2792 window.removeEventListener('error', handleWindowError);
2793 };
2794
2795 invokeGuardedCallbackImpl = invokeGuardedCallbackDev;
2796 }
2797}
2798
2799var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
2800
2801// Used by Fiber to simulate a try-catch.
2802var hasError = false;
2803var caughtError = null;
2804
2805var reporter = {
2806 onError: function (error) {
2807 hasError = true;
2808 caughtError = error;
2809 }
2810};
2811
2812/**
2813 * Call a function while guarding against errors that happens within it.
2814 * Returns an error if it throws, otherwise null.
2815 *
2816 * In production, this is implemented using a try-catch. The reason we don't
2817 * use a try-catch directly is so that we can swap out a different
2818 * implementation in DEV mode.
2819 *
2820 * @param {String} name of the guard to use for logging or debugging
2821 * @param {Function} func The function to invoke
2822 * @param {*} context The context to use when calling the function
2823 * @param {...*} args Arguments for function
2824 */
2825function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
2826 hasError = false;
2827 caughtError = null;
2828 invokeGuardedCallbackImpl$1.apply(reporter, arguments);
2829}
2830
2831/**
2832 * Same as invokeGuardedCallback, but instead of returning an error, it stores
2833 * it in a global so it can be rethrown by `rethrowCaughtError` later.
2834 * TODO: See if caughtError and rethrowError can be unified.
2835 *
2836 * @param {String} name of the guard to use for logging or debugging
2837 * @param {Function} func The function to invoke
2838 * @param {*} context The context to use when calling the function
2839 * @param {...*} args Arguments for function
2840 */
2841
2842
2843/**
2844 * During execution of guarded functions we will capture the first error which
2845 * we will rethrow to be handled by the top level error handler.
2846 */
2847
2848
2849function hasCaughtError() {
2850 return hasError;
2851}
2852
2853function clearCaughtError() {
2854 if (hasError) {
2855 var error = caughtError;
2856 hasError = false;
2857 caughtError = null;
2858 return error;
2859 } else {
2860 (function () {
2861 {
2862 {
2863 throw ReactError('clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.');
2864 }
2865 }
2866 })();
2867 }
2868}
2869
2870/**
2871 * Forked from fbjs/warning:
2872 * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
2873 *
2874 * Only change is we use console.warn instead of console.error,
2875 * and do nothing when 'console' is not supported.
2876 * This really simplifies the code.
2877 * ---
2878 * Similar to invariant but only logs a warning if the condition is not met.
2879 * This can be used to log issues in development environments in critical
2880 * paths. Removing the logging code for production environments will keep the
2881 * same logic and follow the same code paths.
2882 */
2883
2884var lowPriorityWarning = function () {};
2885
2886{
2887 var printWarning$1 = function (format) {
2888 for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
2889 args[_key - 1] = arguments[_key];
2890 }
2891
2892 var argIndex = 0;
2893 var message = 'Warning: ' + format.replace(/%s/g, function () {
2894 return args[argIndex++];
2895 });
2896 if (typeof console !== 'undefined') {
2897 console.warn(message);
2898 }
2899 try {
2900 // --- Welcome to debugging React ---
2901 // This error was thrown as a convenience so that you can use this stack
2902 // to find the callsite that caused this warning to fire.
2903 throw new Error(message);
2904 } catch (x) {}
2905 };
2906
2907 lowPriorityWarning = function (condition, format) {
2908 if (format === undefined) {
2909 throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument');
2910 }
2911 if (!condition) {
2912 for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
2913 args[_key2 - 2] = arguments[_key2];
2914 }
2915
2916 printWarning$1.apply(undefined, [format].concat(args));
2917 }
2918 };
2919}
2920
2921var lowPriorityWarning$1 = lowPriorityWarning;
2922
2923var ReactStrictModeWarnings = {
2924 discardPendingWarnings: function () {},
2925 flushPendingDeprecationWarnings: function () {},
2926 flushPendingUnsafeLifecycleWarnings: function () {},
2927 recordDeprecationWarnings: function (fiber, instance) {},
2928 recordUnsafeLifecycleWarnings: function (fiber, instance) {},
2929 recordLegacyContextWarning: function (fiber, instance) {},
2930 flushLegacyContextWarning: function () {}
2931};
2932
2933{
2934 var LIFECYCLE_SUGGESTIONS = {
2935 UNSAFE_componentWillMount: 'componentDidMount',
2936 UNSAFE_componentWillReceiveProps: 'static getDerivedStateFromProps',
2937 UNSAFE_componentWillUpdate: 'componentDidUpdate'
2938 };
2939
2940 var pendingComponentWillMountWarnings = [];
2941 var pendingComponentWillReceivePropsWarnings = [];
2942 var pendingComponentWillUpdateWarnings = [];
2943 var pendingUnsafeLifecycleWarnings = new Map();
2944 var pendingLegacyContextWarning = new Map();
2945
2946 // Tracks components we have already warned about.
2947 var didWarnAboutDeprecatedLifecycles = new Set();
2948 var didWarnAboutUnsafeLifecycles = new Set();
2949 var didWarnAboutLegacyContext = new Set();
2950
2951 var setToSortedString = function (set) {
2952 var array = [];
2953 set.forEach(function (value) {
2954 array.push(value);
2955 });
2956 return array.sort().join(', ');
2957 };
2958
2959 ReactStrictModeWarnings.discardPendingWarnings = function () {
2960 pendingComponentWillMountWarnings = [];
2961 pendingComponentWillReceivePropsWarnings = [];
2962 pendingComponentWillUpdateWarnings = [];
2963 pendingUnsafeLifecycleWarnings = new Map();
2964 pendingLegacyContextWarning = new Map();
2965 };
2966
2967 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
2968 pendingUnsafeLifecycleWarnings.forEach(function (lifecycleWarningsMap, strictRoot) {
2969 var lifecyclesWarningMessages = [];
2970
2971 Object.keys(lifecycleWarningsMap).forEach(function (lifecycle) {
2972 var lifecycleWarnings = lifecycleWarningsMap[lifecycle];
2973 if (lifecycleWarnings.length > 0) {
2974 var componentNames = new Set();
2975 lifecycleWarnings.forEach(function (fiber) {
2976 componentNames.add(getComponentName(fiber.type) || 'Component');
2977 didWarnAboutUnsafeLifecycles.add(fiber.type);
2978 });
2979
2980 var formatted = lifecycle.replace('UNSAFE_', '');
2981 var suggestion = LIFECYCLE_SUGGESTIONS[lifecycle];
2982 var sortedComponentNames = setToSortedString(componentNames);
2983
2984 lifecyclesWarningMessages.push(formatted + ': Please update the following components to use ' + (suggestion + ' instead: ' + sortedComponentNames));
2985 }
2986 });
2987
2988 if (lifecyclesWarningMessages.length > 0) {
2989 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
2990
2991 warningWithoutStack$1(false, 'Unsafe lifecycle methods were found within a strict-mode tree:%s' + '\n\n%s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-strict-mode-warnings', strictRootComponentStack, lifecyclesWarningMessages.join('\n\n'));
2992 }
2993 });
2994
2995 pendingUnsafeLifecycleWarnings = new Map();
2996 };
2997
2998 var findStrictRoot = function (fiber) {
2999 var maybeStrictRoot = null;
3000
3001 var node = fiber;
3002 while (node !== null) {
3003 if (node.mode & StrictMode) {
3004 maybeStrictRoot = node;
3005 }
3006 node = node.return;
3007 }
3008
3009 return maybeStrictRoot;
3010 };
3011
3012 ReactStrictModeWarnings.flushPendingDeprecationWarnings = function () {
3013 if (pendingComponentWillMountWarnings.length > 0) {
3014 var uniqueNames = new Set();
3015 pendingComponentWillMountWarnings.forEach(function (fiber) {
3016 uniqueNames.add(getComponentName(fiber.type) || 'Component');
3017 didWarnAboutDeprecatedLifecycles.add(fiber.type);
3018 });
3019
3020 var sortedNames = setToSortedString(uniqueNames);
3021
3022 lowPriorityWarning$1(false, 'componentWillMount is deprecated and will be removed in the next major version. ' + 'Use componentDidMount instead. As a temporary workaround, ' + 'you can rename to UNSAFE_componentWillMount.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-async-component-lifecycle-hooks', sortedNames);
3023
3024 pendingComponentWillMountWarnings = [];
3025 }
3026
3027 if (pendingComponentWillReceivePropsWarnings.length > 0) {
3028 var _uniqueNames = new Set();
3029 pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
3030 _uniqueNames.add(getComponentName(fiber.type) || 'Component');
3031 didWarnAboutDeprecatedLifecycles.add(fiber.type);
3032 });
3033
3034 var _sortedNames = setToSortedString(_uniqueNames);
3035
3036 lowPriorityWarning$1(false, 'componentWillReceiveProps is deprecated and will be removed in the next major version. ' + 'Use static getDerivedStateFromProps instead.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-async-component-lifecycle-hooks', _sortedNames);
3037
3038 pendingComponentWillReceivePropsWarnings = [];
3039 }
3040
3041 if (pendingComponentWillUpdateWarnings.length > 0) {
3042 var _uniqueNames2 = new Set();
3043 pendingComponentWillUpdateWarnings.forEach(function (fiber) {
3044 _uniqueNames2.add(getComponentName(fiber.type) || 'Component');
3045 didWarnAboutDeprecatedLifecycles.add(fiber.type);
3046 });
3047
3048 var _sortedNames2 = setToSortedString(_uniqueNames2);
3049
3050 lowPriorityWarning$1(false, 'componentWillUpdate is deprecated and will be removed in the next major version. ' + 'Use componentDidUpdate instead. As a temporary workaround, ' + 'you can rename to UNSAFE_componentWillUpdate.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-async-component-lifecycle-hooks', _sortedNames2);
3051
3052 pendingComponentWillUpdateWarnings = [];
3053 }
3054 };
3055
3056 ReactStrictModeWarnings.recordDeprecationWarnings = function (fiber, instance) {
3057 // Dedup strategy: Warn once per component.
3058 if (didWarnAboutDeprecatedLifecycles.has(fiber.type)) {
3059 return;
3060 }
3061
3062 // Don't warn about react-lifecycles-compat polyfilled components.
3063 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
3064 pendingComponentWillMountWarnings.push(fiber);
3065 }
3066 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
3067 pendingComponentWillReceivePropsWarnings.push(fiber);
3068 }
3069 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
3070 pendingComponentWillUpdateWarnings.push(fiber);
3071 }
3072 };
3073
3074 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
3075 var strictRoot = findStrictRoot(fiber);
3076 if (strictRoot === null) {
3077 warningWithoutStack$1(false, 'Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.');
3078 return;
3079 }
3080
3081 // Dedup strategy: Warn once per component.
3082 // This is difficult to track any other way since component names
3083 // are often vague and are likely to collide between 3rd party libraries.
3084 // An expand property is probably okay to use here since it's DEV-only,
3085 // and will only be set in the event of serious warnings.
3086 if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
3087 return;
3088 }
3089
3090 var warningsForRoot = void 0;
3091 if (!pendingUnsafeLifecycleWarnings.has(strictRoot)) {
3092 warningsForRoot = {
3093 UNSAFE_componentWillMount: [],
3094 UNSAFE_componentWillReceiveProps: [],
3095 UNSAFE_componentWillUpdate: []
3096 };
3097
3098 pendingUnsafeLifecycleWarnings.set(strictRoot, warningsForRoot);
3099 } else {
3100 warningsForRoot = pendingUnsafeLifecycleWarnings.get(strictRoot);
3101 }
3102
3103 var unsafeLifecycles = [];
3104 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillMount === 'function') {
3105 unsafeLifecycles.push('UNSAFE_componentWillMount');
3106 }
3107 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
3108 unsafeLifecycles.push('UNSAFE_componentWillReceiveProps');
3109 }
3110 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillUpdate === 'function') {
3111 unsafeLifecycles.push('UNSAFE_componentWillUpdate');
3112 }
3113
3114 if (unsafeLifecycles.length > 0) {
3115 unsafeLifecycles.forEach(function (lifecycle) {
3116 warningsForRoot[lifecycle].push(fiber);
3117 });
3118 }
3119 };
3120
3121 ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
3122 var strictRoot = findStrictRoot(fiber);
3123 if (strictRoot === null) {
3124 warningWithoutStack$1(false, 'Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.');
3125 return;
3126 }
3127
3128 // Dedup strategy: Warn once per component.
3129 if (didWarnAboutLegacyContext.has(fiber.type)) {
3130 return;
3131 }
3132
3133 var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
3134
3135 if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
3136 if (warningsForRoot === undefined) {
3137 warningsForRoot = [];
3138 pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
3139 }
3140 warningsForRoot.push(fiber);
3141 }
3142 };
3143
3144 ReactStrictModeWarnings.flushLegacyContextWarning = function () {
3145 pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
3146 var uniqueNames = new Set();
3147 fiberArray.forEach(function (fiber) {
3148 uniqueNames.add(getComponentName(fiber.type) || 'Component');
3149 didWarnAboutLegacyContext.add(fiber.type);
3150 });
3151
3152 var sortedNames = setToSortedString(uniqueNames);
3153 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
3154
3155 warningWithoutStack$1(false, 'Legacy context API has been detected within a strict-mode tree: %s' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-strict-mode-warnings', strictRootComponentStack, sortedNames);
3156 });
3157 };
3158}
3159
3160// This lets us hook into Fiber to debug what it's doing.
3161// See https://github.com/facebook/react/pull/8033.
3162// This is not part of the public API, not even for React DevTools.
3163// You may only inject a debugTool if you work on React Fiber itself.
3164var ReactFiberInstrumentation = {
3165 debugTool: null
3166};
3167
3168var ReactFiberInstrumentation_1 = ReactFiberInstrumentation;
3169
3170// TODO: Offscreen updates should never suspend. However, a promise that
3171// suspended inside an offscreen subtree should be able to ping at the priority
3172// of the outer render.
3173
3174function markPendingPriorityLevel(root, expirationTime) {
3175 // If there's a gap between completing a failed root and retrying it,
3176 // additional updates may be scheduled. Clear `didError`, in case the update
3177 // is sufficient to fix the error.
3178 root.didError = false;
3179
3180 // Update the latest and earliest pending times
3181 var earliestPendingTime = root.earliestPendingTime;
3182 if (earliestPendingTime === NoWork) {
3183 // No other pending updates.
3184 root.earliestPendingTime = root.latestPendingTime = expirationTime;
3185 } else {
3186 if (earliestPendingTime < expirationTime) {
3187 // This is the earliest pending update.
3188 root.earliestPendingTime = expirationTime;
3189 } else {
3190 var latestPendingTime = root.latestPendingTime;
3191 if (latestPendingTime > expirationTime) {
3192 // This is the latest pending update
3193 root.latestPendingTime = expirationTime;
3194 }
3195 }
3196 }
3197 findNextExpirationTimeToWorkOn(expirationTime, root);
3198}
3199
3200function markCommittedPriorityLevels(root, earliestRemainingTime) {
3201 root.didError = false;
3202
3203 if (earliestRemainingTime === NoWork) {
3204 // Fast path. There's no remaining work. Clear everything.
3205 root.earliestPendingTime = NoWork;
3206 root.latestPendingTime = NoWork;
3207 root.earliestSuspendedTime = NoWork;
3208 root.latestSuspendedTime = NoWork;
3209 root.latestPingedTime = NoWork;
3210 findNextExpirationTimeToWorkOn(NoWork, root);
3211 return;
3212 }
3213
3214 if (earliestRemainingTime < root.latestPingedTime) {
3215 root.latestPingedTime = NoWork;
3216 }
3217
3218 // Let's see if the previous latest known pending level was just flushed.
3219 var latestPendingTime = root.latestPendingTime;
3220 if (latestPendingTime !== NoWork) {
3221 if (latestPendingTime > earliestRemainingTime) {
3222 // We've flushed all the known pending levels.
3223 root.earliestPendingTime = root.latestPendingTime = NoWork;
3224 } else {
3225 var earliestPendingTime = root.earliestPendingTime;
3226 if (earliestPendingTime > earliestRemainingTime) {
3227 // We've flushed the earliest known pending level. Set this to the
3228 // latest pending time.
3229 root.earliestPendingTime = root.latestPendingTime;
3230 }
3231 }
3232 }
3233
3234 // Now let's handle the earliest remaining level in the whole tree. We need to
3235 // decide whether to treat it as a pending level or as suspended. Check
3236 // it falls within the range of known suspended levels.
3237
3238 var earliestSuspendedTime = root.earliestSuspendedTime;
3239 if (earliestSuspendedTime === NoWork) {
3240 // There's no suspended work. Treat the earliest remaining level as a
3241 // pending level.
3242 markPendingPriorityLevel(root, earliestRemainingTime);
3243 findNextExpirationTimeToWorkOn(NoWork, root);
3244 return;
3245 }
3246
3247 var latestSuspendedTime = root.latestSuspendedTime;
3248 if (earliestRemainingTime < latestSuspendedTime) {
3249 // The earliest remaining level is later than all the suspended work. That
3250 // means we've flushed all the suspended work.
3251 root.earliestSuspendedTime = NoWork;
3252 root.latestSuspendedTime = NoWork;
3253 root.latestPingedTime = NoWork;
3254
3255 // There's no suspended work. Treat the earliest remaining level as a
3256 // pending level.
3257 markPendingPriorityLevel(root, earliestRemainingTime);
3258 findNextExpirationTimeToWorkOn(NoWork, root);
3259 return;
3260 }
3261
3262 if (earliestRemainingTime > earliestSuspendedTime) {
3263 // The earliest remaining time is earlier than all the suspended work.
3264 // Treat it as a pending update.
3265 markPendingPriorityLevel(root, earliestRemainingTime);
3266 findNextExpirationTimeToWorkOn(NoWork, root);
3267 return;
3268 }
3269
3270 // The earliest remaining time falls within the range of known suspended
3271 // levels. We should treat this as suspended work.
3272 findNextExpirationTimeToWorkOn(NoWork, root);
3273}
3274
3275function hasLowerPriorityWork(root, erroredExpirationTime) {
3276 var latestPendingTime = root.latestPendingTime;
3277 var latestSuspendedTime = root.latestSuspendedTime;
3278 var latestPingedTime = root.latestPingedTime;
3279 return latestPendingTime !== NoWork && latestPendingTime < erroredExpirationTime || latestSuspendedTime !== NoWork && latestSuspendedTime < erroredExpirationTime || latestPingedTime !== NoWork && latestPingedTime < erroredExpirationTime;
3280}
3281
3282function isPriorityLevelSuspended(root, expirationTime) {
3283 var earliestSuspendedTime = root.earliestSuspendedTime;
3284 var latestSuspendedTime = root.latestSuspendedTime;
3285 return earliestSuspendedTime !== NoWork && expirationTime <= earliestSuspendedTime && expirationTime >= latestSuspendedTime;
3286}
3287
3288function markSuspendedPriorityLevel(root, suspendedTime) {
3289 root.didError = false;
3290 clearPing(root, suspendedTime);
3291
3292 // First, check the known pending levels and update them if needed.
3293 var earliestPendingTime = root.earliestPendingTime;
3294 var latestPendingTime = root.latestPendingTime;
3295 if (earliestPendingTime === suspendedTime) {
3296 if (latestPendingTime === suspendedTime) {
3297 // Both known pending levels were suspended. Clear them.
3298 root.earliestPendingTime = root.latestPendingTime = NoWork;
3299 } else {
3300 // The earliest pending level was suspended. Clear by setting it to the
3301 // latest pending level.
3302 root.earliestPendingTime = latestPendingTime;
3303 }
3304 } else if (latestPendingTime === suspendedTime) {
3305 // The latest pending level was suspended. Clear by setting it to the
3306 // latest pending level.
3307 root.latestPendingTime = earliestPendingTime;
3308 }
3309
3310 // Finally, update the known suspended levels.
3311 var earliestSuspendedTime = root.earliestSuspendedTime;
3312 var latestSuspendedTime = root.latestSuspendedTime;
3313 if (earliestSuspendedTime === NoWork) {
3314 // No other suspended levels.
3315 root.earliestSuspendedTime = root.latestSuspendedTime = suspendedTime;
3316 } else {
3317 if (earliestSuspendedTime < suspendedTime) {
3318 // This is the earliest suspended level.
3319 root.earliestSuspendedTime = suspendedTime;
3320 } else if (latestSuspendedTime > suspendedTime) {
3321 // This is the latest suspended level
3322 root.latestSuspendedTime = suspendedTime;
3323 }
3324 }
3325
3326 findNextExpirationTimeToWorkOn(suspendedTime, root);
3327}
3328
3329function markPingedPriorityLevel(root, pingedTime) {
3330 root.didError = false;
3331
3332 // TODO: When we add back resuming, we need to ensure the progressed work
3333 // is thrown out and not reused during the restarted render. One way to
3334 // invalidate the progressed work is to restart at expirationTime + 1.
3335 var latestPingedTime = root.latestPingedTime;
3336 if (latestPingedTime === NoWork || latestPingedTime > pingedTime) {
3337 root.latestPingedTime = pingedTime;
3338 }
3339 findNextExpirationTimeToWorkOn(pingedTime, root);
3340}
3341
3342function clearPing(root, completedTime) {
3343 var latestPingedTime = root.latestPingedTime;
3344 if (latestPingedTime >= completedTime) {
3345 root.latestPingedTime = NoWork;
3346 }
3347}
3348
3349function findEarliestOutstandingPriorityLevel(root, renderExpirationTime) {
3350 var earliestExpirationTime = renderExpirationTime;
3351
3352 var earliestPendingTime = root.earliestPendingTime;
3353 var earliestSuspendedTime = root.earliestSuspendedTime;
3354 if (earliestPendingTime > earliestExpirationTime) {
3355 earliestExpirationTime = earliestPendingTime;
3356 }
3357 if (earliestSuspendedTime > earliestExpirationTime) {
3358 earliestExpirationTime = earliestSuspendedTime;
3359 }
3360 return earliestExpirationTime;
3361}
3362
3363function didExpireAtExpirationTime(root, currentTime) {
3364 var expirationTime = root.expirationTime;
3365 if (expirationTime !== NoWork && currentTime <= expirationTime) {
3366 // The root has expired. Flush all work up to the current time.
3367 root.nextExpirationTimeToWorkOn = currentTime;
3368 }
3369}
3370
3371function findNextExpirationTimeToWorkOn(completedExpirationTime, root) {
3372 var earliestSuspendedTime = root.earliestSuspendedTime;
3373 var latestSuspendedTime = root.latestSuspendedTime;
3374 var earliestPendingTime = root.earliestPendingTime;
3375 var latestPingedTime = root.latestPingedTime;
3376
3377 // Work on the earliest pending time. Failing that, work on the latest
3378 // pinged time.
3379 var nextExpirationTimeToWorkOn = earliestPendingTime !== NoWork ? earliestPendingTime : latestPingedTime;
3380
3381 // If there is no pending or pinged work, check if there's suspended work
3382 // that's lower priority than what we just completed.
3383 if (nextExpirationTimeToWorkOn === NoWork && (completedExpirationTime === NoWork || latestSuspendedTime < completedExpirationTime)) {
3384 // The lowest priority suspended work is the work most likely to be
3385 // committed next. Let's start rendering it again, so that if it times out,
3386 // it's ready to commit.
3387 nextExpirationTimeToWorkOn = latestSuspendedTime;
3388 }
3389
3390 var expirationTime = nextExpirationTimeToWorkOn;
3391 if (expirationTime !== NoWork && earliestSuspendedTime > expirationTime) {
3392 // Expire using the earliest known expiration time.
3393 expirationTime = earliestSuspendedTime;
3394 }
3395
3396 root.nextExpirationTimeToWorkOn = nextExpirationTimeToWorkOn;
3397 root.expirationTime = expirationTime;
3398}
3399
3400/**
3401 * inlined Object.is polyfill to avoid requiring consumers ship their own
3402 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
3403 */
3404function is(x, y) {
3405 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
3406 ;
3407}
3408
3409var hasOwnProperty = Object.prototype.hasOwnProperty;
3410
3411/**
3412 * Performs equality by iterating through keys on an object and returning false
3413 * when any key has values which are not strictly equal between the arguments.
3414 * Returns true when the values of all keys are strictly equal.
3415 */
3416function shallowEqual(objA, objB) {
3417 if (is(objA, objB)) {
3418 return true;
3419 }
3420
3421 if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
3422 return false;
3423 }
3424
3425 var keysA = Object.keys(objA);
3426 var keysB = Object.keys(objB);
3427
3428 if (keysA.length !== keysB.length) {
3429 return false;
3430 }
3431
3432 // Test for A's keys different from B.
3433 for (var i = 0; i < keysA.length; i++) {
3434 if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
3435 return false;
3436 }
3437 }
3438
3439 return true;
3440}
3441
3442function resolveDefaultProps(Component, baseProps) {
3443 if (Component && Component.defaultProps) {
3444 // Resolve default props. Taken from ReactElement
3445 var props = _assign({}, baseProps);
3446 var defaultProps = Component.defaultProps;
3447 for (var propName in defaultProps) {
3448 if (props[propName] === undefined) {
3449 props[propName] = defaultProps[propName];
3450 }
3451 }
3452 return props;
3453 }
3454 return baseProps;
3455}
3456
3457function readLazyComponentType(lazyComponent) {
3458 var status = lazyComponent._status;
3459 var result = lazyComponent._result;
3460 switch (status) {
3461 case Resolved:
3462 {
3463 var Component = result;
3464 return Component;
3465 }
3466 case Rejected:
3467 {
3468 var error = result;
3469 throw error;
3470 }
3471 case Pending:
3472 {
3473 var thenable = result;
3474 throw thenable;
3475 }
3476 default:
3477 {
3478 lazyComponent._status = Pending;
3479 var ctor = lazyComponent._ctor;
3480 var _thenable = ctor();
3481 _thenable.then(function (moduleObject) {
3482 if (lazyComponent._status === Pending) {
3483 var defaultExport = moduleObject.default;
3484 {
3485 if (defaultExport === undefined) {
3486 warning$1(false, 'lazy: Expected the result of a dynamic import() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + "const MyComponent = lazy(() => import('./MyComponent'))", moduleObject);
3487 }
3488 }
3489 lazyComponent._status = Resolved;
3490 lazyComponent._result = defaultExport;
3491 }
3492 }, function (error) {
3493 if (lazyComponent._status === Pending) {
3494 lazyComponent._status = Rejected;
3495 lazyComponent._result = error;
3496 }
3497 });
3498 // Handle synchronous thenables.
3499 switch (lazyComponent._status) {
3500 case Resolved:
3501 return lazyComponent._result;
3502 case Rejected:
3503 throw lazyComponent._result;
3504 }
3505 lazyComponent._result = _thenable;
3506 throw _thenable;
3507 }
3508 }
3509}
3510
3511var fakeInternalInstance = {};
3512var isArray$1 = Array.isArray;
3513
3514// React.Component uses a shared frozen object by default.
3515// We'll use it to determine whether we need to initialize legacy refs.
3516var emptyRefsObject = new React.Component().refs;
3517
3518var didWarnAboutStateAssignmentForComponent = void 0;
3519var didWarnAboutUninitializedState = void 0;
3520var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = void 0;
3521var didWarnAboutLegacyLifecyclesAndDerivedState = void 0;
3522var didWarnAboutUndefinedDerivedState = void 0;
3523var warnOnUndefinedDerivedState = void 0;
3524var warnOnInvalidCallback = void 0;
3525var didWarnAboutDirectlyAssigningPropsToState = void 0;
3526var didWarnAboutContextTypeAndContextTypes = void 0;
3527var didWarnAboutInvalidateContextType = void 0;
3528
3529{
3530 didWarnAboutStateAssignmentForComponent = new Set();
3531 didWarnAboutUninitializedState = new Set();
3532 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
3533 didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
3534 didWarnAboutDirectlyAssigningPropsToState = new Set();
3535 didWarnAboutUndefinedDerivedState = new Set();
3536 didWarnAboutContextTypeAndContextTypes = new Set();
3537 didWarnAboutInvalidateContextType = new Set();
3538
3539 var didWarnOnInvalidCallback = new Set();
3540
3541 warnOnInvalidCallback = function (callback, callerName) {
3542 if (callback === null || typeof callback === 'function') {
3543 return;
3544 }
3545 var key = callerName + '_' + callback;
3546 if (!didWarnOnInvalidCallback.has(key)) {
3547 didWarnOnInvalidCallback.add(key);
3548 warningWithoutStack$1(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
3549 }
3550 };
3551
3552 warnOnUndefinedDerivedState = function (type, partialState) {
3553 if (partialState === undefined) {
3554 var componentName = getComponentName(type) || 'Component';
3555 if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
3556 didWarnAboutUndefinedDerivedState.add(componentName);
3557 warningWithoutStack$1(false, '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
3558 }
3559 }
3560 };
3561
3562 // This is so gross but it's at least non-critical and can be removed if
3563 // it causes problems. This is meant to give a nicer error message for
3564 // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
3565 // ...)) which otherwise throws a "_processChildContext is not a function"
3566 // exception.
3567 Object.defineProperty(fakeInternalInstance, '_processChildContext', {
3568 enumerable: false,
3569 value: function () {
3570 (function () {
3571 {
3572 {
3573 throw ReactError('_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn\'t supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal).');
3574 }
3575 }
3576 })();
3577 }
3578 });
3579 Object.freeze(fakeInternalInstance);
3580}
3581
3582function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
3583 var prevState = workInProgress.memoizedState;
3584
3585 {
3586 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
3587 // Invoke the function an extra time to help detect side-effects.
3588 getDerivedStateFromProps(nextProps, prevState);
3589 }
3590 }
3591
3592 var partialState = getDerivedStateFromProps(nextProps, prevState);
3593
3594 {
3595 warnOnUndefinedDerivedState(ctor, partialState);
3596 }
3597 // Merge the partial state and the previous state.
3598 var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
3599 workInProgress.memoizedState = memoizedState;
3600
3601 // Once the update queue is empty, persist the derived state onto the
3602 // base state.
3603 var updateQueue = workInProgress.updateQueue;
3604 if (updateQueue !== null && workInProgress.expirationTime === NoWork) {
3605 updateQueue.baseState = memoizedState;
3606 }
3607}
3608
3609var classComponentUpdater = {
3610 isMounted: isMounted,
3611 enqueueSetState: function (inst, payload, callback) {
3612 var fiber = get(inst);
3613 var currentTime = requestCurrentTime$$1();
3614 var expirationTime = computeExpirationForFiber$$1(currentTime, fiber);
3615
3616 var update = createUpdate(expirationTime);
3617 update.payload = payload;
3618 if (callback !== undefined && callback !== null) {
3619 {
3620 warnOnInvalidCallback(callback, 'setState');
3621 }
3622 update.callback = callback;
3623 }
3624
3625 flushPassiveEffects$$1();
3626 enqueueUpdate(fiber, update);
3627 scheduleWork$$1(fiber, expirationTime);
3628 },
3629 enqueueReplaceState: function (inst, payload, callback) {
3630 var fiber = get(inst);
3631 var currentTime = requestCurrentTime$$1();
3632 var expirationTime = computeExpirationForFiber$$1(currentTime, fiber);
3633
3634 var update = createUpdate(expirationTime);
3635 update.tag = ReplaceState;
3636 update.payload = payload;
3637
3638 if (callback !== undefined && callback !== null) {
3639 {
3640 warnOnInvalidCallback(callback, 'replaceState');
3641 }
3642 update.callback = callback;
3643 }
3644
3645 flushPassiveEffects$$1();
3646 enqueueUpdate(fiber, update);
3647 scheduleWork$$1(fiber, expirationTime);
3648 },
3649 enqueueForceUpdate: function (inst, callback) {
3650 var fiber = get(inst);
3651 var currentTime = requestCurrentTime$$1();
3652 var expirationTime = computeExpirationForFiber$$1(currentTime, fiber);
3653
3654 var update = createUpdate(expirationTime);
3655 update.tag = ForceUpdate;
3656
3657 if (callback !== undefined && callback !== null) {
3658 {
3659 warnOnInvalidCallback(callback, 'forceUpdate');
3660 }
3661 update.callback = callback;
3662 }
3663
3664 flushPassiveEffects$$1();
3665 enqueueUpdate(fiber, update);
3666 scheduleWork$$1(fiber, expirationTime);
3667 }
3668};
3669
3670function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
3671 var instance = workInProgress.stateNode;
3672 if (typeof instance.shouldComponentUpdate === 'function') {
3673 startPhaseTimer(workInProgress, 'shouldComponentUpdate');
3674 var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
3675 stopPhaseTimer();
3676
3677 {
3678 !(shouldUpdate !== undefined) ? warningWithoutStack$1(false, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentName(ctor) || 'Component') : void 0;
3679 }
3680
3681 return shouldUpdate;
3682 }
3683
3684 if (ctor.prototype && ctor.prototype.isPureReactComponent) {
3685 return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
3686 }
3687
3688 return true;
3689}
3690
3691function checkClassInstance(workInProgress, ctor, newProps) {
3692 var instance = workInProgress.stateNode;
3693 {
3694 var name = getComponentName(ctor) || 'Component';
3695 var renderPresent = instance.render;
3696
3697 if (!renderPresent) {
3698 if (ctor.prototype && typeof ctor.prototype.render === 'function') {
3699 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
3700 } else {
3701 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
3702 }
3703 }
3704
3705 var noGetInitialStateOnES6 = !instance.getInitialState || instance.getInitialState.isReactClassApproved || instance.state;
3706 !noGetInitialStateOnES6 ? warningWithoutStack$1(false, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name) : void 0;
3707 var noGetDefaultPropsOnES6 = !instance.getDefaultProps || instance.getDefaultProps.isReactClassApproved;
3708 !noGetDefaultPropsOnES6 ? warningWithoutStack$1(false, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name) : void 0;
3709 var noInstancePropTypes = !instance.propTypes;
3710 !noInstancePropTypes ? warningWithoutStack$1(false, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name) : void 0;
3711 var noInstanceContextType = !instance.contextType;
3712 !noInstanceContextType ? warningWithoutStack$1(false, 'contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name) : void 0;
3713 var noInstanceContextTypes = !instance.contextTypes;
3714 !noInstanceContextTypes ? warningWithoutStack$1(false, 'contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name) : void 0;
3715
3716 if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
3717 didWarnAboutContextTypeAndContextTypes.add(ctor);
3718 warningWithoutStack$1(false, '%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
3719 }
3720
3721 var noComponentShouldUpdate = typeof instance.componentShouldUpdate !== 'function';
3722 !noComponentShouldUpdate ? warningWithoutStack$1(false, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name) : void 0;
3723 if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
3724 warningWithoutStack$1(false, '%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentName(ctor) || 'A pure component');
3725 }
3726 var noComponentDidUnmount = typeof instance.componentDidUnmount !== 'function';
3727 !noComponentDidUnmount ? warningWithoutStack$1(false, '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name) : void 0;
3728 var noComponentDidReceiveProps = typeof instance.componentDidReceiveProps !== 'function';
3729 !noComponentDidReceiveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name) : void 0;
3730 var noComponentWillRecieveProps = typeof instance.componentWillRecieveProps !== 'function';
3731 !noComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name) : void 0;
3732 var noUnsafeComponentWillRecieveProps = typeof instance.UNSAFE_componentWillRecieveProps !== 'function';
3733 !noUnsafeComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name) : void 0;
3734 var hasMutatedProps = instance.props !== newProps;
3735 !(instance.props === undefined || !hasMutatedProps) ? warningWithoutStack$1(false, '%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name) : void 0;
3736 var noInstanceDefaultProps = !instance.defaultProps;
3737 !noInstanceDefaultProps ? warningWithoutStack$1(false, 'Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name) : void 0;
3738
3739 if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
3740 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
3741 warningWithoutStack$1(false, '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor));
3742 }
3743
3744 var noInstanceGetDerivedStateFromProps = typeof instance.getDerivedStateFromProps !== 'function';
3745 !noInstanceGetDerivedStateFromProps ? warningWithoutStack$1(false, '%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name) : void 0;
3746 var noInstanceGetDerivedStateFromCatch = typeof instance.getDerivedStateFromError !== 'function';
3747 !noInstanceGetDerivedStateFromCatch ? warningWithoutStack$1(false, '%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name) : void 0;
3748 var noStaticGetSnapshotBeforeUpdate = typeof ctor.getSnapshotBeforeUpdate !== 'function';
3749 !noStaticGetSnapshotBeforeUpdate ? warningWithoutStack$1(false, '%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name) : void 0;
3750 var _state = instance.state;
3751 if (_state && (typeof _state !== 'object' || isArray$1(_state))) {
3752 warningWithoutStack$1(false, '%s.state: must be set to an object or null', name);
3753 }
3754 if (typeof instance.getChildContext === 'function') {
3755 !(typeof ctor.childContextTypes === 'object') ? warningWithoutStack$1(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name) : void 0;
3756 }
3757 }
3758}
3759
3760function adoptClassInstance(workInProgress, instance) {
3761 instance.updater = classComponentUpdater;
3762 workInProgress.stateNode = instance;
3763 // The instance needs access to the fiber so that it can schedule updates
3764 set(instance, workInProgress);
3765 {
3766 instance._reactInternalInstance = fakeInternalInstance;
3767 }
3768}
3769
3770function constructClassInstance(workInProgress, ctor, props, renderExpirationTime) {
3771 var isLegacyContextConsumer = false;
3772 var unmaskedContext = emptyContextObject;
3773 var context = null;
3774 var contextType = ctor.contextType;
3775
3776 {
3777 if ('contextType' in ctor) {
3778 var isValid =
3779 // Allow null for conditional declaration
3780 contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>
3781
3782 if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
3783 didWarnAboutInvalidateContextType.add(ctor);
3784
3785 var addendum = '';
3786 if (contextType === undefined) {
3787 addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';
3788 } else if (typeof contextType !== 'object') {
3789 addendum = ' However, it is set to a ' + typeof contextType + '.';
3790 } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
3791 addendum = ' Did you accidentally pass the Context.Provider instead?';
3792 } else if (contextType._context !== undefined) {
3793 // <Context.Consumer>
3794 addendum = ' Did you accidentally pass the Context.Consumer instead?';
3795 } else {
3796 addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
3797 }
3798 warningWithoutStack$1(false, '%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentName(ctor) || 'Component', addendum);
3799 }
3800 }
3801 }
3802
3803 if (typeof contextType === 'object' && contextType !== null) {
3804 context = readContext(contextType);
3805 } else {
3806 unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
3807 var contextTypes = ctor.contextTypes;
3808 isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
3809 context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
3810 }
3811
3812 // Instantiate twice to help detect side-effects.
3813 {
3814 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
3815 new ctor(props, context); // eslint-disable-line no-new
3816 }
3817 }
3818
3819 var instance = new ctor(props, context);
3820 var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
3821 adoptClassInstance(workInProgress, instance);
3822
3823 {
3824 if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
3825 var componentName = getComponentName(ctor) || 'Component';
3826 if (!didWarnAboutUninitializedState.has(componentName)) {
3827 didWarnAboutUninitializedState.add(componentName);
3828 warningWithoutStack$1(false, '`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);
3829 }
3830 }
3831
3832 // If new component APIs are defined, "unsafe" lifecycles won't be called.
3833 // Warn about these lifecycles if they are present.
3834 // Don't warn about react-lifecycles-compat polyfilled methods though.
3835 if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
3836 var foundWillMountName = null;
3837 var foundWillReceivePropsName = null;
3838 var foundWillUpdateName = null;
3839 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
3840 foundWillMountName = 'componentWillMount';
3841 } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
3842 foundWillMountName = 'UNSAFE_componentWillMount';
3843 }
3844 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
3845 foundWillReceivePropsName = 'componentWillReceiveProps';
3846 } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
3847 foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
3848 }
3849 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
3850 foundWillUpdateName = 'componentWillUpdate';
3851 } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
3852 foundWillUpdateName = 'UNSAFE_componentWillUpdate';
3853 }
3854 if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
3855 var _componentName = getComponentName(ctor) || 'Component';
3856 var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
3857 if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
3858 didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
3859 warningWithoutStack$1(false, 'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://fb.me/react-async-component-lifecycle-hooks', _componentName, newApiName, foundWillMountName !== null ? '\n ' + foundWillMountName : '', foundWillReceivePropsName !== null ? '\n ' + foundWillReceivePropsName : '', foundWillUpdateName !== null ? '\n ' + foundWillUpdateName : '');
3860 }
3861 }
3862 }
3863 }
3864
3865 // Cache unmasked context so we can avoid recreating masked context unless necessary.
3866 // ReactFiberContext usually updates this cache but can't for newly-created instances.
3867 if (isLegacyContextConsumer) {
3868 cacheContext(workInProgress, unmaskedContext, context);
3869 }
3870
3871 return instance;
3872}
3873
3874function callComponentWillMount(workInProgress, instance) {
3875 startPhaseTimer(workInProgress, 'componentWillMount');
3876 var oldState = instance.state;
3877
3878 if (typeof instance.componentWillMount === 'function') {
3879 instance.componentWillMount();
3880 }
3881 if (typeof instance.UNSAFE_componentWillMount === 'function') {
3882 instance.UNSAFE_componentWillMount();
3883 }
3884
3885 stopPhaseTimer();
3886
3887 if (oldState !== instance.state) {
3888 {
3889 warningWithoutStack$1(false, '%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentName(workInProgress.type) || 'Component');
3890 }
3891 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
3892 }
3893}
3894
3895function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
3896 var oldState = instance.state;
3897 startPhaseTimer(workInProgress, 'componentWillReceiveProps');
3898 if (typeof instance.componentWillReceiveProps === 'function') {
3899 instance.componentWillReceiveProps(newProps, nextContext);
3900 }
3901 if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
3902 instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
3903 }
3904 stopPhaseTimer();
3905
3906 if (instance.state !== oldState) {
3907 {
3908 var componentName = getComponentName(workInProgress.type) || 'Component';
3909 if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
3910 didWarnAboutStateAssignmentForComponent.add(componentName);
3911 warningWithoutStack$1(false, '%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
3912 }
3913 }
3914 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
3915 }
3916}
3917
3918// Invokes the mount life-cycles on a previously never rendered instance.
3919function mountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
3920 {
3921 checkClassInstance(workInProgress, ctor, newProps);
3922 }
3923
3924 var instance = workInProgress.stateNode;
3925 instance.props = newProps;
3926 instance.state = workInProgress.memoizedState;
3927 instance.refs = emptyRefsObject;
3928
3929 var contextType = ctor.contextType;
3930 if (typeof contextType === 'object' && contextType !== null) {
3931 instance.context = readContext(contextType);
3932 } else {
3933 var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
3934 instance.context = getMaskedContext(workInProgress, unmaskedContext);
3935 }
3936
3937 {
3938 if (instance.state === newProps) {
3939 var componentName = getComponentName(ctor) || 'Component';
3940 if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
3941 didWarnAboutDirectlyAssigningPropsToState.add(componentName);
3942 warningWithoutStack$1(false, '%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName);
3943 }
3944 }
3945
3946 if (workInProgress.mode & StrictMode) {
3947 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
3948
3949 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
3950 }
3951
3952 if (warnAboutDeprecatedLifecycles) {
3953 ReactStrictModeWarnings.recordDeprecationWarnings(workInProgress, instance);
3954 }
3955 }
3956
3957 var updateQueue = workInProgress.updateQueue;
3958 if (updateQueue !== null) {
3959 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
3960 instance.state = workInProgress.memoizedState;
3961 }
3962
3963 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
3964 if (typeof getDerivedStateFromProps === 'function') {
3965 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
3966 instance.state = workInProgress.memoizedState;
3967 }
3968
3969 // In order to support react-lifecycles-compat polyfilled components,
3970 // Unsafe lifecycles should not be invoked for components using the new APIs.
3971 if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
3972 callComponentWillMount(workInProgress, instance);
3973 // If we had additional state updates during this life-cycle, let's
3974 // process them now.
3975 updateQueue = workInProgress.updateQueue;
3976 if (updateQueue !== null) {
3977 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
3978 instance.state = workInProgress.memoizedState;
3979 }
3980 }
3981
3982 if (typeof instance.componentDidMount === 'function') {
3983 workInProgress.effectTag |= Update;
3984 }
3985}
3986
3987function resumeMountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
3988 var instance = workInProgress.stateNode;
3989
3990 var oldProps = workInProgress.memoizedProps;
3991 instance.props = oldProps;
3992
3993 var oldContext = instance.context;
3994 var contextType = ctor.contextType;
3995 var nextContext = void 0;
3996 if (typeof contextType === 'object' && contextType !== null) {
3997 nextContext = readContext(contextType);
3998 } else {
3999 var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
4000 nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
4001 }
4002
4003 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
4004 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';
4005
4006 // Note: During these life-cycles, instance.props/instance.state are what
4007 // ever the previously attempted to render - not the "current". However,
4008 // during componentDidUpdate we pass the "current" props.
4009
4010 // In order to support react-lifecycles-compat polyfilled components,
4011 // Unsafe lifecycles should not be invoked for components using the new APIs.
4012 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
4013 if (oldProps !== newProps || oldContext !== nextContext) {
4014 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
4015 }
4016 }
4017
4018 resetHasForceUpdateBeforeProcessing();
4019
4020 var oldState = workInProgress.memoizedState;
4021 var newState = instance.state = oldState;
4022 var updateQueue = workInProgress.updateQueue;
4023 if (updateQueue !== null) {
4024 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
4025 newState = workInProgress.memoizedState;
4026 }
4027 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
4028 // If an update was already in progress, we should schedule an Update
4029 // effect even though we're bailing out, so that cWU/cDU are called.
4030 if (typeof instance.componentDidMount === 'function') {
4031 workInProgress.effectTag |= Update;
4032 }
4033 return false;
4034 }
4035
4036 if (typeof getDerivedStateFromProps === 'function') {
4037 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
4038 newState = workInProgress.memoizedState;
4039 }
4040
4041 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
4042
4043 if (shouldUpdate) {
4044 // In order to support react-lifecycles-compat polyfilled components,
4045 // Unsafe lifecycles should not be invoked for components using the new APIs.
4046 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
4047 startPhaseTimer(workInProgress, 'componentWillMount');
4048 if (typeof instance.componentWillMount === 'function') {
4049 instance.componentWillMount();
4050 }
4051 if (typeof instance.UNSAFE_componentWillMount === 'function') {
4052 instance.UNSAFE_componentWillMount();
4053 }
4054 stopPhaseTimer();
4055 }
4056 if (typeof instance.componentDidMount === 'function') {
4057 workInProgress.effectTag |= Update;
4058 }
4059 } else {
4060 // If an update was already in progress, we should schedule an Update
4061 // effect even though we're bailing out, so that cWU/cDU are called.
4062 if (typeof instance.componentDidMount === 'function') {
4063 workInProgress.effectTag |= Update;
4064 }
4065
4066 // If shouldComponentUpdate returned false, we should still update the
4067 // memoized state to indicate that this work can be reused.
4068 workInProgress.memoizedProps = newProps;
4069 workInProgress.memoizedState = newState;
4070 }
4071
4072 // Update the existing instance's state, props, and context pointers even
4073 // if shouldComponentUpdate returns false.
4074 instance.props = newProps;
4075 instance.state = newState;
4076 instance.context = nextContext;
4077
4078 return shouldUpdate;
4079}
4080
4081// Invokes the update life-cycles and returns false if it shouldn't rerender.
4082function updateClassInstance(current, workInProgress, ctor, newProps, renderExpirationTime) {
4083 var instance = workInProgress.stateNode;
4084
4085 var oldProps = workInProgress.memoizedProps;
4086 instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps);
4087
4088 var oldContext = instance.context;
4089 var contextType = ctor.contextType;
4090 var nextContext = void 0;
4091 if (typeof contextType === 'object' && contextType !== null) {
4092 nextContext = readContext(contextType);
4093 } else {
4094 var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
4095 nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
4096 }
4097
4098 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
4099 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';
4100
4101 // Note: During these life-cycles, instance.props/instance.state are what
4102 // ever the previously attempted to render - not the "current". However,
4103 // during componentDidUpdate we pass the "current" props.
4104
4105 // In order to support react-lifecycles-compat polyfilled components,
4106 // Unsafe lifecycles should not be invoked for components using the new APIs.
4107 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
4108 if (oldProps !== newProps || oldContext !== nextContext) {
4109 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
4110 }
4111 }
4112
4113 resetHasForceUpdateBeforeProcessing();
4114
4115 var oldState = workInProgress.memoizedState;
4116 var newState = instance.state = oldState;
4117 var updateQueue = workInProgress.updateQueue;
4118 if (updateQueue !== null) {
4119 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
4120 newState = workInProgress.memoizedState;
4121 }
4122
4123 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
4124 // If an update was already in progress, we should schedule an Update
4125 // effect even though we're bailing out, so that cWU/cDU are called.
4126 if (typeof instance.componentDidUpdate === 'function') {
4127 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
4128 workInProgress.effectTag |= Update;
4129 }
4130 }
4131 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
4132 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
4133 workInProgress.effectTag |= Snapshot;
4134 }
4135 }
4136 return false;
4137 }
4138
4139 if (typeof getDerivedStateFromProps === 'function') {
4140 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
4141 newState = workInProgress.memoizedState;
4142 }
4143
4144 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
4145
4146 if (shouldUpdate) {
4147 // In order to support react-lifecycles-compat polyfilled components,
4148 // Unsafe lifecycles should not be invoked for components using the new APIs.
4149 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
4150 startPhaseTimer(workInProgress, 'componentWillUpdate');
4151 if (typeof instance.componentWillUpdate === 'function') {
4152 instance.componentWillUpdate(newProps, newState, nextContext);
4153 }
4154 if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
4155 instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
4156 }
4157 stopPhaseTimer();
4158 }
4159 if (typeof instance.componentDidUpdate === 'function') {
4160 workInProgress.effectTag |= Update;
4161 }
4162 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
4163 workInProgress.effectTag |= Snapshot;
4164 }
4165 } else {
4166 // If an update was already in progress, we should schedule an Update
4167 // effect even though we're bailing out, so that cWU/cDU are called.
4168 if (typeof instance.componentDidUpdate === 'function') {
4169 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
4170 workInProgress.effectTag |= Update;
4171 }
4172 }
4173 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
4174 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
4175 workInProgress.effectTag |= Snapshot;
4176 }
4177 }
4178
4179 // If shouldComponentUpdate returned false, we should still update the
4180 // memoized props/state to indicate that this work can be reused.
4181 workInProgress.memoizedProps = newProps;
4182 workInProgress.memoizedState = newState;
4183 }
4184
4185 // Update the existing instance's state, props, and context pointers even
4186 // if shouldComponentUpdate returns false.
4187 instance.props = newProps;
4188 instance.state = newState;
4189 instance.context = nextContext;
4190
4191 return shouldUpdate;
4192}
4193
4194var didWarnAboutMaps = void 0;
4195var didWarnAboutGenerators = void 0;
4196var didWarnAboutStringRefInStrictMode = void 0;
4197var ownerHasKeyUseWarning = void 0;
4198var ownerHasFunctionTypeWarning = void 0;
4199var warnForMissingKey = function (child) {};
4200
4201{
4202 didWarnAboutMaps = false;
4203 didWarnAboutGenerators = false;
4204 didWarnAboutStringRefInStrictMode = {};
4205
4206 /**
4207 * Warn if there's no key explicitly set on dynamic arrays of children or
4208 * object keys are not valid. This allows us to keep track of children between
4209 * updates.
4210 */
4211 ownerHasKeyUseWarning = {};
4212 ownerHasFunctionTypeWarning = {};
4213
4214 warnForMissingKey = function (child) {
4215 if (child === null || typeof child !== 'object') {
4216 return;
4217 }
4218 if (!child._store || child._store.validated || child.key != null) {
4219 return;
4220 }
4221 (function () {
4222 if (!(typeof child._store === 'object')) {
4223 {
4224 throw ReactError('React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue.');
4225 }
4226 }
4227 })();
4228 child._store.validated = true;
4229
4230 var currentComponentErrorInfo = 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + getCurrentFiberStackInDev();
4231 if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
4232 return;
4233 }
4234 ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
4235
4236 warning$1(false, 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.');
4237 };
4238}
4239
4240var isArray = Array.isArray;
4241
4242function coerceRef(returnFiber, current$$1, element) {
4243 var mixedRef = element.ref;
4244 if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
4245 {
4246 if (returnFiber.mode & StrictMode) {
4247 var componentName = getComponentName(returnFiber.type) || 'Component';
4248 if (!didWarnAboutStringRefInStrictMode[componentName]) {
4249 warningWithoutStack$1(false, 'A string ref, "%s", has been found within a strict mode tree. ' + 'String refs are a source of potential bugs and should be avoided. ' + 'We recommend using createRef() instead.' + '\n%s' + '\n\nLearn more about using refs safely here:' + '\nhttps://fb.me/react-strict-mode-string-ref', mixedRef, getStackByFiberInDevAndProd(returnFiber));
4250 didWarnAboutStringRefInStrictMode[componentName] = true;
4251 }
4252 }
4253 }
4254
4255 if (element._owner) {
4256 var owner = element._owner;
4257 var inst = void 0;
4258 if (owner) {
4259 var ownerFiber = owner;
4260 (function () {
4261 if (!(ownerFiber.tag === ClassComponent)) {
4262 {
4263 throw ReactError('Function components cannot have refs. Did you mean to use React.forwardRef()?');
4264 }
4265 }
4266 })();
4267 inst = ownerFiber.stateNode;
4268 }
4269 (function () {
4270 if (!inst) {
4271 {
4272 throw ReactError('Missing owner for string ref ' + mixedRef + '. This error is likely caused by a bug in React. Please file an issue.');
4273 }
4274 }
4275 })();
4276 var stringRef = '' + mixedRef;
4277 // Check if previous string ref matches new string ref
4278 if (current$$1 !== null && current$$1.ref !== null && typeof current$$1.ref === 'function' && current$$1.ref._stringRef === stringRef) {
4279 return current$$1.ref;
4280 }
4281 var ref = function (value) {
4282 var refs = inst.refs;
4283 if (refs === emptyRefsObject) {
4284 // This is a lazy pooled frozen object, so we need to initialize.
4285 refs = inst.refs = {};
4286 }
4287 if (value === null) {
4288 delete refs[stringRef];
4289 } else {
4290 refs[stringRef] = value;
4291 }
4292 };
4293 ref._stringRef = stringRef;
4294 return ref;
4295 } else {
4296 (function () {
4297 if (!(typeof mixedRef === 'string')) {
4298 {
4299 throw ReactError('Expected ref to be a function, a string, an object returned by React.createRef(), or null.');
4300 }
4301 }
4302 })();
4303 (function () {
4304 if (!element._owner) {
4305 {
4306 throw ReactError('Element ref was specified as a string (' + mixedRef + ') but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component\'s render method\n3. You have multiple copies of React loaded\nSee https://fb.me/react-refs-must-have-owner for more information.');
4307 }
4308 }
4309 })();
4310 }
4311 }
4312 return mixedRef;
4313}
4314
4315function throwOnInvalidObjectType(returnFiber, newChild) {
4316 if (returnFiber.type !== 'textarea') {
4317 var addendum = '';
4318 {
4319 addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + getCurrentFiberStackInDev();
4320 }
4321 (function () {
4322 {
4323 {
4324 throw ReactError('Objects are not valid as a React child (found: ' + (Object.prototype.toString.call(newChild) === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : newChild) + ').' + addendum);
4325 }
4326 }
4327 })();
4328 }
4329}
4330
4331function warnOnFunctionType() {
4332 var currentComponentErrorInfo = 'Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.' + getCurrentFiberStackInDev();
4333
4334 if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) {
4335 return;
4336 }
4337 ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true;
4338
4339 warning$1(false, 'Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.');
4340}
4341
4342// This wrapper function exists because I expect to clone the code in each path
4343// to be able to optimize each path individually by branching early. This needs
4344// a compiler or we can do it manually. Helpers that don't need this branching
4345// live outside of this function.
4346function ChildReconciler(shouldTrackSideEffects) {
4347 function deleteChild(returnFiber, childToDelete) {
4348 if (!shouldTrackSideEffects) {
4349 // Noop.
4350 return;
4351 }
4352 // Deletions are added in reversed order so we add it to the front.
4353 // At this point, the return fiber's effect list is empty except for
4354 // deletions, so we can just append the deletion to the list. The remaining
4355 // effects aren't added until the complete phase. Once we implement
4356 // resuming, this may not be true.
4357 var last = returnFiber.lastEffect;
4358 if (last !== null) {
4359 last.nextEffect = childToDelete;
4360 returnFiber.lastEffect = childToDelete;
4361 } else {
4362 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
4363 }
4364 childToDelete.nextEffect = null;
4365 childToDelete.effectTag = Deletion;
4366 }
4367
4368 function deleteRemainingChildren(returnFiber, currentFirstChild) {
4369 if (!shouldTrackSideEffects) {
4370 // Noop.
4371 return null;
4372 }
4373
4374 // TODO: For the shouldClone case, this could be micro-optimized a bit by
4375 // assuming that after the first child we've already added everything.
4376 var childToDelete = currentFirstChild;
4377 while (childToDelete !== null) {
4378 deleteChild(returnFiber, childToDelete);
4379 childToDelete = childToDelete.sibling;
4380 }
4381 return null;
4382 }
4383
4384 function mapRemainingChildren(returnFiber, currentFirstChild) {
4385 // Add the remaining children to a temporary map so that we can find them by
4386 // keys quickly. Implicit (null) keys get added to this set with their index
4387 var existingChildren = new Map();
4388
4389 var existingChild = currentFirstChild;
4390 while (existingChild !== null) {
4391 if (existingChild.key !== null) {
4392 existingChildren.set(existingChild.key, existingChild);
4393 } else {
4394 existingChildren.set(existingChild.index, existingChild);
4395 }
4396 existingChild = existingChild.sibling;
4397 }
4398 return existingChildren;
4399 }
4400
4401 function useFiber(fiber, pendingProps, expirationTime) {
4402 // We currently set sibling to null and index to 0 here because it is easy
4403 // to forget to do before returning it. E.g. for the single child case.
4404 var clone = createWorkInProgress(fiber, pendingProps, expirationTime);
4405 clone.index = 0;
4406 clone.sibling = null;
4407 return clone;
4408 }
4409
4410 function placeChild(newFiber, lastPlacedIndex, newIndex) {
4411 newFiber.index = newIndex;
4412 if (!shouldTrackSideEffects) {
4413 // Noop.
4414 return lastPlacedIndex;
4415 }
4416 var current$$1 = newFiber.alternate;
4417 if (current$$1 !== null) {
4418 var oldIndex = current$$1.index;
4419 if (oldIndex < lastPlacedIndex) {
4420 // This is a move.
4421 newFiber.effectTag = Placement;
4422 return lastPlacedIndex;
4423 } else {
4424 // This item can stay in place.
4425 return oldIndex;
4426 }
4427 } else {
4428 // This is an insertion.
4429 newFiber.effectTag = Placement;
4430 return lastPlacedIndex;
4431 }
4432 }
4433
4434 function placeSingleChild(newFiber) {
4435 // This is simpler for the single child case. We only need to do a
4436 // placement for inserting new children.
4437 if (shouldTrackSideEffects && newFiber.alternate === null) {
4438 newFiber.effectTag = Placement;
4439 }
4440 return newFiber;
4441 }
4442
4443 function updateTextNode(returnFiber, current$$1, textContent, expirationTime) {
4444 if (current$$1 === null || current$$1.tag !== HostText) {
4445 // Insert
4446 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
4447 created.return = returnFiber;
4448 return created;
4449 } else {
4450 // Update
4451 var existing = useFiber(current$$1, textContent, expirationTime);
4452 existing.return = returnFiber;
4453 return existing;
4454 }
4455 }
4456
4457 function updateElement(returnFiber, current$$1, element, expirationTime) {
4458 if (current$$1 !== null && current$$1.elementType === element.type) {
4459 // Move based on index
4460 var existing = useFiber(current$$1, element.props, expirationTime);
4461 existing.ref = coerceRef(returnFiber, current$$1, element);
4462 existing.return = returnFiber;
4463 {
4464 existing._debugSource = element._source;
4465 existing._debugOwner = element._owner;
4466 }
4467 return existing;
4468 } else {
4469 // Insert
4470 var created = createFiberFromElement(element, returnFiber.mode, expirationTime);
4471 created.ref = coerceRef(returnFiber, current$$1, element);
4472 created.return = returnFiber;
4473 return created;
4474 }
4475 }
4476
4477 function updatePortal(returnFiber, current$$1, portal, expirationTime) {
4478 if (current$$1 === null || current$$1.tag !== HostPortal || current$$1.stateNode.containerInfo !== portal.containerInfo || current$$1.stateNode.implementation !== portal.implementation) {
4479 // Insert
4480 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
4481 created.return = returnFiber;
4482 return created;
4483 } else {
4484 // Update
4485 var existing = useFiber(current$$1, portal.children || [], expirationTime);
4486 existing.return = returnFiber;
4487 return existing;
4488 }
4489 }
4490
4491 function updateFragment(returnFiber, current$$1, fragment, expirationTime, key) {
4492 if (current$$1 === null || current$$1.tag !== Fragment) {
4493 // Insert
4494 var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key);
4495 created.return = returnFiber;
4496 return created;
4497 } else {
4498 // Update
4499 var existing = useFiber(current$$1, fragment, expirationTime);
4500 existing.return = returnFiber;
4501 return existing;
4502 }
4503 }
4504
4505 function createChild(returnFiber, newChild, expirationTime) {
4506 if (typeof newChild === 'string' || typeof newChild === 'number') {
4507 // Text nodes don't have keys. If the previous node is implicitly keyed
4508 // we can continue to replace it without aborting even if it is not a text
4509 // node.
4510 var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime);
4511 created.return = returnFiber;
4512 return created;
4513 }
4514
4515 if (typeof newChild === 'object' && newChild !== null) {
4516 switch (newChild.$$typeof) {
4517 case REACT_ELEMENT_TYPE:
4518 {
4519 var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime);
4520 _created.ref = coerceRef(returnFiber, null, newChild);
4521 _created.return = returnFiber;
4522 return _created;
4523 }
4524 case REACT_PORTAL_TYPE:
4525 {
4526 var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime);
4527 _created2.return = returnFiber;
4528 return _created2;
4529 }
4530 }
4531
4532 if (isArray(newChild) || getIteratorFn(newChild)) {
4533 var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null);
4534 _created3.return = returnFiber;
4535 return _created3;
4536 }
4537
4538 throwOnInvalidObjectType(returnFiber, newChild);
4539 }
4540
4541 {
4542 if (typeof newChild === 'function') {
4543 warnOnFunctionType();
4544 }
4545 }
4546
4547 return null;
4548 }
4549
4550 function updateSlot(returnFiber, oldFiber, newChild, expirationTime) {
4551 // Update the fiber if the keys match, otherwise return null.
4552
4553 var key = oldFiber !== null ? oldFiber.key : null;
4554
4555 if (typeof newChild === 'string' || typeof newChild === 'number') {
4556 // Text nodes don't have keys. If the previous node is implicitly keyed
4557 // we can continue to replace it without aborting even if it is not a text
4558 // node.
4559 if (key !== null) {
4560 return null;
4561 }
4562 return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime);
4563 }
4564
4565 if (typeof newChild === 'object' && newChild !== null) {
4566 switch (newChild.$$typeof) {
4567 case REACT_ELEMENT_TYPE:
4568 {
4569 if (newChild.key === key) {
4570 if (newChild.type === REACT_FRAGMENT_TYPE) {
4571 return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key);
4572 }
4573 return updateElement(returnFiber, oldFiber, newChild, expirationTime);
4574 } else {
4575 return null;
4576 }
4577 }
4578 case REACT_PORTAL_TYPE:
4579 {
4580 if (newChild.key === key) {
4581 return updatePortal(returnFiber, oldFiber, newChild, expirationTime);
4582 } else {
4583 return null;
4584 }
4585 }
4586 }
4587
4588 if (isArray(newChild) || getIteratorFn(newChild)) {
4589 if (key !== null) {
4590 return null;
4591 }
4592
4593 return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null);
4594 }
4595
4596 throwOnInvalidObjectType(returnFiber, newChild);
4597 }
4598
4599 {
4600 if (typeof newChild === 'function') {
4601 warnOnFunctionType();
4602 }
4603 }
4604
4605 return null;
4606 }
4607
4608 function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) {
4609 if (typeof newChild === 'string' || typeof newChild === 'number') {
4610 // Text nodes don't have keys, so we neither have to check the old nor
4611 // new node for the key. If both are text nodes, they match.
4612 var matchedFiber = existingChildren.get(newIdx) || null;
4613 return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime);
4614 }
4615
4616 if (typeof newChild === 'object' && newChild !== null) {
4617 switch (newChild.$$typeof) {
4618 case REACT_ELEMENT_TYPE:
4619 {
4620 var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
4621 if (newChild.type === REACT_FRAGMENT_TYPE) {
4622 return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key);
4623 }
4624 return updateElement(returnFiber, _matchedFiber, newChild, expirationTime);
4625 }
4626 case REACT_PORTAL_TYPE:
4627 {
4628 var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
4629 return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime);
4630 }
4631 }
4632
4633 if (isArray(newChild) || getIteratorFn(newChild)) {
4634 var _matchedFiber3 = existingChildren.get(newIdx) || null;
4635 return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null);
4636 }
4637
4638 throwOnInvalidObjectType(returnFiber, newChild);
4639 }
4640
4641 {
4642 if (typeof newChild === 'function') {
4643 warnOnFunctionType();
4644 }
4645 }
4646
4647 return null;
4648 }
4649
4650 /**
4651 * Warns if there is a duplicate or missing key
4652 */
4653 function warnOnInvalidKey(child, knownKeys) {
4654 {
4655 if (typeof child !== 'object' || child === null) {
4656 return knownKeys;
4657 }
4658 switch (child.$$typeof) {
4659 case REACT_ELEMENT_TYPE:
4660 case REACT_PORTAL_TYPE:
4661 warnForMissingKey(child);
4662 var key = child.key;
4663 if (typeof key !== 'string') {
4664 break;
4665 }
4666 if (knownKeys === null) {
4667 knownKeys = new Set();
4668 knownKeys.add(key);
4669 break;
4670 }
4671 if (!knownKeys.has(key)) {
4672 knownKeys.add(key);
4673 break;
4674 }
4675 warning$1(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key);
4676 break;
4677 default:
4678 break;
4679 }
4680 }
4681 return knownKeys;
4682 }
4683
4684 function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) {
4685 // This algorithm can't optimize by searching from both ends since we
4686 // don't have backpointers on fibers. I'm trying to see how far we can get
4687 // with that model. If it ends up not being worth the tradeoffs, we can
4688 // add it later.
4689
4690 // Even with a two ended optimization, we'd want to optimize for the case
4691 // where there are few changes and brute force the comparison instead of
4692 // going for the Map. It'd like to explore hitting that path first in
4693 // forward-only mode and only go for the Map once we notice that we need
4694 // lots of look ahead. This doesn't handle reversal as well as two ended
4695 // search but that's unusual. Besides, for the two ended optimization to
4696 // work on Iterables, we'd need to copy the whole set.
4697
4698 // In this first iteration, we'll just live with hitting the bad case
4699 // (adding everything to a Map) in for every insert/move.
4700
4701 // If you change this code, also update reconcileChildrenIterator() which
4702 // uses the same algorithm.
4703
4704 {
4705 // First, validate keys.
4706 var knownKeys = null;
4707 for (var i = 0; i < newChildren.length; i++) {
4708 var child = newChildren[i];
4709 knownKeys = warnOnInvalidKey(child, knownKeys);
4710 }
4711 }
4712
4713 var resultingFirstChild = null;
4714 var previousNewFiber = null;
4715
4716 var oldFiber = currentFirstChild;
4717 var lastPlacedIndex = 0;
4718 var newIdx = 0;
4719 var nextOldFiber = null;
4720 for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
4721 if (oldFiber.index > newIdx) {
4722 nextOldFiber = oldFiber;
4723 oldFiber = null;
4724 } else {
4725 nextOldFiber = oldFiber.sibling;
4726 }
4727 var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime);
4728 if (newFiber === null) {
4729 // TODO: This breaks on empty slots like null children. That's
4730 // unfortunate because it triggers the slow path all the time. We need
4731 // a better way to communicate whether this was a miss or null,
4732 // boolean, undefined, etc.
4733 if (oldFiber === null) {
4734 oldFiber = nextOldFiber;
4735 }
4736 break;
4737 }
4738 if (shouldTrackSideEffects) {
4739 if (oldFiber && newFiber.alternate === null) {
4740 // We matched the slot, but we didn't reuse the existing fiber, so we
4741 // need to delete the existing child.
4742 deleteChild(returnFiber, oldFiber);
4743 }
4744 }
4745 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
4746 if (previousNewFiber === null) {
4747 // TODO: Move out of the loop. This only happens for the first run.
4748 resultingFirstChild = newFiber;
4749 } else {
4750 // TODO: Defer siblings if we're not at the right index for this slot.
4751 // I.e. if we had null values before, then we want to defer this
4752 // for each null value. However, we also don't want to call updateSlot
4753 // with the previous one.
4754 previousNewFiber.sibling = newFiber;
4755 }
4756 previousNewFiber = newFiber;
4757 oldFiber = nextOldFiber;
4758 }
4759
4760 if (newIdx === newChildren.length) {
4761 // We've reached the end of the new children. We can delete the rest.
4762 deleteRemainingChildren(returnFiber, oldFiber);
4763 return resultingFirstChild;
4764 }
4765
4766 if (oldFiber === null) {
4767 // If we don't have any more existing children we can choose a fast path
4768 // since the rest will all be insertions.
4769 for (; newIdx < newChildren.length; newIdx++) {
4770 var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime);
4771 if (!_newFiber) {
4772 continue;
4773 }
4774 lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
4775 if (previousNewFiber === null) {
4776 // TODO: Move out of the loop. This only happens for the first run.
4777 resultingFirstChild = _newFiber;
4778 } else {
4779 previousNewFiber.sibling = _newFiber;
4780 }
4781 previousNewFiber = _newFiber;
4782 }
4783 return resultingFirstChild;
4784 }
4785
4786 // Add all children to a key map for quick lookups.
4787 var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
4788
4789 // Keep scanning and use the map to restore deleted items as moves.
4790 for (; newIdx < newChildren.length; newIdx++) {
4791 var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime);
4792 if (_newFiber2) {
4793 if (shouldTrackSideEffects) {
4794 if (_newFiber2.alternate !== null) {
4795 // The new fiber is a work in progress, but if there exists a
4796 // current, that means that we reused the fiber. We need to delete
4797 // it from the child list so that we don't add it to the deletion
4798 // list.
4799 existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
4800 }
4801 }
4802 lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
4803 if (previousNewFiber === null) {
4804 resultingFirstChild = _newFiber2;
4805 } else {
4806 previousNewFiber.sibling = _newFiber2;
4807 }
4808 previousNewFiber = _newFiber2;
4809 }
4810 }
4811
4812 if (shouldTrackSideEffects) {
4813 // Any existing children that weren't consumed above were deleted. We need
4814 // to add them to the deletion list.
4815 existingChildren.forEach(function (child) {
4816 return deleteChild(returnFiber, child);
4817 });
4818 }
4819
4820 return resultingFirstChild;
4821 }
4822
4823 function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) {
4824 // This is the same implementation as reconcileChildrenArray(),
4825 // but using the iterator instead.
4826
4827 var iteratorFn = getIteratorFn(newChildrenIterable);
4828 (function () {
4829 if (!(typeof iteratorFn === 'function')) {
4830 {
4831 throw ReactError('An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.');
4832 }
4833 }
4834 })();
4835
4836 {
4837 // We don't support rendering Generators because it's a mutation.
4838 // See https://github.com/facebook/react/issues/12995
4839 if (typeof Symbol === 'function' &&
4840 // $FlowFixMe Flow doesn't know about toStringTag
4841 newChildrenIterable[Symbol.toStringTag] === 'Generator') {
4842 !didWarnAboutGenerators ? warning$1(false, 'Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.') : void 0;
4843 didWarnAboutGenerators = true;
4844 }
4845
4846 // Warn about using Maps as children
4847 if (newChildrenIterable.entries === iteratorFn) {
4848 !didWarnAboutMaps ? warning$1(false, 'Using Maps as children is unsupported and will likely yield ' + 'unexpected results. Convert it to a sequence/iterable of keyed ' + 'ReactElements instead.') : void 0;
4849 didWarnAboutMaps = true;
4850 }
4851
4852 // First, validate keys.
4853 // We'll get a different iterator later for the main pass.
4854 var _newChildren = iteratorFn.call(newChildrenIterable);
4855 if (_newChildren) {
4856 var knownKeys = null;
4857 var _step = _newChildren.next();
4858 for (; !_step.done; _step = _newChildren.next()) {
4859 var child = _step.value;
4860 knownKeys = warnOnInvalidKey(child, knownKeys);
4861 }
4862 }
4863 }
4864
4865 var newChildren = iteratorFn.call(newChildrenIterable);
4866 (function () {
4867 if (!(newChildren != null)) {
4868 {
4869 throw ReactError('An iterable object provided no iterator.');
4870 }
4871 }
4872 })();
4873
4874 var resultingFirstChild = null;
4875 var previousNewFiber = null;
4876
4877 var oldFiber = currentFirstChild;
4878 var lastPlacedIndex = 0;
4879 var newIdx = 0;
4880 var nextOldFiber = null;
4881
4882 var step = newChildren.next();
4883 for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
4884 if (oldFiber.index > newIdx) {
4885 nextOldFiber = oldFiber;
4886 oldFiber = null;
4887 } else {
4888 nextOldFiber = oldFiber.sibling;
4889 }
4890 var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime);
4891 if (newFiber === null) {
4892 // TODO: This breaks on empty slots like null children. That's
4893 // unfortunate because it triggers the slow path all the time. We need
4894 // a better way to communicate whether this was a miss or null,
4895 // boolean, undefined, etc.
4896 if (!oldFiber) {
4897 oldFiber = nextOldFiber;
4898 }
4899 break;
4900 }
4901 if (shouldTrackSideEffects) {
4902 if (oldFiber && newFiber.alternate === null) {
4903 // We matched the slot, but we didn't reuse the existing fiber, so we
4904 // need to delete the existing child.
4905 deleteChild(returnFiber, oldFiber);
4906 }
4907 }
4908 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
4909 if (previousNewFiber === null) {
4910 // TODO: Move out of the loop. This only happens for the first run.
4911 resultingFirstChild = newFiber;
4912 } else {
4913 // TODO: Defer siblings if we're not at the right index for this slot.
4914 // I.e. if we had null values before, then we want to defer this
4915 // for each null value. However, we also don't want to call updateSlot
4916 // with the previous one.
4917 previousNewFiber.sibling = newFiber;
4918 }
4919 previousNewFiber = newFiber;
4920 oldFiber = nextOldFiber;
4921 }
4922
4923 if (step.done) {
4924 // We've reached the end of the new children. We can delete the rest.
4925 deleteRemainingChildren(returnFiber, oldFiber);
4926 return resultingFirstChild;
4927 }
4928
4929 if (oldFiber === null) {
4930 // If we don't have any more existing children we can choose a fast path
4931 // since the rest will all be insertions.
4932 for (; !step.done; newIdx++, step = newChildren.next()) {
4933 var _newFiber3 = createChild(returnFiber, step.value, expirationTime);
4934 if (_newFiber3 === null) {
4935 continue;
4936 }
4937 lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
4938 if (previousNewFiber === null) {
4939 // TODO: Move out of the loop. This only happens for the first run.
4940 resultingFirstChild = _newFiber3;
4941 } else {
4942 previousNewFiber.sibling = _newFiber3;
4943 }
4944 previousNewFiber = _newFiber3;
4945 }
4946 return resultingFirstChild;
4947 }
4948
4949 // Add all children to a key map for quick lookups.
4950 var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
4951
4952 // Keep scanning and use the map to restore deleted items as moves.
4953 for (; !step.done; newIdx++, step = newChildren.next()) {
4954 var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime);
4955 if (_newFiber4 !== null) {
4956 if (shouldTrackSideEffects) {
4957 if (_newFiber4.alternate !== null) {
4958 // The new fiber is a work in progress, but if there exists a
4959 // current, that means that we reused the fiber. We need to delete
4960 // it from the child list so that we don't add it to the deletion
4961 // list.
4962 existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
4963 }
4964 }
4965 lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
4966 if (previousNewFiber === null) {
4967 resultingFirstChild = _newFiber4;
4968 } else {
4969 previousNewFiber.sibling = _newFiber4;
4970 }
4971 previousNewFiber = _newFiber4;
4972 }
4973 }
4974
4975 if (shouldTrackSideEffects) {
4976 // Any existing children that weren't consumed above were deleted. We need
4977 // to add them to the deletion list.
4978 existingChildren.forEach(function (child) {
4979 return deleteChild(returnFiber, child);
4980 });
4981 }
4982
4983 return resultingFirstChild;
4984 }
4985
4986 function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) {
4987 // There's no need to check for keys on text nodes since we don't have a
4988 // way to define them.
4989 if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
4990 // We already have an existing node so let's just update it and delete
4991 // the rest.
4992 deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
4993 var existing = useFiber(currentFirstChild, textContent, expirationTime);
4994 existing.return = returnFiber;
4995 return existing;
4996 }
4997 // The existing first child is not a text node so we need to create one
4998 // and delete the existing ones.
4999 deleteRemainingChildren(returnFiber, currentFirstChild);
5000 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
5001 created.return = returnFiber;
5002 return created;
5003 }
5004
5005 function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) {
5006 var key = element.key;
5007 var child = currentFirstChild;
5008 while (child !== null) {
5009 // TODO: If key === null and child.key === null, then this only applies to
5010 // the first item in the list.
5011 if (child.key === key) {
5012 if (child.tag === Fragment ? element.type === REACT_FRAGMENT_TYPE : child.elementType === element.type) {
5013 deleteRemainingChildren(returnFiber, child.sibling);
5014 var existing = useFiber(child, element.type === REACT_FRAGMENT_TYPE ? element.props.children : element.props, expirationTime);
5015 existing.ref = coerceRef(returnFiber, child, element);
5016 existing.return = returnFiber;
5017 {
5018 existing._debugSource = element._source;
5019 existing._debugOwner = element._owner;
5020 }
5021 return existing;
5022 } else {
5023 deleteRemainingChildren(returnFiber, child);
5024 break;
5025 }
5026 } else {
5027 deleteChild(returnFiber, child);
5028 }
5029 child = child.sibling;
5030 }
5031
5032 if (element.type === REACT_FRAGMENT_TYPE) {
5033 var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key);
5034 created.return = returnFiber;
5035 return created;
5036 } else {
5037 var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime);
5038 _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
5039 _created4.return = returnFiber;
5040 return _created4;
5041 }
5042 }
5043
5044 function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) {
5045 var key = portal.key;
5046 var child = currentFirstChild;
5047 while (child !== null) {
5048 // TODO: If key === null and child.key === null, then this only applies to
5049 // the first item in the list.
5050 if (child.key === key) {
5051 if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
5052 deleteRemainingChildren(returnFiber, child.sibling);
5053 var existing = useFiber(child, portal.children || [], expirationTime);
5054 existing.return = returnFiber;
5055 return existing;
5056 } else {
5057 deleteRemainingChildren(returnFiber, child);
5058 break;
5059 }
5060 } else {
5061 deleteChild(returnFiber, child);
5062 }
5063 child = child.sibling;
5064 }
5065
5066 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
5067 created.return = returnFiber;
5068 return created;
5069 }
5070
5071 // This API will tag the children with the side-effect of the reconciliation
5072 // itself. They will be added to the side-effect list as we pass through the
5073 // children and the parent.
5074 function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) {
5075 // This function is not recursive.
5076 // If the top level item is an array, we treat it as a set of children,
5077 // not as a fragment. Nested arrays on the other hand will be treated as
5078 // fragment nodes. Recursion happens at the normal flow.
5079
5080 // Handle top level unkeyed fragments as if they were arrays.
5081 // This leads to an ambiguity between <>{[...]}</> and <>...</>.
5082 // We treat the ambiguous cases above the same.
5083 var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
5084 if (isUnkeyedTopLevelFragment) {
5085 newChild = newChild.props.children;
5086 }
5087
5088 // Handle object types
5089 var isObject = typeof newChild === 'object' && newChild !== null;
5090
5091 if (isObject) {
5092 switch (newChild.$$typeof) {
5093 case REACT_ELEMENT_TYPE:
5094 return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime));
5095 case REACT_PORTAL_TYPE:
5096 return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime));
5097 }
5098 }
5099
5100 if (typeof newChild === 'string' || typeof newChild === 'number') {
5101 return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime));
5102 }
5103
5104 if (isArray(newChild)) {
5105 return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime);
5106 }
5107
5108 if (getIteratorFn(newChild)) {
5109 return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime);
5110 }
5111
5112 if (isObject) {
5113 throwOnInvalidObjectType(returnFiber, newChild);
5114 }
5115
5116 {
5117 if (typeof newChild === 'function') {
5118 warnOnFunctionType();
5119 }
5120 }
5121 if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {
5122 // If the new child is undefined, and the return fiber is a composite
5123 // component, throw an error. If Fiber return types are disabled,
5124 // we already threw above.
5125 switch (returnFiber.tag) {
5126 case ClassComponent:
5127 {
5128 {
5129 var instance = returnFiber.stateNode;
5130 if (instance.render._isMockFunction) {
5131 // We allow auto-mocks to proceed as if they're returning null.
5132 break;
5133 }
5134 }
5135 }
5136 // Intentionally fall through to the next case, which handles both
5137 // functions and classes
5138 // eslint-disable-next-lined no-fallthrough
5139 case FunctionComponent:
5140 {
5141 var Component = returnFiber.type;
5142 (function () {
5143 {
5144 {
5145 throw ReactError((Component.displayName || Component.name || 'Component') + '(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.');
5146 }
5147 }
5148 })();
5149 }
5150 }
5151 }
5152
5153 // Remaining cases are all treated as empty.
5154 return deleteRemainingChildren(returnFiber, currentFirstChild);
5155 }
5156
5157 return reconcileChildFibers;
5158}
5159
5160var reconcileChildFibers = ChildReconciler(true);
5161var mountChildFibers = ChildReconciler(false);
5162
5163function cloneChildFibers(current$$1, workInProgress) {
5164 (function () {
5165 if (!(current$$1 === null || workInProgress.child === current$$1.child)) {
5166 {
5167 throw ReactError('Resuming work not yet implemented.');
5168 }
5169 }
5170 })();
5171
5172 if (workInProgress.child === null) {
5173 return;
5174 }
5175
5176 var currentChild = workInProgress.child;
5177 var newChild = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
5178 workInProgress.child = newChild;
5179
5180 newChild.return = workInProgress;
5181 while (currentChild.sibling !== null) {
5182 currentChild = currentChild.sibling;
5183 newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
5184 newChild.return = workInProgress;
5185 }
5186 newChild.sibling = null;
5187}
5188
5189var NO_CONTEXT$1 = {};
5190
5191var contextStackCursor$1 = createCursor(NO_CONTEXT$1);
5192var contextFiberStackCursor = createCursor(NO_CONTEXT$1);
5193var rootInstanceStackCursor = createCursor(NO_CONTEXT$1);
5194
5195function requiredContext(c) {
5196 (function () {
5197 if (!(c !== NO_CONTEXT$1)) {
5198 {
5199 throw ReactError('Expected host context to exist. This error is likely caused by a bug in React. Please file an issue.');
5200 }
5201 }
5202 })();
5203 return c;
5204}
5205
5206function getRootHostContainer() {
5207 var rootInstance = requiredContext(rootInstanceStackCursor.current);
5208 return rootInstance;
5209}
5210
5211function pushHostContainer(fiber, nextRootInstance) {
5212 // Push current root instance onto the stack;
5213 // This allows us to reset root when portals are popped.
5214 push(rootInstanceStackCursor, nextRootInstance, fiber);
5215 // Track the context and the Fiber that provided it.
5216 // This enables us to pop only Fibers that provide unique contexts.
5217 push(contextFiberStackCursor, fiber, fiber);
5218
5219 // Finally, we need to push the host context to the stack.
5220 // However, we can't just call getRootHostContext() and push it because
5221 // we'd have a different number of entries on the stack depending on
5222 // whether getRootHostContext() throws somewhere in renderer code or not.
5223 // So we push an empty value first. This lets us safely unwind on errors.
5224 push(contextStackCursor$1, NO_CONTEXT$1, fiber);
5225 var nextRootContext = getRootHostContext(nextRootInstance);
5226 // Now that we know this function doesn't throw, replace it.
5227 pop(contextStackCursor$1, fiber);
5228 push(contextStackCursor$1, nextRootContext, fiber);
5229}
5230
5231function popHostContainer(fiber) {
5232 pop(contextStackCursor$1, fiber);
5233 pop(contextFiberStackCursor, fiber);
5234 pop(rootInstanceStackCursor, fiber);
5235}
5236
5237function getHostContext() {
5238 var context = requiredContext(contextStackCursor$1.current);
5239 return context;
5240}
5241
5242function pushHostContext(fiber) {
5243 var rootInstance = requiredContext(rootInstanceStackCursor.current);
5244 var context = requiredContext(contextStackCursor$1.current);
5245 var nextContext = getChildHostContext(context, fiber.type, rootInstance);
5246
5247 // Don't push this Fiber's context unless it's unique.
5248 if (context === nextContext) {
5249 return;
5250 }
5251
5252 // Track the context and the Fiber that provided it.
5253 // This enables us to pop only Fibers that provide unique contexts.
5254 push(contextFiberStackCursor, fiber, fiber);
5255 push(contextStackCursor$1, nextContext, fiber);
5256}
5257
5258function pushHostContextForEventComponent(fiber) {
5259 var context = requiredContext(contextStackCursor$1.current);
5260 var nextContext = getChildHostContextForEventComponent(context);
5261
5262 // Don't push this Fiber's context unless it's unique.
5263 if (context === nextContext) {
5264 return;
5265 }
5266
5267 // Track the context and the Fiber that provided it.
5268 // This enables us to pop only Fibers that provide unique contexts.
5269 push(contextFiberStackCursor, fiber, fiber);
5270 push(contextStackCursor$1, nextContext, fiber);
5271}
5272
5273function pushHostContextForEventTarget(fiber) {
5274 var context = requiredContext(contextStackCursor$1.current);
5275 var eventTargetType = fiber.type.type;
5276 var nextContext = getChildHostContextForEventTarget(context, eventTargetType);
5277
5278 // Don't push this Fiber's context unless it's unique.
5279 if (context === nextContext) {
5280 return;
5281 }
5282
5283 // Track the context and the Fiber that provided it.
5284 // This enables us to pop only Fibers that provide unique contexts.
5285 push(contextFiberStackCursor, fiber, fiber);
5286 push(contextStackCursor$1, nextContext, fiber);
5287}
5288
5289function popHostContext(fiber) {
5290 // Do not pop unless this Fiber provided the current context.
5291 // pushHostContext() only pushes Fibers that provide unique contexts.
5292 if (contextFiberStackCursor.current !== fiber) {
5293 return;
5294 }
5295
5296 pop(contextStackCursor$1, fiber);
5297 pop(contextFiberStackCursor, fiber);
5298}
5299
5300var NoEffect$1 = /* */0;
5301var UnmountSnapshot = /* */2;
5302var UnmountMutation = /* */4;
5303var MountMutation = /* */8;
5304var UnmountLayout = /* */16;
5305var MountLayout = /* */32;
5306var MountPassive = /* */64;
5307var UnmountPassive = /* */128;
5308
5309var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
5310
5311
5312var didWarnAboutMismatchedHooksForComponent = void 0;
5313{
5314 didWarnAboutMismatchedHooksForComponent = new Set();
5315}
5316
5317// These are set right before calling the component.
5318var renderExpirationTime = NoWork;
5319// The work-in-progress fiber. I've named it differently to distinguish it from
5320// the work-in-progress hook.
5321var currentlyRenderingFiber$1 = null;
5322
5323// Hooks are stored as a linked list on the fiber's memoizedState field. The
5324// current hook list is the list that belongs to the current fiber. The
5325// work-in-progress hook list is a new list that will be added to the
5326// work-in-progress fiber.
5327var currentHook = null;
5328var nextCurrentHook = null;
5329var firstWorkInProgressHook = null;
5330var workInProgressHook = null;
5331var nextWorkInProgressHook = null;
5332
5333var remainingExpirationTime = NoWork;
5334var componentUpdateQueue = null;
5335var sideEffectTag = 0;
5336
5337// Updates scheduled during render will trigger an immediate re-render at the
5338// end of the current pass. We can't store these updates on the normal queue,
5339// because if the work is aborted, they should be discarded. Because this is
5340// a relatively rare case, we also don't want to add an additional field to
5341// either the hook or queue object types. So we store them in a lazily create
5342// map of queue -> render-phase updates, which are discarded once the component
5343// completes without re-rendering.
5344
5345// Whether an update was scheduled during the currently executing render pass.
5346var didScheduleRenderPhaseUpdate = false;
5347// Lazily created map of render-phase updates
5348var renderPhaseUpdates = null;
5349// Counter to prevent infinite loops.
5350var numberOfReRenders = 0;
5351var RE_RENDER_LIMIT = 25;
5352
5353// In DEV, this is the name of the currently executing primitive hook
5354var currentHookNameInDev = null;
5355
5356// In DEV, this list ensures that hooks are called in the same order between renders.
5357// The list stores the order of hooks used during the initial render (mount).
5358// Subsequent renders (updates) reference this list.
5359var hookTypesDev = null;
5360var hookTypesUpdateIndexDev = -1;
5361
5362function mountHookTypesDev() {
5363 {
5364 var hookName = currentHookNameInDev;
5365
5366 if (hookTypesDev === null) {
5367 hookTypesDev = [hookName];
5368 } else {
5369 hookTypesDev.push(hookName);
5370 }
5371 }
5372}
5373
5374function updateHookTypesDev() {
5375 {
5376 var hookName = currentHookNameInDev;
5377
5378 if (hookTypesDev !== null) {
5379 hookTypesUpdateIndexDev++;
5380 if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
5381 warnOnHookMismatchInDev(hookName);
5382 }
5383 }
5384 }
5385}
5386
5387function checkDepsAreArrayDev(deps) {
5388 {
5389 if (deps !== undefined && deps !== null && !Array.isArray(deps)) {
5390 // Verify deps, but only on mount to avoid extra checks.
5391 // It's unlikely their type would change as usually you define them inline.
5392 warning$1(false, '%s received a final argument that is not an array (instead, received `%s`). When ' + 'specified, the final argument must be an array.', currentHookNameInDev, typeof deps);
5393 }
5394 }
5395}
5396
5397function warnOnHookMismatchInDev(currentHookName) {
5398 {
5399 var componentName = getComponentName(currentlyRenderingFiber$1.type);
5400 if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
5401 didWarnAboutMismatchedHooksForComponent.add(componentName);
5402
5403 if (hookTypesDev !== null) {
5404 var table = '';
5405
5406 var secondColumnStart = 30;
5407
5408 for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {
5409 var oldHookName = hookTypesDev[i];
5410 var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
5411
5412 var row = i + 1 + '. ' + oldHookName;
5413
5414 // Extra space so second column lines up
5415 // lol @ IE not supporting String#repeat
5416 while (row.length < secondColumnStart) {
5417 row += ' ';
5418 }
5419
5420 row += newHookName + '\n';
5421
5422 table += row;
5423 }
5424
5425 warning$1(false, 'React has detected a change in the order of Hooks called by %s. ' + 'This will lead to bugs and errors if not fixed. ' + 'For more information, read the Rules of Hooks: https://fb.me/rules-of-hooks\n\n' + ' Previous render Next render\n' + ' ------------------------------------------------------\n' + '%s' + ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n', componentName, table);
5426 }
5427 }
5428 }
5429}
5430
5431function throwInvalidHookError() {
5432 (function () {
5433 {
5434 {
5435 throw ReactError('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.');
5436 }
5437 }
5438 })();
5439}
5440
5441function areHookInputsEqual(nextDeps, prevDeps) {
5442 if (prevDeps === null) {
5443 {
5444 warning$1(false, '%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);
5445 }
5446 return false;
5447 }
5448
5449 {
5450 // Don't bother comparing lengths in prod because these arrays should be
5451 // passed inline.
5452 if (nextDeps.length !== prevDeps.length) {
5453 warning$1(false, 'The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, '[' + nextDeps.join(', ') + ']', '[' + prevDeps.join(', ') + ']');
5454 }
5455 }
5456 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
5457 if (is(nextDeps[i], prevDeps[i])) {
5458 continue;
5459 }
5460 return false;
5461 }
5462 return true;
5463}
5464
5465function renderWithHooks(current, workInProgress, Component, props, refOrContext, nextRenderExpirationTime) {
5466 renderExpirationTime = nextRenderExpirationTime;
5467 currentlyRenderingFiber$1 = workInProgress;
5468 nextCurrentHook = current !== null ? current.memoizedState : null;
5469
5470 {
5471 hookTypesDev = current !== null ? current._debugHookTypes : null;
5472 hookTypesUpdateIndexDev = -1;
5473 }
5474
5475 // The following should have already been reset
5476 // currentHook = null;
5477 // workInProgressHook = null;
5478
5479 // remainingExpirationTime = NoWork;
5480 // componentUpdateQueue = null;
5481
5482 // didScheduleRenderPhaseUpdate = false;
5483 // renderPhaseUpdates = null;
5484 // numberOfReRenders = 0;
5485 // sideEffectTag = 0;
5486
5487 // TODO Warn if no hooks are used at all during mount, then some are used during update.
5488 // Currently we will identify the update render as a mount because nextCurrentHook === null.
5489 // This is tricky because it's valid for certain types of components (e.g. React.lazy)
5490
5491 // Using nextCurrentHook to differentiate between mount/update only works if at least one stateful hook is used.
5492 // Non-stateful hooks (e.g. context) don't get added to memoizedState,
5493 // so nextCurrentHook would be null during updates and mounts.
5494 {
5495 if (nextCurrentHook !== null) {
5496 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
5497 } else if (hookTypesDev !== null) {
5498 // This dispatcher handles an edge case where a component is updating,
5499 // but no stateful hooks have been used.
5500 // We want to match the production code behavior (which will use HooksDispatcherOnMount),
5501 // but with the extra DEV validation to ensure hooks ordering hasn't changed.
5502 // This dispatcher does that.
5503 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV;
5504 } else {
5505 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV;
5506 }
5507 }
5508
5509 var children = Component(props, refOrContext);
5510
5511 if (didScheduleRenderPhaseUpdate) {
5512 do {
5513 didScheduleRenderPhaseUpdate = false;
5514 numberOfReRenders += 1;
5515
5516 // Start over from the beginning of the list
5517 nextCurrentHook = current !== null ? current.memoizedState : null;
5518 nextWorkInProgressHook = firstWorkInProgressHook;
5519
5520 currentHook = null;
5521 workInProgressHook = null;
5522 componentUpdateQueue = null;
5523
5524 {
5525 // Also validate hook order for cascading updates.
5526 hookTypesUpdateIndexDev = -1;
5527 }
5528
5529 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
5530
5531 children = Component(props, refOrContext);
5532 } while (didScheduleRenderPhaseUpdate);
5533
5534 renderPhaseUpdates = null;
5535 numberOfReRenders = 0;
5536 }
5537
5538 // We can assume the previous dispatcher is always this one, since we set it
5539 // at the beginning of the render phase and there's no re-entrancy.
5540 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
5541
5542 var renderedWork = currentlyRenderingFiber$1;
5543
5544 renderedWork.memoizedState = firstWorkInProgressHook;
5545 renderedWork.expirationTime = remainingExpirationTime;
5546 renderedWork.updateQueue = componentUpdateQueue;
5547 renderedWork.effectTag |= sideEffectTag;
5548
5549 {
5550 renderedWork._debugHookTypes = hookTypesDev;
5551 }
5552
5553 // This check uses currentHook so that it works the same in DEV and prod bundles.
5554 // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.
5555 var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
5556
5557 renderExpirationTime = NoWork;
5558 currentlyRenderingFiber$1 = null;
5559
5560 currentHook = null;
5561 nextCurrentHook = null;
5562 firstWorkInProgressHook = null;
5563 workInProgressHook = null;
5564 nextWorkInProgressHook = null;
5565
5566 {
5567 currentHookNameInDev = null;
5568 hookTypesDev = null;
5569 hookTypesUpdateIndexDev = -1;
5570 }
5571
5572 remainingExpirationTime = NoWork;
5573 componentUpdateQueue = null;
5574 sideEffectTag = 0;
5575
5576 // These were reset above
5577 // didScheduleRenderPhaseUpdate = false;
5578 // renderPhaseUpdates = null;
5579 // numberOfReRenders = 0;
5580
5581 (function () {
5582 if (!!didRenderTooFewHooks) {
5583 {
5584 throw ReactError('Rendered fewer hooks than expected. This may be caused by an accidental early return statement.');
5585 }
5586 }
5587 })();
5588
5589 return children;
5590}
5591
5592function bailoutHooks(current, workInProgress, expirationTime) {
5593 workInProgress.updateQueue = current.updateQueue;
5594 workInProgress.effectTag &= ~(Passive | Update);
5595 if (current.expirationTime <= expirationTime) {
5596 current.expirationTime = NoWork;
5597 }
5598}
5599
5600function resetHooks() {
5601 // We can assume the previous dispatcher is always this one, since we set it
5602 // at the beginning of the render phase and there's no re-entrancy.
5603 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
5604
5605 // This is used to reset the state of this module when a component throws.
5606 // It's also called inside mountIndeterminateComponent if we determine the
5607 // component is a module-style component.
5608 renderExpirationTime = NoWork;
5609 currentlyRenderingFiber$1 = null;
5610
5611 currentHook = null;
5612 nextCurrentHook = null;
5613 firstWorkInProgressHook = null;
5614 workInProgressHook = null;
5615 nextWorkInProgressHook = null;
5616
5617 {
5618 hookTypesDev = null;
5619 hookTypesUpdateIndexDev = -1;
5620
5621 currentHookNameInDev = null;
5622 }
5623
5624 remainingExpirationTime = NoWork;
5625 componentUpdateQueue = null;
5626 sideEffectTag = 0;
5627
5628 didScheduleRenderPhaseUpdate = false;
5629 renderPhaseUpdates = null;
5630 numberOfReRenders = 0;
5631}
5632
5633function mountWorkInProgressHook() {
5634 var hook = {
5635 memoizedState: null,
5636
5637 baseState: null,
5638 queue: null,
5639 baseUpdate: null,
5640
5641 next: null
5642 };
5643
5644 if (workInProgressHook === null) {
5645 // This is the first hook in the list
5646 firstWorkInProgressHook = workInProgressHook = hook;
5647 } else {
5648 // Append to the end of the list
5649 workInProgressHook = workInProgressHook.next = hook;
5650 }
5651 return workInProgressHook;
5652}
5653
5654function updateWorkInProgressHook() {
5655 // This function is used both for updates and for re-renders triggered by a
5656 // render phase update. It assumes there is either a current hook we can
5657 // clone, or a work-in-progress hook from a previous render pass that we can
5658 // use as a base. When we reach the end of the base list, we must switch to
5659 // the dispatcher used for mounts.
5660 if (nextWorkInProgressHook !== null) {
5661 // There's already a work-in-progress. Reuse it.
5662 workInProgressHook = nextWorkInProgressHook;
5663 nextWorkInProgressHook = workInProgressHook.next;
5664
5665 currentHook = nextCurrentHook;
5666 nextCurrentHook = currentHook !== null ? currentHook.next : null;
5667 } else {
5668 // Clone from the current hook.
5669 (function () {
5670 if (!(nextCurrentHook !== null)) {
5671 {
5672 throw ReactError('Rendered more hooks than during the previous render.');
5673 }
5674 }
5675 })();
5676 currentHook = nextCurrentHook;
5677
5678 var newHook = {
5679 memoizedState: currentHook.memoizedState,
5680
5681 baseState: currentHook.baseState,
5682 queue: currentHook.queue,
5683 baseUpdate: currentHook.baseUpdate,
5684
5685 next: null
5686 };
5687
5688 if (workInProgressHook === null) {
5689 // This is the first hook in the list.
5690 workInProgressHook = firstWorkInProgressHook = newHook;
5691 } else {
5692 // Append to the end of the list.
5693 workInProgressHook = workInProgressHook.next = newHook;
5694 }
5695 nextCurrentHook = currentHook.next;
5696 }
5697 return workInProgressHook;
5698}
5699
5700function createFunctionComponentUpdateQueue() {
5701 return {
5702 lastEffect: null
5703 };
5704}
5705
5706function basicStateReducer(state, action) {
5707 return typeof action === 'function' ? action(state) : action;
5708}
5709
5710function mountReducer(reducer, initialArg, init) {
5711 var hook = mountWorkInProgressHook();
5712 var initialState = void 0;
5713 if (init !== undefined) {
5714 initialState = init(initialArg);
5715 } else {
5716 initialState = initialArg;
5717 }
5718 hook.memoizedState = hook.baseState = initialState;
5719 var queue = hook.queue = {
5720 last: null,
5721 dispatch: null,
5722 lastRenderedReducer: reducer,
5723 lastRenderedState: initialState
5724 };
5725 var dispatch = queue.dispatch = dispatchAction.bind(null,
5726 // Flow doesn't know this is non-null, but we do.
5727 currentlyRenderingFiber$1, queue);
5728 return [hook.memoizedState, dispatch];
5729}
5730
5731function updateReducer(reducer, initialArg, init) {
5732 var hook = updateWorkInProgressHook();
5733 var queue = hook.queue;
5734 (function () {
5735 if (!(queue !== null)) {
5736 {
5737 throw ReactError('Should have a queue. This is likely a bug in React. Please file an issue.');
5738 }
5739 }
5740 })();
5741
5742 queue.lastRenderedReducer = reducer;
5743
5744 if (numberOfReRenders > 0) {
5745 // This is a re-render. Apply the new render phase updates to the previous
5746 var _dispatch = queue.dispatch;
5747 if (renderPhaseUpdates !== null) {
5748 // Render phase updates are stored in a map of queue -> linked list
5749 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
5750 if (firstRenderPhaseUpdate !== undefined) {
5751 renderPhaseUpdates.delete(queue);
5752 var newState = hook.memoizedState;
5753 var update = firstRenderPhaseUpdate;
5754 do {
5755 // Process this render phase update. We don't have to check the
5756 // priority because it will always be the same as the current
5757 // render's.
5758 var _action = update.action;
5759 newState = reducer(newState, _action);
5760 update = update.next;
5761 } while (update !== null);
5762
5763 // Mark that the fiber performed work, but only if the new state is
5764 // different from the current state.
5765 if (!is(newState, hook.memoizedState)) {
5766 markWorkInProgressReceivedUpdate();
5767 }
5768
5769 hook.memoizedState = newState;
5770 // Don't persist the state accumlated from the render phase updates to
5771 // the base state unless the queue is empty.
5772 // TODO: Not sure if this is the desired semantics, but it's what we
5773 // do for gDSFP. I can't remember why.
5774 if (hook.baseUpdate === queue.last) {
5775 hook.baseState = newState;
5776 }
5777
5778 queue.lastRenderedState = newState;
5779
5780 return [newState, _dispatch];
5781 }
5782 }
5783 return [hook.memoizedState, _dispatch];
5784 }
5785
5786 // The last update in the entire queue
5787 var last = queue.last;
5788 // The last update that is part of the base state.
5789 var baseUpdate = hook.baseUpdate;
5790 var baseState = hook.baseState;
5791
5792 // Find the first unprocessed update.
5793 var first = void 0;
5794 if (baseUpdate !== null) {
5795 if (last !== null) {
5796 // For the first update, the queue is a circular linked list where
5797 // `queue.last.next = queue.first`. Once the first update commits, and
5798 // the `baseUpdate` is no longer empty, we can unravel the list.
5799 last.next = null;
5800 }
5801 first = baseUpdate.next;
5802 } else {
5803 first = last !== null ? last.next : null;
5804 }
5805 if (first !== null) {
5806 var _newState = baseState;
5807 var newBaseState = null;
5808 var newBaseUpdate = null;
5809 var prevUpdate = baseUpdate;
5810 var _update = first;
5811 var didSkip = false;
5812 do {
5813 var updateExpirationTime = _update.expirationTime;
5814 if (updateExpirationTime < renderExpirationTime) {
5815 // Priority is insufficient. Skip this update. If this is the first
5816 // skipped update, the previous update/state is the new base
5817 // update/state.
5818 if (!didSkip) {
5819 didSkip = true;
5820 newBaseUpdate = prevUpdate;
5821 newBaseState = _newState;
5822 }
5823 // Update the remaining priority in the queue.
5824 if (updateExpirationTime > remainingExpirationTime) {
5825 remainingExpirationTime = updateExpirationTime;
5826 }
5827 } else {
5828 // Process this update.
5829 if (_update.eagerReducer === reducer) {
5830 // If this update was processed eagerly, and its reducer matches the
5831 // current reducer, we can use the eagerly computed state.
5832 _newState = _update.eagerState;
5833 } else {
5834 var _action2 = _update.action;
5835 _newState = reducer(_newState, _action2);
5836 }
5837 }
5838 prevUpdate = _update;
5839 _update = _update.next;
5840 } while (_update !== null && _update !== first);
5841
5842 if (!didSkip) {
5843 newBaseUpdate = prevUpdate;
5844 newBaseState = _newState;
5845 }
5846
5847 // Mark that the fiber performed work, but only if the new state is
5848 // different from the current state.
5849 if (!is(_newState, hook.memoizedState)) {
5850 markWorkInProgressReceivedUpdate();
5851 }
5852
5853 hook.memoizedState = _newState;
5854 hook.baseUpdate = newBaseUpdate;
5855 hook.baseState = newBaseState;
5856
5857 queue.lastRenderedState = _newState;
5858 }
5859
5860 var dispatch = queue.dispatch;
5861 return [hook.memoizedState, dispatch];
5862}
5863
5864function mountState(initialState) {
5865 var hook = mountWorkInProgressHook();
5866 if (typeof initialState === 'function') {
5867 initialState = initialState();
5868 }
5869 hook.memoizedState = hook.baseState = initialState;
5870 var queue = hook.queue = {
5871 last: null,
5872 dispatch: null,
5873 lastRenderedReducer: basicStateReducer,
5874 lastRenderedState: initialState
5875 };
5876 var dispatch = queue.dispatch = dispatchAction.bind(null,
5877 // Flow doesn't know this is non-null, but we do.
5878 currentlyRenderingFiber$1, queue);
5879 return [hook.memoizedState, dispatch];
5880}
5881
5882function updateState(initialState) {
5883 return updateReducer(basicStateReducer, initialState);
5884}
5885
5886function pushEffect(tag, create, destroy, deps) {
5887 var effect = {
5888 tag: tag,
5889 create: create,
5890 destroy: destroy,
5891 deps: deps,
5892 // Circular
5893 next: null
5894 };
5895 if (componentUpdateQueue === null) {
5896 componentUpdateQueue = createFunctionComponentUpdateQueue();
5897 componentUpdateQueue.lastEffect = effect.next = effect;
5898 } else {
5899 var _lastEffect = componentUpdateQueue.lastEffect;
5900 if (_lastEffect === null) {
5901 componentUpdateQueue.lastEffect = effect.next = effect;
5902 } else {
5903 var firstEffect = _lastEffect.next;
5904 _lastEffect.next = effect;
5905 effect.next = firstEffect;
5906 componentUpdateQueue.lastEffect = effect;
5907 }
5908 }
5909 return effect;
5910}
5911
5912function mountRef(initialValue) {
5913 var hook = mountWorkInProgressHook();
5914 var ref = { current: initialValue };
5915 {
5916 Object.seal(ref);
5917 }
5918 hook.memoizedState = ref;
5919 return ref;
5920}
5921
5922function updateRef(initialValue) {
5923 var hook = updateWorkInProgressHook();
5924 return hook.memoizedState;
5925}
5926
5927function mountEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
5928 var hook = mountWorkInProgressHook();
5929 var nextDeps = deps === undefined ? null : deps;
5930 sideEffectTag |= fiberEffectTag;
5931 hook.memoizedState = pushEffect(hookEffectTag, create, undefined, nextDeps);
5932}
5933
5934function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
5935 var hook = updateWorkInProgressHook();
5936 var nextDeps = deps === undefined ? null : deps;
5937 var destroy = undefined;
5938
5939 if (currentHook !== null) {
5940 var prevEffect = currentHook.memoizedState;
5941 destroy = prevEffect.destroy;
5942 if (nextDeps !== null) {
5943 var prevDeps = prevEffect.deps;
5944 if (areHookInputsEqual(nextDeps, prevDeps)) {
5945 pushEffect(NoEffect$1, create, destroy, nextDeps);
5946 return;
5947 }
5948 }
5949 }
5950
5951 sideEffectTag |= fiberEffectTag;
5952 hook.memoizedState = pushEffect(hookEffectTag, create, destroy, nextDeps);
5953}
5954
5955function mountEffect(create, deps) {
5956 return mountEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
5957}
5958
5959function updateEffect(create, deps) {
5960 return updateEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
5961}
5962
5963function mountLayoutEffect(create, deps) {
5964 return mountEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
5965}
5966
5967function updateLayoutEffect(create, deps) {
5968 return updateEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
5969}
5970
5971function imperativeHandleEffect(create, ref) {
5972 if (typeof ref === 'function') {
5973 var refCallback = ref;
5974 var _inst = create();
5975 refCallback(_inst);
5976 return function () {
5977 refCallback(null);
5978 };
5979 } else if (ref !== null && ref !== undefined) {
5980 var refObject = ref;
5981 {
5982 !refObject.hasOwnProperty('current') ? warning$1(false, 'Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}') : void 0;
5983 }
5984 var _inst2 = create();
5985 refObject.current = _inst2;
5986 return function () {
5987 refObject.current = null;
5988 };
5989 }
5990}
5991
5992function mountImperativeHandle(ref, create, deps) {
5993 {
5994 !(typeof create === 'function') ? warning$1(false, 'Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null') : void 0;
5995 }
5996
5997 // TODO: If deps are provided, should we skip comparing the ref itself?
5998 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
5999
6000 return mountEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
6001}
6002
6003function updateImperativeHandle(ref, create, deps) {
6004 {
6005 !(typeof create === 'function') ? warning$1(false, 'Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null') : void 0;
6006 }
6007
6008 // TODO: If deps are provided, should we skip comparing the ref itself?
6009 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
6010
6011 return updateEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
6012}
6013
6014function mountDebugValue(value, formatterFn) {
6015 // This hook is normally a no-op.
6016 // The react-debug-hooks package injects its own implementation
6017 // so that e.g. DevTools can display custom hook values.
6018}
6019
6020var updateDebugValue = mountDebugValue;
6021
6022function mountCallback(callback, deps) {
6023 var hook = mountWorkInProgressHook();
6024 var nextDeps = deps === undefined ? null : deps;
6025 hook.memoizedState = [callback, nextDeps];
6026 return callback;
6027}
6028
6029function updateCallback(callback, deps) {
6030 var hook = updateWorkInProgressHook();
6031 var nextDeps = deps === undefined ? null : deps;
6032 var prevState = hook.memoizedState;
6033 if (prevState !== null) {
6034 if (nextDeps !== null) {
6035 var prevDeps = prevState[1];
6036 if (areHookInputsEqual(nextDeps, prevDeps)) {
6037 return prevState[0];
6038 }
6039 }
6040 }
6041 hook.memoizedState = [callback, nextDeps];
6042 return callback;
6043}
6044
6045function mountMemo(nextCreate, deps) {
6046 var hook = mountWorkInProgressHook();
6047 var nextDeps = deps === undefined ? null : deps;
6048 var nextValue = nextCreate();
6049 hook.memoizedState = [nextValue, nextDeps];
6050 return nextValue;
6051}
6052
6053function updateMemo(nextCreate, deps) {
6054 var hook = updateWorkInProgressHook();
6055 var nextDeps = deps === undefined ? null : deps;
6056 var prevState = hook.memoizedState;
6057 if (prevState !== null) {
6058 // Assume these are defined. If they're not, areHookInputsEqual will warn.
6059 if (nextDeps !== null) {
6060 var prevDeps = prevState[1];
6061 if (areHookInputsEqual(nextDeps, prevDeps)) {
6062 return prevState[0];
6063 }
6064 }
6065 }
6066 var nextValue = nextCreate();
6067 hook.memoizedState = [nextValue, nextDeps];
6068 return nextValue;
6069}
6070
6071function dispatchAction(fiber, queue, action) {
6072 (function () {
6073 if (!(numberOfReRenders < RE_RENDER_LIMIT)) {
6074 {
6075 throw ReactError('Too many re-renders. React limits the number of renders to prevent an infinite loop.');
6076 }
6077 }
6078 })();
6079
6080 {
6081 !(arguments.length <= 3) ? warning$1(false, "State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().') : void 0;
6082 }
6083
6084 var alternate = fiber.alternate;
6085 if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {
6086 // This is a render phase update. Stash it in a lazily-created map of
6087 // queue -> linked list of updates. After this render pass, we'll restart
6088 // and apply the stashed updates on top of the work-in-progress hook.
6089 didScheduleRenderPhaseUpdate = true;
6090 var update = {
6091 expirationTime: renderExpirationTime,
6092 action: action,
6093 eagerReducer: null,
6094 eagerState: null,
6095 next: null
6096 };
6097 if (renderPhaseUpdates === null) {
6098 renderPhaseUpdates = new Map();
6099 }
6100 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
6101 if (firstRenderPhaseUpdate === undefined) {
6102 renderPhaseUpdates.set(queue, update);
6103 } else {
6104 // Append the update to the end of the list.
6105 var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
6106 while (lastRenderPhaseUpdate.next !== null) {
6107 lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
6108 }
6109 lastRenderPhaseUpdate.next = update;
6110 }
6111 } else {
6112 flushPassiveEffects$$1();
6113
6114 var currentTime = requestCurrentTime$$1();
6115 var _expirationTime = computeExpirationForFiber$$1(currentTime, fiber);
6116
6117 var _update2 = {
6118 expirationTime: _expirationTime,
6119 action: action,
6120 eagerReducer: null,
6121 eagerState: null,
6122 next: null
6123 };
6124
6125 // Append the update to the end of the list.
6126 var _last = queue.last;
6127 if (_last === null) {
6128 // This is the first update. Create a circular list.
6129 _update2.next = _update2;
6130 } else {
6131 var first = _last.next;
6132 if (first !== null) {
6133 // Still circular.
6134 _update2.next = first;
6135 }
6136 _last.next = _update2;
6137 }
6138 queue.last = _update2;
6139
6140 if (fiber.expirationTime === NoWork && (alternate === null || alternate.expirationTime === NoWork)) {
6141 // The queue is currently empty, which means we can eagerly compute the
6142 // next state before entering the render phase. If the new state is the
6143 // same as the current state, we may be able to bail out entirely.
6144 var _lastRenderedReducer = queue.lastRenderedReducer;
6145 if (_lastRenderedReducer !== null) {
6146 var prevDispatcher = void 0;
6147 {
6148 prevDispatcher = ReactCurrentDispatcher$1.current;
6149 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
6150 }
6151 try {
6152 var currentState = queue.lastRenderedState;
6153 var _eagerState = _lastRenderedReducer(currentState, action);
6154 // Stash the eagerly computed state, and the reducer used to compute
6155 // it, on the update object. If the reducer hasn't changed by the
6156 // time we enter the render phase, then the eager state can be used
6157 // without calling the reducer again.
6158 _update2.eagerReducer = _lastRenderedReducer;
6159 _update2.eagerState = _eagerState;
6160 if (is(_eagerState, currentState)) {
6161 // Fast path. We can bail out without scheduling React to re-render.
6162 // It's still possible that we'll need to rebase this update later,
6163 // if the component re-renders for a different reason and by that
6164 // time the reducer has changed.
6165 return;
6166 }
6167 } catch (error) {
6168 // Suppress the error. It will throw again in the render phase.
6169 } finally {
6170 {
6171 ReactCurrentDispatcher$1.current = prevDispatcher;
6172 }
6173 }
6174 }
6175 }
6176 {
6177 // jest isn't a 'global', it's just exposed to tests via a wrapped function
6178 // further, this isn't a test file, so flow doesn't recognize the symbol. So...
6179 // $FlowExpectedError - because requirements don't give a damn about your type sigs.
6180 if ('undefined' !== typeof jest) {
6181 warnIfNotCurrentlyActingUpdatesInDev$$1(fiber);
6182 }
6183 }
6184 scheduleWork$$1(fiber, _expirationTime);
6185 }
6186}
6187
6188var ContextOnlyDispatcher = {
6189 readContext: readContext,
6190
6191 useCallback: throwInvalidHookError,
6192 useContext: throwInvalidHookError,
6193 useEffect: throwInvalidHookError,
6194 useImperativeHandle: throwInvalidHookError,
6195 useLayoutEffect: throwInvalidHookError,
6196 useMemo: throwInvalidHookError,
6197 useReducer: throwInvalidHookError,
6198 useRef: throwInvalidHookError,
6199 useState: throwInvalidHookError,
6200 useDebugValue: throwInvalidHookError
6201};
6202
6203var HooksDispatcherOnMountInDEV = null;
6204var HooksDispatcherOnMountWithHookTypesInDEV = null;
6205var HooksDispatcherOnUpdateInDEV = null;
6206var InvalidNestedHooksDispatcherOnMountInDEV = null;
6207var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
6208
6209{
6210 var warnInvalidContextAccess = function () {
6211 warning$1(false, 'Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
6212 };
6213
6214 var warnInvalidHookAccess = function () {
6215 warning$1(false, 'Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://fb.me/rules-of-hooks');
6216 };
6217
6218 HooksDispatcherOnMountInDEV = {
6219 readContext: function (context, observedBits) {
6220 return readContext(context, observedBits);
6221 },
6222 useCallback: function (callback, deps) {
6223 currentHookNameInDev = 'useCallback';
6224 mountHookTypesDev();
6225 checkDepsAreArrayDev(deps);
6226 return mountCallback(callback, deps);
6227 },
6228 useContext: function (context, observedBits) {
6229 currentHookNameInDev = 'useContext';
6230 mountHookTypesDev();
6231 return readContext(context, observedBits);
6232 },
6233 useEffect: function (create, deps) {
6234 currentHookNameInDev = 'useEffect';
6235 mountHookTypesDev();
6236 checkDepsAreArrayDev(deps);
6237 return mountEffect(create, deps);
6238 },
6239 useImperativeHandle: function (ref, create, deps) {
6240 currentHookNameInDev = 'useImperativeHandle';
6241 mountHookTypesDev();
6242 checkDepsAreArrayDev(deps);
6243 return mountImperativeHandle(ref, create, deps);
6244 },
6245 useLayoutEffect: function (create, deps) {
6246 currentHookNameInDev = 'useLayoutEffect';
6247 mountHookTypesDev();
6248 checkDepsAreArrayDev(deps);
6249 return mountLayoutEffect(create, deps);
6250 },
6251 useMemo: function (create, deps) {
6252 currentHookNameInDev = 'useMemo';
6253 mountHookTypesDev();
6254 checkDepsAreArrayDev(deps);
6255 var prevDispatcher = ReactCurrentDispatcher$1.current;
6256 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
6257 try {
6258 return mountMemo(create, deps);
6259 } finally {
6260 ReactCurrentDispatcher$1.current = prevDispatcher;
6261 }
6262 },
6263 useReducer: function (reducer, initialArg, init) {
6264 currentHookNameInDev = 'useReducer';
6265 mountHookTypesDev();
6266 var prevDispatcher = ReactCurrentDispatcher$1.current;
6267 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
6268 try {
6269 return mountReducer(reducer, initialArg, init);
6270 } finally {
6271 ReactCurrentDispatcher$1.current = prevDispatcher;
6272 }
6273 },
6274 useRef: function (initialValue) {
6275 currentHookNameInDev = 'useRef';
6276 mountHookTypesDev();
6277 return mountRef(initialValue);
6278 },
6279 useState: function (initialState) {
6280 currentHookNameInDev = 'useState';
6281 mountHookTypesDev();
6282 var prevDispatcher = ReactCurrentDispatcher$1.current;
6283 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
6284 try {
6285 return mountState(initialState);
6286 } finally {
6287 ReactCurrentDispatcher$1.current = prevDispatcher;
6288 }
6289 },
6290 useDebugValue: function (value, formatterFn) {
6291 currentHookNameInDev = 'useDebugValue';
6292 mountHookTypesDev();
6293 return mountDebugValue(value, formatterFn);
6294 }
6295 };
6296
6297 HooksDispatcherOnMountWithHookTypesInDEV = {
6298 readContext: function (context, observedBits) {
6299 return readContext(context, observedBits);
6300 },
6301 useCallback: function (callback, deps) {
6302 currentHookNameInDev = 'useCallback';
6303 updateHookTypesDev();
6304 return mountCallback(callback, deps);
6305 },
6306 useContext: function (context, observedBits) {
6307 currentHookNameInDev = 'useContext';
6308 updateHookTypesDev();
6309 return readContext(context, observedBits);
6310 },
6311 useEffect: function (create, deps) {
6312 currentHookNameInDev = 'useEffect';
6313 updateHookTypesDev();
6314 return mountEffect(create, deps);
6315 },
6316 useImperativeHandle: function (ref, create, deps) {
6317 currentHookNameInDev = 'useImperativeHandle';
6318 updateHookTypesDev();
6319 return mountImperativeHandle(ref, create, deps);
6320 },
6321 useLayoutEffect: function (create, deps) {
6322 currentHookNameInDev = 'useLayoutEffect';
6323 updateHookTypesDev();
6324 return mountLayoutEffect(create, deps);
6325 },
6326 useMemo: function (create, deps) {
6327 currentHookNameInDev = 'useMemo';
6328 updateHookTypesDev();
6329 var prevDispatcher = ReactCurrentDispatcher$1.current;
6330 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
6331 try {
6332 return mountMemo(create, deps);
6333 } finally {
6334 ReactCurrentDispatcher$1.current = prevDispatcher;
6335 }
6336 },
6337 useReducer: function (reducer, initialArg, init) {
6338 currentHookNameInDev = 'useReducer';
6339 updateHookTypesDev();
6340 var prevDispatcher = ReactCurrentDispatcher$1.current;
6341 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
6342 try {
6343 return mountReducer(reducer, initialArg, init);
6344 } finally {
6345 ReactCurrentDispatcher$1.current = prevDispatcher;
6346 }
6347 },
6348 useRef: function (initialValue) {
6349 currentHookNameInDev = 'useRef';
6350 updateHookTypesDev();
6351 return mountRef(initialValue);
6352 },
6353 useState: function (initialState) {
6354 currentHookNameInDev = 'useState';
6355 updateHookTypesDev();
6356 var prevDispatcher = ReactCurrentDispatcher$1.current;
6357 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
6358 try {
6359 return mountState(initialState);
6360 } finally {
6361 ReactCurrentDispatcher$1.current = prevDispatcher;
6362 }
6363 },
6364 useDebugValue: function (value, formatterFn) {
6365 currentHookNameInDev = 'useDebugValue';
6366 updateHookTypesDev();
6367 return mountDebugValue(value, formatterFn);
6368 }
6369 };
6370
6371 HooksDispatcherOnUpdateInDEV = {
6372 readContext: function (context, observedBits) {
6373 return readContext(context, observedBits);
6374 },
6375 useCallback: function (callback, deps) {
6376 currentHookNameInDev = 'useCallback';
6377 updateHookTypesDev();
6378 return updateCallback(callback, deps);
6379 },
6380 useContext: function (context, observedBits) {
6381 currentHookNameInDev = 'useContext';
6382 updateHookTypesDev();
6383 return readContext(context, observedBits);
6384 },
6385 useEffect: function (create, deps) {
6386 currentHookNameInDev = 'useEffect';
6387 updateHookTypesDev();
6388 return updateEffect(create, deps);
6389 },
6390 useImperativeHandle: function (ref, create, deps) {
6391 currentHookNameInDev = 'useImperativeHandle';
6392 updateHookTypesDev();
6393 return updateImperativeHandle(ref, create, deps);
6394 },
6395 useLayoutEffect: function (create, deps) {
6396 currentHookNameInDev = 'useLayoutEffect';
6397 updateHookTypesDev();
6398 return updateLayoutEffect(create, deps);
6399 },
6400 useMemo: function (create, deps) {
6401 currentHookNameInDev = 'useMemo';
6402 updateHookTypesDev();
6403 var prevDispatcher = ReactCurrentDispatcher$1.current;
6404 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
6405 try {
6406 return updateMemo(create, deps);
6407 } finally {
6408 ReactCurrentDispatcher$1.current = prevDispatcher;
6409 }
6410 },
6411 useReducer: function (reducer, initialArg, init) {
6412 currentHookNameInDev = 'useReducer';
6413 updateHookTypesDev();
6414 var prevDispatcher = ReactCurrentDispatcher$1.current;
6415 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
6416 try {
6417 return updateReducer(reducer, initialArg, init);
6418 } finally {
6419 ReactCurrentDispatcher$1.current = prevDispatcher;
6420 }
6421 },
6422 useRef: function (initialValue) {
6423 currentHookNameInDev = 'useRef';
6424 updateHookTypesDev();
6425 return updateRef(initialValue);
6426 },
6427 useState: function (initialState) {
6428 currentHookNameInDev = 'useState';
6429 updateHookTypesDev();
6430 var prevDispatcher = ReactCurrentDispatcher$1.current;
6431 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
6432 try {
6433 return updateState(initialState);
6434 } finally {
6435 ReactCurrentDispatcher$1.current = prevDispatcher;
6436 }
6437 },
6438 useDebugValue: function (value, formatterFn) {
6439 currentHookNameInDev = 'useDebugValue';
6440 updateHookTypesDev();
6441 return updateDebugValue(value, formatterFn);
6442 }
6443 };
6444
6445 InvalidNestedHooksDispatcherOnMountInDEV = {
6446 readContext: function (context, observedBits) {
6447 warnInvalidContextAccess();
6448 return readContext(context, observedBits);
6449 },
6450 useCallback: function (callback, deps) {
6451 currentHookNameInDev = 'useCallback';
6452 warnInvalidHookAccess();
6453 mountHookTypesDev();
6454 return mountCallback(callback, deps);
6455 },
6456 useContext: function (context, observedBits) {
6457 currentHookNameInDev = 'useContext';
6458 warnInvalidHookAccess();
6459 mountHookTypesDev();
6460 return readContext(context, observedBits);
6461 },
6462 useEffect: function (create, deps) {
6463 currentHookNameInDev = 'useEffect';
6464 warnInvalidHookAccess();
6465 mountHookTypesDev();
6466 return mountEffect(create, deps);
6467 },
6468 useImperativeHandle: function (ref, create, deps) {
6469 currentHookNameInDev = 'useImperativeHandle';
6470 warnInvalidHookAccess();
6471 mountHookTypesDev();
6472 return mountImperativeHandle(ref, create, deps);
6473 },
6474 useLayoutEffect: function (create, deps) {
6475 currentHookNameInDev = 'useLayoutEffect';
6476 warnInvalidHookAccess();
6477 mountHookTypesDev();
6478 return mountLayoutEffect(create, deps);
6479 },
6480 useMemo: function (create, deps) {
6481 currentHookNameInDev = 'useMemo';
6482 warnInvalidHookAccess();
6483 mountHookTypesDev();
6484 var prevDispatcher = ReactCurrentDispatcher$1.current;
6485 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
6486 try {
6487 return mountMemo(create, deps);
6488 } finally {
6489 ReactCurrentDispatcher$1.current = prevDispatcher;
6490 }
6491 },
6492 useReducer: function (reducer, initialArg, init) {
6493 currentHookNameInDev = 'useReducer';
6494 warnInvalidHookAccess();
6495 mountHookTypesDev();
6496 var prevDispatcher = ReactCurrentDispatcher$1.current;
6497 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
6498 try {
6499 return mountReducer(reducer, initialArg, init);
6500 } finally {
6501 ReactCurrentDispatcher$1.current = prevDispatcher;
6502 }
6503 },
6504 useRef: function (initialValue) {
6505 currentHookNameInDev = 'useRef';
6506 warnInvalidHookAccess();
6507 mountHookTypesDev();
6508 return mountRef(initialValue);
6509 },
6510 useState: function (initialState) {
6511 currentHookNameInDev = 'useState';
6512 warnInvalidHookAccess();
6513 mountHookTypesDev();
6514 var prevDispatcher = ReactCurrentDispatcher$1.current;
6515 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
6516 try {
6517 return mountState(initialState);
6518 } finally {
6519 ReactCurrentDispatcher$1.current = prevDispatcher;
6520 }
6521 },
6522 useDebugValue: function (value, formatterFn) {
6523 currentHookNameInDev = 'useDebugValue';
6524 warnInvalidHookAccess();
6525 mountHookTypesDev();
6526 return mountDebugValue(value, formatterFn);
6527 }
6528 };
6529
6530 InvalidNestedHooksDispatcherOnUpdateInDEV = {
6531 readContext: function (context, observedBits) {
6532 warnInvalidContextAccess();
6533 return readContext(context, observedBits);
6534 },
6535 useCallback: function (callback, deps) {
6536 currentHookNameInDev = 'useCallback';
6537 warnInvalidHookAccess();
6538 updateHookTypesDev();
6539 return updateCallback(callback, deps);
6540 },
6541 useContext: function (context, observedBits) {
6542 currentHookNameInDev = 'useContext';
6543 warnInvalidHookAccess();
6544 updateHookTypesDev();
6545 return readContext(context, observedBits);
6546 },
6547 useEffect: function (create, deps) {
6548 currentHookNameInDev = 'useEffect';
6549 warnInvalidHookAccess();
6550 updateHookTypesDev();
6551 return updateEffect(create, deps);
6552 },
6553 useImperativeHandle: function (ref, create, deps) {
6554 currentHookNameInDev = 'useImperativeHandle';
6555 warnInvalidHookAccess();
6556 updateHookTypesDev();
6557 return updateImperativeHandle(ref, create, deps);
6558 },
6559 useLayoutEffect: function (create, deps) {
6560 currentHookNameInDev = 'useLayoutEffect';
6561 warnInvalidHookAccess();
6562 updateHookTypesDev();
6563 return updateLayoutEffect(create, deps);
6564 },
6565 useMemo: function (create, deps) {
6566 currentHookNameInDev = 'useMemo';
6567 warnInvalidHookAccess();
6568 updateHookTypesDev();
6569 var prevDispatcher = ReactCurrentDispatcher$1.current;
6570 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
6571 try {
6572 return updateMemo(create, deps);
6573 } finally {
6574 ReactCurrentDispatcher$1.current = prevDispatcher;
6575 }
6576 },
6577 useReducer: function (reducer, initialArg, init) {
6578 currentHookNameInDev = 'useReducer';
6579 warnInvalidHookAccess();
6580 updateHookTypesDev();
6581 var prevDispatcher = ReactCurrentDispatcher$1.current;
6582 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
6583 try {
6584 return updateReducer(reducer, initialArg, init);
6585 } finally {
6586 ReactCurrentDispatcher$1.current = prevDispatcher;
6587 }
6588 },
6589 useRef: function (initialValue) {
6590 currentHookNameInDev = 'useRef';
6591 warnInvalidHookAccess();
6592 updateHookTypesDev();
6593 return updateRef(initialValue);
6594 },
6595 useState: function (initialState) {
6596 currentHookNameInDev = 'useState';
6597 warnInvalidHookAccess();
6598 updateHookTypesDev();
6599 var prevDispatcher = ReactCurrentDispatcher$1.current;
6600 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
6601 try {
6602 return updateState(initialState);
6603 } finally {
6604 ReactCurrentDispatcher$1.current = prevDispatcher;
6605 }
6606 },
6607 useDebugValue: function (value, formatterFn) {
6608 currentHookNameInDev = 'useDebugValue';
6609 warnInvalidHookAccess();
6610 updateHookTypesDev();
6611 return updateDebugValue(value, formatterFn);
6612 }
6613 };
6614}
6615
6616// Intentionally not named imports because Rollup would use dynamic dispatch for
6617// CommonJS interop named imports.
6618var now$2 = Scheduler$1.unstable_now;
6619
6620
6621var commitTime = 0;
6622var profilerStartTime = -1;
6623
6624function getCommitTime() {
6625 return commitTime;
6626}
6627
6628function recordCommitTime() {
6629 if (!enableProfilerTimer) {
6630 return;
6631 }
6632 commitTime = now$2();
6633}
6634
6635function startProfilerTimer(fiber) {
6636 if (!enableProfilerTimer) {
6637 return;
6638 }
6639
6640 profilerStartTime = now$2();
6641
6642 if (fiber.actualStartTime < 0) {
6643 fiber.actualStartTime = now$2();
6644 }
6645}
6646
6647function stopProfilerTimerIfRunning(fiber) {
6648 if (!enableProfilerTimer) {
6649 return;
6650 }
6651 profilerStartTime = -1;
6652}
6653
6654function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
6655 if (!enableProfilerTimer) {
6656 return;
6657 }
6658
6659 if (profilerStartTime >= 0) {
6660 var elapsedTime = now$2() - profilerStartTime;
6661 fiber.actualDuration += elapsedTime;
6662 if (overrideBaseTime) {
6663 fiber.selfBaseDuration = elapsedTime;
6664 }
6665 profilerStartTime = -1;
6666 }
6667}
6668
6669// The deepest Fiber on the stack involved in a hydration context.
6670// This may have been an insertion or a hydration.
6671var hydrationParentFiber = null;
6672var nextHydratableInstance = null;
6673var isHydrating = false;
6674
6675function enterHydrationState(fiber) {
6676 if (!supportsHydration) {
6677 return false;
6678 }
6679
6680 var parentInstance = fiber.stateNode.containerInfo;
6681 nextHydratableInstance = getFirstHydratableChild(parentInstance);
6682 hydrationParentFiber = fiber;
6683 isHydrating = true;
6684 return true;
6685}
6686
6687function reenterHydrationStateFromDehydratedSuspenseInstance(fiber) {
6688 if (!supportsHydration) {
6689 return false;
6690 }
6691
6692 var suspenseInstance = fiber.stateNode;
6693 nextHydratableInstance = getNextHydratableSibling(suspenseInstance);
6694 popToNextHostParent(fiber);
6695 isHydrating = true;
6696 return true;
6697}
6698
6699function deleteHydratableInstance(returnFiber, instance) {
6700 {
6701 switch (returnFiber.tag) {
6702 case HostRoot:
6703 didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance);
6704 break;
6705 case HostComponent:
6706 didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance);
6707 break;
6708 }
6709 }
6710
6711 var childToDelete = createFiberFromHostInstanceForDeletion();
6712 childToDelete.stateNode = instance;
6713 childToDelete.return = returnFiber;
6714 childToDelete.effectTag = Deletion;
6715
6716 // This might seem like it belongs on progressedFirstDeletion. However,
6717 // these children are not part of the reconciliation list of children.
6718 // Even if we abort and rereconcile the children, that will try to hydrate
6719 // again and the nodes are still in the host tree so these will be
6720 // recreated.
6721 if (returnFiber.lastEffect !== null) {
6722 returnFiber.lastEffect.nextEffect = childToDelete;
6723 returnFiber.lastEffect = childToDelete;
6724 } else {
6725 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
6726 }
6727}
6728
6729function insertNonHydratedInstance(returnFiber, fiber) {
6730 fiber.effectTag |= Placement;
6731 {
6732 switch (returnFiber.tag) {
6733 case HostRoot:
6734 {
6735 var parentContainer = returnFiber.stateNode.containerInfo;
6736 switch (fiber.tag) {
6737 case HostComponent:
6738 var type = fiber.type;
6739 var props = fiber.pendingProps;
6740 didNotFindHydratableContainerInstance(parentContainer, type, props);
6741 break;
6742 case HostText:
6743 var text = fiber.pendingProps;
6744 didNotFindHydratableContainerTextInstance(parentContainer, text);
6745 break;
6746 case SuspenseComponent:
6747 didNotFindHydratableContainerSuspenseInstance(parentContainer);
6748 break;
6749 }
6750 break;
6751 }
6752 case HostComponent:
6753 {
6754 var parentType = returnFiber.type;
6755 var parentProps = returnFiber.memoizedProps;
6756 var parentInstance = returnFiber.stateNode;
6757 switch (fiber.tag) {
6758 case HostComponent:
6759 var _type = fiber.type;
6760 var _props = fiber.pendingProps;
6761 didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props);
6762 break;
6763 case HostText:
6764 var _text = fiber.pendingProps;
6765 didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text);
6766 break;
6767 case SuspenseComponent:
6768 didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance);
6769 break;
6770 }
6771 break;
6772 }
6773 default:
6774 return;
6775 }
6776 }
6777}
6778
6779function tryHydrate(fiber, nextInstance) {
6780 switch (fiber.tag) {
6781 case HostComponent:
6782 {
6783 var type = fiber.type;
6784 var props = fiber.pendingProps;
6785 var instance = canHydrateInstance(nextInstance, type, props);
6786 if (instance !== null) {
6787 fiber.stateNode = instance;
6788 return true;
6789 }
6790 return false;
6791 }
6792 case HostText:
6793 {
6794 var text = fiber.pendingProps;
6795 var textInstance = canHydrateTextInstance(nextInstance, text);
6796 if (textInstance !== null) {
6797 fiber.stateNode = textInstance;
6798 return true;
6799 }
6800 return false;
6801 }
6802 case SuspenseComponent:
6803 {
6804 if (enableSuspenseServerRenderer) {
6805 var suspenseInstance = canHydrateSuspenseInstance(nextInstance);
6806 if (suspenseInstance !== null) {
6807 // Downgrade the tag to a dehydrated component until we've hydrated it.
6808 fiber.tag = DehydratedSuspenseComponent;
6809 fiber.stateNode = suspenseInstance;
6810 return true;
6811 }
6812 }
6813 return false;
6814 }
6815 default:
6816 return false;
6817 }
6818}
6819
6820function tryToClaimNextHydratableInstance(fiber) {
6821 if (!isHydrating) {
6822 return;
6823 }
6824 var nextInstance = nextHydratableInstance;
6825 if (!nextInstance) {
6826 // Nothing to hydrate. Make it an insertion.
6827 insertNonHydratedInstance(hydrationParentFiber, fiber);
6828 isHydrating = false;
6829 hydrationParentFiber = fiber;
6830 return;
6831 }
6832 var firstAttemptedInstance = nextInstance;
6833 if (!tryHydrate(fiber, nextInstance)) {
6834 // If we can't hydrate this instance let's try the next one.
6835 // We use this as a heuristic. It's based on intuition and not data so it
6836 // might be flawed or unnecessary.
6837 nextInstance = getNextHydratableSibling(firstAttemptedInstance);
6838 if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
6839 // Nothing to hydrate. Make it an insertion.
6840 insertNonHydratedInstance(hydrationParentFiber, fiber);
6841 isHydrating = false;
6842 hydrationParentFiber = fiber;
6843 return;
6844 }
6845 // We matched the next one, we'll now assume that the first one was
6846 // superfluous and we'll delete it. Since we can't eagerly delete it
6847 // we'll have to schedule a deletion. To do that, this node needs a dummy
6848 // fiber associated with it.
6849 deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance);
6850 }
6851 hydrationParentFiber = fiber;
6852 nextHydratableInstance = getFirstHydratableChild(nextInstance);
6853}
6854
6855function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
6856 if (!supportsHydration) {
6857 (function () {
6858 {
6859 {
6860 throw ReactError('Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
6861 }
6862 }
6863 })();
6864 }
6865
6866 var instance = fiber.stateNode;
6867 var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber);
6868 // TODO: Type this specific to this type of component.
6869 fiber.updateQueue = updatePayload;
6870 // If the update payload indicates that there is a change or if there
6871 // is a new ref we mark this as an update.
6872 if (updatePayload !== null) {
6873 return true;
6874 }
6875 return false;
6876}
6877
6878function prepareToHydrateHostTextInstance(fiber) {
6879 if (!supportsHydration) {
6880 (function () {
6881 {
6882 {
6883 throw ReactError('Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
6884 }
6885 }
6886 })();
6887 }
6888
6889 var textInstance = fiber.stateNode;
6890 var textContent = fiber.memoizedProps;
6891 var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
6892 {
6893 if (shouldUpdate) {
6894 // We assume that prepareToHydrateHostTextInstance is called in a context where the
6895 // hydration parent is the parent host component of this host text.
6896 var returnFiber = hydrationParentFiber;
6897 if (returnFiber !== null) {
6898 switch (returnFiber.tag) {
6899 case HostRoot:
6900 {
6901 var parentContainer = returnFiber.stateNode.containerInfo;
6902 didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent);
6903 break;
6904 }
6905 case HostComponent:
6906 {
6907 var parentType = returnFiber.type;
6908 var parentProps = returnFiber.memoizedProps;
6909 var parentInstance = returnFiber.stateNode;
6910 didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent);
6911 break;
6912 }
6913 }
6914 }
6915 }
6916 }
6917 return shouldUpdate;
6918}
6919
6920function skipPastDehydratedSuspenseInstance(fiber) {
6921 if (!supportsHydration) {
6922 (function () {
6923 {
6924 {
6925 throw ReactError('Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
6926 }
6927 }
6928 })();
6929 }
6930 var suspenseInstance = fiber.stateNode;
6931 (function () {
6932 if (!suspenseInstance) {
6933 {
6934 throw ReactError('Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.');
6935 }
6936 }
6937 })();
6938 nextHydratableInstance = getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
6939}
6940
6941function popToNextHostParent(fiber) {
6942 var parent = fiber.return;
6943 while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== DehydratedSuspenseComponent) {
6944 parent = parent.return;
6945 }
6946 hydrationParentFiber = parent;
6947}
6948
6949function popHydrationState(fiber) {
6950 if (!supportsHydration) {
6951 return false;
6952 }
6953 if (fiber !== hydrationParentFiber) {
6954 // We're deeper than the current hydration context, inside an inserted
6955 // tree.
6956 return false;
6957 }
6958 if (!isHydrating) {
6959 // If we're not currently hydrating but we're in a hydration context, then
6960 // we were an insertion and now need to pop up reenter hydration of our
6961 // siblings.
6962 popToNextHostParent(fiber);
6963 isHydrating = true;
6964 return false;
6965 }
6966
6967 var type = fiber.type;
6968
6969 // If we have any remaining hydratable nodes, we need to delete them now.
6970 // We only do this deeper than head and body since they tend to have random
6971 // other nodes in them. We also ignore components with pure text content in
6972 // side of them.
6973 // TODO: Better heuristic.
6974 if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) {
6975 var nextInstance = nextHydratableInstance;
6976 while (nextInstance) {
6977 deleteHydratableInstance(fiber, nextInstance);
6978 nextInstance = getNextHydratableSibling(nextInstance);
6979 }
6980 }
6981
6982 popToNextHostParent(fiber);
6983 nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
6984 return true;
6985}
6986
6987function resetHydrationState() {
6988 if (!supportsHydration) {
6989 return;
6990 }
6991
6992 hydrationParentFiber = null;
6993 nextHydratableInstance = null;
6994 isHydrating = false;
6995}
6996
6997var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner;
6998
6999var didReceiveUpdate = false;
7000
7001var didWarnAboutBadClass = void 0;
7002var didWarnAboutModulePatternComponent = void 0;
7003var didWarnAboutContextTypeOnFunctionComponent = void 0;
7004var didWarnAboutGetDerivedStateOnFunctionComponent = void 0;
7005var didWarnAboutFunctionRefs = void 0;
7006var didWarnAboutReassigningProps = void 0;
7007var didWarnAboutMaxDuration = void 0;
7008
7009{
7010 didWarnAboutBadClass = {};
7011 didWarnAboutModulePatternComponent = {};
7012 didWarnAboutContextTypeOnFunctionComponent = {};
7013 didWarnAboutGetDerivedStateOnFunctionComponent = {};
7014 didWarnAboutFunctionRefs = {};
7015 didWarnAboutReassigningProps = false;
7016 didWarnAboutMaxDuration = false;
7017}
7018
7019function reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime) {
7020 if (current$$1 === null) {
7021 // If this is a fresh new component that hasn't been rendered yet, we
7022 // won't update its child set by applying minimal side-effects. Instead,
7023 // we will add them all to the child before it gets rendered. That means
7024 // we can optimize this reconciliation pass by not tracking side-effects.
7025 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
7026 } else {
7027 // If the current child is the same as the work in progress, it means that
7028 // we haven't yet started any work on these children. Therefore, we use
7029 // the clone algorithm to create a copy of all the current children.
7030
7031 // If we had any progressed work already, that is invalid at this point so
7032 // let's throw it out.
7033 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, nextChildren, renderExpirationTime);
7034 }
7035}
7036
7037function forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime) {
7038 // This function is fork of reconcileChildren. It's used in cases where we
7039 // want to reconcile without matching against the existing set. This has the
7040 // effect of all current children being unmounted; even if the type and key
7041 // are the same, the old child is unmounted and a new child is created.
7042 //
7043 // To do this, we're going to go through the reconcile algorithm twice. In
7044 // the first pass, we schedule a deletion for all the current children by
7045 // passing null.
7046 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, null, renderExpirationTime);
7047 // In the second pass, we mount the new children. The trick here is that we
7048 // pass null in place of where we usually pass the current child set. This has
7049 // the effect of remounting all children regardless of whether their their
7050 // identity matches.
7051 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
7052}
7053
7054function updateForwardRef(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
7055 // TODO: current can be non-null here even if the component
7056 // hasn't yet mounted. This happens after the first render suspends.
7057 // We'll need to figure out if this is fine or can cause issues.
7058
7059 {
7060 if (workInProgress.type !== workInProgress.elementType) {
7061 // Lazy component props can't be validated in createElement
7062 // because they're only guaranteed to be resolved here.
7063 var innerPropTypes = Component.propTypes;
7064 if (innerPropTypes) {
7065 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
7066 'prop', getComponentName(Component), getCurrentFiberStackInDev);
7067 }
7068 }
7069 }
7070
7071 var render = Component.render;
7072 var ref = workInProgress.ref;
7073
7074 // The rest is a fork of updateFunctionComponent
7075 var nextChildren = void 0;
7076 prepareToReadContext(workInProgress, renderExpirationTime);
7077 {
7078 ReactCurrentOwner$2.current = workInProgress;
7079 setCurrentPhase('render');
7080 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
7081 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
7082 // Only double-render components with Hooks
7083 if (workInProgress.memoizedState !== null) {
7084 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
7085 }
7086 }
7087 setCurrentPhase(null);
7088 }
7089
7090 if (current$$1 !== null && !didReceiveUpdate) {
7091 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
7092 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
7093 }
7094
7095 // React DevTools reads this flag.
7096 workInProgress.effectTag |= PerformedWork;
7097 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
7098 return workInProgress.child;
7099}
7100
7101function updateMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
7102 if (current$$1 === null) {
7103 var type = Component.type;
7104 if (isSimpleFunctionComponent(type) && Component.compare === null &&
7105 // SimpleMemoComponent codepath doesn't resolve outer props either.
7106 Component.defaultProps === undefined) {
7107 // If this is a plain function component without default props,
7108 // and with only the default shallow comparison, we upgrade it
7109 // to a SimpleMemoComponent to allow fast path updates.
7110 workInProgress.tag = SimpleMemoComponent;
7111 workInProgress.type = type;
7112 {
7113 validateFunctionComponentInDev(workInProgress, type);
7114 }
7115 return updateSimpleMemoComponent(current$$1, workInProgress, type, nextProps, updateExpirationTime, renderExpirationTime);
7116 }
7117 {
7118 var innerPropTypes = type.propTypes;
7119 if (innerPropTypes) {
7120 // Inner memo component props aren't currently validated in createElement.
7121 // We could move it there, but we'd still need this for lazy code path.
7122 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
7123 'prop', getComponentName(type), getCurrentFiberStackInDev);
7124 }
7125 }
7126 var child = createFiberFromTypeAndProps(Component.type, null, nextProps, null, workInProgress.mode, renderExpirationTime);
7127 child.ref = workInProgress.ref;
7128 child.return = workInProgress;
7129 workInProgress.child = child;
7130 return child;
7131 }
7132 {
7133 var _type = Component.type;
7134 var _innerPropTypes = _type.propTypes;
7135 if (_innerPropTypes) {
7136 // Inner memo component props aren't currently validated in createElement.
7137 // We could move it there, but we'd still need this for lazy code path.
7138 checkPropTypes_1(_innerPropTypes, nextProps, // Resolved props
7139 'prop', getComponentName(_type), getCurrentFiberStackInDev);
7140 }
7141 }
7142 var currentChild = current$$1.child; // This is always exactly one child
7143 if (updateExpirationTime < renderExpirationTime) {
7144 // This will be the props with resolved defaultProps,
7145 // unlike current.memoizedProps which will be the unresolved ones.
7146 var prevProps = currentChild.memoizedProps;
7147 // Default to shallow comparison
7148 var compare = Component.compare;
7149 compare = compare !== null ? compare : shallowEqual;
7150 if (compare(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
7151 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
7152 }
7153 }
7154 // React DevTools reads this flag.
7155 workInProgress.effectTag |= PerformedWork;
7156 var newChild = createWorkInProgress(currentChild, nextProps, renderExpirationTime);
7157 newChild.ref = workInProgress.ref;
7158 newChild.return = workInProgress;
7159 workInProgress.child = newChild;
7160 return newChild;
7161}
7162
7163function updateSimpleMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
7164 // TODO: current can be non-null here even if the component
7165 // hasn't yet mounted. This happens when the inner render suspends.
7166 // We'll need to figure out if this is fine or can cause issues.
7167
7168 {
7169 if (workInProgress.type !== workInProgress.elementType) {
7170 // Lazy component props can't be validated in createElement
7171 // because they're only guaranteed to be resolved here.
7172 var outerMemoType = workInProgress.elementType;
7173 if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
7174 // We warn when you define propTypes on lazy()
7175 // so let's just skip over it to find memo() outer wrapper.
7176 // Inner props for memo are validated later.
7177 outerMemoType = refineResolvedLazyComponent(outerMemoType);
7178 }
7179 var outerPropTypes = outerMemoType && outerMemoType.propTypes;
7180 if (outerPropTypes) {
7181 checkPropTypes_1(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
7182 'prop', getComponentName(outerMemoType), getCurrentFiberStackInDev);
7183 }
7184 // Inner propTypes will be validated in the function component path.
7185 }
7186 }
7187 if (current$$1 !== null) {
7188 var prevProps = current$$1.memoizedProps;
7189 if (shallowEqual(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
7190 didReceiveUpdate = false;
7191 if (updateExpirationTime < renderExpirationTime) {
7192 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
7193 }
7194 }
7195 }
7196 return updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
7197}
7198
7199function updateFragment(current$$1, workInProgress, renderExpirationTime) {
7200 var nextChildren = workInProgress.pendingProps;
7201 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
7202 return workInProgress.child;
7203}
7204
7205function updateMode(current$$1, workInProgress, renderExpirationTime) {
7206 var nextChildren = workInProgress.pendingProps.children;
7207 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
7208 return workInProgress.child;
7209}
7210
7211function updateProfiler(current$$1, workInProgress, renderExpirationTime) {
7212 if (enableProfilerTimer) {
7213 workInProgress.effectTag |= Update;
7214 }
7215 var nextProps = workInProgress.pendingProps;
7216 var nextChildren = nextProps.children;
7217 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
7218 return workInProgress.child;
7219}
7220
7221function markRef(current$$1, workInProgress) {
7222 var ref = workInProgress.ref;
7223 if (current$$1 === null && ref !== null || current$$1 !== null && current$$1.ref !== ref) {
7224 // Schedule a Ref effect
7225 workInProgress.effectTag |= Ref;
7226 }
7227}
7228
7229function updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
7230 {
7231 if (workInProgress.type !== workInProgress.elementType) {
7232 // Lazy component props can't be validated in createElement
7233 // because they're only guaranteed to be resolved here.
7234 var innerPropTypes = Component.propTypes;
7235 if (innerPropTypes) {
7236 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
7237 'prop', getComponentName(Component), getCurrentFiberStackInDev);
7238 }
7239 }
7240 }
7241
7242 var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
7243 var context = getMaskedContext(workInProgress, unmaskedContext);
7244
7245 var nextChildren = void 0;
7246 prepareToReadContext(workInProgress, renderExpirationTime);
7247 {
7248 ReactCurrentOwner$2.current = workInProgress;
7249 setCurrentPhase('render');
7250 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
7251 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
7252 // Only double-render components with Hooks
7253 if (workInProgress.memoizedState !== null) {
7254 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
7255 }
7256 }
7257 setCurrentPhase(null);
7258 }
7259
7260 if (current$$1 !== null && !didReceiveUpdate) {
7261 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
7262 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
7263 }
7264
7265 // React DevTools reads this flag.
7266 workInProgress.effectTag |= PerformedWork;
7267 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
7268 return workInProgress.child;
7269}
7270
7271function updateClassComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
7272 {
7273 if (workInProgress.type !== workInProgress.elementType) {
7274 // Lazy component props can't be validated in createElement
7275 // because they're only guaranteed to be resolved here.
7276 var innerPropTypes = Component.propTypes;
7277 if (innerPropTypes) {
7278 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
7279 'prop', getComponentName(Component), getCurrentFiberStackInDev);
7280 }
7281 }
7282 }
7283
7284 // Push context providers early to prevent context stack mismatches.
7285 // During mounting we don't know the child context yet as the instance doesn't exist.
7286 // We will invalidate the child context in finishClassComponent() right after rendering.
7287 var hasContext = void 0;
7288 if (isContextProvider(Component)) {
7289 hasContext = true;
7290 pushContextProvider(workInProgress);
7291 } else {
7292 hasContext = false;
7293 }
7294 prepareToReadContext(workInProgress, renderExpirationTime);
7295
7296 var instance = workInProgress.stateNode;
7297 var shouldUpdate = void 0;
7298 if (instance === null) {
7299 if (current$$1 !== null) {
7300 // An class component without an instance only mounts if it suspended
7301 // inside a non- concurrent tree, in an inconsistent state. We want to
7302 // tree it like a new mount, even though an empty version of it already
7303 // committed. Disconnect the alternate pointers.
7304 current$$1.alternate = null;
7305 workInProgress.alternate = null;
7306 // Since this is conceptually a new fiber, schedule a Placement effect
7307 workInProgress.effectTag |= Placement;
7308 }
7309 // In the initial pass we might need to construct the instance.
7310 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
7311 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
7312 shouldUpdate = true;
7313 } else if (current$$1 === null) {
7314 // In a resume, we'll already have an instance we can reuse.
7315 shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
7316 } else {
7317 shouldUpdate = updateClassInstance(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
7318 }
7319 var nextUnitOfWork = finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime);
7320 {
7321 var inst = workInProgress.stateNode;
7322 if (inst.props !== nextProps) {
7323 !didWarnAboutReassigningProps ? warning$1(false, 'It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentName(workInProgress.type) || 'a component') : void 0;
7324 didWarnAboutReassigningProps = true;
7325 }
7326 }
7327 return nextUnitOfWork;
7328}
7329
7330function finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime) {
7331 // Refs should update even if shouldComponentUpdate returns false
7332 markRef(current$$1, workInProgress);
7333
7334 var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;
7335
7336 if (!shouldUpdate && !didCaptureError) {
7337 // Context providers should defer to sCU for rendering
7338 if (hasContext) {
7339 invalidateContextProvider(workInProgress, Component, false);
7340 }
7341
7342 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
7343 }
7344
7345 var instance = workInProgress.stateNode;
7346
7347 // Rerender
7348 ReactCurrentOwner$2.current = workInProgress;
7349 var nextChildren = void 0;
7350 if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
7351 // If we captured an error, but getDerivedStateFrom catch is not defined,
7352 // unmount all the children. componentDidCatch will schedule an update to
7353 // re-render a fallback. This is temporary until we migrate everyone to
7354 // the new API.
7355 // TODO: Warn in a future release.
7356 nextChildren = null;
7357
7358 if (enableProfilerTimer) {
7359 stopProfilerTimerIfRunning(workInProgress);
7360 }
7361 } else {
7362 {
7363 setCurrentPhase('render');
7364 nextChildren = instance.render();
7365 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
7366 instance.render();
7367 }
7368 setCurrentPhase(null);
7369 }
7370 }
7371
7372 // React DevTools reads this flag.
7373 workInProgress.effectTag |= PerformedWork;
7374 if (current$$1 !== null && didCaptureError) {
7375 // If we're recovering from an error, reconcile without reusing any of
7376 // the existing children. Conceptually, the normal children and the children
7377 // that are shown on error are two different sets, so we shouldn't reuse
7378 // normal children even if their identities match.
7379 forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime);
7380 } else {
7381 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
7382 }
7383
7384 // Memoize state using the values we just used to render.
7385 // TODO: Restructure so we never read values from the instance.
7386 workInProgress.memoizedState = instance.state;
7387
7388 // The context might have changed so we need to recalculate it.
7389 if (hasContext) {
7390 invalidateContextProvider(workInProgress, Component, true);
7391 }
7392
7393 return workInProgress.child;
7394}
7395
7396function pushHostRootContext(workInProgress) {
7397 var root = workInProgress.stateNode;
7398 if (root.pendingContext) {
7399 pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
7400 } else if (root.context) {
7401 // Should always be set
7402 pushTopLevelContextObject(workInProgress, root.context, false);
7403 }
7404 pushHostContainer(workInProgress, root.containerInfo);
7405}
7406
7407function updateHostRoot(current$$1, workInProgress, renderExpirationTime) {
7408 pushHostRootContext(workInProgress);
7409 var updateQueue = workInProgress.updateQueue;
7410 (function () {
7411 if (!(updateQueue !== null)) {
7412 {
7413 throw ReactError('If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue.');
7414 }
7415 }
7416 })();
7417 var nextProps = workInProgress.pendingProps;
7418 var prevState = workInProgress.memoizedState;
7419 var prevChildren = prevState !== null ? prevState.element : null;
7420 processUpdateQueue(workInProgress, updateQueue, nextProps, null, renderExpirationTime);
7421 var nextState = workInProgress.memoizedState;
7422 // Caution: React DevTools currently depends on this property
7423 // being called "element".
7424 var nextChildren = nextState.element;
7425 if (nextChildren === prevChildren) {
7426 // If the state is the same as before, that's a bailout because we had
7427 // no work that expires at this time.
7428 resetHydrationState();
7429 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
7430 }
7431 var root = workInProgress.stateNode;
7432 if ((current$$1 === null || current$$1.child === null) && root.hydrate && enterHydrationState(workInProgress)) {
7433 // If we don't have any current children this might be the first pass.
7434 // We always try to hydrate. If this isn't a hydration pass there won't
7435 // be any children to hydrate which is effectively the same thing as
7436 // not hydrating.
7437
7438 // This is a bit of a hack. We track the host root as a placement to
7439 // know that we're currently in a mounting state. That way isMounted
7440 // works as expected. We must reset this before committing.
7441 // TODO: Delete this when we delete isMounted and findDOMNode.
7442 workInProgress.effectTag |= Placement;
7443
7444 // Ensure that children mount into this root without tracking
7445 // side-effects. This ensures that we don't store Placement effects on
7446 // nodes that will be hydrated.
7447 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
7448 } else {
7449 // Otherwise reset hydration state in case we aborted and resumed another
7450 // root.
7451 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
7452 resetHydrationState();
7453 }
7454 return workInProgress.child;
7455}
7456
7457function updateHostComponent(current$$1, workInProgress, renderExpirationTime) {
7458 pushHostContext(workInProgress);
7459
7460 if (current$$1 === null) {
7461 tryToClaimNextHydratableInstance(workInProgress);
7462 }
7463
7464 var type = workInProgress.type;
7465 var nextProps = workInProgress.pendingProps;
7466 var prevProps = current$$1 !== null ? current$$1.memoizedProps : null;
7467
7468 var nextChildren = nextProps.children;
7469 var isDirectTextChild = shouldSetTextContent(type, nextProps);
7470
7471 if (isDirectTextChild) {
7472 // We special case a direct text child of a host node. This is a common
7473 // case. We won't handle it as a reified child. We will instead handle
7474 // this in the host environment that also have access to this prop. That
7475 // avoids allocating another HostText fiber and traversing it.
7476 nextChildren = null;
7477 } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
7478 // If we're switching from a direct text child to a normal child, or to
7479 // empty, we need to schedule the text content to be reset.
7480 workInProgress.effectTag |= ContentReset;
7481 }
7482
7483 markRef(current$$1, workInProgress);
7484
7485 // Check the host config to see if the children are offscreen/hidden.
7486 if (renderExpirationTime !== Never && workInProgress.mode & ConcurrentMode && shouldDeprioritizeSubtree(type, nextProps)) {
7487 // Schedule this fiber to re-render at offscreen priority. Then bailout.
7488 workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
7489 return null;
7490 }
7491
7492 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
7493 return workInProgress.child;
7494}
7495
7496function updateHostText(current$$1, workInProgress) {
7497 if (current$$1 === null) {
7498 tryToClaimNextHydratableInstance(workInProgress);
7499 }
7500 // Nothing to do here. This is terminal. We'll do the completion step
7501 // immediately after.
7502 return null;
7503}
7504
7505function mountLazyComponent(_current, workInProgress, elementType, updateExpirationTime, renderExpirationTime) {
7506 if (_current !== null) {
7507 // An lazy component only mounts if it suspended inside a non-
7508 // concurrent tree, in an inconsistent state. We want to treat it like
7509 // a new mount, even though an empty version of it already committed.
7510 // Disconnect the alternate pointers.
7511 _current.alternate = null;
7512 workInProgress.alternate = null;
7513 // Since this is conceptually a new fiber, schedule a Placement effect
7514 workInProgress.effectTag |= Placement;
7515 }
7516
7517 var props = workInProgress.pendingProps;
7518 // We can't start a User Timing measurement with correct label yet.
7519 // Cancel and resume right after we know the tag.
7520 cancelWorkTimer(workInProgress);
7521 var Component = readLazyComponentType(elementType);
7522 // Store the unwrapped component in the type.
7523 workInProgress.type = Component;
7524 var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
7525 startWorkTimer(workInProgress);
7526 var resolvedProps = resolveDefaultProps(Component, props);
7527 var child = void 0;
7528 switch (resolvedTag) {
7529 case FunctionComponent:
7530 {
7531 {
7532 validateFunctionComponentInDev(workInProgress, Component);
7533 }
7534 child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
7535 break;
7536 }
7537 case ClassComponent:
7538 {
7539 child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
7540 break;
7541 }
7542 case ForwardRef:
7543 {
7544 child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderExpirationTime);
7545 break;
7546 }
7547 case MemoComponent:
7548 {
7549 {
7550 if (workInProgress.type !== workInProgress.elementType) {
7551 var outerPropTypes = Component.propTypes;
7552 if (outerPropTypes) {
7553 checkPropTypes_1(outerPropTypes, resolvedProps, // Resolved for outer only
7554 'prop', getComponentName(Component), getCurrentFiberStackInDev);
7555 }
7556 }
7557 }
7558 child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
7559 updateExpirationTime, renderExpirationTime);
7560 break;
7561 }
7562 default:
7563 {
7564 var hint = '';
7565 {
7566 if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
7567 hint = ' Did you wrap a component in React.lazy() more than once?';
7568 }
7569 }
7570 // This message intentionally doesn't mention ForwardRef or MemoComponent
7571 // because the fact that it's a separate type of work is an
7572 // implementation detail.
7573 (function () {
7574 {
7575 {
7576 throw ReactError('Element type is invalid. Received a promise that resolves to: ' + Component + '. Lazy element type must resolve to a class or function.' + hint);
7577 }
7578 }
7579 })();
7580 }
7581 }
7582 return child;
7583}
7584
7585function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderExpirationTime) {
7586 if (_current !== null) {
7587 // An incomplete component only mounts if it suspended inside a non-
7588 // concurrent tree, in an inconsistent state. We want to treat it like
7589 // a new mount, even though an empty version of it already committed.
7590 // Disconnect the alternate pointers.
7591 _current.alternate = null;
7592 workInProgress.alternate = null;
7593 // Since this is conceptually a new fiber, schedule a Placement effect
7594 workInProgress.effectTag |= Placement;
7595 }
7596
7597 // Promote the fiber to a class and try rendering again.
7598 workInProgress.tag = ClassComponent;
7599
7600 // The rest of this function is a fork of `updateClassComponent`
7601
7602 // Push context providers early to prevent context stack mismatches.
7603 // During mounting we don't know the child context yet as the instance doesn't exist.
7604 // We will invalidate the child context in finishClassComponent() right after rendering.
7605 var hasContext = void 0;
7606 if (isContextProvider(Component)) {
7607 hasContext = true;
7608 pushContextProvider(workInProgress);
7609 } else {
7610 hasContext = false;
7611 }
7612 prepareToReadContext(workInProgress, renderExpirationTime);
7613
7614 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
7615 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
7616
7617 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
7618}
7619
7620function mountIndeterminateComponent(_current, workInProgress, Component, renderExpirationTime) {
7621 if (_current !== null) {
7622 // An indeterminate component only mounts if it suspended inside a non-
7623 // concurrent tree, in an inconsistent state. We want to treat it like
7624 // a new mount, even though an empty version of it already committed.
7625 // Disconnect the alternate pointers.
7626 _current.alternate = null;
7627 workInProgress.alternate = null;
7628 // Since this is conceptually a new fiber, schedule a Placement effect
7629 workInProgress.effectTag |= Placement;
7630 }
7631
7632 var props = workInProgress.pendingProps;
7633 var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
7634 var context = getMaskedContext(workInProgress, unmaskedContext);
7635
7636 prepareToReadContext(workInProgress, renderExpirationTime);
7637
7638 var value = void 0;
7639
7640 {
7641 if (Component.prototype && typeof Component.prototype.render === 'function') {
7642 var componentName = getComponentName(Component) || 'Unknown';
7643
7644 if (!didWarnAboutBadClass[componentName]) {
7645 warningWithoutStack$1(false, "The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);
7646 didWarnAboutBadClass[componentName] = true;
7647 }
7648 }
7649
7650 if (workInProgress.mode & StrictMode) {
7651 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
7652 }
7653
7654 ReactCurrentOwner$2.current = workInProgress;
7655 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
7656 }
7657 // React DevTools reads this flag.
7658 workInProgress.effectTag |= PerformedWork;
7659
7660 if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
7661 {
7662 var _componentName = getComponentName(Component) || 'Unknown';
7663 if (!didWarnAboutModulePatternComponent[_componentName]) {
7664 warningWithoutStack$1(false, 'The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);
7665 didWarnAboutModulePatternComponent[_componentName] = true;
7666 }
7667 }
7668
7669 // Proceed under the assumption that this is a class instance
7670 workInProgress.tag = ClassComponent;
7671
7672 // Throw out any hooks that were used.
7673 resetHooks();
7674
7675 // Push context providers early to prevent context stack mismatches.
7676 // During mounting we don't know the child context yet as the instance doesn't exist.
7677 // We will invalidate the child context in finishClassComponent() right after rendering.
7678 var hasContext = false;
7679 if (isContextProvider(Component)) {
7680 hasContext = true;
7681 pushContextProvider(workInProgress);
7682 } else {
7683 hasContext = false;
7684 }
7685
7686 workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
7687
7688 var getDerivedStateFromProps = Component.getDerivedStateFromProps;
7689 if (typeof getDerivedStateFromProps === 'function') {
7690 applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);
7691 }
7692
7693 adoptClassInstance(workInProgress, value);
7694 mountClassInstance(workInProgress, Component, props, renderExpirationTime);
7695 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
7696 } else {
7697 // Proceed under the assumption that this is a function component
7698 workInProgress.tag = FunctionComponent;
7699 {
7700 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
7701 // Only double-render components with Hooks
7702 if (workInProgress.memoizedState !== null) {
7703 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
7704 }
7705 }
7706 }
7707 reconcileChildren(null, workInProgress, value, renderExpirationTime);
7708 {
7709 validateFunctionComponentInDev(workInProgress, Component);
7710 }
7711 return workInProgress.child;
7712 }
7713}
7714
7715function validateFunctionComponentInDev(workInProgress, Component) {
7716 if (Component) {
7717 !!Component.childContextTypes ? warningWithoutStack$1(false, '%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component') : void 0;
7718 }
7719 if (workInProgress.ref !== null) {
7720 var info = '';
7721 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
7722 if (ownerName) {
7723 info += '\n\nCheck the render method of `' + ownerName + '`.';
7724 }
7725
7726 var warningKey = ownerName || workInProgress._debugID || '';
7727 var debugSource = workInProgress._debugSource;
7728 if (debugSource) {
7729 warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
7730 }
7731 if (!didWarnAboutFunctionRefs[warningKey]) {
7732 didWarnAboutFunctionRefs[warningKey] = true;
7733 warning$1(false, 'Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info);
7734 }
7735 }
7736
7737 if (typeof Component.getDerivedStateFromProps === 'function') {
7738 var componentName = getComponentName(Component) || 'Unknown';
7739
7740 if (!didWarnAboutGetDerivedStateOnFunctionComponent[componentName]) {
7741 warningWithoutStack$1(false, '%s: Function components do not support getDerivedStateFromProps.', componentName);
7742 didWarnAboutGetDerivedStateOnFunctionComponent[componentName] = true;
7743 }
7744 }
7745
7746 if (typeof Component.contextType === 'object' && Component.contextType !== null) {
7747 var _componentName2 = getComponentName(Component) || 'Unknown';
7748
7749 if (!didWarnAboutContextTypeOnFunctionComponent[_componentName2]) {
7750 warningWithoutStack$1(false, '%s: Function components do not support contextType.', _componentName2);
7751 didWarnAboutContextTypeOnFunctionComponent[_componentName2] = true;
7752 }
7753 }
7754}
7755
7756function updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime) {
7757 var mode = workInProgress.mode;
7758 var nextProps = workInProgress.pendingProps;
7759
7760 // We should attempt to render the primary children unless this boundary
7761 // already suspended during this render (`alreadyCaptured` is true).
7762 var nextState = workInProgress.memoizedState;
7763
7764 var nextDidTimeout = void 0;
7765 if ((workInProgress.effectTag & DidCapture) === NoEffect) {
7766 // This is the first attempt.
7767 nextState = null;
7768 nextDidTimeout = false;
7769 } else {
7770 // Something in this boundary's subtree already suspended. Switch to
7771 // rendering the fallback children.
7772 nextState = {
7773 timedOutAt: nextState !== null ? nextState.timedOutAt : NoWork
7774 };
7775 nextDidTimeout = true;
7776 workInProgress.effectTag &= ~DidCapture;
7777 }
7778
7779 {
7780 if ('maxDuration' in nextProps) {
7781 if (!didWarnAboutMaxDuration) {
7782 didWarnAboutMaxDuration = true;
7783 warning$1(false, 'maxDuration has been removed from React. ' + 'Remove the maxDuration prop.');
7784 }
7785 }
7786 }
7787
7788 // This next part is a bit confusing. If the children timeout, we switch to
7789 // showing the fallback children in place of the "primary" children.
7790 // However, we don't want to delete the primary children because then their
7791 // state will be lost (both the React state and the host state, e.g.
7792 // uncontrolled form inputs). Instead we keep them mounted and hide them.
7793 // Both the fallback children AND the primary children are rendered at the
7794 // same time. Once the primary children are un-suspended, we can delete
7795 // the fallback children — don't need to preserve their state.
7796 //
7797 // The two sets of children are siblings in the host environment, but
7798 // semantically, for purposes of reconciliation, they are two separate sets.
7799 // So we store them using two fragment fibers.
7800 //
7801 // However, we want to avoid allocating extra fibers for every placeholder.
7802 // They're only necessary when the children time out, because that's the
7803 // only time when both sets are mounted.
7804 //
7805 // So, the extra fragment fibers are only used if the children time out.
7806 // Otherwise, we render the primary children directly. This requires some
7807 // custom reconciliation logic to preserve the state of the primary
7808 // children. It's essentially a very basic form of re-parenting.
7809
7810 // `child` points to the child fiber. In the normal case, this is the first
7811 // fiber of the primary children set. In the timed-out case, it's a
7812 // a fragment fiber containing the primary children.
7813 var child = void 0;
7814 // `next` points to the next fiber React should render. In the normal case,
7815 // it's the same as `child`: the first fiber of the primary children set.
7816 // In the timed-out case, it's a fragment fiber containing the *fallback*
7817 // children -- we skip over the primary children entirely.
7818 var next = void 0;
7819 if (current$$1 === null) {
7820 if (enableSuspenseServerRenderer) {
7821 // If we're currently hydrating, try to hydrate this boundary.
7822 // But only if this has a fallback.
7823 if (nextProps.fallback !== undefined) {
7824 tryToClaimNextHydratableInstance(workInProgress);
7825 // This could've changed the tag if this was a dehydrated suspense component.
7826 if (workInProgress.tag === DehydratedSuspenseComponent) {
7827 return updateDehydratedSuspenseComponent(null, workInProgress, renderExpirationTime);
7828 }
7829 }
7830 }
7831
7832 // This is the initial mount. This branch is pretty simple because there's
7833 // no previous state that needs to be preserved.
7834 if (nextDidTimeout) {
7835 // Mount separate fragments for primary and fallback children.
7836 var nextFallbackChildren = nextProps.fallback;
7837 var primaryChildFragment = createFiberFromFragment(null, mode, NoWork, null);
7838
7839 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
7840 // Outside of concurrent mode, we commit the effects from the
7841 var progressedState = workInProgress.memoizedState;
7842 var progressedPrimaryChild = progressedState !== null ? workInProgress.child.child : workInProgress.child;
7843 primaryChildFragment.child = progressedPrimaryChild;
7844 }
7845
7846 var fallbackChildFragment = createFiberFromFragment(nextFallbackChildren, mode, renderExpirationTime, null);
7847 primaryChildFragment.sibling = fallbackChildFragment;
7848 child = primaryChildFragment;
7849 // Skip the primary children, and continue working on the
7850 // fallback children.
7851 next = fallbackChildFragment;
7852 child.return = next.return = workInProgress;
7853 } else {
7854 // Mount the primary children without an intermediate fragment fiber.
7855 var nextPrimaryChildren = nextProps.children;
7856 child = next = mountChildFibers(workInProgress, null, nextPrimaryChildren, renderExpirationTime);
7857 }
7858 } else {
7859 // This is an update. This branch is more complicated because we need to
7860 // ensure the state of the primary children is preserved.
7861 var prevState = current$$1.memoizedState;
7862 var prevDidTimeout = prevState !== null;
7863 if (prevDidTimeout) {
7864 // The current tree already timed out. That means each child set is
7865 var currentPrimaryChildFragment = current$$1.child;
7866 var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
7867 if (nextDidTimeout) {
7868 // Still timed out. Reuse the current primary children by cloning
7869 // its fragment. We're going to skip over these entirely.
7870 var _nextFallbackChildren = nextProps.fallback;
7871 var _primaryChildFragment = createWorkInProgress(currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps, NoWork);
7872
7873 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
7874 // Outside of concurrent mode, we commit the effects from the
7875 var _progressedState = workInProgress.memoizedState;
7876 var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child;
7877 if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) {
7878 _primaryChildFragment.child = _progressedPrimaryChild;
7879 }
7880 }
7881
7882 // Because primaryChildFragment is a new fiber that we're inserting as the
7883 // parent of a new tree, we need to set its treeBaseDuration.
7884 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
7885 // treeBaseDuration is the sum of all the child tree base durations.
7886 var treeBaseDuration = 0;
7887 var hiddenChild = _primaryChildFragment.child;
7888 while (hiddenChild !== null) {
7889 treeBaseDuration += hiddenChild.treeBaseDuration;
7890 hiddenChild = hiddenChild.sibling;
7891 }
7892 _primaryChildFragment.treeBaseDuration = treeBaseDuration;
7893 }
7894
7895 // Clone the fallback child fragment, too. These we'll continue
7896 // working on.
7897 var _fallbackChildFragment = _primaryChildFragment.sibling = createWorkInProgress(currentFallbackChildFragment, _nextFallbackChildren, currentFallbackChildFragment.expirationTime);
7898 child = _primaryChildFragment;
7899 _primaryChildFragment.childExpirationTime = NoWork;
7900 // Skip the primary children, and continue working on the
7901 // fallback children.
7902 next = _fallbackChildFragment;
7903 child.return = next.return = workInProgress;
7904 } else {
7905 // No longer suspended. Switch back to showing the primary children,
7906 // and remove the intermediate fragment fiber.
7907 var _nextPrimaryChildren = nextProps.children;
7908 var currentPrimaryChild = currentPrimaryChildFragment.child;
7909 var primaryChild = reconcileChildFibers(workInProgress, currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime);
7910
7911 // If this render doesn't suspend, we need to delete the fallback
7912 // children. Wait until the complete phase, after we've confirmed the
7913 // fallback is no longer needed.
7914 // TODO: Would it be better to store the fallback fragment on
7915 // the stateNode?
7916
7917 // Continue rendering the children, like we normally do.
7918 child = next = primaryChild;
7919 }
7920 } else {
7921 // The current tree has not already timed out. That means the primary
7922 // children are not wrapped in a fragment fiber.
7923 var _currentPrimaryChild = current$$1.child;
7924 if (nextDidTimeout) {
7925 // Timed out. Wrap the children in a fragment fiber to keep them
7926 // separate from the fallback children.
7927 var _nextFallbackChildren2 = nextProps.fallback;
7928 var _primaryChildFragment2 = createFiberFromFragment(
7929 // It shouldn't matter what the pending props are because we aren't
7930 // going to render this fragment.
7931 null, mode, NoWork, null);
7932 _primaryChildFragment2.child = _currentPrimaryChild;
7933
7934 // Even though we're creating a new fiber, there are no new children,
7935 // because we're reusing an already mounted tree. So we don't need to
7936 // schedule a placement.
7937 // primaryChildFragment.effectTag |= Placement;
7938
7939 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
7940 // Outside of concurrent mode, we commit the effects from the
7941 var _progressedState2 = workInProgress.memoizedState;
7942 var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child;
7943 _primaryChildFragment2.child = _progressedPrimaryChild2;
7944 }
7945
7946 // Because primaryChildFragment is a new fiber that we're inserting as the
7947 // parent of a new tree, we need to set its treeBaseDuration.
7948 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
7949 // treeBaseDuration is the sum of all the child tree base durations.
7950 var _treeBaseDuration = 0;
7951 var _hiddenChild = _primaryChildFragment2.child;
7952 while (_hiddenChild !== null) {
7953 _treeBaseDuration += _hiddenChild.treeBaseDuration;
7954 _hiddenChild = _hiddenChild.sibling;
7955 }
7956 _primaryChildFragment2.treeBaseDuration = _treeBaseDuration;
7957 }
7958
7959 // Create a fragment from the fallback children, too.
7960 var _fallbackChildFragment2 = _primaryChildFragment2.sibling = createFiberFromFragment(_nextFallbackChildren2, mode, renderExpirationTime, null);
7961 _fallbackChildFragment2.effectTag |= Placement;
7962 child = _primaryChildFragment2;
7963 _primaryChildFragment2.childExpirationTime = NoWork;
7964 // Skip the primary children, and continue working on the
7965 // fallback children.
7966 next = _fallbackChildFragment2;
7967 child.return = next.return = workInProgress;
7968 } else {
7969 // Still haven't timed out. Continue rendering the children, like we
7970 // normally do.
7971 var _nextPrimaryChildren2 = nextProps.children;
7972 next = child = reconcileChildFibers(workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime);
7973 }
7974 }
7975 workInProgress.stateNode = current$$1.stateNode;
7976 }
7977
7978 workInProgress.memoizedState = nextState;
7979 workInProgress.child = child;
7980 return next;
7981}
7982
7983function retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime) {
7984 // Detach from the current dehydrated boundary.
7985 current$$1.alternate = null;
7986 workInProgress.alternate = null;
7987
7988 // Insert a deletion in the effect list.
7989 var returnFiber = workInProgress.return;
7990 (function () {
7991 if (!(returnFiber !== null)) {
7992 {
7993 throw ReactError('Suspense boundaries are never on the root. This is probably a bug in React.');
7994 }
7995 }
7996 })();
7997 var last = returnFiber.lastEffect;
7998 if (last !== null) {
7999 last.nextEffect = current$$1;
8000 returnFiber.lastEffect = current$$1;
8001 } else {
8002 returnFiber.firstEffect = returnFiber.lastEffect = current$$1;
8003 }
8004 current$$1.nextEffect = null;
8005 current$$1.effectTag = Deletion;
8006
8007 // Upgrade this work in progress to a real Suspense component.
8008 workInProgress.tag = SuspenseComponent;
8009 workInProgress.stateNode = null;
8010 workInProgress.memoizedState = null;
8011 // This is now an insertion.
8012 workInProgress.effectTag |= Placement;
8013 // Retry as a real Suspense component.
8014 return updateSuspenseComponent(null, workInProgress, renderExpirationTime);
8015}
8016
8017function updateDehydratedSuspenseComponent(current$$1, workInProgress, renderExpirationTime) {
8018 var suspenseInstance = workInProgress.stateNode;
8019 if (current$$1 === null) {
8020 // During the first pass, we'll bail out and not drill into the children.
8021 // Instead, we'll leave the content in place and try to hydrate it later.
8022 if (isSuspenseInstanceFallback(suspenseInstance)) {
8023 // This is a client-only boundary. Since we won't get any content from the server
8024 // for this, we need to schedule that at a higher priority based on when it would
8025 // have timed out. In theory we could render it in this pass but it would have the
8026 // wrong priority associated with it and will prevent hydration of parent path.
8027 // Instead, we'll leave work left on it to render it in a separate commit.
8028
8029 // TODO This time should be the time at which the server rendered response that is
8030 // a parent to this boundary was displayed. However, since we currently don't have
8031 // a protocol to transfer that time, we'll just estimate it by using the current
8032 // time. This will mean that Suspense timeouts are slightly shifted to later than
8033 // they should be.
8034 var serverDisplayTime = requestCurrentTime$$1();
8035 // Schedule a normal pri update to render this content.
8036 workInProgress.expirationTime = computeAsyncExpiration(serverDisplayTime);
8037 } else {
8038 // We'll continue hydrating the rest at offscreen priority since we'll already
8039 // be showing the right content coming from the server, it is no rush.
8040 workInProgress.expirationTime = Never;
8041 }
8042 return null;
8043 }
8044 if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
8045 // Something suspended. Leave the existing children in place.
8046 // TODO: In non-concurrent mode, should we commit the nodes we have hydrated so far?
8047 workInProgress.child = null;
8048 return null;
8049 }
8050 if (isSuspenseInstanceFallback(suspenseInstance)) {
8051 // This boundary is in a permanent fallback state. In this case, we'll never
8052 // get an update and we'll never be able to hydrate the final content. Let's just try the
8053 // client side render instead.
8054 return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
8055 }
8056 // We use childExpirationTime to indicate that a child might depend on context, so if
8057 // any context has changed, we need to treat is as if the input might have changed.
8058 var hasContextChanged$$1 = current$$1.childExpirationTime >= renderExpirationTime;
8059 if (didReceiveUpdate || hasContextChanged$$1) {
8060 // This boundary has changed since the first render. This means that we are now unable to
8061 // hydrate it. We might still be able to hydrate it using an earlier expiration time but
8062 // during this render we can't. Instead, we're going to delete the whole subtree and
8063 // instead inject a new real Suspense boundary to take its place, which may render content
8064 // or fallback. The real Suspense boundary will suspend for a while so we have some time
8065 // to ensure it can produce real content, but all state and pending events will be lost.
8066 return retrySuspenseComponentWithoutHydrating(current$$1, workInProgress, renderExpirationTime);
8067 } else if (isSuspenseInstancePending(suspenseInstance)) {
8068 // This component is still pending more data from the server, so we can't hydrate its
8069 // content. We treat it as if this component suspended itself. It might seem as if
8070 // we could just try to render it client-side instead. However, this will perform a
8071 // lot of unnecessary work and is unlikely to complete since it often will suspend
8072 // on missing data anyway. Additionally, the server might be able to render more
8073 // than we can on the client yet. In that case we'd end up with more fallback states
8074 // on the client than if we just leave it alone. If the server times out or errors
8075 // these should update this boundary to the permanent Fallback state instead.
8076 // Mark it as having captured (i.e. suspended).
8077 workInProgress.effectTag |= DidCapture;
8078 // Leave the children in place. I.e. empty.
8079 workInProgress.child = null;
8080 // Register a callback to retry this boundary once the server has sent the result.
8081 registerSuspenseInstanceRetry(suspenseInstance, retryTimedOutBoundary$$1.bind(null, current$$1));
8082 return null;
8083 } else {
8084 // This is the first attempt.
8085 reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress);
8086 var nextProps = workInProgress.pendingProps;
8087 var nextChildren = nextProps.children;
8088 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
8089 return workInProgress.child;
8090 }
8091}
8092
8093function updatePortalComponent(current$$1, workInProgress, renderExpirationTime) {
8094 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
8095 var nextChildren = workInProgress.pendingProps;
8096 if (current$$1 === null) {
8097 // Portals are special because we don't append the children during mount
8098 // but at commit. Therefore we need to track insertions which the normal
8099 // flow doesn't do during mount. This doesn't happen at the root because
8100 // the root always starts with a "current" with a null child.
8101 // TODO: Consider unifying this with how the root works.
8102 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
8103 } else {
8104 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
8105 }
8106 return workInProgress.child;
8107}
8108
8109function updateContextProvider(current$$1, workInProgress, renderExpirationTime) {
8110 var providerType = workInProgress.type;
8111 var context = providerType._context;
8112
8113 var newProps = workInProgress.pendingProps;
8114 var oldProps = workInProgress.memoizedProps;
8115
8116 var newValue = newProps.value;
8117
8118 {
8119 var providerPropTypes = workInProgress.type.propTypes;
8120
8121 if (providerPropTypes) {
8122 checkPropTypes_1(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackInDev);
8123 }
8124 }
8125
8126 pushProvider(workInProgress, newValue);
8127
8128 if (oldProps !== null) {
8129 var oldValue = oldProps.value;
8130 var changedBits = calculateChangedBits(context, newValue, oldValue);
8131 if (changedBits === 0) {
8132 // No change. Bailout early if children are the same.
8133 if (oldProps.children === newProps.children && !hasContextChanged()) {
8134 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
8135 }
8136 } else {
8137 // The context value changed. Search for matching consumers and schedule
8138 // them to update.
8139 propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);
8140 }
8141 }
8142
8143 var newChildren = newProps.children;
8144 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
8145 return workInProgress.child;
8146}
8147
8148var hasWarnedAboutUsingContextAsConsumer = false;
8149
8150function updateContextConsumer(current$$1, workInProgress, renderExpirationTime) {
8151 var context = workInProgress.type;
8152 // The logic below for Context differs depending on PROD or DEV mode. In
8153 // DEV mode, we create a separate object for Context.Consumer that acts
8154 // like a proxy to Context. This proxy object adds unnecessary code in PROD
8155 // so we use the old behaviour (Context.Consumer references Context) to
8156 // reduce size and overhead. The separate object references context via
8157 // a property called "_context", which also gives us the ability to check
8158 // in DEV mode if this property exists or not and warn if it does not.
8159 {
8160 if (context._context === undefined) {
8161 // This may be because it's a Context (rather than a Consumer).
8162 // Or it may be because it's older React where they're the same thing.
8163 // We only want to warn if we're sure it's a new React.
8164 if (context !== context.Consumer) {
8165 if (!hasWarnedAboutUsingContextAsConsumer) {
8166 hasWarnedAboutUsingContextAsConsumer = true;
8167 warning$1(false, 'Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
8168 }
8169 }
8170 } else {
8171 context = context._context;
8172 }
8173 }
8174 var newProps = workInProgress.pendingProps;
8175 var render = newProps.children;
8176
8177 {
8178 !(typeof render === 'function') ? warningWithoutStack$1(false, 'A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.') : void 0;
8179 }
8180
8181 prepareToReadContext(workInProgress, renderExpirationTime);
8182 var newValue = readContext(context, newProps.unstable_observedBits);
8183 var newChildren = void 0;
8184 {
8185 ReactCurrentOwner$2.current = workInProgress;
8186 setCurrentPhase('render');
8187 newChildren = render(newValue);
8188 setCurrentPhase(null);
8189 }
8190
8191 // React DevTools reads this flag.
8192 workInProgress.effectTag |= PerformedWork;
8193 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
8194 return workInProgress.child;
8195}
8196
8197function updateEventComponent(current$$1, workInProgress, renderExpirationTime) {
8198 var nextProps = workInProgress.pendingProps;
8199 var nextChildren = nextProps.children;
8200
8201 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
8202 pushHostContextForEventComponent(workInProgress);
8203 return workInProgress.child;
8204}
8205
8206function updateEventTarget(current$$1, workInProgress, renderExpirationTime) {
8207 var nextProps = workInProgress.pendingProps;
8208 var nextChildren = nextProps.children;
8209
8210 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
8211 pushHostContextForEventTarget(workInProgress);
8212 return workInProgress.child;
8213}
8214
8215function markWorkInProgressReceivedUpdate() {
8216 didReceiveUpdate = true;
8217}
8218
8219function bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime) {
8220 cancelWorkTimer(workInProgress);
8221
8222 if (current$$1 !== null) {
8223 // Reuse previous context list
8224 workInProgress.contextDependencies = current$$1.contextDependencies;
8225 }
8226
8227 if (enableProfilerTimer) {
8228 // Don't update "base" render times for bailouts.
8229 stopProfilerTimerIfRunning(workInProgress);
8230 }
8231
8232 // Check if the children have any pending work.
8233 var childExpirationTime = workInProgress.childExpirationTime;
8234 if (childExpirationTime < renderExpirationTime) {
8235 // The children don't have any work either. We can skip them.
8236 // TODO: Once we add back resuming, we should check if the children are
8237 // a work-in-progress set. If so, we need to transfer their effects.
8238 return null;
8239 } else {
8240 // This fiber doesn't have work, but its subtree does. Clone the child
8241 // fibers and continue.
8242 cloneChildFibers(current$$1, workInProgress);
8243 return workInProgress.child;
8244 }
8245}
8246
8247function beginWork(current$$1, workInProgress, renderExpirationTime) {
8248 var updateExpirationTime = workInProgress.expirationTime;
8249
8250 if (current$$1 !== null) {
8251 var oldProps = current$$1.memoizedProps;
8252 var newProps = workInProgress.pendingProps;
8253
8254 if (oldProps !== newProps || hasContextChanged()) {
8255 // If props or context changed, mark the fiber as having performed work.
8256 // This may be unset if the props are determined to be equal later (memo).
8257 didReceiveUpdate = true;
8258 } else if (updateExpirationTime < renderExpirationTime) {
8259 didReceiveUpdate = false;
8260 // This fiber does not have any pending work. Bailout without entering
8261 // the begin phase. There's still some bookkeeping we that needs to be done
8262 // in this optimized path, mostly pushing stuff onto the stack.
8263 switch (workInProgress.tag) {
8264 case HostRoot:
8265 pushHostRootContext(workInProgress);
8266 resetHydrationState();
8267 break;
8268 case HostComponent:
8269 pushHostContext(workInProgress);
8270 break;
8271 case ClassComponent:
8272 {
8273 var Component = workInProgress.type;
8274 if (isContextProvider(Component)) {
8275 pushContextProvider(workInProgress);
8276 }
8277 break;
8278 }
8279 case HostPortal:
8280 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
8281 break;
8282 case ContextProvider:
8283 {
8284 var newValue = workInProgress.memoizedProps.value;
8285 pushProvider(workInProgress, newValue);
8286 break;
8287 }
8288 case Profiler:
8289 if (enableProfilerTimer) {
8290 workInProgress.effectTag |= Update;
8291 }
8292 break;
8293 case SuspenseComponent:
8294 {
8295 var state = workInProgress.memoizedState;
8296 var didTimeout = state !== null;
8297 if (didTimeout) {
8298 // If this boundary is currently timed out, we need to decide
8299 // whether to retry the primary children, or to skip over it and
8300 // go straight to the fallback. Check the priority of the primary
8301 var primaryChildFragment = workInProgress.child;
8302 var primaryChildExpirationTime = primaryChildFragment.childExpirationTime;
8303 if (primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime) {
8304 // The primary children have pending work. Use the normal path
8305 // to attempt to render the primary children again.
8306 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
8307 } else {
8308 // The primary children do not have pending work with sufficient
8309 // priority. Bailout.
8310 var child = bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
8311 if (child !== null) {
8312 // The fallback children have pending work. Skip over the
8313 // primary children and work on the fallback.
8314 return child.sibling;
8315 } else {
8316 return null;
8317 }
8318 }
8319 }
8320 break;
8321 }
8322 case DehydratedSuspenseComponent:
8323 {
8324 if (enableSuspenseServerRenderer) {
8325 // We know that this component will suspend again because if it has
8326 // been unsuspended it has committed as a regular Suspense component.
8327 // If it needs to be retried, it should have work scheduled on it.
8328 workInProgress.effectTag |= DidCapture;
8329 }
8330 break;
8331 }
8332 case EventComponent:
8333 if (enableEventAPI) {
8334 pushHostContextForEventComponent(workInProgress);
8335 }
8336 break;
8337 case EventTarget:
8338 {
8339 if (enableEventAPI) {
8340 pushHostContextForEventTarget(workInProgress);
8341 }
8342 break;
8343 }
8344 }
8345 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
8346 }
8347 } else {
8348 didReceiveUpdate = false;
8349 }
8350
8351 // Before entering the begin phase, clear the expiration time.
8352 workInProgress.expirationTime = NoWork;
8353
8354 switch (workInProgress.tag) {
8355 case IndeterminateComponent:
8356 {
8357 var elementType = workInProgress.elementType;
8358 return mountIndeterminateComponent(current$$1, workInProgress, elementType, renderExpirationTime);
8359 }
8360 case LazyComponent:
8361 {
8362 var _elementType = workInProgress.elementType;
8363 return mountLazyComponent(current$$1, workInProgress, _elementType, updateExpirationTime, renderExpirationTime);
8364 }
8365 case FunctionComponent:
8366 {
8367 var _Component = workInProgress.type;
8368 var unresolvedProps = workInProgress.pendingProps;
8369 var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
8370 return updateFunctionComponent(current$$1, workInProgress, _Component, resolvedProps, renderExpirationTime);
8371 }
8372 case ClassComponent:
8373 {
8374 var _Component2 = workInProgress.type;
8375 var _unresolvedProps = workInProgress.pendingProps;
8376 var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);
8377 return updateClassComponent(current$$1, workInProgress, _Component2, _resolvedProps, renderExpirationTime);
8378 }
8379 case HostRoot:
8380 return updateHostRoot(current$$1, workInProgress, renderExpirationTime);
8381 case HostComponent:
8382 return updateHostComponent(current$$1, workInProgress, renderExpirationTime);
8383 case HostText:
8384 return updateHostText(current$$1, workInProgress);
8385 case SuspenseComponent:
8386 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
8387 case HostPortal:
8388 return updatePortalComponent(current$$1, workInProgress, renderExpirationTime);
8389 case ForwardRef:
8390 {
8391 var type = workInProgress.type;
8392 var _unresolvedProps2 = workInProgress.pendingProps;
8393 var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
8394 return updateForwardRef(current$$1, workInProgress, type, _resolvedProps2, renderExpirationTime);
8395 }
8396 case Fragment:
8397 return updateFragment(current$$1, workInProgress, renderExpirationTime);
8398 case Mode:
8399 return updateMode(current$$1, workInProgress, renderExpirationTime);
8400 case Profiler:
8401 return updateProfiler(current$$1, workInProgress, renderExpirationTime);
8402 case ContextProvider:
8403 return updateContextProvider(current$$1, workInProgress, renderExpirationTime);
8404 case ContextConsumer:
8405 return updateContextConsumer(current$$1, workInProgress, renderExpirationTime);
8406 case MemoComponent:
8407 {
8408 var _type2 = workInProgress.type;
8409 var _unresolvedProps3 = workInProgress.pendingProps;
8410 // Resolve outer props first, then resolve inner props.
8411 var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
8412 {
8413 if (workInProgress.type !== workInProgress.elementType) {
8414 var outerPropTypes = _type2.propTypes;
8415 if (outerPropTypes) {
8416 checkPropTypes_1(outerPropTypes, _resolvedProps3, // Resolved for outer only
8417 'prop', getComponentName(_type2), getCurrentFiberStackInDev);
8418 }
8419 }
8420 }
8421 _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
8422 return updateMemoComponent(current$$1, workInProgress, _type2, _resolvedProps3, updateExpirationTime, renderExpirationTime);
8423 }
8424 case SimpleMemoComponent:
8425 {
8426 return updateSimpleMemoComponent(current$$1, workInProgress, workInProgress.type, workInProgress.pendingProps, updateExpirationTime, renderExpirationTime);
8427 }
8428 case IncompleteClassComponent:
8429 {
8430 var _Component3 = workInProgress.type;
8431 var _unresolvedProps4 = workInProgress.pendingProps;
8432 var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);
8433 return mountIncompleteClassComponent(current$$1, workInProgress, _Component3, _resolvedProps4, renderExpirationTime);
8434 }
8435 case DehydratedSuspenseComponent:
8436 {
8437 if (enableSuspenseServerRenderer) {
8438 return updateDehydratedSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
8439 }
8440 break;
8441 }
8442 case EventComponent:
8443 {
8444 if (enableEventAPI) {
8445 return updateEventComponent(current$$1, workInProgress, renderExpirationTime);
8446 }
8447 break;
8448 }
8449 case EventTarget:
8450 {
8451 if (enableEventAPI) {
8452 return updateEventTarget(current$$1, workInProgress, renderExpirationTime);
8453 }
8454 break;
8455 }
8456 }
8457 (function () {
8458 {
8459 {
8460 throw ReactError('Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
8461 }
8462 }
8463 })();
8464}
8465
8466var valueCursor = createCursor(null);
8467
8468var rendererSigil = void 0;
8469{
8470 // Use this to detect multiple renderers using the same context
8471 rendererSigil = {};
8472}
8473
8474var currentlyRenderingFiber = null;
8475var lastContextDependency = null;
8476var lastContextWithAllBitsObserved = null;
8477
8478var isDisallowedContextReadInDEV = false;
8479
8480function resetContextDependences() {
8481 // This is called right before React yields execution, to ensure `readContext`
8482 // cannot be called outside the render phase.
8483 currentlyRenderingFiber = null;
8484 lastContextDependency = null;
8485 lastContextWithAllBitsObserved = null;
8486 {
8487 isDisallowedContextReadInDEV = false;
8488 }
8489}
8490
8491function enterDisallowedContextReadInDEV() {
8492 {
8493 isDisallowedContextReadInDEV = true;
8494 }
8495}
8496
8497function exitDisallowedContextReadInDEV() {
8498 {
8499 isDisallowedContextReadInDEV = false;
8500 }
8501}
8502
8503function pushProvider(providerFiber, nextValue) {
8504 var context = providerFiber.type._context;
8505
8506 if (isPrimaryRenderer) {
8507 push(valueCursor, context._currentValue, providerFiber);
8508
8509 context._currentValue = nextValue;
8510 {
8511 !(context._currentRenderer === undefined || context._currentRenderer === null || context._currentRenderer === rendererSigil) ? warningWithoutStack$1(false, 'Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.') : void 0;
8512 context._currentRenderer = rendererSigil;
8513 }
8514 } else {
8515 push(valueCursor, context._currentValue2, providerFiber);
8516
8517 context._currentValue2 = nextValue;
8518 {
8519 !(context._currentRenderer2 === undefined || context._currentRenderer2 === null || context._currentRenderer2 === rendererSigil) ? warningWithoutStack$1(false, 'Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.') : void 0;
8520 context._currentRenderer2 = rendererSigil;
8521 }
8522 }
8523}
8524
8525function popProvider(providerFiber) {
8526 var currentValue = valueCursor.current;
8527
8528 pop(valueCursor, providerFiber);
8529
8530 var context = providerFiber.type._context;
8531 if (isPrimaryRenderer) {
8532 context._currentValue = currentValue;
8533 } else {
8534 context._currentValue2 = currentValue;
8535 }
8536}
8537
8538function calculateChangedBits(context, newValue, oldValue) {
8539 if (is(oldValue, newValue)) {
8540 // No change
8541 return 0;
8542 } else {
8543 var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : maxSigned31BitInt;
8544
8545 {
8546 !((changedBits & maxSigned31BitInt) === changedBits) ? warning$1(false, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits) : void 0;
8547 }
8548 return changedBits | 0;
8549 }
8550}
8551
8552function scheduleWorkOnParentPath(parent, renderExpirationTime) {
8553 // Update the child expiration time of all the ancestors, including
8554 // the alternates.
8555 var node = parent;
8556 while (node !== null) {
8557 var alternate = node.alternate;
8558 if (node.childExpirationTime < renderExpirationTime) {
8559 node.childExpirationTime = renderExpirationTime;
8560 if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
8561 alternate.childExpirationTime = renderExpirationTime;
8562 }
8563 } else if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
8564 alternate.childExpirationTime = renderExpirationTime;
8565 } else {
8566 // Neither alternate was updated, which means the rest of the
8567 // ancestor path already has sufficient priority.
8568 break;
8569 }
8570 node = node.return;
8571 }
8572}
8573
8574function propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) {
8575 var fiber = workInProgress.child;
8576 if (fiber !== null) {
8577 // Set the return pointer of the child to the work-in-progress fiber.
8578 fiber.return = workInProgress;
8579 }
8580 while (fiber !== null) {
8581 var nextFiber = void 0;
8582
8583 // Visit this fiber.
8584 var list = fiber.contextDependencies;
8585 if (list !== null) {
8586 nextFiber = fiber.child;
8587
8588 var dependency = list.first;
8589 while (dependency !== null) {
8590 // Check if the context matches.
8591 if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {
8592 // Match! Schedule an update on this fiber.
8593
8594 if (fiber.tag === ClassComponent) {
8595 // Schedule a force update on the work-in-progress.
8596 var update = createUpdate(renderExpirationTime);
8597 update.tag = ForceUpdate;
8598 // TODO: Because we don't have a work-in-progress, this will add the
8599 // update to the current fiber, too, which means it will persist even if
8600 // this render is thrown away. Since it's a race condition, not sure it's
8601 // worth fixing.
8602 enqueueUpdate(fiber, update);
8603 }
8604
8605 if (fiber.expirationTime < renderExpirationTime) {
8606 fiber.expirationTime = renderExpirationTime;
8607 }
8608 var alternate = fiber.alternate;
8609 if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
8610 alternate.expirationTime = renderExpirationTime;
8611 }
8612
8613 scheduleWorkOnParentPath(fiber.return, renderExpirationTime);
8614
8615 // Mark the expiration time on the list, too.
8616 if (list.expirationTime < renderExpirationTime) {
8617 list.expirationTime = renderExpirationTime;
8618 }
8619
8620 // Since we already found a match, we can stop traversing the
8621 // dependency list.
8622 break;
8623 }
8624 dependency = dependency.next;
8625 }
8626 } else if (fiber.tag === ContextProvider) {
8627 // Don't scan deeper if this is a matching provider
8628 nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
8629 } else if (enableSuspenseServerRenderer && fiber.tag === DehydratedSuspenseComponent) {
8630 // If a dehydrated suspense component is in this subtree, we don't know
8631 // if it will have any context consumers in it. The best we can do is
8632 // mark it as having updates on its children.
8633 if (fiber.expirationTime < renderExpirationTime) {
8634 fiber.expirationTime = renderExpirationTime;
8635 }
8636 var _alternate = fiber.alternate;
8637 if (_alternate !== null && _alternate.expirationTime < renderExpirationTime) {
8638 _alternate.expirationTime = renderExpirationTime;
8639 }
8640 // This is intentionally passing this fiber as the parent
8641 // because we want to schedule this fiber as having work
8642 // on its children. We'll use the childExpirationTime on
8643 // this fiber to indicate that a context has changed.
8644 scheduleWorkOnParentPath(fiber, renderExpirationTime);
8645 nextFiber = fiber.sibling;
8646 } else {
8647 // Traverse down.
8648 nextFiber = fiber.child;
8649 }
8650
8651 if (nextFiber !== null) {
8652 // Set the return pointer of the child to the work-in-progress fiber.
8653 nextFiber.return = fiber;
8654 } else {
8655 // No child. Traverse to next sibling.
8656 nextFiber = fiber;
8657 while (nextFiber !== null) {
8658 if (nextFiber === workInProgress) {
8659 // We're back to the root of this subtree. Exit.
8660 nextFiber = null;
8661 break;
8662 }
8663 var sibling = nextFiber.sibling;
8664 if (sibling !== null) {
8665 // Set the return pointer of the sibling to the work-in-progress fiber.
8666 sibling.return = nextFiber.return;
8667 nextFiber = sibling;
8668 break;
8669 }
8670 // No more siblings. Traverse up.
8671 nextFiber = nextFiber.return;
8672 }
8673 }
8674 fiber = nextFiber;
8675 }
8676}
8677
8678function prepareToReadContext(workInProgress, renderExpirationTime) {
8679 currentlyRenderingFiber = workInProgress;
8680 lastContextDependency = null;
8681 lastContextWithAllBitsObserved = null;
8682
8683 var currentDependencies = workInProgress.contextDependencies;
8684 if (currentDependencies !== null && currentDependencies.expirationTime >= renderExpirationTime) {
8685 // Context list has a pending update. Mark that this fiber performed work.
8686 markWorkInProgressReceivedUpdate();
8687 }
8688
8689 // Reset the work-in-progress list
8690 workInProgress.contextDependencies = null;
8691}
8692
8693function readContext(context, observedBits) {
8694 {
8695 // This warning would fire if you read context inside a Hook like useMemo.
8696 // Unlike the class check below, it's not enforced in production for perf.
8697 !!isDisallowedContextReadInDEV ? warning$1(false, 'Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().') : void 0;
8698 }
8699
8700 if (lastContextWithAllBitsObserved === context) {
8701 // Nothing to do. We already observe everything in this context.
8702 } else if (observedBits === false || observedBits === 0) {
8703 // Do not observe any updates.
8704 } else {
8705 var resolvedObservedBits = void 0; // Avoid deopting on observable arguments or heterogeneous types.
8706 if (typeof observedBits !== 'number' || observedBits === maxSigned31BitInt) {
8707 // Observe all updates.
8708 lastContextWithAllBitsObserved = context;
8709 resolvedObservedBits = maxSigned31BitInt;
8710 } else {
8711 resolvedObservedBits = observedBits;
8712 }
8713
8714 var contextItem = {
8715 context: context,
8716 observedBits: resolvedObservedBits,
8717 next: null
8718 };
8719
8720 if (lastContextDependency === null) {
8721 (function () {
8722 if (!(currentlyRenderingFiber !== null)) {
8723 {
8724 throw ReactError('Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo().');
8725 }
8726 }
8727 })();
8728
8729 // This is the first dependency for this component. Create a new list.
8730 lastContextDependency = contextItem;
8731 currentlyRenderingFiber.contextDependencies = {
8732 first: contextItem,
8733 expirationTime: NoWork
8734 };
8735 } else {
8736 // Append a new context item.
8737 lastContextDependency = lastContextDependency.next = contextItem;
8738 }
8739 }
8740 return isPrimaryRenderer ? context._currentValue : context._currentValue2;
8741}
8742
8743// UpdateQueue is a linked list of prioritized updates.
8744//
8745// Like fibers, update queues come in pairs: a current queue, which represents
8746// the visible state of the screen, and a work-in-progress queue, which can be
8747// mutated and processed asynchronously before it is committed — a form of
8748// double buffering. If a work-in-progress render is discarded before finishing,
8749// we create a new work-in-progress by cloning the current queue.
8750//
8751// Both queues share a persistent, singly-linked list structure. To schedule an
8752// update, we append it to the end of both queues. Each queue maintains a
8753// pointer to first update in the persistent list that hasn't been processed.
8754// The work-in-progress pointer always has a position equal to or greater than
8755// the current queue, since we always work on that one. The current queue's
8756// pointer is only updated during the commit phase, when we swap in the
8757// work-in-progress.
8758//
8759// For example:
8760//
8761// Current pointer: A - B - C - D - E - F
8762// Work-in-progress pointer: D - E - F
8763// ^
8764// The work-in-progress queue has
8765// processed more updates than current.
8766//
8767// The reason we append to both queues is because otherwise we might drop
8768// updates without ever processing them. For example, if we only add updates to
8769// the work-in-progress queue, some updates could be lost whenever a work-in
8770// -progress render restarts by cloning from current. Similarly, if we only add
8771// updates to the current queue, the updates will be lost whenever an already
8772// in-progress queue commits and swaps with the current queue. However, by
8773// adding to both queues, we guarantee that the update will be part of the next
8774// work-in-progress. (And because the work-in-progress queue becomes the
8775// current queue once it commits, there's no danger of applying the same
8776// update twice.)
8777//
8778// Prioritization
8779// --------------
8780//
8781// Updates are not sorted by priority, but by insertion; new updates are always
8782// appended to the end of the list.
8783//
8784// The priority is still important, though. When processing the update queue
8785// during the render phase, only the updates with sufficient priority are
8786// included in the result. If we skip an update because it has insufficient
8787// priority, it remains in the queue to be processed later, during a lower
8788// priority render. Crucially, all updates subsequent to a skipped update also
8789// remain in the queue *regardless of their priority*. That means high priority
8790// updates are sometimes processed twice, at two separate priorities. We also
8791// keep track of a base state, that represents the state before the first
8792// update in the queue is applied.
8793//
8794// For example:
8795//
8796// Given a base state of '', and the following queue of updates
8797//
8798// A1 - B2 - C1 - D2
8799//
8800// where the number indicates the priority, and the update is applied to the
8801// previous state by appending a letter, React will process these updates as
8802// two separate renders, one per distinct priority level:
8803//
8804// First render, at priority 1:
8805// Base state: ''
8806// Updates: [A1, C1]
8807// Result state: 'AC'
8808//
8809// Second render, at priority 2:
8810// Base state: 'A' <- The base state does not include C1,
8811// because B2 was skipped.
8812// Updates: [B2, C1, D2] <- C1 was rebased on top of B2
8813// Result state: 'ABCD'
8814//
8815// Because we process updates in insertion order, and rebase high priority
8816// updates when preceding updates are skipped, the final result is deterministic
8817// regardless of priority. Intermediate state may vary according to system
8818// resources, but the final state is always the same.
8819
8820var UpdateState = 0;
8821var ReplaceState = 1;
8822var ForceUpdate = 2;
8823var CaptureUpdate = 3;
8824
8825// Global state that is reset at the beginning of calling `processUpdateQueue`.
8826// It should only be read right after calling `processUpdateQueue`, via
8827// `checkHasForceUpdateAfterProcessing`.
8828var hasForceUpdate = false;
8829
8830var didWarnUpdateInsideUpdate = void 0;
8831var currentlyProcessingQueue = void 0;
8832var resetCurrentlyProcessingQueue = void 0;
8833{
8834 didWarnUpdateInsideUpdate = false;
8835 currentlyProcessingQueue = null;
8836 resetCurrentlyProcessingQueue = function () {
8837 currentlyProcessingQueue = null;
8838 };
8839}
8840
8841function createUpdateQueue(baseState) {
8842 var queue = {
8843 baseState: baseState,
8844 firstUpdate: null,
8845 lastUpdate: null,
8846 firstCapturedUpdate: null,
8847 lastCapturedUpdate: null,
8848 firstEffect: null,
8849 lastEffect: null,
8850 firstCapturedEffect: null,
8851 lastCapturedEffect: null
8852 };
8853 return queue;
8854}
8855
8856function cloneUpdateQueue(currentQueue) {
8857 var queue = {
8858 baseState: currentQueue.baseState,
8859 firstUpdate: currentQueue.firstUpdate,
8860 lastUpdate: currentQueue.lastUpdate,
8861
8862 // TODO: With resuming, if we bail out and resuse the child tree, we should
8863 // keep these effects.
8864 firstCapturedUpdate: null,
8865 lastCapturedUpdate: null,
8866
8867 firstEffect: null,
8868 lastEffect: null,
8869
8870 firstCapturedEffect: null,
8871 lastCapturedEffect: null
8872 };
8873 return queue;
8874}
8875
8876function createUpdate(expirationTime) {
8877 return {
8878 expirationTime: expirationTime,
8879
8880 tag: UpdateState,
8881 payload: null,
8882 callback: null,
8883
8884 next: null,
8885 nextEffect: null
8886 };
8887}
8888
8889function appendUpdateToQueue(queue, update) {
8890 // Append the update to the end of the list.
8891 if (queue.lastUpdate === null) {
8892 // Queue is empty
8893 queue.firstUpdate = queue.lastUpdate = update;
8894 } else {
8895 queue.lastUpdate.next = update;
8896 queue.lastUpdate = update;
8897 }
8898}
8899
8900function enqueueUpdate(fiber, update) {
8901 // Update queues are created lazily.
8902 var alternate = fiber.alternate;
8903 var queue1 = void 0;
8904 var queue2 = void 0;
8905 if (alternate === null) {
8906 // There's only one fiber.
8907 queue1 = fiber.updateQueue;
8908 queue2 = null;
8909 if (queue1 === null) {
8910 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
8911 }
8912 } else {
8913 // There are two owners.
8914 queue1 = fiber.updateQueue;
8915 queue2 = alternate.updateQueue;
8916 if (queue1 === null) {
8917 if (queue2 === null) {
8918 // Neither fiber has an update queue. Create new ones.
8919 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
8920 queue2 = alternate.updateQueue = createUpdateQueue(alternate.memoizedState);
8921 } else {
8922 // Only one fiber has an update queue. Clone to create a new one.
8923 queue1 = fiber.updateQueue = cloneUpdateQueue(queue2);
8924 }
8925 } else {
8926 if (queue2 === null) {
8927 // Only one fiber has an update queue. Clone to create a new one.
8928 queue2 = alternate.updateQueue = cloneUpdateQueue(queue1);
8929 } else {
8930 // Both owners have an update queue.
8931 }
8932 }
8933 }
8934 if (queue2 === null || queue1 === queue2) {
8935 // There's only a single queue.
8936 appendUpdateToQueue(queue1, update);
8937 } else {
8938 // There are two queues. We need to append the update to both queues,
8939 // while accounting for the persistent structure of the list — we don't
8940 // want the same update to be added multiple times.
8941 if (queue1.lastUpdate === null || queue2.lastUpdate === null) {
8942 // One of the queues is not empty. We must add the update to both queues.
8943 appendUpdateToQueue(queue1, update);
8944 appendUpdateToQueue(queue2, update);
8945 } else {
8946 // Both queues are non-empty. The last update is the same in both lists,
8947 // because of structural sharing. So, only append to one of the lists.
8948 appendUpdateToQueue(queue1, update);
8949 // But we still need to update the `lastUpdate` pointer of queue2.
8950 queue2.lastUpdate = update;
8951 }
8952 }
8953
8954 {
8955 if (fiber.tag === ClassComponent && (currentlyProcessingQueue === queue1 || queue2 !== null && currentlyProcessingQueue === queue2) && !didWarnUpdateInsideUpdate) {
8956 warningWithoutStack$1(false, 'An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.');
8957 didWarnUpdateInsideUpdate = true;
8958 }
8959 }
8960}
8961
8962function enqueueCapturedUpdate(workInProgress, update) {
8963 // Captured updates go into a separate list, and only on the work-in-
8964 // progress queue.
8965 var workInProgressQueue = workInProgress.updateQueue;
8966 if (workInProgressQueue === null) {
8967 workInProgressQueue = workInProgress.updateQueue = createUpdateQueue(workInProgress.memoizedState);
8968 } else {
8969 // TODO: I put this here rather than createWorkInProgress so that we don't
8970 // clone the queue unnecessarily. There's probably a better way to
8971 // structure this.
8972 workInProgressQueue = ensureWorkInProgressQueueIsAClone(workInProgress, workInProgressQueue);
8973 }
8974
8975 // Append the update to the end of the list.
8976 if (workInProgressQueue.lastCapturedUpdate === null) {
8977 // This is the first render phase update
8978 workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update;
8979 } else {
8980 workInProgressQueue.lastCapturedUpdate.next = update;
8981 workInProgressQueue.lastCapturedUpdate = update;
8982 }
8983}
8984
8985function ensureWorkInProgressQueueIsAClone(workInProgress, queue) {
8986 var current = workInProgress.alternate;
8987 if (current !== null) {
8988 // If the work-in-progress queue is equal to the current queue,
8989 // we need to clone it first.
8990 if (queue === current.updateQueue) {
8991 queue = workInProgress.updateQueue = cloneUpdateQueue(queue);
8992 }
8993 }
8994 return queue;
8995}
8996
8997function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
8998 switch (update.tag) {
8999 case ReplaceState:
9000 {
9001 var _payload = update.payload;
9002 if (typeof _payload === 'function') {
9003 // Updater function
9004 {
9005 enterDisallowedContextReadInDEV();
9006 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
9007 _payload.call(instance, prevState, nextProps);
9008 }
9009 }
9010 var nextState = _payload.call(instance, prevState, nextProps);
9011 {
9012 exitDisallowedContextReadInDEV();
9013 }
9014 return nextState;
9015 }
9016 // State object
9017 return _payload;
9018 }
9019 case CaptureUpdate:
9020 {
9021 workInProgress.effectTag = workInProgress.effectTag & ~ShouldCapture | DidCapture;
9022 }
9023 // Intentional fallthrough
9024 case UpdateState:
9025 {
9026 var _payload2 = update.payload;
9027 var partialState = void 0;
9028 if (typeof _payload2 === 'function') {
9029 // Updater function
9030 {
9031 enterDisallowedContextReadInDEV();
9032 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
9033 _payload2.call(instance, prevState, nextProps);
9034 }
9035 }
9036 partialState = _payload2.call(instance, prevState, nextProps);
9037 {
9038 exitDisallowedContextReadInDEV();
9039 }
9040 } else {
9041 // Partial state object
9042 partialState = _payload2;
9043 }
9044 if (partialState === null || partialState === undefined) {
9045 // Null and undefined are treated as no-ops.
9046 return prevState;
9047 }
9048 // Merge the partial state and the previous state.
9049 return _assign({}, prevState, partialState);
9050 }
9051 case ForceUpdate:
9052 {
9053 hasForceUpdate = true;
9054 return prevState;
9055 }
9056 }
9057 return prevState;
9058}
9059
9060function processUpdateQueue(workInProgress, queue, props, instance, renderExpirationTime) {
9061 hasForceUpdate = false;
9062
9063 queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue);
9064
9065 {
9066 currentlyProcessingQueue = queue;
9067 }
9068
9069 // These values may change as we process the queue.
9070 var newBaseState = queue.baseState;
9071 var newFirstUpdate = null;
9072 var newExpirationTime = NoWork;
9073
9074 // Iterate through the list of updates to compute the result.
9075 var update = queue.firstUpdate;
9076 var resultState = newBaseState;
9077 while (update !== null) {
9078 var updateExpirationTime = update.expirationTime;
9079 if (updateExpirationTime < renderExpirationTime) {
9080 // This update does not have sufficient priority. Skip it.
9081 if (newFirstUpdate === null) {
9082 // This is the first skipped update. It will be the first update in
9083 // the new list.
9084 newFirstUpdate = update;
9085 // Since this is the first update that was skipped, the current result
9086 // is the new base state.
9087 newBaseState = resultState;
9088 }
9089 // Since this update will remain in the list, update the remaining
9090 // expiration time.
9091 if (newExpirationTime < updateExpirationTime) {
9092 newExpirationTime = updateExpirationTime;
9093 }
9094 } else {
9095 // This update does have sufficient priority. Process it and compute
9096 // a new result.
9097 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
9098 var _callback = update.callback;
9099 if (_callback !== null) {
9100 workInProgress.effectTag |= Callback;
9101 // Set this to null, in case it was mutated during an aborted render.
9102 update.nextEffect = null;
9103 if (queue.lastEffect === null) {
9104 queue.firstEffect = queue.lastEffect = update;
9105 } else {
9106 queue.lastEffect.nextEffect = update;
9107 queue.lastEffect = update;
9108 }
9109 }
9110 }
9111 // Continue to the next update.
9112 update = update.next;
9113 }
9114
9115 // Separately, iterate though the list of captured updates.
9116 var newFirstCapturedUpdate = null;
9117 update = queue.firstCapturedUpdate;
9118 while (update !== null) {
9119 var _updateExpirationTime = update.expirationTime;
9120 if (_updateExpirationTime < renderExpirationTime) {
9121 // This update does not have sufficient priority. Skip it.
9122 if (newFirstCapturedUpdate === null) {
9123 // This is the first skipped captured update. It will be the first
9124 // update in the new list.
9125 newFirstCapturedUpdate = update;
9126 // If this is the first update that was skipped, the current result is
9127 // the new base state.
9128 if (newFirstUpdate === null) {
9129 newBaseState = resultState;
9130 }
9131 }
9132 // Since this update will remain in the list, update the remaining
9133 // expiration time.
9134 if (newExpirationTime < _updateExpirationTime) {
9135 newExpirationTime = _updateExpirationTime;
9136 }
9137 } else {
9138 // This update does have sufficient priority. Process it and compute
9139 // a new result.
9140 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
9141 var _callback2 = update.callback;
9142 if (_callback2 !== null) {
9143 workInProgress.effectTag |= Callback;
9144 // Set this to null, in case it was mutated during an aborted render.
9145 update.nextEffect = null;
9146 if (queue.lastCapturedEffect === null) {
9147 queue.firstCapturedEffect = queue.lastCapturedEffect = update;
9148 } else {
9149 queue.lastCapturedEffect.nextEffect = update;
9150 queue.lastCapturedEffect = update;
9151 }
9152 }
9153 }
9154 update = update.next;
9155 }
9156
9157 if (newFirstUpdate === null) {
9158 queue.lastUpdate = null;
9159 }
9160 if (newFirstCapturedUpdate === null) {
9161 queue.lastCapturedUpdate = null;
9162 } else {
9163 workInProgress.effectTag |= Callback;
9164 }
9165 if (newFirstUpdate === null && newFirstCapturedUpdate === null) {
9166 // We processed every update, without skipping. That means the new base
9167 // state is the same as the result state.
9168 newBaseState = resultState;
9169 }
9170
9171 queue.baseState = newBaseState;
9172 queue.firstUpdate = newFirstUpdate;
9173 queue.firstCapturedUpdate = newFirstCapturedUpdate;
9174
9175 // Set the remaining expiration time to be whatever is remaining in the queue.
9176 // This should be fine because the only two other things that contribute to
9177 // expiration time are props and context. We're already in the middle of the
9178 // begin phase by the time we start processing the queue, so we've already
9179 // dealt with the props. Context in components that specify
9180 // shouldComponentUpdate is tricky; but we'll have to account for
9181 // that regardless.
9182 workInProgress.expirationTime = newExpirationTime;
9183 workInProgress.memoizedState = resultState;
9184
9185 {
9186 currentlyProcessingQueue = null;
9187 }
9188}
9189
9190function callCallback(callback, context) {
9191 (function () {
9192 if (!(typeof callback === 'function')) {
9193 {
9194 throw ReactError('Invalid argument passed as callback. Expected a function. Instead received: ' + callback);
9195 }
9196 }
9197 })();
9198 callback.call(context);
9199}
9200
9201function resetHasForceUpdateBeforeProcessing() {
9202 hasForceUpdate = false;
9203}
9204
9205function checkHasForceUpdateAfterProcessing() {
9206 return hasForceUpdate;
9207}
9208
9209function commitUpdateQueue(finishedWork, finishedQueue, instance, renderExpirationTime) {
9210 // If the finished render included captured updates, and there are still
9211 // lower priority updates left over, we need to keep the captured updates
9212 // in the queue so that they are rebased and not dropped once we process the
9213 // queue again at the lower priority.
9214 if (finishedQueue.firstCapturedUpdate !== null) {
9215 // Join the captured update list to the end of the normal list.
9216 if (finishedQueue.lastUpdate !== null) {
9217 finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate;
9218 finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate;
9219 }
9220 // Clear the list of captured updates.
9221 finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null;
9222 }
9223
9224 // Commit the effects
9225 commitUpdateEffects(finishedQueue.firstEffect, instance);
9226 finishedQueue.firstEffect = finishedQueue.lastEffect = null;
9227
9228 commitUpdateEffects(finishedQueue.firstCapturedEffect, instance);
9229 finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null;
9230}
9231
9232function commitUpdateEffects(effect, instance) {
9233 while (effect !== null) {
9234 var _callback3 = effect.callback;
9235 if (_callback3 !== null) {
9236 effect.callback = null;
9237 callCallback(_callback3, instance);
9238 }
9239 effect = effect.nextEffect;
9240 }
9241}
9242
9243function createCapturedValue(value, source) {
9244 // If the value is an error, call this function immediately after it is thrown
9245 // so the stack is accurate.
9246 return {
9247 value: value,
9248 source: source,
9249 stack: getStackByFiberInDevAndProd(source)
9250 };
9251}
9252
9253function markUpdate(workInProgress) {
9254 // Tag the fiber with an update effect. This turns a Placement into
9255 // a PlacementAndUpdate.
9256 workInProgress.effectTag |= Update;
9257}
9258
9259function markRef$1(workInProgress) {
9260 workInProgress.effectTag |= Ref;
9261}
9262
9263var appendAllChildren = void 0;
9264var updateHostContainer = void 0;
9265var updateHostComponent$1 = void 0;
9266var updateHostText$1 = void 0;
9267if (supportsMutation) {
9268 // Mutation mode
9269
9270 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
9271 // We only have the top Fiber that was created but we need recurse down its
9272 // children to find all the terminal nodes.
9273 var node = workInProgress.child;
9274 while (node !== null) {
9275 if (node.tag === HostComponent || node.tag === HostText) {
9276 appendInitialChild(parent, node.stateNode);
9277 } else if (node.tag === HostPortal) {
9278 // If we have a portal child, then we don't want to traverse
9279 // down its children. Instead, we'll get insertions from each child in
9280 // the portal directly.
9281 } else if (node.child !== null) {
9282 node.child.return = node;
9283 node = node.child;
9284 continue;
9285 }
9286 if (node === workInProgress) {
9287 return;
9288 }
9289 while (node.sibling === null) {
9290 if (node.return === null || node.return === workInProgress) {
9291 return;
9292 }
9293 node = node.return;
9294 }
9295 node.sibling.return = node.return;
9296 node = node.sibling;
9297 }
9298 };
9299
9300 updateHostContainer = function (workInProgress) {
9301 // Noop
9302 };
9303 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
9304 // If we have an alternate, that means this is an update and we need to
9305 // schedule a side-effect to do the updates.
9306 var oldProps = current.memoizedProps;
9307 if (oldProps === newProps) {
9308 // In mutation mode, this is sufficient for a bailout because
9309 // we won't touch this node even if children changed.
9310 return;
9311 }
9312
9313 // If we get updated because one of our children updated, we don't
9314 // have newProps so we'll have to reuse them.
9315 // TODO: Split the update API as separate for the props vs. children.
9316 // Even better would be if children weren't special cased at all tho.
9317 var instance = workInProgress.stateNode;
9318 var currentHostContext = getHostContext();
9319 // TODO: Experiencing an error where oldProps is null. Suggests a host
9320 // component is hitting the resume path. Figure out why. Possibly
9321 // related to `hidden`.
9322 var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
9323 // TODO: Type this specific to this type of component.
9324 workInProgress.updateQueue = updatePayload;
9325 // If the update payload indicates that there is a change or if there
9326 // is a new ref we mark this as an update. All the work is done in commitWork.
9327 if (updatePayload) {
9328 markUpdate(workInProgress);
9329 }
9330 };
9331 updateHostText$1 = function (current, workInProgress, oldText, newText) {
9332 // If the text differs, mark it as an update. All the work in done in commitWork.
9333 if (oldText !== newText) {
9334 markUpdate(workInProgress);
9335 }
9336 };
9337} else if (supportsPersistence) {
9338 // Persistent host tree mode
9339
9340 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
9341 // We only have the top Fiber that was created but we need recurse down its
9342 // children to find all the terminal nodes.
9343 var node = workInProgress.child;
9344 while (node !== null) {
9345 // eslint-disable-next-line no-labels
9346 branches: if (node.tag === HostComponent) {
9347 var instance = node.stateNode;
9348 if (needsVisibilityToggle && isHidden) {
9349 // This child is inside a timed out tree. Hide it.
9350 var props = node.memoizedProps;
9351 var type = node.type;
9352 instance = cloneHiddenInstance(instance, type, props, node);
9353 }
9354 appendInitialChild(parent, instance);
9355 } else if (node.tag === HostText) {
9356 var _instance = node.stateNode;
9357 if (needsVisibilityToggle && isHidden) {
9358 // This child is inside a timed out tree. Hide it.
9359 var text = node.memoizedProps;
9360 _instance = cloneHiddenTextInstance(_instance, text, node);
9361 }
9362 appendInitialChild(parent, _instance);
9363 } else if (node.tag === HostPortal) {
9364 // If we have a portal child, then we don't want to traverse
9365 // down its children. Instead, we'll get insertions from each child in
9366 // the portal directly.
9367 } else if (node.tag === SuspenseComponent) {
9368 if ((node.effectTag & Update) !== NoEffect) {
9369 // Need to toggle the visibility of the primary children.
9370 var newIsHidden = node.memoizedState !== null;
9371 if (newIsHidden) {
9372 var primaryChildParent = node.child;
9373 if (primaryChildParent !== null) {
9374 if (primaryChildParent.child !== null) {
9375 primaryChildParent.child.return = primaryChildParent;
9376 appendAllChildren(parent, primaryChildParent, true, newIsHidden);
9377 }
9378 var fallbackChildParent = primaryChildParent.sibling;
9379 if (fallbackChildParent !== null) {
9380 fallbackChildParent.return = node;
9381 node = fallbackChildParent;
9382 continue;
9383 }
9384 }
9385 }
9386 }
9387 if (node.child !== null) {
9388 // Continue traversing like normal
9389 node.child.return = node;
9390 node = node.child;
9391 continue;
9392 }
9393 } else if (node.child !== null) {
9394 node.child.return = node;
9395 node = node.child;
9396 continue;
9397 }
9398 // $FlowFixMe This is correct but Flow is confused by the labeled break.
9399 node = node;
9400 if (node === workInProgress) {
9401 return;
9402 }
9403 while (node.sibling === null) {
9404 if (node.return === null || node.return === workInProgress) {
9405 return;
9406 }
9407 node = node.return;
9408 }
9409 node.sibling.return = node.return;
9410 node = node.sibling;
9411 }
9412 };
9413
9414 // An unfortunate fork of appendAllChildren because we have two different parent types.
9415 var appendAllChildrenToContainer = function (containerChildSet, workInProgress, needsVisibilityToggle, isHidden) {
9416 // We only have the top Fiber that was created but we need recurse down its
9417 // children to find all the terminal nodes.
9418 var node = workInProgress.child;
9419 while (node !== null) {
9420 // eslint-disable-next-line no-labels
9421 branches: if (node.tag === HostComponent) {
9422 var instance = node.stateNode;
9423 if (needsVisibilityToggle && isHidden) {
9424 // This child is inside a timed out tree. Hide it.
9425 var props = node.memoizedProps;
9426 var type = node.type;
9427 instance = cloneHiddenInstance(instance, type, props, node);
9428 }
9429 appendChildToContainerChildSet(containerChildSet, instance);
9430 } else if (node.tag === HostText) {
9431 var _instance2 = node.stateNode;
9432 if (needsVisibilityToggle && isHidden) {
9433 // This child is inside a timed out tree. Hide it.
9434 var text = node.memoizedProps;
9435 _instance2 = cloneHiddenTextInstance(_instance2, text, node);
9436 }
9437 appendChildToContainerChildSet(containerChildSet, _instance2);
9438 } else if (node.tag === HostPortal) {
9439 // If we have a portal child, then we don't want to traverse
9440 // down its children. Instead, we'll get insertions from each child in
9441 // the portal directly.
9442 } else if (node.tag === SuspenseComponent) {
9443 if ((node.effectTag & Update) !== NoEffect) {
9444 // Need to toggle the visibility of the primary children.
9445 var newIsHidden = node.memoizedState !== null;
9446 if (newIsHidden) {
9447 var primaryChildParent = node.child;
9448 if (primaryChildParent !== null) {
9449 if (primaryChildParent.child !== null) {
9450 primaryChildParent.child.return = primaryChildParent;
9451 appendAllChildrenToContainer(containerChildSet, primaryChildParent, true, newIsHidden);
9452 }
9453 var fallbackChildParent = primaryChildParent.sibling;
9454 if (fallbackChildParent !== null) {
9455 fallbackChildParent.return = node;
9456 node = fallbackChildParent;
9457 continue;
9458 }
9459 }
9460 }
9461 }
9462 if (node.child !== null) {
9463 // Continue traversing like normal
9464 node.child.return = node;
9465 node = node.child;
9466 continue;
9467 }
9468 } else if (node.child !== null) {
9469 node.child.return = node;
9470 node = node.child;
9471 continue;
9472 }
9473 // $FlowFixMe This is correct but Flow is confused by the labeled break.
9474 node = node;
9475 if (node === workInProgress) {
9476 return;
9477 }
9478 while (node.sibling === null) {
9479 if (node.return === null || node.return === workInProgress) {
9480 return;
9481 }
9482 node = node.return;
9483 }
9484 node.sibling.return = node.return;
9485 node = node.sibling;
9486 }
9487 };
9488 updateHostContainer = function (workInProgress) {
9489 var portalOrRoot = workInProgress.stateNode;
9490 var childrenUnchanged = workInProgress.firstEffect === null;
9491 if (childrenUnchanged) {
9492 // No changes, just reuse the existing instance.
9493 } else {
9494 var container = portalOrRoot.containerInfo;
9495 var newChildSet = createContainerChildSet(container);
9496 // If children might have changed, we have to add them all to the set.
9497 appendAllChildrenToContainer(newChildSet, workInProgress, false, false);
9498 portalOrRoot.pendingChildren = newChildSet;
9499 // Schedule an update on the container to swap out the container.
9500 markUpdate(workInProgress);
9501 finalizeContainerChildren(container, newChildSet);
9502 }
9503 };
9504 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
9505 var currentInstance = current.stateNode;
9506 var oldProps = current.memoizedProps;
9507 // If there are no effects associated with this node, then none of our children had any updates.
9508 // This guarantees that we can reuse all of them.
9509 var childrenUnchanged = workInProgress.firstEffect === null;
9510 if (childrenUnchanged && oldProps === newProps) {
9511 // No changes, just reuse the existing instance.
9512 // Note that this might release a previous clone.
9513 workInProgress.stateNode = currentInstance;
9514 return;
9515 }
9516 var recyclableInstance = workInProgress.stateNode;
9517 var currentHostContext = getHostContext();
9518 var updatePayload = null;
9519 if (oldProps !== newProps) {
9520 updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
9521 }
9522 if (childrenUnchanged && updatePayload === null) {
9523 // No changes, just reuse the existing instance.
9524 // Note that this might release a previous clone.
9525 workInProgress.stateNode = currentInstance;
9526 return;
9527 }
9528 var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance);
9529 if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) {
9530 markUpdate(workInProgress);
9531 }
9532 workInProgress.stateNode = newInstance;
9533 if (childrenUnchanged) {
9534 // If there are no other effects in this tree, we need to flag this node as having one.
9535 // Even though we're not going to use it for anything.
9536 // Otherwise parents won't know that there are new children to propagate upwards.
9537 markUpdate(workInProgress);
9538 } else {
9539 // If children might have changed, we have to add them all to the set.
9540 appendAllChildren(newInstance, workInProgress, false, false);
9541 }
9542 };
9543 updateHostText$1 = function (current, workInProgress, oldText, newText) {
9544 if (oldText !== newText) {
9545 // If the text content differs, we'll create a new text instance for it.
9546 var rootContainerInstance = getRootHostContainer();
9547 var currentHostContext = getHostContext();
9548 workInProgress.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress);
9549 // We'll have to mark it as having an effect, even though we won't use the effect for anything.
9550 // This lets the parents know that at least one of their children has changed.
9551 markUpdate(workInProgress);
9552 }
9553 };
9554} else {
9555 // No host operations
9556 updateHostContainer = function (workInProgress) {
9557 // Noop
9558 };
9559 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
9560 // Noop
9561 };
9562 updateHostText$1 = function (current, workInProgress, oldText, newText) {
9563 // Noop
9564 };
9565}
9566
9567function completeWork(current, workInProgress, renderExpirationTime) {
9568 var newProps = workInProgress.pendingProps;
9569
9570 switch (workInProgress.tag) {
9571 case IndeterminateComponent:
9572 break;
9573 case LazyComponent:
9574 break;
9575 case SimpleMemoComponent:
9576 case FunctionComponent:
9577 break;
9578 case ClassComponent:
9579 {
9580 var Component = workInProgress.type;
9581 if (isContextProvider(Component)) {
9582 popContext(workInProgress);
9583 }
9584 break;
9585 }
9586 case HostRoot:
9587 {
9588 popHostContainer(workInProgress);
9589 popTopLevelContextObject(workInProgress);
9590 var fiberRoot = workInProgress.stateNode;
9591 if (fiberRoot.pendingContext) {
9592 fiberRoot.context = fiberRoot.pendingContext;
9593 fiberRoot.pendingContext = null;
9594 }
9595 if (current === null || current.child === null) {
9596 // If we hydrated, pop so that we can delete any remaining children
9597 // that weren't hydrated.
9598 popHydrationState(workInProgress);
9599 // This resets the hacky state to fix isMounted before committing.
9600 // TODO: Delete this when we delete isMounted and findDOMNode.
9601 workInProgress.effectTag &= ~Placement;
9602 }
9603 updateHostContainer(workInProgress);
9604 break;
9605 }
9606 case HostComponent:
9607 {
9608 popHostContext(workInProgress);
9609 var rootContainerInstance = getRootHostContainer();
9610 var type = workInProgress.type;
9611 if (current !== null && workInProgress.stateNode != null) {
9612 updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);
9613
9614 if (current.ref !== workInProgress.ref) {
9615 markRef$1(workInProgress);
9616 }
9617 } else {
9618 if (!newProps) {
9619 (function () {
9620 if (!(workInProgress.stateNode !== null)) {
9621 {
9622 throw ReactError('We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.');
9623 }
9624 }
9625 })();
9626 // This can happen when we abort work.
9627 break;
9628 }
9629
9630 var currentHostContext = getHostContext();
9631 // TODO: Move createInstance to beginWork and keep it on a context
9632 // "stack" as the parent. Then append children as we go in beginWork
9633 // or completeWork depending on we want to add then top->down or
9634 // bottom->up. Top->down is faster in IE11.
9635 var wasHydrated = popHydrationState(workInProgress);
9636 if (wasHydrated) {
9637 // TODO: Move this and createInstance step into the beginPhase
9638 // to consolidate.
9639 if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
9640 // If changes to the hydrated node needs to be applied at the
9641 // commit-phase we mark this as such.
9642 markUpdate(workInProgress);
9643 }
9644 } else {
9645 var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
9646
9647 appendAllChildren(instance, workInProgress, false, false);
9648
9649 // Certain renderers require commit-time effects for initial mount.
9650 // (eg DOM renderer supports auto-focus for certain elements).
9651 // Make sure such renderers get scheduled for later work.
9652 if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) {
9653 markUpdate(workInProgress);
9654 }
9655 workInProgress.stateNode = instance;
9656 }
9657
9658 if (workInProgress.ref !== null) {
9659 // If there is a ref on a host node we need to schedule a callback
9660 markRef$1(workInProgress);
9661 }
9662 }
9663 break;
9664 }
9665 case HostText:
9666 {
9667 var newText = newProps;
9668 if (current && workInProgress.stateNode != null) {
9669 var oldText = current.memoizedProps;
9670 // If we have an alternate, that means this is an update and we need
9671 // to schedule a side-effect to do the updates.
9672 updateHostText$1(current, workInProgress, oldText, newText);
9673 } else {
9674 if (typeof newText !== 'string') {
9675 (function () {
9676 if (!(workInProgress.stateNode !== null)) {
9677 {
9678 throw ReactError('We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.');
9679 }
9680 }
9681 })();
9682 // This can happen when we abort work.
9683 }
9684 var _rootContainerInstance = getRootHostContainer();
9685 var _currentHostContext = getHostContext();
9686 var _wasHydrated = popHydrationState(workInProgress);
9687 if (_wasHydrated) {
9688 if (prepareToHydrateHostTextInstance(workInProgress)) {
9689 markUpdate(workInProgress);
9690 }
9691 } else {
9692 workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
9693 }
9694 }
9695 break;
9696 }
9697 case ForwardRef:
9698 break;
9699 case SuspenseComponent:
9700 {
9701 var nextState = workInProgress.memoizedState;
9702 if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
9703 // Something suspended. Re-render with the fallback children.
9704 workInProgress.expirationTime = renderExpirationTime;
9705 // Do not reset the effect list.
9706 return workInProgress;
9707 }
9708
9709 var nextDidTimeout = nextState !== null;
9710 var prevDidTimeout = current !== null && current.memoizedState !== null;
9711
9712 if (current === null) {
9713 // In cases where we didn't find a suitable hydration boundary we never
9714 // downgraded this to a DehydratedSuspenseComponent, but we still need to
9715 // pop the hydration state since we might be inside the insertion tree.
9716 popHydrationState(workInProgress);
9717 } else if (!nextDidTimeout && prevDidTimeout) {
9718 // We just switched from the fallback to the normal children. Delete
9719 // the fallback.
9720 // TODO: Would it be better to store the fallback fragment on
9721 var currentFallbackChild = current.child.sibling;
9722 if (currentFallbackChild !== null) {
9723 // Deletions go at the beginning of the return fiber's effect list
9724 var first = workInProgress.firstEffect;
9725 if (first !== null) {
9726 workInProgress.firstEffect = currentFallbackChild;
9727 currentFallbackChild.nextEffect = first;
9728 } else {
9729 workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;
9730 currentFallbackChild.nextEffect = null;
9731 }
9732 currentFallbackChild.effectTag = Deletion;
9733 }
9734 }
9735
9736 if (supportsPersistence) {
9737 if (nextDidTimeout) {
9738 // If this boundary just timed out, schedule an effect to attach a
9739 // retry listener to the proimse. This flag is also used to hide the
9740 // primary children.
9741 workInProgress.effectTag |= Update;
9742 }
9743 }
9744 if (supportsMutation) {
9745 if (nextDidTimeout || prevDidTimeout) {
9746 // If this boundary just timed out, schedule an effect to attach a
9747 // retry listener to the proimse. This flag is also used to hide the
9748 // primary children. In mutation mode, we also need the flag to
9749 // *unhide* children that were previously hidden, so check if the
9750 // is currently timed out, too.
9751 workInProgress.effectTag |= Update;
9752 }
9753 }
9754 break;
9755 }
9756 case Fragment:
9757 break;
9758 case Mode:
9759 break;
9760 case Profiler:
9761 break;
9762 case HostPortal:
9763 popHostContainer(workInProgress);
9764 updateHostContainer(workInProgress);
9765 break;
9766 case ContextProvider:
9767 // Pop provider fiber
9768 popProvider(workInProgress);
9769 break;
9770 case ContextConsumer:
9771 break;
9772 case MemoComponent:
9773 break;
9774 case IncompleteClassComponent:
9775 {
9776 // Same as class component case. I put it down here so that the tags are
9777 // sequential to ensure this switch is compiled to a jump table.
9778 var _Component = workInProgress.type;
9779 if (isContextProvider(_Component)) {
9780 popContext(workInProgress);
9781 }
9782 break;
9783 }
9784 case DehydratedSuspenseComponent:
9785 {
9786 if (enableSuspenseServerRenderer) {
9787 if (current === null) {
9788 var _wasHydrated2 = popHydrationState(workInProgress);
9789 (function () {
9790 if (!_wasHydrated2) {
9791 {
9792 throw ReactError('A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React.');
9793 }
9794 }
9795 })();
9796 skipPastDehydratedSuspenseInstance(workInProgress);
9797 } else if ((workInProgress.effectTag & DidCapture) === NoEffect) {
9798 // This boundary did not suspend so it's now hydrated.
9799 // To handle any future suspense cases, we're going to now upgrade it
9800 // to a Suspense component. We detach it from the existing current fiber.
9801 current.alternate = null;
9802 workInProgress.alternate = null;
9803 workInProgress.tag = SuspenseComponent;
9804 workInProgress.memoizedState = null;
9805 workInProgress.stateNode = null;
9806 }
9807 }
9808 break;
9809 }
9810 case EventComponent:
9811 {
9812 if (enableEventAPI) {
9813 popHostContext(workInProgress);
9814 var _rootContainerInstance2 = getRootHostContainer();
9815 var responder = workInProgress.type.responder;
9816 // Update the props on the event component state node
9817 workInProgress.stateNode.props = newProps;
9818
9819 }
9820 break;
9821 }
9822 case EventTarget:
9823 {
9824 if (enableEventAPI) {
9825 popHostContext(workInProgress);
9826 var _type = workInProgress.type.type;
9827 var node = workInProgress.return;
9828 var parentHostInstance = null;
9829 // Traverse up the fiber tree till we find a host component fiber
9830 while (node !== null) {
9831 if (node.tag === HostComponent) {
9832 parentHostInstance = node.stateNode;
9833 break;
9834 }
9835 node = node.return;
9836 }
9837
9838 }
9839 break;
9840 }
9841 default:
9842 (function () {
9843 {
9844 {
9845 throw ReactError('Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
9846 }
9847 }
9848 })();
9849 }
9850
9851 return null;
9852}
9853
9854function shouldCaptureSuspense(workInProgress) {
9855 // In order to capture, the Suspense component must have a fallback prop.
9856 if (workInProgress.memoizedProps.fallback === undefined) {
9857 return false;
9858 }
9859 // If it was the primary children that just suspended, capture and render the
9860 // fallback. Otherwise, don't capture and bubble to the next boundary.
9861 var nextState = workInProgress.memoizedState;
9862 return nextState === null;
9863}
9864
9865// This module is forked in different environments.
9866// By default, return `true` to log errors to the console.
9867// Forks can return `false` if this isn't desirable.
9868function showErrorDialog(capturedError) {
9869 return true;
9870}
9871
9872function logCapturedError(capturedError) {
9873 var logError = showErrorDialog(capturedError);
9874
9875 // Allow injected showErrorDialog() to prevent default console.error logging.
9876 // This enables renderers like ReactNative to better manage redbox behavior.
9877 if (logError === false) {
9878 return;
9879 }
9880
9881 var error = capturedError.error;
9882 {
9883 var componentName = capturedError.componentName,
9884 componentStack = capturedError.componentStack,
9885 errorBoundaryName = capturedError.errorBoundaryName,
9886 errorBoundaryFound = capturedError.errorBoundaryFound,
9887 willRetry = capturedError.willRetry;
9888
9889 // Browsers support silencing uncaught errors by calling
9890 // `preventDefault()` in window `error` handler.
9891 // We record this information as an expando on the error.
9892
9893 if (error != null && error._suppressLogging) {
9894 if (errorBoundaryFound && willRetry) {
9895 // The error is recoverable and was silenced.
9896 // Ignore it and don't print the stack addendum.
9897 // This is handy for testing error boundaries without noise.
9898 return;
9899 }
9900 // The error is fatal. Since the silencing might have
9901 // been accidental, we'll surface it anyway.
9902 // However, the browser would have silenced the original error
9903 // so we'll print it first, and then print the stack addendum.
9904 console.error(error);
9905 // For a more detailed description of this block, see:
9906 // https://github.com/facebook/react/pull/13384
9907 }
9908
9909 var componentNameMessage = componentName ? 'The above error occurred in the <' + componentName + '> component:' : 'The above error occurred in one of your React components:';
9910
9911 var errorBoundaryMessage = void 0;
9912 // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.
9913 if (errorBoundaryFound && errorBoundaryName) {
9914 if (willRetry) {
9915 errorBoundaryMessage = 'React will try to recreate this component tree from scratch ' + ('using the error boundary you provided, ' + errorBoundaryName + '.');
9916 } else {
9917 errorBoundaryMessage = 'This error was initially handled by the error boundary ' + errorBoundaryName + '.\n' + 'Recreating the tree from scratch failed so React will unmount the tree.';
9918 }
9919 } else {
9920 errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\n' + 'Visit https://fb.me/react-error-boundaries to learn more about error boundaries.';
9921 }
9922 var combinedMessage = '' + componentNameMessage + componentStack + '\n\n' + ('' + errorBoundaryMessage);
9923
9924 // In development, we provide our own message with just the component stack.
9925 // We don't include the original error message and JS stack because the browser
9926 // has already printed it. Even if the application swallows the error, it is still
9927 // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
9928 console.error(combinedMessage);
9929 }
9930}
9931
9932var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
9933{
9934 didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
9935}
9936
9937var PossiblyWeakSet$1 = typeof WeakSet === 'function' ? WeakSet : Set;
9938
9939function logError(boundary, errorInfo) {
9940 var source = errorInfo.source;
9941 var stack = errorInfo.stack;
9942 if (stack === null && source !== null) {
9943 stack = getStackByFiberInDevAndProd(source);
9944 }
9945
9946 var capturedError = {
9947 componentName: source !== null ? getComponentName(source.type) : null,
9948 componentStack: stack !== null ? stack : '',
9949 error: errorInfo.value,
9950 errorBoundary: null,
9951 errorBoundaryName: null,
9952 errorBoundaryFound: false,
9953 willRetry: false
9954 };
9955
9956 if (boundary !== null && boundary.tag === ClassComponent) {
9957 capturedError.errorBoundary = boundary.stateNode;
9958 capturedError.errorBoundaryName = getComponentName(boundary.type);
9959 capturedError.errorBoundaryFound = true;
9960 capturedError.willRetry = true;
9961 }
9962
9963 try {
9964 logCapturedError(capturedError);
9965 } catch (e) {
9966 // This method must not throw, or React internal state will get messed up.
9967 // If console.error is overridden, or logCapturedError() shows a dialog that throws,
9968 // we want to report this error outside of the normal stack as a last resort.
9969 // https://github.com/facebook/react/issues/13188
9970 setTimeout(function () {
9971 throw e;
9972 });
9973 }
9974}
9975
9976var callComponentWillUnmountWithTimer = function (current$$1, instance) {
9977 startPhaseTimer(current$$1, 'componentWillUnmount');
9978 instance.props = current$$1.memoizedProps;
9979 instance.state = current$$1.memoizedState;
9980 instance.componentWillUnmount();
9981 stopPhaseTimer();
9982};
9983
9984// Capture errors so they don't interrupt unmounting.
9985function safelyCallComponentWillUnmount(current$$1, instance) {
9986 {
9987 invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current$$1, instance);
9988 if (hasCaughtError()) {
9989 var unmountError = clearCaughtError();
9990 captureCommitPhaseError$$1(current$$1, unmountError);
9991 }
9992 }
9993}
9994
9995function safelyDetachRef(current$$1) {
9996 var ref = current$$1.ref;
9997 if (ref !== null) {
9998 if (typeof ref === 'function') {
9999 {
10000 invokeGuardedCallback(null, ref, null, null);
10001 if (hasCaughtError()) {
10002 var refError = clearCaughtError();
10003 captureCommitPhaseError$$1(current$$1, refError);
10004 }
10005 }
10006 } else {
10007 ref.current = null;
10008 }
10009 }
10010}
10011
10012function safelyCallDestroy(current$$1, destroy) {
10013 {
10014 invokeGuardedCallback(null, destroy, null);
10015 if (hasCaughtError()) {
10016 var error = clearCaughtError();
10017 captureCommitPhaseError$$1(current$$1, error);
10018 }
10019 }
10020}
10021
10022function commitBeforeMutationLifeCycles(current$$1, finishedWork) {
10023 switch (finishedWork.tag) {
10024 case FunctionComponent:
10025 case ForwardRef:
10026 case SimpleMemoComponent:
10027 {
10028 commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork);
10029 return;
10030 }
10031 case ClassComponent:
10032 {
10033 if (finishedWork.effectTag & Snapshot) {
10034 if (current$$1 !== null) {
10035 var prevProps = current$$1.memoizedProps;
10036 var prevState = current$$1.memoizedState;
10037 startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');
10038 var instance = finishedWork.stateNode;
10039 // We could update instance props and state here,
10040 // but instead we rely on them being set during last render.
10041 // TODO: revisit this when we implement resuming.
10042 {
10043 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
10044 !(instance.props === finishedWork.memoizedProps) ? warning$1(false, 'Expected %s props to match memoized props before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
10045 !(instance.state === finishedWork.memoizedState) ? warning$1(false, 'Expected %s state to match memoized state before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
10046 }
10047 }
10048 var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
10049 {
10050 var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
10051 if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
10052 didWarnSet.add(finishedWork.type);
10053 warningWithoutStack$1(false, '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));
10054 }
10055 }
10056 instance.__reactInternalSnapshotBeforeUpdate = snapshot;
10057 stopPhaseTimer();
10058 }
10059 }
10060 return;
10061 }
10062 case HostRoot:
10063 case HostComponent:
10064 case HostText:
10065 case HostPortal:
10066 case IncompleteClassComponent:
10067 // Nothing to do for these component types
10068 return;
10069 default:
10070 {
10071 (function () {
10072 {
10073 {
10074 throw ReactError('This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
10075 }
10076 }
10077 })();
10078 }
10079 }
10080}
10081
10082function commitHookEffectList(unmountTag, mountTag, finishedWork) {
10083 var updateQueue = finishedWork.updateQueue;
10084 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
10085 if (lastEffect !== null) {
10086 var firstEffect = lastEffect.next;
10087 var effect = firstEffect;
10088 do {
10089 if ((effect.tag & unmountTag) !== NoEffect$1) {
10090 // Unmount
10091 var destroy = effect.destroy;
10092 effect.destroy = undefined;
10093 if (destroy !== undefined) {
10094 destroy();
10095 }
10096 }
10097 if ((effect.tag & mountTag) !== NoEffect$1) {
10098 // Mount
10099 var create = effect.create;
10100 effect.destroy = create();
10101
10102 {
10103 var _destroy = effect.destroy;
10104 if (_destroy !== undefined && typeof _destroy !== 'function') {
10105 var addendum = void 0;
10106 if (_destroy === null) {
10107 addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
10108 } else if (typeof _destroy.then === 'function') {
10109 addendum = '\n\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + 'useEffect(() => {\n' + ' async function fetchData() {\n' + ' // You can await here\n' + ' const response = await MyAPI.getData(someId);\n' + ' // ...\n' + ' }\n' + ' fetchData();\n' + '}, [someId]); // Or [] if effect doesn\'t need props or state\n\n' + 'Learn more about data fetching with Hooks: https://fb.me/react-hooks-data-fetching';
10110 } else {
10111 addendum = ' You returned: ' + _destroy;
10112 }
10113 warningWithoutStack$1(false, 'An effect function must not return anything besides a function, ' + 'which is used for clean-up.%s%s', addendum, getStackByFiberInDevAndProd(finishedWork));
10114 }
10115 }
10116 }
10117 effect = effect.next;
10118 } while (effect !== firstEffect);
10119 }
10120}
10121
10122function commitPassiveHookEffects(finishedWork) {
10123 commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork);
10124 commitHookEffectList(NoEffect$1, MountPassive, finishedWork);
10125}
10126
10127function commitLifeCycles(finishedRoot, current$$1, finishedWork, committedExpirationTime) {
10128 switch (finishedWork.tag) {
10129 case FunctionComponent:
10130 case ForwardRef:
10131 case SimpleMemoComponent:
10132 {
10133 commitHookEffectList(UnmountLayout, MountLayout, finishedWork);
10134 break;
10135 }
10136 case ClassComponent:
10137 {
10138 var instance = finishedWork.stateNode;
10139 if (finishedWork.effectTag & Update) {
10140 if (current$$1 === null) {
10141 startPhaseTimer(finishedWork, 'componentDidMount');
10142 // We could update instance props and state here,
10143 // but instead we rely on them being set during last render.
10144 // TODO: revisit this when we implement resuming.
10145 {
10146 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
10147 !(instance.props === finishedWork.memoizedProps) ? warning$1(false, 'Expected %s props to match memoized props before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
10148 !(instance.state === finishedWork.memoizedState) ? warning$1(false, 'Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
10149 }
10150 }
10151 instance.componentDidMount();
10152 stopPhaseTimer();
10153 } else {
10154 var prevProps = finishedWork.elementType === finishedWork.type ? current$$1.memoizedProps : resolveDefaultProps(finishedWork.type, current$$1.memoizedProps);
10155 var prevState = current$$1.memoizedState;
10156 startPhaseTimer(finishedWork, 'componentDidUpdate');
10157 // We could update instance props and state here,
10158 // but instead we rely on them being set during last render.
10159 // TODO: revisit this when we implement resuming.
10160 {
10161 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
10162 !(instance.props === finishedWork.memoizedProps) ? warning$1(false, 'Expected %s props to match memoized props before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
10163 !(instance.state === finishedWork.memoizedState) ? warning$1(false, 'Expected %s state to match memoized state before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
10164 }
10165 }
10166 instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
10167 stopPhaseTimer();
10168 }
10169 }
10170 var updateQueue = finishedWork.updateQueue;
10171 if (updateQueue !== null) {
10172 {
10173 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
10174 !(instance.props === finishedWork.memoizedProps) ? warning$1(false, 'Expected %s props to match memoized props before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
10175 !(instance.state === finishedWork.memoizedState) ? warning$1(false, 'Expected %s state to match memoized state before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
10176 }
10177 }
10178 // We could update instance props and state here,
10179 // but instead we rely on them being set during last render.
10180 // TODO: revisit this when we implement resuming.
10181 commitUpdateQueue(finishedWork, updateQueue, instance, committedExpirationTime);
10182 }
10183 return;
10184 }
10185 case HostRoot:
10186 {
10187 var _updateQueue = finishedWork.updateQueue;
10188 if (_updateQueue !== null) {
10189 var _instance = null;
10190 if (finishedWork.child !== null) {
10191 switch (finishedWork.child.tag) {
10192 case HostComponent:
10193 _instance = getPublicInstance(finishedWork.child.stateNode);
10194 break;
10195 case ClassComponent:
10196 _instance = finishedWork.child.stateNode;
10197 break;
10198 }
10199 }
10200 commitUpdateQueue(finishedWork, _updateQueue, _instance, committedExpirationTime);
10201 }
10202 return;
10203 }
10204 case HostComponent:
10205 {
10206 var _instance2 = finishedWork.stateNode;
10207
10208 // Renderers may schedule work to be done after host components are mounted
10209 // (eg DOM renderer may schedule auto-focus for inputs and form controls).
10210 // These effects should only be committed when components are first mounted,
10211 // aka when there is no current/alternate.
10212 if (current$$1 === null && finishedWork.effectTag & Update) {
10213 var type = finishedWork.type;
10214 var props = finishedWork.memoizedProps;
10215
10216 }
10217
10218 return;
10219 }
10220 case HostText:
10221 {
10222 // We have no life-cycles associated with text.
10223 return;
10224 }
10225 case HostPortal:
10226 {
10227 // We have no life-cycles associated with portals.
10228 return;
10229 }
10230 case Profiler:
10231 {
10232 if (enableProfilerTimer) {
10233 var onRender = finishedWork.memoizedProps.onRender;
10234
10235 if (enableSchedulerTracing) {
10236 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime(), finishedRoot.memoizedInteractions);
10237 } else {
10238 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime());
10239 }
10240 }
10241 return;
10242 }
10243 case SuspenseComponent:
10244 case IncompleteClassComponent:
10245 break;
10246 default:
10247 {
10248 (function () {
10249 {
10250 {
10251 throw ReactError('This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
10252 }
10253 }
10254 })();
10255 }
10256 }
10257}
10258
10259function hideOrUnhideAllChildren(finishedWork, isHidden) {
10260 if (supportsMutation) {
10261 // We only have the top Fiber that was inserted but we need to recurse down its
10262 var node = finishedWork;
10263 while (true) {
10264 if (node.tag === HostComponent) {
10265 var instance = node.stateNode;
10266 if (isHidden) {
10267 hideInstance(instance);
10268 } else {
10269 unhideInstance(node.stateNode, node.memoizedProps);
10270 }
10271 } else if (node.tag === HostText) {
10272 var _instance3 = node.stateNode;
10273 if (isHidden) {
10274 hideTextInstance(_instance3);
10275 } else {
10276 unhideTextInstance(_instance3, node.memoizedProps);
10277 }
10278 } else if (node.tag === SuspenseComponent && node.memoizedState !== null) {
10279 // Found a nested Suspense component that timed out. Skip over the
10280 var fallbackChildFragment = node.child.sibling;
10281 fallbackChildFragment.return = node;
10282 node = fallbackChildFragment;
10283 continue;
10284 } else if (node.child !== null) {
10285 node.child.return = node;
10286 node = node.child;
10287 continue;
10288 }
10289 if (node === finishedWork) {
10290 return;
10291 }
10292 while (node.sibling === null) {
10293 if (node.return === null || node.return === finishedWork) {
10294 return;
10295 }
10296 node = node.return;
10297 }
10298 node.sibling.return = node.return;
10299 node = node.sibling;
10300 }
10301 }
10302}
10303
10304function commitAttachRef(finishedWork) {
10305 var ref = finishedWork.ref;
10306 if (ref !== null) {
10307 var instance = finishedWork.stateNode;
10308 var instanceToUse = void 0;
10309 switch (finishedWork.tag) {
10310 case HostComponent:
10311 instanceToUse = getPublicInstance(instance);
10312 break;
10313 default:
10314 instanceToUse = instance;
10315 }
10316 if (typeof ref === 'function') {
10317 ref(instanceToUse);
10318 } else {
10319 {
10320 if (!ref.hasOwnProperty('current')) {
10321 warningWithoutStack$1(false, 'Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork));
10322 }
10323 }
10324
10325 ref.current = instanceToUse;
10326 }
10327 }
10328}
10329
10330function commitDetachRef(current$$1) {
10331 var currentRef = current$$1.ref;
10332 if (currentRef !== null) {
10333 if (typeof currentRef === 'function') {
10334 currentRef(null);
10335 } else {
10336 currentRef.current = null;
10337 }
10338 }
10339}
10340
10341// User-originating errors (lifecycles and refs) should not interrupt
10342// deletion, so don't let them throw. Host-originating errors should
10343// interrupt deletion, so it's okay
10344function commitUnmount(current$$1) {
10345 onCommitUnmount(current$$1);
10346
10347 switch (current$$1.tag) {
10348 case FunctionComponent:
10349 case ForwardRef:
10350 case MemoComponent:
10351 case SimpleMemoComponent:
10352 {
10353 var updateQueue = current$$1.updateQueue;
10354 if (updateQueue !== null) {
10355 var lastEffect = updateQueue.lastEffect;
10356 if (lastEffect !== null) {
10357 var firstEffect = lastEffect.next;
10358 var effect = firstEffect;
10359 do {
10360 var destroy = effect.destroy;
10361 if (destroy !== undefined) {
10362 safelyCallDestroy(current$$1, destroy);
10363 }
10364 effect = effect.next;
10365 } while (effect !== firstEffect);
10366 }
10367 }
10368 break;
10369 }
10370 case ClassComponent:
10371 {
10372 safelyDetachRef(current$$1);
10373 var instance = current$$1.stateNode;
10374 if (typeof instance.componentWillUnmount === 'function') {
10375 safelyCallComponentWillUnmount(current$$1, instance);
10376 }
10377 return;
10378 }
10379 case HostComponent:
10380 {
10381 safelyDetachRef(current$$1);
10382 return;
10383 }
10384 case HostPortal:
10385 {
10386 // TODO: this is recursive.
10387 // We are also not using this parent because
10388 // the portal will get pushed immediately.
10389 if (supportsMutation) {
10390 unmountHostComponents(current$$1);
10391 } else if (supportsPersistence) {
10392 emptyPortalContainer(current$$1);
10393 }
10394 return;
10395 }
10396 }
10397}
10398
10399function commitNestedUnmounts(root) {
10400 // While we're inside a removed host node we don't want to call
10401 // removeChild on the inner nodes because they're removed by the top
10402 // call anyway. We also want to call componentWillUnmount on all
10403 // composites before this host node is removed from the tree. Therefore
10404 var node = root;
10405 while (true) {
10406 commitUnmount(node);
10407 // Visit children because they may contain more composite or host nodes.
10408 // Skip portals because commitUnmount() currently visits them recursively.
10409 if (node.child !== null && (
10410 // If we use mutation we drill down into portals using commitUnmount above.
10411 // If we don't use mutation we drill down into portals here instead.
10412 !supportsMutation || node.tag !== HostPortal)) {
10413 node.child.return = node;
10414 node = node.child;
10415 continue;
10416 }
10417 if (node === root) {
10418 return;
10419 }
10420 while (node.sibling === null) {
10421 if (node.return === null || node.return === root) {
10422 return;
10423 }
10424 node = node.return;
10425 }
10426 node.sibling.return = node.return;
10427 node = node.sibling;
10428 }
10429}
10430
10431function detachFiber(current$$1) {
10432 // Cut off the return pointers to disconnect it from the tree. Ideally, we
10433 // should clear the child pointer of the parent alternate to let this
10434 // get GC:ed but we don't know which for sure which parent is the current
10435 // one so we'll settle for GC:ing the subtree of this child. This child
10436 // itself will be GC:ed when the parent updates the next time.
10437 current$$1.return = null;
10438 current$$1.child = null;
10439 current$$1.memoizedState = null;
10440 current$$1.updateQueue = null;
10441 var alternate = current$$1.alternate;
10442 if (alternate !== null) {
10443 alternate.return = null;
10444 alternate.child = null;
10445 alternate.memoizedState = null;
10446 alternate.updateQueue = null;
10447 }
10448}
10449
10450function emptyPortalContainer(current$$1) {
10451 if (!supportsPersistence) {
10452 return;
10453 }
10454
10455 var portal = current$$1.stateNode;
10456 var containerInfo = portal.containerInfo;
10457
10458 var emptyChildSet = createContainerChildSet(containerInfo);
10459 replaceContainerChildren(containerInfo, emptyChildSet);
10460}
10461
10462function commitContainer(finishedWork) {
10463 if (!supportsPersistence) {
10464 return;
10465 }
10466
10467 switch (finishedWork.tag) {
10468 case ClassComponent:
10469 case HostComponent:
10470 case HostText:
10471 {
10472 return;
10473 }
10474 case HostRoot:
10475 case HostPortal:
10476 {
10477 var portalOrRoot = finishedWork.stateNode;
10478 var containerInfo = portalOrRoot.containerInfo,
10479 _pendingChildren = portalOrRoot.pendingChildren;
10480
10481 replaceContainerChildren(containerInfo, _pendingChildren);
10482 return;
10483 }
10484 default:
10485 {
10486 (function () {
10487 {
10488 {
10489 throw ReactError('This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
10490 }
10491 }
10492 })();
10493 }
10494 }
10495}
10496
10497function getHostParentFiber(fiber) {
10498 var parent = fiber.return;
10499 while (parent !== null) {
10500 if (isHostParent(parent)) {
10501 return parent;
10502 }
10503 parent = parent.return;
10504 }
10505 (function () {
10506 {
10507 {
10508 throw ReactError('Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.');
10509 }
10510 }
10511 })();
10512}
10513
10514function isHostParent(fiber) {
10515 return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
10516}
10517
10518function getHostSibling(fiber) {
10519 // We're going to search forward into the tree until we find a sibling host
10520 // node. Unfortunately, if multiple insertions are done in a row we have to
10521 // search past them. This leads to exponential search for the next sibling.
10522 var node = fiber;
10523 siblings: while (true) {
10524 // If we didn't find anything, let's try the next sibling.
10525 while (node.sibling === null) {
10526 if (node.return === null || isHostParent(node.return)) {
10527 // If we pop out of the root or hit the parent the fiber we are the
10528 // last sibling.
10529 return null;
10530 }
10531 node = node.return;
10532 }
10533 node.sibling.return = node.return;
10534 node = node.sibling;
10535 while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedSuspenseComponent) {
10536 // If it is not host node and, we might have a host node inside it.
10537 // Try to search down until we find one.
10538 if (node.effectTag & Placement) {
10539 // If we don't have a child, try the siblings instead.
10540 continue siblings;
10541 }
10542 // If we don't have a child, try the siblings instead.
10543 // We also skip portals because they are not part of this host tree.
10544 if (node.child === null || node.tag === HostPortal) {
10545 continue siblings;
10546 } else {
10547 node.child.return = node;
10548 node = node.child;
10549 }
10550 }
10551 // Check if this host node is stable or about to be placed.
10552 if (!(node.effectTag & Placement)) {
10553 // Found it!
10554 return node.stateNode;
10555 }
10556 }
10557}
10558
10559function commitPlacement(finishedWork) {
10560 if (!supportsMutation) {
10561 return;
10562 }
10563
10564 // Recursively insert all host nodes into the parent.
10565 var parentFiber = getHostParentFiber(finishedWork);
10566
10567 // Note: these two variables *must* always be updated together.
10568 var parent = void 0;
10569 var isContainer = void 0;
10570
10571 switch (parentFiber.tag) {
10572 case HostComponent:
10573 parent = parentFiber.stateNode;
10574 isContainer = false;
10575 break;
10576 case HostRoot:
10577 parent = parentFiber.stateNode.containerInfo;
10578 isContainer = true;
10579 break;
10580 case HostPortal:
10581 parent = parentFiber.stateNode.containerInfo;
10582 isContainer = true;
10583 break;
10584 default:
10585 (function () {
10586 {
10587 {
10588 throw ReactError('Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.');
10589 }
10590 }
10591 })();
10592 }
10593 if (parentFiber.effectTag & ContentReset) {
10594 // Reset the text content of the parent before doing any insertions
10595 parentFiber.effectTag &= ~ContentReset;
10596 }
10597
10598 var before = getHostSibling(finishedWork);
10599 // We only have the top Fiber that was inserted but we need to recurse down its
10600 // children to find all the terminal nodes.
10601 var node = finishedWork;
10602 while (true) {
10603 if (node.tag === HostComponent || node.tag === HostText) {
10604 if (before) {
10605 if (isContainer) {
10606 insertInContainerBefore(parent, node.stateNode, before);
10607 } else {
10608 insertBefore(parent, node.stateNode, before);
10609 }
10610 } else {
10611 if (isContainer) {
10612 appendChildToContainer(parent, node.stateNode);
10613 } else {
10614 appendChild(parent, node.stateNode);
10615 }
10616 }
10617 } else if (node.tag === HostPortal) {
10618 // If the insertion itself is a portal, then we don't want to traverse
10619 // down its children. Instead, we'll get insertions from each child in
10620 // the portal directly.
10621 } else if (node.child !== null) {
10622 node.child.return = node;
10623 node = node.child;
10624 continue;
10625 }
10626 if (node === finishedWork) {
10627 return;
10628 }
10629 while (node.sibling === null) {
10630 if (node.return === null || node.return === finishedWork) {
10631 return;
10632 }
10633 node = node.return;
10634 }
10635 node.sibling.return = node.return;
10636 node = node.sibling;
10637 }
10638}
10639
10640function unmountHostComponents(current$$1) {
10641 // We only have the top Fiber that was deleted but we need to recurse down its
10642 var node = current$$1;
10643
10644 // Each iteration, currentParent is populated with node's host parent if not
10645 // currentParentIsValid.
10646 var currentParentIsValid = false;
10647
10648 // Note: these two variables *must* always be updated together.
10649 var currentParent = void 0;
10650 var currentParentIsContainer = void 0;
10651
10652 while (true) {
10653 if (!currentParentIsValid) {
10654 var parent = node.return;
10655 findParent: while (true) {
10656 (function () {
10657 if (!(parent !== null)) {
10658 {
10659 throw ReactError('Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.');
10660 }
10661 }
10662 })();
10663 switch (parent.tag) {
10664 case HostComponent:
10665 currentParent = parent.stateNode;
10666 currentParentIsContainer = false;
10667 break findParent;
10668 case HostRoot:
10669 currentParent = parent.stateNode.containerInfo;
10670 currentParentIsContainer = true;
10671 break findParent;
10672 case HostPortal:
10673 currentParent = parent.stateNode.containerInfo;
10674 currentParentIsContainer = true;
10675 break findParent;
10676 }
10677 parent = parent.return;
10678 }
10679 currentParentIsValid = true;
10680 }
10681
10682 if (node.tag === HostComponent || node.tag === HostText) {
10683 commitNestedUnmounts(node);
10684 // After all the children have unmounted, it is now safe to remove the
10685 // node from the tree.
10686 if (currentParentIsContainer) {
10687 removeChildFromContainer(currentParent, node.stateNode);
10688 } else {
10689 removeChild(currentParent, node.stateNode);
10690 }
10691 // Don't visit children because we already visited them.
10692 } else if (enableSuspenseServerRenderer && node.tag === DehydratedSuspenseComponent) {
10693 // Delete the dehydrated suspense boundary and all of its content.
10694 if (currentParentIsContainer) {
10695 clearSuspenseBoundaryFromContainer(currentParent, node.stateNode);
10696 } else {
10697 clearSuspenseBoundary(currentParent, node.stateNode);
10698 }
10699 } else if (node.tag === HostPortal) {
10700 if (node.child !== null) {
10701 // When we go into a portal, it becomes the parent to remove from.
10702 // We will reassign it back when we pop the portal on the way up.
10703 currentParent = node.stateNode.containerInfo;
10704 currentParentIsContainer = true;
10705 // Visit children because portals might contain host components.
10706 node.child.return = node;
10707 node = node.child;
10708 continue;
10709 }
10710 } else {
10711 commitUnmount(node);
10712 // Visit children because we may find more host components below.
10713 if (node.child !== null) {
10714 node.child.return = node;
10715 node = node.child;
10716 continue;
10717 }
10718 }
10719 if (node === current$$1) {
10720 return;
10721 }
10722 while (node.sibling === null) {
10723 if (node.return === null || node.return === current$$1) {
10724 return;
10725 }
10726 node = node.return;
10727 if (node.tag === HostPortal) {
10728 // When we go out of the portal, we need to restore the parent.
10729 // Since we don't keep a stack of them, we will search for it.
10730 currentParentIsValid = false;
10731 }
10732 }
10733 node.sibling.return = node.return;
10734 node = node.sibling;
10735 }
10736}
10737
10738function commitDeletion(current$$1) {
10739 if (supportsMutation) {
10740 // Recursively delete all host nodes from the parent.
10741 // Detach refs and call componentWillUnmount() on the whole subtree.
10742 unmountHostComponents(current$$1);
10743 } else {
10744 // Detach refs and call componentWillUnmount() on the whole subtree.
10745 commitNestedUnmounts(current$$1);
10746 }
10747 detachFiber(current$$1);
10748}
10749
10750function commitWork(current$$1, finishedWork) {
10751 if (!supportsMutation) {
10752 switch (finishedWork.tag) {
10753 case FunctionComponent:
10754 case ForwardRef:
10755 case MemoComponent:
10756 case SimpleMemoComponent:
10757 {
10758 // Note: We currently never use MountMutation, but useLayout uses
10759 // UnmountMutation.
10760 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
10761 return;
10762 }
10763 case Profiler:
10764 {
10765 return;
10766 }
10767 case SuspenseComponent:
10768 {
10769 commitSuspenseComponent(finishedWork);
10770 return;
10771 }
10772 }
10773
10774 commitContainer(finishedWork);
10775 return;
10776 }
10777
10778 switch (finishedWork.tag) {
10779 case FunctionComponent:
10780 case ForwardRef:
10781 case MemoComponent:
10782 case SimpleMemoComponent:
10783 {
10784 // Note: We currently never use MountMutation, but useLayout uses
10785 // UnmountMutation.
10786 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
10787 return;
10788 }
10789 case ClassComponent:
10790 {
10791 return;
10792 }
10793 case HostComponent:
10794 {
10795 var instance = finishedWork.stateNode;
10796 if (instance != null) {
10797 // Commit the work prepared earlier.
10798 var newProps = finishedWork.memoizedProps;
10799 // For hydration we reuse the update path but we treat the oldProps
10800 // as the newProps. The updatePayload will contain the real change in
10801 // this case.
10802 var oldProps = current$$1 !== null ? current$$1.memoizedProps : newProps;
10803 var type = finishedWork.type;
10804 // TODO: Type the updateQueue to be specific to host components.
10805 var updatePayload = finishedWork.updateQueue;
10806 finishedWork.updateQueue = null;
10807 if (updatePayload !== null) {
10808 commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork);
10809 }
10810 }
10811 return;
10812 }
10813 case HostText:
10814 {
10815 (function () {
10816 if (!(finishedWork.stateNode !== null)) {
10817 {
10818 throw ReactError('This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.');
10819 }
10820 }
10821 })();
10822 var textInstance = finishedWork.stateNode;
10823 var newText = finishedWork.memoizedProps;
10824 // For hydration we reuse the update path but we treat the oldProps
10825 // as the newProps. The updatePayload will contain the real change in
10826 // this case.
10827 var oldText = current$$1 !== null ? current$$1.memoizedProps : newText;
10828 commitTextUpdate(textInstance, oldText, newText);
10829 return;
10830 }
10831 case HostRoot:
10832 {
10833 return;
10834 }
10835 case Profiler:
10836 {
10837 return;
10838 }
10839 case SuspenseComponent:
10840 {
10841 commitSuspenseComponent(finishedWork);
10842 return;
10843 }
10844 case IncompleteClassComponent:
10845 {
10846 return;
10847 }
10848 default:
10849 {
10850 (function () {
10851 {
10852 {
10853 throw ReactError('This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
10854 }
10855 }
10856 })();
10857 }
10858 }
10859}
10860
10861function commitSuspenseComponent(finishedWork) {
10862 var newState = finishedWork.memoizedState;
10863
10864 var newDidTimeout = void 0;
10865 var primaryChildParent = finishedWork;
10866 if (newState === null) {
10867 newDidTimeout = false;
10868 } else {
10869 newDidTimeout = true;
10870 primaryChildParent = finishedWork.child;
10871 if (newState.timedOutAt === NoWork) {
10872 // If the children had not already timed out, record the time.
10873 // This is used to compute the elapsed time during subsequent
10874 // attempts to render the children.
10875 newState.timedOutAt = requestCurrentTime$$1();
10876 }
10877 }
10878
10879 if (supportsMutation && primaryChildParent !== null) {
10880 hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);
10881 }
10882
10883 // If this boundary just timed out, then it will have a set of thenables.
10884 // For each thenable, attach a listener so that when it resolves, React
10885 // attempts to re-render the boundary in the primary (pre-timeout) state.
10886 var thenables = finishedWork.updateQueue;
10887 if (thenables !== null) {
10888 finishedWork.updateQueue = null;
10889 var retryCache = finishedWork.stateNode;
10890 if (retryCache === null) {
10891 retryCache = finishedWork.stateNode = new PossiblyWeakSet$1();
10892 }
10893 thenables.forEach(function (thenable) {
10894 // Memoize using the boundary fiber to prevent redundant listeners.
10895 var retry = resolveRetryThenable$$1.bind(null, finishedWork, thenable);
10896 if (enableSchedulerTracing) {
10897 retry = unstable_wrap(retry);
10898 }
10899 if (!retryCache.has(thenable)) {
10900 retryCache.add(thenable);
10901 thenable.then(retry, retry);
10902 }
10903 });
10904 }
10905}
10906
10907function commitResetTextContent(current$$1) {
10908 if (!supportsMutation) {
10909 return;
10910 }
10911 resetTextContent(current$$1.stateNode);
10912}
10913
10914var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
10915var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
10916
10917function createRootErrorUpdate(fiber, errorInfo, expirationTime) {
10918 var update = createUpdate(expirationTime);
10919 // Unmount the root by rendering null.
10920 update.tag = CaptureUpdate;
10921 // Caution: React DevTools currently depends on this property
10922 // being called "element".
10923 update.payload = { element: null };
10924 var error = errorInfo.value;
10925 update.callback = function () {
10926 onUncaughtError$$1(error);
10927 logError(fiber, errorInfo);
10928 };
10929 return update;
10930}
10931
10932function createClassErrorUpdate(fiber, errorInfo, expirationTime) {
10933 var update = createUpdate(expirationTime);
10934 update.tag = CaptureUpdate;
10935 var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
10936 if (typeof getDerivedStateFromError === 'function') {
10937 var error = errorInfo.value;
10938 update.payload = function () {
10939 return getDerivedStateFromError(error);
10940 };
10941 }
10942
10943 var inst = fiber.stateNode;
10944 if (inst !== null && typeof inst.componentDidCatch === 'function') {
10945 update.callback = function callback() {
10946 if (typeof getDerivedStateFromError !== 'function') {
10947 // To preserve the preexisting retry behavior of error boundaries,
10948 // we keep track of which ones already failed during this batch.
10949 // This gets reset before we yield back to the browser.
10950 // TODO: Warn in strict mode if getDerivedStateFromError is
10951 // not defined.
10952 markLegacyErrorBoundaryAsFailed$$1(this);
10953 }
10954 var error = errorInfo.value;
10955 var stack = errorInfo.stack;
10956 logError(fiber, errorInfo);
10957 this.componentDidCatch(error, {
10958 componentStack: stack !== null ? stack : ''
10959 });
10960 {
10961 if (typeof getDerivedStateFromError !== 'function') {
10962 // If componentDidCatch is the only error boundary method defined,
10963 // then it needs to call setState to recover from errors.
10964 // If no state update is scheduled then the boundary will swallow the error.
10965 !(fiber.expirationTime === Sync) ? warningWithoutStack$1(false, '%s: Error boundaries should implement getDerivedStateFromError(). ' + 'In that method, return a state update to display an error message or fallback UI.', getComponentName(fiber.type) || 'Unknown') : void 0;
10966 }
10967 }
10968 };
10969 }
10970 return update;
10971}
10972
10973function attachPingListener(root, renderExpirationTime, thenable) {
10974 // Attach a listener to the promise to "ping" the root and retry. But
10975 // only if one does not already exist for the current render expiration
10976 // time (which acts like a "thread ID" here).
10977 var pingCache = root.pingCache;
10978 var threadIDs = void 0;
10979 if (pingCache === null) {
10980 pingCache = root.pingCache = new PossiblyWeakMap();
10981 threadIDs = new Set();
10982 pingCache.set(thenable, threadIDs);
10983 } else {
10984 threadIDs = pingCache.get(thenable);
10985 if (threadIDs === undefined) {
10986 threadIDs = new Set();
10987 pingCache.set(thenable, threadIDs);
10988 }
10989 }
10990 if (!threadIDs.has(renderExpirationTime)) {
10991 // Memoize using the thread ID to prevent redundant listeners.
10992 threadIDs.add(renderExpirationTime);
10993 var ping = pingSuspendedRoot$$1.bind(null, root, thenable, renderExpirationTime);
10994 if (enableSchedulerTracing) {
10995 ping = unstable_wrap(ping);
10996 }
10997 thenable.then(ping, ping);
10998 }
10999}
11000
11001function throwException(root, returnFiber, sourceFiber, value, renderExpirationTime) {
11002 // The source fiber did not complete.
11003 sourceFiber.effectTag |= Incomplete;
11004 // Its effect list is no longer valid.
11005 sourceFiber.firstEffect = sourceFiber.lastEffect = null;
11006
11007 if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
11008 // This is a thenable.
11009 var thenable = value;
11010
11011 // Find the earliest timeout threshold of all the placeholders in the
11012 // ancestor path. We could avoid this traversal by storing the thresholds on
11013 // the stack, but we choose not to because we only hit this path if we're
11014 // IO-bound (i.e. if something suspends). Whereas the stack is used even in
11015 // the non-IO- bound case.
11016 var _workInProgress = returnFiber;
11017 var earliestTimeoutMs = -1;
11018 var startTimeMs = -1;
11019 do {
11020 if (_workInProgress.tag === SuspenseComponent) {
11021 var current$$1 = _workInProgress.alternate;
11022 if (current$$1 !== null) {
11023 var currentState = current$$1.memoizedState;
11024 if (currentState !== null) {
11025 // Reached a boundary that already timed out. Do not search
11026 // any further.
11027 var timedOutAt = currentState.timedOutAt;
11028 startTimeMs = expirationTimeToMs(timedOutAt);
11029 // Do not search any further.
11030 break;
11031 }
11032 }
11033 var defaultSuspenseTimeout = 150;
11034 if (earliestTimeoutMs === -1 || defaultSuspenseTimeout < earliestTimeoutMs) {
11035 earliestTimeoutMs = defaultSuspenseTimeout;
11036 }
11037 }
11038 // If there is a DehydratedSuspenseComponent we don't have to do anything because
11039 // if something suspends inside it, we will simply leave that as dehydrated. It
11040 // will never timeout.
11041 _workInProgress = _workInProgress.return;
11042 } while (_workInProgress !== null);
11043
11044 // Schedule the nearest Suspense to re-render the timed out view.
11045 _workInProgress = returnFiber;
11046 do {
11047 if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress)) {
11048 // Found the nearest boundary.
11049
11050 // Stash the promise on the boundary fiber. If the boundary times out, we'll
11051 var thenables = _workInProgress.updateQueue;
11052 if (thenables === null) {
11053 var updateQueue = new Set();
11054 updateQueue.add(thenable);
11055 _workInProgress.updateQueue = updateQueue;
11056 } else {
11057 thenables.add(thenable);
11058 }
11059
11060 // If the boundary is outside of concurrent mode, we should *not*
11061 // suspend the commit. Pretend as if the suspended component rendered
11062 // null and keep rendering. In the commit phase, we'll schedule a
11063 // subsequent synchronous update to re-render the Suspense.
11064 //
11065 // Note: It doesn't matter whether the component that suspended was
11066 // inside a concurrent mode tree. If the Suspense is outside of it, we
11067 // should *not* suspend the commit.
11068 if ((_workInProgress.mode & ConcurrentMode) === NoEffect) {
11069 _workInProgress.effectTag |= DidCapture;
11070
11071 // We're going to commit this fiber even though it didn't complete.
11072 // But we shouldn't call any lifecycle methods or callbacks. Remove
11073 // all lifecycle effect tags.
11074 sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete);
11075
11076 if (sourceFiber.tag === ClassComponent) {
11077 var currentSourceFiber = sourceFiber.alternate;
11078 if (currentSourceFiber === null) {
11079 // This is a new mount. Change the tag so it's not mistaken for a
11080 // completed class component. For example, we should not call
11081 // componentWillUnmount if it is deleted.
11082 sourceFiber.tag = IncompleteClassComponent;
11083 } else {
11084 // When we try rendering again, we should not reuse the current fiber,
11085 // since it's known to be in an inconsistent state. Use a force updte to
11086 // prevent a bail out.
11087 var update = createUpdate(Sync);
11088 update.tag = ForceUpdate;
11089 enqueueUpdate(sourceFiber, update);
11090 }
11091 }
11092
11093 // The source fiber did not complete. Mark it with Sync priority to
11094 // indicate that it still has pending work.
11095 sourceFiber.expirationTime = Sync;
11096
11097 // Exit without suspending.
11098 return;
11099 }
11100
11101 // Confirmed that the boundary is in a concurrent mode tree. Continue
11102 // with the normal suspend path.
11103
11104 attachPingListener(root, renderExpirationTime, thenable);
11105
11106 var absoluteTimeoutMs = void 0;
11107 if (earliestTimeoutMs === -1) {
11108 // If no explicit threshold is given, default to an arbitrarily large
11109 // value. The actual size doesn't matter because the threshold for the
11110 // whole tree will be clamped to the expiration time.
11111 absoluteTimeoutMs = maxSigned31BitInt;
11112 } else {
11113 if (startTimeMs === -1) {
11114 // This suspend happened outside of any already timed-out
11115 // placeholders. We don't know exactly when the update was
11116 // scheduled, but we can infer an approximate start time based on
11117 // the expiration time and the priority.
11118 startTimeMs = inferStartTimeFromExpirationTime$$1(root, renderExpirationTime);
11119 }
11120 absoluteTimeoutMs = startTimeMs + earliestTimeoutMs;
11121 }
11122
11123 // Mark the earliest timeout in the suspended fiber's ancestor path.
11124 // After completing the root, we'll take the largest of all the
11125 // suspended fiber's timeouts and use it to compute a timeout for the
11126 // whole tree.
11127 renderDidSuspend$$1(root, absoluteTimeoutMs, renderExpirationTime);
11128
11129 _workInProgress.effectTag |= ShouldCapture;
11130 _workInProgress.expirationTime = renderExpirationTime;
11131 return;
11132 } else if (enableSuspenseServerRenderer && _workInProgress.tag === DehydratedSuspenseComponent) {
11133 attachPingListener(root, renderExpirationTime, thenable);
11134
11135 // Since we already have a current fiber, we can eagerly add a retry listener.
11136 var retryCache = _workInProgress.memoizedState;
11137 if (retryCache === null) {
11138 retryCache = _workInProgress.memoizedState = new PossiblyWeakSet();
11139 var _current = _workInProgress.alternate;
11140 (function () {
11141 if (!_current) {
11142 {
11143 throw ReactError('A dehydrated suspense boundary must commit before trying to render. This is probably a bug in React.');
11144 }
11145 }
11146 })();
11147 _current.memoizedState = retryCache;
11148 }
11149 // Memoize using the boundary fiber to prevent redundant listeners.
11150 if (!retryCache.has(thenable)) {
11151 retryCache.add(thenable);
11152 var retry = resolveRetryThenable$$1.bind(null, _workInProgress, thenable);
11153 if (enableSchedulerTracing) {
11154 retry = unstable_wrap(retry);
11155 }
11156 thenable.then(retry, retry);
11157 }
11158 _workInProgress.effectTag |= ShouldCapture;
11159 _workInProgress.expirationTime = renderExpirationTime;
11160 return;
11161 }
11162 // This boundary already captured during this render. Continue to the next
11163 // boundary.
11164 _workInProgress = _workInProgress.return;
11165 } while (_workInProgress !== null);
11166 // No boundary was found. Fallthrough to error mode.
11167 // TODO: Use invariant so the message is stripped in prod?
11168 value = new Error((getComponentName(sourceFiber.type) || 'A React component') + ' suspended while rendering, but no fallback UI was specified.\n' + '\n' + 'Add a <Suspense fallback=...> component higher in the tree to ' + 'provide a loading indicator or placeholder to display.' + getStackByFiberInDevAndProd(sourceFiber));
11169 }
11170
11171 // We didn't find a boundary that could handle this type of exception. Start
11172 // over and traverse parent path again, this time treating the exception
11173 // as an error.
11174 renderDidError$$1();
11175 value = createCapturedValue(value, sourceFiber);
11176 var workInProgress = returnFiber;
11177 do {
11178 switch (workInProgress.tag) {
11179 case HostRoot:
11180 {
11181 var _errorInfo = value;
11182 workInProgress.effectTag |= ShouldCapture;
11183 workInProgress.expirationTime = renderExpirationTime;
11184 var _update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime);
11185 enqueueCapturedUpdate(workInProgress, _update);
11186 return;
11187 }
11188 case ClassComponent:
11189 // Capture and retry
11190 var errorInfo = value;
11191 var ctor = workInProgress.type;
11192 var instance = workInProgress.stateNode;
11193 if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary$$1(instance))) {
11194 workInProgress.effectTag |= ShouldCapture;
11195 workInProgress.expirationTime = renderExpirationTime;
11196 // Schedule the error boundary to re-render using updated state
11197 var _update2 = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime);
11198 enqueueCapturedUpdate(workInProgress, _update2);
11199 return;
11200 }
11201 break;
11202 default:
11203 break;
11204 }
11205 workInProgress = workInProgress.return;
11206 } while (workInProgress !== null);
11207}
11208
11209function unwindWork(workInProgress, renderExpirationTime) {
11210 switch (workInProgress.tag) {
11211 case ClassComponent:
11212 {
11213 var Component = workInProgress.type;
11214 if (isContextProvider(Component)) {
11215 popContext(workInProgress);
11216 }
11217 var effectTag = workInProgress.effectTag;
11218 if (effectTag & ShouldCapture) {
11219 workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture;
11220 return workInProgress;
11221 }
11222 return null;
11223 }
11224 case HostRoot:
11225 {
11226 popHostContainer(workInProgress);
11227 popTopLevelContextObject(workInProgress);
11228 var _effectTag = workInProgress.effectTag;
11229 (function () {
11230 if (!((_effectTag & DidCapture) === NoEffect)) {
11231 {
11232 throw ReactError('The root failed to unmount after an error. This is likely a bug in React. Please file an issue.');
11233 }
11234 }
11235 })();
11236 workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture;
11237 return workInProgress;
11238 }
11239 case HostComponent:
11240 {
11241 // TODO: popHydrationState
11242 popHostContext(workInProgress);
11243 return null;
11244 }
11245 case SuspenseComponent:
11246 {
11247 var _effectTag2 = workInProgress.effectTag;
11248 if (_effectTag2 & ShouldCapture) {
11249 workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture;
11250 // Captured a suspense effect. Re-render the boundary.
11251 return workInProgress;
11252 }
11253 return null;
11254 }
11255 case DehydratedSuspenseComponent:
11256 {
11257 if (enableSuspenseServerRenderer) {
11258 // TODO: popHydrationState
11259 var _effectTag3 = workInProgress.effectTag;
11260 if (_effectTag3 & ShouldCapture) {
11261 workInProgress.effectTag = _effectTag3 & ~ShouldCapture | DidCapture;
11262 // Captured a suspense effect. Re-render the boundary.
11263 return workInProgress;
11264 }
11265 }
11266 return null;
11267 }
11268 case HostPortal:
11269 popHostContainer(workInProgress);
11270 return null;
11271 case ContextProvider:
11272 popProvider(workInProgress);
11273 return null;
11274 case EventComponent:
11275 case EventTarget:
11276 if (enableEventAPI) {
11277 popHostContext(workInProgress);
11278 }
11279 return null;
11280 default:
11281 return null;
11282 }
11283}
11284
11285function unwindInterruptedWork(interruptedWork) {
11286 switch (interruptedWork.tag) {
11287 case ClassComponent:
11288 {
11289 var childContextTypes = interruptedWork.type.childContextTypes;
11290 if (childContextTypes !== null && childContextTypes !== undefined) {
11291 popContext(interruptedWork);
11292 }
11293 break;
11294 }
11295 case HostRoot:
11296 {
11297 popHostContainer(interruptedWork);
11298 popTopLevelContextObject(interruptedWork);
11299 break;
11300 }
11301 case HostComponent:
11302 {
11303 popHostContext(interruptedWork);
11304 break;
11305 }
11306 case HostPortal:
11307 popHostContainer(interruptedWork);
11308 break;
11309 case ContextProvider:
11310 popProvider(interruptedWork);
11311 break;
11312 default:
11313 break;
11314 }
11315}
11316
11317// Intentionally not named imports because Rollup would use dynamic dispatch for
11318// CommonJS interop named imports.
11319// Intentionally not named imports because Rollup would use dynamic dispatch for
11320// CommonJS interop named imports.
11321var scheduleCallback$1 = Scheduler$1.unstable_scheduleCallback;
11322var cancelCallback$1 = Scheduler$1.unstable_cancelCallback;
11323var shouldYield$1 = Scheduler$1.unstable_shouldYield;
11324var now$1 = Scheduler$1.unstable_now;
11325var getCurrentPriorityLevel$1 = Scheduler$1.unstable_getCurrentPriorityLevel;
11326var NormalPriority$1 = Scheduler$1.unstable_NormalPriority;
11327var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
11328var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
11329var ReactShouldWarnActingUpdates = ReactSharedInternals.ReactShouldWarnActingUpdates;
11330
11331
11332var didWarnAboutStateTransition = void 0;
11333var didWarnSetStateChildContext = void 0;
11334var warnAboutUpdateOnUnmounted = void 0;
11335var warnAboutInvalidUpdates = void 0;
11336
11337if (enableSchedulerTracing) {
11338 // Provide explicit error message when production+profiling bundle of e.g. react-dom
11339 // is used with production (non-profiling) bundle of scheduler/tracing
11340 (function () {
11341 if (!(__interactionsRef != null && __interactionsRef.current != null)) {
11342 {
11343 throw ReactError('It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at http://fb.me/react-profiling');
11344 }
11345 }
11346 })();
11347}
11348
11349{
11350 didWarnAboutStateTransition = false;
11351 didWarnSetStateChildContext = false;
11352 var didWarnStateUpdateForUnmountedComponent = {};
11353
11354 warnAboutUpdateOnUnmounted = function (fiber, isClass) {
11355 // We show the whole stack but dedupe on the top component's name because
11356 // the problematic code almost always lies inside that component.
11357 var componentName = getComponentName(fiber.type) || 'ReactComponent';
11358 if (didWarnStateUpdateForUnmountedComponent[componentName]) {
11359 return;
11360 }
11361 warningWithoutStack$1(false, "Can't perform a React state update on an unmounted component. This " + 'is a no-op, but it indicates a memory leak in your application. To ' + 'fix, cancel all subscriptions and asynchronous tasks in %s.%s', isClass ? 'the componentWillUnmount method' : 'a useEffect cleanup function', getStackByFiberInDevAndProd(fiber));
11362 didWarnStateUpdateForUnmountedComponent[componentName] = true;
11363 };
11364
11365 warnAboutInvalidUpdates = function (instance) {
11366 switch (phase) {
11367 case 'getChildContext':
11368 if (didWarnSetStateChildContext) {
11369 return;
11370 }
11371 warningWithoutStack$1(false, 'setState(...): Cannot call setState() inside getChildContext()');
11372 didWarnSetStateChildContext = true;
11373 break;
11374 case 'render':
11375 if (didWarnAboutStateTransition) {
11376 return;
11377 }
11378 warningWithoutStack$1(false, 'Cannot update during an existing state transition (such as within ' + '`render`). Render methods should be a pure function of props and state.');
11379 didWarnAboutStateTransition = true;
11380 break;
11381 }
11382 };
11383}
11384
11385// Represents the expiration time that incoming updates should use. (If this
11386// is NoWork, use the default strategy: async updates in async mode, sync
11387// updates in sync mode.)
11388var expirationContext = NoWork;
11389
11390var isWorking = false;
11391
11392// The next work in progress fiber that we're currently working on.
11393var nextUnitOfWork = null;
11394var nextRoot = null;
11395// The time at which we're currently rendering work.
11396var nextRenderExpirationTime = NoWork;
11397var nextLatestAbsoluteTimeoutMs = -1;
11398var nextRenderDidError = false;
11399
11400// The next fiber with an effect that we're currently committing.
11401var nextEffect = null;
11402
11403var isCommitting$1 = false;
11404var rootWithPendingPassiveEffects = null;
11405var passiveEffectCallbackHandle = null;
11406var passiveEffectCallback = null;
11407
11408var legacyErrorBoundariesThatAlreadyFailed = null;
11409
11410// Used for performance tracking.
11411var interruptedBy = null;
11412
11413var stashedWorkInProgressProperties = void 0;
11414var replayUnitOfWork = void 0;
11415var mayReplayFailedUnitOfWork = void 0;
11416var isReplayingFailedUnitOfWork = void 0;
11417var originalReplayError = void 0;
11418var rethrowOriginalError = void 0;
11419if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
11420 stashedWorkInProgressProperties = null;
11421 mayReplayFailedUnitOfWork = true;
11422 isReplayingFailedUnitOfWork = false;
11423 originalReplayError = null;
11424 replayUnitOfWork = function (failedUnitOfWork, thrownValue, isYieldy) {
11425 if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') {
11426 // Don't replay promises. Treat everything else like an error.
11427 // TODO: Need to figure out a different strategy if/when we add
11428 // support for catching other types.
11429 return;
11430 }
11431
11432 // Restore the original state of the work-in-progress
11433 if (stashedWorkInProgressProperties === null) {
11434 // This should never happen. Don't throw because this code is DEV-only.
11435 warningWithoutStack$1(false, 'Could not replay rendering after an error. This is likely a bug in React. ' + 'Please file an issue.');
11436 return;
11437 }
11438 assignFiberPropertiesInDEV(failedUnitOfWork, stashedWorkInProgressProperties);
11439
11440 switch (failedUnitOfWork.tag) {
11441 case HostRoot:
11442 popHostContainer(failedUnitOfWork);
11443 popTopLevelContextObject(failedUnitOfWork);
11444 break;
11445 case HostComponent:
11446 popHostContext(failedUnitOfWork);
11447 break;
11448 case ClassComponent:
11449 {
11450 var Component = failedUnitOfWork.type;
11451 if (isContextProvider(Component)) {
11452 popContext(failedUnitOfWork);
11453 }
11454 break;
11455 }
11456 case HostPortal:
11457 popHostContainer(failedUnitOfWork);
11458 break;
11459 case ContextProvider:
11460 popProvider(failedUnitOfWork);
11461 break;
11462 }
11463 // Replay the begin phase.
11464 isReplayingFailedUnitOfWork = true;
11465 originalReplayError = thrownValue;
11466 invokeGuardedCallback(null, workLoop, null, isYieldy);
11467 isReplayingFailedUnitOfWork = false;
11468 originalReplayError = null;
11469 if (hasCaughtError()) {
11470 var replayError = clearCaughtError();
11471 if (replayError != null && thrownValue != null) {
11472 try {
11473 // Reading the expando property is intentionally
11474 // inside `try` because it might be a getter or Proxy.
11475 if (replayError._suppressLogging) {
11476 // Also suppress logging for the original error.
11477 thrownValue._suppressLogging = true;
11478 }
11479 } catch (inner) {
11480 // Ignore.
11481 }
11482 }
11483 } else {
11484 // If the begin phase did not fail the second time, set this pointer
11485 // back to the original value.
11486 nextUnitOfWork = failedUnitOfWork;
11487 }
11488 };
11489 rethrowOriginalError = function () {
11490 throw originalReplayError;
11491 };
11492}
11493
11494function resetStack() {
11495 if (nextUnitOfWork !== null) {
11496 var interruptedWork = nextUnitOfWork.return;
11497 while (interruptedWork !== null) {
11498 unwindInterruptedWork(interruptedWork);
11499 interruptedWork = interruptedWork.return;
11500 }
11501 }
11502
11503 {
11504 ReactStrictModeWarnings.discardPendingWarnings();
11505 checkThatStackIsEmpty();
11506 }
11507
11508 nextRoot = null;
11509 nextRenderExpirationTime = NoWork;
11510 nextLatestAbsoluteTimeoutMs = -1;
11511 nextRenderDidError = false;
11512 nextUnitOfWork = null;
11513}
11514
11515function commitAllHostEffects() {
11516 while (nextEffect !== null) {
11517 {
11518 setCurrentFiber(nextEffect);
11519 }
11520 recordEffect();
11521
11522 var effectTag = nextEffect.effectTag;
11523
11524 if (effectTag & ContentReset) {
11525 commitResetTextContent(nextEffect);
11526 }
11527
11528 if (effectTag & Ref) {
11529 var current$$1 = nextEffect.alternate;
11530 if (current$$1 !== null) {
11531 commitDetachRef(current$$1);
11532 }
11533 }
11534
11535 // The following switch statement is only concerned about placement,
11536 // updates, and deletions. To avoid needing to add a case for every
11537 // possible bitmap value, we remove the secondary effects from the
11538 // effect tag and switch on that value.
11539 var primaryEffectTag = effectTag & (Placement | Update | Deletion);
11540 switch (primaryEffectTag) {
11541 case Placement:
11542 {
11543 commitPlacement(nextEffect);
11544 // Clear the "placement" from effect tag so that we know that this is inserted, before
11545 // any life-cycles like componentDidMount gets called.
11546 // TODO: findDOMNode doesn't rely on this any more but isMounted
11547 // does and isMounted is deprecated anyway so we should be able
11548 // to kill this.
11549 nextEffect.effectTag &= ~Placement;
11550 break;
11551 }
11552 case PlacementAndUpdate:
11553 {
11554 // Placement
11555 commitPlacement(nextEffect);
11556 // Clear the "placement" from effect tag so that we know that this is inserted, before
11557 // any life-cycles like componentDidMount gets called.
11558 nextEffect.effectTag &= ~Placement;
11559
11560 // Update
11561 var _current = nextEffect.alternate;
11562 commitWork(_current, nextEffect);
11563 break;
11564 }
11565 case Update:
11566 {
11567 var _current2 = nextEffect.alternate;
11568 commitWork(_current2, nextEffect);
11569 break;
11570 }
11571 case Deletion:
11572 {
11573 commitDeletion(nextEffect);
11574 break;
11575 }
11576 }
11577 nextEffect = nextEffect.nextEffect;
11578 }
11579
11580 {
11581 resetCurrentFiber();
11582 }
11583}
11584
11585function commitBeforeMutationLifecycles() {
11586 while (nextEffect !== null) {
11587 {
11588 setCurrentFiber(nextEffect);
11589 }
11590
11591 var effectTag = nextEffect.effectTag;
11592 if (effectTag & Snapshot) {
11593 recordEffect();
11594 var current$$1 = nextEffect.alternate;
11595 commitBeforeMutationLifeCycles(current$$1, nextEffect);
11596 }
11597
11598 nextEffect = nextEffect.nextEffect;
11599 }
11600
11601 {
11602 resetCurrentFiber();
11603 }
11604}
11605
11606function commitAllLifeCycles(finishedRoot, committedExpirationTime) {
11607 {
11608 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
11609 ReactStrictModeWarnings.flushLegacyContextWarning();
11610
11611 if (warnAboutDeprecatedLifecycles) {
11612 ReactStrictModeWarnings.flushPendingDeprecationWarnings();
11613 }
11614 }
11615 while (nextEffect !== null) {
11616 {
11617 setCurrentFiber(nextEffect);
11618 }
11619 var effectTag = nextEffect.effectTag;
11620
11621 if (effectTag & (Update | Callback)) {
11622 recordEffect();
11623 var current$$1 = nextEffect.alternate;
11624 commitLifeCycles(finishedRoot, current$$1, nextEffect, committedExpirationTime);
11625 }
11626
11627 if (effectTag & Ref) {
11628 recordEffect();
11629 commitAttachRef(nextEffect);
11630 }
11631
11632 if (effectTag & Passive) {
11633 rootWithPendingPassiveEffects = finishedRoot;
11634 }
11635
11636 nextEffect = nextEffect.nextEffect;
11637 }
11638 {
11639 resetCurrentFiber();
11640 }
11641}
11642
11643function commitPassiveEffects(root, firstEffect) {
11644 rootWithPendingPassiveEffects = null;
11645 passiveEffectCallbackHandle = null;
11646 passiveEffectCallback = null;
11647
11648 // Set this to true to prevent re-entrancy
11649 var previousIsRendering = isRendering;
11650 isRendering = true;
11651
11652 var effect = firstEffect;
11653 do {
11654 {
11655 setCurrentFiber(effect);
11656 }
11657
11658 if (effect.effectTag & Passive) {
11659 var didError = false;
11660 var error = void 0;
11661 {
11662 isInPassiveEffectDEV = true;
11663 invokeGuardedCallback(null, commitPassiveHookEffects, null, effect);
11664 isInPassiveEffectDEV = false;
11665 if (hasCaughtError()) {
11666 didError = true;
11667 error = clearCaughtError();
11668 }
11669 }
11670 if (didError) {
11671 captureCommitPhaseError$1(effect, error);
11672 }
11673 }
11674 effect = effect.nextEffect;
11675 } while (effect !== null);
11676 {
11677 resetCurrentFiber();
11678 }
11679
11680 isRendering = previousIsRendering;
11681
11682 // Check if work was scheduled by one of the effects
11683 var rootExpirationTime = root.expirationTime;
11684 if (rootExpirationTime !== NoWork) {
11685 requestWork(root, rootExpirationTime);
11686 }
11687 // Flush any sync work that was scheduled by effects
11688 if (!isBatchingUpdates && !isRendering) {
11689 performSyncWork();
11690 }
11691
11692 {
11693 if (rootWithPendingPassiveEffects === root) {
11694 nestedPassiveEffectCountDEV++;
11695 } else {
11696 nestedPassiveEffectCountDEV = 0;
11697 }
11698 }
11699}
11700
11701function isAlreadyFailedLegacyErrorBoundary$1(instance) {
11702 return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
11703}
11704
11705function markLegacyErrorBoundaryAsFailed$1(instance) {
11706 if (legacyErrorBoundariesThatAlreadyFailed === null) {
11707 legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
11708 } else {
11709 legacyErrorBoundariesThatAlreadyFailed.add(instance);
11710 }
11711}
11712
11713function flushPassiveEffects$1() {
11714 var didFlushEffects = passiveEffectCallback !== null;
11715 if (passiveEffectCallbackHandle !== null) {
11716 cancelCallback$1(passiveEffectCallbackHandle);
11717 }
11718 if (passiveEffectCallback !== null) {
11719 // We call the scheduled callback instead of commitPassiveEffects directly
11720 // to ensure tracing works correctly.
11721 passiveEffectCallback();
11722 }
11723 return didFlushEffects;
11724}
11725
11726function commitRoot(root, finishedWork) {
11727 isWorking = true;
11728 isCommitting$1 = true;
11729 startCommitTimer();
11730
11731 (function () {
11732 if (!(root.current !== finishedWork)) {
11733 {
11734 throw ReactError('Cannot commit the same tree as before. This is probably a bug related to the return field. This error is likely caused by a bug in React. Please file an issue.');
11735 }
11736 }
11737 })();
11738 var committedExpirationTime = root.pendingCommitExpirationTime;
11739 (function () {
11740 if (!(committedExpirationTime !== NoWork)) {
11741 {
11742 throw ReactError('Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue.');
11743 }
11744 }
11745 })();
11746 root.pendingCommitExpirationTime = NoWork;
11747
11748 // Update the pending priority levels to account for the work that we are
11749 // about to commit. This needs to happen before calling the lifecycles, since
11750 // they may schedule additional updates.
11751 var updateExpirationTimeBeforeCommit = finishedWork.expirationTime;
11752 var childExpirationTimeBeforeCommit = finishedWork.childExpirationTime;
11753 var earliestRemainingTimeBeforeCommit = childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit ? childExpirationTimeBeforeCommit : updateExpirationTimeBeforeCommit;
11754 markCommittedPriorityLevels(root, earliestRemainingTimeBeforeCommit);
11755
11756 var prevInteractions = null;
11757 if (enableSchedulerTracing) {
11758 // Restore any pending interactions at this point,
11759 // So that cascading work triggered during the render phase will be accounted for.
11760 prevInteractions = __interactionsRef.current;
11761 __interactionsRef.current = root.memoizedInteractions;
11762 }
11763
11764 // Reset this to null before calling lifecycles
11765 ReactCurrentOwner$1.current = null;
11766
11767 var firstEffect = void 0;
11768 if (finishedWork.effectTag > PerformedWork) {
11769 // A fiber's effect list consists only of its children, not itself. So if
11770 // the root has an effect, we need to add it to the end of the list. The
11771 // resulting list is the set that would belong to the root's parent, if
11772 // it had one; that is, all the effects in the tree including the root.
11773 if (finishedWork.lastEffect !== null) {
11774 finishedWork.lastEffect.nextEffect = finishedWork;
11775 firstEffect = finishedWork.firstEffect;
11776 } else {
11777 firstEffect = finishedWork;
11778 }
11779 } else {
11780 // There is no effect on the root.
11781 firstEffect = finishedWork.firstEffect;
11782 }
11783
11784 prepareForCommit(root.containerInfo);
11785
11786 // Invoke instances of getSnapshotBeforeUpdate before mutation.
11787 nextEffect = firstEffect;
11788 startCommitSnapshotEffectsTimer();
11789 while (nextEffect !== null) {
11790 var didError = false;
11791 var error = void 0;
11792 {
11793 invokeGuardedCallback(null, commitBeforeMutationLifecycles, null);
11794 if (hasCaughtError()) {
11795 didError = true;
11796 error = clearCaughtError();
11797 }
11798 }
11799 if (didError) {
11800 (function () {
11801 if (!(nextEffect !== null)) {
11802 {
11803 throw ReactError('Should have next effect. This error is likely caused by a bug in React. Please file an issue.');
11804 }
11805 }
11806 })();
11807 captureCommitPhaseError$1(nextEffect, error);
11808 // Clean-up
11809 if (nextEffect !== null) {
11810 nextEffect = nextEffect.nextEffect;
11811 }
11812 }
11813 }
11814 stopCommitSnapshotEffectsTimer();
11815
11816 if (enableProfilerTimer) {
11817 // Mark the current commit time to be shared by all Profilers in this batch.
11818 // This enables them to be grouped later.
11819 recordCommitTime();
11820 }
11821
11822 // Commit all the side-effects within a tree. We'll do this in two passes.
11823 // The first pass performs all the host insertions, updates, deletions and
11824 // ref unmounts.
11825 nextEffect = firstEffect;
11826 startCommitHostEffectsTimer();
11827 while (nextEffect !== null) {
11828 var _didError = false;
11829 var _error = void 0;
11830 {
11831 invokeGuardedCallback(null, commitAllHostEffects, null);
11832 if (hasCaughtError()) {
11833 _didError = true;
11834 _error = clearCaughtError();
11835 }
11836 }
11837 if (_didError) {
11838 (function () {
11839 if (!(nextEffect !== null)) {
11840 {
11841 throw ReactError('Should have next effect. This error is likely caused by a bug in React. Please file an issue.');
11842 }
11843 }
11844 })();
11845 captureCommitPhaseError$1(nextEffect, _error);
11846 // Clean-up
11847 if (nextEffect !== null) {
11848 nextEffect = nextEffect.nextEffect;
11849 }
11850 }
11851 }
11852 stopCommitHostEffectsTimer();
11853
11854 resetAfterCommit(root.containerInfo);
11855
11856 // The work-in-progress tree is now the current tree. This must come after
11857 // the first pass of the commit phase, so that the previous tree is still
11858 // current during componentWillUnmount, but before the second pass, so that
11859 // the finished work is current during componentDidMount/Update.
11860 root.current = finishedWork;
11861
11862 // In the second pass we'll perform all life-cycles and ref callbacks.
11863 // Life-cycles happen as a separate pass so that all placements, updates,
11864 // and deletions in the entire tree have already been invoked.
11865 // This pass also triggers any renderer-specific initial effects.
11866 nextEffect = firstEffect;
11867 startCommitLifeCyclesTimer();
11868 while (nextEffect !== null) {
11869 var _didError2 = false;
11870 var _error2 = void 0;
11871 {
11872 invokeGuardedCallback(null, commitAllLifeCycles, null, root, committedExpirationTime);
11873 if (hasCaughtError()) {
11874 _didError2 = true;
11875 _error2 = clearCaughtError();
11876 }
11877 }
11878 if (_didError2) {
11879 (function () {
11880 if (!(nextEffect !== null)) {
11881 {
11882 throw ReactError('Should have next effect. This error is likely caused by a bug in React. Please file an issue.');
11883 }
11884 }
11885 })();
11886 captureCommitPhaseError$1(nextEffect, _error2);
11887 if (nextEffect !== null) {
11888 nextEffect = nextEffect.nextEffect;
11889 }
11890 }
11891 }
11892
11893 if (firstEffect !== null && rootWithPendingPassiveEffects !== null) {
11894 // This commit included a passive effect. These do not need to fire until
11895 // after the next paint. Schedule an callback to fire them in an async
11896 // event. To ensure serial execution, the callback will be flushed early if
11897 // we enter rootWithPendingPassiveEffects commit phase before then.
11898 var callback = commitPassiveEffects.bind(null, root, firstEffect);
11899 if (enableSchedulerTracing) {
11900 // TODO: Avoid this extra callback by mutating the tracing ref directly,
11901 // like we do at the beginning of commitRoot. I've opted not to do that
11902 // here because that code is still in flux.
11903 callback = unstable_wrap(callback);
11904 }
11905 passiveEffectCallbackHandle = scheduleCallback$1(NormalPriority$1, callback);
11906 passiveEffectCallback = callback;
11907 }
11908
11909 isCommitting$1 = false;
11910 isWorking = false;
11911 stopCommitLifeCyclesTimer();
11912 stopCommitTimer();
11913 onCommitRoot(finishedWork.stateNode);
11914 if (true && ReactFiberInstrumentation_1.debugTool) {
11915 ReactFiberInstrumentation_1.debugTool.onCommitWork(finishedWork);
11916 }
11917
11918 var updateExpirationTimeAfterCommit = finishedWork.expirationTime;
11919 var childExpirationTimeAfterCommit = finishedWork.childExpirationTime;
11920 var earliestRemainingTimeAfterCommit = childExpirationTimeAfterCommit > updateExpirationTimeAfterCommit ? childExpirationTimeAfterCommit : updateExpirationTimeAfterCommit;
11921 if (earliestRemainingTimeAfterCommit === NoWork) {
11922 // If there's no remaining work, we can clear the set of already failed
11923 // error boundaries.
11924 legacyErrorBoundariesThatAlreadyFailed = null;
11925 }
11926 onCommit(root, earliestRemainingTimeAfterCommit);
11927
11928 if (enableSchedulerTracing) {
11929 __interactionsRef.current = prevInteractions;
11930
11931 var subscriber = void 0;
11932
11933 try {
11934 subscriber = __subscriberRef.current;
11935 if (subscriber !== null && root.memoizedInteractions.size > 0) {
11936 var threadID = computeThreadID(committedExpirationTime, root.interactionThreadID);
11937 subscriber.onWorkStopped(root.memoizedInteractions, threadID);
11938 }
11939 } catch (error) {
11940 // It's not safe for commitRoot() to throw.
11941 // Store the error for now and we'll re-throw in finishRendering().
11942 if (!hasUnhandledError) {
11943 hasUnhandledError = true;
11944 unhandledError = error;
11945 }
11946 } finally {
11947 // Clear completed interactions from the pending Map.
11948 // Unless the render was suspended or cascading work was scheduled,
11949 // In which case– leave pending interactions until the subsequent render.
11950 var pendingInteractionMap = root.pendingInteractionMap;
11951 pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
11952 // Only decrement the pending interaction count if we're done.
11953 // If there's still work at the current priority,
11954 // That indicates that we are waiting for suspense data.
11955 if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {
11956 pendingInteractionMap.delete(scheduledExpirationTime);
11957
11958 scheduledInteractions.forEach(function (interaction) {
11959 interaction.__count--;
11960
11961 if (subscriber !== null && interaction.__count === 0) {
11962 try {
11963 subscriber.onInteractionScheduledWorkCompleted(interaction);
11964 } catch (error) {
11965 // It's not safe for commitRoot() to throw.
11966 // Store the error for now and we'll re-throw in finishRendering().
11967 if (!hasUnhandledError) {
11968 hasUnhandledError = true;
11969 unhandledError = error;
11970 }
11971 }
11972 }
11973 });
11974 }
11975 });
11976 }
11977 }
11978}
11979
11980function resetChildExpirationTime(workInProgress, renderTime) {
11981 if (renderTime !== Never && workInProgress.childExpirationTime === Never) {
11982 // The children of this component are hidden. Don't bubble their
11983 // expiration times.
11984 return;
11985 }
11986
11987 var newChildExpirationTime = NoWork;
11988
11989 // Bubble up the earliest expiration time.
11990 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
11991 // We're in profiling mode.
11992 // Let's use this same traversal to update the render durations.
11993 var actualDuration = workInProgress.actualDuration;
11994 var treeBaseDuration = workInProgress.selfBaseDuration;
11995
11996 // When a fiber is cloned, its actualDuration is reset to 0.
11997 // This value will only be updated if work is done on the fiber (i.e. it doesn't bailout).
11998 // When work is done, it should bubble to the parent's actualDuration.
11999 // If the fiber has not been cloned though, (meaning no work was done),
12000 // Then this value will reflect the amount of time spent working on a previous render.
12001 // In that case it should not bubble.
12002 // We determine whether it was cloned by comparing the child pointer.
12003 var shouldBubbleActualDurations = workInProgress.alternate === null || workInProgress.child !== workInProgress.alternate.child;
12004
12005 var child = workInProgress.child;
12006 while (child !== null) {
12007 var childUpdateExpirationTime = child.expirationTime;
12008 var childChildExpirationTime = child.childExpirationTime;
12009 if (childUpdateExpirationTime > newChildExpirationTime) {
12010 newChildExpirationTime = childUpdateExpirationTime;
12011 }
12012 if (childChildExpirationTime > newChildExpirationTime) {
12013 newChildExpirationTime = childChildExpirationTime;
12014 }
12015 if (shouldBubbleActualDurations) {
12016 actualDuration += child.actualDuration;
12017 }
12018 treeBaseDuration += child.treeBaseDuration;
12019 child = child.sibling;
12020 }
12021 workInProgress.actualDuration = actualDuration;
12022 workInProgress.treeBaseDuration = treeBaseDuration;
12023 } else {
12024 var _child = workInProgress.child;
12025 while (_child !== null) {
12026 var _childUpdateExpirationTime = _child.expirationTime;
12027 var _childChildExpirationTime = _child.childExpirationTime;
12028 if (_childUpdateExpirationTime > newChildExpirationTime) {
12029 newChildExpirationTime = _childUpdateExpirationTime;
12030 }
12031 if (_childChildExpirationTime > newChildExpirationTime) {
12032 newChildExpirationTime = _childChildExpirationTime;
12033 }
12034 _child = _child.sibling;
12035 }
12036 }
12037
12038 workInProgress.childExpirationTime = newChildExpirationTime;
12039}
12040
12041function completeUnitOfWork(workInProgress) {
12042 // Attempt to complete the current unit of work, then move to the
12043 // next sibling. If there are no more siblings, return to the
12044 // parent fiber.
12045 while (true) {
12046 // The current, flushed, state of this fiber is the alternate.
12047 // Ideally nothing should rely on this, but relying on it here
12048 // means that we don't need an additional field on the work in
12049 // progress.
12050 var current$$1 = workInProgress.alternate;
12051 {
12052 setCurrentFiber(workInProgress);
12053 }
12054
12055 var returnFiber = workInProgress.return;
12056 var siblingFiber = workInProgress.sibling;
12057
12058 if ((workInProgress.effectTag & Incomplete) === NoEffect) {
12059 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
12060 // Don't replay if it fails during completion phase.
12061 mayReplayFailedUnitOfWork = false;
12062 }
12063 // This fiber completed.
12064 // Remember we're completing this unit so we can find a boundary if it fails.
12065 nextUnitOfWork = workInProgress;
12066 if (enableProfilerTimer) {
12067 if (workInProgress.mode & ProfileMode) {
12068 startProfilerTimer(workInProgress);
12069 }
12070 nextUnitOfWork = completeWork(current$$1, workInProgress, nextRenderExpirationTime);
12071 if (workInProgress.mode & ProfileMode) {
12072 // Update render duration assuming we didn't error.
12073 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
12074 }
12075 } else {
12076 nextUnitOfWork = completeWork(current$$1, workInProgress, nextRenderExpirationTime);
12077 }
12078 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
12079 // We're out of completion phase so replaying is fine now.
12080 mayReplayFailedUnitOfWork = true;
12081 }
12082 stopWorkTimer(workInProgress);
12083 resetChildExpirationTime(workInProgress, nextRenderExpirationTime);
12084 {
12085 resetCurrentFiber();
12086 }
12087
12088 if (nextUnitOfWork !== null) {
12089 // Completing this fiber spawned new work. Work on that next.
12090 return nextUnitOfWork;
12091 }
12092
12093 if (returnFiber !== null &&
12094 // Do not append effects to parents if a sibling failed to complete
12095 (returnFiber.effectTag & Incomplete) === NoEffect) {
12096 // Append all the effects of the subtree and this fiber onto the effect
12097 // list of the parent. The completion order of the children affects the
12098 // side-effect order.
12099 if (returnFiber.firstEffect === null) {
12100 returnFiber.firstEffect = workInProgress.firstEffect;
12101 }
12102 if (workInProgress.lastEffect !== null) {
12103 if (returnFiber.lastEffect !== null) {
12104 returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
12105 }
12106 returnFiber.lastEffect = workInProgress.lastEffect;
12107 }
12108
12109 // If this fiber had side-effects, we append it AFTER the children's
12110 // side-effects. We can perform certain side-effects earlier if
12111 // needed, by doing multiple passes over the effect list. We don't want
12112 // to schedule our own side-effect on our own list because if end up
12113 // reusing children we'll schedule this effect onto itself since we're
12114 // at the end.
12115 var effectTag = workInProgress.effectTag;
12116 // Skip both NoWork and PerformedWork tags when creating the effect list.
12117 // PerformedWork effect is read by React DevTools but shouldn't be committed.
12118 if (effectTag > PerformedWork) {
12119 if (returnFiber.lastEffect !== null) {
12120 returnFiber.lastEffect.nextEffect = workInProgress;
12121 } else {
12122 returnFiber.firstEffect = workInProgress;
12123 }
12124 returnFiber.lastEffect = workInProgress;
12125 }
12126 }
12127
12128 if (true && ReactFiberInstrumentation_1.debugTool) {
12129 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
12130 }
12131
12132 if (siblingFiber !== null) {
12133 // If there is more work to do in this returnFiber, do that next.
12134 return siblingFiber;
12135 } else if (returnFiber !== null) {
12136 // If there's no more work in this returnFiber. Complete the returnFiber.
12137 workInProgress = returnFiber;
12138 continue;
12139 } else {
12140 // We've reached the root.
12141 return null;
12142 }
12143 } else {
12144 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
12145 // Record the render duration for the fiber that errored.
12146 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
12147
12148 // Include the time spent working on failed children before continuing.
12149 var actualDuration = workInProgress.actualDuration;
12150 var child = workInProgress.child;
12151 while (child !== null) {
12152 actualDuration += child.actualDuration;
12153 child = child.sibling;
12154 }
12155 workInProgress.actualDuration = actualDuration;
12156 }
12157
12158 // This fiber did not complete because something threw. Pop values off
12159 // the stack without entering the complete phase. If this is a boundary,
12160 // capture values if possible.
12161 var next = unwindWork(workInProgress, nextRenderExpirationTime);
12162 // Because this fiber did not complete, don't reset its expiration time.
12163 if (workInProgress.effectTag & DidCapture) {
12164 // Restarting an error boundary
12165 stopFailedWorkTimer(workInProgress);
12166 } else {
12167 stopWorkTimer(workInProgress);
12168 }
12169
12170 {
12171 resetCurrentFiber();
12172 }
12173
12174 if (next !== null) {
12175 stopWorkTimer(workInProgress);
12176 if (true && ReactFiberInstrumentation_1.debugTool) {
12177 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
12178 }
12179
12180 // If completing this work spawned new work, do that next. We'll come
12181 // back here again.
12182 // Since we're restarting, remove anything that is not a host effect
12183 // from the effect tag.
12184 next.effectTag &= HostEffectMask;
12185 return next;
12186 }
12187
12188 if (returnFiber !== null) {
12189 // Mark the parent fiber as incomplete and clear its effect list.
12190 returnFiber.firstEffect = returnFiber.lastEffect = null;
12191 returnFiber.effectTag |= Incomplete;
12192 }
12193
12194 if (true && ReactFiberInstrumentation_1.debugTool) {
12195 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
12196 }
12197
12198 if (siblingFiber !== null) {
12199 // If there is more work to do in this returnFiber, do that next.
12200 return siblingFiber;
12201 } else if (returnFiber !== null) {
12202 // If there's no more work in this returnFiber. Complete the returnFiber.
12203 workInProgress = returnFiber;
12204 continue;
12205 } else {
12206 return null;
12207 }
12208 }
12209 }
12210
12211 // Without this explicit null return Flow complains of invalid return type
12212 // TODO Remove the above while(true) loop
12213 // eslint-disable-next-line no-unreachable
12214 return null;
12215}
12216
12217function performUnitOfWork(workInProgress) {
12218 // The current, flushed, state of this fiber is the alternate.
12219 // Ideally nothing should rely on this, but relying on it here
12220 // means that we don't need an additional field on the work in
12221 // progress.
12222 var current$$1 = workInProgress.alternate;
12223
12224 // See if beginning this work spawns more work.
12225 startWorkTimer(workInProgress);
12226 {
12227 setCurrentFiber(workInProgress);
12228 }
12229
12230 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
12231 stashedWorkInProgressProperties = assignFiberPropertiesInDEV(stashedWorkInProgressProperties, workInProgress);
12232 }
12233
12234 var next = void 0;
12235 if (enableProfilerTimer) {
12236 if (workInProgress.mode & ProfileMode) {
12237 startProfilerTimer(workInProgress);
12238 }
12239
12240 next = beginWork(current$$1, workInProgress, nextRenderExpirationTime);
12241 workInProgress.memoizedProps = workInProgress.pendingProps;
12242
12243 if (workInProgress.mode & ProfileMode) {
12244 // Record the render duration assuming we didn't bailout (or error).
12245 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true);
12246 }
12247 } else {
12248 next = beginWork(current$$1, workInProgress, nextRenderExpirationTime);
12249 workInProgress.memoizedProps = workInProgress.pendingProps;
12250 }
12251
12252 {
12253 resetCurrentFiber();
12254 if (isReplayingFailedUnitOfWork) {
12255 // Currently replaying a failed unit of work. This should be unreachable,
12256 // because the render phase is meant to be idempotent, and it should
12257 // have thrown again. Since it didn't, rethrow the original error, so
12258 // React's internal stack is not misaligned.
12259 rethrowOriginalError();
12260 }
12261 }
12262 if (true && ReactFiberInstrumentation_1.debugTool) {
12263 ReactFiberInstrumentation_1.debugTool.onBeginWork(workInProgress);
12264 }
12265
12266 if (next === null) {
12267 // If this doesn't spawn new work, complete the current work.
12268 next = completeUnitOfWork(workInProgress);
12269 }
12270
12271 ReactCurrentOwner$1.current = null;
12272
12273 return next;
12274}
12275
12276function workLoop(isYieldy) {
12277 if (!isYieldy) {
12278 // Flush work without yielding
12279 while (nextUnitOfWork !== null) {
12280 nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
12281 }
12282 } else {
12283 // Flush asynchronous work until there's a higher priority event
12284 while (nextUnitOfWork !== null && !shouldYield$1()) {
12285 nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
12286 }
12287 }
12288}
12289
12290function renderRoot(root, isYieldy) {
12291 (function () {
12292 if (!!isWorking) {
12293 {
12294 throw ReactError('renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.');
12295 }
12296 }
12297 })();
12298
12299 flushPassiveEffects$1();
12300
12301 isWorking = true;
12302 var previousDispatcher = ReactCurrentDispatcher.current;
12303 ReactCurrentDispatcher.current = ContextOnlyDispatcher;
12304
12305 var expirationTime = root.nextExpirationTimeToWorkOn;
12306
12307 // Check if we're starting from a fresh stack, or if we're resuming from
12308 // previously yielded work.
12309 if (expirationTime !== nextRenderExpirationTime || root !== nextRoot || nextUnitOfWork === null) {
12310 // Reset the stack and start working from the root.
12311 resetStack();
12312 nextRoot = root;
12313 nextRenderExpirationTime = expirationTime;
12314 nextUnitOfWork = createWorkInProgress(nextRoot.current, null, nextRenderExpirationTime);
12315 root.pendingCommitExpirationTime = NoWork;
12316
12317 if (enableSchedulerTracing) {
12318 // Determine which interactions this batch of work currently includes,
12319 // So that we can accurately attribute time spent working on it,
12320 var interactions = new Set();
12321 root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
12322 if (scheduledExpirationTime >= expirationTime) {
12323 scheduledInteractions.forEach(function (interaction) {
12324 return interactions.add(interaction);
12325 });
12326 }
12327 });
12328
12329 // Store the current set of interactions on the FiberRoot for a few reasons:
12330 // We can re-use it in hot functions like renderRoot() without having to recalculate it.
12331 // We will also use it in commitWork() to pass to any Profiler onRender() hooks.
12332 // This also provides DevTools with a way to access it when the onCommitRoot() hook is called.
12333 root.memoizedInteractions = interactions;
12334
12335 if (interactions.size > 0) {
12336 var subscriber = __subscriberRef.current;
12337 if (subscriber !== null) {
12338 var threadID = computeThreadID(expirationTime, root.interactionThreadID);
12339 try {
12340 subscriber.onWorkStarted(interactions, threadID);
12341 } catch (error) {
12342 // Work thrown by an interaction tracing subscriber should be rethrown,
12343 // But only once it's safe (to avoid leaving the scheduler in an invalid state).
12344 // Store the error for now and we'll re-throw in finishRendering().
12345 if (!hasUnhandledError) {
12346 hasUnhandledError = true;
12347 unhandledError = error;
12348 }
12349 }
12350 }
12351 }
12352 }
12353 }
12354
12355 var prevInteractions = null;
12356 if (enableSchedulerTracing) {
12357 // We're about to start new traced work.
12358 // Restore pending interactions so cascading work triggered during the render phase will be accounted for.
12359 prevInteractions = __interactionsRef.current;
12360 __interactionsRef.current = root.memoizedInteractions;
12361 }
12362
12363 var didFatal = false;
12364
12365 startWorkLoopTimer(nextUnitOfWork);
12366
12367 do {
12368 try {
12369 workLoop(isYieldy);
12370 } catch (thrownValue) {
12371 resetContextDependences();
12372 resetHooks();
12373
12374 // Reset in case completion throws.
12375 // This is only used in DEV and when replaying is on.
12376 var mayReplay = void 0;
12377 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
12378 mayReplay = mayReplayFailedUnitOfWork;
12379 mayReplayFailedUnitOfWork = true;
12380 }
12381
12382 if (nextUnitOfWork === null) {
12383 // This is a fatal error.
12384 didFatal = true;
12385 onUncaughtError$1(thrownValue);
12386 } else {
12387 if (enableProfilerTimer && nextUnitOfWork.mode & ProfileMode) {
12388 // Record the time spent rendering before an error was thrown.
12389 // This avoids inaccurate Profiler durations in the case of a suspended render.
12390 stopProfilerTimerIfRunningAndRecordDelta(nextUnitOfWork, true);
12391 }
12392
12393 {
12394 // Reset global debug state
12395 // We assume this is defined in DEV
12396 resetCurrentlyProcessingQueue();
12397 }
12398
12399 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
12400 if (mayReplay) {
12401 var failedUnitOfWork = nextUnitOfWork;
12402 replayUnitOfWork(failedUnitOfWork, thrownValue, isYieldy);
12403 }
12404 }
12405
12406 // TODO: we already know this isn't true in some cases.
12407 // At least this shows a nicer error message until we figure out the cause.
12408 // https://github.com/facebook/react/issues/12449#issuecomment-386727431
12409 (function () {
12410 if (!(nextUnitOfWork !== null)) {
12411 {
12412 throw ReactError('Failed to replay rendering after an error. This is likely caused by a bug in React. Please file an issue with a reproducing case to help us find it.');
12413 }
12414 }
12415 })();
12416
12417 var sourceFiber = nextUnitOfWork;
12418 var returnFiber = sourceFiber.return;
12419 if (returnFiber === null) {
12420 // This is the root. The root could capture its own errors. However,
12421 // we don't know if it errors before or after we pushed the host
12422 // context. This information is needed to avoid a stack mismatch.
12423 // Because we're not sure, treat this as a fatal error. We could track
12424 // which phase it fails in, but doesn't seem worth it. At least
12425 // for now.
12426 didFatal = true;
12427 onUncaughtError$1(thrownValue);
12428 } else {
12429 throwException(root, returnFiber, sourceFiber, thrownValue, nextRenderExpirationTime);
12430 nextUnitOfWork = completeUnitOfWork(sourceFiber);
12431 continue;
12432 }
12433 }
12434 }
12435 break;
12436 } while (true);
12437
12438 if (enableSchedulerTracing) {
12439 // Traced work is done for now; restore the previous interactions.
12440 __interactionsRef.current = prevInteractions;
12441 }
12442
12443 // We're done performing work. Time to clean up.
12444 isWorking = false;
12445 ReactCurrentDispatcher.current = previousDispatcher;
12446 resetContextDependences();
12447 resetHooks();
12448
12449 // Yield back to main thread.
12450 if (didFatal) {
12451 var _didCompleteRoot = false;
12452 stopWorkLoopTimer(interruptedBy, _didCompleteRoot);
12453 interruptedBy = null;
12454 // There was a fatal error.
12455 {
12456 resetStackAfterFatalErrorInDev();
12457 }
12458 // `nextRoot` points to the in-progress root. A non-null value indicates
12459 // that we're in the middle of an async render. Set it to null to indicate
12460 // there's no more work to be done in the current batch.
12461 nextRoot = null;
12462 onFatal(root);
12463 return;
12464 }
12465
12466 if (nextUnitOfWork !== null) {
12467 // There's still remaining async work in this tree, but we ran out of time
12468 // in the current frame. Yield back to the renderer. Unless we're
12469 // interrupted by a higher priority update, we'll continue later from where
12470 // we left off.
12471 var _didCompleteRoot2 = false;
12472 stopWorkLoopTimer(interruptedBy, _didCompleteRoot2);
12473 interruptedBy = null;
12474 onYield(root);
12475 return;
12476 }
12477
12478 // We completed the whole tree.
12479 var didCompleteRoot = true;
12480 stopWorkLoopTimer(interruptedBy, didCompleteRoot);
12481 var rootWorkInProgress = root.current.alternate;
12482 (function () {
12483 if (!(rootWorkInProgress !== null)) {
12484 {
12485 throw ReactError('Finished root should have a work-in-progress. This error is likely caused by a bug in React. Please file an issue.');
12486 }
12487 }
12488 })();
12489
12490 // `nextRoot` points to the in-progress root. A non-null value indicates
12491 // that we're in the middle of an async render. Set it to null to indicate
12492 // there's no more work to be done in the current batch.
12493 nextRoot = null;
12494 interruptedBy = null;
12495
12496 if (nextRenderDidError) {
12497 // There was an error
12498 if (hasLowerPriorityWork(root, expirationTime)) {
12499 // There's lower priority work. If so, it may have the effect of fixing
12500 // the exception that was just thrown. Exit without committing. This is
12501 // similar to a suspend, but without a timeout because we're not waiting
12502 // for a promise to resolve. React will restart at the lower
12503 // priority level.
12504 markSuspendedPriorityLevel(root, expirationTime);
12505 var suspendedExpirationTime = expirationTime;
12506 var rootExpirationTime = root.expirationTime;
12507 onSuspend(root, rootWorkInProgress, suspendedExpirationTime, rootExpirationTime, -1 // Indicates no timeout
12508 );
12509 return;
12510 } else if (
12511 // There's no lower priority work, but we're rendering asynchronously.
12512 // Synchronously attempt to render the same level one more time. This is
12513 // similar to a suspend, but without a timeout because we're not waiting
12514 // for a promise to resolve.
12515 !root.didError && isYieldy) {
12516 root.didError = true;
12517 var _suspendedExpirationTime = root.nextExpirationTimeToWorkOn = expirationTime;
12518 var _rootExpirationTime = root.expirationTime = Sync;
12519 onSuspend(root, rootWorkInProgress, _suspendedExpirationTime, _rootExpirationTime, -1 // Indicates no timeout
12520 );
12521 return;
12522 }
12523 }
12524
12525 if (isYieldy && nextLatestAbsoluteTimeoutMs !== -1) {
12526 // The tree was suspended.
12527 var _suspendedExpirationTime2 = expirationTime;
12528 markSuspendedPriorityLevel(root, _suspendedExpirationTime2);
12529
12530 // Find the earliest uncommitted expiration time in the tree, including
12531 // work that is suspended. The timeout threshold cannot be longer than
12532 // the overall expiration.
12533 var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, expirationTime);
12534 var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime);
12535 if (earliestExpirationTimeMs < nextLatestAbsoluteTimeoutMs) {
12536 nextLatestAbsoluteTimeoutMs = earliestExpirationTimeMs;
12537 }
12538
12539 // Subtract the current time from the absolute timeout to get the number
12540 // of milliseconds until the timeout. In other words, convert an absolute
12541 // timestamp to a relative time. This is the value that is passed
12542 // to `setTimeout`.
12543 var currentTimeMs = expirationTimeToMs(requestCurrentTime$1());
12544 var msUntilTimeout = nextLatestAbsoluteTimeoutMs - currentTimeMs;
12545 msUntilTimeout = msUntilTimeout < 0 ? 0 : msUntilTimeout;
12546
12547 // TODO: Account for the Just Noticeable Difference
12548
12549 var _rootExpirationTime2 = root.expirationTime;
12550 onSuspend(root, rootWorkInProgress, _suspendedExpirationTime2, _rootExpirationTime2, msUntilTimeout);
12551 return;
12552 }
12553
12554 // Ready to commit.
12555 onComplete(root, rootWorkInProgress, expirationTime);
12556}
12557
12558function captureCommitPhaseError$1(sourceFiber, value) {
12559 var expirationTime = Sync;
12560 var fiber = sourceFiber.return;
12561 while (fiber !== null) {
12562 switch (fiber.tag) {
12563 case ClassComponent:
12564 var ctor = fiber.type;
12565 var instance = fiber.stateNode;
12566 if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary$1(instance)) {
12567 var errorInfo = createCapturedValue(value, sourceFiber);
12568 var update = createClassErrorUpdate(fiber, errorInfo, expirationTime);
12569 enqueueUpdate(fiber, update);
12570 scheduleWork$1(fiber, expirationTime);
12571 return;
12572 }
12573 break;
12574 case HostRoot:
12575 {
12576 var _errorInfo = createCapturedValue(value, sourceFiber);
12577 var _update = createRootErrorUpdate(fiber, _errorInfo, expirationTime);
12578 enqueueUpdate(fiber, _update);
12579 scheduleWork$1(fiber, expirationTime);
12580 return;
12581 }
12582 }
12583 fiber = fiber.return;
12584 }
12585
12586 if (sourceFiber.tag === HostRoot) {
12587 // Error was thrown at the root. There is no parent, so the root
12588 // itself should capture it.
12589 var rootFiber = sourceFiber;
12590 var _errorInfo2 = createCapturedValue(value, rootFiber);
12591 var _update2 = createRootErrorUpdate(rootFiber, _errorInfo2, expirationTime);
12592 enqueueUpdate(rootFiber, _update2);
12593 scheduleWork$1(rootFiber, expirationTime);
12594 }
12595}
12596
12597function computeThreadID(expirationTime, interactionThreadID) {
12598 // Interaction threads are unique per root and expiration time.
12599 return expirationTime * 1000 + interactionThreadID;
12600}
12601
12602function computeExpirationForFiber$1(currentTime, fiber) {
12603 var expirationTime = void 0;
12604 if (expirationContext !== NoWork) {
12605 // An explicit expiration context was set;
12606 expirationTime = expirationContext;
12607 } else if (isWorking) {
12608 if (isCommitting$1) {
12609 // Updates that occur during the commit phase should have sync priority
12610 // by default.
12611 expirationTime = Sync;
12612 } else {
12613 // Updates during the render phase should expire at the same time as
12614 // the work that is being rendered.
12615 expirationTime = nextRenderExpirationTime;
12616 }
12617 } else {
12618 // No explicit expiration context was set, and we're not currently
12619 // performing work. Calculate a new expiration time.
12620 if (fiber.mode & ConcurrentMode) {
12621 if (isBatchingInteractiveUpdates) {
12622 // This is an interactive update
12623 expirationTime = computeInteractiveExpiration(currentTime);
12624 } else {
12625 // This is an async update
12626 expirationTime = computeAsyncExpiration(currentTime);
12627 }
12628 // If we're in the middle of rendering a tree, do not update at the same
12629 // expiration time that is already rendering.
12630 if (nextRoot !== null && expirationTime === nextRenderExpirationTime) {
12631 expirationTime -= 1;
12632 }
12633 } else {
12634 // This is a sync update
12635 expirationTime = Sync;
12636 }
12637 }
12638 return expirationTime;
12639}
12640
12641function renderDidSuspend$1(root, absoluteTimeoutMs, suspendedTime) {
12642 // Schedule the timeout.
12643 if (absoluteTimeoutMs >= 0 && nextLatestAbsoluteTimeoutMs < absoluteTimeoutMs) {
12644 nextLatestAbsoluteTimeoutMs = absoluteTimeoutMs;
12645 }
12646}
12647
12648function renderDidError$1() {
12649 nextRenderDidError = true;
12650}
12651
12652function inferStartTimeFromExpirationTime$1(root, expirationTime) {
12653 // We don't know exactly when the update was scheduled, but we can infer an
12654 // approximate start time from the expiration time. First, find the earliest
12655 // uncommitted expiration time in the tree, including work that is suspended.
12656 // Then subtract the offset used to compute an async update's expiration time.
12657 // This will cause high priority (interactive) work to expire earlier than
12658 // necessary, but we can account for this by adjusting for the Just
12659 // Noticeable Difference.
12660 var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, expirationTime);
12661 var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime);
12662 return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;
12663}
12664
12665function pingSuspendedRoot$1(root, thenable, pingTime) {
12666 // A promise that previously suspended React from committing has resolved.
12667 // If React is still suspended, try again at the previous level (pingTime).
12668
12669 var pingCache = root.pingCache;
12670 if (pingCache !== null) {
12671 // The thenable resolved, so we no longer need to memoize, because it will
12672 // never be thrown again.
12673 pingCache.delete(thenable);
12674 }
12675
12676 if (nextRoot !== null && nextRenderExpirationTime === pingTime) {
12677 // Received a ping at the same priority level at which we're currently
12678 // rendering. Restart from the root.
12679 nextRoot = null;
12680 } else {
12681 // Confirm that the root is still suspended at this level. Otherwise exit.
12682 if (isPriorityLevelSuspended(root, pingTime)) {
12683 // Ping at the original level
12684 markPingedPriorityLevel(root, pingTime);
12685 var rootExpirationTime = root.expirationTime;
12686 if (rootExpirationTime !== NoWork) {
12687 requestWork(root, rootExpirationTime);
12688 }
12689 }
12690 }
12691}
12692
12693function retryTimedOutBoundary$1(boundaryFiber) {
12694 var currentTime = requestCurrentTime$1();
12695 var retryTime = computeExpirationForFiber$1(currentTime, boundaryFiber);
12696 var root = scheduleWorkToRoot(boundaryFiber, retryTime);
12697 if (root !== null) {
12698 markPendingPriorityLevel(root, retryTime);
12699 var rootExpirationTime = root.expirationTime;
12700 if (rootExpirationTime !== NoWork) {
12701 requestWork(root, rootExpirationTime);
12702 }
12703 }
12704}
12705
12706function resolveRetryThenable$1(boundaryFiber, thenable) {
12707 // The boundary fiber (a Suspense component) previously timed out and was
12708 // rendered in its fallback state. One of the promises that suspended it has
12709 // resolved, which means at least part of the tree was likely unblocked. Try
12710 var retryCache = void 0;
12711 if (enableSuspenseServerRenderer) {
12712 switch (boundaryFiber.tag) {
12713 case SuspenseComponent:
12714 retryCache = boundaryFiber.stateNode;
12715 break;
12716 case DehydratedSuspenseComponent:
12717 retryCache = boundaryFiber.memoizedState;
12718 break;
12719 default:
12720 (function () {
12721 {
12722 {
12723 throw ReactError('Pinged unknown suspense boundary type. This is probably a bug in React.');
12724 }
12725 }
12726 })();
12727 }
12728 } else {
12729 retryCache = boundaryFiber.stateNode;
12730 }
12731 if (retryCache !== null) {
12732 // The thenable resolved, so we no longer need to memoize, because it will
12733 // never be thrown again.
12734 retryCache.delete(thenable);
12735 }
12736
12737 retryTimedOutBoundary$1(boundaryFiber);
12738}
12739
12740function scheduleWorkToRoot(fiber, expirationTime) {
12741 recordScheduleUpdate();
12742
12743 {
12744 if (fiber.tag === ClassComponent) {
12745 var instance = fiber.stateNode;
12746 warnAboutInvalidUpdates(instance);
12747 }
12748 }
12749
12750 // Update the source fiber's expiration time
12751 if (fiber.expirationTime < expirationTime) {
12752 fiber.expirationTime = expirationTime;
12753 }
12754 var alternate = fiber.alternate;
12755 if (alternate !== null && alternate.expirationTime < expirationTime) {
12756 alternate.expirationTime = expirationTime;
12757 }
12758 // Walk the parent path to the root and update the child expiration time.
12759 var node = fiber.return;
12760 var root = null;
12761 if (node === null && fiber.tag === HostRoot) {
12762 root = fiber.stateNode;
12763 } else {
12764 while (node !== null) {
12765 alternate = node.alternate;
12766 if (node.childExpirationTime < expirationTime) {
12767 node.childExpirationTime = expirationTime;
12768 if (alternate !== null && alternate.childExpirationTime < expirationTime) {
12769 alternate.childExpirationTime = expirationTime;
12770 }
12771 } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {
12772 alternate.childExpirationTime = expirationTime;
12773 }
12774 if (node.return === null && node.tag === HostRoot) {
12775 root = node.stateNode;
12776 break;
12777 }
12778 node = node.return;
12779 }
12780 }
12781
12782 if (enableSchedulerTracing) {
12783 if (root !== null) {
12784 var interactions = __interactionsRef.current;
12785 if (interactions.size > 0) {
12786 var pendingInteractionMap = root.pendingInteractionMap;
12787 var pendingInteractions = pendingInteractionMap.get(expirationTime);
12788 if (pendingInteractions != null) {
12789 interactions.forEach(function (interaction) {
12790 if (!pendingInteractions.has(interaction)) {
12791 // Update the pending async work count for previously unscheduled interaction.
12792 interaction.__count++;
12793 }
12794
12795 pendingInteractions.add(interaction);
12796 });
12797 } else {
12798 pendingInteractionMap.set(expirationTime, new Set(interactions));
12799
12800 // Update the pending async work count for the current interactions.
12801 interactions.forEach(function (interaction) {
12802 interaction.__count++;
12803 });
12804 }
12805
12806 var subscriber = __subscriberRef.current;
12807 if (subscriber !== null) {
12808 var threadID = computeThreadID(expirationTime, root.interactionThreadID);
12809 subscriber.onWorkScheduled(interactions, threadID);
12810 }
12811 }
12812 }
12813 }
12814 return root;
12815}
12816
12817// in a test-like environment, we want to warn if dispatchAction() is
12818// called outside of a TestUtils.act(...)/batchedUpdates/render call.
12819// so we have a a step counter for when we descend/ascend from
12820// act() calls, and test on it for when to warn
12821// It's a tuple with a single value. Look for shared/createAct to
12822// see how we change the value inside act() calls
12823
12824function warnIfNotCurrentlyActingUpdatesInDev$1(fiber) {
12825 {
12826 if (isBatchingUpdates === false && isRendering === false && ReactShouldWarnActingUpdates.current === false) {
12827 warningWithoutStack$1(false, 'An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be wrapped into act(...):\n\n' + 'act(() => {\n' + ' /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see in the browser." + ' Learn more at https://fb.me/react-wrap-tests-with-act' + '%s', getComponentName(fiber.type), getStackByFiberInDevAndProd(fiber));
12828 }
12829 }
12830}
12831
12832function scheduleWork$1(fiber, expirationTime) {
12833 var root = scheduleWorkToRoot(fiber, expirationTime);
12834 if (root === null) {
12835 {
12836 switch (fiber.tag) {
12837 case ClassComponent:
12838 warnAboutUpdateOnUnmounted(fiber, true);
12839 break;
12840 case FunctionComponent:
12841 case ForwardRef:
12842 case MemoComponent:
12843 case SimpleMemoComponent:
12844 warnAboutUpdateOnUnmounted(fiber, false);
12845 break;
12846 }
12847 }
12848 return;
12849 }
12850
12851 if (!isWorking && nextRenderExpirationTime !== NoWork && expirationTime > nextRenderExpirationTime) {
12852 // This is an interruption. (Used for performance tracking.)
12853 interruptedBy = fiber;
12854 resetStack();
12855 }
12856 markPendingPriorityLevel(root, expirationTime);
12857 if (
12858 // If we're in the render phase, we don't need to schedule this root
12859 // for an update, because we'll do it before we exit...
12860 !isWorking || isCommitting$1 ||
12861 // ...unless this is a different root than the one we're rendering.
12862 nextRoot !== root) {
12863 var rootExpirationTime = root.expirationTime;
12864 requestWork(root, rootExpirationTime);
12865 }
12866 if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
12867 // Reset this back to zero so subsequent updates don't throw.
12868 nestedUpdateCount = 0;
12869 (function () {
12870 {
12871 {
12872 throw ReactError('Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.');
12873 }
12874 }
12875 })();
12876 }
12877 {
12878 if (isInPassiveEffectDEV && nestedPassiveEffectCountDEV > NESTED_PASSIVE_UPDATE_LIMIT) {
12879 nestedPassiveEffectCountDEV = 0;
12880 warning$1(false, 'Maximum update depth exceeded. This can happen when a ' + 'component calls setState inside useEffect, but ' + "useEffect either doesn't have a dependency array, or " + 'one of the dependencies changes on every render.');
12881 }
12882 }
12883}
12884
12885function syncUpdates$1(fn, a, b, c, d) {
12886 var previousExpirationContext = expirationContext;
12887 expirationContext = Sync;
12888 try {
12889 return fn(a, b, c, d);
12890 } finally {
12891 expirationContext = previousExpirationContext;
12892 }
12893}
12894
12895// TODO: Everything below this is written as if it has been lifted to the
12896// renderers. I'll do this in a follow-up.
12897
12898// Linked-list of roots
12899var firstScheduledRoot = null;
12900var lastScheduledRoot = null;
12901
12902var callbackExpirationTime = NoWork;
12903var callbackID = void 0;
12904var isRendering = false;
12905var nextFlushedRoot = null;
12906var nextFlushedExpirationTime = NoWork;
12907var hasUnhandledError = false;
12908var unhandledError = null;
12909
12910var isBatchingUpdates = false;
12911var isUnbatchingUpdates = false;
12912var isBatchingInteractiveUpdates = false;
12913
12914var completedBatches = null;
12915
12916var originalStartTimeMs = now$1();
12917var currentRendererTime = msToExpirationTime(originalStartTimeMs);
12918var currentSchedulerTime = currentRendererTime;
12919
12920// Use these to prevent an infinite loop of nested updates
12921var NESTED_UPDATE_LIMIT = 50;
12922var nestedUpdateCount = 0;
12923var lastCommittedRootDuringThisBatch = null;
12924
12925// Similar, but for useEffect infinite loops. These are DEV-only.
12926var NESTED_PASSIVE_UPDATE_LIMIT = 50;
12927var nestedPassiveEffectCountDEV = void 0;
12928var isInPassiveEffectDEV = void 0;
12929{
12930 nestedPassiveEffectCountDEV = 0;
12931 isInPassiveEffectDEV = false;
12932}
12933
12934function recomputeCurrentRendererTime() {
12935 var currentTimeMs = now$1() - originalStartTimeMs;
12936 currentRendererTime = msToExpirationTime(currentTimeMs);
12937}
12938
12939function scheduleCallbackWithExpirationTime(root, expirationTime) {
12940 if (callbackExpirationTime !== NoWork) {
12941 // A callback is already scheduled. Check its expiration time (timeout).
12942 if (expirationTime < callbackExpirationTime) {
12943 // Existing callback has sufficient timeout. Exit.
12944 return;
12945 } else {
12946 if (callbackID !== null) {
12947 // Existing callback has insufficient timeout. Cancel and schedule a
12948 // new one.
12949 cancelCallback$1(callbackID);
12950 }
12951 }
12952 // The request callback timer is already running. Don't start a new one.
12953 } else {
12954 startRequestCallbackTimer();
12955 }
12956
12957 callbackExpirationTime = expirationTime;
12958 var currentMs = now$1() - originalStartTimeMs;
12959 var expirationTimeMs = expirationTimeToMs(expirationTime);
12960 var timeout = expirationTimeMs - currentMs;
12961 var priorityLevel = getCurrentPriorityLevel$1();
12962 callbackID = scheduleCallback$1(priorityLevel, performAsyncWork, { timeout: timeout });
12963}
12964
12965// For every call to renderRoot, one of onFatal, onComplete, onSuspend, and
12966// onYield is called upon exiting. We use these in lieu of returning a tuple.
12967// I've also chosen not to inline them into renderRoot because these will
12968// eventually be lifted into the renderer.
12969function onFatal(root) {
12970 root.finishedWork = null;
12971}
12972
12973function onComplete(root, finishedWork, expirationTime) {
12974 root.pendingCommitExpirationTime = expirationTime;
12975 root.finishedWork = finishedWork;
12976}
12977
12978function onSuspend(root, finishedWork, suspendedExpirationTime, rootExpirationTime, msUntilTimeout) {
12979 root.expirationTime = rootExpirationTime;
12980 if (msUntilTimeout === 0 && (disableYielding || !shouldYield$1())) {
12981 // Don't wait an additional tick. Commit the tree immediately.
12982 root.pendingCommitExpirationTime = suspendedExpirationTime;
12983 root.finishedWork = finishedWork;
12984 } else if (msUntilTimeout > 0) {
12985 // Wait `msUntilTimeout` milliseconds before committing.
12986 root.timeoutHandle = scheduleTimeout(onTimeout.bind(null, root, finishedWork, suspendedExpirationTime), msUntilTimeout);
12987 }
12988}
12989
12990function onYield(root) {
12991 root.finishedWork = null;
12992}
12993
12994function onTimeout(root, finishedWork, suspendedExpirationTime) {
12995 // The root timed out. Commit it.
12996 root.pendingCommitExpirationTime = suspendedExpirationTime;
12997 root.finishedWork = finishedWork;
12998 // Read the current time before entering the commit phase. We can be
12999 // certain this won't cause tearing related to batching of event updates
13000 // because we're at the top of a timer event.
13001 recomputeCurrentRendererTime();
13002 currentSchedulerTime = currentRendererTime;
13003 flushRoot$1(root, suspendedExpirationTime);
13004}
13005
13006function onCommit(root, expirationTime) {
13007 root.expirationTime = expirationTime;
13008 root.finishedWork = null;
13009}
13010
13011function requestCurrentTime$1() {
13012 // requestCurrentTime is called by the scheduler to compute an expiration
13013 // time.
13014 //
13015 // Expiration times are computed by adding to the current time (the start
13016 // time). However, if two updates are scheduled within the same event, we
13017 // should treat their start times as simultaneous, even if the actual clock
13018 // time has advanced between the first and second call.
13019
13020 // In other words, because expiration times determine how updates are batched,
13021 // we want all updates of like priority that occur within the same event to
13022 // receive the same expiration time. Otherwise we get tearing.
13023 //
13024 // We keep track of two separate times: the current "renderer" time and the
13025 // current "scheduler" time. The renderer time can be updated whenever; it
13026 // only exists to minimize the calls performance.now.
13027 //
13028 // But the scheduler time can only be updated if there's no pending work, or
13029 // if we know for certain that we're not in the middle of an event.
13030
13031 if (isRendering) {
13032 // We're already rendering. Return the most recently read time.
13033 return currentSchedulerTime;
13034 }
13035 // Check if there's pending work.
13036 findHighestPriorityRoot();
13037 if (nextFlushedExpirationTime === NoWork || nextFlushedExpirationTime === Never) {
13038 // If there's no pending work, or if the pending work is offscreen, we can
13039 // read the current time without risk of tearing.
13040 recomputeCurrentRendererTime();
13041 currentSchedulerTime = currentRendererTime;
13042 return currentSchedulerTime;
13043 }
13044 // There's already pending work. We might be in the middle of a browser
13045 // event. If we were to read the current time, it could cause multiple updates
13046 // within the same event to receive different expiration times, leading to
13047 // tearing. Return the last read time. During the next idle callback, the
13048 // time will be updated.
13049 return currentSchedulerTime;
13050}
13051
13052// requestWork is called by the scheduler whenever a root receives an update.
13053// It's up to the renderer to call renderRoot at some point in the future.
13054function requestWork(root, expirationTime) {
13055 addRootToSchedule(root, expirationTime);
13056 if (isRendering) {
13057 // Prevent reentrancy. Remaining work will be scheduled at the end of
13058 // the currently rendering batch.
13059 return;
13060 }
13061
13062 if (isBatchingUpdates) {
13063 // Flush work at the end of the batch.
13064 if (isUnbatchingUpdates) {
13065 // ...unless we're inside unbatchedUpdates, in which case we should
13066 // flush it now.
13067 nextFlushedRoot = root;
13068 nextFlushedExpirationTime = Sync;
13069 performWorkOnRoot(root, Sync, false);
13070 }
13071 return;
13072 }
13073
13074 // TODO: Get rid of Sync and use current time?
13075 if (expirationTime === Sync) {
13076 performSyncWork();
13077 } else {
13078 scheduleCallbackWithExpirationTime(root, expirationTime);
13079 }
13080}
13081
13082function addRootToSchedule(root, expirationTime) {
13083 // Add the root to the schedule.
13084 // Check if this root is already part of the schedule.
13085 if (root.nextScheduledRoot === null) {
13086 // This root is not already scheduled. Add it.
13087 root.expirationTime = expirationTime;
13088 if (lastScheduledRoot === null) {
13089 firstScheduledRoot = lastScheduledRoot = root;
13090 root.nextScheduledRoot = root;
13091 } else {
13092 lastScheduledRoot.nextScheduledRoot = root;
13093 lastScheduledRoot = root;
13094 lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
13095 }
13096 } else {
13097 // This root is already scheduled, but its priority may have increased.
13098 var remainingExpirationTime = root.expirationTime;
13099 if (expirationTime > remainingExpirationTime) {
13100 // Update the priority.
13101 root.expirationTime = expirationTime;
13102 }
13103 }
13104}
13105
13106function findHighestPriorityRoot() {
13107 var highestPriorityWork = NoWork;
13108 var highestPriorityRoot = null;
13109 if (lastScheduledRoot !== null) {
13110 var previousScheduledRoot = lastScheduledRoot;
13111 var root = firstScheduledRoot;
13112 while (root !== null) {
13113 var remainingExpirationTime = root.expirationTime;
13114 if (remainingExpirationTime === NoWork) {
13115 // This root no longer has work. Remove it from the scheduler.
13116
13117 // TODO: This check is redudant, but Flow is confused by the branch
13118 // below where we set lastScheduledRoot to null, even though we break
13119 // from the loop right after.
13120 (function () {
13121 if (!(previousScheduledRoot !== null && lastScheduledRoot !== null)) {
13122 {
13123 throw ReactError('Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue.');
13124 }
13125 }
13126 })();
13127 if (root === root.nextScheduledRoot) {
13128 // This is the only root in the list.
13129 root.nextScheduledRoot = null;
13130 firstScheduledRoot = lastScheduledRoot = null;
13131 break;
13132 } else if (root === firstScheduledRoot) {
13133 // This is the first root in the list.
13134 var next = root.nextScheduledRoot;
13135 firstScheduledRoot = next;
13136 lastScheduledRoot.nextScheduledRoot = next;
13137 root.nextScheduledRoot = null;
13138 } else if (root === lastScheduledRoot) {
13139 // This is the last root in the list.
13140 lastScheduledRoot = previousScheduledRoot;
13141 lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
13142 root.nextScheduledRoot = null;
13143 break;
13144 } else {
13145 previousScheduledRoot.nextScheduledRoot = root.nextScheduledRoot;
13146 root.nextScheduledRoot = null;
13147 }
13148 root = previousScheduledRoot.nextScheduledRoot;
13149 } else {
13150 if (remainingExpirationTime > highestPriorityWork) {
13151 // Update the priority, if it's higher
13152 highestPriorityWork = remainingExpirationTime;
13153 highestPriorityRoot = root;
13154 }
13155 if (root === lastScheduledRoot) {
13156 break;
13157 }
13158 if (highestPriorityWork === Sync) {
13159 // Sync is highest priority by definition so
13160 // we can stop searching.
13161 break;
13162 }
13163 previousScheduledRoot = root;
13164 root = root.nextScheduledRoot;
13165 }
13166 }
13167 }
13168
13169 nextFlushedRoot = highestPriorityRoot;
13170 nextFlushedExpirationTime = highestPriorityWork;
13171}
13172
13173function performAsyncWork(didTimeout) {
13174 if (didTimeout) {
13175 // The callback timed out. That means at least one update has expired.
13176 // Iterate through the root schedule. If they contain expired work, set
13177 // the next render expiration time to the current time. This has the effect
13178 // of flushing all expired work in a single batch, instead of flushing each
13179 // level one at a time.
13180 if (firstScheduledRoot !== null) {
13181 recomputeCurrentRendererTime();
13182 var root = firstScheduledRoot;
13183 do {
13184 didExpireAtExpirationTime(root, currentRendererTime);
13185 // The root schedule is circular, so this is never null.
13186 root = root.nextScheduledRoot;
13187 } while (root !== firstScheduledRoot);
13188 }
13189 }
13190
13191 // Keep working on roots until there's no more work, or until there's a higher
13192 // priority event.
13193 findHighestPriorityRoot();
13194
13195 if (disableYielding) {
13196 // Just do it all
13197 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork) {
13198 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false);
13199 findHighestPriorityRoot();
13200 }
13201 } else {
13202 recomputeCurrentRendererTime();
13203 currentSchedulerTime = currentRendererTime;
13204
13205 if (enableUserTimingAPI) {
13206 var didExpire = nextFlushedExpirationTime > currentRendererTime;
13207 var timeout = expirationTimeToMs(nextFlushedExpirationTime);
13208 stopRequestCallbackTimer(didExpire, timeout);
13209 }
13210
13211 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && !(shouldYield$1() && currentRendererTime > nextFlushedExpirationTime)) {
13212 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, currentRendererTime > nextFlushedExpirationTime);
13213 findHighestPriorityRoot();
13214 recomputeCurrentRendererTime();
13215 currentSchedulerTime = currentRendererTime;
13216 }
13217 }
13218
13219 // We're done flushing work. Either we ran out of time in this callback,
13220 // or there's no more work left with sufficient priority.
13221
13222 // If we're inside a callback, set this to false since we just completed it.
13223 callbackExpirationTime = NoWork;
13224 callbackID = null;
13225
13226 // If there's work left over, schedule a new callback.
13227 if (nextFlushedExpirationTime !== NoWork) {
13228 scheduleCallbackWithExpirationTime(nextFlushedRoot, nextFlushedExpirationTime);
13229 }
13230
13231 // Clean-up.
13232 finishRendering();
13233}
13234
13235function performSyncWork() {
13236 performWork(Sync);
13237}
13238
13239function performWork(minExpirationTime) {
13240 // Keep working on roots until there's no more work, or until there's a higher
13241 // priority event.
13242 findHighestPriorityRoot();
13243
13244 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && minExpirationTime <= nextFlushedExpirationTime) {
13245 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false);
13246 findHighestPriorityRoot();
13247 }
13248
13249 // We're done flushing work. Either we ran out of time in this callback,
13250 // or there's no more work left with sufficient priority.
13251
13252 // If there's work left over, schedule a new callback.
13253 if (nextFlushedExpirationTime !== NoWork) {
13254 scheduleCallbackWithExpirationTime(nextFlushedRoot, nextFlushedExpirationTime);
13255 }
13256
13257 // Clean-up.
13258 finishRendering();
13259}
13260
13261function flushRoot$1(root, expirationTime) {
13262 (function () {
13263 if (!!isRendering) {
13264 {
13265 throw ReactError('work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method.');
13266 }
13267 }
13268 })();
13269 // Perform work on root as if the given expiration time is the current time.
13270 // This has the effect of synchronously flushing all work up to and
13271 // including the given time.
13272 nextFlushedRoot = root;
13273 nextFlushedExpirationTime = expirationTime;
13274 performWorkOnRoot(root, expirationTime, false);
13275 // Flush any sync work that was scheduled by lifecycles
13276 performSyncWork();
13277}
13278
13279function finishRendering() {
13280 nestedUpdateCount = 0;
13281 lastCommittedRootDuringThisBatch = null;
13282
13283 {
13284 if (rootWithPendingPassiveEffects === null) {
13285 nestedPassiveEffectCountDEV = 0;
13286 }
13287 }
13288
13289 if (completedBatches !== null) {
13290 var batches = completedBatches;
13291 completedBatches = null;
13292 for (var i = 0; i < batches.length; i++) {
13293 var batch = batches[i];
13294 try {
13295 batch._onComplete();
13296 } catch (error) {
13297 if (!hasUnhandledError) {
13298 hasUnhandledError = true;
13299 unhandledError = error;
13300 }
13301 }
13302 }
13303 }
13304
13305 if (hasUnhandledError) {
13306 var error = unhandledError;
13307 unhandledError = null;
13308 hasUnhandledError = false;
13309 throw error;
13310 }
13311}
13312
13313function performWorkOnRoot(root, expirationTime, isYieldy) {
13314 (function () {
13315 if (!!isRendering) {
13316 {
13317 throw ReactError('performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.');
13318 }
13319 }
13320 })();
13321
13322 isRendering = true;
13323
13324 // Check if this is async work or sync/expired work.
13325 if (!isYieldy) {
13326 // Flush work without yielding.
13327 // TODO: Non-yieldy work does not necessarily imply expired work. A renderer
13328 // may want to perform some work without yielding, but also without
13329 // requiring the root to complete (by triggering placeholders).
13330
13331 var finishedWork = root.finishedWork;
13332 if (finishedWork !== null) {
13333 // This root is already complete. We can commit it.
13334 completeRoot(root, finishedWork, expirationTime);
13335 } else {
13336 root.finishedWork = null;
13337 // If this root previously suspended, clear its existing timeout, since
13338 // we're about to try rendering again.
13339 var timeoutHandle = root.timeoutHandle;
13340 if (timeoutHandle !== noTimeout) {
13341 root.timeoutHandle = noTimeout;
13342 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
13343 cancelTimeout(timeoutHandle);
13344 }
13345 renderRoot(root, isYieldy);
13346 finishedWork = root.finishedWork;
13347 if (finishedWork !== null) {
13348 // We've completed the root. Commit it.
13349 completeRoot(root, finishedWork, expirationTime);
13350 }
13351 }
13352 } else {
13353 // Flush async work.
13354 var _finishedWork = root.finishedWork;
13355 if (_finishedWork !== null) {
13356 // This root is already complete. We can commit it.
13357 completeRoot(root, _finishedWork, expirationTime);
13358 } else {
13359 root.finishedWork = null;
13360 // If this root previously suspended, clear its existing timeout, since
13361 // we're about to try rendering again.
13362 var _timeoutHandle = root.timeoutHandle;
13363 if (_timeoutHandle !== noTimeout) {
13364 root.timeoutHandle = noTimeout;
13365 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
13366 cancelTimeout(_timeoutHandle);
13367 }
13368 renderRoot(root, isYieldy);
13369 _finishedWork = root.finishedWork;
13370 if (_finishedWork !== null) {
13371 // We've completed the root. Check the if we should yield one more time
13372 // before committing.
13373 if (!shouldYield$1()) {
13374 // Still time left. Commit the root.
13375 completeRoot(root, _finishedWork, expirationTime);
13376 } else {
13377 // There's no time left. Mark this root as complete. We'll come
13378 // back and commit it later.
13379 root.finishedWork = _finishedWork;
13380 }
13381 }
13382 }
13383 }
13384
13385 isRendering = false;
13386}
13387
13388function completeRoot(root, finishedWork, expirationTime) {
13389 // Check if there's a batch that matches this expiration time.
13390 var firstBatch = root.firstBatch;
13391 if (firstBatch !== null && firstBatch._expirationTime >= expirationTime) {
13392 if (completedBatches === null) {
13393 completedBatches = [firstBatch];
13394 } else {
13395 completedBatches.push(firstBatch);
13396 }
13397 if (firstBatch._defer) {
13398 // This root is blocked from committing by a batch. Unschedule it until
13399 // we receive another update.
13400 root.finishedWork = finishedWork;
13401 root.expirationTime = NoWork;
13402 return;
13403 }
13404 }
13405
13406 // Commit the root.
13407 root.finishedWork = null;
13408
13409 // Check if this is a nested update (a sync update scheduled during the
13410 // commit phase).
13411 if (root === lastCommittedRootDuringThisBatch) {
13412 // If the next root is the same as the previous root, this is a nested
13413 // update. To prevent an infinite loop, increment the nested update count.
13414 nestedUpdateCount++;
13415 } else {
13416 // Reset whenever we switch roots.
13417 lastCommittedRootDuringThisBatch = root;
13418 nestedUpdateCount = 0;
13419 }
13420 commitRoot(root, finishedWork);
13421}
13422
13423function onUncaughtError$1(error) {
13424 (function () {
13425 if (!(nextFlushedRoot !== null)) {
13426 {
13427 throw ReactError('Should be working on a root. This error is likely caused by a bug in React. Please file an issue.');
13428 }
13429 }
13430 })();
13431 // Unschedule this root so we don't work on it again until there's
13432 // another update.
13433 nextFlushedRoot.expirationTime = NoWork;
13434 if (!hasUnhandledError) {
13435 hasUnhandledError = true;
13436 unhandledError = error;
13437 }
13438}
13439
13440// TODO: Batching should be implemented at the renderer level, not inside
13441// the reconciler.
13442function batchedUpdates$1(fn, a) {
13443 var previousIsBatchingUpdates = isBatchingUpdates;
13444 isBatchingUpdates = true;
13445 try {
13446 return fn(a);
13447 } finally {
13448 isBatchingUpdates = previousIsBatchingUpdates;
13449 if (!isBatchingUpdates && !isRendering) {
13450 performSyncWork();
13451 }
13452 }
13453}
13454
13455// TODO: Batching should be implemented at the renderer level, not within
13456// the reconciler.
13457function flushSync$1(fn, a) {
13458 (function () {
13459 if (!!isRendering) {
13460 {
13461 throw ReactError('flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.');
13462 }
13463 }
13464 })();
13465 var previousIsBatchingUpdates = isBatchingUpdates;
13466 isBatchingUpdates = true;
13467 try {
13468 return syncUpdates$1(fn, a);
13469 } finally {
13470 isBatchingUpdates = previousIsBatchingUpdates;
13471 performSyncWork();
13472 }
13473}
13474
13475// TODO: Ahaha Andrew is bad at spellling
13476// DEV stuff
13477var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher;
13478var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
13479var ReactShouldWarnActingUpdates$1 = ReactSharedInternals.ReactShouldWarnActingUpdates;
13480
13481var NotWorking = 0;
13482var BatchedPhase = 1;
13483var LegacyUnbatchedPhase = 2;
13484var FlushSyncPhase = 3;
13485var RenderPhase = 4;
13486var CommitPhase = 5;
13487
13488var RootIncomplete = 0;
13489var RootErrored = 1;
13490var RootSuspended = 2;
13491var RootCompleted = 3;
13492
13493// The phase of work we're currently in
13494var workPhase = NotWorking;
13495// The root we're working on
13496var workInProgressRoot = null;
13497// The fiber we're working on
13498var workInProgress = null;
13499// The expiration time we're rendering
13500var renderExpirationTime$1 = NoWork;
13501// Whether to root completed, errored, suspended, etc.
13502var workInProgressRootExitStatus = RootIncomplete;
13503var workInProgressRootAbsoluteTimeoutMs = -1;
13504
13505var nextEffect$1 = null;
13506var hasUncaughtError = false;
13507var firstUncaughtError = null;
13508var legacyErrorBoundariesThatAlreadyFailed$1 = null;
13509
13510var rootDoesHavePassiveEffects = false;
13511var rootWithPendingPassiveEffects$1 = null;
13512var pendingPassiveEffectsExpirationTime = NoWork;
13513
13514var rootsWithPendingDiscreteUpdates = null;
13515
13516// Use these to prevent an infinite loop of nested updates
13517var NESTED_UPDATE_LIMIT$1 = 50;
13518var nestedUpdateCount$1 = 0;
13519var rootWithNestedUpdates = null;
13520
13521var NESTED_PASSIVE_UPDATE_LIMIT$1 = 50;
13522var nestedPassiveUpdateCount = 0;
13523
13524var interruptedBy$1 = null;
13525
13526// Expiration times are computed by adding to the current time (the start
13527// time). However, if two updates are scheduled within the same event, we
13528// should treat their start times as simultaneous, even if the actual clock
13529// time has advanced between the first and second call.
13530
13531// In other words, because expiration times determine how updates are batched,
13532// we want all updates of like priority that occur within the same event to
13533// receive the same expiration time. Otherwise we get tearing.
13534var currentEventTime = NoWork;
13535
13536function requestCurrentTime$2() {
13537 if (workPhase === RenderPhase || workPhase === CommitPhase) {
13538 // We're inside React, so it's fine to read the actual time.
13539 return msToExpirationTime(now());
13540 }
13541 // We're not inside React, so we may be in the middle of a browser event.
13542 if (currentEventTime !== NoWork) {
13543 // Use the same start time for all updates until we enter React again.
13544 return currentEventTime;
13545 }
13546 // This is the first update since React yielded. Compute a new start time.
13547 currentEventTime = msToExpirationTime(now());
13548 return currentEventTime;
13549}
13550
13551function computeExpirationForFiber$2(currentTime, fiber) {
13552 if ((fiber.mode & ConcurrentMode) === NoContext) {
13553 return Sync;
13554 }
13555
13556 if (workPhase === RenderPhase) {
13557 // Use whatever time we're already rendering
13558 return renderExpirationTime$1;
13559 }
13560
13561 // Compute an expiration time based on the Scheduler priority.
13562 var expirationTime = void 0;
13563 var priorityLevel = getCurrentPriorityLevel();
13564 switch (priorityLevel) {
13565 case ImmediatePriority:
13566 expirationTime = Sync;
13567 break;
13568 case UserBlockingPriority:
13569 // TODO: Rename this to computeUserBlockingExpiration
13570 expirationTime = computeInteractiveExpiration(currentTime);
13571 break;
13572 case NormalPriority:
13573 case LowPriority:
13574 // TODO: Handle LowPriority
13575 // TODO: Rename this to... something better.
13576 expirationTime = computeAsyncExpiration(currentTime);
13577 break;
13578 case IdlePriority:
13579 expirationTime = Never;
13580 break;
13581 default:
13582 (function () {
13583 {
13584 {
13585 throw ReactError('Expected a valid priority level');
13586 }
13587 }
13588 })();
13589 }
13590
13591 // If we're in the middle of rendering a tree, do not update at the same
13592 // expiration time that is already rendering.
13593 if (workInProgressRoot !== null && expirationTime === renderExpirationTime$1) {
13594 // This is a trick to move this update into a separate batch
13595 expirationTime -= 1;
13596 }
13597
13598 return expirationTime;
13599}
13600
13601
13602
13603function scheduleUpdateOnFiber(fiber, expirationTime) {
13604 checkForNestedUpdates();
13605 warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber);
13606
13607 var root = markUpdateTimeFromFiberToRoot(fiber, expirationTime);
13608 if (root === null) {
13609 warnAboutUpdateOnUnmountedFiberInDEV(fiber);
13610 return;
13611 }
13612
13613 root.pingTime = NoWork;
13614
13615 checkForInterruption(fiber, expirationTime);
13616 recordScheduleUpdate();
13617
13618 if (expirationTime === Sync) {
13619 if (workPhase === LegacyUnbatchedPhase) {
13620 // This is a legacy edge case. The initial mount of a ReactDOM.render-ed
13621 // root inside of batchedUpdates should be synchronous, but layout updates
13622 // should be deferred until the end of the batch.
13623 var callback = renderRoot$1(root, Sync, true);
13624 while (callback !== null) {
13625 callback = callback(true);
13626 }
13627 } else {
13628 scheduleCallbackForRoot(root, ImmediatePriority, Sync);
13629 if (workPhase === NotWorking) {
13630 // Flush the synchronous work now, wnless we're already working or inside
13631 // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
13632 // scheduleCallbackForFiber to preserve the ability to schedule a callback
13633 // without immediately flushing it. We only do this for user-initated
13634 // updates, to preserve historical behavior of sync mode.
13635 flushImmediateQueue();
13636 }
13637 }
13638 } else {
13639 // TODO: computeExpirationForFiber also reads the priority. Pass the
13640 // priority as an argument to that function and this one.
13641 var priorityLevel = getCurrentPriorityLevel();
13642 if (priorityLevel === UserBlockingPriority) {
13643 // This is the result of a discrete event. Track the lowest priority
13644 // discrete update per root so we can flush them early, if needed.
13645 if (rootsWithPendingDiscreteUpdates === null) {
13646 rootsWithPendingDiscreteUpdates = new Map([[root, expirationTime]]);
13647 } else {
13648 var lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root);
13649 if (lastDiscreteTime === undefined || lastDiscreteTime > expirationTime) {
13650 rootsWithPendingDiscreteUpdates.set(root, expirationTime);
13651 }
13652 }
13653 }
13654 scheduleCallbackForRoot(root, priorityLevel, expirationTime);
13655 }
13656}
13657var scheduleWork$2 = scheduleUpdateOnFiber;
13658
13659// This is split into a separate function so we can mark a fiber with pending
13660// work without treating it as a typical update that originates from an event;
13661// e.g. retrying a Suspense boundary isn't an update, but it does schedule work
13662// on a fiber.
13663function markUpdateTimeFromFiberToRoot(fiber, expirationTime) {
13664 // Update the source fiber's expiration time
13665 if (fiber.expirationTime < expirationTime) {
13666 fiber.expirationTime = expirationTime;
13667 }
13668 var alternate = fiber.alternate;
13669 if (alternate !== null && alternate.expirationTime < expirationTime) {
13670 alternate.expirationTime = expirationTime;
13671 }
13672 // Walk the parent path to the root and update the child expiration time.
13673 var node = fiber.return;
13674 var root = null;
13675 if (node === null && fiber.tag === HostRoot) {
13676 root = fiber.stateNode;
13677 } else {
13678 while (node !== null) {
13679 alternate = node.alternate;
13680 if (node.childExpirationTime < expirationTime) {
13681 node.childExpirationTime = expirationTime;
13682 if (alternate !== null && alternate.childExpirationTime < expirationTime) {
13683 alternate.childExpirationTime = expirationTime;
13684 }
13685 } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {
13686 alternate.childExpirationTime = expirationTime;
13687 }
13688 if (node.return === null && node.tag === HostRoot) {
13689 root = node.stateNode;
13690 break;
13691 }
13692 node = node.return;
13693 }
13694 }
13695
13696 if (root !== null) {
13697 // Update the first and last pending expiration times in this root
13698 var firstPendingTime = root.firstPendingTime;
13699 if (expirationTime > firstPendingTime) {
13700 root.firstPendingTime = expirationTime;
13701 }
13702 var lastPendingTime = root.lastPendingTime;
13703 if (lastPendingTime === NoWork || expirationTime < lastPendingTime) {
13704 root.lastPendingTime = expirationTime;
13705 }
13706 }
13707
13708 return root;
13709}
13710
13711// Use this function, along with runRootCallback, to ensure that only a single
13712// callback per root is scheduled. It's still possible to call renderRoot
13713// directly, but scheduling via this function helps avoid excessive callbacks.
13714// It works by storing the callback node and expiration time on the root. When a
13715// new callback comes in, it compares the expiration time to determine if it
13716// should cancel the previous one. It also relies on commitRoot scheduling a
13717// callback to render the next level, because that means we don't need a
13718// separate callback per expiration time.
13719function scheduleCallbackForRoot(root, priorityLevel, expirationTime) {
13720 var existingCallbackExpirationTime = root.callbackExpirationTime;
13721 if (existingCallbackExpirationTime < expirationTime) {
13722 // New callback has higher priority than the existing one.
13723 var existingCallbackNode = root.callbackNode;
13724 if (existingCallbackNode !== null) {
13725 cancelCallback(existingCallbackNode);
13726 }
13727 root.callbackExpirationTime = expirationTime;
13728 var options = expirationTime === Sync ? null : { timeout: expirationTimeToMs(expirationTime) };
13729 root.callbackNode = scheduleCallback(priorityLevel, runRootCallback.bind(null, root, renderRoot$1.bind(null, root, expirationTime)), options);
13730 if (enableUserTimingAPI && expirationTime !== Sync && workPhase !== RenderPhase && workPhase !== CommitPhase) {
13731 // Scheduled an async callback, and we're not already working. Add an
13732 // entry to the flamegraph that shows we're waiting for a callback
13733 // to fire.
13734 startRequestCallbackTimer();
13735 }
13736 }
13737
13738 var timeoutHandle = root.timeoutHandle;
13739 if (timeoutHandle !== noTimeout) {
13740 // The root previous suspended and scheduled a timeout to commit a fallback
13741 // state. Now that we have additional work, cancel the timeout.
13742 root.timeoutHandle = noTimeout;
13743 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
13744 cancelTimeout(timeoutHandle);
13745 }
13746
13747 // Add the current set of interactions to the pending set associated with
13748 // this root.
13749 schedulePendingInteraction(root, expirationTime);
13750}
13751
13752function runRootCallback(root, callback, isSync) {
13753 var prevCallbackNode = root.callbackNode;
13754 var continuation = null;
13755 try {
13756 continuation = callback(isSync);
13757 if (continuation !== null) {
13758 return runRootCallback.bind(null, root, continuation);
13759 } else {
13760 return null;
13761 }
13762 } finally {
13763 // If the callback exits without returning a continuation, remove the
13764 // corresponding callback node from the root. Unless the callback node
13765 // has changed, which implies that it was already cancelled by a high
13766 // priority update.
13767 if (continuation === null && prevCallbackNode === root.callbackNode) {
13768 root.callbackNode = null;
13769 root.callbackExpirationTime = NoWork;
13770 }
13771 }
13772}
13773
13774
13775
13776
13777
13778function resolveLocksOnRoot(root, expirationTime) {
13779 var firstBatch = root.firstBatch;
13780 if (firstBatch !== null && firstBatch._defer && firstBatch._expirationTime >= expirationTime) {
13781 root.finishedWork = root.current.alternate;
13782 root.pendingCommitExpirationTime = expirationTime;
13783 scheduleCallback(NormalPriority, function () {
13784 firstBatch._onComplete();
13785 return null;
13786 });
13787 return true;
13788 } else {
13789 return false;
13790 }
13791}
13792
13793
13794
13795
13796
13797
13798
13799function batchedUpdates$2(fn, a) {
13800 if (workPhase !== NotWorking) {
13801 // We're already working, or inside a batch, so batchedUpdates is a no-op.
13802 return fn(a);
13803 }
13804 workPhase = BatchedPhase;
13805 try {
13806 return fn(a);
13807 } finally {
13808 workPhase = NotWorking;
13809 // Flush the immediate callbacks that were scheduled during this batch
13810 flushImmediateQueue();
13811 }
13812}
13813
13814
13815
13816function flushSync$2(fn, a) {
13817 if (workPhase === RenderPhase || workPhase === CommitPhase) {
13818 (function () {
13819 {
13820 {
13821 throw ReactError('flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.');
13822 }
13823 }
13824 })();
13825 }
13826 var prevWorkPhase = workPhase;
13827 workPhase = FlushSyncPhase;
13828 try {
13829 return runWithPriority(ImmediatePriority, fn.bind(null, a));
13830 } finally {
13831 workPhase = prevWorkPhase;
13832 // Flush the immediate callbacks that were scheduled during this batch.
13833 // Note that this will happen even if batchedUpdates is higher up
13834 // the stack.
13835 flushImmediateQueue();
13836 }
13837}
13838
13839
13840
13841function prepareFreshStack(root, expirationTime) {
13842 root.pendingCommitExpirationTime = NoWork;
13843
13844 if (workInProgress !== null) {
13845 var interruptedWork = workInProgress.return;
13846 while (interruptedWork !== null) {
13847 unwindInterruptedWork(interruptedWork);
13848 interruptedWork = interruptedWork.return;
13849 }
13850 }
13851 workInProgressRoot = root;
13852 workInProgress = createWorkInProgress(root.current, null, expirationTime);
13853 renderExpirationTime$1 = expirationTime;
13854 workInProgressRootExitStatus = RootIncomplete;
13855 workInProgressRootAbsoluteTimeoutMs = -1;
13856
13857 {
13858 ReactStrictModeWarnings.discardPendingWarnings();
13859 }
13860}
13861
13862function renderRoot$1(root, expirationTime, isSync) {
13863 (function () {
13864 if (!(workPhase !== RenderPhase && workPhase !== CommitPhase)) {
13865 {
13866 throw ReactError('Should not already be working.');
13867 }
13868 }
13869 })();
13870
13871 if (enableUserTimingAPI && expirationTime !== Sync) {
13872 var didExpire = isSync;
13873 var timeoutMs = expirationTimeToMs(expirationTime);
13874 stopRequestCallbackTimer(didExpire, timeoutMs);
13875 }
13876
13877 if (root.firstPendingTime < expirationTime) {
13878 // If there's no work left at this expiration time, exit immediately. This
13879 // happens when multiple callbacks are scheduled for a single root, but an
13880 // earlier callback flushes the work of a later one.
13881 return null;
13882 }
13883
13884 if (root.pendingCommitExpirationTime === expirationTime) {
13885 // There's already a pending commit at this expiration time.
13886 root.pendingCommitExpirationTime = NoWork;
13887 return commitRoot$1.bind(null, root, expirationTime);
13888 }
13889
13890 flushPassiveEffects$2();
13891
13892 // If the root or expiration time have changed, throw out the existing stack
13893 // and prepare a fresh one. Otherwise we'll continue where we left off.
13894 if (root !== workInProgressRoot || expirationTime !== renderExpirationTime$1) {
13895 prepareFreshStack(root, expirationTime);
13896 startWorkOnPendingInteraction(root, expirationTime);
13897 }
13898
13899 // If we have a work-in-progress fiber, it means there's still work to do
13900 // in this root.
13901 if (workInProgress !== null) {
13902 var prevWorkPhase = workPhase;
13903 workPhase = RenderPhase;
13904 var prevDispatcher = ReactCurrentDispatcher$2.current;
13905 if (prevDispatcher === null) {
13906 // The React isomorphic package does not include a default dispatcher.
13907 // Instead the first renderer will lazily attach one, in order to give
13908 // nicer error messages.
13909 prevDispatcher = ContextOnlyDispatcher;
13910 }
13911 ReactCurrentDispatcher$2.current = ContextOnlyDispatcher;
13912 var prevInteractions = null;
13913 if (enableSchedulerTracing) {
13914 prevInteractions = __interactionsRef.current;
13915 __interactionsRef.current = root.memoizedInteractions;
13916 }
13917
13918 startWorkLoopTimer(workInProgress);
13919 do {
13920 try {
13921 if (isSync) {
13922 if (expirationTime !== Sync) {
13923 // An async update expired. There may be other expired updates on
13924 // this root. We should render all the expired work in a
13925 // single batch.
13926 var currentTime = requestCurrentTime$2();
13927 if (currentTime < expirationTime) {
13928 // Restart at the current time.
13929 workPhase = prevWorkPhase;
13930 ReactCurrentDispatcher$2.current = prevDispatcher;
13931 return renderRoot$1.bind(null, root, currentTime);
13932 }
13933 }
13934 workLoopSync();
13935 } else {
13936 // Since we know we're in a React event, we can clear the current
13937 // event time. The next update will compute a new event time.
13938 currentEventTime = NoWork;
13939 workLoop$1();
13940 }
13941 break;
13942 } catch (thrownValue) {
13943 // Reset module-level state that was set during the render phase.
13944 resetContextDependences();
13945 resetHooks();
13946
13947 var sourceFiber = workInProgress;
13948 if (sourceFiber === null || sourceFiber.return === null) {
13949 // Expected to be working on a non-root fiber. This is a fatal error
13950 // because there's no ancestor that can handle it; the root is
13951 // supposed to capture all errors that weren't caught by an error
13952 // boundary.
13953 prepareFreshStack(root, expirationTime);
13954 workPhase = prevWorkPhase;
13955 throw thrownValue;
13956 }
13957
13958 if (enableProfilerTimer && sourceFiber.mode & ProfileMode) {
13959 // Record the time spent rendering before an error was thrown. This
13960 // avoids inaccurate Profiler durations in the case of a
13961 // suspended render.
13962 stopProfilerTimerIfRunningAndRecordDelta(sourceFiber, true);
13963 }
13964
13965 var returnFiber = sourceFiber.return;
13966 throwException(root, returnFiber, sourceFiber, thrownValue, renderExpirationTime$1);
13967 workInProgress = completeUnitOfWork$1(sourceFiber);
13968 }
13969 } while (true);
13970
13971 workPhase = prevWorkPhase;
13972 resetContextDependences();
13973 ReactCurrentDispatcher$2.current = prevDispatcher;
13974 if (enableSchedulerTracing) {
13975 __interactionsRef.current = prevInteractions;
13976 }
13977
13978 if (workInProgress !== null) {
13979 // There's still work left over. Return a continuation.
13980 stopInterruptedWorkLoopTimer();
13981 if (expirationTime !== Sync) {
13982 startRequestCallbackTimer();
13983 }
13984 return renderRoot$1.bind(null, root, expirationTime);
13985 }
13986 }
13987
13988 // We now have a consistent tree. The next step is either to commit it, or, if
13989 // something suspended, wait to commit it after a timeout.
13990 stopFinishedWorkLoopTimer();
13991
13992 var isLocked = resolveLocksOnRoot(root, expirationTime);
13993 if (isLocked) {
13994 // This root has a lock that prevents it from committing. Exit. If we begin
13995 // work on the root again, without any intervening updates, it will finish
13996 // without doing additional work.
13997 return null;
13998 }
13999
14000 // Set this to null to indicate there's no in-progress render.
14001 workInProgressRoot = null;
14002
14003 switch (workInProgressRootExitStatus) {
14004 case RootIncomplete:
14005 {
14006 (function () {
14007 {
14008 {
14009 throw ReactError('Should have a work-in-progress.');
14010 }
14011 }
14012 })();
14013 }
14014 // Flow knows about invariant, so it compains if I add a break statement,
14015 // but eslint doesn't know about invariant, so it complains if I do.
14016 // eslint-disable-next-line no-fallthrough
14017 case RootErrored:
14018 {
14019 // An error was thrown. First check if there is lower priority work
14020 // scheduled on this root.
14021 var lastPendingTime = root.lastPendingTime;
14022 if (root.lastPendingTime < expirationTime) {
14023 // There's lower priority work. Before raising the error, try rendering
14024 // at the lower priority to see if it fixes it. Use a continuation to
14025 // maintain the existing priority and position in the queue.
14026 return renderRoot$1.bind(null, root, lastPendingTime);
14027 }
14028 if (!isSync) {
14029 // If we're rendering asynchronously, it's possible the error was
14030 // caused by tearing due to a mutation during an event. Try rendering
14031 // one more time without yiedling to events.
14032 prepareFreshStack(root, expirationTime);
14033 scheduleCallback(ImmediatePriority, renderRoot$1.bind(null, root, expirationTime));
14034 return null;
14035 }
14036 // If we're already rendering synchronously, commit the root in its
14037 // errored state.
14038 return commitRoot$1.bind(null, root, expirationTime);
14039 }
14040 case RootSuspended:
14041 {
14042 var _lastPendingTime = root.lastPendingTime;
14043 if (root.lastPendingTime < expirationTime) {
14044 // There's lower priority work. It might be unsuspended. Try rendering
14045 // at that level.
14046 return renderRoot$1.bind(null, root, _lastPendingTime);
14047 }
14048 if (!isSync) {
14049 var msUntilTimeout = computeMsUntilTimeout(root, workInProgressRootAbsoluteTimeoutMs);
14050 if (msUntilTimeout > 0) {
14051 // The render is suspended, it hasn't timed out, and there's no lower
14052 // priority work to do. Instead of committing the fallback
14053 // immediately, wait for more data to arrive.
14054 root.timeoutHandle = scheduleTimeout(commitRoot$1.bind(null, root, expirationTime), msUntilTimeout);
14055 return null;
14056 }
14057 }
14058 // The work expired. Commit immediately.
14059 return commitRoot$1.bind(null, root, expirationTime);
14060 }
14061 case RootCompleted:
14062 {
14063 // The work completed. Ready to commit.
14064 return commitRoot$1.bind(null, root, expirationTime);
14065 }
14066 default:
14067 {
14068 (function () {
14069 {
14070 {
14071 throw ReactError('Unknown root exit status.');
14072 }
14073 }
14074 })();
14075 }
14076 }
14077}
14078
14079function renderDidSuspend$2(root, absoluteTimeoutMs,
14080// TODO: Don't need this argument anymore
14081suspendedTime) {
14082 if (absoluteTimeoutMs >= 0 && workInProgressRootAbsoluteTimeoutMs < absoluteTimeoutMs) {
14083 workInProgressRootAbsoluteTimeoutMs = absoluteTimeoutMs;
14084 if (workInProgressRootExitStatus === RootIncomplete) {
14085 workInProgressRootExitStatus = RootSuspended;
14086 }
14087 }
14088}
14089
14090function renderDidError$2() {
14091 if (workInProgressRootExitStatus === RootIncomplete || workInProgressRootExitStatus === RootSuspended) {
14092 workInProgressRootExitStatus = RootErrored;
14093 }
14094}
14095
14096function workLoopSync() {
14097 // Already timed out, so perform work without checking if we need to yield.
14098 while (workInProgress !== null) {
14099 workInProgress = performUnitOfWork$1(workInProgress);
14100 }
14101}
14102
14103function workLoop$1() {
14104 // Perform work until Scheduler asks us to yield
14105 while (workInProgress !== null && !shouldYield()) {
14106 workInProgress = performUnitOfWork$1(workInProgress);
14107 }
14108}
14109
14110function performUnitOfWork$1(unitOfWork) {
14111 // The current, flushed, state of this fiber is the alternate. Ideally
14112 // nothing should rely on this, but relying on it here means that we don't
14113 // need an additional field on the work in progress.
14114 var current$$1 = unitOfWork.alternate;
14115
14116 startWorkTimer(unitOfWork);
14117 setCurrentFiber(unitOfWork);
14118
14119 var next = void 0;
14120 if (enableProfilerTimer && (unitOfWork.mode & ProfileMode) !== NoContext) {
14121 startProfilerTimer(unitOfWork);
14122 next = beginWork$1(current$$1, unitOfWork, renderExpirationTime$1);
14123 stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
14124 } else {
14125 next = beginWork$1(current$$1, unitOfWork, renderExpirationTime$1);
14126 }
14127
14128 resetCurrentFiber();
14129 unitOfWork.memoizedProps = unitOfWork.pendingProps;
14130 if (next === null) {
14131 // If this doesn't spawn new work, complete the current work.
14132 next = completeUnitOfWork$1(unitOfWork);
14133 }
14134
14135 ReactCurrentOwner$3.current = null;
14136 return next;
14137}
14138
14139function completeUnitOfWork$1(unitOfWork) {
14140 // Attempt to complete the current unit of work, then move to the next
14141 // sibling. If there are no more siblings, return to the parent fiber.
14142 workInProgress = unitOfWork;
14143 do {
14144 // The current, flushed, state of this fiber is the alternate. Ideally
14145 // nothing should rely on this, but relying on it here means that we don't
14146 // need an additional field on the work in progress.
14147 var current$$1 = workInProgress.alternate;
14148 var returnFiber = workInProgress.return;
14149
14150 // Check if the work completed or if something threw.
14151 if ((workInProgress.effectTag & Incomplete) === NoEffect) {
14152 setCurrentFiber(workInProgress);
14153 var next = void 0;
14154 if (!enableProfilerTimer || (workInProgress.mode & ProfileMode) === NoContext) {
14155 next = completeWork(current$$1, workInProgress, renderExpirationTime$1);
14156 } else {
14157 startProfilerTimer(workInProgress);
14158 next = completeWork(current$$1, workInProgress, renderExpirationTime$1);
14159 // Update render duration assuming we didn't error.
14160 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
14161 }
14162 stopWorkTimer(workInProgress);
14163 resetCurrentFiber();
14164 resetChildExpirationTime$1(workInProgress);
14165
14166 if (next !== null) {
14167 // Completing this fiber spawned new work. Work on that next.
14168 return next;
14169 }
14170
14171 if (returnFiber !== null &&
14172 // Do not append effects to parents if a sibling failed to complete
14173 (returnFiber.effectTag & Incomplete) === NoEffect) {
14174 // Append all the effects of the subtree and this fiber onto the effect
14175 // list of the parent. The completion order of the children affects the
14176 // side-effect order.
14177 if (returnFiber.firstEffect === null) {
14178 returnFiber.firstEffect = workInProgress.firstEffect;
14179 }
14180 if (workInProgress.lastEffect !== null) {
14181 if (returnFiber.lastEffect !== null) {
14182 returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
14183 }
14184 returnFiber.lastEffect = workInProgress.lastEffect;
14185 }
14186
14187 // If this fiber had side-effects, we append it AFTER the children's
14188 // side-effects. We can perform certain side-effects earlier if needed,
14189 // by doing multiple passes over the effect list. We don't want to
14190 // schedule our own side-effect on our own list because if end up
14191 // reusing children we'll schedule this effect onto itself since we're
14192 // at the end.
14193 var effectTag = workInProgress.effectTag;
14194
14195 // Skip both NoWork and PerformedWork tags when creating the effect
14196 // list. PerformedWork effect is read by React DevTools but shouldn't be
14197 // committed.
14198 if (effectTag > PerformedWork) {
14199 if (returnFiber.lastEffect !== null) {
14200 returnFiber.lastEffect.nextEffect = workInProgress;
14201 } else {
14202 returnFiber.firstEffect = workInProgress;
14203 }
14204 returnFiber.lastEffect = workInProgress;
14205 }
14206 }
14207 } else {
14208 // This fiber did not complete because something threw. Pop values off
14209 // the stack without entering the complete phase. If this is a boundary,
14210 // capture values if possible.
14211 var _next = unwindWork(workInProgress, renderExpirationTime$1);
14212
14213 // Because this fiber did not complete, don't reset its expiration time.
14214
14215 if (enableProfilerTimer && (workInProgress.mode & ProfileMode) !== NoContext) {
14216 // Record the render duration for the fiber that errored.
14217 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
14218
14219 // Include the time spent working on failed children before continuing.
14220 var actualDuration = workInProgress.actualDuration;
14221 var child = workInProgress.child;
14222 while (child !== null) {
14223 actualDuration += child.actualDuration;
14224 child = child.sibling;
14225 }
14226 workInProgress.actualDuration = actualDuration;
14227 }
14228
14229 if (_next !== null) {
14230 // If completing this work spawned new work, do that next. We'll come
14231 // back here again.
14232 // Since we're restarting, remove anything that is not a host effect
14233 // from the effect tag.
14234 // TODO: The name stopFailedWorkTimer is misleading because Suspense
14235 // also captures and restarts.
14236 stopFailedWorkTimer(workInProgress);
14237 _next.effectTag &= HostEffectMask;
14238 return _next;
14239 }
14240 stopWorkTimer(workInProgress);
14241
14242 if (returnFiber !== null) {
14243 // Mark the parent fiber as incomplete and clear its effect list.
14244 returnFiber.firstEffect = returnFiber.lastEffect = null;
14245 returnFiber.effectTag |= Incomplete;
14246 }
14247 }
14248
14249 var siblingFiber = workInProgress.sibling;
14250 if (siblingFiber !== null) {
14251 // If there is more work to do in this returnFiber, do that next.
14252 return siblingFiber;
14253 }
14254 // Otherwise, return to the parent
14255 workInProgress = returnFiber;
14256 } while (workInProgress !== null);
14257
14258 // We've reached the root.
14259 if (workInProgressRootExitStatus === RootIncomplete) {
14260 workInProgressRootExitStatus = RootCompleted;
14261 }
14262 return null;
14263}
14264
14265function resetChildExpirationTime$1(completedWork) {
14266 if (renderExpirationTime$1 !== Never && completedWork.childExpirationTime === Never) {
14267 // The children of this component are hidden. Don't bubble their
14268 // expiration times.
14269 return;
14270 }
14271
14272 var newChildExpirationTime = NoWork;
14273
14274 // Bubble up the earliest expiration time.
14275 if (enableProfilerTimer && (completedWork.mode & ProfileMode) !== NoContext) {
14276 // In profiling mode, resetChildExpirationTime is also used to reset
14277 // profiler durations.
14278 var actualDuration = completedWork.actualDuration;
14279 var treeBaseDuration = completedWork.selfBaseDuration;
14280
14281 // When a fiber is cloned, its actualDuration is reset to 0. This value will
14282 // only be updated if work is done on the fiber (i.e. it doesn't bailout).
14283 // When work is done, it should bubble to the parent's actualDuration. If
14284 // the fiber has not been cloned though, (meaning no work was done), then
14285 // this value will reflect the amount of time spent working on a previous
14286 // render. In that case it should not bubble. We determine whether it was
14287 // cloned by comparing the child pointer.
14288 var shouldBubbleActualDurations = completedWork.alternate === null || completedWork.child !== completedWork.alternate.child;
14289
14290 var child = completedWork.child;
14291 while (child !== null) {
14292 var childUpdateExpirationTime = child.expirationTime;
14293 var childChildExpirationTime = child.childExpirationTime;
14294 if (childUpdateExpirationTime > newChildExpirationTime) {
14295 newChildExpirationTime = childUpdateExpirationTime;
14296 }
14297 if (childChildExpirationTime > newChildExpirationTime) {
14298 newChildExpirationTime = childChildExpirationTime;
14299 }
14300 if (shouldBubbleActualDurations) {
14301 actualDuration += child.actualDuration;
14302 }
14303 treeBaseDuration += child.treeBaseDuration;
14304 child = child.sibling;
14305 }
14306 completedWork.actualDuration = actualDuration;
14307 completedWork.treeBaseDuration = treeBaseDuration;
14308 } else {
14309 var _child = completedWork.child;
14310 while (_child !== null) {
14311 var _childUpdateExpirationTime = _child.expirationTime;
14312 var _childChildExpirationTime = _child.childExpirationTime;
14313 if (_childUpdateExpirationTime > newChildExpirationTime) {
14314 newChildExpirationTime = _childUpdateExpirationTime;
14315 }
14316 if (_childChildExpirationTime > newChildExpirationTime) {
14317 newChildExpirationTime = _childChildExpirationTime;
14318 }
14319 _child = _child.sibling;
14320 }
14321 }
14322
14323 completedWork.childExpirationTime = newChildExpirationTime;
14324}
14325
14326function commitRoot$1(root, expirationTime) {
14327 runWithPriority(ImmediatePriority, commitRootImpl.bind(null, root, expirationTime));
14328 // If there are passive effects, schedule a callback to flush them. This goes
14329 // outside commitRootImpl so that it inherits the priority of the render.
14330 if (rootWithPendingPassiveEffects$1 !== null) {
14331 var priorityLevel = getCurrentPriorityLevel();
14332 scheduleCallback(priorityLevel, function () {
14333 flushPassiveEffects$2();
14334 return null;
14335 });
14336 }
14337 return null;
14338}
14339
14340function commitRootImpl(root, expirationTime) {
14341 flushPassiveEffects$2();
14342 flushRenderPhaseStrictModeWarningsInDEV();
14343
14344 (function () {
14345 if (!(workPhase !== RenderPhase && workPhase !== CommitPhase)) {
14346 {
14347 throw ReactError('Should not already be working.');
14348 }
14349 }
14350 })();
14351 var finishedWork = root.current.alternate;
14352 (function () {
14353 if (!(finishedWork !== null)) {
14354 {
14355 throw ReactError('Should have a work-in-progress root.');
14356 }
14357 }
14358 })();
14359
14360 // commitRoot never returns a continuation; it always finishes synchronously.
14361 // So we can clear these now to allow a new callback to be scheduled.
14362 root.callbackNode = null;
14363 root.callbackExpirationTime = NoWork;
14364
14365 startCommitTimer();
14366
14367 // Update the first and last pending times on this root. The new first
14368 // pending time is whatever is left on the root fiber.
14369 var updateExpirationTimeBeforeCommit = finishedWork.expirationTime;
14370 var childExpirationTimeBeforeCommit = finishedWork.childExpirationTime;
14371 var firstPendingTimeBeforeCommit = childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit ? childExpirationTimeBeforeCommit : updateExpirationTimeBeforeCommit;
14372 root.firstPendingTime = firstPendingTimeBeforeCommit;
14373 if (firstPendingTimeBeforeCommit < root.lastPendingTime) {
14374 // This usually means we've finished all the work, but it can also happen
14375 // when something gets downprioritized during render, like a hidden tree.
14376 root.lastPendingTime = firstPendingTimeBeforeCommit;
14377 }
14378
14379 if (root === workInProgressRoot) {
14380 // We can reset these now that they are finished.
14381 workInProgressRoot = null;
14382 workInProgress = null;
14383 renderExpirationTime$1 = NoWork;
14384 } else {}
14385 // This indicates that the last root we worked on is not the same one that
14386 // we're committing now. This most commonly happens when a suspended root
14387 // times out.
14388
14389
14390 // Get the list of effects.
14391 var firstEffect = void 0;
14392 if (finishedWork.effectTag > PerformedWork) {
14393 // A fiber's effect list consists only of its children, not itself. So if
14394 // the root has an effect, we need to add it to the end of the list. The
14395 // resulting list is the set that would belong to the root's parent, if it
14396 // had one; that is, all the effects in the tree including the root.
14397 if (finishedWork.lastEffect !== null) {
14398 finishedWork.lastEffect.nextEffect = finishedWork;
14399 firstEffect = finishedWork.firstEffect;
14400 } else {
14401 firstEffect = finishedWork;
14402 }
14403 } else {
14404 // There is no effect on the root.
14405 firstEffect = finishedWork.firstEffect;
14406 }
14407
14408 if (firstEffect !== null) {
14409 var prevWorkPhase = workPhase;
14410 workPhase = CommitPhase;
14411 var prevInteractions = null;
14412 if (enableSchedulerTracing) {
14413 prevInteractions = __interactionsRef.current;
14414 __interactionsRef.current = root.memoizedInteractions;
14415 }
14416
14417 // Reset this to null before calling lifecycles
14418 ReactCurrentOwner$3.current = null;
14419
14420 // The commit phase is broken into several sub-phases. We do a separate pass
14421 // of the effect list for each phase: all mutation effects come before all
14422 // layout effects, and so on.
14423
14424 // The first phase a "before mutation" phase. We use this phase to read the
14425 // state of the host tree right before we mutate it. This is where
14426 // getSnapshotBeforeUpdate is called.
14427 startCommitSnapshotEffectsTimer();
14428 prepareForCommit(root.containerInfo);
14429 nextEffect$1 = firstEffect;
14430 do {
14431 {
14432 invokeGuardedCallback(null, commitBeforeMutationEffects, null);
14433 if (hasCaughtError()) {
14434 (function () {
14435 if (!(nextEffect$1 !== null)) {
14436 {
14437 throw ReactError('Should be working on an effect.');
14438 }
14439 }
14440 })();
14441 var error = clearCaughtError();
14442 captureCommitPhaseError$2(nextEffect$1, error);
14443 nextEffect$1 = nextEffect$1.nextEffect;
14444 }
14445 }
14446 } while (nextEffect$1 !== null);
14447 stopCommitSnapshotEffectsTimer();
14448
14449 if (enableProfilerTimer) {
14450 // Mark the current commit time to be shared by all Profilers in this
14451 // batch. This enables them to be grouped later.
14452 recordCommitTime();
14453 }
14454
14455 // The next phase is the mutation phase, where we mutate the host tree.
14456 startCommitHostEffectsTimer();
14457 nextEffect$1 = firstEffect;
14458 do {
14459 {
14460 invokeGuardedCallback(null, commitMutationEffects, null);
14461 if (hasCaughtError()) {
14462 (function () {
14463 if (!(nextEffect$1 !== null)) {
14464 {
14465 throw ReactError('Should be working on an effect.');
14466 }
14467 }
14468 })();
14469 var _error = clearCaughtError();
14470 captureCommitPhaseError$2(nextEffect$1, _error);
14471 nextEffect$1 = nextEffect$1.nextEffect;
14472 }
14473 }
14474 } while (nextEffect$1 !== null);
14475 stopCommitHostEffectsTimer();
14476 resetAfterCommit(root.containerInfo);
14477
14478 // The work-in-progress tree is now the current tree. This must come after
14479 // the mutation phase, so that the previous tree is still current during
14480 // componentWillUnmount, but before the layout phase, so that the finished
14481 // work is current during componentDidMount/Update.
14482 root.current = finishedWork;
14483
14484 // The next phase is the layout phase, where we call effects that read
14485 // the host tree after it's been mutated. The idiomatic use case for this is
14486 // layout, but class component lifecycles also fire here for legacy reasons.
14487 startCommitLifeCyclesTimer();
14488 nextEffect$1 = firstEffect;
14489 do {
14490 {
14491 invokeGuardedCallback(null, commitLayoutEffects, null, root, expirationTime);
14492 if (hasCaughtError()) {
14493 (function () {
14494 if (!(nextEffect$1 !== null)) {
14495 {
14496 throw ReactError('Should be working on an effect.');
14497 }
14498 }
14499 })();
14500 var _error2 = clearCaughtError();
14501 captureCommitPhaseError$2(nextEffect$1, _error2);
14502 nextEffect$1 = nextEffect$1.nextEffect;
14503 }
14504 }
14505 } while (nextEffect$1 !== null);
14506 stopCommitLifeCyclesTimer();
14507
14508 nextEffect$1 = null;
14509
14510 if (enableSchedulerTracing) {
14511 __interactionsRef.current = prevInteractions;
14512 }
14513 workPhase = prevWorkPhase;
14514 } else {
14515 // No effects.
14516 root.current = finishedWork;
14517 // Measure these anyway so the flamegraph explicitly shows that there were
14518 // no effects.
14519 // TODO: Maybe there's a better way to report this.
14520 startCommitSnapshotEffectsTimer();
14521 stopCommitSnapshotEffectsTimer();
14522 if (enableProfilerTimer) {
14523 recordCommitTime();
14524 }
14525 startCommitHostEffectsTimer();
14526 stopCommitHostEffectsTimer();
14527 startCommitLifeCyclesTimer();
14528 stopCommitLifeCyclesTimer();
14529 }
14530
14531 stopCommitTimer();
14532
14533 if (rootDoesHavePassiveEffects) {
14534 // This commit has passive effects. Stash a reference to them. But don't
14535 // schedule a callback until after flushing layout work.
14536 rootDoesHavePassiveEffects = false;
14537 rootWithPendingPassiveEffects$1 = root;
14538 pendingPassiveEffectsExpirationTime = expirationTime;
14539 } else {
14540 if (enableSchedulerTracing) {
14541 // If there are no passive effects, then we can complete the pending
14542 // interactions. Otherwise, we'll wait until after the passive effects
14543 // are flushed.
14544 finishPendingInteractions(root, expirationTime);
14545 }
14546 }
14547
14548 // Check if there's remaining work on this root
14549 var remainingExpirationTime = root.firstPendingTime;
14550 if (remainingExpirationTime !== NoWork) {
14551 var currentTime = requestCurrentTime$2();
14552 var priorityLevel = inferPriorityFromExpirationTime(currentTime, remainingExpirationTime);
14553 scheduleCallbackForRoot(root, priorityLevel, remainingExpirationTime);
14554 } else {
14555 // If there's no remaining work, we can clear the set of already failed
14556 // error boundaries.
14557 legacyErrorBoundariesThatAlreadyFailed$1 = null;
14558 }
14559
14560 onCommitRoot(finishedWork.stateNode);
14561
14562 if (remainingExpirationTime === Sync) {
14563 // Count the number of times the root synchronously re-renders without
14564 // finishing. If there are too many, it indicates an infinite update loop.
14565 if (root === rootWithNestedUpdates) {
14566 nestedUpdateCount$1++;
14567 } else {
14568 nestedUpdateCount$1 = 0;
14569 rootWithNestedUpdates = root;
14570 }
14571 } else {
14572 nestedUpdateCount$1 = 0;
14573 }
14574
14575 if (hasUncaughtError) {
14576 hasUncaughtError = false;
14577 var _error3 = firstUncaughtError;
14578 firstUncaughtError = null;
14579 throw _error3;
14580 }
14581
14582 if (workPhase === LegacyUnbatchedPhase) {
14583 // This is a legacy edge case. We just committed the initial mount of
14584 // a ReactDOM.render-ed root inside of batchedUpdates. The commit fired
14585 // synchronously, but layout updates should be deferred until the end
14586 // of the batch.
14587 return null;
14588 }
14589
14590 // If layout work was scheduled, flush it now.
14591 flushImmediateQueue();
14592 return null;
14593}
14594
14595function commitBeforeMutationEffects() {
14596 while (nextEffect$1 !== null) {
14597 if ((nextEffect$1.effectTag & Snapshot) !== NoEffect) {
14598 setCurrentFiber(nextEffect$1);
14599 recordEffect();
14600
14601 var current$$1 = nextEffect$1.alternate;
14602 commitBeforeMutationLifeCycles(current$$1, nextEffect$1);
14603
14604 resetCurrentFiber();
14605 }
14606 nextEffect$1 = nextEffect$1.nextEffect;
14607 }
14608}
14609
14610function commitMutationEffects() {
14611 // TODO: Should probably move the bulk of this function to commitWork.
14612 while (nextEffect$1 !== null) {
14613 setCurrentFiber(nextEffect$1);
14614
14615 var effectTag = nextEffect$1.effectTag;
14616
14617 if (effectTag & ContentReset) {
14618 commitResetTextContent(nextEffect$1);
14619 }
14620
14621 if (effectTag & Ref) {
14622 var current$$1 = nextEffect$1.alternate;
14623 if (current$$1 !== null) {
14624 commitDetachRef(current$$1);
14625 }
14626 }
14627
14628 // The following switch statement is only concerned about placement,
14629 // updates, and deletions. To avoid needing to add a case for every possible
14630 // bitmap value, we remove the secondary effects from the effect tag and
14631 // switch on that value.
14632 var primaryEffectTag = effectTag & (Placement | Update | Deletion);
14633 switch (primaryEffectTag) {
14634 case Placement:
14635 {
14636 commitPlacement(nextEffect$1);
14637 // Clear the "placement" from effect tag so that we know that this is
14638 // inserted, before any life-cycles like componentDidMount gets called.
14639 // TODO: findDOMNode doesn't rely on this any more but isMounted does
14640 // and isMounted is deprecated anyway so we should be able to kill this.
14641 nextEffect$1.effectTag &= ~Placement;
14642 break;
14643 }
14644 case PlacementAndUpdate:
14645 {
14646 // Placement
14647 commitPlacement(nextEffect$1);
14648 // Clear the "placement" from effect tag so that we know that this is
14649 // inserted, before any life-cycles like componentDidMount gets called.
14650 nextEffect$1.effectTag &= ~Placement;
14651
14652 // Update
14653 var _current = nextEffect$1.alternate;
14654 commitWork(_current, nextEffect$1);
14655 break;
14656 }
14657 case Update:
14658 {
14659 var _current2 = nextEffect$1.alternate;
14660 commitWork(_current2, nextEffect$1);
14661 break;
14662 }
14663 case Deletion:
14664 {
14665 commitDeletion(nextEffect$1);
14666 break;
14667 }
14668 }
14669
14670 // TODO: Only record a mutation effect if primaryEffectTag is non-zero.
14671 recordEffect();
14672
14673 resetCurrentFiber();
14674 nextEffect$1 = nextEffect$1.nextEffect;
14675 }
14676}
14677
14678function commitLayoutEffects(root, committedExpirationTime) {
14679 // TODO: Should probably move the bulk of this function to commitWork.
14680 while (nextEffect$1 !== null) {
14681 setCurrentFiber(nextEffect$1);
14682
14683 var effectTag = nextEffect$1.effectTag;
14684
14685 if (effectTag & (Update | Callback)) {
14686 recordEffect();
14687 var current$$1 = nextEffect$1.alternate;
14688 commitLifeCycles(root, current$$1, nextEffect$1, committedExpirationTime);
14689 }
14690
14691 if (effectTag & Ref) {
14692 recordEffect();
14693 commitAttachRef(nextEffect$1);
14694 }
14695
14696 if (effectTag & Passive) {
14697 rootDoesHavePassiveEffects = true;
14698 }
14699
14700 resetCurrentFiber();
14701 nextEffect$1 = nextEffect$1.nextEffect;
14702 }
14703}
14704
14705function flushPassiveEffects$2() {
14706 if (rootWithPendingPassiveEffects$1 === null) {
14707 return false;
14708 }
14709 var root = rootWithPendingPassiveEffects$1;
14710 var expirationTime = pendingPassiveEffectsExpirationTime;
14711 rootWithPendingPassiveEffects$1 = null;
14712 pendingPassiveEffectsExpirationTime = NoWork;
14713
14714 var prevInteractions = null;
14715 if (enableSchedulerTracing) {
14716 prevInteractions = __interactionsRef.current;
14717 __interactionsRef.current = root.memoizedInteractions;
14718 }
14719
14720 (function () {
14721 if (!(workPhase !== RenderPhase && workPhase !== CommitPhase)) {
14722 {
14723 throw ReactError('Cannot flush passive effects while already rendering.');
14724 }
14725 }
14726 })();
14727 var prevWorkPhase = workPhase;
14728 workPhase = CommitPhase;
14729
14730 // Note: This currently assumes there are no passive effects on the root
14731 // fiber, because the root is not part of its own effect list. This could
14732 // change in the future.
14733 var effect = root.current.firstEffect;
14734 while (effect !== null) {
14735 {
14736 setCurrentFiber(effect);
14737 invokeGuardedCallback(null, commitPassiveHookEffects, null, effect);
14738 if (hasCaughtError()) {
14739 (function () {
14740 if (!(effect !== null)) {
14741 {
14742 throw ReactError('Should be working on an effect.');
14743 }
14744 }
14745 })();
14746 var error = clearCaughtError();
14747 captureCommitPhaseError$2(effect, error);
14748 }
14749 resetCurrentFiber();
14750 }
14751 effect = effect.nextEffect;
14752 }
14753
14754 if (enableSchedulerTracing) {
14755 __interactionsRef.current = prevInteractions;
14756 finishPendingInteractions(root, expirationTime);
14757 }
14758
14759 workPhase = prevWorkPhase;
14760 flushImmediateQueue();
14761
14762 // If additional passive effects were scheduled, increment a counter. If this
14763 // exceeds the limit, we'll fire a warning.
14764 nestedPassiveUpdateCount = rootWithPendingPassiveEffects$1 === null ? 0 : nestedPassiveUpdateCount + 1;
14765
14766 return true;
14767}
14768
14769function isAlreadyFailedLegacyErrorBoundary$2(instance) {
14770 return legacyErrorBoundariesThatAlreadyFailed$1 !== null && legacyErrorBoundariesThatAlreadyFailed$1.has(instance);
14771}
14772
14773function markLegacyErrorBoundaryAsFailed$2(instance) {
14774 if (legacyErrorBoundariesThatAlreadyFailed$1 === null) {
14775 legacyErrorBoundariesThatAlreadyFailed$1 = new Set([instance]);
14776 } else {
14777 legacyErrorBoundariesThatAlreadyFailed$1.add(instance);
14778 }
14779}
14780
14781function prepareToThrowUncaughtError(error) {
14782 if (!hasUncaughtError) {
14783 hasUncaughtError = true;
14784 firstUncaughtError = error;
14785 }
14786}
14787var onUncaughtError$2 = prepareToThrowUncaughtError;
14788
14789function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
14790 var errorInfo = createCapturedValue(error, sourceFiber);
14791 var update = createRootErrorUpdate(rootFiber, errorInfo, Sync);
14792 enqueueUpdate(rootFiber, update);
14793 var root = markUpdateTimeFromFiberToRoot(rootFiber, Sync);
14794 if (root !== null) {
14795 scheduleCallbackForRoot(root, ImmediatePriority, Sync);
14796 }
14797}
14798
14799function captureCommitPhaseError$2(sourceFiber, error) {
14800 if (sourceFiber.tag === HostRoot) {
14801 // Error was thrown at the root. There is no parent, so the root
14802 // itself should capture it.
14803 captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
14804 return;
14805 }
14806
14807 var fiber = sourceFiber.return;
14808 while (fiber !== null) {
14809 if (fiber.tag === HostRoot) {
14810 captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error);
14811 return;
14812 } else if (fiber.tag === ClassComponent) {
14813 var ctor = fiber.type;
14814 var instance = fiber.stateNode;
14815 if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary$2(instance)) {
14816 var errorInfo = createCapturedValue(error, sourceFiber);
14817 var update = createClassErrorUpdate(fiber, errorInfo,
14818 // TODO: This is always sync
14819 Sync);
14820 enqueueUpdate(fiber, update);
14821 var root = markUpdateTimeFromFiberToRoot(fiber, Sync);
14822 if (root !== null) {
14823 scheduleCallbackForRoot(root, ImmediatePriority, Sync);
14824 }
14825 return;
14826 }
14827 }
14828 fiber = fiber.return;
14829 }
14830}
14831
14832function pingSuspendedRoot$2(root, thenable, suspendedTime) {
14833 var pingCache = root.pingCache;
14834 if (pingCache !== null) {
14835 // The thenable resolved, so we no longer need to memoize, because it will
14836 // never be thrown again.
14837 pingCache.delete(thenable);
14838 }
14839
14840 if (workInProgressRoot === root && renderExpirationTime$1 === suspendedTime) {
14841 // Received a ping at the same priority level at which we're currently
14842 // rendering. Restart from the root. Don't need to schedule a ping because
14843 // we're already working on this tree.
14844 prepareFreshStack(root, renderExpirationTime$1);
14845 return;
14846 }
14847
14848 var lastPendingTime = root.lastPendingTime;
14849 if (lastPendingTime < suspendedTime) {
14850 // The root is no longer suspended at this time.
14851 return;
14852 }
14853
14854 var pingTime = root.pingTime;
14855 if (pingTime !== NoWork && pingTime < suspendedTime) {
14856 // There's already a lower priority ping scheduled.
14857 return;
14858 }
14859
14860 // Mark the time at which this ping was scheduled.
14861 root.pingTime = suspendedTime;
14862
14863 var currentTime = requestCurrentTime$2();
14864 var priorityLevel = inferPriorityFromExpirationTime(currentTime, suspendedTime);
14865 scheduleCallbackForRoot(root, priorityLevel, suspendedTime);
14866}
14867
14868function retryTimedOutBoundary$2(boundaryFiber) {
14869 // The boundary fiber (a Suspense component) previously timed out and was
14870 // rendered in its fallback state. One of the promises that suspended it has
14871 // resolved, which means at least part of the tree was likely unblocked. Try
14872 // rendering again, at a new expiration time.
14873 var currentTime = requestCurrentTime$2();
14874 var retryTime = computeExpirationForFiber$2(currentTime, boundaryFiber);
14875 // TODO: Special case idle priority?
14876 var priorityLevel = inferPriorityFromExpirationTime(currentTime, retryTime);
14877 var root = markUpdateTimeFromFiberToRoot(boundaryFiber, retryTime);
14878 if (root !== null) {
14879 scheduleCallbackForRoot(root, priorityLevel, retryTime);
14880 }
14881}
14882
14883function resolveRetryThenable$2(boundaryFiber, thenable) {
14884 var retryCache = void 0;
14885 if (enableSuspenseServerRenderer) {
14886 switch (boundaryFiber.tag) {
14887 case SuspenseComponent:
14888 retryCache = boundaryFiber.stateNode;
14889 break;
14890 case DehydratedSuspenseComponent:
14891 retryCache = boundaryFiber.memoizedState;
14892 break;
14893 default:
14894 (function () {
14895 {
14896 {
14897 throw ReactError('Pinged unknown suspense boundary type. This is probably a bug in React.');
14898 }
14899 }
14900 })();
14901 }
14902 } else {
14903 retryCache = boundaryFiber.stateNode;
14904 }
14905
14906 if (retryCache !== null) {
14907 // The thenable resolved, so we no longer need to memoize, because it will
14908 // never be thrown again.
14909 retryCache.delete(thenable);
14910 }
14911
14912 retryTimedOutBoundary$2(boundaryFiber);
14913}
14914
14915function inferStartTimeFromExpirationTime$2(root, expirationTime) {
14916 // We don't know exactly when the update was scheduled, but we can infer an
14917 // approximate start time from the expiration time.
14918 var earliestExpirationTimeMs = expirationTimeToMs(root.firstPendingTime);
14919 // TODO: Track this on the root instead. It's more accurate, doesn't rely on
14920 // assumptions about priority, and isn't coupled to Scheduler details.
14921 return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;
14922}
14923
14924function computeMsUntilTimeout(root, absoluteTimeoutMs) {
14925 if (disableYielding) {
14926 // Timeout immediately when yielding is disabled.
14927 return 0;
14928 }
14929
14930 // Find the earliest uncommitted expiration time in the tree, including
14931 // work that is suspended. The timeout threshold cannot be longer than
14932 // the overall expiration.
14933 var earliestExpirationTimeMs = expirationTimeToMs(root.firstPendingTime);
14934 if (earliestExpirationTimeMs < absoluteTimeoutMs) {
14935 absoluteTimeoutMs = earliestExpirationTimeMs;
14936 }
14937
14938 // Subtract the current time from the absolute timeout to get the number
14939 // of milliseconds until the timeout. In other words, convert an absolute
14940 // timestamp to a relative time. This is the value that is passed
14941 // to `setTimeout`.
14942 var msUntilTimeout = absoluteTimeoutMs - now();
14943 return msUntilTimeout < 0 ? 0 : msUntilTimeout;
14944}
14945
14946function checkForNestedUpdates() {
14947 if (nestedUpdateCount$1 > NESTED_UPDATE_LIMIT$1) {
14948 nestedUpdateCount$1 = 0;
14949 rootWithNestedUpdates = null;
14950 (function () {
14951 {
14952 {
14953 throw ReactError('Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.');
14954 }
14955 }
14956 })();
14957 }
14958
14959 {
14960 if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT$1) {
14961 nestedPassiveUpdateCount = 0;
14962 warning$1(false, 'Maximum update depth exceeded. This can happen when a component ' + "calls setState inside useEffect, but useEffect either doesn't " + 'have a dependency array, or one of the dependencies changes on ' + 'every render.');
14963 }
14964 }
14965}
14966
14967function flushRenderPhaseStrictModeWarningsInDEV() {
14968 {
14969 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
14970 ReactStrictModeWarnings.flushLegacyContextWarning();
14971
14972 if (warnAboutDeprecatedLifecycles) {
14973 ReactStrictModeWarnings.flushPendingDeprecationWarnings();
14974 }
14975 }
14976}
14977
14978function stopFinishedWorkLoopTimer() {
14979 var didCompleteRoot = true;
14980 stopWorkLoopTimer(interruptedBy$1, didCompleteRoot);
14981 interruptedBy$1 = null;
14982}
14983
14984function stopInterruptedWorkLoopTimer() {
14985 // TODO: Track which fiber caused the interruption.
14986 var didCompleteRoot = false;
14987 stopWorkLoopTimer(interruptedBy$1, didCompleteRoot);
14988 interruptedBy$1 = null;
14989}
14990
14991function checkForInterruption(fiberThatReceivedUpdate, updateExpirationTime) {
14992 if (enableUserTimingAPI && workInProgressRoot !== null && updateExpirationTime > renderExpirationTime$1) {
14993 interruptedBy$1 = fiberThatReceivedUpdate;
14994 }
14995}
14996
14997var didWarnStateUpdateForUnmountedComponent$1 = null;
14998function warnAboutUpdateOnUnmountedFiberInDEV(fiber) {
14999 {
15000 var tag = fiber.tag;
15001 if (tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) {
15002 // Only warn for user-defined components, not internal ones like Suspense.
15003 return;
15004 }
15005 // We show the whole stack but dedupe on the top component's name because
15006 // the problematic code almost always lies inside that component.
15007 var componentName = getComponentName(fiber.type) || 'ReactComponent';
15008 if (didWarnStateUpdateForUnmountedComponent$1 !== null) {
15009 if (didWarnStateUpdateForUnmountedComponent$1.has(componentName)) {
15010 return;
15011 }
15012 didWarnStateUpdateForUnmountedComponent$1.add(componentName);
15013 } else {
15014 didWarnStateUpdateForUnmountedComponent$1 = new Set([componentName]);
15015 }
15016 warningWithoutStack$1(false, "Can't perform a React state update on an unmounted component. This " + 'is a no-op, but it indicates a memory leak in your application. To ' + 'fix, cancel all subscriptions and asynchronous tasks in %s.%s', tag === ClassComponent ? 'the componentWillUnmount method' : 'a useEffect cleanup function', getStackByFiberInDevAndProd(fiber));
15017 }
15018}
15019
15020var beginWork$1 = void 0;
15021if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
15022 var dummyFiber = null;
15023 beginWork$1 = function (current$$1, unitOfWork, expirationTime) {
15024 // If a component throws an error, we replay it again in a synchronously
15025 // dispatched event, so that the debugger will treat it as an uncaught
15026 // error See ReactErrorUtils for more information.
15027
15028 // Before entering the begin phase, copy the work-in-progress onto a dummy
15029 // fiber. If beginWork throws, we'll use this to reset the state.
15030 var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);
15031 try {
15032 return beginWork(current$$1, unitOfWork, expirationTime);
15033 } catch (originalError) {
15034 if (originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') {
15035 // Don't replay promises. Treat everything else like an error.
15036 throw originalError;
15037 }
15038
15039 // Keep this code in sync with renderRoot; any changes here must have
15040 // corresponding changes there.
15041 resetContextDependences();
15042 resetHooks();
15043
15044 // Unwind the failed stack frame
15045 unwindInterruptedWork(unitOfWork);
15046
15047 // Restore the original properties of the fiber.
15048 assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);
15049
15050 if (enableProfilerTimer && unitOfWork.mode & ProfileMode) {
15051 // Reset the profiler timer.
15052 startProfilerTimer(unitOfWork);
15053 }
15054
15055 // Run beginWork again.
15056 invokeGuardedCallback(null, beginWork, null, current$$1, unitOfWork, expirationTime);
15057
15058 if (hasCaughtError()) {
15059 var replayError = clearCaughtError();
15060 // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.
15061 // Rethrow this error instead of the original one.
15062 throw replayError;
15063 } else {
15064 // This branch is reachable if the render phase is impure.
15065 throw originalError;
15066 }
15067 }
15068 };
15069} else {
15070 beginWork$1 = beginWork;
15071}
15072
15073var didWarnAboutUpdateInRender = false;
15074var didWarnAboutUpdateInGetChildContext = false;
15075function warnAboutInvalidUpdatesOnClassComponentsInDEV(fiber) {
15076 {
15077 if (fiber.tag === ClassComponent) {
15078 switch (phase) {
15079 case 'getChildContext':
15080 if (didWarnAboutUpdateInGetChildContext) {
15081 return;
15082 }
15083 warningWithoutStack$1(false, 'setState(...): Cannot call setState() inside getChildContext()');
15084 didWarnAboutUpdateInGetChildContext = true;
15085 break;
15086 case 'render':
15087 if (didWarnAboutUpdateInRender) {
15088 return;
15089 }
15090 warningWithoutStack$1(false, 'Cannot update during an existing state transition (such as ' + 'within `render`). Render methods should be a pure function of ' + 'props and state.');
15091 didWarnAboutUpdateInRender = true;
15092 break;
15093 }
15094 }
15095 }
15096}
15097
15098function warnIfNotCurrentlyActingUpdatesInDEV(fiber) {
15099 {
15100 if (workPhase === NotWorking && ReactShouldWarnActingUpdates$1.current === false) {
15101 warningWithoutStack$1(false, 'An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\n\n' + 'act(() => {\n' + ' /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://fb.me/react-wrap-tests-with-act' + '%s', getComponentName(fiber.type), getStackByFiberInDevAndProd(fiber));
15102 }
15103 }
15104}
15105
15106var warnIfNotCurrentlyActingUpdatesInDev$2 = warnIfNotCurrentlyActingUpdatesInDEV;
15107
15108function computeThreadID$1(root, expirationTime) {
15109 // Interaction threads are unique per root and expiration time.
15110 return expirationTime * 1000 + root.interactionThreadID;
15111}
15112
15113function schedulePendingInteraction(root, expirationTime) {
15114 // This is called when work is scheduled on a root. It sets up a pending
15115 // interaction, which is completed once the work commits.
15116 if (!enableSchedulerTracing) {
15117 return;
15118 }
15119
15120 var interactions = __interactionsRef.current;
15121 if (interactions.size > 0) {
15122 var pendingInteractionMap = root.pendingInteractionMap;
15123 var pendingInteractions = pendingInteractionMap.get(expirationTime);
15124 if (pendingInteractions != null) {
15125 interactions.forEach(function (interaction) {
15126 if (!pendingInteractions.has(interaction)) {
15127 // Update the pending async work count for previously unscheduled interaction.
15128 interaction.__count++;
15129 }
15130
15131 pendingInteractions.add(interaction);
15132 });
15133 } else {
15134 pendingInteractionMap.set(expirationTime, new Set(interactions));
15135
15136 // Update the pending async work count for the current interactions.
15137 interactions.forEach(function (interaction) {
15138 interaction.__count++;
15139 });
15140 }
15141
15142 var subscriber = __subscriberRef.current;
15143 if (subscriber !== null) {
15144 var threadID = computeThreadID$1(root, expirationTime);
15145 subscriber.onWorkScheduled(interactions, threadID);
15146 }
15147 }
15148}
15149
15150function startWorkOnPendingInteraction(root, expirationTime) {
15151 // This is called when new work is started on a root.
15152 if (!enableSchedulerTracing) {
15153 return;
15154 }
15155
15156 // Determine which interactions this batch of work currently includes, So that
15157 // we can accurately attribute time spent working on it, And so that cascading
15158 // work triggered during the render phase will be associated with it.
15159 var interactions = new Set();
15160 root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
15161 if (scheduledExpirationTime >= expirationTime) {
15162 scheduledInteractions.forEach(function (interaction) {
15163 return interactions.add(interaction);
15164 });
15165 }
15166 });
15167
15168 // Store the current set of interactions on the FiberRoot for a few reasons:
15169 // We can re-use it in hot functions like renderRoot() without having to
15170 // recalculate it. We will also use it in commitWork() to pass to any Profiler
15171 // onRender() hooks. This also provides DevTools with a way to access it when
15172 // the onCommitRoot() hook is called.
15173 root.memoizedInteractions = interactions;
15174
15175 if (interactions.size > 0) {
15176 var subscriber = __subscriberRef.current;
15177 if (subscriber !== null) {
15178 var threadID = computeThreadID$1(root, expirationTime);
15179 try {
15180 subscriber.onWorkStarted(interactions, threadID);
15181 } catch (error) {
15182 // If the subscriber throws, rethrow it in a separate task
15183 scheduleCallback(ImmediatePriority, function () {
15184 throw error;
15185 });
15186 }
15187 }
15188 }
15189}
15190
15191function finishPendingInteractions(root, committedExpirationTime) {
15192 if (!enableSchedulerTracing) {
15193 return;
15194 }
15195
15196 var earliestRemainingTimeAfterCommit = root.firstPendingTime;
15197
15198 var subscriber = void 0;
15199
15200 try {
15201 subscriber = __subscriberRef.current;
15202 if (subscriber !== null && root.memoizedInteractions.size > 0) {
15203 var threadID = computeThreadID$1(root, committedExpirationTime);
15204 subscriber.onWorkStopped(root.memoizedInteractions, threadID);
15205 }
15206 } catch (error) {
15207 // If the subscriber throws, rethrow it in a separate task
15208 scheduleCallback(ImmediatePriority, function () {
15209 throw error;
15210 });
15211 } finally {
15212 // Clear completed interactions from the pending Map.
15213 // Unless the render was suspended or cascading work was scheduled,
15214 // In which case– leave pending interactions until the subsequent render.
15215 var pendingInteractionMap = root.pendingInteractionMap;
15216 pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
15217 // Only decrement the pending interaction count if we're done.
15218 // If there's still work at the current priority,
15219 // That indicates that we are waiting for suspense data.
15220 if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {
15221 pendingInteractionMap.delete(scheduledExpirationTime);
15222
15223 scheduledInteractions.forEach(function (interaction) {
15224 interaction.__count--;
15225
15226 if (subscriber !== null && interaction.__count === 0) {
15227 try {
15228 subscriber.onInteractionScheduledWorkCompleted(interaction);
15229 } catch (error) {
15230 // If the subscriber throws, rethrow it in a separate task
15231 scheduleCallback(ImmediatePriority, function () {
15232 throw error;
15233 });
15234 }
15235 }
15236 });
15237 }
15238 });
15239 }
15240}
15241
15242var requestCurrentTime$$1 = enableNewScheduler ? requestCurrentTime$2 : requestCurrentTime$1;
15243var computeExpirationForFiber$$1 = enableNewScheduler ? computeExpirationForFiber$2 : computeExpirationForFiber$1;
15244var captureCommitPhaseError$$1 = enableNewScheduler ? captureCommitPhaseError$2 : captureCommitPhaseError$1;
15245var onUncaughtError$$1 = enableNewScheduler ? onUncaughtError$2 : onUncaughtError$1;
15246var renderDidSuspend$$1 = enableNewScheduler ? renderDidSuspend$2 : renderDidSuspend$1;
15247var renderDidError$$1 = enableNewScheduler ? renderDidError$2 : renderDidError$1;
15248var pingSuspendedRoot$$1 = enableNewScheduler ? pingSuspendedRoot$2 : pingSuspendedRoot$1;
15249var retryTimedOutBoundary$$1 = enableNewScheduler ? retryTimedOutBoundary$2 : retryTimedOutBoundary$1;
15250var resolveRetryThenable$$1 = enableNewScheduler ? resolveRetryThenable$2 : resolveRetryThenable$1;
15251var markLegacyErrorBoundaryAsFailed$$1 = enableNewScheduler ? markLegacyErrorBoundaryAsFailed$2 : markLegacyErrorBoundaryAsFailed$1;
15252var isAlreadyFailedLegacyErrorBoundary$$1 = enableNewScheduler ? isAlreadyFailedLegacyErrorBoundary$2 : isAlreadyFailedLegacyErrorBoundary$1;
15253var scheduleWork$$1 = enableNewScheduler ? scheduleWork$2 : scheduleWork$1;
15254
15255var batchedUpdates$$1 = enableNewScheduler ? batchedUpdates$2 : batchedUpdates$1;
15256
15257var flushSync$$1 = enableNewScheduler ? flushSync$2 : flushSync$1;
15258
15259
15260
15261
15262
15263
15264var flushPassiveEffects$$1 = enableNewScheduler ? flushPassiveEffects$2 : flushPassiveEffects$1;
15265var warnIfNotCurrentlyActingUpdatesInDev$$1 = enableNewScheduler ? warnIfNotCurrentlyActingUpdatesInDev$2 : warnIfNotCurrentlyActingUpdatesInDev$1;
15266var inferStartTimeFromExpirationTime$$1 = enableNewScheduler ? inferStartTimeFromExpirationTime$2 : inferStartTimeFromExpirationTime$1;
15267
15268// 0 is PROD, 1 is DEV.
15269// Might add PROFILE later.
15270
15271
15272var didWarnAboutNestedUpdates = void 0;
15273{
15274 didWarnAboutNestedUpdates = false;
15275
15276}
15277
15278function getContextForSubtree(parentComponent) {
15279 if (!parentComponent) {
15280 return emptyContextObject;
15281 }
15282
15283 var fiber = get(parentComponent);
15284 var parentContext = findCurrentUnmaskedContext(fiber);
15285
15286 if (fiber.tag === ClassComponent) {
15287 var Component = fiber.type;
15288 if (isContextProvider(Component)) {
15289 return processChildContext(fiber, Component, parentContext);
15290 }
15291 }
15292
15293 return parentContext;
15294}
15295
15296function scheduleRootUpdate(current$$1, element, expirationTime, callback) {
15297 {
15298 if (phase === 'render' && current !== null && !didWarnAboutNestedUpdates) {
15299 didWarnAboutNestedUpdates = true;
15300 warningWithoutStack$1(false, 'Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentName(current.type) || 'Unknown');
15301 }
15302 }
15303
15304 var update = createUpdate(expirationTime);
15305 // Caution: React DevTools currently depends on this property
15306 // being called "element".
15307 update.payload = { element: element };
15308
15309 callback = callback === undefined ? null : callback;
15310 if (callback !== null) {
15311 !(typeof callback === 'function') ? warningWithoutStack$1(false, 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback) : void 0;
15312 update.callback = callback;
15313 }
15314
15315 flushPassiveEffects$$1();
15316 enqueueUpdate(current$$1, update);
15317 scheduleWork$$1(current$$1, expirationTime);
15318
15319 return expirationTime;
15320}
15321
15322function updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback) {
15323 // TODO: If this is a nested container, this won't be the root.
15324 var current$$1 = container.current;
15325
15326 {
15327 if (ReactFiberInstrumentation_1.debugTool) {
15328 if (current$$1.alternate === null) {
15329 ReactFiberInstrumentation_1.debugTool.onMountContainer(container);
15330 } else if (element === null) {
15331 ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container);
15332 } else {
15333 ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container);
15334 }
15335 }
15336 }
15337
15338 var context = getContextForSubtree(parentComponent);
15339 if (container.context === null) {
15340 container.context = context;
15341 } else {
15342 container.pendingContext = context;
15343 }
15344
15345 return scheduleRootUpdate(current$$1, element, expirationTime, callback);
15346}
15347
15348function createContainer(containerInfo, isConcurrent, hydrate) {
15349 return createFiberRoot(containerInfo, isConcurrent, hydrate);
15350}
15351
15352function updateContainer(element, container, parentComponent, callback) {
15353 var current$$1 = container.current;
15354 var currentTime = requestCurrentTime$$1();
15355 var expirationTime = computeExpirationForFiber$$1(currentTime, current$$1);
15356 return updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback);
15357}
15358
15359function getPublicRootInstance(container) {
15360 var containerFiber = container.current;
15361 if (!containerFiber.child) {
15362 return null;
15363 }
15364 switch (containerFiber.child.tag) {
15365 case HostComponent:
15366 return getPublicInstance(containerFiber.child.stateNode);
15367 default:
15368 return containerFiber.child.stateNode;
15369 }
15370}
15371
15372
15373
15374var overrideHookState = null;
15375var overrideProps = null;
15376
15377{
15378 var copyWithSetImpl = function (obj, path, idx, value) {
15379 if (idx >= path.length) {
15380 return value;
15381 }
15382 var key = path[idx];
15383 var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj);
15384 // $FlowFixMe number or string is fine here
15385 updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value);
15386 return updated;
15387 };
15388
15389 var copyWithSet = function (obj, path, value) {
15390 return copyWithSetImpl(obj, path, 0, value);
15391 };
15392
15393 // Support DevTools editable values for useState and useReducer.
15394 overrideHookState = function (fiber, id, path, value) {
15395 // For now, the "id" of stateful hooks is just the stateful hook index.
15396 // This may change in the future with e.g. nested hooks.
15397 var currentHook = fiber.memoizedState;
15398 while (currentHook !== null && id > 0) {
15399 currentHook = currentHook.next;
15400 id--;
15401 }
15402 if (currentHook !== null) {
15403 flushPassiveEffects$$1();
15404
15405 var newState = copyWithSet(currentHook.memoizedState, path, value);
15406 currentHook.memoizedState = newState;
15407 currentHook.baseState = newState;
15408
15409 // We aren't actually adding an update to the queue,
15410 // because there is no update we can add for useReducer hooks that won't trigger an error.
15411 // (There's no appropriate action type for DevTools overrides.)
15412 // As a result though, React will see the scheduled update as a noop and bailout.
15413 // Shallow cloning props works as a workaround for now to bypass the bailout check.
15414 fiber.memoizedProps = _assign({}, fiber.memoizedProps);
15415
15416 scheduleWork$$1(fiber, Sync);
15417 }
15418 };
15419
15420 // Support DevTools props for function components, forwardRef, memo, host components, etc.
15421 overrideProps = function (fiber, path, value) {
15422 flushPassiveEffects$$1();
15423 fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
15424 if (fiber.alternate) {
15425 fiber.alternate.pendingProps = fiber.pendingProps;
15426 }
15427 scheduleWork$$1(fiber, Sync);
15428 };
15429}
15430
15431function injectIntoDevTools(devToolsConfig) {
15432 var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
15433 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
15434
15435
15436 return injectInternals(_assign({}, devToolsConfig, {
15437 overrideHookState: overrideHookState,
15438 overrideProps: overrideProps,
15439 currentDispatcherRef: ReactCurrentDispatcher,
15440 findHostInstanceByFiber: function (fiber) {
15441 var hostFiber = findCurrentHostFiber(fiber);
15442 if (hostFiber === null) {
15443 return null;
15444 }
15445 return hostFiber.stateNode;
15446 },
15447 findFiberByHostInstance: function (instance) {
15448 if (!findFiberByHostInstance) {
15449 // Might not be implemented by the renderer.
15450 return null;
15451 }
15452 return findFiberByHostInstance(instance);
15453 }
15454 }));
15455}
15456
15457// This file intentionally does *not* have the Flow annotation.
15458// Don't add it. See `./inline-typed.js` for an explanation.
15459
15460// TODO: this is special because it gets imported during build.
15461
15462var ReactVersion = '16.9.0-alpha.0';
15463
15464var didWarnAboutMessageChannel = false;
15465var enqueueTask = void 0;
15466try {
15467 // read require off the module object to get around the bundlers.
15468 // we don't want them to detect a require and bundle a Node polyfill.
15469 var requireString = ('require' + Math.random()).slice(0, 7);
15470 var nodeRequire = module && module[requireString];
15471 // assuming we're in node, let's try to get node's
15472 // version of setImmediate, bypassing fake timers if any.
15473 enqueueTask = nodeRequire('timers').setImmediate;
15474} catch (_err) {
15475 // we're in a browser
15476 // we can't use regular timers because they may still be faked
15477 // so we try MessageChannel+postMessage instead
15478 enqueueTask = function (callback) {
15479 {
15480 if (didWarnAboutMessageChannel === false) {
15481 didWarnAboutMessageChannel = true;
15482 !(typeof MessageChannel !== 'undefined') ? warningWithoutStack$1(false, 'This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.') : void 0;
15483 }
15484 }
15485 var channel = new MessageChannel();
15486 channel.port1.onmessage = callback;
15487 channel.port2.postMessage(undefined);
15488 };
15489}
15490
15491var enqueueTask$1 = enqueueTask;
15492
15493var ReactShouldWarnActingUpdates$2 = ReactSharedInternals.ReactShouldWarnActingUpdates;
15494
15495// this implementation should be exactly the same in
15496// ReactTestUtilsAct.js, ReactTestRendererAct.js, createReactNoop.js
15497
15498// we track the 'depth' of the act() calls with this counter,
15499// so we can tell if any async act() calls try to run in parallel.
15500
15501var actingUpdatesScopeDepth = 0;
15502
15503function flushEffectsAndMicroTasks(onDone) {
15504 try {
15505 flushPassiveEffects$$1();
15506 enqueueTask$1(function () {
15507 if (flushPassiveEffects$$1()) {
15508 flushEffectsAndMicroTasks(onDone);
15509 } else {
15510 onDone();
15511 }
15512 });
15513 } catch (err) {
15514 onDone(err);
15515 }
15516}
15517
15518function act(callback) {
15519 var previousActingUpdatesScopeDepth = void 0;
15520 {
15521 previousActingUpdatesScopeDepth = actingUpdatesScopeDepth;
15522 actingUpdatesScopeDepth++;
15523 ReactShouldWarnActingUpdates$2.current = true;
15524 }
15525
15526 function onDone() {
15527 {
15528 actingUpdatesScopeDepth--;
15529 if (actingUpdatesScopeDepth === 0) {
15530 ReactShouldWarnActingUpdates$2.current = false;
15531 }
15532 if (actingUpdatesScopeDepth > previousActingUpdatesScopeDepth) {
15533 // if it's _less than_ previousActingUpdatesScopeDepth, then we can assume the 'other' one has warned
15534 warningWithoutStack$1(false, 'You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. ');
15535 }
15536 }
15537 }
15538
15539 var result = batchedUpdates$$1(callback);
15540 if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
15541 // setup a boolean that gets set to true only
15542 // once this act() call is await-ed
15543 var called = false;
15544 {
15545 if (typeof Promise !== 'undefined') {
15546 //eslint-disable-next-line no-undef
15547 Promise.resolve().then(function () {}).then(function () {
15548 if (called === false) {
15549 warningWithoutStack$1(false, 'You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, interleaving multiple act ' + 'calls and mixing their scopes. You should - await act(async () => ...);');
15550 }
15551 });
15552 }
15553 }
15554
15555 // in the async case, the returned thenable runs the callback, flushes
15556 // effects and microtasks in a loop until flushPassiveEffects() === false,
15557 // and cleans up
15558 return {
15559 then: function (resolve, reject) {
15560 called = true;
15561 result.then(function () {
15562 flushEffectsAndMicroTasks(function (err) {
15563 onDone();
15564 if (err) {
15565 reject(err);
15566 } else {
15567 resolve();
15568 }
15569 });
15570 }, function (err) {
15571 onDone();
15572 reject(err);
15573 });
15574 }
15575 };
15576 } else {
15577 {
15578 !(result === undefined) ? warningWithoutStack$1(false, 'The callback passed to act(...) function ' + 'must return undefined, or a Promise. You returned %s', result) : void 0;
15579 }
15580
15581 // flush effects until none remain, and cleanup
15582 try {
15583 while (flushPassiveEffects$$1()) {}
15584 onDone();
15585 } catch (err) {
15586 onDone();
15587 throw err;
15588 }
15589
15590 // in the sync case, the returned thenable only warns *if* await-ed
15591 return {
15592 then: function (resolve) {
15593 {
15594 warningWithoutStack$1(false, 'Do not await the result of calling act(...) with sync logic, it is not a Promise.');
15595 }
15596 resolve();
15597 }
15598 };
15599 }
15600}
15601
15602var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
15603
15604function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
15605
15606function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
15607
15608var defaultTestOptions = {
15609 createNodeMock: function () {
15610 return null;
15611 }
15612};
15613
15614function toJSON(inst) {
15615 if (inst.isHidden) {
15616 // Omit timed out children from output entirely. This seems like the least
15617 // surprising behavior. We could perhaps add a separate API that includes
15618 // them, if it turns out people need it.
15619 return null;
15620 }
15621 switch (inst.tag) {
15622 case 'TEXT':
15623 return inst.text;
15624 case 'INSTANCE':
15625 {
15626 /* eslint-disable no-unused-vars */
15627 // We don't include the `children` prop in JSON.
15628 // Instead, we will include the actual rendered children.
15629 var _inst$props = inst.props,
15630 _children = _inst$props.children,
15631 _props = _objectWithoutProperties(_inst$props, ['children']);
15632 /* eslint-enable */
15633
15634
15635 var renderedChildren = null;
15636 if (inst.children && inst.children.length) {
15637 for (var i = 0; i < inst.children.length; i++) {
15638 var renderedChild = toJSON(inst.children[i]);
15639 if (renderedChild !== null) {
15640 if (renderedChildren === null) {
15641 renderedChildren = [renderedChild];
15642 } else {
15643 renderedChildren.push(renderedChild);
15644 }
15645 }
15646 }
15647 }
15648 var json = {
15649 type: inst.type,
15650 props: _props,
15651 children: renderedChildren
15652 };
15653 Object.defineProperty(json, '$$typeof', {
15654 value: Symbol.for('react.test.json')
15655 });
15656 return json;
15657 }
15658 default:
15659 throw new Error('Unexpected node type in toJSON: ' + inst.tag);
15660 }
15661}
15662
15663function childrenToTree(node) {
15664 if (!node) {
15665 return null;
15666 }
15667 var children = nodeAndSiblingsArray(node);
15668 if (children.length === 0) {
15669 return null;
15670 } else if (children.length === 1) {
15671 return toTree(children[0]);
15672 }
15673 return flatten(children.map(toTree));
15674}
15675
15676function nodeAndSiblingsArray(nodeWithSibling) {
15677 var array = [];
15678 var node = nodeWithSibling;
15679 while (node != null) {
15680 array.push(node);
15681 node = node.sibling;
15682 }
15683 return array;
15684}
15685
15686function flatten(arr) {
15687 var result = [];
15688 var stack = [{ i: 0, array: arr }];
15689 while (stack.length) {
15690 var n = stack.pop();
15691 while (n.i < n.array.length) {
15692 var el = n.array[n.i];
15693 n.i += 1;
15694 if (Array.isArray(el)) {
15695 stack.push(n);
15696 stack.push({ i: 0, array: el });
15697 break;
15698 }
15699 result.push(el);
15700 }
15701 }
15702 return result;
15703}
15704
15705function toTree(node) {
15706 if (node == null) {
15707 return null;
15708 }
15709 switch (node.tag) {
15710 case HostRoot:
15711 return childrenToTree(node.child);
15712 case HostPortal:
15713 return childrenToTree(node.child);
15714 case ClassComponent:
15715 return {
15716 nodeType: 'component',
15717 type: node.type,
15718 props: _assign({}, node.memoizedProps),
15719 instance: node.stateNode,
15720 rendered: childrenToTree(node.child)
15721 };
15722 case FunctionComponent:
15723 case SimpleMemoComponent:
15724 return {
15725 nodeType: 'component',
15726 type: node.type,
15727 props: _assign({}, node.memoizedProps),
15728 instance: null,
15729 rendered: childrenToTree(node.child)
15730 };
15731 case HostComponent:
15732 {
15733 return {
15734 nodeType: 'host',
15735 type: node.type,
15736 props: _assign({}, node.memoizedProps),
15737 instance: null, // TODO: use createNodeMock here somehow?
15738 rendered: flatten(nodeAndSiblingsArray(node.child).map(toTree))
15739 };
15740 }
15741 case HostText:
15742 return node.stateNode.text;
15743 case Fragment:
15744 case ContextProvider:
15745 case ContextConsumer:
15746 case Mode:
15747 case Profiler:
15748 case ForwardRef:
15749 case MemoComponent:
15750 case IncompleteClassComponent:
15751 return childrenToTree(node.child);
15752 default:
15753 (function () {
15754 {
15755 {
15756 throw ReactError('toTree() does not yet know how to handle nodes with tag=' + node.tag);
15757 }
15758 }
15759 })();
15760 }
15761}
15762
15763var validWrapperTypes = new Set([FunctionComponent, ClassComponent, HostComponent, ForwardRef, MemoComponent, SimpleMemoComponent,
15764// Normally skipped, but used when there's more than one root child.
15765HostRoot]);
15766
15767function getChildren(parent) {
15768 var children = [];
15769 var startingNode = parent;
15770 var node = startingNode;
15771 if (node.child === null) {
15772 return children;
15773 }
15774 node.child.return = node;
15775 node = node.child;
15776 outer: while (true) {
15777 var descend = false;
15778 if (validWrapperTypes.has(node.tag)) {
15779 children.push(wrapFiber(node));
15780 } else if (node.tag === HostText) {
15781 children.push('' + node.memoizedProps);
15782 } else {
15783 descend = true;
15784 }
15785 if (descend && node.child !== null) {
15786 node.child.return = node;
15787 node = node.child;
15788 continue;
15789 }
15790 while (node.sibling === null) {
15791 if (node.return === startingNode) {
15792 break outer;
15793 }
15794 node = node.return;
15795 }
15796 node.sibling.return = node.return;
15797 node = node.sibling;
15798 }
15799 return children;
15800}
15801
15802var ReactTestInstance = function () {
15803 ReactTestInstance.prototype._currentFiber = function _currentFiber() {
15804 // Throws if this component has been unmounted.
15805 var fiber = findCurrentFiberUsingSlowPath(this._fiber);
15806 (function () {
15807 if (!(fiber !== null)) {
15808 {
15809 throw ReactError('Can\'t read from currently-mounting component. This error is likely caused by a bug in React. Please file an issue.');
15810 }
15811 }
15812 })();
15813 return fiber;
15814 };
15815
15816 function ReactTestInstance(fiber) {
15817 _classCallCheck(this, ReactTestInstance);
15818
15819 (function () {
15820 if (!validWrapperTypes.has(fiber.tag)) {
15821 {
15822 throw ReactError('Unexpected object passed to ReactTestInstance constructor (tag: ' + fiber.tag + '). This is probably a bug in React.');
15823 }
15824 }
15825 })();
15826 this._fiber = fiber;
15827 }
15828
15829 // Custom search functions
15830 ReactTestInstance.prototype.find = function find(predicate) {
15831 return expectOne(this.findAll(predicate, { deep: false }), 'matching custom predicate: ' + predicate.toString());
15832 };
15833
15834 ReactTestInstance.prototype.findByType = function findByType(type) {
15835 return expectOne(this.findAllByType(type, { deep: false }), 'with node type: "' + (type.displayName || type.name) + '"');
15836 };
15837
15838 ReactTestInstance.prototype.findByProps = function findByProps(props) {
15839 return expectOne(this.findAllByProps(props, { deep: false }), 'with props: ' + JSON.stringify(props));
15840 };
15841
15842 ReactTestInstance.prototype.findAll = function findAll(predicate) {
15843 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
15844
15845 return _findAll(this, predicate, options);
15846 };
15847
15848 ReactTestInstance.prototype.findAllByType = function findAllByType(type) {
15849 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
15850
15851 return _findAll(this, function (node) {
15852 return node.type === type;
15853 }, options);
15854 };
15855
15856 ReactTestInstance.prototype.findAllByProps = function findAllByProps(props) {
15857 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
15858
15859 return _findAll(this, function (node) {
15860 return node.props && propsMatch(node.props, props);
15861 }, options);
15862 };
15863
15864 _createClass(ReactTestInstance, [{
15865 key: 'instance',
15866 get: function () {
15867 if (this._fiber.tag === HostComponent) {
15868 return getPublicInstance(this._fiber.stateNode);
15869 } else {
15870 return this._fiber.stateNode;
15871 }
15872 }
15873 }, {
15874 key: 'type',
15875 get: function () {
15876 return this._fiber.type;
15877 }
15878 }, {
15879 key: 'props',
15880 get: function () {
15881 return this._currentFiber().memoizedProps;
15882 }
15883 }, {
15884 key: 'parent',
15885 get: function () {
15886 var parent = this._fiber.return;
15887 while (parent !== null) {
15888 if (validWrapperTypes.has(parent.tag)) {
15889 if (parent.tag === HostRoot) {
15890 // Special case: we only "materialize" instances for roots
15891 // if they have more than a single child. So we'll check that now.
15892 if (getChildren(parent).length < 2) {
15893 return null;
15894 }
15895 }
15896 return wrapFiber(parent);
15897 }
15898 parent = parent.return;
15899 }
15900 return null;
15901 }
15902 }, {
15903 key: 'children',
15904 get: function () {
15905 return getChildren(this._currentFiber());
15906 }
15907 }]);
15908
15909 return ReactTestInstance;
15910}();
15911
15912function _findAll(root, predicate, options) {
15913 var deep = options ? options.deep : true;
15914 var results = [];
15915
15916 if (predicate(root)) {
15917 results.push(root);
15918 if (!deep) {
15919 return results;
15920 }
15921 }
15922
15923 root.children.forEach(function (child) {
15924 if (typeof child === 'string') {
15925 return;
15926 }
15927 results.push.apply(results, _findAll(child, predicate, options));
15928 });
15929
15930 return results;
15931}
15932
15933function expectOne(all, message) {
15934 if (all.length === 1) {
15935 return all[0];
15936 }
15937
15938 var prefix = all.length === 0 ? 'No instances found ' : 'Expected 1 but found ' + all.length + ' instances ';
15939
15940 throw new Error(prefix + message);
15941}
15942
15943function propsMatch(props, filter) {
15944 for (var key in filter) {
15945 if (props[key] !== filter[key]) {
15946 return false;
15947 }
15948 }
15949 return true;
15950}
15951
15952var ReactTestRendererFiber = {
15953 _Scheduler: Scheduler,
15954
15955 create: function (element, options) {
15956 var createNodeMock = defaultTestOptions.createNodeMock;
15957 var isConcurrent = false;
15958 if (typeof options === 'object' && options !== null) {
15959 if (typeof options.createNodeMock === 'function') {
15960 createNodeMock = options.createNodeMock;
15961 }
15962 if (options.unstable_isConcurrent === true) {
15963 isConcurrent = true;
15964 }
15965 }
15966 var container = {
15967 children: [],
15968 createNodeMock: createNodeMock,
15969 tag: 'CONTAINER'
15970 };
15971 var root = createContainer(container, isConcurrent, false);
15972 (function () {
15973 if (!(root != null)) {
15974 {
15975 throw ReactError('something went wrong');
15976 }
15977 }
15978 })();
15979 updateContainer(element, root, null, null);
15980
15981 var entry = {
15982 _Scheduler: Scheduler,
15983
15984 root: undefined, // makes flow happy
15985 // we define a 'getter' for 'root' below using 'Object.defineProperty'
15986 toJSON: function () {
15987 if (root == null || root.current == null || container == null) {
15988 return null;
15989 }
15990 if (container.children.length === 0) {
15991 return null;
15992 }
15993 if (container.children.length === 1) {
15994 return toJSON(container.children[0]);
15995 }
15996 if (container.children.length === 2 && container.children[0].isHidden === true && container.children[1].isHidden === false) {
15997 // Omit timed out children from output entirely, including the fact that we
15998 // temporarily wrap fallback and timed out children in an array.
15999 return toJSON(container.children[1]);
16000 }
16001 var renderedChildren = null;
16002 if (container.children && container.children.length) {
16003 for (var i = 0; i < container.children.length; i++) {
16004 var renderedChild = toJSON(container.children[i]);
16005 if (renderedChild !== null) {
16006 if (renderedChildren === null) {
16007 renderedChildren = [renderedChild];
16008 } else {
16009 renderedChildren.push(renderedChild);
16010 }
16011 }
16012 }
16013 }
16014 return renderedChildren;
16015 },
16016 toTree: function () {
16017 if (root == null || root.current == null) {
16018 return null;
16019 }
16020 return toTree(root.current);
16021 },
16022 update: function (newElement) {
16023 if (root == null || root.current == null) {
16024 return;
16025 }
16026 updateContainer(newElement, root, null, null);
16027 },
16028 unmount: function () {
16029 if (root == null || root.current == null) {
16030 return;
16031 }
16032 updateContainer(null, root, null, null);
16033 container = null;
16034 root = null;
16035 },
16036 getInstance: function () {
16037 if (root == null || root.current == null) {
16038 return null;
16039 }
16040 return getPublicRootInstance(root);
16041 },
16042 unstable_flushSync: function (fn) {
16043 return flushSync$$1(fn);
16044 }
16045 };
16046
16047 Object.defineProperty(entry, 'root', {
16048 configurable: true,
16049 enumerable: true,
16050 get: function () {
16051 if (root === null) {
16052 throw new Error("Can't access .root on unmounted test renderer");
16053 }
16054 var children = getChildren(root.current);
16055 if (children.length === 0) {
16056 throw new Error("Can't access .root on unmounted test renderer");
16057 } else if (children.length === 1) {
16058 // Normally, we skip the root and just give you the child.
16059 return children[0];
16060 } else {
16061 // However, we give you the root if there's more than one root child.
16062 // We could make this the behavior for all cases but it would be a breaking change.
16063 return wrapFiber(root.current);
16064 }
16065 }
16066 });
16067
16068 return entry;
16069 },
16070
16071
16072 /* eslint-disable-next-line camelcase */
16073 unstable_batchedUpdates: batchedUpdates$$1,
16074
16075 act: act
16076};
16077
16078var fiberToWrapper = new WeakMap();
16079function wrapFiber(fiber) {
16080 var wrapper = fiberToWrapper.get(fiber);
16081 if (wrapper === undefined && fiber.alternate !== null) {
16082 wrapper = fiberToWrapper.get(fiber.alternate);
16083 }
16084 if (wrapper === undefined) {
16085 wrapper = new ReactTestInstance(fiber);
16086 fiberToWrapper.set(fiber, wrapper);
16087 }
16088 return wrapper;
16089}
16090
16091// Enable ReactTestRenderer to be used to test DevTools integration.
16092injectIntoDevTools({
16093 findFiberByHostInstance: function () {
16094 throw new Error('TestRenderer does not support findFiberByHostInstance()');
16095 },
16096 bundleType: 1,
16097 version: ReactVersion,
16098 rendererPackageName: 'react-test-renderer'
16099});
16100
16101
16102
16103var ReactTestRenderer = Object.freeze({
16104 default: ReactTestRendererFiber
16105});
16106
16107var ReactTestRenderer$1 = ( ReactTestRenderer && ReactTestRendererFiber ) || ReactTestRenderer;
16108
16109// TODO: decide on the top-level export form.
16110// This is hacky but makes it work with both Rollup and Jest.
16111var reactTestRenderer = ReactTestRenderer$1.default || ReactTestRenderer$1;
16112
16113return reactTestRenderer;
16114
16115})));