UNPKG

620 kBJavaScriptView Raw
1/** @license React v17.0.1
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(function (global, factory) {
10 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('scheduler/unstable_mock'), require('scheduler')) :
11 typeof define === 'function' && define.amd ? define(['exports', 'react', 'scheduler/unstable_mock', 'scheduler'], factory) :
12 (global = global || self, factory(global.ReactTestRenderer = {}, global.React, global.SchedulerMock, global.Scheduler));
13}(this, (function (exports, React, Scheduler, Scheduler$1) { 'use strict';
14
15 var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
16
17 // by calls to these methods by a Babel plugin.
18 //
19 // In PROD (or in packages without access to React internals),
20 // they are left as they are instead.
21
22 function warn(format) {
23 {
24 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
25 args[_key - 1] = arguments[_key];
26 }
27
28 printWarning('warn', format, args);
29 }
30 }
31 function error(format) {
32 {
33 for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
34 args[_key2 - 1] = arguments[_key2];
35 }
36
37 printWarning('error', format, args);
38 }
39 }
40
41 function printWarning(level, format, args) {
42 // When changing this logic, you might want to also
43 // update consoleWithStackDev.www.js as well.
44 {
45 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
46 var stack = ReactDebugCurrentFrame.getStackAddendum();
47
48 if (stack !== '') {
49 format += '%s';
50 args = args.concat([stack]);
51 }
52
53 var argsWithFormat = args.map(function (item) {
54 return '' + item;
55 }); // Careful: RN currently depends on this prefix
56
57 argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
58 // breaks IE9: https://github.com/facebook/react/issues/13610
59 // eslint-disable-next-line react-internal/no-production-logging
60
61 Function.prototype.apply.call(console[level], console, argsWithFormat);
62 }
63 }
64
65 function _defineProperties(target, props) {
66 for (var i = 0; i < props.length; i++) {
67 var descriptor = props[i];
68 descriptor.enumerable = descriptor.enumerable || false;
69 descriptor.configurable = true;
70 if ("value" in descriptor) descriptor.writable = true;
71 Object.defineProperty(target, descriptor.key, descriptor);
72 }
73 }
74
75 function _createClass(Constructor, protoProps, staticProps) {
76 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
77 if (staticProps) _defineProperties(Constructor, staticProps);
78 return Constructor;
79 }
80
81 function _objectWithoutPropertiesLoose(source, excluded) {
82 if (source == null) return {};
83 var target = {};
84 var sourceKeys = Object.keys(source);
85 var key, i;
86
87 for (i = 0; i < sourceKeys.length; i++) {
88 key = sourceKeys[i];
89 if (excluded.indexOf(key) >= 0) continue;
90 target[key] = source[key];
91 }
92
93 return target;
94 }
95
96 var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
97 var _assign = ReactInternals.assign;
98
99 var FunctionComponent = 0;
100 var ClassComponent = 1;
101 var IndeterminateComponent = 2; // Before we know whether it is function or class
102
103 var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
104
105 var HostPortal = 4; // A subtree. Could be an entry point to a different renderer.
106
107 var HostComponent = 5;
108 var HostText = 6;
109 var Fragment = 7;
110 var Mode = 8;
111 var ContextConsumer = 9;
112 var ContextProvider = 10;
113 var ForwardRef = 11;
114 var Profiler = 12;
115 var SuspenseComponent = 13;
116 var MemoComponent = 14;
117 var SimpleMemoComponent = 15;
118 var LazyComponent = 16;
119 var IncompleteClassComponent = 17;
120 var DehydratedFragment = 18;
121 var SuspenseListComponent = 19;
122 var FundamentalComponent = 20;
123 var ScopeComponent = 21;
124 var Block = 22;
125 var OffscreenComponent = 23;
126 var LegacyHiddenComponent = 24;
127
128 /**
129 * `ReactInstanceMap` maintains a mapping from a public facing stateful
130 * instance (key) and the internal representation (value). This allows public
131 * methods to accept the user facing instance as an argument and map them back
132 * to internal methods.
133 *
134 * Note that this module is currently shared and assumed to be stateless.
135 * If this becomes an actual Map, that will break.
136 */
137 function get(key) {
138 return key._reactInternals;
139 }
140 function set(key, value) {
141 key._reactInternals = value;
142 }
143
144 // ATTENTION
145 // When adding new symbols to this file,
146 // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
147 // The Symbol used to tag the ReactElement-like types. If there is no native Symbol
148 // nor polyfill, then a plain number is used for performance.
149 var REACT_ELEMENT_TYPE = 0xeac7;
150 var REACT_PORTAL_TYPE = 0xeaca;
151 var REACT_FRAGMENT_TYPE = 0xeacb;
152 var REACT_STRICT_MODE_TYPE = 0xeacc;
153 var REACT_PROFILER_TYPE = 0xead2;
154 var REACT_PROVIDER_TYPE = 0xeacd;
155 var REACT_CONTEXT_TYPE = 0xeace;
156 var REACT_FORWARD_REF_TYPE = 0xead0;
157 var REACT_SUSPENSE_TYPE = 0xead1;
158 var REACT_SUSPENSE_LIST_TYPE = 0xead8;
159 var REACT_MEMO_TYPE = 0xead3;
160 var REACT_LAZY_TYPE = 0xead4;
161 var REACT_BLOCK_TYPE = 0xead9;
162 var REACT_SERVER_BLOCK_TYPE = 0xeada;
163 var REACT_FUNDAMENTAL_TYPE = 0xead5;
164 var REACT_SCOPE_TYPE = 0xead7;
165 var REACT_OPAQUE_ID_TYPE = 0xeae0;
166 var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1;
167 var REACT_OFFSCREEN_TYPE = 0xeae2;
168 var REACT_LEGACY_HIDDEN_TYPE = 0xeae3;
169
170 if (typeof Symbol === 'function' && Symbol.for) {
171 var symbolFor = Symbol.for;
172 REACT_ELEMENT_TYPE = symbolFor('react.element');
173 REACT_PORTAL_TYPE = symbolFor('react.portal');
174 REACT_FRAGMENT_TYPE = symbolFor('react.fragment');
175 REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode');
176 REACT_PROFILER_TYPE = symbolFor('react.profiler');
177 REACT_PROVIDER_TYPE = symbolFor('react.provider');
178 REACT_CONTEXT_TYPE = symbolFor('react.context');
179 REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref');
180 REACT_SUSPENSE_TYPE = symbolFor('react.suspense');
181 REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list');
182 REACT_MEMO_TYPE = symbolFor('react.memo');
183 REACT_LAZY_TYPE = symbolFor('react.lazy');
184 REACT_BLOCK_TYPE = symbolFor('react.block');
185 REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block');
186 REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental');
187 REACT_SCOPE_TYPE = symbolFor('react.scope');
188 REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id');
189 REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode');
190 REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen');
191 REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden');
192 }
193
194 var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
195 var FAUX_ITERATOR_SYMBOL = '@@iterator';
196 function getIteratorFn(maybeIterable) {
197 if (maybeIterable === null || typeof maybeIterable !== 'object') {
198 return null;
199 }
200
201 var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
202
203 if (typeof maybeIterator === 'function') {
204 return maybeIterator;
205 }
206
207 return null;
208 }
209
210 function getWrappedName(outerType, innerType, wrapperName) {
211 var functionName = innerType.displayName || innerType.name || '';
212 return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName);
213 }
214
215 function getContextName(type) {
216 return type.displayName || 'Context';
217 }
218
219 function getComponentName(type) {
220 if (type == null) {
221 // Host root, text node or just invalid type.
222 return null;
223 }
224
225 {
226 if (typeof type.tag === 'number') {
227 error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
228 }
229 }
230
231 if (typeof type === 'function') {
232 return type.displayName || type.name || null;
233 }
234
235 if (typeof type === 'string') {
236 return type;
237 }
238
239 switch (type) {
240 case REACT_FRAGMENT_TYPE:
241 return 'Fragment';
242
243 case REACT_PORTAL_TYPE:
244 return 'Portal';
245
246 case REACT_PROFILER_TYPE:
247 return 'Profiler';
248
249 case REACT_STRICT_MODE_TYPE:
250 return 'StrictMode';
251
252 case REACT_SUSPENSE_TYPE:
253 return 'Suspense';
254
255 case REACT_SUSPENSE_LIST_TYPE:
256 return 'SuspenseList';
257 }
258
259 if (typeof type === 'object') {
260 switch (type.$$typeof) {
261 case REACT_CONTEXT_TYPE:
262 var context = type;
263 return getContextName(context) + '.Consumer';
264
265 case REACT_PROVIDER_TYPE:
266 var provider = type;
267 return getContextName(provider._context) + '.Provider';
268
269 case REACT_FORWARD_REF_TYPE:
270 return getWrappedName(type, type.render, 'ForwardRef');
271
272 case REACT_MEMO_TYPE:
273 return getComponentName(type.type);
274
275 case REACT_BLOCK_TYPE:
276 return getComponentName(type._render);
277
278 case REACT_LAZY_TYPE:
279 {
280 var lazyComponent = type;
281 var payload = lazyComponent._payload;
282 var init = lazyComponent._init;
283
284 try {
285 return getComponentName(init(payload));
286 } catch (x) {
287 return null;
288 }
289 }
290 }
291 }
292
293 return null;
294 }
295
296 // Don't change these two values. They're used by React Dev Tools.
297 var NoFlags =
298 /* */
299 0;
300 var PerformedWork =
301 /* */
302 1; // You can change the rest (and add more).
303
304 var Placement =
305 /* */
306 2;
307 var Update =
308 /* */
309 4;
310 var PlacementAndUpdate =
311 /* */
312 6;
313 var Deletion =
314 /* */
315 8;
316 var ContentReset =
317 /* */
318 16;
319 var Callback =
320 /* */
321 32;
322 var DidCapture =
323 /* */
324 64;
325 var Ref =
326 /* */
327 128;
328 var Snapshot =
329 /* */
330 256;
331 var Passive =
332 /* */
333 512; // TODO (effects) Remove this bit once the new reconciler is synced to the old.
334
335 var PassiveUnmountPendingDev =
336 /* */
337 8192;
338 var Hydrating =
339 /* */
340 1024;
341 var HydratingAndUpdate =
342 /* */
343 1028; // Passive & Update & Callback & Ref & Snapshot
344
345 var LifecycleEffectMask =
346 /* */
347 932; // Union of all host effects
348
349 var HostEffectMask =
350 /* */
351 2047; // These are not really side effects, but we still reuse this field.
352
353 var Incomplete =
354 /* */
355 2048;
356 var ShouldCapture =
357 /* */
358 4096;
359 var ForceUpdateForLegacySuspense =
360 /* */
361 16384; // Static tags describe aspects of a fiber that are not specific to a render,
362
363 var enableProfilerTimer = true;
364 var enableFundamentalAPI = false;
365 var warnAboutStringRefs = false;
366 var enableNewReconciler = false;
367
368 var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
369 function getNearestMountedFiber(fiber) {
370 var node = fiber;
371 var nearestMounted = fiber;
372
373 if (!fiber.alternate) {
374 // If there is no alternate, this might be a new tree that isn't inserted
375 // yet. If it is, then it will have a pending insertion effect on it.
376 var nextNode = node;
377
378 do {
379 node = nextNode;
380
381 if ((node.flags & (Placement | Hydrating)) !== NoFlags) {
382 // This is an insertion or in-progress hydration. The nearest possible
383 // mounted fiber is the parent but we need to continue to figure out
384 // if that one is still mounted.
385 nearestMounted = node.return;
386 }
387
388 nextNode = node.return;
389 } while (nextNode);
390 } else {
391 while (node.return) {
392 node = node.return;
393 }
394 }
395
396 if (node.tag === HostRoot) {
397 // TODO: Check if this was a nested HostRoot when used with
398 // renderContainerIntoSubtree.
399 return nearestMounted;
400 } // If we didn't hit the root, that means that we're in an disconnected tree
401 // that has been unmounted.
402
403
404 return null;
405 }
406 function isFiberMounted(fiber) {
407 return getNearestMountedFiber(fiber) === fiber;
408 }
409 function isMounted(component) {
410 {
411 var owner = ReactCurrentOwner.current;
412
413 if (owner !== null && owner.tag === ClassComponent) {
414 var ownerFiber = owner;
415 var instance = ownerFiber.stateNode;
416
417 if (!instance._warnedAboutRefsInRender) {
418 error('%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');
419 }
420
421 instance._warnedAboutRefsInRender = true;
422 }
423 }
424
425 var fiber = get(component);
426
427 if (!fiber) {
428 return false;
429 }
430
431 return getNearestMountedFiber(fiber) === fiber;
432 }
433
434 function assertIsMounted(fiber) {
435 if (!(getNearestMountedFiber(fiber) === fiber)) {
436 {
437 throw Error( "Unable to find node on an unmounted component." );
438 }
439 }
440 }
441
442 function findCurrentFiberUsingSlowPath(fiber) {
443 var alternate = fiber.alternate;
444
445 if (!alternate) {
446 // If there is no alternate, then we only need to check if it is mounted.
447 var nearestMounted = getNearestMountedFiber(fiber);
448
449 if (!(nearestMounted !== null)) {
450 {
451 throw Error( "Unable to find node on an unmounted component." );
452 }
453 }
454
455 if (nearestMounted !== fiber) {
456 return null;
457 }
458
459 return fiber;
460 } // If we have two possible branches, we'll walk backwards up to the root
461 // to see what path the root points to. On the way we may hit one of the
462 // special cases and we'll deal with them.
463
464
465 var a = fiber;
466 var b = alternate;
467
468 while (true) {
469 var parentA = a.return;
470
471 if (parentA === null) {
472 // We're at the root.
473 break;
474 }
475
476 var parentB = parentA.alternate;
477
478 if (parentB === null) {
479 // There is no alternate. This is an unusual case. Currently, it only
480 // happens when a Suspense component is hidden. An extra fragment fiber
481 // is inserted in between the Suspense fiber and its children. Skip
482 // over this extra fragment fiber and proceed to the next parent.
483 var nextParent = parentA.return;
484
485 if (nextParent !== null) {
486 a = b = nextParent;
487 continue;
488 } // If there's no parent, we're at the root.
489
490
491 break;
492 } // If both copies of the parent fiber point to the same child, we can
493 // assume that the child is current. This happens when we bailout on low
494 // priority: the bailed out fiber's child reuses the current child.
495
496
497 if (parentA.child === parentB.child) {
498 var child = parentA.child;
499
500 while (child) {
501 if (child === a) {
502 // We've determined that A is the current branch.
503 assertIsMounted(parentA);
504 return fiber;
505 }
506
507 if (child === b) {
508 // We've determined that B is the current branch.
509 assertIsMounted(parentA);
510 return alternate;
511 }
512
513 child = child.sibling;
514 } // We should never have an alternate for any mounting node. So the only
515 // way this could possibly happen is if this was unmounted, if at all.
516
517
518 {
519 {
520 throw Error( "Unable to find node on an unmounted component." );
521 }
522 }
523 }
524
525 if (a.return !== b.return) {
526 // The return pointer of A and the return pointer of B point to different
527 // fibers. We assume that return pointers never criss-cross, so A must
528 // belong to the child set of A.return, and B must belong to the child
529 // set of B.return.
530 a = parentA;
531 b = parentB;
532 } else {
533 // The return pointers point to the same fiber. We'll have to use the
534 // default, slow path: scan the child sets of each parent alternate to see
535 // which child belongs to which set.
536 //
537 // Search parent A's child set
538 var didFindChild = false;
539 var _child = parentA.child;
540
541 while (_child) {
542 if (_child === a) {
543 didFindChild = true;
544 a = parentA;
545 b = parentB;
546 break;
547 }
548
549 if (_child === b) {
550 didFindChild = true;
551 b = parentA;
552 a = parentB;
553 break;
554 }
555
556 _child = _child.sibling;
557 }
558
559 if (!didFindChild) {
560 // Search parent B's child set
561 _child = parentB.child;
562
563 while (_child) {
564 if (_child === a) {
565 didFindChild = true;
566 a = parentB;
567 b = parentA;
568 break;
569 }
570
571 if (_child === b) {
572 didFindChild = true;
573 b = parentB;
574 a = parentA;
575 break;
576 }
577
578 _child = _child.sibling;
579 }
580
581 if (!didFindChild) {
582 {
583 throw Error( "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." );
584 }
585 }
586 }
587 }
588
589 if (!(a.alternate === b)) {
590 {
591 throw Error( "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." );
592 }
593 }
594 } // If the root is not a host container, we're in a disconnected tree. I.e.
595 // unmounted.
596
597
598 if (!(a.tag === HostRoot)) {
599 {
600 throw Error( "Unable to find node on an unmounted component." );
601 }
602 }
603
604 if (a.stateNode.current === a) {
605 // We've determined that A is the current branch.
606 return fiber;
607 } // Otherwise B has to be current branch.
608
609
610 return alternate;
611 }
612 function findCurrentHostFiber(parent) {
613 var currentParent = findCurrentFiberUsingSlowPath(parent);
614
615 if (!currentParent) {
616 return null;
617 } // Next we'll drill down this component to find the first HostComponent/Text.
618
619
620 var node = currentParent;
621
622 while (true) {
623 if (node.tag === HostComponent || node.tag === HostText) {
624 return node;
625 } else if (node.child) {
626 node.child.return = node;
627 node = node.child;
628 continue;
629 }
630
631 if (node === currentParent) {
632 return null;
633 }
634
635 while (!node.sibling) {
636 if (!node.return || node.return === currentParent) {
637 return null;
638 }
639
640 node = node.return;
641 }
642
643 node.sibling.return = node.return;
644 node = node.sibling;
645 } // Flow needs the return null here, but ESLint complains about it.
646 // eslint-disable-next-line no-unreachable
647
648
649 return null;
650 }
651 function doesFiberContain(parentFiber, childFiber) {
652 var node = childFiber;
653 var parentFiberAlternate = parentFiber.alternate;
654
655 while (node !== null) {
656 if (node === parentFiber || node === parentFiberAlternate) {
657 return true;
658 }
659
660 node = node.return;
661 }
662
663 return false;
664 }
665
666 // can re-export everything from this module.
667
668 function shim() {
669 {
670 {
671 throw Error( "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." );
672 }
673 }
674 } // Hydration (when unsupported)
675 var isSuspenseInstancePending = shim;
676 var isSuspenseInstanceFallback = shim;
677 var hydrateTextInstance = shim;
678
679 var NO_CONTEXT = {};
680 var UPDATE_SIGNAL = {};
681 var nodeToInstanceMap = new WeakMap();
682
683 {
684 Object.freeze(NO_CONTEXT);
685 Object.freeze(UPDATE_SIGNAL);
686 }
687
688 function getPublicInstance(inst) {
689 switch (inst.tag) {
690 case 'INSTANCE':
691 var createNodeMock = inst.rootContainerInstance.createNodeMock;
692 var mockNode = createNodeMock({
693 type: inst.type,
694 props: inst.props
695 });
696
697 if (typeof mockNode === 'object' && mockNode !== null) {
698 nodeToInstanceMap.set(mockNode, inst);
699 }
700
701 return mockNode;
702
703 default:
704 return inst;
705 }
706 }
707 function appendChild(parentInstance, child) {
708 {
709 if (!Array.isArray(parentInstance.children)) {
710 error('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.');
711 }
712 }
713
714 var index = parentInstance.children.indexOf(child);
715
716 if (index !== -1) {
717 parentInstance.children.splice(index, 1);
718 }
719
720 parentInstance.children.push(child);
721 }
722 function insertBefore(parentInstance, child, beforeChild) {
723 var index = parentInstance.children.indexOf(child);
724
725 if (index !== -1) {
726 parentInstance.children.splice(index, 1);
727 }
728
729 var beforeIndex = parentInstance.children.indexOf(beforeChild);
730 parentInstance.children.splice(beforeIndex, 0, child);
731 }
732 function removeChild(parentInstance, child) {
733 var index = parentInstance.children.indexOf(child);
734 parentInstance.children.splice(index, 1);
735 }
736 function clearContainer(container) {
737 container.children.splice(0);
738 }
739 function getRootHostContext(rootContainerInstance) {
740 return NO_CONTEXT;
741 }
742 function getChildHostContext(parentHostContext, type, rootContainerInstance) {
743 return NO_CONTEXT;
744 }
745 function prepareForCommit(containerInfo) {
746 // noop
747 return null;
748 }
749 function resetAfterCommit(containerInfo) {// noop
750 }
751 function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
752 return {
753 type: type,
754 props: props,
755 isHidden: false,
756 children: [],
757 internalInstanceHandle: internalInstanceHandle,
758 rootContainerInstance: rootContainerInstance,
759 tag: 'INSTANCE'
760 };
761 }
762 function appendInitialChild(parentInstance, child) {
763 var index = parentInstance.children.indexOf(child);
764
765 if (index !== -1) {
766 parentInstance.children.splice(index, 1);
767 }
768
769 parentInstance.children.push(child);
770 }
771 function prepareUpdate(testElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
772 return UPDATE_SIGNAL;
773 }
774 function shouldSetTextContent(type, props) {
775 return false;
776 }
777 function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
778 return {
779 text: text,
780 isHidden: false,
781 tag: 'TEXT'
782 };
783 }
784 var scheduleTimeout = setTimeout;
785 var cancelTimeout = clearTimeout;
786 var noTimeout = -1; // -------------------
787 function commitUpdate(instance, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
788 instance.type = type;
789 instance.props = newProps;
790 }
791 function commitTextUpdate(textInstance, oldText, newText) {
792 textInstance.text = newText;
793 }
794 function resetTextContent(testElement) {// noop
795 }
796 var appendChildToContainer = appendChild;
797 var insertInContainerBefore = insertBefore;
798 var removeChildFromContainer = removeChild;
799 function hideInstance(instance) {
800 instance.isHidden = true;
801 }
802 function hideTextInstance(textInstance) {
803 textInstance.isHidden = true;
804 }
805 function unhideInstance(instance, props) {
806 instance.isHidden = false;
807 }
808 function unhideTextInstance(textInstance, text) {
809 textInstance.isHidden = false;
810 }
811 var clientId = 0;
812 function makeClientIdInDEV(warnOnAccessInDEV) {
813 var id = 'c_' + (clientId++).toString(36);
814 return {
815 toString: function () {
816 warnOnAccessInDEV();
817 return id;
818 },
819 valueOf: function () {
820 warnOnAccessInDEV();
821 return id;
822 }
823 };
824 }
825 function preparePortalMount(portalInstance) {// noop
826 }
827
828 // Helpers to patch console.logs to avoid logging during side-effect free
829 // replaying on render function. This currently only patches the object
830 // lazily which won't cover if the log function was extracted eagerly.
831 // We could also eagerly patch the method.
832 var disabledDepth = 0;
833 var prevLog;
834 var prevInfo;
835 var prevWarn;
836 var prevError;
837 var prevGroup;
838 var prevGroupCollapsed;
839 var prevGroupEnd;
840
841 function disabledLog() {}
842
843 disabledLog.__reactDisabledLog = true;
844 function disableLogs() {
845 {
846 if (disabledDepth === 0) {
847 /* eslint-disable react-internal/no-production-logging */
848 prevLog = console.log;
849 prevInfo = console.info;
850 prevWarn = console.warn;
851 prevError = console.error;
852 prevGroup = console.group;
853 prevGroupCollapsed = console.groupCollapsed;
854 prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
855
856 var props = {
857 configurable: true,
858 enumerable: true,
859 value: disabledLog,
860 writable: true
861 }; // $FlowFixMe Flow thinks console is immutable.
862
863 Object.defineProperties(console, {
864 info: props,
865 log: props,
866 warn: props,
867 error: props,
868 group: props,
869 groupCollapsed: props,
870 groupEnd: props
871 });
872 /* eslint-enable react-internal/no-production-logging */
873 }
874
875 disabledDepth++;
876 }
877 }
878 function reenableLogs() {
879 {
880 disabledDepth--;
881
882 if (disabledDepth === 0) {
883 /* eslint-disable react-internal/no-production-logging */
884 var props = {
885 configurable: true,
886 enumerable: true,
887 writable: true
888 }; // $FlowFixMe Flow thinks console is immutable.
889
890 Object.defineProperties(console, {
891 log: _assign({}, props, {
892 value: prevLog
893 }),
894 info: _assign({}, props, {
895 value: prevInfo
896 }),
897 warn: _assign({}, props, {
898 value: prevWarn
899 }),
900 error: _assign({}, props, {
901 value: prevError
902 }),
903 group: _assign({}, props, {
904 value: prevGroup
905 }),
906 groupCollapsed: _assign({}, props, {
907 value: prevGroupCollapsed
908 }),
909 groupEnd: _assign({}, props, {
910 value: prevGroupEnd
911 })
912 });
913 /* eslint-enable react-internal/no-production-logging */
914 }
915
916 if (disabledDepth < 0) {
917 error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
918 }
919 }
920 }
921
922 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
923 var prefix;
924 function describeBuiltInComponentFrame(name, source, ownerFn) {
925 {
926 if (prefix === undefined) {
927 // Extract the VM specific prefix used by each line.
928 try {
929 throw Error();
930 } catch (x) {
931 var match = x.stack.trim().match(/\n( *(at )?)/);
932 prefix = match && match[1] || '';
933 }
934 } // We use the prefix to ensure our stacks line up with native stack frames.
935
936
937 return '\n' + prefix + name;
938 }
939 }
940 var reentry = false;
941 var componentFrameCache;
942
943 {
944 var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
945 componentFrameCache = new PossiblyWeakMap();
946 }
947
948 function describeNativeComponentFrame(fn, construct) {
949 // If something asked for a stack inside a fake render, it should get ignored.
950 if (!fn || reentry) {
951 return '';
952 }
953
954 {
955 var frame = componentFrameCache.get(fn);
956
957 if (frame !== undefined) {
958 return frame;
959 }
960 }
961
962 var control;
963 reentry = true;
964 var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
965
966 Error.prepareStackTrace = undefined;
967 var previousDispatcher;
968
969 {
970 previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
971 // for warnings.
972
973 ReactCurrentDispatcher.current = null;
974 disableLogs();
975 }
976
977 try {
978 // This should throw.
979 if (construct) {
980 // Something should be setting the props in the constructor.
981 var Fake = function () {
982 throw Error();
983 }; // $FlowFixMe
984
985
986 Object.defineProperty(Fake.prototype, 'props', {
987 set: function () {
988 // We use a throwing setter instead of frozen or non-writable props
989 // because that won't throw in a non-strict mode function.
990 throw Error();
991 }
992 });
993
994 if (typeof Reflect === 'object' && Reflect.construct) {
995 // We construct a different control for this case to include any extra
996 // frames added by the construct call.
997 try {
998 Reflect.construct(Fake, []);
999 } catch (x) {
1000 control = x;
1001 }
1002
1003 Reflect.construct(fn, [], Fake);
1004 } else {
1005 try {
1006 Fake.call();
1007 } catch (x) {
1008 control = x;
1009 }
1010
1011 fn.call(Fake.prototype);
1012 }
1013 } else {
1014 try {
1015 throw Error();
1016 } catch (x) {
1017 control = x;
1018 }
1019
1020 fn();
1021 }
1022 } catch (sample) {
1023 // This is inlined manually because closure doesn't do it for us.
1024 if (sample && control && typeof sample.stack === 'string') {
1025 // This extracts the first frame from the sample that isn't also in the control.
1026 // Skipping one frame that we assume is the frame that calls the two.
1027 var sampleLines = sample.stack.split('\n');
1028 var controlLines = control.stack.split('\n');
1029 var s = sampleLines.length - 1;
1030 var c = controlLines.length - 1;
1031
1032 while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
1033 // We expect at least one stack frame to be shared.
1034 // Typically this will be the root most one. However, stack frames may be
1035 // cut off due to maximum stack limits. In this case, one maybe cut off
1036 // earlier than the other. We assume that the sample is longer or the same
1037 // and there for cut off earlier. So we should find the root most frame in
1038 // the sample somewhere in the control.
1039 c--;
1040 }
1041
1042 for (; s >= 1 && c >= 0; s--, c--) {
1043 // Next we find the first one that isn't the same which should be the
1044 // frame that called our sample function and the control.
1045 if (sampleLines[s] !== controlLines[c]) {
1046 // In V8, the first line is describing the message but other VMs don't.
1047 // If we're about to return the first line, and the control is also on the same
1048 // line, that's a pretty good indicator that our sample threw at same line as
1049 // the control. I.e. before we entered the sample frame. So we ignore this result.
1050 // This can happen if you passed a class to function component, or non-function.
1051 if (s !== 1 || c !== 1) {
1052 do {
1053 s--;
1054 c--; // We may still have similar intermediate frames from the construct call.
1055 // The next one that isn't the same should be our match though.
1056
1057 if (c < 0 || sampleLines[s] !== controlLines[c]) {
1058 // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
1059 var _frame = '\n' + sampleLines[s].replace(' at new ', ' at ');
1060
1061 {
1062 if (typeof fn === 'function') {
1063 componentFrameCache.set(fn, _frame);
1064 }
1065 } // Return the line we found.
1066
1067
1068 return _frame;
1069 }
1070 } while (s >= 1 && c >= 0);
1071 }
1072
1073 break;
1074 }
1075 }
1076 }
1077 } finally {
1078 reentry = false;
1079
1080 {
1081 ReactCurrentDispatcher.current = previousDispatcher;
1082 reenableLogs();
1083 }
1084
1085 Error.prepareStackTrace = previousPrepareStackTrace;
1086 } // Fallback to just using the name if we couldn't make it throw.
1087
1088
1089 var name = fn ? fn.displayName || fn.name : '';
1090 var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
1091
1092 {
1093 if (typeof fn === 'function') {
1094 componentFrameCache.set(fn, syntheticFrame);
1095 }
1096 }
1097
1098 return syntheticFrame;
1099 }
1100
1101 function describeClassComponentFrame(ctor, source, ownerFn) {
1102 {
1103 return describeNativeComponentFrame(ctor, true);
1104 }
1105 }
1106 function describeFunctionComponentFrame(fn, source, ownerFn) {
1107 {
1108 return describeNativeComponentFrame(fn, false);
1109 }
1110 }
1111
1112 function shouldConstruct(Component) {
1113 var prototype = Component.prototype;
1114 return !!(prototype && prototype.isReactComponent);
1115 }
1116
1117 function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
1118
1119 if (type == null) {
1120 return '';
1121 }
1122
1123 if (typeof type === 'function') {
1124 {
1125 return describeNativeComponentFrame(type, shouldConstruct(type));
1126 }
1127 }
1128
1129 if (typeof type === 'string') {
1130 return describeBuiltInComponentFrame(type);
1131 }
1132
1133 switch (type) {
1134 case REACT_SUSPENSE_TYPE:
1135 return describeBuiltInComponentFrame('Suspense');
1136
1137 case REACT_SUSPENSE_LIST_TYPE:
1138 return describeBuiltInComponentFrame('SuspenseList');
1139 }
1140
1141 if (typeof type === 'object') {
1142 switch (type.$$typeof) {
1143 case REACT_FORWARD_REF_TYPE:
1144 return describeFunctionComponentFrame(type.render);
1145
1146 case REACT_MEMO_TYPE:
1147 // Memo may contain any component type so we recursively resolve it.
1148 return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
1149
1150 case REACT_BLOCK_TYPE:
1151 return describeFunctionComponentFrame(type._render);
1152
1153 case REACT_LAZY_TYPE:
1154 {
1155 var lazyComponent = type;
1156 var payload = lazyComponent._payload;
1157 var init = lazyComponent._init;
1158
1159 try {
1160 // Lazy may contain any component type so we recursively resolve it.
1161 return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
1162 } catch (x) {}
1163 }
1164 }
1165 }
1166
1167 return '';
1168 }
1169
1170 var loggedTypeFailures = {};
1171 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
1172
1173 function setCurrentlyValidatingElement(element) {
1174 {
1175 if (element) {
1176 var owner = element._owner;
1177 var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
1178 ReactDebugCurrentFrame.setExtraStackFrame(stack);
1179 } else {
1180 ReactDebugCurrentFrame.setExtraStackFrame(null);
1181 }
1182 }
1183 }
1184
1185 function checkPropTypes(typeSpecs, values, location, componentName, element) {
1186 {
1187 // $FlowFixMe This is okay but Flow doesn't know it.
1188 var has = Function.call.bind(Object.prototype.hasOwnProperty);
1189
1190 for (var typeSpecName in typeSpecs) {
1191 if (has(typeSpecs, typeSpecName)) {
1192 var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
1193 // fail the render phase where it didn't fail before. So we log it.
1194 // After these have been cleaned up, we'll let them throw.
1195
1196 try {
1197 // This is intentionally an invariant that gets caught. It's the same
1198 // behavior as without this statement except with a better message.
1199 if (typeof typeSpecs[typeSpecName] !== 'function') {
1200 var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
1201 err.name = 'Invariant Violation';
1202 throw err;
1203 }
1204
1205 error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
1206 } catch (ex) {
1207 error$1 = ex;
1208 }
1209
1210 if (error$1 && !(error$1 instanceof Error)) {
1211 setCurrentlyValidatingElement(element);
1212
1213 error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
1214
1215 setCurrentlyValidatingElement(null);
1216 }
1217
1218 if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
1219 // Only monitor this failure once because there tends to be a lot of the
1220 // same error.
1221 loggedTypeFailures[error$1.message] = true;
1222 setCurrentlyValidatingElement(element);
1223
1224 error('Failed %s type: %s', location, error$1.message);
1225
1226 setCurrentlyValidatingElement(null);
1227 }
1228 }
1229 }
1230 }
1231 }
1232
1233 var valueStack = [];
1234 var fiberStack;
1235
1236 {
1237 fiberStack = [];
1238 }
1239
1240 var index = -1;
1241
1242 function createCursor(defaultValue) {
1243 return {
1244 current: defaultValue
1245 };
1246 }
1247
1248 function pop(cursor, fiber) {
1249 if (index < 0) {
1250 {
1251 error('Unexpected pop.');
1252 }
1253
1254 return;
1255 }
1256
1257 {
1258 if (fiber !== fiberStack[index]) {
1259 error('Unexpected Fiber popped.');
1260 }
1261 }
1262
1263 cursor.current = valueStack[index];
1264 valueStack[index] = null;
1265
1266 {
1267 fiberStack[index] = null;
1268 }
1269
1270 index--;
1271 }
1272
1273 function push(cursor, value, fiber) {
1274 index++;
1275 valueStack[index] = cursor.current;
1276
1277 {
1278 fiberStack[index] = fiber;
1279 }
1280
1281 cursor.current = value;
1282 }
1283
1284 var warnedAboutMissingGetChildContext;
1285
1286 {
1287 warnedAboutMissingGetChildContext = {};
1288 }
1289
1290 var emptyContextObject = {};
1291
1292 {
1293 Object.freeze(emptyContextObject);
1294 } // A cursor to the current merged context object on the stack.
1295
1296
1297 var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed.
1298
1299 var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack.
1300 // We use this to get access to the parent context after we have already
1301 // pushed the next context provider, and now need to merge their contexts.
1302
1303 var previousContext = emptyContextObject;
1304
1305 function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
1306 {
1307 if (didPushOwnContextIfProvider && isContextProvider(Component)) {
1308 // If the fiber is a context provider itself, when we read its context
1309 // we may have already pushed its own child context on the stack. A context
1310 // provider should not "see" its own child context. Therefore we read the
1311 // previous (parent) context instead for a context provider.
1312 return previousContext;
1313 }
1314
1315 return contextStackCursor.current;
1316 }
1317 }
1318
1319 function cacheContext(workInProgress, unmaskedContext, maskedContext) {
1320 {
1321 var instance = workInProgress.stateNode;
1322 instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
1323 instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
1324 }
1325 }
1326
1327 function getMaskedContext(workInProgress, unmaskedContext) {
1328 {
1329 var type = workInProgress.type;
1330 var contextTypes = type.contextTypes;
1331
1332 if (!contextTypes) {
1333 return emptyContextObject;
1334 } // Avoid recreating masked context unless unmasked context has changed.
1335 // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
1336 // This may trigger infinite loops if componentWillReceiveProps calls setState.
1337
1338
1339 var instance = workInProgress.stateNode;
1340
1341 if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
1342 return instance.__reactInternalMemoizedMaskedChildContext;
1343 }
1344
1345 var context = {};
1346
1347 for (var key in contextTypes) {
1348 context[key] = unmaskedContext[key];
1349 }
1350
1351 {
1352 var name = getComponentName(type) || 'Unknown';
1353 checkPropTypes(contextTypes, context, 'context', name);
1354 } // Cache unmasked context so we can avoid recreating masked context unless necessary.
1355 // Context is created before the class component is instantiated so check for instance.
1356
1357
1358 if (instance) {
1359 cacheContext(workInProgress, unmaskedContext, context);
1360 }
1361
1362 return context;
1363 }
1364 }
1365
1366 function hasContextChanged() {
1367 {
1368 return didPerformWorkStackCursor.current;
1369 }
1370 }
1371
1372 function isContextProvider(type) {
1373 {
1374 var childContextTypes = type.childContextTypes;
1375 return childContextTypes !== null && childContextTypes !== undefined;
1376 }
1377 }
1378
1379 function popContext(fiber) {
1380 {
1381 pop(didPerformWorkStackCursor, fiber);
1382 pop(contextStackCursor, fiber);
1383 }
1384 }
1385
1386 function popTopLevelContextObject(fiber) {
1387 {
1388 pop(didPerformWorkStackCursor, fiber);
1389 pop(contextStackCursor, fiber);
1390 }
1391 }
1392
1393 function pushTopLevelContextObject(fiber, context, didChange) {
1394 {
1395 if (!(contextStackCursor.current === emptyContextObject)) {
1396 {
1397 throw Error( "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." );
1398 }
1399 }
1400
1401 push(contextStackCursor, context, fiber);
1402 push(didPerformWorkStackCursor, didChange, fiber);
1403 }
1404 }
1405
1406 function processChildContext(fiber, type, parentContext) {
1407 {
1408 var instance = fiber.stateNode;
1409 var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future.
1410 // It has only been added in Fiber to match the (unintentional) behavior in Stack.
1411
1412 if (typeof instance.getChildContext !== 'function') {
1413 {
1414 var componentName = getComponentName(type) || 'Unknown';
1415
1416 if (!warnedAboutMissingGetChildContext[componentName]) {
1417 warnedAboutMissingGetChildContext[componentName] = true;
1418
1419 error('%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);
1420 }
1421 }
1422
1423 return parentContext;
1424 }
1425
1426 var childContext = instance.getChildContext();
1427
1428 for (var contextKey in childContext) {
1429 if (!(contextKey in childContextTypes)) {
1430 {
1431 throw Error( (getComponentName(type) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes." );
1432 }
1433 }
1434 }
1435
1436 {
1437 var name = getComponentName(type) || 'Unknown';
1438 checkPropTypes(childContextTypes, childContext, 'child context', name);
1439 }
1440
1441 return _assign({}, parentContext, childContext);
1442 }
1443 }
1444
1445 function pushContextProvider(workInProgress) {
1446 {
1447 var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity.
1448 // If the instance does not exist yet, we will push null at first,
1449 // and replace it on the stack later when invalidating the context.
1450
1451 var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later.
1452 // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
1453
1454 previousContext = contextStackCursor.current;
1455 push(contextStackCursor, memoizedMergedChildContext, workInProgress);
1456 push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
1457 return true;
1458 }
1459 }
1460
1461 function invalidateContextProvider(workInProgress, type, didChange) {
1462 {
1463 var instance = workInProgress.stateNode;
1464
1465 if (!instance) {
1466 {
1467 throw Error( "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." );
1468 }
1469 }
1470
1471 if (didChange) {
1472 // Merge parent and own context.
1473 // Skip this if we're not updating due to sCU.
1474 // This avoids unnecessarily recomputing memoized values.
1475 var mergedContext = processChildContext(workInProgress, type, previousContext);
1476 instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one.
1477 // It is important to unwind the context in the reverse order.
1478
1479 pop(didPerformWorkStackCursor, workInProgress);
1480 pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed.
1481
1482 push(contextStackCursor, mergedContext, workInProgress);
1483 push(didPerformWorkStackCursor, didChange, workInProgress);
1484 } else {
1485 pop(didPerformWorkStackCursor, workInProgress);
1486 push(didPerformWorkStackCursor, didChange, workInProgress);
1487 }
1488 }
1489 }
1490
1491 function findCurrentUnmaskedContext(fiber) {
1492 {
1493 // Currently this is only used with renderSubtreeIntoContainer; not sure if it
1494 // makes sense elsewhere
1495 if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) {
1496 {
1497 throw Error( "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." );
1498 }
1499 }
1500
1501 var node = fiber;
1502
1503 do {
1504 switch (node.tag) {
1505 case HostRoot:
1506 return node.stateNode.context;
1507
1508 case ClassComponent:
1509 {
1510 var Component = node.type;
1511
1512 if (isContextProvider(Component)) {
1513 return node.stateNode.__reactInternalMemoizedMergedChildContext;
1514 }
1515
1516 break;
1517 }
1518 }
1519
1520 node = node.return;
1521 } while (node !== null);
1522
1523 {
1524 {
1525 throw Error( "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." );
1526 }
1527 }
1528 }
1529 }
1530
1531 var LegacyRoot = 0;
1532 var BlockingRoot = 1;
1533 var ConcurrentRoot = 2;
1534
1535 var rendererID = null;
1536 var injectedHook = null;
1537 var hasLoggedError = false;
1538 var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
1539 function injectInternals(internals) {
1540 if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
1541 // No DevTools
1542 return false;
1543 }
1544
1545 var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
1546
1547 if (hook.isDisabled) {
1548 // This isn't a real property on the hook, but it can be set to opt out
1549 // of DevTools integration and associated warnings and logs.
1550 // https://github.com/facebook/react/issues/3877
1551 return true;
1552 }
1553
1554 if (!hook.supportsFiber) {
1555 {
1556 error('The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://reactjs.org/link/react-devtools');
1557 } // DevTools exists, even though it doesn't support Fiber.
1558
1559
1560 return true;
1561 }
1562
1563 try {
1564 rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks.
1565
1566 injectedHook = hook;
1567 } catch (err) {
1568 // Catch all errors because it is unsafe to throw during initialization.
1569 {
1570 error('React instrumentation encountered an error: %s.', err);
1571 }
1572 } // DevTools exists
1573
1574
1575 return true;
1576 }
1577 function onScheduleRoot(root, children) {
1578 {
1579 if (injectedHook && typeof injectedHook.onScheduleFiberRoot === 'function') {
1580 try {
1581 injectedHook.onScheduleFiberRoot(rendererID, root, children);
1582 } catch (err) {
1583 if ( !hasLoggedError) {
1584 hasLoggedError = true;
1585
1586 error('React instrumentation encountered an error: %s', err);
1587 }
1588 }
1589 }
1590 }
1591 }
1592 function onCommitRoot(root, priorityLevel) {
1593 if (injectedHook && typeof injectedHook.onCommitFiberRoot === 'function') {
1594 try {
1595 var didError = (root.current.flags & DidCapture) === DidCapture;
1596
1597 if (enableProfilerTimer) {
1598 injectedHook.onCommitFiberRoot(rendererID, root, priorityLevel, didError);
1599 } else {
1600 injectedHook.onCommitFiberRoot(rendererID, root, undefined, didError);
1601 }
1602 } catch (err) {
1603 {
1604 if (!hasLoggedError) {
1605 hasLoggedError = true;
1606
1607 error('React instrumentation encountered an error: %s', err);
1608 }
1609 }
1610 }
1611 }
1612 }
1613 function onCommitUnmount(fiber) {
1614 if (injectedHook && typeof injectedHook.onCommitFiberUnmount === 'function') {
1615 try {
1616 injectedHook.onCommitFiberUnmount(rendererID, fiber);
1617 } catch (err) {
1618 {
1619 if (!hasLoggedError) {
1620 hasLoggedError = true;
1621
1622 error('React instrumentation encountered an error: %s', err);
1623 }
1624 }
1625 }
1626 }
1627 }
1628
1629 var ReactInternals$1 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
1630 var _ReactInternals$Sched = ReactInternals$1.SchedulerTracing,
1631 __interactionsRef = _ReactInternals$Sched.__interactionsRef,
1632 __subscriberRef = _ReactInternals$Sched.__subscriberRef,
1633 unstable_clear = _ReactInternals$Sched.unstable_clear,
1634 unstable_getCurrent = _ReactInternals$Sched.unstable_getCurrent,
1635 unstable_getThreadID = _ReactInternals$Sched.unstable_getThreadID,
1636 unstable_subscribe = _ReactInternals$Sched.unstable_subscribe,
1637 unstable_trace = _ReactInternals$Sched.unstable_trace,
1638 unstable_unsubscribe = _ReactInternals$Sched.unstable_unsubscribe,
1639 unstable_wrap = _ReactInternals$Sched.unstable_wrap;
1640
1641 var Scheduler_now = Scheduler$1.unstable_now;
1642
1643 {
1644 // Provide explicit error message when production+profiling bundle of e.g.
1645 // react-dom is used with production (non-profiling) bundle of
1646 // scheduler/tracing
1647 if (!(__interactionsRef != null && __interactionsRef.current != null)) {
1648 {
1649 throw Error( "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 https://reactjs.org/link/profiling" );
1650 }
1651 }
1652 }
1653 // ascending numbers so we can compare them like numbers. They start at 90 to
1654 // avoid clashing with Scheduler's priorities.
1655
1656 var ImmediatePriority = 99;
1657 var UserBlockingPriority = 98;
1658 var NormalPriority = 97;
1659 var LowPriority = 96;
1660 var IdlePriority = 95; // NoPriority is the absence of priority. Also React-only.
1661
1662 var NoPriority = 90;
1663 var initialTimeMs = Scheduler_now(); // If the initial timestamp is reasonably small, use Scheduler's `now` directly.
1664
1665 var SyncLanePriority = 15;
1666 var SyncBatchedLanePriority = 14;
1667 var InputDiscreteHydrationLanePriority = 13;
1668 var InputDiscreteLanePriority = 12;
1669 var InputContinuousHydrationLanePriority = 11;
1670 var InputContinuousLanePriority = 10;
1671 var DefaultHydrationLanePriority = 9;
1672 var DefaultLanePriority = 8;
1673 var TransitionHydrationPriority = 7;
1674 var TransitionPriority = 6;
1675 var RetryLanePriority = 5;
1676 var SelectiveHydrationLanePriority = 4;
1677 var IdleHydrationLanePriority = 3;
1678 var IdleLanePriority = 2;
1679 var OffscreenLanePriority = 1;
1680 var NoLanePriority = 0;
1681 var TotalLanes = 31;
1682 var NoLanes =
1683 /* */
1684 0;
1685 var NoLane =
1686 /* */
1687 0;
1688 var SyncLane =
1689 /* */
1690 1;
1691 var SyncBatchedLane =
1692 /* */
1693 2;
1694 var InputDiscreteHydrationLane =
1695 /* */
1696 4;
1697 var InputDiscreteLanes =
1698 /* */
1699 24;
1700 var InputContinuousHydrationLane =
1701 /* */
1702 32;
1703 var InputContinuousLanes =
1704 /* */
1705 192;
1706 var DefaultHydrationLane =
1707 /* */
1708 256;
1709 var DefaultLanes =
1710 /* */
1711 3584;
1712 var TransitionHydrationLane =
1713 /* */
1714 4096;
1715 var TransitionLanes =
1716 /* */
1717 4186112;
1718 var RetryLanes =
1719 /* */
1720 62914560;
1721 var SomeRetryLane =
1722 /* */
1723 33554432;
1724 var SelectiveHydrationLane =
1725 /* */
1726 67108864;
1727 var NonIdleLanes =
1728 /* */
1729 134217727;
1730 var IdleHydrationLane =
1731 /* */
1732 134217728;
1733 var IdleLanes =
1734 /* */
1735 805306368;
1736 var OffscreenLane =
1737 /* */
1738 1073741824;
1739 var NoTimestamp = -1;
1740 // Used by getHighestPriorityLanes and getNextLanes:
1741
1742 var return_highestLanePriority = DefaultLanePriority;
1743
1744 function getHighestPriorityLanes(lanes) {
1745 if ((SyncLane & lanes) !== NoLanes) {
1746 return_highestLanePriority = SyncLanePriority;
1747 return SyncLane;
1748 }
1749
1750 if ((SyncBatchedLane & lanes) !== NoLanes) {
1751 return_highestLanePriority = SyncBatchedLanePriority;
1752 return SyncBatchedLane;
1753 }
1754
1755 if ((InputDiscreteHydrationLane & lanes) !== NoLanes) {
1756 return_highestLanePriority = InputDiscreteHydrationLanePriority;
1757 return InputDiscreteHydrationLane;
1758 }
1759
1760 var inputDiscreteLanes = InputDiscreteLanes & lanes;
1761
1762 if (inputDiscreteLanes !== NoLanes) {
1763 return_highestLanePriority = InputDiscreteLanePriority;
1764 return inputDiscreteLanes;
1765 }
1766
1767 if ((lanes & InputContinuousHydrationLane) !== NoLanes) {
1768 return_highestLanePriority = InputContinuousHydrationLanePriority;
1769 return InputContinuousHydrationLane;
1770 }
1771
1772 var inputContinuousLanes = InputContinuousLanes & lanes;
1773
1774 if (inputContinuousLanes !== NoLanes) {
1775 return_highestLanePriority = InputContinuousLanePriority;
1776 return inputContinuousLanes;
1777 }
1778
1779 if ((lanes & DefaultHydrationLane) !== NoLanes) {
1780 return_highestLanePriority = DefaultHydrationLanePriority;
1781 return DefaultHydrationLane;
1782 }
1783
1784 var defaultLanes = DefaultLanes & lanes;
1785
1786 if (defaultLanes !== NoLanes) {
1787 return_highestLanePriority = DefaultLanePriority;
1788 return defaultLanes;
1789 }
1790
1791 if ((lanes & TransitionHydrationLane) !== NoLanes) {
1792 return_highestLanePriority = TransitionHydrationPriority;
1793 return TransitionHydrationLane;
1794 }
1795
1796 var transitionLanes = TransitionLanes & lanes;
1797
1798 if (transitionLanes !== NoLanes) {
1799 return_highestLanePriority = TransitionPriority;
1800 return transitionLanes;
1801 }
1802
1803 var retryLanes = RetryLanes & lanes;
1804
1805 if (retryLanes !== NoLanes) {
1806 return_highestLanePriority = RetryLanePriority;
1807 return retryLanes;
1808 }
1809
1810 if (lanes & SelectiveHydrationLane) {
1811 return_highestLanePriority = SelectiveHydrationLanePriority;
1812 return SelectiveHydrationLane;
1813 }
1814
1815 if ((lanes & IdleHydrationLane) !== NoLanes) {
1816 return_highestLanePriority = IdleHydrationLanePriority;
1817 return IdleHydrationLane;
1818 }
1819
1820 var idleLanes = IdleLanes & lanes;
1821
1822 if (idleLanes !== NoLanes) {
1823 return_highestLanePriority = IdleLanePriority;
1824 return idleLanes;
1825 }
1826
1827 if ((OffscreenLane & lanes) !== NoLanes) {
1828 return_highestLanePriority = OffscreenLanePriority;
1829 return OffscreenLane;
1830 }
1831
1832 {
1833 error('Should have found matching lanes. This is a bug in React.');
1834 } // This shouldn't be reachable, but as a fallback, return the entire bitmask.
1835
1836
1837 return_highestLanePriority = DefaultLanePriority;
1838 return lanes;
1839 }
1840
1841 function schedulerPriorityToLanePriority(schedulerPriorityLevel) {
1842 switch (schedulerPriorityLevel) {
1843 case ImmediatePriority:
1844 return SyncLanePriority;
1845
1846 case UserBlockingPriority:
1847 return InputContinuousLanePriority;
1848
1849 case NormalPriority:
1850 case LowPriority:
1851 // TODO: Handle LowSchedulerPriority, somehow. Maybe the same lane as hydration.
1852 return DefaultLanePriority;
1853
1854 case IdlePriority:
1855 return IdleLanePriority;
1856
1857 default:
1858 return NoLanePriority;
1859 }
1860 }
1861 function lanePriorityToSchedulerPriority(lanePriority) {
1862 switch (lanePriority) {
1863 case SyncLanePriority:
1864 case SyncBatchedLanePriority:
1865 return ImmediatePriority;
1866
1867 case InputDiscreteHydrationLanePriority:
1868 case InputDiscreteLanePriority:
1869 case InputContinuousHydrationLanePriority:
1870 case InputContinuousLanePriority:
1871 return UserBlockingPriority;
1872
1873 case DefaultHydrationLanePriority:
1874 case DefaultLanePriority:
1875 case TransitionHydrationPriority:
1876 case TransitionPriority:
1877 case SelectiveHydrationLanePriority:
1878 case RetryLanePriority:
1879 return NormalPriority;
1880
1881 case IdleHydrationLanePriority:
1882 case IdleLanePriority:
1883 case OffscreenLanePriority:
1884 return IdlePriority;
1885
1886 case NoLanePriority:
1887 return NoPriority;
1888
1889 default:
1890 {
1891 {
1892 throw Error( "Invalid update priority: " + lanePriority + ". This is a bug in React." );
1893 }
1894 }
1895
1896 }
1897 }
1898 function getNextLanes(root, wipLanes) {
1899 // Early bailout if there's no pending work left.
1900 var pendingLanes = root.pendingLanes;
1901
1902 if (pendingLanes === NoLanes) {
1903 return_highestLanePriority = NoLanePriority;
1904 return NoLanes;
1905 }
1906
1907 var nextLanes = NoLanes;
1908 var nextLanePriority = NoLanePriority;
1909 var expiredLanes = root.expiredLanes;
1910 var suspendedLanes = root.suspendedLanes;
1911 var pingedLanes = root.pingedLanes; // Check if any work has expired.
1912
1913 if (expiredLanes !== NoLanes) {
1914 nextLanes = expiredLanes;
1915 nextLanePriority = return_highestLanePriority = SyncLanePriority;
1916 } else {
1917 // Do not work on any idle work until all the non-idle work has finished,
1918 // even if the work is suspended.
1919 var nonIdlePendingLanes = pendingLanes & NonIdleLanes;
1920
1921 if (nonIdlePendingLanes !== NoLanes) {
1922 var nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes;
1923
1924 if (nonIdleUnblockedLanes !== NoLanes) {
1925 nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes);
1926 nextLanePriority = return_highestLanePriority;
1927 } else {
1928 var nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes;
1929
1930 if (nonIdlePingedLanes !== NoLanes) {
1931 nextLanes = getHighestPriorityLanes(nonIdlePingedLanes);
1932 nextLanePriority = return_highestLanePriority;
1933 }
1934 }
1935 } else {
1936 // The only remaining work is Idle.
1937 var unblockedLanes = pendingLanes & ~suspendedLanes;
1938
1939 if (unblockedLanes !== NoLanes) {
1940 nextLanes = getHighestPriorityLanes(unblockedLanes);
1941 nextLanePriority = return_highestLanePriority;
1942 } else {
1943 if (pingedLanes !== NoLanes) {
1944 nextLanes = getHighestPriorityLanes(pingedLanes);
1945 nextLanePriority = return_highestLanePriority;
1946 }
1947 }
1948 }
1949 }
1950
1951 if (nextLanes === NoLanes) {
1952 // This should only be reachable if we're suspended
1953 // TODO: Consider warning in this path if a fallback timer is not scheduled.
1954 return NoLanes;
1955 } // If there are higher priority lanes, we'll include them even if they
1956 // are suspended.
1957
1958
1959 nextLanes = pendingLanes & getEqualOrHigherPriorityLanes(nextLanes); // If we're already in the middle of a render, switching lanes will interrupt
1960 // it and we'll lose our progress. We should only do this if the new lanes are
1961 // higher priority.
1962
1963 if (wipLanes !== NoLanes && wipLanes !== nextLanes && // If we already suspended with a delay, then interrupting is fine. Don't
1964 // bother waiting until the root is complete.
1965 (wipLanes & suspendedLanes) === NoLanes) {
1966 getHighestPriorityLanes(wipLanes);
1967 var wipLanePriority = return_highestLanePriority;
1968
1969 if (nextLanePriority <= wipLanePriority) {
1970 return wipLanes;
1971 } else {
1972 return_highestLanePriority = nextLanePriority;
1973 }
1974 } // Check for entangled lanes and add them to the batch.
1975 //
1976 // A lane is said to be entangled with another when it's not allowed to render
1977 // in a batch that does not also include the other lane. Typically we do this
1978 // when multiple updates have the same source, and we only want to respond to
1979 // the most recent event from that source.
1980 //
1981 // Note that we apply entanglements *after* checking for partial work above.
1982 // This means that if a lane is entangled during an interleaved event while
1983 // it's already rendering, we won't interrupt it. This is intentional, since
1984 // entanglement is usually "best effort": we'll try our best to render the
1985 // lanes in the same batch, but it's not worth throwing out partially
1986 // completed work in order to do it.
1987 //
1988 // For those exceptions where entanglement is semantically important, like
1989 // useMutableSource, we should ensure that there is no partial work at the
1990 // time we apply the entanglement.
1991
1992
1993 var entangledLanes = root.entangledLanes;
1994
1995 if (entangledLanes !== NoLanes) {
1996 var entanglements = root.entanglements;
1997 var lanes = nextLanes & entangledLanes;
1998
1999 while (lanes > 0) {
2000 var index = pickArbitraryLaneIndex(lanes);
2001 var lane = 1 << index;
2002 nextLanes |= entanglements[index];
2003 lanes &= ~lane;
2004 }
2005 }
2006
2007 return nextLanes;
2008 }
2009 function getMostRecentEventTime(root, lanes) {
2010 var eventTimes = root.eventTimes;
2011 var mostRecentEventTime = NoTimestamp;
2012
2013 while (lanes > 0) {
2014 var index = pickArbitraryLaneIndex(lanes);
2015 var lane = 1 << index;
2016 var eventTime = eventTimes[index];
2017
2018 if (eventTime > mostRecentEventTime) {
2019 mostRecentEventTime = eventTime;
2020 }
2021
2022 lanes &= ~lane;
2023 }
2024
2025 return mostRecentEventTime;
2026 }
2027
2028 function computeExpirationTime(lane, currentTime) {
2029 // TODO: Expiration heuristic is constant per lane, so could use a map.
2030 getHighestPriorityLanes(lane);
2031 var priority = return_highestLanePriority;
2032
2033 if (priority >= InputContinuousLanePriority) {
2034 // User interactions should expire slightly more quickly.
2035 //
2036 // NOTE: This is set to the corresponding constant as in Scheduler.js. When
2037 // we made it larger, a product metric in www regressed, suggesting there's
2038 // a user interaction that's being starved by a series of synchronous
2039 // updates. If that theory is correct, the proper solution is to fix the
2040 // starvation. However, this scenario supports the idea that expiration
2041 // times are an important safeguard when starvation does happen.
2042 //
2043 // Also note that, in the case of user input specifically, this will soon no
2044 // longer be an issue because we plan to make user input synchronous by
2045 // default (until you enter `startTransition`, of course.)
2046 //
2047 // If weren't planning to make these updates synchronous soon anyway, I
2048 // would probably make this number a configurable parameter.
2049 return currentTime + 250;
2050 } else if (priority >= TransitionPriority) {
2051 return currentTime + 5000;
2052 } else {
2053 // Anything idle priority or lower should never expire.
2054 return NoTimestamp;
2055 }
2056 }
2057
2058 function markStarvedLanesAsExpired(root, currentTime) {
2059 // TODO: This gets called every time we yield. We can optimize by storing
2060 // the earliest expiration time on the root. Then use that to quickly bail out
2061 // of this function.
2062 var pendingLanes = root.pendingLanes;
2063 var suspendedLanes = root.suspendedLanes;
2064 var pingedLanes = root.pingedLanes;
2065 var expirationTimes = root.expirationTimes; // Iterate through the pending lanes and check if we've reached their
2066 // expiration time. If so, we'll assume the update is being starved and mark
2067 // it as expired to force it to finish.
2068
2069 var lanes = pendingLanes;
2070
2071 while (lanes > 0) {
2072 var index = pickArbitraryLaneIndex(lanes);
2073 var lane = 1 << index;
2074 var expirationTime = expirationTimes[index];
2075
2076 if (expirationTime === NoTimestamp) {
2077 // Found a pending lane with no expiration time. If it's not suspended, or
2078 // if it's pinged, assume it's CPU-bound. Compute a new expiration time
2079 // using the current time.
2080 if ((lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes) {
2081 // Assumes timestamps are monotonically increasing.
2082 expirationTimes[index] = computeExpirationTime(lane, currentTime);
2083 }
2084 } else if (expirationTime <= currentTime) {
2085 // This lane expired
2086 root.expiredLanes |= lane;
2087 }
2088
2089 lanes &= ~lane;
2090 }
2091 } // This returns the highest priority pending lanes regardless of whether they
2092 function getLanesToRetrySynchronouslyOnError(root) {
2093 var everythingButOffscreen = root.pendingLanes & ~OffscreenLane;
2094
2095 if (everythingButOffscreen !== NoLanes) {
2096 return everythingButOffscreen;
2097 }
2098
2099 if (everythingButOffscreen & OffscreenLane) {
2100 return OffscreenLane;
2101 }
2102
2103 return NoLanes;
2104 }
2105 function returnNextLanesPriority() {
2106 return return_highestLanePriority;
2107 }
2108 function includesNonIdleWork(lanes) {
2109 return (lanes & NonIdleLanes) !== NoLanes;
2110 }
2111 function includesOnlyRetries(lanes) {
2112 return (lanes & RetryLanes) === lanes;
2113 }
2114 function includesOnlyTransitions(lanes) {
2115 return (lanes & TransitionLanes) === lanes;
2116 } // To ensure consistency across multiple updates in the same event, this should
2117 // be a pure function, so that it always returns the same lane for given inputs.
2118
2119 function findUpdateLane(lanePriority, wipLanes) {
2120 switch (lanePriority) {
2121 case NoLanePriority:
2122 break;
2123
2124 case SyncLanePriority:
2125 return SyncLane;
2126
2127 case SyncBatchedLanePriority:
2128 return SyncBatchedLane;
2129
2130 case InputDiscreteLanePriority:
2131 {
2132 var _lane = pickArbitraryLane(InputDiscreteLanes & ~wipLanes);
2133
2134 if (_lane === NoLane) {
2135 // Shift to the next priority level
2136 return findUpdateLane(InputContinuousLanePriority, wipLanes);
2137 }
2138
2139 return _lane;
2140 }
2141
2142 case InputContinuousLanePriority:
2143 {
2144 var _lane2 = pickArbitraryLane(InputContinuousLanes & ~wipLanes);
2145
2146 if (_lane2 === NoLane) {
2147 // Shift to the next priority level
2148 return findUpdateLane(DefaultLanePriority, wipLanes);
2149 }
2150
2151 return _lane2;
2152 }
2153
2154 case DefaultLanePriority:
2155 {
2156 var _lane3 = pickArbitraryLane(DefaultLanes & ~wipLanes);
2157
2158 if (_lane3 === NoLane) {
2159 // If all the default lanes are already being worked on, look for a
2160 // lane in the transition range.
2161 _lane3 = pickArbitraryLane(TransitionLanes & ~wipLanes);
2162
2163 if (_lane3 === NoLane) {
2164 // All the transition lanes are taken, too. This should be very
2165 // rare, but as a last resort, pick a default lane. This will have
2166 // the effect of interrupting the current work-in-progress render.
2167 _lane3 = pickArbitraryLane(DefaultLanes);
2168 }
2169 }
2170
2171 return _lane3;
2172 }
2173
2174 case TransitionPriority: // Should be handled by findTransitionLane instead
2175
2176 case RetryLanePriority:
2177 // Should be handled by findRetryLane instead
2178 break;
2179
2180 case IdleLanePriority:
2181 var lane = pickArbitraryLane(IdleLanes & ~wipLanes);
2182
2183 if (lane === NoLane) {
2184 lane = pickArbitraryLane(IdleLanes);
2185 }
2186
2187 return lane;
2188 }
2189
2190 {
2191 {
2192 throw Error( "Invalid update priority: " + lanePriority + ". This is a bug in React." );
2193 }
2194 }
2195 } // To ensure consistency across multiple updates in the same event, this should
2196 // be pure function, so that it always returns the same lane for given inputs.
2197
2198 function findTransitionLane(wipLanes, pendingLanes) {
2199 // First look for lanes that are completely unclaimed, i.e. have no
2200 // pending work.
2201 var lane = pickArbitraryLane(TransitionLanes & ~pendingLanes);
2202
2203 if (lane === NoLane) {
2204 // If all lanes have pending work, look for a lane that isn't currently
2205 // being worked on.
2206 lane = pickArbitraryLane(TransitionLanes & ~wipLanes);
2207
2208 if (lane === NoLane) {
2209 // If everything is being worked on, pick any lane. This has the
2210 // effect of interrupting the current work-in-progress.
2211 lane = pickArbitraryLane(TransitionLanes);
2212 }
2213 }
2214
2215 return lane;
2216 } // To ensure consistency across multiple updates in the same event, this should
2217 // be pure function, so that it always returns the same lane for given inputs.
2218
2219 function findRetryLane(wipLanes) {
2220 // This is a fork of `findUpdateLane` designed specifically for Suspense
2221 // "retries" — a special update that attempts to flip a Suspense boundary
2222 // from its placeholder state to its primary/resolved state.
2223 var lane = pickArbitraryLane(RetryLanes & ~wipLanes);
2224
2225 if (lane === NoLane) {
2226 lane = pickArbitraryLane(RetryLanes);
2227 }
2228
2229 return lane;
2230 }
2231
2232 function getHighestPriorityLane(lanes) {
2233 return lanes & -lanes;
2234 }
2235
2236 function getLowestPriorityLane(lanes) {
2237 // This finds the most significant non-zero bit.
2238 var index = 31 - clz32(lanes);
2239 return index < 0 ? NoLanes : 1 << index;
2240 }
2241
2242 function getEqualOrHigherPriorityLanes(lanes) {
2243 return (getLowestPriorityLane(lanes) << 1) - 1;
2244 }
2245
2246 function pickArbitraryLane(lanes) {
2247 // This wrapper function gets inlined. Only exists so to communicate that it
2248 // doesn't matter which bit is selected; you can pick any bit without
2249 // affecting the algorithms where its used. Here I'm using
2250 // getHighestPriorityLane because it requires the fewest operations.
2251 return getHighestPriorityLane(lanes);
2252 }
2253
2254 function pickArbitraryLaneIndex(lanes) {
2255 return 31 - clz32(lanes);
2256 }
2257
2258 function laneToIndex(lane) {
2259 return pickArbitraryLaneIndex(lane);
2260 }
2261
2262 function includesSomeLane(a, b) {
2263 return (a & b) !== NoLanes;
2264 }
2265 function isSubsetOfLanes(set, subset) {
2266 return (set & subset) === subset;
2267 }
2268 function mergeLanes(a, b) {
2269 return a | b;
2270 }
2271 function removeLanes(set, subset) {
2272 return set & ~subset;
2273 } // Seems redundant, but it changes the type from a single lane (used for
2274 // updates) to a group of lanes (used for flushing work).
2275
2276 function laneToLanes(lane) {
2277 return lane;
2278 }
2279 function createLaneMap(initial) {
2280 // Intentionally pushing one by one.
2281 // https://v8.dev/blog/elements-kinds#avoid-creating-holes
2282 var laneMap = [];
2283
2284 for (var i = 0; i < TotalLanes; i++) {
2285 laneMap.push(initial);
2286 }
2287
2288 return laneMap;
2289 }
2290 function markRootUpdated(root, updateLane, eventTime) {
2291 root.pendingLanes |= updateLane; // TODO: Theoretically, any update to any lane can unblock any other lane. But
2292 // it's not practical to try every single possible combination. We need a
2293 // heuristic to decide which lanes to attempt to render, and in which batches.
2294 // For now, we use the same heuristic as in the old ExpirationTimes model:
2295 // retry any lane at equal or lower priority, but don't try updates at higher
2296 // priority without also including the lower priority updates. This works well
2297 // when considering updates across different priority levels, but isn't
2298 // sufficient for updates within the same priority, since we want to treat
2299 // those updates as parallel.
2300 // Unsuspend any update at equal or lower priority.
2301
2302 var higherPriorityLanes = updateLane - 1; // Turns 0b1000 into 0b0111
2303
2304 root.suspendedLanes &= higherPriorityLanes;
2305 root.pingedLanes &= higherPriorityLanes;
2306 var eventTimes = root.eventTimes;
2307 var index = laneToIndex(updateLane); // We can always overwrite an existing timestamp because we prefer the most
2308 // recent event, and we assume time is monotonically increasing.
2309
2310 eventTimes[index] = eventTime;
2311 }
2312 function markRootSuspended(root, suspendedLanes) {
2313 root.suspendedLanes |= suspendedLanes;
2314 root.pingedLanes &= ~suspendedLanes; // The suspended lanes are no longer CPU-bound. Clear their expiration times.
2315
2316 var expirationTimes = root.expirationTimes;
2317 var lanes = suspendedLanes;
2318
2319 while (lanes > 0) {
2320 var index = pickArbitraryLaneIndex(lanes);
2321 var lane = 1 << index;
2322 expirationTimes[index] = NoTimestamp;
2323 lanes &= ~lane;
2324 }
2325 }
2326 function markRootPinged(root, pingedLanes, eventTime) {
2327 root.pingedLanes |= root.suspendedLanes & pingedLanes;
2328 }
2329 function hasDiscreteLanes(lanes) {
2330 return (lanes & InputDiscreteLanes) !== NoLanes;
2331 }
2332 function markRootMutableRead(root, updateLane) {
2333 root.mutableReadLanes |= updateLane & root.pendingLanes;
2334 }
2335 function markRootFinished(root, remainingLanes) {
2336 var noLongerPendingLanes = root.pendingLanes & ~remainingLanes;
2337 root.pendingLanes = remainingLanes; // Let's try everything again
2338
2339 root.suspendedLanes = 0;
2340 root.pingedLanes = 0;
2341 root.expiredLanes &= remainingLanes;
2342 root.mutableReadLanes &= remainingLanes;
2343 root.entangledLanes &= remainingLanes;
2344 var entanglements = root.entanglements;
2345 var eventTimes = root.eventTimes;
2346 var expirationTimes = root.expirationTimes; // Clear the lanes that no longer have pending work
2347
2348 var lanes = noLongerPendingLanes;
2349
2350 while (lanes > 0) {
2351 var index = pickArbitraryLaneIndex(lanes);
2352 var lane = 1 << index;
2353 entanglements[index] = NoLanes;
2354 eventTimes[index] = NoTimestamp;
2355 expirationTimes[index] = NoTimestamp;
2356 lanes &= ~lane;
2357 }
2358 }
2359 function markRootEntangled(root, entangledLanes) {
2360 root.entangledLanes |= entangledLanes;
2361 var entanglements = root.entanglements;
2362 var lanes = entangledLanes;
2363
2364 while (lanes > 0) {
2365 var index = pickArbitraryLaneIndex(lanes);
2366 var lane = 1 << index;
2367 entanglements[index] |= entangledLanes;
2368 lanes &= ~lane;
2369 }
2370 }
2371 var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. Only used on lanes, so assume input is an integer.
2372 // Based on:
2373 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32
2374
2375 var log = Math.log;
2376 var LN2 = Math.LN2;
2377
2378 function clz32Fallback(lanes) {
2379 if (lanes === 0) {
2380 return 32;
2381 }
2382
2383 return 31 - (log(lanes) / LN2 | 0) | 0;
2384 }
2385
2386 var Scheduler_runWithPriority = Scheduler$1.unstable_runWithPriority,
2387 Scheduler_scheduleCallback = Scheduler$1.unstable_scheduleCallback,
2388 Scheduler_cancelCallback = Scheduler$1.unstable_cancelCallback,
2389 Scheduler_shouldYield = Scheduler$1.unstable_shouldYield,
2390 Scheduler_requestPaint = Scheduler$1.unstable_requestPaint,
2391 Scheduler_now$1 = Scheduler$1.unstable_now,
2392 Scheduler_getCurrentPriorityLevel = Scheduler$1.unstable_getCurrentPriorityLevel,
2393 Scheduler_ImmediatePriority = Scheduler$1.unstable_ImmediatePriority,
2394 Scheduler_UserBlockingPriority = Scheduler$1.unstable_UserBlockingPriority,
2395 Scheduler_NormalPriority = Scheduler$1.unstable_NormalPriority,
2396 Scheduler_LowPriority = Scheduler$1.unstable_LowPriority,
2397 Scheduler_IdlePriority = Scheduler$1.unstable_IdlePriority;
2398
2399 {
2400 // Provide explicit error message when production+profiling bundle of e.g.
2401 // react-dom is used with production (non-profiling) bundle of
2402 // scheduler/tracing
2403 if (!(__interactionsRef != null && __interactionsRef.current != null)) {
2404 {
2405 throw Error( "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 https://reactjs.org/link/profiling" );
2406 }
2407 }
2408 }
2409
2410 var fakeCallbackNode = {}; // Except for NoPriority, these correspond to Scheduler priorities. We use
2411 // ascending numbers so we can compare them like numbers. They start at 90 to
2412 // avoid clashing with Scheduler's priorities.
2413
2414 var ImmediatePriority$1 = 99;
2415 var UserBlockingPriority$1 = 98;
2416 var NormalPriority$1 = 97;
2417 var LowPriority$1 = 96;
2418 var IdlePriority$1 = 95; // NoPriority is the absence of priority. Also React-only.
2419
2420 var NoPriority$1 = 90;
2421 var shouldYield = Scheduler_shouldYield;
2422 var requestPaint = // Fall back gracefully if we're running an older version of Scheduler.
2423 Scheduler_requestPaint !== undefined ? Scheduler_requestPaint : function () {};
2424 var syncQueue = null;
2425 var immediateQueueCallbackNode = null;
2426 var isFlushingSyncQueue = false;
2427 var initialTimeMs$1 = Scheduler_now$1(); // If the initial timestamp is reasonably small, use Scheduler's `now` directly.
2428 // This will be the case for modern browsers that support `performance.now`. In
2429 // older browsers, Scheduler falls back to `Date.now`, which returns a Unix
2430 // timestamp. In that case, subtract the module initialization time to simulate
2431 // the behavior of performance.now and keep our times small enough to fit
2432 // within 32 bits.
2433 // TODO: Consider lifting this into Scheduler.
2434
2435 var now = initialTimeMs$1 < 10000 ? Scheduler_now$1 : function () {
2436 return Scheduler_now$1() - initialTimeMs$1;
2437 };
2438 function getCurrentPriorityLevel() {
2439 switch (Scheduler_getCurrentPriorityLevel()) {
2440 case Scheduler_ImmediatePriority:
2441 return ImmediatePriority$1;
2442
2443 case Scheduler_UserBlockingPriority:
2444 return UserBlockingPriority$1;
2445
2446 case Scheduler_NormalPriority:
2447 return NormalPriority$1;
2448
2449 case Scheduler_LowPriority:
2450 return LowPriority$1;
2451
2452 case Scheduler_IdlePriority:
2453 return IdlePriority$1;
2454
2455 default:
2456 {
2457 {
2458 throw Error( "Unknown priority level." );
2459 }
2460 }
2461
2462 }
2463 }
2464
2465 function reactPriorityToSchedulerPriority(reactPriorityLevel) {
2466 switch (reactPriorityLevel) {
2467 case ImmediatePriority$1:
2468 return Scheduler_ImmediatePriority;
2469
2470 case UserBlockingPriority$1:
2471 return Scheduler_UserBlockingPriority;
2472
2473 case NormalPriority$1:
2474 return Scheduler_NormalPriority;
2475
2476 case LowPriority$1:
2477 return Scheduler_LowPriority;
2478
2479 case IdlePriority$1:
2480 return Scheduler_IdlePriority;
2481
2482 default:
2483 {
2484 {
2485 throw Error( "Unknown priority level." );
2486 }
2487 }
2488
2489 }
2490 }
2491
2492 function runWithPriority(reactPriorityLevel, fn) {
2493 var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
2494 return Scheduler_runWithPriority(priorityLevel, fn);
2495 }
2496 function scheduleCallback(reactPriorityLevel, callback, options) {
2497 var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
2498 return Scheduler_scheduleCallback(priorityLevel, callback, options);
2499 }
2500 function scheduleSyncCallback(callback) {
2501 // Push this callback into an internal queue. We'll flush these either in
2502 // the next tick, or earlier if something calls `flushSyncCallbackQueue`.
2503 if (syncQueue === null) {
2504 syncQueue = [callback]; // Flush the queue in the next tick, at the earliest.
2505
2506 immediateQueueCallbackNode = Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueueImpl);
2507 } else {
2508 // Push onto existing queue. Don't need to schedule a callback because
2509 // we already scheduled one when we created the queue.
2510 syncQueue.push(callback);
2511 }
2512
2513 return fakeCallbackNode;
2514 }
2515 function cancelCallback(callbackNode) {
2516 if (callbackNode !== fakeCallbackNode) {
2517 Scheduler_cancelCallback(callbackNode);
2518 }
2519 }
2520 function flushSyncCallbackQueue() {
2521 if (immediateQueueCallbackNode !== null) {
2522 var node = immediateQueueCallbackNode;
2523 immediateQueueCallbackNode = null;
2524 Scheduler_cancelCallback(node);
2525 }
2526
2527 flushSyncCallbackQueueImpl();
2528 }
2529
2530 function flushSyncCallbackQueueImpl() {
2531 if (!isFlushingSyncQueue && syncQueue !== null) {
2532 // Prevent re-entrancy.
2533 isFlushingSyncQueue = true;
2534 var i = 0;
2535
2536 {
2537 try {
2538 var _isSync2 = true;
2539 var _queue = syncQueue;
2540 runWithPriority(ImmediatePriority$1, function () {
2541 for (; i < _queue.length; i++) {
2542 var callback = _queue[i];
2543
2544 do {
2545 callback = callback(_isSync2);
2546 } while (callback !== null);
2547 }
2548 });
2549 syncQueue = null;
2550 } catch (error) {
2551 // If something throws, leave the remaining callbacks on the queue.
2552 if (syncQueue !== null) {
2553 syncQueue = syncQueue.slice(i + 1);
2554 } // Resume flushing in the next tick
2555
2556
2557 Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueue);
2558 throw error;
2559 } finally {
2560 isFlushingSyncQueue = false;
2561 }
2562 }
2563 }
2564 }
2565
2566 // TODO: this is special because it gets imported during build.
2567 var ReactVersion = '17.0.1';
2568
2569 var NoMode = 0;
2570 var StrictMode = 1; // TODO: Remove BlockingMode and ConcurrentMode by reading from the root
2571 // tag instead
2572
2573 var BlockingMode = 2;
2574 var ConcurrentMode = 4;
2575 var ProfileMode = 8;
2576 var DebugTracingMode = 16;
2577
2578 var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig;
2579 var NoTransition = 0;
2580 function requestCurrentTransition() {
2581 return ReactCurrentBatchConfig.transition;
2582 }
2583
2584 /**
2585 * inlined Object.is polyfill to avoid requiring consumers ship their own
2586 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
2587 */
2588 function is(x, y) {
2589 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
2590 ;
2591 }
2592
2593 var objectIs = typeof Object.is === 'function' ? Object.is : is;
2594
2595 var hasOwnProperty = Object.prototype.hasOwnProperty;
2596 /**
2597 * Performs equality by iterating through keys on an object and returning false
2598 * when any key has values which are not strictly equal between the arguments.
2599 * Returns true when the values of all keys are strictly equal.
2600 */
2601
2602 function shallowEqual(objA, objB) {
2603 if (objectIs(objA, objB)) {
2604 return true;
2605 }
2606
2607 if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
2608 return false;
2609 }
2610
2611 var keysA = Object.keys(objA);
2612 var keysB = Object.keys(objB);
2613
2614 if (keysA.length !== keysB.length) {
2615 return false;
2616 } // Test for A's keys different from B.
2617
2618
2619 for (var i = 0; i < keysA.length; i++) {
2620 if (!hasOwnProperty.call(objB, keysA[i]) || !objectIs(objA[keysA[i]], objB[keysA[i]])) {
2621 return false;
2622 }
2623 }
2624
2625 return true;
2626 }
2627
2628 function describeFiber(fiber) {
2629 var owner = fiber._debugOwner ? fiber._debugOwner.type : null ;
2630 var source = fiber._debugSource ;
2631
2632 switch (fiber.tag) {
2633 case HostComponent:
2634 return describeBuiltInComponentFrame(fiber.type);
2635
2636 case LazyComponent:
2637 return describeBuiltInComponentFrame('Lazy');
2638
2639 case SuspenseComponent:
2640 return describeBuiltInComponentFrame('Suspense');
2641
2642 case SuspenseListComponent:
2643 return describeBuiltInComponentFrame('SuspenseList');
2644
2645 case FunctionComponent:
2646 case IndeterminateComponent:
2647 case SimpleMemoComponent:
2648 return describeFunctionComponentFrame(fiber.type);
2649
2650 case ForwardRef:
2651 return describeFunctionComponentFrame(fiber.type.render);
2652
2653 case Block:
2654 return describeFunctionComponentFrame(fiber.type._render);
2655
2656 case ClassComponent:
2657 return describeClassComponentFrame(fiber.type);
2658
2659 default:
2660 return '';
2661 }
2662 }
2663
2664 function getStackByFiberInDevAndProd(workInProgress) {
2665 try {
2666 var info = '';
2667 var node = workInProgress;
2668
2669 do {
2670 info += describeFiber(node);
2671 node = node.return;
2672 } while (node);
2673
2674 return info;
2675 } catch (x) {
2676 return '\nError generating stack: ' + x.message + '\n' + x.stack;
2677 }
2678 }
2679
2680 var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
2681 var current = null;
2682 var isRendering = false;
2683 function getCurrentFiberOwnerNameInDevOrNull() {
2684 {
2685 if (current === null) {
2686 return null;
2687 }
2688
2689 var owner = current._debugOwner;
2690
2691 if (owner !== null && typeof owner !== 'undefined') {
2692 return getComponentName(owner.type);
2693 }
2694 }
2695
2696 return null;
2697 }
2698
2699 function getCurrentFiberStackInDev() {
2700 {
2701 if (current === null) {
2702 return '';
2703 } // Safe because if current fiber exists, we are reconciling,
2704 // and it is guaranteed to be the work-in-progress version.
2705
2706
2707 return getStackByFiberInDevAndProd(current);
2708 }
2709 }
2710
2711 function resetCurrentFiber() {
2712 {
2713 ReactDebugCurrentFrame$1.getCurrentStack = null;
2714 current = null;
2715 isRendering = false;
2716 }
2717 }
2718 function setCurrentFiber(fiber) {
2719 {
2720 ReactDebugCurrentFrame$1.getCurrentStack = getCurrentFiberStackInDev;
2721 current = fiber;
2722 isRendering = false;
2723 }
2724 }
2725 function setIsRendering(rendering) {
2726 {
2727 isRendering = rendering;
2728 }
2729 }
2730 function getIsRendering() {
2731 {
2732 return isRendering;
2733 }
2734 }
2735
2736 var ReactStrictModeWarnings = {
2737 recordUnsafeLifecycleWarnings: function (fiber, instance) {},
2738 flushPendingUnsafeLifecycleWarnings: function () {},
2739 recordLegacyContextWarning: function (fiber, instance) {},
2740 flushLegacyContextWarning: function () {},
2741 discardPendingWarnings: function () {}
2742 };
2743
2744 {
2745 var findStrictRoot = function (fiber) {
2746 var maybeStrictRoot = null;
2747 var node = fiber;
2748
2749 while (node !== null) {
2750 if (node.mode & StrictMode) {
2751 maybeStrictRoot = node;
2752 }
2753
2754 node = node.return;
2755 }
2756
2757 return maybeStrictRoot;
2758 };
2759
2760 var setToSortedString = function (set) {
2761 var array = [];
2762 set.forEach(function (value) {
2763 array.push(value);
2764 });
2765 return array.sort().join(', ');
2766 };
2767
2768 var pendingComponentWillMountWarnings = [];
2769 var pendingUNSAFE_ComponentWillMountWarnings = [];
2770 var pendingComponentWillReceivePropsWarnings = [];
2771 var pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
2772 var pendingComponentWillUpdateWarnings = [];
2773 var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about.
2774
2775 var didWarnAboutUnsafeLifecycles = new Set();
2776
2777 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
2778 // Dedup strategy: Warn once per component.
2779 if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
2780 return;
2781 }
2782
2783 if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components.
2784 instance.componentWillMount.__suppressDeprecationWarning !== true) {
2785 pendingComponentWillMountWarnings.push(fiber);
2786 }
2787
2788 if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillMount === 'function') {
2789 pendingUNSAFE_ComponentWillMountWarnings.push(fiber);
2790 }
2791
2792 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
2793 pendingComponentWillReceivePropsWarnings.push(fiber);
2794 }
2795
2796 if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
2797 pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);
2798 }
2799
2800 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
2801 pendingComponentWillUpdateWarnings.push(fiber);
2802 }
2803
2804 if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillUpdate === 'function') {
2805 pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);
2806 }
2807 };
2808
2809 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
2810 // We do an initial pass to gather component names
2811 var componentWillMountUniqueNames = new Set();
2812
2813 if (pendingComponentWillMountWarnings.length > 0) {
2814 pendingComponentWillMountWarnings.forEach(function (fiber) {
2815 componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');
2816 didWarnAboutUnsafeLifecycles.add(fiber.type);
2817 });
2818 pendingComponentWillMountWarnings = [];
2819 }
2820
2821 var UNSAFE_componentWillMountUniqueNames = new Set();
2822
2823 if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) {
2824 pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) {
2825 UNSAFE_componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');
2826 didWarnAboutUnsafeLifecycles.add(fiber.type);
2827 });
2828 pendingUNSAFE_ComponentWillMountWarnings = [];
2829 }
2830
2831 var componentWillReceivePropsUniqueNames = new Set();
2832
2833 if (pendingComponentWillReceivePropsWarnings.length > 0) {
2834 pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
2835 componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');
2836 didWarnAboutUnsafeLifecycles.add(fiber.type);
2837 });
2838 pendingComponentWillReceivePropsWarnings = [];
2839 }
2840
2841 var UNSAFE_componentWillReceivePropsUniqueNames = new Set();
2842
2843 if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) {
2844 pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) {
2845 UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');
2846 didWarnAboutUnsafeLifecycles.add(fiber.type);
2847 });
2848 pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
2849 }
2850
2851 var componentWillUpdateUniqueNames = new Set();
2852
2853 if (pendingComponentWillUpdateWarnings.length > 0) {
2854 pendingComponentWillUpdateWarnings.forEach(function (fiber) {
2855 componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');
2856 didWarnAboutUnsafeLifecycles.add(fiber.type);
2857 });
2858 pendingComponentWillUpdateWarnings = [];
2859 }
2860
2861 var UNSAFE_componentWillUpdateUniqueNames = new Set();
2862
2863 if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) {
2864 pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) {
2865 UNSAFE_componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');
2866 didWarnAboutUnsafeLifecycles.add(fiber.type);
2867 });
2868 pendingUNSAFE_ComponentWillUpdateWarnings = [];
2869 } // Finally, we flush all the warnings
2870 // UNSAFE_ ones before the deprecated ones, since they'll be 'louder'
2871
2872
2873 if (UNSAFE_componentWillMountUniqueNames.size > 0) {
2874 var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames);
2875
2876 error('Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '\nPlease update the following components: %s', sortedNames);
2877 }
2878
2879 if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) {
2880 var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames);
2881
2882 error('Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, " + 'refactor your code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '\nPlease update the following components: %s', _sortedNames);
2883 }
2884
2885 if (UNSAFE_componentWillUpdateUniqueNames.size > 0) {
2886 var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames);
2887
2888 error('Using UNSAFE_componentWillUpdate in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '\nPlease update the following components: %s', _sortedNames2);
2889 }
2890
2891 if (componentWillMountUniqueNames.size > 0) {
2892 var _sortedNames3 = setToSortedString(componentWillMountUniqueNames);
2893
2894 warn('componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames3);
2895 }
2896
2897 if (componentWillReceivePropsUniqueNames.size > 0) {
2898 var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);
2899
2900 warn('componentWillReceiveProps has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, refactor your " + 'code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames4);
2901 }
2902
2903 if (componentWillUpdateUniqueNames.size > 0) {
2904 var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames);
2905
2906 warn('componentWillUpdate has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames5);
2907 }
2908 };
2909
2910 var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about.
2911
2912 var didWarnAboutLegacyContext = new Set();
2913
2914 ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
2915 var strictRoot = findStrictRoot(fiber);
2916
2917 if (strictRoot === null) {
2918 error('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.');
2919
2920 return;
2921 } // Dedup strategy: Warn once per component.
2922
2923
2924 if (didWarnAboutLegacyContext.has(fiber.type)) {
2925 return;
2926 }
2927
2928 var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
2929
2930 if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
2931 if (warningsForRoot === undefined) {
2932 warningsForRoot = [];
2933 pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
2934 }
2935
2936 warningsForRoot.push(fiber);
2937 }
2938 };
2939
2940 ReactStrictModeWarnings.flushLegacyContextWarning = function () {
2941 pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
2942 if (fiberArray.length === 0) {
2943 return;
2944 }
2945
2946 var firstFiber = fiberArray[0];
2947 var uniqueNames = new Set();
2948 fiberArray.forEach(function (fiber) {
2949 uniqueNames.add(getComponentName(fiber.type) || 'Component');
2950 didWarnAboutLegacyContext.add(fiber.type);
2951 });
2952 var sortedNames = setToSortedString(uniqueNames);
2953
2954 try {
2955 setCurrentFiber(firstFiber);
2956
2957 error('Legacy context API has been detected within a strict-mode tree.' + '\n\nThe old API will be supported in all 16.x releases, but applications ' + 'using it should migrate to the new version.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context', sortedNames);
2958 } finally {
2959 resetCurrentFiber();
2960 }
2961 });
2962 };
2963
2964 ReactStrictModeWarnings.discardPendingWarnings = function () {
2965 pendingComponentWillMountWarnings = [];
2966 pendingUNSAFE_ComponentWillMountWarnings = [];
2967 pendingComponentWillReceivePropsWarnings = [];
2968 pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
2969 pendingComponentWillUpdateWarnings = [];
2970 pendingUNSAFE_ComponentWillUpdateWarnings = [];
2971 pendingLegacyContextWarning = new Map();
2972 };
2973 }
2974
2975 function resolveDefaultProps(Component, baseProps) {
2976 if (Component && Component.defaultProps) {
2977 // Resolve default props. Taken from ReactElement
2978 var props = _assign({}, baseProps);
2979
2980 var defaultProps = Component.defaultProps;
2981
2982 for (var propName in defaultProps) {
2983 if (props[propName] === undefined) {
2984 props[propName] = defaultProps[propName];
2985 }
2986 }
2987
2988 return props;
2989 }
2990
2991 return baseProps;
2992 }
2993
2994 // Max 31 bit integer. The max integer size in V8 for 32-bit systems.
2995 // Math.pow(2, 30) - 1
2996 // 0b111111111111111111111111111111
2997 var MAX_SIGNED_31_BIT_INT = 1073741823;
2998
2999 var valueCursor = createCursor(null);
3000 var rendererSigil;
3001
3002 {
3003 // Use this to detect multiple renderers using the same context
3004 rendererSigil = {};
3005 }
3006
3007 var currentlyRenderingFiber = null;
3008 var lastContextDependency = null;
3009 var lastContextWithAllBitsObserved = null;
3010 var isDisallowedContextReadInDEV = false;
3011 function resetContextDependencies() {
3012 // This is called right before React yields execution, to ensure `readContext`
3013 // cannot be called outside the render phase.
3014 currentlyRenderingFiber = null;
3015 lastContextDependency = null;
3016 lastContextWithAllBitsObserved = null;
3017
3018 {
3019 isDisallowedContextReadInDEV = false;
3020 }
3021 }
3022 function enterDisallowedContextReadInDEV() {
3023 {
3024 isDisallowedContextReadInDEV = true;
3025 }
3026 }
3027 function exitDisallowedContextReadInDEV() {
3028 {
3029 isDisallowedContextReadInDEV = false;
3030 }
3031 }
3032 function pushProvider(providerFiber, nextValue) {
3033 var context = providerFiber.type._context;
3034
3035 {
3036 push(valueCursor, context._currentValue2, providerFiber);
3037 context._currentValue2 = nextValue;
3038
3039 {
3040 if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) {
3041 error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
3042 }
3043
3044 context._currentRenderer2 = rendererSigil;
3045 }
3046 }
3047 }
3048 function popProvider(providerFiber) {
3049 var currentValue = valueCursor.current;
3050 pop(valueCursor, providerFiber);
3051 var context = providerFiber.type._context;
3052
3053 {
3054 context._currentValue2 = currentValue;
3055 }
3056 }
3057 function calculateChangedBits(context, newValue, oldValue) {
3058 if (objectIs(oldValue, newValue)) {
3059 // No change
3060 return 0;
3061 } else {
3062 var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;
3063
3064 {
3065 if ((changedBits & MAX_SIGNED_31_BIT_INT) !== changedBits) {
3066 error('calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits);
3067 }
3068 }
3069
3070 return changedBits | 0;
3071 }
3072 }
3073 function scheduleWorkOnParentPath(parent, renderLanes) {
3074 // Update the child lanes of all the ancestors, including the alternates.
3075 var node = parent;
3076
3077 while (node !== null) {
3078 var alternate = node.alternate;
3079
3080 if (!isSubsetOfLanes(node.childLanes, renderLanes)) {
3081 node.childLanes = mergeLanes(node.childLanes, renderLanes);
3082
3083 if (alternate !== null) {
3084 alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes);
3085 }
3086 } else if (alternate !== null && !isSubsetOfLanes(alternate.childLanes, renderLanes)) {
3087 alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes);
3088 } else {
3089 // Neither alternate was updated, which means the rest of the
3090 // ancestor path already has sufficient priority.
3091 break;
3092 }
3093
3094 node = node.return;
3095 }
3096 }
3097 function propagateContextChange(workInProgress, context, changedBits, renderLanes) {
3098 var fiber = workInProgress.child;
3099
3100 if (fiber !== null) {
3101 // Set the return pointer of the child to the work-in-progress fiber.
3102 fiber.return = workInProgress;
3103 }
3104
3105 while (fiber !== null) {
3106 var nextFiber = void 0; // Visit this fiber.
3107
3108 var list = fiber.dependencies;
3109
3110 if (list !== null) {
3111 nextFiber = fiber.child;
3112 var dependency = list.firstContext;
3113
3114 while (dependency !== null) {
3115 // Check if the context matches.
3116 if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {
3117 // Match! Schedule an update on this fiber.
3118 if (fiber.tag === ClassComponent) {
3119 // Schedule a force update on the work-in-progress.
3120 var update = createUpdate(NoTimestamp, pickArbitraryLane(renderLanes));
3121 update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the
3122 // update to the current fiber, too, which means it will persist even if
3123 // this render is thrown away. Since it's a race condition, not sure it's
3124 // worth fixing.
3125
3126 enqueueUpdate(fiber, update);
3127 }
3128
3129 fiber.lanes = mergeLanes(fiber.lanes, renderLanes);
3130 var alternate = fiber.alternate;
3131
3132 if (alternate !== null) {
3133 alternate.lanes = mergeLanes(alternate.lanes, renderLanes);
3134 }
3135
3136 scheduleWorkOnParentPath(fiber.return, renderLanes); // Mark the updated lanes on the list, too.
3137
3138 list.lanes = mergeLanes(list.lanes, renderLanes); // Since we already found a match, we can stop traversing the
3139 // dependency list.
3140
3141 break;
3142 }
3143
3144 dependency = dependency.next;
3145 }
3146 } else if (fiber.tag === ContextProvider) {
3147 // Don't scan deeper if this is a matching provider
3148 nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
3149 } else {
3150 // Traverse down.
3151 nextFiber = fiber.child;
3152 }
3153
3154 if (nextFiber !== null) {
3155 // Set the return pointer of the child to the work-in-progress fiber.
3156 nextFiber.return = fiber;
3157 } else {
3158 // No child. Traverse to next sibling.
3159 nextFiber = fiber;
3160
3161 while (nextFiber !== null) {
3162 if (nextFiber === workInProgress) {
3163 // We're back to the root of this subtree. Exit.
3164 nextFiber = null;
3165 break;
3166 }
3167
3168 var sibling = nextFiber.sibling;
3169
3170 if (sibling !== null) {
3171 // Set the return pointer of the sibling to the work-in-progress fiber.
3172 sibling.return = nextFiber.return;
3173 nextFiber = sibling;
3174 break;
3175 } // No more siblings. Traverse up.
3176
3177
3178 nextFiber = nextFiber.return;
3179 }
3180 }
3181
3182 fiber = nextFiber;
3183 }
3184 }
3185 function prepareToReadContext(workInProgress, renderLanes) {
3186 currentlyRenderingFiber = workInProgress;
3187 lastContextDependency = null;
3188 lastContextWithAllBitsObserved = null;
3189 var dependencies = workInProgress.dependencies;
3190
3191 if (dependencies !== null) {
3192 var firstContext = dependencies.firstContext;
3193
3194 if (firstContext !== null) {
3195 if (includesSomeLane(dependencies.lanes, renderLanes)) {
3196 // Context list has a pending update. Mark that this fiber performed work.
3197 markWorkInProgressReceivedUpdate();
3198 } // Reset the work-in-progress list
3199
3200
3201 dependencies.firstContext = null;
3202 }
3203 }
3204 }
3205 function readContext(context, observedBits) {
3206 {
3207 // This warning would fire if you read context inside a Hook like useMemo.
3208 // Unlike the class check below, it's not enforced in production for perf.
3209 if (isDisallowedContextReadInDEV) {
3210 error('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().');
3211 }
3212 }
3213
3214 if (lastContextWithAllBitsObserved === context) ; else if (observedBits === false || observedBits === 0) ; else {
3215 var resolvedObservedBits; // Avoid deopting on observable arguments or heterogeneous types.
3216
3217 if (typeof observedBits !== 'number' || observedBits === MAX_SIGNED_31_BIT_INT) {
3218 // Observe all updates.
3219 lastContextWithAllBitsObserved = context;
3220 resolvedObservedBits = MAX_SIGNED_31_BIT_INT;
3221 } else {
3222 resolvedObservedBits = observedBits;
3223 }
3224
3225 var contextItem = {
3226 context: context,
3227 observedBits: resolvedObservedBits,
3228 next: null
3229 };
3230
3231 if (lastContextDependency === null) {
3232 if (!(currentlyRenderingFiber !== null)) {
3233 {
3234 throw Error( "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()." );
3235 }
3236 } // This is the first dependency for this component. Create a new list.
3237
3238
3239 lastContextDependency = contextItem;
3240 currentlyRenderingFiber.dependencies = {
3241 lanes: NoLanes,
3242 firstContext: contextItem,
3243 responders: null
3244 };
3245 } else {
3246 // Append a new context item.
3247 lastContextDependency = lastContextDependency.next = contextItem;
3248 }
3249 }
3250
3251 return context._currentValue2;
3252 }
3253
3254 var UpdateState = 0;
3255 var ReplaceState = 1;
3256 var ForceUpdate = 2;
3257 var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`.
3258 // It should only be read right after calling `processUpdateQueue`, via
3259 // `checkHasForceUpdateAfterProcessing`.
3260
3261 var hasForceUpdate = false;
3262 var didWarnUpdateInsideUpdate;
3263 var currentlyProcessingQueue;
3264
3265 {
3266 didWarnUpdateInsideUpdate = false;
3267 currentlyProcessingQueue = null;
3268 }
3269
3270 function initializeUpdateQueue(fiber) {
3271 var queue = {
3272 baseState: fiber.memoizedState,
3273 firstBaseUpdate: null,
3274 lastBaseUpdate: null,
3275 shared: {
3276 pending: null
3277 },
3278 effects: null
3279 };
3280 fiber.updateQueue = queue;
3281 }
3282 function cloneUpdateQueue(current, workInProgress) {
3283 // Clone the update queue from current. Unless it's already a clone.
3284 var queue = workInProgress.updateQueue;
3285 var currentQueue = current.updateQueue;
3286
3287 if (queue === currentQueue) {
3288 var clone = {
3289 baseState: currentQueue.baseState,
3290 firstBaseUpdate: currentQueue.firstBaseUpdate,
3291 lastBaseUpdate: currentQueue.lastBaseUpdate,
3292 shared: currentQueue.shared,
3293 effects: currentQueue.effects
3294 };
3295 workInProgress.updateQueue = clone;
3296 }
3297 }
3298 function createUpdate(eventTime, lane) {
3299 var update = {
3300 eventTime: eventTime,
3301 lane: lane,
3302 tag: UpdateState,
3303 payload: null,
3304 callback: null,
3305 next: null
3306 };
3307 return update;
3308 }
3309 function enqueueUpdate(fiber, update) {
3310 var updateQueue = fiber.updateQueue;
3311
3312 if (updateQueue === null) {
3313 // Only occurs if the fiber has been unmounted.
3314 return;
3315 }
3316
3317 var sharedQueue = updateQueue.shared;
3318 var pending = sharedQueue.pending;
3319
3320 if (pending === null) {
3321 // This is the first update. Create a circular list.
3322 update.next = update;
3323 } else {
3324 update.next = pending.next;
3325 pending.next = update;
3326 }
3327
3328 sharedQueue.pending = update;
3329
3330 {
3331 if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) {
3332 error('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.');
3333
3334 didWarnUpdateInsideUpdate = true;
3335 }
3336 }
3337 }
3338 function enqueueCapturedUpdate(workInProgress, capturedUpdate) {
3339 // Captured updates are updates that are thrown by a child during the render
3340 // phase. They should be discarded if the render is aborted. Therefore,
3341 // we should only put them on the work-in-progress queue, not the current one.
3342 var queue = workInProgress.updateQueue; // Check if the work-in-progress queue is a clone.
3343
3344 var current = workInProgress.alternate;
3345
3346 if (current !== null) {
3347 var currentQueue = current.updateQueue;
3348
3349 if (queue === currentQueue) {
3350 // The work-in-progress queue is the same as current. This happens when
3351 // we bail out on a parent fiber that then captures an error thrown by
3352 // a child. Since we want to append the update only to the work-in
3353 // -progress queue, we need to clone the updates. We usually clone during
3354 // processUpdateQueue, but that didn't happen in this case because we
3355 // skipped over the parent when we bailed out.
3356 var newFirst = null;
3357 var newLast = null;
3358 var firstBaseUpdate = queue.firstBaseUpdate;
3359
3360 if (firstBaseUpdate !== null) {
3361 // Loop through the updates and clone them.
3362 var update = firstBaseUpdate;
3363
3364 do {
3365 var clone = {
3366 eventTime: update.eventTime,
3367 lane: update.lane,
3368 tag: update.tag,
3369 payload: update.payload,
3370 callback: update.callback,
3371 next: null
3372 };
3373
3374 if (newLast === null) {
3375 newFirst = newLast = clone;
3376 } else {
3377 newLast.next = clone;
3378 newLast = clone;
3379 }
3380
3381 update = update.next;
3382 } while (update !== null); // Append the captured update the end of the cloned list.
3383
3384
3385 if (newLast === null) {
3386 newFirst = newLast = capturedUpdate;
3387 } else {
3388 newLast.next = capturedUpdate;
3389 newLast = capturedUpdate;
3390 }
3391 } else {
3392 // There are no base updates.
3393 newFirst = newLast = capturedUpdate;
3394 }
3395
3396 queue = {
3397 baseState: currentQueue.baseState,
3398 firstBaseUpdate: newFirst,
3399 lastBaseUpdate: newLast,
3400 shared: currentQueue.shared,
3401 effects: currentQueue.effects
3402 };
3403 workInProgress.updateQueue = queue;
3404 return;
3405 }
3406 } // Append the update to the end of the list.
3407
3408
3409 var lastBaseUpdate = queue.lastBaseUpdate;
3410
3411 if (lastBaseUpdate === null) {
3412 queue.firstBaseUpdate = capturedUpdate;
3413 } else {
3414 lastBaseUpdate.next = capturedUpdate;
3415 }
3416
3417 queue.lastBaseUpdate = capturedUpdate;
3418 }
3419
3420 function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
3421 switch (update.tag) {
3422 case ReplaceState:
3423 {
3424 var payload = update.payload;
3425
3426 if (typeof payload === 'function') {
3427 // Updater function
3428 {
3429 enterDisallowedContextReadInDEV();
3430 }
3431
3432 var nextState = payload.call(instance, prevState, nextProps);
3433
3434 {
3435
3436 exitDisallowedContextReadInDEV();
3437 }
3438
3439 return nextState;
3440 } // State object
3441
3442
3443 return payload;
3444 }
3445
3446 case CaptureUpdate:
3447 {
3448 workInProgress.flags = workInProgress.flags & ~ShouldCapture | DidCapture;
3449 }
3450 // Intentional fallthrough
3451
3452 case UpdateState:
3453 {
3454 var _payload = update.payload;
3455 var partialState;
3456
3457 if (typeof _payload === 'function') {
3458 // Updater function
3459 {
3460 enterDisallowedContextReadInDEV();
3461 }
3462
3463 partialState = _payload.call(instance, prevState, nextProps);
3464
3465 {
3466
3467 exitDisallowedContextReadInDEV();
3468 }
3469 } else {
3470 // Partial state object
3471 partialState = _payload;
3472 }
3473
3474 if (partialState === null || partialState === undefined) {
3475 // Null and undefined are treated as no-ops.
3476 return prevState;
3477 } // Merge the partial state and the previous state.
3478
3479
3480 return _assign({}, prevState, partialState);
3481 }
3482
3483 case ForceUpdate:
3484 {
3485 hasForceUpdate = true;
3486 return prevState;
3487 }
3488 }
3489
3490 return prevState;
3491 }
3492
3493 function processUpdateQueue(workInProgress, props, instance, renderLanes) {
3494 // This is always non-null on a ClassComponent or HostRoot
3495 var queue = workInProgress.updateQueue;
3496 hasForceUpdate = false;
3497
3498 {
3499 currentlyProcessingQueue = queue.shared;
3500 }
3501
3502 var firstBaseUpdate = queue.firstBaseUpdate;
3503 var lastBaseUpdate = queue.lastBaseUpdate; // Check if there are pending updates. If so, transfer them to the base queue.
3504
3505 var pendingQueue = queue.shared.pending;
3506
3507 if (pendingQueue !== null) {
3508 queue.shared.pending = null; // The pending queue is circular. Disconnect the pointer between first
3509 // and last so that it's non-circular.
3510
3511 var lastPendingUpdate = pendingQueue;
3512 var firstPendingUpdate = lastPendingUpdate.next;
3513 lastPendingUpdate.next = null; // Append pending updates to base queue
3514
3515 if (lastBaseUpdate === null) {
3516 firstBaseUpdate = firstPendingUpdate;
3517 } else {
3518 lastBaseUpdate.next = firstPendingUpdate;
3519 }
3520
3521 lastBaseUpdate = lastPendingUpdate; // If there's a current queue, and it's different from the base queue, then
3522 // we need to transfer the updates to that queue, too. Because the base
3523 // queue is a singly-linked list with no cycles, we can append to both
3524 // lists and take advantage of structural sharing.
3525 // TODO: Pass `current` as argument
3526
3527 var current = workInProgress.alternate;
3528
3529 if (current !== null) {
3530 // This is always non-null on a ClassComponent or HostRoot
3531 var currentQueue = current.updateQueue;
3532 var currentLastBaseUpdate = currentQueue.lastBaseUpdate;
3533
3534 if (currentLastBaseUpdate !== lastBaseUpdate) {
3535 if (currentLastBaseUpdate === null) {
3536 currentQueue.firstBaseUpdate = firstPendingUpdate;
3537 } else {
3538 currentLastBaseUpdate.next = firstPendingUpdate;
3539 }
3540
3541 currentQueue.lastBaseUpdate = lastPendingUpdate;
3542 }
3543 }
3544 } // These values may change as we process the queue.
3545
3546
3547 if (firstBaseUpdate !== null) {
3548 // Iterate through the list of updates to compute the result.
3549 var newState = queue.baseState; // TODO: Don't need to accumulate this. Instead, we can remove renderLanes
3550 // from the original lanes.
3551
3552 var newLanes = NoLanes;
3553 var newBaseState = null;
3554 var newFirstBaseUpdate = null;
3555 var newLastBaseUpdate = null;
3556 var update = firstBaseUpdate;
3557
3558 do {
3559 var updateLane = update.lane;
3560 var updateEventTime = update.eventTime;
3561
3562 if (!isSubsetOfLanes(renderLanes, updateLane)) {
3563 // Priority is insufficient. Skip this update. If this is the first
3564 // skipped update, the previous update/state is the new base
3565 // update/state.
3566 var clone = {
3567 eventTime: updateEventTime,
3568 lane: updateLane,
3569 tag: update.tag,
3570 payload: update.payload,
3571 callback: update.callback,
3572 next: null
3573 };
3574
3575 if (newLastBaseUpdate === null) {
3576 newFirstBaseUpdate = newLastBaseUpdate = clone;
3577 newBaseState = newState;
3578 } else {
3579 newLastBaseUpdate = newLastBaseUpdate.next = clone;
3580 } // Update the remaining priority in the queue.
3581
3582
3583 newLanes = mergeLanes(newLanes, updateLane);
3584 } else {
3585 // This update does have sufficient priority.
3586 if (newLastBaseUpdate !== null) {
3587 var _clone = {
3588 eventTime: updateEventTime,
3589 // This update is going to be committed so we never want uncommit
3590 // it. Using NoLane works because 0 is a subset of all bitmasks, so
3591 // this will never be skipped by the check above.
3592 lane: NoLane,
3593 tag: update.tag,
3594 payload: update.payload,
3595 callback: update.callback,
3596 next: null
3597 };
3598 newLastBaseUpdate = newLastBaseUpdate.next = _clone;
3599 } // Process this update.
3600
3601
3602 newState = getStateFromUpdate(workInProgress, queue, update, newState, props, instance);
3603 var callback = update.callback;
3604
3605 if (callback !== null) {
3606 workInProgress.flags |= Callback;
3607 var effects = queue.effects;
3608
3609 if (effects === null) {
3610 queue.effects = [update];
3611 } else {
3612 effects.push(update);
3613 }
3614 }
3615 }
3616
3617 update = update.next;
3618
3619 if (update === null) {
3620 pendingQueue = queue.shared.pending;
3621
3622 if (pendingQueue === null) {
3623 break;
3624 } else {
3625 // An update was scheduled from inside a reducer. Add the new
3626 // pending updates to the end of the list and keep processing.
3627 var _lastPendingUpdate = pendingQueue; // Intentionally unsound. Pending updates form a circular list, but we
3628 // unravel them when transferring them to the base queue.
3629
3630 var _firstPendingUpdate = _lastPendingUpdate.next;
3631 _lastPendingUpdate.next = null;
3632 update = _firstPendingUpdate;
3633 queue.lastBaseUpdate = _lastPendingUpdate;
3634 queue.shared.pending = null;
3635 }
3636 }
3637 } while (true);
3638
3639 if (newLastBaseUpdate === null) {
3640 newBaseState = newState;
3641 }
3642
3643 queue.baseState = newBaseState;
3644 queue.firstBaseUpdate = newFirstBaseUpdate;
3645 queue.lastBaseUpdate = newLastBaseUpdate; // Set the remaining expiration time to be whatever is remaining in the queue.
3646 // This should be fine because the only two other things that contribute to
3647 // expiration time are props and context. We're already in the middle of the
3648 // begin phase by the time we start processing the queue, so we've already
3649 // dealt with the props. Context in components that specify
3650 // shouldComponentUpdate is tricky; but we'll have to account for
3651 // that regardless.
3652
3653 markSkippedUpdateLanes(newLanes);
3654 workInProgress.lanes = newLanes;
3655 workInProgress.memoizedState = newState;
3656 }
3657
3658 {
3659 currentlyProcessingQueue = null;
3660 }
3661 }
3662
3663 function callCallback(callback, context) {
3664 if (!(typeof callback === 'function')) {
3665 {
3666 throw Error( "Invalid argument passed as callback. Expected a function. Instead received: " + callback );
3667 }
3668 }
3669
3670 callback.call(context);
3671 }
3672
3673 function resetHasForceUpdateBeforeProcessing() {
3674 hasForceUpdate = false;
3675 }
3676 function checkHasForceUpdateAfterProcessing() {
3677 return hasForceUpdate;
3678 }
3679 function commitUpdateQueue(finishedWork, finishedQueue, instance) {
3680 // Commit the effects
3681 var effects = finishedQueue.effects;
3682 finishedQueue.effects = null;
3683
3684 if (effects !== null) {
3685 for (var i = 0; i < effects.length; i++) {
3686 var effect = effects[i];
3687 var callback = effect.callback;
3688
3689 if (callback !== null) {
3690 effect.callback = null;
3691 callCallback(callback, instance);
3692 }
3693 }
3694 }
3695 }
3696
3697 var fakeInternalInstance = {};
3698 var isArray = Array.isArray; // React.Component uses a shared frozen object by default.
3699 // We'll use it to determine whether we need to initialize legacy refs.
3700
3701 var emptyRefsObject = new React.Component().refs;
3702 var didWarnAboutStateAssignmentForComponent;
3703 var didWarnAboutUninitializedState;
3704 var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
3705 var didWarnAboutLegacyLifecyclesAndDerivedState;
3706 var didWarnAboutUndefinedDerivedState;
3707 var warnOnUndefinedDerivedState;
3708 var warnOnInvalidCallback;
3709 var didWarnAboutDirectlyAssigningPropsToState;
3710 var didWarnAboutContextTypeAndContextTypes;
3711 var didWarnAboutInvalidateContextType;
3712
3713 {
3714 didWarnAboutStateAssignmentForComponent = new Set();
3715 didWarnAboutUninitializedState = new Set();
3716 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
3717 didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
3718 didWarnAboutDirectlyAssigningPropsToState = new Set();
3719 didWarnAboutUndefinedDerivedState = new Set();
3720 didWarnAboutContextTypeAndContextTypes = new Set();
3721 didWarnAboutInvalidateContextType = new Set();
3722 var didWarnOnInvalidCallback = new Set();
3723
3724 warnOnInvalidCallback = function (callback, callerName) {
3725 if (callback === null || typeof callback === 'function') {
3726 return;
3727 }
3728
3729 var key = callerName + '_' + callback;
3730
3731 if (!didWarnOnInvalidCallback.has(key)) {
3732 didWarnOnInvalidCallback.add(key);
3733
3734 error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
3735 }
3736 };
3737
3738 warnOnUndefinedDerivedState = function (type, partialState) {
3739 if (partialState === undefined) {
3740 var componentName = getComponentName(type) || 'Component';
3741
3742 if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
3743 didWarnAboutUndefinedDerivedState.add(componentName);
3744
3745 error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
3746 }
3747 }
3748 }; // This is so gross but it's at least non-critical and can be removed if
3749 // it causes problems. This is meant to give a nicer error message for
3750 // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
3751 // ...)) which otherwise throws a "_processChildContext is not a function"
3752 // exception.
3753
3754
3755 Object.defineProperty(fakeInternalInstance, '_processChildContext', {
3756 enumerable: false,
3757 value: function () {
3758 {
3759 {
3760 throw Error( "_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)." );
3761 }
3762 }
3763 }
3764 });
3765 Object.freeze(fakeInternalInstance);
3766 }
3767
3768 function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
3769 var prevState = workInProgress.memoizedState;
3770
3771 var partialState = getDerivedStateFromProps(nextProps, prevState);
3772
3773 {
3774 warnOnUndefinedDerivedState(ctor, partialState);
3775 } // Merge the partial state and the previous state.
3776
3777
3778 var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
3779 workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the
3780 // base state.
3781
3782 if (workInProgress.lanes === NoLanes) {
3783 // Queue is always non-null for classes
3784 var updateQueue = workInProgress.updateQueue;
3785 updateQueue.baseState = memoizedState;
3786 }
3787 }
3788 var classComponentUpdater = {
3789 isMounted: isMounted,
3790 enqueueSetState: function (inst, payload, callback) {
3791 var fiber = get(inst);
3792 var eventTime = requestEventTime();
3793 var lane = requestUpdateLane(fiber);
3794 var update = createUpdate(eventTime, lane);
3795 update.payload = payload;
3796
3797 if (callback !== undefined && callback !== null) {
3798 {
3799 warnOnInvalidCallback(callback, 'setState');
3800 }
3801
3802 update.callback = callback;
3803 }
3804
3805 enqueueUpdate(fiber, update);
3806 scheduleUpdateOnFiber(fiber, lane, eventTime);
3807 },
3808 enqueueReplaceState: function (inst, payload, callback) {
3809 var fiber = get(inst);
3810 var eventTime = requestEventTime();
3811 var lane = requestUpdateLane(fiber);
3812 var update = createUpdate(eventTime, lane);
3813 update.tag = ReplaceState;
3814 update.payload = payload;
3815
3816 if (callback !== undefined && callback !== null) {
3817 {
3818 warnOnInvalidCallback(callback, 'replaceState');
3819 }
3820
3821 update.callback = callback;
3822 }
3823
3824 enqueueUpdate(fiber, update);
3825 scheduleUpdateOnFiber(fiber, lane, eventTime);
3826 },
3827 enqueueForceUpdate: function (inst, callback) {
3828 var fiber = get(inst);
3829 var eventTime = requestEventTime();
3830 var lane = requestUpdateLane(fiber);
3831 var update = createUpdate(eventTime, lane);
3832 update.tag = ForceUpdate;
3833
3834 if (callback !== undefined && callback !== null) {
3835 {
3836 warnOnInvalidCallback(callback, 'forceUpdate');
3837 }
3838
3839 update.callback = callback;
3840 }
3841
3842 enqueueUpdate(fiber, update);
3843 scheduleUpdateOnFiber(fiber, lane, eventTime);
3844 }
3845 };
3846
3847 function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
3848 var instance = workInProgress.stateNode;
3849
3850 if (typeof instance.shouldComponentUpdate === 'function') {
3851
3852 var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
3853
3854 {
3855 if (shouldUpdate === undefined) {
3856 error('%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentName(ctor) || 'Component');
3857 }
3858 }
3859
3860 return shouldUpdate;
3861 }
3862
3863 if (ctor.prototype && ctor.prototype.isPureReactComponent) {
3864 return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
3865 }
3866
3867 return true;
3868 }
3869
3870 function checkClassInstance(workInProgress, ctor, newProps) {
3871 var instance = workInProgress.stateNode;
3872
3873 {
3874 var name = getComponentName(ctor) || 'Component';
3875 var renderPresent = instance.render;
3876
3877 if (!renderPresent) {
3878 if (ctor.prototype && typeof ctor.prototype.render === 'function') {
3879 error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
3880 } else {
3881 error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
3882 }
3883 }
3884
3885 if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {
3886 error('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);
3887 }
3888
3889 if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {
3890 error('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);
3891 }
3892
3893 if (instance.propTypes) {
3894 error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);
3895 }
3896
3897 if (instance.contextType) {
3898 error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);
3899 }
3900
3901 {
3902 if (instance.contextTypes) {
3903 error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name);
3904 }
3905
3906 if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
3907 didWarnAboutContextTypeAndContextTypes.add(ctor);
3908
3909 error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
3910 }
3911 }
3912
3913 if (typeof instance.componentShouldUpdate === 'function') {
3914 error('%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);
3915 }
3916
3917 if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
3918 error('%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');
3919 }
3920
3921 if (typeof instance.componentDidUnmount === 'function') {
3922 error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);
3923 }
3924
3925 if (typeof instance.componentDidReceiveProps === 'function') {
3926 error('%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);
3927 }
3928
3929 if (typeof instance.componentWillRecieveProps === 'function') {
3930 error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);
3931 }
3932
3933 if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {
3934 error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);
3935 }
3936
3937 var hasMutatedProps = instance.props !== newProps;
3938
3939 if (instance.props !== undefined && hasMutatedProps) {
3940 error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name);
3941 }
3942
3943 if (instance.defaultProps) {
3944 error('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);
3945 }
3946
3947 if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
3948 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
3949
3950 error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor));
3951 }
3952
3953 if (typeof instance.getDerivedStateFromProps === 'function') {
3954 error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
3955 }
3956
3957 if (typeof instance.getDerivedStateFromError === 'function') {
3958 error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
3959 }
3960
3961 if (typeof ctor.getSnapshotBeforeUpdate === 'function') {
3962 error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);
3963 }
3964
3965 var _state = instance.state;
3966
3967 if (_state && (typeof _state !== 'object' || isArray(_state))) {
3968 error('%s.state: must be set to an object or null', name);
3969 }
3970
3971 if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {
3972 error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);
3973 }
3974 }
3975 }
3976
3977 function adoptClassInstance(workInProgress, instance) {
3978 instance.updater = classComponentUpdater;
3979 workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates
3980
3981 set(instance, workInProgress);
3982
3983 {
3984 instance._reactInternalInstance = fakeInternalInstance;
3985 }
3986 }
3987
3988 function constructClassInstance(workInProgress, ctor, props) {
3989 var isLegacyContextConsumer = false;
3990 var unmaskedContext = emptyContextObject;
3991 var context = emptyContextObject;
3992 var contextType = ctor.contextType;
3993
3994 {
3995 if ('contextType' in ctor) {
3996 var isValid = // Allow null for conditional declaration
3997 contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>
3998
3999 if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
4000 didWarnAboutInvalidateContextType.add(ctor);
4001 var addendum = '';
4002
4003 if (contextType === undefined) {
4004 addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';
4005 } else if (typeof contextType !== 'object') {
4006 addendum = ' However, it is set to a ' + typeof contextType + '.';
4007 } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
4008 addendum = ' Did you accidentally pass the Context.Provider instead?';
4009 } else if (contextType._context !== undefined) {
4010 // <Context.Consumer>
4011 addendum = ' Did you accidentally pass the Context.Consumer instead?';
4012 } else {
4013 addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
4014 }
4015
4016 error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentName(ctor) || 'Component', addendum);
4017 }
4018 }
4019 }
4020
4021 if (typeof contextType === 'object' && contextType !== null) {
4022 context = readContext(contextType);
4023 } else {
4024 unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
4025 var contextTypes = ctor.contextTypes;
4026 isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
4027 context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
4028 } // Instantiate twice to help detect side-effects.
4029
4030 var instance = new ctor(props, context);
4031 var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
4032 adoptClassInstance(workInProgress, instance);
4033
4034 {
4035 if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
4036 var componentName = getComponentName(ctor) || 'Component';
4037
4038 if (!didWarnAboutUninitializedState.has(componentName)) {
4039 didWarnAboutUninitializedState.add(componentName);
4040
4041 error('`%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);
4042 }
4043 } // If new component APIs are defined, "unsafe" lifecycles won't be called.
4044 // Warn about these lifecycles if they are present.
4045 // Don't warn about react-lifecycles-compat polyfilled methods though.
4046
4047
4048 if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
4049 var foundWillMountName = null;
4050 var foundWillReceivePropsName = null;
4051 var foundWillUpdateName = null;
4052
4053 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
4054 foundWillMountName = 'componentWillMount';
4055 } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
4056 foundWillMountName = 'UNSAFE_componentWillMount';
4057 }
4058
4059 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
4060 foundWillReceivePropsName = 'componentWillReceiveProps';
4061 } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
4062 foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
4063 }
4064
4065 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
4066 foundWillUpdateName = 'componentWillUpdate';
4067 } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
4068 foundWillUpdateName = 'UNSAFE_componentWillUpdate';
4069 }
4070
4071 if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
4072 var _componentName = getComponentName(ctor) || 'Component';
4073
4074 var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
4075
4076 if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
4077 didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
4078
4079 error('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://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n " + foundWillUpdateName : '');
4080 }
4081 }
4082 }
4083 } // Cache unmasked context so we can avoid recreating masked context unless necessary.
4084 // ReactFiberContext usually updates this cache but can't for newly-created instances.
4085
4086
4087 if (isLegacyContextConsumer) {
4088 cacheContext(workInProgress, unmaskedContext, context);
4089 }
4090
4091 return instance;
4092 }
4093
4094 function callComponentWillMount(workInProgress, instance) {
4095 var oldState = instance.state;
4096
4097 if (typeof instance.componentWillMount === 'function') {
4098 instance.componentWillMount();
4099 }
4100
4101 if (typeof instance.UNSAFE_componentWillMount === 'function') {
4102 instance.UNSAFE_componentWillMount();
4103 }
4104
4105 if (oldState !== instance.state) {
4106 {
4107 error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentName(workInProgress.type) || 'Component');
4108 }
4109
4110 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
4111 }
4112 }
4113
4114 function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
4115 var oldState = instance.state;
4116
4117 if (typeof instance.componentWillReceiveProps === 'function') {
4118 instance.componentWillReceiveProps(newProps, nextContext);
4119 }
4120
4121 if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
4122 instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
4123 }
4124
4125 if (instance.state !== oldState) {
4126 {
4127 var componentName = getComponentName(workInProgress.type) || 'Component';
4128
4129 if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
4130 didWarnAboutStateAssignmentForComponent.add(componentName);
4131
4132 error('%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
4133 }
4134 }
4135
4136 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
4137 }
4138 } // Invokes the mount life-cycles on a previously never rendered instance.
4139
4140
4141 function mountClassInstance(workInProgress, ctor, newProps, renderLanes) {
4142 {
4143 checkClassInstance(workInProgress, ctor, newProps);
4144 }
4145
4146 var instance = workInProgress.stateNode;
4147 instance.props = newProps;
4148 instance.state = workInProgress.memoizedState;
4149 instance.refs = emptyRefsObject;
4150 initializeUpdateQueue(workInProgress);
4151 var contextType = ctor.contextType;
4152
4153 if (typeof contextType === 'object' && contextType !== null) {
4154 instance.context = readContext(contextType);
4155 } else {
4156 var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
4157 instance.context = getMaskedContext(workInProgress, unmaskedContext);
4158 }
4159
4160 {
4161 if (instance.state === newProps) {
4162 var componentName = getComponentName(ctor) || 'Component';
4163
4164 if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
4165 didWarnAboutDirectlyAssigningPropsToState.add(componentName);
4166
4167 error('%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);
4168 }
4169 }
4170
4171 if (workInProgress.mode & StrictMode) {
4172 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
4173 }
4174
4175 {
4176 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
4177 }
4178 }
4179
4180 processUpdateQueue(workInProgress, newProps, instance, renderLanes);
4181 instance.state = workInProgress.memoizedState;
4182 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
4183
4184 if (typeof getDerivedStateFromProps === 'function') {
4185 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
4186 instance.state = workInProgress.memoizedState;
4187 } // In order to support react-lifecycles-compat polyfilled components,
4188 // Unsafe lifecycles should not be invoked for components using the new APIs.
4189
4190
4191 if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
4192 callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's
4193 // process them now.
4194
4195 processUpdateQueue(workInProgress, newProps, instance, renderLanes);
4196 instance.state = workInProgress.memoizedState;
4197 }
4198
4199 if (typeof instance.componentDidMount === 'function') {
4200 workInProgress.flags |= Update;
4201 }
4202 }
4203
4204 function resumeMountClassInstance(workInProgress, ctor, newProps, renderLanes) {
4205 var instance = workInProgress.stateNode;
4206 var oldProps = workInProgress.memoizedProps;
4207 instance.props = oldProps;
4208 var oldContext = instance.context;
4209 var contextType = ctor.contextType;
4210 var nextContext = emptyContextObject;
4211
4212 if (typeof contextType === 'object' && contextType !== null) {
4213 nextContext = readContext(contextType);
4214 } else {
4215 var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
4216 nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
4217 }
4218
4219 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
4220 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
4221 // ever the previously attempted to render - not the "current". However,
4222 // during componentDidUpdate we pass the "current" props.
4223 // In order to support react-lifecycles-compat polyfilled components,
4224 // Unsafe lifecycles should not be invoked for components using the new APIs.
4225
4226 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
4227 if (oldProps !== newProps || oldContext !== nextContext) {
4228 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
4229 }
4230 }
4231
4232 resetHasForceUpdateBeforeProcessing();
4233 var oldState = workInProgress.memoizedState;
4234 var newState = instance.state = oldState;
4235 processUpdateQueue(workInProgress, newProps, instance, renderLanes);
4236 newState = workInProgress.memoizedState;
4237
4238 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
4239 // If an update was already in progress, we should schedule an Update
4240 // effect even though we're bailing out, so that cWU/cDU are called.
4241 if (typeof instance.componentDidMount === 'function') {
4242 workInProgress.flags |= Update;
4243 }
4244
4245 return false;
4246 }
4247
4248 if (typeof getDerivedStateFromProps === 'function') {
4249 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
4250 newState = workInProgress.memoizedState;
4251 }
4252
4253 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
4254
4255 if (shouldUpdate) {
4256 // In order to support react-lifecycles-compat polyfilled components,
4257 // Unsafe lifecycles should not be invoked for components using the new APIs.
4258 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
4259 if (typeof instance.componentWillMount === 'function') {
4260 instance.componentWillMount();
4261 }
4262
4263 if (typeof instance.UNSAFE_componentWillMount === 'function') {
4264 instance.UNSAFE_componentWillMount();
4265 }
4266 }
4267
4268 if (typeof instance.componentDidMount === 'function') {
4269 workInProgress.flags |= Update;
4270 }
4271 } else {
4272 // If an update was already in progress, we should schedule an Update
4273 // effect even though we're bailing out, so that cWU/cDU are called.
4274 if (typeof instance.componentDidMount === 'function') {
4275 workInProgress.flags |= Update;
4276 } // If shouldComponentUpdate returned false, we should still update the
4277 // memoized state to indicate that this work can be reused.
4278
4279
4280 workInProgress.memoizedProps = newProps;
4281 workInProgress.memoizedState = newState;
4282 } // Update the existing instance's state, props, and context pointers even
4283 // if shouldComponentUpdate returns false.
4284
4285
4286 instance.props = newProps;
4287 instance.state = newState;
4288 instance.context = nextContext;
4289 return shouldUpdate;
4290 } // Invokes the update life-cycles and returns false if it shouldn't rerender.
4291
4292
4293 function updateClassInstance(current, workInProgress, ctor, newProps, renderLanes) {
4294 var instance = workInProgress.stateNode;
4295 cloneUpdateQueue(current, workInProgress);
4296 var unresolvedOldProps = workInProgress.memoizedProps;
4297 var oldProps = workInProgress.type === workInProgress.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress.type, unresolvedOldProps);
4298 instance.props = oldProps;
4299 var unresolvedNewProps = workInProgress.pendingProps;
4300 var oldContext = instance.context;
4301 var contextType = ctor.contextType;
4302 var nextContext = emptyContextObject;
4303
4304 if (typeof contextType === 'object' && contextType !== null) {
4305 nextContext = readContext(contextType);
4306 } else {
4307 var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
4308 nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
4309 }
4310
4311 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
4312 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
4313 // ever the previously attempted to render - not the "current". However,
4314 // during componentDidUpdate we pass the "current" props.
4315 // In order to support react-lifecycles-compat polyfilled components,
4316 // Unsafe lifecycles should not be invoked for components using the new APIs.
4317
4318 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
4319 if (unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext) {
4320 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
4321 }
4322 }
4323
4324 resetHasForceUpdateBeforeProcessing();
4325 var oldState = workInProgress.memoizedState;
4326 var newState = instance.state = oldState;
4327 processUpdateQueue(workInProgress, newProps, instance, renderLanes);
4328 newState = workInProgress.memoizedState;
4329
4330 if (unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
4331 // If an update was already in progress, we should schedule an Update
4332 // effect even though we're bailing out, so that cWU/cDU are called.
4333 if (typeof instance.componentDidUpdate === 'function') {
4334 if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
4335 workInProgress.flags |= Update;
4336 }
4337 }
4338
4339 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
4340 if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
4341 workInProgress.flags |= Snapshot;
4342 }
4343 }
4344
4345 return false;
4346 }
4347
4348 if (typeof getDerivedStateFromProps === 'function') {
4349 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
4350 newState = workInProgress.memoizedState;
4351 }
4352
4353 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
4354
4355 if (shouldUpdate) {
4356 // In order to support react-lifecycles-compat polyfilled components,
4357 // Unsafe lifecycles should not be invoked for components using the new APIs.
4358 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
4359 if (typeof instance.componentWillUpdate === 'function') {
4360 instance.componentWillUpdate(newProps, newState, nextContext);
4361 }
4362
4363 if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
4364 instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
4365 }
4366 }
4367
4368 if (typeof instance.componentDidUpdate === 'function') {
4369 workInProgress.flags |= Update;
4370 }
4371
4372 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
4373 workInProgress.flags |= Snapshot;
4374 }
4375 } else {
4376 // If an update was already in progress, we should schedule an Update
4377 // effect even though we're bailing out, so that cWU/cDU are called.
4378 if (typeof instance.componentDidUpdate === 'function') {
4379 if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
4380 workInProgress.flags |= Update;
4381 }
4382 }
4383
4384 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
4385 if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
4386 workInProgress.flags |= Snapshot;
4387 }
4388 } // If shouldComponentUpdate returned false, we should still update the
4389 // memoized props/state to indicate that this work can be reused.
4390
4391
4392 workInProgress.memoizedProps = newProps;
4393 workInProgress.memoizedState = newState;
4394 } // Update the existing instance's state, props, and context pointers even
4395 // if shouldComponentUpdate returns false.
4396
4397
4398 instance.props = newProps;
4399 instance.state = newState;
4400 instance.context = nextContext;
4401 return shouldUpdate;
4402 }
4403
4404 var didWarnAboutMaps;
4405 var didWarnAboutGenerators;
4406 var didWarnAboutStringRefs;
4407 var ownerHasKeyUseWarning;
4408 var ownerHasFunctionTypeWarning;
4409
4410 var warnForMissingKey = function (child, returnFiber) {};
4411
4412 {
4413 didWarnAboutMaps = false;
4414 didWarnAboutGenerators = false;
4415 didWarnAboutStringRefs = {};
4416 /**
4417 * Warn if there's no key explicitly set on dynamic arrays of children or
4418 * object keys are not valid. This allows us to keep track of children between
4419 * updates.
4420 */
4421
4422 ownerHasKeyUseWarning = {};
4423 ownerHasFunctionTypeWarning = {};
4424
4425 warnForMissingKey = function (child, returnFiber) {
4426 if (child === null || typeof child !== 'object') {
4427 return;
4428 }
4429
4430 if (!child._store || child._store.validated || child.key != null) {
4431 return;
4432 }
4433
4434 if (!(typeof child._store === 'object')) {
4435 {
4436 throw Error( "React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue." );
4437 }
4438 }
4439
4440 child._store.validated = true;
4441 var componentName = getComponentName(returnFiber.type) || 'Component';
4442
4443 if (ownerHasKeyUseWarning[componentName]) {
4444 return;
4445 }
4446
4447 ownerHasKeyUseWarning[componentName] = true;
4448
4449 error('Each child in a list should have a unique ' + '"key" prop. See https://reactjs.org/link/warning-keys for ' + 'more information.');
4450 };
4451 }
4452
4453 var isArray$1 = Array.isArray;
4454
4455 function coerceRef(returnFiber, current, element) {
4456 var mixedRef = element.ref;
4457
4458 if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
4459 {
4460 // TODO: Clean this up once we turn on the string ref warning for
4461 // everyone, because the strict mode case will no longer be relevant
4462 if ((returnFiber.mode & StrictMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs
4463 // because these cannot be automatically converted to an arrow function
4464 // using a codemod. Therefore, we don't have to warn about string refs again.
4465 !(element._owner && element._self && element._owner.stateNode !== element._self)) {
4466 var componentName = getComponentName(returnFiber.type) || 'Component';
4467
4468 if (!didWarnAboutStringRefs[componentName]) {
4469 {
4470 error('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 useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', mixedRef);
4471 }
4472
4473 didWarnAboutStringRefs[componentName] = true;
4474 }
4475 }
4476 }
4477
4478 if (element._owner) {
4479 var owner = element._owner;
4480 var inst;
4481
4482 if (owner) {
4483 var ownerFiber = owner;
4484
4485 if (!(ownerFiber.tag === ClassComponent)) {
4486 {
4487 throw Error( "Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref" );
4488 }
4489 }
4490
4491 inst = ownerFiber.stateNode;
4492 }
4493
4494 if (!inst) {
4495 {
4496 throw Error( "Missing owner for string ref " + mixedRef + ". This error is likely caused by a bug in React. Please file an issue." );
4497 }
4498 }
4499
4500 var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref
4501
4502 if (current !== null && current.ref !== null && typeof current.ref === 'function' && current.ref._stringRef === stringRef) {
4503 return current.ref;
4504 }
4505
4506 var ref = function (value) {
4507 var refs = inst.refs;
4508
4509 if (refs === emptyRefsObject) {
4510 // This is a lazy pooled frozen object, so we need to initialize.
4511 refs = inst.refs = {};
4512 }
4513
4514 if (value === null) {
4515 delete refs[stringRef];
4516 } else {
4517 refs[stringRef] = value;
4518 }
4519 };
4520
4521 ref._stringRef = stringRef;
4522 return ref;
4523 } else {
4524 if (!(typeof mixedRef === 'string')) {
4525 {
4526 throw Error( "Expected ref to be a function, a string, an object returned by React.createRef(), or null." );
4527 }
4528 }
4529
4530 if (!element._owner) {
4531 {
4532 throw Error( "Element ref was specified as a string (" + mixedRef + ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://reactjs.org/link/refs-must-have-owner for more information." );
4533 }
4534 }
4535 }
4536 }
4537
4538 return mixedRef;
4539 }
4540
4541 function throwOnInvalidObjectType(returnFiber, newChild) {
4542 if (returnFiber.type !== 'textarea') {
4543 {
4544 {
4545 throw Error( "Objects are not valid as a React child (found: " + (Object.prototype.toString.call(newChild) === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : newChild) + "). If you meant to render a collection of children, use an array instead." );
4546 }
4547 }
4548 }
4549 }
4550
4551 function warnOnFunctionType(returnFiber) {
4552 {
4553 var componentName = getComponentName(returnFiber.type) || 'Component';
4554
4555 if (ownerHasFunctionTypeWarning[componentName]) {
4556 return;
4557 }
4558
4559 ownerHasFunctionTypeWarning[componentName] = true;
4560
4561 error('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.');
4562 }
4563 } // We avoid inlining this to avoid potential deopts from using try/catch.
4564 // to be able to optimize each path individually by branching early. This needs
4565 // a compiler or we can do it manually. Helpers that don't need this branching
4566 // live outside of this function.
4567
4568
4569 function ChildReconciler(shouldTrackSideEffects) {
4570 function deleteChild(returnFiber, childToDelete) {
4571 if (!shouldTrackSideEffects) {
4572 // Noop.
4573 return;
4574 } // Deletions are added in reversed order so we add it to the front.
4575 // At this point, the return fiber's effect list is empty except for
4576 // deletions, so we can just append the deletion to the list. The remaining
4577 // effects aren't added until the complete phase. Once we implement
4578 // resuming, this may not be true.
4579
4580
4581 var last = returnFiber.lastEffect;
4582
4583 if (last !== null) {
4584 last.nextEffect = childToDelete;
4585 returnFiber.lastEffect = childToDelete;
4586 } else {
4587 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
4588 }
4589
4590 childToDelete.nextEffect = null;
4591 childToDelete.flags = Deletion;
4592 }
4593
4594 function deleteRemainingChildren(returnFiber, currentFirstChild) {
4595 if (!shouldTrackSideEffects) {
4596 // Noop.
4597 return null;
4598 } // TODO: For the shouldClone case, this could be micro-optimized a bit by
4599 // assuming that after the first child we've already added everything.
4600
4601
4602 var childToDelete = currentFirstChild;
4603
4604 while (childToDelete !== null) {
4605 deleteChild(returnFiber, childToDelete);
4606 childToDelete = childToDelete.sibling;
4607 }
4608
4609 return null;
4610 }
4611
4612 function mapRemainingChildren(returnFiber, currentFirstChild) {
4613 // Add the remaining children to a temporary map so that we can find them by
4614 // keys quickly. Implicit (null) keys get added to this set with their index
4615 // instead.
4616 var existingChildren = new Map();
4617 var existingChild = currentFirstChild;
4618
4619 while (existingChild !== null) {
4620 if (existingChild.key !== null) {
4621 existingChildren.set(existingChild.key, existingChild);
4622 } else {
4623 existingChildren.set(existingChild.index, existingChild);
4624 }
4625
4626 existingChild = existingChild.sibling;
4627 }
4628
4629 return existingChildren;
4630 }
4631
4632 function useFiber(fiber, pendingProps) {
4633 // We currently set sibling to null and index to 0 here because it is easy
4634 // to forget to do before returning it. E.g. for the single child case.
4635 var clone = createWorkInProgress(fiber, pendingProps);
4636 clone.index = 0;
4637 clone.sibling = null;
4638 return clone;
4639 }
4640
4641 function placeChild(newFiber, lastPlacedIndex, newIndex) {
4642 newFiber.index = newIndex;
4643
4644 if (!shouldTrackSideEffects) {
4645 // Noop.
4646 return lastPlacedIndex;
4647 }
4648
4649 var current = newFiber.alternate;
4650
4651 if (current !== null) {
4652 var oldIndex = current.index;
4653
4654 if (oldIndex < lastPlacedIndex) {
4655 // This is a move.
4656 newFiber.flags = Placement;
4657 return lastPlacedIndex;
4658 } else {
4659 // This item can stay in place.
4660 return oldIndex;
4661 }
4662 } else {
4663 // This is an insertion.
4664 newFiber.flags = Placement;
4665 return lastPlacedIndex;
4666 }
4667 }
4668
4669 function placeSingleChild(newFiber) {
4670 // This is simpler for the single child case. We only need to do a
4671 // placement for inserting new children.
4672 if (shouldTrackSideEffects && newFiber.alternate === null) {
4673 newFiber.flags = Placement;
4674 }
4675
4676 return newFiber;
4677 }
4678
4679 function updateTextNode(returnFiber, current, textContent, lanes) {
4680 if (current === null || current.tag !== HostText) {
4681 // Insert
4682 var created = createFiberFromText(textContent, returnFiber.mode, lanes);
4683 created.return = returnFiber;
4684 return created;
4685 } else {
4686 // Update
4687 var existing = useFiber(current, textContent);
4688 existing.return = returnFiber;
4689 return existing;
4690 }
4691 }
4692
4693 function updateElement(returnFiber, current, element, lanes) {
4694 if (current !== null) {
4695 if (current.elementType === element.type || ( // Keep this check inline so it only runs on the false path:
4696 isCompatibleFamilyForHotReloading(current, element) )) {
4697 // Move based on index
4698 var existing = useFiber(current, element.props);
4699 existing.ref = coerceRef(returnFiber, current, element);
4700 existing.return = returnFiber;
4701
4702 {
4703 existing._debugSource = element._source;
4704 existing._debugOwner = element._owner;
4705 }
4706
4707 return existing;
4708 }
4709 } // Insert
4710
4711
4712 var created = createFiberFromElement(element, returnFiber.mode, lanes);
4713 created.ref = coerceRef(returnFiber, current, element);
4714 created.return = returnFiber;
4715 return created;
4716 }
4717
4718 function updatePortal(returnFiber, current, portal, lanes) {
4719 if (current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) {
4720 // Insert
4721 var created = createFiberFromPortal(portal, returnFiber.mode, lanes);
4722 created.return = returnFiber;
4723 return created;
4724 } else {
4725 // Update
4726 var existing = useFiber(current, portal.children || []);
4727 existing.return = returnFiber;
4728 return existing;
4729 }
4730 }
4731
4732 function updateFragment(returnFiber, current, fragment, lanes, key) {
4733 if (current === null || current.tag !== Fragment) {
4734 // Insert
4735 var created = createFiberFromFragment(fragment, returnFiber.mode, lanes, key);
4736 created.return = returnFiber;
4737 return created;
4738 } else {
4739 // Update
4740 var existing = useFiber(current, fragment);
4741 existing.return = returnFiber;
4742 return existing;
4743 }
4744 }
4745
4746 function createChild(returnFiber, newChild, lanes) {
4747 if (typeof newChild === 'string' || typeof newChild === 'number') {
4748 // Text nodes don't have keys. If the previous node is implicitly keyed
4749 // we can continue to replace it without aborting even if it is not a text
4750 // node.
4751 var created = createFiberFromText('' + newChild, returnFiber.mode, lanes);
4752 created.return = returnFiber;
4753 return created;
4754 }
4755
4756 if (typeof newChild === 'object' && newChild !== null) {
4757 switch (newChild.$$typeof) {
4758 case REACT_ELEMENT_TYPE:
4759 {
4760 var _created = createFiberFromElement(newChild, returnFiber.mode, lanes);
4761
4762 _created.ref = coerceRef(returnFiber, null, newChild);
4763 _created.return = returnFiber;
4764 return _created;
4765 }
4766
4767 case REACT_PORTAL_TYPE:
4768 {
4769 var _created2 = createFiberFromPortal(newChild, returnFiber.mode, lanes);
4770
4771 _created2.return = returnFiber;
4772 return _created2;
4773 }
4774 }
4775
4776 if (isArray$1(newChild) || getIteratorFn(newChild)) {
4777 var _created3 = createFiberFromFragment(newChild, returnFiber.mode, lanes, null);
4778
4779 _created3.return = returnFiber;
4780 return _created3;
4781 }
4782
4783 throwOnInvalidObjectType(returnFiber, newChild);
4784 }
4785
4786 {
4787 if (typeof newChild === 'function') {
4788 warnOnFunctionType(returnFiber);
4789 }
4790 }
4791
4792 return null;
4793 }
4794
4795 function updateSlot(returnFiber, oldFiber, newChild, lanes) {
4796 // Update the fiber if the keys match, otherwise return null.
4797 var key = oldFiber !== null ? oldFiber.key : null;
4798
4799 if (typeof newChild === 'string' || typeof newChild === 'number') {
4800 // Text nodes don't have keys. If the previous node is implicitly keyed
4801 // we can continue to replace it without aborting even if it is not a text
4802 // node.
4803 if (key !== null) {
4804 return null;
4805 }
4806
4807 return updateTextNode(returnFiber, oldFiber, '' + newChild, lanes);
4808 }
4809
4810 if (typeof newChild === 'object' && newChild !== null) {
4811 switch (newChild.$$typeof) {
4812 case REACT_ELEMENT_TYPE:
4813 {
4814 if (newChild.key === key) {
4815 if (newChild.type === REACT_FRAGMENT_TYPE) {
4816 return updateFragment(returnFiber, oldFiber, newChild.props.children, lanes, key);
4817 }
4818
4819 return updateElement(returnFiber, oldFiber, newChild, lanes);
4820 } else {
4821 return null;
4822 }
4823 }
4824
4825 case REACT_PORTAL_TYPE:
4826 {
4827 if (newChild.key === key) {
4828 return updatePortal(returnFiber, oldFiber, newChild, lanes);
4829 } else {
4830 return null;
4831 }
4832 }
4833 }
4834
4835 if (isArray$1(newChild) || getIteratorFn(newChild)) {
4836 if (key !== null) {
4837 return null;
4838 }
4839
4840 return updateFragment(returnFiber, oldFiber, newChild, lanes, null);
4841 }
4842
4843 throwOnInvalidObjectType(returnFiber, newChild);
4844 }
4845
4846 {
4847 if (typeof newChild === 'function') {
4848 warnOnFunctionType(returnFiber);
4849 }
4850 }
4851
4852 return null;
4853 }
4854
4855 function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) {
4856 if (typeof newChild === 'string' || typeof newChild === 'number') {
4857 // Text nodes don't have keys, so we neither have to check the old nor
4858 // new node for the key. If both are text nodes, they match.
4859 var matchedFiber = existingChildren.get(newIdx) || null;
4860 return updateTextNode(returnFiber, matchedFiber, '' + newChild, lanes);
4861 }
4862
4863 if (typeof newChild === 'object' && newChild !== null) {
4864 switch (newChild.$$typeof) {
4865 case REACT_ELEMENT_TYPE:
4866 {
4867 var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
4868
4869 if (newChild.type === REACT_FRAGMENT_TYPE) {
4870 return updateFragment(returnFiber, _matchedFiber, newChild.props.children, lanes, newChild.key);
4871 }
4872
4873 return updateElement(returnFiber, _matchedFiber, newChild, lanes);
4874 }
4875
4876 case REACT_PORTAL_TYPE:
4877 {
4878 var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
4879
4880 return updatePortal(returnFiber, _matchedFiber2, newChild, lanes);
4881 }
4882
4883 }
4884
4885 if (isArray$1(newChild) || getIteratorFn(newChild)) {
4886 var _matchedFiber3 = existingChildren.get(newIdx) || null;
4887
4888 return updateFragment(returnFiber, _matchedFiber3, newChild, lanes, null);
4889 }
4890
4891 throwOnInvalidObjectType(returnFiber, newChild);
4892 }
4893
4894 {
4895 if (typeof newChild === 'function') {
4896 warnOnFunctionType(returnFiber);
4897 }
4898 }
4899
4900 return null;
4901 }
4902 /**
4903 * Warns if there is a duplicate or missing key
4904 */
4905
4906
4907 function warnOnInvalidKey(child, knownKeys, returnFiber) {
4908 {
4909 if (typeof child !== 'object' || child === null) {
4910 return knownKeys;
4911 }
4912
4913 switch (child.$$typeof) {
4914 case REACT_ELEMENT_TYPE:
4915 case REACT_PORTAL_TYPE:
4916 warnForMissingKey(child, returnFiber);
4917 var key = child.key;
4918
4919 if (typeof key !== 'string') {
4920 break;
4921 }
4922
4923 if (knownKeys === null) {
4924 knownKeys = new Set();
4925 knownKeys.add(key);
4926 break;
4927 }
4928
4929 if (!knownKeys.has(key)) {
4930 knownKeys.add(key);
4931 break;
4932 }
4933
4934 error('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);
4935
4936 break;
4937 }
4938 }
4939
4940 return knownKeys;
4941 }
4942
4943 function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) {
4944 // This algorithm can't optimize by searching from both ends since we
4945 // don't have backpointers on fibers. I'm trying to see how far we can get
4946 // with that model. If it ends up not being worth the tradeoffs, we can
4947 // add it later.
4948 // Even with a two ended optimization, we'd want to optimize for the case
4949 // where there are few changes and brute force the comparison instead of
4950 // going for the Map. It'd like to explore hitting that path first in
4951 // forward-only mode and only go for the Map once we notice that we need
4952 // lots of look ahead. This doesn't handle reversal as well as two ended
4953 // search but that's unusual. Besides, for the two ended optimization to
4954 // work on Iterables, we'd need to copy the whole set.
4955 // In this first iteration, we'll just live with hitting the bad case
4956 // (adding everything to a Map) in for every insert/move.
4957 // If you change this code, also update reconcileChildrenIterator() which
4958 // uses the same algorithm.
4959 {
4960 // First, validate keys.
4961 var knownKeys = null;
4962
4963 for (var i = 0; i < newChildren.length; i++) {
4964 var child = newChildren[i];
4965 knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
4966 }
4967 }
4968
4969 var resultingFirstChild = null;
4970 var previousNewFiber = null;
4971 var oldFiber = currentFirstChild;
4972 var lastPlacedIndex = 0;
4973 var newIdx = 0;
4974 var nextOldFiber = null;
4975
4976 for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
4977 if (oldFiber.index > newIdx) {
4978 nextOldFiber = oldFiber;
4979 oldFiber = null;
4980 } else {
4981 nextOldFiber = oldFiber.sibling;
4982 }
4983
4984 var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], lanes);
4985
4986 if (newFiber === null) {
4987 // TODO: This breaks on empty slots like null children. That's
4988 // unfortunate because it triggers the slow path all the time. We need
4989 // a better way to communicate whether this was a miss or null,
4990 // boolean, undefined, etc.
4991 if (oldFiber === null) {
4992 oldFiber = nextOldFiber;
4993 }
4994
4995 break;
4996 }
4997
4998 if (shouldTrackSideEffects) {
4999 if (oldFiber && newFiber.alternate === null) {
5000 // We matched the slot, but we didn't reuse the existing fiber, so we
5001 // need to delete the existing child.
5002 deleteChild(returnFiber, oldFiber);
5003 }
5004 }
5005
5006 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
5007
5008 if (previousNewFiber === null) {
5009 // TODO: Move out of the loop. This only happens for the first run.
5010 resultingFirstChild = newFiber;
5011 } else {
5012 // TODO: Defer siblings if we're not at the right index for this slot.
5013 // I.e. if we had null values before, then we want to defer this
5014 // for each null value. However, we also don't want to call updateSlot
5015 // with the previous one.
5016 previousNewFiber.sibling = newFiber;
5017 }
5018
5019 previousNewFiber = newFiber;
5020 oldFiber = nextOldFiber;
5021 }
5022
5023 if (newIdx === newChildren.length) {
5024 // We've reached the end of the new children. We can delete the rest.
5025 deleteRemainingChildren(returnFiber, oldFiber);
5026 return resultingFirstChild;
5027 }
5028
5029 if (oldFiber === null) {
5030 // If we don't have any more existing children we can choose a fast path
5031 // since the rest will all be insertions.
5032 for (; newIdx < newChildren.length; newIdx++) {
5033 var _newFiber = createChild(returnFiber, newChildren[newIdx], lanes);
5034
5035 if (_newFiber === null) {
5036 continue;
5037 }
5038
5039 lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
5040
5041 if (previousNewFiber === null) {
5042 // TODO: Move out of the loop. This only happens for the first run.
5043 resultingFirstChild = _newFiber;
5044 } else {
5045 previousNewFiber.sibling = _newFiber;
5046 }
5047
5048 previousNewFiber = _newFiber;
5049 }
5050
5051 return resultingFirstChild;
5052 } // Add all children to a key map for quick lookups.
5053
5054
5055 var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.
5056
5057 for (; newIdx < newChildren.length; newIdx++) {
5058 var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], lanes);
5059
5060 if (_newFiber2 !== null) {
5061 if (shouldTrackSideEffects) {
5062 if (_newFiber2.alternate !== null) {
5063 // The new fiber is a work in progress, but if there exists a
5064 // current, that means that we reused the fiber. We need to delete
5065 // it from the child list so that we don't add it to the deletion
5066 // list.
5067 existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
5068 }
5069 }
5070
5071 lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
5072
5073 if (previousNewFiber === null) {
5074 resultingFirstChild = _newFiber2;
5075 } else {
5076 previousNewFiber.sibling = _newFiber2;
5077 }
5078
5079 previousNewFiber = _newFiber2;
5080 }
5081 }
5082
5083 if (shouldTrackSideEffects) {
5084 // Any existing children that weren't consumed above were deleted. We need
5085 // to add them to the deletion list.
5086 existingChildren.forEach(function (child) {
5087 return deleteChild(returnFiber, child);
5088 });
5089 }
5090
5091 return resultingFirstChild;
5092 }
5093
5094 function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, lanes) {
5095 // This is the same implementation as reconcileChildrenArray(),
5096 // but using the iterator instead.
5097 var iteratorFn = getIteratorFn(newChildrenIterable);
5098
5099 if (!(typeof iteratorFn === 'function')) {
5100 {
5101 throw Error( "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." );
5102 }
5103 }
5104
5105 {
5106 // We don't support rendering Generators because it's a mutation.
5107 // See https://github.com/facebook/react/issues/12995
5108 if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag
5109 newChildrenIterable[Symbol.toStringTag] === 'Generator') {
5110 if (!didWarnAboutGenerators) {
5111 error('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.');
5112 }
5113
5114 didWarnAboutGenerators = true;
5115 } // Warn about using Maps as children
5116
5117
5118 if (newChildrenIterable.entries === iteratorFn) {
5119 if (!didWarnAboutMaps) {
5120 error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
5121 }
5122
5123 didWarnAboutMaps = true;
5124 } // First, validate keys.
5125 // We'll get a different iterator later for the main pass.
5126
5127
5128 var _newChildren = iteratorFn.call(newChildrenIterable);
5129
5130 if (_newChildren) {
5131 var knownKeys = null;
5132
5133 var _step = _newChildren.next();
5134
5135 for (; !_step.done; _step = _newChildren.next()) {
5136 var child = _step.value;
5137 knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
5138 }
5139 }
5140 }
5141
5142 var newChildren = iteratorFn.call(newChildrenIterable);
5143
5144 if (!(newChildren != null)) {
5145 {
5146 throw Error( "An iterable object provided no iterator." );
5147 }
5148 }
5149
5150 var resultingFirstChild = null;
5151 var previousNewFiber = null;
5152 var oldFiber = currentFirstChild;
5153 var lastPlacedIndex = 0;
5154 var newIdx = 0;
5155 var nextOldFiber = null;
5156 var step = newChildren.next();
5157
5158 for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
5159 if (oldFiber.index > newIdx) {
5160 nextOldFiber = oldFiber;
5161 oldFiber = null;
5162 } else {
5163 nextOldFiber = oldFiber.sibling;
5164 }
5165
5166 var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);
5167
5168 if (newFiber === null) {
5169 // TODO: This breaks on empty slots like null children. That's
5170 // unfortunate because it triggers the slow path all the time. We need
5171 // a better way to communicate whether this was a miss or null,
5172 // boolean, undefined, etc.
5173 if (oldFiber === null) {
5174 oldFiber = nextOldFiber;
5175 }
5176
5177 break;
5178 }
5179
5180 if (shouldTrackSideEffects) {
5181 if (oldFiber && newFiber.alternate === null) {
5182 // We matched the slot, but we didn't reuse the existing fiber, so we
5183 // need to delete the existing child.
5184 deleteChild(returnFiber, oldFiber);
5185 }
5186 }
5187
5188 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
5189
5190 if (previousNewFiber === null) {
5191 // TODO: Move out of the loop. This only happens for the first run.
5192 resultingFirstChild = newFiber;
5193 } else {
5194 // TODO: Defer siblings if we're not at the right index for this slot.
5195 // I.e. if we had null values before, then we want to defer this
5196 // for each null value. However, we also don't want to call updateSlot
5197 // with the previous one.
5198 previousNewFiber.sibling = newFiber;
5199 }
5200
5201 previousNewFiber = newFiber;
5202 oldFiber = nextOldFiber;
5203 }
5204
5205 if (step.done) {
5206 // We've reached the end of the new children. We can delete the rest.
5207 deleteRemainingChildren(returnFiber, oldFiber);
5208 return resultingFirstChild;
5209 }
5210
5211 if (oldFiber === null) {
5212 // If we don't have any more existing children we can choose a fast path
5213 // since the rest will all be insertions.
5214 for (; !step.done; newIdx++, step = newChildren.next()) {
5215 var _newFiber3 = createChild(returnFiber, step.value, lanes);
5216
5217 if (_newFiber3 === null) {
5218 continue;
5219 }
5220
5221 lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
5222
5223 if (previousNewFiber === null) {
5224 // TODO: Move out of the loop. This only happens for the first run.
5225 resultingFirstChild = _newFiber3;
5226 } else {
5227 previousNewFiber.sibling = _newFiber3;
5228 }
5229
5230 previousNewFiber = _newFiber3;
5231 }
5232
5233 return resultingFirstChild;
5234 } // Add all children to a key map for quick lookups.
5235
5236
5237 var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.
5238
5239 for (; !step.done; newIdx++, step = newChildren.next()) {
5240 var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, lanes);
5241
5242 if (_newFiber4 !== null) {
5243 if (shouldTrackSideEffects) {
5244 if (_newFiber4.alternate !== null) {
5245 // The new fiber is a work in progress, but if there exists a
5246 // current, that means that we reused the fiber. We need to delete
5247 // it from the child list so that we don't add it to the deletion
5248 // list.
5249 existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
5250 }
5251 }
5252
5253 lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
5254
5255 if (previousNewFiber === null) {
5256 resultingFirstChild = _newFiber4;
5257 } else {
5258 previousNewFiber.sibling = _newFiber4;
5259 }
5260
5261 previousNewFiber = _newFiber4;
5262 }
5263 }
5264
5265 if (shouldTrackSideEffects) {
5266 // Any existing children that weren't consumed above were deleted. We need
5267 // to add them to the deletion list.
5268 existingChildren.forEach(function (child) {
5269 return deleteChild(returnFiber, child);
5270 });
5271 }
5272
5273 return resultingFirstChild;
5274 }
5275
5276 function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, lanes) {
5277 // There's no need to check for keys on text nodes since we don't have a
5278 // way to define them.
5279 if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
5280 // We already have an existing node so let's just update it and delete
5281 // the rest.
5282 deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
5283 var existing = useFiber(currentFirstChild, textContent);
5284 existing.return = returnFiber;
5285 return existing;
5286 } // The existing first child is not a text node so we need to create one
5287 // and delete the existing ones.
5288
5289
5290 deleteRemainingChildren(returnFiber, currentFirstChild);
5291 var created = createFiberFromText(textContent, returnFiber.mode, lanes);
5292 created.return = returnFiber;
5293 return created;
5294 }
5295
5296 function reconcileSingleElement(returnFiber, currentFirstChild, element, lanes) {
5297 var key = element.key;
5298 var child = currentFirstChild;
5299
5300 while (child !== null) {
5301 // TODO: If key === null and child.key === null, then this only applies to
5302 // the first item in the list.
5303 if (child.key === key) {
5304 switch (child.tag) {
5305 case Fragment:
5306 {
5307 if (element.type === REACT_FRAGMENT_TYPE) {
5308 deleteRemainingChildren(returnFiber, child.sibling);
5309 var existing = useFiber(child, element.props.children);
5310 existing.return = returnFiber;
5311
5312 {
5313 existing._debugSource = element._source;
5314 existing._debugOwner = element._owner;
5315 }
5316
5317 return existing;
5318 }
5319
5320 break;
5321 }
5322
5323 case Block:
5324
5325 // We intentionally fallthrough here if enableBlocksAPI is not on.
5326 // eslint-disable-next-lined no-fallthrough
5327
5328 default:
5329 {
5330 if (child.elementType === element.type || ( // Keep this check inline so it only runs on the false path:
5331 isCompatibleFamilyForHotReloading(child, element) )) {
5332 deleteRemainingChildren(returnFiber, child.sibling);
5333
5334 var _existing3 = useFiber(child, element.props);
5335
5336 _existing3.ref = coerceRef(returnFiber, child, element);
5337 _existing3.return = returnFiber;
5338
5339 {
5340 _existing3._debugSource = element._source;
5341 _existing3._debugOwner = element._owner;
5342 }
5343
5344 return _existing3;
5345 }
5346
5347 break;
5348 }
5349 } // Didn't match.
5350
5351
5352 deleteRemainingChildren(returnFiber, child);
5353 break;
5354 } else {
5355 deleteChild(returnFiber, child);
5356 }
5357
5358 child = child.sibling;
5359 }
5360
5361 if (element.type === REACT_FRAGMENT_TYPE) {
5362 var created = createFiberFromFragment(element.props.children, returnFiber.mode, lanes, element.key);
5363 created.return = returnFiber;
5364 return created;
5365 } else {
5366 var _created4 = createFiberFromElement(element, returnFiber.mode, lanes);
5367
5368 _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
5369 _created4.return = returnFiber;
5370 return _created4;
5371 }
5372 }
5373
5374 function reconcileSinglePortal(returnFiber, currentFirstChild, portal, lanes) {
5375 var key = portal.key;
5376 var child = currentFirstChild;
5377
5378 while (child !== null) {
5379 // TODO: If key === null and child.key === null, then this only applies to
5380 // the first item in the list.
5381 if (child.key === key) {
5382 if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
5383 deleteRemainingChildren(returnFiber, child.sibling);
5384 var existing = useFiber(child, portal.children || []);
5385 existing.return = returnFiber;
5386 return existing;
5387 } else {
5388 deleteRemainingChildren(returnFiber, child);
5389 break;
5390 }
5391 } else {
5392 deleteChild(returnFiber, child);
5393 }
5394
5395 child = child.sibling;
5396 }
5397
5398 var created = createFiberFromPortal(portal, returnFiber.mode, lanes);
5399 created.return = returnFiber;
5400 return created;
5401 } // This API will tag the children with the side-effect of the reconciliation
5402 // itself. They will be added to the side-effect list as we pass through the
5403 // children and the parent.
5404
5405
5406 function reconcileChildFibers(returnFiber, currentFirstChild, newChild, lanes) {
5407 // This function is not recursive.
5408 // If the top level item is an array, we treat it as a set of children,
5409 // not as a fragment. Nested arrays on the other hand will be treated as
5410 // fragment nodes. Recursion happens at the normal flow.
5411 // Handle top level unkeyed fragments as if they were arrays.
5412 // This leads to an ambiguity between <>{[...]}</> and <>...</>.
5413 // We treat the ambiguous cases above the same.
5414 var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
5415
5416 if (isUnkeyedTopLevelFragment) {
5417 newChild = newChild.props.children;
5418 } // Handle object types
5419
5420
5421 var isObject = typeof newChild === 'object' && newChild !== null;
5422
5423 if (isObject) {
5424 switch (newChild.$$typeof) {
5425 case REACT_ELEMENT_TYPE:
5426 return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, lanes));
5427
5428 case REACT_PORTAL_TYPE:
5429 return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, lanes));
5430
5431 }
5432 }
5433
5434 if (typeof newChild === 'string' || typeof newChild === 'number') {
5435 return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, lanes));
5436 }
5437
5438 if (isArray$1(newChild)) {
5439 return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, lanes);
5440 }
5441
5442 if (getIteratorFn(newChild)) {
5443 return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, lanes);
5444 }
5445
5446 if (isObject) {
5447 throwOnInvalidObjectType(returnFiber, newChild);
5448 }
5449
5450 {
5451 if (typeof newChild === 'function') {
5452 warnOnFunctionType(returnFiber);
5453 }
5454 }
5455
5456 if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {
5457 // If the new child is undefined, and the return fiber is a composite
5458 // component, throw an error. If Fiber return types are disabled,
5459 // we already threw above.
5460 switch (returnFiber.tag) {
5461 case ClassComponent:
5462 {
5463 {
5464 var instance = returnFiber.stateNode;
5465
5466 if (instance.render._isMockFunction) {
5467 // We allow auto-mocks to proceed as if they're returning null.
5468 break;
5469 }
5470 }
5471 }
5472 // Intentionally fall through to the next case, which handles both
5473 // functions and classes
5474 // eslint-disable-next-lined no-fallthrough
5475
5476 case Block:
5477 case FunctionComponent:
5478 case ForwardRef:
5479 case SimpleMemoComponent:
5480 {
5481 {
5482 {
5483 throw Error( (getComponentName(returnFiber.type) || 'Component') + "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." );
5484 }
5485 }
5486 }
5487 }
5488 } // Remaining cases are all treated as empty.
5489
5490
5491 return deleteRemainingChildren(returnFiber, currentFirstChild);
5492 }
5493
5494 return reconcileChildFibers;
5495 }
5496
5497 var reconcileChildFibers = ChildReconciler(true);
5498 var mountChildFibers = ChildReconciler(false);
5499 function cloneChildFibers(current, workInProgress) {
5500 if (!(current === null || workInProgress.child === current.child)) {
5501 {
5502 throw Error( "Resuming work not yet implemented." );
5503 }
5504 }
5505
5506 if (workInProgress.child === null) {
5507 return;
5508 }
5509
5510 var currentChild = workInProgress.child;
5511 var newChild = createWorkInProgress(currentChild, currentChild.pendingProps);
5512 workInProgress.child = newChild;
5513 newChild.return = workInProgress;
5514
5515 while (currentChild.sibling !== null) {
5516 currentChild = currentChild.sibling;
5517 newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps);
5518 newChild.return = workInProgress;
5519 }
5520
5521 newChild.sibling = null;
5522 } // Reset a workInProgress child set to prepare it for a second pass.
5523
5524 function resetChildFibers(workInProgress, lanes) {
5525 var child = workInProgress.child;
5526
5527 while (child !== null) {
5528 resetWorkInProgress(child, lanes);
5529 child = child.sibling;
5530 }
5531 }
5532
5533 var NO_CONTEXT$1 = {};
5534 var contextStackCursor$1 = createCursor(NO_CONTEXT$1);
5535 var contextFiberStackCursor = createCursor(NO_CONTEXT$1);
5536 var rootInstanceStackCursor = createCursor(NO_CONTEXT$1);
5537
5538 function requiredContext(c) {
5539 if (!(c !== NO_CONTEXT$1)) {
5540 {
5541 throw Error( "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." );
5542 }
5543 }
5544
5545 return c;
5546 }
5547
5548 function getRootHostContainer() {
5549 var rootInstance = requiredContext(rootInstanceStackCursor.current);
5550 return rootInstance;
5551 }
5552
5553 function pushHostContainer(fiber, nextRootInstance) {
5554 // Push current root instance onto the stack;
5555 // This allows us to reset root when portals are popped.
5556 push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it.
5557 // This enables us to pop only Fibers that provide unique contexts.
5558
5559 push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack.
5560 // However, we can't just call getRootHostContext() and push it because
5561 // we'd have a different number of entries on the stack depending on
5562 // whether getRootHostContext() throws somewhere in renderer code or not.
5563 // So we push an empty value first. This lets us safely unwind on errors.
5564
5565 push(contextStackCursor$1, NO_CONTEXT$1, fiber);
5566 var nextRootContext = getRootHostContext(); // Now that we know this function doesn't throw, replace it.
5567
5568 pop(contextStackCursor$1, fiber);
5569 push(contextStackCursor$1, nextRootContext, fiber);
5570 }
5571
5572 function popHostContainer(fiber) {
5573 pop(contextStackCursor$1, fiber);
5574 pop(contextFiberStackCursor, fiber);
5575 pop(rootInstanceStackCursor, fiber);
5576 }
5577
5578 function getHostContext() {
5579 var context = requiredContext(contextStackCursor$1.current);
5580 return context;
5581 }
5582
5583 function pushHostContext(fiber) {
5584 var rootInstance = requiredContext(rootInstanceStackCursor.current);
5585 var context = requiredContext(contextStackCursor$1.current);
5586 var nextContext = getChildHostContext(context, fiber.type); // Don't push this Fiber's context unless it's unique.
5587
5588 if (context === nextContext) {
5589 return;
5590 } // Track the context and the Fiber that provided it.
5591 // This enables us to pop only Fibers that provide unique contexts.
5592
5593
5594 push(contextFiberStackCursor, fiber, fiber);
5595 push(contextStackCursor$1, nextContext, fiber);
5596 }
5597
5598 function popHostContext(fiber) {
5599 // Do not pop unless this Fiber provided the current context.
5600 // pushHostContext() only pushes Fibers that provide unique contexts.
5601 if (contextFiberStackCursor.current !== fiber) {
5602 return;
5603 }
5604
5605 pop(contextStackCursor$1, fiber);
5606 pop(contextFiberStackCursor, fiber);
5607 }
5608
5609 var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is
5610 // inherited deeply down the subtree. The upper bits only affect
5611 // this immediate suspense boundary and gets reset each new
5612 // boundary or suspense list.
5613
5614 var SubtreeSuspenseContextMask = 1; // Subtree Flags:
5615 // InvisibleParentSuspenseContext indicates that one of our parent Suspense
5616 // boundaries is not currently showing visible main content.
5617 // Either because it is already showing a fallback or is not mounted at all.
5618 // We can use this to determine if it is desirable to trigger a fallback at
5619 // the parent. If not, then we might need to trigger undesirable boundaries
5620 // and/or suspend the commit to avoid hiding the parent content.
5621
5622 var InvisibleParentSuspenseContext = 1; // Shallow Flags:
5623 // ForceSuspenseFallback can be used by SuspenseList to force newly added
5624 // items into their fallback state during one of the render passes.
5625
5626 var ForceSuspenseFallback = 2;
5627 var suspenseStackCursor = createCursor(DefaultSuspenseContext);
5628 function hasSuspenseContext(parentContext, flag) {
5629 return (parentContext & flag) !== 0;
5630 }
5631 function setDefaultShallowSuspenseContext(parentContext) {
5632 return parentContext & SubtreeSuspenseContextMask;
5633 }
5634 function setShallowSuspenseContext(parentContext, shallowContext) {
5635 return parentContext & SubtreeSuspenseContextMask | shallowContext;
5636 }
5637 function addSubtreeSuspenseContext(parentContext, subtreeContext) {
5638 return parentContext | subtreeContext;
5639 }
5640 function pushSuspenseContext(fiber, newContext) {
5641 push(suspenseStackCursor, newContext, fiber);
5642 }
5643 function popSuspenseContext(fiber) {
5644 pop(suspenseStackCursor, fiber);
5645 }
5646
5647 function shouldCaptureSuspense(workInProgress, hasInvisibleParent) {
5648 // If it was the primary children that just suspended, capture and render the
5649 // fallback. Otherwise, don't capture and bubble to the next boundary.
5650 var nextState = workInProgress.memoizedState;
5651
5652 if (nextState !== null) {
5653 if (nextState.dehydrated !== null) {
5654 // A dehydrated boundary always captures.
5655 return true;
5656 }
5657
5658 return false;
5659 }
5660
5661 var props = workInProgress.memoizedProps; // In order to capture, the Suspense component must have a fallback prop.
5662
5663 if (props.fallback === undefined) {
5664 return false;
5665 } // Regular boundaries always capture.
5666
5667
5668 if (props.unstable_avoidThisFallback !== true) {
5669 return true;
5670 } // If it's a boundary we should avoid, then we prefer to bubble up to the
5671 // parent boundary if it is currently invisible.
5672
5673
5674 if (hasInvisibleParent) {
5675 return false;
5676 } // If the parent is not able to handle it, we must handle it.
5677
5678
5679 return true;
5680 }
5681 function findFirstSuspended(row) {
5682 var node = row;
5683
5684 while (node !== null) {
5685 if (node.tag === SuspenseComponent) {
5686 var state = node.memoizedState;
5687
5688 if (state !== null) {
5689 var dehydrated = state.dehydrated;
5690
5691 if (dehydrated === null || isSuspenseInstancePending() || isSuspenseInstanceFallback()) {
5692 return node;
5693 }
5694 }
5695 } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't
5696 // keep track of whether it suspended or not.
5697 node.memoizedProps.revealOrder !== undefined) {
5698 var didSuspend = (node.flags & DidCapture) !== NoFlags;
5699
5700 if (didSuspend) {
5701 return node;
5702 }
5703 } else if (node.child !== null) {
5704 node.child.return = node;
5705 node = node.child;
5706 continue;
5707 }
5708
5709 if (node === row) {
5710 return null;
5711 }
5712
5713 while (node.sibling === null) {
5714 if (node.return === null || node.return === row) {
5715 return null;
5716 }
5717
5718 node = node.return;
5719 }
5720
5721 node.sibling.return = node.return;
5722 node = node.sibling;
5723 }
5724
5725 return null;
5726 }
5727
5728 var NoFlags$1 =
5729 /* */
5730 0; // Represents whether effect should fire.
5731
5732 var HasEffect =
5733 /* */
5734 1; // Represents the phase in which the effect (not the clean-up) fires.
5735
5736 var Layout =
5737 /* */
5738 2;
5739 var Passive$1 =
5740 /* */
5741 4;
5742
5743 var isHydrating = false;
5744
5745 function enterHydrationState(fiber) {
5746 {
5747 return false;
5748 }
5749 }
5750
5751 function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
5752 {
5753 {
5754 {
5755 throw Error( "Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." );
5756 }
5757 }
5758 }
5759 }
5760
5761 function prepareToHydrateHostTextInstance(fiber) {
5762 {
5763 {
5764 {
5765 throw Error( "Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." );
5766 }
5767 }
5768 }
5769 var shouldUpdate = hydrateTextInstance();
5770 }
5771
5772 function popHydrationState(fiber) {
5773 {
5774 return false;
5775 }
5776 }
5777
5778 function getIsHydrating() {
5779 return isHydrating;
5780 }
5781
5782 // and should be reset before starting a new render.
5783 // This tracks which mutable sources need to be reset after a render.
5784
5785 var workInProgressSources = [];
5786 var rendererSigil$1;
5787
5788 {
5789 // Used to detect multiple renderers using the same mutable source.
5790 rendererSigil$1 = {};
5791 }
5792
5793 function markSourceAsDirty(mutableSource) {
5794 workInProgressSources.push(mutableSource);
5795 }
5796 function resetWorkInProgressVersions() {
5797 for (var i = 0; i < workInProgressSources.length; i++) {
5798 var mutableSource = workInProgressSources[i];
5799
5800 {
5801 mutableSource._workInProgressVersionSecondary = null;
5802 }
5803 }
5804
5805 workInProgressSources.length = 0;
5806 }
5807 function getWorkInProgressVersion(mutableSource) {
5808 {
5809 return mutableSource._workInProgressVersionSecondary;
5810 }
5811 }
5812 function setWorkInProgressVersion(mutableSource, version) {
5813 {
5814 mutableSource._workInProgressVersionSecondary = version;
5815 }
5816
5817 workInProgressSources.push(mutableSource);
5818 }
5819 function warnAboutMultipleRenderersDEV(mutableSource) {
5820 {
5821 {
5822 if (mutableSource._currentSecondaryRenderer == null) {
5823 mutableSource._currentSecondaryRenderer = rendererSigil$1;
5824 } else if (mutableSource._currentSecondaryRenderer !== rendererSigil$1) {
5825 error('Detected multiple renderers concurrently rendering the ' + 'same mutable source. This is currently unsupported.');
5826 }
5827 }
5828 }
5829 } // Eager reads the version of a mutable source and stores it on the root.
5830
5831 var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher,
5832 ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig;
5833 var didWarnAboutMismatchedHooksForComponent;
5834 var didWarnAboutUseOpaqueIdentifier;
5835
5836 {
5837 didWarnAboutUseOpaqueIdentifier = {};
5838 didWarnAboutMismatchedHooksForComponent = new Set();
5839 }
5840
5841 // These are set right before calling the component.
5842 var renderLanes = NoLanes; // The work-in-progress fiber. I've named it differently to distinguish it from
5843 // the work-in-progress hook.
5844
5845 var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The
5846 // current hook list is the list that belongs to the current fiber. The
5847 // work-in-progress hook list is a new list that will be added to the
5848 // work-in-progress fiber.
5849
5850 var currentHook = null;
5851 var workInProgressHook = null; // Whether an update was scheduled at any point during the render phase. This
5852 // does not get reset if we do another render pass; only when we're completely
5853 // finished evaluating this component. This is an optimization so we know
5854 // whether we need to clear render phase updates after a throw.
5855
5856 var didScheduleRenderPhaseUpdate = false; // Where an update was scheduled only during the current render pass. This
5857 // gets reset after each attempt.
5858 // TODO: Maybe there's some way to consolidate this with
5859 // `didScheduleRenderPhaseUpdate`. Or with `numberOfReRenders`.
5860
5861 var didScheduleRenderPhaseUpdateDuringThisPass = false;
5862 var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook
5863
5864 var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders.
5865 // The list stores the order of hooks used during the initial render (mount).
5866 // Subsequent renders (updates) reference this list.
5867
5868 var hookTypesDev = null;
5869 var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore
5870 // the dependencies for Hooks that need them (e.g. useEffect or useMemo).
5871 // When true, such Hooks will always be "remounted". Only used during hot reload.
5872
5873 var ignorePreviousDependencies = false;
5874
5875 function mountHookTypesDev() {
5876 {
5877 var hookName = currentHookNameInDev;
5878
5879 if (hookTypesDev === null) {
5880 hookTypesDev = [hookName];
5881 } else {
5882 hookTypesDev.push(hookName);
5883 }
5884 }
5885 }
5886
5887 function updateHookTypesDev() {
5888 {
5889 var hookName = currentHookNameInDev;
5890
5891 if (hookTypesDev !== null) {
5892 hookTypesUpdateIndexDev++;
5893
5894 if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
5895 warnOnHookMismatchInDev(hookName);
5896 }
5897 }
5898 }
5899 }
5900
5901 function checkDepsAreArrayDev(deps) {
5902 {
5903 if (deps !== undefined && deps !== null && !Array.isArray(deps)) {
5904 // Verify deps, but only on mount to avoid extra checks.
5905 // It's unlikely their type would change as usually you define them inline.
5906 error('%s received a final argument that is not an array (instead, received `%s`). When ' + 'specified, the final argument must be an array.', currentHookNameInDev, typeof deps);
5907 }
5908 }
5909 }
5910
5911 function warnOnHookMismatchInDev(currentHookName) {
5912 {
5913 var componentName = getComponentName(currentlyRenderingFiber$1.type);
5914
5915 if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
5916 didWarnAboutMismatchedHooksForComponent.add(componentName);
5917
5918 if (hookTypesDev !== null) {
5919 var table = '';
5920 var secondColumnStart = 30;
5921
5922 for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {
5923 var oldHookName = hookTypesDev[i];
5924 var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
5925 var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up
5926 // lol @ IE not supporting String#repeat
5927
5928 while (row.length < secondColumnStart) {
5929 row += ' ';
5930 }
5931
5932 row += newHookName + '\n';
5933 table += row;
5934 }
5935
5936 error('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://reactjs.org/link/rules-of-hooks\n\n' + ' Previous render Next render\n' + ' ------------------------------------------------------\n' + '%s' + ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n', componentName, table);
5937 }
5938 }
5939 }
5940 }
5941
5942 function throwInvalidHookError() {
5943 {
5944 {
5945 throw Error( "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem." );
5946 }
5947 }
5948 }
5949
5950 function areHookInputsEqual(nextDeps, prevDeps) {
5951 {
5952 if (ignorePreviousDependencies) {
5953 // Only true when this component is being hot reloaded.
5954 return false;
5955 }
5956 }
5957
5958 if (prevDeps === null) {
5959 {
5960 error('%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);
5961 }
5962
5963 return false;
5964 }
5965
5966 {
5967 // Don't bother comparing lengths in prod because these arrays should be
5968 // passed inline.
5969 if (nextDeps.length !== prevDeps.length) {
5970 error('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, "[" + prevDeps.join(', ') + "]", "[" + nextDeps.join(', ') + "]");
5971 }
5972 }
5973
5974 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
5975 if (objectIs(nextDeps[i], prevDeps[i])) {
5976 continue;
5977 }
5978
5979 return false;
5980 }
5981
5982 return true;
5983 }
5984
5985 function renderWithHooks(current, workInProgress, Component, props, secondArg, nextRenderLanes) {
5986 renderLanes = nextRenderLanes;
5987 currentlyRenderingFiber$1 = workInProgress;
5988
5989 {
5990 hookTypesDev = current !== null ? current._debugHookTypes : null;
5991 hookTypesUpdateIndexDev = -1; // Used for hot reloading:
5992
5993 ignorePreviousDependencies = current !== null && current.type !== workInProgress.type;
5994 }
5995
5996 workInProgress.memoizedState = null;
5997 workInProgress.updateQueue = null;
5998 workInProgress.lanes = NoLanes; // The following should have already been reset
5999 // currentHook = null;
6000 // workInProgressHook = null;
6001 // didScheduleRenderPhaseUpdate = false;
6002 // TODO Warn if no hooks are used at all during mount, then some are used during update.
6003 // Currently we will identify the update render as a mount because memoizedState === null.
6004 // This is tricky because it's valid for certain types of components (e.g. React.lazy)
6005 // Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used.
6006 // Non-stateful hooks (e.g. context) don't get added to memoizedState,
6007 // so memoizedState would be null during updates and mounts.
6008
6009 {
6010 if (current !== null && current.memoizedState !== null) {
6011 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
6012 } else if (hookTypesDev !== null) {
6013 // This dispatcher handles an edge case where a component is updating,
6014 // but no stateful hooks have been used.
6015 // We want to match the production code behavior (which will use HooksDispatcherOnMount),
6016 // but with the extra DEV validation to ensure hooks ordering hasn't changed.
6017 // This dispatcher does that.
6018 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV;
6019 } else {
6020 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV;
6021 }
6022 }
6023
6024 var children = Component(props, secondArg); // Check if there was a render phase update
6025
6026 if (didScheduleRenderPhaseUpdateDuringThisPass) {
6027 // Keep rendering in a loop for as long as render phase updates continue to
6028 // be scheduled. Use a counter to prevent infinite loops.
6029 var numberOfReRenders = 0;
6030
6031 do {
6032 didScheduleRenderPhaseUpdateDuringThisPass = false;
6033
6034 if (!(numberOfReRenders < RE_RENDER_LIMIT)) {
6035 {
6036 throw Error( "Too many re-renders. React limits the number of renders to prevent an infinite loop." );
6037 }
6038 }
6039
6040 numberOfReRenders += 1;
6041
6042 {
6043 // Even when hot reloading, allow dependencies to stabilize
6044 // after first render to prevent infinite render phase updates.
6045 ignorePreviousDependencies = false;
6046 } // Start over from the beginning of the list
6047
6048
6049 currentHook = null;
6050 workInProgressHook = null;
6051 workInProgress.updateQueue = null;
6052
6053 {
6054 // Also validate hook order for cascading updates.
6055 hookTypesUpdateIndexDev = -1;
6056 }
6057
6058 ReactCurrentDispatcher$1.current = HooksDispatcherOnRerenderInDEV ;
6059 children = Component(props, secondArg);
6060 } while (didScheduleRenderPhaseUpdateDuringThisPass);
6061 } // We can assume the previous dispatcher is always this one, since we set it
6062 // at the beginning of the render phase and there's no re-entrancy.
6063
6064
6065 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
6066
6067 {
6068 workInProgress._debugHookTypes = hookTypesDev;
6069 } // This check uses currentHook so that it works the same in DEV and prod bundles.
6070 // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.
6071
6072
6073 var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
6074 renderLanes = NoLanes;
6075 currentlyRenderingFiber$1 = null;
6076 currentHook = null;
6077 workInProgressHook = null;
6078
6079 {
6080 currentHookNameInDev = null;
6081 hookTypesDev = null;
6082 hookTypesUpdateIndexDev = -1;
6083 }
6084
6085 didScheduleRenderPhaseUpdate = false;
6086
6087 if (!!didRenderTooFewHooks) {
6088 {
6089 throw Error( "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." );
6090 }
6091 }
6092
6093 return children;
6094 }
6095 function bailoutHooks(current, workInProgress, lanes) {
6096 workInProgress.updateQueue = current.updateQueue;
6097 workInProgress.flags &= ~(Passive | Update);
6098 current.lanes = removeLanes(current.lanes, lanes);
6099 }
6100 function resetHooksAfterThrow() {
6101 // We can assume the previous dispatcher is always this one, since we set it
6102 // at the beginning of the render phase and there's no re-entrancy.
6103 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
6104
6105 if (didScheduleRenderPhaseUpdate) {
6106 // There were render phase updates. These are only valid for this render
6107 // phase, which we are now aborting. Remove the updates from the queues so
6108 // they do not persist to the next render. Do not remove updates from hooks
6109 // that weren't processed.
6110 //
6111 // Only reset the updates from the queue if it has a clone. If it does
6112 // not have a clone, that means it wasn't processed, and the updates were
6113 // scheduled before we entered the render phase.
6114 var hook = currentlyRenderingFiber$1.memoizedState;
6115
6116 while (hook !== null) {
6117 var queue = hook.queue;
6118
6119 if (queue !== null) {
6120 queue.pending = null;
6121 }
6122
6123 hook = hook.next;
6124 }
6125
6126 didScheduleRenderPhaseUpdate = false;
6127 }
6128
6129 renderLanes = NoLanes;
6130 currentlyRenderingFiber$1 = null;
6131 currentHook = null;
6132 workInProgressHook = null;
6133
6134 {
6135 hookTypesDev = null;
6136 hookTypesUpdateIndexDev = -1;
6137 currentHookNameInDev = null;
6138 isUpdatingOpaqueValueInRenderPhase = false;
6139 }
6140
6141 didScheduleRenderPhaseUpdateDuringThisPass = false;
6142 }
6143
6144 function mountWorkInProgressHook() {
6145 var hook = {
6146 memoizedState: null,
6147 baseState: null,
6148 baseQueue: null,
6149 queue: null,
6150 next: null
6151 };
6152
6153 if (workInProgressHook === null) {
6154 // This is the first hook in the list
6155 currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook;
6156 } else {
6157 // Append to the end of the list
6158 workInProgressHook = workInProgressHook.next = hook;
6159 }
6160
6161 return workInProgressHook;
6162 }
6163
6164 function updateWorkInProgressHook() {
6165 // This function is used both for updates and for re-renders triggered by a
6166 // render phase update. It assumes there is either a current hook we can
6167 // clone, or a work-in-progress hook from a previous render pass that we can
6168 // use as a base. When we reach the end of the base list, we must switch to
6169 // the dispatcher used for mounts.
6170 var nextCurrentHook;
6171
6172 if (currentHook === null) {
6173 var current = currentlyRenderingFiber$1.alternate;
6174
6175 if (current !== null) {
6176 nextCurrentHook = current.memoizedState;
6177 } else {
6178 nextCurrentHook = null;
6179 }
6180 } else {
6181 nextCurrentHook = currentHook.next;
6182 }
6183
6184 var nextWorkInProgressHook;
6185
6186 if (workInProgressHook === null) {
6187 nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState;
6188 } else {
6189 nextWorkInProgressHook = workInProgressHook.next;
6190 }
6191
6192 if (nextWorkInProgressHook !== null) {
6193 // There's already a work-in-progress. Reuse it.
6194 workInProgressHook = nextWorkInProgressHook;
6195 nextWorkInProgressHook = workInProgressHook.next;
6196 currentHook = nextCurrentHook;
6197 } else {
6198 // Clone from the current hook.
6199 if (!(nextCurrentHook !== null)) {
6200 {
6201 throw Error( "Rendered more hooks than during the previous render." );
6202 }
6203 }
6204
6205 currentHook = nextCurrentHook;
6206 var newHook = {
6207 memoizedState: currentHook.memoizedState,
6208 baseState: currentHook.baseState,
6209 baseQueue: currentHook.baseQueue,
6210 queue: currentHook.queue,
6211 next: null
6212 };
6213
6214 if (workInProgressHook === null) {
6215 // This is the first hook in the list.
6216 currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook;
6217 } else {
6218 // Append to the end of the list.
6219 workInProgressHook = workInProgressHook.next = newHook;
6220 }
6221 }
6222
6223 return workInProgressHook;
6224 }
6225
6226 function createFunctionComponentUpdateQueue() {
6227 return {
6228 lastEffect: null
6229 };
6230 }
6231
6232 function basicStateReducer(state, action) {
6233 // $FlowFixMe: Flow doesn't like mixed types
6234 return typeof action === 'function' ? action(state) : action;
6235 }
6236
6237 function mountReducer(reducer, initialArg, init) {
6238 var hook = mountWorkInProgressHook();
6239 var initialState;
6240
6241 if (init !== undefined) {
6242 initialState = init(initialArg);
6243 } else {
6244 initialState = initialArg;
6245 }
6246
6247 hook.memoizedState = hook.baseState = initialState;
6248 var queue = hook.queue = {
6249 pending: null,
6250 dispatch: null,
6251 lastRenderedReducer: reducer,
6252 lastRenderedState: initialState
6253 };
6254 var dispatch = queue.dispatch = dispatchAction.bind(null, currentlyRenderingFiber$1, queue);
6255 return [hook.memoizedState, dispatch];
6256 }
6257
6258 function updateReducer(reducer, initialArg, init) {
6259 var hook = updateWorkInProgressHook();
6260 var queue = hook.queue;
6261
6262 if (!(queue !== null)) {
6263 {
6264 throw Error( "Should have a queue. This is likely a bug in React. Please file an issue." );
6265 }
6266 }
6267
6268 queue.lastRenderedReducer = reducer;
6269 var current = currentHook; // The last rebase update that is NOT part of the base state.
6270
6271 var baseQueue = current.baseQueue; // The last pending update that hasn't been processed yet.
6272
6273 var pendingQueue = queue.pending;
6274
6275 if (pendingQueue !== null) {
6276 // We have new updates that haven't been processed yet.
6277 // We'll add them to the base queue.
6278 if (baseQueue !== null) {
6279 // Merge the pending queue and the base queue.
6280 var baseFirst = baseQueue.next;
6281 var pendingFirst = pendingQueue.next;
6282 baseQueue.next = pendingFirst;
6283 pendingQueue.next = baseFirst;
6284 }
6285
6286 {
6287 if (current.baseQueue !== baseQueue) {
6288 // Internal invariant that should never happen, but feasibly could in
6289 // the future if we implement resuming, or some form of that.
6290 error('Internal error: Expected work-in-progress queue to be a clone. ' + 'This is a bug in React.');
6291 }
6292 }
6293
6294 current.baseQueue = baseQueue = pendingQueue;
6295 queue.pending = null;
6296 }
6297
6298 if (baseQueue !== null) {
6299 // We have a queue to process.
6300 var first = baseQueue.next;
6301 var newState = current.baseState;
6302 var newBaseState = null;
6303 var newBaseQueueFirst = null;
6304 var newBaseQueueLast = null;
6305 var update = first;
6306
6307 do {
6308 var updateLane = update.lane;
6309
6310 if (!isSubsetOfLanes(renderLanes, updateLane)) {
6311 // Priority is insufficient. Skip this update. If this is the first
6312 // skipped update, the previous update/state is the new base
6313 // update/state.
6314 var clone = {
6315 lane: updateLane,
6316 action: update.action,
6317 eagerReducer: update.eagerReducer,
6318 eagerState: update.eagerState,
6319 next: null
6320 };
6321
6322 if (newBaseQueueLast === null) {
6323 newBaseQueueFirst = newBaseQueueLast = clone;
6324 newBaseState = newState;
6325 } else {
6326 newBaseQueueLast = newBaseQueueLast.next = clone;
6327 } // Update the remaining priority in the queue.
6328 // TODO: Don't need to accumulate this. Instead, we can remove
6329 // renderLanes from the original lanes.
6330
6331
6332 currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, updateLane);
6333 markSkippedUpdateLanes(updateLane);
6334 } else {
6335 // This update does have sufficient priority.
6336 if (newBaseQueueLast !== null) {
6337 var _clone = {
6338 // This update is going to be committed so we never want uncommit
6339 // it. Using NoLane works because 0 is a subset of all bitmasks, so
6340 // this will never be skipped by the check above.
6341 lane: NoLane,
6342 action: update.action,
6343 eagerReducer: update.eagerReducer,
6344 eagerState: update.eagerState,
6345 next: null
6346 };
6347 newBaseQueueLast = newBaseQueueLast.next = _clone;
6348 } // Process this update.
6349
6350
6351 if (update.eagerReducer === reducer) {
6352 // If this update was processed eagerly, and its reducer matches the
6353 // current reducer, we can use the eagerly computed state.
6354 newState = update.eagerState;
6355 } else {
6356 var action = update.action;
6357 newState = reducer(newState, action);
6358 }
6359 }
6360
6361 update = update.next;
6362 } while (update !== null && update !== first);
6363
6364 if (newBaseQueueLast === null) {
6365 newBaseState = newState;
6366 } else {
6367 newBaseQueueLast.next = newBaseQueueFirst;
6368 } // Mark that the fiber performed work, but only if the new state is
6369 // different from the current state.
6370
6371
6372 if (!objectIs(newState, hook.memoizedState)) {
6373 markWorkInProgressReceivedUpdate();
6374 }
6375
6376 hook.memoizedState = newState;
6377 hook.baseState = newBaseState;
6378 hook.baseQueue = newBaseQueueLast;
6379 queue.lastRenderedState = newState;
6380 }
6381
6382 var dispatch = queue.dispatch;
6383 return [hook.memoizedState, dispatch];
6384 }
6385
6386 function rerenderReducer(reducer, initialArg, init) {
6387 var hook = updateWorkInProgressHook();
6388 var queue = hook.queue;
6389
6390 if (!(queue !== null)) {
6391 {
6392 throw Error( "Should have a queue. This is likely a bug in React. Please file an issue." );
6393 }
6394 }
6395
6396 queue.lastRenderedReducer = reducer; // This is a re-render. Apply the new render phase updates to the previous
6397 // work-in-progress hook.
6398
6399 var dispatch = queue.dispatch;
6400 var lastRenderPhaseUpdate = queue.pending;
6401 var newState = hook.memoizedState;
6402
6403 if (lastRenderPhaseUpdate !== null) {
6404 // The queue doesn't persist past this render pass.
6405 queue.pending = null;
6406 var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next;
6407 var update = firstRenderPhaseUpdate;
6408
6409 do {
6410 // Process this render phase update. We don't have to check the
6411 // priority because it will always be the same as the current
6412 // render's.
6413 var action = update.action;
6414 newState = reducer(newState, action);
6415 update = update.next;
6416 } while (update !== firstRenderPhaseUpdate); // Mark that the fiber performed work, but only if the new state is
6417 // different from the current state.
6418
6419
6420 if (!objectIs(newState, hook.memoizedState)) {
6421 markWorkInProgressReceivedUpdate();
6422 }
6423
6424 hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to
6425 // the base state unless the queue is empty.
6426 // TODO: Not sure if this is the desired semantics, but it's what we
6427 // do for gDSFP. I can't remember why.
6428
6429 if (hook.baseQueue === null) {
6430 hook.baseState = newState;
6431 }
6432
6433 queue.lastRenderedState = newState;
6434 }
6435
6436 return [newState, dispatch];
6437 }
6438
6439 function readFromUnsubcribedMutableSource(root, source, getSnapshot) {
6440 {
6441 warnAboutMultipleRenderersDEV(source);
6442 }
6443
6444 var getVersion = source._getVersion;
6445 var version = getVersion(source._source); // Is it safe for this component to read from this source during the current render?
6446
6447 var isSafeToReadFromSource = false; // Check the version first.
6448 // If this render has already been started with a specific version,
6449 // we can use it alone to determine if we can safely read from the source.
6450
6451 var currentRenderVersion = getWorkInProgressVersion(source);
6452
6453 if (currentRenderVersion !== null) {
6454 // It's safe to read if the store hasn't been mutated since the last time
6455 // we read something.
6456 isSafeToReadFromSource = currentRenderVersion === version;
6457 } else {
6458 // If there's no version, then this is the first time we've read from the
6459 // source during the current render pass, so we need to do a bit more work.
6460 // What we need to determine is if there are any hooks that already
6461 // subscribed to the source, and if so, whether there are any pending
6462 // mutations that haven't been synchronized yet.
6463 //
6464 // If there are no pending mutations, then `root.mutableReadLanes` will be
6465 // empty, and we know we can safely read.
6466 //
6467 // If there *are* pending mutations, we may still be able to safely read
6468 // if the currently rendering lanes are inclusive of the pending mutation
6469 // lanes, since that guarantees that the value we're about to read from
6470 // the source is consistent with the values that we read during the most
6471 // recent mutation.
6472 isSafeToReadFromSource = isSubsetOfLanes(renderLanes, root.mutableReadLanes);
6473
6474 if (isSafeToReadFromSource) {
6475 // If it's safe to read from this source during the current render,
6476 // store the version in case other components read from it.
6477 // A changed version number will let those components know to throw and restart the render.
6478 setWorkInProgressVersion(source, version);
6479 }
6480 }
6481
6482 if (isSafeToReadFromSource) {
6483 var snapshot = getSnapshot(source._source);
6484
6485 {
6486 if (typeof snapshot === 'function') {
6487 error('Mutable source should not return a function as the snapshot value. ' + 'Functions may close over mutable values and cause tearing.');
6488 }
6489 }
6490
6491 return snapshot;
6492 } else {
6493 // This handles the special case of a mutable source being shared between renderers.
6494 // In that case, if the source is mutated between the first and second renderer,
6495 // The second renderer don't know that it needs to reset the WIP version during unwind,
6496 // (because the hook only marks sources as dirty if it's written to their WIP version).
6497 // That would cause this tear check to throw again and eventually be visible to the user.
6498 // We can avoid this infinite loop by explicitly marking the source as dirty.
6499 //
6500 // This can lead to tearing in the first renderer when it resumes,
6501 // but there's nothing we can do about that (short of throwing here and refusing to continue the render).
6502 markSourceAsDirty(source);
6503
6504 {
6505 {
6506 throw Error( "Cannot read from mutable source during the current render without tearing. This is a bug in React. Please file an issue." );
6507 }
6508 }
6509 }
6510 }
6511
6512 function useMutableSource(hook, source, getSnapshot, subscribe) {
6513 var root = getWorkInProgressRoot();
6514
6515 if (!(root !== null)) {
6516 {
6517 throw Error( "Expected a work-in-progress root. This is a bug in React. Please file an issue." );
6518 }
6519 }
6520
6521 var getVersion = source._getVersion;
6522 var version = getVersion(source._source);
6523 var dispatcher = ReactCurrentDispatcher$1.current; // eslint-disable-next-line prefer-const
6524
6525 var _dispatcher$useState = dispatcher.useState(function () {
6526 return readFromUnsubcribedMutableSource(root, source, getSnapshot);
6527 }),
6528 currentSnapshot = _dispatcher$useState[0],
6529 setSnapshot = _dispatcher$useState[1];
6530
6531 var snapshot = currentSnapshot; // Grab a handle to the state hook as well.
6532 // We use it to clear the pending update queue if we have a new source.
6533
6534 var stateHook = workInProgressHook;
6535 var memoizedState = hook.memoizedState;
6536 var refs = memoizedState.refs;
6537 var prevGetSnapshot = refs.getSnapshot;
6538 var prevSource = memoizedState.source;
6539 var prevSubscribe = memoizedState.subscribe;
6540 var fiber = currentlyRenderingFiber$1;
6541 hook.memoizedState = {
6542 refs: refs,
6543 source: source,
6544 subscribe: subscribe
6545 }; // Sync the values needed by our subscription handler after each commit.
6546
6547 dispatcher.useEffect(function () {
6548 refs.getSnapshot = getSnapshot; // Normally the dispatch function for a state hook never changes,
6549 // but this hook recreates the queue in certain cases to avoid updates from stale sources.
6550 // handleChange() below needs to reference the dispatch function without re-subscribing,
6551 // so we use a ref to ensure that it always has the latest version.
6552
6553 refs.setSnapshot = setSnapshot; // Check for a possible change between when we last rendered now.
6554
6555 var maybeNewVersion = getVersion(source._source);
6556
6557 if (!objectIs(version, maybeNewVersion)) {
6558 var maybeNewSnapshot = getSnapshot(source._source);
6559
6560 {
6561 if (typeof maybeNewSnapshot === 'function') {
6562 error('Mutable source should not return a function as the snapshot value. ' + 'Functions may close over mutable values and cause tearing.');
6563 }
6564 }
6565
6566 if (!objectIs(snapshot, maybeNewSnapshot)) {
6567 setSnapshot(maybeNewSnapshot);
6568 var lane = requestUpdateLane(fiber);
6569 markRootMutableRead(root, lane);
6570 } // If the source mutated between render and now,
6571 // there may be state updates already scheduled from the old source.
6572 // Entangle the updates so that they render in the same batch.
6573
6574
6575 markRootEntangled(root, root.mutableReadLanes);
6576 }
6577 }, [getSnapshot, source, subscribe]); // If we got a new source or subscribe function, re-subscribe in a passive effect.
6578
6579 dispatcher.useEffect(function () {
6580 var handleChange = function () {
6581 var latestGetSnapshot = refs.getSnapshot;
6582 var latestSetSnapshot = refs.setSnapshot;
6583
6584 try {
6585 latestSetSnapshot(latestGetSnapshot(source._source)); // Record a pending mutable source update with the same expiration time.
6586
6587 var lane = requestUpdateLane(fiber);
6588 markRootMutableRead(root, lane);
6589 } catch (error) {
6590 // A selector might throw after a source mutation.
6591 // e.g. it might try to read from a part of the store that no longer exists.
6592 // In this case we should still schedule an update with React.
6593 // Worst case the selector will throw again and then an error boundary will handle it.
6594 latestSetSnapshot(function () {
6595 throw error;
6596 });
6597 }
6598 };
6599
6600 var unsubscribe = subscribe(source._source, handleChange);
6601
6602 {
6603 if (typeof unsubscribe !== 'function') {
6604 error('Mutable source subscribe function must return an unsubscribe function.');
6605 }
6606 }
6607
6608 return unsubscribe;
6609 }, [source, subscribe]); // If any of the inputs to useMutableSource change, reading is potentially unsafe.
6610 //
6611 // If either the source or the subscription have changed we can't can't trust the update queue.
6612 // Maybe the source changed in a way that the old subscription ignored but the new one depends on.
6613 //
6614 // If the getSnapshot function changed, we also shouldn't rely on the update queue.
6615 // It's possible that the underlying source was mutated between the when the last "change" event fired,
6616 // and when the current render (with the new getSnapshot function) is processed.
6617 //
6618 // In both cases, we need to throw away pending updates (since they are no longer relevant)
6619 // and treat reading from the source as we do in the mount case.
6620
6621 if (!objectIs(prevGetSnapshot, getSnapshot) || !objectIs(prevSource, source) || !objectIs(prevSubscribe, subscribe)) {
6622 // Create a new queue and setState method,
6623 // So if there are interleaved updates, they get pushed to the older queue.
6624 // When this becomes current, the previous queue and dispatch method will be discarded,
6625 // including any interleaving updates that occur.
6626 var newQueue = {
6627 pending: null,
6628 dispatch: null,
6629 lastRenderedReducer: basicStateReducer,
6630 lastRenderedState: snapshot
6631 };
6632 newQueue.dispatch = setSnapshot = dispatchAction.bind(null, currentlyRenderingFiber$1, newQueue);
6633 stateHook.queue = newQueue;
6634 stateHook.baseQueue = null;
6635 snapshot = readFromUnsubcribedMutableSource(root, source, getSnapshot);
6636 stateHook.memoizedState = stateHook.baseState = snapshot;
6637 }
6638
6639 return snapshot;
6640 }
6641
6642 function mountMutableSource(source, getSnapshot, subscribe) {
6643 var hook = mountWorkInProgressHook();
6644 hook.memoizedState = {
6645 refs: {
6646 getSnapshot: getSnapshot,
6647 setSnapshot: null
6648 },
6649 source: source,
6650 subscribe: subscribe
6651 };
6652 return useMutableSource(hook, source, getSnapshot, subscribe);
6653 }
6654
6655 function updateMutableSource(source, getSnapshot, subscribe) {
6656 var hook = updateWorkInProgressHook();
6657 return useMutableSource(hook, source, getSnapshot, subscribe);
6658 }
6659
6660 function mountState(initialState) {
6661 var hook = mountWorkInProgressHook();
6662
6663 if (typeof initialState === 'function') {
6664 // $FlowFixMe: Flow doesn't like mixed types
6665 initialState = initialState();
6666 }
6667
6668 hook.memoizedState = hook.baseState = initialState;
6669 var queue = hook.queue = {
6670 pending: null,
6671 dispatch: null,
6672 lastRenderedReducer: basicStateReducer,
6673 lastRenderedState: initialState
6674 };
6675 var dispatch = queue.dispatch = dispatchAction.bind(null, currentlyRenderingFiber$1, queue);
6676 return [hook.memoizedState, dispatch];
6677 }
6678
6679 function updateState(initialState) {
6680 return updateReducer(basicStateReducer);
6681 }
6682
6683 function rerenderState(initialState) {
6684 return rerenderReducer(basicStateReducer);
6685 }
6686
6687 function pushEffect(tag, create, destroy, deps) {
6688 var effect = {
6689 tag: tag,
6690 create: create,
6691 destroy: destroy,
6692 deps: deps,
6693 // Circular
6694 next: null
6695 };
6696 var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue;
6697
6698 if (componentUpdateQueue === null) {
6699 componentUpdateQueue = createFunctionComponentUpdateQueue();
6700 currentlyRenderingFiber$1.updateQueue = componentUpdateQueue;
6701 componentUpdateQueue.lastEffect = effect.next = effect;
6702 } else {
6703 var lastEffect = componentUpdateQueue.lastEffect;
6704
6705 if (lastEffect === null) {
6706 componentUpdateQueue.lastEffect = effect.next = effect;
6707 } else {
6708 var firstEffect = lastEffect.next;
6709 lastEffect.next = effect;
6710 effect.next = firstEffect;
6711 componentUpdateQueue.lastEffect = effect;
6712 }
6713 }
6714
6715 return effect;
6716 }
6717
6718 function mountRef(initialValue) {
6719 var hook = mountWorkInProgressHook();
6720 var ref = {
6721 current: initialValue
6722 };
6723
6724 {
6725 Object.seal(ref);
6726 }
6727
6728 hook.memoizedState = ref;
6729 return ref;
6730 }
6731
6732 function updateRef(initialValue) {
6733 var hook = updateWorkInProgressHook();
6734 return hook.memoizedState;
6735 }
6736
6737 function mountEffectImpl(fiberFlags, hookFlags, create, deps) {
6738 var hook = mountWorkInProgressHook();
6739 var nextDeps = deps === undefined ? null : deps;
6740 currentlyRenderingFiber$1.flags |= fiberFlags;
6741 hook.memoizedState = pushEffect(HasEffect | hookFlags, create, undefined, nextDeps);
6742 }
6743
6744 function updateEffectImpl(fiberFlags, hookFlags, create, deps) {
6745 var hook = updateWorkInProgressHook();
6746 var nextDeps = deps === undefined ? null : deps;
6747 var destroy = undefined;
6748
6749 if (currentHook !== null) {
6750 var prevEffect = currentHook.memoizedState;
6751 destroy = prevEffect.destroy;
6752
6753 if (nextDeps !== null) {
6754 var prevDeps = prevEffect.deps;
6755
6756 if (areHookInputsEqual(nextDeps, prevDeps)) {
6757 pushEffect(hookFlags, create, destroy, nextDeps);
6758 return;
6759 }
6760 }
6761 }
6762
6763 currentlyRenderingFiber$1.flags |= fiberFlags;
6764 hook.memoizedState = pushEffect(HasEffect | hookFlags, create, destroy, nextDeps);
6765 }
6766
6767 function mountEffect(create, deps) {
6768 {
6769 // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
6770 if ('undefined' !== typeof jest) {
6771 warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);
6772 }
6773 }
6774
6775 return mountEffectImpl(Update | Passive, Passive$1, create, deps);
6776 }
6777
6778 function updateEffect(create, deps) {
6779 {
6780 // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
6781 if ('undefined' !== typeof jest) {
6782 warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);
6783 }
6784 }
6785
6786 return updateEffectImpl(Update | Passive, Passive$1, create, deps);
6787 }
6788
6789 function mountLayoutEffect(create, deps) {
6790 return mountEffectImpl(Update, Layout, create, deps);
6791 }
6792
6793 function updateLayoutEffect(create, deps) {
6794 return updateEffectImpl(Update, Layout, create, deps);
6795 }
6796
6797 function imperativeHandleEffect(create, ref) {
6798 if (typeof ref === 'function') {
6799 var refCallback = ref;
6800
6801 var _inst = create();
6802
6803 refCallback(_inst);
6804 return function () {
6805 refCallback(null);
6806 };
6807 } else if (ref !== null && ref !== undefined) {
6808 var refObject = ref;
6809
6810 {
6811 if (!refObject.hasOwnProperty('current')) {
6812 error('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(', ') + '}');
6813 }
6814 }
6815
6816 var _inst2 = create();
6817
6818 refObject.current = _inst2;
6819 return function () {
6820 refObject.current = null;
6821 };
6822 }
6823 }
6824
6825 function mountImperativeHandle(ref, create, deps) {
6826 {
6827 if (typeof create !== 'function') {
6828 error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');
6829 }
6830 } // TODO: If deps are provided, should we skip comparing the ref itself?
6831
6832
6833 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
6834 return mountEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
6835 }
6836
6837 function updateImperativeHandle(ref, create, deps) {
6838 {
6839 if (typeof create !== 'function') {
6840 error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');
6841 }
6842 } // TODO: If deps are provided, should we skip comparing the ref itself?
6843
6844
6845 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
6846 return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
6847 }
6848
6849 function mountDebugValue(value, formatterFn) {// This hook is normally a no-op.
6850 // The react-debug-hooks package injects its own implementation
6851 // so that e.g. DevTools can display custom hook values.
6852 }
6853
6854 var updateDebugValue = mountDebugValue;
6855
6856 function mountCallback(callback, deps) {
6857 var hook = mountWorkInProgressHook();
6858 var nextDeps = deps === undefined ? null : deps;
6859 hook.memoizedState = [callback, nextDeps];
6860 return callback;
6861 }
6862
6863 function updateCallback(callback, deps) {
6864 var hook = updateWorkInProgressHook();
6865 var nextDeps = deps === undefined ? null : deps;
6866 var prevState = hook.memoizedState;
6867
6868 if (prevState !== null) {
6869 if (nextDeps !== null) {
6870 var prevDeps = prevState[1];
6871
6872 if (areHookInputsEqual(nextDeps, prevDeps)) {
6873 return prevState[0];
6874 }
6875 }
6876 }
6877
6878 hook.memoizedState = [callback, nextDeps];
6879 return callback;
6880 }
6881
6882 function mountMemo(nextCreate, deps) {
6883 var hook = mountWorkInProgressHook();
6884 var nextDeps = deps === undefined ? null : deps;
6885 var nextValue = nextCreate();
6886 hook.memoizedState = [nextValue, nextDeps];
6887 return nextValue;
6888 }
6889
6890 function updateMemo(nextCreate, deps) {
6891 var hook = updateWorkInProgressHook();
6892 var nextDeps = deps === undefined ? null : deps;
6893 var prevState = hook.memoizedState;
6894
6895 if (prevState !== null) {
6896 // Assume these are defined. If they're not, areHookInputsEqual will warn.
6897 if (nextDeps !== null) {
6898 var prevDeps = prevState[1];
6899
6900 if (areHookInputsEqual(nextDeps, prevDeps)) {
6901 return prevState[0];
6902 }
6903 }
6904 }
6905
6906 var nextValue = nextCreate();
6907 hook.memoizedState = [nextValue, nextDeps];
6908 return nextValue;
6909 }
6910
6911 function mountDeferredValue(value) {
6912 var _mountState = mountState(value),
6913 prevValue = _mountState[0],
6914 setValue = _mountState[1];
6915
6916 mountEffect(function () {
6917 var prevTransition = ReactCurrentBatchConfig$1.transition;
6918 ReactCurrentBatchConfig$1.transition = 1;
6919
6920 try {
6921 setValue(value);
6922 } finally {
6923 ReactCurrentBatchConfig$1.transition = prevTransition;
6924 }
6925 }, [value]);
6926 return prevValue;
6927 }
6928
6929 function updateDeferredValue(value) {
6930 var _updateState = updateState(),
6931 prevValue = _updateState[0],
6932 setValue = _updateState[1];
6933
6934 updateEffect(function () {
6935 var prevTransition = ReactCurrentBatchConfig$1.transition;
6936 ReactCurrentBatchConfig$1.transition = 1;
6937
6938 try {
6939 setValue(value);
6940 } finally {
6941 ReactCurrentBatchConfig$1.transition = prevTransition;
6942 }
6943 }, [value]);
6944 return prevValue;
6945 }
6946
6947 function rerenderDeferredValue(value) {
6948 var _rerenderState = rerenderState(),
6949 prevValue = _rerenderState[0],
6950 setValue = _rerenderState[1];
6951
6952 updateEffect(function () {
6953 var prevTransition = ReactCurrentBatchConfig$1.transition;
6954 ReactCurrentBatchConfig$1.transition = 1;
6955
6956 try {
6957 setValue(value);
6958 } finally {
6959 ReactCurrentBatchConfig$1.transition = prevTransition;
6960 }
6961 }, [value]);
6962 return prevValue;
6963 }
6964
6965 function startTransition(setPending, callback) {
6966 var priorityLevel = getCurrentPriorityLevel();
6967
6968 {
6969 runWithPriority(priorityLevel < UserBlockingPriority$1 ? UserBlockingPriority$1 : priorityLevel, function () {
6970 setPending(true);
6971 });
6972 runWithPriority(priorityLevel > NormalPriority$1 ? NormalPriority$1 : priorityLevel, function () {
6973 var prevTransition = ReactCurrentBatchConfig$1.transition;
6974 ReactCurrentBatchConfig$1.transition = 1;
6975
6976 try {
6977 setPending(false);
6978 callback();
6979 } finally {
6980 ReactCurrentBatchConfig$1.transition = prevTransition;
6981 }
6982 });
6983 }
6984 }
6985
6986 function mountTransition() {
6987 var _mountState2 = mountState(false),
6988 isPending = _mountState2[0],
6989 setPending = _mountState2[1]; // The `start` method can be stored on a ref, since `setPending`
6990 // never changes.
6991
6992
6993 var start = startTransition.bind(null, setPending);
6994 mountRef(start);
6995 return [start, isPending];
6996 }
6997
6998 function updateTransition() {
6999 var _updateState2 = updateState(),
7000 isPending = _updateState2[0];
7001
7002 var startRef = updateRef();
7003 var start = startRef.current;
7004 return [start, isPending];
7005 }
7006
7007 function rerenderTransition() {
7008 var _rerenderState2 = rerenderState(),
7009 isPending = _rerenderState2[0];
7010
7011 var startRef = updateRef();
7012 var start = startRef.current;
7013 return [start, isPending];
7014 }
7015
7016 var isUpdatingOpaqueValueInRenderPhase = false;
7017 function getIsUpdatingOpaqueValueInRenderPhaseInDEV() {
7018 {
7019 return isUpdatingOpaqueValueInRenderPhase;
7020 }
7021 }
7022
7023 function warnOnOpaqueIdentifierAccessInDEV(fiber) {
7024 {
7025 // TODO: Should warn in effects and callbacks, too
7026 var name = getComponentName(fiber.type) || 'Unknown';
7027
7028 if (getIsRendering() && !didWarnAboutUseOpaqueIdentifier[name]) {
7029 error('The object passed back from useOpaqueIdentifier is meant to be ' + 'passed through to attributes only. Do not read the ' + 'value directly.');
7030
7031 didWarnAboutUseOpaqueIdentifier[name] = true;
7032 }
7033 }
7034 }
7035
7036 function mountOpaqueIdentifier() {
7037 var makeId = makeClientIdInDEV.bind(null, warnOnOpaqueIdentifierAccessInDEV.bind(null, currentlyRenderingFiber$1)) ;
7038
7039 {
7040 var _id = makeId();
7041
7042 mountState(_id);
7043 return _id;
7044 }
7045 }
7046
7047 function updateOpaqueIdentifier() {
7048 var id = updateState()[0];
7049 return id;
7050 }
7051
7052 function rerenderOpaqueIdentifier() {
7053 var id = rerenderState()[0];
7054 return id;
7055 }
7056
7057 function dispatchAction(fiber, queue, action) {
7058 {
7059 if (typeof arguments[3] === 'function') {
7060 error("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().');
7061 }
7062 }
7063
7064 var eventTime = requestEventTime();
7065 var lane = requestUpdateLane(fiber);
7066 var update = {
7067 lane: lane,
7068 action: action,
7069 eagerReducer: null,
7070 eagerState: null,
7071 next: null
7072 }; // Append the update to the end of the list.
7073
7074 var pending = queue.pending;
7075
7076 if (pending === null) {
7077 // This is the first update. Create a circular list.
7078 update.next = update;
7079 } else {
7080 update.next = pending.next;
7081 pending.next = update;
7082 }
7083
7084 queue.pending = update;
7085 var alternate = fiber.alternate;
7086
7087 if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {
7088 // This is a render phase update. Stash it in a lazily-created map of
7089 // queue -> linked list of updates. After this render pass, we'll restart
7090 // and apply the stashed updates on top of the work-in-progress hook.
7091 didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true;
7092 } else {
7093 if (fiber.lanes === NoLanes && (alternate === null || alternate.lanes === NoLanes)) {
7094 // The queue is currently empty, which means we can eagerly compute the
7095 // next state before entering the render phase. If the new state is the
7096 // same as the current state, we may be able to bail out entirely.
7097 var lastRenderedReducer = queue.lastRenderedReducer;
7098
7099 if (lastRenderedReducer !== null) {
7100 var prevDispatcher;
7101
7102 {
7103 prevDispatcher = ReactCurrentDispatcher$1.current;
7104 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
7105 }
7106
7107 try {
7108 var currentState = queue.lastRenderedState;
7109 var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute
7110 // it, on the update object. If the reducer hasn't changed by the
7111 // time we enter the render phase, then the eager state can be used
7112 // without calling the reducer again.
7113
7114 update.eagerReducer = lastRenderedReducer;
7115 update.eagerState = eagerState;
7116
7117 if (objectIs(eagerState, currentState)) {
7118 // Fast path. We can bail out without scheduling React to re-render.
7119 // It's still possible that we'll need to rebase this update later,
7120 // if the component re-renders for a different reason and by that
7121 // time the reducer has changed.
7122 return;
7123 }
7124 } catch (error) {// Suppress the error. It will throw again in the render phase.
7125 } finally {
7126 {
7127 ReactCurrentDispatcher$1.current = prevDispatcher;
7128 }
7129 }
7130 }
7131 }
7132
7133 {
7134 // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
7135 if ('undefined' !== typeof jest) {
7136 warnIfNotScopedWithMatchingAct(fiber);
7137 warnIfNotCurrentlyActingUpdatesInDev(fiber);
7138 }
7139 }
7140
7141 scheduleUpdateOnFiber(fiber, lane, eventTime);
7142 }
7143 }
7144
7145 var ContextOnlyDispatcher = {
7146 readContext: readContext,
7147 useCallback: throwInvalidHookError,
7148 useContext: throwInvalidHookError,
7149 useEffect: throwInvalidHookError,
7150 useImperativeHandle: throwInvalidHookError,
7151 useLayoutEffect: throwInvalidHookError,
7152 useMemo: throwInvalidHookError,
7153 useReducer: throwInvalidHookError,
7154 useRef: throwInvalidHookError,
7155 useState: throwInvalidHookError,
7156 useDebugValue: throwInvalidHookError,
7157 useDeferredValue: throwInvalidHookError,
7158 useTransition: throwInvalidHookError,
7159 useMutableSource: throwInvalidHookError,
7160 useOpaqueIdentifier: throwInvalidHookError,
7161 unstable_isNewReconciler: enableNewReconciler
7162 };
7163 var HooksDispatcherOnMountInDEV = null;
7164 var HooksDispatcherOnMountWithHookTypesInDEV = null;
7165 var HooksDispatcherOnUpdateInDEV = null;
7166 var HooksDispatcherOnRerenderInDEV = null;
7167 var InvalidNestedHooksDispatcherOnMountInDEV = null;
7168 var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
7169 var InvalidNestedHooksDispatcherOnRerenderInDEV = null;
7170
7171 {
7172 var warnInvalidContextAccess = function () {
7173 error('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().');
7174 };
7175
7176 var warnInvalidHookAccess = function () {
7177 error('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://reactjs.org/link/rules-of-hooks');
7178 };
7179
7180 HooksDispatcherOnMountInDEV = {
7181 readContext: function (context, observedBits) {
7182 return readContext(context, observedBits);
7183 },
7184 useCallback: function (callback, deps) {
7185 currentHookNameInDev = 'useCallback';
7186 mountHookTypesDev();
7187 checkDepsAreArrayDev(deps);
7188 return mountCallback(callback, deps);
7189 },
7190 useContext: function (context, observedBits) {
7191 currentHookNameInDev = 'useContext';
7192 mountHookTypesDev();
7193 return readContext(context, observedBits);
7194 },
7195 useEffect: function (create, deps) {
7196 currentHookNameInDev = 'useEffect';
7197 mountHookTypesDev();
7198 checkDepsAreArrayDev(deps);
7199 return mountEffect(create, deps);
7200 },
7201 useImperativeHandle: function (ref, create, deps) {
7202 currentHookNameInDev = 'useImperativeHandle';
7203 mountHookTypesDev();
7204 checkDepsAreArrayDev(deps);
7205 return mountImperativeHandle(ref, create, deps);
7206 },
7207 useLayoutEffect: function (create, deps) {
7208 currentHookNameInDev = 'useLayoutEffect';
7209 mountHookTypesDev();
7210 checkDepsAreArrayDev(deps);
7211 return mountLayoutEffect(create, deps);
7212 },
7213 useMemo: function (create, deps) {
7214 currentHookNameInDev = 'useMemo';
7215 mountHookTypesDev();
7216 checkDepsAreArrayDev(deps);
7217 var prevDispatcher = ReactCurrentDispatcher$1.current;
7218 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
7219
7220 try {
7221 return mountMemo(create, deps);
7222 } finally {
7223 ReactCurrentDispatcher$1.current = prevDispatcher;
7224 }
7225 },
7226 useReducer: function (reducer, initialArg, init) {
7227 currentHookNameInDev = 'useReducer';
7228 mountHookTypesDev();
7229 var prevDispatcher = ReactCurrentDispatcher$1.current;
7230 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
7231
7232 try {
7233 return mountReducer(reducer, initialArg, init);
7234 } finally {
7235 ReactCurrentDispatcher$1.current = prevDispatcher;
7236 }
7237 },
7238 useRef: function (initialValue) {
7239 currentHookNameInDev = 'useRef';
7240 mountHookTypesDev();
7241 return mountRef(initialValue);
7242 },
7243 useState: function (initialState) {
7244 currentHookNameInDev = 'useState';
7245 mountHookTypesDev();
7246 var prevDispatcher = ReactCurrentDispatcher$1.current;
7247 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
7248
7249 try {
7250 return mountState(initialState);
7251 } finally {
7252 ReactCurrentDispatcher$1.current = prevDispatcher;
7253 }
7254 },
7255 useDebugValue: function (value, formatterFn) {
7256 currentHookNameInDev = 'useDebugValue';
7257 mountHookTypesDev();
7258 return mountDebugValue();
7259 },
7260 useDeferredValue: function (value) {
7261 currentHookNameInDev = 'useDeferredValue';
7262 mountHookTypesDev();
7263 return mountDeferredValue(value);
7264 },
7265 useTransition: function () {
7266 currentHookNameInDev = 'useTransition';
7267 mountHookTypesDev();
7268 return mountTransition();
7269 },
7270 useMutableSource: function (source, getSnapshot, subscribe) {
7271 currentHookNameInDev = 'useMutableSource';
7272 mountHookTypesDev();
7273 return mountMutableSource(source, getSnapshot, subscribe);
7274 },
7275 useOpaqueIdentifier: function () {
7276 currentHookNameInDev = 'useOpaqueIdentifier';
7277 mountHookTypesDev();
7278 return mountOpaqueIdentifier();
7279 },
7280 unstable_isNewReconciler: enableNewReconciler
7281 };
7282 HooksDispatcherOnMountWithHookTypesInDEV = {
7283 readContext: function (context, observedBits) {
7284 return readContext(context, observedBits);
7285 },
7286 useCallback: function (callback, deps) {
7287 currentHookNameInDev = 'useCallback';
7288 updateHookTypesDev();
7289 return mountCallback(callback, deps);
7290 },
7291 useContext: function (context, observedBits) {
7292 currentHookNameInDev = 'useContext';
7293 updateHookTypesDev();
7294 return readContext(context, observedBits);
7295 },
7296 useEffect: function (create, deps) {
7297 currentHookNameInDev = 'useEffect';
7298 updateHookTypesDev();
7299 return mountEffect(create, deps);
7300 },
7301 useImperativeHandle: function (ref, create, deps) {
7302 currentHookNameInDev = 'useImperativeHandle';
7303 updateHookTypesDev();
7304 return mountImperativeHandle(ref, create, deps);
7305 },
7306 useLayoutEffect: function (create, deps) {
7307 currentHookNameInDev = 'useLayoutEffect';
7308 updateHookTypesDev();
7309 return mountLayoutEffect(create, deps);
7310 },
7311 useMemo: function (create, deps) {
7312 currentHookNameInDev = 'useMemo';
7313 updateHookTypesDev();
7314 var prevDispatcher = ReactCurrentDispatcher$1.current;
7315 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
7316
7317 try {
7318 return mountMemo(create, deps);
7319 } finally {
7320 ReactCurrentDispatcher$1.current = prevDispatcher;
7321 }
7322 },
7323 useReducer: function (reducer, initialArg, init) {
7324 currentHookNameInDev = 'useReducer';
7325 updateHookTypesDev();
7326 var prevDispatcher = ReactCurrentDispatcher$1.current;
7327 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
7328
7329 try {
7330 return mountReducer(reducer, initialArg, init);
7331 } finally {
7332 ReactCurrentDispatcher$1.current = prevDispatcher;
7333 }
7334 },
7335 useRef: function (initialValue) {
7336 currentHookNameInDev = 'useRef';
7337 updateHookTypesDev();
7338 return mountRef(initialValue);
7339 },
7340 useState: function (initialState) {
7341 currentHookNameInDev = 'useState';
7342 updateHookTypesDev();
7343 var prevDispatcher = ReactCurrentDispatcher$1.current;
7344 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
7345
7346 try {
7347 return mountState(initialState);
7348 } finally {
7349 ReactCurrentDispatcher$1.current = prevDispatcher;
7350 }
7351 },
7352 useDebugValue: function (value, formatterFn) {
7353 currentHookNameInDev = 'useDebugValue';
7354 updateHookTypesDev();
7355 return mountDebugValue();
7356 },
7357 useDeferredValue: function (value) {
7358 currentHookNameInDev = 'useDeferredValue';
7359 updateHookTypesDev();
7360 return mountDeferredValue(value);
7361 },
7362 useTransition: function () {
7363 currentHookNameInDev = 'useTransition';
7364 updateHookTypesDev();
7365 return mountTransition();
7366 },
7367 useMutableSource: function (source, getSnapshot, subscribe) {
7368 currentHookNameInDev = 'useMutableSource';
7369 updateHookTypesDev();
7370 return mountMutableSource(source, getSnapshot, subscribe);
7371 },
7372 useOpaqueIdentifier: function () {
7373 currentHookNameInDev = 'useOpaqueIdentifier';
7374 updateHookTypesDev();
7375 return mountOpaqueIdentifier();
7376 },
7377 unstable_isNewReconciler: enableNewReconciler
7378 };
7379 HooksDispatcherOnUpdateInDEV = {
7380 readContext: function (context, observedBits) {
7381 return readContext(context, observedBits);
7382 },
7383 useCallback: function (callback, deps) {
7384 currentHookNameInDev = 'useCallback';
7385 updateHookTypesDev();
7386 return updateCallback(callback, deps);
7387 },
7388 useContext: function (context, observedBits) {
7389 currentHookNameInDev = 'useContext';
7390 updateHookTypesDev();
7391 return readContext(context, observedBits);
7392 },
7393 useEffect: function (create, deps) {
7394 currentHookNameInDev = 'useEffect';
7395 updateHookTypesDev();
7396 return updateEffect(create, deps);
7397 },
7398 useImperativeHandle: function (ref, create, deps) {
7399 currentHookNameInDev = 'useImperativeHandle';
7400 updateHookTypesDev();
7401 return updateImperativeHandle(ref, create, deps);
7402 },
7403 useLayoutEffect: function (create, deps) {
7404 currentHookNameInDev = 'useLayoutEffect';
7405 updateHookTypesDev();
7406 return updateLayoutEffect(create, deps);
7407 },
7408 useMemo: function (create, deps) {
7409 currentHookNameInDev = 'useMemo';
7410 updateHookTypesDev();
7411 var prevDispatcher = ReactCurrentDispatcher$1.current;
7412 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
7413
7414 try {
7415 return updateMemo(create, deps);
7416 } finally {
7417 ReactCurrentDispatcher$1.current = prevDispatcher;
7418 }
7419 },
7420 useReducer: function (reducer, initialArg, init) {
7421 currentHookNameInDev = 'useReducer';
7422 updateHookTypesDev();
7423 var prevDispatcher = ReactCurrentDispatcher$1.current;
7424 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
7425
7426 try {
7427 return updateReducer(reducer, initialArg, init);
7428 } finally {
7429 ReactCurrentDispatcher$1.current = prevDispatcher;
7430 }
7431 },
7432 useRef: function (initialValue) {
7433 currentHookNameInDev = 'useRef';
7434 updateHookTypesDev();
7435 return updateRef();
7436 },
7437 useState: function (initialState) {
7438 currentHookNameInDev = 'useState';
7439 updateHookTypesDev();
7440 var prevDispatcher = ReactCurrentDispatcher$1.current;
7441 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
7442
7443 try {
7444 return updateState(initialState);
7445 } finally {
7446 ReactCurrentDispatcher$1.current = prevDispatcher;
7447 }
7448 },
7449 useDebugValue: function (value, formatterFn) {
7450 currentHookNameInDev = 'useDebugValue';
7451 updateHookTypesDev();
7452 return updateDebugValue();
7453 },
7454 useDeferredValue: function (value) {
7455 currentHookNameInDev = 'useDeferredValue';
7456 updateHookTypesDev();
7457 return updateDeferredValue(value);
7458 },
7459 useTransition: function () {
7460 currentHookNameInDev = 'useTransition';
7461 updateHookTypesDev();
7462 return updateTransition();
7463 },
7464 useMutableSource: function (source, getSnapshot, subscribe) {
7465 currentHookNameInDev = 'useMutableSource';
7466 updateHookTypesDev();
7467 return updateMutableSource(source, getSnapshot, subscribe);
7468 },
7469 useOpaqueIdentifier: function () {
7470 currentHookNameInDev = 'useOpaqueIdentifier';
7471 updateHookTypesDev();
7472 return updateOpaqueIdentifier();
7473 },
7474 unstable_isNewReconciler: enableNewReconciler
7475 };
7476 HooksDispatcherOnRerenderInDEV = {
7477 readContext: function (context, observedBits) {
7478 return readContext(context, observedBits);
7479 },
7480 useCallback: function (callback, deps) {
7481 currentHookNameInDev = 'useCallback';
7482 updateHookTypesDev();
7483 return updateCallback(callback, deps);
7484 },
7485 useContext: function (context, observedBits) {
7486 currentHookNameInDev = 'useContext';
7487 updateHookTypesDev();
7488 return readContext(context, observedBits);
7489 },
7490 useEffect: function (create, deps) {
7491 currentHookNameInDev = 'useEffect';
7492 updateHookTypesDev();
7493 return updateEffect(create, deps);
7494 },
7495 useImperativeHandle: function (ref, create, deps) {
7496 currentHookNameInDev = 'useImperativeHandle';
7497 updateHookTypesDev();
7498 return updateImperativeHandle(ref, create, deps);
7499 },
7500 useLayoutEffect: function (create, deps) {
7501 currentHookNameInDev = 'useLayoutEffect';
7502 updateHookTypesDev();
7503 return updateLayoutEffect(create, deps);
7504 },
7505 useMemo: function (create, deps) {
7506 currentHookNameInDev = 'useMemo';
7507 updateHookTypesDev();
7508 var prevDispatcher = ReactCurrentDispatcher$1.current;
7509 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
7510
7511 try {
7512 return updateMemo(create, deps);
7513 } finally {
7514 ReactCurrentDispatcher$1.current = prevDispatcher;
7515 }
7516 },
7517 useReducer: function (reducer, initialArg, init) {
7518 currentHookNameInDev = 'useReducer';
7519 updateHookTypesDev();
7520 var prevDispatcher = ReactCurrentDispatcher$1.current;
7521 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
7522
7523 try {
7524 return rerenderReducer(reducer, initialArg, init);
7525 } finally {
7526 ReactCurrentDispatcher$1.current = prevDispatcher;
7527 }
7528 },
7529 useRef: function (initialValue) {
7530 currentHookNameInDev = 'useRef';
7531 updateHookTypesDev();
7532 return updateRef();
7533 },
7534 useState: function (initialState) {
7535 currentHookNameInDev = 'useState';
7536 updateHookTypesDev();
7537 var prevDispatcher = ReactCurrentDispatcher$1.current;
7538 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
7539
7540 try {
7541 return rerenderState(initialState);
7542 } finally {
7543 ReactCurrentDispatcher$1.current = prevDispatcher;
7544 }
7545 },
7546 useDebugValue: function (value, formatterFn) {
7547 currentHookNameInDev = 'useDebugValue';
7548 updateHookTypesDev();
7549 return updateDebugValue();
7550 },
7551 useDeferredValue: function (value) {
7552 currentHookNameInDev = 'useDeferredValue';
7553 updateHookTypesDev();
7554 return rerenderDeferredValue(value);
7555 },
7556 useTransition: function () {
7557 currentHookNameInDev = 'useTransition';
7558 updateHookTypesDev();
7559 return rerenderTransition();
7560 },
7561 useMutableSource: function (source, getSnapshot, subscribe) {
7562 currentHookNameInDev = 'useMutableSource';
7563 updateHookTypesDev();
7564 return updateMutableSource(source, getSnapshot, subscribe);
7565 },
7566 useOpaqueIdentifier: function () {
7567 currentHookNameInDev = 'useOpaqueIdentifier';
7568 updateHookTypesDev();
7569 return rerenderOpaqueIdentifier();
7570 },
7571 unstable_isNewReconciler: enableNewReconciler
7572 };
7573 InvalidNestedHooksDispatcherOnMountInDEV = {
7574 readContext: function (context, observedBits) {
7575 warnInvalidContextAccess();
7576 return readContext(context, observedBits);
7577 },
7578 useCallback: function (callback, deps) {
7579 currentHookNameInDev = 'useCallback';
7580 warnInvalidHookAccess();
7581 mountHookTypesDev();
7582 return mountCallback(callback, deps);
7583 },
7584 useContext: function (context, observedBits) {
7585 currentHookNameInDev = 'useContext';
7586 warnInvalidHookAccess();
7587 mountHookTypesDev();
7588 return readContext(context, observedBits);
7589 },
7590 useEffect: function (create, deps) {
7591 currentHookNameInDev = 'useEffect';
7592 warnInvalidHookAccess();
7593 mountHookTypesDev();
7594 return mountEffect(create, deps);
7595 },
7596 useImperativeHandle: function (ref, create, deps) {
7597 currentHookNameInDev = 'useImperativeHandle';
7598 warnInvalidHookAccess();
7599 mountHookTypesDev();
7600 return mountImperativeHandle(ref, create, deps);
7601 },
7602 useLayoutEffect: function (create, deps) {
7603 currentHookNameInDev = 'useLayoutEffect';
7604 warnInvalidHookAccess();
7605 mountHookTypesDev();
7606 return mountLayoutEffect(create, deps);
7607 },
7608 useMemo: function (create, deps) {
7609 currentHookNameInDev = 'useMemo';
7610 warnInvalidHookAccess();
7611 mountHookTypesDev();
7612 var prevDispatcher = ReactCurrentDispatcher$1.current;
7613 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
7614
7615 try {
7616 return mountMemo(create, deps);
7617 } finally {
7618 ReactCurrentDispatcher$1.current = prevDispatcher;
7619 }
7620 },
7621 useReducer: function (reducer, initialArg, init) {
7622 currentHookNameInDev = 'useReducer';
7623 warnInvalidHookAccess();
7624 mountHookTypesDev();
7625 var prevDispatcher = ReactCurrentDispatcher$1.current;
7626 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
7627
7628 try {
7629 return mountReducer(reducer, initialArg, init);
7630 } finally {
7631 ReactCurrentDispatcher$1.current = prevDispatcher;
7632 }
7633 },
7634 useRef: function (initialValue) {
7635 currentHookNameInDev = 'useRef';
7636 warnInvalidHookAccess();
7637 mountHookTypesDev();
7638 return mountRef(initialValue);
7639 },
7640 useState: function (initialState) {
7641 currentHookNameInDev = 'useState';
7642 warnInvalidHookAccess();
7643 mountHookTypesDev();
7644 var prevDispatcher = ReactCurrentDispatcher$1.current;
7645 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
7646
7647 try {
7648 return mountState(initialState);
7649 } finally {
7650 ReactCurrentDispatcher$1.current = prevDispatcher;
7651 }
7652 },
7653 useDebugValue: function (value, formatterFn) {
7654 currentHookNameInDev = 'useDebugValue';
7655 warnInvalidHookAccess();
7656 mountHookTypesDev();
7657 return mountDebugValue();
7658 },
7659 useDeferredValue: function (value) {
7660 currentHookNameInDev = 'useDeferredValue';
7661 warnInvalidHookAccess();
7662 mountHookTypesDev();
7663 return mountDeferredValue(value);
7664 },
7665 useTransition: function () {
7666 currentHookNameInDev = 'useTransition';
7667 warnInvalidHookAccess();
7668 mountHookTypesDev();
7669 return mountTransition();
7670 },
7671 useMutableSource: function (source, getSnapshot, subscribe) {
7672 currentHookNameInDev = 'useMutableSource';
7673 warnInvalidHookAccess();
7674 mountHookTypesDev();
7675 return mountMutableSource(source, getSnapshot, subscribe);
7676 },
7677 useOpaqueIdentifier: function () {
7678 currentHookNameInDev = 'useOpaqueIdentifier';
7679 warnInvalidHookAccess();
7680 mountHookTypesDev();
7681 return mountOpaqueIdentifier();
7682 },
7683 unstable_isNewReconciler: enableNewReconciler
7684 };
7685 InvalidNestedHooksDispatcherOnUpdateInDEV = {
7686 readContext: function (context, observedBits) {
7687 warnInvalidContextAccess();
7688 return readContext(context, observedBits);
7689 },
7690 useCallback: function (callback, deps) {
7691 currentHookNameInDev = 'useCallback';
7692 warnInvalidHookAccess();
7693 updateHookTypesDev();
7694 return updateCallback(callback, deps);
7695 },
7696 useContext: function (context, observedBits) {
7697 currentHookNameInDev = 'useContext';
7698 warnInvalidHookAccess();
7699 updateHookTypesDev();
7700 return readContext(context, observedBits);
7701 },
7702 useEffect: function (create, deps) {
7703 currentHookNameInDev = 'useEffect';
7704 warnInvalidHookAccess();
7705 updateHookTypesDev();
7706 return updateEffect(create, deps);
7707 },
7708 useImperativeHandle: function (ref, create, deps) {
7709 currentHookNameInDev = 'useImperativeHandle';
7710 warnInvalidHookAccess();
7711 updateHookTypesDev();
7712 return updateImperativeHandle(ref, create, deps);
7713 },
7714 useLayoutEffect: function (create, deps) {
7715 currentHookNameInDev = 'useLayoutEffect';
7716 warnInvalidHookAccess();
7717 updateHookTypesDev();
7718 return updateLayoutEffect(create, deps);
7719 },
7720 useMemo: function (create, deps) {
7721 currentHookNameInDev = 'useMemo';
7722 warnInvalidHookAccess();
7723 updateHookTypesDev();
7724 var prevDispatcher = ReactCurrentDispatcher$1.current;
7725 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
7726
7727 try {
7728 return updateMemo(create, deps);
7729 } finally {
7730 ReactCurrentDispatcher$1.current = prevDispatcher;
7731 }
7732 },
7733 useReducer: function (reducer, initialArg, init) {
7734 currentHookNameInDev = 'useReducer';
7735 warnInvalidHookAccess();
7736 updateHookTypesDev();
7737 var prevDispatcher = ReactCurrentDispatcher$1.current;
7738 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
7739
7740 try {
7741 return updateReducer(reducer, initialArg, init);
7742 } finally {
7743 ReactCurrentDispatcher$1.current = prevDispatcher;
7744 }
7745 },
7746 useRef: function (initialValue) {
7747 currentHookNameInDev = 'useRef';
7748 warnInvalidHookAccess();
7749 updateHookTypesDev();
7750 return updateRef();
7751 },
7752 useState: function (initialState) {
7753 currentHookNameInDev = 'useState';
7754 warnInvalidHookAccess();
7755 updateHookTypesDev();
7756 var prevDispatcher = ReactCurrentDispatcher$1.current;
7757 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
7758
7759 try {
7760 return updateState(initialState);
7761 } finally {
7762 ReactCurrentDispatcher$1.current = prevDispatcher;
7763 }
7764 },
7765 useDebugValue: function (value, formatterFn) {
7766 currentHookNameInDev = 'useDebugValue';
7767 warnInvalidHookAccess();
7768 updateHookTypesDev();
7769 return updateDebugValue();
7770 },
7771 useDeferredValue: function (value) {
7772 currentHookNameInDev = 'useDeferredValue';
7773 warnInvalidHookAccess();
7774 updateHookTypesDev();
7775 return updateDeferredValue(value);
7776 },
7777 useTransition: function () {
7778 currentHookNameInDev = 'useTransition';
7779 warnInvalidHookAccess();
7780 updateHookTypesDev();
7781 return updateTransition();
7782 },
7783 useMutableSource: function (source, getSnapshot, subscribe) {
7784 currentHookNameInDev = 'useMutableSource';
7785 warnInvalidHookAccess();
7786 updateHookTypesDev();
7787 return updateMutableSource(source, getSnapshot, subscribe);
7788 },
7789 useOpaqueIdentifier: function () {
7790 currentHookNameInDev = 'useOpaqueIdentifier';
7791 warnInvalidHookAccess();
7792 updateHookTypesDev();
7793 return updateOpaqueIdentifier();
7794 },
7795 unstable_isNewReconciler: enableNewReconciler
7796 };
7797 InvalidNestedHooksDispatcherOnRerenderInDEV = {
7798 readContext: function (context, observedBits) {
7799 warnInvalidContextAccess();
7800 return readContext(context, observedBits);
7801 },
7802 useCallback: function (callback, deps) {
7803 currentHookNameInDev = 'useCallback';
7804 warnInvalidHookAccess();
7805 updateHookTypesDev();
7806 return updateCallback(callback, deps);
7807 },
7808 useContext: function (context, observedBits) {
7809 currentHookNameInDev = 'useContext';
7810 warnInvalidHookAccess();
7811 updateHookTypesDev();
7812 return readContext(context, observedBits);
7813 },
7814 useEffect: function (create, deps) {
7815 currentHookNameInDev = 'useEffect';
7816 warnInvalidHookAccess();
7817 updateHookTypesDev();
7818 return updateEffect(create, deps);
7819 },
7820 useImperativeHandle: function (ref, create, deps) {
7821 currentHookNameInDev = 'useImperativeHandle';
7822 warnInvalidHookAccess();
7823 updateHookTypesDev();
7824 return updateImperativeHandle(ref, create, deps);
7825 },
7826 useLayoutEffect: function (create, deps) {
7827 currentHookNameInDev = 'useLayoutEffect';
7828 warnInvalidHookAccess();
7829 updateHookTypesDev();
7830 return updateLayoutEffect(create, deps);
7831 },
7832 useMemo: function (create, deps) {
7833 currentHookNameInDev = 'useMemo';
7834 warnInvalidHookAccess();
7835 updateHookTypesDev();
7836 var prevDispatcher = ReactCurrentDispatcher$1.current;
7837 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
7838
7839 try {
7840 return updateMemo(create, deps);
7841 } finally {
7842 ReactCurrentDispatcher$1.current = prevDispatcher;
7843 }
7844 },
7845 useReducer: function (reducer, initialArg, init) {
7846 currentHookNameInDev = 'useReducer';
7847 warnInvalidHookAccess();
7848 updateHookTypesDev();
7849 var prevDispatcher = ReactCurrentDispatcher$1.current;
7850 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
7851
7852 try {
7853 return rerenderReducer(reducer, initialArg, init);
7854 } finally {
7855 ReactCurrentDispatcher$1.current = prevDispatcher;
7856 }
7857 },
7858 useRef: function (initialValue) {
7859 currentHookNameInDev = 'useRef';
7860 warnInvalidHookAccess();
7861 updateHookTypesDev();
7862 return updateRef();
7863 },
7864 useState: function (initialState) {
7865 currentHookNameInDev = 'useState';
7866 warnInvalidHookAccess();
7867 updateHookTypesDev();
7868 var prevDispatcher = ReactCurrentDispatcher$1.current;
7869 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
7870
7871 try {
7872 return rerenderState(initialState);
7873 } finally {
7874 ReactCurrentDispatcher$1.current = prevDispatcher;
7875 }
7876 },
7877 useDebugValue: function (value, formatterFn) {
7878 currentHookNameInDev = 'useDebugValue';
7879 warnInvalidHookAccess();
7880 updateHookTypesDev();
7881 return updateDebugValue();
7882 },
7883 useDeferredValue: function (value) {
7884 currentHookNameInDev = 'useDeferredValue';
7885 warnInvalidHookAccess();
7886 updateHookTypesDev();
7887 return rerenderDeferredValue(value);
7888 },
7889 useTransition: function () {
7890 currentHookNameInDev = 'useTransition';
7891 warnInvalidHookAccess();
7892 updateHookTypesDev();
7893 return rerenderTransition();
7894 },
7895 useMutableSource: function (source, getSnapshot, subscribe) {
7896 currentHookNameInDev = 'useMutableSource';
7897 warnInvalidHookAccess();
7898 updateHookTypesDev();
7899 return updateMutableSource(source, getSnapshot, subscribe);
7900 },
7901 useOpaqueIdentifier: function () {
7902 currentHookNameInDev = 'useOpaqueIdentifier';
7903 warnInvalidHookAccess();
7904 updateHookTypesDev();
7905 return rerenderOpaqueIdentifier();
7906 },
7907 unstable_isNewReconciler: enableNewReconciler
7908 };
7909 }
7910
7911 var now$1 = Scheduler$1.unstable_now;
7912 var commitTime = 0;
7913 var profilerStartTime = -1;
7914
7915 function getCommitTime() {
7916 return commitTime;
7917 }
7918
7919 function recordCommitTime() {
7920
7921 commitTime = now$1();
7922 }
7923
7924 function startProfilerTimer(fiber) {
7925
7926 profilerStartTime = now$1();
7927
7928 if (fiber.actualStartTime < 0) {
7929 fiber.actualStartTime = now$1();
7930 }
7931 }
7932
7933 function stopProfilerTimerIfRunning(fiber) {
7934
7935 profilerStartTime = -1;
7936 }
7937
7938 function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
7939
7940 if (profilerStartTime >= 0) {
7941 var elapsedTime = now$1() - profilerStartTime;
7942 fiber.actualDuration += elapsedTime;
7943
7944 if (overrideBaseTime) {
7945 fiber.selfBaseDuration = elapsedTime;
7946 }
7947
7948 profilerStartTime = -1;
7949 }
7950 }
7951
7952 function transferActualDuration(fiber) {
7953 // Transfer time spent rendering these children so we don't lose it
7954 // after we rerender. This is used as a helper in special cases
7955 // where we should count the work of multiple passes.
7956 var child = fiber.child;
7957
7958 while (child) {
7959 fiber.actualDuration += child.actualDuration;
7960 child = child.sibling;
7961 }
7962 }
7963
7964 var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
7965 var didReceiveUpdate = false;
7966 var didWarnAboutBadClass;
7967 var didWarnAboutModulePatternComponent;
7968 var didWarnAboutContextTypeOnFunctionComponent;
7969 var didWarnAboutGetDerivedStateOnFunctionComponent;
7970 var didWarnAboutFunctionRefs;
7971 var didWarnAboutReassigningProps;
7972 var didWarnAboutRevealOrder;
7973 var didWarnAboutTailOptions;
7974
7975 {
7976 didWarnAboutBadClass = {};
7977 didWarnAboutModulePatternComponent = {};
7978 didWarnAboutContextTypeOnFunctionComponent = {};
7979 didWarnAboutGetDerivedStateOnFunctionComponent = {};
7980 didWarnAboutFunctionRefs = {};
7981 didWarnAboutReassigningProps = false;
7982 didWarnAboutRevealOrder = {};
7983 didWarnAboutTailOptions = {};
7984 }
7985
7986 function reconcileChildren(current, workInProgress, nextChildren, renderLanes) {
7987 if (current === null) {
7988 // If this is a fresh new component that hasn't been rendered yet, we
7989 // won't update its child set by applying minimal side-effects. Instead,
7990 // we will add them all to the child before it gets rendered. That means
7991 // we can optimize this reconciliation pass by not tracking side-effects.
7992 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderLanes);
7993 } else {
7994 // If the current child is the same as the work in progress, it means that
7995 // we haven't yet started any work on these children. Therefore, we use
7996 // the clone algorithm to create a copy of all the current children.
7997 // If we had any progressed work already, that is invalid at this point so
7998 // let's throw it out.
7999 workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren, renderLanes);
8000 }
8001 }
8002
8003 function forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes) {
8004 // This function is fork of reconcileChildren. It's used in cases where we
8005 // want to reconcile without matching against the existing set. This has the
8006 // effect of all current children being unmounted; even if the type and key
8007 // are the same, the old child is unmounted and a new child is created.
8008 //
8009 // To do this, we're going to go through the reconcile algorithm twice. In
8010 // the first pass, we schedule a deletion for all the current children by
8011 // passing null.
8012 workInProgress.child = reconcileChildFibers(workInProgress, current.child, null, renderLanes); // In the second pass, we mount the new children. The trick here is that we
8013 // pass null in place of where we usually pass the current child set. This has
8014 // the effect of remounting all children regardless of whether their
8015 // identities match.
8016
8017 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes);
8018 }
8019
8020 function updateForwardRef(current, workInProgress, Component, nextProps, renderLanes) {
8021 // TODO: current can be non-null here even if the component
8022 // hasn't yet mounted. This happens after the first render suspends.
8023 // We'll need to figure out if this is fine or can cause issues.
8024 {
8025 if (workInProgress.type !== workInProgress.elementType) {
8026 // Lazy component props can't be validated in createElement
8027 // because they're only guaranteed to be resolved here.
8028 var innerPropTypes = Component.propTypes;
8029
8030 if (innerPropTypes) {
8031 checkPropTypes(innerPropTypes, nextProps, // Resolved props
8032 'prop', getComponentName(Component));
8033 }
8034 }
8035 }
8036
8037 var render = Component.render;
8038 var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent
8039
8040 var nextChildren;
8041 prepareToReadContext(workInProgress, renderLanes);
8042
8043 {
8044 ReactCurrentOwner$1.current = workInProgress;
8045 setIsRendering(true);
8046 nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes);
8047
8048 setIsRendering(false);
8049 }
8050
8051 if (current !== null && !didReceiveUpdate) {
8052 bailoutHooks(current, workInProgress, renderLanes);
8053 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
8054 } // React DevTools reads this flag.
8055
8056
8057 workInProgress.flags |= PerformedWork;
8058 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
8059 return workInProgress.child;
8060 }
8061
8062 function updateMemoComponent(current, workInProgress, Component, nextProps, updateLanes, renderLanes) {
8063 if (current === null) {
8064 var type = Component.type;
8065
8066 if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either.
8067 Component.defaultProps === undefined) {
8068 var resolvedType = type;
8069
8070 {
8071 resolvedType = resolveFunctionForHotReloading(type);
8072 } // If this is a plain function component without default props,
8073 // and with only the default shallow comparison, we upgrade it
8074 // to a SimpleMemoComponent to allow fast path updates.
8075
8076
8077 workInProgress.tag = SimpleMemoComponent;
8078 workInProgress.type = resolvedType;
8079
8080 {
8081 validateFunctionComponentInDev(workInProgress, type);
8082 }
8083
8084 return updateSimpleMemoComponent(current, workInProgress, resolvedType, nextProps, updateLanes, renderLanes);
8085 }
8086
8087 {
8088 var innerPropTypes = type.propTypes;
8089
8090 if (innerPropTypes) {
8091 // Inner memo component props aren't currently validated in createElement.
8092 // We could move it there, but we'd still need this for lazy code path.
8093 checkPropTypes(innerPropTypes, nextProps, // Resolved props
8094 'prop', getComponentName(type));
8095 }
8096 }
8097
8098 var child = createFiberFromTypeAndProps(Component.type, null, nextProps, workInProgress, workInProgress.mode, renderLanes);
8099 child.ref = workInProgress.ref;
8100 child.return = workInProgress;
8101 workInProgress.child = child;
8102 return child;
8103 }
8104
8105 {
8106 var _type = Component.type;
8107 var _innerPropTypes = _type.propTypes;
8108
8109 if (_innerPropTypes) {
8110 // Inner memo component props aren't currently validated in createElement.
8111 // We could move it there, but we'd still need this for lazy code path.
8112 checkPropTypes(_innerPropTypes, nextProps, // Resolved props
8113 'prop', getComponentName(_type));
8114 }
8115 }
8116
8117 var currentChild = current.child; // This is always exactly one child
8118
8119 if (!includesSomeLane(updateLanes, renderLanes)) {
8120 // This will be the props with resolved defaultProps,
8121 // unlike current.memoizedProps which will be the unresolved ones.
8122 var prevProps = currentChild.memoizedProps; // Default to shallow comparison
8123
8124 var compare = Component.compare;
8125 compare = compare !== null ? compare : shallowEqual;
8126
8127 if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) {
8128 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
8129 }
8130 } // React DevTools reads this flag.
8131
8132
8133 workInProgress.flags |= PerformedWork;
8134 var newChild = createWorkInProgress(currentChild, nextProps);
8135 newChild.ref = workInProgress.ref;
8136 newChild.return = workInProgress;
8137 workInProgress.child = newChild;
8138 return newChild;
8139 }
8140
8141 function updateSimpleMemoComponent(current, workInProgress, Component, nextProps, updateLanes, renderLanes) {
8142 // TODO: current can be non-null here even if the component
8143 // hasn't yet mounted. This happens when the inner render suspends.
8144 // We'll need to figure out if this is fine or can cause issues.
8145 {
8146 if (workInProgress.type !== workInProgress.elementType) {
8147 // Lazy component props can't be validated in createElement
8148 // because they're only guaranteed to be resolved here.
8149 var outerMemoType = workInProgress.elementType;
8150
8151 if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
8152 // We warn when you define propTypes on lazy()
8153 // so let's just skip over it to find memo() outer wrapper.
8154 // Inner props for memo are validated later.
8155 var lazyComponent = outerMemoType;
8156 var payload = lazyComponent._payload;
8157 var init = lazyComponent._init;
8158
8159 try {
8160 outerMemoType = init(payload);
8161 } catch (x) {
8162 outerMemoType = null;
8163 } // Inner propTypes will be validated in the function component path.
8164
8165
8166 var outerPropTypes = outerMemoType && outerMemoType.propTypes;
8167
8168 if (outerPropTypes) {
8169 checkPropTypes(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
8170 'prop', getComponentName(outerMemoType));
8171 }
8172 }
8173 }
8174 }
8175
8176 if (current !== null) {
8177 var prevProps = current.memoizedProps;
8178
8179 if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload.
8180 workInProgress.type === current.type )) {
8181 didReceiveUpdate = false;
8182
8183 if (!includesSomeLane(renderLanes, updateLanes)) {
8184 // The pending lanes were cleared at the beginning of beginWork. We're
8185 // about to bail out, but there might be other lanes that weren't
8186 // included in the current render. Usually, the priority level of the
8187 // remaining updates is accumlated during the evaluation of the
8188 // component (i.e. when processing the update queue). But since since
8189 // we're bailing out early *without* evaluating the component, we need
8190 // to account for it here, too. Reset to the value of the current fiber.
8191 // NOTE: This only applies to SimpleMemoComponent, not MemoComponent,
8192 // because a MemoComponent fiber does not have hooks or an update queue;
8193 // rather, it wraps around an inner component, which may or may not
8194 // contains hooks.
8195 // TODO: Move the reset at in beginWork out of the common path so that
8196 // this is no longer necessary.
8197 workInProgress.lanes = current.lanes;
8198 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
8199 } else if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
8200 // This is a special case that only exists for legacy mode.
8201 // See https://github.com/facebook/react/pull/19216.
8202 didReceiveUpdate = true;
8203 }
8204 }
8205 }
8206
8207 return updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes);
8208 }
8209
8210 function updateOffscreenComponent(current, workInProgress, renderLanes) {
8211 var nextProps = workInProgress.pendingProps;
8212 var nextChildren = nextProps.children;
8213 var prevState = current !== null ? current.memoizedState : null;
8214
8215 if (nextProps.mode === 'hidden' || nextProps.mode === 'unstable-defer-without-hiding') {
8216 if ((workInProgress.mode & ConcurrentMode) === NoMode) {
8217 // In legacy sync mode, don't defer the subtree. Render it now.
8218 // TODO: Figure out what we should do in Blocking mode.
8219 var nextState = {
8220 baseLanes: NoLanes
8221 };
8222 workInProgress.memoizedState = nextState;
8223 pushRenderLanes(workInProgress, renderLanes);
8224 } else if (!includesSomeLane(renderLanes, OffscreenLane)) {
8225 var nextBaseLanes;
8226
8227 if (prevState !== null) {
8228 var prevBaseLanes = prevState.baseLanes;
8229 nextBaseLanes = mergeLanes(prevBaseLanes, renderLanes);
8230 } else {
8231 nextBaseLanes = renderLanes;
8232 } // Schedule this fiber to re-render at offscreen priority. Then bailout.
8233
8234
8235 {
8236 markSpawnedWork(OffscreenLane);
8237 }
8238
8239 workInProgress.lanes = workInProgress.childLanes = laneToLanes(OffscreenLane);
8240 var _nextState = {
8241 baseLanes: nextBaseLanes
8242 };
8243 workInProgress.memoizedState = _nextState; // We're about to bail out, but we need to push this to the stack anyway
8244 // to avoid a push/pop misalignment.
8245
8246 pushRenderLanes(workInProgress, nextBaseLanes);
8247 return null;
8248 } else {
8249 // Rendering at offscreen, so we can clear the base lanes.
8250 var _nextState2 = {
8251 baseLanes: NoLanes
8252 };
8253 workInProgress.memoizedState = _nextState2; // Push the lanes that were skipped when we bailed out.
8254
8255 var subtreeRenderLanes = prevState !== null ? prevState.baseLanes : renderLanes;
8256 pushRenderLanes(workInProgress, subtreeRenderLanes);
8257 }
8258 } else {
8259 var _subtreeRenderLanes;
8260
8261 if (prevState !== null) {
8262 _subtreeRenderLanes = mergeLanes(prevState.baseLanes, renderLanes); // Since we're not hidden anymore, reset the state
8263
8264 workInProgress.memoizedState = null;
8265 } else {
8266 // We weren't previously hidden, and we still aren't, so there's nothing
8267 // special to do. Need to push to the stack regardless, though, to avoid
8268 // a push/pop misalignment.
8269 _subtreeRenderLanes = renderLanes;
8270 }
8271
8272 pushRenderLanes(workInProgress, _subtreeRenderLanes);
8273 }
8274
8275 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
8276 return workInProgress.child;
8277 } // Note: These happen to have identical begin phases, for now. We shouldn't hold
8278 // ourselves to this constraint, though. If the behavior diverges, we should
8279 // fork the function.
8280
8281
8282 var updateLegacyHiddenComponent = updateOffscreenComponent;
8283
8284 function updateFragment(current, workInProgress, renderLanes) {
8285 var nextChildren = workInProgress.pendingProps;
8286 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
8287 return workInProgress.child;
8288 }
8289
8290 function updateMode(current, workInProgress, renderLanes) {
8291 var nextChildren = workInProgress.pendingProps.children;
8292 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
8293 return workInProgress.child;
8294 }
8295
8296 function updateProfiler(current, workInProgress, renderLanes) {
8297 {
8298 workInProgress.flags |= Update; // Reset effect durations for the next eventual effect phase.
8299 // These are reset during render to allow the DevTools commit hook a chance to read them,
8300
8301 var stateNode = workInProgress.stateNode;
8302 stateNode.effectDuration = 0;
8303 stateNode.passiveEffectDuration = 0;
8304 }
8305
8306 var nextProps = workInProgress.pendingProps;
8307 var nextChildren = nextProps.children;
8308 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
8309 return workInProgress.child;
8310 }
8311
8312 function markRef(current, workInProgress) {
8313 var ref = workInProgress.ref;
8314
8315 if (current === null && ref !== null || current !== null && current.ref !== ref) {
8316 // Schedule a Ref effect
8317 workInProgress.flags |= Ref;
8318 }
8319 }
8320
8321 function updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes) {
8322 {
8323 if (workInProgress.type !== workInProgress.elementType) {
8324 // Lazy component props can't be validated in createElement
8325 // because they're only guaranteed to be resolved here.
8326 var innerPropTypes = Component.propTypes;
8327
8328 if (innerPropTypes) {
8329 checkPropTypes(innerPropTypes, nextProps, // Resolved props
8330 'prop', getComponentName(Component));
8331 }
8332 }
8333 }
8334
8335 var context;
8336
8337 {
8338 var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
8339 context = getMaskedContext(workInProgress, unmaskedContext);
8340 }
8341
8342 var nextChildren;
8343 prepareToReadContext(workInProgress, renderLanes);
8344
8345 {
8346 ReactCurrentOwner$1.current = workInProgress;
8347 setIsRendering(true);
8348 nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes);
8349
8350 setIsRendering(false);
8351 }
8352
8353 if (current !== null && !didReceiveUpdate) {
8354 bailoutHooks(current, workInProgress, renderLanes);
8355 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
8356 } // React DevTools reads this flag.
8357
8358
8359 workInProgress.flags |= PerformedWork;
8360 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
8361 return workInProgress.child;
8362 }
8363
8364 function updateClassComponent(current, workInProgress, Component, nextProps, renderLanes) {
8365 {
8366 if (workInProgress.type !== workInProgress.elementType) {
8367 // Lazy component props can't be validated in createElement
8368 // because they're only guaranteed to be resolved here.
8369 var innerPropTypes = Component.propTypes;
8370
8371 if (innerPropTypes) {
8372 checkPropTypes(innerPropTypes, nextProps, // Resolved props
8373 'prop', getComponentName(Component));
8374 }
8375 }
8376 } // Push context providers early to prevent context stack mismatches.
8377 // During mounting we don't know the child context yet as the instance doesn't exist.
8378 // We will invalidate the child context in finishClassComponent() right after rendering.
8379
8380
8381 var hasContext;
8382
8383 if (isContextProvider(Component)) {
8384 hasContext = true;
8385 pushContextProvider(workInProgress);
8386 } else {
8387 hasContext = false;
8388 }
8389
8390 prepareToReadContext(workInProgress, renderLanes);
8391 var instance = workInProgress.stateNode;
8392 var shouldUpdate;
8393
8394 if (instance === null) {
8395 if (current !== null) {
8396 // A class component without an instance only mounts if it suspended
8397 // inside a non-concurrent tree, in an inconsistent state. We want to
8398 // treat it like a new mount, even though an empty version of it already
8399 // committed. Disconnect the alternate pointers.
8400 current.alternate = null;
8401 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
8402
8403 workInProgress.flags |= Placement;
8404 } // In the initial pass we might need to construct the instance.
8405
8406
8407 constructClassInstance(workInProgress, Component, nextProps);
8408 mountClassInstance(workInProgress, Component, nextProps, renderLanes);
8409 shouldUpdate = true;
8410 } else if (current === null) {
8411 // In a resume, we'll already have an instance we can reuse.
8412 shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderLanes);
8413 } else {
8414 shouldUpdate = updateClassInstance(current, workInProgress, Component, nextProps, renderLanes);
8415 }
8416
8417 var nextUnitOfWork = finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes);
8418
8419 {
8420 var inst = workInProgress.stateNode;
8421
8422 if (shouldUpdate && inst.props !== nextProps) {
8423 if (!didWarnAboutReassigningProps) {
8424 error('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');
8425 }
8426
8427 didWarnAboutReassigningProps = true;
8428 }
8429 }
8430
8431 return nextUnitOfWork;
8432 }
8433
8434 function finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes) {
8435 // Refs should update even if shouldComponentUpdate returns false
8436 markRef(current, workInProgress);
8437 var didCaptureError = (workInProgress.flags & DidCapture) !== NoFlags;
8438
8439 if (!shouldUpdate && !didCaptureError) {
8440 // Context providers should defer to sCU for rendering
8441 if (hasContext) {
8442 invalidateContextProvider(workInProgress, Component, false);
8443 }
8444
8445 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
8446 }
8447
8448 var instance = workInProgress.stateNode; // Rerender
8449
8450 ReactCurrentOwner$1.current = workInProgress;
8451 var nextChildren;
8452
8453 if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
8454 // If we captured an error, but getDerivedStateFromError is not defined,
8455 // unmount all the children. componentDidCatch will schedule an update to
8456 // re-render a fallback. This is temporary until we migrate everyone to
8457 // the new API.
8458 // TODO: Warn in a future release.
8459 nextChildren = null;
8460
8461 {
8462 stopProfilerTimerIfRunning();
8463 }
8464 } else {
8465 {
8466 setIsRendering(true);
8467 nextChildren = instance.render();
8468
8469 setIsRendering(false);
8470 }
8471 } // React DevTools reads this flag.
8472
8473
8474 workInProgress.flags |= PerformedWork;
8475
8476 if (current !== null && didCaptureError) {
8477 // If we're recovering from an error, reconcile without reusing any of
8478 // the existing children. Conceptually, the normal children and the children
8479 // that are shown on error are two different sets, so we shouldn't reuse
8480 // normal children even if their identities match.
8481 forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes);
8482 } else {
8483 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
8484 } // Memoize state using the values we just used to render.
8485 // TODO: Restructure so we never read values from the instance.
8486
8487
8488 workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it.
8489
8490 if (hasContext) {
8491 invalidateContextProvider(workInProgress, Component, true);
8492 }
8493
8494 return workInProgress.child;
8495 }
8496
8497 function pushHostRootContext(workInProgress) {
8498 var root = workInProgress.stateNode;
8499
8500 if (root.pendingContext) {
8501 pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
8502 } else if (root.context) {
8503 // Should always be set
8504 pushTopLevelContextObject(workInProgress, root.context, false);
8505 }
8506
8507 pushHostContainer(workInProgress, root.containerInfo);
8508 }
8509
8510 function updateHostRoot(current, workInProgress, renderLanes) {
8511 pushHostRootContext(workInProgress);
8512 var updateQueue = workInProgress.updateQueue;
8513
8514 if (!(current !== null && updateQueue !== null)) {
8515 {
8516 throw Error( "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." );
8517 }
8518 }
8519
8520 var nextProps = workInProgress.pendingProps;
8521 var prevState = workInProgress.memoizedState;
8522 var prevChildren = prevState !== null ? prevState.element : null;
8523 cloneUpdateQueue(current, workInProgress);
8524 processUpdateQueue(workInProgress, nextProps, null, renderLanes);
8525 var nextState = workInProgress.memoizedState; // Caution: React DevTools currently depends on this property
8526 // being called "element".
8527
8528 var nextChildren = nextState.element;
8529
8530 if (nextChildren === prevChildren) {
8531 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
8532 }
8533
8534 var root = workInProgress.stateNode;
8535
8536 if (root.hydrate && enterHydrationState()) {
8537
8538 var child = mountChildFibers(workInProgress, null, nextChildren, renderLanes);
8539 workInProgress.child = child;
8540 var node = child;
8541
8542 while (node) {
8543 // Mark each child as hydrating. This is a fast path to know whether this
8544 // tree is part of a hydrating tree. This is used to determine if a child
8545 // node has fully mounted yet, and for scheduling event replaying.
8546 // Conceptually this is similar to Placement in that a new subtree is
8547 // inserted into the React tree here. It just happens to not need DOM
8548 // mutations because it already exists.
8549 node.flags = node.flags & ~Placement | Hydrating;
8550 node = node.sibling;
8551 }
8552 } else {
8553 // Otherwise reset hydration state in case we aborted and resumed another
8554 // root.
8555 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
8556 }
8557
8558 return workInProgress.child;
8559 }
8560
8561 function updateHostComponent(current, workInProgress, renderLanes) {
8562 pushHostContext(workInProgress);
8563
8564 var type = workInProgress.type;
8565 var nextProps = workInProgress.pendingProps;
8566 var prevProps = current !== null ? current.memoizedProps : null;
8567 var nextChildren = nextProps.children;
8568
8569 if (prevProps !== null && shouldSetTextContent()) {
8570 // If we're switching from a direct text child to a normal child, or to
8571 // empty, we need to schedule the text content to be reset.
8572 workInProgress.flags |= ContentReset;
8573 }
8574
8575 markRef(current, workInProgress);
8576 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
8577 return workInProgress.child;
8578 }
8579
8580 function updateHostText(current, workInProgress) {
8581 // immediately after.
8582
8583
8584 return null;
8585 }
8586
8587 function mountLazyComponent(_current, workInProgress, elementType, updateLanes, renderLanes) {
8588 if (_current !== null) {
8589 // A lazy component only mounts if it suspended inside a non-
8590 // concurrent tree, in an inconsistent state. We want to treat it like
8591 // a new mount, even though an empty version of it already committed.
8592 // Disconnect the alternate pointers.
8593 _current.alternate = null;
8594 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
8595
8596 workInProgress.flags |= Placement;
8597 }
8598
8599 var props = workInProgress.pendingProps;
8600 var lazyComponent = elementType;
8601 var payload = lazyComponent._payload;
8602 var init = lazyComponent._init;
8603 var Component = init(payload); // Store the unwrapped component in the type.
8604
8605 workInProgress.type = Component;
8606 var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
8607 var resolvedProps = resolveDefaultProps(Component, props);
8608 var child;
8609
8610 switch (resolvedTag) {
8611 case FunctionComponent:
8612 {
8613 {
8614 validateFunctionComponentInDev(workInProgress, Component);
8615 workInProgress.type = Component = resolveFunctionForHotReloading(Component);
8616 }
8617
8618 child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderLanes);
8619 return child;
8620 }
8621
8622 case ClassComponent:
8623 {
8624 {
8625 workInProgress.type = Component = resolveClassForHotReloading(Component);
8626 }
8627
8628 child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderLanes);
8629 return child;
8630 }
8631
8632 case ForwardRef:
8633 {
8634 {
8635 workInProgress.type = Component = resolveForwardRefForHotReloading(Component);
8636 }
8637
8638 child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderLanes);
8639 return child;
8640 }
8641
8642 case MemoComponent:
8643 {
8644 {
8645 if (workInProgress.type !== workInProgress.elementType) {
8646 var outerPropTypes = Component.propTypes;
8647
8648 if (outerPropTypes) {
8649 checkPropTypes(outerPropTypes, resolvedProps, // Resolved for outer only
8650 'prop', getComponentName(Component));
8651 }
8652 }
8653 }
8654
8655 child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
8656 updateLanes, renderLanes);
8657 return child;
8658 }
8659 }
8660
8661 var hint = '';
8662
8663 {
8664 if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
8665 hint = ' Did you wrap a component in React.lazy() more than once?';
8666 }
8667 } // This message intentionally doesn't mention ForwardRef or MemoComponent
8668 // because the fact that it's a separate type of work is an
8669 // implementation detail.
8670
8671
8672 {
8673 {
8674 throw Error( "Element type is invalid. Received a promise that resolves to: " + Component + ". Lazy element type must resolve to a class or function." + hint );
8675 }
8676 }
8677 }
8678
8679 function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderLanes) {
8680 if (_current !== null) {
8681 // An incomplete component only mounts if it suspended inside a non-
8682 // concurrent tree, in an inconsistent state. We want to treat it like
8683 // a new mount, even though an empty version of it already committed.
8684 // Disconnect the alternate pointers.
8685 _current.alternate = null;
8686 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
8687
8688 workInProgress.flags |= Placement;
8689 } // Promote the fiber to a class and try rendering again.
8690
8691
8692 workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent`
8693 // Push context providers early to prevent context stack mismatches.
8694 // During mounting we don't know the child context yet as the instance doesn't exist.
8695 // We will invalidate the child context in finishClassComponent() right after rendering.
8696
8697 var hasContext;
8698
8699 if (isContextProvider(Component)) {
8700 hasContext = true;
8701 pushContextProvider(workInProgress);
8702 } else {
8703 hasContext = false;
8704 }
8705
8706 prepareToReadContext(workInProgress, renderLanes);
8707 constructClassInstance(workInProgress, Component, nextProps);
8708 mountClassInstance(workInProgress, Component, nextProps, renderLanes);
8709 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes);
8710 }
8711
8712 function mountIndeterminateComponent(_current, workInProgress, Component, renderLanes) {
8713 if (_current !== null) {
8714 // An indeterminate component only mounts if it suspended inside a non-
8715 // concurrent tree, in an inconsistent state. We want to treat it like
8716 // a new mount, even though an empty version of it already committed.
8717 // Disconnect the alternate pointers.
8718 _current.alternate = null;
8719 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
8720
8721 workInProgress.flags |= Placement;
8722 }
8723
8724 var props = workInProgress.pendingProps;
8725 var context;
8726
8727 {
8728 var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
8729 context = getMaskedContext(workInProgress, unmaskedContext);
8730 }
8731
8732 prepareToReadContext(workInProgress, renderLanes);
8733 var value;
8734
8735 {
8736 if (Component.prototype && typeof Component.prototype.render === 'function') {
8737 var componentName = getComponentName(Component) || 'Unknown';
8738
8739 if (!didWarnAboutBadClass[componentName]) {
8740 error("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);
8741
8742 didWarnAboutBadClass[componentName] = true;
8743 }
8744 }
8745
8746 if (workInProgress.mode & StrictMode) {
8747 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
8748 }
8749
8750 setIsRendering(true);
8751 ReactCurrentOwner$1.current = workInProgress;
8752 value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes);
8753 setIsRendering(false);
8754 } // React DevTools reads this flag.
8755
8756
8757 workInProgress.flags |= PerformedWork;
8758
8759 {
8760 // Support for module components is deprecated and is removed behind a flag.
8761 // Whether or not it would crash later, we want to show a good message in DEV first.
8762 if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
8763 var _componentName = getComponentName(Component) || 'Unknown';
8764
8765 if (!didWarnAboutModulePatternComponent[_componentName]) {
8766 error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);
8767
8768 didWarnAboutModulePatternComponent[_componentName] = true;
8769 }
8770 }
8771 }
8772
8773 if ( // Run these checks in production only if the flag is off.
8774 // Eventually we'll delete this branch altogether.
8775 typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
8776 {
8777 var _componentName2 = getComponentName(Component) || 'Unknown';
8778
8779 if (!didWarnAboutModulePatternComponent[_componentName2]) {
8780 error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2);
8781
8782 didWarnAboutModulePatternComponent[_componentName2] = true;
8783 }
8784 } // Proceed under the assumption that this is a class instance
8785
8786
8787 workInProgress.tag = ClassComponent; // Throw out any hooks that were used.
8788
8789 workInProgress.memoizedState = null;
8790 workInProgress.updateQueue = null; // Push context providers early to prevent context stack mismatches.
8791 // During mounting we don't know the child context yet as the instance doesn't exist.
8792 // We will invalidate the child context in finishClassComponent() right after rendering.
8793
8794 var hasContext = false;
8795
8796 if (isContextProvider(Component)) {
8797 hasContext = true;
8798 pushContextProvider(workInProgress);
8799 } else {
8800 hasContext = false;
8801 }
8802
8803 workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
8804 initializeUpdateQueue(workInProgress);
8805 var getDerivedStateFromProps = Component.getDerivedStateFromProps;
8806
8807 if (typeof getDerivedStateFromProps === 'function') {
8808 applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);
8809 }
8810
8811 adoptClassInstance(workInProgress, value);
8812 mountClassInstance(workInProgress, Component, props, renderLanes);
8813 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes);
8814 } else {
8815 // Proceed under the assumption that this is a function component
8816 workInProgress.tag = FunctionComponent;
8817
8818 reconcileChildren(null, workInProgress, value, renderLanes);
8819
8820 {
8821 validateFunctionComponentInDev(workInProgress, Component);
8822 }
8823
8824 return workInProgress.child;
8825 }
8826 }
8827
8828 function validateFunctionComponentInDev(workInProgress, Component) {
8829 {
8830 if (Component) {
8831 if (Component.childContextTypes) {
8832 error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component');
8833 }
8834 }
8835
8836 if (workInProgress.ref !== null) {
8837 var info = '';
8838 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
8839
8840 if (ownerName) {
8841 info += '\n\nCheck the render method of `' + ownerName + '`.';
8842 }
8843
8844 var warningKey = ownerName || workInProgress._debugID || '';
8845 var debugSource = workInProgress._debugSource;
8846
8847 if (debugSource) {
8848 warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
8849 }
8850
8851 if (!didWarnAboutFunctionRefs[warningKey]) {
8852 didWarnAboutFunctionRefs[warningKey] = true;
8853
8854 error('Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info);
8855 }
8856 }
8857
8858 if (typeof Component.getDerivedStateFromProps === 'function') {
8859 var _componentName3 = getComponentName(Component) || 'Unknown';
8860
8861 if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) {
8862 error('%s: Function components do not support getDerivedStateFromProps.', _componentName3);
8863
8864 didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true;
8865 }
8866 }
8867
8868 if (typeof Component.contextType === 'object' && Component.contextType !== null) {
8869 var _componentName4 = getComponentName(Component) || 'Unknown';
8870
8871 if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) {
8872 error('%s: Function components do not support contextType.', _componentName4);
8873
8874 didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true;
8875 }
8876 }
8877 }
8878 }
8879
8880 var SUSPENDED_MARKER = {
8881 dehydrated: null,
8882 retryLane: NoLane
8883 };
8884
8885 function mountSuspenseOffscreenState(renderLanes) {
8886 return {
8887 baseLanes: renderLanes
8888 };
8889 }
8890
8891 function updateSuspenseOffscreenState(prevOffscreenState, renderLanes) {
8892 return {
8893 baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes)
8894 };
8895 } // TODO: Probably should inline this back
8896
8897
8898 function shouldRemainOnFallback(suspenseContext, current, workInProgress, renderLanes) {
8899 // If we're already showing a fallback, there are cases where we need to
8900 // remain on that fallback regardless of whether the content has resolved.
8901 // For example, SuspenseList coordinates when nested content appears.
8902 if (current !== null) {
8903 var suspenseState = current.memoizedState;
8904
8905 if (suspenseState === null) {
8906 // Currently showing content. Don't hide it, even if ForceSuspenseFallack
8907 // is true. More precise name might be "ForceRemainSuspenseFallback".
8908 // Note: This is a factoring smell. Can't remain on a fallback if there's
8909 // no fallback to remain on.
8910 return false;
8911 }
8912 } // Not currently showing content. Consult the Suspense context.
8913
8914
8915 return hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
8916 }
8917
8918 function getRemainingWorkInPrimaryTree(current, renderLanes) {
8919 // TODO: Should not remove render lanes that were pinged during this render
8920 return removeLanes(current.childLanes, renderLanes);
8921 }
8922
8923 function updateSuspenseComponent(current, workInProgress, renderLanes) {
8924 var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend.
8925
8926 {
8927 if (shouldSuspend(workInProgress)) {
8928 workInProgress.flags |= DidCapture;
8929 }
8930 }
8931
8932 var suspenseContext = suspenseStackCursor.current;
8933 var showFallback = false;
8934 var didSuspend = (workInProgress.flags & DidCapture) !== NoFlags;
8935
8936 if (didSuspend || shouldRemainOnFallback(suspenseContext, current)) {
8937 // Something in this boundary's subtree already suspended. Switch to
8938 // rendering the fallback children.
8939 showFallback = true;
8940 workInProgress.flags &= ~DidCapture;
8941 } else {
8942 // Attempting the main content
8943 if (current === null || current.memoizedState !== null) {
8944 // This is a new mount or this boundary is already showing a fallback state.
8945 // Mark this subtree context as having at least one invisible parent that could
8946 // handle the fallback state.
8947 // Boundaries without fallbacks or should be avoided are not considered since
8948 // they cannot handle preferred fallback states.
8949 if (nextProps.fallback !== undefined && nextProps.unstable_avoidThisFallback !== true) {
8950 suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext);
8951 }
8952 }
8953 }
8954
8955 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
8956 pushSuspenseContext(workInProgress, suspenseContext); // OK, the next part is confusing. We're about to reconcile the Suspense
8957 // boundary's children. This involves some custom reconcilation logic. Two
8958 // main reasons this is so complicated.
8959 //
8960 // First, Legacy Mode has different semantics for backwards compatibility. The
8961 // primary tree will commit in an inconsistent state, so when we do the
8962 // second pass to render the fallback, we do some exceedingly, uh, clever
8963 // hacks to make that not totally break. Like transferring effects and
8964 // deletions from hidden tree. In Concurrent Mode, it's much simpler,
8965 // because we bailout on the primary tree completely and leave it in its old
8966 // state, no effects. Same as what we do for Offscreen (except that
8967 // Offscreen doesn't have the first render pass).
8968 //
8969 // Second is hydration. During hydration, the Suspense fiber has a slightly
8970 // different layout, where the child points to a dehydrated fragment, which
8971 // contains the DOM rendered by the server.
8972 //
8973 // Third, even if you set all that aside, Suspense is like error boundaries in
8974 // that we first we try to render one tree, and if that fails, we render again
8975 // and switch to a different tree. Like a try/catch block. So we have to track
8976 // which branch we're currently rendering. Ideally we would model this using
8977 // a stack.
8978
8979 if (current === null) {
8980 // Initial mount
8981 // If we're currently hydrating, try to hydrate this boundary.
8982 // But only if this has a fallback.
8983 if (nextProps.fallback !== undefined) ;
8984
8985 var nextPrimaryChildren = nextProps.children;
8986 var nextFallbackChildren = nextProps.fallback;
8987
8988 if (showFallback) {
8989 var fallbackFragment = mountSuspenseFallbackChildren(workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes);
8990 var primaryChildFragment = workInProgress.child;
8991 primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes);
8992 workInProgress.memoizedState = SUSPENDED_MARKER;
8993 return fallbackFragment;
8994 } else if (typeof nextProps.unstable_expectedLoadTime === 'number') {
8995 // This is a CPU-bound tree. Skip this tree and show a placeholder to
8996 // unblock the surrounding content. Then immediately retry after the
8997 // initial commit.
8998 var _fallbackFragment = mountSuspenseFallbackChildren(workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes);
8999
9000 var _primaryChildFragment = workInProgress.child;
9001 _primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes);
9002 workInProgress.memoizedState = SUSPENDED_MARKER; // Since nothing actually suspended, there will nothing to ping this to
9003 // get it started back up to attempt the next item. While in terms of
9004 // priority this work has the same priority as this current render, it's
9005 // not part of the same transition once the transition has committed. If
9006 // it's sync, we still want to yield so that it can be painted.
9007 // Conceptually, this is really the same as pinging. We can use any
9008 // RetryLane even if it's the one currently rendering since we're leaving
9009 // it behind on this node.
9010
9011 workInProgress.lanes = SomeRetryLane;
9012
9013 {
9014 markSpawnedWork(SomeRetryLane);
9015 }
9016
9017 return _fallbackFragment;
9018 } else {
9019 return mountSuspensePrimaryChildren(workInProgress, nextPrimaryChildren, renderLanes);
9020 }
9021 } else {
9022 // This is an update.
9023 // If the current fiber has a SuspenseState, that means it's already showing
9024 // a fallback.
9025 var prevState = current.memoizedState;
9026
9027 if (prevState !== null) {
9028
9029 if (showFallback) {
9030 var _nextFallbackChildren2 = nextProps.fallback;
9031 var _nextPrimaryChildren2 = nextProps.children;
9032
9033 var _fallbackChildFragment = updateSuspenseFallbackChildren(current, workInProgress, _nextPrimaryChildren2, _nextFallbackChildren2, renderLanes);
9034
9035 var _primaryChildFragment3 = workInProgress.child;
9036 var prevOffscreenState = current.child.memoizedState;
9037 _primaryChildFragment3.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes);
9038 _primaryChildFragment3.childLanes = getRemainingWorkInPrimaryTree(current, renderLanes);
9039 workInProgress.memoizedState = SUSPENDED_MARKER;
9040 return _fallbackChildFragment;
9041 } else {
9042 var _nextPrimaryChildren3 = nextProps.children;
9043
9044 var _primaryChildFragment4 = updateSuspensePrimaryChildren(current, workInProgress, _nextPrimaryChildren3, renderLanes);
9045
9046 workInProgress.memoizedState = null;
9047 return _primaryChildFragment4;
9048 }
9049 } else {
9050 // The current tree is not already showing a fallback.
9051 if (showFallback) {
9052 // Timed out.
9053 var _nextFallbackChildren3 = nextProps.fallback;
9054 var _nextPrimaryChildren4 = nextProps.children;
9055
9056 var _fallbackChildFragment2 = updateSuspenseFallbackChildren(current, workInProgress, _nextPrimaryChildren4, _nextFallbackChildren3, renderLanes);
9057
9058 var _primaryChildFragment5 = workInProgress.child;
9059 var _prevOffscreenState = current.child.memoizedState;
9060 _primaryChildFragment5.memoizedState = _prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(_prevOffscreenState, renderLanes);
9061 _primaryChildFragment5.childLanes = getRemainingWorkInPrimaryTree(current, renderLanes); // Skip the primary children, and continue working on the
9062 // fallback children.
9063
9064 workInProgress.memoizedState = SUSPENDED_MARKER;
9065 return _fallbackChildFragment2;
9066 } else {
9067 // Still haven't timed out. Continue rendering the children, like we
9068 // normally do.
9069 var _nextPrimaryChildren5 = nextProps.children;
9070
9071 var _primaryChildFragment6 = updateSuspensePrimaryChildren(current, workInProgress, _nextPrimaryChildren5, renderLanes);
9072
9073 workInProgress.memoizedState = null;
9074 return _primaryChildFragment6;
9075 }
9076 }
9077 }
9078 }
9079
9080 function mountSuspensePrimaryChildren(workInProgress, primaryChildren, renderLanes) {
9081 var mode = workInProgress.mode;
9082 var primaryChildProps = {
9083 mode: 'visible',
9084 children: primaryChildren
9085 };
9086 var primaryChildFragment = createFiberFromOffscreen(primaryChildProps, mode, renderLanes, null);
9087 primaryChildFragment.return = workInProgress;
9088 workInProgress.child = primaryChildFragment;
9089 return primaryChildFragment;
9090 }
9091
9092 function mountSuspenseFallbackChildren(workInProgress, primaryChildren, fallbackChildren, renderLanes) {
9093 var mode = workInProgress.mode;
9094 var progressedPrimaryFragment = workInProgress.child;
9095 var primaryChildProps = {
9096 mode: 'hidden',
9097 children: primaryChildren
9098 };
9099 var primaryChildFragment;
9100 var fallbackChildFragment;
9101
9102 if ((mode & BlockingMode) === NoMode && progressedPrimaryFragment !== null) {
9103 // In legacy mode, we commit the primary tree as if it successfully
9104 // completed, even though it's in an inconsistent state.
9105 primaryChildFragment = progressedPrimaryFragment;
9106 primaryChildFragment.childLanes = NoLanes;
9107 primaryChildFragment.pendingProps = primaryChildProps;
9108
9109 if ( workInProgress.mode & ProfileMode) {
9110 // Reset the durations from the first pass so they aren't included in the
9111 // final amounts. This seems counterintuitive, since we're intentionally
9112 // not measuring part of the render phase, but this makes it match what we
9113 // do in Concurrent Mode.
9114 primaryChildFragment.actualDuration = 0;
9115 primaryChildFragment.actualStartTime = -1;
9116 primaryChildFragment.selfBaseDuration = 0;
9117 primaryChildFragment.treeBaseDuration = 0;
9118 }
9119
9120 fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null);
9121 } else {
9122 primaryChildFragment = createFiberFromOffscreen(primaryChildProps, mode, NoLanes, null);
9123 fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null);
9124 }
9125
9126 primaryChildFragment.return = workInProgress;
9127 fallbackChildFragment.return = workInProgress;
9128 primaryChildFragment.sibling = fallbackChildFragment;
9129 workInProgress.child = primaryChildFragment;
9130 return fallbackChildFragment;
9131 }
9132
9133 function createWorkInProgressOffscreenFiber(current, offscreenProps) {
9134 // The props argument to `createWorkInProgress` is `any` typed, so we use this
9135 // wrapper function to constrain it.
9136 return createWorkInProgress(current, offscreenProps);
9137 }
9138
9139 function updateSuspensePrimaryChildren(current, workInProgress, primaryChildren, renderLanes) {
9140 var currentPrimaryChildFragment = current.child;
9141 var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
9142 var primaryChildFragment = createWorkInProgressOffscreenFiber(currentPrimaryChildFragment, {
9143 mode: 'visible',
9144 children: primaryChildren
9145 });
9146
9147 if ((workInProgress.mode & BlockingMode) === NoMode) {
9148 primaryChildFragment.lanes = renderLanes;
9149 }
9150
9151 primaryChildFragment.return = workInProgress;
9152 primaryChildFragment.sibling = null;
9153
9154 if (currentFallbackChildFragment !== null) {
9155 // Delete the fallback child fragment
9156 currentFallbackChildFragment.nextEffect = null;
9157 currentFallbackChildFragment.flags = Deletion;
9158 workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChildFragment;
9159 }
9160
9161 workInProgress.child = primaryChildFragment;
9162 return primaryChildFragment;
9163 }
9164
9165 function updateSuspenseFallbackChildren(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) {
9166 var mode = workInProgress.mode;
9167 var currentPrimaryChildFragment = current.child;
9168 var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
9169 var primaryChildProps = {
9170 mode: 'hidden',
9171 children: primaryChildren
9172 };
9173 var primaryChildFragment;
9174
9175 if ( // In legacy mode, we commit the primary tree as if it successfully
9176 // completed, even though it's in an inconsistent state.
9177 (mode & BlockingMode) === NoMode && // Make sure we're on the second pass, i.e. the primary child fragment was
9178 // already cloned. In legacy mode, the only case where this isn't true is
9179 // when DevTools forces us to display a fallback; we skip the first render
9180 // pass entirely and go straight to rendering the fallback. (In Concurrent
9181 // Mode, SuspenseList can also trigger this scenario, but this is a legacy-
9182 // only codepath.)
9183 workInProgress.child !== currentPrimaryChildFragment) {
9184 var progressedPrimaryFragment = workInProgress.child;
9185 primaryChildFragment = progressedPrimaryFragment;
9186 primaryChildFragment.childLanes = NoLanes;
9187 primaryChildFragment.pendingProps = primaryChildProps;
9188
9189 if ( workInProgress.mode & ProfileMode) {
9190 // Reset the durations from the first pass so they aren't included in the
9191 // final amounts. This seems counterintuitive, since we're intentionally
9192 // not measuring part of the render phase, but this makes it match what we
9193 // do in Concurrent Mode.
9194 primaryChildFragment.actualDuration = 0;
9195 primaryChildFragment.actualStartTime = -1;
9196 primaryChildFragment.selfBaseDuration = currentPrimaryChildFragment.selfBaseDuration;
9197 primaryChildFragment.treeBaseDuration = currentPrimaryChildFragment.treeBaseDuration;
9198 } // The fallback fiber was added as a deletion effect during the first pass.
9199 // However, since we're going to remain on the fallback, we no longer want
9200 // to delete it. So we need to remove it from the list. Deletions are stored
9201 // on the same list as effects. We want to keep the effects from the primary
9202 // tree. So we copy the primary child fragment's effect list, which does not
9203 // include the fallback deletion effect.
9204
9205
9206 var progressedLastEffect = primaryChildFragment.lastEffect;
9207
9208 if (progressedLastEffect !== null) {
9209 workInProgress.firstEffect = primaryChildFragment.firstEffect;
9210 workInProgress.lastEffect = progressedLastEffect;
9211 progressedLastEffect.nextEffect = null;
9212 } else {
9213 // TODO: Reset this somewhere else? Lol legacy mode is so weird.
9214 workInProgress.firstEffect = workInProgress.lastEffect = null;
9215 }
9216 } else {
9217 primaryChildFragment = createWorkInProgressOffscreenFiber(currentPrimaryChildFragment, primaryChildProps);
9218 }
9219
9220 var fallbackChildFragment;
9221
9222 if (currentFallbackChildFragment !== null) {
9223 fallbackChildFragment = createWorkInProgress(currentFallbackChildFragment, fallbackChildren);
9224 } else {
9225 fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); // Needs a placement effect because the parent (the Suspense boundary) already
9226 // mounted but this is a new fiber.
9227
9228 fallbackChildFragment.flags |= Placement;
9229 }
9230
9231 fallbackChildFragment.return = workInProgress;
9232 primaryChildFragment.return = workInProgress;
9233 primaryChildFragment.sibling = fallbackChildFragment;
9234 workInProgress.child = primaryChildFragment;
9235 return fallbackChildFragment;
9236 }
9237
9238 function scheduleWorkOnFiber(fiber, renderLanes) {
9239 fiber.lanes = mergeLanes(fiber.lanes, renderLanes);
9240 var alternate = fiber.alternate;
9241
9242 if (alternate !== null) {
9243 alternate.lanes = mergeLanes(alternate.lanes, renderLanes);
9244 }
9245
9246 scheduleWorkOnParentPath(fiber.return, renderLanes);
9247 }
9248
9249 function propagateSuspenseContextChange(workInProgress, firstChild, renderLanes) {
9250 // Mark any Suspense boundaries with fallbacks as having work to do.
9251 // If they were previously forced into fallbacks, they may now be able
9252 // to unblock.
9253 var node = firstChild;
9254
9255 while (node !== null) {
9256 if (node.tag === SuspenseComponent) {
9257 var state = node.memoizedState;
9258
9259 if (state !== null) {
9260 scheduleWorkOnFiber(node, renderLanes);
9261 }
9262 } else if (node.tag === SuspenseListComponent) {
9263 // If the tail is hidden there might not be an Suspense boundaries
9264 // to schedule work on. In this case we have to schedule it on the
9265 // list itself.
9266 // We don't have to traverse to the children of the list since
9267 // the list will propagate the change when it rerenders.
9268 scheduleWorkOnFiber(node, renderLanes);
9269 } else if (node.child !== null) {
9270 node.child.return = node;
9271 node = node.child;
9272 continue;
9273 }
9274
9275 if (node === workInProgress) {
9276 return;
9277 }
9278
9279 while (node.sibling === null) {
9280 if (node.return === null || node.return === workInProgress) {
9281 return;
9282 }
9283
9284 node = node.return;
9285 }
9286
9287 node.sibling.return = node.return;
9288 node = node.sibling;
9289 }
9290 }
9291
9292 function findLastContentRow(firstChild) {
9293 // This is going to find the last row among these children that is already
9294 // showing content on the screen, as opposed to being in fallback state or
9295 // new. If a row has multiple Suspense boundaries, any of them being in the
9296 // fallback state, counts as the whole row being in a fallback state.
9297 // Note that the "rows" will be workInProgress, but any nested children
9298 // will still be current since we haven't rendered them yet. The mounted
9299 // order may not be the same as the new order. We use the new order.
9300 var row = firstChild;
9301 var lastContentRow = null;
9302
9303 while (row !== null) {
9304 var currentRow = row.alternate; // New rows can't be content rows.
9305
9306 if (currentRow !== null && findFirstSuspended(currentRow) === null) {
9307 lastContentRow = row;
9308 }
9309
9310 row = row.sibling;
9311 }
9312
9313 return lastContentRow;
9314 }
9315
9316 function validateRevealOrder(revealOrder) {
9317 {
9318 if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) {
9319 didWarnAboutRevealOrder[revealOrder] = true;
9320
9321 if (typeof revealOrder === 'string') {
9322 switch (revealOrder.toLowerCase()) {
9323 case 'together':
9324 case 'forwards':
9325 case 'backwards':
9326 {
9327 error('"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase());
9328
9329 break;
9330 }
9331
9332 case 'forward':
9333 case 'backward':
9334 {
9335 error('"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase());
9336
9337 break;
9338 }
9339
9340 default:
9341 error('"%s" is not a supported revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
9342
9343 break;
9344 }
9345 } else {
9346 error('%s is not a supported value for revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
9347 }
9348 }
9349 }
9350 }
9351
9352 function validateTailOptions(tailMode, revealOrder) {
9353 {
9354 if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) {
9355 if (tailMode !== 'collapsed' && tailMode !== 'hidden') {
9356 didWarnAboutTailOptions[tailMode] = true;
9357
9358 error('"%s" is not a supported value for tail on <SuspenseList />. ' + 'Did you mean "collapsed" or "hidden"?', tailMode);
9359 } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') {
9360 didWarnAboutTailOptions[tailMode] = true;
9361
9362 error('<SuspenseList tail="%s" /> is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode);
9363 }
9364 }
9365 }
9366 }
9367
9368 function validateSuspenseListNestedChild(childSlot, index) {
9369 {
9370 var isArray = Array.isArray(childSlot);
9371 var isIterable = !isArray && typeof getIteratorFn(childSlot) === 'function';
9372
9373 if (isArray || isIterable) {
9374 var type = isArray ? 'array' : 'iterable';
9375
9376 error('A nested %s was passed to row #%s in <SuspenseList />. Wrap it in ' + 'an additional SuspenseList to configure its revealOrder: ' + '<SuspenseList revealOrder=...> ... ' + '<SuspenseList revealOrder=...>{%s}</SuspenseList> ... ' + '</SuspenseList>', type, index, type);
9377
9378 return false;
9379 }
9380 }
9381
9382 return true;
9383 }
9384
9385 function validateSuspenseListChildren(children, revealOrder) {
9386 {
9387 if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) {
9388 if (Array.isArray(children)) {
9389 for (var i = 0; i < children.length; i++) {
9390 if (!validateSuspenseListNestedChild(children[i], i)) {
9391 return;
9392 }
9393 }
9394 } else {
9395 var iteratorFn = getIteratorFn(children);
9396
9397 if (typeof iteratorFn === 'function') {
9398 var childrenIterator = iteratorFn.call(children);
9399
9400 if (childrenIterator) {
9401 var step = childrenIterator.next();
9402 var _i = 0;
9403
9404 for (; !step.done; step = childrenIterator.next()) {
9405 if (!validateSuspenseListNestedChild(step.value, _i)) {
9406 return;
9407 }
9408
9409 _i++;
9410 }
9411 }
9412 } else {
9413 error('A single row was passed to a <SuspenseList revealOrder="%s" />. ' + 'This is not useful since it needs multiple rows. ' + 'Did you mean to pass multiple children or an array?', revealOrder);
9414 }
9415 }
9416 }
9417 }
9418 }
9419
9420 function initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode, lastEffectBeforeRendering) {
9421 var renderState = workInProgress.memoizedState;
9422
9423 if (renderState === null) {
9424 workInProgress.memoizedState = {
9425 isBackwards: isBackwards,
9426 rendering: null,
9427 renderingStartTime: 0,
9428 last: lastContentRow,
9429 tail: tail,
9430 tailMode: tailMode,
9431 lastEffect: lastEffectBeforeRendering
9432 };
9433 } else {
9434 // We can reuse the existing object from previous renders.
9435 renderState.isBackwards = isBackwards;
9436 renderState.rendering = null;
9437 renderState.renderingStartTime = 0;
9438 renderState.last = lastContentRow;
9439 renderState.tail = tail;
9440 renderState.tailMode = tailMode;
9441 renderState.lastEffect = lastEffectBeforeRendering;
9442 }
9443 } // This can end up rendering this component multiple passes.
9444 // The first pass splits the children fibers into two sets. A head and tail.
9445 // We first render the head. If anything is in fallback state, we do another
9446 // pass through beginWork to rerender all children (including the tail) with
9447 // the force suspend context. If the first render didn't have anything in
9448 // in fallback state. Then we render each row in the tail one-by-one.
9449 // That happens in the completeWork phase without going back to beginWork.
9450
9451
9452 function updateSuspenseListComponent(current, workInProgress, renderLanes) {
9453 var nextProps = workInProgress.pendingProps;
9454 var revealOrder = nextProps.revealOrder;
9455 var tailMode = nextProps.tail;
9456 var newChildren = nextProps.children;
9457 validateRevealOrder(revealOrder);
9458 validateTailOptions(tailMode, revealOrder);
9459 validateSuspenseListChildren(newChildren, revealOrder);
9460 reconcileChildren(current, workInProgress, newChildren, renderLanes);
9461 var suspenseContext = suspenseStackCursor.current;
9462 var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
9463
9464 if (shouldForceFallback) {
9465 suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
9466 workInProgress.flags |= DidCapture;
9467 } else {
9468 var didSuspendBefore = current !== null && (current.flags & DidCapture) !== NoFlags;
9469
9470 if (didSuspendBefore) {
9471 // If we previously forced a fallback, we need to schedule work
9472 // on any nested boundaries to let them know to try to render
9473 // again. This is the same as context updating.
9474 propagateSuspenseContextChange(workInProgress, workInProgress.child, renderLanes);
9475 }
9476
9477 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
9478 }
9479
9480 pushSuspenseContext(workInProgress, suspenseContext);
9481
9482 if ((workInProgress.mode & BlockingMode) === NoMode) {
9483 // In legacy mode, SuspenseList doesn't work so we just
9484 // use make it a noop by treating it as the default revealOrder.
9485 workInProgress.memoizedState = null;
9486 } else {
9487 switch (revealOrder) {
9488 case 'forwards':
9489 {
9490 var lastContentRow = findLastContentRow(workInProgress.child);
9491 var tail;
9492
9493 if (lastContentRow === null) {
9494 // The whole list is part of the tail.
9495 // TODO: We could fast path by just rendering the tail now.
9496 tail = workInProgress.child;
9497 workInProgress.child = null;
9498 } else {
9499 // Disconnect the tail rows after the content row.
9500 // We're going to render them separately later.
9501 tail = lastContentRow.sibling;
9502 lastContentRow.sibling = null;
9503 }
9504
9505 initSuspenseListRenderState(workInProgress, false, // isBackwards
9506 tail, lastContentRow, tailMode, workInProgress.lastEffect);
9507 break;
9508 }
9509
9510 case 'backwards':
9511 {
9512 // We're going to find the first row that has existing content.
9513 // At the same time we're going to reverse the list of everything
9514 // we pass in the meantime. That's going to be our tail in reverse
9515 // order.
9516 var _tail = null;
9517 var row = workInProgress.child;
9518 workInProgress.child = null;
9519
9520 while (row !== null) {
9521 var currentRow = row.alternate; // New rows can't be content rows.
9522
9523 if (currentRow !== null && findFirstSuspended(currentRow) === null) {
9524 // This is the beginning of the main content.
9525 workInProgress.child = row;
9526 break;
9527 }
9528
9529 var nextRow = row.sibling;
9530 row.sibling = _tail;
9531 _tail = row;
9532 row = nextRow;
9533 } // TODO: If workInProgress.child is null, we can continue on the tail immediately.
9534
9535
9536 initSuspenseListRenderState(workInProgress, true, // isBackwards
9537 _tail, null, // last
9538 tailMode, workInProgress.lastEffect);
9539 break;
9540 }
9541
9542 case 'together':
9543 {
9544 initSuspenseListRenderState(workInProgress, false, // isBackwards
9545 null, // tail
9546 null, // last
9547 undefined, workInProgress.lastEffect);
9548 break;
9549 }
9550
9551 default:
9552 {
9553 // The default reveal order is the same as not having
9554 // a boundary.
9555 workInProgress.memoizedState = null;
9556 }
9557 }
9558 }
9559
9560 return workInProgress.child;
9561 }
9562
9563 function updatePortalComponent(current, workInProgress, renderLanes) {
9564 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
9565 var nextChildren = workInProgress.pendingProps;
9566
9567 if (current === null) {
9568 // Portals are special because we don't append the children during mount
9569 // but at commit. Therefore we need to track insertions which the normal
9570 // flow doesn't do during mount. This doesn't happen at the root because
9571 // the root always starts with a "current" with a null child.
9572 // TODO: Consider unifying this with how the root works.
9573 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes);
9574 } else {
9575 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
9576 }
9577
9578 return workInProgress.child;
9579 }
9580
9581 var hasWarnedAboutUsingNoValuePropOnContextProvider = false;
9582
9583 function updateContextProvider(current, workInProgress, renderLanes) {
9584 var providerType = workInProgress.type;
9585 var context = providerType._context;
9586 var newProps = workInProgress.pendingProps;
9587 var oldProps = workInProgress.memoizedProps;
9588 var newValue = newProps.value;
9589
9590 {
9591 if (!('value' in newProps)) {
9592 if (!hasWarnedAboutUsingNoValuePropOnContextProvider) {
9593 hasWarnedAboutUsingNoValuePropOnContextProvider = true;
9594
9595 error('The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?');
9596 }
9597 }
9598
9599 var providerPropTypes = workInProgress.type.propTypes;
9600
9601 if (providerPropTypes) {
9602 checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider');
9603 }
9604 }
9605
9606 pushProvider(workInProgress, newValue);
9607
9608 if (oldProps !== null) {
9609 var oldValue = oldProps.value;
9610 var changedBits = calculateChangedBits(context, newValue, oldValue);
9611
9612 if (changedBits === 0) {
9613 // No change. Bailout early if children are the same.
9614 if (oldProps.children === newProps.children && !hasContextChanged()) {
9615 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
9616 }
9617 } else {
9618 // The context value changed. Search for matching consumers and schedule
9619 // them to update.
9620 propagateContextChange(workInProgress, context, changedBits, renderLanes);
9621 }
9622 }
9623
9624 var newChildren = newProps.children;
9625 reconcileChildren(current, workInProgress, newChildren, renderLanes);
9626 return workInProgress.child;
9627 }
9628
9629 var hasWarnedAboutUsingContextAsConsumer = false;
9630
9631 function updateContextConsumer(current, workInProgress, renderLanes) {
9632 var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In
9633 // DEV mode, we create a separate object for Context.Consumer that acts
9634 // like a proxy to Context. This proxy object adds unnecessary code in PROD
9635 // so we use the old behaviour (Context.Consumer references Context) to
9636 // reduce size and overhead. The separate object references context via
9637 // a property called "_context", which also gives us the ability to check
9638 // in DEV mode if this property exists or not and warn if it does not.
9639
9640 {
9641 if (context._context === undefined) {
9642 // This may be because it's a Context (rather than a Consumer).
9643 // Or it may be because it's older React where they're the same thing.
9644 // We only want to warn if we're sure it's a new React.
9645 if (context !== context.Consumer) {
9646 if (!hasWarnedAboutUsingContextAsConsumer) {
9647 hasWarnedAboutUsingContextAsConsumer = true;
9648
9649 error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
9650 }
9651 }
9652 } else {
9653 context = context._context;
9654 }
9655 }
9656
9657 var newProps = workInProgress.pendingProps;
9658 var render = newProps.children;
9659
9660 {
9661 if (typeof render !== 'function') {
9662 error('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.');
9663 }
9664 }
9665
9666 prepareToReadContext(workInProgress, renderLanes);
9667 var newValue = readContext(context, newProps.unstable_observedBits);
9668 var newChildren;
9669
9670 {
9671 ReactCurrentOwner$1.current = workInProgress;
9672 setIsRendering(true);
9673 newChildren = render(newValue);
9674 setIsRendering(false);
9675 } // React DevTools reads this flag.
9676
9677
9678 workInProgress.flags |= PerformedWork;
9679 reconcileChildren(current, workInProgress, newChildren, renderLanes);
9680 return workInProgress.child;
9681 }
9682
9683 function markWorkInProgressReceivedUpdate() {
9684 didReceiveUpdate = true;
9685 }
9686
9687 function bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes) {
9688 if (current !== null) {
9689 // Reuse previous dependencies
9690 workInProgress.dependencies = current.dependencies;
9691 }
9692
9693 {
9694 // Don't update "base" render times for bailouts.
9695 stopProfilerTimerIfRunning();
9696 }
9697
9698 markSkippedUpdateLanes(workInProgress.lanes); // Check if the children have any pending work.
9699
9700 if (!includesSomeLane(renderLanes, workInProgress.childLanes)) {
9701 // The children don't have any work either. We can skip them.
9702 // TODO: Once we add back resuming, we should check if the children are
9703 // a work-in-progress set. If so, we need to transfer their effects.
9704 return null;
9705 } else {
9706 // This fiber doesn't have work, but its subtree does. Clone the child
9707 // fibers and continue.
9708 cloneChildFibers(current, workInProgress);
9709 return workInProgress.child;
9710 }
9711 }
9712
9713 function remountFiber(current, oldWorkInProgress, newWorkInProgress) {
9714 {
9715 var returnFiber = oldWorkInProgress.return;
9716
9717 if (returnFiber === null) {
9718 throw new Error('Cannot swap the root fiber.');
9719 } // Disconnect from the old current.
9720 // It will get deleted.
9721
9722
9723 current.alternate = null;
9724 oldWorkInProgress.alternate = null; // Connect to the new tree.
9725
9726 newWorkInProgress.index = oldWorkInProgress.index;
9727 newWorkInProgress.sibling = oldWorkInProgress.sibling;
9728 newWorkInProgress.return = oldWorkInProgress.return;
9729 newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it.
9730
9731 if (oldWorkInProgress === returnFiber.child) {
9732 returnFiber.child = newWorkInProgress;
9733 } else {
9734 var prevSibling = returnFiber.child;
9735
9736 if (prevSibling === null) {
9737 throw new Error('Expected parent to have a child.');
9738 }
9739
9740 while (prevSibling.sibling !== oldWorkInProgress) {
9741 prevSibling = prevSibling.sibling;
9742
9743 if (prevSibling === null) {
9744 throw new Error('Expected to find the previous sibling.');
9745 }
9746 }
9747
9748 prevSibling.sibling = newWorkInProgress;
9749 } // Delete the old fiber and place the new one.
9750 // Since the old fiber is disconnected, we have to schedule it manually.
9751
9752
9753 var last = returnFiber.lastEffect;
9754
9755 if (last !== null) {
9756 last.nextEffect = current;
9757 returnFiber.lastEffect = current;
9758 } else {
9759 returnFiber.firstEffect = returnFiber.lastEffect = current;
9760 }
9761
9762 current.nextEffect = null;
9763 current.flags = Deletion;
9764 newWorkInProgress.flags |= Placement; // Restart work from the new fiber.
9765
9766 return newWorkInProgress;
9767 }
9768 }
9769
9770 function beginWork(current, workInProgress, renderLanes) {
9771 var updateLanes = workInProgress.lanes;
9772
9773 {
9774 if (workInProgress._debugNeedsRemount && current !== null) {
9775 // This will restart the begin phase with a new fiber.
9776 return remountFiber(current, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.lanes));
9777 }
9778 }
9779
9780 if (current !== null) {
9781 var oldProps = current.memoizedProps;
9782 var newProps = workInProgress.pendingProps;
9783
9784 if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload:
9785 workInProgress.type !== current.type )) {
9786 // If props or context changed, mark the fiber as having performed work.
9787 // This may be unset if the props are determined to be equal later (memo).
9788 didReceiveUpdate = true;
9789 } else if (!includesSomeLane(renderLanes, updateLanes)) {
9790 didReceiveUpdate = false; // This fiber does not have any pending work. Bailout without entering
9791 // the begin phase. There's still some bookkeeping we that needs to be done
9792 // in this optimized path, mostly pushing stuff onto the stack.
9793
9794 switch (workInProgress.tag) {
9795 case HostRoot:
9796 pushHostRootContext(workInProgress);
9797 break;
9798
9799 case HostComponent:
9800 pushHostContext(workInProgress);
9801 break;
9802
9803 case ClassComponent:
9804 {
9805 var Component = workInProgress.type;
9806
9807 if (isContextProvider(Component)) {
9808 pushContextProvider(workInProgress);
9809 }
9810
9811 break;
9812 }
9813
9814 case HostPortal:
9815 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
9816 break;
9817
9818 case ContextProvider:
9819 {
9820 var newValue = workInProgress.memoizedProps.value;
9821 pushProvider(workInProgress, newValue);
9822 break;
9823 }
9824
9825 case Profiler:
9826 {
9827 // Profiler should only call onRender when one of its descendants actually rendered.
9828 var hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes);
9829
9830 if (hasChildWork) {
9831 workInProgress.flags |= Update;
9832 } // Reset effect durations for the next eventual effect phase.
9833 // These are reset during render to allow the DevTools commit hook a chance to read them,
9834
9835
9836 var stateNode = workInProgress.stateNode;
9837 stateNode.effectDuration = 0;
9838 stateNode.passiveEffectDuration = 0;
9839 }
9840
9841 break;
9842
9843 case SuspenseComponent:
9844 {
9845 var state = workInProgress.memoizedState;
9846
9847 if (state !== null) {
9848 // whether to retry the primary children, or to skip over it and
9849 // go straight to the fallback. Check the priority of the primary
9850 // child fragment.
9851
9852
9853 var primaryChildFragment = workInProgress.child;
9854 var primaryChildLanes = primaryChildFragment.childLanes;
9855
9856 if (includesSomeLane(renderLanes, primaryChildLanes)) {
9857 // The primary children have pending work. Use the normal path
9858 // to attempt to render the primary children again.
9859 return updateSuspenseComponent(current, workInProgress, renderLanes);
9860 } else {
9861 // The primary child fragment does not have pending work marked
9862 // on it
9863 pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient
9864 // priority. Bailout.
9865
9866 var child = bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
9867
9868 if (child !== null) {
9869 // The fallback children have pending work. Skip over the
9870 // primary children and work on the fallback.
9871 return child.sibling;
9872 } else {
9873 return null;
9874 }
9875 }
9876 } else {
9877 pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
9878 }
9879
9880 break;
9881 }
9882
9883 case SuspenseListComponent:
9884 {
9885 var didSuspendBefore = (current.flags & DidCapture) !== NoFlags;
9886
9887 var _hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes);
9888
9889 if (didSuspendBefore) {
9890 if (_hasChildWork) {
9891 // If something was in fallback state last time, and we have all the
9892 // same children then we're still in progressive loading state.
9893 // Something might get unblocked by state updates or retries in the
9894 // tree which will affect the tail. So we need to use the normal
9895 // path to compute the correct tail.
9896 return updateSuspenseListComponent(current, workInProgress, renderLanes);
9897 } // If none of the children had any work, that means that none of
9898 // them got retried so they'll still be blocked in the same way
9899 // as before. We can fast bail out.
9900
9901
9902 workInProgress.flags |= DidCapture;
9903 } // If nothing suspended before and we're rendering the same children,
9904 // then the tail doesn't matter. Anything new that suspends will work
9905 // in the "together" mode, so we can continue from the state we had.
9906
9907
9908 var renderState = workInProgress.memoizedState;
9909
9910 if (renderState !== null) {
9911 // Reset to the "together" mode in case we've started a different
9912 // update in the past but didn't complete it.
9913 renderState.rendering = null;
9914 renderState.tail = null;
9915 renderState.lastEffect = null;
9916 }
9917
9918 pushSuspenseContext(workInProgress, suspenseStackCursor.current);
9919
9920 if (_hasChildWork) {
9921 break;
9922 } else {
9923 // If none of the children had any work, that means that none of
9924 // them got retried so they'll still be blocked in the same way
9925 // as before. We can fast bail out.
9926 return null;
9927 }
9928 }
9929
9930 case OffscreenComponent:
9931 case LegacyHiddenComponent:
9932 {
9933 // Need to check if the tree still needs to be deferred. This is
9934 // almost identical to the logic used in the normal update path,
9935 // so we'll just enter that. The only difference is we'll bail out
9936 // at the next level instead of this one, because the child props
9937 // have not changed. Which is fine.
9938 // TODO: Probably should refactor `beginWork` to split the bailout
9939 // path from the normal path. I'm tempted to do a labeled break here
9940 // but I won't :)
9941 workInProgress.lanes = NoLanes;
9942 return updateOffscreenComponent(current, workInProgress, renderLanes);
9943 }
9944 }
9945
9946 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
9947 } else {
9948 if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
9949 // This is a special case that only exists for legacy mode.
9950 // See https://github.com/facebook/react/pull/19216.
9951 didReceiveUpdate = true;
9952 } else {
9953 // An update was scheduled on this fiber, but there are no new props
9954 // nor legacy context. Set this to false. If an update queue or context
9955 // consumer produces a changed value, it will set this to true. Otherwise,
9956 // the component will assume the children have not changed and bail out.
9957 didReceiveUpdate = false;
9958 }
9959 }
9960 } else {
9961 didReceiveUpdate = false;
9962 } // Before entering the begin phase, clear pending update priority.
9963 // TODO: This assumes that we're about to evaluate the component and process
9964 // the update queue. However, there's an exception: SimpleMemoComponent
9965 // sometimes bails out later in the begin phase. This indicates that we should
9966 // move this assignment out of the common path and into each branch.
9967
9968
9969 workInProgress.lanes = NoLanes;
9970
9971 switch (workInProgress.tag) {
9972 case IndeterminateComponent:
9973 {
9974 return mountIndeterminateComponent(current, workInProgress, workInProgress.type, renderLanes);
9975 }
9976
9977 case LazyComponent:
9978 {
9979 var elementType = workInProgress.elementType;
9980 return mountLazyComponent(current, workInProgress, elementType, updateLanes, renderLanes);
9981 }
9982
9983 case FunctionComponent:
9984 {
9985 var _Component = workInProgress.type;
9986 var unresolvedProps = workInProgress.pendingProps;
9987 var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
9988 return updateFunctionComponent(current, workInProgress, _Component, resolvedProps, renderLanes);
9989 }
9990
9991 case ClassComponent:
9992 {
9993 var _Component2 = workInProgress.type;
9994 var _unresolvedProps = workInProgress.pendingProps;
9995
9996 var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);
9997
9998 return updateClassComponent(current, workInProgress, _Component2, _resolvedProps, renderLanes);
9999 }
10000
10001 case HostRoot:
10002 return updateHostRoot(current, workInProgress, renderLanes);
10003
10004 case HostComponent:
10005 return updateHostComponent(current, workInProgress, renderLanes);
10006
10007 case HostText:
10008 return updateHostText();
10009
10010 case SuspenseComponent:
10011 return updateSuspenseComponent(current, workInProgress, renderLanes);
10012
10013 case HostPortal:
10014 return updatePortalComponent(current, workInProgress, renderLanes);
10015
10016 case ForwardRef:
10017 {
10018 var type = workInProgress.type;
10019 var _unresolvedProps2 = workInProgress.pendingProps;
10020
10021 var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
10022
10023 return updateForwardRef(current, workInProgress, type, _resolvedProps2, renderLanes);
10024 }
10025
10026 case Fragment:
10027 return updateFragment(current, workInProgress, renderLanes);
10028
10029 case Mode:
10030 return updateMode(current, workInProgress, renderLanes);
10031
10032 case Profiler:
10033 return updateProfiler(current, workInProgress, renderLanes);
10034
10035 case ContextProvider:
10036 return updateContextProvider(current, workInProgress, renderLanes);
10037
10038 case ContextConsumer:
10039 return updateContextConsumer(current, workInProgress, renderLanes);
10040
10041 case MemoComponent:
10042 {
10043 var _type2 = workInProgress.type;
10044 var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props.
10045
10046 var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
10047
10048 {
10049 if (workInProgress.type !== workInProgress.elementType) {
10050 var outerPropTypes = _type2.propTypes;
10051
10052 if (outerPropTypes) {
10053 checkPropTypes(outerPropTypes, _resolvedProps3, // Resolved for outer only
10054 'prop', getComponentName(_type2));
10055 }
10056 }
10057 }
10058
10059 _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
10060 return updateMemoComponent(current, workInProgress, _type2, _resolvedProps3, updateLanes, renderLanes);
10061 }
10062
10063 case SimpleMemoComponent:
10064 {
10065 return updateSimpleMemoComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps, updateLanes, renderLanes);
10066 }
10067
10068 case IncompleteClassComponent:
10069 {
10070 var _Component3 = workInProgress.type;
10071 var _unresolvedProps4 = workInProgress.pendingProps;
10072
10073 var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);
10074
10075 return mountIncompleteClassComponent(current, workInProgress, _Component3, _resolvedProps4, renderLanes);
10076 }
10077
10078 case SuspenseListComponent:
10079 {
10080 return updateSuspenseListComponent(current, workInProgress, renderLanes);
10081 }
10082
10083 case FundamentalComponent:
10084 {
10085
10086 break;
10087 }
10088
10089 case ScopeComponent:
10090 {
10091
10092 break;
10093 }
10094
10095 case Block:
10096 {
10097
10098 break;
10099 }
10100
10101 case OffscreenComponent:
10102 {
10103 return updateOffscreenComponent(current, workInProgress, renderLanes);
10104 }
10105
10106 case LegacyHiddenComponent:
10107 {
10108 return updateLegacyHiddenComponent(current, workInProgress, renderLanes);
10109 }
10110 }
10111
10112 {
10113 {
10114 throw Error( "Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in React. Please file an issue." );
10115 }
10116 }
10117 }
10118
10119 function markUpdate(workInProgress) {
10120 // Tag the fiber with an update effect. This turns a Placement into
10121 // a PlacementAndUpdate.
10122 workInProgress.flags |= Update;
10123 }
10124
10125 function markRef$1(workInProgress) {
10126 workInProgress.flags |= Ref;
10127 }
10128
10129 var appendAllChildren;
10130 var updateHostContainer;
10131 var updateHostComponent$1;
10132 var updateHostText$1;
10133
10134 {
10135 // Mutation mode
10136 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
10137 // We only have the top Fiber that was created but we need recurse down its
10138 // children to find all the terminal nodes.
10139 var node = workInProgress.child;
10140
10141 while (node !== null) {
10142 if (node.tag === HostComponent || node.tag === HostText) {
10143 appendInitialChild(parent, node.stateNode);
10144 } else if (node.tag === HostPortal) ; else if (node.child !== null) {
10145 node.child.return = node;
10146 node = node.child;
10147 continue;
10148 }
10149
10150 if (node === workInProgress) {
10151 return;
10152 }
10153
10154 while (node.sibling === null) {
10155 if (node.return === null || node.return === workInProgress) {
10156 return;
10157 }
10158
10159 node = node.return;
10160 }
10161
10162 node.sibling.return = node.return;
10163 node = node.sibling;
10164 }
10165 };
10166
10167 updateHostContainer = function (workInProgress) {// Noop
10168 };
10169
10170 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
10171 // If we have an alternate, that means this is an update and we need to
10172 // schedule a side-effect to do the updates.
10173 var oldProps = current.memoizedProps;
10174
10175 if (oldProps === newProps) {
10176 // In mutation mode, this is sufficient for a bailout because
10177 // we won't touch this node even if children changed.
10178 return;
10179 } // If we get updated because one of our children updated, we don't
10180 // have newProps so we'll have to reuse them.
10181 // TODO: Split the update API as separate for the props vs. children.
10182 // Even better would be if children weren't special cased at all tho.
10183
10184
10185 var instance = workInProgress.stateNode;
10186 var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host
10187 // component is hitting the resume path. Figure out why. Possibly
10188 // related to `hidden`.
10189
10190 var updatePayload = prepareUpdate(); // TODO: Type this specific to this type of component.
10191
10192 workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
10193 // is a new ref we mark this as an update. All the work is done in commitWork.
10194
10195 if (updatePayload) {
10196 markUpdate(workInProgress);
10197 }
10198 };
10199
10200 updateHostText$1 = function (current, workInProgress, oldText, newText) {
10201 // If the text differs, mark it as an update. All the work in done in commitWork.
10202 if (oldText !== newText) {
10203 markUpdate(workInProgress);
10204 }
10205 };
10206 }
10207
10208 function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
10209
10210 switch (renderState.tailMode) {
10211 case 'hidden':
10212 {
10213 // Any insertions at the end of the tail list after this point
10214 // should be invisible. If there are already mounted boundaries
10215 // anything before them are not considered for collapsing.
10216 // Therefore we need to go through the whole tail to find if
10217 // there are any.
10218 var tailNode = renderState.tail;
10219 var lastTailNode = null;
10220
10221 while (tailNode !== null) {
10222 if (tailNode.alternate !== null) {
10223 lastTailNode = tailNode;
10224 }
10225
10226 tailNode = tailNode.sibling;
10227 } // Next we're simply going to delete all insertions after the
10228 // last rendered item.
10229
10230
10231 if (lastTailNode === null) {
10232 // All remaining items in the tail are insertions.
10233 renderState.tail = null;
10234 } else {
10235 // Detach the insertion after the last node that was already
10236 // inserted.
10237 lastTailNode.sibling = null;
10238 }
10239
10240 break;
10241 }
10242
10243 case 'collapsed':
10244 {
10245 // Any insertions at the end of the tail list after this point
10246 // should be invisible. If there are already mounted boundaries
10247 // anything before them are not considered for collapsing.
10248 // Therefore we need to go through the whole tail to find if
10249 // there are any.
10250 var _tailNode = renderState.tail;
10251 var _lastTailNode = null;
10252
10253 while (_tailNode !== null) {
10254 if (_tailNode.alternate !== null) {
10255 _lastTailNode = _tailNode;
10256 }
10257
10258 _tailNode = _tailNode.sibling;
10259 } // Next we're simply going to delete all insertions after the
10260 // last rendered item.
10261
10262
10263 if (_lastTailNode === null) {
10264 // All remaining items in the tail are insertions.
10265 if (!hasRenderedATailFallback && renderState.tail !== null) {
10266 // We suspended during the head. We want to show at least one
10267 // row at the tail. So we'll keep on and cut off the rest.
10268 renderState.tail.sibling = null;
10269 } else {
10270 renderState.tail = null;
10271 }
10272 } else {
10273 // Detach the insertion after the last node that was already
10274 // inserted.
10275 _lastTailNode.sibling = null;
10276 }
10277
10278 break;
10279 }
10280 }
10281 }
10282
10283 function completeWork(current, workInProgress, renderLanes) {
10284 var newProps = workInProgress.pendingProps;
10285
10286 switch (workInProgress.tag) {
10287 case IndeterminateComponent:
10288 case LazyComponent:
10289 case SimpleMemoComponent:
10290 case FunctionComponent:
10291 case ForwardRef:
10292 case Fragment:
10293 case Mode:
10294 case Profiler:
10295 case ContextConsumer:
10296 case MemoComponent:
10297 return null;
10298
10299 case ClassComponent:
10300 {
10301 var Component = workInProgress.type;
10302
10303 if (isContextProvider(Component)) {
10304 popContext(workInProgress);
10305 }
10306
10307 return null;
10308 }
10309
10310 case HostRoot:
10311 {
10312 popHostContainer(workInProgress);
10313 popTopLevelContextObject(workInProgress);
10314 resetWorkInProgressVersions();
10315 var fiberRoot = workInProgress.stateNode;
10316
10317 if (fiberRoot.pendingContext) {
10318 fiberRoot.context = fiberRoot.pendingContext;
10319 fiberRoot.pendingContext = null;
10320 }
10321
10322 if (current === null || current.child === null) {
10323 // If we hydrated, pop so that we can delete any remaining children
10324 // that weren't hydrated.
10325 var wasHydrated = popHydrationState();
10326
10327 if (wasHydrated) {
10328 // If we hydrated, then we'll need to schedule an update for
10329 // the commit side-effects on the root.
10330 markUpdate(workInProgress);
10331 } else if (!fiberRoot.hydrate) {
10332 // Schedule an effect to clear this container at the start of the next commit.
10333 // This handles the case of React rendering into a container with previous children.
10334 // It's also safe to do for updates too, because current.child would only be null
10335 // if the previous render was null (so the the container would already be empty).
10336 workInProgress.flags |= Snapshot;
10337 }
10338 }
10339
10340 updateHostContainer(workInProgress);
10341 return null;
10342 }
10343
10344 case HostComponent:
10345 {
10346 popHostContext(workInProgress);
10347 var rootContainerInstance = getRootHostContainer();
10348 var type = workInProgress.type;
10349
10350 if (current !== null && workInProgress.stateNode != null) {
10351 updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);
10352
10353 if (current.ref !== workInProgress.ref) {
10354 markRef$1(workInProgress);
10355 }
10356 } else {
10357 if (!newProps) {
10358 if (!(workInProgress.stateNode !== null)) {
10359 {
10360 throw Error( "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." );
10361 }
10362 } // This can happen when we abort work.
10363
10364
10365 return null;
10366 }
10367
10368 var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context
10369 // "stack" as the parent. Then append children as we go in beginWork
10370 // or completeWork depending on whether we want to add them top->down or
10371 // bottom->up. Top->down is faster in IE11.
10372
10373 var _wasHydrated = popHydrationState();
10374
10375 if (_wasHydrated) {
10376 // TODO: Move this and createInstance step into the beginPhase
10377 // to consolidate.
10378 if (prepareToHydrateHostInstance()) {
10379 // If changes to the hydrated node need to be applied at the
10380 // commit-phase we mark this as such.
10381 markUpdate(workInProgress);
10382 }
10383 } else {
10384 var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
10385 appendAllChildren(instance, workInProgress, false, false);
10386 workInProgress.stateNode = instance; // Certain renderers require commit-time effects for initial mount.
10387 }
10388
10389 if (workInProgress.ref !== null) {
10390 // If there is a ref on a host node we need to schedule a callback
10391 markRef$1(workInProgress);
10392 }
10393 }
10394
10395 return null;
10396 }
10397
10398 case HostText:
10399 {
10400 var newText = newProps;
10401
10402 if (current && workInProgress.stateNode != null) {
10403 var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need
10404 // to schedule a side-effect to do the updates.
10405
10406 updateHostText$1(current, workInProgress, oldText, newText);
10407 } else {
10408 if (typeof newText !== 'string') {
10409 if (!(workInProgress.stateNode !== null)) {
10410 {
10411 throw Error( "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." );
10412 }
10413 } // This can happen when we abort work.
10414
10415 }
10416
10417 var _rootContainerInstance = getRootHostContainer();
10418
10419 var _currentHostContext = getHostContext();
10420
10421 var _wasHydrated2 = popHydrationState();
10422
10423 if (_wasHydrated2) {
10424 if (prepareToHydrateHostTextInstance()) {
10425 markUpdate(workInProgress);
10426 }
10427 } else {
10428 workInProgress.stateNode = createTextInstance(newText);
10429 }
10430 }
10431
10432 return null;
10433 }
10434
10435 case SuspenseComponent:
10436 {
10437 popSuspenseContext(workInProgress);
10438 var nextState = workInProgress.memoizedState;
10439
10440 if ((workInProgress.flags & DidCapture) !== NoFlags) {
10441 // Something suspended. Re-render with the fallback children.
10442 workInProgress.lanes = renderLanes; // Do not reset the effect list.
10443
10444 if ( (workInProgress.mode & ProfileMode) !== NoMode) {
10445 transferActualDuration(workInProgress);
10446 }
10447
10448 return workInProgress;
10449 }
10450
10451 var nextDidTimeout = nextState !== null;
10452 var prevDidTimeout = false;
10453
10454 if (current === null) {
10455 if (workInProgress.memoizedProps.fallback !== undefined) ;
10456 } else {
10457 var prevState = current.memoizedState;
10458 prevDidTimeout = prevState !== null;
10459 }
10460
10461 if (nextDidTimeout && !prevDidTimeout) {
10462 // If this subtreee is running in blocking mode we can suspend,
10463 // otherwise we won't suspend.
10464 // TODO: This will still suspend a synchronous tree if anything
10465 // in the concurrent tree already suspended during this render.
10466 // This is a known bug.
10467 if ((workInProgress.mode & BlockingMode) !== NoMode) {
10468 // TODO: Move this back to throwException because this is too late
10469 // if this is a large tree which is common for initial loads. We
10470 // don't know if we should restart a render or not until we get
10471 // this marker, and this is too late.
10472 // If this render already had a ping or lower pri updates,
10473 // and this is the first time we know we're going to suspend we
10474 // should be able to immediately restart from within throwException.
10475 var hasInvisibleChildContext = current === null && workInProgress.memoizedProps.unstable_avoidThisFallback !== true;
10476
10477 if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) {
10478 // If this was in an invisible tree or a new render, then showing
10479 // this boundary is ok.
10480 renderDidSuspend();
10481 } else {
10482 // Otherwise, we're going to have to hide content so we should
10483 // suspend for longer if possible.
10484 renderDidSuspendDelayIfPossible();
10485 }
10486 }
10487 }
10488
10489 {
10490 // TODO: Only schedule updates if these values are non equal, i.e. it changed.
10491 if (nextDidTimeout || prevDidTimeout) {
10492 // If this boundary just timed out, schedule an effect to attach a
10493 // retry listener to the promise. This flag is also used to hide the
10494 // primary children. In mutation mode, we also need the flag to
10495 // *unhide* children that were previously hidden, so check if this
10496 // is currently timed out, too.
10497 workInProgress.flags |= Update;
10498 }
10499 }
10500
10501 return null;
10502 }
10503
10504 case HostPortal:
10505 popHostContainer(workInProgress);
10506 updateHostContainer(workInProgress);
10507
10508 if (current === null) {
10509 preparePortalMount(workInProgress.stateNode.containerInfo);
10510 }
10511
10512 return null;
10513
10514 case ContextProvider:
10515 // Pop provider fiber
10516 popProvider(workInProgress);
10517 return null;
10518
10519 case IncompleteClassComponent:
10520 {
10521 // Same as class component case. I put it down here so that the tags are
10522 // sequential to ensure this switch is compiled to a jump table.
10523 var _Component = workInProgress.type;
10524
10525 if (isContextProvider(_Component)) {
10526 popContext(workInProgress);
10527 }
10528
10529 return null;
10530 }
10531
10532 case SuspenseListComponent:
10533 {
10534 popSuspenseContext(workInProgress);
10535 var renderState = workInProgress.memoizedState;
10536
10537 if (renderState === null) {
10538 // We're running in the default, "independent" mode.
10539 // We don't do anything in this mode.
10540 return null;
10541 }
10542
10543 var didSuspendAlready = (workInProgress.flags & DidCapture) !== NoFlags;
10544 var renderedTail = renderState.rendering;
10545
10546 if (renderedTail === null) {
10547 // We just rendered the head.
10548 if (!didSuspendAlready) {
10549 // This is the first pass. We need to figure out if anything is still
10550 // suspended in the rendered set.
10551 // If new content unsuspended, but there's still some content that
10552 // didn't. Then we need to do a second pass that forces everything
10553 // to keep showing their fallbacks.
10554 // We might be suspended if something in this render pass suspended, or
10555 // something in the previous committed pass suspended. Otherwise,
10556 // there's no chance so we can skip the expensive call to
10557 // findFirstSuspended.
10558 var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.flags & DidCapture) === NoFlags);
10559
10560 if (!cannotBeSuspended) {
10561 var row = workInProgress.child;
10562
10563 while (row !== null) {
10564 var suspended = findFirstSuspended(row);
10565
10566 if (suspended !== null) {
10567 didSuspendAlready = true;
10568 workInProgress.flags |= DidCapture;
10569 cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as
10570 // part of the second pass. In that case nothing will subscribe to
10571 // its thennables. Instead, we'll transfer its thennables to the
10572 // SuspenseList so that it can retry if they resolve.
10573 // There might be multiple of these in the list but since we're
10574 // going to wait for all of them anyway, it doesn't really matter
10575 // which ones gets to ping. In theory we could get clever and keep
10576 // track of how many dependencies remain but it gets tricky because
10577 // in the meantime, we can add/remove/change items and dependencies.
10578 // We might bail out of the loop before finding any but that
10579 // doesn't matter since that means that the other boundaries that
10580 // we did find already has their listeners attached.
10581
10582 var newThennables = suspended.updateQueue;
10583
10584 if (newThennables !== null) {
10585 workInProgress.updateQueue = newThennables;
10586 workInProgress.flags |= Update;
10587 } // Rerender the whole list, but this time, we'll force fallbacks
10588 // to stay in place.
10589 // Reset the effect list before doing the second pass since that's now invalid.
10590
10591
10592 if (renderState.lastEffect === null) {
10593 workInProgress.firstEffect = null;
10594 }
10595
10596 workInProgress.lastEffect = renderState.lastEffect; // Reset the child fibers to their original state.
10597
10598 resetChildFibers(workInProgress, renderLanes); // Set up the Suspense Context to force suspense and immediately
10599 // rerender the children.
10600
10601 pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback));
10602 return workInProgress.child;
10603 }
10604
10605 row = row.sibling;
10606 }
10607 }
10608
10609 if (renderState.tail !== null && now() > getRenderTargetTime()) {
10610 // We have already passed our CPU deadline but we still have rows
10611 // left in the tail. We'll just give up further attempts to render
10612 // the main content and only render fallbacks.
10613 workInProgress.flags |= DidCapture;
10614 didSuspendAlready = true;
10615 cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this
10616 // to get it started back up to attempt the next item. While in terms
10617 // of priority this work has the same priority as this current render,
10618 // it's not part of the same transition once the transition has
10619 // committed. If it's sync, we still want to yield so that it can be
10620 // painted. Conceptually, this is really the same as pinging.
10621 // We can use any RetryLane even if it's the one currently rendering
10622 // since we're leaving it behind on this node.
10623
10624 workInProgress.lanes = SomeRetryLane;
10625
10626 {
10627 markSpawnedWork(SomeRetryLane);
10628 }
10629 }
10630 } else {
10631 cutOffTailIfNeeded(renderState, false);
10632 } // Next we're going to render the tail.
10633
10634 } else {
10635 // Append the rendered row to the child list.
10636 if (!didSuspendAlready) {
10637 var _suspended = findFirstSuspended(renderedTail);
10638
10639 if (_suspended !== null) {
10640 workInProgress.flags |= DidCapture;
10641 didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't
10642 // get lost if this row ends up dropped during a second pass.
10643
10644 var _newThennables = _suspended.updateQueue;
10645
10646 if (_newThennables !== null) {
10647 workInProgress.updateQueue = _newThennables;
10648 workInProgress.flags |= Update;
10649 }
10650
10651 cutOffTailIfNeeded(renderState, true); // This might have been modified.
10652
10653 if (renderState.tail === null && renderState.tailMode === 'hidden' && !renderedTail.alternate && !getIsHydrating() // We don't cut it if we're hydrating.
10654 ) {
10655 // We need to delete the row we just rendered.
10656 // Reset the effect list to what it was before we rendered this
10657 // child. The nested children have already appended themselves.
10658 var lastEffect = workInProgress.lastEffect = renderState.lastEffect; // Remove any effects that were appended after this point.
10659
10660 if (lastEffect !== null) {
10661 lastEffect.nextEffect = null;
10662 } // We're done.
10663
10664
10665 return null;
10666 }
10667 } else if ( // The time it took to render last row is greater than the remaining
10668 // time we have to render. So rendering one more row would likely
10669 // exceed it.
10670 now() * 2 - renderState.renderingStartTime > getRenderTargetTime() && renderLanes !== OffscreenLane) {
10671 // We have now passed our CPU deadline and we'll just give up further
10672 // attempts to render the main content and only render fallbacks.
10673 // The assumption is that this is usually faster.
10674 workInProgress.flags |= DidCapture;
10675 didSuspendAlready = true;
10676 cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this
10677 // to get it started back up to attempt the next item. While in terms
10678 // of priority this work has the same priority as this current render,
10679 // it's not part of the same transition once the transition has
10680 // committed. If it's sync, we still want to yield so that it can be
10681 // painted. Conceptually, this is really the same as pinging.
10682 // We can use any RetryLane even if it's the one currently rendering
10683 // since we're leaving it behind on this node.
10684
10685 workInProgress.lanes = SomeRetryLane;
10686
10687 {
10688 markSpawnedWork(SomeRetryLane);
10689 }
10690 }
10691 }
10692
10693 if (renderState.isBackwards) {
10694 // The effect list of the backwards tail will have been added
10695 // to the end. This breaks the guarantee that life-cycles fire in
10696 // sibling order but that isn't a strong guarantee promised by React.
10697 // Especially since these might also just pop in during future commits.
10698 // Append to the beginning of the list.
10699 renderedTail.sibling = workInProgress.child;
10700 workInProgress.child = renderedTail;
10701 } else {
10702 var previousSibling = renderState.last;
10703
10704 if (previousSibling !== null) {
10705 previousSibling.sibling = renderedTail;
10706 } else {
10707 workInProgress.child = renderedTail;
10708 }
10709
10710 renderState.last = renderedTail;
10711 }
10712 }
10713
10714 if (renderState.tail !== null) {
10715 // We still have tail rows to render.
10716 // Pop a row.
10717 var next = renderState.tail;
10718 renderState.rendering = next;
10719 renderState.tail = next.sibling;
10720 renderState.lastEffect = workInProgress.lastEffect;
10721 renderState.renderingStartTime = now();
10722 next.sibling = null; // Restore the context.
10723 // TODO: We can probably just avoid popping it instead and only
10724 // setting it the first time we go from not suspended to suspended.
10725
10726 var suspenseContext = suspenseStackCursor.current;
10727
10728 if (didSuspendAlready) {
10729 suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
10730 } else {
10731 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
10732 }
10733
10734 pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row.
10735
10736 return next;
10737 }
10738
10739 return null;
10740 }
10741
10742 case FundamentalComponent:
10743 {
10744
10745 break;
10746 }
10747
10748 case ScopeComponent:
10749 {
10750
10751 break;
10752 }
10753
10754 case Block:
10755
10756 break;
10757
10758 case OffscreenComponent:
10759 case LegacyHiddenComponent:
10760 {
10761 popRenderLanes(workInProgress);
10762
10763 if (current !== null) {
10764 var _nextState = workInProgress.memoizedState;
10765 var _prevState = current.memoizedState;
10766 var prevIsHidden = _prevState !== null;
10767 var nextIsHidden = _nextState !== null;
10768
10769 if (prevIsHidden !== nextIsHidden && newProps.mode !== 'unstable-defer-without-hiding') {
10770 workInProgress.flags |= Update;
10771 }
10772 }
10773
10774 return null;
10775 }
10776 }
10777
10778 {
10779 {
10780 throw Error( "Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in React. Please file an issue." );
10781 }
10782 }
10783 }
10784
10785 function unwindWork(workInProgress, renderLanes) {
10786 switch (workInProgress.tag) {
10787 case ClassComponent:
10788 {
10789 var Component = workInProgress.type;
10790
10791 if (isContextProvider(Component)) {
10792 popContext(workInProgress);
10793 }
10794
10795 var flags = workInProgress.flags;
10796
10797 if (flags & ShouldCapture) {
10798 workInProgress.flags = flags & ~ShouldCapture | DidCapture;
10799
10800 if ( (workInProgress.mode & ProfileMode) !== NoMode) {
10801 transferActualDuration(workInProgress);
10802 }
10803
10804 return workInProgress;
10805 }
10806
10807 return null;
10808 }
10809
10810 case HostRoot:
10811 {
10812 popHostContainer(workInProgress);
10813 popTopLevelContextObject(workInProgress);
10814 resetWorkInProgressVersions();
10815 var _flags = workInProgress.flags;
10816
10817 if (!((_flags & DidCapture) === NoFlags)) {
10818 {
10819 throw Error( "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." );
10820 }
10821 }
10822
10823 workInProgress.flags = _flags & ~ShouldCapture | DidCapture;
10824 return workInProgress;
10825 }
10826
10827 case HostComponent:
10828 {
10829 // TODO: popHydrationState
10830 popHostContext(workInProgress);
10831 return null;
10832 }
10833
10834 case SuspenseComponent:
10835 {
10836 popSuspenseContext(workInProgress);
10837
10838 var _flags2 = workInProgress.flags;
10839
10840 if (_flags2 & ShouldCapture) {
10841 workInProgress.flags = _flags2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary.
10842
10843 if ( (workInProgress.mode & ProfileMode) !== NoMode) {
10844 transferActualDuration(workInProgress);
10845 }
10846
10847 return workInProgress;
10848 }
10849
10850 return null;
10851 }
10852
10853 case SuspenseListComponent:
10854 {
10855 popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been
10856 // caught by a nested boundary. If not, it should bubble through.
10857
10858 return null;
10859 }
10860
10861 case HostPortal:
10862 popHostContainer(workInProgress);
10863 return null;
10864
10865 case ContextProvider:
10866 popProvider(workInProgress);
10867 return null;
10868
10869 case OffscreenComponent:
10870 case LegacyHiddenComponent:
10871 popRenderLanes(workInProgress);
10872 return null;
10873
10874 default:
10875 return null;
10876 }
10877 }
10878
10879 function unwindInterruptedWork(interruptedWork) {
10880 switch (interruptedWork.tag) {
10881 case ClassComponent:
10882 {
10883 var childContextTypes = interruptedWork.type.childContextTypes;
10884
10885 if (childContextTypes !== null && childContextTypes !== undefined) {
10886 popContext(interruptedWork);
10887 }
10888
10889 break;
10890 }
10891
10892 case HostRoot:
10893 {
10894 popHostContainer(interruptedWork);
10895 popTopLevelContextObject(interruptedWork);
10896 resetWorkInProgressVersions();
10897 break;
10898 }
10899
10900 case HostComponent:
10901 {
10902 popHostContext(interruptedWork);
10903 break;
10904 }
10905
10906 case HostPortal:
10907 popHostContainer(interruptedWork);
10908 break;
10909
10910 case SuspenseComponent:
10911 popSuspenseContext(interruptedWork);
10912 break;
10913
10914 case SuspenseListComponent:
10915 popSuspenseContext(interruptedWork);
10916 break;
10917
10918 case ContextProvider:
10919 popProvider(interruptedWork);
10920 break;
10921
10922 case OffscreenComponent:
10923 case LegacyHiddenComponent:
10924 popRenderLanes(interruptedWork);
10925 break;
10926 }
10927 }
10928
10929 function createCapturedValue(value, source) {
10930 // If the value is an error, call this function immediately after it is thrown
10931 // so the stack is accurate.
10932 return {
10933 value: value,
10934 source: source,
10935 stack: getStackByFiberInDevAndProd(source)
10936 };
10937 }
10938
10939 // This module is forked in different environments.
10940 // By default, return `true` to log errors to the console.
10941 // Forks can return `false` if this isn't desirable.
10942 function showErrorDialog(boundary, errorInfo) {
10943 return true;
10944 }
10945
10946 function logCapturedError(boundary, errorInfo) {
10947 try {
10948 var logError = showErrorDialog(boundary, errorInfo); // Allow injected showErrorDialog() to prevent default console.error logging.
10949 // This enables renderers like ReactNative to better manage redbox behavior.
10950
10951 if (logError === false) {
10952 return;
10953 }
10954
10955 var error = errorInfo.value;
10956
10957 if (true) {
10958 var source = errorInfo.source;
10959 var stack = errorInfo.stack;
10960 var componentStack = stack !== null ? stack : ''; // Browsers support silencing uncaught errors by calling
10961 // `preventDefault()` in window `error` handler.
10962 // We record this information as an expando on the error.
10963
10964 if (error != null && error._suppressLogging) {
10965 if (boundary.tag === ClassComponent) {
10966 // The error is recoverable and was silenced.
10967 // Ignore it and don't print the stack addendum.
10968 // This is handy for testing error boundaries without noise.
10969 return;
10970 } // The error is fatal. Since the silencing might have
10971 // been accidental, we'll surface it anyway.
10972 // However, the browser would have silenced the original error
10973 // so we'll print it first, and then print the stack addendum.
10974
10975
10976 console['error'](error); // Don't transform to our wrapper
10977 // For a more detailed description of this block, see:
10978 // https://github.com/facebook/react/pull/13384
10979 }
10980
10981 var componentName = source ? getComponentName(source.type) : null;
10982 var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : 'The above error occurred in one of your React components:';
10983 var errorBoundaryMessage;
10984 var errorBoundaryName = getComponentName(boundary.type);
10985
10986 if (errorBoundaryName) {
10987 errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + ".");
10988 } else {
10989 errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\n' + 'Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.';
10990 }
10991
10992 var combinedMessage = componentNameMessage + "\n" + componentStack + "\n\n" + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack.
10993 // We don't include the original error message and JS stack because the browser
10994 // has already printed it. Even if the application swallows the error, it is still
10995 // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
10996
10997 console['error'](combinedMessage); // Don't transform to our wrapper
10998 } else {
10999 // In production, we print the error directly.
11000 // This will include the message, the JS stack, and anything the browser wants to show.
11001 // We pass the error object instead of custom message so that the browser displays the error natively.
11002 console['error'](error); // Don't transform to our wrapper
11003 }
11004 } catch (e) {
11005 // This method must not throw, or React internal state will get messed up.
11006 // If console.error is overridden, or logCapturedError() shows a dialog that throws,
11007 // we want to report this error outside of the normal stack as a last resort.
11008 // https://github.com/facebook/react/issues/13188
11009 setTimeout(function () {
11010 throw e;
11011 });
11012 }
11013 }
11014
11015 var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map;
11016
11017 function createRootErrorUpdate(fiber, errorInfo, lane) {
11018 var update = createUpdate(NoTimestamp, lane); // Unmount the root by rendering null.
11019
11020 update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property
11021 // being called "element".
11022
11023 update.payload = {
11024 element: null
11025 };
11026 var error = errorInfo.value;
11027
11028 update.callback = function () {
11029 onUncaughtError(error);
11030 logCapturedError(fiber, errorInfo);
11031 };
11032
11033 return update;
11034 }
11035
11036 function createClassErrorUpdate(fiber, errorInfo, lane) {
11037 var update = createUpdate(NoTimestamp, lane);
11038 update.tag = CaptureUpdate;
11039 var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
11040
11041 if (typeof getDerivedStateFromError === 'function') {
11042 var error$1 = errorInfo.value;
11043
11044 update.payload = function () {
11045 logCapturedError(fiber, errorInfo);
11046 return getDerivedStateFromError(error$1);
11047 };
11048 }
11049
11050 var inst = fiber.stateNode;
11051
11052 if (inst !== null && typeof inst.componentDidCatch === 'function') {
11053 update.callback = function callback() {
11054 {
11055 markFailedErrorBoundaryForHotReloading(fiber);
11056 }
11057
11058 if (typeof getDerivedStateFromError !== 'function') {
11059 // To preserve the preexisting retry behavior of error boundaries,
11060 // we keep track of which ones already failed during this batch.
11061 // This gets reset before we yield back to the browser.
11062 // TODO: Warn in strict mode if getDerivedStateFromError is
11063 // not defined.
11064 markLegacyErrorBoundaryAsFailed(this); // Only log here if componentDidCatch is the only error boundary method defined
11065
11066 logCapturedError(fiber, errorInfo);
11067 }
11068
11069 var error$1 = errorInfo.value;
11070 var stack = errorInfo.stack;
11071 this.componentDidCatch(error$1, {
11072 componentStack: stack !== null ? stack : ''
11073 });
11074
11075 {
11076 if (typeof getDerivedStateFromError !== 'function') {
11077 // If componentDidCatch is the only error boundary method defined,
11078 // then it needs to call setState to recover from errors.
11079 // If no state update is scheduled then the boundary will swallow the error.
11080 if (!includesSomeLane(fiber.lanes, SyncLane)) {
11081 error('%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');
11082 }
11083 }
11084 }
11085 };
11086 } else {
11087 update.callback = function () {
11088 markFailedErrorBoundaryForHotReloading(fiber);
11089 };
11090 }
11091
11092 return update;
11093 }
11094
11095 function attachPingListener(root, wakeable, lanes) {
11096 // Attach a listener to the promise to "ping" the root and retry. But only if
11097 // one does not already exist for the lanes we're currently rendering (which
11098 // acts like a "thread ID" here).
11099 var pingCache = root.pingCache;
11100 var threadIDs;
11101
11102 if (pingCache === null) {
11103 pingCache = root.pingCache = new PossiblyWeakMap$1();
11104 threadIDs = new Set();
11105 pingCache.set(wakeable, threadIDs);
11106 } else {
11107 threadIDs = pingCache.get(wakeable);
11108
11109 if (threadIDs === undefined) {
11110 threadIDs = new Set();
11111 pingCache.set(wakeable, threadIDs);
11112 }
11113 }
11114
11115 if (!threadIDs.has(lanes)) {
11116 // Memoize using the thread ID to prevent redundant listeners.
11117 threadIDs.add(lanes);
11118 var ping = pingSuspendedRoot.bind(null, root, wakeable, lanes);
11119 wakeable.then(ping, ping);
11120 }
11121 }
11122
11123 function throwException(root, returnFiber, sourceFiber, value, rootRenderLanes) {
11124 // The source fiber did not complete.
11125 sourceFiber.flags |= Incomplete; // Its effect list is no longer valid.
11126
11127 sourceFiber.firstEffect = sourceFiber.lastEffect = null;
11128
11129 if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
11130 // This is a wakeable.
11131 var wakeable = value;
11132
11133 if ((sourceFiber.mode & BlockingMode) === NoMode) {
11134 // Reset the memoizedState to what it was before we attempted
11135 // to render it.
11136 var currentSource = sourceFiber.alternate;
11137
11138 if (currentSource) {
11139 sourceFiber.updateQueue = currentSource.updateQueue;
11140 sourceFiber.memoizedState = currentSource.memoizedState;
11141 sourceFiber.lanes = currentSource.lanes;
11142 } else {
11143 sourceFiber.updateQueue = null;
11144 sourceFiber.memoizedState = null;
11145 }
11146 }
11147
11148 var hasInvisibleParentBoundary = hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext); // Schedule the nearest Suspense to re-render the timed out view.
11149
11150 var _workInProgress = returnFiber;
11151
11152 do {
11153 if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress, hasInvisibleParentBoundary)) {
11154 // Found the nearest boundary.
11155 // Stash the promise on the boundary fiber. If the boundary times out, we'll
11156 // attach another listener to flip the boundary back to its normal state.
11157 var wakeables = _workInProgress.updateQueue;
11158
11159 if (wakeables === null) {
11160 var updateQueue = new Set();
11161 updateQueue.add(wakeable);
11162 _workInProgress.updateQueue = updateQueue;
11163 } else {
11164 wakeables.add(wakeable);
11165 } // If the boundary is outside of blocking mode, we should *not*
11166 // suspend the commit. Pretend as if the suspended component rendered
11167 // null and keep rendering. In the commit phase, we'll schedule a
11168 // subsequent synchronous update to re-render the Suspense.
11169 //
11170 // Note: It doesn't matter whether the component that suspended was
11171 // inside a blocking mode tree. If the Suspense is outside of it, we
11172 // should *not* suspend the commit.
11173
11174
11175 if ((_workInProgress.mode & BlockingMode) === NoMode) {
11176 _workInProgress.flags |= DidCapture;
11177 sourceFiber.flags |= ForceUpdateForLegacySuspense; // We're going to commit this fiber even though it didn't complete.
11178 // But we shouldn't call any lifecycle methods or callbacks. Remove
11179 // all lifecycle effect tags.
11180
11181 sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete);
11182
11183 if (sourceFiber.tag === ClassComponent) {
11184 var currentSourceFiber = sourceFiber.alternate;
11185
11186 if (currentSourceFiber === null) {
11187 // This is a new mount. Change the tag so it's not mistaken for a
11188 // completed class component. For example, we should not call
11189 // componentWillUnmount if it is deleted.
11190 sourceFiber.tag = IncompleteClassComponent;
11191 } else {
11192 // When we try rendering again, we should not reuse the current fiber,
11193 // since it's known to be in an inconsistent state. Use a force update to
11194 // prevent a bail out.
11195 var update = createUpdate(NoTimestamp, SyncLane);
11196 update.tag = ForceUpdate;
11197 enqueueUpdate(sourceFiber, update);
11198 }
11199 } // The source fiber did not complete. Mark it with Sync priority to
11200 // indicate that it still has pending work.
11201
11202
11203 sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane); // Exit without suspending.
11204
11205 return;
11206 } // Confirmed that the boundary is in a concurrent mode tree. Continue
11207 // with the normal suspend path.
11208 //
11209 // After this we'll use a set of heuristics to determine whether this
11210 // render pass will run to completion or restart or "suspend" the commit.
11211 // The actual logic for this is spread out in different places.
11212 //
11213 // This first principle is that if we're going to suspend when we complete
11214 // a root, then we should also restart if we get an update or ping that
11215 // might unsuspend it, and vice versa. The only reason to suspend is
11216 // because you think you might want to restart before committing. However,
11217 // it doesn't make sense to restart only while in the period we're suspended.
11218 //
11219 // Restarting too aggressively is also not good because it starves out any
11220 // intermediate loading state. So we use heuristics to determine when.
11221 // Suspense Heuristics
11222 //
11223 // If nothing threw a Promise or all the same fallbacks are already showing,
11224 // then don't suspend/restart.
11225 //
11226 // If this is an initial render of a new tree of Suspense boundaries and
11227 // those trigger a fallback, then don't suspend/restart. We want to ensure
11228 // that we can show the initial loading state as quickly as possible.
11229 //
11230 // If we hit a "Delayed" case, such as when we'd switch from content back into
11231 // a fallback, then we should always suspend/restart. Transitions apply
11232 // to this case. If none is defined, JND is used instead.
11233 //
11234 // If we're already showing a fallback and it gets "retried", allowing us to show
11235 // another level, but there's still an inner boundary that would show a fallback,
11236 // then we suspend/restart for 500ms since the last time we showed a fallback
11237 // anywhere in the tree. This effectively throttles progressive loading into a
11238 // consistent train of commits. This also gives us an opportunity to restart to
11239 // get to the completed state slightly earlier.
11240 //
11241 // If there's ambiguity due to batching it's resolved in preference of:
11242 // 1) "delayed", 2) "initial render", 3) "retry".
11243 //
11244 // We want to ensure that a "busy" state doesn't get force committed. We want to
11245 // ensure that new initial loading states can commit as soon as possible.
11246
11247
11248 attachPingListener(root, wakeable, rootRenderLanes);
11249 _workInProgress.flags |= ShouldCapture;
11250 _workInProgress.lanes = rootRenderLanes;
11251 return;
11252 } // This boundary already captured during this render. Continue to the next
11253 // boundary.
11254
11255
11256 _workInProgress = _workInProgress.return;
11257 } while (_workInProgress !== null); // No boundary was found. Fallthrough to error mode.
11258 // TODO: Use invariant so the message is stripped in prod?
11259
11260
11261 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.');
11262 } // We didn't find a boundary that could handle this type of exception. Start
11263 // over and traverse parent path again, this time treating the exception
11264 // as an error.
11265
11266
11267 renderDidError();
11268 value = createCapturedValue(value, sourceFiber);
11269 var workInProgress = returnFiber;
11270
11271 do {
11272 switch (workInProgress.tag) {
11273 case HostRoot:
11274 {
11275 var _errorInfo = value;
11276 workInProgress.flags |= ShouldCapture;
11277 var lane = pickArbitraryLane(rootRenderLanes);
11278 workInProgress.lanes = mergeLanes(workInProgress.lanes, lane);
11279
11280 var _update = createRootErrorUpdate(workInProgress, _errorInfo, lane);
11281
11282 enqueueCapturedUpdate(workInProgress, _update);
11283 return;
11284 }
11285
11286 case ClassComponent:
11287 // Capture and retry
11288 var errorInfo = value;
11289 var ctor = workInProgress.type;
11290 var instance = workInProgress.stateNode;
11291
11292 if ((workInProgress.flags & DidCapture) === NoFlags && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
11293 workInProgress.flags |= ShouldCapture;
11294
11295 var _lane = pickArbitraryLane(rootRenderLanes);
11296
11297 workInProgress.lanes = mergeLanes(workInProgress.lanes, _lane); // Schedule the error boundary to re-render using updated state
11298
11299 var _update2 = createClassErrorUpdate(workInProgress, errorInfo, _lane);
11300
11301 enqueueCapturedUpdate(workInProgress, _update2);
11302 return;
11303 }
11304
11305 break;
11306 }
11307
11308 workInProgress = workInProgress.return;
11309 } while (workInProgress !== null);
11310 }
11311
11312 function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) {
11313 var funcArgs = Array.prototype.slice.call(arguments, 3);
11314
11315 try {
11316 func.apply(context, funcArgs);
11317 } catch (error) {
11318 this.onError(error);
11319 }
11320 }
11321
11322 var invokeGuardedCallbackImpl = invokeGuardedCallbackProd;
11323
11324 {
11325 // In DEV mode, we swap out invokeGuardedCallback for a special version
11326 // that plays more nicely with the browser's DevTools. The idea is to preserve
11327 // "Pause on exceptions" behavior. Because React wraps all user-provided
11328 // functions in invokeGuardedCallback, and the production version of
11329 // invokeGuardedCallback uses a try-catch, all user exceptions are treated
11330 // like caught exceptions, and the DevTools won't pause unless the developer
11331 // takes the extra step of enabling pause on caught exceptions. This is
11332 // unintuitive, though, because even though React has caught the error, from
11333 // the developer's perspective, the error is uncaught.
11334 //
11335 // To preserve the expected "Pause on exceptions" behavior, we don't use a
11336 // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
11337 // DOM node, and call the user-provided callback from inside an event handler
11338 // for that fake event. If the callback throws, the error is "captured" using
11339 // a global event handler. But because the error happens in a different
11340 // event loop context, it does not interrupt the normal program flow.
11341 // Effectively, this gives us try-catch behavior without actually using
11342 // try-catch. Neat!
11343 // Check that the browser supports the APIs we need to implement our special
11344 // DEV version of invokeGuardedCallback
11345 if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
11346 var fakeNode = document.createElement('react');
11347
11348 invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) {
11349 // If document doesn't exist we know for sure we will crash in this method
11350 // when we call document.createEvent(). However this can cause confusing
11351 // errors: https://github.com/facebookincubator/create-react-app/issues/3482
11352 // So we preemptively throw with a better message instead.
11353 if (!(typeof document !== 'undefined')) {
11354 {
11355 throw Error( "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." );
11356 }
11357 }
11358
11359 var evt = document.createEvent('Event');
11360 var didCall = false; // Keeps track of whether the user-provided callback threw an error. We
11361 // set this to true at the beginning, then set it to false right after
11362 // calling the function. If the function errors, `didError` will never be
11363 // set to false. This strategy works even if the browser is flaky and
11364 // fails to call our global error handler, because it doesn't rely on
11365 // the error event at all.
11366
11367 var didError = true; // Keeps track of the value of window.event so that we can reset it
11368 // during the callback to let user code access window.event in the
11369 // browsers that support it.
11370
11371 var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event
11372 // dispatching: https://github.com/facebook/react/issues/13688
11373
11374 var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event');
11375
11376 function restoreAfterDispatch() {
11377 // We immediately remove the callback from event listeners so that
11378 // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
11379 // nested call would trigger the fake event handlers of any call higher
11380 // in the stack.
11381 fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the
11382 // window.event assignment in both IE <= 10 as they throw an error
11383 // "Member not found" in strict mode, and in Firefox which does not
11384 // support window.event.
11385
11386 if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
11387 window.event = windowEvent;
11388 }
11389 } // Create an event handler for our fake event. We will synchronously
11390 // dispatch our fake event using `dispatchEvent`. Inside the handler, we
11391 // call the user-provided callback.
11392
11393
11394 var funcArgs = Array.prototype.slice.call(arguments, 3);
11395
11396 function callCallback() {
11397 didCall = true;
11398 restoreAfterDispatch();
11399 func.apply(context, funcArgs);
11400 didError = false;
11401 } // Create a global error event handler. We use this to capture the value
11402 // that was thrown. It's possible that this error handler will fire more
11403 // than once; for example, if non-React code also calls `dispatchEvent`
11404 // and a handler for that event throws. We should be resilient to most of
11405 // those cases. Even if our error event handler fires more than once, the
11406 // last error event is always used. If the callback actually does error,
11407 // we know that the last error event is the correct one, because it's not
11408 // possible for anything else to have happened in between our callback
11409 // erroring and the code that follows the `dispatchEvent` call below. If
11410 // the callback doesn't error, but the error event was fired, we know to
11411 // ignore it because `didError` will be false, as described above.
11412
11413
11414 var error; // Use this to track whether the error event is ever called.
11415
11416 var didSetError = false;
11417 var isCrossOriginError = false;
11418
11419 function handleWindowError(event) {
11420 error = event.error;
11421 didSetError = true;
11422
11423 if (error === null && event.colno === 0 && event.lineno === 0) {
11424 isCrossOriginError = true;
11425 }
11426
11427 if (event.defaultPrevented) {
11428 // Some other error handler has prevented default.
11429 // Browsers silence the error report if this happens.
11430 // We'll remember this to later decide whether to log it or not.
11431 if (error != null && typeof error === 'object') {
11432 try {
11433 error._suppressLogging = true;
11434 } catch (inner) {// Ignore.
11435 }
11436 }
11437 }
11438 } // Create a fake event type.
11439
11440
11441 var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers
11442
11443 window.addEventListener('error', handleWindowError);
11444 fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function
11445 // errors, it will trigger our global error handler.
11446
11447 evt.initEvent(evtType, false, false);
11448 fakeNode.dispatchEvent(evt);
11449
11450 if (windowEventDescriptor) {
11451 Object.defineProperty(window, 'event', windowEventDescriptor);
11452 }
11453
11454 if (didCall && didError) {
11455 if (!didSetError) {
11456 // The callback errored, but the error event never fired.
11457 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.');
11458 } else if (isCrossOriginError) {
11459 error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://reactjs.org/link/crossorigin-error for more information.');
11460 }
11461
11462 this.onError(error);
11463 } // Remove our event listeners
11464
11465
11466 window.removeEventListener('error', handleWindowError);
11467
11468 if (!didCall) {
11469 // Something went really wrong, and our event was not dispatched.
11470 // https://github.com/facebook/react/issues/16734
11471 // https://github.com/facebook/react/issues/16585
11472 // Fall back to the production implementation.
11473 restoreAfterDispatch();
11474 return invokeGuardedCallbackProd.apply(this, arguments);
11475 }
11476 };
11477 }
11478 }
11479
11480 var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
11481
11482 var hasError = false;
11483 var caughtError = null; // Used by event system to capture/rethrow the first error.
11484 var reporter = {
11485 onError: function (error) {
11486 hasError = true;
11487 caughtError = error;
11488 }
11489 };
11490 /**
11491 * Call a function while guarding against errors that happens within it.
11492 * Returns an error if it throws, otherwise null.
11493 *
11494 * In production, this is implemented using a try-catch. The reason we don't
11495 * use a try-catch directly is so that we can swap out a different
11496 * implementation in DEV mode.
11497 *
11498 * @param {String} name of the guard to use for logging or debugging
11499 * @param {Function} func The function to invoke
11500 * @param {*} context The context to use when calling the function
11501 * @param {...*} args Arguments for function
11502 */
11503
11504 function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
11505 hasError = false;
11506 caughtError = null;
11507 invokeGuardedCallbackImpl$1.apply(reporter, arguments);
11508 }
11509 function hasCaughtError() {
11510 return hasError;
11511 }
11512 function clearCaughtError() {
11513 if (hasError) {
11514 var error = caughtError;
11515 hasError = false;
11516 caughtError = null;
11517 return error;
11518 } else {
11519 {
11520 {
11521 throw Error( "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." );
11522 }
11523 }
11524 }
11525 }
11526
11527 var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
11528
11529 {
11530 didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
11531 }
11532
11533 var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
11534
11535 var callComponentWillUnmountWithTimer = function (current, instance) {
11536 instance.props = current.memoizedProps;
11537 instance.state = current.memoizedState;
11538
11539 {
11540 instance.componentWillUnmount();
11541 }
11542 }; // Capture errors so they don't interrupt unmounting.
11543
11544
11545 function safelyCallComponentWillUnmount(current, instance) {
11546 {
11547 invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current, instance);
11548
11549 if (hasCaughtError()) {
11550 var unmountError = clearCaughtError();
11551 captureCommitPhaseError(current, unmountError);
11552 }
11553 }
11554 }
11555
11556 function safelyDetachRef(current) {
11557 var ref = current.ref;
11558
11559 if (ref !== null) {
11560 if (typeof ref === 'function') {
11561 {
11562 invokeGuardedCallback(null, ref, null, null);
11563
11564 if (hasCaughtError()) {
11565 var refError = clearCaughtError();
11566 captureCommitPhaseError(current, refError);
11567 }
11568 }
11569 } else {
11570 ref.current = null;
11571 }
11572 }
11573 }
11574
11575 function safelyCallDestroy(current, destroy) {
11576 {
11577 invokeGuardedCallback(null, destroy, null);
11578
11579 if (hasCaughtError()) {
11580 var error = clearCaughtError();
11581 captureCommitPhaseError(current, error);
11582 }
11583 }
11584 }
11585
11586 function commitBeforeMutationLifeCycles(current, finishedWork) {
11587 switch (finishedWork.tag) {
11588 case FunctionComponent:
11589 case ForwardRef:
11590 case SimpleMemoComponent:
11591 case Block:
11592 {
11593 return;
11594 }
11595
11596 case ClassComponent:
11597 {
11598 if (finishedWork.flags & Snapshot) {
11599 if (current !== null) {
11600 var prevProps = current.memoizedProps;
11601 var prevState = current.memoizedState;
11602 var instance = finishedWork.stateNode; // We could update instance props and state here,
11603 // but instead we rely on them being set during last render.
11604 // TODO: revisit this when we implement resuming.
11605
11606 {
11607 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
11608 if (instance.props !== finishedWork.memoizedProps) {
11609 error('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');
11610 }
11611
11612 if (instance.state !== finishedWork.memoizedState) {
11613 error('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.state`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
11614 }
11615 }
11616 }
11617
11618 var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
11619
11620 {
11621 var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
11622
11623 if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
11624 didWarnSet.add(finishedWork.type);
11625
11626 error('%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));
11627 }
11628 }
11629
11630 instance.__reactInternalSnapshotBeforeUpdate = snapshot;
11631 }
11632 }
11633
11634 return;
11635 }
11636
11637 case HostRoot:
11638 {
11639 {
11640 if (finishedWork.flags & Snapshot) {
11641 var root = finishedWork.stateNode;
11642 clearContainer(root.containerInfo);
11643 }
11644 }
11645
11646 return;
11647 }
11648
11649 case HostComponent:
11650 case HostText:
11651 case HostPortal:
11652 case IncompleteClassComponent:
11653 // Nothing to do for these component types
11654 return;
11655 }
11656
11657 {
11658 {
11659 throw Error( "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." );
11660 }
11661 }
11662 }
11663
11664 function commitHookEffectListUnmount(tag, finishedWork) {
11665 var updateQueue = finishedWork.updateQueue;
11666 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
11667
11668 if (lastEffect !== null) {
11669 var firstEffect = lastEffect.next;
11670 var effect = firstEffect;
11671
11672 do {
11673 if ((effect.tag & tag) === tag) {
11674 // Unmount
11675 var destroy = effect.destroy;
11676 effect.destroy = undefined;
11677
11678 if (destroy !== undefined) {
11679 destroy();
11680 }
11681 }
11682
11683 effect = effect.next;
11684 } while (effect !== firstEffect);
11685 }
11686 }
11687
11688 function commitHookEffectListMount(tag, finishedWork) {
11689 var updateQueue = finishedWork.updateQueue;
11690 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
11691
11692 if (lastEffect !== null) {
11693 var firstEffect = lastEffect.next;
11694 var effect = firstEffect;
11695
11696 do {
11697 if ((effect.tag & tag) === tag) {
11698 // Mount
11699 var create = effect.create;
11700 effect.destroy = create();
11701
11702 {
11703 var destroy = effect.destroy;
11704
11705 if (destroy !== undefined && typeof destroy !== 'function') {
11706 var addendum = void 0;
11707
11708 if (destroy === null) {
11709 addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
11710 } else if (typeof destroy.then === 'function') {
11711 addendum = '\n\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + 'useEffect(() => {\n' + ' async function fetchData() {\n' + ' // You can await here\n' + ' const response = await MyAPI.getData(someId);\n' + ' // ...\n' + ' }\n' + ' fetchData();\n' + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + 'Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching';
11712 } else {
11713 addendum = ' You returned: ' + destroy;
11714 }
11715
11716 error('An effect function must not return anything besides a function, ' + 'which is used for clean-up.%s', addendum);
11717 }
11718 }
11719 }
11720
11721 effect = effect.next;
11722 } while (effect !== firstEffect);
11723 }
11724 }
11725
11726 function schedulePassiveEffects(finishedWork) {
11727 var updateQueue = finishedWork.updateQueue;
11728 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
11729
11730 if (lastEffect !== null) {
11731 var firstEffect = lastEffect.next;
11732 var effect = firstEffect;
11733
11734 do {
11735 var _effect = effect,
11736 next = _effect.next,
11737 tag = _effect.tag;
11738
11739 if ((tag & Passive$1) !== NoFlags$1 && (tag & HasEffect) !== NoFlags$1) {
11740 enqueuePendingPassiveHookEffectUnmount(finishedWork, effect);
11741 enqueuePendingPassiveHookEffectMount(finishedWork, effect);
11742 }
11743
11744 effect = next;
11745 } while (effect !== firstEffect);
11746 }
11747 }
11748
11749 function commitLifeCycles(finishedRoot, current, finishedWork, committedLanes) {
11750 switch (finishedWork.tag) {
11751 case FunctionComponent:
11752 case ForwardRef:
11753 case SimpleMemoComponent:
11754 case Block:
11755 {
11756 // At this point layout effects have already been destroyed (during mutation phase).
11757 // This is done to prevent sibling component effects from interfering with each other,
11758 // e.g. a destroy function in one component should never override a ref set
11759 // by a create function in another component during the same commit.
11760 {
11761 commitHookEffectListMount(Layout | HasEffect, finishedWork);
11762 }
11763
11764 schedulePassiveEffects(finishedWork);
11765 return;
11766 }
11767
11768 case ClassComponent:
11769 {
11770 var instance = finishedWork.stateNode;
11771
11772 if (finishedWork.flags & Update) {
11773 if (current === null) {
11774 // We could update instance props and state here,
11775 // but instead we rely on them being set during last render.
11776 // TODO: revisit this when we implement resuming.
11777 {
11778 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
11779 if (instance.props !== finishedWork.memoizedProps) {
11780 error('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');
11781 }
11782
11783 if (instance.state !== finishedWork.memoizedState) {
11784 error('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.state`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
11785 }
11786 }
11787 }
11788
11789 {
11790 instance.componentDidMount();
11791 }
11792 } else {
11793 var prevProps = finishedWork.elementType === finishedWork.type ? current.memoizedProps : resolveDefaultProps(finishedWork.type, current.memoizedProps);
11794 var prevState = current.memoizedState; // We could update instance props and state here,
11795 // but instead we rely on them being set during last render.
11796 // TODO: revisit this when we implement resuming.
11797
11798 {
11799 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
11800 if (instance.props !== finishedWork.memoizedProps) {
11801 error('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');
11802 }
11803
11804 if (instance.state !== finishedWork.memoizedState) {
11805 error('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.state`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
11806 }
11807 }
11808 }
11809
11810 {
11811 instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
11812 }
11813 }
11814 } // TODO: I think this is now always non-null by the time it reaches the
11815 // commit phase. Consider removing the type check.
11816
11817
11818 var updateQueue = finishedWork.updateQueue;
11819
11820 if (updateQueue !== null) {
11821 {
11822 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
11823 if (instance.props !== finishedWork.memoizedProps) {
11824 error('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');
11825 }
11826
11827 if (instance.state !== finishedWork.memoizedState) {
11828 error('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.state`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
11829 }
11830 }
11831 } // We could update instance props and state here,
11832 // but instead we rely on them being set during last render.
11833 // TODO: revisit this when we implement resuming.
11834
11835
11836 commitUpdateQueue(finishedWork, updateQueue, instance);
11837 }
11838
11839 return;
11840 }
11841
11842 case HostRoot:
11843 {
11844 // TODO: I think this is now always non-null by the time it reaches the
11845 // commit phase. Consider removing the type check.
11846 var _updateQueue = finishedWork.updateQueue;
11847
11848 if (_updateQueue !== null) {
11849 var _instance = null;
11850
11851 if (finishedWork.child !== null) {
11852 switch (finishedWork.child.tag) {
11853 case HostComponent:
11854 _instance = getPublicInstance(finishedWork.child.stateNode);
11855 break;
11856
11857 case ClassComponent:
11858 _instance = finishedWork.child.stateNode;
11859 break;
11860 }
11861 }
11862
11863 commitUpdateQueue(finishedWork, _updateQueue, _instance);
11864 }
11865
11866 return;
11867 }
11868
11869 case HostComponent:
11870 {
11871 var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted
11872 // (eg DOM renderer may schedule auto-focus for inputs and form controls).
11873 // These effects should only be committed when components are first mounted,
11874 // aka when there is no current/alternate.
11875
11876 if (current === null && finishedWork.flags & Update) {
11877 var type = finishedWork.type;
11878 var props = finishedWork.memoizedProps;
11879 }
11880
11881 return;
11882 }
11883
11884 case HostText:
11885 {
11886 // We have no life-cycles associated with text.
11887 return;
11888 }
11889
11890 case HostPortal:
11891 {
11892 // We have no life-cycles associated with portals.
11893 return;
11894 }
11895
11896 case Profiler:
11897 {
11898 {
11899 var _finishedWork$memoize2 = finishedWork.memoizedProps,
11900 onCommit = _finishedWork$memoize2.onCommit,
11901 onRender = _finishedWork$memoize2.onRender;
11902 var effectDuration = finishedWork.stateNode.effectDuration;
11903 var commitTime = getCommitTime();
11904
11905 if (typeof onRender === 'function') {
11906 {
11907 onRender(finishedWork.memoizedProps.id, current === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitTime, finishedRoot.memoizedInteractions);
11908 }
11909 }
11910 }
11911
11912 return;
11913 }
11914
11915 case SuspenseComponent:
11916 {
11917 return;
11918 }
11919
11920 case SuspenseListComponent:
11921 case IncompleteClassComponent:
11922 case FundamentalComponent:
11923 case ScopeComponent:
11924 case OffscreenComponent:
11925 case LegacyHiddenComponent:
11926 return;
11927 }
11928
11929 {
11930 {
11931 throw Error( "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." );
11932 }
11933 }
11934 }
11935
11936 function hideOrUnhideAllChildren(finishedWork, isHidden) {
11937 {
11938 // We only have the top Fiber that was inserted but we need to recurse down its
11939 // children to find all the terminal nodes.
11940 var node = finishedWork;
11941
11942 while (true) {
11943 if (node.tag === HostComponent) {
11944 var instance = node.stateNode;
11945
11946 if (isHidden) {
11947 hideInstance(instance);
11948 } else {
11949 unhideInstance(node.stateNode, node.memoizedProps);
11950 }
11951 } else if (node.tag === HostText) {
11952 var _instance3 = node.stateNode;
11953
11954 if (isHidden) {
11955 hideTextInstance(_instance3);
11956 } else {
11957 unhideTextInstance(_instance3, node.memoizedProps);
11958 }
11959 } else if ((node.tag === OffscreenComponent || node.tag === LegacyHiddenComponent) && node.memoizedState !== null && node !== finishedWork) ; else if (node.child !== null) {
11960 node.child.return = node;
11961 node = node.child;
11962 continue;
11963 }
11964
11965 if (node === finishedWork) {
11966 return;
11967 }
11968
11969 while (node.sibling === null) {
11970 if (node.return === null || node.return === finishedWork) {
11971 return;
11972 }
11973
11974 node = node.return;
11975 }
11976
11977 node.sibling.return = node.return;
11978 node = node.sibling;
11979 }
11980 }
11981 }
11982
11983 function commitAttachRef(finishedWork) {
11984 var ref = finishedWork.ref;
11985
11986 if (ref !== null) {
11987 var instance = finishedWork.stateNode;
11988 var instanceToUse;
11989
11990 switch (finishedWork.tag) {
11991 case HostComponent:
11992 instanceToUse = getPublicInstance(instance);
11993 break;
11994
11995 default:
11996 instanceToUse = instance;
11997 } // Moved outside to ensure DCE works with this flag
11998
11999 if (typeof ref === 'function') {
12000 ref(instanceToUse);
12001 } else {
12002 {
12003 if (!ref.hasOwnProperty('current')) {
12004 error('Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().', getComponentName(finishedWork.type));
12005 }
12006 }
12007
12008 ref.current = instanceToUse;
12009 }
12010 }
12011 }
12012
12013 function commitDetachRef(current) {
12014 var currentRef = current.ref;
12015
12016 if (currentRef !== null) {
12017 if (typeof currentRef === 'function') {
12018 currentRef(null);
12019 } else {
12020 currentRef.current = null;
12021 }
12022 }
12023 } // User-originating errors (lifecycles and refs) should not interrupt
12024 // deletion, so don't let them throw. Host-originating errors should
12025 // interrupt deletion, so it's okay
12026
12027
12028 function commitUnmount(finishedRoot, current, renderPriorityLevel) {
12029 onCommitUnmount(current);
12030
12031 switch (current.tag) {
12032 case FunctionComponent:
12033 case ForwardRef:
12034 case MemoComponent:
12035 case SimpleMemoComponent:
12036 case Block:
12037 {
12038 var updateQueue = current.updateQueue;
12039
12040 if (updateQueue !== null) {
12041 var lastEffect = updateQueue.lastEffect;
12042
12043 if (lastEffect !== null) {
12044 var firstEffect = lastEffect.next;
12045 var effect = firstEffect;
12046
12047 do {
12048 var _effect2 = effect,
12049 destroy = _effect2.destroy,
12050 tag = _effect2.tag;
12051
12052 if (destroy !== undefined) {
12053 if ((tag & Passive$1) !== NoFlags$1) {
12054 enqueuePendingPassiveHookEffectUnmount(current, effect);
12055 } else {
12056 {
12057 safelyCallDestroy(current, destroy);
12058 }
12059 }
12060 }
12061
12062 effect = effect.next;
12063 } while (effect !== firstEffect);
12064 }
12065 }
12066
12067 return;
12068 }
12069
12070 case ClassComponent:
12071 {
12072 safelyDetachRef(current);
12073 var instance = current.stateNode;
12074
12075 if (typeof instance.componentWillUnmount === 'function') {
12076 safelyCallComponentWillUnmount(current, instance);
12077 }
12078
12079 return;
12080 }
12081
12082 case HostComponent:
12083 {
12084 safelyDetachRef(current);
12085 return;
12086 }
12087
12088 case HostPortal:
12089 {
12090 // TODO: this is recursive.
12091 // We are also not using this parent because
12092 // the portal will get pushed immediately.
12093 {
12094 unmountHostComponents(finishedRoot, current);
12095 }
12096
12097 return;
12098 }
12099
12100 case FundamentalComponent:
12101 {
12102
12103 return;
12104 }
12105
12106 case DehydratedFragment:
12107 {
12108
12109 return;
12110 }
12111
12112 case ScopeComponent:
12113 {
12114
12115 return;
12116 }
12117 }
12118 }
12119
12120 function commitNestedUnmounts(finishedRoot, root, renderPriorityLevel) {
12121 // While we're inside a removed host node we don't want to call
12122 // removeChild on the inner nodes because they're removed by the top
12123 // call anyway. We also want to call componentWillUnmount on all
12124 // composites before this host node is removed from the tree. Therefore
12125 // we do an inner loop while we're still inside the host node.
12126 var node = root;
12127
12128 while (true) {
12129 commitUnmount(finishedRoot, node); // Visit children because they may contain more composite or host nodes.
12130 // Skip portals because commitUnmount() currently visits them recursively.
12131
12132 if (node.child !== null && ( // If we use mutation we drill down into portals using commitUnmount above.
12133 // If we don't use mutation we drill down into portals here instead.
12134 node.tag !== HostPortal)) {
12135 node.child.return = node;
12136 node = node.child;
12137 continue;
12138 }
12139
12140 if (node === root) {
12141 return;
12142 }
12143
12144 while (node.sibling === null) {
12145 if (node.return === null || node.return === root) {
12146 return;
12147 }
12148
12149 node = node.return;
12150 }
12151
12152 node.sibling.return = node.return;
12153 node = node.sibling;
12154 }
12155 }
12156
12157 function detachFiberMutation(fiber) {
12158 // Cut off the return pointers to disconnect it from the tree. Ideally, we
12159 // should clear the child pointer of the parent alternate to let this
12160 // get GC:ed but we don't know which for sure which parent is the current
12161 // one so we'll settle for GC:ing the subtree of this child. This child
12162 // itself will be GC:ed when the parent updates the next time.
12163 // Note: we cannot null out sibling here, otherwise it can cause issues
12164 // with findDOMNode and how it requires the sibling field to carry out
12165 // traversal in a later effect. See PR #16820. We now clear the sibling
12166 // field after effects, see: detachFiberAfterEffects.
12167 //
12168 // Don't disconnect stateNode now; it will be detached in detachFiberAfterEffects.
12169 // It may be required if the current component is an error boundary,
12170 // and one of its descendants throws while unmounting a passive effect.
12171 fiber.alternate = null;
12172 fiber.child = null;
12173 fiber.dependencies = null;
12174 fiber.firstEffect = null;
12175 fiber.lastEffect = null;
12176 fiber.memoizedProps = null;
12177 fiber.memoizedState = null;
12178 fiber.pendingProps = null;
12179 fiber.return = null;
12180 fiber.updateQueue = null;
12181
12182 {
12183 fiber._debugOwner = null;
12184 }
12185 }
12186
12187 function getHostParentFiber(fiber) {
12188 var parent = fiber.return;
12189
12190 while (parent !== null) {
12191 if (isHostParent(parent)) {
12192 return parent;
12193 }
12194
12195 parent = parent.return;
12196 }
12197
12198 {
12199 {
12200 throw Error( "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." );
12201 }
12202 }
12203 }
12204
12205 function isHostParent(fiber) {
12206 return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
12207 }
12208
12209 function getHostSibling(fiber) {
12210 // We're going to search forward into the tree until we find a sibling host
12211 // node. Unfortunately, if multiple insertions are done in a row we have to
12212 // search past them. This leads to exponential search for the next sibling.
12213 // TODO: Find a more efficient way to do this.
12214 var node = fiber;
12215
12216 siblings: while (true) {
12217 // If we didn't find anything, let's try the next sibling.
12218 while (node.sibling === null) {
12219 if (node.return === null || isHostParent(node.return)) {
12220 // If we pop out of the root or hit the parent the fiber we are the
12221 // last sibling.
12222 return null;
12223 }
12224
12225 node = node.return;
12226 }
12227
12228 node.sibling.return = node.return;
12229 node = node.sibling;
12230
12231 while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) {
12232 // If it is not host node and, we might have a host node inside it.
12233 // Try to search down until we find one.
12234 if (node.flags & Placement) {
12235 // If we don't have a child, try the siblings instead.
12236 continue siblings;
12237 } // If we don't have a child, try the siblings instead.
12238 // We also skip portals because they are not part of this host tree.
12239
12240
12241 if (node.child === null || node.tag === HostPortal) {
12242 continue siblings;
12243 } else {
12244 node.child.return = node;
12245 node = node.child;
12246 }
12247 } // Check if this host node is stable or about to be placed.
12248
12249
12250 if (!(node.flags & Placement)) {
12251 // Found it!
12252 return node.stateNode;
12253 }
12254 }
12255 }
12256
12257 function commitPlacement(finishedWork) {
12258
12259
12260 var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together.
12261
12262 var parent;
12263 var isContainer;
12264 var parentStateNode = parentFiber.stateNode;
12265
12266 switch (parentFiber.tag) {
12267 case HostComponent:
12268 parent = parentStateNode;
12269 isContainer = false;
12270 break;
12271
12272 case HostRoot:
12273 parent = parentStateNode.containerInfo;
12274 isContainer = true;
12275 break;
12276
12277 case HostPortal:
12278 parent = parentStateNode.containerInfo;
12279 isContainer = true;
12280 break;
12281
12282 case FundamentalComponent:
12283
12284 // eslint-disable-next-line-no-fallthrough
12285
12286 default:
12287 {
12288 {
12289 throw Error( "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." );
12290 }
12291 }
12292
12293 }
12294
12295 if (parentFiber.flags & ContentReset) {
12296
12297 parentFiber.flags &= ~ContentReset;
12298 }
12299
12300 var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its
12301 // children to find all the terminal nodes.
12302
12303 if (isContainer) {
12304 insertOrAppendPlacementNodeIntoContainer(finishedWork, before, parent);
12305 } else {
12306 insertOrAppendPlacementNode(finishedWork, before, parent);
12307 }
12308 }
12309
12310 function insertOrAppendPlacementNodeIntoContainer(node, before, parent) {
12311 var tag = node.tag;
12312 var isHost = tag === HostComponent || tag === HostText;
12313
12314 if (isHost || enableFundamentalAPI ) {
12315 var stateNode = isHost ? node.stateNode : node.stateNode.instance;
12316
12317 if (before) {
12318 insertInContainerBefore(parent, stateNode, before);
12319 } else {
12320 appendChildToContainer(parent, stateNode);
12321 }
12322 } else if (tag === HostPortal) ; else {
12323 var child = node.child;
12324
12325 if (child !== null) {
12326 insertOrAppendPlacementNodeIntoContainer(child, before, parent);
12327 var sibling = child.sibling;
12328
12329 while (sibling !== null) {
12330 insertOrAppendPlacementNodeIntoContainer(sibling, before, parent);
12331 sibling = sibling.sibling;
12332 }
12333 }
12334 }
12335 }
12336
12337 function insertOrAppendPlacementNode(node, before, parent) {
12338 var tag = node.tag;
12339 var isHost = tag === HostComponent || tag === HostText;
12340
12341 if (isHost || enableFundamentalAPI ) {
12342 var stateNode = isHost ? node.stateNode : node.stateNode.instance;
12343
12344 if (before) {
12345 insertBefore(parent, stateNode, before);
12346 } else {
12347 appendChild(parent, stateNode);
12348 }
12349 } else if (tag === HostPortal) ; else {
12350 var child = node.child;
12351
12352 if (child !== null) {
12353 insertOrAppendPlacementNode(child, before, parent);
12354 var sibling = child.sibling;
12355
12356 while (sibling !== null) {
12357 insertOrAppendPlacementNode(sibling, before, parent);
12358 sibling = sibling.sibling;
12359 }
12360 }
12361 }
12362 }
12363
12364 function unmountHostComponents(finishedRoot, current, renderPriorityLevel) {
12365 // We only have the top Fiber that was deleted but we need to recurse down its
12366 // children to find all the terminal nodes.
12367 var node = current; // Each iteration, currentParent is populated with node's host parent if not
12368 // currentParentIsValid.
12369
12370 var currentParentIsValid = false; // Note: these two variables *must* always be updated together.
12371
12372 var currentParent;
12373 var currentParentIsContainer;
12374
12375 while (true) {
12376 if (!currentParentIsValid) {
12377 var parent = node.return;
12378
12379 findParent: while (true) {
12380 if (!(parent !== null)) {
12381 {
12382 throw Error( "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." );
12383 }
12384 }
12385
12386 var parentStateNode = parent.stateNode;
12387
12388 switch (parent.tag) {
12389 case HostComponent:
12390 currentParent = parentStateNode;
12391 currentParentIsContainer = false;
12392 break findParent;
12393
12394 case HostRoot:
12395 currentParent = parentStateNode.containerInfo;
12396 currentParentIsContainer = true;
12397 break findParent;
12398
12399 case HostPortal:
12400 currentParent = parentStateNode.containerInfo;
12401 currentParentIsContainer = true;
12402 break findParent;
12403
12404 }
12405
12406 parent = parent.return;
12407 }
12408
12409 currentParentIsValid = true;
12410 }
12411
12412 if (node.tag === HostComponent || node.tag === HostText) {
12413 commitNestedUnmounts(finishedRoot, node); // After all the children have unmounted, it is now safe to remove the
12414 // node from the tree.
12415
12416 if (currentParentIsContainer) {
12417 removeChildFromContainer(currentParent, node.stateNode);
12418 } else {
12419 removeChild(currentParent, node.stateNode);
12420 } // Don't visit children because we already visited them.
12421
12422 } else if (node.tag === HostPortal) {
12423 if (node.child !== null) {
12424 // When we go into a portal, it becomes the parent to remove from.
12425 // We will reassign it back when we pop the portal on the way up.
12426 currentParent = node.stateNode.containerInfo;
12427 currentParentIsContainer = true; // Visit children because portals might contain host components.
12428
12429 node.child.return = node;
12430 node = node.child;
12431 continue;
12432 }
12433 } else {
12434 commitUnmount(finishedRoot, node); // Visit children because we may find more host components below.
12435
12436 if (node.child !== null) {
12437 node.child.return = node;
12438 node = node.child;
12439 continue;
12440 }
12441 }
12442
12443 if (node === current) {
12444 return;
12445 }
12446
12447 while (node.sibling === null) {
12448 if (node.return === null || node.return === current) {
12449 return;
12450 }
12451
12452 node = node.return;
12453
12454 if (node.tag === HostPortal) {
12455 // When we go out of the portal, we need to restore the parent.
12456 // Since we don't keep a stack of them, we will search for it.
12457 currentParentIsValid = false;
12458 }
12459 }
12460
12461 node.sibling.return = node.return;
12462 node = node.sibling;
12463 }
12464 }
12465
12466 function commitDeletion(finishedRoot, current, renderPriorityLevel) {
12467 {
12468 // Recursively delete all host nodes from the parent.
12469 // Detach refs and call componentWillUnmount() on the whole subtree.
12470 unmountHostComponents(finishedRoot, current);
12471 }
12472
12473 var alternate = current.alternate;
12474 detachFiberMutation(current);
12475
12476 if (alternate !== null) {
12477 detachFiberMutation(alternate);
12478 }
12479 }
12480
12481 function commitWork(current, finishedWork) {
12482
12483 switch (finishedWork.tag) {
12484 case FunctionComponent:
12485 case ForwardRef:
12486 case MemoComponent:
12487 case SimpleMemoComponent:
12488 case Block:
12489 {
12490 // Layout effects are destroyed during the mutation phase so that all
12491 // destroy functions for all fibers are called before any create functions.
12492 // This prevents sibling component effects from interfering with each other,
12493 // e.g. a destroy function in one component should never override a ref set
12494 // by a create function in another component during the same commit.
12495 {
12496 commitHookEffectListUnmount(Layout | HasEffect, finishedWork);
12497 }
12498
12499 return;
12500 }
12501
12502 case ClassComponent:
12503 {
12504 return;
12505 }
12506
12507 case HostComponent:
12508 {
12509 var instance = finishedWork.stateNode;
12510
12511 if (instance != null) {
12512 // Commit the work prepared earlier.
12513 var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
12514 // as the newProps. The updatePayload will contain the real change in
12515 // this case.
12516
12517 var oldProps = current !== null ? current.memoizedProps : newProps;
12518 var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components.
12519
12520 var updatePayload = finishedWork.updateQueue;
12521 finishedWork.updateQueue = null;
12522
12523 if (updatePayload !== null) {
12524 commitUpdate(instance, updatePayload, type, oldProps, newProps);
12525 }
12526 }
12527
12528 return;
12529 }
12530
12531 case HostText:
12532 {
12533 if (!(finishedWork.stateNode !== null)) {
12534 {
12535 throw Error( "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." );
12536 }
12537 }
12538
12539 var textInstance = finishedWork.stateNode;
12540 var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
12541 // as the newProps. The updatePayload will contain the real change in
12542 // this case.
12543
12544 var oldText = current !== null ? current.memoizedProps : newText;
12545 commitTextUpdate(textInstance, oldText, newText);
12546 return;
12547 }
12548
12549 case HostRoot:
12550 {
12551
12552 return;
12553 }
12554
12555 case Profiler:
12556 {
12557 return;
12558 }
12559
12560 case SuspenseComponent:
12561 {
12562 commitSuspenseComponent(finishedWork);
12563 attachSuspenseRetryListeners(finishedWork);
12564 return;
12565 }
12566
12567 case SuspenseListComponent:
12568 {
12569 attachSuspenseRetryListeners(finishedWork);
12570 return;
12571 }
12572
12573 case IncompleteClassComponent:
12574 {
12575 return;
12576 }
12577
12578 case FundamentalComponent:
12579 {
12580
12581 break;
12582 }
12583
12584 case ScopeComponent:
12585 {
12586
12587 break;
12588 }
12589
12590 case OffscreenComponent:
12591 case LegacyHiddenComponent:
12592 {
12593 var newState = finishedWork.memoizedState;
12594 var isHidden = newState !== null;
12595 hideOrUnhideAllChildren(finishedWork, isHidden);
12596 return;
12597 }
12598 }
12599
12600 {
12601 {
12602 throw Error( "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." );
12603 }
12604 }
12605 }
12606
12607 function commitSuspenseComponent(finishedWork) {
12608 var newState = finishedWork.memoizedState;
12609
12610 if (newState !== null) {
12611 markCommitTimeOfFallback();
12612
12613 {
12614 // Hide the Offscreen component that contains the primary children. TODO:
12615 // Ideally, this effect would have been scheduled on the Offscreen fiber
12616 // itself. That's how unhiding works: the Offscreen component schedules an
12617 // effect on itself. However, in this case, the component didn't complete,
12618 // so the fiber was never added to the effect list in the normal path. We
12619 // could have appended it to the effect list in the Suspense component's
12620 // second pass, but doing it this way is less complicated. This would be
12621 // simpler if we got rid of the effect list and traversed the tree, like
12622 // we're planning to do.
12623 var primaryChildParent = finishedWork.child;
12624 hideOrUnhideAllChildren(primaryChildParent, true);
12625 }
12626 }
12627 }
12628
12629 function attachSuspenseRetryListeners(finishedWork) {
12630 // If this boundary just timed out, then it will have a set of wakeables.
12631 // For each wakeable, attach a listener so that when it resolves, React
12632 // attempts to re-render the boundary in the primary (pre-timeout) state.
12633 var wakeables = finishedWork.updateQueue;
12634
12635 if (wakeables !== null) {
12636 finishedWork.updateQueue = null;
12637 var retryCache = finishedWork.stateNode;
12638
12639 if (retryCache === null) {
12640 retryCache = finishedWork.stateNode = new PossiblyWeakSet();
12641 }
12642
12643 wakeables.forEach(function (wakeable) {
12644 // Memoize using the boundary fiber to prevent redundant listeners.
12645 var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable);
12646
12647 if (!retryCache.has(wakeable)) {
12648 {
12649 if (wakeable.__reactDoNotTraceInteractions !== true) {
12650 retry = unstable_wrap(retry);
12651 }
12652 }
12653
12654 retryCache.add(wakeable);
12655 wakeable.then(retry, retry);
12656 }
12657 });
12658 }
12659 } // This function detects when a Suspense boundary goes from visible to hidden.
12660 // It returns false if the boundary is already hidden.
12661 // TODO: Use an effect tag.
12662
12663
12664 function isSuspenseBoundaryBeingHidden(current, finishedWork) {
12665 if (current !== null) {
12666 var oldState = current.memoizedState;
12667
12668 if (oldState === null || oldState.dehydrated !== null) {
12669 var newState = finishedWork.memoizedState;
12670 return newState !== null && newState.dehydrated === null;
12671 }
12672 }
12673
12674 return false;
12675 }
12676
12677 function commitResetTextContent(current) {
12678
12679 resetTextContent(current.stateNode);
12680 }
12681
12682 var COMPONENT_TYPE = 0;
12683 var HAS_PSEUDO_CLASS_TYPE = 1;
12684 var ROLE_TYPE = 2;
12685 var TEST_NAME_TYPE = 3;
12686 var TEXT_TYPE = 4;
12687
12688 if (typeof Symbol === 'function' && Symbol.for) {
12689 var symbolFor$1 = Symbol.for;
12690 COMPONENT_TYPE = symbolFor$1('selector.component');
12691 HAS_PSEUDO_CLASS_TYPE = symbolFor$1('selector.has_pseudo_class');
12692 ROLE_TYPE = symbolFor$1('selector.role');
12693 TEST_NAME_TYPE = symbolFor$1('selector.test_id');
12694 TEXT_TYPE = symbolFor$1('selector.text');
12695 }
12696
12697 var didWarnAboutMessageChannel = false;
12698 var enqueueTaskImpl = null;
12699 function enqueueTask(task) {
12700 if (enqueueTaskImpl === null) {
12701 try {
12702 // read require off the module object to get around the bundlers.
12703 // we don't want them to detect a require and bundle a Node polyfill.
12704 var requireString = ('require' + Math.random()).slice(0, 7);
12705 var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's
12706 // version of setImmediate, bypassing fake timers if any.
12707
12708 enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate;
12709 } catch (_err) {
12710 // we're in a browser
12711 // we can't use regular timers because they may still be faked
12712 // so we try MessageChannel+postMessage instead
12713 enqueueTaskImpl = function (callback) {
12714 {
12715 if (didWarnAboutMessageChannel === false) {
12716 didWarnAboutMessageChannel = true;
12717
12718 if (typeof MessageChannel === 'undefined') {
12719 error('This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.');
12720 }
12721 }
12722 }
12723
12724 var channel = new MessageChannel();
12725 channel.port1.onmessage = callback;
12726 channel.port2.postMessage(undefined);
12727 };
12728 }
12729 }
12730
12731 return enqueueTaskImpl(task);
12732 }
12733
12734 var ceil = Math.ceil;
12735 var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher,
12736 ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner,
12737 IsSomeRendererActing = ReactSharedInternals.IsSomeRendererActing;
12738 var NoContext =
12739 /* */
12740 0;
12741 var BatchedContext =
12742 /* */
12743 1;
12744 var DiscreteEventContext =
12745 /* */
12746 4;
12747 var LegacyUnbatchedContext =
12748 /* */
12749 8;
12750 var RenderContext =
12751 /* */
12752 16;
12753 var CommitContext =
12754 /* */
12755 32;
12756 var RetryAfterError =
12757 /* */
12758 64;
12759 var RootIncomplete = 0;
12760 var RootFatalErrored = 1;
12761 var RootErrored = 2;
12762 var RootSuspended = 3;
12763 var RootSuspendedWithDelay = 4;
12764 var RootCompleted = 5; // Describes where we are in the React execution stack
12765
12766 var executionContext = NoContext; // The root we're working on
12767
12768 var workInProgressRoot = null; // The fiber we're working on
12769
12770 var workInProgress = null; // The lanes we're rendering
12771
12772 var workInProgressRootRenderLanes = NoLanes; // Stack that allows components to change the render lanes for its subtree
12773 // This is a superset of the lanes we started working on at the root. The only
12774 // case where it's different from `workInProgressRootRenderLanes` is when we
12775 // enter a subtree that is hidden and needs to be unhidden: Suspense and
12776 // Offscreen component.
12777 //
12778 // Most things in the work loop should deal with workInProgressRootRenderLanes.
12779 // Most things in begin/complete phases should deal with subtreeRenderLanes.
12780
12781 var subtreeRenderLanes = NoLanes;
12782 var subtreeRenderLanesCursor = createCursor(NoLanes); // Whether to root completed, errored, suspended, etc.
12783
12784 var workInProgressRootExitStatus = RootIncomplete; // A fatal error, if one is thrown
12785
12786 var workInProgressRootFatalError = null; // "Included" lanes refer to lanes that were worked on during this render. It's
12787 // slightly different than `renderLanes` because `renderLanes` can change as you
12788 // enter and exit an Offscreen tree. This value is the combination of all render
12789 // lanes for the entire render phase.
12790
12791 var workInProgressRootIncludedLanes = NoLanes; // The work left over by components that were visited during this render. Only
12792 // includes unprocessed updates, not work in bailed out children.
12793
12794 var workInProgressRootSkippedLanes = NoLanes; // Lanes that were updated (in an interleaved event) during this render.
12795
12796 var workInProgressRootUpdatedLanes = NoLanes; // Lanes that were pinged (in an interleaved event) during this render.
12797
12798 var workInProgressRootPingedLanes = NoLanes;
12799 var mostRecentlyUpdatedRoot = null; // The most recent time we committed a fallback. This lets us ensure a train
12800 // model where we don't commit new loading states in too quick succession.
12801
12802 var globalMostRecentFallbackTime = 0;
12803 var FALLBACK_THROTTLE_MS = 500; // The absolute time for when we should start giving up on rendering
12804 // more and prefer CPU suspense heuristics instead.
12805
12806 var workInProgressRootRenderTargetTime = Infinity; // How long a render is supposed to take before we start following CPU
12807 // suspense heuristics and opt out of rendering more content.
12808
12809 var RENDER_TIMEOUT_MS = 500;
12810
12811 function resetRenderTimer() {
12812 workInProgressRootRenderTargetTime = now() + RENDER_TIMEOUT_MS;
12813 }
12814
12815 function getRenderTargetTime() {
12816 return workInProgressRootRenderTargetTime;
12817 }
12818 var nextEffect = null;
12819 var hasUncaughtError = false;
12820 var firstUncaughtError = null;
12821 var legacyErrorBoundariesThatAlreadyFailed = null;
12822 var rootDoesHavePassiveEffects = false;
12823 var rootWithPendingPassiveEffects = null;
12824 var pendingPassiveEffectsRenderPriority = NoPriority$1;
12825 var pendingPassiveEffectsLanes = NoLanes;
12826 var pendingPassiveHookEffectsMount = [];
12827 var pendingPassiveHookEffectsUnmount = [];
12828 var rootsWithPendingDiscreteUpdates = null; // Use these to prevent an infinite loop of nested updates
12829
12830 var NESTED_UPDATE_LIMIT = 50;
12831 var nestedUpdateCount = 0;
12832 var rootWithNestedUpdates = null;
12833 var NESTED_PASSIVE_UPDATE_LIMIT = 50;
12834 var nestedPassiveUpdateCount = 0; // Marks the need to reschedule pending interactions at these lanes
12835 // during the commit phase. This enables them to be traced across components
12836 // that spawn new work during render. E.g. hidden boundaries, suspended SSR
12837 // hydration or SuspenseList.
12838 // TODO: Can use a bitmask instead of an array
12839
12840 var spawnedWorkDuringRender = null; // If two updates are scheduled within the same event, we should treat their
12841 // event times as simultaneous, even if the actual clock time has advanced
12842 // between the first and second call.
12843
12844 var currentEventTime = NoTimestamp;
12845 var currentEventWipLanes = NoLanes;
12846 var currentEventPendingLanes = NoLanes; // Dev only flag that tracks if passive effects are currently being flushed.
12847 // We warn about state updates for unmounted components differently in this case.
12848
12849 var isFlushingPassiveEffects = false;
12850 var focusedInstanceHandle = null;
12851 var shouldFireAfterActiveInstanceBlur = false;
12852 function getWorkInProgressRoot() {
12853 return workInProgressRoot;
12854 }
12855 function requestEventTime() {
12856 if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
12857 // We're inside React, so it's fine to read the actual time.
12858 return now();
12859 } // We're not inside React, so we may be in the middle of a browser event.
12860
12861
12862 if (currentEventTime !== NoTimestamp) {
12863 // Use the same start time for all updates until we enter React again.
12864 return currentEventTime;
12865 } // This is the first update since React yielded. Compute a new start time.
12866
12867
12868 currentEventTime = now();
12869 return currentEventTime;
12870 }
12871 function requestUpdateLane(fiber) {
12872 // Special cases
12873 var mode = fiber.mode;
12874
12875 if ((mode & BlockingMode) === NoMode) {
12876 return SyncLane;
12877 } else if ((mode & ConcurrentMode) === NoMode) {
12878 return getCurrentPriorityLevel() === ImmediatePriority$1 ? SyncLane : SyncBatchedLane;
12879 } // The algorithm for assigning an update to a lane should be stable for all
12880 // updates at the same priority within the same event. To do this, the inputs
12881 // to the algorithm must be the same. For example, we use the `renderLanes`
12882 // to avoid choosing a lane that is already in the middle of rendering.
12883 //
12884 // However, the "included" lanes could be mutated in between updates in the
12885 // same event, like if you perform an update inside `flushSync`. Or any other
12886 // code path that might call `prepareFreshStack`.
12887 //
12888 // The trick we use is to cache the first of each of these inputs within an
12889 // event. Then reset the cached values once we can be sure the event is over.
12890 // Our heuristic for that is whenever we enter a concurrent work loop.
12891 //
12892 // We'll do the same for `currentEventPendingLanes` below.
12893
12894
12895 if (currentEventWipLanes === NoLanes) {
12896 currentEventWipLanes = workInProgressRootIncludedLanes;
12897 }
12898
12899 var isTransition = requestCurrentTransition() !== NoTransition;
12900
12901 if (isTransition) {
12902 if (currentEventPendingLanes !== NoLanes) {
12903 currentEventPendingLanes = mostRecentlyUpdatedRoot !== null ? mostRecentlyUpdatedRoot.pendingLanes : NoLanes;
12904 }
12905
12906 return findTransitionLane(currentEventWipLanes, currentEventPendingLanes);
12907 } // TODO: Remove this dependency on the Scheduler priority.
12908 // To do that, we're replacing it with an update lane priority.
12909
12910
12911 var schedulerPriority = getCurrentPriorityLevel(); // The old behavior was using the priority level of the Scheduler.
12912 // This couples React to the Scheduler internals, so we're replacing it
12913 // with the currentUpdateLanePriority above. As an example of how this
12914 // could be problematic, if we're not inside `Scheduler.runWithPriority`,
12915 // then we'll get the priority of the current running Scheduler task,
12916 // which is probably not what we want.
12917
12918 var lane;
12919
12920 if ( // TODO: Temporary. We're removing the concept of discrete updates.
12921 (executionContext & DiscreteEventContext) !== NoContext && schedulerPriority === UserBlockingPriority$1) {
12922 lane = findUpdateLane(InputDiscreteLanePriority, currentEventWipLanes);
12923 } else {
12924 var schedulerLanePriority = schedulerPriorityToLanePriority(schedulerPriority);
12925
12926 lane = findUpdateLane(schedulerLanePriority, currentEventWipLanes);
12927 }
12928
12929 return lane;
12930 }
12931
12932 function requestRetryLane(fiber) {
12933 // This is a fork of `requestUpdateLane` designed specifically for Suspense
12934 // "retries" — a special update that attempts to flip a Suspense boundary
12935 // from its placeholder state to its primary/resolved state.
12936 // Special cases
12937 var mode = fiber.mode;
12938
12939 if ((mode & BlockingMode) === NoMode) {
12940 return SyncLane;
12941 } else if ((mode & ConcurrentMode) === NoMode) {
12942 return getCurrentPriorityLevel() === ImmediatePriority$1 ? SyncLane : SyncBatchedLane;
12943 } // See `requestUpdateLane` for explanation of `currentEventWipLanes`
12944
12945
12946 if (currentEventWipLanes === NoLanes) {
12947 currentEventWipLanes = workInProgressRootIncludedLanes;
12948 }
12949
12950 return findRetryLane(currentEventWipLanes);
12951 }
12952
12953 function scheduleUpdateOnFiber(fiber, lane, eventTime) {
12954 checkForNestedUpdates();
12955 warnAboutRenderPhaseUpdatesInDEV(fiber);
12956 var root = markUpdateLaneFromFiberToRoot(fiber, lane);
12957
12958 if (root === null) {
12959 warnAboutUpdateOnUnmountedFiberInDEV(fiber);
12960 return null;
12961 } // Mark that the root has a pending update.
12962
12963
12964 markRootUpdated(root, lane, eventTime);
12965
12966 if (root === workInProgressRoot) {
12967 // Received an update to a tree that's in the middle of rendering. Mark
12968 // that there was an interleaved update work on this root. Unless the
12969 // `deferRenderPhaseUpdateToNextBatch` flag is off and this is a render
12970 // phase update. In that case, we don't treat render phase updates as if
12971 // they were interleaved, for backwards compat reasons.
12972 {
12973 workInProgressRootUpdatedLanes = mergeLanes(workInProgressRootUpdatedLanes, lane);
12974 }
12975
12976 if (workInProgressRootExitStatus === RootSuspendedWithDelay) {
12977 // The root already suspended with a delay, which means this render
12978 // definitely won't finish. Since we have a new update, let's mark it as
12979 // suspended now, right before marking the incoming update. This has the
12980 // effect of interrupting the current render and switching to the update.
12981 // TODO: Make sure this doesn't override pings that happen while we've
12982 // already started rendering.
12983 markRootSuspended$1(root, workInProgressRootRenderLanes);
12984 }
12985 } // TODO: requestUpdateLanePriority also reads the priority. Pass the
12986 // priority as an argument to that function and this one.
12987
12988
12989 var priorityLevel = getCurrentPriorityLevel();
12990
12991 if (lane === SyncLane) {
12992 if ( // Check if we're inside unbatchedUpdates
12993 (executionContext & LegacyUnbatchedContext) !== NoContext && // Check if we're not already rendering
12994 (executionContext & (RenderContext | CommitContext)) === NoContext) {
12995 // Register pending interactions on the root to avoid losing traced interaction data.
12996 schedulePendingInteractions(root, lane); // This is a legacy edge case. The initial mount of a ReactDOM.render-ed
12997 // root inside of batchedUpdates should be synchronous, but layout updates
12998 // should be deferred until the end of the batch.
12999
13000 performSyncWorkOnRoot(root);
13001 } else {
13002 ensureRootIsScheduled(root, eventTime);
13003 schedulePendingInteractions(root, lane);
13004
13005 if (executionContext === NoContext) {
13006 // Flush the synchronous work now, unless we're already working or inside
13007 // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
13008 // scheduleCallbackForFiber to preserve the ability to schedule a callback
13009 // without immediately flushing it. We only do this for user-initiated
13010 // updates, to preserve historical behavior of legacy mode.
13011 resetRenderTimer();
13012 flushSyncCallbackQueue();
13013 }
13014 }
13015 } else {
13016 // Schedule a discrete update but only if it's not Sync.
13017 if ((executionContext & DiscreteEventContext) !== NoContext && ( // Only updates at user-blocking priority or greater are considered
13018 // discrete, even inside a discrete event.
13019 priorityLevel === UserBlockingPriority$1 || priorityLevel === ImmediatePriority$1)) {
13020 // This is the result of a discrete event. Track the lowest priority
13021 // discrete update per root so we can flush them early, if needed.
13022 if (rootsWithPendingDiscreteUpdates === null) {
13023 rootsWithPendingDiscreteUpdates = new Set([root]);
13024 } else {
13025 rootsWithPendingDiscreteUpdates.add(root);
13026 }
13027 } // Schedule other updates after in case the callback is sync.
13028
13029
13030 ensureRootIsScheduled(root, eventTime);
13031 schedulePendingInteractions(root, lane);
13032 } // We use this when assigning a lane for a transition inside
13033 // `requestUpdateLane`. We assume it's the same as the root being updated,
13034 // since in the common case of a single root app it probably is. If it's not
13035 // the same root, then it's not a huge deal, we just might batch more stuff
13036 // together more than necessary.
13037
13038
13039 mostRecentlyUpdatedRoot = root;
13040 } // This is split into a separate function so we can mark a fiber with pending
13041 // work without treating it as a typical update that originates from an event;
13042 // e.g. retrying a Suspense boundary isn't an update, but it does schedule work
13043 // on a fiber.
13044
13045 function markUpdateLaneFromFiberToRoot(sourceFiber, lane) {
13046 // Update the source fiber's lanes
13047 sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane);
13048 var alternate = sourceFiber.alternate;
13049
13050 if (alternate !== null) {
13051 alternate.lanes = mergeLanes(alternate.lanes, lane);
13052 }
13053
13054 {
13055 if (alternate === null && (sourceFiber.flags & (Placement | Hydrating)) !== NoFlags) {
13056 warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
13057 }
13058 } // Walk the parent path to the root and update the child expiration time.
13059
13060
13061 var node = sourceFiber;
13062 var parent = sourceFiber.return;
13063
13064 while (parent !== null) {
13065 parent.childLanes = mergeLanes(parent.childLanes, lane);
13066 alternate = parent.alternate;
13067
13068 if (alternate !== null) {
13069 alternate.childLanes = mergeLanes(alternate.childLanes, lane);
13070 } else {
13071 {
13072 if ((parent.flags & (Placement | Hydrating)) !== NoFlags) {
13073 warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
13074 }
13075 }
13076 }
13077
13078 node = parent;
13079 parent = parent.return;
13080 }
13081
13082 if (node.tag === HostRoot) {
13083 var root = node.stateNode;
13084 return root;
13085 } else {
13086 return null;
13087 }
13088 } // Use this function to schedule a task for a root. There's only one task per
13089 // root; if a task was already scheduled, we'll check to make sure the priority
13090 // of the existing task is the same as the priority of the next level that the
13091 // root has work on. This function is called on every update, and right before
13092 // exiting a task.
13093
13094
13095 function ensureRootIsScheduled(root, currentTime) {
13096 var existingCallbackNode = root.callbackNode; // Check if any lanes are being starved by other work. If so, mark them as
13097 // expired so we know to work on those next.
13098
13099 markStarvedLanesAsExpired(root, currentTime); // Determine the next lanes to work on, and their priority.
13100
13101 var nextLanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); // This returns the priority level computed during the `getNextLanes` call.
13102
13103 var newCallbackPriority = returnNextLanesPriority();
13104
13105 if (nextLanes === NoLanes) {
13106 // Special case: There's nothing to work on.
13107 if (existingCallbackNode !== null) {
13108 cancelCallback(existingCallbackNode);
13109 root.callbackNode = null;
13110 root.callbackPriority = NoLanePriority;
13111 }
13112
13113 return;
13114 } // Check if there's an existing task. We may be able to reuse it.
13115
13116
13117 if (existingCallbackNode !== null) {
13118 var existingCallbackPriority = root.callbackPriority;
13119
13120 if (existingCallbackPriority === newCallbackPriority) {
13121 // The priority hasn't changed. We can reuse the existing task. Exit.
13122 return;
13123 } // The priority changed. Cancel the existing callback. We'll schedule a new
13124 // one below.
13125
13126
13127 cancelCallback(existingCallbackNode);
13128 } // Schedule a new callback.
13129
13130
13131 var newCallbackNode;
13132
13133 if (newCallbackPriority === SyncLanePriority) {
13134 // Special case: Sync React callbacks are scheduled on a special
13135 // internal queue
13136 newCallbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
13137 } else if (newCallbackPriority === SyncBatchedLanePriority) {
13138 newCallbackNode = scheduleCallback(ImmediatePriority$1, performSyncWorkOnRoot.bind(null, root));
13139 } else {
13140 var schedulerPriorityLevel = lanePriorityToSchedulerPriority(newCallbackPriority);
13141 newCallbackNode = scheduleCallback(schedulerPriorityLevel, performConcurrentWorkOnRoot.bind(null, root));
13142 }
13143
13144 root.callbackPriority = newCallbackPriority;
13145 root.callbackNode = newCallbackNode;
13146 } // This is the entry point for every concurrent task, i.e. anything that
13147 // goes through Scheduler.
13148
13149
13150 function performConcurrentWorkOnRoot(root) {
13151 // Since we know we're in a React event, we can clear the current
13152 // event time. The next update will compute a new event time.
13153 currentEventTime = NoTimestamp;
13154 currentEventWipLanes = NoLanes;
13155 currentEventPendingLanes = NoLanes;
13156
13157 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
13158 {
13159 throw Error( "Should not already be working." );
13160 }
13161 } // Flush any pending passive effects before deciding which lanes to work on,
13162 // in case they schedule additional work.
13163
13164
13165 var originalCallbackNode = root.callbackNode;
13166 var didFlushPassiveEffects = flushPassiveEffects();
13167
13168 if (didFlushPassiveEffects) {
13169 // Something in the passive effect phase may have canceled the current task.
13170 // Check if the task node for this root was changed.
13171 if (root.callbackNode !== originalCallbackNode) {
13172 // The current task was canceled. Exit. We don't need to call
13173 // `ensureRootIsScheduled` because the check above implies either that
13174 // there's a new task, or that there's no remaining work on this root.
13175 return null;
13176 }
13177 } // Determine the next expiration time to work on, using the fields stored
13178 // on the root.
13179
13180
13181 var lanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes);
13182
13183 if (lanes === NoLanes) {
13184 // Defensive coding. This is never expected to happen.
13185 return null;
13186 }
13187
13188 var exitStatus = renderRootConcurrent(root, lanes);
13189
13190 if (includesSomeLane(workInProgressRootIncludedLanes, workInProgressRootUpdatedLanes)) {
13191 // The render included lanes that were updated during the render phase.
13192 // For example, when unhiding a hidden tree, we include all the lanes
13193 // that were previously skipped when the tree was hidden. That set of
13194 // lanes is a superset of the lanes we started rendering with.
13195 //
13196 // So we'll throw out the current work and restart.
13197 prepareFreshStack(root, NoLanes);
13198 } else if (exitStatus !== RootIncomplete) {
13199 if (exitStatus === RootErrored) {
13200 executionContext |= RetryAfterError; // If an error occurred during hydration,
13201 // discard server response and fall back to client side render.
13202
13203 if (root.hydrate) {
13204 root.hydrate = false;
13205 clearContainer(root.containerInfo);
13206 } // If something threw an error, try rendering one more time. We'll render
13207 // synchronously to block concurrent data mutations, and we'll includes
13208 // all pending updates are included. If it still fails after the second
13209 // attempt, we'll give up and commit the resulting tree.
13210
13211
13212 lanes = getLanesToRetrySynchronouslyOnError(root);
13213
13214 if (lanes !== NoLanes) {
13215 exitStatus = renderRootSync(root, lanes);
13216 }
13217 }
13218
13219 if (exitStatus === RootFatalErrored) {
13220 var fatalError = workInProgressRootFatalError;
13221 prepareFreshStack(root, NoLanes);
13222 markRootSuspended$1(root, lanes);
13223 ensureRootIsScheduled(root, now());
13224 throw fatalError;
13225 } // We now have a consistent tree. The next step is either to commit it,
13226 // or, if something suspended, wait to commit it after a timeout.
13227
13228
13229 var finishedWork = root.current.alternate;
13230 root.finishedWork = finishedWork;
13231 root.finishedLanes = lanes;
13232 finishConcurrentRender(root, exitStatus, lanes);
13233 }
13234
13235 ensureRootIsScheduled(root, now());
13236
13237 if (root.callbackNode === originalCallbackNode) {
13238 // The task node scheduled for this root is the same one that's
13239 // currently executed. Need to return a continuation.
13240 return performConcurrentWorkOnRoot.bind(null, root);
13241 }
13242
13243 return null;
13244 }
13245
13246 function finishConcurrentRender(root, exitStatus, lanes) {
13247 switch (exitStatus) {
13248 case RootIncomplete:
13249 case RootFatalErrored:
13250 {
13251 {
13252 {
13253 throw Error( "Root did not complete. This is a bug in React." );
13254 }
13255 }
13256 }
13257 // Flow knows about invariant, so it complains if I add a break
13258 // statement, but eslint doesn't know about invariant, so it complains
13259 // if I do. eslint-disable-next-line no-fallthrough
13260
13261 case RootErrored:
13262 {
13263 // We should have already attempted to retry this tree. If we reached
13264 // this point, it errored again. Commit it.
13265 commitRoot(root);
13266 break;
13267 }
13268
13269 case RootSuspended:
13270 {
13271 markRootSuspended$1(root, lanes); // We have an acceptable loading state. We need to figure out if we
13272 // should immediately commit it or wait a bit.
13273
13274 if (includesOnlyRetries(lanes) && // do not delay if we're inside an act() scope
13275 !shouldForceFlushFallbacksInDEV()) {
13276 // This render only included retries, no updates. Throttle committing
13277 // retries so that we don't show too many loading states too quickly.
13278 var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time.
13279
13280 if (msUntilTimeout > 10) {
13281 var nextLanes = getNextLanes(root, NoLanes);
13282
13283 if (nextLanes !== NoLanes) {
13284 // There's additional work on this root.
13285 break;
13286 }
13287
13288 var suspendedLanes = root.suspendedLanes;
13289
13290 if (!isSubsetOfLanes(suspendedLanes, lanes)) {
13291 // We should prefer to render the fallback of at the last
13292 // suspended level. Ping the last suspended level to try
13293 // rendering it again.
13294 // FIXME: What if the suspended lanes are Idle? Should not restart.
13295 var eventTime = requestEventTime();
13296 markRootPinged(root, suspendedLanes);
13297 break;
13298 } // The render is suspended, it hasn't timed out, and there's no
13299 // lower priority work to do. Instead of committing the fallback
13300 // immediately, wait for more data to arrive.
13301
13302
13303 root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), msUntilTimeout);
13304 break;
13305 }
13306 } // The work expired. Commit immediately.
13307
13308
13309 commitRoot(root);
13310 break;
13311 }
13312
13313 case RootSuspendedWithDelay:
13314 {
13315 markRootSuspended$1(root, lanes);
13316
13317 if (includesOnlyTransitions(lanes)) {
13318 // This is a transition, so we should exit without committing a
13319 // placeholder and without scheduling a timeout. Delay indefinitely
13320 // until we receive more data.
13321 break;
13322 }
13323
13324 if (!shouldForceFlushFallbacksInDEV()) {
13325 // This is not a transition, but we did trigger an avoided state.
13326 // Schedule a placeholder to display after a short delay, using the Just
13327 // Noticeable Difference.
13328 // TODO: Is the JND optimization worth the added complexity? If this is
13329 // the only reason we track the event time, then probably not.
13330 // Consider removing.
13331 var mostRecentEventTime = getMostRecentEventTime(root, lanes);
13332 var eventTimeMs = mostRecentEventTime;
13333 var timeElapsedMs = now() - eventTimeMs;
13334
13335 var _msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs; // Don't bother with a very short suspense time.
13336
13337
13338 if (_msUntilTimeout > 10) {
13339 // Instead of committing the fallback immediately, wait for more data
13340 // to arrive.
13341 root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout);
13342 break;
13343 }
13344 } // Commit the placeholder.
13345
13346
13347 commitRoot(root);
13348 break;
13349 }
13350
13351 case RootCompleted:
13352 {
13353 // The work completed. Ready to commit.
13354 commitRoot(root);
13355 break;
13356 }
13357
13358 default:
13359 {
13360 {
13361 {
13362 throw Error( "Unknown root exit status." );
13363 }
13364 }
13365 }
13366 }
13367 }
13368
13369 function markRootSuspended$1(root, suspendedLanes) {
13370 // When suspending, we should always exclude lanes that were pinged or (more
13371 // rarely, since we try to avoid it) updated during the render phase.
13372 // TODO: Lol maybe there's a better way to factor this besides this
13373 // obnoxiously named function :)
13374 suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes);
13375 suspendedLanes = removeLanes(suspendedLanes, workInProgressRootUpdatedLanes);
13376 markRootSuspended(root, suspendedLanes);
13377 } // This is the entry point for synchronous tasks that don't go
13378 // through Scheduler
13379
13380
13381 function performSyncWorkOnRoot(root) {
13382 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
13383 {
13384 throw Error( "Should not already be working." );
13385 }
13386 }
13387
13388 flushPassiveEffects();
13389 var lanes;
13390 var exitStatus;
13391
13392 if (root === workInProgressRoot && includesSomeLane(root.expiredLanes, workInProgressRootRenderLanes)) {
13393 // There's a partial tree, and at least one of its lanes has expired. Finish
13394 // rendering it before rendering the rest of the expired work.
13395 lanes = workInProgressRootRenderLanes;
13396 exitStatus = renderRootSync(root, lanes);
13397
13398 if (includesSomeLane(workInProgressRootIncludedLanes, workInProgressRootUpdatedLanes)) {
13399 // The render included lanes that were updated during the render phase.
13400 // For example, when unhiding a hidden tree, we include all the lanes
13401 // that were previously skipped when the tree was hidden. That set of
13402 // lanes is a superset of the lanes we started rendering with.
13403 //
13404 // Note that this only happens when part of the tree is rendered
13405 // concurrently. If the whole tree is rendered synchronously, then there
13406 // are no interleaved events.
13407 lanes = getNextLanes(root, lanes);
13408 exitStatus = renderRootSync(root, lanes);
13409 }
13410 } else {
13411 lanes = getNextLanes(root, NoLanes);
13412 exitStatus = renderRootSync(root, lanes);
13413 }
13414
13415 if (root.tag !== LegacyRoot && exitStatus === RootErrored) {
13416 executionContext |= RetryAfterError; // If an error occurred during hydration,
13417 // discard server response and fall back to client side render.
13418
13419 if (root.hydrate) {
13420 root.hydrate = false;
13421 clearContainer(root.containerInfo);
13422 } // If something threw an error, try rendering one more time. We'll render
13423 // synchronously to block concurrent data mutations, and we'll includes
13424 // all pending updates are included. If it still fails after the second
13425 // attempt, we'll give up and commit the resulting tree.
13426
13427
13428 lanes = getLanesToRetrySynchronouslyOnError(root);
13429
13430 if (lanes !== NoLanes) {
13431 exitStatus = renderRootSync(root, lanes);
13432 }
13433 }
13434
13435 if (exitStatus === RootFatalErrored) {
13436 var fatalError = workInProgressRootFatalError;
13437 prepareFreshStack(root, NoLanes);
13438 markRootSuspended$1(root, lanes);
13439 ensureRootIsScheduled(root, now());
13440 throw fatalError;
13441 } // We now have a consistent tree. Because this is a sync render, we
13442 // will commit it even if something suspended.
13443
13444
13445 var finishedWork = root.current.alternate;
13446 root.finishedWork = finishedWork;
13447 root.finishedLanes = lanes;
13448 commitRoot(root); // Before exiting, make sure there's a callback scheduled for the next
13449 // pending level.
13450
13451 ensureRootIsScheduled(root, now());
13452 return null;
13453 }
13454
13455 function batchedUpdates(fn, a) {
13456 var prevExecutionContext = executionContext;
13457 executionContext |= BatchedContext;
13458
13459 try {
13460 return fn(a);
13461 } finally {
13462 executionContext = prevExecutionContext;
13463
13464 if (executionContext === NoContext) {
13465 // Flush the immediate callbacks that were scheduled during this batch
13466 resetRenderTimer();
13467 flushSyncCallbackQueue();
13468 }
13469 }
13470 }
13471 function flushSync(fn, a) {
13472 var prevExecutionContext = executionContext;
13473
13474 if ((prevExecutionContext & (RenderContext | CommitContext)) !== NoContext) {
13475 {
13476 error('flushSync was called from inside a lifecycle method. React cannot ' + 'flush when React is already rendering. Consider moving this call to ' + 'a scheduler task or micro task.');
13477 }
13478
13479 return fn(a);
13480 }
13481
13482 executionContext |= BatchedContext;
13483
13484 {
13485 try {
13486 if (fn) {
13487 return runWithPriority(ImmediatePriority$1, fn.bind(null, a));
13488 } else {
13489 return undefined;
13490 }
13491 } finally {
13492 executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch.
13493 // Note that this will happen even if batchedUpdates is higher up
13494 // the stack.
13495
13496 flushSyncCallbackQueue();
13497 }
13498 }
13499 }
13500 function pushRenderLanes(fiber, lanes) {
13501 push(subtreeRenderLanesCursor, subtreeRenderLanes, fiber);
13502 subtreeRenderLanes = mergeLanes(subtreeRenderLanes, lanes);
13503 workInProgressRootIncludedLanes = mergeLanes(workInProgressRootIncludedLanes, lanes);
13504 }
13505 function popRenderLanes(fiber) {
13506 subtreeRenderLanes = subtreeRenderLanesCursor.current;
13507 pop(subtreeRenderLanesCursor, fiber);
13508 }
13509
13510 function prepareFreshStack(root, lanes) {
13511 root.finishedWork = null;
13512 root.finishedLanes = NoLanes;
13513 var timeoutHandle = root.timeoutHandle;
13514
13515 if (timeoutHandle !== noTimeout) {
13516 // The root previous suspended and scheduled a timeout to commit a fallback
13517 // state. Now that we have additional work, cancel the timeout.
13518 root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
13519
13520 cancelTimeout(timeoutHandle);
13521 }
13522
13523 if (workInProgress !== null) {
13524 var interruptedWork = workInProgress.return;
13525
13526 while (interruptedWork !== null) {
13527 unwindInterruptedWork(interruptedWork);
13528 interruptedWork = interruptedWork.return;
13529 }
13530 }
13531
13532 workInProgressRoot = root;
13533 workInProgress = createWorkInProgress(root.current, null);
13534 workInProgressRootRenderLanes = subtreeRenderLanes = workInProgressRootIncludedLanes = lanes;
13535 workInProgressRootExitStatus = RootIncomplete;
13536 workInProgressRootFatalError = null;
13537 workInProgressRootSkippedLanes = NoLanes;
13538 workInProgressRootUpdatedLanes = NoLanes;
13539 workInProgressRootPingedLanes = NoLanes;
13540
13541 {
13542 spawnedWorkDuringRender = null;
13543 }
13544
13545 {
13546 ReactStrictModeWarnings.discardPendingWarnings();
13547 }
13548 }
13549
13550 function handleError(root, thrownValue) {
13551 do {
13552 var erroredWork = workInProgress;
13553
13554 try {
13555 // Reset module-level state that was set during the render phase.
13556 resetContextDependencies();
13557 resetHooksAfterThrow();
13558 resetCurrentFiber(); // TODO: I found and added this missing line while investigating a
13559 // separate issue. Write a regression test using string refs.
13560
13561 ReactCurrentOwner$2.current = null;
13562
13563 if (erroredWork === null || erroredWork.return === null) {
13564 // Expected to be working on a non-root fiber. This is a fatal error
13565 // because there's no ancestor that can handle it; the root is
13566 // supposed to capture all errors that weren't caught by an error
13567 // boundary.
13568 workInProgressRootExitStatus = RootFatalErrored;
13569 workInProgressRootFatalError = thrownValue; // Set `workInProgress` to null. This represents advancing to the next
13570 // sibling, or the parent if there are no siblings. But since the root
13571 // has no siblings nor a parent, we set it to null. Usually this is
13572 // handled by `completeUnitOfWork` or `unwindWork`, but since we're
13573 // intentionally not calling those, we need set it here.
13574 // TODO: Consider calling `unwindWork` to pop the contexts.
13575
13576 workInProgress = null;
13577 return;
13578 }
13579
13580 if (enableProfilerTimer && erroredWork.mode & ProfileMode) {
13581 // Record the time spent rendering before an error was thrown. This
13582 // avoids inaccurate Profiler durations in the case of a
13583 // suspended render.
13584 stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true);
13585 }
13586
13587 throwException(root, erroredWork.return, erroredWork, thrownValue, workInProgressRootRenderLanes);
13588 completeUnitOfWork(erroredWork);
13589 } catch (yetAnotherThrownValue) {
13590 // Something in the return path also threw.
13591 thrownValue = yetAnotherThrownValue;
13592
13593 if (workInProgress === erroredWork && erroredWork !== null) {
13594 // If this boundary has already errored, then we had trouble processing
13595 // the error. Bubble it to the next boundary.
13596 erroredWork = erroredWork.return;
13597 workInProgress = erroredWork;
13598 } else {
13599 erroredWork = workInProgress;
13600 }
13601
13602 continue;
13603 } // Return to the normal work loop.
13604
13605
13606 return;
13607 } while (true);
13608 }
13609
13610 function pushDispatcher() {
13611 var prevDispatcher = ReactCurrentDispatcher$2.current;
13612 ReactCurrentDispatcher$2.current = ContextOnlyDispatcher;
13613
13614 if (prevDispatcher === null) {
13615 // The React isomorphic package does not include a default dispatcher.
13616 // Instead the first renderer will lazily attach one, in order to give
13617 // nicer error messages.
13618 return ContextOnlyDispatcher;
13619 } else {
13620 return prevDispatcher;
13621 }
13622 }
13623
13624 function popDispatcher(prevDispatcher) {
13625 ReactCurrentDispatcher$2.current = prevDispatcher;
13626 }
13627
13628 function pushInteractions(root) {
13629 {
13630 var prevInteractions = __interactionsRef.current;
13631 __interactionsRef.current = root.memoizedInteractions;
13632 return prevInteractions;
13633 }
13634 }
13635
13636 function popInteractions(prevInteractions) {
13637 {
13638 __interactionsRef.current = prevInteractions;
13639 }
13640 }
13641
13642 function markCommitTimeOfFallback() {
13643 globalMostRecentFallbackTime = now();
13644 }
13645 function markSkippedUpdateLanes(lane) {
13646 workInProgressRootSkippedLanes = mergeLanes(lane, workInProgressRootSkippedLanes);
13647 }
13648 function renderDidSuspend() {
13649 if (workInProgressRootExitStatus === RootIncomplete) {
13650 workInProgressRootExitStatus = RootSuspended;
13651 }
13652 }
13653 function renderDidSuspendDelayIfPossible() {
13654 if (workInProgressRootExitStatus === RootIncomplete || workInProgressRootExitStatus === RootSuspended) {
13655 workInProgressRootExitStatus = RootSuspendedWithDelay;
13656 } // Check if there are updates that we skipped tree that might have unblocked
13657 // this render.
13658
13659
13660 if (workInProgressRoot !== null && (includesNonIdleWork(workInProgressRootSkippedLanes) || includesNonIdleWork(workInProgressRootUpdatedLanes))) {
13661 // Mark the current render as suspended so that we switch to working on
13662 // the updates that were skipped. Usually we only suspend at the end of
13663 // the render phase.
13664 // TODO: We should probably always mark the root as suspended immediately
13665 // (inside this function), since by suspending at the end of the render
13666 // phase introduces a potential mistake where we suspend lanes that were
13667 // pinged or updated while we were rendering.
13668 markRootSuspended$1(workInProgressRoot, workInProgressRootRenderLanes);
13669 }
13670 }
13671 function renderDidError() {
13672 if (workInProgressRootExitStatus !== RootCompleted) {
13673 workInProgressRootExitStatus = RootErrored;
13674 }
13675 } // Called during render to determine if anything has suspended.
13676 // Returns false if we're not sure.
13677
13678 function renderHasNotSuspendedYet() {
13679 // If something errored or completed, we can't really be sure,
13680 // so those are false.
13681 return workInProgressRootExitStatus === RootIncomplete;
13682 }
13683
13684 function renderRootSync(root, lanes) {
13685 var prevExecutionContext = executionContext;
13686 executionContext |= RenderContext;
13687 var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack
13688 // and prepare a fresh one. Otherwise we'll continue where we left off.
13689
13690 if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) {
13691 prepareFreshStack(root, lanes);
13692 startWorkOnPendingInteractions(root, lanes);
13693 }
13694
13695 var prevInteractions = pushInteractions(root);
13696
13697 do {
13698 try {
13699 workLoopSync();
13700 break;
13701 } catch (thrownValue) {
13702 handleError(root, thrownValue);
13703 }
13704 } while (true);
13705
13706 resetContextDependencies();
13707
13708 {
13709 popInteractions(prevInteractions);
13710 }
13711
13712 executionContext = prevExecutionContext;
13713 popDispatcher(prevDispatcher);
13714
13715 if (workInProgress !== null) {
13716 // This is a sync render, so we should have finished the whole tree.
13717 {
13718 {
13719 throw Error( "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." );
13720 }
13721 }
13722 }
13723
13724
13725 workInProgressRoot = null;
13726 workInProgressRootRenderLanes = NoLanes;
13727 return workInProgressRootExitStatus;
13728 } // The work loop is an extremely hot path. Tell Closure not to inline it.
13729
13730 /** @noinline */
13731
13732
13733 function workLoopSync() {
13734 // Already timed out, so perform work without checking if we need to yield.
13735 while (workInProgress !== null) {
13736 performUnitOfWork(workInProgress);
13737 }
13738 }
13739
13740 function renderRootConcurrent(root, lanes) {
13741 var prevExecutionContext = executionContext;
13742 executionContext |= RenderContext;
13743 var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack
13744 // and prepare a fresh one. Otherwise we'll continue where we left off.
13745
13746 if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) {
13747 resetRenderTimer();
13748 prepareFreshStack(root, lanes);
13749 startWorkOnPendingInteractions(root, lanes);
13750 }
13751
13752 var prevInteractions = pushInteractions(root);
13753
13754 do {
13755 try {
13756 workLoopConcurrent();
13757 break;
13758 } catch (thrownValue) {
13759 handleError(root, thrownValue);
13760 }
13761 } while (true);
13762
13763 resetContextDependencies();
13764
13765 {
13766 popInteractions(prevInteractions);
13767 }
13768
13769 popDispatcher(prevDispatcher);
13770 executionContext = prevExecutionContext;
13771
13772
13773 if (workInProgress !== null) {
13774
13775 return RootIncomplete;
13776 } else {
13777
13778
13779 workInProgressRoot = null;
13780 workInProgressRootRenderLanes = NoLanes; // Return the final exit status.
13781
13782 return workInProgressRootExitStatus;
13783 }
13784 }
13785 /** @noinline */
13786
13787
13788 function workLoopConcurrent() {
13789 // Perform work until Scheduler asks us to yield
13790 while (workInProgress !== null && !shouldYield()) {
13791 performUnitOfWork(workInProgress);
13792 }
13793 }
13794
13795 function performUnitOfWork(unitOfWork) {
13796 // The current, flushed, state of this fiber is the alternate. Ideally
13797 // nothing should rely on this, but relying on it here means that we don't
13798 // need an additional field on the work in progress.
13799 var current = unitOfWork.alternate;
13800 setCurrentFiber(unitOfWork);
13801 var next;
13802
13803 if ( (unitOfWork.mode & ProfileMode) !== NoMode) {
13804 startProfilerTimer(unitOfWork);
13805 next = beginWork$1(current, unitOfWork, subtreeRenderLanes);
13806 stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
13807 } else {
13808 next = beginWork$1(current, unitOfWork, subtreeRenderLanes);
13809 }
13810
13811 resetCurrentFiber();
13812 unitOfWork.memoizedProps = unitOfWork.pendingProps;
13813
13814 if (next === null) {
13815 // If this doesn't spawn new work, complete the current work.
13816 completeUnitOfWork(unitOfWork);
13817 } else {
13818 workInProgress = next;
13819 }
13820
13821 ReactCurrentOwner$2.current = null;
13822 }
13823
13824 function completeUnitOfWork(unitOfWork) {
13825 // Attempt to complete the current unit of work, then move to the next
13826 // sibling. If there are no more siblings, return to the parent fiber.
13827 var completedWork = unitOfWork;
13828
13829 do {
13830 // The current, flushed, state of this fiber is the alternate. Ideally
13831 // nothing should rely on this, but relying on it here means that we don't
13832 // need an additional field on the work in progress.
13833 var current = completedWork.alternate;
13834 var returnFiber = completedWork.return; // Check if the work completed or if something threw.
13835
13836 if ((completedWork.flags & Incomplete) === NoFlags) {
13837 setCurrentFiber(completedWork);
13838 var next = void 0;
13839
13840 if ( (completedWork.mode & ProfileMode) === NoMode) {
13841 next = completeWork(current, completedWork, subtreeRenderLanes);
13842 } else {
13843 startProfilerTimer(completedWork);
13844 next = completeWork(current, completedWork, subtreeRenderLanes); // Update render duration assuming we didn't error.
13845
13846 stopProfilerTimerIfRunningAndRecordDelta(completedWork, false);
13847 }
13848
13849 resetCurrentFiber();
13850
13851 if (next !== null) {
13852 // Completing this fiber spawned new work. Work on that next.
13853 workInProgress = next;
13854 return;
13855 }
13856
13857 resetChildLanes(completedWork);
13858
13859 if (returnFiber !== null && // Do not append effects to parents if a sibling failed to complete
13860 (returnFiber.flags & Incomplete) === NoFlags) {
13861 // Append all the effects of the subtree and this fiber onto the effect
13862 // list of the parent. The completion order of the children affects the
13863 // side-effect order.
13864 if (returnFiber.firstEffect === null) {
13865 returnFiber.firstEffect = completedWork.firstEffect;
13866 }
13867
13868 if (completedWork.lastEffect !== null) {
13869 if (returnFiber.lastEffect !== null) {
13870 returnFiber.lastEffect.nextEffect = completedWork.firstEffect;
13871 }
13872
13873 returnFiber.lastEffect = completedWork.lastEffect;
13874 } // If this fiber had side-effects, we append it AFTER the children's
13875 // side-effects. We can perform certain side-effects earlier if needed,
13876 // by doing multiple passes over the effect list. We don't want to
13877 // schedule our own side-effect on our own list because if end up
13878 // reusing children we'll schedule this effect onto itself since we're
13879 // at the end.
13880
13881
13882 var flags = completedWork.flags; // Skip both NoWork and PerformedWork tags when creating the effect
13883 // list. PerformedWork effect is read by React DevTools but shouldn't be
13884 // committed.
13885
13886 if (flags > PerformedWork) {
13887 if (returnFiber.lastEffect !== null) {
13888 returnFiber.lastEffect.nextEffect = completedWork;
13889 } else {
13890 returnFiber.firstEffect = completedWork;
13891 }
13892
13893 returnFiber.lastEffect = completedWork;
13894 }
13895 }
13896 } else {
13897 // This fiber did not complete because something threw. Pop values off
13898 // the stack without entering the complete phase. If this is a boundary,
13899 // capture values if possible.
13900 var _next = unwindWork(completedWork); // Because this fiber did not complete, don't reset its expiration time.
13901
13902
13903 if (_next !== null) {
13904 // If completing this work spawned new work, do that next. We'll come
13905 // back here again.
13906 // Since we're restarting, remove anything that is not a host effect
13907 // from the effect tag.
13908 _next.flags &= HostEffectMask;
13909 workInProgress = _next;
13910 return;
13911 }
13912
13913 if ( (completedWork.mode & ProfileMode) !== NoMode) {
13914 // Record the render duration for the fiber that errored.
13915 stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); // Include the time spent working on failed children before continuing.
13916
13917 var actualDuration = completedWork.actualDuration;
13918 var child = completedWork.child;
13919
13920 while (child !== null) {
13921 actualDuration += child.actualDuration;
13922 child = child.sibling;
13923 }
13924
13925 completedWork.actualDuration = actualDuration;
13926 }
13927
13928 if (returnFiber !== null) {
13929 // Mark the parent fiber as incomplete and clear its effect list.
13930 returnFiber.firstEffect = returnFiber.lastEffect = null;
13931 returnFiber.flags |= Incomplete;
13932 }
13933 }
13934
13935 var siblingFiber = completedWork.sibling;
13936
13937 if (siblingFiber !== null) {
13938 // If there is more work to do in this returnFiber, do that next.
13939 workInProgress = siblingFiber;
13940 return;
13941 } // Otherwise, return to the parent
13942
13943
13944 completedWork = returnFiber; // Update the next thing we're working on in case something throws.
13945
13946 workInProgress = completedWork;
13947 } while (completedWork !== null); // We've reached the root.
13948
13949
13950 if (workInProgressRootExitStatus === RootIncomplete) {
13951 workInProgressRootExitStatus = RootCompleted;
13952 }
13953 }
13954
13955 function resetChildLanes(completedWork) {
13956 if ( // TODO: Move this check out of the hot path by moving `resetChildLanes`
13957 // to switch statement in `completeWork`.
13958 (completedWork.tag === LegacyHiddenComponent || completedWork.tag === OffscreenComponent) && completedWork.memoizedState !== null && !includesSomeLane(subtreeRenderLanes, OffscreenLane) && (completedWork.mode & ConcurrentMode) !== NoLanes) {
13959 // The children of this component are hidden. Don't bubble their
13960 // expiration times.
13961 return;
13962 }
13963
13964 var newChildLanes = NoLanes; // Bubble up the earliest expiration time.
13965
13966 if ( (completedWork.mode & ProfileMode) !== NoMode) {
13967 // In profiling mode, resetChildExpirationTime is also used to reset
13968 // profiler durations.
13969 var actualDuration = completedWork.actualDuration;
13970 var treeBaseDuration = completedWork.selfBaseDuration; // When a fiber is cloned, its actualDuration is reset to 0. This value will
13971 // only be updated if work is done on the fiber (i.e. it doesn't bailout).
13972 // When work is done, it should bubble to the parent's actualDuration. If
13973 // the fiber has not been cloned though, (meaning no work was done), then
13974 // this value will reflect the amount of time spent working on a previous
13975 // render. In that case it should not bubble. We determine whether it was
13976 // cloned by comparing the child pointer.
13977
13978 var shouldBubbleActualDurations = completedWork.alternate === null || completedWork.child !== completedWork.alternate.child;
13979 var child = completedWork.child;
13980
13981 while (child !== null) {
13982 newChildLanes = mergeLanes(newChildLanes, mergeLanes(child.lanes, child.childLanes));
13983
13984 if (shouldBubbleActualDurations) {
13985 actualDuration += child.actualDuration;
13986 }
13987
13988 treeBaseDuration += child.treeBaseDuration;
13989 child = child.sibling;
13990 }
13991
13992 var isTimedOutSuspense = completedWork.tag === SuspenseComponent && completedWork.memoizedState !== null;
13993
13994 if (isTimedOutSuspense) {
13995 // Don't count time spent in a timed out Suspense subtree as part of the base duration.
13996 var primaryChildFragment = completedWork.child;
13997
13998 if (primaryChildFragment !== null) {
13999 treeBaseDuration -= primaryChildFragment.treeBaseDuration;
14000 }
14001 }
14002
14003 completedWork.actualDuration = actualDuration;
14004 completedWork.treeBaseDuration = treeBaseDuration;
14005 } else {
14006 var _child = completedWork.child;
14007
14008 while (_child !== null) {
14009 newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child.lanes, _child.childLanes));
14010 _child = _child.sibling;
14011 }
14012 }
14013
14014 completedWork.childLanes = newChildLanes;
14015 }
14016
14017 function commitRoot(root) {
14018 var renderPriorityLevel = getCurrentPriorityLevel();
14019 runWithPriority(ImmediatePriority$1, commitRootImpl.bind(null, root, renderPriorityLevel));
14020 return null;
14021 }
14022
14023 function commitRootImpl(root, renderPriorityLevel) {
14024 do {
14025 // `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which
14026 // means `flushPassiveEffects` will sometimes result in additional
14027 // passive effects. So we need to keep flushing in a loop until there are
14028 // no more pending effects.
14029 // TODO: Might be better if `flushPassiveEffects` did not automatically
14030 // flush synchronous work at the end, to avoid factoring hazards like this.
14031 flushPassiveEffects();
14032 } while (rootWithPendingPassiveEffects !== null);
14033
14034 flushRenderPhaseStrictModeWarningsInDEV();
14035
14036 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
14037 {
14038 throw Error( "Should not already be working." );
14039 }
14040 }
14041
14042 var finishedWork = root.finishedWork;
14043 var lanes = root.finishedLanes;
14044
14045 if (finishedWork === null) {
14046
14047 return null;
14048 }
14049
14050 root.finishedWork = null;
14051 root.finishedLanes = NoLanes;
14052
14053 if (!(finishedWork !== root.current)) {
14054 {
14055 throw Error( "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." );
14056 }
14057 } // commitRoot never returns a continuation; it always finishes synchronously.
14058 // So we can clear these now to allow a new callback to be scheduled.
14059
14060
14061 root.callbackNode = null; // Update the first and last pending times on this root. The new first
14062 // pending time is whatever is left on the root fiber.
14063
14064 var remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes);
14065 markRootFinished(root, remainingLanes); // Clear already finished discrete updates in case that a later call of
14066 // `flushDiscreteUpdates` starts a useless render pass which may cancels
14067 // a scheduled timeout.
14068
14069 if (rootsWithPendingDiscreteUpdates !== null) {
14070 if (!hasDiscreteLanes(remainingLanes) && rootsWithPendingDiscreteUpdates.has(root)) {
14071 rootsWithPendingDiscreteUpdates.delete(root);
14072 }
14073 }
14074
14075 if (root === workInProgressRoot) {
14076 // We can reset these now that they are finished.
14077 workInProgressRoot = null;
14078 workInProgress = null;
14079 workInProgressRootRenderLanes = NoLanes;
14080 } // Get the list of effects.
14081
14082
14083 var firstEffect;
14084
14085 if (finishedWork.flags > PerformedWork) {
14086 // A fiber's effect list consists only of its children, not itself. So if
14087 // the root has an effect, we need to add it to the end of the list. The
14088 // resulting list is the set that would belong to the root's parent, if it
14089 // had one; that is, all the effects in the tree including the root.
14090 if (finishedWork.lastEffect !== null) {
14091 finishedWork.lastEffect.nextEffect = finishedWork;
14092 firstEffect = finishedWork.firstEffect;
14093 } else {
14094 firstEffect = finishedWork;
14095 }
14096 } else {
14097 // There is no effect on the root.
14098 firstEffect = finishedWork.firstEffect;
14099 }
14100
14101 if (firstEffect !== null) {
14102
14103 var prevExecutionContext = executionContext;
14104 executionContext |= CommitContext;
14105 var prevInteractions = pushInteractions(root); // Reset this to null before calling lifecycles
14106
14107 ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass
14108 // of the effect list for each phase: all mutation effects come before all
14109 // layout effects, and so on.
14110 // The first phase a "before mutation" phase. We use this phase to read the
14111 // state of the host tree right before we mutate it. This is where
14112 // getSnapshotBeforeUpdate is called.
14113
14114 focusedInstanceHandle = prepareForCommit(root.containerInfo);
14115 shouldFireAfterActiveInstanceBlur = false;
14116 nextEffect = firstEffect;
14117
14118 do {
14119 {
14120 invokeGuardedCallback(null, commitBeforeMutationEffects, null);
14121
14122 if (hasCaughtError()) {
14123 if (!(nextEffect !== null)) {
14124 {
14125 throw Error( "Should be working on an effect." );
14126 }
14127 }
14128
14129 var error = clearCaughtError();
14130 captureCommitPhaseError(nextEffect, error);
14131 nextEffect = nextEffect.nextEffect;
14132 }
14133 }
14134 } while (nextEffect !== null); // We no longer need to track the active instance fiber
14135
14136
14137 focusedInstanceHandle = null;
14138
14139 {
14140 // Mark the current commit time to be shared by all Profilers in this
14141 // batch. This enables them to be grouped later.
14142 recordCommitTime();
14143 } // The next phase is the mutation phase, where we mutate the host tree.
14144
14145
14146 nextEffect = firstEffect;
14147
14148 do {
14149 {
14150 invokeGuardedCallback(null, commitMutationEffects, null, root, renderPriorityLevel);
14151
14152 if (hasCaughtError()) {
14153 if (!(nextEffect !== null)) {
14154 {
14155 throw Error( "Should be working on an effect." );
14156 }
14157 }
14158
14159 var _error = clearCaughtError();
14160
14161 captureCommitPhaseError(nextEffect, _error);
14162 nextEffect = nextEffect.nextEffect;
14163 }
14164 }
14165 } while (nextEffect !== null);
14166
14167 resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after
14168 // the mutation phase, so that the previous tree is still current during
14169 // componentWillUnmount, but before the layout phase, so that the finished
14170 // work is current during componentDidMount/Update.
14171
14172 root.current = finishedWork; // The next phase is the layout phase, where we call effects that read
14173 // the host tree after it's been mutated. The idiomatic use case for this is
14174 // layout, but class component lifecycles also fire here for legacy reasons.
14175
14176 nextEffect = firstEffect;
14177
14178 do {
14179 {
14180 invokeGuardedCallback(null, commitLayoutEffects, null, root, lanes);
14181
14182 if (hasCaughtError()) {
14183 if (!(nextEffect !== null)) {
14184 {
14185 throw Error( "Should be working on an effect." );
14186 }
14187 }
14188
14189 var _error2 = clearCaughtError();
14190
14191 captureCommitPhaseError(nextEffect, _error2);
14192 nextEffect = nextEffect.nextEffect;
14193 }
14194 }
14195 } while (nextEffect !== null);
14196
14197 nextEffect = null; // Tell Scheduler to yield at the end of the frame, so the browser has an
14198 // opportunity to paint.
14199
14200 requestPaint();
14201
14202 {
14203 popInteractions(prevInteractions);
14204 }
14205
14206 executionContext = prevExecutionContext;
14207 } else {
14208 // No effects.
14209 root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were
14210 // no effects.
14211 // TODO: Maybe there's a better way to report this.
14212
14213 {
14214 recordCommitTime();
14215 }
14216 }
14217
14218 var rootDidHavePassiveEffects = rootDoesHavePassiveEffects;
14219
14220 if (rootDoesHavePassiveEffects) {
14221 // This commit has passive effects. Stash a reference to them. But don't
14222 // schedule a callback until after flushing layout work.
14223 rootDoesHavePassiveEffects = false;
14224 rootWithPendingPassiveEffects = root;
14225 pendingPassiveEffectsLanes = lanes;
14226 pendingPassiveEffectsRenderPriority = renderPriorityLevel;
14227 } else {
14228 // We are done with the effect chain at this point so let's clear the
14229 // nextEffect pointers to assist with GC. If we have passive effects, we'll
14230 // clear this in flushPassiveEffects.
14231 nextEffect = firstEffect;
14232
14233 while (nextEffect !== null) {
14234 var nextNextEffect = nextEffect.nextEffect;
14235 nextEffect.nextEffect = null;
14236
14237 if (nextEffect.flags & Deletion) {
14238 detachFiberAfterEffects(nextEffect);
14239 }
14240
14241 nextEffect = nextNextEffect;
14242 }
14243 } // Read this again, since an effect might have updated it
14244
14245
14246 remainingLanes = root.pendingLanes; // Check if there's remaining work on this root
14247
14248 if (remainingLanes !== NoLanes) {
14249 {
14250 if (spawnedWorkDuringRender !== null) {
14251 var expirationTimes = spawnedWorkDuringRender;
14252 spawnedWorkDuringRender = null;
14253
14254 for (var i = 0; i < expirationTimes.length; i++) {
14255 scheduleInteractions(root, expirationTimes[i], root.memoizedInteractions);
14256 }
14257 }
14258
14259 schedulePendingInteractions(root, remainingLanes);
14260 }
14261 } else {
14262 // If there's no remaining work, we can clear the set of already failed
14263 // error boundaries.
14264 legacyErrorBoundariesThatAlreadyFailed = null;
14265 }
14266
14267 {
14268 if (!rootDidHavePassiveEffects) {
14269 // If there are no passive effects, then we can complete the pending interactions.
14270 // Otherwise, we'll wait until after the passive effects are flushed.
14271 // Wait to do this until after remaining work has been scheduled,
14272 // so that we don't prematurely signal complete for interactions when there's e.g. hidden work.
14273 finishPendingInteractions(root, lanes);
14274 }
14275 }
14276
14277 if (remainingLanes === SyncLane) {
14278 // Count the number of times the root synchronously re-renders without
14279 // finishing. If there are too many, it indicates an infinite update loop.
14280 if (root === rootWithNestedUpdates) {
14281 nestedUpdateCount++;
14282 } else {
14283 nestedUpdateCount = 0;
14284 rootWithNestedUpdates = root;
14285 }
14286 } else {
14287 nestedUpdateCount = 0;
14288 }
14289
14290 onCommitRoot(finishedWork.stateNode, renderPriorityLevel);
14291 // additional work on this root is scheduled.
14292
14293
14294 ensureRootIsScheduled(root, now());
14295
14296 if (hasUncaughtError) {
14297 hasUncaughtError = false;
14298 var _error3 = firstUncaughtError;
14299 firstUncaughtError = null;
14300 throw _error3;
14301 }
14302
14303 if ((executionContext & LegacyUnbatchedContext) !== NoContext) {
14304 // a ReactDOM.render-ed root inside of batchedUpdates. The commit fired
14305 // synchronously, but layout updates should be deferred until the end
14306 // of the batch.
14307
14308
14309 return null;
14310 } // If layout work was scheduled, flush it now.
14311
14312
14313 flushSyncCallbackQueue();
14314
14315 return null;
14316 }
14317
14318 function commitBeforeMutationEffects() {
14319 while (nextEffect !== null) {
14320 var current = nextEffect.alternate;
14321
14322 if (!shouldFireAfterActiveInstanceBlur && focusedInstanceHandle !== null) {
14323 if ((nextEffect.flags & Deletion) !== NoFlags) {
14324 if (doesFiberContain(nextEffect, focusedInstanceHandle)) {
14325 shouldFireAfterActiveInstanceBlur = true;
14326 }
14327 } else {
14328 // TODO: Move this out of the hot path using a dedicated effect tag.
14329 if (nextEffect.tag === SuspenseComponent && isSuspenseBoundaryBeingHidden(current, nextEffect) && doesFiberContain(nextEffect, focusedInstanceHandle)) {
14330 shouldFireAfterActiveInstanceBlur = true;
14331 }
14332 }
14333 }
14334
14335 var flags = nextEffect.flags;
14336
14337 if ((flags & Snapshot) !== NoFlags) {
14338 setCurrentFiber(nextEffect);
14339 commitBeforeMutationLifeCycles(current, nextEffect);
14340 resetCurrentFiber();
14341 }
14342
14343 if ((flags & Passive) !== NoFlags) {
14344 // If there are passive effects, schedule a callback to flush at
14345 // the earliest opportunity.
14346 if (!rootDoesHavePassiveEffects) {
14347 rootDoesHavePassiveEffects = true;
14348 scheduleCallback(NormalPriority$1, function () {
14349 flushPassiveEffects();
14350 return null;
14351 });
14352 }
14353 }
14354
14355 nextEffect = nextEffect.nextEffect;
14356 }
14357 }
14358
14359 function commitMutationEffects(root, renderPriorityLevel) {
14360 // TODO: Should probably move the bulk of this function to commitWork.
14361 while (nextEffect !== null) {
14362 setCurrentFiber(nextEffect);
14363 var flags = nextEffect.flags;
14364
14365 if (flags & ContentReset) {
14366 commitResetTextContent(nextEffect);
14367 }
14368
14369 if (flags & Ref) {
14370 var current = nextEffect.alternate;
14371
14372 if (current !== null) {
14373 commitDetachRef(current);
14374 }
14375 } // The following switch statement is only concerned about placement,
14376 // updates, and deletions. To avoid needing to add a case for every possible
14377 // bitmap value, we remove the secondary effects from the effect tag and
14378 // switch on that value.
14379
14380
14381 var primaryFlags = flags & (Placement | Update | Deletion | Hydrating);
14382
14383 switch (primaryFlags) {
14384 case Placement:
14385 {
14386 commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is
14387 // inserted, before any life-cycles like componentDidMount gets called.
14388 // TODO: findDOMNode doesn't rely on this any more but isMounted does
14389 // and isMounted is deprecated anyway so we should be able to kill this.
14390
14391 nextEffect.flags &= ~Placement;
14392 break;
14393 }
14394
14395 case PlacementAndUpdate:
14396 {
14397 // Placement
14398 commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is
14399 // inserted, before any life-cycles like componentDidMount gets called.
14400
14401 nextEffect.flags &= ~Placement; // Update
14402
14403 var _current = nextEffect.alternate;
14404 commitWork(_current, nextEffect);
14405 break;
14406 }
14407
14408 case Hydrating:
14409 {
14410 nextEffect.flags &= ~Hydrating;
14411 break;
14412 }
14413
14414 case HydratingAndUpdate:
14415 {
14416 nextEffect.flags &= ~Hydrating; // Update
14417
14418 var _current2 = nextEffect.alternate;
14419 commitWork(_current2, nextEffect);
14420 break;
14421 }
14422
14423 case Update:
14424 {
14425 var _current3 = nextEffect.alternate;
14426 commitWork(_current3, nextEffect);
14427 break;
14428 }
14429
14430 case Deletion:
14431 {
14432 commitDeletion(root, nextEffect);
14433 break;
14434 }
14435 }
14436
14437 resetCurrentFiber();
14438 nextEffect = nextEffect.nextEffect;
14439 }
14440 }
14441
14442 function commitLayoutEffects(root, committedLanes) {
14443
14444
14445 while (nextEffect !== null) {
14446 setCurrentFiber(nextEffect);
14447 var flags = nextEffect.flags;
14448
14449 if (flags & (Update | Callback)) {
14450 var current = nextEffect.alternate;
14451 commitLifeCycles(root, current, nextEffect);
14452 }
14453
14454 {
14455 if (flags & Ref) {
14456 commitAttachRef(nextEffect);
14457 }
14458 }
14459
14460 resetCurrentFiber();
14461 nextEffect = nextEffect.nextEffect;
14462 }
14463 }
14464
14465 function flushPassiveEffects() {
14466 // Returns whether passive effects were flushed.
14467 if (pendingPassiveEffectsRenderPriority !== NoPriority$1) {
14468 var priorityLevel = pendingPassiveEffectsRenderPriority > NormalPriority$1 ? NormalPriority$1 : pendingPassiveEffectsRenderPriority;
14469 pendingPassiveEffectsRenderPriority = NoPriority$1;
14470
14471 {
14472 return runWithPriority(priorityLevel, flushPassiveEffectsImpl);
14473 }
14474 }
14475
14476 return false;
14477 }
14478 function enqueuePendingPassiveHookEffectMount(fiber, effect) {
14479 pendingPassiveHookEffectsMount.push(effect, fiber);
14480
14481 if (!rootDoesHavePassiveEffects) {
14482 rootDoesHavePassiveEffects = true;
14483 scheduleCallback(NormalPriority$1, function () {
14484 flushPassiveEffects();
14485 return null;
14486 });
14487 }
14488 }
14489 function enqueuePendingPassiveHookEffectUnmount(fiber, effect) {
14490 pendingPassiveHookEffectsUnmount.push(effect, fiber);
14491
14492 {
14493 fiber.flags |= PassiveUnmountPendingDev;
14494 var alternate = fiber.alternate;
14495
14496 if (alternate !== null) {
14497 alternate.flags |= PassiveUnmountPendingDev;
14498 }
14499 }
14500
14501 if (!rootDoesHavePassiveEffects) {
14502 rootDoesHavePassiveEffects = true;
14503 scheduleCallback(NormalPriority$1, function () {
14504 flushPassiveEffects();
14505 return null;
14506 });
14507 }
14508 }
14509
14510 function invokePassiveEffectCreate(effect) {
14511 var create = effect.create;
14512 effect.destroy = create();
14513 }
14514
14515 function flushPassiveEffectsImpl() {
14516 if (rootWithPendingPassiveEffects === null) {
14517 return false;
14518 }
14519
14520 var root = rootWithPendingPassiveEffects;
14521 var lanes = pendingPassiveEffectsLanes;
14522 rootWithPendingPassiveEffects = null;
14523 pendingPassiveEffectsLanes = NoLanes;
14524
14525 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
14526 {
14527 throw Error( "Cannot flush passive effects while already rendering." );
14528 }
14529 }
14530
14531 {
14532 isFlushingPassiveEffects = true;
14533 }
14534
14535 var prevExecutionContext = executionContext;
14536 executionContext |= CommitContext;
14537 var prevInteractions = pushInteractions(root); // It's important that ALL pending passive effect destroy functions are called
14538 // before ANY passive effect create functions are called.
14539 // Otherwise effects in sibling components might interfere with each other.
14540 // e.g. a destroy function in one component may unintentionally override a ref
14541 // value set by a create function in another component.
14542 // Layout effects have the same constraint.
14543 // First pass: Destroy stale passive effects.
14544
14545 var unmountEffects = pendingPassiveHookEffectsUnmount;
14546 pendingPassiveHookEffectsUnmount = [];
14547
14548 for (var i = 0; i < unmountEffects.length; i += 2) {
14549 var _effect = unmountEffects[i];
14550 var fiber = unmountEffects[i + 1];
14551 var destroy = _effect.destroy;
14552 _effect.destroy = undefined;
14553
14554 {
14555 fiber.flags &= ~PassiveUnmountPendingDev;
14556 var alternate = fiber.alternate;
14557
14558 if (alternate !== null) {
14559 alternate.flags &= ~PassiveUnmountPendingDev;
14560 }
14561 }
14562
14563 if (typeof destroy === 'function') {
14564 {
14565 setCurrentFiber(fiber);
14566
14567 {
14568 invokeGuardedCallback(null, destroy, null);
14569 }
14570
14571 if (hasCaughtError()) {
14572 if (!(fiber !== null)) {
14573 {
14574 throw Error( "Should be working on an effect." );
14575 }
14576 }
14577
14578 var error = clearCaughtError();
14579 captureCommitPhaseError(fiber, error);
14580 }
14581
14582 resetCurrentFiber();
14583 }
14584 }
14585 } // Second pass: Create new passive effects.
14586
14587
14588 var mountEffects = pendingPassiveHookEffectsMount;
14589 pendingPassiveHookEffectsMount = [];
14590
14591 for (var _i = 0; _i < mountEffects.length; _i += 2) {
14592 var _effect2 = mountEffects[_i];
14593 var _fiber = mountEffects[_i + 1];
14594
14595 {
14596 setCurrentFiber(_fiber);
14597
14598 {
14599 invokeGuardedCallback(null, invokePassiveEffectCreate, null, _effect2);
14600 }
14601
14602 if (hasCaughtError()) {
14603 if (!(_fiber !== null)) {
14604 {
14605 throw Error( "Should be working on an effect." );
14606 }
14607 }
14608
14609 var _error4 = clearCaughtError();
14610
14611 captureCommitPhaseError(_fiber, _error4);
14612 }
14613
14614 resetCurrentFiber();
14615 }
14616 } // Note: This currently assumes there are no passive effects on the root fiber
14617 // because the root is not part of its own effect list.
14618 // This could change in the future.
14619
14620
14621 var effect = root.current.firstEffect;
14622
14623 while (effect !== null) {
14624 var nextNextEffect = effect.nextEffect; // Remove nextEffect pointer to assist GC
14625
14626 effect.nextEffect = null;
14627
14628 if (effect.flags & Deletion) {
14629 detachFiberAfterEffects(effect);
14630 }
14631
14632 effect = nextNextEffect;
14633 }
14634
14635 {
14636 popInteractions(prevInteractions);
14637 finishPendingInteractions(root, lanes);
14638 }
14639
14640 {
14641 isFlushingPassiveEffects = false;
14642 }
14643
14644 executionContext = prevExecutionContext;
14645 flushSyncCallbackQueue(); // If additional passive effects were scheduled, increment a counter. If this
14646 // exceeds the limit, we'll fire a warning.
14647
14648 nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1;
14649 return true;
14650 }
14651
14652 function isAlreadyFailedLegacyErrorBoundary(instance) {
14653 return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
14654 }
14655 function markLegacyErrorBoundaryAsFailed(instance) {
14656 if (legacyErrorBoundariesThatAlreadyFailed === null) {
14657 legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
14658 } else {
14659 legacyErrorBoundariesThatAlreadyFailed.add(instance);
14660 }
14661 }
14662
14663 function prepareToThrowUncaughtError(error) {
14664 if (!hasUncaughtError) {
14665 hasUncaughtError = true;
14666 firstUncaughtError = error;
14667 }
14668 }
14669
14670 var onUncaughtError = prepareToThrowUncaughtError;
14671
14672 function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
14673 var errorInfo = createCapturedValue(error, sourceFiber);
14674 var update = createRootErrorUpdate(rootFiber, errorInfo, SyncLane);
14675 enqueueUpdate(rootFiber, update);
14676 var eventTime = requestEventTime();
14677 var root = markUpdateLaneFromFiberToRoot(rootFiber, SyncLane);
14678
14679 if (root !== null) {
14680 markRootUpdated(root, SyncLane, eventTime);
14681 ensureRootIsScheduled(root, eventTime);
14682 schedulePendingInteractions(root, SyncLane);
14683 }
14684 }
14685
14686 function captureCommitPhaseError(sourceFiber, error) {
14687 if (sourceFiber.tag === HostRoot) {
14688 // Error was thrown at the root. There is no parent, so the root
14689 // itself should capture it.
14690 captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
14691 return;
14692 }
14693
14694 var fiber = sourceFiber.return;
14695
14696 while (fiber !== null) {
14697 if (fiber.tag === HostRoot) {
14698 captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error);
14699 return;
14700 } else if (fiber.tag === ClassComponent) {
14701 var ctor = fiber.type;
14702 var instance = fiber.stateNode;
14703
14704 if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
14705 var errorInfo = createCapturedValue(error, sourceFiber);
14706 var update = createClassErrorUpdate(fiber, errorInfo, SyncLane);
14707 enqueueUpdate(fiber, update);
14708 var eventTime = requestEventTime();
14709 var root = markUpdateLaneFromFiberToRoot(fiber, SyncLane);
14710
14711 if (root !== null) {
14712 markRootUpdated(root, SyncLane, eventTime);
14713 ensureRootIsScheduled(root, eventTime);
14714 schedulePendingInteractions(root, SyncLane);
14715 } else {
14716 // This component has already been unmounted.
14717 // We can't schedule any follow up work for the root because the fiber is already unmounted,
14718 // but we can still call the log-only boundary so the error isn't swallowed.
14719 //
14720 // TODO This is only a temporary bandaid for the old reconciler fork.
14721 // We can delete this special case once the new fork is merged.
14722 if (typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
14723 try {
14724 instance.componentDidCatch(error, errorInfo);
14725 } catch (errorToIgnore) {// TODO Ignore this error? Rethrow it?
14726 // This is kind of an edge case.
14727 }
14728 }
14729 }
14730
14731 return;
14732 }
14733 }
14734
14735 fiber = fiber.return;
14736 }
14737 }
14738 function pingSuspendedRoot(root, wakeable, pingedLanes) {
14739 var pingCache = root.pingCache;
14740
14741 if (pingCache !== null) {
14742 // The wakeable resolved, so we no longer need to memoize, because it will
14743 // never be thrown again.
14744 pingCache.delete(wakeable);
14745 }
14746
14747 var eventTime = requestEventTime();
14748 markRootPinged(root, pingedLanes);
14749
14750 if (workInProgressRoot === root && isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)) {
14751 // Received a ping at the same priority level at which we're currently
14752 // rendering. We might want to restart this render. This should mirror
14753 // the logic of whether or not a root suspends once it completes.
14754 // TODO: If we're rendering sync either due to Sync, Batched or expired,
14755 // we should probably never restart.
14756 // If we're suspended with delay, or if it's a retry, we'll always suspend
14757 // so we can always restart.
14758 if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && includesOnlyRetries(workInProgressRootRenderLanes) && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) {
14759 // Restart from the root.
14760 prepareFreshStack(root, NoLanes);
14761 } else {
14762 // Even though we can't restart right now, we might get an
14763 // opportunity later. So we mark this render as having a ping.
14764 workInProgressRootPingedLanes = mergeLanes(workInProgressRootPingedLanes, pingedLanes);
14765 }
14766 }
14767
14768 ensureRootIsScheduled(root, eventTime);
14769 schedulePendingInteractions(root, pingedLanes);
14770 }
14771
14772 function retryTimedOutBoundary(boundaryFiber, retryLane) {
14773 // The boundary fiber (a Suspense component or SuspenseList component)
14774 // previously was rendered in its fallback state. One of the promises that
14775 // suspended it has resolved, which means at least part of the tree was
14776 // likely unblocked. Try rendering again, at a new expiration time.
14777 if (retryLane === NoLane) {
14778 retryLane = requestRetryLane(boundaryFiber);
14779 } // TODO: Special case idle priority?
14780
14781
14782 var eventTime = requestEventTime();
14783 var root = markUpdateLaneFromFiberToRoot(boundaryFiber, retryLane);
14784
14785 if (root !== null) {
14786 markRootUpdated(root, retryLane, eventTime);
14787 ensureRootIsScheduled(root, eventTime);
14788 schedulePendingInteractions(root, retryLane);
14789 }
14790 }
14791 function resolveRetryWakeable(boundaryFiber, wakeable) {
14792 var retryLane = NoLane; // Default
14793
14794 var retryCache;
14795
14796 {
14797 retryCache = boundaryFiber.stateNode;
14798 }
14799
14800 if (retryCache !== null) {
14801 // The wakeable resolved, so we no longer need to memoize, because it will
14802 // never be thrown again.
14803 retryCache.delete(wakeable);
14804 }
14805
14806 retryTimedOutBoundary(boundaryFiber, retryLane);
14807 } // Computes the next Just Noticeable Difference (JND) boundary.
14808 // The theory is that a person can't tell the difference between small differences in time.
14809 // Therefore, if we wait a bit longer than necessary that won't translate to a noticeable
14810 // difference in the experience. However, waiting for longer might mean that we can avoid
14811 // showing an intermediate loading state. The longer we have already waited, the harder it
14812 // is to tell small differences in time. Therefore, the longer we've already waited,
14813 // the longer we can wait additionally. At some point we have to give up though.
14814 // We pick a train model where the next boundary commits at a consistent schedule.
14815 // These particular numbers are vague estimates. We expect to adjust them based on research.
14816
14817 function jnd(timeElapsed) {
14818 return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960;
14819 }
14820
14821 function checkForNestedUpdates() {
14822 if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
14823 nestedUpdateCount = 0;
14824 rootWithNestedUpdates = null;
14825
14826 {
14827 {
14828 throw Error( "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." );
14829 }
14830 }
14831 }
14832
14833 {
14834 if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
14835 nestedPassiveUpdateCount = 0;
14836
14837 error('Maximum update depth exceeded. This can happen when a component ' + "calls setState inside useEffect, but useEffect either doesn't " + 'have a dependency array, or one of the dependencies changes on ' + 'every render.');
14838 }
14839 }
14840 }
14841
14842 function flushRenderPhaseStrictModeWarningsInDEV() {
14843 {
14844 ReactStrictModeWarnings.flushLegacyContextWarning();
14845
14846 {
14847 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
14848 }
14849 }
14850 }
14851
14852 var didWarnStateUpdateForNotYetMountedComponent = null;
14853
14854 function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) {
14855 {
14856 if ((executionContext & RenderContext) !== NoContext) {
14857 // We let the other warning about render phase updates deal with this one.
14858 return;
14859 }
14860
14861 if (!(fiber.mode & (BlockingMode | ConcurrentMode))) {
14862 return;
14863 }
14864
14865 var tag = fiber.tag;
14866
14867 if (tag !== IndeterminateComponent && tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent && tag !== Block) {
14868 // Only warn for user-defined components, not internal ones like Suspense.
14869 return;
14870 } // We show the whole stack but dedupe on the top component's name because
14871 // the problematic code almost always lies inside that component.
14872
14873
14874 var componentName = getComponentName(fiber.type) || 'ReactComponent';
14875
14876 if (didWarnStateUpdateForNotYetMountedComponent !== null) {
14877 if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) {
14878 return;
14879 }
14880
14881 didWarnStateUpdateForNotYetMountedComponent.add(componentName);
14882 } else {
14883 didWarnStateUpdateForNotYetMountedComponent = new Set([componentName]);
14884 }
14885
14886 var previousFiber = current;
14887
14888 try {
14889 setCurrentFiber(fiber);
14890
14891 error("Can't perform a React state update on a component that hasn't mounted yet. " + 'This indicates that you have a side-effect in your render function that ' + 'asynchronously later calls tries to update the component. Move this work to ' + 'useEffect instead.');
14892 } finally {
14893 if (previousFiber) {
14894 setCurrentFiber(fiber);
14895 } else {
14896 resetCurrentFiber();
14897 }
14898 }
14899 }
14900 }
14901
14902 var didWarnStateUpdateForUnmountedComponent = null;
14903
14904 function warnAboutUpdateOnUnmountedFiberInDEV(fiber) {
14905 {
14906 var tag = fiber.tag;
14907
14908 if (tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent && tag !== Block) {
14909 // Only warn for user-defined components, not internal ones like Suspense.
14910 return;
14911 } // If there are pending passive effects unmounts for this Fiber,
14912 // we can assume that they would have prevented this update.
14913
14914
14915 if ((fiber.flags & PassiveUnmountPendingDev) !== NoFlags) {
14916 return;
14917 } // We show the whole stack but dedupe on the top component's name because
14918 // the problematic code almost always lies inside that component.
14919
14920
14921 var componentName = getComponentName(fiber.type) || 'ReactComponent';
14922
14923 if (didWarnStateUpdateForUnmountedComponent !== null) {
14924 if (didWarnStateUpdateForUnmountedComponent.has(componentName)) {
14925 return;
14926 }
14927
14928 didWarnStateUpdateForUnmountedComponent.add(componentName);
14929 } else {
14930 didWarnStateUpdateForUnmountedComponent = new Set([componentName]);
14931 }
14932
14933 if (isFlushingPassiveEffects) ; else {
14934 var previousFiber = current;
14935
14936 try {
14937 setCurrentFiber(fiber);
14938
14939 error("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.', tag === ClassComponent ? 'the componentWillUnmount method' : 'a useEffect cleanup function');
14940 } finally {
14941 if (previousFiber) {
14942 setCurrentFiber(fiber);
14943 } else {
14944 resetCurrentFiber();
14945 }
14946 }
14947 }
14948 }
14949 }
14950
14951 var beginWork$1;
14952
14953 {
14954 beginWork$1 = beginWork;
14955 }
14956
14957 var didWarnAboutUpdateInRender = false;
14958 var didWarnAboutUpdateInRenderForAnotherComponent;
14959
14960 {
14961 didWarnAboutUpdateInRenderForAnotherComponent = new Set();
14962 }
14963
14964 function warnAboutRenderPhaseUpdatesInDEV(fiber) {
14965 {
14966 if (isRendering && (executionContext & RenderContext) !== NoContext && !getIsUpdatingOpaqueValueInRenderPhaseInDEV()) {
14967 switch (fiber.tag) {
14968 case FunctionComponent:
14969 case ForwardRef:
14970 case SimpleMemoComponent:
14971 {
14972 var renderingComponentName = workInProgress && getComponentName(workInProgress.type) || 'Unknown'; // Dedupe by the rendering component because it's the one that needs to be fixed.
14973
14974 var dedupeKey = renderingComponentName;
14975
14976 if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) {
14977 didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey);
14978 var setStateComponentName = getComponentName(fiber.type) || 'Unknown';
14979
14980 error('Cannot update a component (`%s`) while rendering a ' + 'different component (`%s`). To locate the bad setState() call inside `%s`, ' + 'follow the stack trace as described in https://reactjs.org/link/setstate-in-render', setStateComponentName, renderingComponentName, renderingComponentName);
14981 }
14982
14983 break;
14984 }
14985
14986 case ClassComponent:
14987 {
14988 if (!didWarnAboutUpdateInRender) {
14989 error('Cannot update during an existing state transition (such as ' + 'within `render`). Render methods should be a pure ' + 'function of props and state.');
14990
14991 didWarnAboutUpdateInRender = true;
14992 }
14993
14994 break;
14995 }
14996 }
14997 }
14998 }
14999 } // a 'shared' variable that changes when act() opens/closes in tests.
15000
15001
15002 var IsThisRendererActing = {
15003 current: false
15004 };
15005 function warnIfNotScopedWithMatchingAct(fiber) {
15006 {
15007 if ( IsSomeRendererActing.current === true && IsThisRendererActing.current !== true) {
15008 var previousFiber = current;
15009
15010 try {
15011 setCurrentFiber(fiber);
15012
15013 error("It looks like you're using the wrong act() around your test interactions.\n" + 'Be sure to use the matching version of act() corresponding to your renderer:\n\n' + '// for react-dom:\n' + // Break up imports to avoid accidentally parsing them as dependencies.
15014 'import {act} fr' + "om 'react-dom/test-utils';\n" + '// ...\n' + 'act(() => ...);\n\n' + '// for react-test-renderer:\n' + // Break up imports to avoid accidentally parsing them as dependencies.
15015 'import TestRenderer fr' + "om react-test-renderer';\n" + 'const {act} = TestRenderer;\n' + '// ...\n' + 'act(() => ...);');
15016 } finally {
15017 if (previousFiber) {
15018 setCurrentFiber(fiber);
15019 } else {
15020 resetCurrentFiber();
15021 }
15022 }
15023 }
15024 }
15025 }
15026 function warnIfNotCurrentlyActingEffectsInDEV(fiber) {
15027 {
15028 if ( (fiber.mode & StrictMode) !== NoMode && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {
15029 error('An update to %s ran an effect, but 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://reactjs.org/link/wrap-tests-with-act', getComponentName(fiber.type));
15030 }
15031 }
15032 }
15033
15034 function warnIfNotCurrentlyActingUpdatesInDEV(fiber) {
15035 {
15036 if ( executionContext === NoContext && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {
15037 var previousFiber = current;
15038
15039 try {
15040 setCurrentFiber(fiber);
15041
15042 error('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://reactjs.org/link/wrap-tests-with-act', getComponentName(fiber.type));
15043 } finally {
15044 if (previousFiber) {
15045 setCurrentFiber(fiber);
15046 } else {
15047 resetCurrentFiber();
15048 }
15049 }
15050 }
15051 }
15052 }
15053
15054 var warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV; // In tests, we want to enforce a mocked scheduler.
15055
15056 var didWarnAboutUnmockedScheduler = false; // TODO Before we release concurrent mode, revisit this and decide whether a mocked
15057 // scheduler is the actual recommendation. The alternative could be a testing build,
15058 // a new lib, or whatever; we dunno just yet. This message is for early adopters
15059 // to get their tests right.
15060
15061 function warnIfUnmockedScheduler(fiber) {
15062 {
15063 if (didWarnAboutUnmockedScheduler === false && Scheduler$1.unstable_flushAllWithoutAsserting === undefined) {
15064 if (fiber.mode & BlockingMode || fiber.mode & ConcurrentMode) {
15065 didWarnAboutUnmockedScheduler = true;
15066
15067 error('In Concurrent or Sync modes, the "scheduler" module needs to be mocked ' + 'to guarantee consistent behaviour across tests and browsers. ' + 'For example, with jest: \n' + // Break up requires to avoid accidentally parsing them as dependencies.
15068 "jest.mock('scheduler', () => require" + "('scheduler/unstable_mock'));\n\n" + 'For more info, visit https://reactjs.org/link/mock-scheduler');
15069 }
15070 }
15071 }
15072 }
15073
15074 function computeThreadID(root, lane) {
15075 // Interaction threads are unique per root and expiration time.
15076 // NOTE: Intentionally unsound cast. All that matters is that it's a number
15077 // and it represents a batch of work. Could make a helper function instead,
15078 // but meh this is fine for now.
15079 return lane * 1000 + root.interactionThreadID;
15080 }
15081
15082 function markSpawnedWork(lane) {
15083
15084 if (spawnedWorkDuringRender === null) {
15085 spawnedWorkDuringRender = [lane];
15086 } else {
15087 spawnedWorkDuringRender.push(lane);
15088 }
15089 }
15090
15091 function scheduleInteractions(root, lane, interactions) {
15092
15093 if (interactions.size > 0) {
15094 var pendingInteractionMap = root.pendingInteractionMap;
15095 var pendingInteractions = pendingInteractionMap.get(lane);
15096
15097 if (pendingInteractions != null) {
15098 interactions.forEach(function (interaction) {
15099 if (!pendingInteractions.has(interaction)) {
15100 // Update the pending async work count for previously unscheduled interaction.
15101 interaction.__count++;
15102 }
15103
15104 pendingInteractions.add(interaction);
15105 });
15106 } else {
15107 pendingInteractionMap.set(lane, new Set(interactions)); // Update the pending async work count for the current interactions.
15108
15109 interactions.forEach(function (interaction) {
15110 interaction.__count++;
15111 });
15112 }
15113
15114 var subscriber = __subscriberRef.current;
15115
15116 if (subscriber !== null) {
15117 var threadID = computeThreadID(root, lane);
15118 subscriber.onWorkScheduled(interactions, threadID);
15119 }
15120 }
15121 }
15122
15123 function schedulePendingInteractions(root, lane) {
15124
15125 scheduleInteractions(root, lane, __interactionsRef.current);
15126 }
15127
15128 function startWorkOnPendingInteractions(root, lanes) {
15129 // we can accurately attribute time spent working on it, And so that cascading
15130 // work triggered during the render phase will be associated with it.
15131
15132
15133 var interactions = new Set();
15134 root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledLane) {
15135 if (includesSomeLane(lanes, scheduledLane)) {
15136 scheduledInteractions.forEach(function (interaction) {
15137 return interactions.add(interaction);
15138 });
15139 }
15140 }); // Store the current set of interactions on the FiberRoot for a few reasons:
15141 // We can re-use it in hot functions like performConcurrentWorkOnRoot()
15142 // without having to recalculate it. We will also use it in commitWork() to
15143 // pass to any Profiler onRender() hooks. This also provides DevTools with a
15144 // way to access it when the onCommitRoot() hook is called.
15145
15146 root.memoizedInteractions = interactions;
15147
15148 if (interactions.size > 0) {
15149 var subscriber = __subscriberRef.current;
15150
15151 if (subscriber !== null) {
15152 var threadID = computeThreadID(root, lanes);
15153
15154 try {
15155 subscriber.onWorkStarted(interactions, threadID);
15156 } catch (error) {
15157 // If the subscriber throws, rethrow it in a separate task
15158 scheduleCallback(ImmediatePriority$1, function () {
15159 throw error;
15160 });
15161 }
15162 }
15163 }
15164 }
15165
15166 function finishPendingInteractions(root, committedLanes) {
15167
15168 var remainingLanesAfterCommit = root.pendingLanes;
15169 var subscriber;
15170
15171 try {
15172 subscriber = __subscriberRef.current;
15173
15174 if (subscriber !== null && root.memoizedInteractions.size > 0) {
15175 // FIXME: More than one lane can finish in a single commit.
15176 var threadID = computeThreadID(root, committedLanes);
15177 subscriber.onWorkStopped(root.memoizedInteractions, threadID);
15178 }
15179 } catch (error) {
15180 // If the subscriber throws, rethrow it in a separate task
15181 scheduleCallback(ImmediatePriority$1, function () {
15182 throw error;
15183 });
15184 } finally {
15185 // Clear completed interactions from the pending Map.
15186 // Unless the render was suspended or cascading work was scheduled,
15187 // In which case– leave pending interactions until the subsequent render.
15188 var pendingInteractionMap = root.pendingInteractionMap;
15189 pendingInteractionMap.forEach(function (scheduledInteractions, lane) {
15190 // Only decrement the pending interaction count if we're done.
15191 // If there's still work at the current priority,
15192 // That indicates that we are waiting for suspense data.
15193 if (!includesSomeLane(remainingLanesAfterCommit, lane)) {
15194 pendingInteractionMap.delete(lane);
15195 scheduledInteractions.forEach(function (interaction) {
15196 interaction.__count--;
15197
15198 if (subscriber !== null && interaction.__count === 0) {
15199 try {
15200 subscriber.onInteractionScheduledWorkCompleted(interaction);
15201 } catch (error) {
15202 // If the subscriber throws, rethrow it in a separate task
15203 scheduleCallback(ImmediatePriority$1, function () {
15204 throw error;
15205 });
15206 }
15207 }
15208 });
15209 }
15210 });
15211 }
15212 } // `act` testing API
15213
15214 function shouldForceFlushFallbacksInDEV() {
15215 // Never force flush in production. This function should get stripped out.
15216 return actingUpdatesScopeDepth > 0;
15217 }
15218
15219 var flushMockScheduler = Scheduler$1.unstable_flushAllWithoutAsserting;
15220 var isSchedulerMocked = typeof flushMockScheduler === 'function'; // Returns whether additional work was scheduled. Caller should keep flushing
15221 // until there's no work left.
15222
15223 function flushActWork() {
15224 if (flushMockScheduler !== undefined) {
15225
15226 try {
15227 return flushMockScheduler();
15228 } finally {
15229 }
15230 } else {
15231
15232 try {
15233 var didFlushWork = false;
15234
15235 while (flushPassiveEffects()) {
15236 didFlushWork = true;
15237 }
15238
15239 return didFlushWork;
15240 } finally {
15241 }
15242 }
15243 }
15244
15245 function flushWorkAndMicroTasks(onDone) {
15246 try {
15247 flushActWork();
15248 enqueueTask(function () {
15249 if (flushActWork()) {
15250 flushWorkAndMicroTasks(onDone);
15251 } else {
15252 onDone();
15253 }
15254 });
15255 } catch (err) {
15256 onDone(err);
15257 }
15258 } // we track the 'depth' of the act() calls with this counter,
15259 // so we can tell if any async act() calls try to run in parallel.
15260
15261
15262 var actingUpdatesScopeDepth = 0;
15263 function act(callback) {
15264
15265 var previousActingUpdatesScopeDepth = actingUpdatesScopeDepth;
15266 actingUpdatesScopeDepth++;
15267 var previousIsSomeRendererActing = IsSomeRendererActing.current;
15268 var previousIsThisRendererActing = IsThisRendererActing.current;
15269 IsSomeRendererActing.current = true;
15270 IsThisRendererActing.current = true;
15271
15272 function onDone() {
15273 actingUpdatesScopeDepth--;
15274 IsSomeRendererActing.current = previousIsSomeRendererActing;
15275 IsThisRendererActing.current = previousIsThisRendererActing;
15276
15277 {
15278 if (actingUpdatesScopeDepth > previousActingUpdatesScopeDepth) {
15279 // if it's _less than_ previousActingUpdatesScopeDepth, then we can assume the 'other' one has warned
15280 error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. ');
15281 }
15282 }
15283 }
15284
15285 var result;
15286
15287 try {
15288 result = batchedUpdates(callback);
15289 } catch (error) {
15290 // on sync errors, we still want to 'cleanup' and decrement actingUpdatesScopeDepth
15291 onDone();
15292 throw error;
15293 }
15294
15295 if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
15296 // setup a boolean that gets set to true only
15297 // once this act() call is await-ed
15298 var called = false;
15299
15300 {
15301 if (typeof Promise !== 'undefined') {
15302 //eslint-disable-next-line no-undef
15303 Promise.resolve().then(function () {}).then(function () {
15304 if (called === false) {
15305 error('You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, interleaving multiple act ' + 'calls and mixing their scopes. You should - await act(async () => ...);');
15306 }
15307 });
15308 }
15309 } // in the async case, the returned thenable runs the callback, flushes
15310 // effects and microtasks in a loop until flushPassiveEffects() === false,
15311 // and cleans up
15312
15313
15314 return {
15315 then: function (resolve, reject) {
15316 called = true;
15317 result.then(function () {
15318 if (actingUpdatesScopeDepth > 1 || isSchedulerMocked === true && previousIsSomeRendererActing === true) {
15319 onDone();
15320 resolve();
15321 return;
15322 } // we're about to exit the act() scope,
15323 // now's the time to flush tasks/effects
15324
15325
15326 flushWorkAndMicroTasks(function (err) {
15327 onDone();
15328
15329 if (err) {
15330 reject(err);
15331 } else {
15332 resolve();
15333 }
15334 });
15335 }, function (err) {
15336 onDone();
15337 reject(err);
15338 });
15339 }
15340 };
15341 } else {
15342 {
15343 if (result !== undefined) {
15344 error('The callback passed to act(...) function ' + 'must return undefined, or a Promise. You returned %s', result);
15345 }
15346 } // flush effects until none remain, and cleanup
15347
15348
15349 try {
15350 if (actingUpdatesScopeDepth === 1 && (isSchedulerMocked === false || previousIsSomeRendererActing === false)) {
15351 // we're about to exit the act() scope,
15352 // now's the time to flush effects
15353 flushActWork();
15354 }
15355
15356 onDone();
15357 } catch (err) {
15358 onDone();
15359 throw err;
15360 } // in the sync case, the returned thenable only warns *if* await-ed
15361
15362
15363 return {
15364 then: function (resolve) {
15365 {
15366 error('Do not await the result of calling act(...) with sync logic, it is not a Promise.');
15367 }
15368
15369 resolve();
15370 }
15371 };
15372 }
15373 }
15374
15375 function detachFiberAfterEffects(fiber) {
15376 fiber.sibling = null;
15377 fiber.stateNode = null;
15378 }
15379
15380 var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below.
15381
15382 var failedBoundaries = null;
15383 var setRefreshHandler = function (handler) {
15384 {
15385 resolveFamily = handler;
15386 }
15387 };
15388 function resolveFunctionForHotReloading(type) {
15389 {
15390 if (resolveFamily === null) {
15391 // Hot reloading is disabled.
15392 return type;
15393 }
15394
15395 var family = resolveFamily(type);
15396
15397 if (family === undefined) {
15398 return type;
15399 } // Use the latest known implementation.
15400
15401
15402 return family.current;
15403 }
15404 }
15405 function resolveClassForHotReloading(type) {
15406 // No implementation differences.
15407 return resolveFunctionForHotReloading(type);
15408 }
15409 function resolveForwardRefForHotReloading(type) {
15410 {
15411 if (resolveFamily === null) {
15412 // Hot reloading is disabled.
15413 return type;
15414 }
15415
15416 var family = resolveFamily(type);
15417
15418 if (family === undefined) {
15419 // Check if we're dealing with a real forwardRef. Don't want to crash early.
15420 if (type !== null && type !== undefined && typeof type.render === 'function') {
15421 // ForwardRef is special because its resolved .type is an object,
15422 // but it's possible that we only have its inner render function in the map.
15423 // If that inner render function is different, we'll build a new forwardRef type.
15424 var currentRender = resolveFunctionForHotReloading(type.render);
15425
15426 if (type.render !== currentRender) {
15427 var syntheticType = {
15428 $$typeof: REACT_FORWARD_REF_TYPE,
15429 render: currentRender
15430 };
15431
15432 if (type.displayName !== undefined) {
15433 syntheticType.displayName = type.displayName;
15434 }
15435
15436 return syntheticType;
15437 }
15438 }
15439
15440 return type;
15441 } // Use the latest known implementation.
15442
15443
15444 return family.current;
15445 }
15446 }
15447 function isCompatibleFamilyForHotReloading(fiber, element) {
15448 {
15449 if (resolveFamily === null) {
15450 // Hot reloading is disabled.
15451 return false;
15452 }
15453
15454 var prevType = fiber.elementType;
15455 var nextType = element.type; // If we got here, we know types aren't === equal.
15456
15457 var needsCompareFamilies = false;
15458 var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null;
15459
15460 switch (fiber.tag) {
15461 case ClassComponent:
15462 {
15463 if (typeof nextType === 'function') {
15464 needsCompareFamilies = true;
15465 }
15466
15467 break;
15468 }
15469
15470 case FunctionComponent:
15471 {
15472 if (typeof nextType === 'function') {
15473 needsCompareFamilies = true;
15474 } else if ($$typeofNextType === REACT_LAZY_TYPE) {
15475 // We don't know the inner type yet.
15476 // We're going to assume that the lazy inner type is stable,
15477 // and so it is sufficient to avoid reconciling it away.
15478 // We're not going to unwrap or actually use the new lazy type.
15479 needsCompareFamilies = true;
15480 }
15481
15482 break;
15483 }
15484
15485 case ForwardRef:
15486 {
15487 if ($$typeofNextType === REACT_FORWARD_REF_TYPE) {
15488 needsCompareFamilies = true;
15489 } else if ($$typeofNextType === REACT_LAZY_TYPE) {
15490 needsCompareFamilies = true;
15491 }
15492
15493 break;
15494 }
15495
15496 case MemoComponent:
15497 case SimpleMemoComponent:
15498 {
15499 if ($$typeofNextType === REACT_MEMO_TYPE) {
15500 // TODO: if it was but can no longer be simple,
15501 // we shouldn't set this.
15502 needsCompareFamilies = true;
15503 } else if ($$typeofNextType === REACT_LAZY_TYPE) {
15504 needsCompareFamilies = true;
15505 }
15506
15507 break;
15508 }
15509
15510 default:
15511 return false;
15512 } // Check if both types have a family and it's the same one.
15513
15514
15515 if (needsCompareFamilies) {
15516 // Note: memo() and forwardRef() we'll compare outer rather than inner type.
15517 // This means both of them need to be registered to preserve state.
15518 // If we unwrapped and compared the inner types for wrappers instead,
15519 // then we would risk falsely saying two separate memo(Foo)
15520 // calls are equivalent because they wrap the same Foo function.
15521 var prevFamily = resolveFamily(prevType);
15522
15523 if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) {
15524 return true;
15525 }
15526 }
15527
15528 return false;
15529 }
15530 }
15531 function markFailedErrorBoundaryForHotReloading(fiber) {
15532 {
15533 if (resolveFamily === null) {
15534 // Hot reloading is disabled.
15535 return;
15536 }
15537
15538 if (typeof WeakSet !== 'function') {
15539 return;
15540 }
15541
15542 if (failedBoundaries === null) {
15543 failedBoundaries = new WeakSet();
15544 }
15545
15546 failedBoundaries.add(fiber);
15547 }
15548 }
15549 var scheduleRefresh = function (root, update) {
15550 {
15551 if (resolveFamily === null) {
15552 // Hot reloading is disabled.
15553 return;
15554 }
15555
15556 var staleFamilies = update.staleFamilies,
15557 updatedFamilies = update.updatedFamilies;
15558 flushPassiveEffects();
15559 flushSync(function () {
15560 scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies);
15561 });
15562 }
15563 };
15564 var scheduleRoot = function (root, element) {
15565 {
15566 if (root.context !== emptyContextObject) {
15567 // Super edge case: root has a legacy _renderSubtree context
15568 // but we don't know the parentComponent so we can't pass it.
15569 // Just ignore. We'll delete this with _renderSubtree code path later.
15570 return;
15571 }
15572
15573 flushPassiveEffects();
15574 flushSync(function () {
15575 updateContainer(element, root, null, null);
15576 });
15577 }
15578 };
15579
15580 function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
15581 {
15582 var alternate = fiber.alternate,
15583 child = fiber.child,
15584 sibling = fiber.sibling,
15585 tag = fiber.tag,
15586 type = fiber.type;
15587 var candidateType = null;
15588
15589 switch (tag) {
15590 case FunctionComponent:
15591 case SimpleMemoComponent:
15592 case ClassComponent:
15593 candidateType = type;
15594 break;
15595
15596 case ForwardRef:
15597 candidateType = type.render;
15598 break;
15599 }
15600
15601 if (resolveFamily === null) {
15602 throw new Error('Expected resolveFamily to be set during hot reload.');
15603 }
15604
15605 var needsRender = false;
15606 var needsRemount = false;
15607
15608 if (candidateType !== null) {
15609 var family = resolveFamily(candidateType);
15610
15611 if (family !== undefined) {
15612 if (staleFamilies.has(family)) {
15613 needsRemount = true;
15614 } else if (updatedFamilies.has(family)) {
15615 if (tag === ClassComponent) {
15616 needsRemount = true;
15617 } else {
15618 needsRender = true;
15619 }
15620 }
15621 }
15622 }
15623
15624 if (failedBoundaries !== null) {
15625 if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) {
15626 needsRemount = true;
15627 }
15628 }
15629
15630 if (needsRemount) {
15631 fiber._debugNeedsRemount = true;
15632 }
15633
15634 if (needsRemount || needsRender) {
15635 scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
15636 }
15637
15638 if (child !== null && !needsRemount) {
15639 scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies);
15640 }
15641
15642 if (sibling !== null) {
15643 scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies);
15644 }
15645 }
15646 }
15647
15648 var findHostInstancesForRefresh = function (root, families) {
15649 {
15650 var hostInstances = new Set();
15651 var types = new Set(families.map(function (family) {
15652 return family.current;
15653 }));
15654 findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances);
15655 return hostInstances;
15656 }
15657 };
15658
15659 function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) {
15660 {
15661 var child = fiber.child,
15662 sibling = fiber.sibling,
15663 tag = fiber.tag,
15664 type = fiber.type;
15665 var candidateType = null;
15666
15667 switch (tag) {
15668 case FunctionComponent:
15669 case SimpleMemoComponent:
15670 case ClassComponent:
15671 candidateType = type;
15672 break;
15673
15674 case ForwardRef:
15675 candidateType = type.render;
15676 break;
15677 }
15678
15679 var didMatch = false;
15680
15681 if (candidateType !== null) {
15682 if (types.has(candidateType)) {
15683 didMatch = true;
15684 }
15685 }
15686
15687 if (didMatch) {
15688 // We have a match. This only drills down to the closest host components.
15689 // There's no need to search deeper because for the purpose of giving
15690 // visual feedback, "flashing" outermost parent rectangles is sufficient.
15691 findHostInstancesForFiberShallowly(fiber, hostInstances);
15692 } else {
15693 // If there's no match, maybe there will be one further down in the child tree.
15694 if (child !== null) {
15695 findHostInstancesForMatchingFibersRecursively(child, types, hostInstances);
15696 }
15697 }
15698
15699 if (sibling !== null) {
15700 findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances);
15701 }
15702 }
15703 }
15704
15705 function findHostInstancesForFiberShallowly(fiber, hostInstances) {
15706 {
15707 var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances);
15708
15709 if (foundHostInstances) {
15710 return;
15711 } // If we didn't find any host children, fallback to closest host parent.
15712
15713
15714 var node = fiber;
15715
15716 while (true) {
15717 switch (node.tag) {
15718 case HostComponent:
15719 hostInstances.add(node.stateNode);
15720 return;
15721
15722 case HostPortal:
15723 hostInstances.add(node.stateNode.containerInfo);
15724 return;
15725
15726 case HostRoot:
15727 hostInstances.add(node.stateNode.containerInfo);
15728 return;
15729 }
15730
15731 if (node.return === null) {
15732 throw new Error('Expected to reach root first.');
15733 }
15734
15735 node = node.return;
15736 }
15737 }
15738 }
15739
15740 function findChildHostInstancesForFiberShallowly(fiber, hostInstances) {
15741 {
15742 var node = fiber;
15743 var foundHostInstances = false;
15744
15745 while (true) {
15746 if (node.tag === HostComponent) {
15747 // We got a match.
15748 foundHostInstances = true;
15749 hostInstances.add(node.stateNode); // There may still be more, so keep searching.
15750 } else if (node.child !== null) {
15751 node.child.return = node;
15752 node = node.child;
15753 continue;
15754 }
15755
15756 if (node === fiber) {
15757 return foundHostInstances;
15758 }
15759
15760 while (node.sibling === null) {
15761 if (node.return === null || node.return === fiber) {
15762 return foundHostInstances;
15763 }
15764
15765 node = node.return;
15766 }
15767
15768 node.sibling.return = node.return;
15769 node = node.sibling;
15770 }
15771 }
15772
15773 return false;
15774 }
15775
15776 var hasBadMapPolyfill;
15777
15778 {
15779 hasBadMapPolyfill = false;
15780
15781 try {
15782 var nonExtensibleObject = Object.preventExtensions({});
15783 /* eslint-disable no-new */
15784
15785 new Map([[nonExtensibleObject, null]]);
15786 new Set([nonExtensibleObject]);
15787 /* eslint-enable no-new */
15788 } catch (e) {
15789 // TODO: Consider warning about bad polyfills
15790 hasBadMapPolyfill = true;
15791 }
15792 }
15793
15794 var debugCounter = 1;
15795
15796 function FiberNode(tag, pendingProps, key, mode) {
15797 // Instance
15798 this.tag = tag;
15799 this.key = key;
15800 this.elementType = null;
15801 this.type = null;
15802 this.stateNode = null; // Fiber
15803
15804 this.return = null;
15805 this.child = null;
15806 this.sibling = null;
15807 this.index = 0;
15808 this.ref = null;
15809 this.pendingProps = pendingProps;
15810 this.memoizedProps = null;
15811 this.updateQueue = null;
15812 this.memoizedState = null;
15813 this.dependencies = null;
15814 this.mode = mode; // Effects
15815
15816 this.flags = NoFlags;
15817 this.nextEffect = null;
15818 this.firstEffect = null;
15819 this.lastEffect = null;
15820 this.lanes = NoLanes;
15821 this.childLanes = NoLanes;
15822 this.alternate = null;
15823
15824 {
15825 // Note: The following is done to avoid a v8 performance cliff.
15826 //
15827 // Initializing the fields below to smis and later updating them with
15828 // double values will cause Fibers to end up having separate shapes.
15829 // This behavior/bug has something to do with Object.preventExtension().
15830 // Fortunately this only impacts DEV builds.
15831 // Unfortunately it makes React unusably slow for some applications.
15832 // To work around this, initialize the fields below with doubles.
15833 //
15834 // Learn more about this here:
15835 // https://github.com/facebook/react/issues/14365
15836 // https://bugs.chromium.org/p/v8/issues/detail?id=8538
15837 this.actualDuration = Number.NaN;
15838 this.actualStartTime = Number.NaN;
15839 this.selfBaseDuration = Number.NaN;
15840 this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization.
15841 // This won't trigger the performance cliff mentioned above,
15842 // and it simplifies other profiler code (including DevTools).
15843
15844 this.actualDuration = 0;
15845 this.actualStartTime = -1;
15846 this.selfBaseDuration = 0;
15847 this.treeBaseDuration = 0;
15848 }
15849
15850 {
15851 // This isn't directly used but is handy for debugging internals:
15852 this._debugID = debugCounter++;
15853 this._debugSource = null;
15854 this._debugOwner = null;
15855 this._debugNeedsRemount = false;
15856 this._debugHookTypes = null;
15857
15858 if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
15859 Object.preventExtensions(this);
15860 }
15861 }
15862 } // This is a constructor function, rather than a POJO constructor, still
15863 // please ensure we do the following:
15864 // 1) Nobody should add any instance methods on this. Instance methods can be
15865 // more difficult to predict when they get optimized and they are almost
15866 // never inlined properly in static compilers.
15867 // 2) Nobody should rely on `instanceof Fiber` for type testing. We should
15868 // always know when it is a fiber.
15869 // 3) We might want to experiment with using numeric keys since they are easier
15870 // to optimize in a non-JIT environment.
15871 // 4) We can easily go from a constructor to a createFiber object literal if that
15872 // is faster.
15873 // 5) It should be easy to port this to a C struct and keep a C implementation
15874 // compatible.
15875
15876
15877 var createFiber = function (tag, pendingProps, key, mode) {
15878 // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
15879 return new FiberNode(tag, pendingProps, key, mode);
15880 };
15881
15882 function shouldConstruct$1(Component) {
15883 var prototype = Component.prototype;
15884 return !!(prototype && prototype.isReactComponent);
15885 }
15886
15887 function isSimpleFunctionComponent(type) {
15888 return typeof type === 'function' && !shouldConstruct$1(type) && type.defaultProps === undefined;
15889 }
15890 function resolveLazyComponentTag(Component) {
15891 if (typeof Component === 'function') {
15892 return shouldConstruct$1(Component) ? ClassComponent : FunctionComponent;
15893 } else if (Component !== undefined && Component !== null) {
15894 var $$typeof = Component.$$typeof;
15895
15896 if ($$typeof === REACT_FORWARD_REF_TYPE) {
15897 return ForwardRef;
15898 }
15899
15900 if ($$typeof === REACT_MEMO_TYPE) {
15901 return MemoComponent;
15902 }
15903 }
15904
15905 return IndeterminateComponent;
15906 } // This is used to create an alternate fiber to do work on.
15907
15908 function createWorkInProgress(current, pendingProps) {
15909 var workInProgress = current.alternate;
15910
15911 if (workInProgress === null) {
15912 // We use a double buffering pooling technique because we know that we'll
15913 // only ever need at most two versions of a tree. We pool the "other" unused
15914 // node that we're free to reuse. This is lazily created to avoid allocating
15915 // extra objects for things that are never updated. It also allow us to
15916 // reclaim the extra memory if needed.
15917 workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
15918 workInProgress.elementType = current.elementType;
15919 workInProgress.type = current.type;
15920 workInProgress.stateNode = current.stateNode;
15921
15922 {
15923 // DEV-only fields
15924 workInProgress._debugID = current._debugID;
15925 workInProgress._debugSource = current._debugSource;
15926 workInProgress._debugOwner = current._debugOwner;
15927 workInProgress._debugHookTypes = current._debugHookTypes;
15928 }
15929
15930 workInProgress.alternate = current;
15931 current.alternate = workInProgress;
15932 } else {
15933 workInProgress.pendingProps = pendingProps; // Needed because Blocks store data on type.
15934
15935 workInProgress.type = current.type; // We already have an alternate.
15936 // Reset the effect tag.
15937
15938 workInProgress.flags = NoFlags; // The effect list is no longer valid.
15939
15940 workInProgress.nextEffect = null;
15941 workInProgress.firstEffect = null;
15942 workInProgress.lastEffect = null;
15943
15944 {
15945 // We intentionally reset, rather than copy, actualDuration & actualStartTime.
15946 // This prevents time from endlessly accumulating in new commits.
15947 // This has the downside of resetting values for different priority renders,
15948 // But works for yielding (the common case) and should support resuming.
15949 workInProgress.actualDuration = 0;
15950 workInProgress.actualStartTime = -1;
15951 }
15952 }
15953
15954 workInProgress.childLanes = current.childLanes;
15955 workInProgress.lanes = current.lanes;
15956 workInProgress.child = current.child;
15957 workInProgress.memoizedProps = current.memoizedProps;
15958 workInProgress.memoizedState = current.memoizedState;
15959 workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
15960 // it cannot be shared with the current fiber.
15961
15962 var currentDependencies = current.dependencies;
15963 workInProgress.dependencies = currentDependencies === null ? null : {
15964 lanes: currentDependencies.lanes,
15965 firstContext: currentDependencies.firstContext
15966 }; // These will be overridden during the parent's reconciliation
15967
15968 workInProgress.sibling = current.sibling;
15969 workInProgress.index = current.index;
15970 workInProgress.ref = current.ref;
15971
15972 {
15973 workInProgress.selfBaseDuration = current.selfBaseDuration;
15974 workInProgress.treeBaseDuration = current.treeBaseDuration;
15975 }
15976
15977 {
15978 workInProgress._debugNeedsRemount = current._debugNeedsRemount;
15979
15980 switch (workInProgress.tag) {
15981 case IndeterminateComponent:
15982 case FunctionComponent:
15983 case SimpleMemoComponent:
15984 workInProgress.type = resolveFunctionForHotReloading(current.type);
15985 break;
15986
15987 case ClassComponent:
15988 workInProgress.type = resolveClassForHotReloading(current.type);
15989 break;
15990
15991 case ForwardRef:
15992 workInProgress.type = resolveForwardRefForHotReloading(current.type);
15993 break;
15994 }
15995 }
15996
15997 return workInProgress;
15998 } // Used to reuse a Fiber for a second pass.
15999
16000 function resetWorkInProgress(workInProgress, renderLanes) {
16001 // This resets the Fiber to what createFiber or createWorkInProgress would
16002 // have set the values to before during the first pass. Ideally this wouldn't
16003 // be necessary but unfortunately many code paths reads from the workInProgress
16004 // when they should be reading from current and writing to workInProgress.
16005 // We assume pendingProps, index, key, ref, return are still untouched to
16006 // avoid doing another reconciliation.
16007 // Reset the effect tag but keep any Placement tags, since that's something
16008 // that child fiber is setting, not the reconciliation.
16009 workInProgress.flags &= Placement; // The effect list is no longer valid.
16010
16011 workInProgress.nextEffect = null;
16012 workInProgress.firstEffect = null;
16013 workInProgress.lastEffect = null;
16014 var current = workInProgress.alternate;
16015
16016 if (current === null) {
16017 // Reset to createFiber's initial values.
16018 workInProgress.childLanes = NoLanes;
16019 workInProgress.lanes = renderLanes;
16020 workInProgress.child = null;
16021 workInProgress.memoizedProps = null;
16022 workInProgress.memoizedState = null;
16023 workInProgress.updateQueue = null;
16024 workInProgress.dependencies = null;
16025 workInProgress.stateNode = null;
16026
16027 {
16028 // Note: We don't reset the actualTime counts. It's useful to accumulate
16029 // actual time across multiple render passes.
16030 workInProgress.selfBaseDuration = 0;
16031 workInProgress.treeBaseDuration = 0;
16032 }
16033 } else {
16034 // Reset to the cloned values that createWorkInProgress would've.
16035 workInProgress.childLanes = current.childLanes;
16036 workInProgress.lanes = current.lanes;
16037 workInProgress.child = current.child;
16038 workInProgress.memoizedProps = current.memoizedProps;
16039 workInProgress.memoizedState = current.memoizedState;
16040 workInProgress.updateQueue = current.updateQueue; // Needed because Blocks store data on type.
16041
16042 workInProgress.type = current.type; // Clone the dependencies object. This is mutated during the render phase, so
16043 // it cannot be shared with the current fiber.
16044
16045 var currentDependencies = current.dependencies;
16046 workInProgress.dependencies = currentDependencies === null ? null : {
16047 lanes: currentDependencies.lanes,
16048 firstContext: currentDependencies.firstContext
16049 };
16050
16051 {
16052 // Note: We don't reset the actualTime counts. It's useful to accumulate
16053 // actual time across multiple render passes.
16054 workInProgress.selfBaseDuration = current.selfBaseDuration;
16055 workInProgress.treeBaseDuration = current.treeBaseDuration;
16056 }
16057 }
16058
16059 return workInProgress;
16060 }
16061 function createHostRootFiber(tag) {
16062 var mode;
16063
16064 if (tag === ConcurrentRoot) {
16065 mode = ConcurrentMode | BlockingMode | StrictMode;
16066 } else if (tag === BlockingRoot) {
16067 mode = BlockingMode | StrictMode;
16068 } else {
16069 mode = NoMode;
16070 }
16071
16072 if ( isDevToolsPresent) {
16073 // Always collect profile timings when DevTools are present.
16074 // This enables DevTools to start capturing timing at any point–
16075 // Without some nodes in the tree having empty base times.
16076 mode |= ProfileMode;
16077 }
16078
16079 return createFiber(HostRoot, null, null, mode);
16080 }
16081 function createFiberFromTypeAndProps(type, // React$ElementType
16082 key, pendingProps, owner, mode, lanes) {
16083 var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
16084
16085 var resolvedType = type;
16086
16087 if (typeof type === 'function') {
16088 if (shouldConstruct$1(type)) {
16089 fiberTag = ClassComponent;
16090
16091 {
16092 resolvedType = resolveClassForHotReloading(resolvedType);
16093 }
16094 } else {
16095 {
16096 resolvedType = resolveFunctionForHotReloading(resolvedType);
16097 }
16098 }
16099 } else if (typeof type === 'string') {
16100 fiberTag = HostComponent;
16101 } else {
16102 getTag: switch (type) {
16103 case REACT_FRAGMENT_TYPE:
16104 return createFiberFromFragment(pendingProps.children, mode, lanes, key);
16105
16106 case REACT_DEBUG_TRACING_MODE_TYPE:
16107 fiberTag = Mode;
16108 mode |= DebugTracingMode;
16109 break;
16110
16111 case REACT_STRICT_MODE_TYPE:
16112 fiberTag = Mode;
16113 mode |= StrictMode;
16114 break;
16115
16116 case REACT_PROFILER_TYPE:
16117 return createFiberFromProfiler(pendingProps, mode, lanes, key);
16118
16119 case REACT_SUSPENSE_TYPE:
16120 return createFiberFromSuspense(pendingProps, mode, lanes, key);
16121
16122 case REACT_SUSPENSE_LIST_TYPE:
16123 return createFiberFromSuspenseList(pendingProps, mode, lanes, key);
16124
16125 case REACT_OFFSCREEN_TYPE:
16126 return createFiberFromOffscreen(pendingProps, mode, lanes, key);
16127
16128 case REACT_LEGACY_HIDDEN_TYPE:
16129 return createFiberFromLegacyHidden(pendingProps, mode, lanes, key);
16130
16131 case REACT_SCOPE_TYPE:
16132
16133 // eslint-disable-next-line no-fallthrough
16134
16135 default:
16136 {
16137 if (typeof type === 'object' && type !== null) {
16138 switch (type.$$typeof) {
16139 case REACT_PROVIDER_TYPE:
16140 fiberTag = ContextProvider;
16141 break getTag;
16142
16143 case REACT_CONTEXT_TYPE:
16144 // This is a consumer
16145 fiberTag = ContextConsumer;
16146 break getTag;
16147
16148 case REACT_FORWARD_REF_TYPE:
16149 fiberTag = ForwardRef;
16150
16151 {
16152 resolvedType = resolveForwardRefForHotReloading(resolvedType);
16153 }
16154
16155 break getTag;
16156
16157 case REACT_MEMO_TYPE:
16158 fiberTag = MemoComponent;
16159 break getTag;
16160
16161 case REACT_LAZY_TYPE:
16162 fiberTag = LazyComponent;
16163 resolvedType = null;
16164 break getTag;
16165
16166 case REACT_BLOCK_TYPE:
16167 fiberTag = Block;
16168 break getTag;
16169 }
16170 }
16171
16172 var info = '';
16173
16174 {
16175 if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
16176 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.';
16177 }
16178
16179 var ownerName = owner ? getComponentName(owner.type) : null;
16180
16181 if (ownerName) {
16182 info += '\n\nCheck the render method of `' + ownerName + '`.';
16183 }
16184 }
16185
16186 {
16187 {
16188 throw Error( "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + (type == null ? type : typeof type) + "." + info );
16189 }
16190 }
16191 }
16192 }
16193 }
16194
16195 var fiber = createFiber(fiberTag, pendingProps, key, mode);
16196 fiber.elementType = type;
16197 fiber.type = resolvedType;
16198 fiber.lanes = lanes;
16199
16200 {
16201 fiber._debugOwner = owner;
16202 }
16203
16204 return fiber;
16205 }
16206 function createFiberFromElement(element, mode, lanes) {
16207 var owner = null;
16208
16209 {
16210 owner = element._owner;
16211 }
16212
16213 var type = element.type;
16214 var key = element.key;
16215 var pendingProps = element.props;
16216 var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes);
16217
16218 {
16219 fiber._debugSource = element._source;
16220 fiber._debugOwner = element._owner;
16221 }
16222
16223 return fiber;
16224 }
16225 function createFiberFromFragment(elements, mode, lanes, key) {
16226 var fiber = createFiber(Fragment, elements, key, mode);
16227 fiber.lanes = lanes;
16228 return fiber;
16229 }
16230
16231 function createFiberFromProfiler(pendingProps, mode, lanes, key) {
16232 {
16233 if (typeof pendingProps.id !== 'string') {
16234 error('Profiler must specify an "id" as a prop');
16235 }
16236 }
16237
16238 var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); // TODO: The Profiler fiber shouldn't have a type. It has a tag.
16239
16240 fiber.elementType = REACT_PROFILER_TYPE;
16241 fiber.type = REACT_PROFILER_TYPE;
16242 fiber.lanes = lanes;
16243
16244 {
16245 fiber.stateNode = {
16246 effectDuration: 0,
16247 passiveEffectDuration: 0
16248 };
16249 }
16250
16251 return fiber;
16252 }
16253
16254 function createFiberFromSuspense(pendingProps, mode, lanes, key) {
16255 var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
16256 // This needs to be fixed in getComponentName so that it relies on the tag
16257 // instead.
16258
16259 fiber.type = REACT_SUSPENSE_TYPE;
16260 fiber.elementType = REACT_SUSPENSE_TYPE;
16261 fiber.lanes = lanes;
16262 return fiber;
16263 }
16264 function createFiberFromSuspenseList(pendingProps, mode, lanes, key) {
16265 var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);
16266
16267 {
16268 // TODO: The SuspenseListComponent fiber shouldn't have a type. It has a tag.
16269 // This needs to be fixed in getComponentName so that it relies on the tag
16270 // instead.
16271 fiber.type = REACT_SUSPENSE_LIST_TYPE;
16272 }
16273
16274 fiber.elementType = REACT_SUSPENSE_LIST_TYPE;
16275 fiber.lanes = lanes;
16276 return fiber;
16277 }
16278 function createFiberFromOffscreen(pendingProps, mode, lanes, key) {
16279 var fiber = createFiber(OffscreenComponent, pendingProps, key, mode); // TODO: The OffscreenComponent fiber shouldn't have a type. It has a tag.
16280 // This needs to be fixed in getComponentName so that it relies on the tag
16281 // instead.
16282
16283 {
16284 fiber.type = REACT_OFFSCREEN_TYPE;
16285 }
16286
16287 fiber.elementType = REACT_OFFSCREEN_TYPE;
16288 fiber.lanes = lanes;
16289 return fiber;
16290 }
16291 function createFiberFromLegacyHidden(pendingProps, mode, lanes, key) {
16292 var fiber = createFiber(LegacyHiddenComponent, pendingProps, key, mode); // TODO: The LegacyHidden fiber shouldn't have a type. It has a tag.
16293 // This needs to be fixed in getComponentName so that it relies on the tag
16294 // instead.
16295
16296 {
16297 fiber.type = REACT_LEGACY_HIDDEN_TYPE;
16298 }
16299
16300 fiber.elementType = REACT_LEGACY_HIDDEN_TYPE;
16301 fiber.lanes = lanes;
16302 return fiber;
16303 }
16304 function createFiberFromText(content, mode, lanes) {
16305 var fiber = createFiber(HostText, content, null, mode);
16306 fiber.lanes = lanes;
16307 return fiber;
16308 }
16309 function createFiberFromPortal(portal, mode, lanes) {
16310 var pendingProps = portal.children !== null ? portal.children : [];
16311 var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
16312 fiber.lanes = lanes;
16313 fiber.stateNode = {
16314 containerInfo: portal.containerInfo,
16315 pendingChildren: null,
16316 // Used by persistent updates
16317 implementation: portal.implementation
16318 };
16319 return fiber;
16320 } // Used for stashing WIP properties to replay failed work in DEV.
16321
16322 function FiberRootNode(containerInfo, tag, hydrate) {
16323 this.tag = tag;
16324 this.containerInfo = containerInfo;
16325 this.pendingChildren = null;
16326 this.current = null;
16327 this.pingCache = null;
16328 this.finishedWork = null;
16329 this.timeoutHandle = noTimeout;
16330 this.context = null;
16331 this.pendingContext = null;
16332 this.hydrate = hydrate;
16333 this.callbackNode = null;
16334 this.callbackPriority = NoLanePriority;
16335 this.eventTimes = createLaneMap(NoLanes);
16336 this.expirationTimes = createLaneMap(NoTimestamp);
16337 this.pendingLanes = NoLanes;
16338 this.suspendedLanes = NoLanes;
16339 this.pingedLanes = NoLanes;
16340 this.expiredLanes = NoLanes;
16341 this.mutableReadLanes = NoLanes;
16342 this.finishedLanes = NoLanes;
16343 this.entangledLanes = NoLanes;
16344 this.entanglements = createLaneMap(NoLanes);
16345
16346 {
16347 this.interactionThreadID = unstable_getThreadID();
16348 this.memoizedInteractions = new Set();
16349 this.pendingInteractionMap = new Map();
16350 }
16351
16352 {
16353 switch (tag) {
16354 case BlockingRoot:
16355 this._debugRootType = 'createBlockingRoot()';
16356 break;
16357
16358 case ConcurrentRoot:
16359 this._debugRootType = 'createRoot()';
16360 break;
16361
16362 case LegacyRoot:
16363 this._debugRootType = 'createLegacyRoot()';
16364 break;
16365 }
16366 }
16367 }
16368
16369 function createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks) {
16370 var root = new FiberRootNode(containerInfo, tag, hydrate);
16371 // stateNode is any.
16372
16373
16374 var uninitializedFiber = createHostRootFiber(tag);
16375 root.current = uninitializedFiber;
16376 uninitializedFiber.stateNode = root;
16377 initializeUpdateQueue(uninitializedFiber);
16378 return root;
16379 }
16380
16381 var didWarnAboutNestedUpdates;
16382
16383 {
16384 didWarnAboutNestedUpdates = false;
16385 }
16386
16387 function getContextForSubtree(parentComponent) {
16388 if (!parentComponent) {
16389 return emptyContextObject;
16390 }
16391
16392 var fiber = get(parentComponent);
16393 var parentContext = findCurrentUnmaskedContext(fiber);
16394
16395 if (fiber.tag === ClassComponent) {
16396 var Component = fiber.type;
16397
16398 if (isContextProvider(Component)) {
16399 return processChildContext(fiber, Component, parentContext);
16400 }
16401 }
16402
16403 return parentContext;
16404 }
16405
16406 function createContainer(containerInfo, tag, hydrate, hydrationCallbacks) {
16407 return createFiberRoot(containerInfo, tag, hydrate);
16408 }
16409 function updateContainer(element, container, parentComponent, callback) {
16410 {
16411 onScheduleRoot(container, element);
16412 }
16413
16414 var current$1 = container.current;
16415 var eventTime = requestEventTime();
16416
16417 {
16418 // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
16419 if ('undefined' !== typeof jest) {
16420 warnIfUnmockedScheduler(current$1);
16421 warnIfNotScopedWithMatchingAct(current$1);
16422 }
16423 }
16424
16425 var lane = requestUpdateLane(current$1);
16426
16427 var context = getContextForSubtree(parentComponent);
16428
16429 if (container.context === null) {
16430 container.context = context;
16431 } else {
16432 container.pendingContext = context;
16433 }
16434
16435 {
16436 if (isRendering && current !== null && !didWarnAboutNestedUpdates) {
16437 didWarnAboutNestedUpdates = true;
16438
16439 error('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');
16440 }
16441 }
16442
16443 var update = createUpdate(eventTime, lane); // Caution: React DevTools currently depends on this property
16444 // being called "element".
16445
16446 update.payload = {
16447 element: element
16448 };
16449 callback = callback === undefined ? null : callback;
16450
16451 if (callback !== null) {
16452 {
16453 if (typeof callback !== 'function') {
16454 error('render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback);
16455 }
16456 }
16457
16458 update.callback = callback;
16459 }
16460
16461 enqueueUpdate(current$1, update);
16462 scheduleUpdateOnFiber(current$1, lane, eventTime);
16463 return lane;
16464 }
16465 function getPublicRootInstance(container) {
16466 var containerFiber = container.current;
16467
16468 if (!containerFiber.child) {
16469 return null;
16470 }
16471
16472 switch (containerFiber.child.tag) {
16473 case HostComponent:
16474 return getPublicInstance(containerFiber.child.stateNode);
16475
16476 default:
16477 return containerFiber.child.stateNode;
16478 }
16479 }
16480
16481 var shouldSuspendImpl = function (fiber) {
16482 return false;
16483 };
16484
16485 function shouldSuspend(fiber) {
16486 return shouldSuspendImpl(fiber);
16487 }
16488 var overrideHookState = null;
16489 var overrideHookStateDeletePath = null;
16490 var overrideHookStateRenamePath = null;
16491 var overrideProps = null;
16492 var overridePropsDeletePath = null;
16493 var overridePropsRenamePath = null;
16494 var scheduleUpdate = null;
16495 var setSuspenseHandler = null;
16496
16497 {
16498 var copyWithDeleteImpl = function (obj, path, index) {
16499 var key = path[index];
16500 var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj);
16501
16502 if (index + 1 === path.length) {
16503 if (Array.isArray(updated)) {
16504 updated.splice(key, 1);
16505 } else {
16506 delete updated[key];
16507 }
16508
16509 return updated;
16510 } // $FlowFixMe number or string is fine here
16511
16512
16513 updated[key] = copyWithDeleteImpl(obj[key], path, index + 1);
16514 return updated;
16515 };
16516
16517 var copyWithDelete = function (obj, path) {
16518 return copyWithDeleteImpl(obj, path, 0);
16519 };
16520
16521 var copyWithRenameImpl = function (obj, oldPath, newPath, index) {
16522 var oldKey = oldPath[index];
16523 var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj);
16524
16525 if (index + 1 === oldPath.length) {
16526 var newKey = newPath[index]; // $FlowFixMe number or string is fine here
16527
16528 updated[newKey] = updated[oldKey];
16529
16530 if (Array.isArray(updated)) {
16531 updated.splice(oldKey, 1);
16532 } else {
16533 delete updated[oldKey];
16534 }
16535 } else {
16536 // $FlowFixMe number or string is fine here
16537 updated[oldKey] = copyWithRenameImpl( // $FlowFixMe number or string is fine here
16538 obj[oldKey], oldPath, newPath, index + 1);
16539 }
16540
16541 return updated;
16542 };
16543
16544 var copyWithRename = function (obj, oldPath, newPath) {
16545 if (oldPath.length !== newPath.length) {
16546 warn('copyWithRename() expects paths of the same length');
16547
16548 return;
16549 } else {
16550 for (var i = 0; i < newPath.length - 1; i++) {
16551 if (oldPath[i] !== newPath[i]) {
16552 warn('copyWithRename() expects paths to be the same except for the deepest key');
16553
16554 return;
16555 }
16556 }
16557 }
16558
16559 return copyWithRenameImpl(obj, oldPath, newPath, 0);
16560 };
16561
16562 var copyWithSetImpl = function (obj, path, index, value) {
16563 if (index >= path.length) {
16564 return value;
16565 }
16566
16567 var key = path[index];
16568 var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj); // $FlowFixMe number or string is fine here
16569
16570 updated[key] = copyWithSetImpl(obj[key], path, index + 1, value);
16571 return updated;
16572 };
16573
16574 var copyWithSet = function (obj, path, value) {
16575 return copyWithSetImpl(obj, path, 0, value);
16576 };
16577
16578 var findHook = function (fiber, id) {
16579 // For now, the "id" of stateful hooks is just the stateful hook index.
16580 // This may change in the future with e.g. nested hooks.
16581 var currentHook = fiber.memoizedState;
16582
16583 while (currentHook !== null && id > 0) {
16584 currentHook = currentHook.next;
16585 id--;
16586 }
16587
16588 return currentHook;
16589 }; // Support DevTools editable values for useState and useReducer.
16590
16591
16592 overrideHookState = function (fiber, id, path, value) {
16593 var hook = findHook(fiber, id);
16594
16595 if (hook !== null) {
16596 var newState = copyWithSet(hook.memoizedState, path, value);
16597 hook.memoizedState = newState;
16598 hook.baseState = newState; // We aren't actually adding an update to the queue,
16599 // because there is no update we can add for useReducer hooks that won't trigger an error.
16600 // (There's no appropriate action type for DevTools overrides.)
16601 // As a result though, React will see the scheduled update as a noop and bailout.
16602 // Shallow cloning props works as a workaround for now to bypass the bailout check.
16603
16604 fiber.memoizedProps = _assign({}, fiber.memoizedProps);
16605 scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
16606 }
16607 };
16608
16609 overrideHookStateDeletePath = function (fiber, id, path) {
16610 var hook = findHook(fiber, id);
16611
16612 if (hook !== null) {
16613 var newState = copyWithDelete(hook.memoizedState, path);
16614 hook.memoizedState = newState;
16615 hook.baseState = newState; // We aren't actually adding an update to the queue,
16616 // because there is no update we can add for useReducer hooks that won't trigger an error.
16617 // (There's no appropriate action type for DevTools overrides.)
16618 // As a result though, React will see the scheduled update as a noop and bailout.
16619 // Shallow cloning props works as a workaround for now to bypass the bailout check.
16620
16621 fiber.memoizedProps = _assign({}, fiber.memoizedProps);
16622 scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
16623 }
16624 };
16625
16626 overrideHookStateRenamePath = function (fiber, id, oldPath, newPath) {
16627 var hook = findHook(fiber, id);
16628
16629 if (hook !== null) {
16630 var newState = copyWithRename(hook.memoizedState, oldPath, newPath);
16631 hook.memoizedState = newState;
16632 hook.baseState = newState; // We aren't actually adding an update to the queue,
16633 // because there is no update we can add for useReducer hooks that won't trigger an error.
16634 // (There's no appropriate action type for DevTools overrides.)
16635 // As a result though, React will see the scheduled update as a noop and bailout.
16636 // Shallow cloning props works as a workaround for now to bypass the bailout check.
16637
16638 fiber.memoizedProps = _assign({}, fiber.memoizedProps);
16639 scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
16640 }
16641 }; // Support DevTools props for function components, forwardRef, memo, host components, etc.
16642
16643
16644 overrideProps = function (fiber, path, value) {
16645 fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
16646
16647 if (fiber.alternate) {
16648 fiber.alternate.pendingProps = fiber.pendingProps;
16649 }
16650
16651 scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
16652 };
16653
16654 overridePropsDeletePath = function (fiber, path) {
16655 fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path);
16656
16657 if (fiber.alternate) {
16658 fiber.alternate.pendingProps = fiber.pendingProps;
16659 }
16660
16661 scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
16662 };
16663
16664 overridePropsRenamePath = function (fiber, oldPath, newPath) {
16665 fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath);
16666
16667 if (fiber.alternate) {
16668 fiber.alternate.pendingProps = fiber.pendingProps;
16669 }
16670
16671 scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
16672 };
16673
16674 scheduleUpdate = function (fiber) {
16675 scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
16676 };
16677
16678 setSuspenseHandler = function (newShouldSuspendImpl) {
16679 shouldSuspendImpl = newShouldSuspendImpl;
16680 };
16681 }
16682
16683 function findHostInstanceByFiber(fiber) {
16684 var hostFiber = findCurrentHostFiber(fiber);
16685
16686 if (hostFiber === null) {
16687 return null;
16688 }
16689
16690 return hostFiber.stateNode;
16691 }
16692
16693 function emptyFindFiberByHostInstance(instance) {
16694 return null;
16695 }
16696
16697 function getCurrentFiberForDevTools() {
16698 return current;
16699 }
16700
16701 function injectIntoDevTools(devToolsConfig) {
16702 var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
16703 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
16704 return injectInternals({
16705 bundleType: devToolsConfig.bundleType,
16706 version: devToolsConfig.version,
16707 rendererPackageName: devToolsConfig.rendererPackageName,
16708 rendererConfig: devToolsConfig.rendererConfig,
16709 overrideHookState: overrideHookState,
16710 overrideHookStateDeletePath: overrideHookStateDeletePath,
16711 overrideHookStateRenamePath: overrideHookStateRenamePath,
16712 overrideProps: overrideProps,
16713 overridePropsDeletePath: overridePropsDeletePath,
16714 overridePropsRenamePath: overridePropsRenamePath,
16715 setSuspenseHandler: setSuspenseHandler,
16716 scheduleUpdate: scheduleUpdate,
16717 currentDispatcherRef: ReactCurrentDispatcher,
16718 findHostInstanceByFiber: findHostInstanceByFiber,
16719 findFiberByHostInstance: findFiberByHostInstance || emptyFindFiberByHostInstance,
16720 // React Refresh
16721 findHostInstancesForRefresh: findHostInstancesForRefresh ,
16722 scheduleRefresh: scheduleRefresh ,
16723 scheduleRoot: scheduleRoot ,
16724 setRefreshHandler: setRefreshHandler ,
16725 // Enables DevTools to append owner stacks to error messages in DEV mode.
16726 getCurrentFiber: getCurrentFiberForDevTools
16727 });
16728 }
16729
16730 var IsSomeRendererActing$1 = ReactSharedInternals.IsSomeRendererActing;
16731 var defaultTestOptions = {
16732 createNodeMock: function () {
16733 return null;
16734 }
16735 };
16736
16737 function toJSON(inst) {
16738 if (inst.isHidden) {
16739 // Omit timed out children from output entirely. This seems like the least
16740 // surprising behavior. We could perhaps add a separate API that includes
16741 // them, if it turns out people need it.
16742 return null;
16743 }
16744
16745 switch (inst.tag) {
16746 case 'TEXT':
16747 return inst.text;
16748
16749 case 'INSTANCE':
16750 {
16751 /* eslint-disable no-unused-vars */
16752 // We don't include the `children` prop in JSON.
16753 // Instead, we will include the actual rendered children.
16754 var _inst$props = inst.props,
16755 children = _inst$props.children,
16756 props = _objectWithoutPropertiesLoose(_inst$props, ["children"]);
16757 /* eslint-enable */
16758
16759
16760 var renderedChildren = null;
16761
16762 if (inst.children && inst.children.length) {
16763 for (var i = 0; i < inst.children.length; i++) {
16764 var renderedChild = toJSON(inst.children[i]);
16765
16766 if (renderedChild !== null) {
16767 if (renderedChildren === null) {
16768 renderedChildren = [renderedChild];
16769 } else {
16770 renderedChildren.push(renderedChild);
16771 }
16772 }
16773 }
16774 }
16775
16776 var json = {
16777 type: inst.type,
16778 props: props,
16779 children: renderedChildren
16780 };
16781 Object.defineProperty(json, '$$typeof', {
16782 value: Symbol.for('react.test.json')
16783 });
16784 return json;
16785 }
16786
16787 default:
16788 throw new Error("Unexpected node type in toJSON: " + inst.tag);
16789 }
16790 }
16791
16792 function childrenToTree(node) {
16793 if (!node) {
16794 return null;
16795 }
16796
16797 var children = nodeAndSiblingsArray(node);
16798
16799 if (children.length === 0) {
16800 return null;
16801 } else if (children.length === 1) {
16802 return toTree(children[0]);
16803 }
16804
16805 return flatten(children.map(toTree));
16806 }
16807
16808 function nodeAndSiblingsArray(nodeWithSibling) {
16809 var array = [];
16810 var node = nodeWithSibling;
16811
16812 while (node != null) {
16813 array.push(node);
16814 node = node.sibling;
16815 }
16816
16817 return array;
16818 }
16819
16820 function flatten(arr) {
16821 var result = [];
16822 var stack = [{
16823 i: 0,
16824 array: arr
16825 }];
16826
16827 while (stack.length) {
16828 var n = stack.pop();
16829
16830 while (n.i < n.array.length) {
16831 var el = n.array[n.i];
16832 n.i += 1;
16833
16834 if (Array.isArray(el)) {
16835 stack.push(n);
16836 stack.push({
16837 i: 0,
16838 array: el
16839 });
16840 break;
16841 }
16842
16843 result.push(el);
16844 }
16845 }
16846
16847 return result;
16848 }
16849
16850 function toTree(node) {
16851 if (node == null) {
16852 return null;
16853 }
16854
16855 switch (node.tag) {
16856 case HostRoot:
16857 return childrenToTree(node.child);
16858
16859 case HostPortal:
16860 return childrenToTree(node.child);
16861
16862 case ClassComponent:
16863 return {
16864 nodeType: 'component',
16865 type: node.type,
16866 props: _assign({}, node.memoizedProps),
16867 instance: node.stateNode,
16868 rendered: childrenToTree(node.child)
16869 };
16870
16871 case FunctionComponent:
16872 case SimpleMemoComponent:
16873 return {
16874 nodeType: 'component',
16875 type: node.type,
16876 props: _assign({}, node.memoizedProps),
16877 instance: null,
16878 rendered: childrenToTree(node.child)
16879 };
16880
16881 case Block:
16882 return {
16883 nodeType: 'block',
16884 type: node.type,
16885 props: _assign({}, node.memoizedProps),
16886 instance: null,
16887 rendered: childrenToTree(node.child)
16888 };
16889
16890 case HostComponent:
16891 {
16892 return {
16893 nodeType: 'host',
16894 type: node.type,
16895 props: _assign({}, node.memoizedProps),
16896 instance: null,
16897 // TODO: use createNodeMock here somehow?
16898 rendered: flatten(nodeAndSiblingsArray(node.child).map(toTree))
16899 };
16900 }
16901
16902 case HostText:
16903 return node.stateNode.text;
16904
16905 case Fragment:
16906 case ContextProvider:
16907 case ContextConsumer:
16908 case Mode:
16909 case Profiler:
16910 case ForwardRef:
16911 case MemoComponent:
16912 case IncompleteClassComponent:
16913 case ScopeComponent:
16914 return childrenToTree(node.child);
16915
16916 default:
16917 {
16918 {
16919 throw Error( "toTree() does not yet know how to handle nodes with tag=" + node.tag );
16920 }
16921 }
16922
16923 }
16924 }
16925
16926 var validWrapperTypes = new Set([FunctionComponent, ClassComponent, HostComponent, ForwardRef, MemoComponent, SimpleMemoComponent, Block, // Normally skipped, but used when there's more than one root child.
16927 HostRoot]);
16928
16929 function getChildren(parent) {
16930 var children = [];
16931 var startingNode = parent;
16932 var node = startingNode;
16933
16934 if (node.child === null) {
16935 return children;
16936 }
16937
16938 node.child.return = node;
16939 node = node.child;
16940
16941 outer: while (true) {
16942 var descend = false;
16943
16944 if (validWrapperTypes.has(node.tag)) {
16945 children.push(wrapFiber(node));
16946 } else if (node.tag === HostText) {
16947 children.push('' + node.memoizedProps);
16948 } else {
16949 descend = true;
16950 }
16951
16952 if (descend && node.child !== null) {
16953 node.child.return = node;
16954 node = node.child;
16955 continue;
16956 }
16957
16958 while (node.sibling === null) {
16959 if (node.return === startingNode) {
16960 break outer;
16961 }
16962
16963 node = node.return;
16964 }
16965
16966 node.sibling.return = node.return;
16967 node = node.sibling;
16968 }
16969
16970 return children;
16971 }
16972
16973 var ReactTestInstance = /*#__PURE__*/function () {
16974 var _proto = ReactTestInstance.prototype;
16975
16976 _proto._currentFiber = function _currentFiber() {
16977 // Throws if this component has been unmounted.
16978 var fiber = findCurrentFiberUsingSlowPath(this._fiber);
16979
16980 if (!(fiber !== null)) {
16981 {
16982 throw Error( "Can't read from currently-mounting component. This error is likely caused by a bug in React. Please file an issue." );
16983 }
16984 }
16985
16986 return fiber;
16987 };
16988
16989 function ReactTestInstance(fiber) {
16990 if (!validWrapperTypes.has(fiber.tag)) {
16991 {
16992 throw Error( "Unexpected object passed to ReactTestInstance constructor (tag: " + fiber.tag + "). This is probably a bug in React." );
16993 }
16994 }
16995
16996 this._fiber = fiber;
16997 }
16998
16999 // Custom search functions
17000 _proto.find = function find(predicate) {
17001 return expectOne(this.findAll(predicate, {
17002 deep: false
17003 }), "matching custom predicate: " + predicate.toString());
17004 };
17005
17006 _proto.findByType = function findByType(type) {
17007 return expectOne(this.findAllByType(type, {
17008 deep: false
17009 }), "with node type: \"" + (getComponentName(type) || 'Unknown') + "\"");
17010 };
17011
17012 _proto.findByProps = function findByProps(props) {
17013 return expectOne(this.findAllByProps(props, {
17014 deep: false
17015 }), "with props: " + JSON.stringify(props));
17016 };
17017
17018 _proto.findAll = function findAll(predicate) {
17019 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
17020 return _findAll(this, predicate, options);
17021 };
17022
17023 _proto.findAllByType = function findAllByType(type) {
17024 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
17025 return _findAll(this, function (node) {
17026 return node.type === type;
17027 }, options);
17028 };
17029
17030 _proto.findAllByProps = function findAllByProps(props) {
17031 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
17032 return _findAll(this, function (node) {
17033 return node.props && propsMatch(node.props, props);
17034 }, options);
17035 };
17036
17037 _createClass(ReactTestInstance, [{
17038 key: "instance",
17039 get: function () {
17040 if (this._fiber.tag === HostComponent) {
17041 return getPublicInstance(this._fiber.stateNode);
17042 } else {
17043 return this._fiber.stateNode;
17044 }
17045 }
17046 }, {
17047 key: "type",
17048 get: function () {
17049 return this._fiber.type;
17050 }
17051 }, {
17052 key: "props",
17053 get: function () {
17054 return this._currentFiber().memoizedProps;
17055 }
17056 }, {
17057 key: "parent",
17058 get: function () {
17059 var parent = this._fiber.return;
17060
17061 while (parent !== null) {
17062 if (validWrapperTypes.has(parent.tag)) {
17063 if (parent.tag === HostRoot) {
17064 // Special case: we only "materialize" instances for roots
17065 // if they have more than a single child. So we'll check that now.
17066 if (getChildren(parent).length < 2) {
17067 return null;
17068 }
17069 }
17070
17071 return wrapFiber(parent);
17072 }
17073
17074 parent = parent.return;
17075 }
17076
17077 return null;
17078 }
17079 }, {
17080 key: "children",
17081 get: function () {
17082 return getChildren(this._currentFiber());
17083 }
17084 }]);
17085
17086 return ReactTestInstance;
17087 }();
17088
17089 function _findAll(root, predicate, options) {
17090 var deep = options ? options.deep : true;
17091 var results = [];
17092
17093 if (predicate(root)) {
17094 results.push(root);
17095
17096 if (!deep) {
17097 return results;
17098 }
17099 }
17100
17101 root.children.forEach(function (child) {
17102 if (typeof child === 'string') {
17103 return;
17104 }
17105
17106 results.push.apply(results, _findAll(child, predicate, options));
17107 });
17108 return results;
17109 }
17110
17111 function expectOne(all, message) {
17112 if (all.length === 1) {
17113 return all[0];
17114 }
17115
17116 var prefix = all.length === 0 ? 'No instances found ' : "Expected 1 but found " + all.length + " instances ";
17117 throw new Error(prefix + message);
17118 }
17119
17120 function propsMatch(props, filter) {
17121 for (var key in filter) {
17122 if (props[key] !== filter[key]) {
17123 return false;
17124 }
17125 }
17126
17127 return true;
17128 }
17129
17130 function create(element, options) {
17131 var createNodeMock = defaultTestOptions.createNodeMock;
17132 var isConcurrent = false;
17133
17134 if (typeof options === 'object' && options !== null) {
17135 if (typeof options.createNodeMock === 'function') {
17136 createNodeMock = options.createNodeMock;
17137 }
17138
17139 if (options.unstable_isConcurrent === true) {
17140 isConcurrent = true;
17141 }
17142 }
17143
17144 var container = {
17145 children: [],
17146 createNodeMock: createNodeMock,
17147 tag: 'CONTAINER'
17148 };
17149 var root = createContainer(container, isConcurrent ? ConcurrentRoot : LegacyRoot, false);
17150
17151 if (!(root != null)) {
17152 {
17153 throw Error( "something went wrong" );
17154 }
17155 }
17156
17157 updateContainer(element, root, null, null);
17158 var entry = {
17159 _Scheduler: Scheduler,
17160 root: undefined,
17161 // makes flow happy
17162 // we define a 'getter' for 'root' below using 'Object.defineProperty'
17163 toJSON: function () {
17164 if (root == null || root.current == null || container == null) {
17165 return null;
17166 }
17167
17168 if (container.children.length === 0) {
17169 return null;
17170 }
17171
17172 if (container.children.length === 1) {
17173 return toJSON(container.children[0]);
17174 }
17175
17176 if (container.children.length === 2 && container.children[0].isHidden === true && container.children[1].isHidden === false) {
17177 // Omit timed out children from output entirely, including the fact that we
17178 // temporarily wrap fallback and timed out children in an array.
17179 return toJSON(container.children[1]);
17180 }
17181
17182 var renderedChildren = null;
17183
17184 if (container.children && container.children.length) {
17185 for (var i = 0; i < container.children.length; i++) {
17186 var renderedChild = toJSON(container.children[i]);
17187
17188 if (renderedChild !== null) {
17189 if (renderedChildren === null) {
17190 renderedChildren = [renderedChild];
17191 } else {
17192 renderedChildren.push(renderedChild);
17193 }
17194 }
17195 }
17196 }
17197
17198 return renderedChildren;
17199 },
17200 toTree: function () {
17201 if (root == null || root.current == null) {
17202 return null;
17203 }
17204
17205 return toTree(root.current);
17206 },
17207 update: function (newElement) {
17208 if (root == null || root.current == null) {
17209 return;
17210 }
17211
17212 updateContainer(newElement, root, null, null);
17213 },
17214 unmount: function () {
17215 if (root == null || root.current == null) {
17216 return;
17217 }
17218
17219 updateContainer(null, root, null, null);
17220 container = null;
17221 root = null;
17222 },
17223 getInstance: function () {
17224 if (root == null || root.current == null) {
17225 return null;
17226 }
17227
17228 return getPublicRootInstance(root);
17229 },
17230 unstable_flushSync: function (fn) {
17231 return flushSync(fn);
17232 }
17233 };
17234 Object.defineProperty(entry, 'root', {
17235 configurable: true,
17236 enumerable: true,
17237 get: function () {
17238 if (root === null) {
17239 throw new Error("Can't access .root on unmounted test renderer");
17240 }
17241
17242 var children = getChildren(root.current);
17243
17244 if (children.length === 0) {
17245 throw new Error("Can't access .root on unmounted test renderer");
17246 } else if (children.length === 1) {
17247 // Normally, we skip the root and just give you the child.
17248 return children[0];
17249 } else {
17250 // However, we give you the root if there's more than one root child.
17251 // We could make this the behavior for all cases but it would be a breaking change.
17252 return wrapFiber(root.current);
17253 }
17254 }
17255 });
17256 return entry;
17257 }
17258
17259 var fiberToWrapper = new WeakMap();
17260
17261 function wrapFiber(fiber) {
17262 var wrapper = fiberToWrapper.get(fiber);
17263
17264 if (wrapper === undefined && fiber.alternate !== null) {
17265 wrapper = fiberToWrapper.get(fiber.alternate);
17266 }
17267
17268 if (wrapper === undefined) {
17269 wrapper = new ReactTestInstance(fiber);
17270 fiberToWrapper.set(fiber, wrapper);
17271 }
17272
17273 return wrapper;
17274 } // Enable ReactTestRenderer to be used to test DevTools integration.
17275
17276
17277 injectIntoDevTools({
17278 findFiberByHostInstance: function () {
17279 throw new Error('TestRenderer does not support findFiberByHostInstance()');
17280 },
17281 bundleType: 1 ,
17282 version: ReactVersion,
17283 rendererPackageName: 'react-test-renderer'
17284 });
17285 var actingUpdatesScopeDepth$1 = 0; // This version of `act` is only used by our tests. Unlike the public version
17286 // of `act`, it's designed to work identically in both production and
17287 // development. It may have slightly different behavior from the public
17288 // version, too, since our constraints in our test suite are not the same as
17289 // those of developers using React — we're testing React itself, as opposed to
17290 // building an app with React.
17291 // TODO: Migrate our tests to use ReactNoop. Although we would need to figure
17292 // out a solution for Relay, which has some Concurrent Mode tests.
17293
17294 function unstable_concurrentAct(scope) {
17295 if (Scheduler.unstable_flushAllWithoutAsserting === undefined) {
17296 throw Error('This version of `act` requires a special mock build of Scheduler.');
17297 }
17298
17299 if (setTimeout._isMockFunction !== true) {
17300 throw Error("This version of `act` requires Jest's timer mocks " + '(i.e. jest.useFakeTimers).');
17301 }
17302
17303 var previousActingUpdatesScopeDepth = actingUpdatesScopeDepth$1;
17304 var previousIsSomeRendererActing = IsSomeRendererActing$1.current;
17305 var previousIsThisRendererActing = IsThisRendererActing.current;
17306 IsSomeRendererActing$1.current = true;
17307 IsThisRendererActing.current = true;
17308 actingUpdatesScopeDepth$1++;
17309
17310 var unwind = function () {
17311 actingUpdatesScopeDepth$1--;
17312 IsSomeRendererActing$1.current = previousIsSomeRendererActing;
17313 IsThisRendererActing.current = previousIsThisRendererActing;
17314
17315 {
17316 if (actingUpdatesScopeDepth$1 > previousActingUpdatesScopeDepth) {
17317 // if it's _less than_ previousActingUpdatesScopeDepth, then we can
17318 // assume the 'other' one has warned
17319 error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. ');
17320 }
17321 }
17322 }; // TODO: This would be way simpler if 1) we required a promise to be
17323 // returned and 2) we could use async/await. Since it's only our used in
17324 // our test suite, we should be able to.
17325
17326
17327 try {
17328 var thenable = batchedUpdates(scope);
17329
17330 if (typeof thenable === 'object' && thenable !== null && typeof thenable.then === 'function') {
17331 return {
17332 then: function (resolve, reject) {
17333 thenable.then(function () {
17334 flushActWork$1(function () {
17335 unwind();
17336 resolve();
17337 }, function (error) {
17338 unwind();
17339 reject(error);
17340 });
17341 }, function (error) {
17342 unwind();
17343 reject(error);
17344 });
17345 }
17346 };
17347 } else {
17348 try {
17349 // TODO: Let's not support non-async scopes at all in our tests. Need to
17350 // migrate existing tests.
17351 var didFlushWork;
17352
17353 do {
17354 didFlushWork = Scheduler.unstable_flushAllWithoutAsserting();
17355 } while (didFlushWork);
17356 } finally {
17357 unwind();
17358 }
17359 }
17360 } catch (error) {
17361 unwind();
17362 throw error;
17363 }
17364 }
17365
17366 function flushActWork$1(resolve, reject) {
17367 // Flush suspended fallbacks
17368 // $FlowFixMe: Flow doesn't know about global Jest object
17369 jest.runOnlyPendingTimers();
17370 enqueueTask(function () {
17371 try {
17372 var didFlushWork = Scheduler.unstable_flushAllWithoutAsserting();
17373
17374 if (didFlushWork) {
17375 flushActWork$1(resolve, reject);
17376 } else {
17377 resolve();
17378 }
17379 } catch (error) {
17380 reject(error);
17381 }
17382 });
17383 }
17384
17385 exports._Scheduler = Scheduler;
17386 exports.act = act;
17387 exports.create = create;
17388 exports.unstable_batchedUpdates = batchedUpdates;
17389 exports.unstable_concurrentAct = unstable_concurrentAct;
17390
17391})));