UNPKG

484 kBJavaScriptView Raw
1/** @license React v16.8.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')) :
14 typeof define === 'function' && define.amd ? define(['react'], factory) :
15 (global.ReactTestRenderer = factory(global.React));
16}(this, (function (React) { 'use strict';
17
18/**
19 * Use invariant() to assert state which your program assumes to be true.
20 *
21 * Provide sprintf-style format (only %s is supported) and arguments
22 * to provide information about what broke and what you were
23 * expecting.
24 *
25 * The invariant message will be stripped in production, but the invariant
26 * will remain to ensure logic does not differ in production.
27 */
28
29var validateFormat = function () {};
30
31{
32 validateFormat = function (format) {
33 if (format === undefined) {
34 throw new Error('invariant requires an error message argument');
35 }
36 };
37}
38
39function invariant(condition, format, a, b, c, d, e, f) {
40 validateFormat(format);
41
42 if (!condition) {
43 var error = void 0;
44 if (format === undefined) {
45 error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
46 } else {
47 var args = [a, b, c, d, e, f];
48 var argIndex = 0;
49 error = new Error(format.replace(/%s/g, function () {
50 return args[argIndex++];
51 }));
52 error.name = 'Invariant Violation';
53 }
54
55 error.framesToPop = 1; // we don't care about invariant's own frame
56 throw error;
57 }
58}
59
60// Relying on the `invariant()` implementation lets us
61// preserve the format and params in the www builds.
62
63var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
64
65var _assign = ReactInternals.assign;
66
67/**
68 * Similar to invariant but only logs a warning if the condition is not met.
69 * This can be used to log issues in development environments in critical
70 * paths. Removing the logging code for production environments will keep the
71 * same logic and follow the same code paths.
72 */
73
74var warningWithoutStack = function () {};
75
76{
77 warningWithoutStack = function (condition, format) {
78 for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
79 args[_key - 2] = arguments[_key];
80 }
81
82 if (format === undefined) {
83 throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
84 }
85 if (args.length > 8) {
86 // Check before the condition to catch violations early.
87 throw new Error('warningWithoutStack() currently supports at most 8 arguments.');
88 }
89 if (condition) {
90 return;
91 }
92 if (typeof console !== 'undefined') {
93 var argsWithFormat = args.map(function (item) {
94 return '' + item;
95 });
96 argsWithFormat.unshift('Warning: ' + format);
97
98 // We intentionally don't use spread (or .apply) directly because it
99 // breaks IE9: https://github.com/facebook/react/issues/13610
100 Function.prototype.apply.call(console.error, console, argsWithFormat);
101 }
102 try {
103 // --- Welcome to debugging React ---
104 // This error was thrown as a convenience so that you can use this stack
105 // to find the callsite that caused this warning to fire.
106 var argIndex = 0;
107 var message = 'Warning: ' + format.replace(/%s/g, function () {
108 return args[argIndex++];
109 });
110 throw new Error(message);
111 } catch (x) {}
112 };
113}
114
115var warningWithoutStack$1 = warningWithoutStack;
116
117/**
118 * `ReactInstanceMap` maintains a mapping from a public facing stateful
119 * instance (key) and the internal representation (value). This allows public
120 * methods to accept the user facing instance as an argument and map them back
121 * to internal methods.
122 *
123 * Note that this module is currently shared and assumed to be stateless.
124 * If this becomes an actual Map, that will break.
125 */
126
127/**
128 * This API should be called `delete` but we'd have to make sure to always
129 * transform these to strings for IE support. When this transform is fully
130 * supported we can rename it.
131 */
132
133
134function get(key) {
135 return key._reactInternalFiber;
136}
137
138
139
140function set(key, value) {
141 key._reactInternalFiber = value;
142}
143
144var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
145
146// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
147// nor polyfill, then a plain number is used for performance.
148var hasSymbol = typeof Symbol === 'function' && Symbol.for;
149
150var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
151var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
152var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
153var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
154var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
155var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
156var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
157
158var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
159var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
160var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
161var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
162var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
163
164var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
165var FAUX_ITERATOR_SYMBOL = '@@iterator';
166
167function getIteratorFn(maybeIterable) {
168 if (maybeIterable === null || typeof maybeIterable !== 'object') {
169 return null;
170 }
171 var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
172 if (typeof maybeIterator === 'function') {
173 return maybeIterator;
174 }
175 return null;
176}
177
178var Pending = 0;
179var Resolved = 1;
180var Rejected = 2;
181
182function refineResolvedLazyComponent(lazyComponent) {
183 return lazyComponent._status === Resolved ? lazyComponent._result : null;
184}
185
186function getWrappedName(outerType, innerType, wrapperName) {
187 var functionName = innerType.displayName || innerType.name || '';
188 return outerType.displayName || (functionName !== '' ? wrapperName + '(' + functionName + ')' : wrapperName);
189}
190
191function getComponentName(type) {
192 if (type == null) {
193 // Host root, text node or just invalid type.
194 return null;
195 }
196 {
197 if (typeof type.tag === 'number') {
198 warningWithoutStack$1(false, 'Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
199 }
200 }
201 if (typeof type === 'function') {
202 return type.displayName || type.name || null;
203 }
204 if (typeof type === 'string') {
205 return type;
206 }
207 switch (type) {
208 case REACT_CONCURRENT_MODE_TYPE:
209 return 'ConcurrentMode';
210 case REACT_FRAGMENT_TYPE:
211 return 'Fragment';
212 case REACT_PORTAL_TYPE:
213 return 'Portal';
214 case REACT_PROFILER_TYPE:
215 return 'Profiler';
216 case REACT_STRICT_MODE_TYPE:
217 return 'StrictMode';
218 case REACT_SUSPENSE_TYPE:
219 return 'Suspense';
220 }
221 if (typeof type === 'object') {
222 switch (type.$$typeof) {
223 case REACT_CONTEXT_TYPE:
224 return 'Context.Consumer';
225 case REACT_PROVIDER_TYPE:
226 return 'Context.Provider';
227 case REACT_FORWARD_REF_TYPE:
228 return getWrappedName(type, type.render, 'ForwardRef');
229 case REACT_MEMO_TYPE:
230 return getComponentName(type.type);
231 case REACT_LAZY_TYPE:
232 {
233 var thenable = type;
234 var resolvedThenable = refineResolvedLazyComponent(thenable);
235 if (resolvedThenable) {
236 return getComponentName(resolvedThenable);
237 }
238 }
239 }
240 }
241 return null;
242}
243
244var FunctionComponent = 0;
245var ClassComponent = 1;
246var IndeterminateComponent = 2; // Before we know whether it is function or class
247var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
248var HostPortal = 4; // A subtree. Could be an entry point to a different renderer.
249var HostComponent = 5;
250var HostText = 6;
251var Fragment = 7;
252var Mode = 8;
253var ContextConsumer = 9;
254var ContextProvider = 10;
255var ForwardRef = 11;
256var Profiler = 12;
257var SuspenseComponent = 13;
258var MemoComponent = 14;
259var SimpleMemoComponent = 15;
260var LazyComponent = 16;
261var IncompleteClassComponent = 17;
262
263// Don't change these two values. They're used by React Dev Tools.
264var NoEffect = /* */0;
265var PerformedWork = /* */1;
266
267// You can change the rest (and add more).
268var Placement = /* */2;
269var Update = /* */4;
270var PlacementAndUpdate = /* */6;
271var Deletion = /* */8;
272var ContentReset = /* */16;
273var Callback = /* */32;
274var DidCapture = /* */64;
275var Ref = /* */128;
276var Snapshot = /* */256;
277var Passive = /* */512;
278
279// Passive & Update & Callback & Ref & Snapshot
280var LifecycleEffectMask = /* */932;
281
282// Union of all host effects
283var HostEffectMask = /* */1023;
284
285var Incomplete = /* */1024;
286var ShouldCapture = /* */2048;
287
288var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
289
290var MOUNTING = 1;
291var MOUNTED = 2;
292var UNMOUNTED = 3;
293
294function isFiberMountedImpl(fiber) {
295 var node = fiber;
296 if (!fiber.alternate) {
297 // If there is no alternate, this might be a new tree that isn't inserted
298 // yet. If it is, then it will have a pending insertion effect on it.
299 if ((node.effectTag & Placement) !== NoEffect) {
300 return MOUNTING;
301 }
302 while (node.return) {
303 node = node.return;
304 if ((node.effectTag & Placement) !== NoEffect) {
305 return MOUNTING;
306 }
307 }
308 } else {
309 while (node.return) {
310 node = node.return;
311 }
312 }
313 if (node.tag === HostRoot) {
314 // TODO: Check if this was a nested HostRoot when used with
315 // renderContainerIntoSubtree.
316 return MOUNTED;
317 }
318 // If we didn't hit the root, that means that we're in an disconnected tree
319 // that has been unmounted.
320 return UNMOUNTED;
321}
322
323function isFiberMounted(fiber) {
324 return isFiberMountedImpl(fiber) === MOUNTED;
325}
326
327function isMounted(component) {
328 {
329 var owner = ReactCurrentOwner.current;
330 if (owner !== null && owner.tag === ClassComponent) {
331 var ownerFiber = owner;
332 var instance = ownerFiber.stateNode;
333 !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;
334 instance._warnedAboutRefsInRender = true;
335 }
336 }
337
338 var fiber = get(component);
339 if (!fiber) {
340 return false;
341 }
342 return isFiberMountedImpl(fiber) === MOUNTED;
343}
344
345function assertIsMounted(fiber) {
346 !(isFiberMountedImpl(fiber) === MOUNTED) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
347}
348
349function findCurrentFiberUsingSlowPath(fiber) {
350 var alternate = fiber.alternate;
351 if (!alternate) {
352 // If there is no alternate, then we only need to check if it is mounted.
353 var state = isFiberMountedImpl(fiber);
354 !(state !== UNMOUNTED) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
355 if (state === MOUNTING) {
356 return null;
357 }
358 return fiber;
359 }
360 // If we have two possible branches, we'll walk backwards up to the root
361 // to see what path the root points to. On the way we may hit one of the
362 // special cases and we'll deal with them.
363 var a = fiber;
364 var b = alternate;
365 while (true) {
366 var parentA = a.return;
367 var parentB = parentA ? parentA.alternate : null;
368 if (!parentA || !parentB) {
369 // We're at the root.
370 break;
371 }
372
373 // If both copies of the parent fiber point to the same child, we can
374 // assume that the child is current. This happens when we bailout on low
375 // priority: the bailed out fiber's child reuses the current child.
376 if (parentA.child === parentB.child) {
377 var child = parentA.child;
378 while (child) {
379 if (child === a) {
380 // We've determined that A is the current branch.
381 assertIsMounted(parentA);
382 return fiber;
383 }
384 if (child === b) {
385 // We've determined that B is the current branch.
386 assertIsMounted(parentA);
387 return alternate;
388 }
389 child = child.sibling;
390 }
391 // We should never have an alternate for any mounting node. So the only
392 // way this could possibly happen is if this was unmounted, if at all.
393 invariant(false, 'Unable to find node on an unmounted component.');
394 }
395
396 if (a.return !== b.return) {
397 // The return pointer of A and the return pointer of B point to different
398 // fibers. We assume that return pointers never criss-cross, so A must
399 // belong to the child set of A.return, and B must belong to the child
400 // set of B.return.
401 a = parentA;
402 b = parentB;
403 } else {
404 // The return pointers point to the same fiber. We'll have to use the
405 // default, slow path: scan the child sets of each parent alternate to see
406 // which child belongs to which set.
407 //
408 // Search parent A's child set
409 var didFindChild = false;
410 var _child = parentA.child;
411 while (_child) {
412 if (_child === a) {
413 didFindChild = true;
414 a = parentA;
415 b = parentB;
416 break;
417 }
418 if (_child === b) {
419 didFindChild = true;
420 b = parentA;
421 a = parentB;
422 break;
423 }
424 _child = _child.sibling;
425 }
426 if (!didFindChild) {
427 // Search parent B's child set
428 _child = parentB.child;
429 while (_child) {
430 if (_child === a) {
431 didFindChild = true;
432 a = parentB;
433 b = parentA;
434 break;
435 }
436 if (_child === b) {
437 didFindChild = true;
438 b = parentB;
439 a = parentA;
440 break;
441 }
442 _child = _child.sibling;
443 }
444 !didFindChild ? invariant(false, 'Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.') : void 0;
445 }
446 }
447
448 !(a.alternate === b) ? invariant(false, 'Return fibers should always be each others\' alternates. This error is likely caused by a bug in React. Please file an issue.') : void 0;
449 }
450 // If the root is not a host container, we're in a disconnected tree. I.e.
451 // unmounted.
452 !(a.tag === HostRoot) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
453 if (a.stateNode.current === a) {
454 // We've determined that A is the current branch.
455 return fiber;
456 }
457 // Otherwise B has to be current branch.
458 return alternate;
459}
460
461function findCurrentHostFiber(parent) {
462 var currentParent = findCurrentFiberUsingSlowPath(parent);
463 if (!currentParent) {
464 return null;
465 }
466
467 // Next we'll drill down this component to find the first HostComponent/Text.
468 var node = currentParent;
469 while (true) {
470 if (node.tag === HostComponent || node.tag === HostText) {
471 return node;
472 } else if (node.child) {
473 node.child.return = node;
474 node = node.child;
475 continue;
476 }
477 if (node === currentParent) {
478 return null;
479 }
480 while (!node.sibling) {
481 if (!node.return || node.return === currentParent) {
482 return null;
483 }
484 node = node.return;
485 }
486 node.sibling.return = node.return;
487 node = node.sibling;
488 }
489 // Flow needs the return null here, but ESLint complains about it.
490 // eslint-disable-next-line no-unreachable
491 return null;
492}
493
494/**
495 * Similar to invariant but only logs a warning if the condition is not met.
496 * This can be used to log issues in development environments in critical
497 * paths. Removing the logging code for production environments will keep the
498 * same logic and follow the same code paths.
499 */
500
501var warning = warningWithoutStack$1;
502
503{
504 warning = function (condition, format) {
505 if (condition) {
506 return;
507 }
508 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
509 var stack = ReactDebugCurrentFrame.getStackAddendum();
510 // eslint-disable-next-line react-internal/warning-and-invariant-args
511
512 for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
513 args[_key - 2] = arguments[_key];
514 }
515
516 warningWithoutStack$1.apply(undefined, [false, format + '%s'].concat(args, [stack]));
517 };
518}
519
520var warning$1 = warning;
521
522// Current virtual time
523var nowImplementation = function () {
524 return 0;
525};
526var scheduledCallback = null;
527var yieldedValues = [];
528
529var didStop = false;
530var expectedNumberOfYields = -1;
531
532function scheduleDeferredCallback$1(callback, options) {
533 scheduledCallback = callback;
534 var fakeCallbackId = 0;
535 return fakeCallbackId;
536}
537
538function cancelDeferredCallback$1(timeoutID) {
539 scheduledCallback = null;
540}
541
542function setNowImplementation(implementation) {
543 nowImplementation = implementation;
544}
545
546function shouldYield$1() {
547 if (expectedNumberOfYields !== -1 && yieldedValues.length >= expectedNumberOfYields) {
548 // We yielded at least as many values as expected. Stop rendering.
549 didStop = true;
550 return true;
551 }
552 // Keep rendering.
553 return false;
554}
555
556function flushAll() {
557 yieldedValues = [];
558 while (scheduledCallback !== null) {
559 var cb = scheduledCallback;
560 scheduledCallback = null;
561 cb();
562 }
563 var values = yieldedValues;
564 yieldedValues = [];
565 return values;
566}
567
568function flushNumberOfYields(count) {
569 expectedNumberOfYields = count;
570 didStop = false;
571 yieldedValues = [];
572 try {
573 while (scheduledCallback !== null && !didStop) {
574 var cb = scheduledCallback;
575 scheduledCallback = null;
576 cb();
577 }
578 return yieldedValues;
579 } finally {
580 expectedNumberOfYields = -1;
581 didStop = false;
582 yieldedValues = [];
583 }
584}
585
586function yieldValue(value) {
587 yieldedValues.push(value);
588}
589
590function clearYields() {
591 var values = yieldedValues;
592 yieldedValues = [];
593 return values;
594}
595
596// Renderers that don't support persistence
597// can re-export everything from this module.
598
599function shim() {
600 invariant(false, 'The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue.');
601}
602
603// Persistence (when unsupported)
604var supportsPersistence = false;
605var cloneInstance = shim;
606var createContainerChildSet = shim;
607var appendChildToContainerChildSet = shim;
608var finalizeContainerChildren = shim;
609var replaceContainerChildren = shim;
610var cloneHiddenInstance = shim;
611var cloneUnhiddenInstance = shim;
612var createHiddenTextInstance = shim;
613
614// Renderers that don't support hydration
615// can re-export everything from this module.
616
617function shim$1() {
618 invariant(false, 'The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue.');
619}
620
621// Hydration (when unsupported)
622var supportsHydration = false;
623var canHydrateInstance = shim$1;
624var canHydrateTextInstance = shim$1;
625var getNextHydratableSibling = shim$1;
626var getFirstHydratableChild = shim$1;
627var hydrateInstance = shim$1;
628var hydrateTextInstance = shim$1;
629var didNotMatchHydratedContainerTextInstance = shim$1;
630var didNotMatchHydratedTextInstance = shim$1;
631var didNotHydrateContainerInstance = shim$1;
632var didNotHydrateInstance = shim$1;
633var didNotFindHydratableContainerInstance = shim$1;
634var didNotFindHydratableContainerTextInstance = shim$1;
635var didNotFindHydratableInstance = shim$1;
636var didNotFindHydratableTextInstance = shim$1;
637
638var NO_CONTEXT = {};
639var UPDATE_SIGNAL = {};
640{
641 Object.freeze(NO_CONTEXT);
642 Object.freeze(UPDATE_SIGNAL);
643}
644
645function getPublicInstance(inst) {
646 switch (inst.tag) {
647 case 'INSTANCE':
648 var _createNodeMock = inst.rootContainerInstance.createNodeMock;
649 return _createNodeMock({
650 type: inst.type,
651 props: inst.props
652 });
653 default:
654 return inst;
655 }
656}
657
658function appendChild(parentInstance, child) {
659 {
660 !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;
661 }
662 var index = parentInstance.children.indexOf(child);
663 if (index !== -1) {
664 parentInstance.children.splice(index, 1);
665 }
666 parentInstance.children.push(child);
667}
668
669function insertBefore(parentInstance, child, beforeChild) {
670 var index = parentInstance.children.indexOf(child);
671 if (index !== -1) {
672 parentInstance.children.splice(index, 1);
673 }
674 var beforeIndex = parentInstance.children.indexOf(beforeChild);
675 parentInstance.children.splice(beforeIndex, 0, child);
676}
677
678function removeChild(parentInstance, child) {
679 var index = parentInstance.children.indexOf(child);
680 parentInstance.children.splice(index, 1);
681}
682
683function getRootHostContext(rootContainerInstance) {
684 return NO_CONTEXT;
685}
686
687function getChildHostContext(parentHostContext, type, rootContainerInstance) {
688 return NO_CONTEXT;
689}
690
691function prepareForCommit(containerInfo) {
692 // noop
693}
694
695function resetAfterCommit(containerInfo) {
696 // noop
697}
698
699function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
700 return {
701 type: type,
702 props: props,
703 isHidden: false,
704 children: [],
705 rootContainerInstance: rootContainerInstance,
706 tag: 'INSTANCE'
707 };
708}
709
710function appendInitialChild(parentInstance, child) {
711 var index = parentInstance.children.indexOf(child);
712 if (index !== -1) {
713 parentInstance.children.splice(index, 1);
714 }
715 parentInstance.children.push(child);
716}
717
718function finalizeInitialChildren(testElement, type, props, rootContainerInstance, hostContext) {
719 return false;
720}
721
722function prepareUpdate(testElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
723 return UPDATE_SIGNAL;
724}
725
726function shouldSetTextContent(type, props) {
727 return false;
728}
729
730function shouldDeprioritizeSubtree(type, props) {
731 return false;
732}
733
734function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
735 return {
736 text: text,
737 isHidden: false,
738 tag: 'TEXT'
739 };
740}
741
742var isPrimaryRenderer = false;
743// This approach enables `now` to be mocked by tests,
744// Even after the reconciler has initialized and read host config values.
745var now = function () {
746 return nowImplementation();
747};
748var scheduleDeferredCallback$$1 = scheduleDeferredCallback$1;
749var cancelDeferredCallback$$1 = cancelDeferredCallback$1;
750var shouldYield$$1 = shouldYield$1;
751
752var scheduleTimeout = setTimeout;
753var cancelTimeout = clearTimeout;
754var noTimeout = -1;
755var schedulePassiveEffects = scheduleDeferredCallback$$1;
756var cancelPassiveEffects = cancelDeferredCallback$$1;
757
758// -------------------
759// Mutation
760// -------------------
761
762var supportsMutation = true;
763
764function commitUpdate(instance, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
765 instance.type = type;
766 instance.props = newProps;
767}
768
769
770
771function commitTextUpdate(textInstance, oldText, newText) {
772 textInstance.text = newText;
773}
774
775function resetTextContent(testElement) {
776 // noop
777}
778
779var appendChildToContainer = appendChild;
780var insertInContainerBefore = insertBefore;
781var removeChildFromContainer = removeChild;
782
783function hideInstance(instance) {
784 instance.isHidden = true;
785}
786
787function hideTextInstance(textInstance) {
788 textInstance.isHidden = true;
789}
790
791function unhideInstance(instance, props) {
792 instance.isHidden = false;
793}
794
795function unhideTextInstance(textInstance, text) {
796 textInstance.isHidden = false;
797}
798
799/**
800 * Copyright (c) 2013-present, Facebook, Inc.
801 *
802 * This source code is licensed under the MIT license found in the
803 * LICENSE file in the root directory of this source tree.
804 */
805
806
807
808var ReactPropTypesSecret$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
809
810var ReactPropTypesSecret_1 = ReactPropTypesSecret$1;
811
812/**
813 * Copyright (c) 2013-present, Facebook, Inc.
814 *
815 * This source code is licensed under the MIT license found in the
816 * LICENSE file in the root directory of this source tree.
817 */
818
819
820
821var printWarning = function() {};
822
823{
824 var ReactPropTypesSecret = ReactPropTypesSecret_1;
825 var loggedTypeFailures = {};
826
827 printWarning = function(text) {
828 var message = 'Warning: ' + text;
829 if (typeof console !== 'undefined') {
830 console.error(message);
831 }
832 try {
833 // --- Welcome to debugging React ---
834 // This error was thrown as a convenience so that you can use this stack
835 // to find the callsite that caused this warning to fire.
836 throw new Error(message);
837 } catch (x) {}
838 };
839}
840
841/**
842 * Assert that the values match with the type specs.
843 * Error messages are memorized and will only be shown once.
844 *
845 * @param {object} typeSpecs Map of name to a ReactPropType
846 * @param {object} values Runtime values that need to be type-checked
847 * @param {string} location e.g. "prop", "context", "child context"
848 * @param {string} componentName Name of the component for error messages.
849 * @param {?Function} getStack Returns the component stack.
850 * @private
851 */
852function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
853 {
854 for (var typeSpecName in typeSpecs) {
855 if (typeSpecs.hasOwnProperty(typeSpecName)) {
856 var error;
857 // Prop type validation may throw. In case they do, we don't want to
858 // fail the render phase where it didn't fail before. So we log it.
859 // After these have been cleaned up, we'll let them throw.
860 try {
861 // This is intentionally an invariant that gets caught. It's the same
862 // behavior as without this statement except with a better message.
863 if (typeof typeSpecs[typeSpecName] !== 'function') {
864 var err = Error(
865 (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
866 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
867 );
868 err.name = 'Invariant Violation';
869 throw err;
870 }
871 error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
872 } catch (ex) {
873 error = ex;
874 }
875 if (error && !(error instanceof Error)) {
876 printWarning(
877 (componentName || 'React class') + ': type specification of ' +
878 location + ' `' + typeSpecName + '` is invalid; the type checker ' +
879 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
880 'You may have forgotten to pass an argument to the type checker ' +
881 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
882 'shape all require an argument).'
883 );
884
885 }
886 if (error instanceof Error && !(error.message in loggedTypeFailures)) {
887 // Only monitor this failure once because there tends to be a lot of the
888 // same error.
889 loggedTypeFailures[error.message] = true;
890
891 var stack = getStack ? getStack() : '';
892
893 printWarning(
894 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
895 );
896 }
897 }
898 }
899 }
900}
901
902var checkPropTypes_1 = checkPropTypes;
903
904var BEFORE_SLASH_RE = /^(.*)[\\\/]/;
905
906var describeComponentFrame = function (name, source, ownerName) {
907 var sourceInfo = '';
908 if (source) {
909 var path = source.fileName;
910 var fileName = path.replace(BEFORE_SLASH_RE, '');
911 {
912 // In DEV, include code for a common special case:
913 // prefer "folder/index.js" instead of just "index.js".
914 if (/^index\./.test(fileName)) {
915 var match = path.match(BEFORE_SLASH_RE);
916 if (match) {
917 var pathBeforeSlash = match[1];
918 if (pathBeforeSlash) {
919 var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
920 fileName = folderName + '/' + fileName;
921 }
922 }
923 }
924 }
925 sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
926 } else if (ownerName) {
927 sourceInfo = ' (created by ' + ownerName + ')';
928 }
929 return '\n in ' + (name || 'Unknown') + sourceInfo;
930};
931
932var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
933
934function describeFiber(fiber) {
935 switch (fiber.tag) {
936 case HostRoot:
937 case HostPortal:
938 case HostText:
939 case Fragment:
940 case ContextProvider:
941 case ContextConsumer:
942 return '';
943 default:
944 var owner = fiber._debugOwner;
945 var source = fiber._debugSource;
946 var name = getComponentName(fiber.type);
947 var ownerName = null;
948 if (owner) {
949 ownerName = getComponentName(owner.type);
950 }
951 return describeComponentFrame(name, source, ownerName);
952 }
953}
954
955function getStackByFiberInDevAndProd(workInProgress) {
956 var info = '';
957 var node = workInProgress;
958 do {
959 info += describeFiber(node);
960 node = node.return;
961 } while (node);
962 return info;
963}
964
965var current = null;
966var phase = null;
967
968function getCurrentFiberOwnerNameInDevOrNull() {
969 {
970 if (current === null) {
971 return null;
972 }
973 var owner = current._debugOwner;
974 if (owner !== null && typeof owner !== 'undefined') {
975 return getComponentName(owner.type);
976 }
977 }
978 return null;
979}
980
981function getCurrentFiberStackInDev() {
982 {
983 if (current === null) {
984 return '';
985 }
986 // Safe because if current fiber exists, we are reconciling,
987 // and it is guaranteed to be the work-in-progress version.
988 return getStackByFiberInDevAndProd(current);
989 }
990 return '';
991}
992
993function resetCurrentFiber() {
994 {
995 ReactDebugCurrentFrame.getCurrentStack = null;
996 current = null;
997 phase = null;
998 }
999}
1000
1001function setCurrentFiber(fiber) {
1002 {
1003 ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev;
1004 current = fiber;
1005 phase = null;
1006 }
1007}
1008
1009function setCurrentPhase(lifeCyclePhase) {
1010 {
1011 phase = lifeCyclePhase;
1012 }
1013}
1014
1015var debugRenderPhaseSideEffects = false;
1016var debugRenderPhaseSideEffectsForStrictMode = false;
1017var enableUserTimingAPI = true;
1018var warnAboutDeprecatedLifecycles = false;
1019var replayFailedUnitOfWorkWithInvokeGuardedCallback = false;
1020var enableProfilerTimer = false;
1021var enableSchedulerTracing = false;
1022
1023
1024
1025
1026
1027
1028// Only used in www builds.
1029
1030// Prefix measurements so that it's possible to filter them.
1031// Longer prefixes are hard to read in DevTools.
1032var reactEmoji = '\u269B';
1033var warningEmoji = '\u26D4';
1034var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function';
1035
1036// Keep track of current fiber so that we know the path to unwind on pause.
1037// TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them?
1038var currentFiber = null;
1039// If we're in the middle of user code, which fiber and method is it?
1040// Reusing `currentFiber` would be confusing for this because user code fiber
1041// can change during commit phase too, but we don't need to unwind it (since
1042// lifecycles in the commit phase don't resemble a tree).
1043var currentPhase = null;
1044var currentPhaseFiber = null;
1045// Did lifecycle hook schedule an update? This is often a performance problem,
1046// so we will keep track of it, and include it in the report.
1047// Track commits caused by cascading updates.
1048var isCommitting = false;
1049var hasScheduledUpdateInCurrentCommit = false;
1050var hasScheduledUpdateInCurrentPhase = false;
1051var commitCountInCurrentWorkLoop = 0;
1052var effectCountInCurrentCommit = 0;
1053var isWaitingForCallback = false;
1054// During commits, we only show a measurement once per method name
1055// to avoid stretch the commit phase with measurement overhead.
1056var labelsInCurrentCommit = new Set();
1057
1058var formatMarkName = function (markName) {
1059 return reactEmoji + ' ' + markName;
1060};
1061
1062var formatLabel = function (label, warning) {
1063 var prefix = warning ? warningEmoji + ' ' : reactEmoji + ' ';
1064 var suffix = warning ? ' Warning: ' + warning : '';
1065 return '' + prefix + label + suffix;
1066};
1067
1068var beginMark = function (markName) {
1069 performance.mark(formatMarkName(markName));
1070};
1071
1072var clearMark = function (markName) {
1073 performance.clearMarks(formatMarkName(markName));
1074};
1075
1076var endMark = function (label, markName, warning) {
1077 var formattedMarkName = formatMarkName(markName);
1078 var formattedLabel = formatLabel(label, warning);
1079 try {
1080 performance.measure(formattedLabel, formattedMarkName);
1081 } catch (err) {}
1082 // If previous mark was missing for some reason, this will throw.
1083 // This could only happen if React crashed in an unexpected place earlier.
1084 // Don't pile on with more errors.
1085
1086 // Clear marks immediately to avoid growing buffer.
1087 performance.clearMarks(formattedMarkName);
1088 performance.clearMeasures(formattedLabel);
1089};
1090
1091var getFiberMarkName = function (label, debugID) {
1092 return label + ' (#' + debugID + ')';
1093};
1094
1095var getFiberLabel = function (componentName, isMounted, phase) {
1096 if (phase === null) {
1097 // These are composite component total time measurements.
1098 return componentName + ' [' + (isMounted ? 'update' : 'mount') + ']';
1099 } else {
1100 // Composite component methods.
1101 return componentName + '.' + phase;
1102 }
1103};
1104
1105var beginFiberMark = function (fiber, phase) {
1106 var componentName = getComponentName(fiber.type) || 'Unknown';
1107 var debugID = fiber._debugID;
1108 var isMounted = fiber.alternate !== null;
1109 var label = getFiberLabel(componentName, isMounted, phase);
1110
1111 if (isCommitting && labelsInCurrentCommit.has(label)) {
1112 // During the commit phase, we don't show duplicate labels because
1113 // there is a fixed overhead for every measurement, and we don't
1114 // want to stretch the commit phase beyond necessary.
1115 return false;
1116 }
1117 labelsInCurrentCommit.add(label);
1118
1119 var markName = getFiberMarkName(label, debugID);
1120 beginMark(markName);
1121 return true;
1122};
1123
1124var clearFiberMark = function (fiber, phase) {
1125 var componentName = getComponentName(fiber.type) || 'Unknown';
1126 var debugID = fiber._debugID;
1127 var isMounted = fiber.alternate !== null;
1128 var label = getFiberLabel(componentName, isMounted, phase);
1129 var markName = getFiberMarkName(label, debugID);
1130 clearMark(markName);
1131};
1132
1133var endFiberMark = function (fiber, phase, warning) {
1134 var componentName = getComponentName(fiber.type) || 'Unknown';
1135 var debugID = fiber._debugID;
1136 var isMounted = fiber.alternate !== null;
1137 var label = getFiberLabel(componentName, isMounted, phase);
1138 var markName = getFiberMarkName(label, debugID);
1139 endMark(label, markName, warning);
1140};
1141
1142var shouldIgnoreFiber = function (fiber) {
1143 // Host components should be skipped in the timeline.
1144 // We could check typeof fiber.type, but does this work with RN?
1145 switch (fiber.tag) {
1146 case HostRoot:
1147 case HostComponent:
1148 case HostText:
1149 case HostPortal:
1150 case Fragment:
1151 case ContextProvider:
1152 case ContextConsumer:
1153 case Mode:
1154 return true;
1155 default:
1156 return false;
1157 }
1158};
1159
1160var clearPendingPhaseMeasurement = function () {
1161 if (currentPhase !== null && currentPhaseFiber !== null) {
1162 clearFiberMark(currentPhaseFiber, currentPhase);
1163 }
1164 currentPhaseFiber = null;
1165 currentPhase = null;
1166 hasScheduledUpdateInCurrentPhase = false;
1167};
1168
1169var pauseTimers = function () {
1170 // Stops all currently active measurements so that they can be resumed
1171 // if we continue in a later deferred loop from the same unit of work.
1172 var fiber = currentFiber;
1173 while (fiber) {
1174 if (fiber._debugIsCurrentlyTiming) {
1175 endFiberMark(fiber, null, null);
1176 }
1177 fiber = fiber.return;
1178 }
1179};
1180
1181var resumeTimersRecursively = function (fiber) {
1182 if (fiber.return !== null) {
1183 resumeTimersRecursively(fiber.return);
1184 }
1185 if (fiber._debugIsCurrentlyTiming) {
1186 beginFiberMark(fiber, null);
1187 }
1188};
1189
1190var resumeTimers = function () {
1191 // Resumes all measurements that were active during the last deferred loop.
1192 if (currentFiber !== null) {
1193 resumeTimersRecursively(currentFiber);
1194 }
1195};
1196
1197function recordEffect() {
1198 if (enableUserTimingAPI) {
1199 effectCountInCurrentCommit++;
1200 }
1201}
1202
1203function recordScheduleUpdate() {
1204 if (enableUserTimingAPI) {
1205 if (isCommitting) {
1206 hasScheduledUpdateInCurrentCommit = true;
1207 }
1208 if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') {
1209 hasScheduledUpdateInCurrentPhase = true;
1210 }
1211 }
1212}
1213
1214function startRequestCallbackTimer() {
1215 if (enableUserTimingAPI) {
1216 if (supportsUserTiming && !isWaitingForCallback) {
1217 isWaitingForCallback = true;
1218 beginMark('(Waiting for async callback...)');
1219 }
1220 }
1221}
1222
1223function stopRequestCallbackTimer(didExpire, expirationTime) {
1224 if (enableUserTimingAPI) {
1225 if (supportsUserTiming) {
1226 isWaitingForCallback = false;
1227 var warning = didExpire ? 'React was blocked by main thread' : null;
1228 endMark('(Waiting for async callback... will force flush in ' + expirationTime + ' ms)', '(Waiting for async callback...)', warning);
1229 }
1230 }
1231}
1232
1233function startWorkTimer(fiber) {
1234 if (enableUserTimingAPI) {
1235 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
1236 return;
1237 }
1238 // If we pause, this is the fiber to unwind from.
1239 currentFiber = fiber;
1240 if (!beginFiberMark(fiber, null)) {
1241 return;
1242 }
1243 fiber._debugIsCurrentlyTiming = true;
1244 }
1245}
1246
1247function cancelWorkTimer(fiber) {
1248 if (enableUserTimingAPI) {
1249 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
1250 return;
1251 }
1252 // Remember we shouldn't complete measurement for this fiber.
1253 // Otherwise flamechart will be deep even for small updates.
1254 fiber._debugIsCurrentlyTiming = false;
1255 clearFiberMark(fiber, null);
1256 }
1257}
1258
1259function stopWorkTimer(fiber) {
1260 if (enableUserTimingAPI) {
1261 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
1262 return;
1263 }
1264 // If we pause, its parent is the fiber to unwind from.
1265 currentFiber = fiber.return;
1266 if (!fiber._debugIsCurrentlyTiming) {
1267 return;
1268 }
1269 fiber._debugIsCurrentlyTiming = false;
1270 endFiberMark(fiber, null, null);
1271 }
1272}
1273
1274function stopFailedWorkTimer(fiber) {
1275 if (enableUserTimingAPI) {
1276 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
1277 return;
1278 }
1279 // If we pause, its parent is the fiber to unwind from.
1280 currentFiber = fiber.return;
1281 if (!fiber._debugIsCurrentlyTiming) {
1282 return;
1283 }
1284 fiber._debugIsCurrentlyTiming = false;
1285 var warning = fiber.tag === SuspenseComponent ? 'Rendering was suspended' : 'An error was thrown inside this error boundary';
1286 endFiberMark(fiber, null, warning);
1287 }
1288}
1289
1290function startPhaseTimer(fiber, phase) {
1291 if (enableUserTimingAPI) {
1292 if (!supportsUserTiming) {
1293 return;
1294 }
1295 clearPendingPhaseMeasurement();
1296 if (!beginFiberMark(fiber, phase)) {
1297 return;
1298 }
1299 currentPhaseFiber = fiber;
1300 currentPhase = phase;
1301 }
1302}
1303
1304function stopPhaseTimer() {
1305 if (enableUserTimingAPI) {
1306 if (!supportsUserTiming) {
1307 return;
1308 }
1309 if (currentPhase !== null && currentPhaseFiber !== null) {
1310 var warning = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null;
1311 endFiberMark(currentPhaseFiber, currentPhase, warning);
1312 }
1313 currentPhase = null;
1314 currentPhaseFiber = null;
1315 }
1316}
1317
1318function startWorkLoopTimer(nextUnitOfWork) {
1319 if (enableUserTimingAPI) {
1320 currentFiber = nextUnitOfWork;
1321 if (!supportsUserTiming) {
1322 return;
1323 }
1324 commitCountInCurrentWorkLoop = 0;
1325 // This is top level call.
1326 // Any other measurements are performed within.
1327 beginMark('(React Tree Reconciliation)');
1328 // Resume any measurements that were in progress during the last loop.
1329 resumeTimers();
1330 }
1331}
1332
1333function stopWorkLoopTimer(interruptedBy, didCompleteRoot) {
1334 if (enableUserTimingAPI) {
1335 if (!supportsUserTiming) {
1336 return;
1337 }
1338 var warning = null;
1339 if (interruptedBy !== null) {
1340 if (interruptedBy.tag === HostRoot) {
1341 warning = 'A top-level update interrupted the previous render';
1342 } else {
1343 var componentName = getComponentName(interruptedBy.type) || 'Unknown';
1344 warning = 'An update to ' + componentName + ' interrupted the previous render';
1345 }
1346 } else if (commitCountInCurrentWorkLoop > 1) {
1347 warning = 'There were cascading updates';
1348 }
1349 commitCountInCurrentWorkLoop = 0;
1350 var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)';
1351 // Pause any measurements until the next loop.
1352 pauseTimers();
1353 endMark(label, '(React Tree Reconciliation)', warning);
1354 }
1355}
1356
1357function startCommitTimer() {
1358 if (enableUserTimingAPI) {
1359 if (!supportsUserTiming) {
1360 return;
1361 }
1362 isCommitting = true;
1363 hasScheduledUpdateInCurrentCommit = false;
1364 labelsInCurrentCommit.clear();
1365 beginMark('(Committing Changes)');
1366 }
1367}
1368
1369function stopCommitTimer() {
1370 if (enableUserTimingAPI) {
1371 if (!supportsUserTiming) {
1372 return;
1373 }
1374
1375 var warning = null;
1376 if (hasScheduledUpdateInCurrentCommit) {
1377 warning = 'Lifecycle hook scheduled a cascading update';
1378 } else if (commitCountInCurrentWorkLoop > 0) {
1379 warning = 'Caused by a cascading update in earlier commit';
1380 }
1381 hasScheduledUpdateInCurrentCommit = false;
1382 commitCountInCurrentWorkLoop++;
1383 isCommitting = false;
1384 labelsInCurrentCommit.clear();
1385
1386 endMark('(Committing Changes)', '(Committing Changes)', warning);
1387 }
1388}
1389
1390function startCommitSnapshotEffectsTimer() {
1391 if (enableUserTimingAPI) {
1392 if (!supportsUserTiming) {
1393 return;
1394 }
1395 effectCountInCurrentCommit = 0;
1396 beginMark('(Committing Snapshot Effects)');
1397 }
1398}
1399
1400function stopCommitSnapshotEffectsTimer() {
1401 if (enableUserTimingAPI) {
1402 if (!supportsUserTiming) {
1403 return;
1404 }
1405 var count = effectCountInCurrentCommit;
1406 effectCountInCurrentCommit = 0;
1407 endMark('(Committing Snapshot Effects: ' + count + ' Total)', '(Committing Snapshot Effects)', null);
1408 }
1409}
1410
1411function startCommitHostEffectsTimer() {
1412 if (enableUserTimingAPI) {
1413 if (!supportsUserTiming) {
1414 return;
1415 }
1416 effectCountInCurrentCommit = 0;
1417 beginMark('(Committing Host Effects)');
1418 }
1419}
1420
1421function stopCommitHostEffectsTimer() {
1422 if (enableUserTimingAPI) {
1423 if (!supportsUserTiming) {
1424 return;
1425 }
1426 var count = effectCountInCurrentCommit;
1427 effectCountInCurrentCommit = 0;
1428 endMark('(Committing Host Effects: ' + count + ' Total)', '(Committing Host Effects)', null);
1429 }
1430}
1431
1432function startCommitLifeCyclesTimer() {
1433 if (enableUserTimingAPI) {
1434 if (!supportsUserTiming) {
1435 return;
1436 }
1437 effectCountInCurrentCommit = 0;
1438 beginMark('(Calling Lifecycle Methods)');
1439 }
1440}
1441
1442function stopCommitLifeCyclesTimer() {
1443 if (enableUserTimingAPI) {
1444 if (!supportsUserTiming) {
1445 return;
1446 }
1447 var count = effectCountInCurrentCommit;
1448 effectCountInCurrentCommit = 0;
1449 endMark('(Calling Lifecycle Methods: ' + count + ' Total)', '(Calling Lifecycle Methods)', null);
1450 }
1451}
1452
1453var valueStack = [];
1454
1455var fiberStack = void 0;
1456
1457{
1458 fiberStack = [];
1459}
1460
1461var index = -1;
1462
1463function createCursor(defaultValue) {
1464 return {
1465 current: defaultValue
1466 };
1467}
1468
1469function pop(cursor, fiber) {
1470 if (index < 0) {
1471 {
1472 warningWithoutStack$1(false, 'Unexpected pop.');
1473 }
1474 return;
1475 }
1476
1477 {
1478 if (fiber !== fiberStack[index]) {
1479 warningWithoutStack$1(false, 'Unexpected Fiber popped.');
1480 }
1481 }
1482
1483 cursor.current = valueStack[index];
1484
1485 valueStack[index] = null;
1486
1487 {
1488 fiberStack[index] = null;
1489 }
1490
1491 index--;
1492}
1493
1494function push(cursor, value, fiber) {
1495 index++;
1496
1497 valueStack[index] = cursor.current;
1498
1499 {
1500 fiberStack[index] = fiber;
1501 }
1502
1503 cursor.current = value;
1504}
1505
1506function checkThatStackIsEmpty() {
1507 {
1508 if (index !== -1) {
1509 warningWithoutStack$1(false, 'Expected an empty stack. Something was not reset properly.');
1510 }
1511 }
1512}
1513
1514function resetStackAfterFatalErrorInDev() {
1515 {
1516 index = -1;
1517 valueStack.length = 0;
1518 fiberStack.length = 0;
1519 }
1520}
1521
1522var warnedAboutMissingGetChildContext = void 0;
1523
1524{
1525 warnedAboutMissingGetChildContext = {};
1526}
1527
1528var emptyContextObject = {};
1529{
1530 Object.freeze(emptyContextObject);
1531}
1532
1533// A cursor to the current merged context object on the stack.
1534var contextStackCursor = createCursor(emptyContextObject);
1535// A cursor to a boolean indicating whether the context has changed.
1536var didPerformWorkStackCursor = createCursor(false);
1537// Keep track of the previous context object that was on the stack.
1538// We use this to get access to the parent context after we have already
1539// pushed the next context provider, and now need to merge their contexts.
1540var previousContext = emptyContextObject;
1541
1542function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
1543 if (didPushOwnContextIfProvider && isContextProvider(Component)) {
1544 // If the fiber is a context provider itself, when we read its context
1545 // we may have already pushed its own child context on the stack. A context
1546 // provider should not "see" its own child context. Therefore we read the
1547 // previous (parent) context instead for a context provider.
1548 return previousContext;
1549 }
1550 return contextStackCursor.current;
1551}
1552
1553function cacheContext(workInProgress, unmaskedContext, maskedContext) {
1554 var instance = workInProgress.stateNode;
1555 instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
1556 instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
1557}
1558
1559function getMaskedContext(workInProgress, unmaskedContext) {
1560 var type = workInProgress.type;
1561 var contextTypes = type.contextTypes;
1562 if (!contextTypes) {
1563 return emptyContextObject;
1564 }
1565
1566 // Avoid recreating masked context unless unmasked context has changed.
1567 // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
1568 // This may trigger infinite loops if componentWillReceiveProps calls setState.
1569 var instance = workInProgress.stateNode;
1570 if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
1571 return instance.__reactInternalMemoizedMaskedChildContext;
1572 }
1573
1574 var context = {};
1575 for (var key in contextTypes) {
1576 context[key] = unmaskedContext[key];
1577 }
1578
1579 {
1580 var name = getComponentName(type) || 'Unknown';
1581 checkPropTypes_1(contextTypes, context, 'context', name, getCurrentFiberStackInDev);
1582 }
1583
1584 // Cache unmasked context so we can avoid recreating masked context unless necessary.
1585 // Context is created before the class component is instantiated so check for instance.
1586 if (instance) {
1587 cacheContext(workInProgress, unmaskedContext, context);
1588 }
1589
1590 return context;
1591}
1592
1593function hasContextChanged() {
1594 return didPerformWorkStackCursor.current;
1595}
1596
1597function isContextProvider(type) {
1598 var childContextTypes = type.childContextTypes;
1599 return childContextTypes !== null && childContextTypes !== undefined;
1600}
1601
1602function popContext(fiber) {
1603 pop(didPerformWorkStackCursor, fiber);
1604 pop(contextStackCursor, fiber);
1605}
1606
1607function popTopLevelContextObject(fiber) {
1608 pop(didPerformWorkStackCursor, fiber);
1609 pop(contextStackCursor, fiber);
1610}
1611
1612function pushTopLevelContextObject(fiber, context, didChange) {
1613 !(contextStackCursor.current === emptyContextObject) ? invariant(false, 'Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue.') : void 0;
1614
1615 push(contextStackCursor, context, fiber);
1616 push(didPerformWorkStackCursor, didChange, fiber);
1617}
1618
1619function processChildContext(fiber, type, parentContext) {
1620 var instance = fiber.stateNode;
1621 var childContextTypes = type.childContextTypes;
1622
1623 // TODO (bvaughn) Replace this behavior with an invariant() in the future.
1624 // It has only been added in Fiber to match the (unintentional) behavior in Stack.
1625 if (typeof instance.getChildContext !== 'function') {
1626 {
1627 var componentName = getComponentName(type) || 'Unknown';
1628
1629 if (!warnedAboutMissingGetChildContext[componentName]) {
1630 warnedAboutMissingGetChildContext[componentName] = true;
1631 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);
1632 }
1633 }
1634 return parentContext;
1635 }
1636
1637 var childContext = void 0;
1638 {
1639 setCurrentPhase('getChildContext');
1640 }
1641 startPhaseTimer(fiber, 'getChildContext');
1642 childContext = instance.getChildContext();
1643 stopPhaseTimer();
1644 {
1645 setCurrentPhase(null);
1646 }
1647 for (var contextKey in childContext) {
1648 !(contextKey in childContextTypes) ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', getComponentName(type) || 'Unknown', contextKey) : void 0;
1649 }
1650 {
1651 var name = getComponentName(type) || 'Unknown';
1652 checkPropTypes_1(childContextTypes, childContext, 'child context', name,
1653 // In practice, there is one case in which we won't get a stack. It's when
1654 // somebody calls unstable_renderSubtreeIntoContainer() and we process
1655 // context from the parent component instance. The stack will be missing
1656 // because it's outside of the reconciliation, and so the pointer has not
1657 // been set. This is rare and doesn't matter. We'll also remove that API.
1658 getCurrentFiberStackInDev);
1659 }
1660
1661 return _assign({}, parentContext, childContext);
1662}
1663
1664function pushContextProvider(workInProgress) {
1665 var instance = workInProgress.stateNode;
1666 // We push the context as early as possible to ensure stack integrity.
1667 // If the instance does not exist yet, we will push null at first,
1668 // and replace it on the stack later when invalidating the context.
1669 var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject;
1670
1671 // Remember the parent context so we can merge with it later.
1672 // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
1673 previousContext = contextStackCursor.current;
1674 push(contextStackCursor, memoizedMergedChildContext, workInProgress);
1675 push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
1676
1677 return true;
1678}
1679
1680function invalidateContextProvider(workInProgress, type, didChange) {
1681 var instance = workInProgress.stateNode;
1682 !instance ? invariant(false, 'Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue.') : void 0;
1683
1684 if (didChange) {
1685 // Merge parent and own context.
1686 // Skip this if we're not updating due to sCU.
1687 // This avoids unnecessarily recomputing memoized values.
1688 var mergedContext = processChildContext(workInProgress, type, previousContext);
1689 instance.__reactInternalMemoizedMergedChildContext = mergedContext;
1690
1691 // Replace the old (or empty) context with the new one.
1692 // It is important to unwind the context in the reverse order.
1693 pop(didPerformWorkStackCursor, workInProgress);
1694 pop(contextStackCursor, workInProgress);
1695 // Now push the new context and mark that it has changed.
1696 push(contextStackCursor, mergedContext, workInProgress);
1697 push(didPerformWorkStackCursor, didChange, workInProgress);
1698 } else {
1699 pop(didPerformWorkStackCursor, workInProgress);
1700 push(didPerformWorkStackCursor, didChange, workInProgress);
1701 }
1702}
1703
1704function findCurrentUnmaskedContext(fiber) {
1705 // Currently this is only used with renderSubtreeIntoContainer; not sure if it
1706 // makes sense elsewhere
1707 !(isFiberMounted(fiber) && fiber.tag === ClassComponent) ? invariant(false, 'Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue.') : void 0;
1708
1709 var node = fiber;
1710 do {
1711 switch (node.tag) {
1712 case HostRoot:
1713 return node.stateNode.context;
1714 case ClassComponent:
1715 {
1716 var Component = node.type;
1717 if (isContextProvider(Component)) {
1718 return node.stateNode.__reactInternalMemoizedMergedChildContext;
1719 }
1720 break;
1721 }
1722 }
1723 node = node.return;
1724 } while (node !== null);
1725 invariant(false, 'Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.');
1726}
1727
1728var onCommitFiberRoot = null;
1729var onCommitFiberUnmount = null;
1730var hasLoggedError = false;
1731
1732function catchErrors(fn) {
1733 return function (arg) {
1734 try {
1735 return fn(arg);
1736 } catch (err) {
1737 if (true && !hasLoggedError) {
1738 hasLoggedError = true;
1739 warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err);
1740 }
1741 }
1742 };
1743}
1744
1745var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
1746
1747function injectInternals(internals) {
1748 if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
1749 // No DevTools
1750 return false;
1751 }
1752 var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
1753 if (hook.isDisabled) {
1754 // This isn't a real property on the hook, but it can be set to opt out
1755 // of DevTools integration and associated warnings and logs.
1756 // https://github.com/facebook/react/issues/3877
1757 return true;
1758 }
1759 if (!hook.supportsFiber) {
1760 {
1761 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');
1762 }
1763 // DevTools exists, even though it doesn't support Fiber.
1764 return true;
1765 }
1766 try {
1767 var rendererID = hook.inject(internals);
1768 // We have successfully injected, so now it is safe to set up hooks.
1769 onCommitFiberRoot = catchErrors(function (root) {
1770 return hook.onCommitFiberRoot(rendererID, root);
1771 });
1772 onCommitFiberUnmount = catchErrors(function (fiber) {
1773 return hook.onCommitFiberUnmount(rendererID, fiber);
1774 });
1775 } catch (err) {
1776 // Catch all errors because it is unsafe to throw during initialization.
1777 {
1778 warningWithoutStack$1(false, 'React DevTools encountered an error: %s.', err);
1779 }
1780 }
1781 // DevTools exists
1782 return true;
1783}
1784
1785function onCommitRoot(root) {
1786 if (typeof onCommitFiberRoot === 'function') {
1787 onCommitFiberRoot(root);
1788 }
1789}
1790
1791function onCommitUnmount(fiber) {
1792 if (typeof onCommitFiberUnmount === 'function') {
1793 onCommitFiberUnmount(fiber);
1794 }
1795}
1796
1797// Max 31 bit integer. The max integer size in V8 for 32-bit systems.
1798// Math.pow(2, 30) - 1
1799// 0b111111111111111111111111111111
1800var maxSigned31BitInt = 1073741823;
1801
1802var NoWork = 0;
1803var Never = 1;
1804var Sync = maxSigned31BitInt;
1805
1806var UNIT_SIZE = 10;
1807var MAGIC_NUMBER_OFFSET = maxSigned31BitInt - 1;
1808
1809// 1 unit of expiration time represents 10ms.
1810function msToExpirationTime(ms) {
1811 // Always add an offset so that we don't clash with the magic number for NoWork.
1812 return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);
1813}
1814
1815function expirationTimeToMs(expirationTime) {
1816 return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE;
1817}
1818
1819function ceiling(num, precision) {
1820 return ((num / precision | 0) + 1) * precision;
1821}
1822
1823function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) {
1824 return MAGIC_NUMBER_OFFSET - ceiling(MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE);
1825}
1826
1827var LOW_PRIORITY_EXPIRATION = 5000;
1828var LOW_PRIORITY_BATCH_SIZE = 250;
1829
1830function computeAsyncExpiration(currentTime) {
1831 return computeExpirationBucket(currentTime, LOW_PRIORITY_EXPIRATION, LOW_PRIORITY_BATCH_SIZE);
1832}
1833
1834// We intentionally set a higher expiration time for interactive updates in
1835// dev than in production.
1836//
1837// If the main thread is being blocked so long that you hit the expiration,
1838// it's a problem that could be solved with better scheduling.
1839//
1840// People will be more likely to notice this and fix it with the long
1841// expiration time in development.
1842//
1843// In production we opt for better UX at the risk of masking scheduling
1844// problems, by expiring fast.
1845var HIGH_PRIORITY_EXPIRATION = 500;
1846var HIGH_PRIORITY_BATCH_SIZE = 100;
1847
1848function computeInteractiveExpiration(currentTime) {
1849 return computeExpirationBucket(currentTime, HIGH_PRIORITY_EXPIRATION, HIGH_PRIORITY_BATCH_SIZE);
1850}
1851
1852var NoContext = 0;
1853var ConcurrentMode = 1;
1854var StrictMode = 2;
1855var ProfileMode = 4;
1856
1857var hasBadMapPolyfill = void 0;
1858
1859{
1860 hasBadMapPolyfill = false;
1861 try {
1862 var nonExtensibleObject = Object.preventExtensions({});
1863 var testMap = new Map([[nonExtensibleObject, null]]);
1864 var testSet = new Set([nonExtensibleObject]);
1865 // This is necessary for Rollup to not consider these unused.
1866 // https://github.com/rollup/rollup/issues/1771
1867 // TODO: we can remove these if Rollup fixes the bug.
1868 testMap.set(0, 0);
1869 testSet.add(0);
1870 } catch (e) {
1871 // TODO: Consider warning about bad polyfills
1872 hasBadMapPolyfill = true;
1873 }
1874}
1875
1876// A Fiber is work on a Component that needs to be done or was done. There can
1877// be more than one per component.
1878
1879
1880var debugCounter = void 0;
1881
1882{
1883 debugCounter = 1;
1884}
1885
1886function FiberNode(tag, pendingProps, key, mode) {
1887 // Instance
1888 this.tag = tag;
1889 this.key = key;
1890 this.elementType = null;
1891 this.type = null;
1892 this.stateNode = null;
1893
1894 // Fiber
1895 this.return = null;
1896 this.child = null;
1897 this.sibling = null;
1898 this.index = 0;
1899
1900 this.ref = null;
1901
1902 this.pendingProps = pendingProps;
1903 this.memoizedProps = null;
1904 this.updateQueue = null;
1905 this.memoizedState = null;
1906 this.contextDependencies = null;
1907
1908 this.mode = mode;
1909
1910 // Effects
1911 this.effectTag = NoEffect;
1912 this.nextEffect = null;
1913
1914 this.firstEffect = null;
1915 this.lastEffect = null;
1916
1917 this.expirationTime = NoWork;
1918 this.childExpirationTime = NoWork;
1919
1920 this.alternate = null;
1921
1922 if (enableProfilerTimer) {
1923 // Note: The following is done to avoid a v8 performance cliff.
1924 //
1925 // Initializing the fields below to smis and later updating them with
1926 // double values will cause Fibers to end up having separate shapes.
1927 // This behavior/bug has something to do with Object.preventExtension().
1928 // Fortunately this only impacts DEV builds.
1929 // Unfortunately it makes React unusably slow for some applications.
1930 // To work around this, initialize the fields below with doubles.
1931 //
1932 // Learn more about this here:
1933 // https://github.com/facebook/react/issues/14365
1934 // https://bugs.chromium.org/p/v8/issues/detail?id=8538
1935 this.actualDuration = Number.NaN;
1936 this.actualStartTime = Number.NaN;
1937 this.selfBaseDuration = Number.NaN;
1938 this.treeBaseDuration = Number.NaN;
1939
1940 // It's okay to replace the initial doubles with smis after initialization.
1941 // This won't trigger the performance cliff mentioned above,
1942 // and it simplifies other profiler code (including DevTools).
1943 this.actualDuration = 0;
1944 this.actualStartTime = -1;
1945 this.selfBaseDuration = 0;
1946 this.treeBaseDuration = 0;
1947 }
1948
1949 {
1950 this._debugID = debugCounter++;
1951 this._debugSource = null;
1952 this._debugOwner = null;
1953 this._debugIsCurrentlyTiming = false;
1954 if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
1955 Object.preventExtensions(this);
1956 }
1957 }
1958}
1959
1960// This is a constructor function, rather than a POJO constructor, still
1961// please ensure we do the following:
1962// 1) Nobody should add any instance methods on this. Instance methods can be
1963// more difficult to predict when they get optimized and they are almost
1964// never inlined properly in static compilers.
1965// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
1966// always know when it is a fiber.
1967// 3) We might want to experiment with using numeric keys since they are easier
1968// to optimize in a non-JIT environment.
1969// 4) We can easily go from a constructor to a createFiber object literal if that
1970// is faster.
1971// 5) It should be easy to port this to a C struct and keep a C implementation
1972// compatible.
1973var createFiber = function (tag, pendingProps, key, mode) {
1974 // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
1975 return new FiberNode(tag, pendingProps, key, mode);
1976};
1977
1978function shouldConstruct(Component) {
1979 var prototype = Component.prototype;
1980 return !!(prototype && prototype.isReactComponent);
1981}
1982
1983function isSimpleFunctionComponent(type) {
1984 return typeof type === 'function' && !shouldConstruct(type) && type.defaultProps === undefined;
1985}
1986
1987function resolveLazyComponentTag(Component) {
1988 if (typeof Component === 'function') {
1989 return shouldConstruct(Component) ? ClassComponent : FunctionComponent;
1990 } else if (Component !== undefined && Component !== null) {
1991 var $$typeof = Component.$$typeof;
1992 if ($$typeof === REACT_FORWARD_REF_TYPE) {
1993 return ForwardRef;
1994 }
1995 if ($$typeof === REACT_MEMO_TYPE) {
1996 return MemoComponent;
1997 }
1998 }
1999 return IndeterminateComponent;
2000}
2001
2002// This is used to create an alternate fiber to do work on.
2003function createWorkInProgress(current, pendingProps, expirationTime) {
2004 var workInProgress = current.alternate;
2005 if (workInProgress === null) {
2006 // We use a double buffering pooling technique because we know that we'll
2007 // only ever need at most two versions of a tree. We pool the "other" unused
2008 // node that we're free to reuse. This is lazily created to avoid allocating
2009 // extra objects for things that are never updated. It also allow us to
2010 // reclaim the extra memory if needed.
2011 workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
2012 workInProgress.elementType = current.elementType;
2013 workInProgress.type = current.type;
2014 workInProgress.stateNode = current.stateNode;
2015
2016 {
2017 // DEV-only fields
2018 workInProgress._debugID = current._debugID;
2019 workInProgress._debugSource = current._debugSource;
2020 workInProgress._debugOwner = current._debugOwner;
2021 }
2022
2023 workInProgress.alternate = current;
2024 current.alternate = workInProgress;
2025 } else {
2026 workInProgress.pendingProps = pendingProps;
2027
2028 // We already have an alternate.
2029 // Reset the effect tag.
2030 workInProgress.effectTag = NoEffect;
2031
2032 // The effect list is no longer valid.
2033 workInProgress.nextEffect = null;
2034 workInProgress.firstEffect = null;
2035 workInProgress.lastEffect = null;
2036
2037 if (enableProfilerTimer) {
2038 // We intentionally reset, rather than copy, actualDuration & actualStartTime.
2039 // This prevents time from endlessly accumulating in new commits.
2040 // This has the downside of resetting values for different priority renders,
2041 // But works for yielding (the common case) and should support resuming.
2042 workInProgress.actualDuration = 0;
2043 workInProgress.actualStartTime = -1;
2044 }
2045 }
2046
2047 workInProgress.childExpirationTime = current.childExpirationTime;
2048 workInProgress.expirationTime = current.expirationTime;
2049
2050 workInProgress.child = current.child;
2051 workInProgress.memoizedProps = current.memoizedProps;
2052 workInProgress.memoizedState = current.memoizedState;
2053 workInProgress.updateQueue = current.updateQueue;
2054 workInProgress.contextDependencies = current.contextDependencies;
2055
2056 // These will be overridden during the parent's reconciliation
2057 workInProgress.sibling = current.sibling;
2058 workInProgress.index = current.index;
2059 workInProgress.ref = current.ref;
2060
2061 if (enableProfilerTimer) {
2062 workInProgress.selfBaseDuration = current.selfBaseDuration;
2063 workInProgress.treeBaseDuration = current.treeBaseDuration;
2064 }
2065
2066 return workInProgress;
2067}
2068
2069function createHostRootFiber(isConcurrent) {
2070 var mode = isConcurrent ? ConcurrentMode | StrictMode : NoContext;
2071
2072 if (enableProfilerTimer && isDevToolsPresent) {
2073 // Always collect profile timings when DevTools are present.
2074 // This enables DevTools to start capturing timing at any point–
2075 // Without some nodes in the tree having empty base times.
2076 mode |= ProfileMode;
2077 }
2078
2079 return createFiber(HostRoot, null, null, mode);
2080}
2081
2082function createFiberFromTypeAndProps(type, // React$ElementType
2083key, pendingProps, owner, mode, expirationTime) {
2084 var fiber = void 0;
2085
2086 var fiberTag = IndeterminateComponent;
2087 // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
2088 var resolvedType = type;
2089 if (typeof type === 'function') {
2090 if (shouldConstruct(type)) {
2091 fiberTag = ClassComponent;
2092 }
2093 } else if (typeof type === 'string') {
2094 fiberTag = HostComponent;
2095 } else {
2096 getTag: switch (type) {
2097 case REACT_FRAGMENT_TYPE:
2098 return createFiberFromFragment(pendingProps.children, mode, expirationTime, key);
2099 case REACT_CONCURRENT_MODE_TYPE:
2100 return createFiberFromMode(pendingProps, mode | ConcurrentMode | StrictMode, expirationTime, key);
2101 case REACT_STRICT_MODE_TYPE:
2102 return createFiberFromMode(pendingProps, mode | StrictMode, expirationTime, key);
2103 case REACT_PROFILER_TYPE:
2104 return createFiberFromProfiler(pendingProps, mode, expirationTime, key);
2105 case REACT_SUSPENSE_TYPE:
2106 return createFiberFromSuspense(pendingProps, mode, expirationTime, key);
2107 default:
2108 {
2109 if (typeof type === 'object' && type !== null) {
2110 switch (type.$$typeof) {
2111 case REACT_PROVIDER_TYPE:
2112 fiberTag = ContextProvider;
2113 break getTag;
2114 case REACT_CONTEXT_TYPE:
2115 // This is a consumer
2116 fiberTag = ContextConsumer;
2117 break getTag;
2118 case REACT_FORWARD_REF_TYPE:
2119 fiberTag = ForwardRef;
2120 break getTag;
2121 case REACT_MEMO_TYPE:
2122 fiberTag = MemoComponent;
2123 break getTag;
2124 case REACT_LAZY_TYPE:
2125 fiberTag = LazyComponent;
2126 resolvedType = null;
2127 break getTag;
2128 }
2129 }
2130 var info = '';
2131 {
2132 if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
2133 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.';
2134 }
2135 var ownerName = owner ? getComponentName(owner.type) : null;
2136 if (ownerName) {
2137 info += '\n\nCheck the render method of `' + ownerName + '`.';
2138 }
2139 }
2140 invariant(false, 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s', type == null ? type : typeof type, info);
2141 }
2142 }
2143 }
2144
2145 fiber = createFiber(fiberTag, pendingProps, key, mode);
2146 fiber.elementType = type;
2147 fiber.type = resolvedType;
2148 fiber.expirationTime = expirationTime;
2149
2150 return fiber;
2151}
2152
2153function createFiberFromElement(element, mode, expirationTime) {
2154 var owner = null;
2155 {
2156 owner = element._owner;
2157 }
2158 var type = element.type;
2159 var key = element.key;
2160 var pendingProps = element.props;
2161 var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, expirationTime);
2162 {
2163 fiber._debugSource = element._source;
2164 fiber._debugOwner = element._owner;
2165 }
2166 return fiber;
2167}
2168
2169function createFiberFromFragment(elements, mode, expirationTime, key) {
2170 var fiber = createFiber(Fragment, elements, key, mode);
2171 fiber.expirationTime = expirationTime;
2172 return fiber;
2173}
2174
2175function createFiberFromProfiler(pendingProps, mode, expirationTime, key) {
2176 {
2177 if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') {
2178 warningWithoutStack$1(false, 'Profiler must specify an "id" string and "onRender" function as props');
2179 }
2180 }
2181
2182 var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode);
2183 // TODO: The Profiler fiber shouldn't have a type. It has a tag.
2184 fiber.elementType = REACT_PROFILER_TYPE;
2185 fiber.type = REACT_PROFILER_TYPE;
2186 fiber.expirationTime = expirationTime;
2187
2188 return fiber;
2189}
2190
2191function createFiberFromMode(pendingProps, mode, expirationTime, key) {
2192 var fiber = createFiber(Mode, pendingProps, key, mode);
2193
2194 // TODO: The Mode fiber shouldn't have a type. It has a tag.
2195 var type = (mode & ConcurrentMode) === NoContext ? REACT_STRICT_MODE_TYPE : REACT_CONCURRENT_MODE_TYPE;
2196 fiber.elementType = type;
2197 fiber.type = type;
2198
2199 fiber.expirationTime = expirationTime;
2200 return fiber;
2201}
2202
2203function createFiberFromSuspense(pendingProps, mode, expirationTime, key) {
2204 var fiber = createFiber(SuspenseComponent, pendingProps, key, mode);
2205
2206 // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
2207 var type = REACT_SUSPENSE_TYPE;
2208 fiber.elementType = type;
2209 fiber.type = type;
2210
2211 fiber.expirationTime = expirationTime;
2212 return fiber;
2213}
2214
2215function createFiberFromText(content, mode, expirationTime) {
2216 var fiber = createFiber(HostText, content, null, mode);
2217 fiber.expirationTime = expirationTime;
2218 return fiber;
2219}
2220
2221function createFiberFromHostInstanceForDeletion() {
2222 var fiber = createFiber(HostComponent, null, null, NoContext);
2223 // TODO: These should not need a type.
2224 fiber.elementType = 'DELETED';
2225 fiber.type = 'DELETED';
2226 return fiber;
2227}
2228
2229function createFiberFromPortal(portal, mode, expirationTime) {
2230 var pendingProps = portal.children !== null ? portal.children : [];
2231 var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
2232 fiber.expirationTime = expirationTime;
2233 fiber.stateNode = {
2234 containerInfo: portal.containerInfo,
2235 pendingChildren: null, // Used by persistent updates
2236 implementation: portal.implementation
2237 };
2238 return fiber;
2239}
2240
2241// Used for stashing WIP properties to replay failed work in DEV.
2242function assignFiberPropertiesInDEV(target, source) {
2243 if (target === null) {
2244 // This Fiber's initial properties will always be overwritten.
2245 // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
2246 target = createFiber(IndeterminateComponent, null, null, NoContext);
2247 }
2248
2249 // This is intentionally written as a list of all properties.
2250 // We tried to use Object.assign() instead but this is called in
2251 // the hottest path, and Object.assign() was too slow:
2252 // https://github.com/facebook/react/issues/12502
2253 // This code is DEV-only so size is not a concern.
2254
2255 target.tag = source.tag;
2256 target.key = source.key;
2257 target.elementType = source.elementType;
2258 target.type = source.type;
2259 target.stateNode = source.stateNode;
2260 target.return = source.return;
2261 target.child = source.child;
2262 target.sibling = source.sibling;
2263 target.index = source.index;
2264 target.ref = source.ref;
2265 target.pendingProps = source.pendingProps;
2266 target.memoizedProps = source.memoizedProps;
2267 target.updateQueue = source.updateQueue;
2268 target.memoizedState = source.memoizedState;
2269 target.contextDependencies = source.contextDependencies;
2270 target.mode = source.mode;
2271 target.effectTag = source.effectTag;
2272 target.nextEffect = source.nextEffect;
2273 target.firstEffect = source.firstEffect;
2274 target.lastEffect = source.lastEffect;
2275 target.expirationTime = source.expirationTime;
2276 target.childExpirationTime = source.childExpirationTime;
2277 target.alternate = source.alternate;
2278 if (enableProfilerTimer) {
2279 target.actualDuration = source.actualDuration;
2280 target.actualStartTime = source.actualStartTime;
2281 target.selfBaseDuration = source.selfBaseDuration;
2282 target.treeBaseDuration = source.treeBaseDuration;
2283 }
2284 target._debugID = source._debugID;
2285 target._debugSource = source._debugSource;
2286 target._debugOwner = source._debugOwner;
2287 target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
2288 return target;
2289}
2290
2291var ReactInternals$1 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
2292
2293var _ReactInternals$Sched = ReactInternals$1.SchedulerTracing;
2294var __interactionsRef = _ReactInternals$Sched.__interactionsRef;
2295var __subscriberRef = _ReactInternals$Sched.__subscriberRef;
2296var unstable_clear = _ReactInternals$Sched.unstable_clear;
2297var unstable_getCurrent = _ReactInternals$Sched.unstable_getCurrent;
2298var unstable_getThreadID = _ReactInternals$Sched.unstable_getThreadID;
2299var unstable_subscribe = _ReactInternals$Sched.unstable_subscribe;
2300var unstable_trace = _ReactInternals$Sched.unstable_trace;
2301var unstable_unsubscribe = _ReactInternals$Sched.unstable_unsubscribe;
2302var unstable_wrap = _ReactInternals$Sched.unstable_wrap;
2303
2304// TODO: This should be lifted into the renderer.
2305
2306
2307// The following attributes are only used by interaction tracing builds.
2308// They enable interactions to be associated with their async work,
2309// And expose interaction metadata to the React DevTools Profiler plugin.
2310// Note that these attributes are only defined when the enableSchedulerTracing flag is enabled.
2311
2312
2313// Exported FiberRoot type includes all properties,
2314// To avoid requiring potentially error-prone :any casts throughout the project.
2315// Profiling properties are only safe to access in profiling builds (when enableSchedulerTracing is true).
2316// The types are defined separately within this file to ensure they stay in sync.
2317// (We don't have to use an inline :any cast when enableSchedulerTracing is disabled.)
2318
2319
2320function createFiberRoot(containerInfo, isConcurrent, hydrate) {
2321 // Cyclic construction. This cheats the type system right now because
2322 // stateNode is any.
2323 var uninitializedFiber = createHostRootFiber(isConcurrent);
2324
2325 var root = void 0;
2326 if (enableSchedulerTracing) {
2327 root = {
2328 current: uninitializedFiber,
2329 containerInfo: containerInfo,
2330 pendingChildren: null,
2331
2332 earliestPendingTime: NoWork,
2333 latestPendingTime: NoWork,
2334 earliestSuspendedTime: NoWork,
2335 latestSuspendedTime: NoWork,
2336 latestPingedTime: NoWork,
2337
2338 pingCache: null,
2339
2340 didError: false,
2341
2342 pendingCommitExpirationTime: NoWork,
2343 finishedWork: null,
2344 timeoutHandle: noTimeout,
2345 context: null,
2346 pendingContext: null,
2347 hydrate: hydrate,
2348 nextExpirationTimeToWorkOn: NoWork,
2349 expirationTime: NoWork,
2350 firstBatch: null,
2351 nextScheduledRoot: null,
2352
2353 interactionThreadID: unstable_getThreadID(),
2354 memoizedInteractions: new Set(),
2355 pendingInteractionMap: new Map()
2356 };
2357 } else {
2358 root = {
2359 current: uninitializedFiber,
2360 containerInfo: containerInfo,
2361 pendingChildren: null,
2362
2363 pingCache: null,
2364
2365 earliestPendingTime: NoWork,
2366 latestPendingTime: NoWork,
2367 earliestSuspendedTime: NoWork,
2368 latestSuspendedTime: NoWork,
2369 latestPingedTime: NoWork,
2370
2371 didError: false,
2372
2373 pendingCommitExpirationTime: NoWork,
2374 finishedWork: null,
2375 timeoutHandle: noTimeout,
2376 context: null,
2377 pendingContext: null,
2378 hydrate: hydrate,
2379 nextExpirationTimeToWorkOn: NoWork,
2380 expirationTime: NoWork,
2381 firstBatch: null,
2382 nextScheduledRoot: null
2383 };
2384 }
2385
2386 uninitializedFiber.stateNode = root;
2387
2388 // The reason for the way the Flow types are structured in this file,
2389 // Is to avoid needing :any casts everywhere interaction tracing fields are used.
2390 // Unfortunately that requires an :any cast for non-interaction tracing capable builds.
2391 // $FlowFixMe Remove this :any cast and replace it with something better.
2392 return root;
2393}
2394
2395var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) {
2396 var funcArgs = Array.prototype.slice.call(arguments, 3);
2397 try {
2398 func.apply(context, funcArgs);
2399 } catch (error) {
2400 this.onError(error);
2401 }
2402};
2403
2404{
2405 // In DEV mode, we swap out invokeGuardedCallback for a special version
2406 // that plays more nicely with the browser's DevTools. The idea is to preserve
2407 // "Pause on exceptions" behavior. Because React wraps all user-provided
2408 // functions in invokeGuardedCallback, and the production version of
2409 // invokeGuardedCallback uses a try-catch, all user exceptions are treated
2410 // like caught exceptions, and the DevTools won't pause unless the developer
2411 // takes the extra step of enabling pause on caught exceptions. This is
2412 // untintuitive, though, because even though React has caught the error, from
2413 // the developer's perspective, the error is uncaught.
2414 //
2415 // To preserve the expected "Pause on exceptions" behavior, we don't use a
2416 // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
2417 // DOM node, and call the user-provided callback from inside an event handler
2418 // for that fake event. If the callback throws, the error is "captured" using
2419 // a global event handler. But because the error happens in a different
2420 // event loop context, it does not interrupt the normal program flow.
2421 // Effectively, this gives us try-catch behavior without actually using
2422 // try-catch. Neat!
2423
2424 // Check that the browser supports the APIs we need to implement our special
2425 // DEV version of invokeGuardedCallback
2426 if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
2427 var fakeNode = document.createElement('react');
2428
2429 var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) {
2430 // If document doesn't exist we know for sure we will crash in this method
2431 // when we call document.createEvent(). However this can cause confusing
2432 // errors: https://github.com/facebookincubator/create-react-app/issues/3482
2433 // So we preemptively throw with a better message instead.
2434 !(typeof document !== 'undefined') ? invariant(false, '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.') : void 0;
2435 var evt = document.createEvent('Event');
2436
2437 // Keeps track of whether the user-provided callback threw an error. We
2438 // set this to true at the beginning, then set it to false right after
2439 // calling the function. If the function errors, `didError` will never be
2440 // set to false. This strategy works even if the browser is flaky and
2441 // fails to call our global error handler, because it doesn't rely on
2442 // the error event at all.
2443 var didError = true;
2444
2445 // Keeps track of the value of window.event so that we can reset it
2446 // during the callback to let user code access window.event in the
2447 // browsers that support it.
2448 var windowEvent = window.event;
2449
2450 // Keeps track of the descriptor of window.event to restore it after event
2451 // dispatching: https://github.com/facebook/react/issues/13688
2452 var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event');
2453
2454 // Create an event handler for our fake event. We will synchronously
2455 // dispatch our fake event using `dispatchEvent`. Inside the handler, we
2456 // call the user-provided callback.
2457 var funcArgs = Array.prototype.slice.call(arguments, 3);
2458 function callCallback() {
2459 // We immediately remove the callback from event listeners so that
2460 // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
2461 // nested call would trigger the fake event handlers of any call higher
2462 // in the stack.
2463 fakeNode.removeEventListener(evtType, callCallback, false);
2464
2465 // We check for window.hasOwnProperty('event') to prevent the
2466 // window.event assignment in both IE <= 10 as they throw an error
2467 // "Member not found" in strict mode, and in Firefox which does not
2468 // support window.event.
2469 if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
2470 window.event = windowEvent;
2471 }
2472
2473 func.apply(context, funcArgs);
2474 didError = false;
2475 }
2476
2477 // Create a global error event handler. We use this to capture the value
2478 // that was thrown. It's possible that this error handler will fire more
2479 // than once; for example, if non-React code also calls `dispatchEvent`
2480 // and a handler for that event throws. We should be resilient to most of
2481 // those cases. Even if our error event handler fires more than once, the
2482 // last error event is always used. If the callback actually does error,
2483 // we know that the last error event is the correct one, because it's not
2484 // possible for anything else to have happened in between our callback
2485 // erroring and the code that follows the `dispatchEvent` call below. If
2486 // the callback doesn't error, but the error event was fired, we know to
2487 // ignore it because `didError` will be false, as described above.
2488 var error = void 0;
2489 // Use this to track whether the error event is ever called.
2490 var didSetError = false;
2491 var isCrossOriginError = false;
2492
2493 function handleWindowError(event) {
2494 error = event.error;
2495 didSetError = true;
2496 if (error === null && event.colno === 0 && event.lineno === 0) {
2497 isCrossOriginError = true;
2498 }
2499 if (event.defaultPrevented) {
2500 // Some other error handler has prevented default.
2501 // Browsers silence the error report if this happens.
2502 // We'll remember this to later decide whether to log it or not.
2503 if (error != null && typeof error === 'object') {
2504 try {
2505 error._suppressLogging = true;
2506 } catch (inner) {
2507 // Ignore.
2508 }
2509 }
2510 }
2511 }
2512
2513 // Create a fake event type.
2514 var evtType = 'react-' + (name ? name : 'invokeguardedcallback');
2515
2516 // Attach our event handlers
2517 window.addEventListener('error', handleWindowError);
2518 fakeNode.addEventListener(evtType, callCallback, false);
2519
2520 // Synchronously dispatch our fake event. If the user-provided function
2521 // errors, it will trigger our global error handler.
2522 evt.initEvent(evtType, false, false);
2523 fakeNode.dispatchEvent(evt);
2524
2525 if (windowEventDescriptor) {
2526 Object.defineProperty(window, 'event', windowEventDescriptor);
2527 }
2528
2529 if (didError) {
2530 if (!didSetError) {
2531 // The callback errored, but the error event never fired.
2532 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.');
2533 } else if (isCrossOriginError) {
2534 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.');
2535 }
2536 this.onError(error);
2537 }
2538
2539 // Remove our event listeners
2540 window.removeEventListener('error', handleWindowError);
2541 };
2542
2543 invokeGuardedCallbackImpl = invokeGuardedCallbackDev;
2544 }
2545}
2546
2547var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
2548
2549// Used by Fiber to simulate a try-catch.
2550var hasError = false;
2551var caughtError = null;
2552
2553var reporter = {
2554 onError: function (error) {
2555 hasError = true;
2556 caughtError = error;
2557 }
2558};
2559
2560/**
2561 * Call a function while guarding against errors that happens within it.
2562 * Returns an error if it throws, otherwise null.
2563 *
2564 * In production, this is implemented using a try-catch. The reason we don't
2565 * use a try-catch directly is so that we can swap out a different
2566 * implementation in DEV mode.
2567 *
2568 * @param {String} name of the guard to use for logging or debugging
2569 * @param {Function} func The function to invoke
2570 * @param {*} context The context to use when calling the function
2571 * @param {...*} args Arguments for function
2572 */
2573function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
2574 hasError = false;
2575 caughtError = null;
2576 invokeGuardedCallbackImpl$1.apply(reporter, arguments);
2577}
2578
2579/**
2580 * Same as invokeGuardedCallback, but instead of returning an error, it stores
2581 * it in a global so it can be rethrown by `rethrowCaughtError` later.
2582 * TODO: See if caughtError and rethrowError can be unified.
2583 *
2584 * @param {String} name of the guard to use for logging or debugging
2585 * @param {Function} func The function to invoke
2586 * @param {*} context The context to use when calling the function
2587 * @param {...*} args Arguments for function
2588 */
2589
2590
2591/**
2592 * During execution of guarded functions we will capture the first error which
2593 * we will rethrow to be handled by the top level error handler.
2594 */
2595
2596
2597function hasCaughtError() {
2598 return hasError;
2599}
2600
2601function clearCaughtError() {
2602 if (hasError) {
2603 var error = caughtError;
2604 hasError = false;
2605 caughtError = null;
2606 return error;
2607 } else {
2608 invariant(false, 'clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.');
2609 }
2610}
2611
2612/**
2613 * Forked from fbjs/warning:
2614 * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
2615 *
2616 * Only change is we use console.warn instead of console.error,
2617 * and do nothing when 'console' is not supported.
2618 * This really simplifies the code.
2619 * ---
2620 * Similar to invariant but only logs a warning if the condition is not met.
2621 * This can be used to log issues in development environments in critical
2622 * paths. Removing the logging code for production environments will keep the
2623 * same logic and follow the same code paths.
2624 */
2625
2626var lowPriorityWarning = function () {};
2627
2628{
2629 var printWarning$1 = function (format) {
2630 for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
2631 args[_key - 1] = arguments[_key];
2632 }
2633
2634 var argIndex = 0;
2635 var message = 'Warning: ' + format.replace(/%s/g, function () {
2636 return args[argIndex++];
2637 });
2638 if (typeof console !== 'undefined') {
2639 console.warn(message);
2640 }
2641 try {
2642 // --- Welcome to debugging React ---
2643 // This error was thrown as a convenience so that you can use this stack
2644 // to find the callsite that caused this warning to fire.
2645 throw new Error(message);
2646 } catch (x) {}
2647 };
2648
2649 lowPriorityWarning = function (condition, format) {
2650 if (format === undefined) {
2651 throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument');
2652 }
2653 if (!condition) {
2654 for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
2655 args[_key2 - 2] = arguments[_key2];
2656 }
2657
2658 printWarning$1.apply(undefined, [format].concat(args));
2659 }
2660 };
2661}
2662
2663var lowPriorityWarning$1 = lowPriorityWarning;
2664
2665var ReactStrictModeWarnings = {
2666 discardPendingWarnings: function () {},
2667 flushPendingDeprecationWarnings: function () {},
2668 flushPendingUnsafeLifecycleWarnings: function () {},
2669 recordDeprecationWarnings: function (fiber, instance) {},
2670 recordUnsafeLifecycleWarnings: function (fiber, instance) {},
2671 recordLegacyContextWarning: function (fiber, instance) {},
2672 flushLegacyContextWarning: function () {}
2673};
2674
2675{
2676 var LIFECYCLE_SUGGESTIONS = {
2677 UNSAFE_componentWillMount: 'componentDidMount',
2678 UNSAFE_componentWillReceiveProps: 'static getDerivedStateFromProps',
2679 UNSAFE_componentWillUpdate: 'componentDidUpdate'
2680 };
2681
2682 var pendingComponentWillMountWarnings = [];
2683 var pendingComponentWillReceivePropsWarnings = [];
2684 var pendingComponentWillUpdateWarnings = [];
2685 var pendingUnsafeLifecycleWarnings = new Map();
2686 var pendingLegacyContextWarning = new Map();
2687
2688 // Tracks components we have already warned about.
2689 var didWarnAboutDeprecatedLifecycles = new Set();
2690 var didWarnAboutUnsafeLifecycles = new Set();
2691 var didWarnAboutLegacyContext = new Set();
2692
2693 var setToSortedString = function (set) {
2694 var array = [];
2695 set.forEach(function (value) {
2696 array.push(value);
2697 });
2698 return array.sort().join(', ');
2699 };
2700
2701 ReactStrictModeWarnings.discardPendingWarnings = function () {
2702 pendingComponentWillMountWarnings = [];
2703 pendingComponentWillReceivePropsWarnings = [];
2704 pendingComponentWillUpdateWarnings = [];
2705 pendingUnsafeLifecycleWarnings = new Map();
2706 pendingLegacyContextWarning = new Map();
2707 };
2708
2709 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
2710 pendingUnsafeLifecycleWarnings.forEach(function (lifecycleWarningsMap, strictRoot) {
2711 var lifecyclesWarningMessages = [];
2712
2713 Object.keys(lifecycleWarningsMap).forEach(function (lifecycle) {
2714 var lifecycleWarnings = lifecycleWarningsMap[lifecycle];
2715 if (lifecycleWarnings.length > 0) {
2716 var componentNames = new Set();
2717 lifecycleWarnings.forEach(function (fiber) {
2718 componentNames.add(getComponentName(fiber.type) || 'Component');
2719 didWarnAboutUnsafeLifecycles.add(fiber.type);
2720 });
2721
2722 var formatted = lifecycle.replace('UNSAFE_', '');
2723 var suggestion = LIFECYCLE_SUGGESTIONS[lifecycle];
2724 var sortedComponentNames = setToSortedString(componentNames);
2725
2726 lifecyclesWarningMessages.push(formatted + ': Please update the following components to use ' + (suggestion + ' instead: ' + sortedComponentNames));
2727 }
2728 });
2729
2730 if (lifecyclesWarningMessages.length > 0) {
2731 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
2732
2733 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'));
2734 }
2735 });
2736
2737 pendingUnsafeLifecycleWarnings = new Map();
2738 };
2739
2740 var findStrictRoot = function (fiber) {
2741 var maybeStrictRoot = null;
2742
2743 var node = fiber;
2744 while (node !== null) {
2745 if (node.mode & StrictMode) {
2746 maybeStrictRoot = node;
2747 }
2748 node = node.return;
2749 }
2750
2751 return maybeStrictRoot;
2752 };
2753
2754 ReactStrictModeWarnings.flushPendingDeprecationWarnings = function () {
2755 if (pendingComponentWillMountWarnings.length > 0) {
2756 var uniqueNames = new Set();
2757 pendingComponentWillMountWarnings.forEach(function (fiber) {
2758 uniqueNames.add(getComponentName(fiber.type) || 'Component');
2759 didWarnAboutDeprecatedLifecycles.add(fiber.type);
2760 });
2761
2762 var sortedNames = setToSortedString(uniqueNames);
2763
2764 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);
2765
2766 pendingComponentWillMountWarnings = [];
2767 }
2768
2769 if (pendingComponentWillReceivePropsWarnings.length > 0) {
2770 var _uniqueNames = new Set();
2771 pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
2772 _uniqueNames.add(getComponentName(fiber.type) || 'Component');
2773 didWarnAboutDeprecatedLifecycles.add(fiber.type);
2774 });
2775
2776 var _sortedNames = setToSortedString(_uniqueNames);
2777
2778 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);
2779
2780 pendingComponentWillReceivePropsWarnings = [];
2781 }
2782
2783 if (pendingComponentWillUpdateWarnings.length > 0) {
2784 var _uniqueNames2 = new Set();
2785 pendingComponentWillUpdateWarnings.forEach(function (fiber) {
2786 _uniqueNames2.add(getComponentName(fiber.type) || 'Component');
2787 didWarnAboutDeprecatedLifecycles.add(fiber.type);
2788 });
2789
2790 var _sortedNames2 = setToSortedString(_uniqueNames2);
2791
2792 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);
2793
2794 pendingComponentWillUpdateWarnings = [];
2795 }
2796 };
2797
2798 ReactStrictModeWarnings.recordDeprecationWarnings = function (fiber, instance) {
2799 // Dedup strategy: Warn once per component.
2800 if (didWarnAboutDeprecatedLifecycles.has(fiber.type)) {
2801 return;
2802 }
2803
2804 // Don't warn about react-lifecycles-compat polyfilled components.
2805 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
2806 pendingComponentWillMountWarnings.push(fiber);
2807 }
2808 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
2809 pendingComponentWillReceivePropsWarnings.push(fiber);
2810 }
2811 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
2812 pendingComponentWillUpdateWarnings.push(fiber);
2813 }
2814 };
2815
2816 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
2817 var strictRoot = findStrictRoot(fiber);
2818 if (strictRoot === null) {
2819 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.');
2820 return;
2821 }
2822
2823 // Dedup strategy: Warn once per component.
2824 // This is difficult to track any other way since component names
2825 // are often vague and are likely to collide between 3rd party libraries.
2826 // An expand property is probably okay to use here since it's DEV-only,
2827 // and will only be set in the event of serious warnings.
2828 if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
2829 return;
2830 }
2831
2832 var warningsForRoot = void 0;
2833 if (!pendingUnsafeLifecycleWarnings.has(strictRoot)) {
2834 warningsForRoot = {
2835 UNSAFE_componentWillMount: [],
2836 UNSAFE_componentWillReceiveProps: [],
2837 UNSAFE_componentWillUpdate: []
2838 };
2839
2840 pendingUnsafeLifecycleWarnings.set(strictRoot, warningsForRoot);
2841 } else {
2842 warningsForRoot = pendingUnsafeLifecycleWarnings.get(strictRoot);
2843 }
2844
2845 var unsafeLifecycles = [];
2846 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillMount === 'function') {
2847 unsafeLifecycles.push('UNSAFE_componentWillMount');
2848 }
2849 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
2850 unsafeLifecycles.push('UNSAFE_componentWillReceiveProps');
2851 }
2852 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillUpdate === 'function') {
2853 unsafeLifecycles.push('UNSAFE_componentWillUpdate');
2854 }
2855
2856 if (unsafeLifecycles.length > 0) {
2857 unsafeLifecycles.forEach(function (lifecycle) {
2858 warningsForRoot[lifecycle].push(fiber);
2859 });
2860 }
2861 };
2862
2863 ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
2864 var strictRoot = findStrictRoot(fiber);
2865 if (strictRoot === null) {
2866 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.');
2867 return;
2868 }
2869
2870 // Dedup strategy: Warn once per component.
2871 if (didWarnAboutLegacyContext.has(fiber.type)) {
2872 return;
2873 }
2874
2875 var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
2876
2877 if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
2878 if (warningsForRoot === undefined) {
2879 warningsForRoot = [];
2880 pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
2881 }
2882 warningsForRoot.push(fiber);
2883 }
2884 };
2885
2886 ReactStrictModeWarnings.flushLegacyContextWarning = function () {
2887 pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
2888 var uniqueNames = new Set();
2889 fiberArray.forEach(function (fiber) {
2890 uniqueNames.add(getComponentName(fiber.type) || 'Component');
2891 didWarnAboutLegacyContext.add(fiber.type);
2892 });
2893
2894 var sortedNames = setToSortedString(uniqueNames);
2895 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
2896
2897 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);
2898 });
2899 };
2900}
2901
2902// This lets us hook into Fiber to debug what it's doing.
2903// See https://github.com/facebook/react/pull/8033.
2904// This is not part of the public API, not even for React DevTools.
2905// You may only inject a debugTool if you work on React Fiber itself.
2906var ReactFiberInstrumentation = {
2907 debugTool: null
2908};
2909
2910var ReactFiberInstrumentation_1 = ReactFiberInstrumentation;
2911
2912// TODO: Offscreen updates should never suspend. However, a promise that
2913// suspended inside an offscreen subtree should be able to ping at the priority
2914// of the outer render.
2915
2916function markPendingPriorityLevel(root, expirationTime) {
2917 // If there's a gap between completing a failed root and retrying it,
2918 // additional updates may be scheduled. Clear `didError`, in case the update
2919 // is sufficient to fix the error.
2920 root.didError = false;
2921
2922 // Update the latest and earliest pending times
2923 var earliestPendingTime = root.earliestPendingTime;
2924 if (earliestPendingTime === NoWork) {
2925 // No other pending updates.
2926 root.earliestPendingTime = root.latestPendingTime = expirationTime;
2927 } else {
2928 if (earliestPendingTime < expirationTime) {
2929 // This is the earliest pending update.
2930 root.earliestPendingTime = expirationTime;
2931 } else {
2932 var latestPendingTime = root.latestPendingTime;
2933 if (latestPendingTime > expirationTime) {
2934 // This is the latest pending update
2935 root.latestPendingTime = expirationTime;
2936 }
2937 }
2938 }
2939 findNextExpirationTimeToWorkOn(expirationTime, root);
2940}
2941
2942function markCommittedPriorityLevels(root, earliestRemainingTime) {
2943 root.didError = false;
2944
2945 if (earliestRemainingTime === NoWork) {
2946 // Fast path. There's no remaining work. Clear everything.
2947 root.earliestPendingTime = NoWork;
2948 root.latestPendingTime = NoWork;
2949 root.earliestSuspendedTime = NoWork;
2950 root.latestSuspendedTime = NoWork;
2951 root.latestPingedTime = NoWork;
2952 findNextExpirationTimeToWorkOn(NoWork, root);
2953 return;
2954 }
2955
2956 if (earliestRemainingTime < root.latestPingedTime) {
2957 root.latestPingedTime = NoWork;
2958 }
2959
2960 // Let's see if the previous latest known pending level was just flushed.
2961 var latestPendingTime = root.latestPendingTime;
2962 if (latestPendingTime !== NoWork) {
2963 if (latestPendingTime > earliestRemainingTime) {
2964 // We've flushed all the known pending levels.
2965 root.earliestPendingTime = root.latestPendingTime = NoWork;
2966 } else {
2967 var earliestPendingTime = root.earliestPendingTime;
2968 if (earliestPendingTime > earliestRemainingTime) {
2969 // We've flushed the earliest known pending level. Set this to the
2970 // latest pending time.
2971 root.earliestPendingTime = root.latestPendingTime;
2972 }
2973 }
2974 }
2975
2976 // Now let's handle the earliest remaining level in the whole tree. We need to
2977 // decide whether to treat it as a pending level or as suspended. Check
2978 // it falls within the range of known suspended levels.
2979
2980 var earliestSuspendedTime = root.earliestSuspendedTime;
2981 if (earliestSuspendedTime === NoWork) {
2982 // There's no suspended work. Treat the earliest remaining level as a
2983 // pending level.
2984 markPendingPriorityLevel(root, earliestRemainingTime);
2985 findNextExpirationTimeToWorkOn(NoWork, root);
2986 return;
2987 }
2988
2989 var latestSuspendedTime = root.latestSuspendedTime;
2990 if (earliestRemainingTime < latestSuspendedTime) {
2991 // The earliest remaining level is later than all the suspended work. That
2992 // means we've flushed all the suspended work.
2993 root.earliestSuspendedTime = NoWork;
2994 root.latestSuspendedTime = NoWork;
2995 root.latestPingedTime = NoWork;
2996
2997 // There's no suspended work. Treat the earliest remaining level as a
2998 // pending level.
2999 markPendingPriorityLevel(root, earliestRemainingTime);
3000 findNextExpirationTimeToWorkOn(NoWork, root);
3001 return;
3002 }
3003
3004 if (earliestRemainingTime > earliestSuspendedTime) {
3005 // The earliest remaining time is earlier than all the suspended work.
3006 // Treat it as a pending update.
3007 markPendingPriorityLevel(root, earliestRemainingTime);
3008 findNextExpirationTimeToWorkOn(NoWork, root);
3009 return;
3010 }
3011
3012 // The earliest remaining time falls within the range of known suspended
3013 // levels. We should treat this as suspended work.
3014 findNextExpirationTimeToWorkOn(NoWork, root);
3015}
3016
3017function hasLowerPriorityWork(root, erroredExpirationTime) {
3018 var latestPendingTime = root.latestPendingTime;
3019 var latestSuspendedTime = root.latestSuspendedTime;
3020 var latestPingedTime = root.latestPingedTime;
3021 return latestPendingTime !== NoWork && latestPendingTime < erroredExpirationTime || latestSuspendedTime !== NoWork && latestSuspendedTime < erroredExpirationTime || latestPingedTime !== NoWork && latestPingedTime < erroredExpirationTime;
3022}
3023
3024function isPriorityLevelSuspended(root, expirationTime) {
3025 var earliestSuspendedTime = root.earliestSuspendedTime;
3026 var latestSuspendedTime = root.latestSuspendedTime;
3027 return earliestSuspendedTime !== NoWork && expirationTime <= earliestSuspendedTime && expirationTime >= latestSuspendedTime;
3028}
3029
3030function markSuspendedPriorityLevel(root, suspendedTime) {
3031 root.didError = false;
3032 clearPing(root, suspendedTime);
3033
3034 // First, check the known pending levels and update them if needed.
3035 var earliestPendingTime = root.earliestPendingTime;
3036 var latestPendingTime = root.latestPendingTime;
3037 if (earliestPendingTime === suspendedTime) {
3038 if (latestPendingTime === suspendedTime) {
3039 // Both known pending levels were suspended. Clear them.
3040 root.earliestPendingTime = root.latestPendingTime = NoWork;
3041 } else {
3042 // The earliest pending level was suspended. Clear by setting it to the
3043 // latest pending level.
3044 root.earliestPendingTime = latestPendingTime;
3045 }
3046 } else if (latestPendingTime === suspendedTime) {
3047 // The latest pending level was suspended. Clear by setting it to the
3048 // latest pending level.
3049 root.latestPendingTime = earliestPendingTime;
3050 }
3051
3052 // Finally, update the known suspended levels.
3053 var earliestSuspendedTime = root.earliestSuspendedTime;
3054 var latestSuspendedTime = root.latestSuspendedTime;
3055 if (earliestSuspendedTime === NoWork) {
3056 // No other suspended levels.
3057 root.earliestSuspendedTime = root.latestSuspendedTime = suspendedTime;
3058 } else {
3059 if (earliestSuspendedTime < suspendedTime) {
3060 // This is the earliest suspended level.
3061 root.earliestSuspendedTime = suspendedTime;
3062 } else if (latestSuspendedTime > suspendedTime) {
3063 // This is the latest suspended level
3064 root.latestSuspendedTime = suspendedTime;
3065 }
3066 }
3067
3068 findNextExpirationTimeToWorkOn(suspendedTime, root);
3069}
3070
3071function markPingedPriorityLevel(root, pingedTime) {
3072 root.didError = false;
3073
3074 // TODO: When we add back resuming, we need to ensure the progressed work
3075 // is thrown out and not reused during the restarted render. One way to
3076 // invalidate the progressed work is to restart at expirationTime + 1.
3077 var latestPingedTime = root.latestPingedTime;
3078 if (latestPingedTime === NoWork || latestPingedTime > pingedTime) {
3079 root.latestPingedTime = pingedTime;
3080 }
3081 findNextExpirationTimeToWorkOn(pingedTime, root);
3082}
3083
3084function clearPing(root, completedTime) {
3085 var latestPingedTime = root.latestPingedTime;
3086 if (latestPingedTime >= completedTime) {
3087 root.latestPingedTime = NoWork;
3088 }
3089}
3090
3091function findEarliestOutstandingPriorityLevel(root, renderExpirationTime) {
3092 var earliestExpirationTime = renderExpirationTime;
3093
3094 var earliestPendingTime = root.earliestPendingTime;
3095 var earliestSuspendedTime = root.earliestSuspendedTime;
3096 if (earliestPendingTime > earliestExpirationTime) {
3097 earliestExpirationTime = earliestPendingTime;
3098 }
3099 if (earliestSuspendedTime > earliestExpirationTime) {
3100 earliestExpirationTime = earliestSuspendedTime;
3101 }
3102 return earliestExpirationTime;
3103}
3104
3105function didExpireAtExpirationTime(root, currentTime) {
3106 var expirationTime = root.expirationTime;
3107 if (expirationTime !== NoWork && currentTime <= expirationTime) {
3108 // The root has expired. Flush all work up to the current time.
3109 root.nextExpirationTimeToWorkOn = currentTime;
3110 }
3111}
3112
3113function findNextExpirationTimeToWorkOn(completedExpirationTime, root) {
3114 var earliestSuspendedTime = root.earliestSuspendedTime;
3115 var latestSuspendedTime = root.latestSuspendedTime;
3116 var earliestPendingTime = root.earliestPendingTime;
3117 var latestPingedTime = root.latestPingedTime;
3118
3119 // Work on the earliest pending time. Failing that, work on the latest
3120 // pinged time.
3121 var nextExpirationTimeToWorkOn = earliestPendingTime !== NoWork ? earliestPendingTime : latestPingedTime;
3122
3123 // If there is no pending or pinged work, check if there's suspended work
3124 // that's lower priority than what we just completed.
3125 if (nextExpirationTimeToWorkOn === NoWork && (completedExpirationTime === NoWork || latestSuspendedTime < completedExpirationTime)) {
3126 // The lowest priority suspended work is the work most likely to be
3127 // committed next. Let's start rendering it again, so that if it times out,
3128 // it's ready to commit.
3129 nextExpirationTimeToWorkOn = latestSuspendedTime;
3130 }
3131
3132 var expirationTime = nextExpirationTimeToWorkOn;
3133 if (expirationTime !== NoWork && earliestSuspendedTime > expirationTime) {
3134 // Expire using the earliest known expiration time.
3135 expirationTime = earliestSuspendedTime;
3136 }
3137
3138 root.nextExpirationTimeToWorkOn = nextExpirationTimeToWorkOn;
3139 root.expirationTime = expirationTime;
3140}
3141
3142/**
3143 * inlined Object.is polyfill to avoid requiring consumers ship their own
3144 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
3145 */
3146function is(x, y) {
3147 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
3148 ;
3149}
3150
3151var hasOwnProperty = Object.prototype.hasOwnProperty;
3152
3153/**
3154 * Performs equality by iterating through keys on an object and returning false
3155 * when any key has values which are not strictly equal between the arguments.
3156 * Returns true when the values of all keys are strictly equal.
3157 */
3158function shallowEqual(objA, objB) {
3159 if (is(objA, objB)) {
3160 return true;
3161 }
3162
3163 if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
3164 return false;
3165 }
3166
3167 var keysA = Object.keys(objA);
3168 var keysB = Object.keys(objB);
3169
3170 if (keysA.length !== keysB.length) {
3171 return false;
3172 }
3173
3174 // Test for A's keys different from B.
3175 for (var i = 0; i < keysA.length; i++) {
3176 if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
3177 return false;
3178 }
3179 }
3180
3181 return true;
3182}
3183
3184function resolveDefaultProps(Component, baseProps) {
3185 if (Component && Component.defaultProps) {
3186 // Resolve default props. Taken from ReactElement
3187 var props = _assign({}, baseProps);
3188 var defaultProps = Component.defaultProps;
3189 for (var propName in defaultProps) {
3190 if (props[propName] === undefined) {
3191 props[propName] = defaultProps[propName];
3192 }
3193 }
3194 return props;
3195 }
3196 return baseProps;
3197}
3198
3199function readLazyComponentType(lazyComponent) {
3200 var status = lazyComponent._status;
3201 var result = lazyComponent._result;
3202 switch (status) {
3203 case Resolved:
3204 {
3205 var Component = result;
3206 return Component;
3207 }
3208 case Rejected:
3209 {
3210 var error = result;
3211 throw error;
3212 }
3213 case Pending:
3214 {
3215 var thenable = result;
3216 throw thenable;
3217 }
3218 default:
3219 {
3220 lazyComponent._status = Pending;
3221 var ctor = lazyComponent._ctor;
3222 var _thenable = ctor();
3223 _thenable.then(function (moduleObject) {
3224 if (lazyComponent._status === Pending) {
3225 var defaultExport = moduleObject.default;
3226 {
3227 if (defaultExport === undefined) {
3228 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);
3229 }
3230 }
3231 lazyComponent._status = Resolved;
3232 lazyComponent._result = defaultExport;
3233 }
3234 }, function (error) {
3235 if (lazyComponent._status === Pending) {
3236 lazyComponent._status = Rejected;
3237 lazyComponent._result = error;
3238 }
3239 });
3240 // Handle synchronous thenables.
3241 switch (lazyComponent._status) {
3242 case Resolved:
3243 return lazyComponent._result;
3244 case Rejected:
3245 throw lazyComponent._result;
3246 }
3247 lazyComponent._result = _thenable;
3248 throw _thenable;
3249 }
3250 }
3251}
3252
3253var fakeInternalInstance = {};
3254var isArray$1 = Array.isArray;
3255
3256// React.Component uses a shared frozen object by default.
3257// We'll use it to determine whether we need to initialize legacy refs.
3258var emptyRefsObject = new React.Component().refs;
3259
3260var didWarnAboutStateAssignmentForComponent = void 0;
3261var didWarnAboutUninitializedState = void 0;
3262var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = void 0;
3263var didWarnAboutLegacyLifecyclesAndDerivedState = void 0;
3264var didWarnAboutUndefinedDerivedState = void 0;
3265var warnOnUndefinedDerivedState = void 0;
3266var warnOnInvalidCallback = void 0;
3267var didWarnAboutDirectlyAssigningPropsToState = void 0;
3268var didWarnAboutContextTypeAndContextTypes = void 0;
3269var didWarnAboutInvalidateContextType = void 0;
3270
3271{
3272 didWarnAboutStateAssignmentForComponent = new Set();
3273 didWarnAboutUninitializedState = new Set();
3274 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
3275 didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
3276 didWarnAboutDirectlyAssigningPropsToState = new Set();
3277 didWarnAboutUndefinedDerivedState = new Set();
3278 didWarnAboutContextTypeAndContextTypes = new Set();
3279 didWarnAboutInvalidateContextType = new Set();
3280
3281 var didWarnOnInvalidCallback = new Set();
3282
3283 warnOnInvalidCallback = function (callback, callerName) {
3284 if (callback === null || typeof callback === 'function') {
3285 return;
3286 }
3287 var key = callerName + '_' + callback;
3288 if (!didWarnOnInvalidCallback.has(key)) {
3289 didWarnOnInvalidCallback.add(key);
3290 warningWithoutStack$1(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
3291 }
3292 };
3293
3294 warnOnUndefinedDerivedState = function (type, partialState) {
3295 if (partialState === undefined) {
3296 var componentName = getComponentName(type) || 'Component';
3297 if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
3298 didWarnAboutUndefinedDerivedState.add(componentName);
3299 warningWithoutStack$1(false, '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
3300 }
3301 }
3302 };
3303
3304 // This is so gross but it's at least non-critical and can be removed if
3305 // it causes problems. This is meant to give a nicer error message for
3306 // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
3307 // ...)) which otherwise throws a "_processChildContext is not a function"
3308 // exception.
3309 Object.defineProperty(fakeInternalInstance, '_processChildContext', {
3310 enumerable: false,
3311 value: function () {
3312 invariant(false, '_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).');
3313 }
3314 });
3315 Object.freeze(fakeInternalInstance);
3316}
3317
3318function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
3319 var prevState = workInProgress.memoizedState;
3320
3321 {
3322 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
3323 // Invoke the function an extra time to help detect side-effects.
3324 getDerivedStateFromProps(nextProps, prevState);
3325 }
3326 }
3327
3328 var partialState = getDerivedStateFromProps(nextProps, prevState);
3329
3330 {
3331 warnOnUndefinedDerivedState(ctor, partialState);
3332 }
3333 // Merge the partial state and the previous state.
3334 var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
3335 workInProgress.memoizedState = memoizedState;
3336
3337 // Once the update queue is empty, persist the derived state onto the
3338 // base state.
3339 var updateQueue = workInProgress.updateQueue;
3340 if (updateQueue !== null && workInProgress.expirationTime === NoWork) {
3341 updateQueue.baseState = memoizedState;
3342 }
3343}
3344
3345var classComponentUpdater = {
3346 isMounted: isMounted,
3347 enqueueSetState: function (inst, payload, callback) {
3348 var fiber = get(inst);
3349 var currentTime = requestCurrentTime();
3350 var expirationTime = computeExpirationForFiber(currentTime, fiber);
3351
3352 var update = createUpdate(expirationTime);
3353 update.payload = payload;
3354 if (callback !== undefined && callback !== null) {
3355 {
3356 warnOnInvalidCallback(callback, 'setState');
3357 }
3358 update.callback = callback;
3359 }
3360
3361 flushPassiveEffects$1();
3362 enqueueUpdate(fiber, update);
3363 scheduleWork(fiber, expirationTime);
3364 },
3365 enqueueReplaceState: function (inst, payload, callback) {
3366 var fiber = get(inst);
3367 var currentTime = requestCurrentTime();
3368 var expirationTime = computeExpirationForFiber(currentTime, fiber);
3369
3370 var update = createUpdate(expirationTime);
3371 update.tag = ReplaceState;
3372 update.payload = payload;
3373
3374 if (callback !== undefined && callback !== null) {
3375 {
3376 warnOnInvalidCallback(callback, 'replaceState');
3377 }
3378 update.callback = callback;
3379 }
3380
3381 flushPassiveEffects$1();
3382 enqueueUpdate(fiber, update);
3383 scheduleWork(fiber, expirationTime);
3384 },
3385 enqueueForceUpdate: function (inst, callback) {
3386 var fiber = get(inst);
3387 var currentTime = requestCurrentTime();
3388 var expirationTime = computeExpirationForFiber(currentTime, fiber);
3389
3390 var update = createUpdate(expirationTime);
3391 update.tag = ForceUpdate;
3392
3393 if (callback !== undefined && callback !== null) {
3394 {
3395 warnOnInvalidCallback(callback, 'forceUpdate');
3396 }
3397 update.callback = callback;
3398 }
3399
3400 flushPassiveEffects$1();
3401 enqueueUpdate(fiber, update);
3402 scheduleWork(fiber, expirationTime);
3403 }
3404};
3405
3406function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
3407 var instance = workInProgress.stateNode;
3408 if (typeof instance.shouldComponentUpdate === 'function') {
3409 startPhaseTimer(workInProgress, 'shouldComponentUpdate');
3410 var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
3411 stopPhaseTimer();
3412
3413 {
3414 !(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;
3415 }
3416
3417 return shouldUpdate;
3418 }
3419
3420 if (ctor.prototype && ctor.prototype.isPureReactComponent) {
3421 return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
3422 }
3423
3424 return true;
3425}
3426
3427function checkClassInstance(workInProgress, ctor, newProps) {
3428 var instance = workInProgress.stateNode;
3429 {
3430 var name = getComponentName(ctor) || 'Component';
3431 var renderPresent = instance.render;
3432
3433 if (!renderPresent) {
3434 if (ctor.prototype && typeof ctor.prototype.render === 'function') {
3435 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
3436 } else {
3437 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
3438 }
3439 }
3440
3441 var noGetInitialStateOnES6 = !instance.getInitialState || instance.getInitialState.isReactClassApproved || instance.state;
3442 !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;
3443 var noGetDefaultPropsOnES6 = !instance.getDefaultProps || instance.getDefaultProps.isReactClassApproved;
3444 !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;
3445 var noInstancePropTypes = !instance.propTypes;
3446 !noInstancePropTypes ? warningWithoutStack$1(false, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name) : void 0;
3447 var noInstanceContextType = !instance.contextType;
3448 !noInstanceContextType ? warningWithoutStack$1(false, 'contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name) : void 0;
3449 var noInstanceContextTypes = !instance.contextTypes;
3450 !noInstanceContextTypes ? warningWithoutStack$1(false, 'contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name) : void 0;
3451
3452 if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
3453 didWarnAboutContextTypeAndContextTypes.add(ctor);
3454 warningWithoutStack$1(false, '%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
3455 }
3456
3457 var noComponentShouldUpdate = typeof instance.componentShouldUpdate !== 'function';
3458 !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;
3459 if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
3460 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');
3461 }
3462 var noComponentDidUnmount = typeof instance.componentDidUnmount !== 'function';
3463 !noComponentDidUnmount ? warningWithoutStack$1(false, '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name) : void 0;
3464 var noComponentDidReceiveProps = typeof instance.componentDidReceiveProps !== 'function';
3465 !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;
3466 var noComponentWillRecieveProps = typeof instance.componentWillRecieveProps !== 'function';
3467 !noComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name) : void 0;
3468 var noUnsafeComponentWillRecieveProps = typeof instance.UNSAFE_componentWillRecieveProps !== 'function';
3469 !noUnsafeComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name) : void 0;
3470 var hasMutatedProps = instance.props !== newProps;
3471 !(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;
3472 var noInstanceDefaultProps = !instance.defaultProps;
3473 !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;
3474
3475 if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
3476 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
3477 warningWithoutStack$1(false, '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor));
3478 }
3479
3480 var noInstanceGetDerivedStateFromProps = typeof instance.getDerivedStateFromProps !== 'function';
3481 !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;
3482 var noInstanceGetDerivedStateFromCatch = typeof instance.getDerivedStateFromError !== 'function';
3483 !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;
3484 var noStaticGetSnapshotBeforeUpdate = typeof ctor.getSnapshotBeforeUpdate !== 'function';
3485 !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;
3486 var _state = instance.state;
3487 if (_state && (typeof _state !== 'object' || isArray$1(_state))) {
3488 warningWithoutStack$1(false, '%s.state: must be set to an object or null', name);
3489 }
3490 if (typeof instance.getChildContext === 'function') {
3491 !(typeof ctor.childContextTypes === 'object') ? warningWithoutStack$1(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name) : void 0;
3492 }
3493 }
3494}
3495
3496function adoptClassInstance(workInProgress, instance) {
3497 instance.updater = classComponentUpdater;
3498 workInProgress.stateNode = instance;
3499 // The instance needs access to the fiber so that it can schedule updates
3500 set(instance, workInProgress);
3501 {
3502 instance._reactInternalInstance = fakeInternalInstance;
3503 }
3504}
3505
3506function constructClassInstance(workInProgress, ctor, props, renderExpirationTime) {
3507 var isLegacyContextConsumer = false;
3508 var unmaskedContext = emptyContextObject;
3509 var context = null;
3510 var contextType = ctor.contextType;
3511 if (typeof contextType === 'object' && contextType !== null) {
3512 {
3513 if (contextType.$$typeof !== REACT_CONTEXT_TYPE && !didWarnAboutInvalidateContextType.has(ctor)) {
3514 didWarnAboutInvalidateContextType.add(ctor);
3515 warningWithoutStack$1(false, '%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext(). ' + 'Did you accidentally pass the Context.Provider instead?', getComponentName(ctor) || 'Component');
3516 }
3517 }
3518
3519 context = readContext(contextType);
3520 } else {
3521 unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
3522 var contextTypes = ctor.contextTypes;
3523 isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
3524 context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
3525 }
3526
3527 // Instantiate twice to help detect side-effects.
3528 {
3529 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
3530 new ctor(props, context); // eslint-disable-line no-new
3531 }
3532 }
3533
3534 var instance = new ctor(props, context);
3535 var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
3536 adoptClassInstance(workInProgress, instance);
3537
3538 {
3539 if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
3540 var componentName = getComponentName(ctor) || 'Component';
3541 if (!didWarnAboutUninitializedState.has(componentName)) {
3542 didWarnAboutUninitializedState.add(componentName);
3543 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);
3544 }
3545 }
3546
3547 // If new component APIs are defined, "unsafe" lifecycles won't be called.
3548 // Warn about these lifecycles if they are present.
3549 // Don't warn about react-lifecycles-compat polyfilled methods though.
3550 if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
3551 var foundWillMountName = null;
3552 var foundWillReceivePropsName = null;
3553 var foundWillUpdateName = null;
3554 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
3555 foundWillMountName = 'componentWillMount';
3556 } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
3557 foundWillMountName = 'UNSAFE_componentWillMount';
3558 }
3559 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
3560 foundWillReceivePropsName = 'componentWillReceiveProps';
3561 } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
3562 foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
3563 }
3564 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
3565 foundWillUpdateName = 'componentWillUpdate';
3566 } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
3567 foundWillUpdateName = 'UNSAFE_componentWillUpdate';
3568 }
3569 if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
3570 var _componentName = getComponentName(ctor) || 'Component';
3571 var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
3572 if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
3573 didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
3574 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 : '');
3575 }
3576 }
3577 }
3578 }
3579
3580 // Cache unmasked context so we can avoid recreating masked context unless necessary.
3581 // ReactFiberContext usually updates this cache but can't for newly-created instances.
3582 if (isLegacyContextConsumer) {
3583 cacheContext(workInProgress, unmaskedContext, context);
3584 }
3585
3586 return instance;
3587}
3588
3589function callComponentWillMount(workInProgress, instance) {
3590 startPhaseTimer(workInProgress, 'componentWillMount');
3591 var oldState = instance.state;
3592
3593 if (typeof instance.componentWillMount === 'function') {
3594 instance.componentWillMount();
3595 }
3596 if (typeof instance.UNSAFE_componentWillMount === 'function') {
3597 instance.UNSAFE_componentWillMount();
3598 }
3599
3600 stopPhaseTimer();
3601
3602 if (oldState !== instance.state) {
3603 {
3604 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');
3605 }
3606 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
3607 }
3608}
3609
3610function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
3611 var oldState = instance.state;
3612 startPhaseTimer(workInProgress, 'componentWillReceiveProps');
3613 if (typeof instance.componentWillReceiveProps === 'function') {
3614 instance.componentWillReceiveProps(newProps, nextContext);
3615 }
3616 if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
3617 instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
3618 }
3619 stopPhaseTimer();
3620
3621 if (instance.state !== oldState) {
3622 {
3623 var componentName = getComponentName(workInProgress.type) || 'Component';
3624 if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
3625 didWarnAboutStateAssignmentForComponent.add(componentName);
3626 warningWithoutStack$1(false, '%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
3627 }
3628 }
3629 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
3630 }
3631}
3632
3633// Invokes the mount life-cycles on a previously never rendered instance.
3634function mountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
3635 {
3636 checkClassInstance(workInProgress, ctor, newProps);
3637 }
3638
3639 var instance = workInProgress.stateNode;
3640 instance.props = newProps;
3641 instance.state = workInProgress.memoizedState;
3642 instance.refs = emptyRefsObject;
3643
3644 var contextType = ctor.contextType;
3645 if (typeof contextType === 'object' && contextType !== null) {
3646 instance.context = readContext(contextType);
3647 } else {
3648 var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
3649 instance.context = getMaskedContext(workInProgress, unmaskedContext);
3650 }
3651
3652 {
3653 if (instance.state === newProps) {
3654 var componentName = getComponentName(ctor) || 'Component';
3655 if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
3656 didWarnAboutDirectlyAssigningPropsToState.add(componentName);
3657 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);
3658 }
3659 }
3660
3661 if (workInProgress.mode & StrictMode) {
3662 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
3663
3664 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
3665 }
3666
3667 if (warnAboutDeprecatedLifecycles) {
3668 ReactStrictModeWarnings.recordDeprecationWarnings(workInProgress, instance);
3669 }
3670 }
3671
3672 var updateQueue = workInProgress.updateQueue;
3673 if (updateQueue !== null) {
3674 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
3675 instance.state = workInProgress.memoizedState;
3676 }
3677
3678 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
3679 if (typeof getDerivedStateFromProps === 'function') {
3680 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
3681 instance.state = workInProgress.memoizedState;
3682 }
3683
3684 // In order to support react-lifecycles-compat polyfilled components,
3685 // Unsafe lifecycles should not be invoked for components using the new APIs.
3686 if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
3687 callComponentWillMount(workInProgress, instance);
3688 // If we had additional state updates during this life-cycle, let's
3689 // process them now.
3690 updateQueue = workInProgress.updateQueue;
3691 if (updateQueue !== null) {
3692 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
3693 instance.state = workInProgress.memoizedState;
3694 }
3695 }
3696
3697 if (typeof instance.componentDidMount === 'function') {
3698 workInProgress.effectTag |= Update;
3699 }
3700}
3701
3702function resumeMountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
3703 var instance = workInProgress.stateNode;
3704
3705 var oldProps = workInProgress.memoizedProps;
3706 instance.props = oldProps;
3707
3708 var oldContext = instance.context;
3709 var contextType = ctor.contextType;
3710 var nextContext = void 0;
3711 if (typeof contextType === 'object' && contextType !== null) {
3712 nextContext = readContext(contextType);
3713 } else {
3714 var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
3715 nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
3716 }
3717
3718 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
3719 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';
3720
3721 // Note: During these life-cycles, instance.props/instance.state are what
3722 // ever the previously attempted to render - not the "current". However,
3723 // during componentDidUpdate we pass the "current" props.
3724
3725 // In order to support react-lifecycles-compat polyfilled components,
3726 // Unsafe lifecycles should not be invoked for components using the new APIs.
3727 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
3728 if (oldProps !== newProps || oldContext !== nextContext) {
3729 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
3730 }
3731 }
3732
3733 resetHasForceUpdateBeforeProcessing();
3734
3735 var oldState = workInProgress.memoizedState;
3736 var newState = instance.state = oldState;
3737 var updateQueue = workInProgress.updateQueue;
3738 if (updateQueue !== null) {
3739 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
3740 newState = workInProgress.memoizedState;
3741 }
3742 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
3743 // If an update was already in progress, we should schedule an Update
3744 // effect even though we're bailing out, so that cWU/cDU are called.
3745 if (typeof instance.componentDidMount === 'function') {
3746 workInProgress.effectTag |= Update;
3747 }
3748 return false;
3749 }
3750
3751 if (typeof getDerivedStateFromProps === 'function') {
3752 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
3753 newState = workInProgress.memoizedState;
3754 }
3755
3756 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
3757
3758 if (shouldUpdate) {
3759 // In order to support react-lifecycles-compat polyfilled components,
3760 // Unsafe lifecycles should not be invoked for components using the new APIs.
3761 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
3762 startPhaseTimer(workInProgress, 'componentWillMount');
3763 if (typeof instance.componentWillMount === 'function') {
3764 instance.componentWillMount();
3765 }
3766 if (typeof instance.UNSAFE_componentWillMount === 'function') {
3767 instance.UNSAFE_componentWillMount();
3768 }
3769 stopPhaseTimer();
3770 }
3771 if (typeof instance.componentDidMount === 'function') {
3772 workInProgress.effectTag |= Update;
3773 }
3774 } else {
3775 // If an update was already in progress, we should schedule an Update
3776 // effect even though we're bailing out, so that cWU/cDU are called.
3777 if (typeof instance.componentDidMount === 'function') {
3778 workInProgress.effectTag |= Update;
3779 }
3780
3781 // If shouldComponentUpdate returned false, we should still update the
3782 // memoized state to indicate that this work can be reused.
3783 workInProgress.memoizedProps = newProps;
3784 workInProgress.memoizedState = newState;
3785 }
3786
3787 // Update the existing instance's state, props, and context pointers even
3788 // if shouldComponentUpdate returns false.
3789 instance.props = newProps;
3790 instance.state = newState;
3791 instance.context = nextContext;
3792
3793 return shouldUpdate;
3794}
3795
3796// Invokes the update life-cycles and returns false if it shouldn't rerender.
3797function updateClassInstance(current, workInProgress, ctor, newProps, renderExpirationTime) {
3798 var instance = workInProgress.stateNode;
3799
3800 var oldProps = workInProgress.memoizedProps;
3801 instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps);
3802
3803 var oldContext = instance.context;
3804 var contextType = ctor.contextType;
3805 var nextContext = void 0;
3806 if (typeof contextType === 'object' && contextType !== null) {
3807 nextContext = readContext(contextType);
3808 } else {
3809 var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
3810 nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
3811 }
3812
3813 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
3814 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';
3815
3816 // Note: During these life-cycles, instance.props/instance.state are what
3817 // ever the previously attempted to render - not the "current". However,
3818 // during componentDidUpdate we pass the "current" props.
3819
3820 // In order to support react-lifecycles-compat polyfilled components,
3821 // Unsafe lifecycles should not be invoked for components using the new APIs.
3822 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
3823 if (oldProps !== newProps || oldContext !== nextContext) {
3824 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
3825 }
3826 }
3827
3828 resetHasForceUpdateBeforeProcessing();
3829
3830 var oldState = workInProgress.memoizedState;
3831 var newState = instance.state = oldState;
3832 var updateQueue = workInProgress.updateQueue;
3833 if (updateQueue !== null) {
3834 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
3835 newState = workInProgress.memoizedState;
3836 }
3837
3838 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
3839 // If an update was already in progress, we should schedule an Update
3840 // effect even though we're bailing out, so that cWU/cDU are called.
3841 if (typeof instance.componentDidUpdate === 'function') {
3842 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
3843 workInProgress.effectTag |= Update;
3844 }
3845 }
3846 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
3847 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
3848 workInProgress.effectTag |= Snapshot;
3849 }
3850 }
3851 return false;
3852 }
3853
3854 if (typeof getDerivedStateFromProps === 'function') {
3855 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
3856 newState = workInProgress.memoizedState;
3857 }
3858
3859 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
3860
3861 if (shouldUpdate) {
3862 // In order to support react-lifecycles-compat polyfilled components,
3863 // Unsafe lifecycles should not be invoked for components using the new APIs.
3864 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
3865 startPhaseTimer(workInProgress, 'componentWillUpdate');
3866 if (typeof instance.componentWillUpdate === 'function') {
3867 instance.componentWillUpdate(newProps, newState, nextContext);
3868 }
3869 if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
3870 instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
3871 }
3872 stopPhaseTimer();
3873 }
3874 if (typeof instance.componentDidUpdate === 'function') {
3875 workInProgress.effectTag |= Update;
3876 }
3877 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
3878 workInProgress.effectTag |= Snapshot;
3879 }
3880 } else {
3881 // If an update was already in progress, we should schedule an Update
3882 // effect even though we're bailing out, so that cWU/cDU are called.
3883 if (typeof instance.componentDidUpdate === 'function') {
3884 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
3885 workInProgress.effectTag |= Update;
3886 }
3887 }
3888 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
3889 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
3890 workInProgress.effectTag |= Snapshot;
3891 }
3892 }
3893
3894 // If shouldComponentUpdate returned false, we should still update the
3895 // memoized props/state to indicate that this work can be reused.
3896 workInProgress.memoizedProps = newProps;
3897 workInProgress.memoizedState = newState;
3898 }
3899
3900 // Update the existing instance's state, props, and context pointers even
3901 // if shouldComponentUpdate returns false.
3902 instance.props = newProps;
3903 instance.state = newState;
3904 instance.context = nextContext;
3905
3906 return shouldUpdate;
3907}
3908
3909var didWarnAboutMaps = void 0;
3910var didWarnAboutGenerators = void 0;
3911var didWarnAboutStringRefInStrictMode = void 0;
3912var ownerHasKeyUseWarning = void 0;
3913var ownerHasFunctionTypeWarning = void 0;
3914var warnForMissingKey = function (child) {};
3915
3916{
3917 didWarnAboutMaps = false;
3918 didWarnAboutGenerators = false;
3919 didWarnAboutStringRefInStrictMode = {};
3920
3921 /**
3922 * Warn if there's no key explicitly set on dynamic arrays of children or
3923 * object keys are not valid. This allows us to keep track of children between
3924 * updates.
3925 */
3926 ownerHasKeyUseWarning = {};
3927 ownerHasFunctionTypeWarning = {};
3928
3929 warnForMissingKey = function (child) {
3930 if (child === null || typeof child !== 'object') {
3931 return;
3932 }
3933 if (!child._store || child._store.validated || child.key != null) {
3934 return;
3935 }
3936 !(typeof child._store === 'object') ? invariant(false, 'React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue.') : void 0;
3937 child._store.validated = true;
3938
3939 var currentComponentErrorInfo = 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + getCurrentFiberStackInDev();
3940 if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
3941 return;
3942 }
3943 ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
3944
3945 warning$1(false, 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.');
3946 };
3947}
3948
3949var isArray = Array.isArray;
3950
3951function coerceRef(returnFiber, current$$1, element) {
3952 var mixedRef = element.ref;
3953 if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
3954 {
3955 if (returnFiber.mode & StrictMode) {
3956 var componentName = getComponentName(returnFiber.type) || 'Component';
3957 if (!didWarnAboutStringRefInStrictMode[componentName]) {
3958 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));
3959 didWarnAboutStringRefInStrictMode[componentName] = true;
3960 }
3961 }
3962 }
3963
3964 if (element._owner) {
3965 var owner = element._owner;
3966 var inst = void 0;
3967 if (owner) {
3968 var ownerFiber = owner;
3969 !(ownerFiber.tag === ClassComponent) ? invariant(false, 'Function components cannot have refs. Did you mean to use React.forwardRef()?') : void 0;
3970 inst = ownerFiber.stateNode;
3971 }
3972 !inst ? invariant(false, 'Missing owner for string ref %s. This error is likely caused by a bug in React. Please file an issue.', mixedRef) : void 0;
3973 var stringRef = '' + mixedRef;
3974 // Check if previous string ref matches new string ref
3975 if (current$$1 !== null && current$$1.ref !== null && typeof current$$1.ref === 'function' && current$$1.ref._stringRef === stringRef) {
3976 return current$$1.ref;
3977 }
3978 var ref = function (value) {
3979 var refs = inst.refs;
3980 if (refs === emptyRefsObject) {
3981 // This is a lazy pooled frozen object, so we need to initialize.
3982 refs = inst.refs = {};
3983 }
3984 if (value === null) {
3985 delete refs[stringRef];
3986 } else {
3987 refs[stringRef] = value;
3988 }
3989 };
3990 ref._stringRef = stringRef;
3991 return ref;
3992 } else {
3993 !(typeof mixedRef === 'string') ? invariant(false, 'Expected ref to be a function, a string, an object returned by React.createRef(), or null.') : void 0;
3994 !element._owner ? invariant(false, 'Element ref was specified as a string (%s) 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.', mixedRef) : void 0;
3995 }
3996 }
3997 return mixedRef;
3998}
3999
4000function throwOnInvalidObjectType(returnFiber, newChild) {
4001 if (returnFiber.type !== 'textarea') {
4002 var addendum = '';
4003 {
4004 addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + getCurrentFiberStackInDev();
4005 }
4006 invariant(false, 'Objects are not valid as a React child (found: %s).%s', Object.prototype.toString.call(newChild) === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : newChild, addendum);
4007 }
4008}
4009
4010function warnOnFunctionType() {
4011 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();
4012
4013 if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) {
4014 return;
4015 }
4016 ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true;
4017
4018 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.');
4019}
4020
4021// This wrapper function exists because I expect to clone the code in each path
4022// to be able to optimize each path individually by branching early. This needs
4023// a compiler or we can do it manually. Helpers that don't need this branching
4024// live outside of this function.
4025function ChildReconciler(shouldTrackSideEffects) {
4026 function deleteChild(returnFiber, childToDelete) {
4027 if (!shouldTrackSideEffects) {
4028 // Noop.
4029 return;
4030 }
4031 // Deletions are added in reversed order so we add it to the front.
4032 // At this point, the return fiber's effect list is empty except for
4033 // deletions, so we can just append the deletion to the list. The remaining
4034 // effects aren't added until the complete phase. Once we implement
4035 // resuming, this may not be true.
4036 var last = returnFiber.lastEffect;
4037 if (last !== null) {
4038 last.nextEffect = childToDelete;
4039 returnFiber.lastEffect = childToDelete;
4040 } else {
4041 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
4042 }
4043 childToDelete.nextEffect = null;
4044 childToDelete.effectTag = Deletion;
4045 }
4046
4047 function deleteRemainingChildren(returnFiber, currentFirstChild) {
4048 if (!shouldTrackSideEffects) {
4049 // Noop.
4050 return null;
4051 }
4052
4053 // TODO: For the shouldClone case, this could be micro-optimized a bit by
4054 // assuming that after the first child we've already added everything.
4055 var childToDelete = currentFirstChild;
4056 while (childToDelete !== null) {
4057 deleteChild(returnFiber, childToDelete);
4058 childToDelete = childToDelete.sibling;
4059 }
4060 return null;
4061 }
4062
4063 function mapRemainingChildren(returnFiber, currentFirstChild) {
4064 // Add the remaining children to a temporary map so that we can find them by
4065 // keys quickly. Implicit (null) keys get added to this set with their index
4066 var existingChildren = new Map();
4067
4068 var existingChild = currentFirstChild;
4069 while (existingChild !== null) {
4070 if (existingChild.key !== null) {
4071 existingChildren.set(existingChild.key, existingChild);
4072 } else {
4073 existingChildren.set(existingChild.index, existingChild);
4074 }
4075 existingChild = existingChild.sibling;
4076 }
4077 return existingChildren;
4078 }
4079
4080 function useFiber(fiber, pendingProps, expirationTime) {
4081 // We currently set sibling to null and index to 0 here because it is easy
4082 // to forget to do before returning it. E.g. for the single child case.
4083 var clone = createWorkInProgress(fiber, pendingProps, expirationTime);
4084 clone.index = 0;
4085 clone.sibling = null;
4086 return clone;
4087 }
4088
4089 function placeChild(newFiber, lastPlacedIndex, newIndex) {
4090 newFiber.index = newIndex;
4091 if (!shouldTrackSideEffects) {
4092 // Noop.
4093 return lastPlacedIndex;
4094 }
4095 var current$$1 = newFiber.alternate;
4096 if (current$$1 !== null) {
4097 var oldIndex = current$$1.index;
4098 if (oldIndex < lastPlacedIndex) {
4099 // This is a move.
4100 newFiber.effectTag = Placement;
4101 return lastPlacedIndex;
4102 } else {
4103 // This item can stay in place.
4104 return oldIndex;
4105 }
4106 } else {
4107 // This is an insertion.
4108 newFiber.effectTag = Placement;
4109 return lastPlacedIndex;
4110 }
4111 }
4112
4113 function placeSingleChild(newFiber) {
4114 // This is simpler for the single child case. We only need to do a
4115 // placement for inserting new children.
4116 if (shouldTrackSideEffects && newFiber.alternate === null) {
4117 newFiber.effectTag = Placement;
4118 }
4119 return newFiber;
4120 }
4121
4122 function updateTextNode(returnFiber, current$$1, textContent, expirationTime) {
4123 if (current$$1 === null || current$$1.tag !== HostText) {
4124 // Insert
4125 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
4126 created.return = returnFiber;
4127 return created;
4128 } else {
4129 // Update
4130 var existing = useFiber(current$$1, textContent, expirationTime);
4131 existing.return = returnFiber;
4132 return existing;
4133 }
4134 }
4135
4136 function updateElement(returnFiber, current$$1, element, expirationTime) {
4137 if (current$$1 !== null && current$$1.elementType === element.type) {
4138 // Move based on index
4139 var existing = useFiber(current$$1, element.props, expirationTime);
4140 existing.ref = coerceRef(returnFiber, current$$1, element);
4141 existing.return = returnFiber;
4142 {
4143 existing._debugSource = element._source;
4144 existing._debugOwner = element._owner;
4145 }
4146 return existing;
4147 } else {
4148 // Insert
4149 var created = createFiberFromElement(element, returnFiber.mode, expirationTime);
4150 created.ref = coerceRef(returnFiber, current$$1, element);
4151 created.return = returnFiber;
4152 return created;
4153 }
4154 }
4155
4156 function updatePortal(returnFiber, current$$1, portal, expirationTime) {
4157 if (current$$1 === null || current$$1.tag !== HostPortal || current$$1.stateNode.containerInfo !== portal.containerInfo || current$$1.stateNode.implementation !== portal.implementation) {
4158 // Insert
4159 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
4160 created.return = returnFiber;
4161 return created;
4162 } else {
4163 // Update
4164 var existing = useFiber(current$$1, portal.children || [], expirationTime);
4165 existing.return = returnFiber;
4166 return existing;
4167 }
4168 }
4169
4170 function updateFragment(returnFiber, current$$1, fragment, expirationTime, key) {
4171 if (current$$1 === null || current$$1.tag !== Fragment) {
4172 // Insert
4173 var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key);
4174 created.return = returnFiber;
4175 return created;
4176 } else {
4177 // Update
4178 var existing = useFiber(current$$1, fragment, expirationTime);
4179 existing.return = returnFiber;
4180 return existing;
4181 }
4182 }
4183
4184 function createChild(returnFiber, newChild, expirationTime) {
4185 if (typeof newChild === 'string' || typeof newChild === 'number') {
4186 // Text nodes don't have keys. If the previous node is implicitly keyed
4187 // we can continue to replace it without aborting even if it is not a text
4188 // node.
4189 var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime);
4190 created.return = returnFiber;
4191 return created;
4192 }
4193
4194 if (typeof newChild === 'object' && newChild !== null) {
4195 switch (newChild.$$typeof) {
4196 case REACT_ELEMENT_TYPE:
4197 {
4198 var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime);
4199 _created.ref = coerceRef(returnFiber, null, newChild);
4200 _created.return = returnFiber;
4201 return _created;
4202 }
4203 case REACT_PORTAL_TYPE:
4204 {
4205 var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime);
4206 _created2.return = returnFiber;
4207 return _created2;
4208 }
4209 }
4210
4211 if (isArray(newChild) || getIteratorFn(newChild)) {
4212 var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null);
4213 _created3.return = returnFiber;
4214 return _created3;
4215 }
4216
4217 throwOnInvalidObjectType(returnFiber, newChild);
4218 }
4219
4220 {
4221 if (typeof newChild === 'function') {
4222 warnOnFunctionType();
4223 }
4224 }
4225
4226 return null;
4227 }
4228
4229 function updateSlot(returnFiber, oldFiber, newChild, expirationTime) {
4230 // Update the fiber if the keys match, otherwise return null.
4231
4232 var key = oldFiber !== null ? oldFiber.key : null;
4233
4234 if (typeof newChild === 'string' || typeof newChild === 'number') {
4235 // Text nodes don't have keys. If the previous node is implicitly keyed
4236 // we can continue to replace it without aborting even if it is not a text
4237 // node.
4238 if (key !== null) {
4239 return null;
4240 }
4241 return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime);
4242 }
4243
4244 if (typeof newChild === 'object' && newChild !== null) {
4245 switch (newChild.$$typeof) {
4246 case REACT_ELEMENT_TYPE:
4247 {
4248 if (newChild.key === key) {
4249 if (newChild.type === REACT_FRAGMENT_TYPE) {
4250 return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key);
4251 }
4252 return updateElement(returnFiber, oldFiber, newChild, expirationTime);
4253 } else {
4254 return null;
4255 }
4256 }
4257 case REACT_PORTAL_TYPE:
4258 {
4259 if (newChild.key === key) {
4260 return updatePortal(returnFiber, oldFiber, newChild, expirationTime);
4261 } else {
4262 return null;
4263 }
4264 }
4265 }
4266
4267 if (isArray(newChild) || getIteratorFn(newChild)) {
4268 if (key !== null) {
4269 return null;
4270 }
4271
4272 return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null);
4273 }
4274
4275 throwOnInvalidObjectType(returnFiber, newChild);
4276 }
4277
4278 {
4279 if (typeof newChild === 'function') {
4280 warnOnFunctionType();
4281 }
4282 }
4283
4284 return null;
4285 }
4286
4287 function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) {
4288 if (typeof newChild === 'string' || typeof newChild === 'number') {
4289 // Text nodes don't have keys, so we neither have to check the old nor
4290 // new node for the key. If both are text nodes, they match.
4291 var matchedFiber = existingChildren.get(newIdx) || null;
4292 return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime);
4293 }
4294
4295 if (typeof newChild === 'object' && newChild !== null) {
4296 switch (newChild.$$typeof) {
4297 case REACT_ELEMENT_TYPE:
4298 {
4299 var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
4300 if (newChild.type === REACT_FRAGMENT_TYPE) {
4301 return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key);
4302 }
4303 return updateElement(returnFiber, _matchedFiber, newChild, expirationTime);
4304 }
4305 case REACT_PORTAL_TYPE:
4306 {
4307 var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
4308 return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime);
4309 }
4310 }
4311
4312 if (isArray(newChild) || getIteratorFn(newChild)) {
4313 var _matchedFiber3 = existingChildren.get(newIdx) || null;
4314 return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null);
4315 }
4316
4317 throwOnInvalidObjectType(returnFiber, newChild);
4318 }
4319
4320 {
4321 if (typeof newChild === 'function') {
4322 warnOnFunctionType();
4323 }
4324 }
4325
4326 return null;
4327 }
4328
4329 /**
4330 * Warns if there is a duplicate or missing key
4331 */
4332 function warnOnInvalidKey(child, knownKeys) {
4333 {
4334 if (typeof child !== 'object' || child === null) {
4335 return knownKeys;
4336 }
4337 switch (child.$$typeof) {
4338 case REACT_ELEMENT_TYPE:
4339 case REACT_PORTAL_TYPE:
4340 warnForMissingKey(child);
4341 var key = child.key;
4342 if (typeof key !== 'string') {
4343 break;
4344 }
4345 if (knownKeys === null) {
4346 knownKeys = new Set();
4347 knownKeys.add(key);
4348 break;
4349 }
4350 if (!knownKeys.has(key)) {
4351 knownKeys.add(key);
4352 break;
4353 }
4354 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);
4355 break;
4356 default:
4357 break;
4358 }
4359 }
4360 return knownKeys;
4361 }
4362
4363 function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) {
4364 // This algorithm can't optimize by searching from boths ends since we
4365 // don't have backpointers on fibers. I'm trying to see how far we can get
4366 // with that model. If it ends up not being worth the tradeoffs, we can
4367 // add it later.
4368
4369 // Even with a two ended optimization, we'd want to optimize for the case
4370 // where there are few changes and brute force the comparison instead of
4371 // going for the Map. It'd like to explore hitting that path first in
4372 // forward-only mode and only go for the Map once we notice that we need
4373 // lots of look ahead. This doesn't handle reversal as well as two ended
4374 // search but that's unusual. Besides, for the two ended optimization to
4375 // work on Iterables, we'd need to copy the whole set.
4376
4377 // In this first iteration, we'll just live with hitting the bad case
4378 // (adding everything to a Map) in for every insert/move.
4379
4380 // If you change this code, also update reconcileChildrenIterator() which
4381 // uses the same algorithm.
4382
4383 {
4384 // First, validate keys.
4385 var knownKeys = null;
4386 for (var i = 0; i < newChildren.length; i++) {
4387 var child = newChildren[i];
4388 knownKeys = warnOnInvalidKey(child, knownKeys);
4389 }
4390 }
4391
4392 var resultingFirstChild = null;
4393 var previousNewFiber = null;
4394
4395 var oldFiber = currentFirstChild;
4396 var lastPlacedIndex = 0;
4397 var newIdx = 0;
4398 var nextOldFiber = null;
4399 for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
4400 if (oldFiber.index > newIdx) {
4401 nextOldFiber = oldFiber;
4402 oldFiber = null;
4403 } else {
4404 nextOldFiber = oldFiber.sibling;
4405 }
4406 var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime);
4407 if (newFiber === null) {
4408 // TODO: This breaks on empty slots like null children. That's
4409 // unfortunate because it triggers the slow path all the time. We need
4410 // a better way to communicate whether this was a miss or null,
4411 // boolean, undefined, etc.
4412 if (oldFiber === null) {
4413 oldFiber = nextOldFiber;
4414 }
4415 break;
4416 }
4417 if (shouldTrackSideEffects) {
4418 if (oldFiber && newFiber.alternate === null) {
4419 // We matched the slot, but we didn't reuse the existing fiber, so we
4420 // need to delete the existing child.
4421 deleteChild(returnFiber, oldFiber);
4422 }
4423 }
4424 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
4425 if (previousNewFiber === null) {
4426 // TODO: Move out of the loop. This only happens for the first run.
4427 resultingFirstChild = newFiber;
4428 } else {
4429 // TODO: Defer siblings if we're not at the right index for this slot.
4430 // I.e. if we had null values before, then we want to defer this
4431 // for each null value. However, we also don't want to call updateSlot
4432 // with the previous one.
4433 previousNewFiber.sibling = newFiber;
4434 }
4435 previousNewFiber = newFiber;
4436 oldFiber = nextOldFiber;
4437 }
4438
4439 if (newIdx === newChildren.length) {
4440 // We've reached the end of the new children. We can delete the rest.
4441 deleteRemainingChildren(returnFiber, oldFiber);
4442 return resultingFirstChild;
4443 }
4444
4445 if (oldFiber === null) {
4446 // If we don't have any more existing children we can choose a fast path
4447 // since the rest will all be insertions.
4448 for (; newIdx < newChildren.length; newIdx++) {
4449 var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime);
4450 if (!_newFiber) {
4451 continue;
4452 }
4453 lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
4454 if (previousNewFiber === null) {
4455 // TODO: Move out of the loop. This only happens for the first run.
4456 resultingFirstChild = _newFiber;
4457 } else {
4458 previousNewFiber.sibling = _newFiber;
4459 }
4460 previousNewFiber = _newFiber;
4461 }
4462 return resultingFirstChild;
4463 }
4464
4465 // Add all children to a key map for quick lookups.
4466 var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
4467
4468 // Keep scanning and use the map to restore deleted items as moves.
4469 for (; newIdx < newChildren.length; newIdx++) {
4470 var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime);
4471 if (_newFiber2) {
4472 if (shouldTrackSideEffects) {
4473 if (_newFiber2.alternate !== null) {
4474 // The new fiber is a work in progress, but if there exists a
4475 // current, that means that we reused the fiber. We need to delete
4476 // it from the child list so that we don't add it to the deletion
4477 // list.
4478 existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
4479 }
4480 }
4481 lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
4482 if (previousNewFiber === null) {
4483 resultingFirstChild = _newFiber2;
4484 } else {
4485 previousNewFiber.sibling = _newFiber2;
4486 }
4487 previousNewFiber = _newFiber2;
4488 }
4489 }
4490
4491 if (shouldTrackSideEffects) {
4492 // Any existing children that weren't consumed above were deleted. We need
4493 // to add them to the deletion list.
4494 existingChildren.forEach(function (child) {
4495 return deleteChild(returnFiber, child);
4496 });
4497 }
4498
4499 return resultingFirstChild;
4500 }
4501
4502 function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) {
4503 // This is the same implementation as reconcileChildrenArray(),
4504 // but using the iterator instead.
4505
4506 var iteratorFn = getIteratorFn(newChildrenIterable);
4507 !(typeof iteratorFn === 'function') ? invariant(false, 'An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.') : void 0;
4508
4509 {
4510 // We don't support rendering Generators because it's a mutation.
4511 // See https://github.com/facebook/react/issues/12995
4512 if (typeof Symbol === 'function' &&
4513 // $FlowFixMe Flow doesn't know about toStringTag
4514 newChildrenIterable[Symbol.toStringTag] === 'Generator') {
4515 !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;
4516 didWarnAboutGenerators = true;
4517 }
4518
4519 // Warn about using Maps as children
4520 if (newChildrenIterable.entries === iteratorFn) {
4521 !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;
4522 didWarnAboutMaps = true;
4523 }
4524
4525 // First, validate keys.
4526 // We'll get a different iterator later for the main pass.
4527 var _newChildren = iteratorFn.call(newChildrenIterable);
4528 if (_newChildren) {
4529 var knownKeys = null;
4530 var _step = _newChildren.next();
4531 for (; !_step.done; _step = _newChildren.next()) {
4532 var child = _step.value;
4533 knownKeys = warnOnInvalidKey(child, knownKeys);
4534 }
4535 }
4536 }
4537
4538 var newChildren = iteratorFn.call(newChildrenIterable);
4539 !(newChildren != null) ? invariant(false, 'An iterable object provided no iterator.') : void 0;
4540
4541 var resultingFirstChild = null;
4542 var previousNewFiber = null;
4543
4544 var oldFiber = currentFirstChild;
4545 var lastPlacedIndex = 0;
4546 var newIdx = 0;
4547 var nextOldFiber = null;
4548
4549 var step = newChildren.next();
4550 for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
4551 if (oldFiber.index > newIdx) {
4552 nextOldFiber = oldFiber;
4553 oldFiber = null;
4554 } else {
4555 nextOldFiber = oldFiber.sibling;
4556 }
4557 var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime);
4558 if (newFiber === null) {
4559 // TODO: This breaks on empty slots like null children. That's
4560 // unfortunate because it triggers the slow path all the time. We need
4561 // a better way to communicate whether this was a miss or null,
4562 // boolean, undefined, etc.
4563 if (!oldFiber) {
4564 oldFiber = nextOldFiber;
4565 }
4566 break;
4567 }
4568 if (shouldTrackSideEffects) {
4569 if (oldFiber && newFiber.alternate === null) {
4570 // We matched the slot, but we didn't reuse the existing fiber, so we
4571 // need to delete the existing child.
4572 deleteChild(returnFiber, oldFiber);
4573 }
4574 }
4575 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
4576 if (previousNewFiber === null) {
4577 // TODO: Move out of the loop. This only happens for the first run.
4578 resultingFirstChild = newFiber;
4579 } else {
4580 // TODO: Defer siblings if we're not at the right index for this slot.
4581 // I.e. if we had null values before, then we want to defer this
4582 // for each null value. However, we also don't want to call updateSlot
4583 // with the previous one.
4584 previousNewFiber.sibling = newFiber;
4585 }
4586 previousNewFiber = newFiber;
4587 oldFiber = nextOldFiber;
4588 }
4589
4590 if (step.done) {
4591 // We've reached the end of the new children. We can delete the rest.
4592 deleteRemainingChildren(returnFiber, oldFiber);
4593 return resultingFirstChild;
4594 }
4595
4596 if (oldFiber === null) {
4597 // If we don't have any more existing children we can choose a fast path
4598 // since the rest will all be insertions.
4599 for (; !step.done; newIdx++, step = newChildren.next()) {
4600 var _newFiber3 = createChild(returnFiber, step.value, expirationTime);
4601 if (_newFiber3 === null) {
4602 continue;
4603 }
4604 lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
4605 if (previousNewFiber === null) {
4606 // TODO: Move out of the loop. This only happens for the first run.
4607 resultingFirstChild = _newFiber3;
4608 } else {
4609 previousNewFiber.sibling = _newFiber3;
4610 }
4611 previousNewFiber = _newFiber3;
4612 }
4613 return resultingFirstChild;
4614 }
4615
4616 // Add all children to a key map for quick lookups.
4617 var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
4618
4619 // Keep scanning and use the map to restore deleted items as moves.
4620 for (; !step.done; newIdx++, step = newChildren.next()) {
4621 var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime);
4622 if (_newFiber4 !== null) {
4623 if (shouldTrackSideEffects) {
4624 if (_newFiber4.alternate !== null) {
4625 // The new fiber is a work in progress, but if there exists a
4626 // current, that means that we reused the fiber. We need to delete
4627 // it from the child list so that we don't add it to the deletion
4628 // list.
4629 existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
4630 }
4631 }
4632 lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
4633 if (previousNewFiber === null) {
4634 resultingFirstChild = _newFiber4;
4635 } else {
4636 previousNewFiber.sibling = _newFiber4;
4637 }
4638 previousNewFiber = _newFiber4;
4639 }
4640 }
4641
4642 if (shouldTrackSideEffects) {
4643 // Any existing children that weren't consumed above were deleted. We need
4644 // to add them to the deletion list.
4645 existingChildren.forEach(function (child) {
4646 return deleteChild(returnFiber, child);
4647 });
4648 }
4649
4650 return resultingFirstChild;
4651 }
4652
4653 function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) {
4654 // There's no need to check for keys on text nodes since we don't have a
4655 // way to define them.
4656 if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
4657 // We already have an existing node so let's just update it and delete
4658 // the rest.
4659 deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
4660 var existing = useFiber(currentFirstChild, textContent, expirationTime);
4661 existing.return = returnFiber;
4662 return existing;
4663 }
4664 // The existing first child is not a text node so we need to create one
4665 // and delete the existing ones.
4666 deleteRemainingChildren(returnFiber, currentFirstChild);
4667 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
4668 created.return = returnFiber;
4669 return created;
4670 }
4671
4672 function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) {
4673 var key = element.key;
4674 var child = currentFirstChild;
4675 while (child !== null) {
4676 // TODO: If key === null and child.key === null, then this only applies to
4677 // the first item in the list.
4678 if (child.key === key) {
4679 if (child.tag === Fragment ? element.type === REACT_FRAGMENT_TYPE : child.elementType === element.type) {
4680 deleteRemainingChildren(returnFiber, child.sibling);
4681 var existing = useFiber(child, element.type === REACT_FRAGMENT_TYPE ? element.props.children : element.props, expirationTime);
4682 existing.ref = coerceRef(returnFiber, child, element);
4683 existing.return = returnFiber;
4684 {
4685 existing._debugSource = element._source;
4686 existing._debugOwner = element._owner;
4687 }
4688 return existing;
4689 } else {
4690 deleteRemainingChildren(returnFiber, child);
4691 break;
4692 }
4693 } else {
4694 deleteChild(returnFiber, child);
4695 }
4696 child = child.sibling;
4697 }
4698
4699 if (element.type === REACT_FRAGMENT_TYPE) {
4700 var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key);
4701 created.return = returnFiber;
4702 return created;
4703 } else {
4704 var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime);
4705 _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
4706 _created4.return = returnFiber;
4707 return _created4;
4708 }
4709 }
4710
4711 function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) {
4712 var key = portal.key;
4713 var child = currentFirstChild;
4714 while (child !== null) {
4715 // TODO: If key === null and child.key === null, then this only applies to
4716 // the first item in the list.
4717 if (child.key === key) {
4718 if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
4719 deleteRemainingChildren(returnFiber, child.sibling);
4720 var existing = useFiber(child, portal.children || [], expirationTime);
4721 existing.return = returnFiber;
4722 return existing;
4723 } else {
4724 deleteRemainingChildren(returnFiber, child);
4725 break;
4726 }
4727 } else {
4728 deleteChild(returnFiber, child);
4729 }
4730 child = child.sibling;
4731 }
4732
4733 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
4734 created.return = returnFiber;
4735 return created;
4736 }
4737
4738 // This API will tag the children with the side-effect of the reconciliation
4739 // itself. They will be added to the side-effect list as we pass through the
4740 // children and the parent.
4741 function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) {
4742 // This function is not recursive.
4743 // If the top level item is an array, we treat it as a set of children,
4744 // not as a fragment. Nested arrays on the other hand will be treated as
4745 // fragment nodes. Recursion happens at the normal flow.
4746
4747 // Handle top level unkeyed fragments as if they were arrays.
4748 // This leads to an ambiguity between <>{[...]}</> and <>...</>.
4749 // We treat the ambiguous cases above the same.
4750 var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
4751 if (isUnkeyedTopLevelFragment) {
4752 newChild = newChild.props.children;
4753 }
4754
4755 // Handle object types
4756 var isObject = typeof newChild === 'object' && newChild !== null;
4757
4758 if (isObject) {
4759 switch (newChild.$$typeof) {
4760 case REACT_ELEMENT_TYPE:
4761 return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime));
4762 case REACT_PORTAL_TYPE:
4763 return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime));
4764 }
4765 }
4766
4767 if (typeof newChild === 'string' || typeof newChild === 'number') {
4768 return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime));
4769 }
4770
4771 if (isArray(newChild)) {
4772 return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime);
4773 }
4774
4775 if (getIteratorFn(newChild)) {
4776 return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime);
4777 }
4778
4779 if (isObject) {
4780 throwOnInvalidObjectType(returnFiber, newChild);
4781 }
4782
4783 {
4784 if (typeof newChild === 'function') {
4785 warnOnFunctionType();
4786 }
4787 }
4788 if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {
4789 // If the new child is undefined, and the return fiber is a composite
4790 // component, throw an error. If Fiber return types are disabled,
4791 // we already threw above.
4792 switch (returnFiber.tag) {
4793 case ClassComponent:
4794 {
4795 {
4796 var instance = returnFiber.stateNode;
4797 if (instance.render._isMockFunction) {
4798 // We allow auto-mocks to proceed as if they're returning null.
4799 break;
4800 }
4801 }
4802 }
4803 // Intentionally fall through to the next case, which handles both
4804 // functions and classes
4805 // eslint-disable-next-lined no-fallthrough
4806 case FunctionComponent:
4807 {
4808 var Component = returnFiber.type;
4809 invariant(false, '%s(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.', Component.displayName || Component.name || 'Component');
4810 }
4811 }
4812 }
4813
4814 // Remaining cases are all treated as empty.
4815 return deleteRemainingChildren(returnFiber, currentFirstChild);
4816 }
4817
4818 return reconcileChildFibers;
4819}
4820
4821var reconcileChildFibers = ChildReconciler(true);
4822var mountChildFibers = ChildReconciler(false);
4823
4824function cloneChildFibers(current$$1, workInProgress) {
4825 !(current$$1 === null || workInProgress.child === current$$1.child) ? invariant(false, 'Resuming work not yet implemented.') : void 0;
4826
4827 if (workInProgress.child === null) {
4828 return;
4829 }
4830
4831 var currentChild = workInProgress.child;
4832 var newChild = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
4833 workInProgress.child = newChild;
4834
4835 newChild.return = workInProgress;
4836 while (currentChild.sibling !== null) {
4837 currentChild = currentChild.sibling;
4838 newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
4839 newChild.return = workInProgress;
4840 }
4841 newChild.sibling = null;
4842}
4843
4844var NO_CONTEXT$1 = {};
4845
4846var contextStackCursor$1 = createCursor(NO_CONTEXT$1);
4847var contextFiberStackCursor = createCursor(NO_CONTEXT$1);
4848var rootInstanceStackCursor = createCursor(NO_CONTEXT$1);
4849
4850function requiredContext(c) {
4851 !(c !== NO_CONTEXT$1) ? invariant(false, 'Expected host context to exist. This error is likely caused by a bug in React. Please file an issue.') : void 0;
4852 return c;
4853}
4854
4855function getRootHostContainer() {
4856 var rootInstance = requiredContext(rootInstanceStackCursor.current);
4857 return rootInstance;
4858}
4859
4860function pushHostContainer(fiber, nextRootInstance) {
4861 // Push current root instance onto the stack;
4862 // This allows us to reset root when portals are popped.
4863 push(rootInstanceStackCursor, nextRootInstance, fiber);
4864 // Track the context and the Fiber that provided it.
4865 // This enables us to pop only Fibers that provide unique contexts.
4866 push(contextFiberStackCursor, fiber, fiber);
4867
4868 // Finally, we need to push the host context to the stack.
4869 // However, we can't just call getRootHostContext() and push it because
4870 // we'd have a different number of entries on the stack depending on
4871 // whether getRootHostContext() throws somewhere in renderer code or not.
4872 // So we push an empty value first. This lets us safely unwind on errors.
4873 push(contextStackCursor$1, NO_CONTEXT$1, fiber);
4874 var nextRootContext = getRootHostContext(nextRootInstance);
4875 // Now that we know this function doesn't throw, replace it.
4876 pop(contextStackCursor$1, fiber);
4877 push(contextStackCursor$1, nextRootContext, fiber);
4878}
4879
4880function popHostContainer(fiber) {
4881 pop(contextStackCursor$1, fiber);
4882 pop(contextFiberStackCursor, fiber);
4883 pop(rootInstanceStackCursor, fiber);
4884}
4885
4886function getHostContext() {
4887 var context = requiredContext(contextStackCursor$1.current);
4888 return context;
4889}
4890
4891function pushHostContext(fiber) {
4892 var rootInstance = requiredContext(rootInstanceStackCursor.current);
4893 var context = requiredContext(contextStackCursor$1.current);
4894 var nextContext = getChildHostContext(context, fiber.type, rootInstance);
4895
4896 // Don't push this Fiber's context unless it's unique.
4897 if (context === nextContext) {
4898 return;
4899 }
4900
4901 // Track the context and the Fiber that provided it.
4902 // This enables us to pop only Fibers that provide unique contexts.
4903 push(contextFiberStackCursor, fiber, fiber);
4904 push(contextStackCursor$1, nextContext, fiber);
4905}
4906
4907function popHostContext(fiber) {
4908 // Do not pop unless this Fiber provided the current context.
4909 // pushHostContext() only pushes Fibers that provide unique contexts.
4910 if (contextFiberStackCursor.current !== fiber) {
4911 return;
4912 }
4913
4914 pop(contextStackCursor$1, fiber);
4915 pop(contextFiberStackCursor, fiber);
4916}
4917
4918var NoEffect$1 = /* */0;
4919var UnmountSnapshot = /* */2;
4920var UnmountMutation = /* */4;
4921var MountMutation = /* */8;
4922var UnmountLayout = /* */16;
4923var MountLayout = /* */32;
4924var MountPassive = /* */64;
4925var UnmountPassive = /* */128;
4926
4927var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
4928
4929
4930var didWarnAboutMismatchedHooksForComponent = void 0;
4931{
4932 didWarnAboutMismatchedHooksForComponent = new Set();
4933}
4934
4935// These are set right before calling the component.
4936var renderExpirationTime = NoWork;
4937// The work-in-progress fiber. I've named it differently to distinguish it from
4938// the work-in-progress hook.
4939var currentlyRenderingFiber$1 = null;
4940
4941// Hooks are stored as a linked list on the fiber's memoizedState field. The
4942// current hook list is the list that belongs to the current fiber. The
4943// work-in-progress hook list is a new list that will be added to the
4944// work-in-progress fiber.
4945var firstCurrentHook = null;
4946var currentHook = null;
4947var nextCurrentHook = null;
4948var firstWorkInProgressHook = null;
4949var workInProgressHook = null;
4950var nextWorkInProgressHook = null;
4951
4952var remainingExpirationTime = NoWork;
4953var componentUpdateQueue = null;
4954var sideEffectTag = 0;
4955
4956// Updates scheduled during render will trigger an immediate re-render at the
4957// end of the current pass. We can't store these updates on the normal queue,
4958// because if the work is aborted, they should be discarded. Because this is
4959// a relatively rare case, we also don't want to add an additional field to
4960// either the hook or queue object types. So we store them in a lazily create
4961// map of queue -> render-phase updates, which are discarded once the component
4962// completes without re-rendering.
4963
4964// Whether an update was scheduled during the currently executing render pass.
4965var didScheduleRenderPhaseUpdate = false;
4966// Lazily created map of render-phase updates
4967var renderPhaseUpdates = null;
4968// Counter to prevent infinite loops.
4969var numberOfReRenders = 0;
4970var RE_RENDER_LIMIT = 25;
4971
4972// In DEV, this is the name of the currently executing primitive hook
4973var currentHookNameInDev = null;
4974
4975function warnOnHookMismatchInDev() {
4976 {
4977 var componentName = getComponentName(currentlyRenderingFiber$1.type);
4978 if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
4979 didWarnAboutMismatchedHooksForComponent.add(componentName);
4980
4981 var secondColumnStart = 22;
4982
4983 var table = '';
4984 var prevHook = firstCurrentHook;
4985 var nextHook = firstWorkInProgressHook;
4986 var n = 1;
4987 while (prevHook !== null && nextHook !== null) {
4988 var oldHookName = prevHook._debugType;
4989 var newHookName = nextHook._debugType;
4990
4991 var row = n + '. ' + oldHookName;
4992
4993 // Extra space so second column lines up
4994 // lol @ IE not supporting String#repeat
4995 while (row.length < secondColumnStart) {
4996 row += ' ';
4997 }
4998
4999 row += newHookName + '\n';
5000
5001 table += row;
5002 prevHook = prevHook.next;
5003 nextHook = nextHook.next;
5004 n++;
5005 }
5006
5007 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);
5008 }
5009 }
5010}
5011
5012function throwInvalidHookError() {
5013 invariant(false, 'Hooks can only be called inside the body of a function component. (https://fb.me/react-invalid-hook-call)');
5014}
5015
5016function areHookInputsEqual(nextDeps, prevDeps) {
5017 if (prevDeps === null) {
5018 {
5019 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);
5020 }
5021 return false;
5022 }
5023
5024 {
5025 // Don't bother comparing lengths in prod because these arrays should be
5026 // passed inline.
5027 if (nextDeps.length !== prevDeps.length) {
5028 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(', ') + ']');
5029 }
5030 }
5031 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
5032 if (is(nextDeps[i], prevDeps[i])) {
5033 continue;
5034 }
5035 return false;
5036 }
5037 return true;
5038}
5039
5040function renderWithHooks(current, workInProgress, Component, props, refOrContext, nextRenderExpirationTime) {
5041 renderExpirationTime = nextRenderExpirationTime;
5042 currentlyRenderingFiber$1 = workInProgress;
5043 firstCurrentHook = nextCurrentHook = current !== null ? current.memoizedState : null;
5044
5045 // The following should have already been reset
5046 // currentHook = null;
5047 // workInProgressHook = null;
5048
5049 // remainingExpirationTime = NoWork;
5050 // componentUpdateQueue = null;
5051
5052 // didScheduleRenderPhaseUpdate = false;
5053 // renderPhaseUpdates = null;
5054 // numberOfReRenders = 0;
5055 // sideEffectTag = 0;
5056
5057 {
5058 ReactCurrentDispatcher$1.current = nextCurrentHook === null ? HooksDispatcherOnMountInDEV : HooksDispatcherOnUpdateInDEV;
5059 }
5060
5061 var children = Component(props, refOrContext);
5062
5063 if (didScheduleRenderPhaseUpdate) {
5064 do {
5065 didScheduleRenderPhaseUpdate = false;
5066 numberOfReRenders += 1;
5067
5068 // Start over from the beginning of the list
5069 firstCurrentHook = nextCurrentHook = current !== null ? current.memoizedState : null;
5070 nextWorkInProgressHook = firstWorkInProgressHook;
5071
5072 currentHook = null;
5073 workInProgressHook = null;
5074 componentUpdateQueue = null;
5075
5076 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
5077
5078 children = Component(props, refOrContext);
5079 } while (didScheduleRenderPhaseUpdate);
5080
5081 renderPhaseUpdates = null;
5082 numberOfReRenders = 0;
5083 }
5084
5085 {
5086 currentHookNameInDev = null;
5087 }
5088
5089 // We can assume the previous dispatcher is always this one, since we set it
5090 // at the beginning of the render phase and there's no re-entrancy.
5091 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
5092
5093 var renderedWork = currentlyRenderingFiber$1;
5094
5095 renderedWork.memoizedState = firstWorkInProgressHook;
5096 renderedWork.expirationTime = remainingExpirationTime;
5097 renderedWork.updateQueue = componentUpdateQueue;
5098 renderedWork.effectTag |= sideEffectTag;
5099
5100 var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
5101
5102 renderExpirationTime = NoWork;
5103 currentlyRenderingFiber$1 = null;
5104
5105 firstCurrentHook = null;
5106 currentHook = null;
5107 nextCurrentHook = null;
5108 firstWorkInProgressHook = null;
5109 workInProgressHook = null;
5110 nextWorkInProgressHook = null;
5111
5112 remainingExpirationTime = NoWork;
5113 componentUpdateQueue = null;
5114 sideEffectTag = 0;
5115
5116 // These were reset above
5117 // didScheduleRenderPhaseUpdate = false;
5118 // renderPhaseUpdates = null;
5119 // numberOfReRenders = 0;
5120
5121 !!didRenderTooFewHooks ? invariant(false, 'Rendered fewer hooks than expected. This may be caused by an accidental early return statement.') : void 0;
5122
5123 return children;
5124}
5125
5126function bailoutHooks(current, workInProgress, expirationTime) {
5127 workInProgress.updateQueue = current.updateQueue;
5128 workInProgress.effectTag &= ~(Passive | Update);
5129 if (current.expirationTime <= expirationTime) {
5130 current.expirationTime = NoWork;
5131 }
5132}
5133
5134function resetHooks() {
5135 // We can assume the previous dispatcher is always this one, since we set it
5136 // at the beginning of the render phase and there's no re-entrancy.
5137 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
5138
5139 // This is used to reset the state of this module when a component throws.
5140 // It's also called inside mountIndeterminateComponent if we determine the
5141 // component is a module-style component.
5142 renderExpirationTime = NoWork;
5143 currentlyRenderingFiber$1 = null;
5144
5145 firstCurrentHook = null;
5146 currentHook = null;
5147 nextCurrentHook = null;
5148 firstWorkInProgressHook = null;
5149 workInProgressHook = null;
5150 nextWorkInProgressHook = null;
5151
5152 remainingExpirationTime = NoWork;
5153 componentUpdateQueue = null;
5154 sideEffectTag = 0;
5155
5156 {
5157 currentHookNameInDev = null;
5158 }
5159
5160 didScheduleRenderPhaseUpdate = false;
5161 renderPhaseUpdates = null;
5162 numberOfReRenders = 0;
5163}
5164
5165function mountWorkInProgressHook() {
5166 var hook = {
5167 memoizedState: null,
5168
5169 baseState: null,
5170 queue: null,
5171 baseUpdate: null,
5172
5173 next: null
5174 };
5175
5176 {
5177 hook._debugType = currentHookNameInDev;
5178 if (currentlyRenderingFiber$1 !== null && currentlyRenderingFiber$1.alternate !== null) {
5179 warning$1(false, '%s: Rendered more hooks than during the previous render. This is ' + 'not currently supported and may lead to unexpected behavior.', getComponentName(currentlyRenderingFiber$1.type));
5180 }
5181 }
5182 if (workInProgressHook === null) {
5183 // This is the first hook in the list
5184 firstWorkInProgressHook = workInProgressHook = hook;
5185 } else {
5186 // Append to the end of the list
5187 workInProgressHook = workInProgressHook.next = hook;
5188 }
5189 return workInProgressHook;
5190}
5191
5192function updateWorkInProgressHook() {
5193 // This function is used both for updates and for re-renders triggered by a
5194 // render phase update. It assumes there is either a current hook we can
5195 // clone, or a work-in-progress hook from a previous render pass that we can
5196 // use as a base. When we reach the end of the base list, we must switch to
5197 // the dispatcher used for mounts.
5198 if (nextWorkInProgressHook !== null) {
5199 // There's already a work-in-progress. Reuse it.
5200 workInProgressHook = nextWorkInProgressHook;
5201 nextWorkInProgressHook = workInProgressHook.next;
5202
5203 currentHook = nextCurrentHook;
5204 nextCurrentHook = currentHook !== null ? currentHook.next : null;
5205 } else {
5206 // Clone from the current hook.
5207 !(nextCurrentHook !== null) ? invariant(false, 'Rendered more hooks than during the previous render.') : void 0;
5208 currentHook = nextCurrentHook;
5209
5210 var newHook = {
5211 memoizedState: currentHook.memoizedState,
5212
5213 baseState: currentHook.baseState,
5214 queue: currentHook.queue,
5215 baseUpdate: currentHook.baseUpdate,
5216
5217 next: null
5218 };
5219
5220 if (workInProgressHook === null) {
5221 // This is the first hook in the list.
5222 workInProgressHook = firstWorkInProgressHook = newHook;
5223 } else {
5224 // Append to the end of the list.
5225 workInProgressHook = workInProgressHook.next = newHook;
5226 }
5227 nextCurrentHook = currentHook.next;
5228
5229 {
5230 newHook._debugType = currentHookNameInDev;
5231 if (currentHookNameInDev !== currentHook._debugType) {
5232 warnOnHookMismatchInDev();
5233 }
5234 }
5235 }
5236 return workInProgressHook;
5237}
5238
5239function createFunctionComponentUpdateQueue() {
5240 return {
5241 lastEffect: null
5242 };
5243}
5244
5245function basicStateReducer(state, action) {
5246 return typeof action === 'function' ? action(state) : action;
5247}
5248
5249function mountContext(context, observedBits) {
5250 {
5251 mountWorkInProgressHook();
5252 }
5253 return readContext(context, observedBits);
5254}
5255
5256function updateContext(context, observedBits) {
5257 {
5258 updateWorkInProgressHook();
5259 }
5260 return readContext(context, observedBits);
5261}
5262
5263function mountReducer(reducer, initialArg, init) {
5264 var hook = mountWorkInProgressHook();
5265 var initialState = void 0;
5266 if (init !== undefined) {
5267 initialState = init(initialArg);
5268 } else {
5269 initialState = initialArg;
5270 }
5271 hook.memoizedState = hook.baseState = initialState;
5272 var queue = hook.queue = {
5273 last: null,
5274 dispatch: null,
5275 eagerReducer: reducer,
5276 eagerState: initialState
5277 };
5278 var dispatch = queue.dispatch = dispatchAction.bind(null,
5279 // Flow doesn't know this is non-null, but we do.
5280 currentlyRenderingFiber$1, queue);
5281 return [hook.memoizedState, dispatch];
5282}
5283
5284function updateReducer(reducer, initialArg, init) {
5285 var hook = updateWorkInProgressHook();
5286 var queue = hook.queue;
5287 !(queue !== null) ? invariant(false, 'Should have a queue. This is likely a bug in React. Please file an issue.') : void 0;
5288
5289 if (numberOfReRenders > 0) {
5290 // This is a re-render. Apply the new render phase updates to the previous
5291 var _dispatch = queue.dispatch;
5292 if (renderPhaseUpdates !== null) {
5293 // Render phase updates are stored in a map of queue -> linked list
5294 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
5295 if (firstRenderPhaseUpdate !== undefined) {
5296 renderPhaseUpdates.delete(queue);
5297 var newState = hook.memoizedState;
5298 var update = firstRenderPhaseUpdate;
5299 do {
5300 // Process this render phase update. We don't have to check the
5301 // priority because it will always be the same as the current
5302 // render's.
5303 var _action = update.action;
5304 newState = reducer(newState, _action);
5305 update = update.next;
5306 } while (update !== null);
5307
5308 // Mark that the fiber performed work, but only if the new state is
5309 // different from the current state.
5310 if (!is(newState, hook.memoizedState)) {
5311 markWorkInProgressReceivedUpdate();
5312 }
5313
5314 hook.memoizedState = newState;
5315
5316 // Don't persist the state accumlated from the render phase updates to
5317 // the base state unless the queue is empty.
5318 // TODO: Not sure if this is the desired semantics, but it's what we
5319 // do for gDSFP. I can't remember why.
5320 if (hook.baseUpdate === queue.last) {
5321 hook.baseState = newState;
5322 }
5323
5324 return [newState, _dispatch];
5325 }
5326 }
5327 return [hook.memoizedState, _dispatch];
5328 }
5329
5330 // The last update in the entire queue
5331 var last = queue.last;
5332 // The last update that is part of the base state.
5333 var baseUpdate = hook.baseUpdate;
5334 var baseState = hook.baseState;
5335
5336 // Find the first unprocessed update.
5337 var first = void 0;
5338 if (baseUpdate !== null) {
5339 if (last !== null) {
5340 // For the first update, the queue is a circular linked list where
5341 // `queue.last.next = queue.first`. Once the first update commits, and
5342 // the `baseUpdate` is no longer empty, we can unravel the list.
5343 last.next = null;
5344 }
5345 first = baseUpdate.next;
5346 } else {
5347 first = last !== null ? last.next : null;
5348 }
5349 if (first !== null) {
5350 var _newState = baseState;
5351 var newBaseState = null;
5352 var newBaseUpdate = null;
5353 var prevUpdate = baseUpdate;
5354 var _update = first;
5355 var didSkip = false;
5356 do {
5357 var updateExpirationTime = _update.expirationTime;
5358 if (updateExpirationTime < renderExpirationTime) {
5359 // Priority is insufficient. Skip this update. If this is the first
5360 // skipped update, the previous update/state is the new base
5361 // update/state.
5362 if (!didSkip) {
5363 didSkip = true;
5364 newBaseUpdate = prevUpdate;
5365 newBaseState = _newState;
5366 }
5367 // Update the remaining priority in the queue.
5368 if (updateExpirationTime > remainingExpirationTime) {
5369 remainingExpirationTime = updateExpirationTime;
5370 }
5371 } else {
5372 // Process this update.
5373 if (_update.eagerReducer === reducer) {
5374 // If this update was processed eagerly, and its reducer matches the
5375 // current reducer, we can use the eagerly computed state.
5376 _newState = _update.eagerState;
5377 } else {
5378 var _action2 = _update.action;
5379 _newState = reducer(_newState, _action2);
5380 }
5381 }
5382 prevUpdate = _update;
5383 _update = _update.next;
5384 } while (_update !== null && _update !== first);
5385
5386 if (!didSkip) {
5387 newBaseUpdate = prevUpdate;
5388 newBaseState = _newState;
5389 }
5390
5391 // Mark that the fiber performed work, but only if the new state is
5392 // different from the current state.
5393 if (!is(_newState, hook.memoizedState)) {
5394 markWorkInProgressReceivedUpdate();
5395 }
5396
5397 hook.memoizedState = _newState;
5398 hook.baseUpdate = newBaseUpdate;
5399 hook.baseState = newBaseState;
5400
5401 queue.eagerReducer = reducer;
5402 queue.eagerState = _newState;
5403 }
5404
5405 var dispatch = queue.dispatch;
5406 return [hook.memoizedState, dispatch];
5407}
5408
5409function mountState(initialState) {
5410 var hook = mountWorkInProgressHook();
5411 if (typeof initialState === 'function') {
5412 initialState = initialState();
5413 }
5414 hook.memoizedState = hook.baseState = initialState;
5415 var queue = hook.queue = {
5416 last: null,
5417 dispatch: null,
5418 eagerReducer: basicStateReducer,
5419 eagerState: initialState
5420 };
5421 var dispatch = queue.dispatch = dispatchAction.bind(null,
5422 // Flow doesn't know this is non-null, but we do.
5423 currentlyRenderingFiber$1, queue);
5424 return [hook.memoizedState, dispatch];
5425}
5426
5427function updateState(initialState) {
5428 return updateReducer(basicStateReducer, initialState);
5429}
5430
5431function pushEffect(tag, create, destroy, deps) {
5432 var effect = {
5433 tag: tag,
5434 create: create,
5435 destroy: destroy,
5436 deps: deps,
5437 // Circular
5438 next: null
5439 };
5440 if (componentUpdateQueue === null) {
5441 componentUpdateQueue = createFunctionComponentUpdateQueue();
5442 componentUpdateQueue.lastEffect = effect.next = effect;
5443 } else {
5444 var _lastEffect = componentUpdateQueue.lastEffect;
5445 if (_lastEffect === null) {
5446 componentUpdateQueue.lastEffect = effect.next = effect;
5447 } else {
5448 var firstEffect = _lastEffect.next;
5449 _lastEffect.next = effect;
5450 effect.next = firstEffect;
5451 componentUpdateQueue.lastEffect = effect;
5452 }
5453 }
5454 return effect;
5455}
5456
5457function mountRef(initialValue) {
5458 var hook = mountWorkInProgressHook();
5459 var ref = { current: initialValue };
5460 {
5461 Object.seal(ref);
5462 }
5463 hook.memoizedState = ref;
5464 return ref;
5465}
5466
5467function updateRef(initialValue) {
5468 var hook = updateWorkInProgressHook();
5469 return hook.memoizedState;
5470}
5471
5472function mountEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
5473 var hook = mountWorkInProgressHook();
5474 var nextDeps = deps === undefined ? null : deps;
5475 sideEffectTag |= fiberEffectTag;
5476 hook.memoizedState = pushEffect(hookEffectTag, create, undefined, nextDeps);
5477}
5478
5479function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
5480 var hook = updateWorkInProgressHook();
5481 var nextDeps = deps === undefined ? null : deps;
5482 var destroy = undefined;
5483
5484 if (currentHook !== null) {
5485 var prevEffect = currentHook.memoizedState;
5486 destroy = prevEffect.destroy;
5487 if (nextDeps !== null) {
5488 var prevDeps = prevEffect.deps;
5489 if (areHookInputsEqual(nextDeps, prevDeps)) {
5490 pushEffect(NoEffect$1, create, destroy, nextDeps);
5491 return;
5492 }
5493 }
5494 }
5495
5496 sideEffectTag |= fiberEffectTag;
5497 hook.memoizedState = pushEffect(hookEffectTag, create, destroy, nextDeps);
5498}
5499
5500function mountEffect(create, deps) {
5501 return mountEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
5502}
5503
5504function updateEffect(create, deps) {
5505 return updateEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
5506}
5507
5508function mountLayoutEffect(create, deps) {
5509 return mountEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
5510}
5511
5512function updateLayoutEffect(create, deps) {
5513 return updateEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
5514}
5515
5516function imperativeHandleEffect(create, ref) {
5517 if (typeof ref === 'function') {
5518 var refCallback = ref;
5519 var _inst = create();
5520 refCallback(_inst);
5521 return function () {
5522 refCallback(null);
5523 };
5524 } else if (ref !== null && ref !== undefined) {
5525 var refObject = ref;
5526 {
5527 !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;
5528 }
5529 var _inst2 = create();
5530 refObject.current = _inst2;
5531 return function () {
5532 refObject.current = null;
5533 };
5534 }
5535}
5536
5537function mountImperativeHandle(ref, create, deps) {
5538 {
5539 !(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;
5540 }
5541
5542 // TODO: If deps are provided, should we skip comparing the ref itself?
5543 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : [ref];
5544
5545 return mountEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
5546}
5547
5548function updateImperativeHandle(ref, create, deps) {
5549 {
5550 !(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;
5551 }
5552
5553 // TODO: If deps are provided, should we skip comparing the ref itself?
5554 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : [ref];
5555
5556 return updateEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
5557}
5558
5559function mountDebugValue(value, formatterFn) {
5560 // This hook is normally a no-op.
5561 // The react-debug-hooks package injects its own implementation
5562 // so that e.g. DevTools can display custom hook values.
5563}
5564
5565var updateDebugValue = mountDebugValue;
5566
5567function mountCallback(callback, deps) {
5568 var hook = mountWorkInProgressHook();
5569 var nextDeps = deps === undefined ? null : deps;
5570 hook.memoizedState = [callback, nextDeps];
5571 return callback;
5572}
5573
5574function updateCallback(callback, deps) {
5575 var hook = updateWorkInProgressHook();
5576 var nextDeps = deps === undefined ? null : deps;
5577 var prevState = hook.memoizedState;
5578 if (prevState !== null) {
5579 if (nextDeps !== null) {
5580 var prevDeps = prevState[1];
5581 if (areHookInputsEqual(nextDeps, prevDeps)) {
5582 return prevState[0];
5583 }
5584 }
5585 }
5586 hook.memoizedState = [callback, nextDeps];
5587 return callback;
5588}
5589
5590function mountMemo(nextCreate, deps) {
5591 var hook = mountWorkInProgressHook();
5592 var nextDeps = deps === undefined ? null : deps;
5593 var nextValue = nextCreate();
5594 hook.memoizedState = [nextValue, nextDeps];
5595 return nextValue;
5596}
5597
5598function updateMemo(nextCreate, deps) {
5599 var hook = updateWorkInProgressHook();
5600 var nextDeps = deps === undefined ? null : deps;
5601 var prevState = hook.memoizedState;
5602 if (prevState !== null) {
5603 // Assume these are defined. If they're not, areHookInputsEqual will warn.
5604 if (nextDeps !== null) {
5605 var prevDeps = prevState[1];
5606 if (areHookInputsEqual(nextDeps, prevDeps)) {
5607 return prevState[0];
5608 }
5609 }
5610 }
5611 var nextValue = nextCreate();
5612 hook.memoizedState = [nextValue, nextDeps];
5613 return nextValue;
5614}
5615
5616// in a test-like environment, we want to warn if dispatchAction()
5617// is called outside of a batchedUpdates/TestUtils.act(...) call.
5618var shouldWarnForUnbatchedSetState = false;
5619
5620{
5621 // jest isnt' a 'global', it's just exposed to tests via a wrapped function
5622 // further, this isn't a test file, so flow doesn't recognize the symbol. So...
5623 // $FlowExpectedError - because requirements don't give a damn about your type sigs.
5624 if ('undefined' !== typeof jest) {
5625 shouldWarnForUnbatchedSetState = true;
5626 }
5627}
5628
5629function dispatchAction(fiber, queue, action) {
5630 !(numberOfReRenders < RE_RENDER_LIMIT) ? invariant(false, 'Too many re-renders. React limits the number of renders to prevent an infinite loop.') : void 0;
5631
5632 {
5633 !(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;
5634 }
5635
5636 var alternate = fiber.alternate;
5637 if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {
5638 // This is a render phase update. Stash it in a lazily-created map of
5639 // queue -> linked list of updates. After this render pass, we'll restart
5640 // and apply the stashed updates on top of the work-in-progress hook.
5641 didScheduleRenderPhaseUpdate = true;
5642 var update = {
5643 expirationTime: renderExpirationTime,
5644 action: action,
5645 eagerReducer: null,
5646 eagerState: null,
5647 next: null
5648 };
5649 if (renderPhaseUpdates === null) {
5650 renderPhaseUpdates = new Map();
5651 }
5652 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
5653 if (firstRenderPhaseUpdate === undefined) {
5654 renderPhaseUpdates.set(queue, update);
5655 } else {
5656 // Append the update to the end of the list.
5657 var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
5658 while (lastRenderPhaseUpdate.next !== null) {
5659 lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
5660 }
5661 lastRenderPhaseUpdate.next = update;
5662 }
5663 } else {
5664 flushPassiveEffects$1();
5665
5666 var currentTime = requestCurrentTime();
5667 var _expirationTime = computeExpirationForFiber(currentTime, fiber);
5668
5669 var _update2 = {
5670 expirationTime: _expirationTime,
5671 action: action,
5672 eagerReducer: null,
5673 eagerState: null,
5674 next: null
5675 };
5676
5677 // Append the update to the end of the list.
5678 var _last = queue.last;
5679 if (_last === null) {
5680 // This is the first update. Create a circular list.
5681 _update2.next = _update2;
5682 } else {
5683 var first = _last.next;
5684 if (first !== null) {
5685 // Still circular.
5686 _update2.next = first;
5687 }
5688 _last.next = _update2;
5689 }
5690 queue.last = _update2;
5691
5692 if (fiber.expirationTime === NoWork && (alternate === null || alternate.expirationTime === NoWork)) {
5693 // The queue is currently empty, which means we can eagerly compute the
5694 // next state before entering the render phase. If the new state is the
5695 // same as the current state, we may be able to bail out entirely.
5696 var _eagerReducer = queue.eagerReducer;
5697 if (_eagerReducer !== null) {
5698 var prevDispatcher = void 0;
5699 {
5700 prevDispatcher = ReactCurrentDispatcher$1.current;
5701 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
5702 }
5703 try {
5704 var currentState = queue.eagerState;
5705 var _eagerState = _eagerReducer(currentState, action);
5706 // Stash the eagerly computed state, and the reducer used to compute
5707 // it, on the update object. If the reducer hasn't changed by the
5708 // time we enter the render phase, then the eager state can be used
5709 // without calling the reducer again.
5710 _update2.eagerReducer = _eagerReducer;
5711 _update2.eagerState = _eagerState;
5712 if (is(_eagerState, currentState)) {
5713 // Fast path. We can bail out without scheduling React to re-render.
5714 // It's still possible that we'll need to rebase this update later,
5715 // if the component re-renders for a different reason and by that
5716 // time the reducer has changed.
5717 return;
5718 }
5719 } catch (error) {
5720 // Suppress the error. It will throw again in the render phase.
5721 } finally {
5722 {
5723 ReactCurrentDispatcher$1.current = prevDispatcher;
5724 }
5725 }
5726 }
5727 }
5728 {
5729 if (shouldWarnForUnbatchedSetState === true) {
5730 warnIfNotCurrentlyBatchingInDev(fiber);
5731 }
5732 }
5733 scheduleWork(fiber, _expirationTime);
5734 }
5735}
5736
5737var ContextOnlyDispatcher = {
5738 readContext: readContext,
5739
5740 useCallback: throwInvalidHookError,
5741 useContext: throwInvalidHookError,
5742 useEffect: throwInvalidHookError,
5743 useImperativeHandle: throwInvalidHookError,
5744 useLayoutEffect: throwInvalidHookError,
5745 useMemo: throwInvalidHookError,
5746 useReducer: throwInvalidHookError,
5747 useRef: throwInvalidHookError,
5748 useState: throwInvalidHookError,
5749 useDebugValue: throwInvalidHookError
5750};
5751
5752var HooksDispatcherOnMountInDEV = null;
5753var HooksDispatcherOnUpdateInDEV = null;
5754var InvalidNestedHooksDispatcherOnMountInDEV = null;
5755var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
5756
5757{
5758 var warnInvalidContextAccess = function () {
5759 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().');
5760 };
5761
5762 var warnInvalidHookAccess = function () {
5763 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');
5764 };
5765
5766 HooksDispatcherOnMountInDEV = {
5767 readContext: function (context, observedBits) {
5768 return readContext(context, observedBits);
5769 },
5770 useCallback: function (callback, deps) {
5771 currentHookNameInDev = 'useCallback';
5772 return mountCallback(callback, deps);
5773 },
5774 useContext: function (context, observedBits) {
5775 currentHookNameInDev = 'useContext';
5776 return mountContext(context, observedBits);
5777 },
5778 useEffect: function (create, deps) {
5779 currentHookNameInDev = 'useEffect';
5780 return mountEffect(create, deps);
5781 },
5782 useImperativeHandle: function (ref, create, deps) {
5783 currentHookNameInDev = 'useImperativeHandle';
5784 return mountImperativeHandle(ref, create, deps);
5785 },
5786 useLayoutEffect: function (create, deps) {
5787 currentHookNameInDev = 'useLayoutEffect';
5788 return mountLayoutEffect(create, deps);
5789 },
5790 useMemo: function (create, deps) {
5791 currentHookNameInDev = 'useMemo';
5792 var prevDispatcher = ReactCurrentDispatcher$1.current;
5793 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
5794 try {
5795 return mountMemo(create, deps);
5796 } finally {
5797 ReactCurrentDispatcher$1.current = prevDispatcher;
5798 }
5799 },
5800 useReducer: function (reducer, initialArg, init) {
5801 currentHookNameInDev = 'useReducer';
5802 var prevDispatcher = ReactCurrentDispatcher$1.current;
5803 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
5804 try {
5805 return mountReducer(reducer, initialArg, init);
5806 } finally {
5807 ReactCurrentDispatcher$1.current = prevDispatcher;
5808 }
5809 },
5810 useRef: function (initialValue) {
5811 currentHookNameInDev = 'useRef';
5812 return mountRef(initialValue);
5813 },
5814 useState: function (initialState) {
5815 currentHookNameInDev = 'useState';
5816 var prevDispatcher = ReactCurrentDispatcher$1.current;
5817 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
5818 try {
5819 return mountState(initialState);
5820 } finally {
5821 ReactCurrentDispatcher$1.current = prevDispatcher;
5822 }
5823 },
5824 useDebugValue: function (value, formatterFn) {
5825 currentHookNameInDev = 'useDebugValue';
5826 return mountDebugValue(value, formatterFn);
5827 }
5828 };
5829
5830 HooksDispatcherOnUpdateInDEV = {
5831 readContext: function (context, observedBits) {
5832 return readContext(context, observedBits);
5833 },
5834 useCallback: function (callback, deps) {
5835 currentHookNameInDev = 'useCallback';
5836 return updateCallback(callback, deps);
5837 },
5838 useContext: function (context, observedBits) {
5839 currentHookNameInDev = 'useContext';
5840 return updateContext(context, observedBits);
5841 },
5842 useEffect: function (create, deps) {
5843 currentHookNameInDev = 'useEffect';
5844 return updateEffect(create, deps);
5845 },
5846 useImperativeHandle: function (ref, create, deps) {
5847 currentHookNameInDev = 'useImperativeHandle';
5848 return updateImperativeHandle(ref, create, deps);
5849 },
5850 useLayoutEffect: function (create, deps) {
5851 currentHookNameInDev = 'useLayoutEffect';
5852 return updateLayoutEffect(create, deps);
5853 },
5854 useMemo: function (create, deps) {
5855 currentHookNameInDev = 'useMemo';
5856 var prevDispatcher = ReactCurrentDispatcher$1.current;
5857 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
5858 try {
5859 return updateMemo(create, deps);
5860 } finally {
5861 ReactCurrentDispatcher$1.current = prevDispatcher;
5862 }
5863 },
5864 useReducer: function (reducer, initialArg, init) {
5865 currentHookNameInDev = 'useReducer';
5866 var prevDispatcher = ReactCurrentDispatcher$1.current;
5867 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
5868 try {
5869 return updateReducer(reducer, initialArg, init);
5870 } finally {
5871 ReactCurrentDispatcher$1.current = prevDispatcher;
5872 }
5873 },
5874 useRef: function (initialValue) {
5875 currentHookNameInDev = 'useRef';
5876 return updateRef(initialValue);
5877 },
5878 useState: function (initialState) {
5879 currentHookNameInDev = 'useState';
5880 var prevDispatcher = ReactCurrentDispatcher$1.current;
5881 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
5882 try {
5883 return updateState(initialState);
5884 } finally {
5885 ReactCurrentDispatcher$1.current = prevDispatcher;
5886 }
5887 },
5888 useDebugValue: function (value, formatterFn) {
5889 currentHookNameInDev = 'useDebugValue';
5890 return updateDebugValue(value, formatterFn);
5891 }
5892 };
5893
5894 InvalidNestedHooksDispatcherOnMountInDEV = {
5895 readContext: function (context, observedBits) {
5896 warnInvalidContextAccess();
5897 return readContext(context, observedBits);
5898 },
5899 useCallback: function (callback, deps) {
5900 currentHookNameInDev = 'useCallback';
5901 warnInvalidHookAccess();
5902 return mountCallback(callback, deps);
5903 },
5904 useContext: function (context, observedBits) {
5905 currentHookNameInDev = 'useContext';
5906 warnInvalidHookAccess();
5907 return mountContext(context, observedBits);
5908 },
5909 useEffect: function (create, deps) {
5910 currentHookNameInDev = 'useEffect';
5911 warnInvalidHookAccess();
5912 return mountEffect(create, deps);
5913 },
5914 useImperativeHandle: function (ref, create, deps) {
5915 currentHookNameInDev = 'useImperativeHandle';
5916 warnInvalidHookAccess();
5917 return mountImperativeHandle(ref, create, deps);
5918 },
5919 useLayoutEffect: function (create, deps) {
5920 currentHookNameInDev = 'useLayoutEffect';
5921 warnInvalidHookAccess();
5922 return mountLayoutEffect(create, deps);
5923 },
5924 useMemo: function (create, deps) {
5925 currentHookNameInDev = 'useMemo';
5926 warnInvalidHookAccess();
5927 var prevDispatcher = ReactCurrentDispatcher$1.current;
5928 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
5929 try {
5930 return mountMemo(create, deps);
5931 } finally {
5932 ReactCurrentDispatcher$1.current = prevDispatcher;
5933 }
5934 },
5935 useReducer: function (reducer, initialArg, init) {
5936 currentHookNameInDev = 'useReducer';
5937 warnInvalidHookAccess();
5938 var prevDispatcher = ReactCurrentDispatcher$1.current;
5939 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
5940 try {
5941 return mountReducer(reducer, initialArg, init);
5942 } finally {
5943 ReactCurrentDispatcher$1.current = prevDispatcher;
5944 }
5945 },
5946 useRef: function (initialValue) {
5947 currentHookNameInDev = 'useRef';
5948 warnInvalidHookAccess();
5949 return mountRef(initialValue);
5950 },
5951 useState: function (initialState) {
5952 currentHookNameInDev = 'useState';
5953 warnInvalidHookAccess();
5954 var prevDispatcher = ReactCurrentDispatcher$1.current;
5955 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
5956 try {
5957 return mountState(initialState);
5958 } finally {
5959 ReactCurrentDispatcher$1.current = prevDispatcher;
5960 }
5961 },
5962 useDebugValue: function (value, formatterFn) {
5963 currentHookNameInDev = 'useDebugValue';
5964 warnInvalidHookAccess();
5965 return mountDebugValue(value, formatterFn);
5966 }
5967 };
5968
5969 InvalidNestedHooksDispatcherOnUpdateInDEV = {
5970 readContext: function (context, observedBits) {
5971 warnInvalidContextAccess();
5972 return readContext(context, observedBits);
5973 },
5974 useCallback: function (callback, deps) {
5975 currentHookNameInDev = 'useCallback';
5976 warnInvalidHookAccess();
5977 return updateCallback(callback, deps);
5978 },
5979 useContext: function (context, observedBits) {
5980 currentHookNameInDev = 'useContext';
5981 warnInvalidHookAccess();
5982 return updateContext(context, observedBits);
5983 },
5984 useEffect: function (create, deps) {
5985 currentHookNameInDev = 'useEffect';
5986 warnInvalidHookAccess();
5987 return updateEffect(create, deps);
5988 },
5989 useImperativeHandle: function (ref, create, deps) {
5990 currentHookNameInDev = 'useImperativeHandle';
5991 warnInvalidHookAccess();
5992 return updateImperativeHandle(ref, create, deps);
5993 },
5994 useLayoutEffect: function (create, deps) {
5995 currentHookNameInDev = 'useLayoutEffect';
5996 warnInvalidHookAccess();
5997 return updateLayoutEffect(create, deps);
5998 },
5999 useMemo: function (create, deps) {
6000 currentHookNameInDev = 'useMemo';
6001 warnInvalidHookAccess();
6002 var prevDispatcher = ReactCurrentDispatcher$1.current;
6003 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
6004 try {
6005 return updateMemo(create, deps);
6006 } finally {
6007 ReactCurrentDispatcher$1.current = prevDispatcher;
6008 }
6009 },
6010 useReducer: function (reducer, initialArg, init) {
6011 currentHookNameInDev = 'useReducer';
6012 warnInvalidHookAccess();
6013 var prevDispatcher = ReactCurrentDispatcher$1.current;
6014 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
6015 try {
6016 return updateReducer(reducer, initialArg, init);
6017 } finally {
6018 ReactCurrentDispatcher$1.current = prevDispatcher;
6019 }
6020 },
6021 useRef: function (initialValue) {
6022 currentHookNameInDev = 'useRef';
6023 warnInvalidHookAccess();
6024 return updateRef(initialValue);
6025 },
6026 useState: function (initialState) {
6027 currentHookNameInDev = 'useState';
6028 warnInvalidHookAccess();
6029 var prevDispatcher = ReactCurrentDispatcher$1.current;
6030 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
6031 try {
6032 return updateState(initialState);
6033 } finally {
6034 ReactCurrentDispatcher$1.current = prevDispatcher;
6035 }
6036 },
6037 useDebugValue: function (value, formatterFn) {
6038 currentHookNameInDev = 'useDebugValue';
6039 warnInvalidHookAccess();
6040 return updateDebugValue(value, formatterFn);
6041 }
6042 };
6043}
6044
6045var commitTime = 0;
6046var profilerStartTime = -1;
6047
6048function getCommitTime() {
6049 return commitTime;
6050}
6051
6052function recordCommitTime() {
6053 if (!enableProfilerTimer) {
6054 return;
6055 }
6056 commitTime = now();
6057}
6058
6059function startProfilerTimer(fiber) {
6060 if (!enableProfilerTimer) {
6061 return;
6062 }
6063
6064 profilerStartTime = now();
6065
6066 if (fiber.actualStartTime < 0) {
6067 fiber.actualStartTime = now();
6068 }
6069}
6070
6071function stopProfilerTimerIfRunning(fiber) {
6072 if (!enableProfilerTimer) {
6073 return;
6074 }
6075 profilerStartTime = -1;
6076}
6077
6078function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
6079 if (!enableProfilerTimer) {
6080 return;
6081 }
6082
6083 if (profilerStartTime >= 0) {
6084 var elapsedTime = now() - profilerStartTime;
6085 fiber.actualDuration += elapsedTime;
6086 if (overrideBaseTime) {
6087 fiber.selfBaseDuration = elapsedTime;
6088 }
6089 profilerStartTime = -1;
6090 }
6091}
6092
6093// The deepest Fiber on the stack involved in a hydration context.
6094// This may have been an insertion or a hydration.
6095var hydrationParentFiber = null;
6096var nextHydratableInstance = null;
6097var isHydrating = false;
6098
6099function enterHydrationState(fiber) {
6100 if (!supportsHydration) {
6101 return false;
6102 }
6103
6104 var parentInstance = fiber.stateNode.containerInfo;
6105 nextHydratableInstance = getFirstHydratableChild(parentInstance);
6106 hydrationParentFiber = fiber;
6107 isHydrating = true;
6108 return true;
6109}
6110
6111function deleteHydratableInstance(returnFiber, instance) {
6112 {
6113 switch (returnFiber.tag) {
6114 case HostRoot:
6115 didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance);
6116 break;
6117 case HostComponent:
6118 didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance);
6119 break;
6120 }
6121 }
6122
6123 var childToDelete = createFiberFromHostInstanceForDeletion();
6124 childToDelete.stateNode = instance;
6125 childToDelete.return = returnFiber;
6126 childToDelete.effectTag = Deletion;
6127
6128 // This might seem like it belongs on progressedFirstDeletion. However,
6129 // these children are not part of the reconciliation list of children.
6130 // Even if we abort and rereconcile the children, that will try to hydrate
6131 // again and the nodes are still in the host tree so these will be
6132 // recreated.
6133 if (returnFiber.lastEffect !== null) {
6134 returnFiber.lastEffect.nextEffect = childToDelete;
6135 returnFiber.lastEffect = childToDelete;
6136 } else {
6137 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
6138 }
6139}
6140
6141function insertNonHydratedInstance(returnFiber, fiber) {
6142 fiber.effectTag |= Placement;
6143 {
6144 switch (returnFiber.tag) {
6145 case HostRoot:
6146 {
6147 var parentContainer = returnFiber.stateNode.containerInfo;
6148 switch (fiber.tag) {
6149 case HostComponent:
6150 var type = fiber.type;
6151 var props = fiber.pendingProps;
6152 didNotFindHydratableContainerInstance(parentContainer, type, props);
6153 break;
6154 case HostText:
6155 var text = fiber.pendingProps;
6156 didNotFindHydratableContainerTextInstance(parentContainer, text);
6157 break;
6158 }
6159 break;
6160 }
6161 case HostComponent:
6162 {
6163 var parentType = returnFiber.type;
6164 var parentProps = returnFiber.memoizedProps;
6165 var parentInstance = returnFiber.stateNode;
6166 switch (fiber.tag) {
6167 case HostComponent:
6168 var _type = fiber.type;
6169 var _props = fiber.pendingProps;
6170 didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props);
6171 break;
6172 case HostText:
6173 var _text = fiber.pendingProps;
6174 didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text);
6175 break;
6176 }
6177 break;
6178 }
6179 default:
6180 return;
6181 }
6182 }
6183}
6184
6185function tryHydrate(fiber, nextInstance) {
6186 switch (fiber.tag) {
6187 case HostComponent:
6188 {
6189 var type = fiber.type;
6190 var props = fiber.pendingProps;
6191 var instance = canHydrateInstance(nextInstance, type, props);
6192 if (instance !== null) {
6193 fiber.stateNode = instance;
6194 return true;
6195 }
6196 return false;
6197 }
6198 case HostText:
6199 {
6200 var text = fiber.pendingProps;
6201 var textInstance = canHydrateTextInstance(nextInstance, text);
6202 if (textInstance !== null) {
6203 fiber.stateNode = textInstance;
6204 return true;
6205 }
6206 return false;
6207 }
6208 default:
6209 return false;
6210 }
6211}
6212
6213function tryToClaimNextHydratableInstance(fiber) {
6214 if (!isHydrating) {
6215 return;
6216 }
6217 var nextInstance = nextHydratableInstance;
6218 if (!nextInstance) {
6219 // Nothing to hydrate. Make it an insertion.
6220 insertNonHydratedInstance(hydrationParentFiber, fiber);
6221 isHydrating = false;
6222 hydrationParentFiber = fiber;
6223 return;
6224 }
6225 var firstAttemptedInstance = nextInstance;
6226 if (!tryHydrate(fiber, nextInstance)) {
6227 // If we can't hydrate this instance let's try the next one.
6228 // We use this as a heuristic. It's based on intuition and not data so it
6229 // might be flawed or unnecessary.
6230 nextInstance = getNextHydratableSibling(firstAttemptedInstance);
6231 if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
6232 // Nothing to hydrate. Make it an insertion.
6233 insertNonHydratedInstance(hydrationParentFiber, fiber);
6234 isHydrating = false;
6235 hydrationParentFiber = fiber;
6236 return;
6237 }
6238 // We matched the next one, we'll now assume that the first one was
6239 // superfluous and we'll delete it. Since we can't eagerly delete it
6240 // we'll have to schedule a deletion. To do that, this node needs a dummy
6241 // fiber associated with it.
6242 deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance);
6243 }
6244 hydrationParentFiber = fiber;
6245 nextHydratableInstance = getFirstHydratableChild(nextInstance);
6246}
6247
6248function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
6249 if (!supportsHydration) {
6250 invariant(false, 'Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
6251 }
6252
6253 var instance = fiber.stateNode;
6254 var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber);
6255 // TODO: Type this specific to this type of component.
6256 fiber.updateQueue = updatePayload;
6257 // If the update payload indicates that there is a change or if there
6258 // is a new ref we mark this as an update.
6259 if (updatePayload !== null) {
6260 return true;
6261 }
6262 return false;
6263}
6264
6265function prepareToHydrateHostTextInstance(fiber) {
6266 if (!supportsHydration) {
6267 invariant(false, 'Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
6268 }
6269
6270 var textInstance = fiber.stateNode;
6271 var textContent = fiber.memoizedProps;
6272 var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
6273 {
6274 if (shouldUpdate) {
6275 // We assume that prepareToHydrateHostTextInstance is called in a context where the
6276 // hydration parent is the parent host component of this host text.
6277 var returnFiber = hydrationParentFiber;
6278 if (returnFiber !== null) {
6279 switch (returnFiber.tag) {
6280 case HostRoot:
6281 {
6282 var parentContainer = returnFiber.stateNode.containerInfo;
6283 didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent);
6284 break;
6285 }
6286 case HostComponent:
6287 {
6288 var parentType = returnFiber.type;
6289 var parentProps = returnFiber.memoizedProps;
6290 var parentInstance = returnFiber.stateNode;
6291 didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent);
6292 break;
6293 }
6294 }
6295 }
6296 }
6297 }
6298 return shouldUpdate;
6299}
6300
6301function popToNextHostParent(fiber) {
6302 var parent = fiber.return;
6303 while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot) {
6304 parent = parent.return;
6305 }
6306 hydrationParentFiber = parent;
6307}
6308
6309function popHydrationState(fiber) {
6310 if (!supportsHydration) {
6311 return false;
6312 }
6313 if (fiber !== hydrationParentFiber) {
6314 // We're deeper than the current hydration context, inside an inserted
6315 // tree.
6316 return false;
6317 }
6318 if (!isHydrating) {
6319 // If we're not currently hydrating but we're in a hydration context, then
6320 // we were an insertion and now need to pop up reenter hydration of our
6321 // siblings.
6322 popToNextHostParent(fiber);
6323 isHydrating = true;
6324 return false;
6325 }
6326
6327 var type = fiber.type;
6328
6329 // If we have any remaining hydratable nodes, we need to delete them now.
6330 // We only do this deeper than head and body since they tend to have random
6331 // other nodes in them. We also ignore components with pure text content in
6332 // side of them.
6333 // TODO: Better heuristic.
6334 if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) {
6335 var nextInstance = nextHydratableInstance;
6336 while (nextInstance) {
6337 deleteHydratableInstance(fiber, nextInstance);
6338 nextInstance = getNextHydratableSibling(nextInstance);
6339 }
6340 }
6341
6342 popToNextHostParent(fiber);
6343 nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
6344 return true;
6345}
6346
6347function resetHydrationState() {
6348 if (!supportsHydration) {
6349 return;
6350 }
6351
6352 hydrationParentFiber = null;
6353 nextHydratableInstance = null;
6354 isHydrating = false;
6355}
6356
6357var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner;
6358
6359var didReceiveUpdate = false;
6360
6361var didWarnAboutBadClass = void 0;
6362var didWarnAboutContextTypeOnFunctionComponent = void 0;
6363var didWarnAboutGetDerivedStateOnFunctionComponent = void 0;
6364var didWarnAboutFunctionRefs = void 0;
6365var didWarnAboutReassigningProps = void 0;
6366
6367{
6368 didWarnAboutBadClass = {};
6369 didWarnAboutContextTypeOnFunctionComponent = {};
6370 didWarnAboutGetDerivedStateOnFunctionComponent = {};
6371 didWarnAboutFunctionRefs = {};
6372 didWarnAboutReassigningProps = false;
6373}
6374
6375function reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime) {
6376 if (current$$1 === null) {
6377 // If this is a fresh new component that hasn't been rendered yet, we
6378 // won't update its child set by applying minimal side-effects. Instead,
6379 // we will add them all to the child before it gets rendered. That means
6380 // we can optimize this reconciliation pass by not tracking side-effects.
6381 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
6382 } else {
6383 // If the current child is the same as the work in progress, it means that
6384 // we haven't yet started any work on these children. Therefore, we use
6385 // the clone algorithm to create a copy of all the current children.
6386
6387 // If we had any progressed work already, that is invalid at this point so
6388 // let's throw it out.
6389 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, nextChildren, renderExpirationTime);
6390 }
6391}
6392
6393function forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime) {
6394 // This function is fork of reconcileChildren. It's used in cases where we
6395 // want to reconcile without matching against the existing set. This has the
6396 // effect of all current children being unmounted; even if the type and key
6397 // are the same, the old child is unmounted and a new child is created.
6398 //
6399 // To do this, we're going to go through the reconcile algorithm twice. In
6400 // the first pass, we schedule a deletion for all the current children by
6401 // passing null.
6402 workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, null, renderExpirationTime);
6403 // In the second pass, we mount the new children. The trick here is that we
6404 // pass null in place of where we usually pass the current child set. This has
6405 // the effect of remounting all children regardless of whether their their
6406 // identity matches.
6407 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
6408}
6409
6410function updateForwardRef(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
6411 {
6412 if (workInProgress.type !== workInProgress.elementType) {
6413 // Lazy component props can't be validated in createElement
6414 // because they're only guaranteed to be resolved here.
6415 var innerPropTypes = Component.propTypes;
6416 if (innerPropTypes) {
6417 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
6418 'prop', getComponentName(Component), getCurrentFiberStackInDev);
6419 }
6420 }
6421 }
6422
6423 var render = Component.render;
6424 var ref = workInProgress.ref;
6425
6426 // The rest is a fork of updateFunctionComponent
6427 var nextChildren = void 0;
6428 prepareToReadContext(workInProgress, renderExpirationTime);
6429 {
6430 ReactCurrentOwner$2.current = workInProgress;
6431 setCurrentPhase('render');
6432 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
6433 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
6434 // Only double-render components with Hooks
6435 if (workInProgress.memoizedState !== null) {
6436 nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime);
6437 }
6438 }
6439 setCurrentPhase(null);
6440 }
6441
6442 if (current$$1 !== null && !didReceiveUpdate) {
6443 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
6444 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
6445 }
6446
6447 // React DevTools reads this flag.
6448 workInProgress.effectTag |= PerformedWork;
6449 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
6450 return workInProgress.child;
6451}
6452
6453function updateMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
6454 if (current$$1 === null) {
6455 var type = Component.type;
6456 if (isSimpleFunctionComponent(type) && Component.compare === null &&
6457 // SimpleMemoComponent codepath doesn't resolve outer props either.
6458 Component.defaultProps === undefined) {
6459 // If this is a plain function component without default props,
6460 // and with only the default shallow comparison, we upgrade it
6461 // to a SimpleMemoComponent to allow fast path updates.
6462 workInProgress.tag = SimpleMemoComponent;
6463 workInProgress.type = type;
6464 {
6465 validateFunctionComponentInDev(workInProgress, type);
6466 }
6467 return updateSimpleMemoComponent(current$$1, workInProgress, type, nextProps, updateExpirationTime, renderExpirationTime);
6468 }
6469 {
6470 var innerPropTypes = type.propTypes;
6471 if (innerPropTypes) {
6472 // Inner memo component props aren't currently validated in createElement.
6473 // We could move it there, but we'd still need this for lazy code path.
6474 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
6475 'prop', getComponentName(type), getCurrentFiberStackInDev);
6476 }
6477 }
6478 var child = createFiberFromTypeAndProps(Component.type, null, nextProps, null, workInProgress.mode, renderExpirationTime);
6479 child.ref = workInProgress.ref;
6480 child.return = workInProgress;
6481 workInProgress.child = child;
6482 return child;
6483 }
6484 {
6485 var _type = Component.type;
6486 var _innerPropTypes = _type.propTypes;
6487 if (_innerPropTypes) {
6488 // Inner memo component props aren't currently validated in createElement.
6489 // We could move it there, but we'd still need this for lazy code path.
6490 checkPropTypes_1(_innerPropTypes, nextProps, // Resolved props
6491 'prop', getComponentName(_type), getCurrentFiberStackInDev);
6492 }
6493 }
6494 var currentChild = current$$1.child; // This is always exactly one child
6495 if (updateExpirationTime < renderExpirationTime) {
6496 // This will be the props with resolved defaultProps,
6497 // unlike current.memoizedProps which will be the unresolved ones.
6498 var prevProps = currentChild.memoizedProps;
6499 // Default to shallow comparison
6500 var compare = Component.compare;
6501 compare = compare !== null ? compare : shallowEqual;
6502 if (compare(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
6503 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
6504 }
6505 }
6506 // React DevTools reads this flag.
6507 workInProgress.effectTag |= PerformedWork;
6508 var newChild = createWorkInProgress(currentChild, nextProps, renderExpirationTime);
6509 newChild.ref = workInProgress.ref;
6510 newChild.return = workInProgress;
6511 workInProgress.child = newChild;
6512 return newChild;
6513}
6514
6515function updateSimpleMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
6516 {
6517 if (workInProgress.type !== workInProgress.elementType) {
6518 // Lazy component props can't be validated in createElement
6519 // because they're only guaranteed to be resolved here.
6520 var outerMemoType = workInProgress.elementType;
6521 if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
6522 // We warn when you define propTypes on lazy()
6523 // so let's just skip over it to find memo() outer wrapper.
6524 // Inner props for memo are validated later.
6525 outerMemoType = refineResolvedLazyComponent(outerMemoType);
6526 }
6527 var outerPropTypes = outerMemoType && outerMemoType.propTypes;
6528 if (outerPropTypes) {
6529 checkPropTypes_1(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
6530 'prop', getComponentName(outerMemoType), getCurrentFiberStackInDev);
6531 }
6532 // Inner propTypes will be validated in the function component path.
6533 }
6534 }
6535 if (current$$1 !== null) {
6536 var prevProps = current$$1.memoizedProps;
6537 if (shallowEqual(prevProps, nextProps) && current$$1.ref === workInProgress.ref) {
6538 didReceiveUpdate = false;
6539 if (updateExpirationTime < renderExpirationTime) {
6540 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
6541 }
6542 }
6543 }
6544 return updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
6545}
6546
6547function updateFragment(current$$1, workInProgress, renderExpirationTime) {
6548 var nextChildren = workInProgress.pendingProps;
6549 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
6550 return workInProgress.child;
6551}
6552
6553function updateMode(current$$1, workInProgress, renderExpirationTime) {
6554 var nextChildren = workInProgress.pendingProps.children;
6555 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
6556 return workInProgress.child;
6557}
6558
6559function updateProfiler(current$$1, workInProgress, renderExpirationTime) {
6560 if (enableProfilerTimer) {
6561 workInProgress.effectTag |= Update;
6562 }
6563 var nextProps = workInProgress.pendingProps;
6564 var nextChildren = nextProps.children;
6565 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
6566 return workInProgress.child;
6567}
6568
6569function markRef(current$$1, workInProgress) {
6570 var ref = workInProgress.ref;
6571 if (current$$1 === null && ref !== null || current$$1 !== null && current$$1.ref !== ref) {
6572 // Schedule a Ref effect
6573 workInProgress.effectTag |= Ref;
6574 }
6575}
6576
6577function updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
6578 {
6579 if (workInProgress.type !== workInProgress.elementType) {
6580 // Lazy component props can't be validated in createElement
6581 // because they're only guaranteed to be resolved here.
6582 var innerPropTypes = Component.propTypes;
6583 if (innerPropTypes) {
6584 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
6585 'prop', getComponentName(Component), getCurrentFiberStackInDev);
6586 }
6587 }
6588 }
6589
6590 var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
6591 var context = getMaskedContext(workInProgress, unmaskedContext);
6592
6593 var nextChildren = void 0;
6594 prepareToReadContext(workInProgress, renderExpirationTime);
6595 {
6596 ReactCurrentOwner$2.current = workInProgress;
6597 setCurrentPhase('render');
6598 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
6599 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
6600 // Only double-render components with Hooks
6601 if (workInProgress.memoizedState !== null) {
6602 nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime);
6603 }
6604 }
6605 setCurrentPhase(null);
6606 }
6607
6608 if (current$$1 !== null && !didReceiveUpdate) {
6609 bailoutHooks(current$$1, workInProgress, renderExpirationTime);
6610 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
6611 }
6612
6613 // React DevTools reads this flag.
6614 workInProgress.effectTag |= PerformedWork;
6615 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
6616 return workInProgress.child;
6617}
6618
6619function updateClassComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) {
6620 {
6621 if (workInProgress.type !== workInProgress.elementType) {
6622 // Lazy component props can't be validated in createElement
6623 // because they're only guaranteed to be resolved here.
6624 var innerPropTypes = Component.propTypes;
6625 if (innerPropTypes) {
6626 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
6627 'prop', getComponentName(Component), getCurrentFiberStackInDev);
6628 }
6629 }
6630 }
6631
6632 // Push context providers early to prevent context stack mismatches.
6633 // During mounting we don't know the child context yet as the instance doesn't exist.
6634 // We will invalidate the child context in finishClassComponent() right after rendering.
6635 var hasContext = void 0;
6636 if (isContextProvider(Component)) {
6637 hasContext = true;
6638 pushContextProvider(workInProgress);
6639 } else {
6640 hasContext = false;
6641 }
6642 prepareToReadContext(workInProgress, renderExpirationTime);
6643
6644 var instance = workInProgress.stateNode;
6645 var shouldUpdate = void 0;
6646 if (instance === null) {
6647 if (current$$1 !== null) {
6648 // An class component without an instance only mounts if it suspended
6649 // inside a non- concurrent tree, in an inconsistent state. We want to
6650 // tree it like a new mount, even though an empty version of it already
6651 // committed. Disconnect the alternate pointers.
6652 current$$1.alternate = null;
6653 workInProgress.alternate = null;
6654 // Since this is conceptually a new fiber, schedule a Placement effect
6655 workInProgress.effectTag |= Placement;
6656 }
6657 // In the initial pass we might need to construct the instance.
6658 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
6659 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
6660 shouldUpdate = true;
6661 } else if (current$$1 === null) {
6662 // In a resume, we'll already have an instance we can reuse.
6663 shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
6664 } else {
6665 shouldUpdate = updateClassInstance(current$$1, workInProgress, Component, nextProps, renderExpirationTime);
6666 }
6667 var nextUnitOfWork = finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime);
6668 {
6669 var inst = workInProgress.stateNode;
6670 if (inst.props !== nextProps) {
6671 !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;
6672 didWarnAboutReassigningProps = true;
6673 }
6674 }
6675 return nextUnitOfWork;
6676}
6677
6678function finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime) {
6679 // Refs should update even if shouldComponentUpdate returns false
6680 markRef(current$$1, workInProgress);
6681
6682 var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;
6683
6684 if (!shouldUpdate && !didCaptureError) {
6685 // Context providers should defer to sCU for rendering
6686 if (hasContext) {
6687 invalidateContextProvider(workInProgress, Component, false);
6688 }
6689
6690 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
6691 }
6692
6693 var instance = workInProgress.stateNode;
6694
6695 // Rerender
6696 ReactCurrentOwner$2.current = workInProgress;
6697 var nextChildren = void 0;
6698 if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
6699 // If we captured an error, but getDerivedStateFrom catch is not defined,
6700 // unmount all the children. componentDidCatch will schedule an update to
6701 // re-render a fallback. This is temporary until we migrate everyone to
6702 // the new API.
6703 // TODO: Warn in a future release.
6704 nextChildren = null;
6705
6706 if (enableProfilerTimer) {
6707 stopProfilerTimerIfRunning(workInProgress);
6708 }
6709 } else {
6710 {
6711 setCurrentPhase('render');
6712 nextChildren = instance.render();
6713 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
6714 instance.render();
6715 }
6716 setCurrentPhase(null);
6717 }
6718 }
6719
6720 // React DevTools reads this flag.
6721 workInProgress.effectTag |= PerformedWork;
6722 if (current$$1 !== null && didCaptureError) {
6723 // If we're recovering from an error, reconcile without reusing any of
6724 // the existing children. Conceptually, the normal children and the children
6725 // that are shown on error are two different sets, so we shouldn't reuse
6726 // normal children even if their identities match.
6727 forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime);
6728 } else {
6729 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
6730 }
6731
6732 // Memoize state using the values we just used to render.
6733 // TODO: Restructure so we never read values from the instance.
6734 workInProgress.memoizedState = instance.state;
6735
6736 // The context might have changed so we need to recalculate it.
6737 if (hasContext) {
6738 invalidateContextProvider(workInProgress, Component, true);
6739 }
6740
6741 return workInProgress.child;
6742}
6743
6744function pushHostRootContext(workInProgress) {
6745 var root = workInProgress.stateNode;
6746 if (root.pendingContext) {
6747 pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
6748 } else if (root.context) {
6749 // Should always be set
6750 pushTopLevelContextObject(workInProgress, root.context, false);
6751 }
6752 pushHostContainer(workInProgress, root.containerInfo);
6753}
6754
6755function updateHostRoot(current$$1, workInProgress, renderExpirationTime) {
6756 pushHostRootContext(workInProgress);
6757 var updateQueue = workInProgress.updateQueue;
6758 !(updateQueue !== null) ? invariant(false, '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.') : void 0;
6759 var nextProps = workInProgress.pendingProps;
6760 var prevState = workInProgress.memoizedState;
6761 var prevChildren = prevState !== null ? prevState.element : null;
6762 processUpdateQueue(workInProgress, updateQueue, nextProps, null, renderExpirationTime);
6763 var nextState = workInProgress.memoizedState;
6764 // Caution: React DevTools currently depends on this property
6765 // being called "element".
6766 var nextChildren = nextState.element;
6767 if (nextChildren === prevChildren) {
6768 // If the state is the same as before, that's a bailout because we had
6769 // no work that expires at this time.
6770 resetHydrationState();
6771 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
6772 }
6773 var root = workInProgress.stateNode;
6774 if ((current$$1 === null || current$$1.child === null) && root.hydrate && enterHydrationState(workInProgress)) {
6775 // If we don't have any current children this might be the first pass.
6776 // We always try to hydrate. If this isn't a hydration pass there won't
6777 // be any children to hydrate which is effectively the same thing as
6778 // not hydrating.
6779
6780 // This is a bit of a hack. We track the host root as a placement to
6781 // know that we're currently in a mounting state. That way isMounted
6782 // works as expected. We must reset this before committing.
6783 // TODO: Delete this when we delete isMounted and findDOMNode.
6784 workInProgress.effectTag |= Placement;
6785
6786 // Ensure that children mount into this root without tracking
6787 // side-effects. This ensures that we don't store Placement effects on
6788 // nodes that will be hydrated.
6789 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
6790 } else {
6791 // Otherwise reset hydration state in case we aborted and resumed another
6792 // root.
6793 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
6794 resetHydrationState();
6795 }
6796 return workInProgress.child;
6797}
6798
6799function updateHostComponent(current$$1, workInProgress, renderExpirationTime) {
6800 pushHostContext(workInProgress);
6801
6802 if (current$$1 === null) {
6803 tryToClaimNextHydratableInstance(workInProgress);
6804 }
6805
6806 var type = workInProgress.type;
6807 var nextProps = workInProgress.pendingProps;
6808 var prevProps = current$$1 !== null ? current$$1.memoizedProps : null;
6809
6810 var nextChildren = nextProps.children;
6811 var isDirectTextChild = shouldSetTextContent(type, nextProps);
6812
6813 if (isDirectTextChild) {
6814 // We special case a direct text child of a host node. This is a common
6815 // case. We won't handle it as a reified child. We will instead handle
6816 // this in the host environment that also have access to this prop. That
6817 // avoids allocating another HostText fiber and traversing it.
6818 nextChildren = null;
6819 } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
6820 // If we're switching from a direct text child to a normal child, or to
6821 // empty, we need to schedule the text content to be reset.
6822 workInProgress.effectTag |= ContentReset;
6823 }
6824
6825 markRef(current$$1, workInProgress);
6826
6827 // Check the host config to see if the children are offscreen/hidden.
6828 if (renderExpirationTime !== Never && workInProgress.mode & ConcurrentMode && shouldDeprioritizeSubtree(type, nextProps)) {
6829 // Schedule this fiber to re-render at offscreen priority. Then bailout.
6830 workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
6831 return null;
6832 }
6833
6834 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
6835 return workInProgress.child;
6836}
6837
6838function updateHostText(current$$1, workInProgress) {
6839 if (current$$1 === null) {
6840 tryToClaimNextHydratableInstance(workInProgress);
6841 }
6842 // Nothing to do here. This is terminal. We'll do the completion step
6843 // immediately after.
6844 return null;
6845}
6846
6847function mountLazyComponent(_current, workInProgress, elementType, updateExpirationTime, renderExpirationTime) {
6848 if (_current !== null) {
6849 // An lazy component only mounts if it suspended inside a non-
6850 // concurrent tree, in an inconsistent state. We want to treat it like
6851 // a new mount, even though an empty version of it already committed.
6852 // Disconnect the alternate pointers.
6853 _current.alternate = null;
6854 workInProgress.alternate = null;
6855 // Since this is conceptually a new fiber, schedule a Placement effect
6856 workInProgress.effectTag |= Placement;
6857 }
6858
6859 var props = workInProgress.pendingProps;
6860 // We can't start a User Timing measurement with correct label yet.
6861 // Cancel and resume right after we know the tag.
6862 cancelWorkTimer(workInProgress);
6863 var Component = readLazyComponentType(elementType);
6864 // Store the unwrapped component in the type.
6865 workInProgress.type = Component;
6866 var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
6867 startWorkTimer(workInProgress);
6868 var resolvedProps = resolveDefaultProps(Component, props);
6869 var child = void 0;
6870 switch (resolvedTag) {
6871 case FunctionComponent:
6872 {
6873 {
6874 validateFunctionComponentInDev(workInProgress, Component);
6875 }
6876 child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
6877 break;
6878 }
6879 case ClassComponent:
6880 {
6881 child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
6882 break;
6883 }
6884 case ForwardRef:
6885 {
6886 child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderExpirationTime);
6887 break;
6888 }
6889 case MemoComponent:
6890 {
6891 {
6892 if (workInProgress.type !== workInProgress.elementType) {
6893 var outerPropTypes = Component.propTypes;
6894 if (outerPropTypes) {
6895 checkPropTypes_1(outerPropTypes, resolvedProps, // Resolved for outer only
6896 'prop', getComponentName(Component), getCurrentFiberStackInDev);
6897 }
6898 }
6899 }
6900 child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
6901 updateExpirationTime, renderExpirationTime);
6902 break;
6903 }
6904 default:
6905 {
6906 var hint = '';
6907 {
6908 if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
6909 hint = ' Did you wrap a component in React.lazy() more than once?';
6910 }
6911 }
6912 // This message intentionally doesn't mention ForwardRef or MemoComponent
6913 // because the fact that it's a separate type of work is an
6914 // implementation detail.
6915 invariant(false, 'Element type is invalid. Received a promise that resolves to: %s. Lazy element type must resolve to a class or function.%s', Component, hint);
6916 }
6917 }
6918 return child;
6919}
6920
6921function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderExpirationTime) {
6922 if (_current !== null) {
6923 // An incomplete component only mounts if it suspended inside a non-
6924 // concurrent tree, in an inconsistent state. We want to treat it like
6925 // a new mount, even though an empty version of it already committed.
6926 // Disconnect the alternate pointers.
6927 _current.alternate = null;
6928 workInProgress.alternate = null;
6929 // Since this is conceptually a new fiber, schedule a Placement effect
6930 workInProgress.effectTag |= Placement;
6931 }
6932
6933 // Promote the fiber to a class and try rendering again.
6934 workInProgress.tag = ClassComponent;
6935
6936 // The rest of this function is a fork of `updateClassComponent`
6937
6938 // Push context providers early to prevent context stack mismatches.
6939 // During mounting we don't know the child context yet as the instance doesn't exist.
6940 // We will invalidate the child context in finishClassComponent() right after rendering.
6941 var hasContext = void 0;
6942 if (isContextProvider(Component)) {
6943 hasContext = true;
6944 pushContextProvider(workInProgress);
6945 } else {
6946 hasContext = false;
6947 }
6948 prepareToReadContext(workInProgress, renderExpirationTime);
6949
6950 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
6951 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
6952
6953 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
6954}
6955
6956function mountIndeterminateComponent(_current, workInProgress, Component, renderExpirationTime) {
6957 if (_current !== null) {
6958 // An indeterminate component only mounts if it suspended inside a non-
6959 // concurrent tree, in an inconsistent state. We want to treat it like
6960 // a new mount, even though an empty version of it already committed.
6961 // Disconnect the alternate pointers.
6962 _current.alternate = null;
6963 workInProgress.alternate = null;
6964 // Since this is conceptually a new fiber, schedule a Placement effect
6965 workInProgress.effectTag |= Placement;
6966 }
6967
6968 var props = workInProgress.pendingProps;
6969 var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
6970 var context = getMaskedContext(workInProgress, unmaskedContext);
6971
6972 prepareToReadContext(workInProgress, renderExpirationTime);
6973
6974 var value = void 0;
6975
6976 {
6977 if (Component.prototype && typeof Component.prototype.render === 'function') {
6978 var componentName = getComponentName(Component) || 'Unknown';
6979
6980 if (!didWarnAboutBadClass[componentName]) {
6981 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);
6982 didWarnAboutBadClass[componentName] = true;
6983 }
6984 }
6985
6986 if (workInProgress.mode & StrictMode) {
6987 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
6988 }
6989
6990 ReactCurrentOwner$2.current = workInProgress;
6991 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
6992 }
6993 // React DevTools reads this flag.
6994 workInProgress.effectTag |= PerformedWork;
6995
6996 if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
6997 // Proceed under the assumption that this is a class instance
6998 workInProgress.tag = ClassComponent;
6999
7000 // Throw out any hooks that were used.
7001 resetHooks();
7002
7003 // Push context providers early to prevent context stack mismatches.
7004 // During mounting we don't know the child context yet as the instance doesn't exist.
7005 // We will invalidate the child context in finishClassComponent() right after rendering.
7006 var hasContext = false;
7007 if (isContextProvider(Component)) {
7008 hasContext = true;
7009 pushContextProvider(workInProgress);
7010 } else {
7011 hasContext = false;
7012 }
7013
7014 workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
7015
7016 var getDerivedStateFromProps = Component.getDerivedStateFromProps;
7017 if (typeof getDerivedStateFromProps === 'function') {
7018 applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);
7019 }
7020
7021 adoptClassInstance(workInProgress, value);
7022 mountClassInstance(workInProgress, Component, props, renderExpirationTime);
7023 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
7024 } else {
7025 // Proceed under the assumption that this is a function component
7026 workInProgress.tag = FunctionComponent;
7027 {
7028 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
7029 // Only double-render components with Hooks
7030 if (workInProgress.memoizedState !== null) {
7031 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
7032 }
7033 }
7034 }
7035 reconcileChildren(null, workInProgress, value, renderExpirationTime);
7036 {
7037 validateFunctionComponentInDev(workInProgress, Component);
7038 }
7039 return workInProgress.child;
7040 }
7041}
7042
7043function validateFunctionComponentInDev(workInProgress, Component) {
7044 if (Component) {
7045 !!Component.childContextTypes ? warningWithoutStack$1(false, '%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component') : void 0;
7046 }
7047 if (workInProgress.ref !== null) {
7048 var info = '';
7049 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
7050 if (ownerName) {
7051 info += '\n\nCheck the render method of `' + ownerName + '`.';
7052 }
7053
7054 var warningKey = ownerName || workInProgress._debugID || '';
7055 var debugSource = workInProgress._debugSource;
7056 if (debugSource) {
7057 warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
7058 }
7059 if (!didWarnAboutFunctionRefs[warningKey]) {
7060 didWarnAboutFunctionRefs[warningKey] = true;
7061 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);
7062 }
7063 }
7064
7065 if (typeof Component.getDerivedStateFromProps === 'function') {
7066 var componentName = getComponentName(Component) || 'Unknown';
7067
7068 if (!didWarnAboutGetDerivedStateOnFunctionComponent[componentName]) {
7069 warningWithoutStack$1(false, '%s: Function components do not support getDerivedStateFromProps.', componentName);
7070 didWarnAboutGetDerivedStateOnFunctionComponent[componentName] = true;
7071 }
7072 }
7073
7074 if (typeof Component.contextType === 'object' && Component.contextType !== null) {
7075 var _componentName = getComponentName(Component) || 'Unknown';
7076
7077 if (!didWarnAboutContextTypeOnFunctionComponent[_componentName]) {
7078 warningWithoutStack$1(false, '%s: Function components do not support contextType.', _componentName);
7079 didWarnAboutContextTypeOnFunctionComponent[_componentName] = true;
7080 }
7081 }
7082}
7083
7084function updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime) {
7085 var mode = workInProgress.mode;
7086 var nextProps = workInProgress.pendingProps;
7087
7088 // We should attempt to render the primary children unless this boundary
7089 // already suspended during this render (`alreadyCaptured` is true).
7090 var nextState = workInProgress.memoizedState;
7091
7092 var nextDidTimeout = void 0;
7093 if ((workInProgress.effectTag & DidCapture) === NoEffect) {
7094 // This is the first attempt.
7095 nextState = null;
7096 nextDidTimeout = false;
7097 } else {
7098 // Something in this boundary's subtree already suspended. Switch to
7099 // rendering the fallback children.
7100 nextState = {
7101 timedOutAt: nextState !== null ? nextState.timedOutAt : NoWork
7102 };
7103 nextDidTimeout = true;
7104 workInProgress.effectTag &= ~DidCapture;
7105 }
7106
7107 // This next part is a bit confusing. If the children timeout, we switch to
7108 // showing the fallback children in place of the "primary" children.
7109 // However, we don't want to delete the primary children because then their
7110 // state will be lost (both the React state and the host state, e.g.
7111 // uncontrolled form inputs). Instead we keep them mounted and hide them.
7112 // Both the fallback children AND the primary children are rendered at the
7113 // same time. Once the primary children are un-suspended, we can delete
7114 // the fallback children — don't need to preserve their state.
7115 //
7116 // The two sets of children are siblings in the host environment, but
7117 // semantically, for purposes of reconciliation, they are two separate sets.
7118 // So we store them using two fragment fibers.
7119 //
7120 // However, we want to avoid allocating extra fibers for every placeholder.
7121 // They're only necessary when the children time out, because that's the
7122 // only time when both sets are mounted.
7123 //
7124 // So, the extra fragment fibers are only used if the children time out.
7125 // Otherwise, we render the primary children directly. This requires some
7126 // custom reconciliation logic to preserve the state of the primary
7127 // children. It's essentially a very basic form of re-parenting.
7128
7129 // `child` points to the child fiber. In the normal case, this is the first
7130 // fiber of the primary children set. In the timed-out case, it's a
7131 // a fragment fiber containing the primary children.
7132 var child = void 0;
7133 // `next` points to the next fiber React should render. In the normal case,
7134 // it's the same as `child`: the first fiber of the primary children set.
7135 // In the timed-out case, it's a fragment fiber containing the *fallback*
7136 // children -- we skip over the primary children entirely.
7137 var next = void 0;
7138 if (current$$1 === null) {
7139 // This is the initial mount. This branch is pretty simple because there's
7140 // no previous state that needs to be preserved.
7141 if (nextDidTimeout) {
7142 // Mount separate fragments for primary and fallback children.
7143 var nextFallbackChildren = nextProps.fallback;
7144 var primaryChildFragment = createFiberFromFragment(null, mode, NoWork, null);
7145
7146 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
7147 // Outside of concurrent mode, we commit the effects from the
7148 var progressedState = workInProgress.memoizedState;
7149 var progressedPrimaryChild = progressedState !== null ? workInProgress.child.child : workInProgress.child;
7150 primaryChildFragment.child = progressedPrimaryChild;
7151 }
7152
7153 var fallbackChildFragment = createFiberFromFragment(nextFallbackChildren, mode, renderExpirationTime, null);
7154 primaryChildFragment.sibling = fallbackChildFragment;
7155 child = primaryChildFragment;
7156 // Skip the primary children, and continue working on the
7157 // fallback children.
7158 next = fallbackChildFragment;
7159 child.return = next.return = workInProgress;
7160 } else {
7161 // Mount the primary children without an intermediate fragment fiber.
7162 var nextPrimaryChildren = nextProps.children;
7163 child = next = mountChildFibers(workInProgress, null, nextPrimaryChildren, renderExpirationTime);
7164 }
7165 } else {
7166 // This is an update. This branch is more complicated because we need to
7167 // ensure the state of the primary children is preserved.
7168 var prevState = current$$1.memoizedState;
7169 var prevDidTimeout = prevState !== null;
7170 if (prevDidTimeout) {
7171 // The current tree already timed out. That means each child set is
7172 var currentPrimaryChildFragment = current$$1.child;
7173 var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
7174 if (nextDidTimeout) {
7175 // Still timed out. Reuse the current primary children by cloning
7176 // its fragment. We're going to skip over these entirely.
7177 var _nextFallbackChildren = nextProps.fallback;
7178 var _primaryChildFragment = createWorkInProgress(currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps, NoWork);
7179
7180 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
7181 // Outside of concurrent mode, we commit the effects from the
7182 var _progressedState = workInProgress.memoizedState;
7183 var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child;
7184 if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) {
7185 _primaryChildFragment.child = _progressedPrimaryChild;
7186 }
7187 }
7188
7189 // Because primaryChildFragment is a new fiber that we're inserting as the
7190 // parent of a new tree, we need to set its treeBaseDuration.
7191 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
7192 // treeBaseDuration is the sum of all the child tree base durations.
7193 var treeBaseDuration = 0;
7194 var hiddenChild = _primaryChildFragment.child;
7195 while (hiddenChild !== null) {
7196 treeBaseDuration += hiddenChild.treeBaseDuration;
7197 hiddenChild = hiddenChild.sibling;
7198 }
7199 _primaryChildFragment.treeBaseDuration = treeBaseDuration;
7200 }
7201
7202 // Clone the fallback child fragment, too. These we'll continue
7203 // working on.
7204 var _fallbackChildFragment = _primaryChildFragment.sibling = createWorkInProgress(currentFallbackChildFragment, _nextFallbackChildren, currentFallbackChildFragment.expirationTime);
7205 child = _primaryChildFragment;
7206 _primaryChildFragment.childExpirationTime = NoWork;
7207 // Skip the primary children, and continue working on the
7208 // fallback children.
7209 next = _fallbackChildFragment;
7210 child.return = next.return = workInProgress;
7211 } else {
7212 // No longer suspended. Switch back to showing the primary children,
7213 // and remove the intermediate fragment fiber.
7214 var _nextPrimaryChildren = nextProps.children;
7215 var currentPrimaryChild = currentPrimaryChildFragment.child;
7216 var primaryChild = reconcileChildFibers(workInProgress, currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime);
7217
7218 // If this render doesn't suspend, we need to delete the fallback
7219 // children. Wait until the complete phase, after we've confirmed the
7220 // fallback is no longer needed.
7221 // TODO: Would it be better to store the fallback fragment on
7222 // the stateNode?
7223
7224 // Continue rendering the children, like we normally do.
7225 child = next = primaryChild;
7226 }
7227 } else {
7228 // The current tree has not already timed out. That means the primary
7229 // children are not wrapped in a fragment fiber.
7230 var _currentPrimaryChild = current$$1.child;
7231 if (nextDidTimeout) {
7232 // Timed out. Wrap the children in a fragment fiber to keep them
7233 // separate from the fallback children.
7234 var _nextFallbackChildren2 = nextProps.fallback;
7235 var _primaryChildFragment2 = createFiberFromFragment(
7236 // It shouldn't matter what the pending props are because we aren't
7237 // going to render this fragment.
7238 null, mode, NoWork, null);
7239 _primaryChildFragment2.child = _currentPrimaryChild;
7240
7241 // Even though we're creating a new fiber, there are no new children,
7242 // because we're reusing an already mounted tree. So we don't need to
7243 // schedule a placement.
7244 // primaryChildFragment.effectTag |= Placement;
7245
7246 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
7247 // Outside of concurrent mode, we commit the effects from the
7248 var _progressedState2 = workInProgress.memoizedState;
7249 var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child;
7250 _primaryChildFragment2.child = _progressedPrimaryChild2;
7251 }
7252
7253 // Because primaryChildFragment is a new fiber that we're inserting as the
7254 // parent of a new tree, we need to set its treeBaseDuration.
7255 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
7256 // treeBaseDuration is the sum of all the child tree base durations.
7257 var _treeBaseDuration = 0;
7258 var _hiddenChild = _primaryChildFragment2.child;
7259 while (_hiddenChild !== null) {
7260 _treeBaseDuration += _hiddenChild.treeBaseDuration;
7261 _hiddenChild = _hiddenChild.sibling;
7262 }
7263 _primaryChildFragment2.treeBaseDuration = _treeBaseDuration;
7264 }
7265
7266 // Create a fragment from the fallback children, too.
7267 var _fallbackChildFragment2 = _primaryChildFragment2.sibling = createFiberFromFragment(_nextFallbackChildren2, mode, renderExpirationTime, null);
7268 _fallbackChildFragment2.effectTag |= Placement;
7269 child = _primaryChildFragment2;
7270 _primaryChildFragment2.childExpirationTime = NoWork;
7271 // Skip the primary children, and continue working on the
7272 // fallback children.
7273 next = _fallbackChildFragment2;
7274 child.return = next.return = workInProgress;
7275 } else {
7276 // Still haven't timed out. Continue rendering the children, like we
7277 // normally do.
7278 var _nextPrimaryChildren2 = nextProps.children;
7279 next = child = reconcileChildFibers(workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime);
7280 }
7281 }
7282 workInProgress.stateNode = current$$1.stateNode;
7283 }
7284
7285 workInProgress.memoizedState = nextState;
7286 workInProgress.child = child;
7287 return next;
7288}
7289
7290function updatePortalComponent(current$$1, workInProgress, renderExpirationTime) {
7291 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
7292 var nextChildren = workInProgress.pendingProps;
7293 if (current$$1 === null) {
7294 // Portals are special because we don't append the children during mount
7295 // but at commit. Therefore we need to track insertions which the normal
7296 // flow doesn't do during mount. This doesn't happen at the root because
7297 // the root always starts with a "current" with a null child.
7298 // TODO: Consider unifying this with how the root works.
7299 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
7300 } else {
7301 reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime);
7302 }
7303 return workInProgress.child;
7304}
7305
7306function updateContextProvider(current$$1, workInProgress, renderExpirationTime) {
7307 var providerType = workInProgress.type;
7308 var context = providerType._context;
7309
7310 var newProps = workInProgress.pendingProps;
7311 var oldProps = workInProgress.memoizedProps;
7312
7313 var newValue = newProps.value;
7314
7315 {
7316 var providerPropTypes = workInProgress.type.propTypes;
7317
7318 if (providerPropTypes) {
7319 checkPropTypes_1(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackInDev);
7320 }
7321 }
7322
7323 pushProvider(workInProgress, newValue);
7324
7325 if (oldProps !== null) {
7326 var oldValue = oldProps.value;
7327 var changedBits = calculateChangedBits(context, newValue, oldValue);
7328 if (changedBits === 0) {
7329 // No change. Bailout early if children are the same.
7330 if (oldProps.children === newProps.children && !hasContextChanged()) {
7331 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
7332 }
7333 } else {
7334 // The context value changed. Search for matching consumers and schedule
7335 // them to update.
7336 propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);
7337 }
7338 }
7339
7340 var newChildren = newProps.children;
7341 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
7342 return workInProgress.child;
7343}
7344
7345var hasWarnedAboutUsingContextAsConsumer = false;
7346
7347function updateContextConsumer(current$$1, workInProgress, renderExpirationTime) {
7348 var context = workInProgress.type;
7349 // The logic below for Context differs depending on PROD or DEV mode. In
7350 // DEV mode, we create a separate object for Context.Consumer that acts
7351 // like a proxy to Context. This proxy object adds unnecessary code in PROD
7352 // so we use the old behaviour (Context.Consumer references Context) to
7353 // reduce size and overhead. The separate object references context via
7354 // a property called "_context", which also gives us the ability to check
7355 // in DEV mode if this property exists or not and warn if it does not.
7356 {
7357 if (context._context === undefined) {
7358 // This may be because it's a Context (rather than a Consumer).
7359 // Or it may be because it's older React where they're the same thing.
7360 // We only want to warn if we're sure it's a new React.
7361 if (context !== context.Consumer) {
7362 if (!hasWarnedAboutUsingContextAsConsumer) {
7363 hasWarnedAboutUsingContextAsConsumer = true;
7364 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?');
7365 }
7366 }
7367 } else {
7368 context = context._context;
7369 }
7370 }
7371 var newProps = workInProgress.pendingProps;
7372 var render = newProps.children;
7373
7374 {
7375 !(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;
7376 }
7377
7378 prepareToReadContext(workInProgress, renderExpirationTime);
7379 var newValue = readContext(context, newProps.unstable_observedBits);
7380 var newChildren = void 0;
7381 {
7382 ReactCurrentOwner$2.current = workInProgress;
7383 setCurrentPhase('render');
7384 newChildren = render(newValue);
7385 setCurrentPhase(null);
7386 }
7387
7388 // React DevTools reads this flag.
7389 workInProgress.effectTag |= PerformedWork;
7390 reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime);
7391 return workInProgress.child;
7392}
7393
7394function markWorkInProgressReceivedUpdate() {
7395 didReceiveUpdate = true;
7396}
7397
7398function bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime) {
7399 cancelWorkTimer(workInProgress);
7400
7401 if (current$$1 !== null) {
7402 // Reuse previous context list
7403 workInProgress.contextDependencies = current$$1.contextDependencies;
7404 }
7405
7406 if (enableProfilerTimer) {
7407 // Don't update "base" render times for bailouts.
7408 stopProfilerTimerIfRunning(workInProgress);
7409 }
7410
7411 // Check if the children have any pending work.
7412 var childExpirationTime = workInProgress.childExpirationTime;
7413 if (childExpirationTime < renderExpirationTime) {
7414 // The children don't have any work either. We can skip them.
7415 // TODO: Once we add back resuming, we should check if the children are
7416 // a work-in-progress set. If so, we need to transfer their effects.
7417 return null;
7418 } else {
7419 // This fiber doesn't have work, but its subtree does. Clone the child
7420 // fibers and continue.
7421 cloneChildFibers(current$$1, workInProgress);
7422 return workInProgress.child;
7423 }
7424}
7425
7426function beginWork(current$$1, workInProgress, renderExpirationTime) {
7427 var updateExpirationTime = workInProgress.expirationTime;
7428
7429 if (current$$1 !== null) {
7430 var oldProps = current$$1.memoizedProps;
7431 var newProps = workInProgress.pendingProps;
7432
7433 if (oldProps !== newProps || hasContextChanged()) {
7434 // If props or context changed, mark the fiber as having performed work.
7435 // This may be unset if the props are determined to be equal later (memo).
7436 didReceiveUpdate = true;
7437 } else if (updateExpirationTime < renderExpirationTime) {
7438 didReceiveUpdate = false;
7439 // This fiber does not have any pending work. Bailout without entering
7440 // the begin phase. There's still some bookkeeping we that needs to be done
7441 // in this optimized path, mostly pushing stuff onto the stack.
7442 switch (workInProgress.tag) {
7443 case HostRoot:
7444 pushHostRootContext(workInProgress);
7445 resetHydrationState();
7446 break;
7447 case HostComponent:
7448 pushHostContext(workInProgress);
7449 break;
7450 case ClassComponent:
7451 {
7452 var Component = workInProgress.type;
7453 if (isContextProvider(Component)) {
7454 pushContextProvider(workInProgress);
7455 }
7456 break;
7457 }
7458 case HostPortal:
7459 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
7460 break;
7461 case ContextProvider:
7462 {
7463 var newValue = workInProgress.memoizedProps.value;
7464 pushProvider(workInProgress, newValue);
7465 break;
7466 }
7467 case Profiler:
7468 if (enableProfilerTimer) {
7469 workInProgress.effectTag |= Update;
7470 }
7471 break;
7472 case SuspenseComponent:
7473 {
7474 var state = workInProgress.memoizedState;
7475 var didTimeout = state !== null;
7476 if (didTimeout) {
7477 // If this boundary is currently timed out, we need to decide
7478 // whether to retry the primary children, or to skip over it and
7479 // go straight to the fallback. Check the priority of the primary
7480 var primaryChildFragment = workInProgress.child;
7481 var primaryChildExpirationTime = primaryChildFragment.childExpirationTime;
7482 if (primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime) {
7483 // The primary children have pending work. Use the normal path
7484 // to attempt to render the primary children again.
7485 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
7486 } else {
7487 // The primary children do not have pending work with sufficient
7488 // priority. Bailout.
7489 var child = bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
7490 if (child !== null) {
7491 // The fallback children have pending work. Skip over the
7492 // primary children and work on the fallback.
7493 return child.sibling;
7494 } else {
7495 return null;
7496 }
7497 }
7498 }
7499 break;
7500 }
7501 }
7502 return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime);
7503 }
7504 } else {
7505 didReceiveUpdate = false;
7506 }
7507
7508 // Before entering the begin phase, clear the expiration time.
7509 workInProgress.expirationTime = NoWork;
7510
7511 switch (workInProgress.tag) {
7512 case IndeterminateComponent:
7513 {
7514 var elementType = workInProgress.elementType;
7515 return mountIndeterminateComponent(current$$1, workInProgress, elementType, renderExpirationTime);
7516 }
7517 case LazyComponent:
7518 {
7519 var _elementType = workInProgress.elementType;
7520 return mountLazyComponent(current$$1, workInProgress, _elementType, updateExpirationTime, renderExpirationTime);
7521 }
7522 case FunctionComponent:
7523 {
7524 var _Component = workInProgress.type;
7525 var unresolvedProps = workInProgress.pendingProps;
7526 var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
7527 return updateFunctionComponent(current$$1, workInProgress, _Component, resolvedProps, renderExpirationTime);
7528 }
7529 case ClassComponent:
7530 {
7531 var _Component2 = workInProgress.type;
7532 var _unresolvedProps = workInProgress.pendingProps;
7533 var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);
7534 return updateClassComponent(current$$1, workInProgress, _Component2, _resolvedProps, renderExpirationTime);
7535 }
7536 case HostRoot:
7537 return updateHostRoot(current$$1, workInProgress, renderExpirationTime);
7538 case HostComponent:
7539 return updateHostComponent(current$$1, workInProgress, renderExpirationTime);
7540 case HostText:
7541 return updateHostText(current$$1, workInProgress);
7542 case SuspenseComponent:
7543 return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime);
7544 case HostPortal:
7545 return updatePortalComponent(current$$1, workInProgress, renderExpirationTime);
7546 case ForwardRef:
7547 {
7548 var type = workInProgress.type;
7549 var _unresolvedProps2 = workInProgress.pendingProps;
7550 var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
7551 return updateForwardRef(current$$1, workInProgress, type, _resolvedProps2, renderExpirationTime);
7552 }
7553 case Fragment:
7554 return updateFragment(current$$1, workInProgress, renderExpirationTime);
7555 case Mode:
7556 return updateMode(current$$1, workInProgress, renderExpirationTime);
7557 case Profiler:
7558 return updateProfiler(current$$1, workInProgress, renderExpirationTime);
7559 case ContextProvider:
7560 return updateContextProvider(current$$1, workInProgress, renderExpirationTime);
7561 case ContextConsumer:
7562 return updateContextConsumer(current$$1, workInProgress, renderExpirationTime);
7563 case MemoComponent:
7564 {
7565 var _type2 = workInProgress.type;
7566 var _unresolvedProps3 = workInProgress.pendingProps;
7567 // Resolve outer props first, then resolve inner props.
7568 var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
7569 {
7570 if (workInProgress.type !== workInProgress.elementType) {
7571 var outerPropTypes = _type2.propTypes;
7572 if (outerPropTypes) {
7573 checkPropTypes_1(outerPropTypes, _resolvedProps3, // Resolved for outer only
7574 'prop', getComponentName(_type2), getCurrentFiberStackInDev);
7575 }
7576 }
7577 }
7578 _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
7579 return updateMemoComponent(current$$1, workInProgress, _type2, _resolvedProps3, updateExpirationTime, renderExpirationTime);
7580 }
7581 case SimpleMemoComponent:
7582 {
7583 return updateSimpleMemoComponent(current$$1, workInProgress, workInProgress.type, workInProgress.pendingProps, updateExpirationTime, renderExpirationTime);
7584 }
7585 case IncompleteClassComponent:
7586 {
7587 var _Component3 = workInProgress.type;
7588 var _unresolvedProps4 = workInProgress.pendingProps;
7589 var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);
7590 return mountIncompleteClassComponent(current$$1, workInProgress, _Component3, _resolvedProps4, renderExpirationTime);
7591 }
7592 default:
7593 invariant(false, 'Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
7594 }
7595}
7596
7597var valueCursor = createCursor(null);
7598
7599var rendererSigil = void 0;
7600{
7601 // Use this to detect multiple renderers using the same context
7602 rendererSigil = {};
7603}
7604
7605var currentlyRenderingFiber = null;
7606var lastContextDependency = null;
7607var lastContextWithAllBitsObserved = null;
7608
7609var isDisallowedContextReadInDEV = false;
7610
7611function resetContextDependences() {
7612 // This is called right before React yields execution, to ensure `readContext`
7613 // cannot be called outside the render phase.
7614 currentlyRenderingFiber = null;
7615 lastContextDependency = null;
7616 lastContextWithAllBitsObserved = null;
7617 {
7618 isDisallowedContextReadInDEV = false;
7619 }
7620}
7621
7622function enterDisallowedContextReadInDEV() {
7623 {
7624 isDisallowedContextReadInDEV = true;
7625 }
7626}
7627
7628function exitDisallowedContextReadInDEV() {
7629 {
7630 isDisallowedContextReadInDEV = false;
7631 }
7632}
7633
7634function pushProvider(providerFiber, nextValue) {
7635 var context = providerFiber.type._context;
7636
7637 if (isPrimaryRenderer) {
7638 push(valueCursor, context._currentValue, providerFiber);
7639
7640 context._currentValue = nextValue;
7641 {
7642 !(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;
7643 context._currentRenderer = rendererSigil;
7644 }
7645 } else {
7646 push(valueCursor, context._currentValue2, providerFiber);
7647
7648 context._currentValue2 = nextValue;
7649 {
7650 !(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;
7651 context._currentRenderer2 = rendererSigil;
7652 }
7653 }
7654}
7655
7656function popProvider(providerFiber) {
7657 var currentValue = valueCursor.current;
7658
7659 pop(valueCursor, providerFiber);
7660
7661 var context = providerFiber.type._context;
7662 if (isPrimaryRenderer) {
7663 context._currentValue = currentValue;
7664 } else {
7665 context._currentValue2 = currentValue;
7666 }
7667}
7668
7669function calculateChangedBits(context, newValue, oldValue) {
7670 if (is(oldValue, newValue)) {
7671 // No change
7672 return 0;
7673 } else {
7674 var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : maxSigned31BitInt;
7675
7676 {
7677 !((changedBits & maxSigned31BitInt) === changedBits) ? warning$1(false, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits) : void 0;
7678 }
7679 return changedBits | 0;
7680 }
7681}
7682
7683function propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) {
7684 var fiber = workInProgress.child;
7685 if (fiber !== null) {
7686 // Set the return pointer of the child to the work-in-progress fiber.
7687 fiber.return = workInProgress;
7688 }
7689 while (fiber !== null) {
7690 var nextFiber = void 0;
7691
7692 // Visit this fiber.
7693 var list = fiber.contextDependencies;
7694 if (list !== null) {
7695 nextFiber = fiber.child;
7696
7697 var dependency = list.first;
7698 while (dependency !== null) {
7699 // Check if the context matches.
7700 if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {
7701 // Match! Schedule an update on this fiber.
7702
7703 if (fiber.tag === ClassComponent) {
7704 // Schedule a force update on the work-in-progress.
7705 var update = createUpdate(renderExpirationTime);
7706 update.tag = ForceUpdate;
7707 // TODO: Because we don't have a work-in-progress, this will add the
7708 // update to the current fiber, too, which means it will persist even if
7709 // this render is thrown away. Since it's a race condition, not sure it's
7710 // worth fixing.
7711 enqueueUpdate(fiber, update);
7712 }
7713
7714 if (fiber.expirationTime < renderExpirationTime) {
7715 fiber.expirationTime = renderExpirationTime;
7716 }
7717 var alternate = fiber.alternate;
7718 if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
7719 alternate.expirationTime = renderExpirationTime;
7720 }
7721 // Update the child expiration time of all the ancestors, including
7722 // the alternates.
7723 var node = fiber.return;
7724 while (node !== null) {
7725 alternate = node.alternate;
7726 if (node.childExpirationTime < renderExpirationTime) {
7727 node.childExpirationTime = renderExpirationTime;
7728 if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
7729 alternate.childExpirationTime = renderExpirationTime;
7730 }
7731 } else if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
7732 alternate.childExpirationTime = renderExpirationTime;
7733 } else {
7734 // Neither alternate was updated, which means the rest of the
7735 // ancestor path already has sufficient priority.
7736 break;
7737 }
7738 node = node.return;
7739 }
7740
7741 // Mark the expiration time on the list, too.
7742 if (list.expirationTime < renderExpirationTime) {
7743 list.expirationTime = renderExpirationTime;
7744 }
7745
7746 // Since we already found a match, we can stop traversing the
7747 // dependency list.
7748 break;
7749 }
7750 dependency = dependency.next;
7751 }
7752 } else if (fiber.tag === ContextProvider) {
7753 // Don't scan deeper if this is a matching provider
7754 nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
7755 } else {
7756 // Traverse down.
7757 nextFiber = fiber.child;
7758 }
7759
7760 if (nextFiber !== null) {
7761 // Set the return pointer of the child to the work-in-progress fiber.
7762 nextFiber.return = fiber;
7763 } else {
7764 // No child. Traverse to next sibling.
7765 nextFiber = fiber;
7766 while (nextFiber !== null) {
7767 if (nextFiber === workInProgress) {
7768 // We're back to the root of this subtree. Exit.
7769 nextFiber = null;
7770 break;
7771 }
7772 var sibling = nextFiber.sibling;
7773 if (sibling !== null) {
7774 // Set the return pointer of the sibling to the work-in-progress fiber.
7775 sibling.return = nextFiber.return;
7776 nextFiber = sibling;
7777 break;
7778 }
7779 // No more siblings. Traverse up.
7780 nextFiber = nextFiber.return;
7781 }
7782 }
7783 fiber = nextFiber;
7784 }
7785}
7786
7787function prepareToReadContext(workInProgress, renderExpirationTime) {
7788 currentlyRenderingFiber = workInProgress;
7789 lastContextDependency = null;
7790 lastContextWithAllBitsObserved = null;
7791
7792 var currentDependencies = workInProgress.contextDependencies;
7793 if (currentDependencies !== null && currentDependencies.expirationTime >= renderExpirationTime) {
7794 // Context list has a pending update. Mark that this fiber performed work.
7795 markWorkInProgressReceivedUpdate();
7796 }
7797
7798 // Reset the work-in-progress list
7799 workInProgress.contextDependencies = null;
7800}
7801
7802function readContext(context, observedBits) {
7803 {
7804 // This warning would fire if you read context inside a Hook like useMemo.
7805 // Unlike the class check below, it's not enforced in production for perf.
7806 !!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;
7807 }
7808
7809 if (lastContextWithAllBitsObserved === context) {
7810 // Nothing to do. We already observe everything in this context.
7811 } else if (observedBits === false || observedBits === 0) {
7812 // Do not observe any updates.
7813 } else {
7814 var resolvedObservedBits = void 0; // Avoid deopting on observable arguments or heterogeneous types.
7815 if (typeof observedBits !== 'number' || observedBits === maxSigned31BitInt) {
7816 // Observe all updates.
7817 lastContextWithAllBitsObserved = context;
7818 resolvedObservedBits = maxSigned31BitInt;
7819 } else {
7820 resolvedObservedBits = observedBits;
7821 }
7822
7823 var contextItem = {
7824 context: context,
7825 observedBits: resolvedObservedBits,
7826 next: null
7827 };
7828
7829 if (lastContextDependency === null) {
7830 !(currentlyRenderingFiber !== null) ? invariant(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;
7831
7832 // This is the first dependency for this component. Create a new list.
7833 lastContextDependency = contextItem;
7834 currentlyRenderingFiber.contextDependencies = {
7835 first: contextItem,
7836 expirationTime: NoWork
7837 };
7838 } else {
7839 // Append a new context item.
7840 lastContextDependency = lastContextDependency.next = contextItem;
7841 }
7842 }
7843 return isPrimaryRenderer ? context._currentValue : context._currentValue2;
7844}
7845
7846// UpdateQueue is a linked list of prioritized updates.
7847//
7848// Like fibers, update queues come in pairs: a current queue, which represents
7849// the visible state of the screen, and a work-in-progress queue, which can be
7850// mutated and processed asynchronously before it is committed — a form of
7851// double buffering. If a work-in-progress render is discarded before finishing,
7852// we create a new work-in-progress by cloning the current queue.
7853//
7854// Both queues share a persistent, singly-linked list structure. To schedule an
7855// update, we append it to the end of both queues. Each queue maintains a
7856// pointer to first update in the persistent list that hasn't been processed.
7857// The work-in-progress pointer always has a position equal to or greater than
7858// the current queue, since we always work on that one. The current queue's
7859// pointer is only updated during the commit phase, when we swap in the
7860// work-in-progress.
7861//
7862// For example:
7863//
7864// Current pointer: A - B - C - D - E - F
7865// Work-in-progress pointer: D - E - F
7866// ^
7867// The work-in-progress queue has
7868// processed more updates than current.
7869//
7870// The reason we append to both queues is because otherwise we might drop
7871// updates without ever processing them. For example, if we only add updates to
7872// the work-in-progress queue, some updates could be lost whenever a work-in
7873// -progress render restarts by cloning from current. Similarly, if we only add
7874// updates to the current queue, the updates will be lost whenever an already
7875// in-progress queue commits and swaps with the current queue. However, by
7876// adding to both queues, we guarantee that the update will be part of the next
7877// work-in-progress. (And because the work-in-progress queue becomes the
7878// current queue once it commits, there's no danger of applying the same
7879// update twice.)
7880//
7881// Prioritization
7882// --------------
7883//
7884// Updates are not sorted by priority, but by insertion; new updates are always
7885// appended to the end of the list.
7886//
7887// The priority is still important, though. When processing the update queue
7888// during the render phase, only the updates with sufficient priority are
7889// included in the result. If we skip an update because it has insufficient
7890// priority, it remains in the queue to be processed later, during a lower
7891// priority render. Crucially, all updates subsequent to a skipped update also
7892// remain in the queue *regardless of their priority*. That means high priority
7893// updates are sometimes processed twice, at two separate priorities. We also
7894// keep track of a base state, that represents the state before the first
7895// update in the queue is applied.
7896//
7897// For example:
7898//
7899// Given a base state of '', and the following queue of updates
7900//
7901// A1 - B2 - C1 - D2
7902//
7903// where the number indicates the priority, and the update is applied to the
7904// previous state by appending a letter, React will process these updates as
7905// two separate renders, one per distinct priority level:
7906//
7907// First render, at priority 1:
7908// Base state: ''
7909// Updates: [A1, C1]
7910// Result state: 'AC'
7911//
7912// Second render, at priority 2:
7913// Base state: 'A' <- The base state does not include C1,
7914// because B2 was skipped.
7915// Updates: [B2, C1, D2] <- C1 was rebased on top of B2
7916// Result state: 'ABCD'
7917//
7918// Because we process updates in insertion order, and rebase high priority
7919// updates when preceding updates are skipped, the final result is deterministic
7920// regardless of priority. Intermediate state may vary according to system
7921// resources, but the final state is always the same.
7922
7923var UpdateState = 0;
7924var ReplaceState = 1;
7925var ForceUpdate = 2;
7926var CaptureUpdate = 3;
7927
7928// Global state that is reset at the beginning of calling `processUpdateQueue`.
7929// It should only be read right after calling `processUpdateQueue`, via
7930// `checkHasForceUpdateAfterProcessing`.
7931var hasForceUpdate = false;
7932
7933var didWarnUpdateInsideUpdate = void 0;
7934var currentlyProcessingQueue = void 0;
7935var resetCurrentlyProcessingQueue = void 0;
7936{
7937 didWarnUpdateInsideUpdate = false;
7938 currentlyProcessingQueue = null;
7939 resetCurrentlyProcessingQueue = function () {
7940 currentlyProcessingQueue = null;
7941 };
7942}
7943
7944function createUpdateQueue(baseState) {
7945 var queue = {
7946 baseState: baseState,
7947 firstUpdate: null,
7948 lastUpdate: null,
7949 firstCapturedUpdate: null,
7950 lastCapturedUpdate: null,
7951 firstEffect: null,
7952 lastEffect: null,
7953 firstCapturedEffect: null,
7954 lastCapturedEffect: null
7955 };
7956 return queue;
7957}
7958
7959function cloneUpdateQueue(currentQueue) {
7960 var queue = {
7961 baseState: currentQueue.baseState,
7962 firstUpdate: currentQueue.firstUpdate,
7963 lastUpdate: currentQueue.lastUpdate,
7964
7965 // TODO: With resuming, if we bail out and resuse the child tree, we should
7966 // keep these effects.
7967 firstCapturedUpdate: null,
7968 lastCapturedUpdate: null,
7969
7970 firstEffect: null,
7971 lastEffect: null,
7972
7973 firstCapturedEffect: null,
7974 lastCapturedEffect: null
7975 };
7976 return queue;
7977}
7978
7979function createUpdate(expirationTime) {
7980 return {
7981 expirationTime: expirationTime,
7982
7983 tag: UpdateState,
7984 payload: null,
7985 callback: null,
7986
7987 next: null,
7988 nextEffect: null
7989 };
7990}
7991
7992function appendUpdateToQueue(queue, update) {
7993 // Append the update to the end of the list.
7994 if (queue.lastUpdate === null) {
7995 // Queue is empty
7996 queue.firstUpdate = queue.lastUpdate = update;
7997 } else {
7998 queue.lastUpdate.next = update;
7999 queue.lastUpdate = update;
8000 }
8001}
8002
8003function enqueueUpdate(fiber, update) {
8004 // Update queues are created lazily.
8005 var alternate = fiber.alternate;
8006 var queue1 = void 0;
8007 var queue2 = void 0;
8008 if (alternate === null) {
8009 // There's only one fiber.
8010 queue1 = fiber.updateQueue;
8011 queue2 = null;
8012 if (queue1 === null) {
8013 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
8014 }
8015 } else {
8016 // There are two owners.
8017 queue1 = fiber.updateQueue;
8018 queue2 = alternate.updateQueue;
8019 if (queue1 === null) {
8020 if (queue2 === null) {
8021 // Neither fiber has an update queue. Create new ones.
8022 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
8023 queue2 = alternate.updateQueue = createUpdateQueue(alternate.memoizedState);
8024 } else {
8025 // Only one fiber has an update queue. Clone to create a new one.
8026 queue1 = fiber.updateQueue = cloneUpdateQueue(queue2);
8027 }
8028 } else {
8029 if (queue2 === null) {
8030 // Only one fiber has an update queue. Clone to create a new one.
8031 queue2 = alternate.updateQueue = cloneUpdateQueue(queue1);
8032 } else {
8033 // Both owners have an update queue.
8034 }
8035 }
8036 }
8037 if (queue2 === null || queue1 === queue2) {
8038 // There's only a single queue.
8039 appendUpdateToQueue(queue1, update);
8040 } else {
8041 // There are two queues. We need to append the update to both queues,
8042 // while accounting for the persistent structure of the list — we don't
8043 // want the same update to be added multiple times.
8044 if (queue1.lastUpdate === null || queue2.lastUpdate === null) {
8045 // One of the queues is not empty. We must add the update to both queues.
8046 appendUpdateToQueue(queue1, update);
8047 appendUpdateToQueue(queue2, update);
8048 } else {
8049 // Both queues are non-empty. The last update is the same in both lists,
8050 // because of structural sharing. So, only append to one of the lists.
8051 appendUpdateToQueue(queue1, update);
8052 // But we still need to update the `lastUpdate` pointer of queue2.
8053 queue2.lastUpdate = update;
8054 }
8055 }
8056
8057 {
8058 if (fiber.tag === ClassComponent && (currentlyProcessingQueue === queue1 || queue2 !== null && currentlyProcessingQueue === queue2) && !didWarnUpdateInsideUpdate) {
8059 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.');
8060 didWarnUpdateInsideUpdate = true;
8061 }
8062 }
8063}
8064
8065function enqueueCapturedUpdate(workInProgress, update) {
8066 // Captured updates go into a separate list, and only on the work-in-
8067 // progress queue.
8068 var workInProgressQueue = workInProgress.updateQueue;
8069 if (workInProgressQueue === null) {
8070 workInProgressQueue = workInProgress.updateQueue = createUpdateQueue(workInProgress.memoizedState);
8071 } else {
8072 // TODO: I put this here rather than createWorkInProgress so that we don't
8073 // clone the queue unnecessarily. There's probably a better way to
8074 // structure this.
8075 workInProgressQueue = ensureWorkInProgressQueueIsAClone(workInProgress, workInProgressQueue);
8076 }
8077
8078 // Append the update to the end of the list.
8079 if (workInProgressQueue.lastCapturedUpdate === null) {
8080 // This is the first render phase update
8081 workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update;
8082 } else {
8083 workInProgressQueue.lastCapturedUpdate.next = update;
8084 workInProgressQueue.lastCapturedUpdate = update;
8085 }
8086}
8087
8088function ensureWorkInProgressQueueIsAClone(workInProgress, queue) {
8089 var current = workInProgress.alternate;
8090 if (current !== null) {
8091 // If the work-in-progress queue is equal to the current queue,
8092 // we need to clone it first.
8093 if (queue === current.updateQueue) {
8094 queue = workInProgress.updateQueue = cloneUpdateQueue(queue);
8095 }
8096 }
8097 return queue;
8098}
8099
8100function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
8101 switch (update.tag) {
8102 case ReplaceState:
8103 {
8104 var _payload = update.payload;
8105 if (typeof _payload === 'function') {
8106 // Updater function
8107 {
8108 enterDisallowedContextReadInDEV();
8109 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
8110 _payload.call(instance, prevState, nextProps);
8111 }
8112 }
8113 var nextState = _payload.call(instance, prevState, nextProps);
8114 {
8115 exitDisallowedContextReadInDEV();
8116 }
8117 return nextState;
8118 }
8119 // State object
8120 return _payload;
8121 }
8122 case CaptureUpdate:
8123 {
8124 workInProgress.effectTag = workInProgress.effectTag & ~ShouldCapture | DidCapture;
8125 }
8126 // Intentional fallthrough
8127 case UpdateState:
8128 {
8129 var _payload2 = update.payload;
8130 var partialState = void 0;
8131 if (typeof _payload2 === 'function') {
8132 // Updater function
8133 {
8134 enterDisallowedContextReadInDEV();
8135 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
8136 _payload2.call(instance, prevState, nextProps);
8137 }
8138 }
8139 partialState = _payload2.call(instance, prevState, nextProps);
8140 {
8141 exitDisallowedContextReadInDEV();
8142 }
8143 } else {
8144 // Partial state object
8145 partialState = _payload2;
8146 }
8147 if (partialState === null || partialState === undefined) {
8148 // Null and undefined are treated as no-ops.
8149 return prevState;
8150 }
8151 // Merge the partial state and the previous state.
8152 return _assign({}, prevState, partialState);
8153 }
8154 case ForceUpdate:
8155 {
8156 hasForceUpdate = true;
8157 return prevState;
8158 }
8159 }
8160 return prevState;
8161}
8162
8163function processUpdateQueue(workInProgress, queue, props, instance, renderExpirationTime) {
8164 hasForceUpdate = false;
8165
8166 queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue);
8167
8168 {
8169 currentlyProcessingQueue = queue;
8170 }
8171
8172 // These values may change as we process the queue.
8173 var newBaseState = queue.baseState;
8174 var newFirstUpdate = null;
8175 var newExpirationTime = NoWork;
8176
8177 // Iterate through the list of updates to compute the result.
8178 var update = queue.firstUpdate;
8179 var resultState = newBaseState;
8180 while (update !== null) {
8181 var updateExpirationTime = update.expirationTime;
8182 if (updateExpirationTime < renderExpirationTime) {
8183 // This update does not have sufficient priority. Skip it.
8184 if (newFirstUpdate === null) {
8185 // This is the first skipped update. It will be the first update in
8186 // the new list.
8187 newFirstUpdate = update;
8188 // Since this is the first update that was skipped, the current result
8189 // is the new base state.
8190 newBaseState = resultState;
8191 }
8192 // Since this update will remain in the list, update the remaining
8193 // expiration time.
8194 if (newExpirationTime < updateExpirationTime) {
8195 newExpirationTime = updateExpirationTime;
8196 }
8197 } else {
8198 // This update does have sufficient priority. Process it and compute
8199 // a new result.
8200 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
8201 var _callback = update.callback;
8202 if (_callback !== null) {
8203 workInProgress.effectTag |= Callback;
8204 // Set this to null, in case it was mutated during an aborted render.
8205 update.nextEffect = null;
8206 if (queue.lastEffect === null) {
8207 queue.firstEffect = queue.lastEffect = update;
8208 } else {
8209 queue.lastEffect.nextEffect = update;
8210 queue.lastEffect = update;
8211 }
8212 }
8213 }
8214 // Continue to the next update.
8215 update = update.next;
8216 }
8217
8218 // Separately, iterate though the list of captured updates.
8219 var newFirstCapturedUpdate = null;
8220 update = queue.firstCapturedUpdate;
8221 while (update !== null) {
8222 var _updateExpirationTime = update.expirationTime;
8223 if (_updateExpirationTime < renderExpirationTime) {
8224 // This update does not have sufficient priority. Skip it.
8225 if (newFirstCapturedUpdate === null) {
8226 // This is the first skipped captured update. It will be the first
8227 // update in the new list.
8228 newFirstCapturedUpdate = update;
8229 // If this is the first update that was skipped, the current result is
8230 // the new base state.
8231 if (newFirstUpdate === null) {
8232 newBaseState = resultState;
8233 }
8234 }
8235 // Since this update will remain in the list, update the remaining
8236 // expiration time.
8237 if (newExpirationTime < _updateExpirationTime) {
8238 newExpirationTime = _updateExpirationTime;
8239 }
8240 } else {
8241 // This update does have sufficient priority. Process it and compute
8242 // a new result.
8243 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
8244 var _callback2 = update.callback;
8245 if (_callback2 !== null) {
8246 workInProgress.effectTag |= Callback;
8247 // Set this to null, in case it was mutated during an aborted render.
8248 update.nextEffect = null;
8249 if (queue.lastCapturedEffect === null) {
8250 queue.firstCapturedEffect = queue.lastCapturedEffect = update;
8251 } else {
8252 queue.lastCapturedEffect.nextEffect = update;
8253 queue.lastCapturedEffect = update;
8254 }
8255 }
8256 }
8257 update = update.next;
8258 }
8259
8260 if (newFirstUpdate === null) {
8261 queue.lastUpdate = null;
8262 }
8263 if (newFirstCapturedUpdate === null) {
8264 queue.lastCapturedUpdate = null;
8265 } else {
8266 workInProgress.effectTag |= Callback;
8267 }
8268 if (newFirstUpdate === null && newFirstCapturedUpdate === null) {
8269 // We processed every update, without skipping. That means the new base
8270 // state is the same as the result state.
8271 newBaseState = resultState;
8272 }
8273
8274 queue.baseState = newBaseState;
8275 queue.firstUpdate = newFirstUpdate;
8276 queue.firstCapturedUpdate = newFirstCapturedUpdate;
8277
8278 // Set the remaining expiration time to be whatever is remaining in the queue.
8279 // This should be fine because the only two other things that contribute to
8280 // expiration time are props and context. We're already in the middle of the
8281 // begin phase by the time we start processing the queue, so we've already
8282 // dealt with the props. Context in components that specify
8283 // shouldComponentUpdate is tricky; but we'll have to account for
8284 // that regardless.
8285 workInProgress.expirationTime = newExpirationTime;
8286 workInProgress.memoizedState = resultState;
8287
8288 {
8289 currentlyProcessingQueue = null;
8290 }
8291}
8292
8293function callCallback(callback, context) {
8294 !(typeof callback === 'function') ? invariant(false, 'Invalid argument passed as callback. Expected a function. Instead received: %s', callback) : void 0;
8295 callback.call(context);
8296}
8297
8298function resetHasForceUpdateBeforeProcessing() {
8299 hasForceUpdate = false;
8300}
8301
8302function checkHasForceUpdateAfterProcessing() {
8303 return hasForceUpdate;
8304}
8305
8306function commitUpdateQueue(finishedWork, finishedQueue, instance, renderExpirationTime) {
8307 // If the finished render included captured updates, and there are still
8308 // lower priority updates left over, we need to keep the captured updates
8309 // in the queue so that they are rebased and not dropped once we process the
8310 // queue again at the lower priority.
8311 if (finishedQueue.firstCapturedUpdate !== null) {
8312 // Join the captured update list to the end of the normal list.
8313 if (finishedQueue.lastUpdate !== null) {
8314 finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate;
8315 finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate;
8316 }
8317 // Clear the list of captured updates.
8318 finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null;
8319 }
8320
8321 // Commit the effects
8322 commitUpdateEffects(finishedQueue.firstEffect, instance);
8323 finishedQueue.firstEffect = finishedQueue.lastEffect = null;
8324
8325 commitUpdateEffects(finishedQueue.firstCapturedEffect, instance);
8326 finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null;
8327}
8328
8329function commitUpdateEffects(effect, instance) {
8330 while (effect !== null) {
8331 var _callback3 = effect.callback;
8332 if (_callback3 !== null) {
8333 effect.callback = null;
8334 callCallback(_callback3, instance);
8335 }
8336 effect = effect.nextEffect;
8337 }
8338}
8339
8340function createCapturedValue(value, source) {
8341 // If the value is an error, call this function immediately after it is thrown
8342 // so the stack is accurate.
8343 return {
8344 value: value,
8345 source: source,
8346 stack: getStackByFiberInDevAndProd(source)
8347 };
8348}
8349
8350function markUpdate(workInProgress) {
8351 // Tag the fiber with an update effect. This turns a Placement into
8352 // a PlacementAndUpdate.
8353 workInProgress.effectTag |= Update;
8354}
8355
8356function markRef$1(workInProgress) {
8357 workInProgress.effectTag |= Ref;
8358}
8359
8360var appendAllChildren = void 0;
8361var updateHostContainer = void 0;
8362var updateHostComponent$1 = void 0;
8363var updateHostText$1 = void 0;
8364if (supportsMutation) {
8365 // Mutation mode
8366
8367 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
8368 // We only have the top Fiber that was created but we need recurse down its
8369 // children to find all the terminal nodes.
8370 var node = workInProgress.child;
8371 while (node !== null) {
8372 if (node.tag === HostComponent || node.tag === HostText) {
8373 appendInitialChild(parent, node.stateNode);
8374 } else if (node.tag === HostPortal) {
8375 // If we have a portal child, then we don't want to traverse
8376 // down its children. Instead, we'll get insertions from each child in
8377 // the portal directly.
8378 } else if (node.child !== null) {
8379 node.child.return = node;
8380 node = node.child;
8381 continue;
8382 }
8383 if (node === workInProgress) {
8384 return;
8385 }
8386 while (node.sibling === null) {
8387 if (node.return === null || node.return === workInProgress) {
8388 return;
8389 }
8390 node = node.return;
8391 }
8392 node.sibling.return = node.return;
8393 node = node.sibling;
8394 }
8395 };
8396
8397 updateHostContainer = function (workInProgress) {
8398 // Noop
8399 };
8400 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
8401 // If we have an alternate, that means this is an update and we need to
8402 // schedule a side-effect to do the updates.
8403 var oldProps = current.memoizedProps;
8404 if (oldProps === newProps) {
8405 // In mutation mode, this is sufficient for a bailout because
8406 // we won't touch this node even if children changed.
8407 return;
8408 }
8409
8410 // If we get updated because one of our children updated, we don't
8411 // have newProps so we'll have to reuse them.
8412 // TODO: Split the update API as separate for the props vs. children.
8413 // Even better would be if children weren't special cased at all tho.
8414 var instance = workInProgress.stateNode;
8415 var currentHostContext = getHostContext();
8416 // TODO: Experiencing an error where oldProps is null. Suggests a host
8417 // component is hitting the resume path. Figure out why. Possibly
8418 // related to `hidden`.
8419 var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
8420 // TODO: Type this specific to this type of component.
8421 workInProgress.updateQueue = updatePayload;
8422 // If the update payload indicates that there is a change or if there
8423 // is a new ref we mark this as an update. All the work is done in commitWork.
8424 if (updatePayload) {
8425 markUpdate(workInProgress);
8426 }
8427 };
8428 updateHostText$1 = function (current, workInProgress, oldText, newText) {
8429 // If the text differs, mark it as an update. All the work in done in commitWork.
8430 if (oldText !== newText) {
8431 markUpdate(workInProgress);
8432 }
8433 };
8434} else if (supportsPersistence) {
8435 // Persistent host tree mode
8436
8437 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
8438 // We only have the top Fiber that was created but we need recurse down its
8439 // children to find all the terminal nodes.
8440 var node = workInProgress.child;
8441 while (node !== null) {
8442 // eslint-disable-next-line no-labels
8443 branches: if (node.tag === HostComponent) {
8444 var instance = node.stateNode;
8445 if (needsVisibilityToggle) {
8446 var props = node.memoizedProps;
8447 var type = node.type;
8448 if (isHidden) {
8449 // This child is inside a timed out tree. Hide it.
8450 instance = cloneHiddenInstance(instance, type, props, node);
8451 } else {
8452 // This child was previously inside a timed out tree. If it was not
8453 // updated during this render, it may need to be unhidden. Clone
8454 // again to be sure.
8455 instance = cloneUnhiddenInstance(instance, type, props, node);
8456 }
8457 node.stateNode = instance;
8458 }
8459 appendInitialChild(parent, instance);
8460 } else if (node.tag === HostText) {
8461 var _instance = node.stateNode;
8462 if (needsVisibilityToggle) {
8463 var text = node.memoizedProps;
8464 var rootContainerInstance = getRootHostContainer();
8465 var currentHostContext = getHostContext();
8466 if (isHidden) {
8467 _instance = createHiddenTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
8468 } else {
8469 _instance = createTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
8470 }
8471 node.stateNode = _instance;
8472 }
8473 appendInitialChild(parent, _instance);
8474 } else if (node.tag === HostPortal) {
8475 // If we have a portal child, then we don't want to traverse
8476 // down its children. Instead, we'll get insertions from each child in
8477 // the portal directly.
8478 } else if (node.tag === SuspenseComponent) {
8479 var current = node.alternate;
8480 if (current !== null) {
8481 var oldState = current.memoizedState;
8482 var newState = node.memoizedState;
8483 var oldIsHidden = oldState !== null;
8484 var newIsHidden = newState !== null;
8485 if (oldIsHidden !== newIsHidden) {
8486 // The placeholder either just timed out or switched back to the normal
8487 // children after having previously timed out. Toggle the visibility of
8488 // the direct host children.
8489 var primaryChildParent = newIsHidden ? node.child : node;
8490 if (primaryChildParent !== null) {
8491 appendAllChildren(parent, primaryChildParent, true, newIsHidden);
8492 }
8493 // eslint-disable-next-line no-labels
8494 break branches;
8495 }
8496 }
8497 if (node.child !== null) {
8498 // Continue traversing like normal
8499 node.child.return = node;
8500 node = node.child;
8501 continue;
8502 }
8503 } else if (node.child !== null) {
8504 node.child.return = node;
8505 node = node.child;
8506 continue;
8507 }
8508 // $FlowFixMe This is correct but Flow is confused by the labeled break.
8509 node = node;
8510 if (node === workInProgress) {
8511 return;
8512 }
8513 while (node.sibling === null) {
8514 if (node.return === null || node.return === workInProgress) {
8515 return;
8516 }
8517 node = node.return;
8518 }
8519 node.sibling.return = node.return;
8520 node = node.sibling;
8521 }
8522 };
8523
8524 // An unfortunate fork of appendAllChildren because we have two different parent types.
8525 var appendAllChildrenToContainer = function (containerChildSet, workInProgress, needsVisibilityToggle, isHidden) {
8526 // We only have the top Fiber that was created but we need recurse down its
8527 // children to find all the terminal nodes.
8528 var node = workInProgress.child;
8529 while (node !== null) {
8530 // eslint-disable-next-line no-labels
8531 branches: if (node.tag === HostComponent) {
8532 var instance = node.stateNode;
8533 if (needsVisibilityToggle) {
8534 var props = node.memoizedProps;
8535 var type = node.type;
8536 if (isHidden) {
8537 // This child is inside a timed out tree. Hide it.
8538 instance = cloneHiddenInstance(instance, type, props, node);
8539 } else {
8540 // This child was previously inside a timed out tree. If it was not
8541 // updated during this render, it may need to be unhidden. Clone
8542 // again to be sure.
8543 instance = cloneUnhiddenInstance(instance, type, props, node);
8544 }
8545 node.stateNode = instance;
8546 }
8547 appendChildToContainerChildSet(containerChildSet, instance);
8548 } else if (node.tag === HostText) {
8549 var _instance2 = node.stateNode;
8550 if (needsVisibilityToggle) {
8551 var text = node.memoizedProps;
8552 var rootContainerInstance = getRootHostContainer();
8553 var currentHostContext = getHostContext();
8554 if (isHidden) {
8555 _instance2 = createHiddenTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
8556 } else {
8557 _instance2 = createTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
8558 }
8559 node.stateNode = _instance2;
8560 }
8561 appendChildToContainerChildSet(containerChildSet, _instance2);
8562 } else if (node.tag === HostPortal) {
8563 // If we have a portal child, then we don't want to traverse
8564 // down its children. Instead, we'll get insertions from each child in
8565 // the portal directly.
8566 } else if (node.tag === SuspenseComponent) {
8567 var current = node.alternate;
8568 if (current !== null) {
8569 var oldState = current.memoizedState;
8570 var newState = node.memoizedState;
8571 var oldIsHidden = oldState !== null;
8572 var newIsHidden = newState !== null;
8573 if (oldIsHidden !== newIsHidden) {
8574 // The placeholder either just timed out or switched back to the normal
8575 // children after having previously timed out. Toggle the visibility of
8576 // the direct host children.
8577 var primaryChildParent = newIsHidden ? node.child : node;
8578 if (primaryChildParent !== null) {
8579 appendAllChildrenToContainer(containerChildSet, primaryChildParent, true, newIsHidden);
8580 }
8581 // eslint-disable-next-line no-labels
8582 break branches;
8583 }
8584 }
8585 if (node.child !== null) {
8586 // Continue traversing like normal
8587 node.child.return = node;
8588 node = node.child;
8589 continue;
8590 }
8591 } else if (node.child !== null) {
8592 node.child.return = node;
8593 node = node.child;
8594 continue;
8595 }
8596 // $FlowFixMe This is correct but Flow is confused by the labeled break.
8597 node = node;
8598 if (node === workInProgress) {
8599 return;
8600 }
8601 while (node.sibling === null) {
8602 if (node.return === null || node.return === workInProgress) {
8603 return;
8604 }
8605 node = node.return;
8606 }
8607 node.sibling.return = node.return;
8608 node = node.sibling;
8609 }
8610 };
8611 updateHostContainer = function (workInProgress) {
8612 var portalOrRoot = workInProgress.stateNode;
8613 var childrenUnchanged = workInProgress.firstEffect === null;
8614 if (childrenUnchanged) {
8615 // No changes, just reuse the existing instance.
8616 } else {
8617 var container = portalOrRoot.containerInfo;
8618 var newChildSet = createContainerChildSet(container);
8619 // If children might have changed, we have to add them all to the set.
8620 appendAllChildrenToContainer(newChildSet, workInProgress, false, false);
8621 portalOrRoot.pendingChildren = newChildSet;
8622 // Schedule an update on the container to swap out the container.
8623 markUpdate(workInProgress);
8624 finalizeContainerChildren(container, newChildSet);
8625 }
8626 };
8627 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
8628 var currentInstance = current.stateNode;
8629 var oldProps = current.memoizedProps;
8630 // If there are no effects associated with this node, then none of our children had any updates.
8631 // This guarantees that we can reuse all of them.
8632 var childrenUnchanged = workInProgress.firstEffect === null;
8633 if (childrenUnchanged && oldProps === newProps) {
8634 // No changes, just reuse the existing instance.
8635 // Note that this might release a previous clone.
8636 workInProgress.stateNode = currentInstance;
8637 return;
8638 }
8639 var recyclableInstance = workInProgress.stateNode;
8640 var currentHostContext = getHostContext();
8641 var updatePayload = null;
8642 if (oldProps !== newProps) {
8643 updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
8644 }
8645 if (childrenUnchanged && updatePayload === null) {
8646 // No changes, just reuse the existing instance.
8647 // Note that this might release a previous clone.
8648 workInProgress.stateNode = currentInstance;
8649 return;
8650 }
8651 var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance);
8652 if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) {
8653 markUpdate(workInProgress);
8654 }
8655 workInProgress.stateNode = newInstance;
8656 if (childrenUnchanged) {
8657 // If there are no other effects in this tree, we need to flag this node as having one.
8658 // Even though we're not going to use it for anything.
8659 // Otherwise parents won't know that there are new children to propagate upwards.
8660 markUpdate(workInProgress);
8661 } else {
8662 // If children might have changed, we have to add them all to the set.
8663 appendAllChildren(newInstance, workInProgress, false, false);
8664 }
8665 };
8666 updateHostText$1 = function (current, workInProgress, oldText, newText) {
8667 if (oldText !== newText) {
8668 // If the text content differs, we'll create a new text instance for it.
8669 var rootContainerInstance = getRootHostContainer();
8670 var currentHostContext = getHostContext();
8671 workInProgress.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress);
8672 // We'll have to mark it as having an effect, even though we won't use the effect for anything.
8673 // This lets the parents know that at least one of their children has changed.
8674 markUpdate(workInProgress);
8675 }
8676 };
8677} else {
8678 // No host operations
8679 updateHostContainer = function (workInProgress) {
8680 // Noop
8681 };
8682 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
8683 // Noop
8684 };
8685 updateHostText$1 = function (current, workInProgress, oldText, newText) {
8686 // Noop
8687 };
8688}
8689
8690function completeWork(current, workInProgress, renderExpirationTime) {
8691 var newProps = workInProgress.pendingProps;
8692
8693 switch (workInProgress.tag) {
8694 case IndeterminateComponent:
8695 break;
8696 case LazyComponent:
8697 break;
8698 case SimpleMemoComponent:
8699 case FunctionComponent:
8700 break;
8701 case ClassComponent:
8702 {
8703 var Component = workInProgress.type;
8704 if (isContextProvider(Component)) {
8705 popContext(workInProgress);
8706 }
8707 break;
8708 }
8709 case HostRoot:
8710 {
8711 popHostContainer(workInProgress);
8712 popTopLevelContextObject(workInProgress);
8713 var fiberRoot = workInProgress.stateNode;
8714 if (fiberRoot.pendingContext) {
8715 fiberRoot.context = fiberRoot.pendingContext;
8716 fiberRoot.pendingContext = null;
8717 }
8718 if (current === null || current.child === null) {
8719 // If we hydrated, pop so that we can delete any remaining children
8720 // that weren't hydrated.
8721 popHydrationState(workInProgress);
8722 // This resets the hacky state to fix isMounted before committing.
8723 // TODO: Delete this when we delete isMounted and findDOMNode.
8724 workInProgress.effectTag &= ~Placement;
8725 }
8726 updateHostContainer(workInProgress);
8727 break;
8728 }
8729 case HostComponent:
8730 {
8731 popHostContext(workInProgress);
8732 var rootContainerInstance = getRootHostContainer();
8733 var type = workInProgress.type;
8734 if (current !== null && workInProgress.stateNode != null) {
8735 updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);
8736
8737 if (current.ref !== workInProgress.ref) {
8738 markRef$1(workInProgress);
8739 }
8740 } else {
8741 if (!newProps) {
8742 !(workInProgress.stateNode !== null) ? invariant(false, 'We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.') : void 0;
8743 // This can happen when we abort work.
8744 break;
8745 }
8746
8747 var currentHostContext = getHostContext();
8748 // TODO: Move createInstance to beginWork and keep it on a context
8749 // "stack" as the parent. Then append children as we go in beginWork
8750 // or completeWork depending on we want to add then top->down or
8751 // bottom->up. Top->down is faster in IE11.
8752 var wasHydrated = popHydrationState(workInProgress);
8753 if (wasHydrated) {
8754 // TODO: Move this and createInstance step into the beginPhase
8755 // to consolidate.
8756 if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
8757 // If changes to the hydrated node needs to be applied at the
8758 // commit-phase we mark this as such.
8759 markUpdate(workInProgress);
8760 }
8761 } else {
8762 var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
8763
8764 appendAllChildren(instance, workInProgress, false, false);
8765
8766 // Certain renderers require commit-time effects for initial mount.
8767 // (eg DOM renderer supports auto-focus for certain elements).
8768 // Make sure such renderers get scheduled for later work.
8769 if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) {
8770 markUpdate(workInProgress);
8771 }
8772 workInProgress.stateNode = instance;
8773 }
8774
8775 if (workInProgress.ref !== null) {
8776 // If there is a ref on a host node we need to schedule a callback
8777 markRef$1(workInProgress);
8778 }
8779 }
8780 break;
8781 }
8782 case HostText:
8783 {
8784 var newText = newProps;
8785 if (current && workInProgress.stateNode != null) {
8786 var oldText = current.memoizedProps;
8787 // If we have an alternate, that means this is an update and we need
8788 // to schedule a side-effect to do the updates.
8789 updateHostText$1(current, workInProgress, oldText, newText);
8790 } else {
8791 if (typeof newText !== 'string') {
8792 !(workInProgress.stateNode !== null) ? invariant(false, 'We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.') : void 0;
8793 // This can happen when we abort work.
8794 }
8795 var _rootContainerInstance = getRootHostContainer();
8796 var _currentHostContext = getHostContext();
8797 var _wasHydrated = popHydrationState(workInProgress);
8798 if (_wasHydrated) {
8799 if (prepareToHydrateHostTextInstance(workInProgress)) {
8800 markUpdate(workInProgress);
8801 }
8802 } else {
8803 workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
8804 }
8805 }
8806 break;
8807 }
8808 case ForwardRef:
8809 break;
8810 case SuspenseComponent:
8811 {
8812 var nextState = workInProgress.memoizedState;
8813 if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
8814 // Something suspended. Re-render with the fallback children.
8815 workInProgress.expirationTime = renderExpirationTime;
8816 // Do not reset the effect list.
8817 return workInProgress;
8818 }
8819
8820 var nextDidTimeout = nextState !== null;
8821 var prevDidTimeout = current !== null && current.memoizedState !== null;
8822
8823 if (current !== null && !nextDidTimeout && prevDidTimeout) {
8824 // We just switched from the fallback to the normal children. Delete
8825 // the fallback.
8826 // TODO: Would it be better to store the fallback fragment on
8827 var currentFallbackChild = current.child.sibling;
8828 if (currentFallbackChild !== null) {
8829 // Deletions go at the beginning of the return fiber's effect list
8830 var first = workInProgress.firstEffect;
8831 if (first !== null) {
8832 workInProgress.firstEffect = currentFallbackChild;
8833 currentFallbackChild.nextEffect = first;
8834 } else {
8835 workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;
8836 currentFallbackChild.nextEffect = null;
8837 }
8838 currentFallbackChild.effectTag = Deletion;
8839 }
8840 }
8841
8842 if (nextDidTimeout || prevDidTimeout) {
8843 // If the children are hidden, or if they were previous hidden, schedule
8844 // an effect to toggle their visibility. This is also used to attach a
8845 // retry listener to the promise.
8846 workInProgress.effectTag |= Update;
8847 }
8848 break;
8849 }
8850 case Fragment:
8851 break;
8852 case Mode:
8853 break;
8854 case Profiler:
8855 break;
8856 case HostPortal:
8857 popHostContainer(workInProgress);
8858 updateHostContainer(workInProgress);
8859 break;
8860 case ContextProvider:
8861 // Pop provider fiber
8862 popProvider(workInProgress);
8863 break;
8864 case ContextConsumer:
8865 break;
8866 case MemoComponent:
8867 break;
8868 case IncompleteClassComponent:
8869 {
8870 // Same as class component case. I put it down here so that the tags are
8871 // sequential to ensure this switch is compiled to a jump table.
8872 var _Component = workInProgress.type;
8873 if (isContextProvider(_Component)) {
8874 popContext(workInProgress);
8875 }
8876 break;
8877 }
8878 default:
8879 invariant(false, 'Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
8880 }
8881
8882 return null;
8883}
8884
8885function shouldCaptureSuspense(workInProgress) {
8886 // In order to capture, the Suspense component must have a fallback prop.
8887 if (workInProgress.memoizedProps.fallback === undefined) {
8888 return false;
8889 }
8890 // If it was the primary children that just suspended, capture and render the
8891 // fallback. Otherwise, don't capture and bubble to the next boundary.
8892 var nextState = workInProgress.memoizedState;
8893 return nextState === null;
8894}
8895
8896// This module is forked in different environments.
8897// By default, return `true` to log errors to the console.
8898// Forks can return `false` if this isn't desirable.
8899function showErrorDialog(capturedError) {
8900 return true;
8901}
8902
8903function logCapturedError(capturedError) {
8904 var logError = showErrorDialog(capturedError);
8905
8906 // Allow injected showErrorDialog() to prevent default console.error logging.
8907 // This enables renderers like ReactNative to better manage redbox behavior.
8908 if (logError === false) {
8909 return;
8910 }
8911
8912 var error = capturedError.error;
8913 {
8914 var componentName = capturedError.componentName,
8915 componentStack = capturedError.componentStack,
8916 errorBoundaryName = capturedError.errorBoundaryName,
8917 errorBoundaryFound = capturedError.errorBoundaryFound,
8918 willRetry = capturedError.willRetry;
8919
8920 // Browsers support silencing uncaught errors by calling
8921 // `preventDefault()` in window `error` handler.
8922 // We record this information as an expando on the error.
8923
8924 if (error != null && error._suppressLogging) {
8925 if (errorBoundaryFound && willRetry) {
8926 // The error is recoverable and was silenced.
8927 // Ignore it and don't print the stack addendum.
8928 // This is handy for testing error boundaries without noise.
8929 return;
8930 }
8931 // The error is fatal. Since the silencing might have
8932 // been accidental, we'll surface it anyway.
8933 // However, the browser would have silenced the original error
8934 // so we'll print it first, and then print the stack addendum.
8935 console.error(error);
8936 // For a more detailed description of this block, see:
8937 // https://github.com/facebook/react/pull/13384
8938 }
8939
8940 var componentNameMessage = componentName ? 'The above error occurred in the <' + componentName + '> component:' : 'The above error occurred in one of your React components:';
8941
8942 var errorBoundaryMessage = void 0;
8943 // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.
8944 if (errorBoundaryFound && errorBoundaryName) {
8945 if (willRetry) {
8946 errorBoundaryMessage = 'React will try to recreate this component tree from scratch ' + ('using the error boundary you provided, ' + errorBoundaryName + '.');
8947 } else {
8948 errorBoundaryMessage = 'This error was initially handled by the error boundary ' + errorBoundaryName + '.\n' + 'Recreating the tree from scratch failed so React will unmount the tree.';
8949 }
8950 } else {
8951 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.';
8952 }
8953 var combinedMessage = '' + componentNameMessage + componentStack + '\n\n' + ('' + errorBoundaryMessage);
8954
8955 // In development, we provide our own message with just the component stack.
8956 // We don't include the original error message and JS stack because the browser
8957 // has already printed it. Even if the application swallows the error, it is still
8958 // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
8959 console.error(combinedMessage);
8960 }
8961}
8962
8963var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
8964{
8965 didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
8966}
8967
8968var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
8969
8970function logError(boundary, errorInfo) {
8971 var source = errorInfo.source;
8972 var stack = errorInfo.stack;
8973 if (stack === null && source !== null) {
8974 stack = getStackByFiberInDevAndProd(source);
8975 }
8976
8977 var capturedError = {
8978 componentName: source !== null ? getComponentName(source.type) : null,
8979 componentStack: stack !== null ? stack : '',
8980 error: errorInfo.value,
8981 errorBoundary: null,
8982 errorBoundaryName: null,
8983 errorBoundaryFound: false,
8984 willRetry: false
8985 };
8986
8987 if (boundary !== null && boundary.tag === ClassComponent) {
8988 capturedError.errorBoundary = boundary.stateNode;
8989 capturedError.errorBoundaryName = getComponentName(boundary.type);
8990 capturedError.errorBoundaryFound = true;
8991 capturedError.willRetry = true;
8992 }
8993
8994 try {
8995 logCapturedError(capturedError);
8996 } catch (e) {
8997 // This method must not throw, or React internal state will get messed up.
8998 // If console.error is overridden, or logCapturedError() shows a dialog that throws,
8999 // we want to report this error outside of the normal stack as a last resort.
9000 // https://github.com/facebook/react/issues/13188
9001 setTimeout(function () {
9002 throw e;
9003 });
9004 }
9005}
9006
9007var callComponentWillUnmountWithTimer = function (current$$1, instance) {
9008 startPhaseTimer(current$$1, 'componentWillUnmount');
9009 instance.props = current$$1.memoizedProps;
9010 instance.state = current$$1.memoizedState;
9011 instance.componentWillUnmount();
9012 stopPhaseTimer();
9013};
9014
9015// Capture errors so they don't interrupt unmounting.
9016function safelyCallComponentWillUnmount(current$$1, instance) {
9017 {
9018 invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current$$1, instance);
9019 if (hasCaughtError()) {
9020 var unmountError = clearCaughtError();
9021 captureCommitPhaseError(current$$1, unmountError);
9022 }
9023 }
9024}
9025
9026function safelyDetachRef(current$$1) {
9027 var ref = current$$1.ref;
9028 if (ref !== null) {
9029 if (typeof ref === 'function') {
9030 {
9031 invokeGuardedCallback(null, ref, null, null);
9032 if (hasCaughtError()) {
9033 var refError = clearCaughtError();
9034 captureCommitPhaseError(current$$1, refError);
9035 }
9036 }
9037 } else {
9038 ref.current = null;
9039 }
9040 }
9041}
9042
9043function safelyCallDestroy(current$$1, destroy) {
9044 {
9045 invokeGuardedCallback(null, destroy, null);
9046 if (hasCaughtError()) {
9047 var error = clearCaughtError();
9048 captureCommitPhaseError(current$$1, error);
9049 }
9050 }
9051}
9052
9053function commitBeforeMutationLifeCycles(current$$1, finishedWork) {
9054 switch (finishedWork.tag) {
9055 case FunctionComponent:
9056 case ForwardRef:
9057 case SimpleMemoComponent:
9058 {
9059 commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork);
9060 return;
9061 }
9062 case ClassComponent:
9063 {
9064 if (finishedWork.effectTag & Snapshot) {
9065 if (current$$1 !== null) {
9066 var prevProps = current$$1.memoizedProps;
9067 var prevState = current$$1.memoizedState;
9068 startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');
9069 var instance = finishedWork.stateNode;
9070 // We could update instance props and state here,
9071 // but instead we rely on them being set during last render.
9072 // TODO: revisit this when we implement resuming.
9073 {
9074 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
9075 !(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;
9076 !(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;
9077 }
9078 }
9079 var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
9080 {
9081 var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
9082 if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
9083 didWarnSet.add(finishedWork.type);
9084 warningWithoutStack$1(false, '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));
9085 }
9086 }
9087 instance.__reactInternalSnapshotBeforeUpdate = snapshot;
9088 stopPhaseTimer();
9089 }
9090 }
9091 return;
9092 }
9093 case HostRoot:
9094 case HostComponent:
9095 case HostText:
9096 case HostPortal:
9097 case IncompleteClassComponent:
9098 // Nothing to do for these component types
9099 return;
9100 default:
9101 {
9102 invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
9103 }
9104 }
9105}
9106
9107function commitHookEffectList(unmountTag, mountTag, finishedWork) {
9108 var updateQueue = finishedWork.updateQueue;
9109 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
9110 if (lastEffect !== null) {
9111 var firstEffect = lastEffect.next;
9112 var effect = firstEffect;
9113 do {
9114 if ((effect.tag & unmountTag) !== NoEffect$1) {
9115 // Unmount
9116 var destroy = effect.destroy;
9117 effect.destroy = undefined;
9118 if (destroy !== undefined) {
9119 destroy();
9120 }
9121 }
9122 if ((effect.tag & mountTag) !== NoEffect$1) {
9123 // Mount
9124 var create = effect.create;
9125 effect.destroy = create();
9126
9127 {
9128 var _destroy = effect.destroy;
9129 if (_destroy !== undefined && typeof _destroy !== 'function') {
9130 var addendum = void 0;
9131 if (_destroy === null) {
9132 addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
9133 } else if (typeof _destroy.then === 'function') {
9134 addendum = '\n\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. ' + 'Instead, you may write an async function separately ' + 'and then call it from inside the effect:\n\n' + 'async function fetchComment(commentId) {\n' + ' // You can await here\n' + '}\n\n' + 'useEffect(() => {\n' + ' fetchComment(commentId);\n' + '}, [commentId]);\n\n' + 'In the future, React will provide a more idiomatic solution for data fetching ' + "that doesn't involve writing effects manually.";
9135 } else {
9136 addendum = ' You returned: ' + _destroy;
9137 }
9138 warningWithoutStack$1(false, 'An Effect function must not return anything besides a function, ' + 'which is used for clean-up.%s%s', addendum, getStackByFiberInDevAndProd(finishedWork));
9139 }
9140 }
9141 }
9142 effect = effect.next;
9143 } while (effect !== firstEffect);
9144 }
9145}
9146
9147function commitPassiveHookEffects(finishedWork) {
9148 commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork);
9149 commitHookEffectList(NoEffect$1, MountPassive, finishedWork);
9150}
9151
9152function commitLifeCycles(finishedRoot, current$$1, finishedWork, committedExpirationTime) {
9153 switch (finishedWork.tag) {
9154 case FunctionComponent:
9155 case ForwardRef:
9156 case SimpleMemoComponent:
9157 {
9158 commitHookEffectList(UnmountLayout, MountLayout, finishedWork);
9159 break;
9160 }
9161 case ClassComponent:
9162 {
9163 var instance = finishedWork.stateNode;
9164 if (finishedWork.effectTag & Update) {
9165 if (current$$1 === null) {
9166 startPhaseTimer(finishedWork, 'componentDidMount');
9167 // We could update instance props and state here,
9168 // but instead we rely on them being set during last render.
9169 // TODO: revisit this when we implement resuming.
9170 {
9171 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
9172 !(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;
9173 !(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;
9174 }
9175 }
9176 instance.componentDidMount();
9177 stopPhaseTimer();
9178 } else {
9179 var prevProps = finishedWork.elementType === finishedWork.type ? current$$1.memoizedProps : resolveDefaultProps(finishedWork.type, current$$1.memoizedProps);
9180 var prevState = current$$1.memoizedState;
9181 startPhaseTimer(finishedWork, 'componentDidUpdate');
9182 // We could update instance props and state here,
9183 // but instead we rely on them being set during last render.
9184 // TODO: revisit this when we implement resuming.
9185 {
9186 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
9187 !(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;
9188 !(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;
9189 }
9190 }
9191 instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
9192 stopPhaseTimer();
9193 }
9194 }
9195 var updateQueue = finishedWork.updateQueue;
9196 if (updateQueue !== null) {
9197 {
9198 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
9199 !(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;
9200 !(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;
9201 }
9202 }
9203 // We could update instance props and state here,
9204 // but instead we rely on them being set during last render.
9205 // TODO: revisit this when we implement resuming.
9206 commitUpdateQueue(finishedWork, updateQueue, instance, committedExpirationTime);
9207 }
9208 return;
9209 }
9210 case HostRoot:
9211 {
9212 var _updateQueue = finishedWork.updateQueue;
9213 if (_updateQueue !== null) {
9214 var _instance = null;
9215 if (finishedWork.child !== null) {
9216 switch (finishedWork.child.tag) {
9217 case HostComponent:
9218 _instance = getPublicInstance(finishedWork.child.stateNode);
9219 break;
9220 case ClassComponent:
9221 _instance = finishedWork.child.stateNode;
9222 break;
9223 }
9224 }
9225 commitUpdateQueue(finishedWork, _updateQueue, _instance, committedExpirationTime);
9226 }
9227 return;
9228 }
9229 case HostComponent:
9230 {
9231 var _instance2 = finishedWork.stateNode;
9232
9233 // Renderers may schedule work to be done after host components are mounted
9234 // (eg DOM renderer may schedule auto-focus for inputs and form controls).
9235 // These effects should only be committed when components are first mounted,
9236 // aka when there is no current/alternate.
9237 if (current$$1 === null && finishedWork.effectTag & Update) {
9238 var type = finishedWork.type;
9239 var props = finishedWork.memoizedProps;
9240
9241 }
9242
9243 return;
9244 }
9245 case HostText:
9246 {
9247 // We have no life-cycles associated with text.
9248 return;
9249 }
9250 case HostPortal:
9251 {
9252 // We have no life-cycles associated with portals.
9253 return;
9254 }
9255 case Profiler:
9256 {
9257 if (enableProfilerTimer) {
9258 var onRender = finishedWork.memoizedProps.onRender;
9259
9260 if (enableSchedulerTracing) {
9261 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime(), finishedRoot.memoizedInteractions);
9262 } else {
9263 onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime());
9264 }
9265 }
9266 return;
9267 }
9268 case SuspenseComponent:
9269 break;
9270 case IncompleteClassComponent:
9271 break;
9272 default:
9273 {
9274 invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
9275 }
9276 }
9277}
9278
9279function hideOrUnhideAllChildren(finishedWork, isHidden) {
9280 if (supportsMutation) {
9281 // We only have the top Fiber that was inserted but we need recurse down its
9282 var node = finishedWork;
9283 while (true) {
9284 if (node.tag === HostComponent) {
9285 var instance = node.stateNode;
9286 if (isHidden) {
9287 hideInstance(instance);
9288 } else {
9289 unhideInstance(node.stateNode, node.memoizedProps);
9290 }
9291 } else if (node.tag === HostText) {
9292 var _instance3 = node.stateNode;
9293 if (isHidden) {
9294 hideTextInstance(_instance3);
9295 } else {
9296 unhideTextInstance(_instance3, node.memoizedProps);
9297 }
9298 } else if (node.tag === SuspenseComponent && node.memoizedState !== null) {
9299 // Found a nested Suspense component that timed out. Skip over the
9300 var fallbackChildFragment = node.child.sibling;
9301 fallbackChildFragment.return = node;
9302 node = fallbackChildFragment;
9303 continue;
9304 } else if (node.child !== null) {
9305 node.child.return = node;
9306 node = node.child;
9307 continue;
9308 }
9309 if (node === finishedWork) {
9310 return;
9311 }
9312 while (node.sibling === null) {
9313 if (node.return === null || node.return === finishedWork) {
9314 return;
9315 }
9316 node = node.return;
9317 }
9318 node.sibling.return = node.return;
9319 node = node.sibling;
9320 }
9321 }
9322}
9323
9324function commitAttachRef(finishedWork) {
9325 var ref = finishedWork.ref;
9326 if (ref !== null) {
9327 var instance = finishedWork.stateNode;
9328 var instanceToUse = void 0;
9329 switch (finishedWork.tag) {
9330 case HostComponent:
9331 instanceToUse = getPublicInstance(instance);
9332 break;
9333 default:
9334 instanceToUse = instance;
9335 }
9336 if (typeof ref === 'function') {
9337 ref(instanceToUse);
9338 } else {
9339 {
9340 if (!ref.hasOwnProperty('current')) {
9341 warningWithoutStack$1(false, 'Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork));
9342 }
9343 }
9344
9345 ref.current = instanceToUse;
9346 }
9347 }
9348}
9349
9350function commitDetachRef(current$$1) {
9351 var currentRef = current$$1.ref;
9352 if (currentRef !== null) {
9353 if (typeof currentRef === 'function') {
9354 currentRef(null);
9355 } else {
9356 currentRef.current = null;
9357 }
9358 }
9359}
9360
9361// User-originating errors (lifecycles and refs) should not interrupt
9362// deletion, so don't let them throw. Host-originating errors should
9363// interrupt deletion, so it's okay
9364function commitUnmount(current$$1) {
9365 onCommitUnmount(current$$1);
9366
9367 switch (current$$1.tag) {
9368 case FunctionComponent:
9369 case ForwardRef:
9370 case MemoComponent:
9371 case SimpleMemoComponent:
9372 {
9373 var updateQueue = current$$1.updateQueue;
9374 if (updateQueue !== null) {
9375 var lastEffect = updateQueue.lastEffect;
9376 if (lastEffect !== null) {
9377 var firstEffect = lastEffect.next;
9378 var effect = firstEffect;
9379 do {
9380 var destroy = effect.destroy;
9381 if (destroy !== undefined) {
9382 safelyCallDestroy(current$$1, destroy);
9383 }
9384 effect = effect.next;
9385 } while (effect !== firstEffect);
9386 }
9387 }
9388 break;
9389 }
9390 case ClassComponent:
9391 {
9392 safelyDetachRef(current$$1);
9393 var instance = current$$1.stateNode;
9394 if (typeof instance.componentWillUnmount === 'function') {
9395 safelyCallComponentWillUnmount(current$$1, instance);
9396 }
9397 return;
9398 }
9399 case HostComponent:
9400 {
9401 safelyDetachRef(current$$1);
9402 return;
9403 }
9404 case HostPortal:
9405 {
9406 // TODO: this is recursive.
9407 // We are also not using this parent because
9408 // the portal will get pushed immediately.
9409 if (supportsMutation) {
9410 unmountHostComponents(current$$1);
9411 } else if (supportsPersistence) {
9412 emptyPortalContainer(current$$1);
9413 }
9414 return;
9415 }
9416 }
9417}
9418
9419function commitNestedUnmounts(root) {
9420 // While we're inside a removed host node we don't want to call
9421 // removeChild on the inner nodes because they're removed by the top
9422 // call anyway. We also want to call componentWillUnmount on all
9423 // composites before this host node is removed from the tree. Therefore
9424 var node = root;
9425 while (true) {
9426 commitUnmount(node);
9427 // Visit children because they may contain more composite or host nodes.
9428 // Skip portals because commitUnmount() currently visits them recursively.
9429 if (node.child !== null && (
9430 // If we use mutation we drill down into portals using commitUnmount above.
9431 // If we don't use mutation we drill down into portals here instead.
9432 !supportsMutation || node.tag !== HostPortal)) {
9433 node.child.return = node;
9434 node = node.child;
9435 continue;
9436 }
9437 if (node === root) {
9438 return;
9439 }
9440 while (node.sibling === null) {
9441 if (node.return === null || node.return === root) {
9442 return;
9443 }
9444 node = node.return;
9445 }
9446 node.sibling.return = node.return;
9447 node = node.sibling;
9448 }
9449}
9450
9451function detachFiber(current$$1) {
9452 // Cut off the return pointers to disconnect it from the tree. Ideally, we
9453 // should clear the child pointer of the parent alternate to let this
9454 // get GC:ed but we don't know which for sure which parent is the current
9455 // one so we'll settle for GC:ing the subtree of this child. This child
9456 // itself will be GC:ed when the parent updates the next time.
9457 current$$1.return = null;
9458 current$$1.child = null;
9459 current$$1.memoizedState = null;
9460 current$$1.updateQueue = null;
9461 var alternate = current$$1.alternate;
9462 if (alternate !== null) {
9463 alternate.return = null;
9464 alternate.child = null;
9465 alternate.memoizedState = null;
9466 alternate.updateQueue = null;
9467 }
9468}
9469
9470function emptyPortalContainer(current$$1) {
9471 if (!supportsPersistence) {
9472 return;
9473 }
9474
9475 var portal = current$$1.stateNode;
9476 var containerInfo = portal.containerInfo;
9477
9478 var emptyChildSet = createContainerChildSet(containerInfo);
9479 replaceContainerChildren(containerInfo, emptyChildSet);
9480}
9481
9482function commitContainer(finishedWork) {
9483 if (!supportsPersistence) {
9484 return;
9485 }
9486
9487 switch (finishedWork.tag) {
9488 case ClassComponent:
9489 {
9490 return;
9491 }
9492 case HostComponent:
9493 {
9494 return;
9495 }
9496 case HostText:
9497 {
9498 return;
9499 }
9500 case HostRoot:
9501 case HostPortal:
9502 {
9503 var portalOrRoot = finishedWork.stateNode;
9504 var containerInfo = portalOrRoot.containerInfo,
9505 _pendingChildren = portalOrRoot.pendingChildren;
9506
9507 replaceContainerChildren(containerInfo, _pendingChildren);
9508 return;
9509 }
9510 default:
9511 {
9512 invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
9513 }
9514 }
9515}
9516
9517function getHostParentFiber(fiber) {
9518 var parent = fiber.return;
9519 while (parent !== null) {
9520 if (isHostParent(parent)) {
9521 return parent;
9522 }
9523 parent = parent.return;
9524 }
9525 invariant(false, 'Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.');
9526}
9527
9528function isHostParent(fiber) {
9529 return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
9530}
9531
9532function getHostSibling(fiber) {
9533 // We're going to search forward into the tree until we find a sibling host
9534 // node. Unfortunately, if multiple insertions are done in a row we have to
9535 // search past them. This leads to exponential search for the next sibling.
9536 var node = fiber;
9537 siblings: while (true) {
9538 // If we didn't find anything, let's try the next sibling.
9539 while (node.sibling === null) {
9540 if (node.return === null || isHostParent(node.return)) {
9541 // If we pop out of the root or hit the parent the fiber we are the
9542 // last sibling.
9543 return null;
9544 }
9545 node = node.return;
9546 }
9547 node.sibling.return = node.return;
9548 node = node.sibling;
9549 while (node.tag !== HostComponent && node.tag !== HostText) {
9550 // If it is not host node and, we might have a host node inside it.
9551 // Try to search down until we find one.
9552 if (node.effectTag & Placement) {
9553 // If we don't have a child, try the siblings instead.
9554 continue siblings;
9555 }
9556 // If we don't have a child, try the siblings instead.
9557 // We also skip portals because they are not part of this host tree.
9558 if (node.child === null || node.tag === HostPortal) {
9559 continue siblings;
9560 } else {
9561 node.child.return = node;
9562 node = node.child;
9563 }
9564 }
9565 // Check if this host node is stable or about to be placed.
9566 if (!(node.effectTag & Placement)) {
9567 // Found it!
9568 return node.stateNode;
9569 }
9570 }
9571}
9572
9573function commitPlacement(finishedWork) {
9574 if (!supportsMutation) {
9575 return;
9576 }
9577
9578 // Recursively insert all host nodes into the parent.
9579 var parentFiber = getHostParentFiber(finishedWork);
9580
9581 // Note: these two variables *must* always be updated together.
9582 var parent = void 0;
9583 var isContainer = void 0;
9584
9585 switch (parentFiber.tag) {
9586 case HostComponent:
9587 parent = parentFiber.stateNode;
9588 isContainer = false;
9589 break;
9590 case HostRoot:
9591 parent = parentFiber.stateNode.containerInfo;
9592 isContainer = true;
9593 break;
9594 case HostPortal:
9595 parent = parentFiber.stateNode.containerInfo;
9596 isContainer = true;
9597 break;
9598 default:
9599 invariant(false, 'Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.');
9600 }
9601 if (parentFiber.effectTag & ContentReset) {
9602 // Reset the text content of the parent before doing any insertions
9603 parentFiber.effectTag &= ~ContentReset;
9604 }
9605
9606 var before = getHostSibling(finishedWork);
9607 // We only have the top Fiber that was inserted but we need recurse down its
9608 // children to find all the terminal nodes.
9609 var node = finishedWork;
9610 while (true) {
9611 if (node.tag === HostComponent || node.tag === HostText) {
9612 if (before) {
9613 if (isContainer) {
9614 insertInContainerBefore(parent, node.stateNode, before);
9615 } else {
9616 insertBefore(parent, node.stateNode, before);
9617 }
9618 } else {
9619 if (isContainer) {
9620 appendChildToContainer(parent, node.stateNode);
9621 } else {
9622 appendChild(parent, node.stateNode);
9623 }
9624 }
9625 } else if (node.tag === HostPortal) {
9626 // If the insertion itself is a portal, then we don't want to traverse
9627 // down its children. Instead, we'll get insertions from each child in
9628 // the portal directly.
9629 } else if (node.child !== null) {
9630 node.child.return = node;
9631 node = node.child;
9632 continue;
9633 }
9634 if (node === finishedWork) {
9635 return;
9636 }
9637 while (node.sibling === null) {
9638 if (node.return === null || node.return === finishedWork) {
9639 return;
9640 }
9641 node = node.return;
9642 }
9643 node.sibling.return = node.return;
9644 node = node.sibling;
9645 }
9646}
9647
9648function unmountHostComponents(current$$1) {
9649 // We only have the top Fiber that was deleted but we need recurse down its
9650 var node = current$$1;
9651
9652 // Each iteration, currentParent is populated with node's host parent if not
9653 // currentParentIsValid.
9654 var currentParentIsValid = false;
9655
9656 // Note: these two variables *must* always be updated together.
9657 var currentParent = void 0;
9658 var currentParentIsContainer = void 0;
9659
9660 while (true) {
9661 if (!currentParentIsValid) {
9662 var parent = node.return;
9663 findParent: while (true) {
9664 !(parent !== null) ? invariant(false, 'Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.') : void 0;
9665 switch (parent.tag) {
9666 case HostComponent:
9667 currentParent = parent.stateNode;
9668 currentParentIsContainer = false;
9669 break findParent;
9670 case HostRoot:
9671 currentParent = parent.stateNode.containerInfo;
9672 currentParentIsContainer = true;
9673 break findParent;
9674 case HostPortal:
9675 currentParent = parent.stateNode.containerInfo;
9676 currentParentIsContainer = true;
9677 break findParent;
9678 }
9679 parent = parent.return;
9680 }
9681 currentParentIsValid = true;
9682 }
9683
9684 if (node.tag === HostComponent || node.tag === HostText) {
9685 commitNestedUnmounts(node);
9686 // After all the children have unmounted, it is now safe to remove the
9687 // node from the tree.
9688 if (currentParentIsContainer) {
9689 removeChildFromContainer(currentParent, node.stateNode);
9690 } else {
9691 removeChild(currentParent, node.stateNode);
9692 }
9693 // Don't visit children because we already visited them.
9694 } else if (node.tag === HostPortal) {
9695 // When we go into a portal, it becomes the parent to remove from.
9696 // We will reassign it back when we pop the portal on the way up.
9697 currentParent = node.stateNode.containerInfo;
9698 currentParentIsContainer = true;
9699 // Visit children because portals might contain host components.
9700 if (node.child !== null) {
9701 node.child.return = node;
9702 node = node.child;
9703 continue;
9704 }
9705 } else {
9706 commitUnmount(node);
9707 // Visit children because we may find more host components below.
9708 if (node.child !== null) {
9709 node.child.return = node;
9710 node = node.child;
9711 continue;
9712 }
9713 }
9714 if (node === current$$1) {
9715 return;
9716 }
9717 while (node.sibling === null) {
9718 if (node.return === null || node.return === current$$1) {
9719 return;
9720 }
9721 node = node.return;
9722 if (node.tag === HostPortal) {
9723 // When we go out of the portal, we need to restore the parent.
9724 // Since we don't keep a stack of them, we will search for it.
9725 currentParentIsValid = false;
9726 }
9727 }
9728 node.sibling.return = node.return;
9729 node = node.sibling;
9730 }
9731}
9732
9733function commitDeletion(current$$1) {
9734 if (supportsMutation) {
9735 // Recursively delete all host nodes from the parent.
9736 // Detach refs and call componentWillUnmount() on the whole subtree.
9737 unmountHostComponents(current$$1);
9738 } else {
9739 // Detach refs and call componentWillUnmount() on the whole subtree.
9740 commitNestedUnmounts(current$$1);
9741 }
9742 detachFiber(current$$1);
9743}
9744
9745function commitWork(current$$1, finishedWork) {
9746 if (!supportsMutation) {
9747 switch (finishedWork.tag) {
9748 case FunctionComponent:
9749 case ForwardRef:
9750 case MemoComponent:
9751 case SimpleMemoComponent:
9752 {
9753 // Note: We currently never use MountMutation, but useLayout uses
9754 // UnmountMutation.
9755 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
9756 return;
9757 }
9758 }
9759
9760 commitContainer(finishedWork);
9761 return;
9762 }
9763
9764 switch (finishedWork.tag) {
9765 case FunctionComponent:
9766 case ForwardRef:
9767 case MemoComponent:
9768 case SimpleMemoComponent:
9769 {
9770 // Note: We currently never use MountMutation, but useLayout uses
9771 // UnmountMutation.
9772 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
9773 return;
9774 }
9775 case ClassComponent:
9776 {
9777 return;
9778 }
9779 case HostComponent:
9780 {
9781 var instance = finishedWork.stateNode;
9782 if (instance != null) {
9783 // Commit the work prepared earlier.
9784 var newProps = finishedWork.memoizedProps;
9785 // For hydration we reuse the update path but we treat the oldProps
9786 // as the newProps. The updatePayload will contain the real change in
9787 // this case.
9788 var oldProps = current$$1 !== null ? current$$1.memoizedProps : newProps;
9789 var type = finishedWork.type;
9790 // TODO: Type the updateQueue to be specific to host components.
9791 var updatePayload = finishedWork.updateQueue;
9792 finishedWork.updateQueue = null;
9793 if (updatePayload !== null) {
9794 commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork);
9795 }
9796 }
9797 return;
9798 }
9799 case HostText:
9800 {
9801 !(finishedWork.stateNode !== null) ? invariant(false, 'This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.') : void 0;
9802 var textInstance = finishedWork.stateNode;
9803 var newText = finishedWork.memoizedProps;
9804 // For hydration we reuse the update path but we treat the oldProps
9805 // as the newProps. The updatePayload will contain the real change in
9806 // this case.
9807 var oldText = current$$1 !== null ? current$$1.memoizedProps : newText;
9808 commitTextUpdate(textInstance, oldText, newText);
9809 return;
9810 }
9811 case HostRoot:
9812 {
9813 return;
9814 }
9815 case Profiler:
9816 {
9817 return;
9818 }
9819 case SuspenseComponent:
9820 {
9821 var newState = finishedWork.memoizedState;
9822
9823 var newDidTimeout = void 0;
9824 var primaryChildParent = finishedWork;
9825 if (newState === null) {
9826 newDidTimeout = false;
9827 } else {
9828 newDidTimeout = true;
9829 primaryChildParent = finishedWork.child;
9830 if (newState.timedOutAt === NoWork) {
9831 // If the children had not already timed out, record the time.
9832 // This is used to compute the elapsed time during subsequent
9833 // attempts to render the children.
9834 newState.timedOutAt = requestCurrentTime();
9835 }
9836 }
9837
9838 if (primaryChildParent !== null) {
9839 hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);
9840 }
9841
9842 // If this boundary just timed out, then it will have a set of thenables.
9843 // For each thenable, attach a listener so that when it resolves, React
9844 // attempts to re-render the boundary in the primary (pre-timeout) state.
9845 var thenables = finishedWork.updateQueue;
9846 if (thenables !== null) {
9847 finishedWork.updateQueue = null;
9848 var retryCache = finishedWork.stateNode;
9849 if (retryCache === null) {
9850 retryCache = finishedWork.stateNode = new PossiblyWeakSet();
9851 }
9852 thenables.forEach(function (thenable) {
9853 // Memoize using the boundary fiber to prevent redundant listeners.
9854 var retry = retryTimedOutBoundary.bind(null, finishedWork, thenable);
9855 if (enableSchedulerTracing) {
9856 retry = unstable_wrap(retry);
9857 }
9858 if (!retryCache.has(thenable)) {
9859 retryCache.add(thenable);
9860 thenable.then(retry, retry);
9861 }
9862 });
9863 }
9864
9865 return;
9866 }
9867 case IncompleteClassComponent:
9868 {
9869 return;
9870 }
9871 default:
9872 {
9873 invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
9874 }
9875 }
9876}
9877
9878function commitResetTextContent(current$$1) {
9879 if (!supportsMutation) {
9880 return;
9881 }
9882 resetTextContent(current$$1.stateNode);
9883}
9884
9885var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
9886
9887function createRootErrorUpdate(fiber, errorInfo, expirationTime) {
9888 var update = createUpdate(expirationTime);
9889 // Unmount the root by rendering null.
9890 update.tag = CaptureUpdate;
9891 // Caution: React DevTools currently depends on this property
9892 // being called "element".
9893 update.payload = { element: null };
9894 var error = errorInfo.value;
9895 update.callback = function () {
9896 onUncaughtError(error);
9897 logError(fiber, errorInfo);
9898 };
9899 return update;
9900}
9901
9902function createClassErrorUpdate(fiber, errorInfo, expirationTime) {
9903 var update = createUpdate(expirationTime);
9904 update.tag = CaptureUpdate;
9905 var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
9906 if (typeof getDerivedStateFromError === 'function') {
9907 var error = errorInfo.value;
9908 update.payload = function () {
9909 return getDerivedStateFromError(error);
9910 };
9911 }
9912
9913 var inst = fiber.stateNode;
9914 if (inst !== null && typeof inst.componentDidCatch === 'function') {
9915 update.callback = function callback() {
9916 if (typeof getDerivedStateFromError !== 'function') {
9917 // To preserve the preexisting retry behavior of error boundaries,
9918 // we keep track of which ones already failed during this batch.
9919 // This gets reset before we yield back to the browser.
9920 // TODO: Warn in strict mode if getDerivedStateFromError is
9921 // not defined.
9922 markLegacyErrorBoundaryAsFailed(this);
9923 }
9924 var error = errorInfo.value;
9925 var stack = errorInfo.stack;
9926 logError(fiber, errorInfo);
9927 this.componentDidCatch(error, {
9928 componentStack: stack !== null ? stack : ''
9929 });
9930 {
9931 if (typeof getDerivedStateFromError !== 'function') {
9932 // If componentDidCatch is the only error boundary method defined,
9933 // then it needs to call setState to recover from errors.
9934 // If no state update is scheduled then the boundary will swallow the error.
9935 !(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;
9936 }
9937 }
9938 };
9939 }
9940 return update;
9941}
9942
9943function throwException(root, returnFiber, sourceFiber, value, renderExpirationTime) {
9944 // The source fiber did not complete.
9945 sourceFiber.effectTag |= Incomplete;
9946 // Its effect list is no longer valid.
9947 sourceFiber.firstEffect = sourceFiber.lastEffect = null;
9948
9949 if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
9950 // This is a thenable.
9951 var thenable = value;
9952
9953 // Find the earliest timeout threshold of all the placeholders in the
9954 // ancestor path. We could avoid this traversal by storing the thresholds on
9955 // the stack, but we choose not to because we only hit this path if we're
9956 // IO-bound (i.e. if something suspends). Whereas the stack is used even in
9957 // the non-IO- bound case.
9958 var _workInProgress = returnFiber;
9959 var earliestTimeoutMs = -1;
9960 var startTimeMs = -1;
9961 do {
9962 if (_workInProgress.tag === SuspenseComponent) {
9963 var current$$1 = _workInProgress.alternate;
9964 if (current$$1 !== null) {
9965 var currentState = current$$1.memoizedState;
9966 if (currentState !== null) {
9967 // Reached a boundary that already timed out. Do not search
9968 // any further.
9969 var timedOutAt = currentState.timedOutAt;
9970 startTimeMs = expirationTimeToMs(timedOutAt);
9971 // Do not search any further.
9972 break;
9973 }
9974 }
9975 var timeoutPropMs = _workInProgress.pendingProps.maxDuration;
9976 if (typeof timeoutPropMs === 'number') {
9977 if (timeoutPropMs <= 0) {
9978 earliestTimeoutMs = 0;
9979 } else if (earliestTimeoutMs === -1 || timeoutPropMs < earliestTimeoutMs) {
9980 earliestTimeoutMs = timeoutPropMs;
9981 }
9982 }
9983 }
9984 _workInProgress = _workInProgress.return;
9985 } while (_workInProgress !== null);
9986
9987 // Schedule the nearest Suspense to re-render the timed out view.
9988 _workInProgress = returnFiber;
9989 do {
9990 if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress)) {
9991 // Found the nearest boundary.
9992
9993 // Stash the promise on the boundary fiber. If the boundary times out, we'll
9994 var thenables = _workInProgress.updateQueue;
9995 if (thenables === null) {
9996 var updateQueue = new Set();
9997 updateQueue.add(thenable);
9998 _workInProgress.updateQueue = updateQueue;
9999 } else {
10000 thenables.add(thenable);
10001 }
10002
10003 // If the boundary is outside of concurrent mode, we should *not*
10004 // suspend the commit. Pretend as if the suspended component rendered
10005 // null and keep rendering. In the commit phase, we'll schedule a
10006 // subsequent synchronous update to re-render the Suspense.
10007 //
10008 // Note: It doesn't matter whether the component that suspended was
10009 // inside a concurrent mode tree. If the Suspense is outside of it, we
10010 // should *not* suspend the commit.
10011 if ((_workInProgress.mode & ConcurrentMode) === NoEffect) {
10012 _workInProgress.effectTag |= DidCapture;
10013
10014 // We're going to commit this fiber even though it didn't complete.
10015 // But we shouldn't call any lifecycle methods or callbacks. Remove
10016 // all lifecycle effect tags.
10017 sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete);
10018
10019 if (sourceFiber.tag === ClassComponent) {
10020 var currentSourceFiber = sourceFiber.alternate;
10021 if (currentSourceFiber === null) {
10022 // This is a new mount. Change the tag so it's not mistaken for a
10023 // completed class component. For example, we should not call
10024 // componentWillUnmount if it is deleted.
10025 sourceFiber.tag = IncompleteClassComponent;
10026 } else {
10027 // When we try rendering again, we should not reuse the current fiber,
10028 // since it's known to be in an inconsistent state. Use a force updte to
10029 // prevent a bail out.
10030 var update = createUpdate(Sync);
10031 update.tag = ForceUpdate;
10032 enqueueUpdate(sourceFiber, update);
10033 }
10034 }
10035
10036 // The source fiber did not complete. Mark it with Sync priority to
10037 // indicate that it still has pending work.
10038 sourceFiber.expirationTime = Sync;
10039
10040 // Exit without suspending.
10041 return;
10042 }
10043
10044 // Confirmed that the boundary is in a concurrent mode tree. Continue
10045 // with the normal suspend path.
10046
10047 // Attach a listener to the promise to "ping" the root and retry. But
10048 // only if one does not already exist for the current render expiration
10049 // time (which acts like a "thread ID" here).
10050 var pingCache = root.pingCache;
10051 var threadIDs = void 0;
10052 if (pingCache === null) {
10053 pingCache = root.pingCache = new PossiblyWeakMap();
10054 threadIDs = new Set();
10055 pingCache.set(thenable, threadIDs);
10056 } else {
10057 threadIDs = pingCache.get(thenable);
10058 if (threadIDs === undefined) {
10059 threadIDs = new Set();
10060 pingCache.set(thenable, threadIDs);
10061 }
10062 }
10063 if (!threadIDs.has(renderExpirationTime)) {
10064 // Memoize using the thread ID to prevent redundant listeners.
10065 threadIDs.add(renderExpirationTime);
10066 var ping = pingSuspendedRoot.bind(null, root, thenable, renderExpirationTime);
10067 if (enableSchedulerTracing) {
10068 ping = unstable_wrap(ping);
10069 }
10070 thenable.then(ping, ping);
10071 }
10072
10073 var absoluteTimeoutMs = void 0;
10074 if (earliestTimeoutMs === -1) {
10075 // If no explicit threshold is given, default to an arbitrarily large
10076 // value. The actual size doesn't matter because the threshold for the
10077 // whole tree will be clamped to the expiration time.
10078 absoluteTimeoutMs = maxSigned31BitInt;
10079 } else {
10080 if (startTimeMs === -1) {
10081 // This suspend happened outside of any already timed-out
10082 // placeholders. We don't know exactly when the update was
10083 // scheduled, but we can infer an approximate start time from the
10084 // expiration time. First, find the earliest uncommitted expiration
10085 // time in the tree, including work that is suspended. Then subtract
10086 // the offset used to compute an async update's expiration time.
10087 // This will cause high priority (interactive) work to expire
10088 // earlier than necessary, but we can account for this by adjusting
10089 // for the Just Noticeable Difference.
10090 var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, renderExpirationTime);
10091 var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime);
10092 startTimeMs = earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;
10093 }
10094 absoluteTimeoutMs = startTimeMs + earliestTimeoutMs;
10095 }
10096
10097 // Mark the earliest timeout in the suspended fiber's ancestor path.
10098 // After completing the root, we'll take the largest of all the
10099 // suspended fiber's timeouts and use it to compute a timeout for the
10100 // whole tree.
10101 renderDidSuspend(root, absoluteTimeoutMs, renderExpirationTime);
10102
10103 _workInProgress.effectTag |= ShouldCapture;
10104 _workInProgress.expirationTime = renderExpirationTime;
10105 return;
10106 }
10107 // This boundary already captured during this render. Continue to the next
10108 // boundary.
10109 _workInProgress = _workInProgress.return;
10110 } while (_workInProgress !== null);
10111 // No boundary was found. Fallthrough to error mode.
10112 // TODO: Use invariant so the message is stripped in prod?
10113 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));
10114 }
10115
10116 // We didn't find a boundary that could handle this type of exception. Start
10117 // over and traverse parent path again, this time treating the exception
10118 // as an error.
10119 renderDidError();
10120 value = createCapturedValue(value, sourceFiber);
10121 var workInProgress = returnFiber;
10122 do {
10123 switch (workInProgress.tag) {
10124 case HostRoot:
10125 {
10126 var _errorInfo = value;
10127 workInProgress.effectTag |= ShouldCapture;
10128 workInProgress.expirationTime = renderExpirationTime;
10129 var _update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime);
10130 enqueueCapturedUpdate(workInProgress, _update);
10131 return;
10132 }
10133 case ClassComponent:
10134 // Capture and retry
10135 var errorInfo = value;
10136 var ctor = workInProgress.type;
10137 var instance = workInProgress.stateNode;
10138 if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
10139 workInProgress.effectTag |= ShouldCapture;
10140 workInProgress.expirationTime = renderExpirationTime;
10141 // Schedule the error boundary to re-render using updated state
10142 var _update2 = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime);
10143 enqueueCapturedUpdate(workInProgress, _update2);
10144 return;
10145 }
10146 break;
10147 default:
10148 break;
10149 }
10150 workInProgress = workInProgress.return;
10151 } while (workInProgress !== null);
10152}
10153
10154function unwindWork(workInProgress, renderExpirationTime) {
10155 switch (workInProgress.tag) {
10156 case ClassComponent:
10157 {
10158 var Component = workInProgress.type;
10159 if (isContextProvider(Component)) {
10160 popContext(workInProgress);
10161 }
10162 var effectTag = workInProgress.effectTag;
10163 if (effectTag & ShouldCapture) {
10164 workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture;
10165 return workInProgress;
10166 }
10167 return null;
10168 }
10169 case HostRoot:
10170 {
10171 popHostContainer(workInProgress);
10172 popTopLevelContextObject(workInProgress);
10173 var _effectTag = workInProgress.effectTag;
10174 !((_effectTag & DidCapture) === NoEffect) ? invariant(false, 'The root failed to unmount after an error. This is likely a bug in React. Please file an issue.') : void 0;
10175 workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture;
10176 return workInProgress;
10177 }
10178 case HostComponent:
10179 {
10180 popHostContext(workInProgress);
10181 return null;
10182 }
10183 case SuspenseComponent:
10184 {
10185 var _effectTag2 = workInProgress.effectTag;
10186 if (_effectTag2 & ShouldCapture) {
10187 workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture;
10188 // Captured a suspense effect. Re-render the boundary.
10189 return workInProgress;
10190 }
10191 return null;
10192 }
10193 case HostPortal:
10194 popHostContainer(workInProgress);
10195 return null;
10196 case ContextProvider:
10197 popProvider(workInProgress);
10198 return null;
10199 default:
10200 return null;
10201 }
10202}
10203
10204function unwindInterruptedWork(interruptedWork) {
10205 switch (interruptedWork.tag) {
10206 case ClassComponent:
10207 {
10208 var childContextTypes = interruptedWork.type.childContextTypes;
10209 if (childContextTypes !== null && childContextTypes !== undefined) {
10210 popContext(interruptedWork);
10211 }
10212 break;
10213 }
10214 case HostRoot:
10215 {
10216 popHostContainer(interruptedWork);
10217 popTopLevelContextObject(interruptedWork);
10218 break;
10219 }
10220 case HostComponent:
10221 {
10222 popHostContext(interruptedWork);
10223 break;
10224 }
10225 case HostPortal:
10226 popHostContainer(interruptedWork);
10227 break;
10228 case ContextProvider:
10229 popProvider(interruptedWork);
10230 break;
10231 default:
10232 break;
10233 }
10234}
10235
10236var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
10237var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
10238
10239
10240var didWarnAboutStateTransition = void 0;
10241var didWarnSetStateChildContext = void 0;
10242var warnAboutUpdateOnUnmounted = void 0;
10243var warnAboutInvalidUpdates = void 0;
10244
10245if (enableSchedulerTracing) {
10246 // Provide explicit error message when production+profiling bundle of e.g. react-dom
10247 // is used with production (non-profiling) bundle of scheduler/tracing
10248 !(__interactionsRef != null && __interactionsRef.current != null) ? invariant(false, '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') : void 0;
10249}
10250
10251{
10252 didWarnAboutStateTransition = false;
10253 didWarnSetStateChildContext = false;
10254 var didWarnStateUpdateForUnmountedComponent = {};
10255
10256 warnAboutUpdateOnUnmounted = function (fiber, isClass) {
10257 // We show the whole stack but dedupe on the top component's name because
10258 // the problematic code almost always lies inside that component.
10259 var componentName = getComponentName(fiber.type) || 'ReactComponent';
10260 if (didWarnStateUpdateForUnmountedComponent[componentName]) {
10261 return;
10262 }
10263 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));
10264 didWarnStateUpdateForUnmountedComponent[componentName] = true;
10265 };
10266
10267 warnAboutInvalidUpdates = function (instance) {
10268 switch (phase) {
10269 case 'getChildContext':
10270 if (didWarnSetStateChildContext) {
10271 return;
10272 }
10273 warningWithoutStack$1(false, 'setState(...): Cannot call setState() inside getChildContext()');
10274 didWarnSetStateChildContext = true;
10275 break;
10276 case 'render':
10277 if (didWarnAboutStateTransition) {
10278 return;
10279 }
10280 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.');
10281 didWarnAboutStateTransition = true;
10282 break;
10283 }
10284 };
10285}
10286
10287// Represents the expiration time that incoming updates should use. (If this
10288// is NoWork, use the default strategy: async updates in async mode, sync
10289// updates in sync mode.)
10290var expirationContext = NoWork;
10291
10292var isWorking = false;
10293
10294// The next work in progress fiber that we're currently working on.
10295var nextUnitOfWork = null;
10296var nextRoot = null;
10297// The time at which we're currently rendering work.
10298var nextRenderExpirationTime = NoWork;
10299var nextLatestAbsoluteTimeoutMs = -1;
10300var nextRenderDidError = false;
10301
10302// The next fiber with an effect that we're currently committing.
10303var nextEffect = null;
10304
10305var isCommitting$1 = false;
10306var rootWithPendingPassiveEffects = null;
10307var passiveEffectCallbackHandle = null;
10308var passiveEffectCallback = null;
10309
10310var legacyErrorBoundariesThatAlreadyFailed = null;
10311
10312// Used for performance tracking.
10313var interruptedBy = null;
10314
10315var stashedWorkInProgressProperties = void 0;
10316var replayUnitOfWork = void 0;
10317var mayReplayFailedUnitOfWork = void 0;
10318var isReplayingFailedUnitOfWork = void 0;
10319var originalReplayError = void 0;
10320var rethrowOriginalError = void 0;
10321if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
10322 stashedWorkInProgressProperties = null;
10323 mayReplayFailedUnitOfWork = true;
10324 isReplayingFailedUnitOfWork = false;
10325 originalReplayError = null;
10326 replayUnitOfWork = function (failedUnitOfWork, thrownValue, isYieldy) {
10327 if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') {
10328 // Don't replay promises. Treat everything else like an error.
10329 // TODO: Need to figure out a different strategy if/when we add
10330 // support for catching other types.
10331 return;
10332 }
10333
10334 // Restore the original state of the work-in-progress
10335 if (stashedWorkInProgressProperties === null) {
10336 // This should never happen. Don't throw because this code is DEV-only.
10337 warningWithoutStack$1(false, 'Could not replay rendering after an error. This is likely a bug in React. ' + 'Please file an issue.');
10338 return;
10339 }
10340 assignFiberPropertiesInDEV(failedUnitOfWork, stashedWorkInProgressProperties);
10341
10342 switch (failedUnitOfWork.tag) {
10343 case HostRoot:
10344 popHostContainer(failedUnitOfWork);
10345 popTopLevelContextObject(failedUnitOfWork);
10346 break;
10347 case HostComponent:
10348 popHostContext(failedUnitOfWork);
10349 break;
10350 case ClassComponent:
10351 {
10352 var Component = failedUnitOfWork.type;
10353 if (isContextProvider(Component)) {
10354 popContext(failedUnitOfWork);
10355 }
10356 break;
10357 }
10358 case HostPortal:
10359 popHostContainer(failedUnitOfWork);
10360 break;
10361 case ContextProvider:
10362 popProvider(failedUnitOfWork);
10363 break;
10364 }
10365 // Replay the begin phase.
10366 isReplayingFailedUnitOfWork = true;
10367 originalReplayError = thrownValue;
10368 invokeGuardedCallback(null, workLoop, null, isYieldy);
10369 isReplayingFailedUnitOfWork = false;
10370 originalReplayError = null;
10371 if (hasCaughtError()) {
10372 var replayError = clearCaughtError();
10373 if (replayError != null && thrownValue != null) {
10374 try {
10375 // Reading the expando property is intentionally
10376 // inside `try` because it might be a getter or Proxy.
10377 if (replayError._suppressLogging) {
10378 // Also suppress logging for the original error.
10379 thrownValue._suppressLogging = true;
10380 }
10381 } catch (inner) {
10382 // Ignore.
10383 }
10384 }
10385 } else {
10386 // If the begin phase did not fail the second time, set this pointer
10387 // back to the original value.
10388 nextUnitOfWork = failedUnitOfWork;
10389 }
10390 };
10391 rethrowOriginalError = function () {
10392 throw originalReplayError;
10393 };
10394}
10395
10396function resetStack() {
10397 if (nextUnitOfWork !== null) {
10398 var interruptedWork = nextUnitOfWork.return;
10399 while (interruptedWork !== null) {
10400 unwindInterruptedWork(interruptedWork);
10401 interruptedWork = interruptedWork.return;
10402 }
10403 }
10404
10405 {
10406 ReactStrictModeWarnings.discardPendingWarnings();
10407 checkThatStackIsEmpty();
10408 }
10409
10410 nextRoot = null;
10411 nextRenderExpirationTime = NoWork;
10412 nextLatestAbsoluteTimeoutMs = -1;
10413 nextRenderDidError = false;
10414 nextUnitOfWork = null;
10415}
10416
10417function commitAllHostEffects() {
10418 while (nextEffect !== null) {
10419 {
10420 setCurrentFiber(nextEffect);
10421 }
10422 recordEffect();
10423
10424 var effectTag = nextEffect.effectTag;
10425
10426 if (effectTag & ContentReset) {
10427 commitResetTextContent(nextEffect);
10428 }
10429
10430 if (effectTag & Ref) {
10431 var current$$1 = nextEffect.alternate;
10432 if (current$$1 !== null) {
10433 commitDetachRef(current$$1);
10434 }
10435 }
10436
10437 // The following switch statement is only concerned about placement,
10438 // updates, and deletions. To avoid needing to add a case for every
10439 // possible bitmap value, we remove the secondary effects from the
10440 // effect tag and switch on that value.
10441 var primaryEffectTag = effectTag & (Placement | Update | Deletion);
10442 switch (primaryEffectTag) {
10443 case Placement:
10444 {
10445 commitPlacement(nextEffect);
10446 // Clear the "placement" from effect tag so that we know that this is inserted, before
10447 // any life-cycles like componentDidMount gets called.
10448 // TODO: findDOMNode doesn't rely on this any more but isMounted
10449 // does and isMounted is deprecated anyway so we should be able
10450 // to kill this.
10451 nextEffect.effectTag &= ~Placement;
10452 break;
10453 }
10454 case PlacementAndUpdate:
10455 {
10456 // Placement
10457 commitPlacement(nextEffect);
10458 // Clear the "placement" from effect tag so that we know that this is inserted, before
10459 // any life-cycles like componentDidMount gets called.
10460 nextEffect.effectTag &= ~Placement;
10461
10462 // Update
10463 var _current = nextEffect.alternate;
10464 commitWork(_current, nextEffect);
10465 break;
10466 }
10467 case Update:
10468 {
10469 var _current2 = nextEffect.alternate;
10470 commitWork(_current2, nextEffect);
10471 break;
10472 }
10473 case Deletion:
10474 {
10475 commitDeletion(nextEffect);
10476 break;
10477 }
10478 }
10479 nextEffect = nextEffect.nextEffect;
10480 }
10481
10482 {
10483 resetCurrentFiber();
10484 }
10485}
10486
10487function commitBeforeMutationLifecycles() {
10488 while (nextEffect !== null) {
10489 {
10490 setCurrentFiber(nextEffect);
10491 }
10492
10493 var effectTag = nextEffect.effectTag;
10494 if (effectTag & Snapshot) {
10495 recordEffect();
10496 var current$$1 = nextEffect.alternate;
10497 commitBeforeMutationLifeCycles(current$$1, nextEffect);
10498 }
10499
10500 nextEffect = nextEffect.nextEffect;
10501 }
10502
10503 {
10504 resetCurrentFiber();
10505 }
10506}
10507
10508function commitAllLifeCycles(finishedRoot, committedExpirationTime) {
10509 {
10510 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
10511 ReactStrictModeWarnings.flushLegacyContextWarning();
10512
10513 if (warnAboutDeprecatedLifecycles) {
10514 ReactStrictModeWarnings.flushPendingDeprecationWarnings();
10515 }
10516 }
10517 while (nextEffect !== null) {
10518 {
10519 setCurrentFiber(nextEffect);
10520 }
10521 var effectTag = nextEffect.effectTag;
10522
10523 if (effectTag & (Update | Callback)) {
10524 recordEffect();
10525 var current$$1 = nextEffect.alternate;
10526 commitLifeCycles(finishedRoot, current$$1, nextEffect, committedExpirationTime);
10527 }
10528
10529 if (effectTag & Ref) {
10530 recordEffect();
10531 commitAttachRef(nextEffect);
10532 }
10533
10534 if (effectTag & Passive) {
10535 rootWithPendingPassiveEffects = finishedRoot;
10536 }
10537
10538 nextEffect = nextEffect.nextEffect;
10539 }
10540 {
10541 resetCurrentFiber();
10542 }
10543}
10544
10545function commitPassiveEffects(root, firstEffect) {
10546 rootWithPendingPassiveEffects = null;
10547 passiveEffectCallbackHandle = null;
10548 passiveEffectCallback = null;
10549
10550 // Set this to true to prevent re-entrancy
10551 var previousIsRendering = isRendering;
10552 isRendering = true;
10553
10554 var effect = firstEffect;
10555 do {
10556 {
10557 setCurrentFiber(effect);
10558 }
10559
10560 if (effect.effectTag & Passive) {
10561 var didError = false;
10562 var error = void 0;
10563 {
10564 invokeGuardedCallback(null, commitPassiveHookEffects, null, effect);
10565 if (hasCaughtError()) {
10566 didError = true;
10567 error = clearCaughtError();
10568 }
10569 }
10570 if (didError) {
10571 captureCommitPhaseError(effect, error);
10572 }
10573 }
10574 effect = effect.nextEffect;
10575 } while (effect !== null);
10576 {
10577 resetCurrentFiber();
10578 }
10579
10580 isRendering = previousIsRendering;
10581
10582 // Check if work was scheduled by one of the effects
10583 var rootExpirationTime = root.expirationTime;
10584 if (rootExpirationTime !== NoWork) {
10585 requestWork(root, rootExpirationTime);
10586 }
10587}
10588
10589function isAlreadyFailedLegacyErrorBoundary(instance) {
10590 return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
10591}
10592
10593function markLegacyErrorBoundaryAsFailed(instance) {
10594 if (legacyErrorBoundariesThatAlreadyFailed === null) {
10595 legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
10596 } else {
10597 legacyErrorBoundariesThatAlreadyFailed.add(instance);
10598 }
10599}
10600
10601function flushPassiveEffects$1() {
10602 if (passiveEffectCallbackHandle !== null) {
10603 cancelPassiveEffects(passiveEffectCallbackHandle);
10604 }
10605 if (passiveEffectCallback !== null) {
10606 // We call the scheduled callback instead of commitPassiveEffects directly
10607 // to ensure tracing works correctly.
10608 passiveEffectCallback();
10609 }
10610}
10611
10612function commitRoot(root, finishedWork) {
10613 isWorking = true;
10614 isCommitting$1 = true;
10615 startCommitTimer();
10616
10617 !(root.current !== finishedWork) ? invariant(false, '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.') : void 0;
10618 var committedExpirationTime = root.pendingCommitExpirationTime;
10619 !(committedExpirationTime !== NoWork) ? invariant(false, 'Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue.') : void 0;
10620 root.pendingCommitExpirationTime = NoWork;
10621
10622 // Update the pending priority levels to account for the work that we are
10623 // about to commit. This needs to happen before calling the lifecycles, since
10624 // they may schedule additional updates.
10625 var updateExpirationTimeBeforeCommit = finishedWork.expirationTime;
10626 var childExpirationTimeBeforeCommit = finishedWork.childExpirationTime;
10627 var earliestRemainingTimeBeforeCommit = childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit ? childExpirationTimeBeforeCommit : updateExpirationTimeBeforeCommit;
10628 markCommittedPriorityLevels(root, earliestRemainingTimeBeforeCommit);
10629
10630 var prevInteractions = null;
10631 if (enableSchedulerTracing) {
10632 // Restore any pending interactions at this point,
10633 // So that cascading work triggered during the render phase will be accounted for.
10634 prevInteractions = __interactionsRef.current;
10635 __interactionsRef.current = root.memoizedInteractions;
10636 }
10637
10638 // Reset this to null before calling lifecycles
10639 ReactCurrentOwner$1.current = null;
10640
10641 var firstEffect = void 0;
10642 if (finishedWork.effectTag > PerformedWork) {
10643 // A fiber's effect list consists only of its children, not itself. So if
10644 // the root has an effect, we need to add it to the end of the list. The
10645 // resulting list is the set that would belong to the root's parent, if
10646 // it had one; that is, all the effects in the tree including the root.
10647 if (finishedWork.lastEffect !== null) {
10648 finishedWork.lastEffect.nextEffect = finishedWork;
10649 firstEffect = finishedWork.firstEffect;
10650 } else {
10651 firstEffect = finishedWork;
10652 }
10653 } else {
10654 // There is no effect on the root.
10655 firstEffect = finishedWork.firstEffect;
10656 }
10657
10658 prepareForCommit(root.containerInfo);
10659
10660 // Invoke instances of getSnapshotBeforeUpdate before mutation.
10661 nextEffect = firstEffect;
10662 startCommitSnapshotEffectsTimer();
10663 while (nextEffect !== null) {
10664 var didError = false;
10665 var error = void 0;
10666 {
10667 invokeGuardedCallback(null, commitBeforeMutationLifecycles, null);
10668 if (hasCaughtError()) {
10669 didError = true;
10670 error = clearCaughtError();
10671 }
10672 }
10673 if (didError) {
10674 !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
10675 captureCommitPhaseError(nextEffect, error);
10676 // Clean-up
10677 if (nextEffect !== null) {
10678 nextEffect = nextEffect.nextEffect;
10679 }
10680 }
10681 }
10682 stopCommitSnapshotEffectsTimer();
10683
10684 if (enableProfilerTimer) {
10685 // Mark the current commit time to be shared by all Profilers in this batch.
10686 // This enables them to be grouped later.
10687 recordCommitTime();
10688 }
10689
10690 // Commit all the side-effects within a tree. We'll do this in two passes.
10691 // The first pass performs all the host insertions, updates, deletions and
10692 // ref unmounts.
10693 nextEffect = firstEffect;
10694 startCommitHostEffectsTimer();
10695 while (nextEffect !== null) {
10696 var _didError = false;
10697 var _error = void 0;
10698 {
10699 invokeGuardedCallback(null, commitAllHostEffects, null);
10700 if (hasCaughtError()) {
10701 _didError = true;
10702 _error = clearCaughtError();
10703 }
10704 }
10705 if (_didError) {
10706 !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
10707 captureCommitPhaseError(nextEffect, _error);
10708 // Clean-up
10709 if (nextEffect !== null) {
10710 nextEffect = nextEffect.nextEffect;
10711 }
10712 }
10713 }
10714 stopCommitHostEffectsTimer();
10715
10716 resetAfterCommit(root.containerInfo);
10717
10718 // The work-in-progress tree is now the current tree. This must come after
10719 // the first pass of the commit phase, so that the previous tree is still
10720 // current during componentWillUnmount, but before the second pass, so that
10721 // the finished work is current during componentDidMount/Update.
10722 root.current = finishedWork;
10723
10724 // In the second pass we'll perform all life-cycles and ref callbacks.
10725 // Life-cycles happen as a separate pass so that all placements, updates,
10726 // and deletions in the entire tree have already been invoked.
10727 // This pass also triggers any renderer-specific initial effects.
10728 nextEffect = firstEffect;
10729 startCommitLifeCyclesTimer();
10730 while (nextEffect !== null) {
10731 var _didError2 = false;
10732 var _error2 = void 0;
10733 {
10734 invokeGuardedCallback(null, commitAllLifeCycles, null, root, committedExpirationTime);
10735 if (hasCaughtError()) {
10736 _didError2 = true;
10737 _error2 = clearCaughtError();
10738 }
10739 }
10740 if (_didError2) {
10741 !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
10742 captureCommitPhaseError(nextEffect, _error2);
10743 if (nextEffect !== null) {
10744 nextEffect = nextEffect.nextEffect;
10745 }
10746 }
10747 }
10748
10749 if (firstEffect !== null && rootWithPendingPassiveEffects !== null) {
10750 // This commit included a passive effect. These do not need to fire until
10751 // after the next paint. Schedule an callback to fire them in an async
10752 // event. To ensure serial execution, the callback will be flushed early if
10753 // we enter rootWithPendingPassiveEffects commit phase before then.
10754 var callback = commitPassiveEffects.bind(null, root, firstEffect);
10755 if (enableSchedulerTracing) {
10756 // TODO: Avoid this extra callback by mutating the tracing ref directly,
10757 // like we do at the beginning of commitRoot. I've opted not to do that
10758 // here because that code is still in flux.
10759 callback = unstable_wrap(callback);
10760 }
10761 passiveEffectCallbackHandle = schedulePassiveEffects(callback);
10762 passiveEffectCallback = callback;
10763 }
10764
10765 isCommitting$1 = false;
10766 isWorking = false;
10767 stopCommitLifeCyclesTimer();
10768 stopCommitTimer();
10769 onCommitRoot(finishedWork.stateNode);
10770 if (true && ReactFiberInstrumentation_1.debugTool) {
10771 ReactFiberInstrumentation_1.debugTool.onCommitWork(finishedWork);
10772 }
10773
10774 var updateExpirationTimeAfterCommit = finishedWork.expirationTime;
10775 var childExpirationTimeAfterCommit = finishedWork.childExpirationTime;
10776 var earliestRemainingTimeAfterCommit = childExpirationTimeAfterCommit > updateExpirationTimeAfterCommit ? childExpirationTimeAfterCommit : updateExpirationTimeAfterCommit;
10777 if (earliestRemainingTimeAfterCommit === NoWork) {
10778 // If there's no remaining work, we can clear the set of already failed
10779 // error boundaries.
10780 legacyErrorBoundariesThatAlreadyFailed = null;
10781 }
10782 onCommit(root, earliestRemainingTimeAfterCommit);
10783
10784 if (enableSchedulerTracing) {
10785 __interactionsRef.current = prevInteractions;
10786
10787 var subscriber = void 0;
10788
10789 try {
10790 subscriber = __subscriberRef.current;
10791 if (subscriber !== null && root.memoizedInteractions.size > 0) {
10792 var threadID = computeThreadID(committedExpirationTime, root.interactionThreadID);
10793 subscriber.onWorkStopped(root.memoizedInteractions, threadID);
10794 }
10795 } catch (error) {
10796 // It's not safe for commitRoot() to throw.
10797 // Store the error for now and we'll re-throw in finishRendering().
10798 if (!hasUnhandledError) {
10799 hasUnhandledError = true;
10800 unhandledError = error;
10801 }
10802 } finally {
10803 // Clear completed interactions from the pending Map.
10804 // Unless the render was suspended or cascading work was scheduled,
10805 // In which case– leave pending interactions until the subsequent render.
10806 var pendingInteractionMap = root.pendingInteractionMap;
10807 pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
10808 // Only decrement the pending interaction count if we're done.
10809 // If there's still work at the current priority,
10810 // That indicates that we are waiting for suspense data.
10811 if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {
10812 pendingInteractionMap.delete(scheduledExpirationTime);
10813
10814 scheduledInteractions.forEach(function (interaction) {
10815 interaction.__count--;
10816
10817 if (subscriber !== null && interaction.__count === 0) {
10818 try {
10819 subscriber.onInteractionScheduledWorkCompleted(interaction);
10820 } catch (error) {
10821 // It's not safe for commitRoot() to throw.
10822 // Store the error for now and we'll re-throw in finishRendering().
10823 if (!hasUnhandledError) {
10824 hasUnhandledError = true;
10825 unhandledError = error;
10826 }
10827 }
10828 }
10829 });
10830 }
10831 });
10832 }
10833 }
10834}
10835
10836function resetChildExpirationTime(workInProgress, renderTime) {
10837 if (renderTime !== Never && workInProgress.childExpirationTime === Never) {
10838 // The children of this component are hidden. Don't bubble their
10839 // expiration times.
10840 return;
10841 }
10842
10843 var newChildExpirationTime = NoWork;
10844
10845 // Bubble up the earliest expiration time.
10846 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
10847 // We're in profiling mode.
10848 // Let's use this same traversal to update the render durations.
10849 var actualDuration = workInProgress.actualDuration;
10850 var treeBaseDuration = workInProgress.selfBaseDuration;
10851
10852 // When a fiber is cloned, its actualDuration is reset to 0.
10853 // This value will only be updated if work is done on the fiber (i.e. it doesn't bailout).
10854 // When work is done, it should bubble to the parent's actualDuration.
10855 // If the fiber has not been cloned though, (meaning no work was done),
10856 // Then this value will reflect the amount of time spent working on a previous render.
10857 // In that case it should not bubble.
10858 // We determine whether it was cloned by comparing the child pointer.
10859 var shouldBubbleActualDurations = workInProgress.alternate === null || workInProgress.child !== workInProgress.alternate.child;
10860
10861 var child = workInProgress.child;
10862 while (child !== null) {
10863 var childUpdateExpirationTime = child.expirationTime;
10864 var childChildExpirationTime = child.childExpirationTime;
10865 if (childUpdateExpirationTime > newChildExpirationTime) {
10866 newChildExpirationTime = childUpdateExpirationTime;
10867 }
10868 if (childChildExpirationTime > newChildExpirationTime) {
10869 newChildExpirationTime = childChildExpirationTime;
10870 }
10871 if (shouldBubbleActualDurations) {
10872 actualDuration += child.actualDuration;
10873 }
10874 treeBaseDuration += child.treeBaseDuration;
10875 child = child.sibling;
10876 }
10877 workInProgress.actualDuration = actualDuration;
10878 workInProgress.treeBaseDuration = treeBaseDuration;
10879 } else {
10880 var _child = workInProgress.child;
10881 while (_child !== null) {
10882 var _childUpdateExpirationTime = _child.expirationTime;
10883 var _childChildExpirationTime = _child.childExpirationTime;
10884 if (_childUpdateExpirationTime > newChildExpirationTime) {
10885 newChildExpirationTime = _childUpdateExpirationTime;
10886 }
10887 if (_childChildExpirationTime > newChildExpirationTime) {
10888 newChildExpirationTime = _childChildExpirationTime;
10889 }
10890 _child = _child.sibling;
10891 }
10892 }
10893
10894 workInProgress.childExpirationTime = newChildExpirationTime;
10895}
10896
10897function completeUnitOfWork(workInProgress) {
10898 // Attempt to complete the current unit of work, then move to the
10899 // next sibling. If there are no more siblings, return to the
10900 // parent fiber.
10901 while (true) {
10902 // The current, flushed, state of this fiber is the alternate.
10903 // Ideally nothing should rely on this, but relying on it here
10904 // means that we don't need an additional field on the work in
10905 // progress.
10906 var current$$1 = workInProgress.alternate;
10907 {
10908 setCurrentFiber(workInProgress);
10909 }
10910
10911 var returnFiber = workInProgress.return;
10912 var siblingFiber = workInProgress.sibling;
10913
10914 if ((workInProgress.effectTag & Incomplete) === NoEffect) {
10915 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
10916 // Don't replay if it fails during completion phase.
10917 mayReplayFailedUnitOfWork = false;
10918 }
10919 // This fiber completed.
10920 // Remember we're completing this unit so we can find a boundary if it fails.
10921 nextUnitOfWork = workInProgress;
10922 if (enableProfilerTimer) {
10923 if (workInProgress.mode & ProfileMode) {
10924 startProfilerTimer(workInProgress);
10925 }
10926 nextUnitOfWork = completeWork(current$$1, workInProgress, nextRenderExpirationTime);
10927 if (workInProgress.mode & ProfileMode) {
10928 // Update render duration assuming we didn't error.
10929 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
10930 }
10931 } else {
10932 nextUnitOfWork = completeWork(current$$1, workInProgress, nextRenderExpirationTime);
10933 }
10934 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
10935 // We're out of completion phase so replaying is fine now.
10936 mayReplayFailedUnitOfWork = true;
10937 }
10938 stopWorkTimer(workInProgress);
10939 resetChildExpirationTime(workInProgress, nextRenderExpirationTime);
10940 {
10941 resetCurrentFiber();
10942 }
10943
10944 if (nextUnitOfWork !== null) {
10945 // Completing this fiber spawned new work. Work on that next.
10946 return nextUnitOfWork;
10947 }
10948
10949 if (returnFiber !== null &&
10950 // Do not append effects to parents if a sibling failed to complete
10951 (returnFiber.effectTag & Incomplete) === NoEffect) {
10952 // Append all the effects of the subtree and this fiber onto the effect
10953 // list of the parent. The completion order of the children affects the
10954 // side-effect order.
10955 if (returnFiber.firstEffect === null) {
10956 returnFiber.firstEffect = workInProgress.firstEffect;
10957 }
10958 if (workInProgress.lastEffect !== null) {
10959 if (returnFiber.lastEffect !== null) {
10960 returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
10961 }
10962 returnFiber.lastEffect = workInProgress.lastEffect;
10963 }
10964
10965 // If this fiber had side-effects, we append it AFTER the children's
10966 // side-effects. We can perform certain side-effects earlier if
10967 // needed, by doing multiple passes over the effect list. We don't want
10968 // to schedule our own side-effect on our own list because if end up
10969 // reusing children we'll schedule this effect onto itself since we're
10970 // at the end.
10971 var effectTag = workInProgress.effectTag;
10972 // Skip both NoWork and PerformedWork tags when creating the effect list.
10973 // PerformedWork effect is read by React DevTools but shouldn't be committed.
10974 if (effectTag > PerformedWork) {
10975 if (returnFiber.lastEffect !== null) {
10976 returnFiber.lastEffect.nextEffect = workInProgress;
10977 } else {
10978 returnFiber.firstEffect = workInProgress;
10979 }
10980 returnFiber.lastEffect = workInProgress;
10981 }
10982 }
10983
10984 if (true && ReactFiberInstrumentation_1.debugTool) {
10985 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
10986 }
10987
10988 if (siblingFiber !== null) {
10989 // If there is more work to do in this returnFiber, do that next.
10990 return siblingFiber;
10991 } else if (returnFiber !== null) {
10992 // If there's no more work in this returnFiber. Complete the returnFiber.
10993 workInProgress = returnFiber;
10994 continue;
10995 } else {
10996 // We've reached the root.
10997 return null;
10998 }
10999 } else {
11000 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
11001 // Record the render duration for the fiber that errored.
11002 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
11003
11004 // Include the time spent working on failed children before continuing.
11005 var actualDuration = workInProgress.actualDuration;
11006 var child = workInProgress.child;
11007 while (child !== null) {
11008 actualDuration += child.actualDuration;
11009 child = child.sibling;
11010 }
11011 workInProgress.actualDuration = actualDuration;
11012 }
11013
11014 // This fiber did not complete because something threw. Pop values off
11015 // the stack without entering the complete phase. If this is a boundary,
11016 // capture values if possible.
11017 var next = unwindWork(workInProgress, nextRenderExpirationTime);
11018 // Because this fiber did not complete, don't reset its expiration time.
11019 if (workInProgress.effectTag & DidCapture) {
11020 // Restarting an error boundary
11021 stopFailedWorkTimer(workInProgress);
11022 } else {
11023 stopWorkTimer(workInProgress);
11024 }
11025
11026 {
11027 resetCurrentFiber();
11028 }
11029
11030 if (next !== null) {
11031 stopWorkTimer(workInProgress);
11032 if (true && ReactFiberInstrumentation_1.debugTool) {
11033 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
11034 }
11035
11036 // If completing this work spawned new work, do that next. We'll come
11037 // back here again.
11038 // Since we're restarting, remove anything that is not a host effect
11039 // from the effect tag.
11040 next.effectTag &= HostEffectMask;
11041 return next;
11042 }
11043
11044 if (returnFiber !== null) {
11045 // Mark the parent fiber as incomplete and clear its effect list.
11046 returnFiber.firstEffect = returnFiber.lastEffect = null;
11047 returnFiber.effectTag |= Incomplete;
11048 }
11049
11050 if (true && ReactFiberInstrumentation_1.debugTool) {
11051 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
11052 }
11053
11054 if (siblingFiber !== null) {
11055 // If there is more work to do in this returnFiber, do that next.
11056 return siblingFiber;
11057 } else if (returnFiber !== null) {
11058 // If there's no more work in this returnFiber. Complete the returnFiber.
11059 workInProgress = returnFiber;
11060 continue;
11061 } else {
11062 return null;
11063 }
11064 }
11065 }
11066
11067 // Without this explicit null return Flow complains of invalid return type
11068 // TODO Remove the above while(true) loop
11069 // eslint-disable-next-line no-unreachable
11070 return null;
11071}
11072
11073function performUnitOfWork(workInProgress) {
11074 // The current, flushed, state of this fiber is the alternate.
11075 // Ideally nothing should rely on this, but relying on it here
11076 // means that we don't need an additional field on the work in
11077 // progress.
11078 var current$$1 = workInProgress.alternate;
11079
11080 // See if beginning this work spawns more work.
11081 startWorkTimer(workInProgress);
11082 {
11083 setCurrentFiber(workInProgress);
11084 }
11085
11086 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
11087 stashedWorkInProgressProperties = assignFiberPropertiesInDEV(stashedWorkInProgressProperties, workInProgress);
11088 }
11089
11090 var next = void 0;
11091 if (enableProfilerTimer) {
11092 if (workInProgress.mode & ProfileMode) {
11093 startProfilerTimer(workInProgress);
11094 }
11095
11096 next = beginWork(current$$1, workInProgress, nextRenderExpirationTime);
11097 workInProgress.memoizedProps = workInProgress.pendingProps;
11098
11099 if (workInProgress.mode & ProfileMode) {
11100 // Record the render duration assuming we didn't bailout (or error).
11101 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true);
11102 }
11103 } else {
11104 next = beginWork(current$$1, workInProgress, nextRenderExpirationTime);
11105 workInProgress.memoizedProps = workInProgress.pendingProps;
11106 }
11107
11108 {
11109 resetCurrentFiber();
11110 if (isReplayingFailedUnitOfWork) {
11111 // Currently replaying a failed unit of work. This should be unreachable,
11112 // because the render phase is meant to be idempotent, and it should
11113 // have thrown again. Since it didn't, rethrow the original error, so
11114 // React's internal stack is not misaligned.
11115 rethrowOriginalError();
11116 }
11117 }
11118 if (true && ReactFiberInstrumentation_1.debugTool) {
11119 ReactFiberInstrumentation_1.debugTool.onBeginWork(workInProgress);
11120 }
11121
11122 if (next === null) {
11123 // If this doesn't spawn new work, complete the current work.
11124 next = completeUnitOfWork(workInProgress);
11125 }
11126
11127 ReactCurrentOwner$1.current = null;
11128
11129 return next;
11130}
11131
11132function workLoop(isYieldy) {
11133 if (!isYieldy) {
11134 // Flush work without yielding
11135 while (nextUnitOfWork !== null) {
11136 nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
11137 }
11138 } else {
11139 // Flush asynchronous work until there's a higher priority event
11140 while (nextUnitOfWork !== null && !shouldYieldToRenderer()) {
11141 nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
11142 }
11143 }
11144}
11145
11146function renderRoot(root, isYieldy) {
11147 !!isWorking ? invariant(false, 'renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.') : void 0;
11148
11149 flushPassiveEffects$1();
11150
11151 isWorking = true;
11152 var previousDispatcher = ReactCurrentDispatcher.current;
11153 ReactCurrentDispatcher.current = ContextOnlyDispatcher;
11154
11155 var expirationTime = root.nextExpirationTimeToWorkOn;
11156
11157 // Check if we're starting from a fresh stack, or if we're resuming from
11158 // previously yielded work.
11159 if (expirationTime !== nextRenderExpirationTime || root !== nextRoot || nextUnitOfWork === null) {
11160 // Reset the stack and start working from the root.
11161 resetStack();
11162 nextRoot = root;
11163 nextRenderExpirationTime = expirationTime;
11164 nextUnitOfWork = createWorkInProgress(nextRoot.current, null, nextRenderExpirationTime);
11165 root.pendingCommitExpirationTime = NoWork;
11166
11167 if (enableSchedulerTracing) {
11168 // Determine which interactions this batch of work currently includes,
11169 // So that we can accurately attribute time spent working on it,
11170 var interactions = new Set();
11171 root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
11172 if (scheduledExpirationTime >= expirationTime) {
11173 scheduledInteractions.forEach(function (interaction) {
11174 return interactions.add(interaction);
11175 });
11176 }
11177 });
11178
11179 // Store the current set of interactions on the FiberRoot for a few reasons:
11180 // We can re-use it in hot functions like renderRoot() without having to recalculate it.
11181 // We will also use it in commitWork() to pass to any Profiler onRender() hooks.
11182 // This also provides DevTools with a way to access it when the onCommitRoot() hook is called.
11183 root.memoizedInteractions = interactions;
11184
11185 if (interactions.size > 0) {
11186 var subscriber = __subscriberRef.current;
11187 if (subscriber !== null) {
11188 var threadID = computeThreadID(expirationTime, root.interactionThreadID);
11189 try {
11190 subscriber.onWorkStarted(interactions, threadID);
11191 } catch (error) {
11192 // Work thrown by an interaction tracing subscriber should be rethrown,
11193 // But only once it's safe (to avoid leaving the scheduler in an invalid state).
11194 // Store the error for now and we'll re-throw in finishRendering().
11195 if (!hasUnhandledError) {
11196 hasUnhandledError = true;
11197 unhandledError = error;
11198 }
11199 }
11200 }
11201 }
11202 }
11203 }
11204
11205 var prevInteractions = null;
11206 if (enableSchedulerTracing) {
11207 // We're about to start new traced work.
11208 // Restore pending interactions so cascading work triggered during the render phase will be accounted for.
11209 prevInteractions = __interactionsRef.current;
11210 __interactionsRef.current = root.memoizedInteractions;
11211 }
11212
11213 var didFatal = false;
11214
11215 startWorkLoopTimer(nextUnitOfWork);
11216
11217 do {
11218 try {
11219 workLoop(isYieldy);
11220 } catch (thrownValue) {
11221 resetContextDependences();
11222 resetHooks();
11223
11224 // Reset in case completion throws.
11225 // This is only used in DEV and when replaying is on.
11226 var mayReplay = void 0;
11227 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
11228 mayReplay = mayReplayFailedUnitOfWork;
11229 mayReplayFailedUnitOfWork = true;
11230 }
11231
11232 if (nextUnitOfWork === null) {
11233 // This is a fatal error.
11234 didFatal = true;
11235 onUncaughtError(thrownValue);
11236 } else {
11237 if (enableProfilerTimer && nextUnitOfWork.mode & ProfileMode) {
11238 // Record the time spent rendering before an error was thrown.
11239 // This avoids inaccurate Profiler durations in the case of a suspended render.
11240 stopProfilerTimerIfRunningAndRecordDelta(nextUnitOfWork, true);
11241 }
11242
11243 {
11244 // Reset global debug state
11245 // We assume this is defined in DEV
11246 resetCurrentlyProcessingQueue();
11247 }
11248
11249 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
11250 if (mayReplay) {
11251 var failedUnitOfWork = nextUnitOfWork;
11252 replayUnitOfWork(failedUnitOfWork, thrownValue, isYieldy);
11253 }
11254 }
11255
11256 // TODO: we already know this isn't true in some cases.
11257 // At least this shows a nicer error message until we figure out the cause.
11258 // https://github.com/facebook/react/issues/12449#issuecomment-386727431
11259 !(nextUnitOfWork !== null) ? invariant(false, '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.') : void 0;
11260
11261 var sourceFiber = nextUnitOfWork;
11262 var returnFiber = sourceFiber.return;
11263 if (returnFiber === null) {
11264 // This is the root. The root could capture its own errors. However,
11265 // we don't know if it errors before or after we pushed the host
11266 // context. This information is needed to avoid a stack mismatch.
11267 // Because we're not sure, treat this as a fatal error. We could track
11268 // which phase it fails in, but doesn't seem worth it. At least
11269 // for now.
11270 didFatal = true;
11271 onUncaughtError(thrownValue);
11272 } else {
11273 throwException(root, returnFiber, sourceFiber, thrownValue, nextRenderExpirationTime);
11274 nextUnitOfWork = completeUnitOfWork(sourceFiber);
11275 continue;
11276 }
11277 }
11278 }
11279 break;
11280 } while (true);
11281
11282 if (enableSchedulerTracing) {
11283 // Traced work is done for now; restore the previous interactions.
11284 __interactionsRef.current = prevInteractions;
11285 }
11286
11287 // We're done performing work. Time to clean up.
11288 isWorking = false;
11289 ReactCurrentDispatcher.current = previousDispatcher;
11290 resetContextDependences();
11291 resetHooks();
11292
11293 // Yield back to main thread.
11294 if (didFatal) {
11295 var _didCompleteRoot = false;
11296 stopWorkLoopTimer(interruptedBy, _didCompleteRoot);
11297 interruptedBy = null;
11298 // There was a fatal error.
11299 {
11300 resetStackAfterFatalErrorInDev();
11301 }
11302 // `nextRoot` points to the in-progress root. A non-null value indicates
11303 // that we're in the middle of an async render. Set it to null to indicate
11304 // there's no more work to be done in the current batch.
11305 nextRoot = null;
11306 onFatal(root);
11307 return;
11308 }
11309
11310 if (nextUnitOfWork !== null) {
11311 // There's still remaining async work in this tree, but we ran out of time
11312 // in the current frame. Yield back to the renderer. Unless we're
11313 // interrupted by a higher priority update, we'll continue later from where
11314 // we left off.
11315 var _didCompleteRoot2 = false;
11316 stopWorkLoopTimer(interruptedBy, _didCompleteRoot2);
11317 interruptedBy = null;
11318 onYield(root);
11319 return;
11320 }
11321
11322 // We completed the whole tree.
11323 var didCompleteRoot = true;
11324 stopWorkLoopTimer(interruptedBy, didCompleteRoot);
11325 var rootWorkInProgress = root.current.alternate;
11326 !(rootWorkInProgress !== null) ? invariant(false, 'Finished root should have a work-in-progress. This error is likely caused by a bug in React. Please file an issue.') : void 0;
11327
11328 // `nextRoot` points to the in-progress root. A non-null value indicates
11329 // that we're in the middle of an async render. Set it to null to indicate
11330 // there's no more work to be done in the current batch.
11331 nextRoot = null;
11332 interruptedBy = null;
11333
11334 if (nextRenderDidError) {
11335 // There was an error
11336 if (hasLowerPriorityWork(root, expirationTime)) {
11337 // There's lower priority work. If so, it may have the effect of fixing
11338 // the exception that was just thrown. Exit without committing. This is
11339 // similar to a suspend, but without a timeout because we're not waiting
11340 // for a promise to resolve. React will restart at the lower
11341 // priority level.
11342 markSuspendedPriorityLevel(root, expirationTime);
11343 var suspendedExpirationTime = expirationTime;
11344 var rootExpirationTime = root.expirationTime;
11345 onSuspend(root, rootWorkInProgress, suspendedExpirationTime, rootExpirationTime, -1 // Indicates no timeout
11346 );
11347 return;
11348 } else if (
11349 // There's no lower priority work, but we're rendering asynchronously.
11350 // Synchronsouly attempt to render the same level one more time. This is
11351 // similar to a suspend, but without a timeout because we're not waiting
11352 // for a promise to resolve.
11353 !root.didError && isYieldy) {
11354 root.didError = true;
11355 var _suspendedExpirationTime = root.nextExpirationTimeToWorkOn = expirationTime;
11356 var _rootExpirationTime = root.expirationTime = Sync;
11357 onSuspend(root, rootWorkInProgress, _suspendedExpirationTime, _rootExpirationTime, -1 // Indicates no timeout
11358 );
11359 return;
11360 }
11361 }
11362
11363 if (isYieldy && nextLatestAbsoluteTimeoutMs !== -1) {
11364 // The tree was suspended.
11365 var _suspendedExpirationTime2 = expirationTime;
11366 markSuspendedPriorityLevel(root, _suspendedExpirationTime2);
11367
11368 // Find the earliest uncommitted expiration time in the tree, including
11369 // work that is suspended. The timeout threshold cannot be longer than
11370 // the overall expiration.
11371 var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, expirationTime);
11372 var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime);
11373 if (earliestExpirationTimeMs < nextLatestAbsoluteTimeoutMs) {
11374 nextLatestAbsoluteTimeoutMs = earliestExpirationTimeMs;
11375 }
11376
11377 // Subtract the current time from the absolute timeout to get the number
11378 // of milliseconds until the timeout. In other words, convert an absolute
11379 // timestamp to a relative time. This is the value that is passed
11380 // to `setTimeout`.
11381 var currentTimeMs = expirationTimeToMs(requestCurrentTime());
11382 var msUntilTimeout = nextLatestAbsoluteTimeoutMs - currentTimeMs;
11383 msUntilTimeout = msUntilTimeout < 0 ? 0 : msUntilTimeout;
11384
11385 // TODO: Account for the Just Noticeable Difference
11386
11387 var _rootExpirationTime2 = root.expirationTime;
11388 onSuspend(root, rootWorkInProgress, _suspendedExpirationTime2, _rootExpirationTime2, msUntilTimeout);
11389 return;
11390 }
11391
11392 // Ready to commit.
11393 onComplete(root, rootWorkInProgress, expirationTime);
11394}
11395
11396function captureCommitPhaseError(sourceFiber, value) {
11397 var expirationTime = Sync;
11398 var fiber = sourceFiber.return;
11399 while (fiber !== null) {
11400 switch (fiber.tag) {
11401 case ClassComponent:
11402 var ctor = fiber.type;
11403 var instance = fiber.stateNode;
11404 if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
11405 var errorInfo = createCapturedValue(value, sourceFiber);
11406 var update = createClassErrorUpdate(fiber, errorInfo, expirationTime);
11407 enqueueUpdate(fiber, update);
11408 scheduleWork(fiber, expirationTime);
11409 return;
11410 }
11411 break;
11412 case HostRoot:
11413 {
11414 var _errorInfo = createCapturedValue(value, sourceFiber);
11415 var _update = createRootErrorUpdate(fiber, _errorInfo, expirationTime);
11416 enqueueUpdate(fiber, _update);
11417 scheduleWork(fiber, expirationTime);
11418 return;
11419 }
11420 }
11421 fiber = fiber.return;
11422 }
11423
11424 if (sourceFiber.tag === HostRoot) {
11425 // Error was thrown at the root. There is no parent, so the root
11426 // itself should capture it.
11427 var rootFiber = sourceFiber;
11428 var _errorInfo2 = createCapturedValue(value, rootFiber);
11429 var _update2 = createRootErrorUpdate(rootFiber, _errorInfo2, expirationTime);
11430 enqueueUpdate(rootFiber, _update2);
11431 scheduleWork(rootFiber, expirationTime);
11432 }
11433}
11434
11435function computeThreadID(expirationTime, interactionThreadID) {
11436 // Interaction threads are unique per root and expiration time.
11437 return expirationTime * 1000 + interactionThreadID;
11438}
11439
11440function computeExpirationForFiber(currentTime, fiber) {
11441 var expirationTime = void 0;
11442 if (expirationContext !== NoWork) {
11443 // An explicit expiration context was set;
11444 expirationTime = expirationContext;
11445 } else if (isWorking) {
11446 if (isCommitting$1) {
11447 // Updates that occur during the commit phase should have sync priority
11448 // by default.
11449 expirationTime = Sync;
11450 } else {
11451 // Updates during the render phase should expire at the same time as
11452 // the work that is being rendered.
11453 expirationTime = nextRenderExpirationTime;
11454 }
11455 } else {
11456 // No explicit expiration context was set, and we're not currently
11457 // performing work. Calculate a new expiration time.
11458 if (fiber.mode & ConcurrentMode) {
11459 if (isBatchingInteractiveUpdates) {
11460 // This is an interactive update
11461 expirationTime = computeInteractiveExpiration(currentTime);
11462 } else {
11463 // This is an async update
11464 expirationTime = computeAsyncExpiration(currentTime);
11465 }
11466 // If we're in the middle of rendering a tree, do not update at the same
11467 // expiration time that is already rendering.
11468 if (nextRoot !== null && expirationTime === nextRenderExpirationTime) {
11469 expirationTime -= 1;
11470 }
11471 } else {
11472 // This is a sync update
11473 expirationTime = Sync;
11474 }
11475 }
11476 return expirationTime;
11477}
11478
11479function renderDidSuspend(root, absoluteTimeoutMs, suspendedTime) {
11480 // Schedule the timeout.
11481 if (absoluteTimeoutMs >= 0 && nextLatestAbsoluteTimeoutMs < absoluteTimeoutMs) {
11482 nextLatestAbsoluteTimeoutMs = absoluteTimeoutMs;
11483 }
11484}
11485
11486function renderDidError() {
11487 nextRenderDidError = true;
11488}
11489
11490function pingSuspendedRoot(root, thenable, pingTime) {
11491 // A promise that previously suspended React from committing has resolved.
11492 // If React is still suspended, try again at the previous level (pingTime).
11493
11494 var pingCache = root.pingCache;
11495 if (pingCache !== null) {
11496 // The thenable resolved, so we no longer need to memoize, because it will
11497 // never be thrown again.
11498 pingCache.delete(thenable);
11499 }
11500
11501 if (nextRoot !== null && nextRenderExpirationTime === pingTime) {
11502 // Received a ping at the same priority level at which we're currently
11503 // rendering. Restart from the root.
11504 nextRoot = null;
11505 } else {
11506 // Confirm that the root is still suspended at this level. Otherwise exit.
11507 if (isPriorityLevelSuspended(root, pingTime)) {
11508 // Ping at the original level
11509 markPingedPriorityLevel(root, pingTime);
11510 var rootExpirationTime = root.expirationTime;
11511 if (rootExpirationTime !== NoWork) {
11512 requestWork(root, rootExpirationTime);
11513 }
11514 }
11515 }
11516}
11517
11518function retryTimedOutBoundary(boundaryFiber, thenable) {
11519 // The boundary fiber (a Suspense component) previously timed out and was
11520 // rendered in its fallback state. One of the promises that suspended it has
11521 // resolved, which means at least part of the tree was likely unblocked. Try
11522 var retryCache = boundaryFiber.stateNode;
11523 if (retryCache !== null) {
11524 // The thenable resolved, so we no longer need to memoize, because it will
11525 // never be thrown again.
11526 retryCache.delete(thenable);
11527 }
11528
11529 var currentTime = requestCurrentTime();
11530 var retryTime = computeExpirationForFiber(currentTime, boundaryFiber);
11531 var root = scheduleWorkToRoot(boundaryFiber, retryTime);
11532 if (root !== null) {
11533 markPendingPriorityLevel(root, retryTime);
11534 var rootExpirationTime = root.expirationTime;
11535 if (rootExpirationTime !== NoWork) {
11536 requestWork(root, rootExpirationTime);
11537 }
11538 }
11539}
11540
11541function scheduleWorkToRoot(fiber, expirationTime) {
11542 recordScheduleUpdate();
11543
11544 {
11545 if (fiber.tag === ClassComponent) {
11546 var instance = fiber.stateNode;
11547 warnAboutInvalidUpdates(instance);
11548 }
11549 }
11550
11551 // Update the source fiber's expiration time
11552 if (fiber.expirationTime < expirationTime) {
11553 fiber.expirationTime = expirationTime;
11554 }
11555 var alternate = fiber.alternate;
11556 if (alternate !== null && alternate.expirationTime < expirationTime) {
11557 alternate.expirationTime = expirationTime;
11558 }
11559 // Walk the parent path to the root and update the child expiration time.
11560 var node = fiber.return;
11561 var root = null;
11562 if (node === null && fiber.tag === HostRoot) {
11563 root = fiber.stateNode;
11564 } else {
11565 while (node !== null) {
11566 alternate = node.alternate;
11567 if (node.childExpirationTime < expirationTime) {
11568 node.childExpirationTime = expirationTime;
11569 if (alternate !== null && alternate.childExpirationTime < expirationTime) {
11570 alternate.childExpirationTime = expirationTime;
11571 }
11572 } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {
11573 alternate.childExpirationTime = expirationTime;
11574 }
11575 if (node.return === null && node.tag === HostRoot) {
11576 root = node.stateNode;
11577 break;
11578 }
11579 node = node.return;
11580 }
11581 }
11582
11583 if (enableSchedulerTracing) {
11584 if (root !== null) {
11585 var interactions = __interactionsRef.current;
11586 if (interactions.size > 0) {
11587 var pendingInteractionMap = root.pendingInteractionMap;
11588 var pendingInteractions = pendingInteractionMap.get(expirationTime);
11589 if (pendingInteractions != null) {
11590 interactions.forEach(function (interaction) {
11591 if (!pendingInteractions.has(interaction)) {
11592 // Update the pending async work count for previously unscheduled interaction.
11593 interaction.__count++;
11594 }
11595
11596 pendingInteractions.add(interaction);
11597 });
11598 } else {
11599 pendingInteractionMap.set(expirationTime, new Set(interactions));
11600
11601 // Update the pending async work count for the current interactions.
11602 interactions.forEach(function (interaction) {
11603 interaction.__count++;
11604 });
11605 }
11606
11607 var subscriber = __subscriberRef.current;
11608 if (subscriber !== null) {
11609 var threadID = computeThreadID(expirationTime, root.interactionThreadID);
11610 subscriber.onWorkScheduled(interactions, threadID);
11611 }
11612 }
11613 }
11614 }
11615 return root;
11616}
11617
11618function warnIfNotCurrentlyBatchingInDev(fiber) {
11619 {
11620 if (isRendering === false && isBatchingUpdates === false) {
11621 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', getComponentName(fiber.type));
11622 }
11623 }
11624}
11625
11626function scheduleWork(fiber, expirationTime) {
11627 var root = scheduleWorkToRoot(fiber, expirationTime);
11628 if (root === null) {
11629 {
11630 switch (fiber.tag) {
11631 case ClassComponent:
11632 warnAboutUpdateOnUnmounted(fiber, true);
11633 break;
11634 case FunctionComponent:
11635 case ForwardRef:
11636 case MemoComponent:
11637 case SimpleMemoComponent:
11638 warnAboutUpdateOnUnmounted(fiber, false);
11639 break;
11640 }
11641 }
11642 return;
11643 }
11644
11645 if (!isWorking && nextRenderExpirationTime !== NoWork && expirationTime > nextRenderExpirationTime) {
11646 // This is an interruption. (Used for performance tracking.)
11647 interruptedBy = fiber;
11648 resetStack();
11649 }
11650 markPendingPriorityLevel(root, expirationTime);
11651 if (
11652 // If we're in the render phase, we don't need to schedule this root
11653 // for an update, because we'll do it before we exit...
11654 !isWorking || isCommitting$1 ||
11655 // ...unless this is a different root than the one we're rendering.
11656 nextRoot !== root) {
11657 var rootExpirationTime = root.expirationTime;
11658 requestWork(root, rootExpirationTime);
11659 }
11660 if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
11661 // Reset this back to zero so subsequent updates don't throw.
11662 nestedUpdateCount = 0;
11663 invariant(false, '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.');
11664 }
11665}
11666
11667function syncUpdates(fn, a, b, c, d) {
11668 var previousExpirationContext = expirationContext;
11669 expirationContext = Sync;
11670 try {
11671 return fn(a, b, c, d);
11672 } finally {
11673 expirationContext = previousExpirationContext;
11674 }
11675}
11676
11677// TODO: Everything below this is written as if it has been lifted to the
11678// renderers. I'll do this in a follow-up.
11679
11680// Linked-list of roots
11681var firstScheduledRoot = null;
11682var lastScheduledRoot = null;
11683
11684var callbackExpirationTime = NoWork;
11685var callbackID = void 0;
11686var isRendering = false;
11687var nextFlushedRoot = null;
11688var nextFlushedExpirationTime = NoWork;
11689var hasUnhandledError = false;
11690var unhandledError = null;
11691
11692var isBatchingUpdates = false;
11693var isUnbatchingUpdates = false;
11694var isBatchingInteractiveUpdates = false;
11695
11696var completedBatches = null;
11697
11698var originalStartTimeMs = now();
11699var currentRendererTime = msToExpirationTime(originalStartTimeMs);
11700var currentSchedulerTime = currentRendererTime;
11701
11702// Use these to prevent an infinite loop of nested updates
11703var NESTED_UPDATE_LIMIT = 50;
11704var nestedUpdateCount = 0;
11705var lastCommittedRootDuringThisBatch = null;
11706
11707function recomputeCurrentRendererTime() {
11708 var currentTimeMs = now() - originalStartTimeMs;
11709 currentRendererTime = msToExpirationTime(currentTimeMs);
11710}
11711
11712function scheduleCallbackWithExpirationTime(root, expirationTime) {
11713 if (callbackExpirationTime !== NoWork) {
11714 // A callback is already scheduled. Check its expiration time (timeout).
11715 if (expirationTime < callbackExpirationTime) {
11716 // Existing callback has sufficient timeout. Exit.
11717 return;
11718 } else {
11719 if (callbackID !== null) {
11720 // Existing callback has insufficient timeout. Cancel and schedule a
11721 // new one.
11722 cancelDeferredCallback$$1(callbackID);
11723 }
11724 }
11725 // The request callback timer is already running. Don't start a new one.
11726 } else {
11727 startRequestCallbackTimer();
11728 }
11729
11730 callbackExpirationTime = expirationTime;
11731 var currentMs = now() - originalStartTimeMs;
11732 var expirationTimeMs = expirationTimeToMs(expirationTime);
11733 var timeout = expirationTimeMs - currentMs;
11734 callbackID = scheduleDeferredCallback$$1(performAsyncWork, { timeout: timeout });
11735}
11736
11737// For every call to renderRoot, one of onFatal, onComplete, onSuspend, and
11738// onYield is called upon exiting. We use these in lieu of returning a tuple.
11739// I've also chosen not to inline them into renderRoot because these will
11740// eventually be lifted into the renderer.
11741function onFatal(root) {
11742 root.finishedWork = null;
11743}
11744
11745function onComplete(root, finishedWork, expirationTime) {
11746 root.pendingCommitExpirationTime = expirationTime;
11747 root.finishedWork = finishedWork;
11748}
11749
11750function onSuspend(root, finishedWork, suspendedExpirationTime, rootExpirationTime, msUntilTimeout) {
11751 root.expirationTime = rootExpirationTime;
11752 if (msUntilTimeout === 0 && !shouldYieldToRenderer()) {
11753 // Don't wait an additional tick. Commit the tree immediately.
11754 root.pendingCommitExpirationTime = suspendedExpirationTime;
11755 root.finishedWork = finishedWork;
11756 } else if (msUntilTimeout > 0) {
11757 // Wait `msUntilTimeout` milliseconds before committing.
11758 root.timeoutHandle = scheduleTimeout(onTimeout.bind(null, root, finishedWork, suspendedExpirationTime), msUntilTimeout);
11759 }
11760}
11761
11762function onYield(root) {
11763 root.finishedWork = null;
11764}
11765
11766function onTimeout(root, finishedWork, suspendedExpirationTime) {
11767 // The root timed out. Commit it.
11768 root.pendingCommitExpirationTime = suspendedExpirationTime;
11769 root.finishedWork = finishedWork;
11770 // Read the current time before entering the commit phase. We can be
11771 // certain this won't cause tearing related to batching of event updates
11772 // because we're at the top of a timer event.
11773 recomputeCurrentRendererTime();
11774 currentSchedulerTime = currentRendererTime;
11775 flushRoot(root, suspendedExpirationTime);
11776}
11777
11778function onCommit(root, expirationTime) {
11779 root.expirationTime = expirationTime;
11780 root.finishedWork = null;
11781}
11782
11783function requestCurrentTime() {
11784 // requestCurrentTime is called by the scheduler to compute an expiration
11785 // time.
11786 //
11787 // Expiration times are computed by adding to the current time (the start
11788 // time). However, if two updates are scheduled within the same event, we
11789 // should treat their start times as simultaneous, even if the actual clock
11790 // time has advanced between the first and second call.
11791
11792 // In other words, because expiration times determine how updates are batched,
11793 // we want all updates of like priority that occur within the same event to
11794 // receive the same expiration time. Otherwise we get tearing.
11795 //
11796 // We keep track of two separate times: the current "renderer" time and the
11797 // current "scheduler" time. The renderer time can be updated whenever; it
11798 // only exists to minimize the calls performance.now.
11799 //
11800 // But the scheduler time can only be updated if there's no pending work, or
11801 // if we know for certain that we're not in the middle of an event.
11802
11803 if (isRendering) {
11804 // We're already rendering. Return the most recently read time.
11805 return currentSchedulerTime;
11806 }
11807 // Check if there's pending work.
11808 findHighestPriorityRoot();
11809 if (nextFlushedExpirationTime === NoWork || nextFlushedExpirationTime === Never) {
11810 // If there's no pending work, or if the pending work is offscreen, we can
11811 // read the current time without risk of tearing.
11812 recomputeCurrentRendererTime();
11813 currentSchedulerTime = currentRendererTime;
11814 return currentSchedulerTime;
11815 }
11816 // There's already pending work. We might be in the middle of a browser
11817 // event. If we were to read the current time, it could cause multiple updates
11818 // within the same event to receive different expiration times, leading to
11819 // tearing. Return the last read time. During the next idle callback, the
11820 // time will be updated.
11821 return currentSchedulerTime;
11822}
11823
11824// requestWork is called by the scheduler whenever a root receives an update.
11825// It's up to the renderer to call renderRoot at some point in the future.
11826function requestWork(root, expirationTime) {
11827 addRootToSchedule(root, expirationTime);
11828 if (isRendering) {
11829 // Prevent reentrancy. Remaining work will be scheduled at the end of
11830 // the currently rendering batch.
11831 return;
11832 }
11833
11834 if (isBatchingUpdates) {
11835 // Flush work at the end of the batch.
11836 if (isUnbatchingUpdates) {
11837 // ...unless we're inside unbatchedUpdates, in which case we should
11838 // flush it now.
11839 nextFlushedRoot = root;
11840 nextFlushedExpirationTime = Sync;
11841 performWorkOnRoot(root, Sync, false);
11842 }
11843 return;
11844 }
11845
11846 // TODO: Get rid of Sync and use current time?
11847 if (expirationTime === Sync) {
11848 performSyncWork();
11849 } else {
11850 scheduleCallbackWithExpirationTime(root, expirationTime);
11851 }
11852}
11853
11854function addRootToSchedule(root, expirationTime) {
11855 // Add the root to the schedule.
11856 // Check if this root is already part of the schedule.
11857 if (root.nextScheduledRoot === null) {
11858 // This root is not already scheduled. Add it.
11859 root.expirationTime = expirationTime;
11860 if (lastScheduledRoot === null) {
11861 firstScheduledRoot = lastScheduledRoot = root;
11862 root.nextScheduledRoot = root;
11863 } else {
11864 lastScheduledRoot.nextScheduledRoot = root;
11865 lastScheduledRoot = root;
11866 lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
11867 }
11868 } else {
11869 // This root is already scheduled, but its priority may have increased.
11870 var remainingExpirationTime = root.expirationTime;
11871 if (expirationTime > remainingExpirationTime) {
11872 // Update the priority.
11873 root.expirationTime = expirationTime;
11874 }
11875 }
11876}
11877
11878function findHighestPriorityRoot() {
11879 var highestPriorityWork = NoWork;
11880 var highestPriorityRoot = null;
11881 if (lastScheduledRoot !== null) {
11882 var previousScheduledRoot = lastScheduledRoot;
11883 var root = firstScheduledRoot;
11884 while (root !== null) {
11885 var remainingExpirationTime = root.expirationTime;
11886 if (remainingExpirationTime === NoWork) {
11887 // This root no longer has work. Remove it from the scheduler.
11888
11889 // TODO: This check is redudant, but Flow is confused by the branch
11890 // below where we set lastScheduledRoot to null, even though we break
11891 // from the loop right after.
11892 !(previousScheduledRoot !== null && lastScheduledRoot !== null) ? invariant(false, 'Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue.') : void 0;
11893 if (root === root.nextScheduledRoot) {
11894 // This is the only root in the list.
11895 root.nextScheduledRoot = null;
11896 firstScheduledRoot = lastScheduledRoot = null;
11897 break;
11898 } else if (root === firstScheduledRoot) {
11899 // This is the first root in the list.
11900 var next = root.nextScheduledRoot;
11901 firstScheduledRoot = next;
11902 lastScheduledRoot.nextScheduledRoot = next;
11903 root.nextScheduledRoot = null;
11904 } else if (root === lastScheduledRoot) {
11905 // This is the last root in the list.
11906 lastScheduledRoot = previousScheduledRoot;
11907 lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
11908 root.nextScheduledRoot = null;
11909 break;
11910 } else {
11911 previousScheduledRoot.nextScheduledRoot = root.nextScheduledRoot;
11912 root.nextScheduledRoot = null;
11913 }
11914 root = previousScheduledRoot.nextScheduledRoot;
11915 } else {
11916 if (remainingExpirationTime > highestPriorityWork) {
11917 // Update the priority, if it's higher
11918 highestPriorityWork = remainingExpirationTime;
11919 highestPriorityRoot = root;
11920 }
11921 if (root === lastScheduledRoot) {
11922 break;
11923 }
11924 if (highestPriorityWork === Sync) {
11925 // Sync is highest priority by definition so
11926 // we can stop searching.
11927 break;
11928 }
11929 previousScheduledRoot = root;
11930 root = root.nextScheduledRoot;
11931 }
11932 }
11933 }
11934
11935 nextFlushedRoot = highestPriorityRoot;
11936 nextFlushedExpirationTime = highestPriorityWork;
11937}
11938
11939// TODO: This wrapper exists because many of the older tests (the ones that use
11940// flushDeferredPri) rely on the number of times `shouldYield` is called. We
11941// should get rid of it.
11942var didYield = false;
11943function shouldYieldToRenderer() {
11944 if (didYield) {
11945 return true;
11946 }
11947 if (shouldYield$$1()) {
11948 didYield = true;
11949 return true;
11950 }
11951 return false;
11952}
11953
11954function performAsyncWork() {
11955 try {
11956 if (!shouldYieldToRenderer()) {
11957 // The callback timed out. That means at least one update has expired.
11958 // Iterate through the root schedule. If they contain expired work, set
11959 // the next render expiration time to the current time. This has the effect
11960 // of flushing all expired work in a single batch, instead of flushing each
11961 // level one at a time.
11962 if (firstScheduledRoot !== null) {
11963 recomputeCurrentRendererTime();
11964 var root = firstScheduledRoot;
11965 do {
11966 didExpireAtExpirationTime(root, currentRendererTime);
11967 // The root schedule is circular, so this is never null.
11968 root = root.nextScheduledRoot;
11969 } while (root !== firstScheduledRoot);
11970 }
11971 }
11972 performWork(NoWork, true);
11973 } finally {
11974 didYield = false;
11975 }
11976}
11977
11978function performSyncWork() {
11979 performWork(Sync, false);
11980}
11981
11982function performWork(minExpirationTime, isYieldy) {
11983 // Keep working on roots until there's no more work, or until there's a higher
11984 // priority event.
11985 findHighestPriorityRoot();
11986
11987 if (isYieldy) {
11988 recomputeCurrentRendererTime();
11989 currentSchedulerTime = currentRendererTime;
11990
11991 if (enableUserTimingAPI) {
11992 var didExpire = nextFlushedExpirationTime > currentRendererTime;
11993 var timeout = expirationTimeToMs(nextFlushedExpirationTime);
11994 stopRequestCallbackTimer(didExpire, timeout);
11995 }
11996
11997 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && minExpirationTime <= nextFlushedExpirationTime && !(didYield && currentRendererTime > nextFlushedExpirationTime)) {
11998 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, currentRendererTime > nextFlushedExpirationTime);
11999 findHighestPriorityRoot();
12000 recomputeCurrentRendererTime();
12001 currentSchedulerTime = currentRendererTime;
12002 }
12003 } else {
12004 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && minExpirationTime <= nextFlushedExpirationTime) {
12005 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false);
12006 findHighestPriorityRoot();
12007 }
12008 }
12009
12010 // We're done flushing work. Either we ran out of time in this callback,
12011 // or there's no more work left with sufficient priority.
12012
12013 // If we're inside a callback, set this to false since we just completed it.
12014 if (isYieldy) {
12015 callbackExpirationTime = NoWork;
12016 callbackID = null;
12017 }
12018 // If there's work left over, schedule a new callback.
12019 if (nextFlushedExpirationTime !== NoWork) {
12020 scheduleCallbackWithExpirationTime(nextFlushedRoot, nextFlushedExpirationTime);
12021 }
12022
12023 // Clean-up.
12024 finishRendering();
12025}
12026
12027function flushRoot(root, expirationTime) {
12028 !!isRendering ? invariant(false, 'work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method.') : void 0;
12029 // Perform work on root as if the given expiration time is the current time.
12030 // This has the effect of synchronously flushing all work up to and
12031 // including the given time.
12032 nextFlushedRoot = root;
12033 nextFlushedExpirationTime = expirationTime;
12034 performWorkOnRoot(root, expirationTime, false);
12035 // Flush any sync work that was scheduled by lifecycles
12036 performSyncWork();
12037}
12038
12039function finishRendering() {
12040 nestedUpdateCount = 0;
12041 lastCommittedRootDuringThisBatch = null;
12042
12043 if (completedBatches !== null) {
12044 var batches = completedBatches;
12045 completedBatches = null;
12046 for (var i = 0; i < batches.length; i++) {
12047 var batch = batches[i];
12048 try {
12049 batch._onComplete();
12050 } catch (error) {
12051 if (!hasUnhandledError) {
12052 hasUnhandledError = true;
12053 unhandledError = error;
12054 }
12055 }
12056 }
12057 }
12058
12059 if (hasUnhandledError) {
12060 var error = unhandledError;
12061 unhandledError = null;
12062 hasUnhandledError = false;
12063 throw error;
12064 }
12065}
12066
12067function performWorkOnRoot(root, expirationTime, isYieldy) {
12068 !!isRendering ? invariant(false, 'performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.') : void 0;
12069
12070 isRendering = true;
12071
12072 // Check if this is async work or sync/expired work.
12073 if (!isYieldy) {
12074 // Flush work without yielding.
12075 // TODO: Non-yieldy work does not necessarily imply expired work. A renderer
12076 // may want to perform some work without yielding, but also without
12077 // requiring the root to complete (by triggering placeholders).
12078
12079 var finishedWork = root.finishedWork;
12080 if (finishedWork !== null) {
12081 // This root is already complete. We can commit it.
12082 completeRoot(root, finishedWork, expirationTime);
12083 } else {
12084 root.finishedWork = null;
12085 // If this root previously suspended, clear its existing timeout, since
12086 // we're about to try rendering again.
12087 var timeoutHandle = root.timeoutHandle;
12088 if (timeoutHandle !== noTimeout) {
12089 root.timeoutHandle = noTimeout;
12090 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
12091 cancelTimeout(timeoutHandle);
12092 }
12093 renderRoot(root, isYieldy);
12094 finishedWork = root.finishedWork;
12095 if (finishedWork !== null) {
12096 // We've completed the root. Commit it.
12097 completeRoot(root, finishedWork, expirationTime);
12098 }
12099 }
12100 } else {
12101 // Flush async work.
12102 var _finishedWork = root.finishedWork;
12103 if (_finishedWork !== null) {
12104 // This root is already complete. We can commit it.
12105 completeRoot(root, _finishedWork, expirationTime);
12106 } else {
12107 root.finishedWork = null;
12108 // If this root previously suspended, clear its existing timeout, since
12109 // we're about to try rendering again.
12110 var _timeoutHandle = root.timeoutHandle;
12111 if (_timeoutHandle !== noTimeout) {
12112 root.timeoutHandle = noTimeout;
12113 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
12114 cancelTimeout(_timeoutHandle);
12115 }
12116 renderRoot(root, isYieldy);
12117 _finishedWork = root.finishedWork;
12118 if (_finishedWork !== null) {
12119 // We've completed the root. Check the if we should yield one more time
12120 // before committing.
12121 if (!shouldYieldToRenderer()) {
12122 // Still time left. Commit the root.
12123 completeRoot(root, _finishedWork, expirationTime);
12124 } else {
12125 // There's no time left. Mark this root as complete. We'll come
12126 // back and commit it later.
12127 root.finishedWork = _finishedWork;
12128 }
12129 }
12130 }
12131 }
12132
12133 isRendering = false;
12134}
12135
12136function completeRoot(root, finishedWork, expirationTime) {
12137 // Check if there's a batch that matches this expiration time.
12138 var firstBatch = root.firstBatch;
12139 if (firstBatch !== null && firstBatch._expirationTime >= expirationTime) {
12140 if (completedBatches === null) {
12141 completedBatches = [firstBatch];
12142 } else {
12143 completedBatches.push(firstBatch);
12144 }
12145 if (firstBatch._defer) {
12146 // This root is blocked from committing by a batch. Unschedule it until
12147 // we receive another update.
12148 root.finishedWork = finishedWork;
12149 root.expirationTime = NoWork;
12150 return;
12151 }
12152 }
12153
12154 // Commit the root.
12155 root.finishedWork = null;
12156
12157 // Check if this is a nested update (a sync update scheduled during the
12158 // commit phase).
12159 if (root === lastCommittedRootDuringThisBatch) {
12160 // If the next root is the same as the previous root, this is a nested
12161 // update. To prevent an infinite loop, increment the nested update count.
12162 nestedUpdateCount++;
12163 } else {
12164 // Reset whenever we switch roots.
12165 lastCommittedRootDuringThisBatch = root;
12166 nestedUpdateCount = 0;
12167 }
12168 commitRoot(root, finishedWork);
12169}
12170
12171function onUncaughtError(error) {
12172 !(nextFlushedRoot !== null) ? invariant(false, 'Should be working on a root. This error is likely caused by a bug in React. Please file an issue.') : void 0;
12173 // Unschedule this root so we don't work on it again until there's
12174 // another update.
12175 nextFlushedRoot.expirationTime = NoWork;
12176 if (!hasUnhandledError) {
12177 hasUnhandledError = true;
12178 unhandledError = error;
12179 }
12180}
12181
12182// TODO: Batching should be implemented at the renderer level, not inside
12183// the reconciler.
12184function batchedUpdates(fn, a) {
12185 var previousIsBatchingUpdates = isBatchingUpdates;
12186 isBatchingUpdates = true;
12187 try {
12188 return fn(a);
12189 } finally {
12190 isBatchingUpdates = previousIsBatchingUpdates;
12191 if (!isBatchingUpdates && !isRendering) {
12192 performSyncWork();
12193 }
12194 }
12195}
12196
12197// TODO: Batching should be implemented at the renderer level, not within
12198// the reconciler.
12199function flushSync(fn, a) {
12200 !!isRendering ? invariant(false, 'flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.') : void 0;
12201 var previousIsBatchingUpdates = isBatchingUpdates;
12202 isBatchingUpdates = true;
12203 try {
12204 return syncUpdates(fn, a);
12205 } finally {
12206 isBatchingUpdates = previousIsBatchingUpdates;
12207 performSyncWork();
12208 }
12209}
12210
12211// 0 is PROD, 1 is DEV.
12212// Might add PROFILE later.
12213
12214
12215var didWarnAboutNestedUpdates = void 0;
12216{
12217 didWarnAboutNestedUpdates = false;
12218
12219}
12220
12221function getContextForSubtree(parentComponent) {
12222 if (!parentComponent) {
12223 return emptyContextObject;
12224 }
12225
12226 var fiber = get(parentComponent);
12227 var parentContext = findCurrentUnmaskedContext(fiber);
12228
12229 if (fiber.tag === ClassComponent) {
12230 var Component = fiber.type;
12231 if (isContextProvider(Component)) {
12232 return processChildContext(fiber, Component, parentContext);
12233 }
12234 }
12235
12236 return parentContext;
12237}
12238
12239function scheduleRootUpdate(current$$1, element, expirationTime, callback) {
12240 {
12241 if (phase === 'render' && current !== null && !didWarnAboutNestedUpdates) {
12242 didWarnAboutNestedUpdates = true;
12243 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');
12244 }
12245 }
12246
12247 var update = createUpdate(expirationTime);
12248 // Caution: React DevTools currently depends on this property
12249 // being called "element".
12250 update.payload = { element: element };
12251
12252 callback = callback === undefined ? null : callback;
12253 if (callback !== null) {
12254 !(typeof callback === 'function') ? warningWithoutStack$1(false, 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback) : void 0;
12255 update.callback = callback;
12256 }
12257
12258 flushPassiveEffects$1();
12259 enqueueUpdate(current$$1, update);
12260 scheduleWork(current$$1, expirationTime);
12261
12262 return expirationTime;
12263}
12264
12265function updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback) {
12266 // TODO: If this is a nested container, this won't be the root.
12267 var current$$1 = container.current;
12268
12269 {
12270 if (ReactFiberInstrumentation_1.debugTool) {
12271 if (current$$1.alternate === null) {
12272 ReactFiberInstrumentation_1.debugTool.onMountContainer(container);
12273 } else if (element === null) {
12274 ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container);
12275 } else {
12276 ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container);
12277 }
12278 }
12279 }
12280
12281 var context = getContextForSubtree(parentComponent);
12282 if (container.context === null) {
12283 container.context = context;
12284 } else {
12285 container.pendingContext = context;
12286 }
12287
12288 return scheduleRootUpdate(current$$1, element, expirationTime, callback);
12289}
12290
12291function createContainer(containerInfo, isConcurrent, hydrate) {
12292 return createFiberRoot(containerInfo, isConcurrent, hydrate);
12293}
12294
12295function updateContainer(element, container, parentComponent, callback) {
12296 var current$$1 = container.current;
12297 var currentTime = requestCurrentTime();
12298 var expirationTime = computeExpirationForFiber(currentTime, current$$1);
12299 return updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback);
12300}
12301
12302function getPublicRootInstance(container) {
12303 var containerFiber = container.current;
12304 if (!containerFiber.child) {
12305 return null;
12306 }
12307 switch (containerFiber.child.tag) {
12308 case HostComponent:
12309 return getPublicInstance(containerFiber.child.stateNode);
12310 default:
12311 return containerFiber.child.stateNode;
12312 }
12313}
12314
12315
12316
12317var overrideProps = null;
12318
12319{
12320 var copyWithSetImpl = function (obj, path, idx, value) {
12321 if (idx >= path.length) {
12322 return value;
12323 }
12324 var key = path[idx];
12325 var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj);
12326 // $FlowFixMe number or string is fine here
12327 updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value);
12328 return updated;
12329 };
12330
12331 var copyWithSet = function (obj, path, value) {
12332 return copyWithSetImpl(obj, path, 0, value);
12333 };
12334
12335 // Support DevTools props for function components, forwardRef, memo, host components, etc.
12336 overrideProps = function (fiber, path, value) {
12337 flushPassiveEffects$1();
12338 fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
12339 if (fiber.alternate) {
12340 fiber.alternate.pendingProps = fiber.pendingProps;
12341 }
12342 scheduleWork(fiber, Sync);
12343 };
12344}
12345
12346function injectIntoDevTools(devToolsConfig) {
12347 var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
12348 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
12349
12350
12351 return injectInternals(_assign({}, devToolsConfig, {
12352 overrideProps: overrideProps,
12353 currentDispatcherRef: ReactCurrentDispatcher,
12354 findHostInstanceByFiber: function (fiber) {
12355 var hostFiber = findCurrentHostFiber(fiber);
12356 if (hostFiber === null) {
12357 return null;
12358 }
12359 return hostFiber.stateNode;
12360 },
12361 findFiberByHostInstance: function (instance) {
12362 if (!findFiberByHostInstance) {
12363 // Might not be implemented by the renderer.
12364 return null;
12365 }
12366 return findFiberByHostInstance(instance);
12367 }
12368 }));
12369}
12370
12371// This file intentionally does *not* have the Flow annotation.
12372// Don't add it. See `./inline-typed.js` for an explanation.
12373
12374// TODO: this is special because it gets imported during build.
12375
12376var ReactVersion = '16.8.0';
12377
12378var _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; }; }();
12379
12380function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
12381
12382function _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; }
12383
12384// for .act's return value
12385
12386
12387var defaultTestOptions = {
12388 createNodeMock: function () {
12389 return null;
12390 }
12391};
12392
12393function toJSON(inst) {
12394 if (inst.isHidden) {
12395 // Omit timed out children from output entirely. This seems like the least
12396 // surprising behavior. We could perhaps add a separate API that includes
12397 // them, if it turns out people need it.
12398 return null;
12399 }
12400 switch (inst.tag) {
12401 case 'TEXT':
12402 return inst.text;
12403 case 'INSTANCE':
12404 {
12405 /* eslint-disable no-unused-vars */
12406 // We don't include the `children` prop in JSON.
12407 // Instead, we will include the actual rendered children.
12408 var _inst$props = inst.props,
12409 _children = _inst$props.children,
12410 _props = _objectWithoutProperties(_inst$props, ['children']);
12411 /* eslint-enable */
12412
12413
12414 var renderedChildren = null;
12415 if (inst.children && inst.children.length) {
12416 for (var i = 0; i < inst.children.length; i++) {
12417 var renderedChild = toJSON(inst.children[i]);
12418 if (renderedChild !== null) {
12419 if (renderedChildren === null) {
12420 renderedChildren = [renderedChild];
12421 } else {
12422 renderedChildren.push(renderedChild);
12423 }
12424 }
12425 }
12426 }
12427 var json = {
12428 type: inst.type,
12429 props: _props,
12430 children: renderedChildren
12431 };
12432 Object.defineProperty(json, '$$typeof', {
12433 value: Symbol.for('react.test.json')
12434 });
12435 return json;
12436 }
12437 default:
12438 throw new Error('Unexpected node type in toJSON: ' + inst.tag);
12439 }
12440}
12441
12442function childrenToTree(node) {
12443 if (!node) {
12444 return null;
12445 }
12446 var children = nodeAndSiblingsArray(node);
12447 if (children.length === 0) {
12448 return null;
12449 } else if (children.length === 1) {
12450 return toTree(children[0]);
12451 }
12452 return flatten(children.map(toTree));
12453}
12454
12455function nodeAndSiblingsArray(nodeWithSibling) {
12456 var array = [];
12457 var node = nodeWithSibling;
12458 while (node != null) {
12459 array.push(node);
12460 node = node.sibling;
12461 }
12462 return array;
12463}
12464
12465function flatten(arr) {
12466 var result = [];
12467 var stack = [{ i: 0, array: arr }];
12468 while (stack.length) {
12469 var n = stack.pop();
12470 while (n.i < n.array.length) {
12471 var el = n.array[n.i];
12472 n.i += 1;
12473 if (Array.isArray(el)) {
12474 stack.push(n);
12475 stack.push({ i: 0, array: el });
12476 break;
12477 }
12478 result.push(el);
12479 }
12480 }
12481 return result;
12482}
12483
12484function toTree(node) {
12485 if (node == null) {
12486 return null;
12487 }
12488 switch (node.tag) {
12489 case HostRoot:
12490 return childrenToTree(node.child);
12491 case HostPortal:
12492 return childrenToTree(node.child);
12493 case ClassComponent:
12494 return {
12495 nodeType: 'component',
12496 type: node.type,
12497 props: _assign({}, node.memoizedProps),
12498 instance: node.stateNode,
12499 rendered: childrenToTree(node.child)
12500 };
12501 case FunctionComponent:
12502 case SimpleMemoComponent:
12503 return {
12504 nodeType: 'component',
12505 type: node.type,
12506 props: _assign({}, node.memoizedProps),
12507 instance: null,
12508 rendered: childrenToTree(node.child)
12509 };
12510 case HostComponent:
12511 {
12512 return {
12513 nodeType: 'host',
12514 type: node.type,
12515 props: _assign({}, node.memoizedProps),
12516 instance: null, // TODO: use createNodeMock here somehow?
12517 rendered: flatten(nodeAndSiblingsArray(node.child).map(toTree))
12518 };
12519 }
12520 case HostText:
12521 return node.stateNode.text;
12522 case Fragment:
12523 case ContextProvider:
12524 case ContextConsumer:
12525 case Mode:
12526 case Profiler:
12527 case ForwardRef:
12528 case MemoComponent:
12529 case IncompleteClassComponent:
12530 return childrenToTree(node.child);
12531 default:
12532 invariant(false, 'toTree() does not yet know how to handle nodes with tag=%s', node.tag);
12533 }
12534}
12535
12536var validWrapperTypes = new Set([FunctionComponent, ClassComponent, HostComponent, ForwardRef, MemoComponent, SimpleMemoComponent,
12537// Normally skipped, but used when there's more than one root child.
12538HostRoot]);
12539
12540function getChildren(parent) {
12541 var children = [];
12542 var startingNode = parent;
12543 var node = startingNode;
12544 if (node.child === null) {
12545 return children;
12546 }
12547 node.child.return = node;
12548 node = node.child;
12549 outer: while (true) {
12550 var descend = false;
12551 if (validWrapperTypes.has(node.tag)) {
12552 children.push(wrapFiber(node));
12553 } else if (node.tag === HostText) {
12554 children.push('' + node.memoizedProps);
12555 } else {
12556 descend = true;
12557 }
12558 if (descend && node.child !== null) {
12559 node.child.return = node;
12560 node = node.child;
12561 continue;
12562 }
12563 while (node.sibling === null) {
12564 if (node.return === startingNode) {
12565 break outer;
12566 }
12567 node = node.return;
12568 }
12569 node.sibling.return = node.return;
12570 node = node.sibling;
12571 }
12572 return children;
12573}
12574
12575var ReactTestInstance = function () {
12576 ReactTestInstance.prototype._currentFiber = function _currentFiber() {
12577 // Throws if this component has been unmounted.
12578 var fiber = findCurrentFiberUsingSlowPath(this._fiber);
12579 !(fiber !== null) ? invariant(false, 'Can\'t read from currently-mounting component. This error is likely caused by a bug in React. Please file an issue.') : void 0;
12580 return fiber;
12581 };
12582
12583 function ReactTestInstance(fiber) {
12584 _classCallCheck(this, ReactTestInstance);
12585
12586 !validWrapperTypes.has(fiber.tag) ? invariant(false, 'Unexpected object passed to ReactTestInstance constructor (tag: %s). This is probably a bug in React.', fiber.tag) : void 0;
12587 this._fiber = fiber;
12588 }
12589
12590 // Custom search functions
12591 ReactTestInstance.prototype.find = function find(predicate) {
12592 return expectOne(this.findAll(predicate, { deep: false }), 'matching custom predicate: ' + predicate.toString());
12593 };
12594
12595 ReactTestInstance.prototype.findByType = function findByType(type) {
12596 return expectOne(this.findAllByType(type, { deep: false }), 'with node type: "' + (type.displayName || type.name) + '"');
12597 };
12598
12599 ReactTestInstance.prototype.findByProps = function findByProps(props) {
12600 return expectOne(this.findAllByProps(props, { deep: false }), 'with props: ' + JSON.stringify(props));
12601 };
12602
12603 ReactTestInstance.prototype.findAll = function findAll(predicate) {
12604 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
12605
12606 return _findAll(this, predicate, options);
12607 };
12608
12609 ReactTestInstance.prototype.findAllByType = function findAllByType(type) {
12610 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
12611
12612 return _findAll(this, function (node) {
12613 return node.type === type;
12614 }, options);
12615 };
12616
12617 ReactTestInstance.prototype.findAllByProps = function findAllByProps(props) {
12618 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
12619
12620 return _findAll(this, function (node) {
12621 return node.props && propsMatch(node.props, props);
12622 }, options);
12623 };
12624
12625 _createClass(ReactTestInstance, [{
12626 key: 'instance',
12627 get: function () {
12628 if (this._fiber.tag === HostComponent) {
12629 return getPublicInstance(this._fiber.stateNode);
12630 } else {
12631 return this._fiber.stateNode;
12632 }
12633 }
12634 }, {
12635 key: 'type',
12636 get: function () {
12637 return this._fiber.type;
12638 }
12639 }, {
12640 key: 'props',
12641 get: function () {
12642 return this._currentFiber().memoizedProps;
12643 }
12644 }, {
12645 key: 'parent',
12646 get: function () {
12647 var parent = this._fiber.return;
12648 while (parent !== null) {
12649 if (validWrapperTypes.has(parent.tag)) {
12650 if (parent.tag === HostRoot) {
12651 // Special case: we only "materialize" instances for roots
12652 // if they have more than a single child. So we'll check that now.
12653 if (getChildren(parent).length < 2) {
12654 return null;
12655 }
12656 }
12657 return wrapFiber(parent);
12658 }
12659 parent = parent.return;
12660 }
12661 return null;
12662 }
12663 }, {
12664 key: 'children',
12665 get: function () {
12666 return getChildren(this._currentFiber());
12667 }
12668 }]);
12669
12670 return ReactTestInstance;
12671}();
12672
12673function _findAll(root, predicate, options) {
12674 var deep = options ? options.deep : true;
12675 var results = [];
12676
12677 if (predicate(root)) {
12678 results.push(root);
12679 if (!deep) {
12680 return results;
12681 }
12682 }
12683
12684 root.children.forEach(function (child) {
12685 if (typeof child === 'string') {
12686 return;
12687 }
12688 results.push.apply(results, _findAll(child, predicate, options));
12689 });
12690
12691 return results;
12692}
12693
12694function expectOne(all, message) {
12695 if (all.length === 1) {
12696 return all[0];
12697 }
12698
12699 var prefix = all.length === 0 ? 'No instances found ' : 'Expected 1 but found ' + all.length + ' instances ';
12700
12701 throw new Error(prefix + message);
12702}
12703
12704function propsMatch(props, filter) {
12705 for (var key in filter) {
12706 if (props[key] !== filter[key]) {
12707 return false;
12708 }
12709 }
12710 return true;
12711}
12712
12713var ReactTestRendererFiber = {
12714 create: function (element, options) {
12715 var createNodeMock = defaultTestOptions.createNodeMock;
12716 var isConcurrent = false;
12717 if (typeof options === 'object' && options !== null) {
12718 if (typeof options.createNodeMock === 'function') {
12719 createNodeMock = options.createNodeMock;
12720 }
12721 if (options.unstable_isConcurrent === true) {
12722 isConcurrent = true;
12723 }
12724 }
12725 var container = {
12726 children: [],
12727 createNodeMock: createNodeMock,
12728 tag: 'CONTAINER'
12729 };
12730 var root = createContainer(container, isConcurrent, false);
12731 !(root != null) ? invariant(false, 'something went wrong') : void 0;
12732 updateContainer(element, root, null, null);
12733
12734 var entry = {
12735 root: undefined, // makes flow happy
12736 // we define a 'getter' for 'root' below using 'Object.defineProperty'
12737 toJSON: function () {
12738 if (root == null || root.current == null || container == null) {
12739 return null;
12740 }
12741 if (container.children.length === 0) {
12742 return null;
12743 }
12744 if (container.children.length === 1) {
12745 return toJSON(container.children[0]);
12746 }
12747 if (container.children.length === 2 && container.children[0].isHidden === true && container.children[1].isHidden === false) {
12748 // Omit timed out children from output entirely, including the fact that we
12749 // temporarily wrap fallback and timed out children in an array.
12750 return toJSON(container.children[1]);
12751 }
12752 var renderedChildren = null;
12753 if (container.children && container.children.length) {
12754 for (var i = 0; i < container.children.length; i++) {
12755 var renderedChild = toJSON(container.children[i]);
12756 if (renderedChild !== null) {
12757 if (renderedChildren === null) {
12758 renderedChildren = [renderedChild];
12759 } else {
12760 renderedChildren.push(renderedChild);
12761 }
12762 }
12763 }
12764 }
12765 return renderedChildren;
12766 },
12767 toTree: function () {
12768 if (root == null || root.current == null) {
12769 return null;
12770 }
12771 return toTree(root.current);
12772 },
12773 update: function (newElement) {
12774 if (root == null || root.current == null) {
12775 return;
12776 }
12777 updateContainer(newElement, root, null, null);
12778 },
12779 unmount: function () {
12780 if (root == null || root.current == null) {
12781 return;
12782 }
12783 updateContainer(null, root, null, null);
12784 container = null;
12785 root = null;
12786 },
12787 getInstance: function () {
12788 if (root == null || root.current == null) {
12789 return null;
12790 }
12791 return getPublicRootInstance(root);
12792 },
12793
12794
12795 unstable_flushAll: flushAll,
12796 unstable_flushSync: function (fn) {
12797 clearYields();
12798 return flushSync(fn);
12799 },
12800
12801 unstable_flushNumberOfYields: flushNumberOfYields,
12802 unstable_clearYields: clearYields
12803 };
12804
12805 Object.defineProperty(entry, 'root', {
12806 configurable: true,
12807 enumerable: true,
12808 get: function () {
12809 if (root === null) {
12810 throw new Error("Can't access .root on unmounted test renderer");
12811 }
12812 var children = getChildren(root.current);
12813 if (children.length === 0) {
12814 throw new Error("Can't access .root on unmounted test renderer");
12815 } else if (children.length === 1) {
12816 // Normally, we skip the root and just give you the child.
12817 return children[0];
12818 } else {
12819 // However, we give you the root if there's more than one root child.
12820 // We could make this the behavior for all cases but it would be a breaking change.
12821 return wrapFiber(root.current);
12822 }
12823 }
12824 });
12825
12826 return entry;
12827 },
12828
12829
12830 unstable_yield: yieldValue,
12831 unstable_clearYields: clearYields,
12832
12833 /* eslint-disable camelcase */
12834 unstable_batchedUpdates: batchedUpdates,
12835 /* eslint-enable camelcase */
12836
12837 unstable_setNowImplementation: setNowImplementation,
12838
12839 act: function (callback) {
12840 // note: keep these warning messages in sync with
12841 // createNoop.js and ReactTestUtils.js
12842 var result = batchedUpdates(callback);
12843 {
12844 if (result !== undefined) {
12845 var addendum = void 0;
12846 if (result !== null && typeof result.then === 'function') {
12847 addendum = "\n\nIt looks like you wrote TestRenderer.act(async () => ...) or returned a Promise from it's callback. " + 'Putting asynchronous logic inside TestRenderer.act(...) is not supported.\n';
12848 } else {
12849 addendum = ' You returned: ' + result;
12850 }
12851 warningWithoutStack$1(false, 'The callback passed to TestRenderer.act(...) function must not return anything.%s', addendum);
12852 }
12853 }
12854 flushPassiveEffects();
12855 // we want the user to not expect a return,
12856 // but we want to warn if they use it like they can await on it.
12857 return {
12858 then: function () {
12859 {
12860 warningWithoutStack$1(false, 'Do not await the result of calling TestRenderer.act(...), it is not a Promise.');
12861 }
12862 }
12863 };
12864 }
12865};
12866
12867// root used to flush effects during .act() calls
12868var actRoot = createContainer({
12869 children: [],
12870 createNodeMock: defaultTestOptions.createNodeMock,
12871 tag: 'CONTAINER'
12872}, true, false);
12873
12874function flushPassiveEffects() {
12875 // Trick to flush passive effects without exposing an internal API:
12876 // Create a throwaway root and schedule a dummy update on it.
12877 updateContainer(null, actRoot, null, null);
12878}
12879
12880var fiberToWrapper = new WeakMap();
12881function wrapFiber(fiber) {
12882 var wrapper = fiberToWrapper.get(fiber);
12883 if (wrapper === undefined && fiber.alternate !== null) {
12884 wrapper = fiberToWrapper.get(fiber.alternate);
12885 }
12886 if (wrapper === undefined) {
12887 wrapper = new ReactTestInstance(fiber);
12888 fiberToWrapper.set(fiber, wrapper);
12889 }
12890 return wrapper;
12891}
12892
12893// Enable ReactTestRenderer to be used to test DevTools integration.
12894injectIntoDevTools({
12895 findFiberByHostInstance: function () {
12896 throw new Error('TestRenderer does not support findFiberByHostInstance()');
12897 },
12898 bundleType: 1,
12899 version: ReactVersion,
12900 rendererPackageName: 'react-test-renderer'
12901});
12902
12903
12904
12905var ReactTestRenderer = Object.freeze({
12906 default: ReactTestRendererFiber
12907});
12908
12909var ReactTestRenderer$1 = ( ReactTestRenderer && ReactTestRendererFiber ) || ReactTestRenderer;
12910
12911// TODO: decide on the top-level export form.
12912// This is hacky but makes it work with both Rollup and Jest.
12913var reactTestRenderer = ReactTestRenderer$1.default || ReactTestRenderer$1;
12914
12915return reactTestRenderer;
12916
12917})));