UNPKG

680 kBJavaScriptView Raw
1/** @license React v17.0.2
2 * react-art.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')) :
11 typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
12 (global = global || self, factory(global.ReactART = {}, global.React));
13}(this, (function (exports, React) { 'use strict';
14
15 function _extends() {
16 _extends = Object.assign || function (target) {
17 for (var i = 1; i < arguments.length; i++) {
18 var source = arguments[i];
19
20 for (var key in source) {
21 if (Object.prototype.hasOwnProperty.call(source, key)) {
22 target[key] = source[key];
23 }
24 }
25 }
26
27 return target;
28 };
29
30 return _extends.apply(this, arguments);
31 }
32
33 function _inheritsLoose(subClass, superClass) {
34 subClass.prototype = Object.create(superClass.prototype);
35 subClass.prototype.constructor = subClass;
36 subClass.__proto__ = superClass;
37 }
38
39 function _assertThisInitialized(self) {
40 if (self === void 0) {
41 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
42 }
43
44 return self;
45 }
46
47 // TODO: this is special because it gets imported during build.
48 var ReactVersion = '17.0.2';
49
50 var LegacyRoot = 0;
51 var BlockingRoot = 1;
52 var ConcurrentRoot = 2;
53
54 var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
55
56 // by calls to these methods by a Babel plugin.
57 //
58 // In PROD (or in packages without access to React internals),
59 // they are left as they are instead.
60
61 function warn(format) {
62 {
63 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
64 args[_key - 1] = arguments[_key];
65 }
66
67 printWarning('warn', format, args);
68 }
69 }
70 function error(format) {
71 {
72 for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
73 args[_key2 - 1] = arguments[_key2];
74 }
75
76 printWarning('error', format, args);
77 }
78 }
79
80 function printWarning(level, format, args) {
81 // When changing this logic, you might want to also
82 // update consoleWithStackDev.www.js as well.
83 {
84 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
85 var stack = ReactDebugCurrentFrame.getStackAddendum();
86
87 if (stack !== '') {
88 format += '%s';
89 args = args.concat([stack]);
90 }
91
92 var argsWithFormat = args.map(function (item) {
93 return '' + item;
94 }); // Careful: RN currently depends on this prefix
95
96 argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
97 // breaks IE9: https://github.com/facebook/react/issues/13610
98 // eslint-disable-next-line react-internal/no-production-logging
99
100 Function.prototype.apply.call(console[level], console, argsWithFormat);
101 }
102 }
103
104 var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
105 var _assign = ReactInternals.assign;
106
107 var FunctionComponent = 0;
108 var ClassComponent = 1;
109 var IndeterminateComponent = 2; // Before we know whether it is function or class
110
111 var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
112
113 var HostPortal = 4; // A subtree. Could be an entry point to a different renderer.
114
115 var HostComponent = 5;
116 var HostText = 6;
117 var Fragment = 7;
118 var Mode = 8;
119 var ContextConsumer = 9;
120 var ContextProvider = 10;
121 var ForwardRef = 11;
122 var Profiler = 12;
123 var SuspenseComponent = 13;
124 var MemoComponent = 14;
125 var SimpleMemoComponent = 15;
126 var LazyComponent = 16;
127 var IncompleteClassComponent = 17;
128 var DehydratedFragment = 18;
129 var SuspenseListComponent = 19;
130 var FundamentalComponent = 20;
131 var ScopeComponent = 21;
132 var Block = 22;
133 var OffscreenComponent = 23;
134 var LegacyHiddenComponent = 24;
135
136 /**
137 * `ReactInstanceMap` maintains a mapping from a public facing stateful
138 * instance (key) and the internal representation (value). This allows public
139 * methods to accept the user facing instance as an argument and map them back
140 * to internal methods.
141 *
142 * Note that this module is currently shared and assumed to be stateless.
143 * If this becomes an actual Map, that will break.
144 */
145 function get(key) {
146 return key._reactInternals;
147 }
148 function set(key, value) {
149 key._reactInternals = value;
150 }
151
152 // ATTENTION
153 // When adding new symbols to this file,
154 // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
155 // The Symbol used to tag the ReactElement-like types. If there is no native Symbol
156 // nor polyfill, then a plain number is used for performance.
157 var REACT_ELEMENT_TYPE = 0xeac7;
158 var REACT_PORTAL_TYPE = 0xeaca;
159 var REACT_FRAGMENT_TYPE = 0xeacb;
160 var REACT_STRICT_MODE_TYPE = 0xeacc;
161 var REACT_PROFILER_TYPE = 0xead2;
162 var REACT_PROVIDER_TYPE = 0xeacd;
163 var REACT_CONTEXT_TYPE = 0xeace;
164 var REACT_FORWARD_REF_TYPE = 0xead0;
165 var REACT_SUSPENSE_TYPE = 0xead1;
166 var REACT_SUSPENSE_LIST_TYPE = 0xead8;
167 var REACT_MEMO_TYPE = 0xead3;
168 var REACT_LAZY_TYPE = 0xead4;
169 var REACT_BLOCK_TYPE = 0xead9;
170 var REACT_SERVER_BLOCK_TYPE = 0xeada;
171 var REACT_FUNDAMENTAL_TYPE = 0xead5;
172 var REACT_SCOPE_TYPE = 0xead7;
173 var REACT_OPAQUE_ID_TYPE = 0xeae0;
174 var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1;
175 var REACT_OFFSCREEN_TYPE = 0xeae2;
176 var REACT_LEGACY_HIDDEN_TYPE = 0xeae3;
177
178 if (typeof Symbol === 'function' && Symbol.for) {
179 var symbolFor = Symbol.for;
180 REACT_ELEMENT_TYPE = symbolFor('react.element');
181 REACT_PORTAL_TYPE = symbolFor('react.portal');
182 REACT_FRAGMENT_TYPE = symbolFor('react.fragment');
183 REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode');
184 REACT_PROFILER_TYPE = symbolFor('react.profiler');
185 REACT_PROVIDER_TYPE = symbolFor('react.provider');
186 REACT_CONTEXT_TYPE = symbolFor('react.context');
187 REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref');
188 REACT_SUSPENSE_TYPE = symbolFor('react.suspense');
189 REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list');
190 REACT_MEMO_TYPE = symbolFor('react.memo');
191 REACT_LAZY_TYPE = symbolFor('react.lazy');
192 REACT_BLOCK_TYPE = symbolFor('react.block');
193 REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block');
194 REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental');
195 REACT_SCOPE_TYPE = symbolFor('react.scope');
196 REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id');
197 REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode');
198 REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen');
199 REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden');
200 }
201
202 var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
203 var FAUX_ITERATOR_SYMBOL = '@@iterator';
204 function getIteratorFn(maybeIterable) {
205 if (maybeIterable === null || typeof maybeIterable !== 'object') {
206 return null;
207 }
208
209 var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
210
211 if (typeof maybeIterator === 'function') {
212 return maybeIterator;
213 }
214
215 return null;
216 }
217
218 function getWrappedName(outerType, innerType, wrapperName) {
219 var functionName = innerType.displayName || innerType.name || '';
220 return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName);
221 }
222
223 function getContextName(type) {
224 return type.displayName || 'Context';
225 }
226
227 function getComponentName(type) {
228 if (type == null) {
229 // Host root, text node or just invalid type.
230 return null;
231 }
232
233 {
234 if (typeof type.tag === 'number') {
235 error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
236 }
237 }
238
239 if (typeof type === 'function') {
240 return type.displayName || type.name || null;
241 }
242
243 if (typeof type === 'string') {
244 return type;
245 }
246
247 switch (type) {
248 case REACT_FRAGMENT_TYPE:
249 return 'Fragment';
250
251 case REACT_PORTAL_TYPE:
252 return 'Portal';
253
254 case REACT_PROFILER_TYPE:
255 return 'Profiler';
256
257 case REACT_STRICT_MODE_TYPE:
258 return 'StrictMode';
259
260 case REACT_SUSPENSE_TYPE:
261 return 'Suspense';
262
263 case REACT_SUSPENSE_LIST_TYPE:
264 return 'SuspenseList';
265 }
266
267 if (typeof type === 'object') {
268 switch (type.$$typeof) {
269 case REACT_CONTEXT_TYPE:
270 var context = type;
271 return getContextName(context) + '.Consumer';
272
273 case REACT_PROVIDER_TYPE:
274 var provider = type;
275 return getContextName(provider._context) + '.Provider';
276
277 case REACT_FORWARD_REF_TYPE:
278 return getWrappedName(type, type.render, 'ForwardRef');
279
280 case REACT_MEMO_TYPE:
281 return getComponentName(type.type);
282
283 case REACT_BLOCK_TYPE:
284 return getComponentName(type._render);
285
286 case REACT_LAZY_TYPE:
287 {
288 var lazyComponent = type;
289 var payload = lazyComponent._payload;
290 var init = lazyComponent._init;
291
292 try {
293 return getComponentName(init(payload));
294 } catch (x) {
295 return null;
296 }
297 }
298 }
299 }
300
301 return null;
302 }
303
304 // Don't change these two values. They're used by React Dev Tools.
305 var NoFlags =
306 /* */
307 0;
308 var PerformedWork =
309 /* */
310 1; // You can change the rest (and add more).
311
312 var Placement =
313 /* */
314 2;
315 var Update =
316 /* */
317 4;
318 var PlacementAndUpdate =
319 /* */
320 6;
321 var Deletion =
322 /* */
323 8;
324 var ContentReset =
325 /* */
326 16;
327 var Callback =
328 /* */
329 32;
330 var DidCapture =
331 /* */
332 64;
333 var Ref =
334 /* */
335 128;
336 var Snapshot =
337 /* */
338 256;
339 var Passive =
340 /* */
341 512; // TODO (effects) Remove this bit once the new reconciler is synced to the old.
342
343 var PassiveUnmountPendingDev =
344 /* */
345 8192;
346 var Hydrating =
347 /* */
348 1024;
349 var HydratingAndUpdate =
350 /* */
351 1028; // Passive & Update & Callback & Ref & Snapshot
352
353 var LifecycleEffectMask =
354 /* */
355 932; // Union of all host effects
356
357 var HostEffectMask =
358 /* */
359 2047; // These are not really side effects, but we still reuse this field.
360
361 var Incomplete =
362 /* */
363 2048;
364 var ShouldCapture =
365 /* */
366 4096;
367 var ForceUpdateForLegacySuspense =
368 /* */
369 16384; // Static tags describe aspects of a fiber that are not specific to a render,
370
371 // Filter certain DOM attributes (e.g. src, href) if their values are empty strings.
372
373 var enableProfilerTimer = true; // Record durations for commit and passive effects phases.
374
375 var enableFundamentalAPI = false; // Experimental Scope support.
376 var enableNewReconciler = false; // Errors that are thrown while unmounting (or after in the case of passive effects)
377 var warnAboutStringRefs = false;
378
379 var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
380 function getNearestMountedFiber(fiber) {
381 var node = fiber;
382 var nearestMounted = fiber;
383
384 if (!fiber.alternate) {
385 // If there is no alternate, this might be a new tree that isn't inserted
386 // yet. If it is, then it will have a pending insertion effect on it.
387 var nextNode = node;
388
389 do {
390 node = nextNode;
391
392 if ((node.flags & (Placement | Hydrating)) !== NoFlags) {
393 // This is an insertion or in-progress hydration. The nearest possible
394 // mounted fiber is the parent but we need to continue to figure out
395 // if that one is still mounted.
396 nearestMounted = node.return;
397 }
398
399 nextNode = node.return;
400 } while (nextNode);
401 } else {
402 while (node.return) {
403 node = node.return;
404 }
405 }
406
407 if (node.tag === HostRoot) {
408 // TODO: Check if this was a nested HostRoot when used with
409 // renderContainerIntoSubtree.
410 return nearestMounted;
411 } // If we didn't hit the root, that means that we're in an disconnected tree
412 // that has been unmounted.
413
414
415 return null;
416 }
417 function isFiberMounted(fiber) {
418 return getNearestMountedFiber(fiber) === fiber;
419 }
420 function isMounted(component) {
421 {
422 var owner = ReactCurrentOwner.current;
423
424 if (owner !== null && owner.tag === ClassComponent) {
425 var ownerFiber = owner;
426 var instance = ownerFiber.stateNode;
427
428 if (!instance._warnedAboutRefsInRender) {
429 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');
430 }
431
432 instance._warnedAboutRefsInRender = true;
433 }
434 }
435
436 var fiber = get(component);
437
438 if (!fiber) {
439 return false;
440 }
441
442 return getNearestMountedFiber(fiber) === fiber;
443 }
444
445 function assertIsMounted(fiber) {
446 if (!(getNearestMountedFiber(fiber) === fiber)) {
447 {
448 throw Error( "Unable to find node on an unmounted component." );
449 }
450 }
451 }
452
453 function findCurrentFiberUsingSlowPath(fiber) {
454 var alternate = fiber.alternate;
455
456 if (!alternate) {
457 // If there is no alternate, then we only need to check if it is mounted.
458 var nearestMounted = getNearestMountedFiber(fiber);
459
460 if (!(nearestMounted !== null)) {
461 {
462 throw Error( "Unable to find node on an unmounted component." );
463 }
464 }
465
466 if (nearestMounted !== fiber) {
467 return null;
468 }
469
470 return fiber;
471 } // If we have two possible branches, we'll walk backwards up to the root
472 // to see what path the root points to. On the way we may hit one of the
473 // special cases and we'll deal with them.
474
475
476 var a = fiber;
477 var b = alternate;
478
479 while (true) {
480 var parentA = a.return;
481
482 if (parentA === null) {
483 // We're at the root.
484 break;
485 }
486
487 var parentB = parentA.alternate;
488
489 if (parentB === null) {
490 // There is no alternate. This is an unusual case. Currently, it only
491 // happens when a Suspense component is hidden. An extra fragment fiber
492 // is inserted in between the Suspense fiber and its children. Skip
493 // over this extra fragment fiber and proceed to the next parent.
494 var nextParent = parentA.return;
495
496 if (nextParent !== null) {
497 a = b = nextParent;
498 continue;
499 } // If there's no parent, we're at the root.
500
501
502 break;
503 } // If both copies of the parent fiber point to the same child, we can
504 // assume that the child is current. This happens when we bailout on low
505 // priority: the bailed out fiber's child reuses the current child.
506
507
508 if (parentA.child === parentB.child) {
509 var child = parentA.child;
510
511 while (child) {
512 if (child === a) {
513 // We've determined that A is the current branch.
514 assertIsMounted(parentA);
515 return fiber;
516 }
517
518 if (child === b) {
519 // We've determined that B is the current branch.
520 assertIsMounted(parentA);
521 return alternate;
522 }
523
524 child = child.sibling;
525 } // We should never have an alternate for any mounting node. So the only
526 // way this could possibly happen is if this was unmounted, if at all.
527
528
529 {
530 {
531 throw Error( "Unable to find node on an unmounted component." );
532 }
533 }
534 }
535
536 if (a.return !== b.return) {
537 // The return pointer of A and the return pointer of B point to different
538 // fibers. We assume that return pointers never criss-cross, so A must
539 // belong to the child set of A.return, and B must belong to the child
540 // set of B.return.
541 a = parentA;
542 b = parentB;
543 } else {
544 // The return pointers point to the same fiber. We'll have to use the
545 // default, slow path: scan the child sets of each parent alternate to see
546 // which child belongs to which set.
547 //
548 // Search parent A's child set
549 var didFindChild = false;
550 var _child = parentA.child;
551
552 while (_child) {
553 if (_child === a) {
554 didFindChild = true;
555 a = parentA;
556 b = parentB;
557 break;
558 }
559
560 if (_child === b) {
561 didFindChild = true;
562 b = parentA;
563 a = parentB;
564 break;
565 }
566
567 _child = _child.sibling;
568 }
569
570 if (!didFindChild) {
571 // Search parent B's child set
572 _child = parentB.child;
573
574 while (_child) {
575 if (_child === a) {
576 didFindChild = true;
577 a = parentB;
578 b = parentA;
579 break;
580 }
581
582 if (_child === b) {
583 didFindChild = true;
584 b = parentB;
585 a = parentA;
586 break;
587 }
588
589 _child = _child.sibling;
590 }
591
592 if (!didFindChild) {
593 {
594 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." );
595 }
596 }
597 }
598 }
599
600 if (!(a.alternate === b)) {
601 {
602 throw Error( "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." );
603 }
604 }
605 } // If the root is not a host container, we're in a disconnected tree. I.e.
606 // unmounted.
607
608
609 if (!(a.tag === HostRoot)) {
610 {
611 throw Error( "Unable to find node on an unmounted component." );
612 }
613 }
614
615 if (a.stateNode.current === a) {
616 // We've determined that A is the current branch.
617 return fiber;
618 } // Otherwise B has to be current branch.
619
620
621 return alternate;
622 }
623 function findCurrentHostFiber(parent) {
624 var currentParent = findCurrentFiberUsingSlowPath(parent);
625
626 if (!currentParent) {
627 return null;
628 } // Next we'll drill down this component to find the first HostComponent/Text.
629
630
631 var node = currentParent;
632
633 while (true) {
634 if (node.tag === HostComponent || node.tag === HostText) {
635 return node;
636 } else if (node.child) {
637 node.child.return = node;
638 node = node.child;
639 continue;
640 }
641
642 if (node === currentParent) {
643 return null;
644 }
645
646 while (!node.sibling) {
647 if (!node.return || node.return === currentParent) {
648 return null;
649 }
650
651 node = node.return;
652 }
653
654 node.sibling.return = node.return;
655 node = node.sibling;
656 } // Flow needs the return null here, but ESLint complains about it.
657 // eslint-disable-next-line no-unreachable
658
659
660 return null;
661 }
662 function doesFiberContain(parentFiber, childFiber) {
663 var node = childFiber;
664 var parentFiberAlternate = parentFiber.alternate;
665
666 while (node !== null) {
667 if (node === parentFiber || node === parentFiberAlternate) {
668 return true;
669 }
670
671 node = node.return;
672 }
673
674 return false;
675 }
676
677 var _class = function(mixins){
678 var proto = {};
679 for (var i = 0, l = arguments.length; i < l; i++){
680 var mixin = arguments[i];
681 if (typeof mixin == 'function') mixin = mixin.prototype;
682 for (var key in mixin) proto[key] = mixin[key];
683 }
684 if (!proto.initialize) proto.initialize = function(){};
685 proto.constructor = function(a,b,c,d,e,f,g,h){
686 return new proto.initialize(a,b,c,d,e,f,g,h);
687 };
688 proto.constructor.prototype = proto.initialize.prototype = proto;
689 return proto.constructor;
690 };
691
692 function Transform(xx, yx, xy, yy, x, y){
693 if (xx && typeof xx == 'object'){
694 yx = xx.yx; yy = xx.yy; y = xx.y;
695 xy = xx.xy; x = xx.x; xx = xx.xx;
696 }
697 this.xx = xx == null ? 1 : xx;
698 this.yx = yx || 0;
699 this.xy = xy || 0;
700 this.yy = yy == null ? 1 : yy;
701 this.x = (x == null ? this.x : x) || 0;
702 this.y = (y == null ? this.y : y) || 0;
703 this._transform();
704 return this;
705 }
706 var transform = _class({
707
708 initialize: Transform,
709
710 _transform: function(){},
711
712 xx: 1, yx: 0, x: 0,
713 xy: 0, yy: 1, y: 0,
714
715 transform: function(xx, yx, xy, yy, x, y){
716 var m = this;
717 if (xx && typeof xx == 'object'){
718 yx = xx.yx; yy = xx.yy; y = xx.y;
719 xy = xx.xy; x = xx.x; xx = xx.xx;
720 }
721 if (!x) x = 0;
722 if (!y) y = 0;
723 return this.transformTo(
724 m.xx * xx + m.xy * yx,
725 m.yx * xx + m.yy * yx,
726 m.xx * xy + m.xy * yy,
727 m.yx * xy + m.yy * yy,
728 m.xx * x + m.xy * y + m.x,
729 m.yx * x + m.yy * y + m.y
730 );
731 },
732
733 transformTo: Transform,
734
735 translate: function(x, y){
736 return this.transform(1, 0, 0, 1, x, y);
737 },
738
739 move: function(x, y){
740 this.x += x || 0;
741 this.y += y || 0;
742 this._transform();
743 return this;
744 },
745
746 scale: function(x, y){
747 if (y == null) y = x;
748 return this.transform(x, 0, 0, y, 0, 0);
749 },
750
751 rotate: function(deg, x, y){
752 if (x == null || y == null){
753 x = (this.left || 0) + (this.width || 0) / 2;
754 y = (this.top || 0) + (this.height || 0) / 2;
755 }
756
757 var rad = deg * Math.PI / 180, sin = Math.sin(rad), cos = Math.cos(rad);
758
759 this.transform(1, 0, 0, 1, x, y);
760 var m = this;
761
762 return this.transformTo(
763 cos * m.xx - sin * m.yx,
764 sin * m.xx + cos * m.yx,
765 cos * m.xy - sin * m.yy,
766 sin * m.xy + cos * m.yy,
767 m.x,
768 m.y
769 ).transform(1, 0, 0, 1, -x, -y);
770 },
771
772 moveTo: function(x, y){
773 var m = this;
774 return this.transformTo(m.xx, m.yx, m.xy, m.yy, x, y);
775 },
776
777 rotateTo: function(deg, x, y){
778 var m = this;
779 var flip = m.yx / m.xx > m.yy / m.xy ? -1 : 1;
780 if (m.xx < 0 ? m.xy >= 0 : m.xy < 0) flip = -flip;
781 return this.rotate(deg - Math.atan2(flip * m.yx, flip * m.xx) * 180 / Math.PI, x, y);
782 },
783
784 scaleTo: function(x, y){
785 // Normalize
786 var m = this;
787
788 var h = Math.sqrt(m.xx * m.xx + m.yx * m.yx);
789 m.xx /= h; m.yx /= h;
790
791 h = Math.sqrt(m.yy * m.yy + m.xy * m.xy);
792 m.yy /= h; m.xy /= h;
793
794 return this.scale(x, y);
795 },
796
797 resizeTo: function(width, height){
798 var w = this.width, h = this.height;
799 if (!w || !h) return this;
800 return this.scaleTo(width / w, height / h);
801 },
802
803 /*
804 inverse: function(){
805 var a = this.xx, b = this.yx,
806 c = this.xy, d = this.yy,
807 e = this.x, f = this.y;
808 if (a * d - b * c == 0) return null;
809 return new Transform(
810 d/(a * d-b * c), b/(b * c-a * d),
811 c/(b * c-a * d), a/(a * d-b * c),
812 (d * e-c * f)/(b * c-a * d), (b * e-a * f)/(a * d-b * c)
813 );
814 },
815 */
816
817 inversePoint: function(x, y){
818 var a = this.xx, b = this.yx,
819 c = this.xy, d = this.yy,
820 e = this.x, f = this.y;
821 var det = b * c - a * d;
822 if (det == 0) return null;
823 return {
824 x: (d * (e - x) + c * (y - f)) / det,
825 y: (a * (f - y) + b * (x - e)) / det
826 };
827 },
828
829 point: function(x, y){
830 var m = this;
831 return {
832 x: m.xx * x + m.xy * y + m.x,
833 y: m.yx * x + m.yy * y + m.y
834 };
835 }
836
837 });
838
839 var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
840
841 function createCommonjsModule(fn, module) {
842 return module = { exports: {} }, fn(module, module.exports), module.exports;
843 }
844
845 var current = createCommonjsModule(function (module, exports) {
846 function warning(){
847 throw new Error('You must require a mode before requiring anything else.');
848 }
849
850 exports.Surface = warning;
851 exports.Path = warning;
852 exports.Shape = warning;
853 exports.Group = warning;
854 exports.ClippingRectangle = warning;
855 exports.Text = warning;
856
857 exports.setCurrent = function(mode){
858 for (var key in mode){
859 exports[key] = mode[key];
860 }
861 };
862 });
863 var current_1 = current.Surface;
864 var current_2 = current.Path;
865 var current_3 = current.Shape;
866 var current_4 = current.Group;
867 var current_5 = current.ClippingRectangle;
868 var current_6 = current.Text;
869 var current_7 = current.setCurrent;
870
871 var TYPES = {
872 CLIPPING_RECTANGLE: 'ClippingRectangle',
873 GROUP: 'Group',
874 SHAPE: 'Shape',
875 TEXT: 'Text'
876 };
877 var EVENT_TYPES = {
878 onClick: 'click',
879 onMouseMove: 'mousemove',
880 onMouseOver: 'mouseover',
881 onMouseOut: 'mouseout',
882 onMouseUp: 'mouseup',
883 onMouseDown: 'mousedown'
884 };
885 function childrenAsString(children) {
886 if (!children) {
887 return '';
888 } else if (typeof children === 'string') {
889 return children;
890 } else if (children.length) {
891 return children.join('');
892 } else {
893 return '';
894 }
895 }
896
897 // can re-export everything from this module.
898
899 function shim() {
900 {
901 {
902 throw Error( "The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue." );
903 }
904 }
905 } // Hydration (when unsupported)
906 var isSuspenseInstancePending = shim;
907 var isSuspenseInstanceFallback = shim;
908 var hydrateTextInstance = shim;
909
910 var pooledTransform = new transform();
911 var NO_CONTEXT = {};
912 var UPDATE_SIGNAL = {};
913
914 {
915 Object.freeze(NO_CONTEXT);
916 Object.freeze(UPDATE_SIGNAL);
917 }
918 /** Helper Methods */
919
920
921 function addEventListeners(instance, type, listener) {
922 // We need to explicitly unregister before unmount.
923 // For this reason we need to track subscriptions.
924 if (!instance._listeners) {
925 instance._listeners = {};
926 instance._subscriptions = {};
927 }
928
929 instance._listeners[type] = listener;
930
931 if (listener) {
932 if (!instance._subscriptions[type]) {
933 instance._subscriptions[type] = instance.subscribe(type, createEventHandler(instance), instance);
934 }
935 } else {
936 if (instance._subscriptions[type]) {
937 instance._subscriptions[type]();
938
939 delete instance._subscriptions[type];
940 }
941 }
942 }
943
944 function createEventHandler(instance) {
945 return function handleEvent(event) {
946 var listener = instance._listeners[event.type];
947
948 if (!listener) ; else if (typeof listener === 'function') {
949 listener.call(instance, event);
950 } else if (listener.handleEvent) {
951 listener.handleEvent(event);
952 }
953 };
954 }
955
956 function destroyEventListeners(instance) {
957 if (instance._subscriptions) {
958 for (var type in instance._subscriptions) {
959 instance._subscriptions[type]();
960 }
961 }
962
963 instance._subscriptions = null;
964 instance._listeners = null;
965 }
966
967 function getScaleX(props) {
968 if (props.scaleX != null) {
969 return props.scaleX;
970 } else if (props.scale != null) {
971 return props.scale;
972 } else {
973 return 1;
974 }
975 }
976
977 function getScaleY(props) {
978 if (props.scaleY != null) {
979 return props.scaleY;
980 } else if (props.scale != null) {
981 return props.scale;
982 } else {
983 return 1;
984 }
985 }
986
987 function isSameFont(oldFont, newFont) {
988 if (oldFont === newFont) {
989 return true;
990 } else if (typeof newFont === 'string' || typeof oldFont === 'string') {
991 return false;
992 } else {
993 return newFont.fontSize === oldFont.fontSize && newFont.fontStyle === oldFont.fontStyle && newFont.fontVariant === oldFont.fontVariant && newFont.fontWeight === oldFont.fontWeight && newFont.fontFamily === oldFont.fontFamily;
994 }
995 }
996 /** Render Methods */
997
998
999 function applyClippingRectangleProps(instance, props) {
1000 var prevProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1001 applyNodeProps(instance, props, prevProps);
1002 instance.width = props.width;
1003 instance.height = props.height;
1004 }
1005
1006 function applyGroupProps(instance, props) {
1007 var prevProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1008 applyNodeProps(instance, props, prevProps);
1009 instance.width = props.width;
1010 instance.height = props.height;
1011 }
1012
1013 function applyNodeProps(instance, props) {
1014 var prevProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1015 var scaleX = getScaleX(props);
1016 var scaleY = getScaleY(props);
1017 pooledTransform.transformTo(1, 0, 0, 1, 0, 0).move(props.x || 0, props.y || 0).rotate(props.rotation || 0, props.originX, props.originY).scale(scaleX, scaleY, props.originX, props.originY);
1018
1019 if (props.transform != null) {
1020 pooledTransform.transform(props.transform);
1021 }
1022
1023 if (instance.xx !== pooledTransform.xx || instance.yx !== pooledTransform.yx || instance.xy !== pooledTransform.xy || instance.yy !== pooledTransform.yy || instance.x !== pooledTransform.x || instance.y !== pooledTransform.y) {
1024 instance.transformTo(pooledTransform);
1025 }
1026
1027 if (props.cursor !== prevProps.cursor || props.title !== prevProps.title) {
1028 instance.indicate(props.cursor, props.title);
1029 }
1030
1031 if (instance.blend && props.opacity !== prevProps.opacity) {
1032 instance.blend(props.opacity == null ? 1 : props.opacity);
1033 }
1034
1035 if (props.visible !== prevProps.visible) {
1036 if (props.visible == null || props.visible) {
1037 instance.show();
1038 } else {
1039 instance.hide();
1040 }
1041 }
1042
1043 for (var type in EVENT_TYPES) {
1044 addEventListeners(instance, EVENT_TYPES[type], props[type]);
1045 }
1046 }
1047
1048 function applyRenderableNodeProps(instance, props) {
1049 var prevProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1050 applyNodeProps(instance, props, prevProps);
1051
1052 if (prevProps.fill !== props.fill) {
1053 if (props.fill && props.fill.applyFill) {
1054 props.fill.applyFill(instance);
1055 } else {
1056 instance.fill(props.fill);
1057 }
1058 }
1059
1060 if (prevProps.stroke !== props.stroke || prevProps.strokeWidth !== props.strokeWidth || prevProps.strokeCap !== props.strokeCap || prevProps.strokeJoin !== props.strokeJoin || // TODO: Consider deep check of stokeDash; may benefit VML in IE.
1061 prevProps.strokeDash !== props.strokeDash) {
1062 instance.stroke(props.stroke, props.strokeWidth, props.strokeCap, props.strokeJoin, props.strokeDash);
1063 }
1064 }
1065
1066 function applyShapeProps(instance, props) {
1067 var prevProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1068 applyRenderableNodeProps(instance, props, prevProps);
1069 var path = props.d || childrenAsString(props.children);
1070 var prevDelta = instance._prevDelta;
1071 var prevPath = instance._prevPath;
1072
1073 if (path !== prevPath || path.delta !== prevDelta || prevProps.height !== props.height || prevProps.width !== props.width) {
1074 instance.draw(path, props.width, props.height);
1075 instance._prevDelta = path.delta;
1076 instance._prevPath = path;
1077 }
1078 }
1079
1080 function applyTextProps(instance, props) {
1081 var prevProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1082 applyRenderableNodeProps(instance, props, prevProps);
1083 var string = props.children;
1084
1085 if (instance._currentString !== string || !isSameFont(props.font, prevProps.font) || props.alignment !== prevProps.alignment || props.path !== prevProps.path) {
1086 instance.draw(string, props.font, props.alignment, props.path);
1087 instance._currentString = string;
1088 }
1089 }
1090 function appendInitialChild(parentInstance, child) {
1091 if (typeof child === 'string') {
1092 // Noop for string children of Text (eg <Text>{'foo'}{'bar'}</Text>)
1093 {
1094 {
1095 throw Error( "Text children should already be flattened." );
1096 }
1097 }
1098 }
1099
1100 child.inject(parentInstance);
1101 }
1102 function createInstance(type, props, internalInstanceHandle) {
1103 var instance;
1104
1105 switch (type) {
1106 case TYPES.CLIPPING_RECTANGLE:
1107 instance = current.ClippingRectangle();
1108 instance._applyProps = applyClippingRectangleProps;
1109 break;
1110
1111 case TYPES.GROUP:
1112 instance = current.Group();
1113 instance._applyProps = applyGroupProps;
1114 break;
1115
1116 case TYPES.SHAPE:
1117 instance = current.Shape();
1118 instance._applyProps = applyShapeProps;
1119 break;
1120
1121 case TYPES.TEXT:
1122 instance = current.Text(props.children, props.font, props.alignment, props.path);
1123 instance._applyProps = applyTextProps;
1124 break;
1125 }
1126
1127 if (!instance) {
1128 {
1129 throw Error( "ReactART does not support the type \"" + type + "\"" );
1130 }
1131 }
1132
1133 instance._applyProps(instance, props);
1134
1135 return instance;
1136 }
1137 function createTextInstance(text, rootContainerInstance, internalInstanceHandle) {
1138 return text;
1139 }
1140 function getPublicInstance(instance) {
1141 return instance;
1142 }
1143 function prepareForCommit() {
1144 // Noop
1145 return null;
1146 }
1147 function prepareUpdate(domElement, type, oldProps, newProps) {
1148 return UPDATE_SIGNAL;
1149 }
1150 function resetAfterCommit() {// Noop
1151 }
1152 function resetTextContent(domElement) {// Noop
1153 }
1154 function getRootHostContext() {
1155 return NO_CONTEXT;
1156 }
1157 function getChildHostContext() {
1158 return NO_CONTEXT;
1159 }
1160 var scheduleTimeout = setTimeout;
1161 var cancelTimeout = clearTimeout;
1162 var noTimeout = -1;
1163 function shouldSetTextContent(type, props) {
1164 return typeof props.children === 'string' || typeof props.children === 'number';
1165 } // The ART renderer is secondary to the React DOM renderer.
1166 function appendChild(parentInstance, child) {
1167 if (child.parentNode === parentInstance) {
1168 child.eject();
1169 }
1170
1171 child.inject(parentInstance);
1172 }
1173 function appendChildToContainer(parentInstance, child) {
1174 if (child.parentNode === parentInstance) {
1175 child.eject();
1176 }
1177
1178 child.inject(parentInstance);
1179 }
1180 function insertBefore(parentInstance, child, beforeChild) {
1181 if (!(child !== beforeChild)) {
1182 {
1183 throw Error( "ReactART: Can not insert node before itself" );
1184 }
1185 }
1186
1187 child.injectBefore(beforeChild);
1188 }
1189 function insertInContainerBefore(parentInstance, child, beforeChild) {
1190 if (!(child !== beforeChild)) {
1191 {
1192 throw Error( "ReactART: Can not insert node before itself" );
1193 }
1194 }
1195
1196 child.injectBefore(beforeChild);
1197 }
1198 function removeChild(parentInstance, child) {
1199 destroyEventListeners(child);
1200 child.eject();
1201 }
1202 function removeChildFromContainer(parentInstance, child) {
1203 destroyEventListeners(child);
1204 child.eject();
1205 }
1206 function commitUpdate(instance, updatePayload, type, oldProps, newProps) {
1207 instance._applyProps(instance, newProps, oldProps);
1208 }
1209 function hideInstance(instance) {
1210 instance.hide();
1211 }
1212 function unhideInstance(instance, props) {
1213 if (props.visible == null || props.visible) {
1214 instance.show();
1215 }
1216 }
1217 function unhideTextInstance(textInstance, text) {// Noop
1218 }
1219 function clearContainer(container) {// TODO Implement this
1220 }
1221 function makeClientIdInDEV(warnOnAccessInDEV) {
1222 throw new Error('Not yet implemented');
1223 }
1224 function preparePortalMount(portalInstance) {// noop
1225 }
1226
1227 // Helpers to patch console.logs to avoid logging during side-effect free
1228 // replaying on render function. This currently only patches the object
1229 // lazily which won't cover if the log function was extracted eagerly.
1230 // We could also eagerly patch the method.
1231 var disabledDepth = 0;
1232 var prevLog;
1233 var prevInfo;
1234 var prevWarn;
1235 var prevError;
1236 var prevGroup;
1237 var prevGroupCollapsed;
1238 var prevGroupEnd;
1239
1240 function disabledLog() {}
1241
1242 disabledLog.__reactDisabledLog = true;
1243 function disableLogs() {
1244 {
1245 if (disabledDepth === 0) {
1246 /* eslint-disable react-internal/no-production-logging */
1247 prevLog = console.log;
1248 prevInfo = console.info;
1249 prevWarn = console.warn;
1250 prevError = console.error;
1251 prevGroup = console.group;
1252 prevGroupCollapsed = console.groupCollapsed;
1253 prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
1254
1255 var props = {
1256 configurable: true,
1257 enumerable: true,
1258 value: disabledLog,
1259 writable: true
1260 }; // $FlowFixMe Flow thinks console is immutable.
1261
1262 Object.defineProperties(console, {
1263 info: props,
1264 log: props,
1265 warn: props,
1266 error: props,
1267 group: props,
1268 groupCollapsed: props,
1269 groupEnd: props
1270 });
1271 /* eslint-enable react-internal/no-production-logging */
1272 }
1273
1274 disabledDepth++;
1275 }
1276 }
1277 function reenableLogs() {
1278 {
1279 disabledDepth--;
1280
1281 if (disabledDepth === 0) {
1282 /* eslint-disable react-internal/no-production-logging */
1283 var props = {
1284 configurable: true,
1285 enumerable: true,
1286 writable: true
1287 }; // $FlowFixMe Flow thinks console is immutable.
1288
1289 Object.defineProperties(console, {
1290 log: _assign({}, props, {
1291 value: prevLog
1292 }),
1293 info: _assign({}, props, {
1294 value: prevInfo
1295 }),
1296 warn: _assign({}, props, {
1297 value: prevWarn
1298 }),
1299 error: _assign({}, props, {
1300 value: prevError
1301 }),
1302 group: _assign({}, props, {
1303 value: prevGroup
1304 }),
1305 groupCollapsed: _assign({}, props, {
1306 value: prevGroupCollapsed
1307 }),
1308 groupEnd: _assign({}, props, {
1309 value: prevGroupEnd
1310 })
1311 });
1312 /* eslint-enable react-internal/no-production-logging */
1313 }
1314
1315 if (disabledDepth < 0) {
1316 error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
1317 }
1318 }
1319 }
1320
1321 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
1322 var prefix;
1323 function describeBuiltInComponentFrame(name, source, ownerFn) {
1324 {
1325 if (prefix === undefined) {
1326 // Extract the VM specific prefix used by each line.
1327 try {
1328 throw Error();
1329 } catch (x) {
1330 var match = x.stack.trim().match(/\n( *(at )?)/);
1331 prefix = match && match[1] || '';
1332 }
1333 } // We use the prefix to ensure our stacks line up with native stack frames.
1334
1335
1336 return '\n' + prefix + name;
1337 }
1338 }
1339 var reentry = false;
1340 var componentFrameCache;
1341
1342 {
1343 var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
1344 componentFrameCache = new PossiblyWeakMap();
1345 }
1346
1347 function describeNativeComponentFrame(fn, construct) {
1348 // If something asked for a stack inside a fake render, it should get ignored.
1349 if (!fn || reentry) {
1350 return '';
1351 }
1352
1353 {
1354 var frame = componentFrameCache.get(fn);
1355
1356 if (frame !== undefined) {
1357 return frame;
1358 }
1359 }
1360
1361 var control;
1362 reentry = true;
1363 var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
1364
1365 Error.prepareStackTrace = undefined;
1366 var previousDispatcher;
1367
1368 {
1369 previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
1370 // for warnings.
1371
1372 ReactCurrentDispatcher.current = null;
1373 disableLogs();
1374 }
1375
1376 try {
1377 // This should throw.
1378 if (construct) {
1379 // Something should be setting the props in the constructor.
1380 var Fake = function () {
1381 throw Error();
1382 }; // $FlowFixMe
1383
1384
1385 Object.defineProperty(Fake.prototype, 'props', {
1386 set: function () {
1387 // We use a throwing setter instead of frozen or non-writable props
1388 // because that won't throw in a non-strict mode function.
1389 throw Error();
1390 }
1391 });
1392
1393 if (typeof Reflect === 'object' && Reflect.construct) {
1394 // We construct a different control for this case to include any extra
1395 // frames added by the construct call.
1396 try {
1397 Reflect.construct(Fake, []);
1398 } catch (x) {
1399 control = x;
1400 }
1401
1402 Reflect.construct(fn, [], Fake);
1403 } else {
1404 try {
1405 Fake.call();
1406 } catch (x) {
1407 control = x;
1408 }
1409
1410 fn.call(Fake.prototype);
1411 }
1412 } else {
1413 try {
1414 throw Error();
1415 } catch (x) {
1416 control = x;
1417 }
1418
1419 fn();
1420 }
1421 } catch (sample) {
1422 // This is inlined manually because closure doesn't do it for us.
1423 if (sample && control && typeof sample.stack === 'string') {
1424 // This extracts the first frame from the sample that isn't also in the control.
1425 // Skipping one frame that we assume is the frame that calls the two.
1426 var sampleLines = sample.stack.split('\n');
1427 var controlLines = control.stack.split('\n');
1428 var s = sampleLines.length - 1;
1429 var c = controlLines.length - 1;
1430
1431 while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
1432 // We expect at least one stack frame to be shared.
1433 // Typically this will be the root most one. However, stack frames may be
1434 // cut off due to maximum stack limits. In this case, one maybe cut off
1435 // earlier than the other. We assume that the sample is longer or the same
1436 // and there for cut off earlier. So we should find the root most frame in
1437 // the sample somewhere in the control.
1438 c--;
1439 }
1440
1441 for (; s >= 1 && c >= 0; s--, c--) {
1442 // Next we find the first one that isn't the same which should be the
1443 // frame that called our sample function and the control.
1444 if (sampleLines[s] !== controlLines[c]) {
1445 // In V8, the first line is describing the message but other VMs don't.
1446 // If we're about to return the first line, and the control is also on the same
1447 // line, that's a pretty good indicator that our sample threw at same line as
1448 // the control. I.e. before we entered the sample frame. So we ignore this result.
1449 // This can happen if you passed a class to function component, or non-function.
1450 if (s !== 1 || c !== 1) {
1451 do {
1452 s--;
1453 c--; // We may still have similar intermediate frames from the construct call.
1454 // The next one that isn't the same should be our match though.
1455
1456 if (c < 0 || sampleLines[s] !== controlLines[c]) {
1457 // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
1458 var _frame = '\n' + sampleLines[s].replace(' at new ', ' at ');
1459
1460 {
1461 if (typeof fn === 'function') {
1462 componentFrameCache.set(fn, _frame);
1463 }
1464 } // Return the line we found.
1465
1466
1467 return _frame;
1468 }
1469 } while (s >= 1 && c >= 0);
1470 }
1471
1472 break;
1473 }
1474 }
1475 }
1476 } finally {
1477 reentry = false;
1478
1479 {
1480 ReactCurrentDispatcher.current = previousDispatcher;
1481 reenableLogs();
1482 }
1483
1484 Error.prepareStackTrace = previousPrepareStackTrace;
1485 } // Fallback to just using the name if we couldn't make it throw.
1486
1487
1488 var name = fn ? fn.displayName || fn.name : '';
1489 var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
1490
1491 {
1492 if (typeof fn === 'function') {
1493 componentFrameCache.set(fn, syntheticFrame);
1494 }
1495 }
1496
1497 return syntheticFrame;
1498 }
1499
1500 function describeClassComponentFrame(ctor, source, ownerFn) {
1501 {
1502 return describeNativeComponentFrame(ctor, true);
1503 }
1504 }
1505 function describeFunctionComponentFrame(fn, source, ownerFn) {
1506 {
1507 return describeNativeComponentFrame(fn, false);
1508 }
1509 }
1510
1511 function shouldConstruct(Component) {
1512 var prototype = Component.prototype;
1513 return !!(prototype && prototype.isReactComponent);
1514 }
1515
1516 function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
1517
1518 if (type == null) {
1519 return '';
1520 }
1521
1522 if (typeof type === 'function') {
1523 {
1524 return describeNativeComponentFrame(type, shouldConstruct(type));
1525 }
1526 }
1527
1528 if (typeof type === 'string') {
1529 return describeBuiltInComponentFrame(type);
1530 }
1531
1532 switch (type) {
1533 case REACT_SUSPENSE_TYPE:
1534 return describeBuiltInComponentFrame('Suspense');
1535
1536 case REACT_SUSPENSE_LIST_TYPE:
1537 return describeBuiltInComponentFrame('SuspenseList');
1538 }
1539
1540 if (typeof type === 'object') {
1541 switch (type.$$typeof) {
1542 case REACT_FORWARD_REF_TYPE:
1543 return describeFunctionComponentFrame(type.render);
1544
1545 case REACT_MEMO_TYPE:
1546 // Memo may contain any component type so we recursively resolve it.
1547 return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
1548
1549 case REACT_BLOCK_TYPE:
1550 return describeFunctionComponentFrame(type._render);
1551
1552 case REACT_LAZY_TYPE:
1553 {
1554 var lazyComponent = type;
1555 var payload = lazyComponent._payload;
1556 var init = lazyComponent._init;
1557
1558 try {
1559 // Lazy may contain any component type so we recursively resolve it.
1560 return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
1561 } catch (x) {}
1562 }
1563 }
1564 }
1565
1566 return '';
1567 }
1568
1569 var loggedTypeFailures = {};
1570 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
1571
1572 function setCurrentlyValidatingElement(element) {
1573 {
1574 if (element) {
1575 var owner = element._owner;
1576 var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
1577 ReactDebugCurrentFrame.setExtraStackFrame(stack);
1578 } else {
1579 ReactDebugCurrentFrame.setExtraStackFrame(null);
1580 }
1581 }
1582 }
1583
1584 function checkPropTypes(typeSpecs, values, location, componentName, element) {
1585 {
1586 // $FlowFixMe This is okay but Flow doesn't know it.
1587 var has = Function.call.bind(Object.prototype.hasOwnProperty);
1588
1589 for (var typeSpecName in typeSpecs) {
1590 if (has(typeSpecs, typeSpecName)) {
1591 var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
1592 // fail the render phase where it didn't fail before. So we log it.
1593 // After these have been cleaned up, we'll let them throw.
1594
1595 try {
1596 // This is intentionally an invariant that gets caught. It's the same
1597 // behavior as without this statement except with a better message.
1598 if (typeof typeSpecs[typeSpecName] !== 'function') {
1599 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`.');
1600 err.name = 'Invariant Violation';
1601 throw err;
1602 }
1603
1604 error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
1605 } catch (ex) {
1606 error$1 = ex;
1607 }
1608
1609 if (error$1 && !(error$1 instanceof Error)) {
1610 setCurrentlyValidatingElement(element);
1611
1612 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);
1613
1614 setCurrentlyValidatingElement(null);
1615 }
1616
1617 if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
1618 // Only monitor this failure once because there tends to be a lot of the
1619 // same error.
1620 loggedTypeFailures[error$1.message] = true;
1621 setCurrentlyValidatingElement(element);
1622
1623 error('Failed %s type: %s', location, error$1.message);
1624
1625 setCurrentlyValidatingElement(null);
1626 }
1627 }
1628 }
1629 }
1630 }
1631
1632 var valueStack = [];
1633 var fiberStack;
1634
1635 {
1636 fiberStack = [];
1637 }
1638
1639 var index = -1;
1640
1641 function createCursor(defaultValue) {
1642 return {
1643 current: defaultValue
1644 };
1645 }
1646
1647 function pop(cursor, fiber) {
1648 if (index < 0) {
1649 {
1650 error('Unexpected pop.');
1651 }
1652
1653 return;
1654 }
1655
1656 {
1657 if (fiber !== fiberStack[index]) {
1658 error('Unexpected Fiber popped.');
1659 }
1660 }
1661
1662 cursor.current = valueStack[index];
1663 valueStack[index] = null;
1664
1665 {
1666 fiberStack[index] = null;
1667 }
1668
1669 index--;
1670 }
1671
1672 function push(cursor, value, fiber) {
1673 index++;
1674 valueStack[index] = cursor.current;
1675
1676 {
1677 fiberStack[index] = fiber;
1678 }
1679
1680 cursor.current = value;
1681 }
1682
1683 var warnedAboutMissingGetChildContext;
1684
1685 {
1686 warnedAboutMissingGetChildContext = {};
1687 }
1688
1689 var emptyContextObject = {};
1690
1691 {
1692 Object.freeze(emptyContextObject);
1693 } // A cursor to the current merged context object on the stack.
1694
1695
1696 var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed.
1697
1698 var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack.
1699 // We use this to get access to the parent context after we have already
1700 // pushed the next context provider, and now need to merge their contexts.
1701
1702 var previousContext = emptyContextObject;
1703
1704 function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
1705 {
1706 if (didPushOwnContextIfProvider && isContextProvider(Component)) {
1707 // If the fiber is a context provider itself, when we read its context
1708 // we may have already pushed its own child context on the stack. A context
1709 // provider should not "see" its own child context. Therefore we read the
1710 // previous (parent) context instead for a context provider.
1711 return previousContext;
1712 }
1713
1714 return contextStackCursor.current;
1715 }
1716 }
1717
1718 function cacheContext(workInProgress, unmaskedContext, maskedContext) {
1719 {
1720 var instance = workInProgress.stateNode;
1721 instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
1722 instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
1723 }
1724 }
1725
1726 function getMaskedContext(workInProgress, unmaskedContext) {
1727 {
1728 var type = workInProgress.type;
1729 var contextTypes = type.contextTypes;
1730
1731 if (!contextTypes) {
1732 return emptyContextObject;
1733 } // Avoid recreating masked context unless unmasked context has changed.
1734 // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
1735 // This may trigger infinite loops if componentWillReceiveProps calls setState.
1736
1737
1738 var instance = workInProgress.stateNode;
1739
1740 if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
1741 return instance.__reactInternalMemoizedMaskedChildContext;
1742 }
1743
1744 var context = {};
1745
1746 for (var key in contextTypes) {
1747 context[key] = unmaskedContext[key];
1748 }
1749
1750 {
1751 var name = getComponentName(type) || 'Unknown';
1752 checkPropTypes(contextTypes, context, 'context', name);
1753 } // Cache unmasked context so we can avoid recreating masked context unless necessary.
1754 // Context is created before the class component is instantiated so check for instance.
1755
1756
1757 if (instance) {
1758 cacheContext(workInProgress, unmaskedContext, context);
1759 }
1760
1761 return context;
1762 }
1763 }
1764
1765 function hasContextChanged() {
1766 {
1767 return didPerformWorkStackCursor.current;
1768 }
1769 }
1770
1771 function isContextProvider(type) {
1772 {
1773 var childContextTypes = type.childContextTypes;
1774 return childContextTypes !== null && childContextTypes !== undefined;
1775 }
1776 }
1777
1778 function popContext(fiber) {
1779 {
1780 pop(didPerformWorkStackCursor, fiber);
1781 pop(contextStackCursor, fiber);
1782 }
1783 }
1784
1785 function popTopLevelContextObject(fiber) {
1786 {
1787 pop(didPerformWorkStackCursor, fiber);
1788 pop(contextStackCursor, fiber);
1789 }
1790 }
1791
1792 function pushTopLevelContextObject(fiber, context, didChange) {
1793 {
1794 if (!(contextStackCursor.current === emptyContextObject)) {
1795 {
1796 throw Error( "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." );
1797 }
1798 }
1799
1800 push(contextStackCursor, context, fiber);
1801 push(didPerformWorkStackCursor, didChange, fiber);
1802 }
1803 }
1804
1805 function processChildContext(fiber, type, parentContext) {
1806 {
1807 var instance = fiber.stateNode;
1808 var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future.
1809 // It has only been added in Fiber to match the (unintentional) behavior in Stack.
1810
1811 if (typeof instance.getChildContext !== 'function') {
1812 {
1813 var componentName = getComponentName(type) || 'Unknown';
1814
1815 if (!warnedAboutMissingGetChildContext[componentName]) {
1816 warnedAboutMissingGetChildContext[componentName] = true;
1817
1818 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);
1819 }
1820 }
1821
1822 return parentContext;
1823 }
1824
1825 var childContext = instance.getChildContext();
1826
1827 for (var contextKey in childContext) {
1828 if (!(contextKey in childContextTypes)) {
1829 {
1830 throw Error( (getComponentName(type) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes." );
1831 }
1832 }
1833 }
1834
1835 {
1836 var name = getComponentName(type) || 'Unknown';
1837 checkPropTypes(childContextTypes, childContext, 'child context', name);
1838 }
1839
1840 return _assign({}, parentContext, childContext);
1841 }
1842 }
1843
1844 function pushContextProvider(workInProgress) {
1845 {
1846 var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity.
1847 // If the instance does not exist yet, we will push null at first,
1848 // and replace it on the stack later when invalidating the context.
1849
1850 var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later.
1851 // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
1852
1853 previousContext = contextStackCursor.current;
1854 push(contextStackCursor, memoizedMergedChildContext, workInProgress);
1855 push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
1856 return true;
1857 }
1858 }
1859
1860 function invalidateContextProvider(workInProgress, type, didChange) {
1861 {
1862 var instance = workInProgress.stateNode;
1863
1864 if (!instance) {
1865 {
1866 throw Error( "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." );
1867 }
1868 }
1869
1870 if (didChange) {
1871 // Merge parent and own context.
1872 // Skip this if we're not updating due to sCU.
1873 // This avoids unnecessarily recomputing memoized values.
1874 var mergedContext = processChildContext(workInProgress, type, previousContext);
1875 instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one.
1876 // It is important to unwind the context in the reverse order.
1877
1878 pop(didPerformWorkStackCursor, workInProgress);
1879 pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed.
1880
1881 push(contextStackCursor, mergedContext, workInProgress);
1882 push(didPerformWorkStackCursor, didChange, workInProgress);
1883 } else {
1884 pop(didPerformWorkStackCursor, workInProgress);
1885 push(didPerformWorkStackCursor, didChange, workInProgress);
1886 }
1887 }
1888 }
1889
1890 function findCurrentUnmaskedContext(fiber) {
1891 {
1892 // Currently this is only used with renderSubtreeIntoContainer; not sure if it
1893 // makes sense elsewhere
1894 if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) {
1895 {
1896 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." );
1897 }
1898 }
1899
1900 var node = fiber;
1901
1902 do {
1903 switch (node.tag) {
1904 case HostRoot:
1905 return node.stateNode.context;
1906
1907 case ClassComponent:
1908 {
1909 var Component = node.type;
1910
1911 if (isContextProvider(Component)) {
1912 return node.stateNode.__reactInternalMemoizedMergedChildContext;
1913 }
1914
1915 break;
1916 }
1917 }
1918
1919 node = node.return;
1920 } while (node !== null);
1921
1922 {
1923 {
1924 throw Error( "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." );
1925 }
1926 }
1927 }
1928 }
1929
1930 var rendererID = null;
1931 var injectedHook = null;
1932 var hasLoggedError = false;
1933 var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
1934 function injectInternals(internals) {
1935 if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
1936 // No DevTools
1937 return false;
1938 }
1939
1940 var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
1941
1942 if (hook.isDisabled) {
1943 // This isn't a real property on the hook, but it can be set to opt out
1944 // of DevTools integration and associated warnings and logs.
1945 // https://github.com/facebook/react/issues/3877
1946 return true;
1947 }
1948
1949 if (!hook.supportsFiber) {
1950 {
1951 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');
1952 } // DevTools exists, even though it doesn't support Fiber.
1953
1954
1955 return true;
1956 }
1957
1958 try {
1959 rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks.
1960
1961 injectedHook = hook;
1962 } catch (err) {
1963 // Catch all errors because it is unsafe to throw during initialization.
1964 {
1965 error('React instrumentation encountered an error: %s.', err);
1966 }
1967 } // DevTools exists
1968
1969
1970 return true;
1971 }
1972 function onScheduleRoot(root, children) {
1973 {
1974 if (injectedHook && typeof injectedHook.onScheduleFiberRoot === 'function') {
1975 try {
1976 injectedHook.onScheduleFiberRoot(rendererID, root, children);
1977 } catch (err) {
1978 if ( !hasLoggedError) {
1979 hasLoggedError = true;
1980
1981 error('React instrumentation encountered an error: %s', err);
1982 }
1983 }
1984 }
1985 }
1986 }
1987 function onCommitRoot(root, priorityLevel) {
1988 if (injectedHook && typeof injectedHook.onCommitFiberRoot === 'function') {
1989 try {
1990 var didError = (root.current.flags & DidCapture) === DidCapture;
1991
1992 if (enableProfilerTimer) {
1993 injectedHook.onCommitFiberRoot(rendererID, root, priorityLevel, didError);
1994 } else {
1995 injectedHook.onCommitFiberRoot(rendererID, root, undefined, didError);
1996 }
1997 } catch (err) {
1998 {
1999 if (!hasLoggedError) {
2000 hasLoggedError = true;
2001
2002 error('React instrumentation encountered an error: %s', err);
2003 }
2004 }
2005 }
2006 }
2007 }
2008 function onCommitUnmount(fiber) {
2009 if (injectedHook && typeof injectedHook.onCommitFiberUnmount === 'function') {
2010 try {
2011 injectedHook.onCommitFiberUnmount(rendererID, fiber);
2012 } catch (err) {
2013 {
2014 if (!hasLoggedError) {
2015 hasLoggedError = true;
2016
2017 error('React instrumentation encountered an error: %s', err);
2018 }
2019 }
2020 }
2021 }
2022 }
2023
2024 var ReactInternals$1 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
2025 var _ReactInternals$Sched = ReactInternals$1.Scheduler,
2026 unstable_cancelCallback = _ReactInternals$Sched.unstable_cancelCallback,
2027 unstable_now = _ReactInternals$Sched.unstable_now,
2028 unstable_scheduleCallback = _ReactInternals$Sched.unstable_scheduleCallback,
2029 unstable_shouldYield = _ReactInternals$Sched.unstable_shouldYield,
2030 unstable_requestPaint = _ReactInternals$Sched.unstable_requestPaint,
2031 unstable_getFirstCallbackNode = _ReactInternals$Sched.unstable_getFirstCallbackNode,
2032 unstable_runWithPriority = _ReactInternals$Sched.unstable_runWithPriority,
2033 unstable_next = _ReactInternals$Sched.unstable_next,
2034 unstable_continueExecution = _ReactInternals$Sched.unstable_continueExecution,
2035 unstable_pauseExecution = _ReactInternals$Sched.unstable_pauseExecution,
2036 unstable_getCurrentPriorityLevel = _ReactInternals$Sched.unstable_getCurrentPriorityLevel,
2037 unstable_ImmediatePriority = _ReactInternals$Sched.unstable_ImmediatePriority,
2038 unstable_UserBlockingPriority = _ReactInternals$Sched.unstable_UserBlockingPriority,
2039 unstable_NormalPriority = _ReactInternals$Sched.unstable_NormalPriority,
2040 unstable_LowPriority = _ReactInternals$Sched.unstable_LowPriority,
2041 unstable_IdlePriority = _ReactInternals$Sched.unstable_IdlePriority,
2042 unstable_forceFrameRate = _ReactInternals$Sched.unstable_forceFrameRate,
2043 unstable_flushAllWithoutAsserting = _ReactInternals$Sched.unstable_flushAllWithoutAsserting;
2044
2045 var ReactInternals$2 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
2046 var _ReactInternals$Sched$1 = ReactInternals$2.SchedulerTracing,
2047 __interactionsRef = _ReactInternals$Sched$1.__interactionsRef,
2048 __subscriberRef = _ReactInternals$Sched$1.__subscriberRef,
2049 unstable_clear = _ReactInternals$Sched$1.unstable_clear,
2050 unstable_getCurrent = _ReactInternals$Sched$1.unstable_getCurrent,
2051 unstable_getThreadID = _ReactInternals$Sched$1.unstable_getThreadID,
2052 unstable_subscribe = _ReactInternals$Sched$1.unstable_subscribe,
2053 unstable_trace = _ReactInternals$Sched$1.unstable_trace,
2054 unstable_unsubscribe = _ReactInternals$Sched$1.unstable_unsubscribe,
2055 unstable_wrap = _ReactInternals$Sched$1.unstable_wrap;
2056
2057 var Scheduler_now = unstable_now;
2058
2059 {
2060 // Provide explicit error message when production+profiling bundle of e.g.
2061 // react-dom is used with production (non-profiling) bundle of
2062 // scheduler/tracing
2063 if (!(__interactionsRef != null && __interactionsRef.current != null)) {
2064 {
2065 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" );
2066 }
2067 }
2068 }
2069 // ascending numbers so we can compare them like numbers. They start at 90 to
2070 // avoid clashing with Scheduler's priorities.
2071
2072 var ImmediatePriority = 99;
2073 var UserBlockingPriority = 98;
2074 var NormalPriority = 97;
2075 var LowPriority = 96;
2076 var IdlePriority = 95; // NoPriority is the absence of priority. Also React-only.
2077
2078 var NoPriority = 90;
2079 var initialTimeMs = Scheduler_now(); // If the initial timestamp is reasonably small, use Scheduler's `now` directly.
2080
2081 var SyncLanePriority = 15;
2082 var SyncBatchedLanePriority = 14;
2083 var InputDiscreteHydrationLanePriority = 13;
2084 var InputDiscreteLanePriority = 12;
2085 var InputContinuousHydrationLanePriority = 11;
2086 var InputContinuousLanePriority = 10;
2087 var DefaultHydrationLanePriority = 9;
2088 var DefaultLanePriority = 8;
2089 var TransitionHydrationPriority = 7;
2090 var TransitionPriority = 6;
2091 var RetryLanePriority = 5;
2092 var SelectiveHydrationLanePriority = 4;
2093 var IdleHydrationLanePriority = 3;
2094 var IdleLanePriority = 2;
2095 var OffscreenLanePriority = 1;
2096 var NoLanePriority = 0;
2097 var TotalLanes = 31;
2098 var NoLanes =
2099 /* */
2100 0;
2101 var NoLane =
2102 /* */
2103 0;
2104 var SyncLane =
2105 /* */
2106 1;
2107 var SyncBatchedLane =
2108 /* */
2109 2;
2110 var InputDiscreteHydrationLane =
2111 /* */
2112 4;
2113 var InputDiscreteLanes =
2114 /* */
2115 24;
2116 var InputContinuousHydrationLane =
2117 /* */
2118 32;
2119 var InputContinuousLanes =
2120 /* */
2121 192;
2122 var DefaultHydrationLane =
2123 /* */
2124 256;
2125 var DefaultLanes =
2126 /* */
2127 3584;
2128 var TransitionHydrationLane =
2129 /* */
2130 4096;
2131 var TransitionLanes =
2132 /* */
2133 4186112;
2134 var RetryLanes =
2135 /* */
2136 62914560;
2137 var SomeRetryLane =
2138 /* */
2139 33554432;
2140 var SelectiveHydrationLane =
2141 /* */
2142 67108864;
2143 var NonIdleLanes =
2144 /* */
2145 134217727;
2146 var IdleHydrationLane =
2147 /* */
2148 134217728;
2149 var IdleLanes =
2150 /* */
2151 805306368;
2152 var OffscreenLane =
2153 /* */
2154 1073741824;
2155 var NoTimestamp = -1;
2156 // Used by getHighestPriorityLanes and getNextLanes:
2157
2158 var return_highestLanePriority = DefaultLanePriority;
2159
2160 function getHighestPriorityLanes(lanes) {
2161 if ((SyncLane & lanes) !== NoLanes) {
2162 return_highestLanePriority = SyncLanePriority;
2163 return SyncLane;
2164 }
2165
2166 if ((SyncBatchedLane & lanes) !== NoLanes) {
2167 return_highestLanePriority = SyncBatchedLanePriority;
2168 return SyncBatchedLane;
2169 }
2170
2171 if ((InputDiscreteHydrationLane & lanes) !== NoLanes) {
2172 return_highestLanePriority = InputDiscreteHydrationLanePriority;
2173 return InputDiscreteHydrationLane;
2174 }
2175
2176 var inputDiscreteLanes = InputDiscreteLanes & lanes;
2177
2178 if (inputDiscreteLanes !== NoLanes) {
2179 return_highestLanePriority = InputDiscreteLanePriority;
2180 return inputDiscreteLanes;
2181 }
2182
2183 if ((lanes & InputContinuousHydrationLane) !== NoLanes) {
2184 return_highestLanePriority = InputContinuousHydrationLanePriority;
2185 return InputContinuousHydrationLane;
2186 }
2187
2188 var inputContinuousLanes = InputContinuousLanes & lanes;
2189
2190 if (inputContinuousLanes !== NoLanes) {
2191 return_highestLanePriority = InputContinuousLanePriority;
2192 return inputContinuousLanes;
2193 }
2194
2195 if ((lanes & DefaultHydrationLane) !== NoLanes) {
2196 return_highestLanePriority = DefaultHydrationLanePriority;
2197 return DefaultHydrationLane;
2198 }
2199
2200 var defaultLanes = DefaultLanes & lanes;
2201
2202 if (defaultLanes !== NoLanes) {
2203 return_highestLanePriority = DefaultLanePriority;
2204 return defaultLanes;
2205 }
2206
2207 if ((lanes & TransitionHydrationLane) !== NoLanes) {
2208 return_highestLanePriority = TransitionHydrationPriority;
2209 return TransitionHydrationLane;
2210 }
2211
2212 var transitionLanes = TransitionLanes & lanes;
2213
2214 if (transitionLanes !== NoLanes) {
2215 return_highestLanePriority = TransitionPriority;
2216 return transitionLanes;
2217 }
2218
2219 var retryLanes = RetryLanes & lanes;
2220
2221 if (retryLanes !== NoLanes) {
2222 return_highestLanePriority = RetryLanePriority;
2223 return retryLanes;
2224 }
2225
2226 if (lanes & SelectiveHydrationLane) {
2227 return_highestLanePriority = SelectiveHydrationLanePriority;
2228 return SelectiveHydrationLane;
2229 }
2230
2231 if ((lanes & IdleHydrationLane) !== NoLanes) {
2232 return_highestLanePriority = IdleHydrationLanePriority;
2233 return IdleHydrationLane;
2234 }
2235
2236 var idleLanes = IdleLanes & lanes;
2237
2238 if (idleLanes !== NoLanes) {
2239 return_highestLanePriority = IdleLanePriority;
2240 return idleLanes;
2241 }
2242
2243 if ((OffscreenLane & lanes) !== NoLanes) {
2244 return_highestLanePriority = OffscreenLanePriority;
2245 return OffscreenLane;
2246 }
2247
2248 {
2249 error('Should have found matching lanes. This is a bug in React.');
2250 } // This shouldn't be reachable, but as a fallback, return the entire bitmask.
2251
2252
2253 return_highestLanePriority = DefaultLanePriority;
2254 return lanes;
2255 }
2256
2257 function schedulerPriorityToLanePriority(schedulerPriorityLevel) {
2258 switch (schedulerPriorityLevel) {
2259 case ImmediatePriority:
2260 return SyncLanePriority;
2261
2262 case UserBlockingPriority:
2263 return InputContinuousLanePriority;
2264
2265 case NormalPriority:
2266 case LowPriority:
2267 // TODO: Handle LowSchedulerPriority, somehow. Maybe the same lane as hydration.
2268 return DefaultLanePriority;
2269
2270 case IdlePriority:
2271 return IdleLanePriority;
2272
2273 default:
2274 return NoLanePriority;
2275 }
2276 }
2277 function lanePriorityToSchedulerPriority(lanePriority) {
2278 switch (lanePriority) {
2279 case SyncLanePriority:
2280 case SyncBatchedLanePriority:
2281 return ImmediatePriority;
2282
2283 case InputDiscreteHydrationLanePriority:
2284 case InputDiscreteLanePriority:
2285 case InputContinuousHydrationLanePriority:
2286 case InputContinuousLanePriority:
2287 return UserBlockingPriority;
2288
2289 case DefaultHydrationLanePriority:
2290 case DefaultLanePriority:
2291 case TransitionHydrationPriority:
2292 case TransitionPriority:
2293 case SelectiveHydrationLanePriority:
2294 case RetryLanePriority:
2295 return NormalPriority;
2296
2297 case IdleHydrationLanePriority:
2298 case IdleLanePriority:
2299 case OffscreenLanePriority:
2300 return IdlePriority;
2301
2302 case NoLanePriority:
2303 return NoPriority;
2304
2305 default:
2306 {
2307 {
2308 throw Error( "Invalid update priority: " + lanePriority + ". This is a bug in React." );
2309 }
2310 }
2311
2312 }
2313 }
2314 function getNextLanes(root, wipLanes) {
2315 // Early bailout if there's no pending work left.
2316 var pendingLanes = root.pendingLanes;
2317
2318 if (pendingLanes === NoLanes) {
2319 return_highestLanePriority = NoLanePriority;
2320 return NoLanes;
2321 }
2322
2323 var nextLanes = NoLanes;
2324 var nextLanePriority = NoLanePriority;
2325 var expiredLanes = root.expiredLanes;
2326 var suspendedLanes = root.suspendedLanes;
2327 var pingedLanes = root.pingedLanes; // Check if any work has expired.
2328
2329 if (expiredLanes !== NoLanes) {
2330 nextLanes = expiredLanes;
2331 nextLanePriority = return_highestLanePriority = SyncLanePriority;
2332 } else {
2333 // Do not work on any idle work until all the non-idle work has finished,
2334 // even if the work is suspended.
2335 var nonIdlePendingLanes = pendingLanes & NonIdleLanes;
2336
2337 if (nonIdlePendingLanes !== NoLanes) {
2338 var nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes;
2339
2340 if (nonIdleUnblockedLanes !== NoLanes) {
2341 nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes);
2342 nextLanePriority = return_highestLanePriority;
2343 } else {
2344 var nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes;
2345
2346 if (nonIdlePingedLanes !== NoLanes) {
2347 nextLanes = getHighestPriorityLanes(nonIdlePingedLanes);
2348 nextLanePriority = return_highestLanePriority;
2349 }
2350 }
2351 } else {
2352 // The only remaining work is Idle.
2353 var unblockedLanes = pendingLanes & ~suspendedLanes;
2354
2355 if (unblockedLanes !== NoLanes) {
2356 nextLanes = getHighestPriorityLanes(unblockedLanes);
2357 nextLanePriority = return_highestLanePriority;
2358 } else {
2359 if (pingedLanes !== NoLanes) {
2360 nextLanes = getHighestPriorityLanes(pingedLanes);
2361 nextLanePriority = return_highestLanePriority;
2362 }
2363 }
2364 }
2365 }
2366
2367 if (nextLanes === NoLanes) {
2368 // This should only be reachable if we're suspended
2369 // TODO: Consider warning in this path if a fallback timer is not scheduled.
2370 return NoLanes;
2371 } // If there are higher priority lanes, we'll include them even if they
2372 // are suspended.
2373
2374
2375 nextLanes = pendingLanes & getEqualOrHigherPriorityLanes(nextLanes); // If we're already in the middle of a render, switching lanes will interrupt
2376 // it and we'll lose our progress. We should only do this if the new lanes are
2377 // higher priority.
2378
2379 if (wipLanes !== NoLanes && wipLanes !== nextLanes && // If we already suspended with a delay, then interrupting is fine. Don't
2380 // bother waiting until the root is complete.
2381 (wipLanes & suspendedLanes) === NoLanes) {
2382 getHighestPriorityLanes(wipLanes);
2383 var wipLanePriority = return_highestLanePriority;
2384
2385 if (nextLanePriority <= wipLanePriority) {
2386 return wipLanes;
2387 } else {
2388 return_highestLanePriority = nextLanePriority;
2389 }
2390 } // Check for entangled lanes and add them to the batch.
2391 //
2392 // A lane is said to be entangled with another when it's not allowed to render
2393 // in a batch that does not also include the other lane. Typically we do this
2394 // when multiple updates have the same source, and we only want to respond to
2395 // the most recent event from that source.
2396 //
2397 // Note that we apply entanglements *after* checking for partial work above.
2398 // This means that if a lane is entangled during an interleaved event while
2399 // it's already rendering, we won't interrupt it. This is intentional, since
2400 // entanglement is usually "best effort": we'll try our best to render the
2401 // lanes in the same batch, but it's not worth throwing out partially
2402 // completed work in order to do it.
2403 //
2404 // For those exceptions where entanglement is semantically important, like
2405 // useMutableSource, we should ensure that there is no partial work at the
2406 // time we apply the entanglement.
2407
2408
2409 var entangledLanes = root.entangledLanes;
2410
2411 if (entangledLanes !== NoLanes) {
2412 var entanglements = root.entanglements;
2413 var lanes = nextLanes & entangledLanes;
2414
2415 while (lanes > 0) {
2416 var index = pickArbitraryLaneIndex(lanes);
2417 var lane = 1 << index;
2418 nextLanes |= entanglements[index];
2419 lanes &= ~lane;
2420 }
2421 }
2422
2423 return nextLanes;
2424 }
2425 function getMostRecentEventTime(root, lanes) {
2426 var eventTimes = root.eventTimes;
2427 var mostRecentEventTime = NoTimestamp;
2428
2429 while (lanes > 0) {
2430 var index = pickArbitraryLaneIndex(lanes);
2431 var lane = 1 << index;
2432 var eventTime = eventTimes[index];
2433
2434 if (eventTime > mostRecentEventTime) {
2435 mostRecentEventTime = eventTime;
2436 }
2437
2438 lanes &= ~lane;
2439 }
2440
2441 return mostRecentEventTime;
2442 }
2443
2444 function computeExpirationTime(lane, currentTime) {
2445 // TODO: Expiration heuristic is constant per lane, so could use a map.
2446 getHighestPriorityLanes(lane);
2447 var priority = return_highestLanePriority;
2448
2449 if (priority >= InputContinuousLanePriority) {
2450 // User interactions should expire slightly more quickly.
2451 //
2452 // NOTE: This is set to the corresponding constant as in Scheduler.js. When
2453 // we made it larger, a product metric in www regressed, suggesting there's
2454 // a user interaction that's being starved by a series of synchronous
2455 // updates. If that theory is correct, the proper solution is to fix the
2456 // starvation. However, this scenario supports the idea that expiration
2457 // times are an important safeguard when starvation does happen.
2458 //
2459 // Also note that, in the case of user input specifically, this will soon no
2460 // longer be an issue because we plan to make user input synchronous by
2461 // default (until you enter `startTransition`, of course.)
2462 //
2463 // If weren't planning to make these updates synchronous soon anyway, I
2464 // would probably make this number a configurable parameter.
2465 return currentTime + 250;
2466 } else if (priority >= TransitionPriority) {
2467 return currentTime + 5000;
2468 } else {
2469 // Anything idle priority or lower should never expire.
2470 return NoTimestamp;
2471 }
2472 }
2473
2474 function markStarvedLanesAsExpired(root, currentTime) {
2475 // TODO: This gets called every time we yield. We can optimize by storing
2476 // the earliest expiration time on the root. Then use that to quickly bail out
2477 // of this function.
2478 var pendingLanes = root.pendingLanes;
2479 var suspendedLanes = root.suspendedLanes;
2480 var pingedLanes = root.pingedLanes;
2481 var expirationTimes = root.expirationTimes; // Iterate through the pending lanes and check if we've reached their
2482 // expiration time. If so, we'll assume the update is being starved and mark
2483 // it as expired to force it to finish.
2484
2485 var lanes = pendingLanes;
2486
2487 while (lanes > 0) {
2488 var index = pickArbitraryLaneIndex(lanes);
2489 var lane = 1 << index;
2490 var expirationTime = expirationTimes[index];
2491
2492 if (expirationTime === NoTimestamp) {
2493 // Found a pending lane with no expiration time. If it's not suspended, or
2494 // if it's pinged, assume it's CPU-bound. Compute a new expiration time
2495 // using the current time.
2496 if ((lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes) {
2497 // Assumes timestamps are monotonically increasing.
2498 expirationTimes[index] = computeExpirationTime(lane, currentTime);
2499 }
2500 } else if (expirationTime <= currentTime) {
2501 // This lane expired
2502 root.expiredLanes |= lane;
2503 }
2504
2505 lanes &= ~lane;
2506 }
2507 } // This returns the highest priority pending lanes regardless of whether they
2508 function getLanesToRetrySynchronouslyOnError(root) {
2509 var everythingButOffscreen = root.pendingLanes & ~OffscreenLane;
2510
2511 if (everythingButOffscreen !== NoLanes) {
2512 return everythingButOffscreen;
2513 }
2514
2515 if (everythingButOffscreen & OffscreenLane) {
2516 return OffscreenLane;
2517 }
2518
2519 return NoLanes;
2520 }
2521 function returnNextLanesPriority() {
2522 return return_highestLanePriority;
2523 }
2524 function includesNonIdleWork(lanes) {
2525 return (lanes & NonIdleLanes) !== NoLanes;
2526 }
2527 function includesOnlyRetries(lanes) {
2528 return (lanes & RetryLanes) === lanes;
2529 }
2530 function includesOnlyTransitions(lanes) {
2531 return (lanes & TransitionLanes) === lanes;
2532 } // To ensure consistency across multiple updates in the same event, this should
2533 // be a pure function, so that it always returns the same lane for given inputs.
2534
2535 function findUpdateLane(lanePriority, wipLanes) {
2536 switch (lanePriority) {
2537 case NoLanePriority:
2538 break;
2539
2540 case SyncLanePriority:
2541 return SyncLane;
2542
2543 case SyncBatchedLanePriority:
2544 return SyncBatchedLane;
2545
2546 case InputDiscreteLanePriority:
2547 {
2548 var _lane = pickArbitraryLane(InputDiscreteLanes & ~wipLanes);
2549
2550 if (_lane === NoLane) {
2551 // Shift to the next priority level
2552 return findUpdateLane(InputContinuousLanePriority, wipLanes);
2553 }
2554
2555 return _lane;
2556 }
2557
2558 case InputContinuousLanePriority:
2559 {
2560 var _lane2 = pickArbitraryLane(InputContinuousLanes & ~wipLanes);
2561
2562 if (_lane2 === NoLane) {
2563 // Shift to the next priority level
2564 return findUpdateLane(DefaultLanePriority, wipLanes);
2565 }
2566
2567 return _lane2;
2568 }
2569
2570 case DefaultLanePriority:
2571 {
2572 var _lane3 = pickArbitraryLane(DefaultLanes & ~wipLanes);
2573
2574 if (_lane3 === NoLane) {
2575 // If all the default lanes are already being worked on, look for a
2576 // lane in the transition range.
2577 _lane3 = pickArbitraryLane(TransitionLanes & ~wipLanes);
2578
2579 if (_lane3 === NoLane) {
2580 // All the transition lanes are taken, too. This should be very
2581 // rare, but as a last resort, pick a default lane. This will have
2582 // the effect of interrupting the current work-in-progress render.
2583 _lane3 = pickArbitraryLane(DefaultLanes);
2584 }
2585 }
2586
2587 return _lane3;
2588 }
2589
2590 case TransitionPriority: // Should be handled by findTransitionLane instead
2591
2592 case RetryLanePriority:
2593 // Should be handled by findRetryLane instead
2594 break;
2595
2596 case IdleLanePriority:
2597 var lane = pickArbitraryLane(IdleLanes & ~wipLanes);
2598
2599 if (lane === NoLane) {
2600 lane = pickArbitraryLane(IdleLanes);
2601 }
2602
2603 return lane;
2604 }
2605
2606 {
2607 {
2608 throw Error( "Invalid update priority: " + lanePriority + ". This is a bug in React." );
2609 }
2610 }
2611 } // To ensure consistency across multiple updates in the same event, this should
2612 // be pure function, so that it always returns the same lane for given inputs.
2613
2614 function findTransitionLane(wipLanes, pendingLanes) {
2615 // First look for lanes that are completely unclaimed, i.e. have no
2616 // pending work.
2617 var lane = pickArbitraryLane(TransitionLanes & ~pendingLanes);
2618
2619 if (lane === NoLane) {
2620 // If all lanes have pending work, look for a lane that isn't currently
2621 // being worked on.
2622 lane = pickArbitraryLane(TransitionLanes & ~wipLanes);
2623
2624 if (lane === NoLane) {
2625 // If everything is being worked on, pick any lane. This has the
2626 // effect of interrupting the current work-in-progress.
2627 lane = pickArbitraryLane(TransitionLanes);
2628 }
2629 }
2630
2631 return lane;
2632 } // To ensure consistency across multiple updates in the same event, this should
2633 // be pure function, so that it always returns the same lane for given inputs.
2634
2635 function findRetryLane(wipLanes) {
2636 // This is a fork of `findUpdateLane` designed specifically for Suspense
2637 // "retries" — a special update that attempts to flip a Suspense boundary
2638 // from its placeholder state to its primary/resolved state.
2639 var lane = pickArbitraryLane(RetryLanes & ~wipLanes);
2640
2641 if (lane === NoLane) {
2642 lane = pickArbitraryLane(RetryLanes);
2643 }
2644
2645 return lane;
2646 }
2647
2648 function getHighestPriorityLane(lanes) {
2649 return lanes & -lanes;
2650 }
2651
2652 function getLowestPriorityLane(lanes) {
2653 // This finds the most significant non-zero bit.
2654 var index = 31 - clz32(lanes);
2655 return index < 0 ? NoLanes : 1 << index;
2656 }
2657
2658 function getEqualOrHigherPriorityLanes(lanes) {
2659 return (getLowestPriorityLane(lanes) << 1) - 1;
2660 }
2661
2662 function pickArbitraryLane(lanes) {
2663 // This wrapper function gets inlined. Only exists so to communicate that it
2664 // doesn't matter which bit is selected; you can pick any bit without
2665 // affecting the algorithms where its used. Here I'm using
2666 // getHighestPriorityLane because it requires the fewest operations.
2667 return getHighestPriorityLane(lanes);
2668 }
2669
2670 function pickArbitraryLaneIndex(lanes) {
2671 return 31 - clz32(lanes);
2672 }
2673
2674 function laneToIndex(lane) {
2675 return pickArbitraryLaneIndex(lane);
2676 }
2677
2678 function includesSomeLane(a, b) {
2679 return (a & b) !== NoLanes;
2680 }
2681 function isSubsetOfLanes(set, subset) {
2682 return (set & subset) === subset;
2683 }
2684 function mergeLanes(a, b) {
2685 return a | b;
2686 }
2687 function removeLanes(set, subset) {
2688 return set & ~subset;
2689 } // Seems redundant, but it changes the type from a single lane (used for
2690 // updates) to a group of lanes (used for flushing work).
2691
2692 function laneToLanes(lane) {
2693 return lane;
2694 }
2695 function createLaneMap(initial) {
2696 // Intentionally pushing one by one.
2697 // https://v8.dev/blog/elements-kinds#avoid-creating-holes
2698 var laneMap = [];
2699
2700 for (var i = 0; i < TotalLanes; i++) {
2701 laneMap.push(initial);
2702 }
2703
2704 return laneMap;
2705 }
2706 function markRootUpdated(root, updateLane, eventTime) {
2707 root.pendingLanes |= updateLane; // TODO: Theoretically, any update to any lane can unblock any other lane. But
2708 // it's not practical to try every single possible combination. We need a
2709 // heuristic to decide which lanes to attempt to render, and in which batches.
2710 // For now, we use the same heuristic as in the old ExpirationTimes model:
2711 // retry any lane at equal or lower priority, but don't try updates at higher
2712 // priority without also including the lower priority updates. This works well
2713 // when considering updates across different priority levels, but isn't
2714 // sufficient for updates within the same priority, since we want to treat
2715 // those updates as parallel.
2716 // Unsuspend any update at equal or lower priority.
2717
2718 var higherPriorityLanes = updateLane - 1; // Turns 0b1000 into 0b0111
2719
2720 root.suspendedLanes &= higherPriorityLanes;
2721 root.pingedLanes &= higherPriorityLanes;
2722 var eventTimes = root.eventTimes;
2723 var index = laneToIndex(updateLane); // We can always overwrite an existing timestamp because we prefer the most
2724 // recent event, and we assume time is monotonically increasing.
2725
2726 eventTimes[index] = eventTime;
2727 }
2728 function markRootSuspended(root, suspendedLanes) {
2729 root.suspendedLanes |= suspendedLanes;
2730 root.pingedLanes &= ~suspendedLanes; // The suspended lanes are no longer CPU-bound. Clear their expiration times.
2731
2732 var expirationTimes = root.expirationTimes;
2733 var lanes = suspendedLanes;
2734
2735 while (lanes > 0) {
2736 var index = pickArbitraryLaneIndex(lanes);
2737 var lane = 1 << index;
2738 expirationTimes[index] = NoTimestamp;
2739 lanes &= ~lane;
2740 }
2741 }
2742 function markRootPinged(root, pingedLanes, eventTime) {
2743 root.pingedLanes |= root.suspendedLanes & pingedLanes;
2744 }
2745 function hasDiscreteLanes(lanes) {
2746 return (lanes & InputDiscreteLanes) !== NoLanes;
2747 }
2748 function markRootMutableRead(root, updateLane) {
2749 root.mutableReadLanes |= updateLane & root.pendingLanes;
2750 }
2751 function markRootFinished(root, remainingLanes) {
2752 var noLongerPendingLanes = root.pendingLanes & ~remainingLanes;
2753 root.pendingLanes = remainingLanes; // Let's try everything again
2754
2755 root.suspendedLanes = 0;
2756 root.pingedLanes = 0;
2757 root.expiredLanes &= remainingLanes;
2758 root.mutableReadLanes &= remainingLanes;
2759 root.entangledLanes &= remainingLanes;
2760 var entanglements = root.entanglements;
2761 var eventTimes = root.eventTimes;
2762 var expirationTimes = root.expirationTimes; // Clear the lanes that no longer have pending work
2763
2764 var lanes = noLongerPendingLanes;
2765
2766 while (lanes > 0) {
2767 var index = pickArbitraryLaneIndex(lanes);
2768 var lane = 1 << index;
2769 entanglements[index] = NoLanes;
2770 eventTimes[index] = NoTimestamp;
2771 expirationTimes[index] = NoTimestamp;
2772 lanes &= ~lane;
2773 }
2774 }
2775 function markRootEntangled(root, entangledLanes) {
2776 root.entangledLanes |= entangledLanes;
2777 var entanglements = root.entanglements;
2778 var lanes = entangledLanes;
2779
2780 while (lanes > 0) {
2781 var index = pickArbitraryLaneIndex(lanes);
2782 var lane = 1 << index;
2783 entanglements[index] |= entangledLanes;
2784 lanes &= ~lane;
2785 }
2786 }
2787 var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. Only used on lanes, so assume input is an integer.
2788 // Based on:
2789 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32
2790
2791 var log = Math.log;
2792 var LN2 = Math.LN2;
2793
2794 function clz32Fallback(lanes) {
2795 if (lanes === 0) {
2796 return 32;
2797 }
2798
2799 return 31 - (log(lanes) / LN2 | 0) | 0;
2800 }
2801
2802 var Scheduler_runWithPriority = unstable_runWithPriority,
2803 Scheduler_scheduleCallback = unstable_scheduleCallback,
2804 Scheduler_cancelCallback = unstable_cancelCallback,
2805 Scheduler_shouldYield = unstable_shouldYield,
2806 Scheduler_requestPaint = unstable_requestPaint,
2807 Scheduler_now$1 = unstable_now,
2808 Scheduler_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel,
2809 Scheduler_ImmediatePriority = unstable_ImmediatePriority,
2810 Scheduler_UserBlockingPriority = unstable_UserBlockingPriority,
2811 Scheduler_NormalPriority = unstable_NormalPriority,
2812 Scheduler_LowPriority = unstable_LowPriority,
2813 Scheduler_IdlePriority = unstable_IdlePriority;
2814
2815 {
2816 // Provide explicit error message when production+profiling bundle of e.g.
2817 // react-dom is used with production (non-profiling) bundle of
2818 // scheduler/tracing
2819 if (!(__interactionsRef != null && __interactionsRef.current != null)) {
2820 {
2821 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" );
2822 }
2823 }
2824 }
2825
2826 var fakeCallbackNode = {}; // Except for NoPriority, these correspond to Scheduler priorities. We use
2827 // ascending numbers so we can compare them like numbers. They start at 90 to
2828 // avoid clashing with Scheduler's priorities.
2829
2830 var ImmediatePriority$1 = 99;
2831 var UserBlockingPriority$1 = 98;
2832 var NormalPriority$1 = 97;
2833 var LowPriority$1 = 96;
2834 var IdlePriority$1 = 95; // NoPriority is the absence of priority. Also React-only.
2835
2836 var NoPriority$1 = 90;
2837 var shouldYield = Scheduler_shouldYield;
2838 var requestPaint = // Fall back gracefully if we're running an older version of Scheduler.
2839 Scheduler_requestPaint !== undefined ? Scheduler_requestPaint : function () {};
2840 var syncQueue = null;
2841 var immediateQueueCallbackNode = null;
2842 var isFlushingSyncQueue = false;
2843 var initialTimeMs$1 = Scheduler_now$1(); // If the initial timestamp is reasonably small, use Scheduler's `now` directly.
2844 // This will be the case for modern browsers that support `performance.now`. In
2845 // older browsers, Scheduler falls back to `Date.now`, which returns a Unix
2846 // timestamp. In that case, subtract the module initialization time to simulate
2847 // the behavior of performance.now and keep our times small enough to fit
2848 // within 32 bits.
2849 // TODO: Consider lifting this into Scheduler.
2850
2851 var now = initialTimeMs$1 < 10000 ? Scheduler_now$1 : function () {
2852 return Scheduler_now$1() - initialTimeMs$1;
2853 };
2854 function getCurrentPriorityLevel() {
2855 switch (Scheduler_getCurrentPriorityLevel()) {
2856 case Scheduler_ImmediatePriority:
2857 return ImmediatePriority$1;
2858
2859 case Scheduler_UserBlockingPriority:
2860 return UserBlockingPriority$1;
2861
2862 case Scheduler_NormalPriority:
2863 return NormalPriority$1;
2864
2865 case Scheduler_LowPriority:
2866 return LowPriority$1;
2867
2868 case Scheduler_IdlePriority:
2869 return IdlePriority$1;
2870
2871 default:
2872 {
2873 {
2874 throw Error( "Unknown priority level." );
2875 }
2876 }
2877
2878 }
2879 }
2880
2881 function reactPriorityToSchedulerPriority(reactPriorityLevel) {
2882 switch (reactPriorityLevel) {
2883 case ImmediatePriority$1:
2884 return Scheduler_ImmediatePriority;
2885
2886 case UserBlockingPriority$1:
2887 return Scheduler_UserBlockingPriority;
2888
2889 case NormalPriority$1:
2890 return Scheduler_NormalPriority;
2891
2892 case LowPriority$1:
2893 return Scheduler_LowPriority;
2894
2895 case IdlePriority$1:
2896 return Scheduler_IdlePriority;
2897
2898 default:
2899 {
2900 {
2901 throw Error( "Unknown priority level." );
2902 }
2903 }
2904
2905 }
2906 }
2907
2908 function runWithPriority(reactPriorityLevel, fn) {
2909 var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
2910 return Scheduler_runWithPriority(priorityLevel, fn);
2911 }
2912 function scheduleCallback(reactPriorityLevel, callback, options) {
2913 var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
2914 return Scheduler_scheduleCallback(priorityLevel, callback, options);
2915 }
2916 function scheduleSyncCallback(callback) {
2917 // Push this callback into an internal queue. We'll flush these either in
2918 // the next tick, or earlier if something calls `flushSyncCallbackQueue`.
2919 if (syncQueue === null) {
2920 syncQueue = [callback]; // Flush the queue in the next tick, at the earliest.
2921
2922 immediateQueueCallbackNode = Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueueImpl);
2923 } else {
2924 // Push onto existing queue. Don't need to schedule a callback because
2925 // we already scheduled one when we created the queue.
2926 syncQueue.push(callback);
2927 }
2928
2929 return fakeCallbackNode;
2930 }
2931 function cancelCallback(callbackNode) {
2932 if (callbackNode !== fakeCallbackNode) {
2933 Scheduler_cancelCallback(callbackNode);
2934 }
2935 }
2936 function flushSyncCallbackQueue() {
2937 if (immediateQueueCallbackNode !== null) {
2938 var node = immediateQueueCallbackNode;
2939 immediateQueueCallbackNode = null;
2940 Scheduler_cancelCallback(node);
2941 }
2942
2943 flushSyncCallbackQueueImpl();
2944 }
2945
2946 function flushSyncCallbackQueueImpl() {
2947 if (!isFlushingSyncQueue && syncQueue !== null) {
2948 // Prevent re-entrancy.
2949 isFlushingSyncQueue = true;
2950 var i = 0;
2951
2952 {
2953 try {
2954 var _isSync2 = true;
2955 var _queue = syncQueue;
2956 runWithPriority(ImmediatePriority$1, function () {
2957 for (; i < _queue.length; i++) {
2958 var callback = _queue[i];
2959
2960 do {
2961 callback = callback(_isSync2);
2962 } while (callback !== null);
2963 }
2964 });
2965 syncQueue = null;
2966 } catch (error) {
2967 // If something throws, leave the remaining callbacks on the queue.
2968 if (syncQueue !== null) {
2969 syncQueue = syncQueue.slice(i + 1);
2970 } // Resume flushing in the next tick
2971
2972
2973 Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueue);
2974 throw error;
2975 } finally {
2976 isFlushingSyncQueue = false;
2977 }
2978 }
2979 }
2980 }
2981
2982 var NoMode = 0;
2983 var StrictMode = 1; // TODO: Remove BlockingMode and ConcurrentMode by reading from the root
2984 // tag instead
2985
2986 var BlockingMode = 2;
2987 var ConcurrentMode = 4;
2988 var ProfileMode = 8;
2989 var DebugTracingMode = 16;
2990
2991 var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig;
2992 var NoTransition = 0;
2993 function requestCurrentTransition() {
2994 return ReactCurrentBatchConfig.transition;
2995 }
2996
2997 /**
2998 * inlined Object.is polyfill to avoid requiring consumers ship their own
2999 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
3000 */
3001 function is(x, y) {
3002 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
3003 ;
3004 }
3005
3006 var objectIs = typeof Object.is === 'function' ? Object.is : is;
3007
3008 var hasOwnProperty = Object.prototype.hasOwnProperty;
3009 /**
3010 * Performs equality by iterating through keys on an object and returning false
3011 * when any key has values which are not strictly equal between the arguments.
3012 * Returns true when the values of all keys are strictly equal.
3013 */
3014
3015 function shallowEqual(objA, objB) {
3016 if (objectIs(objA, objB)) {
3017 return true;
3018 }
3019
3020 if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
3021 return false;
3022 }
3023
3024 var keysA = Object.keys(objA);
3025 var keysB = Object.keys(objB);
3026
3027 if (keysA.length !== keysB.length) {
3028 return false;
3029 } // Test for A's keys different from B.
3030
3031
3032 for (var i = 0; i < keysA.length; i++) {
3033 if (!hasOwnProperty.call(objB, keysA[i]) || !objectIs(objA[keysA[i]], objB[keysA[i]])) {
3034 return false;
3035 }
3036 }
3037
3038 return true;
3039 }
3040
3041 function describeFiber(fiber) {
3042 var owner = fiber._debugOwner ? fiber._debugOwner.type : null ;
3043 var source = fiber._debugSource ;
3044
3045 switch (fiber.tag) {
3046 case HostComponent:
3047 return describeBuiltInComponentFrame(fiber.type);
3048
3049 case LazyComponent:
3050 return describeBuiltInComponentFrame('Lazy');
3051
3052 case SuspenseComponent:
3053 return describeBuiltInComponentFrame('Suspense');
3054
3055 case SuspenseListComponent:
3056 return describeBuiltInComponentFrame('SuspenseList');
3057
3058 case FunctionComponent:
3059 case IndeterminateComponent:
3060 case SimpleMemoComponent:
3061 return describeFunctionComponentFrame(fiber.type);
3062
3063 case ForwardRef:
3064 return describeFunctionComponentFrame(fiber.type.render);
3065
3066 case Block:
3067 return describeFunctionComponentFrame(fiber.type._render);
3068
3069 case ClassComponent:
3070 return describeClassComponentFrame(fiber.type);
3071
3072 default:
3073 return '';
3074 }
3075 }
3076
3077 function getStackByFiberInDevAndProd(workInProgress) {
3078 try {
3079 var info = '';
3080 var node = workInProgress;
3081
3082 do {
3083 info += describeFiber(node);
3084 node = node.return;
3085 } while (node);
3086
3087 return info;
3088 } catch (x) {
3089 return '\nError generating stack: ' + x.message + '\n' + x.stack;
3090 }
3091 }
3092
3093 var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
3094 var current$1 = null;
3095 var isRendering = false;
3096 function getCurrentFiberOwnerNameInDevOrNull() {
3097 {
3098 if (current$1 === null) {
3099 return null;
3100 }
3101
3102 var owner = current$1._debugOwner;
3103
3104 if (owner !== null && typeof owner !== 'undefined') {
3105 return getComponentName(owner.type);
3106 }
3107 }
3108
3109 return null;
3110 }
3111
3112 function getCurrentFiberStackInDev() {
3113 {
3114 if (current$1 === null) {
3115 return '';
3116 } // Safe because if current fiber exists, we are reconciling,
3117 // and it is guaranteed to be the work-in-progress version.
3118
3119
3120 return getStackByFiberInDevAndProd(current$1);
3121 }
3122 }
3123
3124 function resetCurrentFiber() {
3125 {
3126 ReactDebugCurrentFrame$1.getCurrentStack = null;
3127 current$1 = null;
3128 isRendering = false;
3129 }
3130 }
3131 function setCurrentFiber(fiber) {
3132 {
3133 ReactDebugCurrentFrame$1.getCurrentStack = getCurrentFiberStackInDev;
3134 current$1 = fiber;
3135 isRendering = false;
3136 }
3137 }
3138 function setIsRendering(rendering) {
3139 {
3140 isRendering = rendering;
3141 }
3142 }
3143 function getIsRendering() {
3144 {
3145 return isRendering;
3146 }
3147 }
3148
3149 var ReactStrictModeWarnings = {
3150 recordUnsafeLifecycleWarnings: function (fiber, instance) {},
3151 flushPendingUnsafeLifecycleWarnings: function () {},
3152 recordLegacyContextWarning: function (fiber, instance) {},
3153 flushLegacyContextWarning: function () {},
3154 discardPendingWarnings: function () {}
3155 };
3156
3157 {
3158 var findStrictRoot = function (fiber) {
3159 var maybeStrictRoot = null;
3160 var node = fiber;
3161
3162 while (node !== null) {
3163 if (node.mode & StrictMode) {
3164 maybeStrictRoot = node;
3165 }
3166
3167 node = node.return;
3168 }
3169
3170 return maybeStrictRoot;
3171 };
3172
3173 var setToSortedString = function (set) {
3174 var array = [];
3175 set.forEach(function (value) {
3176 array.push(value);
3177 });
3178 return array.sort().join(', ');
3179 };
3180
3181 var pendingComponentWillMountWarnings = [];
3182 var pendingUNSAFE_ComponentWillMountWarnings = [];
3183 var pendingComponentWillReceivePropsWarnings = [];
3184 var pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
3185 var pendingComponentWillUpdateWarnings = [];
3186 var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about.
3187
3188 var didWarnAboutUnsafeLifecycles = new Set();
3189
3190 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
3191 // Dedup strategy: Warn once per component.
3192 if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
3193 return;
3194 }
3195
3196 if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components.
3197 instance.componentWillMount.__suppressDeprecationWarning !== true) {
3198 pendingComponentWillMountWarnings.push(fiber);
3199 }
3200
3201 if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillMount === 'function') {
3202 pendingUNSAFE_ComponentWillMountWarnings.push(fiber);
3203 }
3204
3205 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
3206 pendingComponentWillReceivePropsWarnings.push(fiber);
3207 }
3208
3209 if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
3210 pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);
3211 }
3212
3213 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
3214 pendingComponentWillUpdateWarnings.push(fiber);
3215 }
3216
3217 if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillUpdate === 'function') {
3218 pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);
3219 }
3220 };
3221
3222 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
3223 // We do an initial pass to gather component names
3224 var componentWillMountUniqueNames = new Set();
3225
3226 if (pendingComponentWillMountWarnings.length > 0) {
3227 pendingComponentWillMountWarnings.forEach(function (fiber) {
3228 componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');
3229 didWarnAboutUnsafeLifecycles.add(fiber.type);
3230 });
3231 pendingComponentWillMountWarnings = [];
3232 }
3233
3234 var UNSAFE_componentWillMountUniqueNames = new Set();
3235
3236 if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) {
3237 pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) {
3238 UNSAFE_componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');
3239 didWarnAboutUnsafeLifecycles.add(fiber.type);
3240 });
3241 pendingUNSAFE_ComponentWillMountWarnings = [];
3242 }
3243
3244 var componentWillReceivePropsUniqueNames = new Set();
3245
3246 if (pendingComponentWillReceivePropsWarnings.length > 0) {
3247 pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
3248 componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');
3249 didWarnAboutUnsafeLifecycles.add(fiber.type);
3250 });
3251 pendingComponentWillReceivePropsWarnings = [];
3252 }
3253
3254 var UNSAFE_componentWillReceivePropsUniqueNames = new Set();
3255
3256 if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) {
3257 pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) {
3258 UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');
3259 didWarnAboutUnsafeLifecycles.add(fiber.type);
3260 });
3261 pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
3262 }
3263
3264 var componentWillUpdateUniqueNames = new Set();
3265
3266 if (pendingComponentWillUpdateWarnings.length > 0) {
3267 pendingComponentWillUpdateWarnings.forEach(function (fiber) {
3268 componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');
3269 didWarnAboutUnsafeLifecycles.add(fiber.type);
3270 });
3271 pendingComponentWillUpdateWarnings = [];
3272 }
3273
3274 var UNSAFE_componentWillUpdateUniqueNames = new Set();
3275
3276 if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) {
3277 pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) {
3278 UNSAFE_componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');
3279 didWarnAboutUnsafeLifecycles.add(fiber.type);
3280 });
3281 pendingUNSAFE_ComponentWillUpdateWarnings = [];
3282 } // Finally, we flush all the warnings
3283 // UNSAFE_ ones before the deprecated ones, since they'll be 'louder'
3284
3285
3286 if (UNSAFE_componentWillMountUniqueNames.size > 0) {
3287 var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames);
3288
3289 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);
3290 }
3291
3292 if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) {
3293 var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames);
3294
3295 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);
3296 }
3297
3298 if (UNSAFE_componentWillUpdateUniqueNames.size > 0) {
3299 var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames);
3300
3301 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);
3302 }
3303
3304 if (componentWillMountUniqueNames.size > 0) {
3305 var _sortedNames3 = setToSortedString(componentWillMountUniqueNames);
3306
3307 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);
3308 }
3309
3310 if (componentWillReceivePropsUniqueNames.size > 0) {
3311 var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);
3312
3313 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);
3314 }
3315
3316 if (componentWillUpdateUniqueNames.size > 0) {
3317 var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames);
3318
3319 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);
3320 }
3321 };
3322
3323 var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about.
3324
3325 var didWarnAboutLegacyContext = new Set();
3326
3327 ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
3328 var strictRoot = findStrictRoot(fiber);
3329
3330 if (strictRoot === null) {
3331 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.');
3332
3333 return;
3334 } // Dedup strategy: Warn once per component.
3335
3336
3337 if (didWarnAboutLegacyContext.has(fiber.type)) {
3338 return;
3339 }
3340
3341 var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
3342
3343 if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
3344 if (warningsForRoot === undefined) {
3345 warningsForRoot = [];
3346 pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
3347 }
3348
3349 warningsForRoot.push(fiber);
3350 }
3351 };
3352
3353 ReactStrictModeWarnings.flushLegacyContextWarning = function () {
3354 pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
3355 if (fiberArray.length === 0) {
3356 return;
3357 }
3358
3359 var firstFiber = fiberArray[0];
3360 var uniqueNames = new Set();
3361 fiberArray.forEach(function (fiber) {
3362 uniqueNames.add(getComponentName(fiber.type) || 'Component');
3363 didWarnAboutLegacyContext.add(fiber.type);
3364 });
3365 var sortedNames = setToSortedString(uniqueNames);
3366
3367 try {
3368 setCurrentFiber(firstFiber);
3369
3370 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);
3371 } finally {
3372 resetCurrentFiber();
3373 }
3374 });
3375 };
3376
3377 ReactStrictModeWarnings.discardPendingWarnings = function () {
3378 pendingComponentWillMountWarnings = [];
3379 pendingUNSAFE_ComponentWillMountWarnings = [];
3380 pendingComponentWillReceivePropsWarnings = [];
3381 pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
3382 pendingComponentWillUpdateWarnings = [];
3383 pendingUNSAFE_ComponentWillUpdateWarnings = [];
3384 pendingLegacyContextWarning = new Map();
3385 };
3386 }
3387
3388 function resolveDefaultProps(Component, baseProps) {
3389 if (Component && Component.defaultProps) {
3390 // Resolve default props. Taken from ReactElement
3391 var props = _assign({}, baseProps);
3392
3393 var defaultProps = Component.defaultProps;
3394
3395 for (var propName in defaultProps) {
3396 if (props[propName] === undefined) {
3397 props[propName] = defaultProps[propName];
3398 }
3399 }
3400
3401 return props;
3402 }
3403
3404 return baseProps;
3405 }
3406
3407 // Max 31 bit integer. The max integer size in V8 for 32-bit systems.
3408 // Math.pow(2, 30) - 1
3409 // 0b111111111111111111111111111111
3410 var MAX_SIGNED_31_BIT_INT = 1073741823;
3411
3412 var valueCursor = createCursor(null);
3413 var rendererSigil;
3414
3415 {
3416 // Use this to detect multiple renderers using the same context
3417 rendererSigil = {};
3418 }
3419
3420 var currentlyRenderingFiber = null;
3421 var lastContextDependency = null;
3422 var lastContextWithAllBitsObserved = null;
3423 var isDisallowedContextReadInDEV = false;
3424 function resetContextDependencies() {
3425 // This is called right before React yields execution, to ensure `readContext`
3426 // cannot be called outside the render phase.
3427 currentlyRenderingFiber = null;
3428 lastContextDependency = null;
3429 lastContextWithAllBitsObserved = null;
3430
3431 {
3432 isDisallowedContextReadInDEV = false;
3433 }
3434 }
3435 function enterDisallowedContextReadInDEV() {
3436 {
3437 isDisallowedContextReadInDEV = true;
3438 }
3439 }
3440 function exitDisallowedContextReadInDEV() {
3441 {
3442 isDisallowedContextReadInDEV = false;
3443 }
3444 }
3445 function pushProvider(providerFiber, nextValue) {
3446 var context = providerFiber.type._context;
3447
3448 {
3449 push(valueCursor, context._currentValue2, providerFiber);
3450 context._currentValue2 = nextValue;
3451
3452 {
3453 if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) {
3454 error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
3455 }
3456
3457 context._currentRenderer2 = rendererSigil;
3458 }
3459 }
3460 }
3461 function popProvider(providerFiber) {
3462 var currentValue = valueCursor.current;
3463 pop(valueCursor, providerFiber);
3464 var context = providerFiber.type._context;
3465
3466 {
3467 context._currentValue2 = currentValue;
3468 }
3469 }
3470 function calculateChangedBits(context, newValue, oldValue) {
3471 if (objectIs(oldValue, newValue)) {
3472 // No change
3473 return 0;
3474 } else {
3475 var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;
3476
3477 {
3478 if ((changedBits & MAX_SIGNED_31_BIT_INT) !== changedBits) {
3479 error('calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits);
3480 }
3481 }
3482
3483 return changedBits | 0;
3484 }
3485 }
3486 function scheduleWorkOnParentPath(parent, renderLanes) {
3487 // Update the child lanes of all the ancestors, including the alternates.
3488 var node = parent;
3489
3490 while (node !== null) {
3491 var alternate = node.alternate;
3492
3493 if (!isSubsetOfLanes(node.childLanes, renderLanes)) {
3494 node.childLanes = mergeLanes(node.childLanes, renderLanes);
3495
3496 if (alternate !== null) {
3497 alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes);
3498 }
3499 } else if (alternate !== null && !isSubsetOfLanes(alternate.childLanes, renderLanes)) {
3500 alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes);
3501 } else {
3502 // Neither alternate was updated, which means the rest of the
3503 // ancestor path already has sufficient priority.
3504 break;
3505 }
3506
3507 node = node.return;
3508 }
3509 }
3510 function propagateContextChange(workInProgress, context, changedBits, renderLanes) {
3511 var fiber = workInProgress.child;
3512
3513 if (fiber !== null) {
3514 // Set the return pointer of the child to the work-in-progress fiber.
3515 fiber.return = workInProgress;
3516 }
3517
3518 while (fiber !== null) {
3519 var nextFiber = void 0; // Visit this fiber.
3520
3521 var list = fiber.dependencies;
3522
3523 if (list !== null) {
3524 nextFiber = fiber.child;
3525 var dependency = list.firstContext;
3526
3527 while (dependency !== null) {
3528 // Check if the context matches.
3529 if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {
3530 // Match! Schedule an update on this fiber.
3531 if (fiber.tag === ClassComponent) {
3532 // Schedule a force update on the work-in-progress.
3533 var update = createUpdate(NoTimestamp, pickArbitraryLane(renderLanes));
3534 update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the
3535 // update to the current fiber, too, which means it will persist even if
3536 // this render is thrown away. Since it's a race condition, not sure it's
3537 // worth fixing.
3538
3539 enqueueUpdate(fiber, update);
3540 }
3541
3542 fiber.lanes = mergeLanes(fiber.lanes, renderLanes);
3543 var alternate = fiber.alternate;
3544
3545 if (alternate !== null) {
3546 alternate.lanes = mergeLanes(alternate.lanes, renderLanes);
3547 }
3548
3549 scheduleWorkOnParentPath(fiber.return, renderLanes); // Mark the updated lanes on the list, too.
3550
3551 list.lanes = mergeLanes(list.lanes, renderLanes); // Since we already found a match, we can stop traversing the
3552 // dependency list.
3553
3554 break;
3555 }
3556
3557 dependency = dependency.next;
3558 }
3559 } else if (fiber.tag === ContextProvider) {
3560 // Don't scan deeper if this is a matching provider
3561 nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
3562 } else {
3563 // Traverse down.
3564 nextFiber = fiber.child;
3565 }
3566
3567 if (nextFiber !== null) {
3568 // Set the return pointer of the child to the work-in-progress fiber.
3569 nextFiber.return = fiber;
3570 } else {
3571 // No child. Traverse to next sibling.
3572 nextFiber = fiber;
3573
3574 while (nextFiber !== null) {
3575 if (nextFiber === workInProgress) {
3576 // We're back to the root of this subtree. Exit.
3577 nextFiber = null;
3578 break;
3579 }
3580
3581 var sibling = nextFiber.sibling;
3582
3583 if (sibling !== null) {
3584 // Set the return pointer of the sibling to the work-in-progress fiber.
3585 sibling.return = nextFiber.return;
3586 nextFiber = sibling;
3587 break;
3588 } // No more siblings. Traverse up.
3589
3590
3591 nextFiber = nextFiber.return;
3592 }
3593 }
3594
3595 fiber = nextFiber;
3596 }
3597 }
3598 function prepareToReadContext(workInProgress, renderLanes) {
3599 currentlyRenderingFiber = workInProgress;
3600 lastContextDependency = null;
3601 lastContextWithAllBitsObserved = null;
3602 var dependencies = workInProgress.dependencies;
3603
3604 if (dependencies !== null) {
3605 var firstContext = dependencies.firstContext;
3606
3607 if (firstContext !== null) {
3608 if (includesSomeLane(dependencies.lanes, renderLanes)) {
3609 // Context list has a pending update. Mark that this fiber performed work.
3610 markWorkInProgressReceivedUpdate();
3611 } // Reset the work-in-progress list
3612
3613
3614 dependencies.firstContext = null;
3615 }
3616 }
3617 }
3618 function readContext(context, observedBits) {
3619 {
3620 // This warning would fire if you read context inside a Hook like useMemo.
3621 // Unlike the class check below, it's not enforced in production for perf.
3622 if (isDisallowedContextReadInDEV) {
3623 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().');
3624 }
3625 }
3626
3627 if (lastContextWithAllBitsObserved === context) ; else if (observedBits === false || observedBits === 0) ; else {
3628 var resolvedObservedBits; // Avoid deopting on observable arguments or heterogeneous types.
3629
3630 if (typeof observedBits !== 'number' || observedBits === MAX_SIGNED_31_BIT_INT) {
3631 // Observe all updates.
3632 lastContextWithAllBitsObserved = context;
3633 resolvedObservedBits = MAX_SIGNED_31_BIT_INT;
3634 } else {
3635 resolvedObservedBits = observedBits;
3636 }
3637
3638 var contextItem = {
3639 context: context,
3640 observedBits: resolvedObservedBits,
3641 next: null
3642 };
3643
3644 if (lastContextDependency === null) {
3645 if (!(currentlyRenderingFiber !== null)) {
3646 {
3647 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()." );
3648 }
3649 } // This is the first dependency for this component. Create a new list.
3650
3651
3652 lastContextDependency = contextItem;
3653 currentlyRenderingFiber.dependencies = {
3654 lanes: NoLanes,
3655 firstContext: contextItem,
3656 responders: null
3657 };
3658 } else {
3659 // Append a new context item.
3660 lastContextDependency = lastContextDependency.next = contextItem;
3661 }
3662 }
3663
3664 return context._currentValue2;
3665 }
3666
3667 var UpdateState = 0;
3668 var ReplaceState = 1;
3669 var ForceUpdate = 2;
3670 var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`.
3671 // It should only be read right after calling `processUpdateQueue`, via
3672 // `checkHasForceUpdateAfterProcessing`.
3673
3674 var hasForceUpdate = false;
3675 var didWarnUpdateInsideUpdate;
3676 var currentlyProcessingQueue;
3677
3678 {
3679 didWarnUpdateInsideUpdate = false;
3680 currentlyProcessingQueue = null;
3681 }
3682
3683 function initializeUpdateQueue(fiber) {
3684 var queue = {
3685 baseState: fiber.memoizedState,
3686 firstBaseUpdate: null,
3687 lastBaseUpdate: null,
3688 shared: {
3689 pending: null
3690 },
3691 effects: null
3692 };
3693 fiber.updateQueue = queue;
3694 }
3695 function cloneUpdateQueue(current, workInProgress) {
3696 // Clone the update queue from current. Unless it's already a clone.
3697 var queue = workInProgress.updateQueue;
3698 var currentQueue = current.updateQueue;
3699
3700 if (queue === currentQueue) {
3701 var clone = {
3702 baseState: currentQueue.baseState,
3703 firstBaseUpdate: currentQueue.firstBaseUpdate,
3704 lastBaseUpdate: currentQueue.lastBaseUpdate,
3705 shared: currentQueue.shared,
3706 effects: currentQueue.effects
3707 };
3708 workInProgress.updateQueue = clone;
3709 }
3710 }
3711 function createUpdate(eventTime, lane) {
3712 var update = {
3713 eventTime: eventTime,
3714 lane: lane,
3715 tag: UpdateState,
3716 payload: null,
3717 callback: null,
3718 next: null
3719 };
3720 return update;
3721 }
3722 function enqueueUpdate(fiber, update) {
3723 var updateQueue = fiber.updateQueue;
3724
3725 if (updateQueue === null) {
3726 // Only occurs if the fiber has been unmounted.
3727 return;
3728 }
3729
3730 var sharedQueue = updateQueue.shared;
3731 var pending = sharedQueue.pending;
3732
3733 if (pending === null) {
3734 // This is the first update. Create a circular list.
3735 update.next = update;
3736 } else {
3737 update.next = pending.next;
3738 pending.next = update;
3739 }
3740
3741 sharedQueue.pending = update;
3742
3743 {
3744 if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) {
3745 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.');
3746
3747 didWarnUpdateInsideUpdate = true;
3748 }
3749 }
3750 }
3751 function enqueueCapturedUpdate(workInProgress, capturedUpdate) {
3752 // Captured updates are updates that are thrown by a child during the render
3753 // phase. They should be discarded if the render is aborted. Therefore,
3754 // we should only put them on the work-in-progress queue, not the current one.
3755 var queue = workInProgress.updateQueue; // Check if the work-in-progress queue is a clone.
3756
3757 var current = workInProgress.alternate;
3758
3759 if (current !== null) {
3760 var currentQueue = current.updateQueue;
3761
3762 if (queue === currentQueue) {
3763 // The work-in-progress queue is the same as current. This happens when
3764 // we bail out on a parent fiber that then captures an error thrown by
3765 // a child. Since we want to append the update only to the work-in
3766 // -progress queue, we need to clone the updates. We usually clone during
3767 // processUpdateQueue, but that didn't happen in this case because we
3768 // skipped over the parent when we bailed out.
3769 var newFirst = null;
3770 var newLast = null;
3771 var firstBaseUpdate = queue.firstBaseUpdate;
3772
3773 if (firstBaseUpdate !== null) {
3774 // Loop through the updates and clone them.
3775 var update = firstBaseUpdate;
3776
3777 do {
3778 var clone = {
3779 eventTime: update.eventTime,
3780 lane: update.lane,
3781 tag: update.tag,
3782 payload: update.payload,
3783 callback: update.callback,
3784 next: null
3785 };
3786
3787 if (newLast === null) {
3788 newFirst = newLast = clone;
3789 } else {
3790 newLast.next = clone;
3791 newLast = clone;
3792 }
3793
3794 update = update.next;
3795 } while (update !== null); // Append the captured update the end of the cloned list.
3796
3797
3798 if (newLast === null) {
3799 newFirst = newLast = capturedUpdate;
3800 } else {
3801 newLast.next = capturedUpdate;
3802 newLast = capturedUpdate;
3803 }
3804 } else {
3805 // There are no base updates.
3806 newFirst = newLast = capturedUpdate;
3807 }
3808
3809 queue = {
3810 baseState: currentQueue.baseState,
3811 firstBaseUpdate: newFirst,
3812 lastBaseUpdate: newLast,
3813 shared: currentQueue.shared,
3814 effects: currentQueue.effects
3815 };
3816 workInProgress.updateQueue = queue;
3817 return;
3818 }
3819 } // Append the update to the end of the list.
3820
3821
3822 var lastBaseUpdate = queue.lastBaseUpdate;
3823
3824 if (lastBaseUpdate === null) {
3825 queue.firstBaseUpdate = capturedUpdate;
3826 } else {
3827 lastBaseUpdate.next = capturedUpdate;
3828 }
3829
3830 queue.lastBaseUpdate = capturedUpdate;
3831 }
3832
3833 function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
3834 switch (update.tag) {
3835 case ReplaceState:
3836 {
3837 var payload = update.payload;
3838
3839 if (typeof payload === 'function') {
3840 // Updater function
3841 {
3842 enterDisallowedContextReadInDEV();
3843 }
3844
3845 var nextState = payload.call(instance, prevState, nextProps);
3846
3847 {
3848 if ( workInProgress.mode & StrictMode) {
3849 disableLogs();
3850
3851 try {
3852 payload.call(instance, prevState, nextProps);
3853 } finally {
3854 reenableLogs();
3855 }
3856 }
3857
3858 exitDisallowedContextReadInDEV();
3859 }
3860
3861 return nextState;
3862 } // State object
3863
3864
3865 return payload;
3866 }
3867
3868 case CaptureUpdate:
3869 {
3870 workInProgress.flags = workInProgress.flags & ~ShouldCapture | DidCapture;
3871 }
3872 // Intentional fallthrough
3873
3874 case UpdateState:
3875 {
3876 var _payload = update.payload;
3877 var partialState;
3878
3879 if (typeof _payload === 'function') {
3880 // Updater function
3881 {
3882 enterDisallowedContextReadInDEV();
3883 }
3884
3885 partialState = _payload.call(instance, prevState, nextProps);
3886
3887 {
3888 if ( workInProgress.mode & StrictMode) {
3889 disableLogs();
3890
3891 try {
3892 _payload.call(instance, prevState, nextProps);
3893 } finally {
3894 reenableLogs();
3895 }
3896 }
3897
3898 exitDisallowedContextReadInDEV();
3899 }
3900 } else {
3901 // Partial state object
3902 partialState = _payload;
3903 }
3904
3905 if (partialState === null || partialState === undefined) {
3906 // Null and undefined are treated as no-ops.
3907 return prevState;
3908 } // Merge the partial state and the previous state.
3909
3910
3911 return _assign({}, prevState, partialState);
3912 }
3913
3914 case ForceUpdate:
3915 {
3916 hasForceUpdate = true;
3917 return prevState;
3918 }
3919 }
3920
3921 return prevState;
3922 }
3923
3924 function processUpdateQueue(workInProgress, props, instance, renderLanes) {
3925 // This is always non-null on a ClassComponent or HostRoot
3926 var queue = workInProgress.updateQueue;
3927 hasForceUpdate = false;
3928
3929 {
3930 currentlyProcessingQueue = queue.shared;
3931 }
3932
3933 var firstBaseUpdate = queue.firstBaseUpdate;
3934 var lastBaseUpdate = queue.lastBaseUpdate; // Check if there are pending updates. If so, transfer them to the base queue.
3935
3936 var pendingQueue = queue.shared.pending;
3937
3938 if (pendingQueue !== null) {
3939 queue.shared.pending = null; // The pending queue is circular. Disconnect the pointer between first
3940 // and last so that it's non-circular.
3941
3942 var lastPendingUpdate = pendingQueue;
3943 var firstPendingUpdate = lastPendingUpdate.next;
3944 lastPendingUpdate.next = null; // Append pending updates to base queue
3945
3946 if (lastBaseUpdate === null) {
3947 firstBaseUpdate = firstPendingUpdate;
3948 } else {
3949 lastBaseUpdate.next = firstPendingUpdate;
3950 }
3951
3952 lastBaseUpdate = lastPendingUpdate; // If there's a current queue, and it's different from the base queue, then
3953 // we need to transfer the updates to that queue, too. Because the base
3954 // queue is a singly-linked list with no cycles, we can append to both
3955 // lists and take advantage of structural sharing.
3956 // TODO: Pass `current` as argument
3957
3958 var current = workInProgress.alternate;
3959
3960 if (current !== null) {
3961 // This is always non-null on a ClassComponent or HostRoot
3962 var currentQueue = current.updateQueue;
3963 var currentLastBaseUpdate = currentQueue.lastBaseUpdate;
3964
3965 if (currentLastBaseUpdate !== lastBaseUpdate) {
3966 if (currentLastBaseUpdate === null) {
3967 currentQueue.firstBaseUpdate = firstPendingUpdate;
3968 } else {
3969 currentLastBaseUpdate.next = firstPendingUpdate;
3970 }
3971
3972 currentQueue.lastBaseUpdate = lastPendingUpdate;
3973 }
3974 }
3975 } // These values may change as we process the queue.
3976
3977
3978 if (firstBaseUpdate !== null) {
3979 // Iterate through the list of updates to compute the result.
3980 var newState = queue.baseState; // TODO: Don't need to accumulate this. Instead, we can remove renderLanes
3981 // from the original lanes.
3982
3983 var newLanes = NoLanes;
3984 var newBaseState = null;
3985 var newFirstBaseUpdate = null;
3986 var newLastBaseUpdate = null;
3987 var update = firstBaseUpdate;
3988
3989 do {
3990 var updateLane = update.lane;
3991 var updateEventTime = update.eventTime;
3992
3993 if (!isSubsetOfLanes(renderLanes, updateLane)) {
3994 // Priority is insufficient. Skip this update. If this is the first
3995 // skipped update, the previous update/state is the new base
3996 // update/state.
3997 var clone = {
3998 eventTime: updateEventTime,
3999 lane: updateLane,
4000 tag: update.tag,
4001 payload: update.payload,
4002 callback: update.callback,
4003 next: null
4004 };
4005
4006 if (newLastBaseUpdate === null) {
4007 newFirstBaseUpdate = newLastBaseUpdate = clone;
4008 newBaseState = newState;
4009 } else {
4010 newLastBaseUpdate = newLastBaseUpdate.next = clone;
4011 } // Update the remaining priority in the queue.
4012
4013
4014 newLanes = mergeLanes(newLanes, updateLane);
4015 } else {
4016 // This update does have sufficient priority.
4017 if (newLastBaseUpdate !== null) {
4018 var _clone = {
4019 eventTime: updateEventTime,
4020 // This update is going to be committed so we never want uncommit
4021 // it. Using NoLane works because 0 is a subset of all bitmasks, so
4022 // this will never be skipped by the check above.
4023 lane: NoLane,
4024 tag: update.tag,
4025 payload: update.payload,
4026 callback: update.callback,
4027 next: null
4028 };
4029 newLastBaseUpdate = newLastBaseUpdate.next = _clone;
4030 } // Process this update.
4031
4032
4033 newState = getStateFromUpdate(workInProgress, queue, update, newState, props, instance);
4034 var callback = update.callback;
4035
4036 if (callback !== null) {
4037 workInProgress.flags |= Callback;
4038 var effects = queue.effects;
4039
4040 if (effects === null) {
4041 queue.effects = [update];
4042 } else {
4043 effects.push(update);
4044 }
4045 }
4046 }
4047
4048 update = update.next;
4049
4050 if (update === null) {
4051 pendingQueue = queue.shared.pending;
4052
4053 if (pendingQueue === null) {
4054 break;
4055 } else {
4056 // An update was scheduled from inside a reducer. Add the new
4057 // pending updates to the end of the list and keep processing.
4058 var _lastPendingUpdate = pendingQueue; // Intentionally unsound. Pending updates form a circular list, but we
4059 // unravel them when transferring them to the base queue.
4060
4061 var _firstPendingUpdate = _lastPendingUpdate.next;
4062 _lastPendingUpdate.next = null;
4063 update = _firstPendingUpdate;
4064 queue.lastBaseUpdate = _lastPendingUpdate;
4065 queue.shared.pending = null;
4066 }
4067 }
4068 } while (true);
4069
4070 if (newLastBaseUpdate === null) {
4071 newBaseState = newState;
4072 }
4073
4074 queue.baseState = newBaseState;
4075 queue.firstBaseUpdate = newFirstBaseUpdate;
4076 queue.lastBaseUpdate = newLastBaseUpdate; // Set the remaining expiration time to be whatever is remaining in the queue.
4077 // This should be fine because the only two other things that contribute to
4078 // expiration time are props and context. We're already in the middle of the
4079 // begin phase by the time we start processing the queue, so we've already
4080 // dealt with the props. Context in components that specify
4081 // shouldComponentUpdate is tricky; but we'll have to account for
4082 // that regardless.
4083
4084 markSkippedUpdateLanes(newLanes);
4085 workInProgress.lanes = newLanes;
4086 workInProgress.memoizedState = newState;
4087 }
4088
4089 {
4090 currentlyProcessingQueue = null;
4091 }
4092 }
4093
4094 function callCallback(callback, context) {
4095 if (!(typeof callback === 'function')) {
4096 {
4097 throw Error( "Invalid argument passed as callback. Expected a function. Instead received: " + callback );
4098 }
4099 }
4100
4101 callback.call(context);
4102 }
4103
4104 function resetHasForceUpdateBeforeProcessing() {
4105 hasForceUpdate = false;
4106 }
4107 function checkHasForceUpdateAfterProcessing() {
4108 return hasForceUpdate;
4109 }
4110 function commitUpdateQueue(finishedWork, finishedQueue, instance) {
4111 // Commit the effects
4112 var effects = finishedQueue.effects;
4113 finishedQueue.effects = null;
4114
4115 if (effects !== null) {
4116 for (var i = 0; i < effects.length; i++) {
4117 var effect = effects[i];
4118 var callback = effect.callback;
4119
4120 if (callback !== null) {
4121 effect.callback = null;
4122 callCallback(callback, instance);
4123 }
4124 }
4125 }
4126 }
4127
4128 var fakeInternalInstance = {};
4129 var isArray = Array.isArray; // React.Component uses a shared frozen object by default.
4130 // We'll use it to determine whether we need to initialize legacy refs.
4131
4132 var emptyRefsObject = new React.Component().refs;
4133 var didWarnAboutStateAssignmentForComponent;
4134 var didWarnAboutUninitializedState;
4135 var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
4136 var didWarnAboutLegacyLifecyclesAndDerivedState;
4137 var didWarnAboutUndefinedDerivedState;
4138 var warnOnUndefinedDerivedState;
4139 var warnOnInvalidCallback;
4140 var didWarnAboutDirectlyAssigningPropsToState;
4141 var didWarnAboutContextTypeAndContextTypes;
4142 var didWarnAboutInvalidateContextType;
4143
4144 {
4145 didWarnAboutStateAssignmentForComponent = new Set();
4146 didWarnAboutUninitializedState = new Set();
4147 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
4148 didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
4149 didWarnAboutDirectlyAssigningPropsToState = new Set();
4150 didWarnAboutUndefinedDerivedState = new Set();
4151 didWarnAboutContextTypeAndContextTypes = new Set();
4152 didWarnAboutInvalidateContextType = new Set();
4153 var didWarnOnInvalidCallback = new Set();
4154
4155 warnOnInvalidCallback = function (callback, callerName) {
4156 if (callback === null || typeof callback === 'function') {
4157 return;
4158 }
4159
4160 var key = callerName + '_' + callback;
4161
4162 if (!didWarnOnInvalidCallback.has(key)) {
4163 didWarnOnInvalidCallback.add(key);
4164
4165 error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
4166 }
4167 };
4168
4169 warnOnUndefinedDerivedState = function (type, partialState) {
4170 if (partialState === undefined) {
4171 var componentName = getComponentName(type) || 'Component';
4172
4173 if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
4174 didWarnAboutUndefinedDerivedState.add(componentName);
4175
4176 error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
4177 }
4178 }
4179 }; // This is so gross but it's at least non-critical and can be removed if
4180 // it causes problems. This is meant to give a nicer error message for
4181 // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
4182 // ...)) which otherwise throws a "_processChildContext is not a function"
4183 // exception.
4184
4185
4186 Object.defineProperty(fakeInternalInstance, '_processChildContext', {
4187 enumerable: false,
4188 value: function () {
4189 {
4190 {
4191 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)." );
4192 }
4193 }
4194 }
4195 });
4196 Object.freeze(fakeInternalInstance);
4197 }
4198
4199 function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
4200 var prevState = workInProgress.memoizedState;
4201
4202 {
4203 if ( workInProgress.mode & StrictMode) {
4204 disableLogs();
4205
4206 try {
4207 // Invoke the function an extra time to help detect side-effects.
4208 getDerivedStateFromProps(nextProps, prevState);
4209 } finally {
4210 reenableLogs();
4211 }
4212 }
4213 }
4214
4215 var partialState = getDerivedStateFromProps(nextProps, prevState);
4216
4217 {
4218 warnOnUndefinedDerivedState(ctor, partialState);
4219 } // Merge the partial state and the previous state.
4220
4221
4222 var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
4223 workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the
4224 // base state.
4225
4226 if (workInProgress.lanes === NoLanes) {
4227 // Queue is always non-null for classes
4228 var updateQueue = workInProgress.updateQueue;
4229 updateQueue.baseState = memoizedState;
4230 }
4231 }
4232 var classComponentUpdater = {
4233 isMounted: isMounted,
4234 enqueueSetState: function (inst, payload, callback) {
4235 var fiber = get(inst);
4236 var eventTime = requestEventTime();
4237 var lane = requestUpdateLane(fiber);
4238 var update = createUpdate(eventTime, lane);
4239 update.payload = payload;
4240
4241 if (callback !== undefined && callback !== null) {
4242 {
4243 warnOnInvalidCallback(callback, 'setState');
4244 }
4245
4246 update.callback = callback;
4247 }
4248
4249 enqueueUpdate(fiber, update);
4250 scheduleUpdateOnFiber(fiber, lane, eventTime);
4251 },
4252 enqueueReplaceState: function (inst, payload, callback) {
4253 var fiber = get(inst);
4254 var eventTime = requestEventTime();
4255 var lane = requestUpdateLane(fiber);
4256 var update = createUpdate(eventTime, lane);
4257 update.tag = ReplaceState;
4258 update.payload = payload;
4259
4260 if (callback !== undefined && callback !== null) {
4261 {
4262 warnOnInvalidCallback(callback, 'replaceState');
4263 }
4264
4265 update.callback = callback;
4266 }
4267
4268 enqueueUpdate(fiber, update);
4269 scheduleUpdateOnFiber(fiber, lane, eventTime);
4270 },
4271 enqueueForceUpdate: function (inst, callback) {
4272 var fiber = get(inst);
4273 var eventTime = requestEventTime();
4274 var lane = requestUpdateLane(fiber);
4275 var update = createUpdate(eventTime, lane);
4276 update.tag = ForceUpdate;
4277
4278 if (callback !== undefined && callback !== null) {
4279 {
4280 warnOnInvalidCallback(callback, 'forceUpdate');
4281 }
4282
4283 update.callback = callback;
4284 }
4285
4286 enqueueUpdate(fiber, update);
4287 scheduleUpdateOnFiber(fiber, lane, eventTime);
4288 }
4289 };
4290
4291 function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
4292 var instance = workInProgress.stateNode;
4293
4294 if (typeof instance.shouldComponentUpdate === 'function') {
4295 {
4296 if ( workInProgress.mode & StrictMode) {
4297 disableLogs();
4298
4299 try {
4300 // Invoke the function an extra time to help detect side-effects.
4301 instance.shouldComponentUpdate(newProps, newState, nextContext);
4302 } finally {
4303 reenableLogs();
4304 }
4305 }
4306 }
4307
4308 var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
4309
4310 {
4311 if (shouldUpdate === undefined) {
4312 error('%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentName(ctor) || 'Component');
4313 }
4314 }
4315
4316 return shouldUpdate;
4317 }
4318
4319 if (ctor.prototype && ctor.prototype.isPureReactComponent) {
4320 return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
4321 }
4322
4323 return true;
4324 }
4325
4326 function checkClassInstance(workInProgress, ctor, newProps) {
4327 var instance = workInProgress.stateNode;
4328
4329 {
4330 var name = getComponentName(ctor) || 'Component';
4331 var renderPresent = instance.render;
4332
4333 if (!renderPresent) {
4334 if (ctor.prototype && typeof ctor.prototype.render === 'function') {
4335 error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
4336 } else {
4337 error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
4338 }
4339 }
4340
4341 if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {
4342 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);
4343 }
4344
4345 if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {
4346 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);
4347 }
4348
4349 if (instance.propTypes) {
4350 error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);
4351 }
4352
4353 if (instance.contextType) {
4354 error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);
4355 }
4356
4357 {
4358 if (instance.contextTypes) {
4359 error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name);
4360 }
4361
4362 if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
4363 didWarnAboutContextTypeAndContextTypes.add(ctor);
4364
4365 error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
4366 }
4367 }
4368
4369 if (typeof instance.componentShouldUpdate === 'function') {
4370 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);
4371 }
4372
4373 if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
4374 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');
4375 }
4376
4377 if (typeof instance.componentDidUnmount === 'function') {
4378 error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);
4379 }
4380
4381 if (typeof instance.componentDidReceiveProps === 'function') {
4382 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);
4383 }
4384
4385 if (typeof instance.componentWillRecieveProps === 'function') {
4386 error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);
4387 }
4388
4389 if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {
4390 error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);
4391 }
4392
4393 var hasMutatedProps = instance.props !== newProps;
4394
4395 if (instance.props !== undefined && hasMutatedProps) {
4396 error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name);
4397 }
4398
4399 if (instance.defaultProps) {
4400 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);
4401 }
4402
4403 if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
4404 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
4405
4406 error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor));
4407 }
4408
4409 if (typeof instance.getDerivedStateFromProps === 'function') {
4410 error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
4411 }
4412
4413 if (typeof instance.getDerivedStateFromError === 'function') {
4414 error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
4415 }
4416
4417 if (typeof ctor.getSnapshotBeforeUpdate === 'function') {
4418 error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);
4419 }
4420
4421 var _state = instance.state;
4422
4423 if (_state && (typeof _state !== 'object' || isArray(_state))) {
4424 error('%s.state: must be set to an object or null', name);
4425 }
4426
4427 if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {
4428 error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);
4429 }
4430 }
4431 }
4432
4433 function adoptClassInstance(workInProgress, instance) {
4434 instance.updater = classComponentUpdater;
4435 workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates
4436
4437 set(instance, workInProgress);
4438
4439 {
4440 instance._reactInternalInstance = fakeInternalInstance;
4441 }
4442 }
4443
4444 function constructClassInstance(workInProgress, ctor, props) {
4445 var isLegacyContextConsumer = false;
4446 var unmaskedContext = emptyContextObject;
4447 var context = emptyContextObject;
4448 var contextType = ctor.contextType;
4449
4450 {
4451 if ('contextType' in ctor) {
4452 var isValid = // Allow null for conditional declaration
4453 contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>
4454
4455 if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
4456 didWarnAboutInvalidateContextType.add(ctor);
4457 var addendum = '';
4458
4459 if (contextType === undefined) {
4460 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.';
4461 } else if (typeof contextType !== 'object') {
4462 addendum = ' However, it is set to a ' + typeof contextType + '.';
4463 } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
4464 addendum = ' Did you accidentally pass the Context.Provider instead?';
4465 } else if (contextType._context !== undefined) {
4466 // <Context.Consumer>
4467 addendum = ' Did you accidentally pass the Context.Consumer instead?';
4468 } else {
4469 addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
4470 }
4471
4472 error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentName(ctor) || 'Component', addendum);
4473 }
4474 }
4475 }
4476
4477 if (typeof contextType === 'object' && contextType !== null) {
4478 context = readContext(contextType);
4479 } else {
4480 unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
4481 var contextTypes = ctor.contextTypes;
4482 isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
4483 context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
4484 } // Instantiate twice to help detect side-effects.
4485
4486
4487 {
4488 if ( workInProgress.mode & StrictMode) {
4489 disableLogs();
4490
4491 try {
4492 new ctor(props, context); // eslint-disable-line no-new
4493 } finally {
4494 reenableLogs();
4495 }
4496 }
4497 }
4498
4499 var instance = new ctor(props, context);
4500 var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
4501 adoptClassInstance(workInProgress, instance);
4502
4503 {
4504 if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
4505 var componentName = getComponentName(ctor) || 'Component';
4506
4507 if (!didWarnAboutUninitializedState.has(componentName)) {
4508 didWarnAboutUninitializedState.add(componentName);
4509
4510 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);
4511 }
4512 } // If new component APIs are defined, "unsafe" lifecycles won't be called.
4513 // Warn about these lifecycles if they are present.
4514 // Don't warn about react-lifecycles-compat polyfilled methods though.
4515
4516
4517 if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
4518 var foundWillMountName = null;
4519 var foundWillReceivePropsName = null;
4520 var foundWillUpdateName = null;
4521
4522 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
4523 foundWillMountName = 'componentWillMount';
4524 } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
4525 foundWillMountName = 'UNSAFE_componentWillMount';
4526 }
4527
4528 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
4529 foundWillReceivePropsName = 'componentWillReceiveProps';
4530 } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
4531 foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
4532 }
4533
4534 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
4535 foundWillUpdateName = 'componentWillUpdate';
4536 } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
4537 foundWillUpdateName = 'UNSAFE_componentWillUpdate';
4538 }
4539
4540 if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
4541 var _componentName = getComponentName(ctor) || 'Component';
4542
4543 var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
4544
4545 if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
4546 didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
4547
4548 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 : '');
4549 }
4550 }
4551 }
4552 } // Cache unmasked context so we can avoid recreating masked context unless necessary.
4553 // ReactFiberContext usually updates this cache but can't for newly-created instances.
4554
4555
4556 if (isLegacyContextConsumer) {
4557 cacheContext(workInProgress, unmaskedContext, context);
4558 }
4559
4560 return instance;
4561 }
4562
4563 function callComponentWillMount(workInProgress, instance) {
4564 var oldState = instance.state;
4565
4566 if (typeof instance.componentWillMount === 'function') {
4567 instance.componentWillMount();
4568 }
4569
4570 if (typeof instance.UNSAFE_componentWillMount === 'function') {
4571 instance.UNSAFE_componentWillMount();
4572 }
4573
4574 if (oldState !== instance.state) {
4575 {
4576 error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentName(workInProgress.type) || 'Component');
4577 }
4578
4579 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
4580 }
4581 }
4582
4583 function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
4584 var oldState = instance.state;
4585
4586 if (typeof instance.componentWillReceiveProps === 'function') {
4587 instance.componentWillReceiveProps(newProps, nextContext);
4588 }
4589
4590 if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
4591 instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
4592 }
4593
4594 if (instance.state !== oldState) {
4595 {
4596 var componentName = getComponentName(workInProgress.type) || 'Component';
4597
4598 if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
4599 didWarnAboutStateAssignmentForComponent.add(componentName);
4600
4601 error('%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
4602 }
4603 }
4604
4605 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
4606 }
4607 } // Invokes the mount life-cycles on a previously never rendered instance.
4608
4609
4610 function mountClassInstance(workInProgress, ctor, newProps, renderLanes) {
4611 {
4612 checkClassInstance(workInProgress, ctor, newProps);
4613 }
4614
4615 var instance = workInProgress.stateNode;
4616 instance.props = newProps;
4617 instance.state = workInProgress.memoizedState;
4618 instance.refs = emptyRefsObject;
4619 initializeUpdateQueue(workInProgress);
4620 var contextType = ctor.contextType;
4621
4622 if (typeof contextType === 'object' && contextType !== null) {
4623 instance.context = readContext(contextType);
4624 } else {
4625 var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
4626 instance.context = getMaskedContext(workInProgress, unmaskedContext);
4627 }
4628
4629 {
4630 if (instance.state === newProps) {
4631 var componentName = getComponentName(ctor) || 'Component';
4632
4633 if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
4634 didWarnAboutDirectlyAssigningPropsToState.add(componentName);
4635
4636 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);
4637 }
4638 }
4639
4640 if (workInProgress.mode & StrictMode) {
4641 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
4642 }
4643
4644 {
4645 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
4646 }
4647 }
4648
4649 processUpdateQueue(workInProgress, newProps, instance, renderLanes);
4650 instance.state = workInProgress.memoizedState;
4651 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
4652
4653 if (typeof getDerivedStateFromProps === 'function') {
4654 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
4655 instance.state = workInProgress.memoizedState;
4656 } // In order to support react-lifecycles-compat polyfilled components,
4657 // Unsafe lifecycles should not be invoked for components using the new APIs.
4658
4659
4660 if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
4661 callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's
4662 // process them now.
4663
4664 processUpdateQueue(workInProgress, newProps, instance, renderLanes);
4665 instance.state = workInProgress.memoizedState;
4666 }
4667
4668 if (typeof instance.componentDidMount === 'function') {
4669 workInProgress.flags |= Update;
4670 }
4671 }
4672
4673 function resumeMountClassInstance(workInProgress, ctor, newProps, renderLanes) {
4674 var instance = workInProgress.stateNode;
4675 var oldProps = workInProgress.memoizedProps;
4676 instance.props = oldProps;
4677 var oldContext = instance.context;
4678 var contextType = ctor.contextType;
4679 var nextContext = emptyContextObject;
4680
4681 if (typeof contextType === 'object' && contextType !== null) {
4682 nextContext = readContext(contextType);
4683 } else {
4684 var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
4685 nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
4686 }
4687
4688 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
4689 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
4690 // ever the previously attempted to render - not the "current". However,
4691 // during componentDidUpdate we pass the "current" props.
4692 // In order to support react-lifecycles-compat polyfilled components,
4693 // Unsafe lifecycles should not be invoked for components using the new APIs.
4694
4695 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
4696 if (oldProps !== newProps || oldContext !== nextContext) {
4697 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
4698 }
4699 }
4700
4701 resetHasForceUpdateBeforeProcessing();
4702 var oldState = workInProgress.memoizedState;
4703 var newState = instance.state = oldState;
4704 processUpdateQueue(workInProgress, newProps, instance, renderLanes);
4705 newState = workInProgress.memoizedState;
4706
4707 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
4708 // If an update was already in progress, we should schedule an Update
4709 // effect even though we're bailing out, so that cWU/cDU are called.
4710 if (typeof instance.componentDidMount === 'function') {
4711 workInProgress.flags |= Update;
4712 }
4713
4714 return false;
4715 }
4716
4717 if (typeof getDerivedStateFromProps === 'function') {
4718 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
4719 newState = workInProgress.memoizedState;
4720 }
4721
4722 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
4723
4724 if (shouldUpdate) {
4725 // In order to support react-lifecycles-compat polyfilled components,
4726 // Unsafe lifecycles should not be invoked for components using the new APIs.
4727 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
4728 if (typeof instance.componentWillMount === 'function') {
4729 instance.componentWillMount();
4730 }
4731
4732 if (typeof instance.UNSAFE_componentWillMount === 'function') {
4733 instance.UNSAFE_componentWillMount();
4734 }
4735 }
4736
4737 if (typeof instance.componentDidMount === 'function') {
4738 workInProgress.flags |= Update;
4739 }
4740 } else {
4741 // If an update was already in progress, we should schedule an Update
4742 // effect even though we're bailing out, so that cWU/cDU are called.
4743 if (typeof instance.componentDidMount === 'function') {
4744 workInProgress.flags |= Update;
4745 } // If shouldComponentUpdate returned false, we should still update the
4746 // memoized state to indicate that this work can be reused.
4747
4748
4749 workInProgress.memoizedProps = newProps;
4750 workInProgress.memoizedState = newState;
4751 } // Update the existing instance's state, props, and context pointers even
4752 // if shouldComponentUpdate returns false.
4753
4754
4755 instance.props = newProps;
4756 instance.state = newState;
4757 instance.context = nextContext;
4758 return shouldUpdate;
4759 } // Invokes the update life-cycles and returns false if it shouldn't rerender.
4760
4761
4762 function updateClassInstance(current, workInProgress, ctor, newProps, renderLanes) {
4763 var instance = workInProgress.stateNode;
4764 cloneUpdateQueue(current, workInProgress);
4765 var unresolvedOldProps = workInProgress.memoizedProps;
4766 var oldProps = workInProgress.type === workInProgress.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress.type, unresolvedOldProps);
4767 instance.props = oldProps;
4768 var unresolvedNewProps = workInProgress.pendingProps;
4769 var oldContext = instance.context;
4770 var contextType = ctor.contextType;
4771 var nextContext = emptyContextObject;
4772
4773 if (typeof contextType === 'object' && contextType !== null) {
4774 nextContext = readContext(contextType);
4775 } else {
4776 var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
4777 nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
4778 }
4779
4780 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
4781 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
4782 // ever the previously attempted to render - not the "current". However,
4783 // during componentDidUpdate we pass the "current" props.
4784 // In order to support react-lifecycles-compat polyfilled components,
4785 // Unsafe lifecycles should not be invoked for components using the new APIs.
4786
4787 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
4788 if (unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext) {
4789 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
4790 }
4791 }
4792
4793 resetHasForceUpdateBeforeProcessing();
4794 var oldState = workInProgress.memoizedState;
4795 var newState = instance.state = oldState;
4796 processUpdateQueue(workInProgress, newProps, instance, renderLanes);
4797 newState = workInProgress.memoizedState;
4798
4799 if (unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
4800 // If an update was already in progress, we should schedule an Update
4801 // effect even though we're bailing out, so that cWU/cDU are called.
4802 if (typeof instance.componentDidUpdate === 'function') {
4803 if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
4804 workInProgress.flags |= Update;
4805 }
4806 }
4807
4808 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
4809 if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
4810 workInProgress.flags |= Snapshot;
4811 }
4812 }
4813
4814 return false;
4815 }
4816
4817 if (typeof getDerivedStateFromProps === 'function') {
4818 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
4819 newState = workInProgress.memoizedState;
4820 }
4821
4822 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
4823
4824 if (shouldUpdate) {
4825 // In order to support react-lifecycles-compat polyfilled components,
4826 // Unsafe lifecycles should not be invoked for components using the new APIs.
4827 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
4828 if (typeof instance.componentWillUpdate === 'function') {
4829 instance.componentWillUpdate(newProps, newState, nextContext);
4830 }
4831
4832 if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
4833 instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
4834 }
4835 }
4836
4837 if (typeof instance.componentDidUpdate === 'function') {
4838 workInProgress.flags |= Update;
4839 }
4840
4841 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
4842 workInProgress.flags |= Snapshot;
4843 }
4844 } else {
4845 // If an update was already in progress, we should schedule an Update
4846 // effect even though we're bailing out, so that cWU/cDU are called.
4847 if (typeof instance.componentDidUpdate === 'function') {
4848 if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
4849 workInProgress.flags |= Update;
4850 }
4851 }
4852
4853 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
4854 if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
4855 workInProgress.flags |= Snapshot;
4856 }
4857 } // If shouldComponentUpdate returned false, we should still update the
4858 // memoized props/state to indicate that this work can be reused.
4859
4860
4861 workInProgress.memoizedProps = newProps;
4862 workInProgress.memoizedState = newState;
4863 } // Update the existing instance's state, props, and context pointers even
4864 // if shouldComponentUpdate returns false.
4865
4866
4867 instance.props = newProps;
4868 instance.state = newState;
4869 instance.context = nextContext;
4870 return shouldUpdate;
4871 }
4872
4873 var didWarnAboutMaps;
4874 var didWarnAboutGenerators;
4875 var didWarnAboutStringRefs;
4876 var ownerHasKeyUseWarning;
4877 var ownerHasFunctionTypeWarning;
4878
4879 var warnForMissingKey = function (child, returnFiber) {};
4880
4881 {
4882 didWarnAboutMaps = false;
4883 didWarnAboutGenerators = false;
4884 didWarnAboutStringRefs = {};
4885 /**
4886 * Warn if there's no key explicitly set on dynamic arrays of children or
4887 * object keys are not valid. This allows us to keep track of children between
4888 * updates.
4889 */
4890
4891 ownerHasKeyUseWarning = {};
4892 ownerHasFunctionTypeWarning = {};
4893
4894 warnForMissingKey = function (child, returnFiber) {
4895 if (child === null || typeof child !== 'object') {
4896 return;
4897 }
4898
4899 if (!child._store || child._store.validated || child.key != null) {
4900 return;
4901 }
4902
4903 if (!(typeof child._store === 'object')) {
4904 {
4905 throw Error( "React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue." );
4906 }
4907 }
4908
4909 child._store.validated = true;
4910 var componentName = getComponentName(returnFiber.type) || 'Component';
4911
4912 if (ownerHasKeyUseWarning[componentName]) {
4913 return;
4914 }
4915
4916 ownerHasKeyUseWarning[componentName] = true;
4917
4918 error('Each child in a list should have a unique ' + '"key" prop. See https://reactjs.org/link/warning-keys for ' + 'more information.');
4919 };
4920 }
4921
4922 var isArray$1 = Array.isArray;
4923
4924 function coerceRef(returnFiber, current, element) {
4925 var mixedRef = element.ref;
4926
4927 if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
4928 {
4929 // TODO: Clean this up once we turn on the string ref warning for
4930 // everyone, because the strict mode case will no longer be relevant
4931 if ((returnFiber.mode & StrictMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs
4932 // because these cannot be automatically converted to an arrow function
4933 // using a codemod. Therefore, we don't have to warn about string refs again.
4934 !(element._owner && element._self && element._owner.stateNode !== element._self)) {
4935 var componentName = getComponentName(returnFiber.type) || 'Component';
4936
4937 if (!didWarnAboutStringRefs[componentName]) {
4938 {
4939 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);
4940 }
4941
4942 didWarnAboutStringRefs[componentName] = true;
4943 }
4944 }
4945 }
4946
4947 if (element._owner) {
4948 var owner = element._owner;
4949 var inst;
4950
4951 if (owner) {
4952 var ownerFiber = owner;
4953
4954 if (!(ownerFiber.tag === ClassComponent)) {
4955 {
4956 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" );
4957 }
4958 }
4959
4960 inst = ownerFiber.stateNode;
4961 }
4962
4963 if (!inst) {
4964 {
4965 throw Error( "Missing owner for string ref " + mixedRef + ". This error is likely caused by a bug in React. Please file an issue." );
4966 }
4967 }
4968
4969 var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref
4970
4971 if (current !== null && current.ref !== null && typeof current.ref === 'function' && current.ref._stringRef === stringRef) {
4972 return current.ref;
4973 }
4974
4975 var ref = function (value) {
4976 var refs = inst.refs;
4977
4978 if (refs === emptyRefsObject) {
4979 // This is a lazy pooled frozen object, so we need to initialize.
4980 refs = inst.refs = {};
4981 }
4982
4983 if (value === null) {
4984 delete refs[stringRef];
4985 } else {
4986 refs[stringRef] = value;
4987 }
4988 };
4989
4990 ref._stringRef = stringRef;
4991 return ref;
4992 } else {
4993 if (!(typeof mixedRef === 'string')) {
4994 {
4995 throw Error( "Expected ref to be a function, a string, an object returned by React.createRef(), or null." );
4996 }
4997 }
4998
4999 if (!element._owner) {
5000 {
5001 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." );
5002 }
5003 }
5004 }
5005 }
5006
5007 return mixedRef;
5008 }
5009
5010 function throwOnInvalidObjectType(returnFiber, newChild) {
5011 if (returnFiber.type !== 'textarea') {
5012 {
5013 {
5014 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." );
5015 }
5016 }
5017 }
5018 }
5019
5020 function warnOnFunctionType(returnFiber) {
5021 {
5022 var componentName = getComponentName(returnFiber.type) || 'Component';
5023
5024 if (ownerHasFunctionTypeWarning[componentName]) {
5025 return;
5026 }
5027
5028 ownerHasFunctionTypeWarning[componentName] = true;
5029
5030 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.');
5031 }
5032 } // We avoid inlining this to avoid potential deopts from using try/catch.
5033 // to be able to optimize each path individually by branching early. This needs
5034 // a compiler or we can do it manually. Helpers that don't need this branching
5035 // live outside of this function.
5036
5037
5038 function ChildReconciler(shouldTrackSideEffects) {
5039 function deleteChild(returnFiber, childToDelete) {
5040 if (!shouldTrackSideEffects) {
5041 // Noop.
5042 return;
5043 } // Deletions are added in reversed order so we add it to the front.
5044 // At this point, the return fiber's effect list is empty except for
5045 // deletions, so we can just append the deletion to the list. The remaining
5046 // effects aren't added until the complete phase. Once we implement
5047 // resuming, this may not be true.
5048
5049
5050 var last = returnFiber.lastEffect;
5051
5052 if (last !== null) {
5053 last.nextEffect = childToDelete;
5054 returnFiber.lastEffect = childToDelete;
5055 } else {
5056 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
5057 }
5058
5059 childToDelete.nextEffect = null;
5060 childToDelete.flags = Deletion;
5061 }
5062
5063 function deleteRemainingChildren(returnFiber, currentFirstChild) {
5064 if (!shouldTrackSideEffects) {
5065 // Noop.
5066 return null;
5067 } // TODO: For the shouldClone case, this could be micro-optimized a bit by
5068 // assuming that after the first child we've already added everything.
5069
5070
5071 var childToDelete = currentFirstChild;
5072
5073 while (childToDelete !== null) {
5074 deleteChild(returnFiber, childToDelete);
5075 childToDelete = childToDelete.sibling;
5076 }
5077
5078 return null;
5079 }
5080
5081 function mapRemainingChildren(returnFiber, currentFirstChild) {
5082 // Add the remaining children to a temporary map so that we can find them by
5083 // keys quickly. Implicit (null) keys get added to this set with their index
5084 // instead.
5085 var existingChildren = new Map();
5086 var existingChild = currentFirstChild;
5087
5088 while (existingChild !== null) {
5089 if (existingChild.key !== null) {
5090 existingChildren.set(existingChild.key, existingChild);
5091 } else {
5092 existingChildren.set(existingChild.index, existingChild);
5093 }
5094
5095 existingChild = existingChild.sibling;
5096 }
5097
5098 return existingChildren;
5099 }
5100
5101 function useFiber(fiber, pendingProps) {
5102 // We currently set sibling to null and index to 0 here because it is easy
5103 // to forget to do before returning it. E.g. for the single child case.
5104 var clone = createWorkInProgress(fiber, pendingProps);
5105 clone.index = 0;
5106 clone.sibling = null;
5107 return clone;
5108 }
5109
5110 function placeChild(newFiber, lastPlacedIndex, newIndex) {
5111 newFiber.index = newIndex;
5112
5113 if (!shouldTrackSideEffects) {
5114 // Noop.
5115 return lastPlacedIndex;
5116 }
5117
5118 var current = newFiber.alternate;
5119
5120 if (current !== null) {
5121 var oldIndex = current.index;
5122
5123 if (oldIndex < lastPlacedIndex) {
5124 // This is a move.
5125 newFiber.flags = Placement;
5126 return lastPlacedIndex;
5127 } else {
5128 // This item can stay in place.
5129 return oldIndex;
5130 }
5131 } else {
5132 // This is an insertion.
5133 newFiber.flags = Placement;
5134 return lastPlacedIndex;
5135 }
5136 }
5137
5138 function placeSingleChild(newFiber) {
5139 // This is simpler for the single child case. We only need to do a
5140 // placement for inserting new children.
5141 if (shouldTrackSideEffects && newFiber.alternate === null) {
5142 newFiber.flags = Placement;
5143 }
5144
5145 return newFiber;
5146 }
5147
5148 function updateTextNode(returnFiber, current, textContent, lanes) {
5149 if (current === null || current.tag !== HostText) {
5150 // Insert
5151 var created = createFiberFromText(textContent, returnFiber.mode, lanes);
5152 created.return = returnFiber;
5153 return created;
5154 } else {
5155 // Update
5156 var existing = useFiber(current, textContent);
5157 existing.return = returnFiber;
5158 return existing;
5159 }
5160 }
5161
5162 function updateElement(returnFiber, current, element, lanes) {
5163 if (current !== null) {
5164 if (current.elementType === element.type || ( // Keep this check inline so it only runs on the false path:
5165 isCompatibleFamilyForHotReloading(current, element) )) {
5166 // Move based on index
5167 var existing = useFiber(current, element.props);
5168 existing.ref = coerceRef(returnFiber, current, element);
5169 existing.return = returnFiber;
5170
5171 {
5172 existing._debugSource = element._source;
5173 existing._debugOwner = element._owner;
5174 }
5175
5176 return existing;
5177 }
5178 } // Insert
5179
5180
5181 var created = createFiberFromElement(element, returnFiber.mode, lanes);
5182 created.ref = coerceRef(returnFiber, current, element);
5183 created.return = returnFiber;
5184 return created;
5185 }
5186
5187 function updatePortal(returnFiber, current, portal, lanes) {
5188 if (current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) {
5189 // Insert
5190 var created = createFiberFromPortal(portal, returnFiber.mode, lanes);
5191 created.return = returnFiber;
5192 return created;
5193 } else {
5194 // Update
5195 var existing = useFiber(current, portal.children || []);
5196 existing.return = returnFiber;
5197 return existing;
5198 }
5199 }
5200
5201 function updateFragment(returnFiber, current, fragment, lanes, key) {
5202 if (current === null || current.tag !== Fragment) {
5203 // Insert
5204 var created = createFiberFromFragment(fragment, returnFiber.mode, lanes, key);
5205 created.return = returnFiber;
5206 return created;
5207 } else {
5208 // Update
5209 var existing = useFiber(current, fragment);
5210 existing.return = returnFiber;
5211 return existing;
5212 }
5213 }
5214
5215 function createChild(returnFiber, newChild, lanes) {
5216 if (typeof newChild === 'string' || typeof newChild === 'number') {
5217 // Text nodes don't have keys. If the previous node is implicitly keyed
5218 // we can continue to replace it without aborting even if it is not a text
5219 // node.
5220 var created = createFiberFromText('' + newChild, returnFiber.mode, lanes);
5221 created.return = returnFiber;
5222 return created;
5223 }
5224
5225 if (typeof newChild === 'object' && newChild !== null) {
5226 switch (newChild.$$typeof) {
5227 case REACT_ELEMENT_TYPE:
5228 {
5229 var _created = createFiberFromElement(newChild, returnFiber.mode, lanes);
5230
5231 _created.ref = coerceRef(returnFiber, null, newChild);
5232 _created.return = returnFiber;
5233 return _created;
5234 }
5235
5236 case REACT_PORTAL_TYPE:
5237 {
5238 var _created2 = createFiberFromPortal(newChild, returnFiber.mode, lanes);
5239
5240 _created2.return = returnFiber;
5241 return _created2;
5242 }
5243 }
5244
5245 if (isArray$1(newChild) || getIteratorFn(newChild)) {
5246 var _created3 = createFiberFromFragment(newChild, returnFiber.mode, lanes, null);
5247
5248 _created3.return = returnFiber;
5249 return _created3;
5250 }
5251
5252 throwOnInvalidObjectType(returnFiber, newChild);
5253 }
5254
5255 {
5256 if (typeof newChild === 'function') {
5257 warnOnFunctionType(returnFiber);
5258 }
5259 }
5260
5261 return null;
5262 }
5263
5264 function updateSlot(returnFiber, oldFiber, newChild, lanes) {
5265 // Update the fiber if the keys match, otherwise return null.
5266 var key = oldFiber !== null ? oldFiber.key : null;
5267
5268 if (typeof newChild === 'string' || typeof newChild === 'number') {
5269 // Text nodes don't have keys. If the previous node is implicitly keyed
5270 // we can continue to replace it without aborting even if it is not a text
5271 // node.
5272 if (key !== null) {
5273 return null;
5274 }
5275
5276 return updateTextNode(returnFiber, oldFiber, '' + newChild, lanes);
5277 }
5278
5279 if (typeof newChild === 'object' && newChild !== null) {
5280 switch (newChild.$$typeof) {
5281 case REACT_ELEMENT_TYPE:
5282 {
5283 if (newChild.key === key) {
5284 if (newChild.type === REACT_FRAGMENT_TYPE) {
5285 return updateFragment(returnFiber, oldFiber, newChild.props.children, lanes, key);
5286 }
5287
5288 return updateElement(returnFiber, oldFiber, newChild, lanes);
5289 } else {
5290 return null;
5291 }
5292 }
5293
5294 case REACT_PORTAL_TYPE:
5295 {
5296 if (newChild.key === key) {
5297 return updatePortal(returnFiber, oldFiber, newChild, lanes);
5298 } else {
5299 return null;
5300 }
5301 }
5302 }
5303
5304 if (isArray$1(newChild) || getIteratorFn(newChild)) {
5305 if (key !== null) {
5306 return null;
5307 }
5308
5309 return updateFragment(returnFiber, oldFiber, newChild, lanes, null);
5310 }
5311
5312 throwOnInvalidObjectType(returnFiber, newChild);
5313 }
5314
5315 {
5316 if (typeof newChild === 'function') {
5317 warnOnFunctionType(returnFiber);
5318 }
5319 }
5320
5321 return null;
5322 }
5323
5324 function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) {
5325 if (typeof newChild === 'string' || typeof newChild === 'number') {
5326 // Text nodes don't have keys, so we neither have to check the old nor
5327 // new node for the key. If both are text nodes, they match.
5328 var matchedFiber = existingChildren.get(newIdx) || null;
5329 return updateTextNode(returnFiber, matchedFiber, '' + newChild, lanes);
5330 }
5331
5332 if (typeof newChild === 'object' && newChild !== null) {
5333 switch (newChild.$$typeof) {
5334 case REACT_ELEMENT_TYPE:
5335 {
5336 var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
5337
5338 if (newChild.type === REACT_FRAGMENT_TYPE) {
5339 return updateFragment(returnFiber, _matchedFiber, newChild.props.children, lanes, newChild.key);
5340 }
5341
5342 return updateElement(returnFiber, _matchedFiber, newChild, lanes);
5343 }
5344
5345 case REACT_PORTAL_TYPE:
5346 {
5347 var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
5348
5349 return updatePortal(returnFiber, _matchedFiber2, newChild, lanes);
5350 }
5351
5352 }
5353
5354 if (isArray$1(newChild) || getIteratorFn(newChild)) {
5355 var _matchedFiber3 = existingChildren.get(newIdx) || null;
5356
5357 return updateFragment(returnFiber, _matchedFiber3, newChild, lanes, null);
5358 }
5359
5360 throwOnInvalidObjectType(returnFiber, newChild);
5361 }
5362
5363 {
5364 if (typeof newChild === 'function') {
5365 warnOnFunctionType(returnFiber);
5366 }
5367 }
5368
5369 return null;
5370 }
5371 /**
5372 * Warns if there is a duplicate or missing key
5373 */
5374
5375
5376 function warnOnInvalidKey(child, knownKeys, returnFiber) {
5377 {
5378 if (typeof child !== 'object' || child === null) {
5379 return knownKeys;
5380 }
5381
5382 switch (child.$$typeof) {
5383 case REACT_ELEMENT_TYPE:
5384 case REACT_PORTAL_TYPE:
5385 warnForMissingKey(child, returnFiber);
5386 var key = child.key;
5387
5388 if (typeof key !== 'string') {
5389 break;
5390 }
5391
5392 if (knownKeys === null) {
5393 knownKeys = new Set();
5394 knownKeys.add(key);
5395 break;
5396 }
5397
5398 if (!knownKeys.has(key)) {
5399 knownKeys.add(key);
5400 break;
5401 }
5402
5403 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);
5404
5405 break;
5406 }
5407 }
5408
5409 return knownKeys;
5410 }
5411
5412 function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) {
5413 // This algorithm can't optimize by searching from both ends since we
5414 // don't have backpointers on fibers. I'm trying to see how far we can get
5415 // with that model. If it ends up not being worth the tradeoffs, we can
5416 // add it later.
5417 // Even with a two ended optimization, we'd want to optimize for the case
5418 // where there are few changes and brute force the comparison instead of
5419 // going for the Map. It'd like to explore hitting that path first in
5420 // forward-only mode and only go for the Map once we notice that we need
5421 // lots of look ahead. This doesn't handle reversal as well as two ended
5422 // search but that's unusual. Besides, for the two ended optimization to
5423 // work on Iterables, we'd need to copy the whole set.
5424 // In this first iteration, we'll just live with hitting the bad case
5425 // (adding everything to a Map) in for every insert/move.
5426 // If you change this code, also update reconcileChildrenIterator() which
5427 // uses the same algorithm.
5428 {
5429 // First, validate keys.
5430 var knownKeys = null;
5431
5432 for (var i = 0; i < newChildren.length; i++) {
5433 var child = newChildren[i];
5434 knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
5435 }
5436 }
5437
5438 var resultingFirstChild = null;
5439 var previousNewFiber = null;
5440 var oldFiber = currentFirstChild;
5441 var lastPlacedIndex = 0;
5442 var newIdx = 0;
5443 var nextOldFiber = null;
5444
5445 for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
5446 if (oldFiber.index > newIdx) {
5447 nextOldFiber = oldFiber;
5448 oldFiber = null;
5449 } else {
5450 nextOldFiber = oldFiber.sibling;
5451 }
5452
5453 var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], lanes);
5454
5455 if (newFiber === null) {
5456 // TODO: This breaks on empty slots like null children. That's
5457 // unfortunate because it triggers the slow path all the time. We need
5458 // a better way to communicate whether this was a miss or null,
5459 // boolean, undefined, etc.
5460 if (oldFiber === null) {
5461 oldFiber = nextOldFiber;
5462 }
5463
5464 break;
5465 }
5466
5467 if (shouldTrackSideEffects) {
5468 if (oldFiber && newFiber.alternate === null) {
5469 // We matched the slot, but we didn't reuse the existing fiber, so we
5470 // need to delete the existing child.
5471 deleteChild(returnFiber, oldFiber);
5472 }
5473 }
5474
5475 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
5476
5477 if (previousNewFiber === null) {
5478 // TODO: Move out of the loop. This only happens for the first run.
5479 resultingFirstChild = newFiber;
5480 } else {
5481 // TODO: Defer siblings if we're not at the right index for this slot.
5482 // I.e. if we had null values before, then we want to defer this
5483 // for each null value. However, we also don't want to call updateSlot
5484 // with the previous one.
5485 previousNewFiber.sibling = newFiber;
5486 }
5487
5488 previousNewFiber = newFiber;
5489 oldFiber = nextOldFiber;
5490 }
5491
5492 if (newIdx === newChildren.length) {
5493 // We've reached the end of the new children. We can delete the rest.
5494 deleteRemainingChildren(returnFiber, oldFiber);
5495 return resultingFirstChild;
5496 }
5497
5498 if (oldFiber === null) {
5499 // If we don't have any more existing children we can choose a fast path
5500 // since the rest will all be insertions.
5501 for (; newIdx < newChildren.length; newIdx++) {
5502 var _newFiber = createChild(returnFiber, newChildren[newIdx], lanes);
5503
5504 if (_newFiber === null) {
5505 continue;
5506 }
5507
5508 lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
5509
5510 if (previousNewFiber === null) {
5511 // TODO: Move out of the loop. This only happens for the first run.
5512 resultingFirstChild = _newFiber;
5513 } else {
5514 previousNewFiber.sibling = _newFiber;
5515 }
5516
5517 previousNewFiber = _newFiber;
5518 }
5519
5520 return resultingFirstChild;
5521 } // Add all children to a key map for quick lookups.
5522
5523
5524 var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.
5525
5526 for (; newIdx < newChildren.length; newIdx++) {
5527 var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], lanes);
5528
5529 if (_newFiber2 !== null) {
5530 if (shouldTrackSideEffects) {
5531 if (_newFiber2.alternate !== null) {
5532 // The new fiber is a work in progress, but if there exists a
5533 // current, that means that we reused the fiber. We need to delete
5534 // it from the child list so that we don't add it to the deletion
5535 // list.
5536 existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
5537 }
5538 }
5539
5540 lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
5541
5542 if (previousNewFiber === null) {
5543 resultingFirstChild = _newFiber2;
5544 } else {
5545 previousNewFiber.sibling = _newFiber2;
5546 }
5547
5548 previousNewFiber = _newFiber2;
5549 }
5550 }
5551
5552 if (shouldTrackSideEffects) {
5553 // Any existing children that weren't consumed above were deleted. We need
5554 // to add them to the deletion list.
5555 existingChildren.forEach(function (child) {
5556 return deleteChild(returnFiber, child);
5557 });
5558 }
5559
5560 return resultingFirstChild;
5561 }
5562
5563 function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, lanes) {
5564 // This is the same implementation as reconcileChildrenArray(),
5565 // but using the iterator instead.
5566 var iteratorFn = getIteratorFn(newChildrenIterable);
5567
5568 if (!(typeof iteratorFn === 'function')) {
5569 {
5570 throw Error( "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." );
5571 }
5572 }
5573
5574 {
5575 // We don't support rendering Generators because it's a mutation.
5576 // See https://github.com/facebook/react/issues/12995
5577 if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag
5578 newChildrenIterable[Symbol.toStringTag] === 'Generator') {
5579 if (!didWarnAboutGenerators) {
5580 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.');
5581 }
5582
5583 didWarnAboutGenerators = true;
5584 } // Warn about using Maps as children
5585
5586
5587 if (newChildrenIterable.entries === iteratorFn) {
5588 if (!didWarnAboutMaps) {
5589 error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
5590 }
5591
5592 didWarnAboutMaps = true;
5593 } // First, validate keys.
5594 // We'll get a different iterator later for the main pass.
5595
5596
5597 var _newChildren = iteratorFn.call(newChildrenIterable);
5598
5599 if (_newChildren) {
5600 var knownKeys = null;
5601
5602 var _step = _newChildren.next();
5603
5604 for (; !_step.done; _step = _newChildren.next()) {
5605 var child = _step.value;
5606 knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
5607 }
5608 }
5609 }
5610
5611 var newChildren = iteratorFn.call(newChildrenIterable);
5612
5613 if (!(newChildren != null)) {
5614 {
5615 throw Error( "An iterable object provided no iterator." );
5616 }
5617 }
5618
5619 var resultingFirstChild = null;
5620 var previousNewFiber = null;
5621 var oldFiber = currentFirstChild;
5622 var lastPlacedIndex = 0;
5623 var newIdx = 0;
5624 var nextOldFiber = null;
5625 var step = newChildren.next();
5626
5627 for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
5628 if (oldFiber.index > newIdx) {
5629 nextOldFiber = oldFiber;
5630 oldFiber = null;
5631 } else {
5632 nextOldFiber = oldFiber.sibling;
5633 }
5634
5635 var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);
5636
5637 if (newFiber === null) {
5638 // TODO: This breaks on empty slots like null children. That's
5639 // unfortunate because it triggers the slow path all the time. We need
5640 // a better way to communicate whether this was a miss or null,
5641 // boolean, undefined, etc.
5642 if (oldFiber === null) {
5643 oldFiber = nextOldFiber;
5644 }
5645
5646 break;
5647 }
5648
5649 if (shouldTrackSideEffects) {
5650 if (oldFiber && newFiber.alternate === null) {
5651 // We matched the slot, but we didn't reuse the existing fiber, so we
5652 // need to delete the existing child.
5653 deleteChild(returnFiber, oldFiber);
5654 }
5655 }
5656
5657 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
5658
5659 if (previousNewFiber === null) {
5660 // TODO: Move out of the loop. This only happens for the first run.
5661 resultingFirstChild = newFiber;
5662 } else {
5663 // TODO: Defer siblings if we're not at the right index for this slot.
5664 // I.e. if we had null values before, then we want to defer this
5665 // for each null value. However, we also don't want to call updateSlot
5666 // with the previous one.
5667 previousNewFiber.sibling = newFiber;
5668 }
5669
5670 previousNewFiber = newFiber;
5671 oldFiber = nextOldFiber;
5672 }
5673
5674 if (step.done) {
5675 // We've reached the end of the new children. We can delete the rest.
5676 deleteRemainingChildren(returnFiber, oldFiber);
5677 return resultingFirstChild;
5678 }
5679
5680 if (oldFiber === null) {
5681 // If we don't have any more existing children we can choose a fast path
5682 // since the rest will all be insertions.
5683 for (; !step.done; newIdx++, step = newChildren.next()) {
5684 var _newFiber3 = createChild(returnFiber, step.value, lanes);
5685
5686 if (_newFiber3 === null) {
5687 continue;
5688 }
5689
5690 lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
5691
5692 if (previousNewFiber === null) {
5693 // TODO: Move out of the loop. This only happens for the first run.
5694 resultingFirstChild = _newFiber3;
5695 } else {
5696 previousNewFiber.sibling = _newFiber3;
5697 }
5698
5699 previousNewFiber = _newFiber3;
5700 }
5701
5702 return resultingFirstChild;
5703 } // Add all children to a key map for quick lookups.
5704
5705
5706 var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.
5707
5708 for (; !step.done; newIdx++, step = newChildren.next()) {
5709 var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, lanes);
5710
5711 if (_newFiber4 !== null) {
5712 if (shouldTrackSideEffects) {
5713 if (_newFiber4.alternate !== null) {
5714 // The new fiber is a work in progress, but if there exists a
5715 // current, that means that we reused the fiber. We need to delete
5716 // it from the child list so that we don't add it to the deletion
5717 // list.
5718 existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
5719 }
5720 }
5721
5722 lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
5723
5724 if (previousNewFiber === null) {
5725 resultingFirstChild = _newFiber4;
5726 } else {
5727 previousNewFiber.sibling = _newFiber4;
5728 }
5729
5730 previousNewFiber = _newFiber4;
5731 }
5732 }
5733
5734 if (shouldTrackSideEffects) {
5735 // Any existing children that weren't consumed above were deleted. We need
5736 // to add them to the deletion list.
5737 existingChildren.forEach(function (child) {
5738 return deleteChild(returnFiber, child);
5739 });
5740 }
5741
5742 return resultingFirstChild;
5743 }
5744
5745 function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, lanes) {
5746 // There's no need to check for keys on text nodes since we don't have a
5747 // way to define them.
5748 if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
5749 // We already have an existing node so let's just update it and delete
5750 // the rest.
5751 deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
5752 var existing = useFiber(currentFirstChild, textContent);
5753 existing.return = returnFiber;
5754 return existing;
5755 } // The existing first child is not a text node so we need to create one
5756 // and delete the existing ones.
5757
5758
5759 deleteRemainingChildren(returnFiber, currentFirstChild);
5760 var created = createFiberFromText(textContent, returnFiber.mode, lanes);
5761 created.return = returnFiber;
5762 return created;
5763 }
5764
5765 function reconcileSingleElement(returnFiber, currentFirstChild, element, lanes) {
5766 var key = element.key;
5767 var child = currentFirstChild;
5768
5769 while (child !== null) {
5770 // TODO: If key === null and child.key === null, then this only applies to
5771 // the first item in the list.
5772 if (child.key === key) {
5773 switch (child.tag) {
5774 case Fragment:
5775 {
5776 if (element.type === REACT_FRAGMENT_TYPE) {
5777 deleteRemainingChildren(returnFiber, child.sibling);
5778 var existing = useFiber(child, element.props.children);
5779 existing.return = returnFiber;
5780
5781 {
5782 existing._debugSource = element._source;
5783 existing._debugOwner = element._owner;
5784 }
5785
5786 return existing;
5787 }
5788
5789 break;
5790 }
5791
5792 case Block:
5793
5794 // We intentionally fallthrough here if enableBlocksAPI is not on.
5795 // eslint-disable-next-lined no-fallthrough
5796
5797 default:
5798 {
5799 if (child.elementType === element.type || ( // Keep this check inline so it only runs on the false path:
5800 isCompatibleFamilyForHotReloading(child, element) )) {
5801 deleteRemainingChildren(returnFiber, child.sibling);
5802
5803 var _existing3 = useFiber(child, element.props);
5804
5805 _existing3.ref = coerceRef(returnFiber, child, element);
5806 _existing3.return = returnFiber;
5807
5808 {
5809 _existing3._debugSource = element._source;
5810 _existing3._debugOwner = element._owner;
5811 }
5812
5813 return _existing3;
5814 }
5815
5816 break;
5817 }
5818 } // Didn't match.
5819
5820
5821 deleteRemainingChildren(returnFiber, child);
5822 break;
5823 } else {
5824 deleteChild(returnFiber, child);
5825 }
5826
5827 child = child.sibling;
5828 }
5829
5830 if (element.type === REACT_FRAGMENT_TYPE) {
5831 var created = createFiberFromFragment(element.props.children, returnFiber.mode, lanes, element.key);
5832 created.return = returnFiber;
5833 return created;
5834 } else {
5835 var _created4 = createFiberFromElement(element, returnFiber.mode, lanes);
5836
5837 _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
5838 _created4.return = returnFiber;
5839 return _created4;
5840 }
5841 }
5842
5843 function reconcileSinglePortal(returnFiber, currentFirstChild, portal, lanes) {
5844 var key = portal.key;
5845 var child = currentFirstChild;
5846
5847 while (child !== null) {
5848 // TODO: If key === null and child.key === null, then this only applies to
5849 // the first item in the list.
5850 if (child.key === key) {
5851 if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
5852 deleteRemainingChildren(returnFiber, child.sibling);
5853 var existing = useFiber(child, portal.children || []);
5854 existing.return = returnFiber;
5855 return existing;
5856 } else {
5857 deleteRemainingChildren(returnFiber, child);
5858 break;
5859 }
5860 } else {
5861 deleteChild(returnFiber, child);
5862 }
5863
5864 child = child.sibling;
5865 }
5866
5867 var created = createFiberFromPortal(portal, returnFiber.mode, lanes);
5868 created.return = returnFiber;
5869 return created;
5870 } // This API will tag the children with the side-effect of the reconciliation
5871 // itself. They will be added to the side-effect list as we pass through the
5872 // children and the parent.
5873
5874
5875 function reconcileChildFibers(returnFiber, currentFirstChild, newChild, lanes) {
5876 // This function is not recursive.
5877 // If the top level item is an array, we treat it as a set of children,
5878 // not as a fragment. Nested arrays on the other hand will be treated as
5879 // fragment nodes. Recursion happens at the normal flow.
5880 // Handle top level unkeyed fragments as if they were arrays.
5881 // This leads to an ambiguity between <>{[...]}</> and <>...</>.
5882 // We treat the ambiguous cases above the same.
5883 var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
5884
5885 if (isUnkeyedTopLevelFragment) {
5886 newChild = newChild.props.children;
5887 } // Handle object types
5888
5889
5890 var isObject = typeof newChild === 'object' && newChild !== null;
5891
5892 if (isObject) {
5893 switch (newChild.$$typeof) {
5894 case REACT_ELEMENT_TYPE:
5895 return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, lanes));
5896
5897 case REACT_PORTAL_TYPE:
5898 return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, lanes));
5899
5900 }
5901 }
5902
5903 if (typeof newChild === 'string' || typeof newChild === 'number') {
5904 return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, lanes));
5905 }
5906
5907 if (isArray$1(newChild)) {
5908 return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, lanes);
5909 }
5910
5911 if (getIteratorFn(newChild)) {
5912 return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, lanes);
5913 }
5914
5915 if (isObject) {
5916 throwOnInvalidObjectType(returnFiber, newChild);
5917 }
5918
5919 {
5920 if (typeof newChild === 'function') {
5921 warnOnFunctionType(returnFiber);
5922 }
5923 }
5924
5925 if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {
5926 // If the new child is undefined, and the return fiber is a composite
5927 // component, throw an error. If Fiber return types are disabled,
5928 // we already threw above.
5929 switch (returnFiber.tag) {
5930 case ClassComponent:
5931 {
5932 {
5933 var instance = returnFiber.stateNode;
5934
5935 if (instance.render._isMockFunction) {
5936 // We allow auto-mocks to proceed as if they're returning null.
5937 break;
5938 }
5939 }
5940 }
5941 // Intentionally fall through to the next case, which handles both
5942 // functions and classes
5943 // eslint-disable-next-lined no-fallthrough
5944
5945 case Block:
5946 case FunctionComponent:
5947 case ForwardRef:
5948 case SimpleMemoComponent:
5949 {
5950 {
5951 {
5952 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." );
5953 }
5954 }
5955 }
5956 }
5957 } // Remaining cases are all treated as empty.
5958
5959
5960 return deleteRemainingChildren(returnFiber, currentFirstChild);
5961 }
5962
5963 return reconcileChildFibers;
5964 }
5965
5966 var reconcileChildFibers = ChildReconciler(true);
5967 var mountChildFibers = ChildReconciler(false);
5968 function cloneChildFibers(current, workInProgress) {
5969 if (!(current === null || workInProgress.child === current.child)) {
5970 {
5971 throw Error( "Resuming work not yet implemented." );
5972 }
5973 }
5974
5975 if (workInProgress.child === null) {
5976 return;
5977 }
5978
5979 var currentChild = workInProgress.child;
5980 var newChild = createWorkInProgress(currentChild, currentChild.pendingProps);
5981 workInProgress.child = newChild;
5982 newChild.return = workInProgress;
5983
5984 while (currentChild.sibling !== null) {
5985 currentChild = currentChild.sibling;
5986 newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps);
5987 newChild.return = workInProgress;
5988 }
5989
5990 newChild.sibling = null;
5991 } // Reset a workInProgress child set to prepare it for a second pass.
5992
5993 function resetChildFibers(workInProgress, lanes) {
5994 var child = workInProgress.child;
5995
5996 while (child !== null) {
5997 resetWorkInProgress(child, lanes);
5998 child = child.sibling;
5999 }
6000 }
6001
6002 var NO_CONTEXT$1 = {};
6003 var contextStackCursor$1 = createCursor(NO_CONTEXT$1);
6004 var contextFiberStackCursor = createCursor(NO_CONTEXT$1);
6005 var rootInstanceStackCursor = createCursor(NO_CONTEXT$1);
6006
6007 function requiredContext(c) {
6008 if (!(c !== NO_CONTEXT$1)) {
6009 {
6010 throw Error( "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." );
6011 }
6012 }
6013
6014 return c;
6015 }
6016
6017 function getRootHostContainer() {
6018 var rootInstance = requiredContext(rootInstanceStackCursor.current);
6019 return rootInstance;
6020 }
6021
6022 function pushHostContainer(fiber, nextRootInstance) {
6023 // Push current root instance onto the stack;
6024 // This allows us to reset root when portals are popped.
6025 push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it.
6026 // This enables us to pop only Fibers that provide unique contexts.
6027
6028 push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack.
6029 // However, we can't just call getRootHostContext() and push it because
6030 // we'd have a different number of entries on the stack depending on
6031 // whether getRootHostContext() throws somewhere in renderer code or not.
6032 // So we push an empty value first. This lets us safely unwind on errors.
6033
6034 push(contextStackCursor$1, NO_CONTEXT$1, fiber);
6035 var nextRootContext = getRootHostContext(); // Now that we know this function doesn't throw, replace it.
6036
6037 pop(contextStackCursor$1, fiber);
6038 push(contextStackCursor$1, nextRootContext, fiber);
6039 }
6040
6041 function popHostContainer(fiber) {
6042 pop(contextStackCursor$1, fiber);
6043 pop(contextFiberStackCursor, fiber);
6044 pop(rootInstanceStackCursor, fiber);
6045 }
6046
6047 function getHostContext() {
6048 var context = requiredContext(contextStackCursor$1.current);
6049 return context;
6050 }
6051
6052 function pushHostContext(fiber) {
6053 var rootInstance = requiredContext(rootInstanceStackCursor.current);
6054 var context = requiredContext(contextStackCursor$1.current);
6055 var nextContext = getChildHostContext(context, fiber.type); // Don't push this Fiber's context unless it's unique.
6056
6057 if (context === nextContext) {
6058 return;
6059 } // Track the context and the Fiber that provided it.
6060 // This enables us to pop only Fibers that provide unique contexts.
6061
6062
6063 push(contextFiberStackCursor, fiber, fiber);
6064 push(contextStackCursor$1, nextContext, fiber);
6065 }
6066
6067 function popHostContext(fiber) {
6068 // Do not pop unless this Fiber provided the current context.
6069 // pushHostContext() only pushes Fibers that provide unique contexts.
6070 if (contextFiberStackCursor.current !== fiber) {
6071 return;
6072 }
6073
6074 pop(contextStackCursor$1, fiber);
6075 pop(contextFiberStackCursor, fiber);
6076 }
6077
6078 var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is
6079 // inherited deeply down the subtree. The upper bits only affect
6080 // this immediate suspense boundary and gets reset each new
6081 // boundary or suspense list.
6082
6083 var SubtreeSuspenseContextMask = 1; // Subtree Flags:
6084 // InvisibleParentSuspenseContext indicates that one of our parent Suspense
6085 // boundaries is not currently showing visible main content.
6086 // Either because it is already showing a fallback or is not mounted at all.
6087 // We can use this to determine if it is desirable to trigger a fallback at
6088 // the parent. If not, then we might need to trigger undesirable boundaries
6089 // and/or suspend the commit to avoid hiding the parent content.
6090
6091 var InvisibleParentSuspenseContext = 1; // Shallow Flags:
6092 // ForceSuspenseFallback can be used by SuspenseList to force newly added
6093 // items into their fallback state during one of the render passes.
6094
6095 var ForceSuspenseFallback = 2;
6096 var suspenseStackCursor = createCursor(DefaultSuspenseContext);
6097 function hasSuspenseContext(parentContext, flag) {
6098 return (parentContext & flag) !== 0;
6099 }
6100 function setDefaultShallowSuspenseContext(parentContext) {
6101 return parentContext & SubtreeSuspenseContextMask;
6102 }
6103 function setShallowSuspenseContext(parentContext, shallowContext) {
6104 return parentContext & SubtreeSuspenseContextMask | shallowContext;
6105 }
6106 function addSubtreeSuspenseContext(parentContext, subtreeContext) {
6107 return parentContext | subtreeContext;
6108 }
6109 function pushSuspenseContext(fiber, newContext) {
6110 push(suspenseStackCursor, newContext, fiber);
6111 }
6112 function popSuspenseContext(fiber) {
6113 pop(suspenseStackCursor, fiber);
6114 }
6115
6116 function shouldCaptureSuspense(workInProgress, hasInvisibleParent) {
6117 // If it was the primary children that just suspended, capture and render the
6118 // fallback. Otherwise, don't capture and bubble to the next boundary.
6119 var nextState = workInProgress.memoizedState;
6120
6121 if (nextState !== null) {
6122 if (nextState.dehydrated !== null) {
6123 // A dehydrated boundary always captures.
6124 return true;
6125 }
6126
6127 return false;
6128 }
6129
6130 var props = workInProgress.memoizedProps; // In order to capture, the Suspense component must have a fallback prop.
6131
6132 if (props.fallback === undefined) {
6133 return false;
6134 } // Regular boundaries always capture.
6135
6136
6137 if (props.unstable_avoidThisFallback !== true) {
6138 return true;
6139 } // If it's a boundary we should avoid, then we prefer to bubble up to the
6140 // parent boundary if it is currently invisible.
6141
6142
6143 if (hasInvisibleParent) {
6144 return false;
6145 } // If the parent is not able to handle it, we must handle it.
6146
6147
6148 return true;
6149 }
6150 function findFirstSuspended(row) {
6151 var node = row;
6152
6153 while (node !== null) {
6154 if (node.tag === SuspenseComponent) {
6155 var state = node.memoizedState;
6156
6157 if (state !== null) {
6158 var dehydrated = state.dehydrated;
6159
6160 if (dehydrated === null || isSuspenseInstancePending() || isSuspenseInstanceFallback()) {
6161 return node;
6162 }
6163 }
6164 } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't
6165 // keep track of whether it suspended or not.
6166 node.memoizedProps.revealOrder !== undefined) {
6167 var didSuspend = (node.flags & DidCapture) !== NoFlags;
6168
6169 if (didSuspend) {
6170 return node;
6171 }
6172 } else if (node.child !== null) {
6173 node.child.return = node;
6174 node = node.child;
6175 continue;
6176 }
6177
6178 if (node === row) {
6179 return null;
6180 }
6181
6182 while (node.sibling === null) {
6183 if (node.return === null || node.return === row) {
6184 return null;
6185 }
6186
6187 node = node.return;
6188 }
6189
6190 node.sibling.return = node.return;
6191 node = node.sibling;
6192 }
6193
6194 return null;
6195 }
6196
6197 var NoFlags$1 =
6198 /* */
6199 0; // Represents whether effect should fire.
6200
6201 var HasEffect =
6202 /* */
6203 1; // Represents the phase in which the effect (not the clean-up) fires.
6204
6205 var Layout =
6206 /* */
6207 2;
6208 var Passive$1 =
6209 /* */
6210 4;
6211
6212 var isHydrating = false;
6213
6214 function enterHydrationState(fiber) {
6215 {
6216 return false;
6217 }
6218 }
6219
6220 function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
6221 {
6222 {
6223 {
6224 throw Error( "Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." );
6225 }
6226 }
6227 }
6228 }
6229
6230 function prepareToHydrateHostTextInstance(fiber) {
6231 {
6232 {
6233 {
6234 throw Error( "Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue." );
6235 }
6236 }
6237 }
6238 var shouldUpdate = hydrateTextInstance();
6239 }
6240
6241 function popHydrationState(fiber) {
6242 {
6243 return false;
6244 }
6245 }
6246
6247 function getIsHydrating() {
6248 return isHydrating;
6249 }
6250
6251 // and should be reset before starting a new render.
6252 // This tracks which mutable sources need to be reset after a render.
6253
6254 var workInProgressSources = [];
6255 var rendererSigil$1;
6256
6257 {
6258 // Used to detect multiple renderers using the same mutable source.
6259 rendererSigil$1 = {};
6260 }
6261
6262 function markSourceAsDirty(mutableSource) {
6263 workInProgressSources.push(mutableSource);
6264 }
6265 function resetWorkInProgressVersions() {
6266 for (var i = 0; i < workInProgressSources.length; i++) {
6267 var mutableSource = workInProgressSources[i];
6268
6269 {
6270 mutableSource._workInProgressVersionSecondary = null;
6271 }
6272 }
6273
6274 workInProgressSources.length = 0;
6275 }
6276 function getWorkInProgressVersion(mutableSource) {
6277 {
6278 return mutableSource._workInProgressVersionSecondary;
6279 }
6280 }
6281 function setWorkInProgressVersion(mutableSource, version) {
6282 {
6283 mutableSource._workInProgressVersionSecondary = version;
6284 }
6285
6286 workInProgressSources.push(mutableSource);
6287 }
6288 function warnAboutMultipleRenderersDEV(mutableSource) {
6289 {
6290 {
6291 if (mutableSource._currentSecondaryRenderer == null) {
6292 mutableSource._currentSecondaryRenderer = rendererSigil$1;
6293 } else if (mutableSource._currentSecondaryRenderer !== rendererSigil$1) {
6294 error('Detected multiple renderers concurrently rendering the ' + 'same mutable source. This is currently unsupported.');
6295 }
6296 }
6297 }
6298 } // Eager reads the version of a mutable source and stores it on the root.
6299
6300 var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher,
6301 ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig;
6302 var didWarnAboutMismatchedHooksForComponent;
6303 var didWarnAboutUseOpaqueIdentifier;
6304
6305 {
6306 didWarnAboutUseOpaqueIdentifier = {};
6307 didWarnAboutMismatchedHooksForComponent = new Set();
6308 }
6309
6310 // These are set right before calling the component.
6311 var renderLanes = NoLanes; // The work-in-progress fiber. I've named it differently to distinguish it from
6312 // the work-in-progress hook.
6313
6314 var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The
6315 // current hook list is the list that belongs to the current fiber. The
6316 // work-in-progress hook list is a new list that will be added to the
6317 // work-in-progress fiber.
6318
6319 var currentHook = null;
6320 var workInProgressHook = null; // Whether an update was scheduled at any point during the render phase. This
6321 // does not get reset if we do another render pass; only when we're completely
6322 // finished evaluating this component. This is an optimization so we know
6323 // whether we need to clear render phase updates after a throw.
6324
6325 var didScheduleRenderPhaseUpdate = false; // Where an update was scheduled only during the current render pass. This
6326 // gets reset after each attempt.
6327 // TODO: Maybe there's some way to consolidate this with
6328 // `didScheduleRenderPhaseUpdate`. Or with `numberOfReRenders`.
6329
6330 var didScheduleRenderPhaseUpdateDuringThisPass = false;
6331 var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook
6332
6333 var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders.
6334 // The list stores the order of hooks used during the initial render (mount).
6335 // Subsequent renders (updates) reference this list.
6336
6337 var hookTypesDev = null;
6338 var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore
6339 // the dependencies for Hooks that need them (e.g. useEffect or useMemo).
6340 // When true, such Hooks will always be "remounted". Only used during hot reload.
6341
6342 var ignorePreviousDependencies = false;
6343
6344 function mountHookTypesDev() {
6345 {
6346 var hookName = currentHookNameInDev;
6347
6348 if (hookTypesDev === null) {
6349 hookTypesDev = [hookName];
6350 } else {
6351 hookTypesDev.push(hookName);
6352 }
6353 }
6354 }
6355
6356 function updateHookTypesDev() {
6357 {
6358 var hookName = currentHookNameInDev;
6359
6360 if (hookTypesDev !== null) {
6361 hookTypesUpdateIndexDev++;
6362
6363 if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
6364 warnOnHookMismatchInDev(hookName);
6365 }
6366 }
6367 }
6368 }
6369
6370 function checkDepsAreArrayDev(deps) {
6371 {
6372 if (deps !== undefined && deps !== null && !Array.isArray(deps)) {
6373 // Verify deps, but only on mount to avoid extra checks.
6374 // It's unlikely their type would change as usually you define them inline.
6375 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);
6376 }
6377 }
6378 }
6379
6380 function warnOnHookMismatchInDev(currentHookName) {
6381 {
6382 var componentName = getComponentName(currentlyRenderingFiber$1.type);
6383
6384 if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
6385 didWarnAboutMismatchedHooksForComponent.add(componentName);
6386
6387 if (hookTypesDev !== null) {
6388 var table = '';
6389 var secondColumnStart = 30;
6390
6391 for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {
6392 var oldHookName = hookTypesDev[i];
6393 var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
6394 var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up
6395 // lol @ IE not supporting String#repeat
6396
6397 while (row.length < secondColumnStart) {
6398 row += ' ';
6399 }
6400
6401 row += newHookName + '\n';
6402 table += row;
6403 }
6404
6405 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);
6406 }
6407 }
6408 }
6409 }
6410
6411 function throwInvalidHookError() {
6412 {
6413 {
6414 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." );
6415 }
6416 }
6417 }
6418
6419 function areHookInputsEqual(nextDeps, prevDeps) {
6420 {
6421 if (ignorePreviousDependencies) {
6422 // Only true when this component is being hot reloaded.
6423 return false;
6424 }
6425 }
6426
6427 if (prevDeps === null) {
6428 {
6429 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);
6430 }
6431
6432 return false;
6433 }
6434
6435 {
6436 // Don't bother comparing lengths in prod because these arrays should be
6437 // passed inline.
6438 if (nextDeps.length !== prevDeps.length) {
6439 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(', ') + "]");
6440 }
6441 }
6442
6443 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
6444 if (objectIs(nextDeps[i], prevDeps[i])) {
6445 continue;
6446 }
6447
6448 return false;
6449 }
6450
6451 return true;
6452 }
6453
6454 function renderWithHooks(current, workInProgress, Component, props, secondArg, nextRenderLanes) {
6455 renderLanes = nextRenderLanes;
6456 currentlyRenderingFiber$1 = workInProgress;
6457
6458 {
6459 hookTypesDev = current !== null ? current._debugHookTypes : null;
6460 hookTypesUpdateIndexDev = -1; // Used for hot reloading:
6461
6462 ignorePreviousDependencies = current !== null && current.type !== workInProgress.type;
6463 }
6464
6465 workInProgress.memoizedState = null;
6466 workInProgress.updateQueue = null;
6467 workInProgress.lanes = NoLanes; // The following should have already been reset
6468 // currentHook = null;
6469 // workInProgressHook = null;
6470 // didScheduleRenderPhaseUpdate = false;
6471 // TODO Warn if no hooks are used at all during mount, then some are used during update.
6472 // Currently we will identify the update render as a mount because memoizedState === null.
6473 // This is tricky because it's valid for certain types of components (e.g. React.lazy)
6474 // Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used.
6475 // Non-stateful hooks (e.g. context) don't get added to memoizedState,
6476 // so memoizedState would be null during updates and mounts.
6477
6478 {
6479 if (current !== null && current.memoizedState !== null) {
6480 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
6481 } else if (hookTypesDev !== null) {
6482 // This dispatcher handles an edge case where a component is updating,
6483 // but no stateful hooks have been used.
6484 // We want to match the production code behavior (which will use HooksDispatcherOnMount),
6485 // but with the extra DEV validation to ensure hooks ordering hasn't changed.
6486 // This dispatcher does that.
6487 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV;
6488 } else {
6489 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV;
6490 }
6491 }
6492
6493 var children = Component(props, secondArg); // Check if there was a render phase update
6494
6495 if (didScheduleRenderPhaseUpdateDuringThisPass) {
6496 // Keep rendering in a loop for as long as render phase updates continue to
6497 // be scheduled. Use a counter to prevent infinite loops.
6498 var numberOfReRenders = 0;
6499
6500 do {
6501 didScheduleRenderPhaseUpdateDuringThisPass = false;
6502
6503 if (!(numberOfReRenders < RE_RENDER_LIMIT)) {
6504 {
6505 throw Error( "Too many re-renders. React limits the number of renders to prevent an infinite loop." );
6506 }
6507 }
6508
6509 numberOfReRenders += 1;
6510
6511 {
6512 // Even when hot reloading, allow dependencies to stabilize
6513 // after first render to prevent infinite render phase updates.
6514 ignorePreviousDependencies = false;
6515 } // Start over from the beginning of the list
6516
6517
6518 currentHook = null;
6519 workInProgressHook = null;
6520 workInProgress.updateQueue = null;
6521
6522 {
6523 // Also validate hook order for cascading updates.
6524 hookTypesUpdateIndexDev = -1;
6525 }
6526
6527 ReactCurrentDispatcher$1.current = HooksDispatcherOnRerenderInDEV ;
6528 children = Component(props, secondArg);
6529 } while (didScheduleRenderPhaseUpdateDuringThisPass);
6530 } // We can assume the previous dispatcher is always this one, since we set it
6531 // at the beginning of the render phase and there's no re-entrancy.
6532
6533
6534 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
6535
6536 {
6537 workInProgress._debugHookTypes = hookTypesDev;
6538 } // This check uses currentHook so that it works the same in DEV and prod bundles.
6539 // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.
6540
6541
6542 var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
6543 renderLanes = NoLanes;
6544 currentlyRenderingFiber$1 = null;
6545 currentHook = null;
6546 workInProgressHook = null;
6547
6548 {
6549 currentHookNameInDev = null;
6550 hookTypesDev = null;
6551 hookTypesUpdateIndexDev = -1;
6552 }
6553
6554 didScheduleRenderPhaseUpdate = false;
6555
6556 if (!!didRenderTooFewHooks) {
6557 {
6558 throw Error( "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." );
6559 }
6560 }
6561
6562 return children;
6563 }
6564 function bailoutHooks(current, workInProgress, lanes) {
6565 workInProgress.updateQueue = current.updateQueue;
6566 workInProgress.flags &= ~(Passive | Update);
6567 current.lanes = removeLanes(current.lanes, lanes);
6568 }
6569 function resetHooksAfterThrow() {
6570 // We can assume the previous dispatcher is always this one, since we set it
6571 // at the beginning of the render phase and there's no re-entrancy.
6572 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
6573
6574 if (didScheduleRenderPhaseUpdate) {
6575 // There were render phase updates. These are only valid for this render
6576 // phase, which we are now aborting. Remove the updates from the queues so
6577 // they do not persist to the next render. Do not remove updates from hooks
6578 // that weren't processed.
6579 //
6580 // Only reset the updates from the queue if it has a clone. If it does
6581 // not have a clone, that means it wasn't processed, and the updates were
6582 // scheduled before we entered the render phase.
6583 var hook = currentlyRenderingFiber$1.memoizedState;
6584
6585 while (hook !== null) {
6586 var queue = hook.queue;
6587
6588 if (queue !== null) {
6589 queue.pending = null;
6590 }
6591
6592 hook = hook.next;
6593 }
6594
6595 didScheduleRenderPhaseUpdate = false;
6596 }
6597
6598 renderLanes = NoLanes;
6599 currentlyRenderingFiber$1 = null;
6600 currentHook = null;
6601 workInProgressHook = null;
6602
6603 {
6604 hookTypesDev = null;
6605 hookTypesUpdateIndexDev = -1;
6606 currentHookNameInDev = null;
6607 isUpdatingOpaqueValueInRenderPhase = false;
6608 }
6609
6610 didScheduleRenderPhaseUpdateDuringThisPass = false;
6611 }
6612
6613 function mountWorkInProgressHook() {
6614 var hook = {
6615 memoizedState: null,
6616 baseState: null,
6617 baseQueue: null,
6618 queue: null,
6619 next: null
6620 };
6621
6622 if (workInProgressHook === null) {
6623 // This is the first hook in the list
6624 currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook;
6625 } else {
6626 // Append to the end of the list
6627 workInProgressHook = workInProgressHook.next = hook;
6628 }
6629
6630 return workInProgressHook;
6631 }
6632
6633 function updateWorkInProgressHook() {
6634 // This function is used both for updates and for re-renders triggered by a
6635 // render phase update. It assumes there is either a current hook we can
6636 // clone, or a work-in-progress hook from a previous render pass that we can
6637 // use as a base. When we reach the end of the base list, we must switch to
6638 // the dispatcher used for mounts.
6639 var nextCurrentHook;
6640
6641 if (currentHook === null) {
6642 var current = currentlyRenderingFiber$1.alternate;
6643
6644 if (current !== null) {
6645 nextCurrentHook = current.memoizedState;
6646 } else {
6647 nextCurrentHook = null;
6648 }
6649 } else {
6650 nextCurrentHook = currentHook.next;
6651 }
6652
6653 var nextWorkInProgressHook;
6654
6655 if (workInProgressHook === null) {
6656 nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState;
6657 } else {
6658 nextWorkInProgressHook = workInProgressHook.next;
6659 }
6660
6661 if (nextWorkInProgressHook !== null) {
6662 // There's already a work-in-progress. Reuse it.
6663 workInProgressHook = nextWorkInProgressHook;
6664 nextWorkInProgressHook = workInProgressHook.next;
6665 currentHook = nextCurrentHook;
6666 } else {
6667 // Clone from the current hook.
6668 if (!(nextCurrentHook !== null)) {
6669 {
6670 throw Error( "Rendered more hooks than during the previous render." );
6671 }
6672 }
6673
6674 currentHook = nextCurrentHook;
6675 var newHook = {
6676 memoizedState: currentHook.memoizedState,
6677 baseState: currentHook.baseState,
6678 baseQueue: currentHook.baseQueue,
6679 queue: currentHook.queue,
6680 next: null
6681 };
6682
6683 if (workInProgressHook === null) {
6684 // This is the first hook in the list.
6685 currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook;
6686 } else {
6687 // Append to the end of the list.
6688 workInProgressHook = workInProgressHook.next = newHook;
6689 }
6690 }
6691
6692 return workInProgressHook;
6693 }
6694
6695 function createFunctionComponentUpdateQueue() {
6696 return {
6697 lastEffect: null
6698 };
6699 }
6700
6701 function basicStateReducer(state, action) {
6702 // $FlowFixMe: Flow doesn't like mixed types
6703 return typeof action === 'function' ? action(state) : action;
6704 }
6705
6706 function mountReducer(reducer, initialArg, init) {
6707 var hook = mountWorkInProgressHook();
6708 var initialState;
6709
6710 if (init !== undefined) {
6711 initialState = init(initialArg);
6712 } else {
6713 initialState = initialArg;
6714 }
6715
6716 hook.memoizedState = hook.baseState = initialState;
6717 var queue = hook.queue = {
6718 pending: null,
6719 dispatch: null,
6720 lastRenderedReducer: reducer,
6721 lastRenderedState: initialState
6722 };
6723 var dispatch = queue.dispatch = dispatchAction.bind(null, currentlyRenderingFiber$1, queue);
6724 return [hook.memoizedState, dispatch];
6725 }
6726
6727 function updateReducer(reducer, initialArg, init) {
6728 var hook = updateWorkInProgressHook();
6729 var queue = hook.queue;
6730
6731 if (!(queue !== null)) {
6732 {
6733 throw Error( "Should have a queue. This is likely a bug in React. Please file an issue." );
6734 }
6735 }
6736
6737 queue.lastRenderedReducer = reducer;
6738 var current = currentHook; // The last rebase update that is NOT part of the base state.
6739
6740 var baseQueue = current.baseQueue; // The last pending update that hasn't been processed yet.
6741
6742 var pendingQueue = queue.pending;
6743
6744 if (pendingQueue !== null) {
6745 // We have new updates that haven't been processed yet.
6746 // We'll add them to the base queue.
6747 if (baseQueue !== null) {
6748 // Merge the pending queue and the base queue.
6749 var baseFirst = baseQueue.next;
6750 var pendingFirst = pendingQueue.next;
6751 baseQueue.next = pendingFirst;
6752 pendingQueue.next = baseFirst;
6753 }
6754
6755 {
6756 if (current.baseQueue !== baseQueue) {
6757 // Internal invariant that should never happen, but feasibly could in
6758 // the future if we implement resuming, or some form of that.
6759 error('Internal error: Expected work-in-progress queue to be a clone. ' + 'This is a bug in React.');
6760 }
6761 }
6762
6763 current.baseQueue = baseQueue = pendingQueue;
6764 queue.pending = null;
6765 }
6766
6767 if (baseQueue !== null) {
6768 // We have a queue to process.
6769 var first = baseQueue.next;
6770 var newState = current.baseState;
6771 var newBaseState = null;
6772 var newBaseQueueFirst = null;
6773 var newBaseQueueLast = null;
6774 var update = first;
6775
6776 do {
6777 var updateLane = update.lane;
6778
6779 if (!isSubsetOfLanes(renderLanes, updateLane)) {
6780 // Priority is insufficient. Skip this update. If this is the first
6781 // skipped update, the previous update/state is the new base
6782 // update/state.
6783 var clone = {
6784 lane: updateLane,
6785 action: update.action,
6786 eagerReducer: update.eagerReducer,
6787 eagerState: update.eagerState,
6788 next: null
6789 };
6790
6791 if (newBaseQueueLast === null) {
6792 newBaseQueueFirst = newBaseQueueLast = clone;
6793 newBaseState = newState;
6794 } else {
6795 newBaseQueueLast = newBaseQueueLast.next = clone;
6796 } // Update the remaining priority in the queue.
6797 // TODO: Don't need to accumulate this. Instead, we can remove
6798 // renderLanes from the original lanes.
6799
6800
6801 currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, updateLane);
6802 markSkippedUpdateLanes(updateLane);
6803 } else {
6804 // This update does have sufficient priority.
6805 if (newBaseQueueLast !== null) {
6806 var _clone = {
6807 // This update is going to be committed so we never want uncommit
6808 // it. Using NoLane works because 0 is a subset of all bitmasks, so
6809 // this will never be skipped by the check above.
6810 lane: NoLane,
6811 action: update.action,
6812 eagerReducer: update.eagerReducer,
6813 eagerState: update.eagerState,
6814 next: null
6815 };
6816 newBaseQueueLast = newBaseQueueLast.next = _clone;
6817 } // Process this update.
6818
6819
6820 if (update.eagerReducer === reducer) {
6821 // If this update was processed eagerly, and its reducer matches the
6822 // current reducer, we can use the eagerly computed state.
6823 newState = update.eagerState;
6824 } else {
6825 var action = update.action;
6826 newState = reducer(newState, action);
6827 }
6828 }
6829
6830 update = update.next;
6831 } while (update !== null && update !== first);
6832
6833 if (newBaseQueueLast === null) {
6834 newBaseState = newState;
6835 } else {
6836 newBaseQueueLast.next = newBaseQueueFirst;
6837 } // Mark that the fiber performed work, but only if the new state is
6838 // different from the current state.
6839
6840
6841 if (!objectIs(newState, hook.memoizedState)) {
6842 markWorkInProgressReceivedUpdate();
6843 }
6844
6845 hook.memoizedState = newState;
6846 hook.baseState = newBaseState;
6847 hook.baseQueue = newBaseQueueLast;
6848 queue.lastRenderedState = newState;
6849 }
6850
6851 var dispatch = queue.dispatch;
6852 return [hook.memoizedState, dispatch];
6853 }
6854
6855 function rerenderReducer(reducer, initialArg, init) {
6856 var hook = updateWorkInProgressHook();
6857 var queue = hook.queue;
6858
6859 if (!(queue !== null)) {
6860 {
6861 throw Error( "Should have a queue. This is likely a bug in React. Please file an issue." );
6862 }
6863 }
6864
6865 queue.lastRenderedReducer = reducer; // This is a re-render. Apply the new render phase updates to the previous
6866 // work-in-progress hook.
6867
6868 var dispatch = queue.dispatch;
6869 var lastRenderPhaseUpdate = queue.pending;
6870 var newState = hook.memoizedState;
6871
6872 if (lastRenderPhaseUpdate !== null) {
6873 // The queue doesn't persist past this render pass.
6874 queue.pending = null;
6875 var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next;
6876 var update = firstRenderPhaseUpdate;
6877
6878 do {
6879 // Process this render phase update. We don't have to check the
6880 // priority because it will always be the same as the current
6881 // render's.
6882 var action = update.action;
6883 newState = reducer(newState, action);
6884 update = update.next;
6885 } while (update !== firstRenderPhaseUpdate); // Mark that the fiber performed work, but only if the new state is
6886 // different from the current state.
6887
6888
6889 if (!objectIs(newState, hook.memoizedState)) {
6890 markWorkInProgressReceivedUpdate();
6891 }
6892
6893 hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to
6894 // the base state unless the queue is empty.
6895 // TODO: Not sure if this is the desired semantics, but it's what we
6896 // do for gDSFP. I can't remember why.
6897
6898 if (hook.baseQueue === null) {
6899 hook.baseState = newState;
6900 }
6901
6902 queue.lastRenderedState = newState;
6903 }
6904
6905 return [newState, dispatch];
6906 }
6907
6908 function readFromUnsubcribedMutableSource(root, source, getSnapshot) {
6909 {
6910 warnAboutMultipleRenderersDEV(source);
6911 }
6912
6913 var getVersion = source._getVersion;
6914 var version = getVersion(source._source); // Is it safe for this component to read from this source during the current render?
6915
6916 var isSafeToReadFromSource = false; // Check the version first.
6917 // If this render has already been started with a specific version,
6918 // we can use it alone to determine if we can safely read from the source.
6919
6920 var currentRenderVersion = getWorkInProgressVersion(source);
6921
6922 if (currentRenderVersion !== null) {
6923 // It's safe to read if the store hasn't been mutated since the last time
6924 // we read something.
6925 isSafeToReadFromSource = currentRenderVersion === version;
6926 } else {
6927 // If there's no version, then this is the first time we've read from the
6928 // source during the current render pass, so we need to do a bit more work.
6929 // What we need to determine is if there are any hooks that already
6930 // subscribed to the source, and if so, whether there are any pending
6931 // mutations that haven't been synchronized yet.
6932 //
6933 // If there are no pending mutations, then `root.mutableReadLanes` will be
6934 // empty, and we know we can safely read.
6935 //
6936 // If there *are* pending mutations, we may still be able to safely read
6937 // if the currently rendering lanes are inclusive of the pending mutation
6938 // lanes, since that guarantees that the value we're about to read from
6939 // the source is consistent with the values that we read during the most
6940 // recent mutation.
6941 isSafeToReadFromSource = isSubsetOfLanes(renderLanes, root.mutableReadLanes);
6942
6943 if (isSafeToReadFromSource) {
6944 // If it's safe to read from this source during the current render,
6945 // store the version in case other components read from it.
6946 // A changed version number will let those components know to throw and restart the render.
6947 setWorkInProgressVersion(source, version);
6948 }
6949 }
6950
6951 if (isSafeToReadFromSource) {
6952 var snapshot = getSnapshot(source._source);
6953
6954 {
6955 if (typeof snapshot === 'function') {
6956 error('Mutable source should not return a function as the snapshot value. ' + 'Functions may close over mutable values and cause tearing.');
6957 }
6958 }
6959
6960 return snapshot;
6961 } else {
6962 // This handles the special case of a mutable source being shared between renderers.
6963 // In that case, if the source is mutated between the first and second renderer,
6964 // The second renderer don't know that it needs to reset the WIP version during unwind,
6965 // (because the hook only marks sources as dirty if it's written to their WIP version).
6966 // That would cause this tear check to throw again and eventually be visible to the user.
6967 // We can avoid this infinite loop by explicitly marking the source as dirty.
6968 //
6969 // This can lead to tearing in the first renderer when it resumes,
6970 // but there's nothing we can do about that (short of throwing here and refusing to continue the render).
6971 markSourceAsDirty(source);
6972
6973 {
6974 {
6975 throw Error( "Cannot read from mutable source during the current render without tearing. This is a bug in React. Please file an issue." );
6976 }
6977 }
6978 }
6979 }
6980
6981 function useMutableSource(hook, source, getSnapshot, subscribe) {
6982 var root = getWorkInProgressRoot();
6983
6984 if (!(root !== null)) {
6985 {
6986 throw Error( "Expected a work-in-progress root. This is a bug in React. Please file an issue." );
6987 }
6988 }
6989
6990 var getVersion = source._getVersion;
6991 var version = getVersion(source._source);
6992 var dispatcher = ReactCurrentDispatcher$1.current; // eslint-disable-next-line prefer-const
6993
6994 var _dispatcher$useState = dispatcher.useState(function () {
6995 return readFromUnsubcribedMutableSource(root, source, getSnapshot);
6996 }),
6997 currentSnapshot = _dispatcher$useState[0],
6998 setSnapshot = _dispatcher$useState[1];
6999
7000 var snapshot = currentSnapshot; // Grab a handle to the state hook as well.
7001 // We use it to clear the pending update queue if we have a new source.
7002
7003 var stateHook = workInProgressHook;
7004 var memoizedState = hook.memoizedState;
7005 var refs = memoizedState.refs;
7006 var prevGetSnapshot = refs.getSnapshot;
7007 var prevSource = memoizedState.source;
7008 var prevSubscribe = memoizedState.subscribe;
7009 var fiber = currentlyRenderingFiber$1;
7010 hook.memoizedState = {
7011 refs: refs,
7012 source: source,
7013 subscribe: subscribe
7014 }; // Sync the values needed by our subscription handler after each commit.
7015
7016 dispatcher.useEffect(function () {
7017 refs.getSnapshot = getSnapshot; // Normally the dispatch function for a state hook never changes,
7018 // but this hook recreates the queue in certain cases to avoid updates from stale sources.
7019 // handleChange() below needs to reference the dispatch function without re-subscribing,
7020 // so we use a ref to ensure that it always has the latest version.
7021
7022 refs.setSnapshot = setSnapshot; // Check for a possible change between when we last rendered now.
7023
7024 var maybeNewVersion = getVersion(source._source);
7025
7026 if (!objectIs(version, maybeNewVersion)) {
7027 var maybeNewSnapshot = getSnapshot(source._source);
7028
7029 {
7030 if (typeof maybeNewSnapshot === 'function') {
7031 error('Mutable source should not return a function as the snapshot value. ' + 'Functions may close over mutable values and cause tearing.');
7032 }
7033 }
7034
7035 if (!objectIs(snapshot, maybeNewSnapshot)) {
7036 setSnapshot(maybeNewSnapshot);
7037 var lane = requestUpdateLane(fiber);
7038 markRootMutableRead(root, lane);
7039 } // If the source mutated between render and now,
7040 // there may be state updates already scheduled from the old source.
7041 // Entangle the updates so that they render in the same batch.
7042
7043
7044 markRootEntangled(root, root.mutableReadLanes);
7045 }
7046 }, [getSnapshot, source, subscribe]); // If we got a new source or subscribe function, re-subscribe in a passive effect.
7047
7048 dispatcher.useEffect(function () {
7049 var handleChange = function () {
7050 var latestGetSnapshot = refs.getSnapshot;
7051 var latestSetSnapshot = refs.setSnapshot;
7052
7053 try {
7054 latestSetSnapshot(latestGetSnapshot(source._source)); // Record a pending mutable source update with the same expiration time.
7055
7056 var lane = requestUpdateLane(fiber);
7057 markRootMutableRead(root, lane);
7058 } catch (error) {
7059 // A selector might throw after a source mutation.
7060 // e.g. it might try to read from a part of the store that no longer exists.
7061 // In this case we should still schedule an update with React.
7062 // Worst case the selector will throw again and then an error boundary will handle it.
7063 latestSetSnapshot(function () {
7064 throw error;
7065 });
7066 }
7067 };
7068
7069 var unsubscribe = subscribe(source._source, handleChange);
7070
7071 {
7072 if (typeof unsubscribe !== 'function') {
7073 error('Mutable source subscribe function must return an unsubscribe function.');
7074 }
7075 }
7076
7077 return unsubscribe;
7078 }, [source, subscribe]); // If any of the inputs to useMutableSource change, reading is potentially unsafe.
7079 //
7080 // If either the source or the subscription have changed we can't can't trust the update queue.
7081 // Maybe the source changed in a way that the old subscription ignored but the new one depends on.
7082 //
7083 // If the getSnapshot function changed, we also shouldn't rely on the update queue.
7084 // It's possible that the underlying source was mutated between the when the last "change" event fired,
7085 // and when the current render (with the new getSnapshot function) is processed.
7086 //
7087 // In both cases, we need to throw away pending updates (since they are no longer relevant)
7088 // and treat reading from the source as we do in the mount case.
7089
7090 if (!objectIs(prevGetSnapshot, getSnapshot) || !objectIs(prevSource, source) || !objectIs(prevSubscribe, subscribe)) {
7091 // Create a new queue and setState method,
7092 // So if there are interleaved updates, they get pushed to the older queue.
7093 // When this becomes current, the previous queue and dispatch method will be discarded,
7094 // including any interleaving updates that occur.
7095 var newQueue = {
7096 pending: null,
7097 dispatch: null,
7098 lastRenderedReducer: basicStateReducer,
7099 lastRenderedState: snapshot
7100 };
7101 newQueue.dispatch = setSnapshot = dispatchAction.bind(null, currentlyRenderingFiber$1, newQueue);
7102 stateHook.queue = newQueue;
7103 stateHook.baseQueue = null;
7104 snapshot = readFromUnsubcribedMutableSource(root, source, getSnapshot);
7105 stateHook.memoizedState = stateHook.baseState = snapshot;
7106 }
7107
7108 return snapshot;
7109 }
7110
7111 function mountMutableSource(source, getSnapshot, subscribe) {
7112 var hook = mountWorkInProgressHook();
7113 hook.memoizedState = {
7114 refs: {
7115 getSnapshot: getSnapshot,
7116 setSnapshot: null
7117 },
7118 source: source,
7119 subscribe: subscribe
7120 };
7121 return useMutableSource(hook, source, getSnapshot, subscribe);
7122 }
7123
7124 function updateMutableSource(source, getSnapshot, subscribe) {
7125 var hook = updateWorkInProgressHook();
7126 return useMutableSource(hook, source, getSnapshot, subscribe);
7127 }
7128
7129 function mountState(initialState) {
7130 var hook = mountWorkInProgressHook();
7131
7132 if (typeof initialState === 'function') {
7133 // $FlowFixMe: Flow doesn't like mixed types
7134 initialState = initialState();
7135 }
7136
7137 hook.memoizedState = hook.baseState = initialState;
7138 var queue = hook.queue = {
7139 pending: null,
7140 dispatch: null,
7141 lastRenderedReducer: basicStateReducer,
7142 lastRenderedState: initialState
7143 };
7144 var dispatch = queue.dispatch = dispatchAction.bind(null, currentlyRenderingFiber$1, queue);
7145 return [hook.memoizedState, dispatch];
7146 }
7147
7148 function updateState(initialState) {
7149 return updateReducer(basicStateReducer);
7150 }
7151
7152 function rerenderState(initialState) {
7153 return rerenderReducer(basicStateReducer);
7154 }
7155
7156 function pushEffect(tag, create, destroy, deps) {
7157 var effect = {
7158 tag: tag,
7159 create: create,
7160 destroy: destroy,
7161 deps: deps,
7162 // Circular
7163 next: null
7164 };
7165 var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue;
7166
7167 if (componentUpdateQueue === null) {
7168 componentUpdateQueue = createFunctionComponentUpdateQueue();
7169 currentlyRenderingFiber$1.updateQueue = componentUpdateQueue;
7170 componentUpdateQueue.lastEffect = effect.next = effect;
7171 } else {
7172 var lastEffect = componentUpdateQueue.lastEffect;
7173
7174 if (lastEffect === null) {
7175 componentUpdateQueue.lastEffect = effect.next = effect;
7176 } else {
7177 var firstEffect = lastEffect.next;
7178 lastEffect.next = effect;
7179 effect.next = firstEffect;
7180 componentUpdateQueue.lastEffect = effect;
7181 }
7182 }
7183
7184 return effect;
7185 }
7186
7187 function mountRef(initialValue) {
7188 var hook = mountWorkInProgressHook();
7189 var ref = {
7190 current: initialValue
7191 };
7192
7193 {
7194 Object.seal(ref);
7195 }
7196
7197 hook.memoizedState = ref;
7198 return ref;
7199 }
7200
7201 function updateRef(initialValue) {
7202 var hook = updateWorkInProgressHook();
7203 return hook.memoizedState;
7204 }
7205
7206 function mountEffectImpl(fiberFlags, hookFlags, create, deps) {
7207 var hook = mountWorkInProgressHook();
7208 var nextDeps = deps === undefined ? null : deps;
7209 currentlyRenderingFiber$1.flags |= fiberFlags;
7210 hook.memoizedState = pushEffect(HasEffect | hookFlags, create, undefined, nextDeps);
7211 }
7212
7213 function updateEffectImpl(fiberFlags, hookFlags, create, deps) {
7214 var hook = updateWorkInProgressHook();
7215 var nextDeps = deps === undefined ? null : deps;
7216 var destroy = undefined;
7217
7218 if (currentHook !== null) {
7219 var prevEffect = currentHook.memoizedState;
7220 destroy = prevEffect.destroy;
7221
7222 if (nextDeps !== null) {
7223 var prevDeps = prevEffect.deps;
7224
7225 if (areHookInputsEqual(nextDeps, prevDeps)) {
7226 pushEffect(hookFlags, create, destroy, nextDeps);
7227 return;
7228 }
7229 }
7230 }
7231
7232 currentlyRenderingFiber$1.flags |= fiberFlags;
7233 hook.memoizedState = pushEffect(HasEffect | hookFlags, create, destroy, nextDeps);
7234 }
7235
7236 function mountEffect(create, deps) {
7237
7238 return mountEffectImpl(Update | Passive, Passive$1, create, deps);
7239 }
7240
7241 function updateEffect(create, deps) {
7242
7243 return updateEffectImpl(Update | Passive, Passive$1, create, deps);
7244 }
7245
7246 function mountLayoutEffect(create, deps) {
7247 return mountEffectImpl(Update, Layout, create, deps);
7248 }
7249
7250 function updateLayoutEffect(create, deps) {
7251 return updateEffectImpl(Update, Layout, create, deps);
7252 }
7253
7254 function imperativeHandleEffect(create, ref) {
7255 if (typeof ref === 'function') {
7256 var refCallback = ref;
7257
7258 var _inst = create();
7259
7260 refCallback(_inst);
7261 return function () {
7262 refCallback(null);
7263 };
7264 } else if (ref !== null && ref !== undefined) {
7265 var refObject = ref;
7266
7267 {
7268 if (!refObject.hasOwnProperty('current')) {
7269 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(', ') + '}');
7270 }
7271 }
7272
7273 var _inst2 = create();
7274
7275 refObject.current = _inst2;
7276 return function () {
7277 refObject.current = null;
7278 };
7279 }
7280 }
7281
7282 function mountImperativeHandle(ref, create, deps) {
7283 {
7284 if (typeof create !== 'function') {
7285 error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');
7286 }
7287 } // TODO: If deps are provided, should we skip comparing the ref itself?
7288
7289
7290 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
7291 return mountEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
7292 }
7293
7294 function updateImperativeHandle(ref, create, deps) {
7295 {
7296 if (typeof create !== 'function') {
7297 error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');
7298 }
7299 } // TODO: If deps are provided, should we skip comparing the ref itself?
7300
7301
7302 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
7303 return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
7304 }
7305
7306 function mountDebugValue(value, formatterFn) {// This hook is normally a no-op.
7307 // The react-debug-hooks package injects its own implementation
7308 // so that e.g. DevTools can display custom hook values.
7309 }
7310
7311 var updateDebugValue = mountDebugValue;
7312
7313 function mountCallback(callback, deps) {
7314 var hook = mountWorkInProgressHook();
7315 var nextDeps = deps === undefined ? null : deps;
7316 hook.memoizedState = [callback, nextDeps];
7317 return callback;
7318 }
7319
7320 function updateCallback(callback, deps) {
7321 var hook = updateWorkInProgressHook();
7322 var nextDeps = deps === undefined ? null : deps;
7323 var prevState = hook.memoizedState;
7324
7325 if (prevState !== null) {
7326 if (nextDeps !== null) {
7327 var prevDeps = prevState[1];
7328
7329 if (areHookInputsEqual(nextDeps, prevDeps)) {
7330 return prevState[0];
7331 }
7332 }
7333 }
7334
7335 hook.memoizedState = [callback, nextDeps];
7336 return callback;
7337 }
7338
7339 function mountMemo(nextCreate, deps) {
7340 var hook = mountWorkInProgressHook();
7341 var nextDeps = deps === undefined ? null : deps;
7342 var nextValue = nextCreate();
7343 hook.memoizedState = [nextValue, nextDeps];
7344 return nextValue;
7345 }
7346
7347 function updateMemo(nextCreate, deps) {
7348 var hook = updateWorkInProgressHook();
7349 var nextDeps = deps === undefined ? null : deps;
7350 var prevState = hook.memoizedState;
7351
7352 if (prevState !== null) {
7353 // Assume these are defined. If they're not, areHookInputsEqual will warn.
7354 if (nextDeps !== null) {
7355 var prevDeps = prevState[1];
7356
7357 if (areHookInputsEqual(nextDeps, prevDeps)) {
7358 return prevState[0];
7359 }
7360 }
7361 }
7362
7363 var nextValue = nextCreate();
7364 hook.memoizedState = [nextValue, nextDeps];
7365 return nextValue;
7366 }
7367
7368 function mountDeferredValue(value) {
7369 var _mountState = mountState(value),
7370 prevValue = _mountState[0],
7371 setValue = _mountState[1];
7372
7373 mountEffect(function () {
7374 var prevTransition = ReactCurrentBatchConfig$1.transition;
7375 ReactCurrentBatchConfig$1.transition = 1;
7376
7377 try {
7378 setValue(value);
7379 } finally {
7380 ReactCurrentBatchConfig$1.transition = prevTransition;
7381 }
7382 }, [value]);
7383 return prevValue;
7384 }
7385
7386 function updateDeferredValue(value) {
7387 var _updateState = updateState(),
7388 prevValue = _updateState[0],
7389 setValue = _updateState[1];
7390
7391 updateEffect(function () {
7392 var prevTransition = ReactCurrentBatchConfig$1.transition;
7393 ReactCurrentBatchConfig$1.transition = 1;
7394
7395 try {
7396 setValue(value);
7397 } finally {
7398 ReactCurrentBatchConfig$1.transition = prevTransition;
7399 }
7400 }, [value]);
7401 return prevValue;
7402 }
7403
7404 function rerenderDeferredValue(value) {
7405 var _rerenderState = rerenderState(),
7406 prevValue = _rerenderState[0],
7407 setValue = _rerenderState[1];
7408
7409 updateEffect(function () {
7410 var prevTransition = ReactCurrentBatchConfig$1.transition;
7411 ReactCurrentBatchConfig$1.transition = 1;
7412
7413 try {
7414 setValue(value);
7415 } finally {
7416 ReactCurrentBatchConfig$1.transition = prevTransition;
7417 }
7418 }, [value]);
7419 return prevValue;
7420 }
7421
7422 function startTransition(setPending, callback) {
7423 var priorityLevel = getCurrentPriorityLevel();
7424
7425 {
7426 runWithPriority(priorityLevel < UserBlockingPriority$1 ? UserBlockingPriority$1 : priorityLevel, function () {
7427 setPending(true);
7428 });
7429 runWithPriority(priorityLevel > NormalPriority$1 ? NormalPriority$1 : priorityLevel, function () {
7430 var prevTransition = ReactCurrentBatchConfig$1.transition;
7431 ReactCurrentBatchConfig$1.transition = 1;
7432
7433 try {
7434 setPending(false);
7435 callback();
7436 } finally {
7437 ReactCurrentBatchConfig$1.transition = prevTransition;
7438 }
7439 });
7440 }
7441 }
7442
7443 function mountTransition() {
7444 var _mountState2 = mountState(false),
7445 isPending = _mountState2[0],
7446 setPending = _mountState2[1]; // The `start` method can be stored on a ref, since `setPending`
7447 // never changes.
7448
7449
7450 var start = startTransition.bind(null, setPending);
7451 mountRef(start);
7452 return [start, isPending];
7453 }
7454
7455 function updateTransition() {
7456 var _updateState2 = updateState(),
7457 isPending = _updateState2[0];
7458
7459 var startRef = updateRef();
7460 var start = startRef.current;
7461 return [start, isPending];
7462 }
7463
7464 function rerenderTransition() {
7465 var _rerenderState2 = rerenderState(),
7466 isPending = _rerenderState2[0];
7467
7468 var startRef = updateRef();
7469 var start = startRef.current;
7470 return [start, isPending];
7471 }
7472
7473 var isUpdatingOpaqueValueInRenderPhase = false;
7474 function getIsUpdatingOpaqueValueInRenderPhaseInDEV() {
7475 {
7476 return isUpdatingOpaqueValueInRenderPhase;
7477 }
7478 }
7479
7480 function warnOnOpaqueIdentifierAccessInDEV(fiber) {
7481 {
7482 // TODO: Should warn in effects and callbacks, too
7483 var name = getComponentName(fiber.type) || 'Unknown';
7484
7485 if (getIsRendering() && !didWarnAboutUseOpaqueIdentifier[name]) {
7486 error('The object passed back from useOpaqueIdentifier is meant to be ' + 'passed through to attributes only. Do not read the ' + 'value directly.');
7487
7488 didWarnAboutUseOpaqueIdentifier[name] = true;
7489 }
7490 }
7491 }
7492
7493 function mountOpaqueIdentifier() {
7494 var makeId = makeClientIdInDEV.bind(null, warnOnOpaqueIdentifierAccessInDEV.bind(null, currentlyRenderingFiber$1)) ;
7495
7496 {
7497 var _id = makeId();
7498
7499 mountState(_id);
7500 return _id;
7501 }
7502 }
7503
7504 function updateOpaqueIdentifier() {
7505 var id = updateState()[0];
7506 return id;
7507 }
7508
7509 function rerenderOpaqueIdentifier() {
7510 var id = rerenderState()[0];
7511 return id;
7512 }
7513
7514 function dispatchAction(fiber, queue, action) {
7515 {
7516 if (typeof arguments[3] === 'function') {
7517 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().');
7518 }
7519 }
7520
7521 var eventTime = requestEventTime();
7522 var lane = requestUpdateLane(fiber);
7523 var update = {
7524 lane: lane,
7525 action: action,
7526 eagerReducer: null,
7527 eagerState: null,
7528 next: null
7529 }; // Append the update to the end of the list.
7530
7531 var pending = queue.pending;
7532
7533 if (pending === null) {
7534 // This is the first update. Create a circular list.
7535 update.next = update;
7536 } else {
7537 update.next = pending.next;
7538 pending.next = update;
7539 }
7540
7541 queue.pending = update;
7542 var alternate = fiber.alternate;
7543
7544 if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {
7545 // This is a render phase update. Stash it in a lazily-created map of
7546 // queue -> linked list of updates. After this render pass, we'll restart
7547 // and apply the stashed updates on top of the work-in-progress hook.
7548 didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true;
7549 } else {
7550 if (fiber.lanes === NoLanes && (alternate === null || alternate.lanes === NoLanes)) {
7551 // The queue is currently empty, which means we can eagerly compute the
7552 // next state before entering the render phase. If the new state is the
7553 // same as the current state, we may be able to bail out entirely.
7554 var lastRenderedReducer = queue.lastRenderedReducer;
7555
7556 if (lastRenderedReducer !== null) {
7557 var prevDispatcher;
7558
7559 {
7560 prevDispatcher = ReactCurrentDispatcher$1.current;
7561 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
7562 }
7563
7564 try {
7565 var currentState = queue.lastRenderedState;
7566 var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute
7567 // it, on the update object. If the reducer hasn't changed by the
7568 // time we enter the render phase, then the eager state can be used
7569 // without calling the reducer again.
7570
7571 update.eagerReducer = lastRenderedReducer;
7572 update.eagerState = eagerState;
7573
7574 if (objectIs(eagerState, currentState)) {
7575 // Fast path. We can bail out without scheduling React to re-render.
7576 // It's still possible that we'll need to rebase this update later,
7577 // if the component re-renders for a different reason and by that
7578 // time the reducer has changed.
7579 return;
7580 }
7581 } catch (error) {// Suppress the error. It will throw again in the render phase.
7582 } finally {
7583 {
7584 ReactCurrentDispatcher$1.current = prevDispatcher;
7585 }
7586 }
7587 }
7588 }
7589
7590 scheduleUpdateOnFiber(fiber, lane, eventTime);
7591 }
7592 }
7593
7594 var ContextOnlyDispatcher = {
7595 readContext: readContext,
7596 useCallback: throwInvalidHookError,
7597 useContext: throwInvalidHookError,
7598 useEffect: throwInvalidHookError,
7599 useImperativeHandle: throwInvalidHookError,
7600 useLayoutEffect: throwInvalidHookError,
7601 useMemo: throwInvalidHookError,
7602 useReducer: throwInvalidHookError,
7603 useRef: throwInvalidHookError,
7604 useState: throwInvalidHookError,
7605 useDebugValue: throwInvalidHookError,
7606 useDeferredValue: throwInvalidHookError,
7607 useTransition: throwInvalidHookError,
7608 useMutableSource: throwInvalidHookError,
7609 useOpaqueIdentifier: throwInvalidHookError,
7610 unstable_isNewReconciler: enableNewReconciler
7611 };
7612 var HooksDispatcherOnMountInDEV = null;
7613 var HooksDispatcherOnMountWithHookTypesInDEV = null;
7614 var HooksDispatcherOnUpdateInDEV = null;
7615 var HooksDispatcherOnRerenderInDEV = null;
7616 var InvalidNestedHooksDispatcherOnMountInDEV = null;
7617 var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
7618 var InvalidNestedHooksDispatcherOnRerenderInDEV = null;
7619
7620 {
7621 var warnInvalidContextAccess = function () {
7622 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().');
7623 };
7624
7625 var warnInvalidHookAccess = function () {
7626 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');
7627 };
7628
7629 HooksDispatcherOnMountInDEV = {
7630 readContext: function (context, observedBits) {
7631 return readContext(context, observedBits);
7632 },
7633 useCallback: function (callback, deps) {
7634 currentHookNameInDev = 'useCallback';
7635 mountHookTypesDev();
7636 checkDepsAreArrayDev(deps);
7637 return mountCallback(callback, deps);
7638 },
7639 useContext: function (context, observedBits) {
7640 currentHookNameInDev = 'useContext';
7641 mountHookTypesDev();
7642 return readContext(context, observedBits);
7643 },
7644 useEffect: function (create, deps) {
7645 currentHookNameInDev = 'useEffect';
7646 mountHookTypesDev();
7647 checkDepsAreArrayDev(deps);
7648 return mountEffect(create, deps);
7649 },
7650 useImperativeHandle: function (ref, create, deps) {
7651 currentHookNameInDev = 'useImperativeHandle';
7652 mountHookTypesDev();
7653 checkDepsAreArrayDev(deps);
7654 return mountImperativeHandle(ref, create, deps);
7655 },
7656 useLayoutEffect: function (create, deps) {
7657 currentHookNameInDev = 'useLayoutEffect';
7658 mountHookTypesDev();
7659 checkDepsAreArrayDev(deps);
7660 return mountLayoutEffect(create, deps);
7661 },
7662 useMemo: function (create, deps) {
7663 currentHookNameInDev = 'useMemo';
7664 mountHookTypesDev();
7665 checkDepsAreArrayDev(deps);
7666 var prevDispatcher = ReactCurrentDispatcher$1.current;
7667 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
7668
7669 try {
7670 return mountMemo(create, deps);
7671 } finally {
7672 ReactCurrentDispatcher$1.current = prevDispatcher;
7673 }
7674 },
7675 useReducer: function (reducer, initialArg, init) {
7676 currentHookNameInDev = 'useReducer';
7677 mountHookTypesDev();
7678 var prevDispatcher = ReactCurrentDispatcher$1.current;
7679 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
7680
7681 try {
7682 return mountReducer(reducer, initialArg, init);
7683 } finally {
7684 ReactCurrentDispatcher$1.current = prevDispatcher;
7685 }
7686 },
7687 useRef: function (initialValue) {
7688 currentHookNameInDev = 'useRef';
7689 mountHookTypesDev();
7690 return mountRef(initialValue);
7691 },
7692 useState: function (initialState) {
7693 currentHookNameInDev = 'useState';
7694 mountHookTypesDev();
7695 var prevDispatcher = ReactCurrentDispatcher$1.current;
7696 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
7697
7698 try {
7699 return mountState(initialState);
7700 } finally {
7701 ReactCurrentDispatcher$1.current = prevDispatcher;
7702 }
7703 },
7704 useDebugValue: function (value, formatterFn) {
7705 currentHookNameInDev = 'useDebugValue';
7706 mountHookTypesDev();
7707 return mountDebugValue();
7708 },
7709 useDeferredValue: function (value) {
7710 currentHookNameInDev = 'useDeferredValue';
7711 mountHookTypesDev();
7712 return mountDeferredValue(value);
7713 },
7714 useTransition: function () {
7715 currentHookNameInDev = 'useTransition';
7716 mountHookTypesDev();
7717 return mountTransition();
7718 },
7719 useMutableSource: function (source, getSnapshot, subscribe) {
7720 currentHookNameInDev = 'useMutableSource';
7721 mountHookTypesDev();
7722 return mountMutableSource(source, getSnapshot, subscribe);
7723 },
7724 useOpaqueIdentifier: function () {
7725 currentHookNameInDev = 'useOpaqueIdentifier';
7726 mountHookTypesDev();
7727 return mountOpaqueIdentifier();
7728 },
7729 unstable_isNewReconciler: enableNewReconciler
7730 };
7731 HooksDispatcherOnMountWithHookTypesInDEV = {
7732 readContext: function (context, observedBits) {
7733 return readContext(context, observedBits);
7734 },
7735 useCallback: function (callback, deps) {
7736 currentHookNameInDev = 'useCallback';
7737 updateHookTypesDev();
7738 return mountCallback(callback, deps);
7739 },
7740 useContext: function (context, observedBits) {
7741 currentHookNameInDev = 'useContext';
7742 updateHookTypesDev();
7743 return readContext(context, observedBits);
7744 },
7745 useEffect: function (create, deps) {
7746 currentHookNameInDev = 'useEffect';
7747 updateHookTypesDev();
7748 return mountEffect(create, deps);
7749 },
7750 useImperativeHandle: function (ref, create, deps) {
7751 currentHookNameInDev = 'useImperativeHandle';
7752 updateHookTypesDev();
7753 return mountImperativeHandle(ref, create, deps);
7754 },
7755 useLayoutEffect: function (create, deps) {
7756 currentHookNameInDev = 'useLayoutEffect';
7757 updateHookTypesDev();
7758 return mountLayoutEffect(create, deps);
7759 },
7760 useMemo: function (create, deps) {
7761 currentHookNameInDev = 'useMemo';
7762 updateHookTypesDev();
7763 var prevDispatcher = ReactCurrentDispatcher$1.current;
7764 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
7765
7766 try {
7767 return mountMemo(create, deps);
7768 } finally {
7769 ReactCurrentDispatcher$1.current = prevDispatcher;
7770 }
7771 },
7772 useReducer: function (reducer, initialArg, init) {
7773 currentHookNameInDev = 'useReducer';
7774 updateHookTypesDev();
7775 var prevDispatcher = ReactCurrentDispatcher$1.current;
7776 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
7777
7778 try {
7779 return mountReducer(reducer, initialArg, init);
7780 } finally {
7781 ReactCurrentDispatcher$1.current = prevDispatcher;
7782 }
7783 },
7784 useRef: function (initialValue) {
7785 currentHookNameInDev = 'useRef';
7786 updateHookTypesDev();
7787 return mountRef(initialValue);
7788 },
7789 useState: function (initialState) {
7790 currentHookNameInDev = 'useState';
7791 updateHookTypesDev();
7792 var prevDispatcher = ReactCurrentDispatcher$1.current;
7793 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
7794
7795 try {
7796 return mountState(initialState);
7797 } finally {
7798 ReactCurrentDispatcher$1.current = prevDispatcher;
7799 }
7800 },
7801 useDebugValue: function (value, formatterFn) {
7802 currentHookNameInDev = 'useDebugValue';
7803 updateHookTypesDev();
7804 return mountDebugValue();
7805 },
7806 useDeferredValue: function (value) {
7807 currentHookNameInDev = 'useDeferredValue';
7808 updateHookTypesDev();
7809 return mountDeferredValue(value);
7810 },
7811 useTransition: function () {
7812 currentHookNameInDev = 'useTransition';
7813 updateHookTypesDev();
7814 return mountTransition();
7815 },
7816 useMutableSource: function (source, getSnapshot, subscribe) {
7817 currentHookNameInDev = 'useMutableSource';
7818 updateHookTypesDev();
7819 return mountMutableSource(source, getSnapshot, subscribe);
7820 },
7821 useOpaqueIdentifier: function () {
7822 currentHookNameInDev = 'useOpaqueIdentifier';
7823 updateHookTypesDev();
7824 return mountOpaqueIdentifier();
7825 },
7826 unstable_isNewReconciler: enableNewReconciler
7827 };
7828 HooksDispatcherOnUpdateInDEV = {
7829 readContext: function (context, observedBits) {
7830 return readContext(context, observedBits);
7831 },
7832 useCallback: function (callback, deps) {
7833 currentHookNameInDev = 'useCallback';
7834 updateHookTypesDev();
7835 return updateCallback(callback, deps);
7836 },
7837 useContext: function (context, observedBits) {
7838 currentHookNameInDev = 'useContext';
7839 updateHookTypesDev();
7840 return readContext(context, observedBits);
7841 },
7842 useEffect: function (create, deps) {
7843 currentHookNameInDev = 'useEffect';
7844 updateHookTypesDev();
7845 return updateEffect(create, deps);
7846 },
7847 useImperativeHandle: function (ref, create, deps) {
7848 currentHookNameInDev = 'useImperativeHandle';
7849 updateHookTypesDev();
7850 return updateImperativeHandle(ref, create, deps);
7851 },
7852 useLayoutEffect: function (create, deps) {
7853 currentHookNameInDev = 'useLayoutEffect';
7854 updateHookTypesDev();
7855 return updateLayoutEffect(create, deps);
7856 },
7857 useMemo: function (create, deps) {
7858 currentHookNameInDev = 'useMemo';
7859 updateHookTypesDev();
7860 var prevDispatcher = ReactCurrentDispatcher$1.current;
7861 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
7862
7863 try {
7864 return updateMemo(create, deps);
7865 } finally {
7866 ReactCurrentDispatcher$1.current = prevDispatcher;
7867 }
7868 },
7869 useReducer: function (reducer, initialArg, init) {
7870 currentHookNameInDev = 'useReducer';
7871 updateHookTypesDev();
7872 var prevDispatcher = ReactCurrentDispatcher$1.current;
7873 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
7874
7875 try {
7876 return updateReducer(reducer, initialArg, init);
7877 } finally {
7878 ReactCurrentDispatcher$1.current = prevDispatcher;
7879 }
7880 },
7881 useRef: function (initialValue) {
7882 currentHookNameInDev = 'useRef';
7883 updateHookTypesDev();
7884 return updateRef();
7885 },
7886 useState: function (initialState) {
7887 currentHookNameInDev = 'useState';
7888 updateHookTypesDev();
7889 var prevDispatcher = ReactCurrentDispatcher$1.current;
7890 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
7891
7892 try {
7893 return updateState(initialState);
7894 } finally {
7895 ReactCurrentDispatcher$1.current = prevDispatcher;
7896 }
7897 },
7898 useDebugValue: function (value, formatterFn) {
7899 currentHookNameInDev = 'useDebugValue';
7900 updateHookTypesDev();
7901 return updateDebugValue();
7902 },
7903 useDeferredValue: function (value) {
7904 currentHookNameInDev = 'useDeferredValue';
7905 updateHookTypesDev();
7906 return updateDeferredValue(value);
7907 },
7908 useTransition: function () {
7909 currentHookNameInDev = 'useTransition';
7910 updateHookTypesDev();
7911 return updateTransition();
7912 },
7913 useMutableSource: function (source, getSnapshot, subscribe) {
7914 currentHookNameInDev = 'useMutableSource';
7915 updateHookTypesDev();
7916 return updateMutableSource(source, getSnapshot, subscribe);
7917 },
7918 useOpaqueIdentifier: function () {
7919 currentHookNameInDev = 'useOpaqueIdentifier';
7920 updateHookTypesDev();
7921 return updateOpaqueIdentifier();
7922 },
7923 unstable_isNewReconciler: enableNewReconciler
7924 };
7925 HooksDispatcherOnRerenderInDEV = {
7926 readContext: function (context, observedBits) {
7927 return readContext(context, observedBits);
7928 },
7929 useCallback: function (callback, deps) {
7930 currentHookNameInDev = 'useCallback';
7931 updateHookTypesDev();
7932 return updateCallback(callback, deps);
7933 },
7934 useContext: function (context, observedBits) {
7935 currentHookNameInDev = 'useContext';
7936 updateHookTypesDev();
7937 return readContext(context, observedBits);
7938 },
7939 useEffect: function (create, deps) {
7940 currentHookNameInDev = 'useEffect';
7941 updateHookTypesDev();
7942 return updateEffect(create, deps);
7943 },
7944 useImperativeHandle: function (ref, create, deps) {
7945 currentHookNameInDev = 'useImperativeHandle';
7946 updateHookTypesDev();
7947 return updateImperativeHandle(ref, create, deps);
7948 },
7949 useLayoutEffect: function (create, deps) {
7950 currentHookNameInDev = 'useLayoutEffect';
7951 updateHookTypesDev();
7952 return updateLayoutEffect(create, deps);
7953 },
7954 useMemo: function (create, deps) {
7955 currentHookNameInDev = 'useMemo';
7956 updateHookTypesDev();
7957 var prevDispatcher = ReactCurrentDispatcher$1.current;
7958 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
7959
7960 try {
7961 return updateMemo(create, deps);
7962 } finally {
7963 ReactCurrentDispatcher$1.current = prevDispatcher;
7964 }
7965 },
7966 useReducer: function (reducer, initialArg, init) {
7967 currentHookNameInDev = 'useReducer';
7968 updateHookTypesDev();
7969 var prevDispatcher = ReactCurrentDispatcher$1.current;
7970 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
7971
7972 try {
7973 return rerenderReducer(reducer, initialArg, init);
7974 } finally {
7975 ReactCurrentDispatcher$1.current = prevDispatcher;
7976 }
7977 },
7978 useRef: function (initialValue) {
7979 currentHookNameInDev = 'useRef';
7980 updateHookTypesDev();
7981 return updateRef();
7982 },
7983 useState: function (initialState) {
7984 currentHookNameInDev = 'useState';
7985 updateHookTypesDev();
7986 var prevDispatcher = ReactCurrentDispatcher$1.current;
7987 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
7988
7989 try {
7990 return rerenderState(initialState);
7991 } finally {
7992 ReactCurrentDispatcher$1.current = prevDispatcher;
7993 }
7994 },
7995 useDebugValue: function (value, formatterFn) {
7996 currentHookNameInDev = 'useDebugValue';
7997 updateHookTypesDev();
7998 return updateDebugValue();
7999 },
8000 useDeferredValue: function (value) {
8001 currentHookNameInDev = 'useDeferredValue';
8002 updateHookTypesDev();
8003 return rerenderDeferredValue(value);
8004 },
8005 useTransition: function () {
8006 currentHookNameInDev = 'useTransition';
8007 updateHookTypesDev();
8008 return rerenderTransition();
8009 },
8010 useMutableSource: function (source, getSnapshot, subscribe) {
8011 currentHookNameInDev = 'useMutableSource';
8012 updateHookTypesDev();
8013 return updateMutableSource(source, getSnapshot, subscribe);
8014 },
8015 useOpaqueIdentifier: function () {
8016 currentHookNameInDev = 'useOpaqueIdentifier';
8017 updateHookTypesDev();
8018 return rerenderOpaqueIdentifier();
8019 },
8020 unstable_isNewReconciler: enableNewReconciler
8021 };
8022 InvalidNestedHooksDispatcherOnMountInDEV = {
8023 readContext: function (context, observedBits) {
8024 warnInvalidContextAccess();
8025 return readContext(context, observedBits);
8026 },
8027 useCallback: function (callback, deps) {
8028 currentHookNameInDev = 'useCallback';
8029 warnInvalidHookAccess();
8030 mountHookTypesDev();
8031 return mountCallback(callback, deps);
8032 },
8033 useContext: function (context, observedBits) {
8034 currentHookNameInDev = 'useContext';
8035 warnInvalidHookAccess();
8036 mountHookTypesDev();
8037 return readContext(context, observedBits);
8038 },
8039 useEffect: function (create, deps) {
8040 currentHookNameInDev = 'useEffect';
8041 warnInvalidHookAccess();
8042 mountHookTypesDev();
8043 return mountEffect(create, deps);
8044 },
8045 useImperativeHandle: function (ref, create, deps) {
8046 currentHookNameInDev = 'useImperativeHandle';
8047 warnInvalidHookAccess();
8048 mountHookTypesDev();
8049 return mountImperativeHandle(ref, create, deps);
8050 },
8051 useLayoutEffect: function (create, deps) {
8052 currentHookNameInDev = 'useLayoutEffect';
8053 warnInvalidHookAccess();
8054 mountHookTypesDev();
8055 return mountLayoutEffect(create, deps);
8056 },
8057 useMemo: function (create, deps) {
8058 currentHookNameInDev = 'useMemo';
8059 warnInvalidHookAccess();
8060 mountHookTypesDev();
8061 var prevDispatcher = ReactCurrentDispatcher$1.current;
8062 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
8063
8064 try {
8065 return mountMemo(create, deps);
8066 } finally {
8067 ReactCurrentDispatcher$1.current = prevDispatcher;
8068 }
8069 },
8070 useReducer: function (reducer, initialArg, init) {
8071 currentHookNameInDev = 'useReducer';
8072 warnInvalidHookAccess();
8073 mountHookTypesDev();
8074 var prevDispatcher = ReactCurrentDispatcher$1.current;
8075 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
8076
8077 try {
8078 return mountReducer(reducer, initialArg, init);
8079 } finally {
8080 ReactCurrentDispatcher$1.current = prevDispatcher;
8081 }
8082 },
8083 useRef: function (initialValue) {
8084 currentHookNameInDev = 'useRef';
8085 warnInvalidHookAccess();
8086 mountHookTypesDev();
8087 return mountRef(initialValue);
8088 },
8089 useState: function (initialState) {
8090 currentHookNameInDev = 'useState';
8091 warnInvalidHookAccess();
8092 mountHookTypesDev();
8093 var prevDispatcher = ReactCurrentDispatcher$1.current;
8094 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
8095
8096 try {
8097 return mountState(initialState);
8098 } finally {
8099 ReactCurrentDispatcher$1.current = prevDispatcher;
8100 }
8101 },
8102 useDebugValue: function (value, formatterFn) {
8103 currentHookNameInDev = 'useDebugValue';
8104 warnInvalidHookAccess();
8105 mountHookTypesDev();
8106 return mountDebugValue();
8107 },
8108 useDeferredValue: function (value) {
8109 currentHookNameInDev = 'useDeferredValue';
8110 warnInvalidHookAccess();
8111 mountHookTypesDev();
8112 return mountDeferredValue(value);
8113 },
8114 useTransition: function () {
8115 currentHookNameInDev = 'useTransition';
8116 warnInvalidHookAccess();
8117 mountHookTypesDev();
8118 return mountTransition();
8119 },
8120 useMutableSource: function (source, getSnapshot, subscribe) {
8121 currentHookNameInDev = 'useMutableSource';
8122 warnInvalidHookAccess();
8123 mountHookTypesDev();
8124 return mountMutableSource(source, getSnapshot, subscribe);
8125 },
8126 useOpaqueIdentifier: function () {
8127 currentHookNameInDev = 'useOpaqueIdentifier';
8128 warnInvalidHookAccess();
8129 mountHookTypesDev();
8130 return mountOpaqueIdentifier();
8131 },
8132 unstable_isNewReconciler: enableNewReconciler
8133 };
8134 InvalidNestedHooksDispatcherOnUpdateInDEV = {
8135 readContext: function (context, observedBits) {
8136 warnInvalidContextAccess();
8137 return readContext(context, observedBits);
8138 },
8139 useCallback: function (callback, deps) {
8140 currentHookNameInDev = 'useCallback';
8141 warnInvalidHookAccess();
8142 updateHookTypesDev();
8143 return updateCallback(callback, deps);
8144 },
8145 useContext: function (context, observedBits) {
8146 currentHookNameInDev = 'useContext';
8147 warnInvalidHookAccess();
8148 updateHookTypesDev();
8149 return readContext(context, observedBits);
8150 },
8151 useEffect: function (create, deps) {
8152 currentHookNameInDev = 'useEffect';
8153 warnInvalidHookAccess();
8154 updateHookTypesDev();
8155 return updateEffect(create, deps);
8156 },
8157 useImperativeHandle: function (ref, create, deps) {
8158 currentHookNameInDev = 'useImperativeHandle';
8159 warnInvalidHookAccess();
8160 updateHookTypesDev();
8161 return updateImperativeHandle(ref, create, deps);
8162 },
8163 useLayoutEffect: function (create, deps) {
8164 currentHookNameInDev = 'useLayoutEffect';
8165 warnInvalidHookAccess();
8166 updateHookTypesDev();
8167 return updateLayoutEffect(create, deps);
8168 },
8169 useMemo: function (create, deps) {
8170 currentHookNameInDev = 'useMemo';
8171 warnInvalidHookAccess();
8172 updateHookTypesDev();
8173 var prevDispatcher = ReactCurrentDispatcher$1.current;
8174 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
8175
8176 try {
8177 return updateMemo(create, deps);
8178 } finally {
8179 ReactCurrentDispatcher$1.current = prevDispatcher;
8180 }
8181 },
8182 useReducer: function (reducer, initialArg, init) {
8183 currentHookNameInDev = 'useReducer';
8184 warnInvalidHookAccess();
8185 updateHookTypesDev();
8186 var prevDispatcher = ReactCurrentDispatcher$1.current;
8187 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
8188
8189 try {
8190 return updateReducer(reducer, initialArg, init);
8191 } finally {
8192 ReactCurrentDispatcher$1.current = prevDispatcher;
8193 }
8194 },
8195 useRef: function (initialValue) {
8196 currentHookNameInDev = 'useRef';
8197 warnInvalidHookAccess();
8198 updateHookTypesDev();
8199 return updateRef();
8200 },
8201 useState: function (initialState) {
8202 currentHookNameInDev = 'useState';
8203 warnInvalidHookAccess();
8204 updateHookTypesDev();
8205 var prevDispatcher = ReactCurrentDispatcher$1.current;
8206 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
8207
8208 try {
8209 return updateState(initialState);
8210 } finally {
8211 ReactCurrentDispatcher$1.current = prevDispatcher;
8212 }
8213 },
8214 useDebugValue: function (value, formatterFn) {
8215 currentHookNameInDev = 'useDebugValue';
8216 warnInvalidHookAccess();
8217 updateHookTypesDev();
8218 return updateDebugValue();
8219 },
8220 useDeferredValue: function (value) {
8221 currentHookNameInDev = 'useDeferredValue';
8222 warnInvalidHookAccess();
8223 updateHookTypesDev();
8224 return updateDeferredValue(value);
8225 },
8226 useTransition: function () {
8227 currentHookNameInDev = 'useTransition';
8228 warnInvalidHookAccess();
8229 updateHookTypesDev();
8230 return updateTransition();
8231 },
8232 useMutableSource: function (source, getSnapshot, subscribe) {
8233 currentHookNameInDev = 'useMutableSource';
8234 warnInvalidHookAccess();
8235 updateHookTypesDev();
8236 return updateMutableSource(source, getSnapshot, subscribe);
8237 },
8238 useOpaqueIdentifier: function () {
8239 currentHookNameInDev = 'useOpaqueIdentifier';
8240 warnInvalidHookAccess();
8241 updateHookTypesDev();
8242 return updateOpaqueIdentifier();
8243 },
8244 unstable_isNewReconciler: enableNewReconciler
8245 };
8246 InvalidNestedHooksDispatcherOnRerenderInDEV = {
8247 readContext: function (context, observedBits) {
8248 warnInvalidContextAccess();
8249 return readContext(context, observedBits);
8250 },
8251 useCallback: function (callback, deps) {
8252 currentHookNameInDev = 'useCallback';
8253 warnInvalidHookAccess();
8254 updateHookTypesDev();
8255 return updateCallback(callback, deps);
8256 },
8257 useContext: function (context, observedBits) {
8258 currentHookNameInDev = 'useContext';
8259 warnInvalidHookAccess();
8260 updateHookTypesDev();
8261 return readContext(context, observedBits);
8262 },
8263 useEffect: function (create, deps) {
8264 currentHookNameInDev = 'useEffect';
8265 warnInvalidHookAccess();
8266 updateHookTypesDev();
8267 return updateEffect(create, deps);
8268 },
8269 useImperativeHandle: function (ref, create, deps) {
8270 currentHookNameInDev = 'useImperativeHandle';
8271 warnInvalidHookAccess();
8272 updateHookTypesDev();
8273 return updateImperativeHandle(ref, create, deps);
8274 },
8275 useLayoutEffect: function (create, deps) {
8276 currentHookNameInDev = 'useLayoutEffect';
8277 warnInvalidHookAccess();
8278 updateHookTypesDev();
8279 return updateLayoutEffect(create, deps);
8280 },
8281 useMemo: function (create, deps) {
8282 currentHookNameInDev = 'useMemo';
8283 warnInvalidHookAccess();
8284 updateHookTypesDev();
8285 var prevDispatcher = ReactCurrentDispatcher$1.current;
8286 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
8287
8288 try {
8289 return updateMemo(create, deps);
8290 } finally {
8291 ReactCurrentDispatcher$1.current = prevDispatcher;
8292 }
8293 },
8294 useReducer: function (reducer, initialArg, init) {
8295 currentHookNameInDev = 'useReducer';
8296 warnInvalidHookAccess();
8297 updateHookTypesDev();
8298 var prevDispatcher = ReactCurrentDispatcher$1.current;
8299 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
8300
8301 try {
8302 return rerenderReducer(reducer, initialArg, init);
8303 } finally {
8304 ReactCurrentDispatcher$1.current = prevDispatcher;
8305 }
8306 },
8307 useRef: function (initialValue) {
8308 currentHookNameInDev = 'useRef';
8309 warnInvalidHookAccess();
8310 updateHookTypesDev();
8311 return updateRef();
8312 },
8313 useState: function (initialState) {
8314 currentHookNameInDev = 'useState';
8315 warnInvalidHookAccess();
8316 updateHookTypesDev();
8317 var prevDispatcher = ReactCurrentDispatcher$1.current;
8318 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
8319
8320 try {
8321 return rerenderState(initialState);
8322 } finally {
8323 ReactCurrentDispatcher$1.current = prevDispatcher;
8324 }
8325 },
8326 useDebugValue: function (value, formatterFn) {
8327 currentHookNameInDev = 'useDebugValue';
8328 warnInvalidHookAccess();
8329 updateHookTypesDev();
8330 return updateDebugValue();
8331 },
8332 useDeferredValue: function (value) {
8333 currentHookNameInDev = 'useDeferredValue';
8334 warnInvalidHookAccess();
8335 updateHookTypesDev();
8336 return rerenderDeferredValue(value);
8337 },
8338 useTransition: function () {
8339 currentHookNameInDev = 'useTransition';
8340 warnInvalidHookAccess();
8341 updateHookTypesDev();
8342 return rerenderTransition();
8343 },
8344 useMutableSource: function (source, getSnapshot, subscribe) {
8345 currentHookNameInDev = 'useMutableSource';
8346 warnInvalidHookAccess();
8347 updateHookTypesDev();
8348 return updateMutableSource(source, getSnapshot, subscribe);
8349 },
8350 useOpaqueIdentifier: function () {
8351 currentHookNameInDev = 'useOpaqueIdentifier';
8352 warnInvalidHookAccess();
8353 updateHookTypesDev();
8354 return rerenderOpaqueIdentifier();
8355 },
8356 unstable_isNewReconciler: enableNewReconciler
8357 };
8358 }
8359
8360 var now$1 = unstable_now;
8361 var commitTime = 0;
8362 var profilerStartTime = -1;
8363
8364 function getCommitTime() {
8365 return commitTime;
8366 }
8367
8368 function recordCommitTime() {
8369
8370 commitTime = now$1();
8371 }
8372
8373 function startProfilerTimer(fiber) {
8374
8375 profilerStartTime = now$1();
8376
8377 if (fiber.actualStartTime < 0) {
8378 fiber.actualStartTime = now$1();
8379 }
8380 }
8381
8382 function stopProfilerTimerIfRunning(fiber) {
8383
8384 profilerStartTime = -1;
8385 }
8386
8387 function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
8388
8389 if (profilerStartTime >= 0) {
8390 var elapsedTime = now$1() - profilerStartTime;
8391 fiber.actualDuration += elapsedTime;
8392
8393 if (overrideBaseTime) {
8394 fiber.selfBaseDuration = elapsedTime;
8395 }
8396
8397 profilerStartTime = -1;
8398 }
8399 }
8400
8401 function transferActualDuration(fiber) {
8402 // Transfer time spent rendering these children so we don't lose it
8403 // after we rerender. This is used as a helper in special cases
8404 // where we should count the work of multiple passes.
8405 var child = fiber.child;
8406
8407 while (child) {
8408 fiber.actualDuration += child.actualDuration;
8409 child = child.sibling;
8410 }
8411 }
8412
8413 var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
8414 var didReceiveUpdate = false;
8415 var didWarnAboutBadClass;
8416 var didWarnAboutModulePatternComponent;
8417 var didWarnAboutContextTypeOnFunctionComponent;
8418 var didWarnAboutGetDerivedStateOnFunctionComponent;
8419 var didWarnAboutFunctionRefs;
8420 var didWarnAboutReassigningProps;
8421 var didWarnAboutRevealOrder;
8422 var didWarnAboutTailOptions;
8423
8424 {
8425 didWarnAboutBadClass = {};
8426 didWarnAboutModulePatternComponent = {};
8427 didWarnAboutContextTypeOnFunctionComponent = {};
8428 didWarnAboutGetDerivedStateOnFunctionComponent = {};
8429 didWarnAboutFunctionRefs = {};
8430 didWarnAboutReassigningProps = false;
8431 didWarnAboutRevealOrder = {};
8432 didWarnAboutTailOptions = {};
8433 }
8434
8435 function reconcileChildren(current, workInProgress, nextChildren, renderLanes) {
8436 if (current === null) {
8437 // If this is a fresh new component that hasn't been rendered yet, we
8438 // won't update its child set by applying minimal side-effects. Instead,
8439 // we will add them all to the child before it gets rendered. That means
8440 // we can optimize this reconciliation pass by not tracking side-effects.
8441 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderLanes);
8442 } else {
8443 // If the current child is the same as the work in progress, it means that
8444 // we haven't yet started any work on these children. Therefore, we use
8445 // the clone algorithm to create a copy of all the current children.
8446 // If we had any progressed work already, that is invalid at this point so
8447 // let's throw it out.
8448 workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren, renderLanes);
8449 }
8450 }
8451
8452 function forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes) {
8453 // This function is fork of reconcileChildren. It's used in cases where we
8454 // want to reconcile without matching against the existing set. This has the
8455 // effect of all current children being unmounted; even if the type and key
8456 // are the same, the old child is unmounted and a new child is created.
8457 //
8458 // To do this, we're going to go through the reconcile algorithm twice. In
8459 // the first pass, we schedule a deletion for all the current children by
8460 // passing null.
8461 workInProgress.child = reconcileChildFibers(workInProgress, current.child, null, renderLanes); // In the second pass, we mount the new children. The trick here is that we
8462 // pass null in place of where we usually pass the current child set. This has
8463 // the effect of remounting all children regardless of whether their
8464 // identities match.
8465
8466 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes);
8467 }
8468
8469 function updateForwardRef(current, workInProgress, Component, nextProps, renderLanes) {
8470 // TODO: current can be non-null here even if the component
8471 // hasn't yet mounted. This happens after the first render suspends.
8472 // We'll need to figure out if this is fine or can cause issues.
8473 {
8474 if (workInProgress.type !== workInProgress.elementType) {
8475 // Lazy component props can't be validated in createElement
8476 // because they're only guaranteed to be resolved here.
8477 var innerPropTypes = Component.propTypes;
8478
8479 if (innerPropTypes) {
8480 checkPropTypes(innerPropTypes, nextProps, // Resolved props
8481 'prop', getComponentName(Component));
8482 }
8483 }
8484 }
8485
8486 var render = Component.render;
8487 var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent
8488
8489 var nextChildren;
8490 prepareToReadContext(workInProgress, renderLanes);
8491
8492 {
8493 ReactCurrentOwner$1.current = workInProgress;
8494 setIsRendering(true);
8495 nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes);
8496
8497 if ( workInProgress.mode & StrictMode) {
8498 disableLogs();
8499
8500 try {
8501 nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes);
8502 } finally {
8503 reenableLogs();
8504 }
8505 }
8506
8507 setIsRendering(false);
8508 }
8509
8510 if (current !== null && !didReceiveUpdate) {
8511 bailoutHooks(current, workInProgress, renderLanes);
8512 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
8513 } // React DevTools reads this flag.
8514
8515
8516 workInProgress.flags |= PerformedWork;
8517 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
8518 return workInProgress.child;
8519 }
8520
8521 function updateMemoComponent(current, workInProgress, Component, nextProps, updateLanes, renderLanes) {
8522 if (current === null) {
8523 var type = Component.type;
8524
8525 if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either.
8526 Component.defaultProps === undefined) {
8527 var resolvedType = type;
8528
8529 {
8530 resolvedType = resolveFunctionForHotReloading(type);
8531 } // If this is a plain function component without default props,
8532 // and with only the default shallow comparison, we upgrade it
8533 // to a SimpleMemoComponent to allow fast path updates.
8534
8535
8536 workInProgress.tag = SimpleMemoComponent;
8537 workInProgress.type = resolvedType;
8538
8539 {
8540 validateFunctionComponentInDev(workInProgress, type);
8541 }
8542
8543 return updateSimpleMemoComponent(current, workInProgress, resolvedType, nextProps, updateLanes, renderLanes);
8544 }
8545
8546 {
8547 var innerPropTypes = type.propTypes;
8548
8549 if (innerPropTypes) {
8550 // Inner memo component props aren't currently validated in createElement.
8551 // We could move it there, but we'd still need this for lazy code path.
8552 checkPropTypes(innerPropTypes, nextProps, // Resolved props
8553 'prop', getComponentName(type));
8554 }
8555 }
8556
8557 var child = createFiberFromTypeAndProps(Component.type, null, nextProps, workInProgress, workInProgress.mode, renderLanes);
8558 child.ref = workInProgress.ref;
8559 child.return = workInProgress;
8560 workInProgress.child = child;
8561 return child;
8562 }
8563
8564 {
8565 var _type = Component.type;
8566 var _innerPropTypes = _type.propTypes;
8567
8568 if (_innerPropTypes) {
8569 // Inner memo component props aren't currently validated in createElement.
8570 // We could move it there, but we'd still need this for lazy code path.
8571 checkPropTypes(_innerPropTypes, nextProps, // Resolved props
8572 'prop', getComponentName(_type));
8573 }
8574 }
8575
8576 var currentChild = current.child; // This is always exactly one child
8577
8578 if (!includesSomeLane(updateLanes, renderLanes)) {
8579 // This will be the props with resolved defaultProps,
8580 // unlike current.memoizedProps which will be the unresolved ones.
8581 var prevProps = currentChild.memoizedProps; // Default to shallow comparison
8582
8583 var compare = Component.compare;
8584 compare = compare !== null ? compare : shallowEqual;
8585
8586 if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) {
8587 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
8588 }
8589 } // React DevTools reads this flag.
8590
8591
8592 workInProgress.flags |= PerformedWork;
8593 var newChild = createWorkInProgress(currentChild, nextProps);
8594 newChild.ref = workInProgress.ref;
8595 newChild.return = workInProgress;
8596 workInProgress.child = newChild;
8597 return newChild;
8598 }
8599
8600 function updateSimpleMemoComponent(current, workInProgress, Component, nextProps, updateLanes, renderLanes) {
8601 // TODO: current can be non-null here even if the component
8602 // hasn't yet mounted. This happens when the inner render suspends.
8603 // We'll need to figure out if this is fine or can cause issues.
8604 {
8605 if (workInProgress.type !== workInProgress.elementType) {
8606 // Lazy component props can't be validated in createElement
8607 // because they're only guaranteed to be resolved here.
8608 var outerMemoType = workInProgress.elementType;
8609
8610 if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
8611 // We warn when you define propTypes on lazy()
8612 // so let's just skip over it to find memo() outer wrapper.
8613 // Inner props for memo are validated later.
8614 var lazyComponent = outerMemoType;
8615 var payload = lazyComponent._payload;
8616 var init = lazyComponent._init;
8617
8618 try {
8619 outerMemoType = init(payload);
8620 } catch (x) {
8621 outerMemoType = null;
8622 } // Inner propTypes will be validated in the function component path.
8623
8624
8625 var outerPropTypes = outerMemoType && outerMemoType.propTypes;
8626
8627 if (outerPropTypes) {
8628 checkPropTypes(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
8629 'prop', getComponentName(outerMemoType));
8630 }
8631 }
8632 }
8633 }
8634
8635 if (current !== null) {
8636 var prevProps = current.memoizedProps;
8637
8638 if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload.
8639 workInProgress.type === current.type )) {
8640 didReceiveUpdate = false;
8641
8642 if (!includesSomeLane(renderLanes, updateLanes)) {
8643 // The pending lanes were cleared at the beginning of beginWork. We're
8644 // about to bail out, but there might be other lanes that weren't
8645 // included in the current render. Usually, the priority level of the
8646 // remaining updates is accumlated during the evaluation of the
8647 // component (i.e. when processing the update queue). But since since
8648 // we're bailing out early *without* evaluating the component, we need
8649 // to account for it here, too. Reset to the value of the current fiber.
8650 // NOTE: This only applies to SimpleMemoComponent, not MemoComponent,
8651 // because a MemoComponent fiber does not have hooks or an update queue;
8652 // rather, it wraps around an inner component, which may or may not
8653 // contains hooks.
8654 // TODO: Move the reset at in beginWork out of the common path so that
8655 // this is no longer necessary.
8656 workInProgress.lanes = current.lanes;
8657 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
8658 } else if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
8659 // This is a special case that only exists for legacy mode.
8660 // See https://github.com/facebook/react/pull/19216.
8661 didReceiveUpdate = true;
8662 }
8663 }
8664 }
8665
8666 return updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes);
8667 }
8668
8669 function updateOffscreenComponent(current, workInProgress, renderLanes) {
8670 var nextProps = workInProgress.pendingProps;
8671 var nextChildren = nextProps.children;
8672 var prevState = current !== null ? current.memoizedState : null;
8673
8674 if (nextProps.mode === 'hidden' || nextProps.mode === 'unstable-defer-without-hiding') {
8675 if ((workInProgress.mode & ConcurrentMode) === NoMode) {
8676 // In legacy sync mode, don't defer the subtree. Render it now.
8677 // TODO: Figure out what we should do in Blocking mode.
8678 var nextState = {
8679 baseLanes: NoLanes
8680 };
8681 workInProgress.memoizedState = nextState;
8682 pushRenderLanes(workInProgress, renderLanes);
8683 } else if (!includesSomeLane(renderLanes, OffscreenLane)) {
8684 var nextBaseLanes;
8685
8686 if (prevState !== null) {
8687 var prevBaseLanes = prevState.baseLanes;
8688 nextBaseLanes = mergeLanes(prevBaseLanes, renderLanes);
8689 } else {
8690 nextBaseLanes = renderLanes;
8691 } // Schedule this fiber to re-render at offscreen priority. Then bailout.
8692
8693
8694 {
8695 markSpawnedWork(OffscreenLane);
8696 }
8697
8698 workInProgress.lanes = workInProgress.childLanes = laneToLanes(OffscreenLane);
8699 var _nextState = {
8700 baseLanes: nextBaseLanes
8701 };
8702 workInProgress.memoizedState = _nextState; // We're about to bail out, but we need to push this to the stack anyway
8703 // to avoid a push/pop misalignment.
8704
8705 pushRenderLanes(workInProgress, nextBaseLanes);
8706 return null;
8707 } else {
8708 // Rendering at offscreen, so we can clear the base lanes.
8709 var _nextState2 = {
8710 baseLanes: NoLanes
8711 };
8712 workInProgress.memoizedState = _nextState2; // Push the lanes that were skipped when we bailed out.
8713
8714 var subtreeRenderLanes = prevState !== null ? prevState.baseLanes : renderLanes;
8715 pushRenderLanes(workInProgress, subtreeRenderLanes);
8716 }
8717 } else {
8718 var _subtreeRenderLanes;
8719
8720 if (prevState !== null) {
8721 _subtreeRenderLanes = mergeLanes(prevState.baseLanes, renderLanes); // Since we're not hidden anymore, reset the state
8722
8723 workInProgress.memoizedState = null;
8724 } else {
8725 // We weren't previously hidden, and we still aren't, so there's nothing
8726 // special to do. Need to push to the stack regardless, though, to avoid
8727 // a push/pop misalignment.
8728 _subtreeRenderLanes = renderLanes;
8729 }
8730
8731 pushRenderLanes(workInProgress, _subtreeRenderLanes);
8732 }
8733
8734 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
8735 return workInProgress.child;
8736 } // Note: These happen to have identical begin phases, for now. We shouldn't hold
8737 // ourselves to this constraint, though. If the behavior diverges, we should
8738 // fork the function.
8739
8740
8741 var updateLegacyHiddenComponent = updateOffscreenComponent;
8742
8743 function updateFragment(current, workInProgress, renderLanes) {
8744 var nextChildren = workInProgress.pendingProps;
8745 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
8746 return workInProgress.child;
8747 }
8748
8749 function updateMode(current, workInProgress, renderLanes) {
8750 var nextChildren = workInProgress.pendingProps.children;
8751 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
8752 return workInProgress.child;
8753 }
8754
8755 function updateProfiler(current, workInProgress, renderLanes) {
8756 {
8757 workInProgress.flags |= Update; // Reset effect durations for the next eventual effect phase.
8758 // These are reset during render to allow the DevTools commit hook a chance to read them,
8759
8760 var stateNode = workInProgress.stateNode;
8761 stateNode.effectDuration = 0;
8762 stateNode.passiveEffectDuration = 0;
8763 }
8764
8765 var nextProps = workInProgress.pendingProps;
8766 var nextChildren = nextProps.children;
8767 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
8768 return workInProgress.child;
8769 }
8770
8771 function markRef(current, workInProgress) {
8772 var ref = workInProgress.ref;
8773
8774 if (current === null && ref !== null || current !== null && current.ref !== ref) {
8775 // Schedule a Ref effect
8776 workInProgress.flags |= Ref;
8777 }
8778 }
8779
8780 function updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes) {
8781 {
8782 if (workInProgress.type !== workInProgress.elementType) {
8783 // Lazy component props can't be validated in createElement
8784 // because they're only guaranteed to be resolved here.
8785 var innerPropTypes = Component.propTypes;
8786
8787 if (innerPropTypes) {
8788 checkPropTypes(innerPropTypes, nextProps, // Resolved props
8789 'prop', getComponentName(Component));
8790 }
8791 }
8792 }
8793
8794 var context;
8795
8796 {
8797 var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
8798 context = getMaskedContext(workInProgress, unmaskedContext);
8799 }
8800
8801 var nextChildren;
8802 prepareToReadContext(workInProgress, renderLanes);
8803
8804 {
8805 ReactCurrentOwner$1.current = workInProgress;
8806 setIsRendering(true);
8807 nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes);
8808
8809 if ( workInProgress.mode & StrictMode) {
8810 disableLogs();
8811
8812 try {
8813 nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes);
8814 } finally {
8815 reenableLogs();
8816 }
8817 }
8818
8819 setIsRendering(false);
8820 }
8821
8822 if (current !== null && !didReceiveUpdate) {
8823 bailoutHooks(current, workInProgress, renderLanes);
8824 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
8825 } // React DevTools reads this flag.
8826
8827
8828 workInProgress.flags |= PerformedWork;
8829 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
8830 return workInProgress.child;
8831 }
8832
8833 function updateClassComponent(current, workInProgress, Component, nextProps, renderLanes) {
8834 {
8835 if (workInProgress.type !== workInProgress.elementType) {
8836 // Lazy component props can't be validated in createElement
8837 // because they're only guaranteed to be resolved here.
8838 var innerPropTypes = Component.propTypes;
8839
8840 if (innerPropTypes) {
8841 checkPropTypes(innerPropTypes, nextProps, // Resolved props
8842 'prop', getComponentName(Component));
8843 }
8844 }
8845 } // Push context providers early to prevent context stack mismatches.
8846 // During mounting we don't know the child context yet as the instance doesn't exist.
8847 // We will invalidate the child context in finishClassComponent() right after rendering.
8848
8849
8850 var hasContext;
8851
8852 if (isContextProvider(Component)) {
8853 hasContext = true;
8854 pushContextProvider(workInProgress);
8855 } else {
8856 hasContext = false;
8857 }
8858
8859 prepareToReadContext(workInProgress, renderLanes);
8860 var instance = workInProgress.stateNode;
8861 var shouldUpdate;
8862
8863 if (instance === null) {
8864 if (current !== null) {
8865 // A class component without an instance only mounts if it suspended
8866 // inside a non-concurrent tree, in an inconsistent state. We want to
8867 // treat it like a new mount, even though an empty version of it already
8868 // committed. Disconnect the alternate pointers.
8869 current.alternate = null;
8870 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
8871
8872 workInProgress.flags |= Placement;
8873 } // In the initial pass we might need to construct the instance.
8874
8875
8876 constructClassInstance(workInProgress, Component, nextProps);
8877 mountClassInstance(workInProgress, Component, nextProps, renderLanes);
8878 shouldUpdate = true;
8879 } else if (current === null) {
8880 // In a resume, we'll already have an instance we can reuse.
8881 shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderLanes);
8882 } else {
8883 shouldUpdate = updateClassInstance(current, workInProgress, Component, nextProps, renderLanes);
8884 }
8885
8886 var nextUnitOfWork = finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes);
8887
8888 {
8889 var inst = workInProgress.stateNode;
8890
8891 if (shouldUpdate && inst.props !== nextProps) {
8892 if (!didWarnAboutReassigningProps) {
8893 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');
8894 }
8895
8896 didWarnAboutReassigningProps = true;
8897 }
8898 }
8899
8900 return nextUnitOfWork;
8901 }
8902
8903 function finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes) {
8904 // Refs should update even if shouldComponentUpdate returns false
8905 markRef(current, workInProgress);
8906 var didCaptureError = (workInProgress.flags & DidCapture) !== NoFlags;
8907
8908 if (!shouldUpdate && !didCaptureError) {
8909 // Context providers should defer to sCU for rendering
8910 if (hasContext) {
8911 invalidateContextProvider(workInProgress, Component, false);
8912 }
8913
8914 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
8915 }
8916
8917 var instance = workInProgress.stateNode; // Rerender
8918
8919 ReactCurrentOwner$1.current = workInProgress;
8920 var nextChildren;
8921
8922 if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
8923 // If we captured an error, but getDerivedStateFromError is not defined,
8924 // unmount all the children. componentDidCatch will schedule an update to
8925 // re-render a fallback. This is temporary until we migrate everyone to
8926 // the new API.
8927 // TODO: Warn in a future release.
8928 nextChildren = null;
8929
8930 {
8931 stopProfilerTimerIfRunning();
8932 }
8933 } else {
8934 {
8935 setIsRendering(true);
8936 nextChildren = instance.render();
8937
8938 if ( workInProgress.mode & StrictMode) {
8939 disableLogs();
8940
8941 try {
8942 instance.render();
8943 } finally {
8944 reenableLogs();
8945 }
8946 }
8947
8948 setIsRendering(false);
8949 }
8950 } // React DevTools reads this flag.
8951
8952
8953 workInProgress.flags |= PerformedWork;
8954
8955 if (current !== null && didCaptureError) {
8956 // If we're recovering from an error, reconcile without reusing any of
8957 // the existing children. Conceptually, the normal children and the children
8958 // that are shown on error are two different sets, so we shouldn't reuse
8959 // normal children even if their identities match.
8960 forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes);
8961 } else {
8962 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
8963 } // Memoize state using the values we just used to render.
8964 // TODO: Restructure so we never read values from the instance.
8965
8966
8967 workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it.
8968
8969 if (hasContext) {
8970 invalidateContextProvider(workInProgress, Component, true);
8971 }
8972
8973 return workInProgress.child;
8974 }
8975
8976 function pushHostRootContext(workInProgress) {
8977 var root = workInProgress.stateNode;
8978
8979 if (root.pendingContext) {
8980 pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
8981 } else if (root.context) {
8982 // Should always be set
8983 pushTopLevelContextObject(workInProgress, root.context, false);
8984 }
8985
8986 pushHostContainer(workInProgress, root.containerInfo);
8987 }
8988
8989 function updateHostRoot(current, workInProgress, renderLanes) {
8990 pushHostRootContext(workInProgress);
8991 var updateQueue = workInProgress.updateQueue;
8992
8993 if (!(current !== null && updateQueue !== null)) {
8994 {
8995 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." );
8996 }
8997 }
8998
8999 var nextProps = workInProgress.pendingProps;
9000 var prevState = workInProgress.memoizedState;
9001 var prevChildren = prevState !== null ? prevState.element : null;
9002 cloneUpdateQueue(current, workInProgress);
9003 processUpdateQueue(workInProgress, nextProps, null, renderLanes);
9004 var nextState = workInProgress.memoizedState; // Caution: React DevTools currently depends on this property
9005 // being called "element".
9006
9007 var nextChildren = nextState.element;
9008
9009 if (nextChildren === prevChildren) {
9010 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
9011 }
9012
9013 var root = workInProgress.stateNode;
9014
9015 if (root.hydrate && enterHydrationState()) {
9016
9017 var child = mountChildFibers(workInProgress, null, nextChildren, renderLanes);
9018 workInProgress.child = child;
9019 var node = child;
9020
9021 while (node) {
9022 // Mark each child as hydrating. This is a fast path to know whether this
9023 // tree is part of a hydrating tree. This is used to determine if a child
9024 // node has fully mounted yet, and for scheduling event replaying.
9025 // Conceptually this is similar to Placement in that a new subtree is
9026 // inserted into the React tree here. It just happens to not need DOM
9027 // mutations because it already exists.
9028 node.flags = node.flags & ~Placement | Hydrating;
9029 node = node.sibling;
9030 }
9031 } else {
9032 // Otherwise reset hydration state in case we aborted and resumed another
9033 // root.
9034 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
9035 }
9036
9037 return workInProgress.child;
9038 }
9039
9040 function updateHostComponent(current, workInProgress, renderLanes) {
9041 pushHostContext(workInProgress);
9042
9043 var type = workInProgress.type;
9044 var nextProps = workInProgress.pendingProps;
9045 var prevProps = current !== null ? current.memoizedProps : null;
9046 var nextChildren = nextProps.children;
9047 var isDirectTextChild = shouldSetTextContent(type, nextProps);
9048
9049 if (isDirectTextChild) {
9050 // We special case a direct text child of a host node. This is a common
9051 // case. We won't handle it as a reified child. We will instead handle
9052 // this in the host environment that also has access to this prop. That
9053 // avoids allocating another HostText fiber and traversing it.
9054 nextChildren = null;
9055 } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
9056 // If we're switching from a direct text child to a normal child, or to
9057 // empty, we need to schedule the text content to be reset.
9058 workInProgress.flags |= ContentReset;
9059 }
9060
9061 markRef(current, workInProgress);
9062 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
9063 return workInProgress.child;
9064 }
9065
9066 function updateHostText(current, workInProgress) {
9067 // immediately after.
9068
9069
9070 return null;
9071 }
9072
9073 function mountLazyComponent(_current, workInProgress, elementType, updateLanes, renderLanes) {
9074 if (_current !== null) {
9075 // A lazy component only mounts if it suspended inside a non-
9076 // concurrent tree, in an inconsistent state. We want to treat it like
9077 // a new mount, even though an empty version of it already committed.
9078 // Disconnect the alternate pointers.
9079 _current.alternate = null;
9080 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
9081
9082 workInProgress.flags |= Placement;
9083 }
9084
9085 var props = workInProgress.pendingProps;
9086 var lazyComponent = elementType;
9087 var payload = lazyComponent._payload;
9088 var init = lazyComponent._init;
9089 var Component = init(payload); // Store the unwrapped component in the type.
9090
9091 workInProgress.type = Component;
9092 var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
9093 var resolvedProps = resolveDefaultProps(Component, props);
9094 var child;
9095
9096 switch (resolvedTag) {
9097 case FunctionComponent:
9098 {
9099 {
9100 validateFunctionComponentInDev(workInProgress, Component);
9101 workInProgress.type = Component = resolveFunctionForHotReloading(Component);
9102 }
9103
9104 child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderLanes);
9105 return child;
9106 }
9107
9108 case ClassComponent:
9109 {
9110 {
9111 workInProgress.type = Component = resolveClassForHotReloading(Component);
9112 }
9113
9114 child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderLanes);
9115 return child;
9116 }
9117
9118 case ForwardRef:
9119 {
9120 {
9121 workInProgress.type = Component = resolveForwardRefForHotReloading(Component);
9122 }
9123
9124 child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderLanes);
9125 return child;
9126 }
9127
9128 case MemoComponent:
9129 {
9130 {
9131 if (workInProgress.type !== workInProgress.elementType) {
9132 var outerPropTypes = Component.propTypes;
9133
9134 if (outerPropTypes) {
9135 checkPropTypes(outerPropTypes, resolvedProps, // Resolved for outer only
9136 'prop', getComponentName(Component));
9137 }
9138 }
9139 }
9140
9141 child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
9142 updateLanes, renderLanes);
9143 return child;
9144 }
9145 }
9146
9147 var hint = '';
9148
9149 {
9150 if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
9151 hint = ' Did you wrap a component in React.lazy() more than once?';
9152 }
9153 } // This message intentionally doesn't mention ForwardRef or MemoComponent
9154 // because the fact that it's a separate type of work is an
9155 // implementation detail.
9156
9157
9158 {
9159 {
9160 throw Error( "Element type is invalid. Received a promise that resolves to: " + Component + ". Lazy element type must resolve to a class or function." + hint );
9161 }
9162 }
9163 }
9164
9165 function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderLanes) {
9166 if (_current !== null) {
9167 // An incomplete component only mounts if it suspended inside a non-
9168 // concurrent tree, in an inconsistent state. We want to treat it like
9169 // a new mount, even though an empty version of it already committed.
9170 // Disconnect the alternate pointers.
9171 _current.alternate = null;
9172 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
9173
9174 workInProgress.flags |= Placement;
9175 } // Promote the fiber to a class and try rendering again.
9176
9177
9178 workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent`
9179 // Push context providers early to prevent context stack mismatches.
9180 // During mounting we don't know the child context yet as the instance doesn't exist.
9181 // We will invalidate the child context in finishClassComponent() right after rendering.
9182
9183 var hasContext;
9184
9185 if (isContextProvider(Component)) {
9186 hasContext = true;
9187 pushContextProvider(workInProgress);
9188 } else {
9189 hasContext = false;
9190 }
9191
9192 prepareToReadContext(workInProgress, renderLanes);
9193 constructClassInstance(workInProgress, Component, nextProps);
9194 mountClassInstance(workInProgress, Component, nextProps, renderLanes);
9195 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes);
9196 }
9197
9198 function mountIndeterminateComponent(_current, workInProgress, Component, renderLanes) {
9199 if (_current !== null) {
9200 // An indeterminate component only mounts if it suspended inside a non-
9201 // concurrent tree, in an inconsistent state. We want to treat it like
9202 // a new mount, even though an empty version of it already committed.
9203 // Disconnect the alternate pointers.
9204 _current.alternate = null;
9205 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
9206
9207 workInProgress.flags |= Placement;
9208 }
9209
9210 var props = workInProgress.pendingProps;
9211 var context;
9212
9213 {
9214 var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
9215 context = getMaskedContext(workInProgress, unmaskedContext);
9216 }
9217
9218 prepareToReadContext(workInProgress, renderLanes);
9219 var value;
9220
9221 {
9222 if (Component.prototype && typeof Component.prototype.render === 'function') {
9223 var componentName = getComponentName(Component) || 'Unknown';
9224
9225 if (!didWarnAboutBadClass[componentName]) {
9226 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);
9227
9228 didWarnAboutBadClass[componentName] = true;
9229 }
9230 }
9231
9232 if (workInProgress.mode & StrictMode) {
9233 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
9234 }
9235
9236 setIsRendering(true);
9237 ReactCurrentOwner$1.current = workInProgress;
9238 value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes);
9239 setIsRendering(false);
9240 } // React DevTools reads this flag.
9241
9242
9243 workInProgress.flags |= PerformedWork;
9244
9245 {
9246 // Support for module components is deprecated and is removed behind a flag.
9247 // Whether or not it would crash later, we want to show a good message in DEV first.
9248 if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
9249 var _componentName = getComponentName(Component) || 'Unknown';
9250
9251 if (!didWarnAboutModulePatternComponent[_componentName]) {
9252 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);
9253
9254 didWarnAboutModulePatternComponent[_componentName] = true;
9255 }
9256 }
9257 }
9258
9259 if ( // Run these checks in production only if the flag is off.
9260 // Eventually we'll delete this branch altogether.
9261 typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
9262 {
9263 var _componentName2 = getComponentName(Component) || 'Unknown';
9264
9265 if (!didWarnAboutModulePatternComponent[_componentName2]) {
9266 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);
9267
9268 didWarnAboutModulePatternComponent[_componentName2] = true;
9269 }
9270 } // Proceed under the assumption that this is a class instance
9271
9272
9273 workInProgress.tag = ClassComponent; // Throw out any hooks that were used.
9274
9275 workInProgress.memoizedState = null;
9276 workInProgress.updateQueue = null; // Push context providers early to prevent context stack mismatches.
9277 // During mounting we don't know the child context yet as the instance doesn't exist.
9278 // We will invalidate the child context in finishClassComponent() right after rendering.
9279
9280 var hasContext = false;
9281
9282 if (isContextProvider(Component)) {
9283 hasContext = true;
9284 pushContextProvider(workInProgress);
9285 } else {
9286 hasContext = false;
9287 }
9288
9289 workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
9290 initializeUpdateQueue(workInProgress);
9291 var getDerivedStateFromProps = Component.getDerivedStateFromProps;
9292
9293 if (typeof getDerivedStateFromProps === 'function') {
9294 applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);
9295 }
9296
9297 adoptClassInstance(workInProgress, value);
9298 mountClassInstance(workInProgress, Component, props, renderLanes);
9299 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes);
9300 } else {
9301 // Proceed under the assumption that this is a function component
9302 workInProgress.tag = FunctionComponent;
9303
9304 {
9305
9306 if ( workInProgress.mode & StrictMode) {
9307 disableLogs();
9308
9309 try {
9310 value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes);
9311 } finally {
9312 reenableLogs();
9313 }
9314 }
9315 }
9316
9317 reconcileChildren(null, workInProgress, value, renderLanes);
9318
9319 {
9320 validateFunctionComponentInDev(workInProgress, Component);
9321 }
9322
9323 return workInProgress.child;
9324 }
9325 }
9326
9327 function validateFunctionComponentInDev(workInProgress, Component) {
9328 {
9329 if (Component) {
9330 if (Component.childContextTypes) {
9331 error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component');
9332 }
9333 }
9334
9335 if (workInProgress.ref !== null) {
9336 var info = '';
9337 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
9338
9339 if (ownerName) {
9340 info += '\n\nCheck the render method of `' + ownerName + '`.';
9341 }
9342
9343 var warningKey = ownerName || workInProgress._debugID || '';
9344 var debugSource = workInProgress._debugSource;
9345
9346 if (debugSource) {
9347 warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
9348 }
9349
9350 if (!didWarnAboutFunctionRefs[warningKey]) {
9351 didWarnAboutFunctionRefs[warningKey] = true;
9352
9353 error('Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info);
9354 }
9355 }
9356
9357 if (typeof Component.getDerivedStateFromProps === 'function') {
9358 var _componentName3 = getComponentName(Component) || 'Unknown';
9359
9360 if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) {
9361 error('%s: Function components do not support getDerivedStateFromProps.', _componentName3);
9362
9363 didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true;
9364 }
9365 }
9366
9367 if (typeof Component.contextType === 'object' && Component.contextType !== null) {
9368 var _componentName4 = getComponentName(Component) || 'Unknown';
9369
9370 if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) {
9371 error('%s: Function components do not support contextType.', _componentName4);
9372
9373 didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true;
9374 }
9375 }
9376 }
9377 }
9378
9379 var SUSPENDED_MARKER = {
9380 dehydrated: null,
9381 retryLane: NoLane
9382 };
9383
9384 function mountSuspenseOffscreenState(renderLanes) {
9385 return {
9386 baseLanes: renderLanes
9387 };
9388 }
9389
9390 function updateSuspenseOffscreenState(prevOffscreenState, renderLanes) {
9391 return {
9392 baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes)
9393 };
9394 } // TODO: Probably should inline this back
9395
9396
9397 function shouldRemainOnFallback(suspenseContext, current, workInProgress, renderLanes) {
9398 // If we're already showing a fallback, there are cases where we need to
9399 // remain on that fallback regardless of whether the content has resolved.
9400 // For example, SuspenseList coordinates when nested content appears.
9401 if (current !== null) {
9402 var suspenseState = current.memoizedState;
9403
9404 if (suspenseState === null) {
9405 // Currently showing content. Don't hide it, even if ForceSuspenseFallack
9406 // is true. More precise name might be "ForceRemainSuspenseFallback".
9407 // Note: This is a factoring smell. Can't remain on a fallback if there's
9408 // no fallback to remain on.
9409 return false;
9410 }
9411 } // Not currently showing content. Consult the Suspense context.
9412
9413
9414 return hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
9415 }
9416
9417 function getRemainingWorkInPrimaryTree(current, renderLanes) {
9418 // TODO: Should not remove render lanes that were pinged during this render
9419 return removeLanes(current.childLanes, renderLanes);
9420 }
9421
9422 function updateSuspenseComponent(current, workInProgress, renderLanes) {
9423 var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend.
9424
9425 {
9426 if (shouldSuspend(workInProgress)) {
9427 workInProgress.flags |= DidCapture;
9428 }
9429 }
9430
9431 var suspenseContext = suspenseStackCursor.current;
9432 var showFallback = false;
9433 var didSuspend = (workInProgress.flags & DidCapture) !== NoFlags;
9434
9435 if (didSuspend || shouldRemainOnFallback(suspenseContext, current)) {
9436 // Something in this boundary's subtree already suspended. Switch to
9437 // rendering the fallback children.
9438 showFallback = true;
9439 workInProgress.flags &= ~DidCapture;
9440 } else {
9441 // Attempting the main content
9442 if (current === null || current.memoizedState !== null) {
9443 // This is a new mount or this boundary is already showing a fallback state.
9444 // Mark this subtree context as having at least one invisible parent that could
9445 // handle the fallback state.
9446 // Boundaries without fallbacks or should be avoided are not considered since
9447 // they cannot handle preferred fallback states.
9448 if (nextProps.fallback !== undefined && nextProps.unstable_avoidThisFallback !== true) {
9449 suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext);
9450 }
9451 }
9452 }
9453
9454 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
9455 pushSuspenseContext(workInProgress, suspenseContext); // OK, the next part is confusing. We're about to reconcile the Suspense
9456 // boundary's children. This involves some custom reconcilation logic. Two
9457 // main reasons this is so complicated.
9458 //
9459 // First, Legacy Mode has different semantics for backwards compatibility. The
9460 // primary tree will commit in an inconsistent state, so when we do the
9461 // second pass to render the fallback, we do some exceedingly, uh, clever
9462 // hacks to make that not totally break. Like transferring effects and
9463 // deletions from hidden tree. In Concurrent Mode, it's much simpler,
9464 // because we bailout on the primary tree completely and leave it in its old
9465 // state, no effects. Same as what we do for Offscreen (except that
9466 // Offscreen doesn't have the first render pass).
9467 //
9468 // Second is hydration. During hydration, the Suspense fiber has a slightly
9469 // different layout, where the child points to a dehydrated fragment, which
9470 // contains the DOM rendered by the server.
9471 //
9472 // Third, even if you set all that aside, Suspense is like error boundaries in
9473 // that we first we try to render one tree, and if that fails, we render again
9474 // and switch to a different tree. Like a try/catch block. So we have to track
9475 // which branch we're currently rendering. Ideally we would model this using
9476 // a stack.
9477
9478 if (current === null) {
9479 // Initial mount
9480 // If we're currently hydrating, try to hydrate this boundary.
9481 // But only if this has a fallback.
9482 if (nextProps.fallback !== undefined) ;
9483
9484 var nextPrimaryChildren = nextProps.children;
9485 var nextFallbackChildren = nextProps.fallback;
9486
9487 if (showFallback) {
9488 var fallbackFragment = mountSuspenseFallbackChildren(workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes);
9489 var primaryChildFragment = workInProgress.child;
9490 primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes);
9491 workInProgress.memoizedState = SUSPENDED_MARKER;
9492 return fallbackFragment;
9493 } else if (typeof nextProps.unstable_expectedLoadTime === 'number') {
9494 // This is a CPU-bound tree. Skip this tree and show a placeholder to
9495 // unblock the surrounding content. Then immediately retry after the
9496 // initial commit.
9497 var _fallbackFragment = mountSuspenseFallbackChildren(workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes);
9498
9499 var _primaryChildFragment = workInProgress.child;
9500 _primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes);
9501 workInProgress.memoizedState = SUSPENDED_MARKER; // Since nothing actually suspended, there will nothing to ping this to
9502 // get it started back up to attempt the next item. While in terms of
9503 // priority this work has the same priority as this current render, it's
9504 // not part of the same transition once the transition has committed. If
9505 // it's sync, we still want to yield so that it can be painted.
9506 // Conceptually, this is really the same as pinging. We can use any
9507 // RetryLane even if it's the one currently rendering since we're leaving
9508 // it behind on this node.
9509
9510 workInProgress.lanes = SomeRetryLane;
9511
9512 {
9513 markSpawnedWork(SomeRetryLane);
9514 }
9515
9516 return _fallbackFragment;
9517 } else {
9518 return mountSuspensePrimaryChildren(workInProgress, nextPrimaryChildren, renderLanes);
9519 }
9520 } else {
9521 // This is an update.
9522 // If the current fiber has a SuspenseState, that means it's already showing
9523 // a fallback.
9524 var prevState = current.memoizedState;
9525
9526 if (prevState !== null) {
9527
9528 if (showFallback) {
9529 var _nextFallbackChildren2 = nextProps.fallback;
9530 var _nextPrimaryChildren2 = nextProps.children;
9531
9532 var _fallbackChildFragment = updateSuspenseFallbackChildren(current, workInProgress, _nextPrimaryChildren2, _nextFallbackChildren2, renderLanes);
9533
9534 var _primaryChildFragment3 = workInProgress.child;
9535 var prevOffscreenState = current.child.memoizedState;
9536 _primaryChildFragment3.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes);
9537 _primaryChildFragment3.childLanes = getRemainingWorkInPrimaryTree(current, renderLanes);
9538 workInProgress.memoizedState = SUSPENDED_MARKER;
9539 return _fallbackChildFragment;
9540 } else {
9541 var _nextPrimaryChildren3 = nextProps.children;
9542
9543 var _primaryChildFragment4 = updateSuspensePrimaryChildren(current, workInProgress, _nextPrimaryChildren3, renderLanes);
9544
9545 workInProgress.memoizedState = null;
9546 return _primaryChildFragment4;
9547 }
9548 } else {
9549 // The current tree is not already showing a fallback.
9550 if (showFallback) {
9551 // Timed out.
9552 var _nextFallbackChildren3 = nextProps.fallback;
9553 var _nextPrimaryChildren4 = nextProps.children;
9554
9555 var _fallbackChildFragment2 = updateSuspenseFallbackChildren(current, workInProgress, _nextPrimaryChildren4, _nextFallbackChildren3, renderLanes);
9556
9557 var _primaryChildFragment5 = workInProgress.child;
9558 var _prevOffscreenState = current.child.memoizedState;
9559 _primaryChildFragment5.memoizedState = _prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(_prevOffscreenState, renderLanes);
9560 _primaryChildFragment5.childLanes = getRemainingWorkInPrimaryTree(current, renderLanes); // Skip the primary children, and continue working on the
9561 // fallback children.
9562
9563 workInProgress.memoizedState = SUSPENDED_MARKER;
9564 return _fallbackChildFragment2;
9565 } else {
9566 // Still haven't timed out. Continue rendering the children, like we
9567 // normally do.
9568 var _nextPrimaryChildren5 = nextProps.children;
9569
9570 var _primaryChildFragment6 = updateSuspensePrimaryChildren(current, workInProgress, _nextPrimaryChildren5, renderLanes);
9571
9572 workInProgress.memoizedState = null;
9573 return _primaryChildFragment6;
9574 }
9575 }
9576 }
9577 }
9578
9579 function mountSuspensePrimaryChildren(workInProgress, primaryChildren, renderLanes) {
9580 var mode = workInProgress.mode;
9581 var primaryChildProps = {
9582 mode: 'visible',
9583 children: primaryChildren
9584 };
9585 var primaryChildFragment = createFiberFromOffscreen(primaryChildProps, mode, renderLanes, null);
9586 primaryChildFragment.return = workInProgress;
9587 workInProgress.child = primaryChildFragment;
9588 return primaryChildFragment;
9589 }
9590
9591 function mountSuspenseFallbackChildren(workInProgress, primaryChildren, fallbackChildren, renderLanes) {
9592 var mode = workInProgress.mode;
9593 var progressedPrimaryFragment = workInProgress.child;
9594 var primaryChildProps = {
9595 mode: 'hidden',
9596 children: primaryChildren
9597 };
9598 var primaryChildFragment;
9599 var fallbackChildFragment;
9600
9601 if ((mode & BlockingMode) === NoMode && progressedPrimaryFragment !== null) {
9602 // In legacy mode, we commit the primary tree as if it successfully
9603 // completed, even though it's in an inconsistent state.
9604 primaryChildFragment = progressedPrimaryFragment;
9605 primaryChildFragment.childLanes = NoLanes;
9606 primaryChildFragment.pendingProps = primaryChildProps;
9607
9608 if ( workInProgress.mode & ProfileMode) {
9609 // Reset the durations from the first pass so they aren't included in the
9610 // final amounts. This seems counterintuitive, since we're intentionally
9611 // not measuring part of the render phase, but this makes it match what we
9612 // do in Concurrent Mode.
9613 primaryChildFragment.actualDuration = 0;
9614 primaryChildFragment.actualStartTime = -1;
9615 primaryChildFragment.selfBaseDuration = 0;
9616 primaryChildFragment.treeBaseDuration = 0;
9617 }
9618
9619 fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null);
9620 } else {
9621 primaryChildFragment = createFiberFromOffscreen(primaryChildProps, mode, NoLanes, null);
9622 fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null);
9623 }
9624
9625 primaryChildFragment.return = workInProgress;
9626 fallbackChildFragment.return = workInProgress;
9627 primaryChildFragment.sibling = fallbackChildFragment;
9628 workInProgress.child = primaryChildFragment;
9629 return fallbackChildFragment;
9630 }
9631
9632 function createWorkInProgressOffscreenFiber(current, offscreenProps) {
9633 // The props argument to `createWorkInProgress` is `any` typed, so we use this
9634 // wrapper function to constrain it.
9635 return createWorkInProgress(current, offscreenProps);
9636 }
9637
9638 function updateSuspensePrimaryChildren(current, workInProgress, primaryChildren, renderLanes) {
9639 var currentPrimaryChildFragment = current.child;
9640 var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
9641 var primaryChildFragment = createWorkInProgressOffscreenFiber(currentPrimaryChildFragment, {
9642 mode: 'visible',
9643 children: primaryChildren
9644 });
9645
9646 if ((workInProgress.mode & BlockingMode) === NoMode) {
9647 primaryChildFragment.lanes = renderLanes;
9648 }
9649
9650 primaryChildFragment.return = workInProgress;
9651 primaryChildFragment.sibling = null;
9652
9653 if (currentFallbackChildFragment !== null) {
9654 // Delete the fallback child fragment
9655 currentFallbackChildFragment.nextEffect = null;
9656 currentFallbackChildFragment.flags = Deletion;
9657 workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChildFragment;
9658 }
9659
9660 workInProgress.child = primaryChildFragment;
9661 return primaryChildFragment;
9662 }
9663
9664 function updateSuspenseFallbackChildren(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) {
9665 var mode = workInProgress.mode;
9666 var currentPrimaryChildFragment = current.child;
9667 var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
9668 var primaryChildProps = {
9669 mode: 'hidden',
9670 children: primaryChildren
9671 };
9672 var primaryChildFragment;
9673
9674 if ( // In legacy mode, we commit the primary tree as if it successfully
9675 // completed, even though it's in an inconsistent state.
9676 (mode & BlockingMode) === NoMode && // Make sure we're on the second pass, i.e. the primary child fragment was
9677 // already cloned. In legacy mode, the only case where this isn't true is
9678 // when DevTools forces us to display a fallback; we skip the first render
9679 // pass entirely and go straight to rendering the fallback. (In Concurrent
9680 // Mode, SuspenseList can also trigger this scenario, but this is a legacy-
9681 // only codepath.)
9682 workInProgress.child !== currentPrimaryChildFragment) {
9683 var progressedPrimaryFragment = workInProgress.child;
9684 primaryChildFragment = progressedPrimaryFragment;
9685 primaryChildFragment.childLanes = NoLanes;
9686 primaryChildFragment.pendingProps = primaryChildProps;
9687
9688 if ( workInProgress.mode & ProfileMode) {
9689 // Reset the durations from the first pass so they aren't included in the
9690 // final amounts. This seems counterintuitive, since we're intentionally
9691 // not measuring part of the render phase, but this makes it match what we
9692 // do in Concurrent Mode.
9693 primaryChildFragment.actualDuration = 0;
9694 primaryChildFragment.actualStartTime = -1;
9695 primaryChildFragment.selfBaseDuration = currentPrimaryChildFragment.selfBaseDuration;
9696 primaryChildFragment.treeBaseDuration = currentPrimaryChildFragment.treeBaseDuration;
9697 } // The fallback fiber was added as a deletion effect during the first pass.
9698 // However, since we're going to remain on the fallback, we no longer want
9699 // to delete it. So we need to remove it from the list. Deletions are stored
9700 // on the same list as effects. We want to keep the effects from the primary
9701 // tree. So we copy the primary child fragment's effect list, which does not
9702 // include the fallback deletion effect.
9703
9704
9705 var progressedLastEffect = primaryChildFragment.lastEffect;
9706
9707 if (progressedLastEffect !== null) {
9708 workInProgress.firstEffect = primaryChildFragment.firstEffect;
9709 workInProgress.lastEffect = progressedLastEffect;
9710 progressedLastEffect.nextEffect = null;
9711 } else {
9712 // TODO: Reset this somewhere else? Lol legacy mode is so weird.
9713 workInProgress.firstEffect = workInProgress.lastEffect = null;
9714 }
9715 } else {
9716 primaryChildFragment = createWorkInProgressOffscreenFiber(currentPrimaryChildFragment, primaryChildProps);
9717 }
9718
9719 var fallbackChildFragment;
9720
9721 if (currentFallbackChildFragment !== null) {
9722 fallbackChildFragment = createWorkInProgress(currentFallbackChildFragment, fallbackChildren);
9723 } else {
9724 fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); // Needs a placement effect because the parent (the Suspense boundary) already
9725 // mounted but this is a new fiber.
9726
9727 fallbackChildFragment.flags |= Placement;
9728 }
9729
9730 fallbackChildFragment.return = workInProgress;
9731 primaryChildFragment.return = workInProgress;
9732 primaryChildFragment.sibling = fallbackChildFragment;
9733 workInProgress.child = primaryChildFragment;
9734 return fallbackChildFragment;
9735 }
9736
9737 function scheduleWorkOnFiber(fiber, renderLanes) {
9738 fiber.lanes = mergeLanes(fiber.lanes, renderLanes);
9739 var alternate = fiber.alternate;
9740
9741 if (alternate !== null) {
9742 alternate.lanes = mergeLanes(alternate.lanes, renderLanes);
9743 }
9744
9745 scheduleWorkOnParentPath(fiber.return, renderLanes);
9746 }
9747
9748 function propagateSuspenseContextChange(workInProgress, firstChild, renderLanes) {
9749 // Mark any Suspense boundaries with fallbacks as having work to do.
9750 // If they were previously forced into fallbacks, they may now be able
9751 // to unblock.
9752 var node = firstChild;
9753
9754 while (node !== null) {
9755 if (node.tag === SuspenseComponent) {
9756 var state = node.memoizedState;
9757
9758 if (state !== null) {
9759 scheduleWorkOnFiber(node, renderLanes);
9760 }
9761 } else if (node.tag === SuspenseListComponent) {
9762 // If the tail is hidden there might not be an Suspense boundaries
9763 // to schedule work on. In this case we have to schedule it on the
9764 // list itself.
9765 // We don't have to traverse to the children of the list since
9766 // the list will propagate the change when it rerenders.
9767 scheduleWorkOnFiber(node, renderLanes);
9768 } else if (node.child !== null) {
9769 node.child.return = node;
9770 node = node.child;
9771 continue;
9772 }
9773
9774 if (node === workInProgress) {
9775 return;
9776 }
9777
9778 while (node.sibling === null) {
9779 if (node.return === null || node.return === workInProgress) {
9780 return;
9781 }
9782
9783 node = node.return;
9784 }
9785
9786 node.sibling.return = node.return;
9787 node = node.sibling;
9788 }
9789 }
9790
9791 function findLastContentRow(firstChild) {
9792 // This is going to find the last row among these children that is already
9793 // showing content on the screen, as opposed to being in fallback state or
9794 // new. If a row has multiple Suspense boundaries, any of them being in the
9795 // fallback state, counts as the whole row being in a fallback state.
9796 // Note that the "rows" will be workInProgress, but any nested children
9797 // will still be current since we haven't rendered them yet. The mounted
9798 // order may not be the same as the new order. We use the new order.
9799 var row = firstChild;
9800 var lastContentRow = null;
9801
9802 while (row !== null) {
9803 var currentRow = row.alternate; // New rows can't be content rows.
9804
9805 if (currentRow !== null && findFirstSuspended(currentRow) === null) {
9806 lastContentRow = row;
9807 }
9808
9809 row = row.sibling;
9810 }
9811
9812 return lastContentRow;
9813 }
9814
9815 function validateRevealOrder(revealOrder) {
9816 {
9817 if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) {
9818 didWarnAboutRevealOrder[revealOrder] = true;
9819
9820 if (typeof revealOrder === 'string') {
9821 switch (revealOrder.toLowerCase()) {
9822 case 'together':
9823 case 'forwards':
9824 case 'backwards':
9825 {
9826 error('"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase());
9827
9828 break;
9829 }
9830
9831 case 'forward':
9832 case 'backward':
9833 {
9834 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());
9835
9836 break;
9837 }
9838
9839 default:
9840 error('"%s" is not a supported revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
9841
9842 break;
9843 }
9844 } else {
9845 error('%s is not a supported value for revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
9846 }
9847 }
9848 }
9849 }
9850
9851 function validateTailOptions(tailMode, revealOrder) {
9852 {
9853 if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) {
9854 if (tailMode !== 'collapsed' && tailMode !== 'hidden') {
9855 didWarnAboutTailOptions[tailMode] = true;
9856
9857 error('"%s" is not a supported value for tail on <SuspenseList />. ' + 'Did you mean "collapsed" or "hidden"?', tailMode);
9858 } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') {
9859 didWarnAboutTailOptions[tailMode] = true;
9860
9861 error('<SuspenseList tail="%s" /> is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode);
9862 }
9863 }
9864 }
9865 }
9866
9867 function validateSuspenseListNestedChild(childSlot, index) {
9868 {
9869 var isArray = Array.isArray(childSlot);
9870 var isIterable = !isArray && typeof getIteratorFn(childSlot) === 'function';
9871
9872 if (isArray || isIterable) {
9873 var type = isArray ? 'array' : 'iterable';
9874
9875 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);
9876
9877 return false;
9878 }
9879 }
9880
9881 return true;
9882 }
9883
9884 function validateSuspenseListChildren(children, revealOrder) {
9885 {
9886 if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) {
9887 if (Array.isArray(children)) {
9888 for (var i = 0; i < children.length; i++) {
9889 if (!validateSuspenseListNestedChild(children[i], i)) {
9890 return;
9891 }
9892 }
9893 } else {
9894 var iteratorFn = getIteratorFn(children);
9895
9896 if (typeof iteratorFn === 'function') {
9897 var childrenIterator = iteratorFn.call(children);
9898
9899 if (childrenIterator) {
9900 var step = childrenIterator.next();
9901 var _i = 0;
9902
9903 for (; !step.done; step = childrenIterator.next()) {
9904 if (!validateSuspenseListNestedChild(step.value, _i)) {
9905 return;
9906 }
9907
9908 _i++;
9909 }
9910 }
9911 } else {
9912 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);
9913 }
9914 }
9915 }
9916 }
9917 }
9918
9919 function initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode, lastEffectBeforeRendering) {
9920 var renderState = workInProgress.memoizedState;
9921
9922 if (renderState === null) {
9923 workInProgress.memoizedState = {
9924 isBackwards: isBackwards,
9925 rendering: null,
9926 renderingStartTime: 0,
9927 last: lastContentRow,
9928 tail: tail,
9929 tailMode: tailMode,
9930 lastEffect: lastEffectBeforeRendering
9931 };
9932 } else {
9933 // We can reuse the existing object from previous renders.
9934 renderState.isBackwards = isBackwards;
9935 renderState.rendering = null;
9936 renderState.renderingStartTime = 0;
9937 renderState.last = lastContentRow;
9938 renderState.tail = tail;
9939 renderState.tailMode = tailMode;
9940 renderState.lastEffect = lastEffectBeforeRendering;
9941 }
9942 } // This can end up rendering this component multiple passes.
9943 // The first pass splits the children fibers into two sets. A head and tail.
9944 // We first render the head. If anything is in fallback state, we do another
9945 // pass through beginWork to rerender all children (including the tail) with
9946 // the force suspend context. If the first render didn't have anything in
9947 // in fallback state. Then we render each row in the tail one-by-one.
9948 // That happens in the completeWork phase without going back to beginWork.
9949
9950
9951 function updateSuspenseListComponent(current, workInProgress, renderLanes) {
9952 var nextProps = workInProgress.pendingProps;
9953 var revealOrder = nextProps.revealOrder;
9954 var tailMode = nextProps.tail;
9955 var newChildren = nextProps.children;
9956 validateRevealOrder(revealOrder);
9957 validateTailOptions(tailMode, revealOrder);
9958 validateSuspenseListChildren(newChildren, revealOrder);
9959 reconcileChildren(current, workInProgress, newChildren, renderLanes);
9960 var suspenseContext = suspenseStackCursor.current;
9961 var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
9962
9963 if (shouldForceFallback) {
9964 suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
9965 workInProgress.flags |= DidCapture;
9966 } else {
9967 var didSuspendBefore = current !== null && (current.flags & DidCapture) !== NoFlags;
9968
9969 if (didSuspendBefore) {
9970 // If we previously forced a fallback, we need to schedule work
9971 // on any nested boundaries to let them know to try to render
9972 // again. This is the same as context updating.
9973 propagateSuspenseContextChange(workInProgress, workInProgress.child, renderLanes);
9974 }
9975
9976 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
9977 }
9978
9979 pushSuspenseContext(workInProgress, suspenseContext);
9980
9981 if ((workInProgress.mode & BlockingMode) === NoMode) {
9982 // In legacy mode, SuspenseList doesn't work so we just
9983 // use make it a noop by treating it as the default revealOrder.
9984 workInProgress.memoizedState = null;
9985 } else {
9986 switch (revealOrder) {
9987 case 'forwards':
9988 {
9989 var lastContentRow = findLastContentRow(workInProgress.child);
9990 var tail;
9991
9992 if (lastContentRow === null) {
9993 // The whole list is part of the tail.
9994 // TODO: We could fast path by just rendering the tail now.
9995 tail = workInProgress.child;
9996 workInProgress.child = null;
9997 } else {
9998 // Disconnect the tail rows after the content row.
9999 // We're going to render them separately later.
10000 tail = lastContentRow.sibling;
10001 lastContentRow.sibling = null;
10002 }
10003
10004 initSuspenseListRenderState(workInProgress, false, // isBackwards
10005 tail, lastContentRow, tailMode, workInProgress.lastEffect);
10006 break;
10007 }
10008
10009 case 'backwards':
10010 {
10011 // We're going to find the first row that has existing content.
10012 // At the same time we're going to reverse the list of everything
10013 // we pass in the meantime. That's going to be our tail in reverse
10014 // order.
10015 var _tail = null;
10016 var row = workInProgress.child;
10017 workInProgress.child = null;
10018
10019 while (row !== null) {
10020 var currentRow = row.alternate; // New rows can't be content rows.
10021
10022 if (currentRow !== null && findFirstSuspended(currentRow) === null) {
10023 // This is the beginning of the main content.
10024 workInProgress.child = row;
10025 break;
10026 }
10027
10028 var nextRow = row.sibling;
10029 row.sibling = _tail;
10030 _tail = row;
10031 row = nextRow;
10032 } // TODO: If workInProgress.child is null, we can continue on the tail immediately.
10033
10034
10035 initSuspenseListRenderState(workInProgress, true, // isBackwards
10036 _tail, null, // last
10037 tailMode, workInProgress.lastEffect);
10038 break;
10039 }
10040
10041 case 'together':
10042 {
10043 initSuspenseListRenderState(workInProgress, false, // isBackwards
10044 null, // tail
10045 null, // last
10046 undefined, workInProgress.lastEffect);
10047 break;
10048 }
10049
10050 default:
10051 {
10052 // The default reveal order is the same as not having
10053 // a boundary.
10054 workInProgress.memoizedState = null;
10055 }
10056 }
10057 }
10058
10059 return workInProgress.child;
10060 }
10061
10062 function updatePortalComponent(current, workInProgress, renderLanes) {
10063 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
10064 var nextChildren = workInProgress.pendingProps;
10065
10066 if (current === null) {
10067 // Portals are special because we don't append the children during mount
10068 // but at commit. Therefore we need to track insertions which the normal
10069 // flow doesn't do during mount. This doesn't happen at the root because
10070 // the root always starts with a "current" with a null child.
10071 // TODO: Consider unifying this with how the root works.
10072 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes);
10073 } else {
10074 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
10075 }
10076
10077 return workInProgress.child;
10078 }
10079
10080 var hasWarnedAboutUsingNoValuePropOnContextProvider = false;
10081
10082 function updateContextProvider(current, workInProgress, renderLanes) {
10083 var providerType = workInProgress.type;
10084 var context = providerType._context;
10085 var newProps = workInProgress.pendingProps;
10086 var oldProps = workInProgress.memoizedProps;
10087 var newValue = newProps.value;
10088
10089 {
10090 if (!('value' in newProps)) {
10091 if (!hasWarnedAboutUsingNoValuePropOnContextProvider) {
10092 hasWarnedAboutUsingNoValuePropOnContextProvider = true;
10093
10094 error('The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?');
10095 }
10096 }
10097
10098 var providerPropTypes = workInProgress.type.propTypes;
10099
10100 if (providerPropTypes) {
10101 checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider');
10102 }
10103 }
10104
10105 pushProvider(workInProgress, newValue);
10106
10107 if (oldProps !== null) {
10108 var oldValue = oldProps.value;
10109 var changedBits = calculateChangedBits(context, newValue, oldValue);
10110
10111 if (changedBits === 0) {
10112 // No change. Bailout early if children are the same.
10113 if (oldProps.children === newProps.children && !hasContextChanged()) {
10114 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
10115 }
10116 } else {
10117 // The context value changed. Search for matching consumers and schedule
10118 // them to update.
10119 propagateContextChange(workInProgress, context, changedBits, renderLanes);
10120 }
10121 }
10122
10123 var newChildren = newProps.children;
10124 reconcileChildren(current, workInProgress, newChildren, renderLanes);
10125 return workInProgress.child;
10126 }
10127
10128 var hasWarnedAboutUsingContextAsConsumer = false;
10129
10130 function updateContextConsumer(current, workInProgress, renderLanes) {
10131 var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In
10132 // DEV mode, we create a separate object for Context.Consumer that acts
10133 // like a proxy to Context. This proxy object adds unnecessary code in PROD
10134 // so we use the old behaviour (Context.Consumer references Context) to
10135 // reduce size and overhead. The separate object references context via
10136 // a property called "_context", which also gives us the ability to check
10137 // in DEV mode if this property exists or not and warn if it does not.
10138
10139 {
10140 if (context._context === undefined) {
10141 // This may be because it's a Context (rather than a Consumer).
10142 // Or it may be because it's older React where they're the same thing.
10143 // We only want to warn if we're sure it's a new React.
10144 if (context !== context.Consumer) {
10145 if (!hasWarnedAboutUsingContextAsConsumer) {
10146 hasWarnedAboutUsingContextAsConsumer = true;
10147
10148 error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
10149 }
10150 }
10151 } else {
10152 context = context._context;
10153 }
10154 }
10155
10156 var newProps = workInProgress.pendingProps;
10157 var render = newProps.children;
10158
10159 {
10160 if (typeof render !== 'function') {
10161 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.');
10162 }
10163 }
10164
10165 prepareToReadContext(workInProgress, renderLanes);
10166 var newValue = readContext(context, newProps.unstable_observedBits);
10167 var newChildren;
10168
10169 {
10170 ReactCurrentOwner$1.current = workInProgress;
10171 setIsRendering(true);
10172 newChildren = render(newValue);
10173 setIsRendering(false);
10174 } // React DevTools reads this flag.
10175
10176
10177 workInProgress.flags |= PerformedWork;
10178 reconcileChildren(current, workInProgress, newChildren, renderLanes);
10179 return workInProgress.child;
10180 }
10181
10182 function markWorkInProgressReceivedUpdate() {
10183 didReceiveUpdate = true;
10184 }
10185
10186 function bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes) {
10187 if (current !== null) {
10188 // Reuse previous dependencies
10189 workInProgress.dependencies = current.dependencies;
10190 }
10191
10192 {
10193 // Don't update "base" render times for bailouts.
10194 stopProfilerTimerIfRunning();
10195 }
10196
10197 markSkippedUpdateLanes(workInProgress.lanes); // Check if the children have any pending work.
10198
10199 if (!includesSomeLane(renderLanes, workInProgress.childLanes)) {
10200 // The children don't have any work either. We can skip them.
10201 // TODO: Once we add back resuming, we should check if the children are
10202 // a work-in-progress set. If so, we need to transfer their effects.
10203 return null;
10204 } else {
10205 // This fiber doesn't have work, but its subtree does. Clone the child
10206 // fibers and continue.
10207 cloneChildFibers(current, workInProgress);
10208 return workInProgress.child;
10209 }
10210 }
10211
10212 function remountFiber(current, oldWorkInProgress, newWorkInProgress) {
10213 {
10214 var returnFiber = oldWorkInProgress.return;
10215
10216 if (returnFiber === null) {
10217 throw new Error('Cannot swap the root fiber.');
10218 } // Disconnect from the old current.
10219 // It will get deleted.
10220
10221
10222 current.alternate = null;
10223 oldWorkInProgress.alternate = null; // Connect to the new tree.
10224
10225 newWorkInProgress.index = oldWorkInProgress.index;
10226 newWorkInProgress.sibling = oldWorkInProgress.sibling;
10227 newWorkInProgress.return = oldWorkInProgress.return;
10228 newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it.
10229
10230 if (oldWorkInProgress === returnFiber.child) {
10231 returnFiber.child = newWorkInProgress;
10232 } else {
10233 var prevSibling = returnFiber.child;
10234
10235 if (prevSibling === null) {
10236 throw new Error('Expected parent to have a child.');
10237 }
10238
10239 while (prevSibling.sibling !== oldWorkInProgress) {
10240 prevSibling = prevSibling.sibling;
10241
10242 if (prevSibling === null) {
10243 throw new Error('Expected to find the previous sibling.');
10244 }
10245 }
10246
10247 prevSibling.sibling = newWorkInProgress;
10248 } // Delete the old fiber and place the new one.
10249 // Since the old fiber is disconnected, we have to schedule it manually.
10250
10251
10252 var last = returnFiber.lastEffect;
10253
10254 if (last !== null) {
10255 last.nextEffect = current;
10256 returnFiber.lastEffect = current;
10257 } else {
10258 returnFiber.firstEffect = returnFiber.lastEffect = current;
10259 }
10260
10261 current.nextEffect = null;
10262 current.flags = Deletion;
10263 newWorkInProgress.flags |= Placement; // Restart work from the new fiber.
10264
10265 return newWorkInProgress;
10266 }
10267 }
10268
10269 function beginWork(current, workInProgress, renderLanes) {
10270 var updateLanes = workInProgress.lanes;
10271
10272 {
10273 if (workInProgress._debugNeedsRemount && current !== null) {
10274 // This will restart the begin phase with a new fiber.
10275 return remountFiber(current, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.lanes));
10276 }
10277 }
10278
10279 if (current !== null) {
10280 var oldProps = current.memoizedProps;
10281 var newProps = workInProgress.pendingProps;
10282
10283 if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload:
10284 workInProgress.type !== current.type )) {
10285 // If props or context changed, mark the fiber as having performed work.
10286 // This may be unset if the props are determined to be equal later (memo).
10287 didReceiveUpdate = true;
10288 } else if (!includesSomeLane(renderLanes, updateLanes)) {
10289 didReceiveUpdate = false; // This fiber does not have any pending work. Bailout without entering
10290 // the begin phase. There's still some bookkeeping we that needs to be done
10291 // in this optimized path, mostly pushing stuff onto the stack.
10292
10293 switch (workInProgress.tag) {
10294 case HostRoot:
10295 pushHostRootContext(workInProgress);
10296 break;
10297
10298 case HostComponent:
10299 pushHostContext(workInProgress);
10300 break;
10301
10302 case ClassComponent:
10303 {
10304 var Component = workInProgress.type;
10305
10306 if (isContextProvider(Component)) {
10307 pushContextProvider(workInProgress);
10308 }
10309
10310 break;
10311 }
10312
10313 case HostPortal:
10314 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
10315 break;
10316
10317 case ContextProvider:
10318 {
10319 var newValue = workInProgress.memoizedProps.value;
10320 pushProvider(workInProgress, newValue);
10321 break;
10322 }
10323
10324 case Profiler:
10325 {
10326 // Profiler should only call onRender when one of its descendants actually rendered.
10327 var hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes);
10328
10329 if (hasChildWork) {
10330 workInProgress.flags |= Update;
10331 } // Reset effect durations for the next eventual effect phase.
10332 // These are reset during render to allow the DevTools commit hook a chance to read them,
10333
10334
10335 var stateNode = workInProgress.stateNode;
10336 stateNode.effectDuration = 0;
10337 stateNode.passiveEffectDuration = 0;
10338 }
10339
10340 break;
10341
10342 case SuspenseComponent:
10343 {
10344 var state = workInProgress.memoizedState;
10345
10346 if (state !== null) {
10347 // whether to retry the primary children, or to skip over it and
10348 // go straight to the fallback. Check the priority of the primary
10349 // child fragment.
10350
10351
10352 var primaryChildFragment = workInProgress.child;
10353 var primaryChildLanes = primaryChildFragment.childLanes;
10354
10355 if (includesSomeLane(renderLanes, primaryChildLanes)) {
10356 // The primary children have pending work. Use the normal path
10357 // to attempt to render the primary children again.
10358 return updateSuspenseComponent(current, workInProgress, renderLanes);
10359 } else {
10360 // The primary child fragment does not have pending work marked
10361 // on it
10362 pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient
10363 // priority. Bailout.
10364
10365 var child = bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
10366
10367 if (child !== null) {
10368 // The fallback children have pending work. Skip over the
10369 // primary children and work on the fallback.
10370 return child.sibling;
10371 } else {
10372 return null;
10373 }
10374 }
10375 } else {
10376 pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
10377 }
10378
10379 break;
10380 }
10381
10382 case SuspenseListComponent:
10383 {
10384 var didSuspendBefore = (current.flags & DidCapture) !== NoFlags;
10385
10386 var _hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes);
10387
10388 if (didSuspendBefore) {
10389 if (_hasChildWork) {
10390 // If something was in fallback state last time, and we have all the
10391 // same children then we're still in progressive loading state.
10392 // Something might get unblocked by state updates or retries in the
10393 // tree which will affect the tail. So we need to use the normal
10394 // path to compute the correct tail.
10395 return updateSuspenseListComponent(current, workInProgress, renderLanes);
10396 } // If none of the children had any work, that means that none of
10397 // them got retried so they'll still be blocked in the same way
10398 // as before. We can fast bail out.
10399
10400
10401 workInProgress.flags |= DidCapture;
10402 } // If nothing suspended before and we're rendering the same children,
10403 // then the tail doesn't matter. Anything new that suspends will work
10404 // in the "together" mode, so we can continue from the state we had.
10405
10406
10407 var renderState = workInProgress.memoizedState;
10408
10409 if (renderState !== null) {
10410 // Reset to the "together" mode in case we've started a different
10411 // update in the past but didn't complete it.
10412 renderState.rendering = null;
10413 renderState.tail = null;
10414 renderState.lastEffect = null;
10415 }
10416
10417 pushSuspenseContext(workInProgress, suspenseStackCursor.current);
10418
10419 if (_hasChildWork) {
10420 break;
10421 } else {
10422 // If none of the children had any work, that means that none of
10423 // them got retried so they'll still be blocked in the same way
10424 // as before. We can fast bail out.
10425 return null;
10426 }
10427 }
10428
10429 case OffscreenComponent:
10430 case LegacyHiddenComponent:
10431 {
10432 // Need to check if the tree still needs to be deferred. This is
10433 // almost identical to the logic used in the normal update path,
10434 // so we'll just enter that. The only difference is we'll bail out
10435 // at the next level instead of this one, because the child props
10436 // have not changed. Which is fine.
10437 // TODO: Probably should refactor `beginWork` to split the bailout
10438 // path from the normal path. I'm tempted to do a labeled break here
10439 // but I won't :)
10440 workInProgress.lanes = NoLanes;
10441 return updateOffscreenComponent(current, workInProgress, renderLanes);
10442 }
10443 }
10444
10445 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
10446 } else {
10447 if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
10448 // This is a special case that only exists for legacy mode.
10449 // See https://github.com/facebook/react/pull/19216.
10450 didReceiveUpdate = true;
10451 } else {
10452 // An update was scheduled on this fiber, but there are no new props
10453 // nor legacy context. Set this to false. If an update queue or context
10454 // consumer produces a changed value, it will set this to true. Otherwise,
10455 // the component will assume the children have not changed and bail out.
10456 didReceiveUpdate = false;
10457 }
10458 }
10459 } else {
10460 didReceiveUpdate = false;
10461 } // Before entering the begin phase, clear pending update priority.
10462 // TODO: This assumes that we're about to evaluate the component and process
10463 // the update queue. However, there's an exception: SimpleMemoComponent
10464 // sometimes bails out later in the begin phase. This indicates that we should
10465 // move this assignment out of the common path and into each branch.
10466
10467
10468 workInProgress.lanes = NoLanes;
10469
10470 switch (workInProgress.tag) {
10471 case IndeterminateComponent:
10472 {
10473 return mountIndeterminateComponent(current, workInProgress, workInProgress.type, renderLanes);
10474 }
10475
10476 case LazyComponent:
10477 {
10478 var elementType = workInProgress.elementType;
10479 return mountLazyComponent(current, workInProgress, elementType, updateLanes, renderLanes);
10480 }
10481
10482 case FunctionComponent:
10483 {
10484 var _Component = workInProgress.type;
10485 var unresolvedProps = workInProgress.pendingProps;
10486 var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
10487 return updateFunctionComponent(current, workInProgress, _Component, resolvedProps, renderLanes);
10488 }
10489
10490 case ClassComponent:
10491 {
10492 var _Component2 = workInProgress.type;
10493 var _unresolvedProps = workInProgress.pendingProps;
10494
10495 var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);
10496
10497 return updateClassComponent(current, workInProgress, _Component2, _resolvedProps, renderLanes);
10498 }
10499
10500 case HostRoot:
10501 return updateHostRoot(current, workInProgress, renderLanes);
10502
10503 case HostComponent:
10504 return updateHostComponent(current, workInProgress, renderLanes);
10505
10506 case HostText:
10507 return updateHostText();
10508
10509 case SuspenseComponent:
10510 return updateSuspenseComponent(current, workInProgress, renderLanes);
10511
10512 case HostPortal:
10513 return updatePortalComponent(current, workInProgress, renderLanes);
10514
10515 case ForwardRef:
10516 {
10517 var type = workInProgress.type;
10518 var _unresolvedProps2 = workInProgress.pendingProps;
10519
10520 var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
10521
10522 return updateForwardRef(current, workInProgress, type, _resolvedProps2, renderLanes);
10523 }
10524
10525 case Fragment:
10526 return updateFragment(current, workInProgress, renderLanes);
10527
10528 case Mode:
10529 return updateMode(current, workInProgress, renderLanes);
10530
10531 case Profiler:
10532 return updateProfiler(current, workInProgress, renderLanes);
10533
10534 case ContextProvider:
10535 return updateContextProvider(current, workInProgress, renderLanes);
10536
10537 case ContextConsumer:
10538 return updateContextConsumer(current, workInProgress, renderLanes);
10539
10540 case MemoComponent:
10541 {
10542 var _type2 = workInProgress.type;
10543 var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props.
10544
10545 var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
10546
10547 {
10548 if (workInProgress.type !== workInProgress.elementType) {
10549 var outerPropTypes = _type2.propTypes;
10550
10551 if (outerPropTypes) {
10552 checkPropTypes(outerPropTypes, _resolvedProps3, // Resolved for outer only
10553 'prop', getComponentName(_type2));
10554 }
10555 }
10556 }
10557
10558 _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
10559 return updateMemoComponent(current, workInProgress, _type2, _resolvedProps3, updateLanes, renderLanes);
10560 }
10561
10562 case SimpleMemoComponent:
10563 {
10564 return updateSimpleMemoComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps, updateLanes, renderLanes);
10565 }
10566
10567 case IncompleteClassComponent:
10568 {
10569 var _Component3 = workInProgress.type;
10570 var _unresolvedProps4 = workInProgress.pendingProps;
10571
10572 var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);
10573
10574 return mountIncompleteClassComponent(current, workInProgress, _Component3, _resolvedProps4, renderLanes);
10575 }
10576
10577 case SuspenseListComponent:
10578 {
10579 return updateSuspenseListComponent(current, workInProgress, renderLanes);
10580 }
10581
10582 case FundamentalComponent:
10583 {
10584
10585 break;
10586 }
10587
10588 case ScopeComponent:
10589 {
10590
10591 break;
10592 }
10593
10594 case Block:
10595 {
10596
10597 break;
10598 }
10599
10600 case OffscreenComponent:
10601 {
10602 return updateOffscreenComponent(current, workInProgress, renderLanes);
10603 }
10604
10605 case LegacyHiddenComponent:
10606 {
10607 return updateLegacyHiddenComponent(current, workInProgress, renderLanes);
10608 }
10609 }
10610
10611 {
10612 {
10613 throw Error( "Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in React. Please file an issue." );
10614 }
10615 }
10616 }
10617
10618 function markUpdate(workInProgress) {
10619 // Tag the fiber with an update effect. This turns a Placement into
10620 // a PlacementAndUpdate.
10621 workInProgress.flags |= Update;
10622 }
10623
10624 function markRef$1(workInProgress) {
10625 workInProgress.flags |= Ref;
10626 }
10627
10628 var appendAllChildren;
10629 var updateHostContainer;
10630 var updateHostComponent$1;
10631 var updateHostText$1;
10632
10633 {
10634 // Mutation mode
10635 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
10636 // We only have the top Fiber that was created but we need recurse down its
10637 // children to find all the terminal nodes.
10638 var node = workInProgress.child;
10639
10640 while (node !== null) {
10641 if (node.tag === HostComponent || node.tag === HostText) {
10642 appendInitialChild(parent, node.stateNode);
10643 } else if (node.tag === HostPortal) ; else if (node.child !== null) {
10644 node.child.return = node;
10645 node = node.child;
10646 continue;
10647 }
10648
10649 if (node === workInProgress) {
10650 return;
10651 }
10652
10653 while (node.sibling === null) {
10654 if (node.return === null || node.return === workInProgress) {
10655 return;
10656 }
10657
10658 node = node.return;
10659 }
10660
10661 node.sibling.return = node.return;
10662 node = node.sibling;
10663 }
10664 };
10665
10666 updateHostContainer = function (workInProgress) {// Noop
10667 };
10668
10669 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
10670 // If we have an alternate, that means this is an update and we need to
10671 // schedule a side-effect to do the updates.
10672 var oldProps = current.memoizedProps;
10673
10674 if (oldProps === newProps) {
10675 // In mutation mode, this is sufficient for a bailout because
10676 // we won't touch this node even if children changed.
10677 return;
10678 } // If we get updated because one of our children updated, we don't
10679 // have newProps so we'll have to reuse them.
10680 // TODO: Split the update API as separate for the props vs. children.
10681 // Even better would be if children weren't special cased at all tho.
10682
10683
10684 var instance = workInProgress.stateNode;
10685 var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host
10686 // component is hitting the resume path. Figure out why. Possibly
10687 // related to `hidden`.
10688
10689 var updatePayload = prepareUpdate(); // TODO: Type this specific to this type of component.
10690
10691 workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
10692 // is a new ref we mark this as an update. All the work is done in commitWork.
10693
10694 if (updatePayload) {
10695 markUpdate(workInProgress);
10696 }
10697 };
10698
10699 updateHostText$1 = function (current, workInProgress, oldText, newText) {
10700 // If the text differs, mark it as an update. All the work in done in commitWork.
10701 if (oldText !== newText) {
10702 markUpdate(workInProgress);
10703 }
10704 };
10705 }
10706
10707 function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
10708
10709 switch (renderState.tailMode) {
10710 case 'hidden':
10711 {
10712 // Any insertions at the end of the tail list after this point
10713 // should be invisible. If there are already mounted boundaries
10714 // anything before them are not considered for collapsing.
10715 // Therefore we need to go through the whole tail to find if
10716 // there are any.
10717 var tailNode = renderState.tail;
10718 var lastTailNode = null;
10719
10720 while (tailNode !== null) {
10721 if (tailNode.alternate !== null) {
10722 lastTailNode = tailNode;
10723 }
10724
10725 tailNode = tailNode.sibling;
10726 } // Next we're simply going to delete all insertions after the
10727 // last rendered item.
10728
10729
10730 if (lastTailNode === null) {
10731 // All remaining items in the tail are insertions.
10732 renderState.tail = null;
10733 } else {
10734 // Detach the insertion after the last node that was already
10735 // inserted.
10736 lastTailNode.sibling = null;
10737 }
10738
10739 break;
10740 }
10741
10742 case 'collapsed':
10743 {
10744 // Any insertions at the end of the tail list after this point
10745 // should be invisible. If there are already mounted boundaries
10746 // anything before them are not considered for collapsing.
10747 // Therefore we need to go through the whole tail to find if
10748 // there are any.
10749 var _tailNode = renderState.tail;
10750 var _lastTailNode = null;
10751
10752 while (_tailNode !== null) {
10753 if (_tailNode.alternate !== null) {
10754 _lastTailNode = _tailNode;
10755 }
10756
10757 _tailNode = _tailNode.sibling;
10758 } // Next we're simply going to delete all insertions after the
10759 // last rendered item.
10760
10761
10762 if (_lastTailNode === null) {
10763 // All remaining items in the tail are insertions.
10764 if (!hasRenderedATailFallback && renderState.tail !== null) {
10765 // We suspended during the head. We want to show at least one
10766 // row at the tail. So we'll keep on and cut off the rest.
10767 renderState.tail.sibling = null;
10768 } else {
10769 renderState.tail = null;
10770 }
10771 } else {
10772 // Detach the insertion after the last node that was already
10773 // inserted.
10774 _lastTailNode.sibling = null;
10775 }
10776
10777 break;
10778 }
10779 }
10780 }
10781
10782 function completeWork(current, workInProgress, renderLanes) {
10783 var newProps = workInProgress.pendingProps;
10784
10785 switch (workInProgress.tag) {
10786 case IndeterminateComponent:
10787 case LazyComponent:
10788 case SimpleMemoComponent:
10789 case FunctionComponent:
10790 case ForwardRef:
10791 case Fragment:
10792 case Mode:
10793 case Profiler:
10794 case ContextConsumer:
10795 case MemoComponent:
10796 return null;
10797
10798 case ClassComponent:
10799 {
10800 var Component = workInProgress.type;
10801
10802 if (isContextProvider(Component)) {
10803 popContext(workInProgress);
10804 }
10805
10806 return null;
10807 }
10808
10809 case HostRoot:
10810 {
10811 popHostContainer(workInProgress);
10812 popTopLevelContextObject(workInProgress);
10813 resetWorkInProgressVersions();
10814 var fiberRoot = workInProgress.stateNode;
10815
10816 if (fiberRoot.pendingContext) {
10817 fiberRoot.context = fiberRoot.pendingContext;
10818 fiberRoot.pendingContext = null;
10819 }
10820
10821 if (current === null || current.child === null) {
10822 // If we hydrated, pop so that we can delete any remaining children
10823 // that weren't hydrated.
10824 var wasHydrated = popHydrationState();
10825
10826 if (wasHydrated) {
10827 // If we hydrated, then we'll need to schedule an update for
10828 // the commit side-effects on the root.
10829 markUpdate(workInProgress);
10830 } else if (!fiberRoot.hydrate) {
10831 // Schedule an effect to clear this container at the start of the next commit.
10832 // This handles the case of React rendering into a container with previous children.
10833 // It's also safe to do for updates too, because current.child would only be null
10834 // if the previous render was null (so the the container would already be empty).
10835 workInProgress.flags |= Snapshot;
10836 }
10837 }
10838
10839 updateHostContainer(workInProgress);
10840 return null;
10841 }
10842
10843 case HostComponent:
10844 {
10845 popHostContext(workInProgress);
10846 var rootContainerInstance = getRootHostContainer();
10847 var type = workInProgress.type;
10848
10849 if (current !== null && workInProgress.stateNode != null) {
10850 updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);
10851
10852 if (current.ref !== workInProgress.ref) {
10853 markRef$1(workInProgress);
10854 }
10855 } else {
10856 if (!newProps) {
10857 if (!(workInProgress.stateNode !== null)) {
10858 {
10859 throw Error( "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." );
10860 }
10861 } // This can happen when we abort work.
10862
10863
10864 return null;
10865 }
10866
10867 var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context
10868 // "stack" as the parent. Then append children as we go in beginWork
10869 // or completeWork depending on whether we want to add them top->down or
10870 // bottom->up. Top->down is faster in IE11.
10871
10872 var _wasHydrated = popHydrationState();
10873
10874 if (_wasHydrated) {
10875 // TODO: Move this and createInstance step into the beginPhase
10876 // to consolidate.
10877 if (prepareToHydrateHostInstance()) {
10878 // If changes to the hydrated node need to be applied at the
10879 // commit-phase we mark this as such.
10880 markUpdate(workInProgress);
10881 }
10882 } else {
10883 var instance = createInstance(type, newProps);
10884 appendAllChildren(instance, workInProgress, false, false);
10885 workInProgress.stateNode = instance; // Certain renderers require commit-time effects for initial mount.
10886 }
10887
10888 if (workInProgress.ref !== null) {
10889 // If there is a ref on a host node we need to schedule a callback
10890 markRef$1(workInProgress);
10891 }
10892 }
10893
10894 return null;
10895 }
10896
10897 case HostText:
10898 {
10899 var newText = newProps;
10900
10901 if (current && workInProgress.stateNode != null) {
10902 var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need
10903 // to schedule a side-effect to do the updates.
10904
10905 updateHostText$1(current, workInProgress, oldText, newText);
10906 } else {
10907 if (typeof newText !== 'string') {
10908 if (!(workInProgress.stateNode !== null)) {
10909 {
10910 throw Error( "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." );
10911 }
10912 } // This can happen when we abort work.
10913
10914 }
10915
10916 var _rootContainerInstance = getRootHostContainer();
10917
10918 var _currentHostContext = getHostContext();
10919
10920 var _wasHydrated2 = popHydrationState();
10921
10922 if (_wasHydrated2) {
10923 if (prepareToHydrateHostTextInstance()) {
10924 markUpdate(workInProgress);
10925 }
10926 } else {
10927 workInProgress.stateNode = createTextInstance(newText);
10928 }
10929 }
10930
10931 return null;
10932 }
10933
10934 case SuspenseComponent:
10935 {
10936 popSuspenseContext(workInProgress);
10937 var nextState = workInProgress.memoizedState;
10938
10939 if ((workInProgress.flags & DidCapture) !== NoFlags) {
10940 // Something suspended. Re-render with the fallback children.
10941 workInProgress.lanes = renderLanes; // Do not reset the effect list.
10942
10943 if ( (workInProgress.mode & ProfileMode) !== NoMode) {
10944 transferActualDuration(workInProgress);
10945 }
10946
10947 return workInProgress;
10948 }
10949
10950 var nextDidTimeout = nextState !== null;
10951 var prevDidTimeout = false;
10952
10953 if (current === null) {
10954 if (workInProgress.memoizedProps.fallback !== undefined) ;
10955 } else {
10956 var prevState = current.memoizedState;
10957 prevDidTimeout = prevState !== null;
10958 }
10959
10960 if (nextDidTimeout && !prevDidTimeout) {
10961 // If this subtreee is running in blocking mode we can suspend,
10962 // otherwise we won't suspend.
10963 // TODO: This will still suspend a synchronous tree if anything
10964 // in the concurrent tree already suspended during this render.
10965 // This is a known bug.
10966 if ((workInProgress.mode & BlockingMode) !== NoMode) {
10967 // TODO: Move this back to throwException because this is too late
10968 // if this is a large tree which is common for initial loads. We
10969 // don't know if we should restart a render or not until we get
10970 // this marker, and this is too late.
10971 // If this render already had a ping or lower pri updates,
10972 // and this is the first time we know we're going to suspend we
10973 // should be able to immediately restart from within throwException.
10974 var hasInvisibleChildContext = current === null && workInProgress.memoizedProps.unstable_avoidThisFallback !== true;
10975
10976 if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) {
10977 // If this was in an invisible tree or a new render, then showing
10978 // this boundary is ok.
10979 renderDidSuspend();
10980 } else {
10981 // Otherwise, we're going to have to hide content so we should
10982 // suspend for longer if possible.
10983 renderDidSuspendDelayIfPossible();
10984 }
10985 }
10986 }
10987
10988 {
10989 // TODO: Only schedule updates if these values are non equal, i.e. it changed.
10990 if (nextDidTimeout || prevDidTimeout) {
10991 // If this boundary just timed out, schedule an effect to attach a
10992 // retry listener to the promise. This flag is also used to hide the
10993 // primary children. In mutation mode, we also need the flag to
10994 // *unhide* children that were previously hidden, so check if this
10995 // is currently timed out, too.
10996 workInProgress.flags |= Update;
10997 }
10998 }
10999
11000 return null;
11001 }
11002
11003 case HostPortal:
11004 popHostContainer(workInProgress);
11005 updateHostContainer(workInProgress);
11006
11007 if (current === null) {
11008 preparePortalMount(workInProgress.stateNode.containerInfo);
11009 }
11010
11011 return null;
11012
11013 case ContextProvider:
11014 // Pop provider fiber
11015 popProvider(workInProgress);
11016 return null;
11017
11018 case IncompleteClassComponent:
11019 {
11020 // Same as class component case. I put it down here so that the tags are
11021 // sequential to ensure this switch is compiled to a jump table.
11022 var _Component = workInProgress.type;
11023
11024 if (isContextProvider(_Component)) {
11025 popContext(workInProgress);
11026 }
11027
11028 return null;
11029 }
11030
11031 case SuspenseListComponent:
11032 {
11033 popSuspenseContext(workInProgress);
11034 var renderState = workInProgress.memoizedState;
11035
11036 if (renderState === null) {
11037 // We're running in the default, "independent" mode.
11038 // We don't do anything in this mode.
11039 return null;
11040 }
11041
11042 var didSuspendAlready = (workInProgress.flags & DidCapture) !== NoFlags;
11043 var renderedTail = renderState.rendering;
11044
11045 if (renderedTail === null) {
11046 // We just rendered the head.
11047 if (!didSuspendAlready) {
11048 // This is the first pass. We need to figure out if anything is still
11049 // suspended in the rendered set.
11050 // If new content unsuspended, but there's still some content that
11051 // didn't. Then we need to do a second pass that forces everything
11052 // to keep showing their fallbacks.
11053 // We might be suspended if something in this render pass suspended, or
11054 // something in the previous committed pass suspended. Otherwise,
11055 // there's no chance so we can skip the expensive call to
11056 // findFirstSuspended.
11057 var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.flags & DidCapture) === NoFlags);
11058
11059 if (!cannotBeSuspended) {
11060 var row = workInProgress.child;
11061
11062 while (row !== null) {
11063 var suspended = findFirstSuspended(row);
11064
11065 if (suspended !== null) {
11066 didSuspendAlready = true;
11067 workInProgress.flags |= DidCapture;
11068 cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as
11069 // part of the second pass. In that case nothing will subscribe to
11070 // its thennables. Instead, we'll transfer its thennables to the
11071 // SuspenseList so that it can retry if they resolve.
11072 // There might be multiple of these in the list but since we're
11073 // going to wait for all of them anyway, it doesn't really matter
11074 // which ones gets to ping. In theory we could get clever and keep
11075 // track of how many dependencies remain but it gets tricky because
11076 // in the meantime, we can add/remove/change items and dependencies.
11077 // We might bail out of the loop before finding any but that
11078 // doesn't matter since that means that the other boundaries that
11079 // we did find already has their listeners attached.
11080
11081 var newThennables = suspended.updateQueue;
11082
11083 if (newThennables !== null) {
11084 workInProgress.updateQueue = newThennables;
11085 workInProgress.flags |= Update;
11086 } // Rerender the whole list, but this time, we'll force fallbacks
11087 // to stay in place.
11088 // Reset the effect list before doing the second pass since that's now invalid.
11089
11090
11091 if (renderState.lastEffect === null) {
11092 workInProgress.firstEffect = null;
11093 }
11094
11095 workInProgress.lastEffect = renderState.lastEffect; // Reset the child fibers to their original state.
11096
11097 resetChildFibers(workInProgress, renderLanes); // Set up the Suspense Context to force suspense and immediately
11098 // rerender the children.
11099
11100 pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback));
11101 return workInProgress.child;
11102 }
11103
11104 row = row.sibling;
11105 }
11106 }
11107
11108 if (renderState.tail !== null && now() > getRenderTargetTime()) {
11109 // We have already passed our CPU deadline but we still have rows
11110 // left in the tail. We'll just give up further attempts to render
11111 // the main content and only render fallbacks.
11112 workInProgress.flags |= DidCapture;
11113 didSuspendAlready = true;
11114 cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this
11115 // to get it started back up to attempt the next item. While in terms
11116 // of priority this work has the same priority as this current render,
11117 // it's not part of the same transition once the transition has
11118 // committed. If it's sync, we still want to yield so that it can be
11119 // painted. Conceptually, this is really the same as pinging.
11120 // We can use any RetryLane even if it's the one currently rendering
11121 // since we're leaving it behind on this node.
11122
11123 workInProgress.lanes = SomeRetryLane;
11124
11125 {
11126 markSpawnedWork(SomeRetryLane);
11127 }
11128 }
11129 } else {
11130 cutOffTailIfNeeded(renderState, false);
11131 } // Next we're going to render the tail.
11132
11133 } else {
11134 // Append the rendered row to the child list.
11135 if (!didSuspendAlready) {
11136 var _suspended = findFirstSuspended(renderedTail);
11137
11138 if (_suspended !== null) {
11139 workInProgress.flags |= DidCapture;
11140 didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't
11141 // get lost if this row ends up dropped during a second pass.
11142
11143 var _newThennables = _suspended.updateQueue;
11144
11145 if (_newThennables !== null) {
11146 workInProgress.updateQueue = _newThennables;
11147 workInProgress.flags |= Update;
11148 }
11149
11150 cutOffTailIfNeeded(renderState, true); // This might have been modified.
11151
11152 if (renderState.tail === null && renderState.tailMode === 'hidden' && !renderedTail.alternate && !getIsHydrating() // We don't cut it if we're hydrating.
11153 ) {
11154 // We need to delete the row we just rendered.
11155 // Reset the effect list to what it was before we rendered this
11156 // child. The nested children have already appended themselves.
11157 var lastEffect = workInProgress.lastEffect = renderState.lastEffect; // Remove any effects that were appended after this point.
11158
11159 if (lastEffect !== null) {
11160 lastEffect.nextEffect = null;
11161 } // We're done.
11162
11163
11164 return null;
11165 }
11166 } else if ( // The time it took to render last row is greater than the remaining
11167 // time we have to render. So rendering one more row would likely
11168 // exceed it.
11169 now() * 2 - renderState.renderingStartTime > getRenderTargetTime() && renderLanes !== OffscreenLane) {
11170 // We have now passed our CPU deadline and we'll just give up further
11171 // attempts to render the main content and only render fallbacks.
11172 // The assumption is that this is usually faster.
11173 workInProgress.flags |= DidCapture;
11174 didSuspendAlready = true;
11175 cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this
11176 // to get it started back up to attempt the next item. While in terms
11177 // of priority this work has the same priority as this current render,
11178 // it's not part of the same transition once the transition has
11179 // committed. If it's sync, we still want to yield so that it can be
11180 // painted. Conceptually, this is really the same as pinging.
11181 // We can use any RetryLane even if it's the one currently rendering
11182 // since we're leaving it behind on this node.
11183
11184 workInProgress.lanes = SomeRetryLane;
11185
11186 {
11187 markSpawnedWork(SomeRetryLane);
11188 }
11189 }
11190 }
11191
11192 if (renderState.isBackwards) {
11193 // The effect list of the backwards tail will have been added
11194 // to the end. This breaks the guarantee that life-cycles fire in
11195 // sibling order but that isn't a strong guarantee promised by React.
11196 // Especially since these might also just pop in during future commits.
11197 // Append to the beginning of the list.
11198 renderedTail.sibling = workInProgress.child;
11199 workInProgress.child = renderedTail;
11200 } else {
11201 var previousSibling = renderState.last;
11202
11203 if (previousSibling !== null) {
11204 previousSibling.sibling = renderedTail;
11205 } else {
11206 workInProgress.child = renderedTail;
11207 }
11208
11209 renderState.last = renderedTail;
11210 }
11211 }
11212
11213 if (renderState.tail !== null) {
11214 // We still have tail rows to render.
11215 // Pop a row.
11216 var next = renderState.tail;
11217 renderState.rendering = next;
11218 renderState.tail = next.sibling;
11219 renderState.lastEffect = workInProgress.lastEffect;
11220 renderState.renderingStartTime = now();
11221 next.sibling = null; // Restore the context.
11222 // TODO: We can probably just avoid popping it instead and only
11223 // setting it the first time we go from not suspended to suspended.
11224
11225 var suspenseContext = suspenseStackCursor.current;
11226
11227 if (didSuspendAlready) {
11228 suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
11229 } else {
11230 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
11231 }
11232
11233 pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row.
11234
11235 return next;
11236 }
11237
11238 return null;
11239 }
11240
11241 case FundamentalComponent:
11242 {
11243
11244 break;
11245 }
11246
11247 case ScopeComponent:
11248 {
11249
11250 break;
11251 }
11252
11253 case Block:
11254
11255 break;
11256
11257 case OffscreenComponent:
11258 case LegacyHiddenComponent:
11259 {
11260 popRenderLanes(workInProgress);
11261
11262 if (current !== null) {
11263 var _nextState = workInProgress.memoizedState;
11264 var _prevState = current.memoizedState;
11265 var prevIsHidden = _prevState !== null;
11266 var nextIsHidden = _nextState !== null;
11267
11268 if (prevIsHidden !== nextIsHidden && newProps.mode !== 'unstable-defer-without-hiding') {
11269 workInProgress.flags |= Update;
11270 }
11271 }
11272
11273 return null;
11274 }
11275 }
11276
11277 {
11278 {
11279 throw Error( "Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in React. Please file an issue." );
11280 }
11281 }
11282 }
11283
11284 function unwindWork(workInProgress, renderLanes) {
11285 switch (workInProgress.tag) {
11286 case ClassComponent:
11287 {
11288 var Component = workInProgress.type;
11289
11290 if (isContextProvider(Component)) {
11291 popContext(workInProgress);
11292 }
11293
11294 var flags = workInProgress.flags;
11295
11296 if (flags & ShouldCapture) {
11297 workInProgress.flags = flags & ~ShouldCapture | DidCapture;
11298
11299 if ( (workInProgress.mode & ProfileMode) !== NoMode) {
11300 transferActualDuration(workInProgress);
11301 }
11302
11303 return workInProgress;
11304 }
11305
11306 return null;
11307 }
11308
11309 case HostRoot:
11310 {
11311 popHostContainer(workInProgress);
11312 popTopLevelContextObject(workInProgress);
11313 resetWorkInProgressVersions();
11314 var _flags = workInProgress.flags;
11315
11316 if (!((_flags & DidCapture) === NoFlags)) {
11317 {
11318 throw Error( "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." );
11319 }
11320 }
11321
11322 workInProgress.flags = _flags & ~ShouldCapture | DidCapture;
11323 return workInProgress;
11324 }
11325
11326 case HostComponent:
11327 {
11328 // TODO: popHydrationState
11329 popHostContext(workInProgress);
11330 return null;
11331 }
11332
11333 case SuspenseComponent:
11334 {
11335 popSuspenseContext(workInProgress);
11336
11337 var _flags2 = workInProgress.flags;
11338
11339 if (_flags2 & ShouldCapture) {
11340 workInProgress.flags = _flags2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary.
11341
11342 if ( (workInProgress.mode & ProfileMode) !== NoMode) {
11343 transferActualDuration(workInProgress);
11344 }
11345
11346 return workInProgress;
11347 }
11348
11349 return null;
11350 }
11351
11352 case SuspenseListComponent:
11353 {
11354 popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been
11355 // caught by a nested boundary. If not, it should bubble through.
11356
11357 return null;
11358 }
11359
11360 case HostPortal:
11361 popHostContainer(workInProgress);
11362 return null;
11363
11364 case ContextProvider:
11365 popProvider(workInProgress);
11366 return null;
11367
11368 case OffscreenComponent:
11369 case LegacyHiddenComponent:
11370 popRenderLanes(workInProgress);
11371 return null;
11372
11373 default:
11374 return null;
11375 }
11376 }
11377
11378 function unwindInterruptedWork(interruptedWork) {
11379 switch (interruptedWork.tag) {
11380 case ClassComponent:
11381 {
11382 var childContextTypes = interruptedWork.type.childContextTypes;
11383
11384 if (childContextTypes !== null && childContextTypes !== undefined) {
11385 popContext(interruptedWork);
11386 }
11387
11388 break;
11389 }
11390
11391 case HostRoot:
11392 {
11393 popHostContainer(interruptedWork);
11394 popTopLevelContextObject(interruptedWork);
11395 resetWorkInProgressVersions();
11396 break;
11397 }
11398
11399 case HostComponent:
11400 {
11401 popHostContext(interruptedWork);
11402 break;
11403 }
11404
11405 case HostPortal:
11406 popHostContainer(interruptedWork);
11407 break;
11408
11409 case SuspenseComponent:
11410 popSuspenseContext(interruptedWork);
11411 break;
11412
11413 case SuspenseListComponent:
11414 popSuspenseContext(interruptedWork);
11415 break;
11416
11417 case ContextProvider:
11418 popProvider(interruptedWork);
11419 break;
11420
11421 case OffscreenComponent:
11422 case LegacyHiddenComponent:
11423 popRenderLanes(interruptedWork);
11424 break;
11425 }
11426 }
11427
11428 function createCapturedValue(value, source) {
11429 // If the value is an error, call this function immediately after it is thrown
11430 // so the stack is accurate.
11431 return {
11432 value: value,
11433 source: source,
11434 stack: getStackByFiberInDevAndProd(source)
11435 };
11436 }
11437
11438 // This module is forked in different environments.
11439 // By default, return `true` to log errors to the console.
11440 // Forks can return `false` if this isn't desirable.
11441 function showErrorDialog(boundary, errorInfo) {
11442 return true;
11443 }
11444
11445 function logCapturedError(boundary, errorInfo) {
11446 try {
11447 var logError = showErrorDialog(boundary, errorInfo); // Allow injected showErrorDialog() to prevent default console.error logging.
11448 // This enables renderers like ReactNative to better manage redbox behavior.
11449
11450 if (logError === false) {
11451 return;
11452 }
11453
11454 var error = errorInfo.value;
11455
11456 if (true) {
11457 var source = errorInfo.source;
11458 var stack = errorInfo.stack;
11459 var componentStack = stack !== null ? stack : ''; // Browsers support silencing uncaught errors by calling
11460 // `preventDefault()` in window `error` handler.
11461 // We record this information as an expando on the error.
11462
11463 if (error != null && error._suppressLogging) {
11464 if (boundary.tag === ClassComponent) {
11465 // The error is recoverable and was silenced.
11466 // Ignore it and don't print the stack addendum.
11467 // This is handy for testing error boundaries without noise.
11468 return;
11469 } // The error is fatal. Since the silencing might have
11470 // been accidental, we'll surface it anyway.
11471 // However, the browser would have silenced the original error
11472 // so we'll print it first, and then print the stack addendum.
11473
11474
11475 console['error'](error); // Don't transform to our wrapper
11476 // For a more detailed description of this block, see:
11477 // https://github.com/facebook/react/pull/13384
11478 }
11479
11480 var componentName = source ? getComponentName(source.type) : null;
11481 var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : 'The above error occurred in one of your React components:';
11482 var errorBoundaryMessage;
11483 var errorBoundaryName = getComponentName(boundary.type);
11484
11485 if (errorBoundaryName) {
11486 errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + ".");
11487 } else {
11488 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.';
11489 }
11490
11491 var combinedMessage = componentNameMessage + "\n" + componentStack + "\n\n" + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack.
11492 // We don't include the original error message and JS stack because the browser
11493 // has already printed it. Even if the application swallows the error, it is still
11494 // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
11495
11496 console['error'](combinedMessage); // Don't transform to our wrapper
11497 } else {
11498 // In production, we print the error directly.
11499 // This will include the message, the JS stack, and anything the browser wants to show.
11500 // We pass the error object instead of custom message so that the browser displays the error natively.
11501 console['error'](error); // Don't transform to our wrapper
11502 }
11503 } catch (e) {
11504 // This method must not throw, or React internal state will get messed up.
11505 // If console.error is overridden, or logCapturedError() shows a dialog that throws,
11506 // we want to report this error outside of the normal stack as a last resort.
11507 // https://github.com/facebook/react/issues/13188
11508 setTimeout(function () {
11509 throw e;
11510 });
11511 }
11512 }
11513
11514 var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map;
11515
11516 function createRootErrorUpdate(fiber, errorInfo, lane) {
11517 var update = createUpdate(NoTimestamp, lane); // Unmount the root by rendering null.
11518
11519 update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property
11520 // being called "element".
11521
11522 update.payload = {
11523 element: null
11524 };
11525 var error = errorInfo.value;
11526
11527 update.callback = function () {
11528 onUncaughtError(error);
11529 logCapturedError(fiber, errorInfo);
11530 };
11531
11532 return update;
11533 }
11534
11535 function createClassErrorUpdate(fiber, errorInfo, lane) {
11536 var update = createUpdate(NoTimestamp, lane);
11537 update.tag = CaptureUpdate;
11538 var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
11539
11540 if (typeof getDerivedStateFromError === 'function') {
11541 var error$1 = errorInfo.value;
11542
11543 update.payload = function () {
11544 logCapturedError(fiber, errorInfo);
11545 return getDerivedStateFromError(error$1);
11546 };
11547 }
11548
11549 var inst = fiber.stateNode;
11550
11551 if (inst !== null && typeof inst.componentDidCatch === 'function') {
11552 update.callback = function callback() {
11553 {
11554 markFailedErrorBoundaryForHotReloading(fiber);
11555 }
11556
11557 if (typeof getDerivedStateFromError !== 'function') {
11558 // To preserve the preexisting retry behavior of error boundaries,
11559 // we keep track of which ones already failed during this batch.
11560 // This gets reset before we yield back to the browser.
11561 // TODO: Warn in strict mode if getDerivedStateFromError is
11562 // not defined.
11563 markLegacyErrorBoundaryAsFailed(this); // Only log here if componentDidCatch is the only error boundary method defined
11564
11565 logCapturedError(fiber, errorInfo);
11566 }
11567
11568 var error$1 = errorInfo.value;
11569 var stack = errorInfo.stack;
11570 this.componentDidCatch(error$1, {
11571 componentStack: stack !== null ? stack : ''
11572 });
11573
11574 {
11575 if (typeof getDerivedStateFromError !== 'function') {
11576 // If componentDidCatch is the only error boundary method defined,
11577 // then it needs to call setState to recover from errors.
11578 // If no state update is scheduled then the boundary will swallow the error.
11579 if (!includesSomeLane(fiber.lanes, SyncLane)) {
11580 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');
11581 }
11582 }
11583 }
11584 };
11585 } else {
11586 update.callback = function () {
11587 markFailedErrorBoundaryForHotReloading(fiber);
11588 };
11589 }
11590
11591 return update;
11592 }
11593
11594 function attachPingListener(root, wakeable, lanes) {
11595 // Attach a listener to the promise to "ping" the root and retry. But only if
11596 // one does not already exist for the lanes we're currently rendering (which
11597 // acts like a "thread ID" here).
11598 var pingCache = root.pingCache;
11599 var threadIDs;
11600
11601 if (pingCache === null) {
11602 pingCache = root.pingCache = new PossiblyWeakMap$1();
11603 threadIDs = new Set();
11604 pingCache.set(wakeable, threadIDs);
11605 } else {
11606 threadIDs = pingCache.get(wakeable);
11607
11608 if (threadIDs === undefined) {
11609 threadIDs = new Set();
11610 pingCache.set(wakeable, threadIDs);
11611 }
11612 }
11613
11614 if (!threadIDs.has(lanes)) {
11615 // Memoize using the thread ID to prevent redundant listeners.
11616 threadIDs.add(lanes);
11617 var ping = pingSuspendedRoot.bind(null, root, wakeable, lanes);
11618 wakeable.then(ping, ping);
11619 }
11620 }
11621
11622 function throwException(root, returnFiber, sourceFiber, value, rootRenderLanes) {
11623 // The source fiber did not complete.
11624 sourceFiber.flags |= Incomplete; // Its effect list is no longer valid.
11625
11626 sourceFiber.firstEffect = sourceFiber.lastEffect = null;
11627
11628 if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
11629 // This is a wakeable.
11630 var wakeable = value;
11631
11632 if ((sourceFiber.mode & BlockingMode) === NoMode) {
11633 // Reset the memoizedState to what it was before we attempted
11634 // to render it.
11635 var currentSource = sourceFiber.alternate;
11636
11637 if (currentSource) {
11638 sourceFiber.updateQueue = currentSource.updateQueue;
11639 sourceFiber.memoizedState = currentSource.memoizedState;
11640 sourceFiber.lanes = currentSource.lanes;
11641 } else {
11642 sourceFiber.updateQueue = null;
11643 sourceFiber.memoizedState = null;
11644 }
11645 }
11646
11647 var hasInvisibleParentBoundary = hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext); // Schedule the nearest Suspense to re-render the timed out view.
11648
11649 var _workInProgress = returnFiber;
11650
11651 do {
11652 if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress, hasInvisibleParentBoundary)) {
11653 // Found the nearest boundary.
11654 // Stash the promise on the boundary fiber. If the boundary times out, we'll
11655 // attach another listener to flip the boundary back to its normal state.
11656 var wakeables = _workInProgress.updateQueue;
11657
11658 if (wakeables === null) {
11659 var updateQueue = new Set();
11660 updateQueue.add(wakeable);
11661 _workInProgress.updateQueue = updateQueue;
11662 } else {
11663 wakeables.add(wakeable);
11664 } // If the boundary is outside of blocking mode, we should *not*
11665 // suspend the commit. Pretend as if the suspended component rendered
11666 // null and keep rendering. In the commit phase, we'll schedule a
11667 // subsequent synchronous update to re-render the Suspense.
11668 //
11669 // Note: It doesn't matter whether the component that suspended was
11670 // inside a blocking mode tree. If the Suspense is outside of it, we
11671 // should *not* suspend the commit.
11672
11673
11674 if ((_workInProgress.mode & BlockingMode) === NoMode) {
11675 _workInProgress.flags |= DidCapture;
11676 sourceFiber.flags |= ForceUpdateForLegacySuspense; // We're going to commit this fiber even though it didn't complete.
11677 // But we shouldn't call any lifecycle methods or callbacks. Remove
11678 // all lifecycle effect tags.
11679
11680 sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete);
11681
11682 if (sourceFiber.tag === ClassComponent) {
11683 var currentSourceFiber = sourceFiber.alternate;
11684
11685 if (currentSourceFiber === null) {
11686 // This is a new mount. Change the tag so it's not mistaken for a
11687 // completed class component. For example, we should not call
11688 // componentWillUnmount if it is deleted.
11689 sourceFiber.tag = IncompleteClassComponent;
11690 } else {
11691 // When we try rendering again, we should not reuse the current fiber,
11692 // since it's known to be in an inconsistent state. Use a force update to
11693 // prevent a bail out.
11694 var update = createUpdate(NoTimestamp, SyncLane);
11695 update.tag = ForceUpdate;
11696 enqueueUpdate(sourceFiber, update);
11697 }
11698 } // The source fiber did not complete. Mark it with Sync priority to
11699 // indicate that it still has pending work.
11700
11701
11702 sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane); // Exit without suspending.
11703
11704 return;
11705 } // Confirmed that the boundary is in a concurrent mode tree. Continue
11706 // with the normal suspend path.
11707 //
11708 // After this we'll use a set of heuristics to determine whether this
11709 // render pass will run to completion or restart or "suspend" the commit.
11710 // The actual logic for this is spread out in different places.
11711 //
11712 // This first principle is that if we're going to suspend when we complete
11713 // a root, then we should also restart if we get an update or ping that
11714 // might unsuspend it, and vice versa. The only reason to suspend is
11715 // because you think you might want to restart before committing. However,
11716 // it doesn't make sense to restart only while in the period we're suspended.
11717 //
11718 // Restarting too aggressively is also not good because it starves out any
11719 // intermediate loading state. So we use heuristics to determine when.
11720 // Suspense Heuristics
11721 //
11722 // If nothing threw a Promise or all the same fallbacks are already showing,
11723 // then don't suspend/restart.
11724 //
11725 // If this is an initial render of a new tree of Suspense boundaries and
11726 // those trigger a fallback, then don't suspend/restart. We want to ensure
11727 // that we can show the initial loading state as quickly as possible.
11728 //
11729 // If we hit a "Delayed" case, such as when we'd switch from content back into
11730 // a fallback, then we should always suspend/restart. Transitions apply
11731 // to this case. If none is defined, JND is used instead.
11732 //
11733 // If we're already showing a fallback and it gets "retried", allowing us to show
11734 // another level, but there's still an inner boundary that would show a fallback,
11735 // then we suspend/restart for 500ms since the last time we showed a fallback
11736 // anywhere in the tree. This effectively throttles progressive loading into a
11737 // consistent train of commits. This also gives us an opportunity to restart to
11738 // get to the completed state slightly earlier.
11739 //
11740 // If there's ambiguity due to batching it's resolved in preference of:
11741 // 1) "delayed", 2) "initial render", 3) "retry".
11742 //
11743 // We want to ensure that a "busy" state doesn't get force committed. We want to
11744 // ensure that new initial loading states can commit as soon as possible.
11745
11746
11747 attachPingListener(root, wakeable, rootRenderLanes);
11748 _workInProgress.flags |= ShouldCapture;
11749 _workInProgress.lanes = rootRenderLanes;
11750 return;
11751 } // This boundary already captured during this render. Continue to the next
11752 // boundary.
11753
11754
11755 _workInProgress = _workInProgress.return;
11756 } while (_workInProgress !== null); // No boundary was found. Fallthrough to error mode.
11757 // TODO: Use invariant so the message is stripped in prod?
11758
11759
11760 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.');
11761 } // We didn't find a boundary that could handle this type of exception. Start
11762 // over and traverse parent path again, this time treating the exception
11763 // as an error.
11764
11765
11766 renderDidError();
11767 value = createCapturedValue(value, sourceFiber);
11768 var workInProgress = returnFiber;
11769
11770 do {
11771 switch (workInProgress.tag) {
11772 case HostRoot:
11773 {
11774 var _errorInfo = value;
11775 workInProgress.flags |= ShouldCapture;
11776 var lane = pickArbitraryLane(rootRenderLanes);
11777 workInProgress.lanes = mergeLanes(workInProgress.lanes, lane);
11778
11779 var _update = createRootErrorUpdate(workInProgress, _errorInfo, lane);
11780
11781 enqueueCapturedUpdate(workInProgress, _update);
11782 return;
11783 }
11784
11785 case ClassComponent:
11786 // Capture and retry
11787 var errorInfo = value;
11788 var ctor = workInProgress.type;
11789 var instance = workInProgress.stateNode;
11790
11791 if ((workInProgress.flags & DidCapture) === NoFlags && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
11792 workInProgress.flags |= ShouldCapture;
11793
11794 var _lane = pickArbitraryLane(rootRenderLanes);
11795
11796 workInProgress.lanes = mergeLanes(workInProgress.lanes, _lane); // Schedule the error boundary to re-render using updated state
11797
11798 var _update2 = createClassErrorUpdate(workInProgress, errorInfo, _lane);
11799
11800 enqueueCapturedUpdate(workInProgress, _update2);
11801 return;
11802 }
11803
11804 break;
11805 }
11806
11807 workInProgress = workInProgress.return;
11808 } while (workInProgress !== null);
11809 }
11810
11811 function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) {
11812 var funcArgs = Array.prototype.slice.call(arguments, 3);
11813
11814 try {
11815 func.apply(context, funcArgs);
11816 } catch (error) {
11817 this.onError(error);
11818 }
11819 }
11820
11821 var invokeGuardedCallbackImpl = invokeGuardedCallbackProd;
11822
11823 {
11824 // In DEV mode, we swap out invokeGuardedCallback for a special version
11825 // that plays more nicely with the browser's DevTools. The idea is to preserve
11826 // "Pause on exceptions" behavior. Because React wraps all user-provided
11827 // functions in invokeGuardedCallback, and the production version of
11828 // invokeGuardedCallback uses a try-catch, all user exceptions are treated
11829 // like caught exceptions, and the DevTools won't pause unless the developer
11830 // takes the extra step of enabling pause on caught exceptions. This is
11831 // unintuitive, though, because even though React has caught the error, from
11832 // the developer's perspective, the error is uncaught.
11833 //
11834 // To preserve the expected "Pause on exceptions" behavior, we don't use a
11835 // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
11836 // DOM node, and call the user-provided callback from inside an event handler
11837 // for that fake event. If the callback throws, the error is "captured" using
11838 // a global event handler. But because the error happens in a different
11839 // event loop context, it does not interrupt the normal program flow.
11840 // Effectively, this gives us try-catch behavior without actually using
11841 // try-catch. Neat!
11842 // Check that the browser supports the APIs we need to implement our special
11843 // DEV version of invokeGuardedCallback
11844 if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
11845 var fakeNode = document.createElement('react');
11846
11847 invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) {
11848 // If document doesn't exist we know for sure we will crash in this method
11849 // when we call document.createEvent(). However this can cause confusing
11850 // errors: https://github.com/facebookincubator/create-react-app/issues/3482
11851 // So we preemptively throw with a better message instead.
11852 if (!(typeof document !== 'undefined')) {
11853 {
11854 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." );
11855 }
11856 }
11857
11858 var evt = document.createEvent('Event');
11859 var didCall = false; // Keeps track of whether the user-provided callback threw an error. We
11860 // set this to true at the beginning, then set it to false right after
11861 // calling the function. If the function errors, `didError` will never be
11862 // set to false. This strategy works even if the browser is flaky and
11863 // fails to call our global error handler, because it doesn't rely on
11864 // the error event at all.
11865
11866 var didError = true; // Keeps track of the value of window.event so that we can reset it
11867 // during the callback to let user code access window.event in the
11868 // browsers that support it.
11869
11870 var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event
11871 // dispatching: https://github.com/facebook/react/issues/13688
11872
11873 var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event');
11874
11875 function restoreAfterDispatch() {
11876 // We immediately remove the callback from event listeners so that
11877 // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
11878 // nested call would trigger the fake event handlers of any call higher
11879 // in the stack.
11880 fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the
11881 // window.event assignment in both IE <= 10 as they throw an error
11882 // "Member not found" in strict mode, and in Firefox which does not
11883 // support window.event.
11884
11885 if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
11886 window.event = windowEvent;
11887 }
11888 } // Create an event handler for our fake event. We will synchronously
11889 // dispatch our fake event using `dispatchEvent`. Inside the handler, we
11890 // call the user-provided callback.
11891
11892
11893 var funcArgs = Array.prototype.slice.call(arguments, 3);
11894
11895 function callCallback() {
11896 didCall = true;
11897 restoreAfterDispatch();
11898 func.apply(context, funcArgs);
11899 didError = false;
11900 } // Create a global error event handler. We use this to capture the value
11901 // that was thrown. It's possible that this error handler will fire more
11902 // than once; for example, if non-React code also calls `dispatchEvent`
11903 // and a handler for that event throws. We should be resilient to most of
11904 // those cases. Even if our error event handler fires more than once, the
11905 // last error event is always used. If the callback actually does error,
11906 // we know that the last error event is the correct one, because it's not
11907 // possible for anything else to have happened in between our callback
11908 // erroring and the code that follows the `dispatchEvent` call below. If
11909 // the callback doesn't error, but the error event was fired, we know to
11910 // ignore it because `didError` will be false, as described above.
11911
11912
11913 var error; // Use this to track whether the error event is ever called.
11914
11915 var didSetError = false;
11916 var isCrossOriginError = false;
11917
11918 function handleWindowError(event) {
11919 error = event.error;
11920 didSetError = true;
11921
11922 if (error === null && event.colno === 0 && event.lineno === 0) {
11923 isCrossOriginError = true;
11924 }
11925
11926 if (event.defaultPrevented) {
11927 // Some other error handler has prevented default.
11928 // Browsers silence the error report if this happens.
11929 // We'll remember this to later decide whether to log it or not.
11930 if (error != null && typeof error === 'object') {
11931 try {
11932 error._suppressLogging = true;
11933 } catch (inner) {// Ignore.
11934 }
11935 }
11936 }
11937 } // Create a fake event type.
11938
11939
11940 var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers
11941
11942 window.addEventListener('error', handleWindowError);
11943 fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function
11944 // errors, it will trigger our global error handler.
11945
11946 evt.initEvent(evtType, false, false);
11947 fakeNode.dispatchEvent(evt);
11948
11949 if (windowEventDescriptor) {
11950 Object.defineProperty(window, 'event', windowEventDescriptor);
11951 }
11952
11953 if (didCall && didError) {
11954 if (!didSetError) {
11955 // The callback errored, but the error event never fired.
11956 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.');
11957 } else if (isCrossOriginError) {
11958 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.');
11959 }
11960
11961 this.onError(error);
11962 } // Remove our event listeners
11963
11964
11965 window.removeEventListener('error', handleWindowError);
11966
11967 if (!didCall) {
11968 // Something went really wrong, and our event was not dispatched.
11969 // https://github.com/facebook/react/issues/16734
11970 // https://github.com/facebook/react/issues/16585
11971 // Fall back to the production implementation.
11972 restoreAfterDispatch();
11973 return invokeGuardedCallbackProd.apply(this, arguments);
11974 }
11975 };
11976 }
11977 }
11978
11979 var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
11980
11981 var hasError = false;
11982 var caughtError = null; // Used by event system to capture/rethrow the first error.
11983 var reporter = {
11984 onError: function (error) {
11985 hasError = true;
11986 caughtError = error;
11987 }
11988 };
11989 /**
11990 * Call a function while guarding against errors that happens within it.
11991 * Returns an error if it throws, otherwise null.
11992 *
11993 * In production, this is implemented using a try-catch. The reason we don't
11994 * use a try-catch directly is so that we can swap out a different
11995 * implementation in DEV mode.
11996 *
11997 * @param {String} name of the guard to use for logging or debugging
11998 * @param {Function} func The function to invoke
11999 * @param {*} context The context to use when calling the function
12000 * @param {...*} args Arguments for function
12001 */
12002
12003 function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
12004 hasError = false;
12005 caughtError = null;
12006 invokeGuardedCallbackImpl$1.apply(reporter, arguments);
12007 }
12008 function hasCaughtError() {
12009 return hasError;
12010 }
12011 function clearCaughtError() {
12012 if (hasError) {
12013 var error = caughtError;
12014 hasError = false;
12015 caughtError = null;
12016 return error;
12017 } else {
12018 {
12019 {
12020 throw Error( "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." );
12021 }
12022 }
12023 }
12024 }
12025
12026 var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
12027
12028 {
12029 didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
12030 }
12031
12032 var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
12033
12034 var callComponentWillUnmountWithTimer = function (current, instance) {
12035 instance.props = current.memoizedProps;
12036 instance.state = current.memoizedState;
12037
12038 {
12039 instance.componentWillUnmount();
12040 }
12041 }; // Capture errors so they don't interrupt unmounting.
12042
12043
12044 function safelyCallComponentWillUnmount(current, instance) {
12045 {
12046 invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current, instance);
12047
12048 if (hasCaughtError()) {
12049 var unmountError = clearCaughtError();
12050 captureCommitPhaseError(current, unmountError);
12051 }
12052 }
12053 }
12054
12055 function safelyDetachRef(current) {
12056 var ref = current.ref;
12057
12058 if (ref !== null) {
12059 if (typeof ref === 'function') {
12060 {
12061 invokeGuardedCallback(null, ref, null, null);
12062
12063 if (hasCaughtError()) {
12064 var refError = clearCaughtError();
12065 captureCommitPhaseError(current, refError);
12066 }
12067 }
12068 } else {
12069 ref.current = null;
12070 }
12071 }
12072 }
12073
12074 function safelyCallDestroy(current, destroy) {
12075 {
12076 invokeGuardedCallback(null, destroy, null);
12077
12078 if (hasCaughtError()) {
12079 var error = clearCaughtError();
12080 captureCommitPhaseError(current, error);
12081 }
12082 }
12083 }
12084
12085 function commitBeforeMutationLifeCycles(current, finishedWork) {
12086 switch (finishedWork.tag) {
12087 case FunctionComponent:
12088 case ForwardRef:
12089 case SimpleMemoComponent:
12090 case Block:
12091 {
12092 return;
12093 }
12094
12095 case ClassComponent:
12096 {
12097 if (finishedWork.flags & Snapshot) {
12098 if (current !== null) {
12099 var prevProps = current.memoizedProps;
12100 var prevState = current.memoizedState;
12101 var instance = finishedWork.stateNode; // We could update instance props and state here,
12102 // but instead we rely on them being set during last render.
12103 // TODO: revisit this when we implement resuming.
12104
12105 {
12106 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
12107 if (instance.props !== finishedWork.memoizedProps) {
12108 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');
12109 }
12110
12111 if (instance.state !== finishedWork.memoizedState) {
12112 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');
12113 }
12114 }
12115 }
12116
12117 var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
12118
12119 {
12120 var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
12121
12122 if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
12123 didWarnSet.add(finishedWork.type);
12124
12125 error('%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));
12126 }
12127 }
12128
12129 instance.__reactInternalSnapshotBeforeUpdate = snapshot;
12130 }
12131 }
12132
12133 return;
12134 }
12135
12136 case HostRoot:
12137 {
12138 {
12139 if (finishedWork.flags & Snapshot) {
12140 var root = finishedWork.stateNode;
12141 clearContainer(root.containerInfo);
12142 }
12143 }
12144
12145 return;
12146 }
12147
12148 case HostComponent:
12149 case HostText:
12150 case HostPortal:
12151 case IncompleteClassComponent:
12152 // Nothing to do for these component types
12153 return;
12154 }
12155
12156 {
12157 {
12158 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." );
12159 }
12160 }
12161 }
12162
12163 function commitHookEffectListUnmount(tag, finishedWork) {
12164 var updateQueue = finishedWork.updateQueue;
12165 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
12166
12167 if (lastEffect !== null) {
12168 var firstEffect = lastEffect.next;
12169 var effect = firstEffect;
12170
12171 do {
12172 if ((effect.tag & tag) === tag) {
12173 // Unmount
12174 var destroy = effect.destroy;
12175 effect.destroy = undefined;
12176
12177 if (destroy !== undefined) {
12178 destroy();
12179 }
12180 }
12181
12182 effect = effect.next;
12183 } while (effect !== firstEffect);
12184 }
12185 }
12186
12187 function commitHookEffectListMount(tag, finishedWork) {
12188 var updateQueue = finishedWork.updateQueue;
12189 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
12190
12191 if (lastEffect !== null) {
12192 var firstEffect = lastEffect.next;
12193 var effect = firstEffect;
12194
12195 do {
12196 if ((effect.tag & tag) === tag) {
12197 // Mount
12198 var create = effect.create;
12199 effect.destroy = create();
12200
12201 {
12202 var destroy = effect.destroy;
12203
12204 if (destroy !== undefined && typeof destroy !== 'function') {
12205 var addendum = void 0;
12206
12207 if (destroy === null) {
12208 addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
12209 } else if (typeof destroy.then === 'function') {
12210 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';
12211 } else {
12212 addendum = ' You returned: ' + destroy;
12213 }
12214
12215 error('An effect function must not return anything besides a function, ' + 'which is used for clean-up.%s', addendum);
12216 }
12217 }
12218 }
12219
12220 effect = effect.next;
12221 } while (effect !== firstEffect);
12222 }
12223 }
12224
12225 function schedulePassiveEffects(finishedWork) {
12226 var updateQueue = finishedWork.updateQueue;
12227 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
12228
12229 if (lastEffect !== null) {
12230 var firstEffect = lastEffect.next;
12231 var effect = firstEffect;
12232
12233 do {
12234 var _effect = effect,
12235 next = _effect.next,
12236 tag = _effect.tag;
12237
12238 if ((tag & Passive$1) !== NoFlags$1 && (tag & HasEffect) !== NoFlags$1) {
12239 enqueuePendingPassiveHookEffectUnmount(finishedWork, effect);
12240 enqueuePendingPassiveHookEffectMount(finishedWork, effect);
12241 }
12242
12243 effect = next;
12244 } while (effect !== firstEffect);
12245 }
12246 }
12247
12248 function commitLifeCycles(finishedRoot, current, finishedWork, committedLanes) {
12249 switch (finishedWork.tag) {
12250 case FunctionComponent:
12251 case ForwardRef:
12252 case SimpleMemoComponent:
12253 case Block:
12254 {
12255 // At this point layout effects have already been destroyed (during mutation phase).
12256 // This is done to prevent sibling component effects from interfering with each other,
12257 // e.g. a destroy function in one component should never override a ref set
12258 // by a create function in another component during the same commit.
12259 {
12260 commitHookEffectListMount(Layout | HasEffect, finishedWork);
12261 }
12262
12263 schedulePassiveEffects(finishedWork);
12264 return;
12265 }
12266
12267 case ClassComponent:
12268 {
12269 var instance = finishedWork.stateNode;
12270
12271 if (finishedWork.flags & Update) {
12272 if (current === null) {
12273 // We could update instance props and state here,
12274 // but instead we rely on them being set during last render.
12275 // TODO: revisit this when we implement resuming.
12276 {
12277 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
12278 if (instance.props !== finishedWork.memoizedProps) {
12279 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');
12280 }
12281
12282 if (instance.state !== finishedWork.memoizedState) {
12283 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');
12284 }
12285 }
12286 }
12287
12288 {
12289 instance.componentDidMount();
12290 }
12291 } else {
12292 var prevProps = finishedWork.elementType === finishedWork.type ? current.memoizedProps : resolveDefaultProps(finishedWork.type, current.memoizedProps);
12293 var prevState = current.memoizedState; // We could update instance props and state here,
12294 // but instead we rely on them being set during last render.
12295 // TODO: revisit this when we implement resuming.
12296
12297 {
12298 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
12299 if (instance.props !== finishedWork.memoizedProps) {
12300 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');
12301 }
12302
12303 if (instance.state !== finishedWork.memoizedState) {
12304 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');
12305 }
12306 }
12307 }
12308
12309 {
12310 instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
12311 }
12312 }
12313 } // TODO: I think this is now always non-null by the time it reaches the
12314 // commit phase. Consider removing the type check.
12315
12316
12317 var updateQueue = finishedWork.updateQueue;
12318
12319 if (updateQueue !== null) {
12320 {
12321 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
12322 if (instance.props !== finishedWork.memoizedProps) {
12323 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');
12324 }
12325
12326 if (instance.state !== finishedWork.memoizedState) {
12327 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');
12328 }
12329 }
12330 } // We could update instance props and state here,
12331 // but instead we rely on them being set during last render.
12332 // TODO: revisit this when we implement resuming.
12333
12334
12335 commitUpdateQueue(finishedWork, updateQueue, instance);
12336 }
12337
12338 return;
12339 }
12340
12341 case HostRoot:
12342 {
12343 // TODO: I think this is now always non-null by the time it reaches the
12344 // commit phase. Consider removing the type check.
12345 var _updateQueue = finishedWork.updateQueue;
12346
12347 if (_updateQueue !== null) {
12348 var _instance = null;
12349
12350 if (finishedWork.child !== null) {
12351 switch (finishedWork.child.tag) {
12352 case HostComponent:
12353 _instance = getPublicInstance(finishedWork.child.stateNode);
12354 break;
12355
12356 case ClassComponent:
12357 _instance = finishedWork.child.stateNode;
12358 break;
12359 }
12360 }
12361
12362 commitUpdateQueue(finishedWork, _updateQueue, _instance);
12363 }
12364
12365 return;
12366 }
12367
12368 case HostComponent:
12369 {
12370 var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted
12371 // (eg DOM renderer may schedule auto-focus for inputs and form controls).
12372 // These effects should only be committed when components are first mounted,
12373 // aka when there is no current/alternate.
12374
12375 if (current === null && finishedWork.flags & Update) {
12376 var type = finishedWork.type;
12377 var props = finishedWork.memoizedProps;
12378 }
12379
12380 return;
12381 }
12382
12383 case HostText:
12384 {
12385 // We have no life-cycles associated with text.
12386 return;
12387 }
12388
12389 case HostPortal:
12390 {
12391 // We have no life-cycles associated with portals.
12392 return;
12393 }
12394
12395 case Profiler:
12396 {
12397 {
12398 var _finishedWork$memoize2 = finishedWork.memoizedProps,
12399 onCommit = _finishedWork$memoize2.onCommit,
12400 onRender = _finishedWork$memoize2.onRender;
12401 var effectDuration = finishedWork.stateNode.effectDuration;
12402 var commitTime = getCommitTime();
12403
12404 if (typeof onRender === 'function') {
12405 {
12406 onRender(finishedWork.memoizedProps.id, current === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitTime, finishedRoot.memoizedInteractions);
12407 }
12408 }
12409 }
12410
12411 return;
12412 }
12413
12414 case SuspenseComponent:
12415 {
12416 return;
12417 }
12418
12419 case SuspenseListComponent:
12420 case IncompleteClassComponent:
12421 case FundamentalComponent:
12422 case ScopeComponent:
12423 case OffscreenComponent:
12424 case LegacyHiddenComponent:
12425 return;
12426 }
12427
12428 {
12429 {
12430 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." );
12431 }
12432 }
12433 }
12434
12435 function hideOrUnhideAllChildren(finishedWork, isHidden) {
12436 {
12437 // We only have the top Fiber that was inserted but we need to recurse down its
12438 // children to find all the terminal nodes.
12439 var node = finishedWork;
12440
12441 while (true) {
12442 if (node.tag === HostComponent) {
12443 var instance = node.stateNode;
12444
12445 if (isHidden) {
12446 hideInstance(instance);
12447 } else {
12448 unhideInstance(node.stateNode, node.memoizedProps);
12449 }
12450 } else if (node.tag === HostText) {
12451 var _instance3 = node.stateNode;
12452
12453 if (isHidden) ; else {
12454 unhideTextInstance(_instance3, node.memoizedProps);
12455 }
12456 } else if ((node.tag === OffscreenComponent || node.tag === LegacyHiddenComponent) && node.memoizedState !== null && node !== finishedWork) ; else if (node.child !== null) {
12457 node.child.return = node;
12458 node = node.child;
12459 continue;
12460 }
12461
12462 if (node === finishedWork) {
12463 return;
12464 }
12465
12466 while (node.sibling === null) {
12467 if (node.return === null || node.return === finishedWork) {
12468 return;
12469 }
12470
12471 node = node.return;
12472 }
12473
12474 node.sibling.return = node.return;
12475 node = node.sibling;
12476 }
12477 }
12478 }
12479
12480 function commitAttachRef(finishedWork) {
12481 var ref = finishedWork.ref;
12482
12483 if (ref !== null) {
12484 var instance = finishedWork.stateNode;
12485 var instanceToUse;
12486
12487 switch (finishedWork.tag) {
12488 case HostComponent:
12489 instanceToUse = getPublicInstance(instance);
12490 break;
12491
12492 default:
12493 instanceToUse = instance;
12494 } // Moved outside to ensure DCE works with this flag
12495
12496 if (typeof ref === 'function') {
12497 ref(instanceToUse);
12498 } else {
12499 {
12500 if (!ref.hasOwnProperty('current')) {
12501 error('Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().', getComponentName(finishedWork.type));
12502 }
12503 }
12504
12505 ref.current = instanceToUse;
12506 }
12507 }
12508 }
12509
12510 function commitDetachRef(current) {
12511 var currentRef = current.ref;
12512
12513 if (currentRef !== null) {
12514 if (typeof currentRef === 'function') {
12515 currentRef(null);
12516 } else {
12517 currentRef.current = null;
12518 }
12519 }
12520 } // User-originating errors (lifecycles and refs) should not interrupt
12521 // deletion, so don't let them throw. Host-originating errors should
12522 // interrupt deletion, so it's okay
12523
12524
12525 function commitUnmount(finishedRoot, current, renderPriorityLevel) {
12526 onCommitUnmount(current);
12527
12528 switch (current.tag) {
12529 case FunctionComponent:
12530 case ForwardRef:
12531 case MemoComponent:
12532 case SimpleMemoComponent:
12533 case Block:
12534 {
12535 var updateQueue = current.updateQueue;
12536
12537 if (updateQueue !== null) {
12538 var lastEffect = updateQueue.lastEffect;
12539
12540 if (lastEffect !== null) {
12541 var firstEffect = lastEffect.next;
12542 var effect = firstEffect;
12543
12544 do {
12545 var _effect2 = effect,
12546 destroy = _effect2.destroy,
12547 tag = _effect2.tag;
12548
12549 if (destroy !== undefined) {
12550 if ((tag & Passive$1) !== NoFlags$1) {
12551 enqueuePendingPassiveHookEffectUnmount(current, effect);
12552 } else {
12553 {
12554 safelyCallDestroy(current, destroy);
12555 }
12556 }
12557 }
12558
12559 effect = effect.next;
12560 } while (effect !== firstEffect);
12561 }
12562 }
12563
12564 return;
12565 }
12566
12567 case ClassComponent:
12568 {
12569 safelyDetachRef(current);
12570 var instance = current.stateNode;
12571
12572 if (typeof instance.componentWillUnmount === 'function') {
12573 safelyCallComponentWillUnmount(current, instance);
12574 }
12575
12576 return;
12577 }
12578
12579 case HostComponent:
12580 {
12581 safelyDetachRef(current);
12582 return;
12583 }
12584
12585 case HostPortal:
12586 {
12587 // TODO: this is recursive.
12588 // We are also not using this parent because
12589 // the portal will get pushed immediately.
12590 {
12591 unmountHostComponents(finishedRoot, current);
12592 }
12593
12594 return;
12595 }
12596
12597 case FundamentalComponent:
12598 {
12599
12600 return;
12601 }
12602
12603 case DehydratedFragment:
12604 {
12605
12606 return;
12607 }
12608
12609 case ScopeComponent:
12610 {
12611
12612 return;
12613 }
12614 }
12615 }
12616
12617 function commitNestedUnmounts(finishedRoot, root, renderPriorityLevel) {
12618 // While we're inside a removed host node we don't want to call
12619 // removeChild on the inner nodes because they're removed by the top
12620 // call anyway. We also want to call componentWillUnmount on all
12621 // composites before this host node is removed from the tree. Therefore
12622 // we do an inner loop while we're still inside the host node.
12623 var node = root;
12624
12625 while (true) {
12626 commitUnmount(finishedRoot, node); // Visit children because they may contain more composite or host nodes.
12627 // Skip portals because commitUnmount() currently visits them recursively.
12628
12629 if (node.child !== null && ( // If we use mutation we drill down into portals using commitUnmount above.
12630 // If we don't use mutation we drill down into portals here instead.
12631 node.tag !== HostPortal)) {
12632 node.child.return = node;
12633 node = node.child;
12634 continue;
12635 }
12636
12637 if (node === root) {
12638 return;
12639 }
12640
12641 while (node.sibling === null) {
12642 if (node.return === null || node.return === root) {
12643 return;
12644 }
12645
12646 node = node.return;
12647 }
12648
12649 node.sibling.return = node.return;
12650 node = node.sibling;
12651 }
12652 }
12653
12654 function detachFiberMutation(fiber) {
12655 // Cut off the return pointers to disconnect it from the tree. Ideally, we
12656 // should clear the child pointer of the parent alternate to let this
12657 // get GC:ed but we don't know which for sure which parent is the current
12658 // one so we'll settle for GC:ing the subtree of this child. This child
12659 // itself will be GC:ed when the parent updates the next time.
12660 // Note: we cannot null out sibling here, otherwise it can cause issues
12661 // with findDOMNode and how it requires the sibling field to carry out
12662 // traversal in a later effect. See PR #16820. We now clear the sibling
12663 // field after effects, see: detachFiberAfterEffects.
12664 //
12665 // Don't disconnect stateNode now; it will be detached in detachFiberAfterEffects.
12666 // It may be required if the current component is an error boundary,
12667 // and one of its descendants throws while unmounting a passive effect.
12668 fiber.alternate = null;
12669 fiber.child = null;
12670 fiber.dependencies = null;
12671 fiber.firstEffect = null;
12672 fiber.lastEffect = null;
12673 fiber.memoizedProps = null;
12674 fiber.memoizedState = null;
12675 fiber.pendingProps = null;
12676 fiber.return = null;
12677 fiber.updateQueue = null;
12678
12679 {
12680 fiber._debugOwner = null;
12681 }
12682 }
12683
12684 function getHostParentFiber(fiber) {
12685 var parent = fiber.return;
12686
12687 while (parent !== null) {
12688 if (isHostParent(parent)) {
12689 return parent;
12690 }
12691
12692 parent = parent.return;
12693 }
12694
12695 {
12696 {
12697 throw Error( "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." );
12698 }
12699 }
12700 }
12701
12702 function isHostParent(fiber) {
12703 return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
12704 }
12705
12706 function getHostSibling(fiber) {
12707 // We're going to search forward into the tree until we find a sibling host
12708 // node. Unfortunately, if multiple insertions are done in a row we have to
12709 // search past them. This leads to exponential search for the next sibling.
12710 // TODO: Find a more efficient way to do this.
12711 var node = fiber;
12712
12713 siblings: while (true) {
12714 // If we didn't find anything, let's try the next sibling.
12715 while (node.sibling === null) {
12716 if (node.return === null || isHostParent(node.return)) {
12717 // If we pop out of the root or hit the parent the fiber we are the
12718 // last sibling.
12719 return null;
12720 }
12721
12722 node = node.return;
12723 }
12724
12725 node.sibling.return = node.return;
12726 node = node.sibling;
12727
12728 while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) {
12729 // If it is not host node and, we might have a host node inside it.
12730 // Try to search down until we find one.
12731 if (node.flags & Placement) {
12732 // If we don't have a child, try the siblings instead.
12733 continue siblings;
12734 } // If we don't have a child, try the siblings instead.
12735 // We also skip portals because they are not part of this host tree.
12736
12737
12738 if (node.child === null || node.tag === HostPortal) {
12739 continue siblings;
12740 } else {
12741 node.child.return = node;
12742 node = node.child;
12743 }
12744 } // Check if this host node is stable or about to be placed.
12745
12746
12747 if (!(node.flags & Placement)) {
12748 // Found it!
12749 return node.stateNode;
12750 }
12751 }
12752 }
12753
12754 function commitPlacement(finishedWork) {
12755
12756
12757 var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together.
12758
12759 var parent;
12760 var isContainer;
12761 var parentStateNode = parentFiber.stateNode;
12762
12763 switch (parentFiber.tag) {
12764 case HostComponent:
12765 parent = parentStateNode;
12766 isContainer = false;
12767 break;
12768
12769 case HostRoot:
12770 parent = parentStateNode.containerInfo;
12771 isContainer = true;
12772 break;
12773
12774 case HostPortal:
12775 parent = parentStateNode.containerInfo;
12776 isContainer = true;
12777 break;
12778
12779 case FundamentalComponent:
12780
12781 // eslint-disable-next-line-no-fallthrough
12782
12783 default:
12784 {
12785 {
12786 throw Error( "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." );
12787 }
12788 }
12789
12790 }
12791
12792 if (parentFiber.flags & ContentReset) {
12793
12794 parentFiber.flags &= ~ContentReset;
12795 }
12796
12797 var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its
12798 // children to find all the terminal nodes.
12799
12800 if (isContainer) {
12801 insertOrAppendPlacementNodeIntoContainer(finishedWork, before, parent);
12802 } else {
12803 insertOrAppendPlacementNode(finishedWork, before, parent);
12804 }
12805 }
12806
12807 function insertOrAppendPlacementNodeIntoContainer(node, before, parent) {
12808 var tag = node.tag;
12809 var isHost = tag === HostComponent || tag === HostText;
12810
12811 if (isHost || enableFundamentalAPI ) {
12812 var stateNode = isHost ? node.stateNode : node.stateNode.instance;
12813
12814 if (before) {
12815 insertInContainerBefore(parent, stateNode, before);
12816 } else {
12817 appendChildToContainer(parent, stateNode);
12818 }
12819 } else if (tag === HostPortal) ; else {
12820 var child = node.child;
12821
12822 if (child !== null) {
12823 insertOrAppendPlacementNodeIntoContainer(child, before, parent);
12824 var sibling = child.sibling;
12825
12826 while (sibling !== null) {
12827 insertOrAppendPlacementNodeIntoContainer(sibling, before, parent);
12828 sibling = sibling.sibling;
12829 }
12830 }
12831 }
12832 }
12833
12834 function insertOrAppendPlacementNode(node, before, parent) {
12835 var tag = node.tag;
12836 var isHost = tag === HostComponent || tag === HostText;
12837
12838 if (isHost || enableFundamentalAPI ) {
12839 var stateNode = isHost ? node.stateNode : node.stateNode.instance;
12840
12841 if (before) {
12842 insertBefore(parent, stateNode, before);
12843 } else {
12844 appendChild(parent, stateNode);
12845 }
12846 } else if (tag === HostPortal) ; else {
12847 var child = node.child;
12848
12849 if (child !== null) {
12850 insertOrAppendPlacementNode(child, before, parent);
12851 var sibling = child.sibling;
12852
12853 while (sibling !== null) {
12854 insertOrAppendPlacementNode(sibling, before, parent);
12855 sibling = sibling.sibling;
12856 }
12857 }
12858 }
12859 }
12860
12861 function unmountHostComponents(finishedRoot, current, renderPriorityLevel) {
12862 // We only have the top Fiber that was deleted but we need to recurse down its
12863 // children to find all the terminal nodes.
12864 var node = current; // Each iteration, currentParent is populated with node's host parent if not
12865 // currentParentIsValid.
12866
12867 var currentParentIsValid = false; // Note: these two variables *must* always be updated together.
12868
12869 var currentParent;
12870 var currentParentIsContainer;
12871
12872 while (true) {
12873 if (!currentParentIsValid) {
12874 var parent = node.return;
12875
12876 findParent: while (true) {
12877 if (!(parent !== null)) {
12878 {
12879 throw Error( "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." );
12880 }
12881 }
12882
12883 var parentStateNode = parent.stateNode;
12884
12885 switch (parent.tag) {
12886 case HostComponent:
12887 currentParent = parentStateNode;
12888 currentParentIsContainer = false;
12889 break findParent;
12890
12891 case HostRoot:
12892 currentParent = parentStateNode.containerInfo;
12893 currentParentIsContainer = true;
12894 break findParent;
12895
12896 case HostPortal:
12897 currentParent = parentStateNode.containerInfo;
12898 currentParentIsContainer = true;
12899 break findParent;
12900
12901 }
12902
12903 parent = parent.return;
12904 }
12905
12906 currentParentIsValid = true;
12907 }
12908
12909 if (node.tag === HostComponent || node.tag === HostText) {
12910 commitNestedUnmounts(finishedRoot, node); // After all the children have unmounted, it is now safe to remove the
12911 // node from the tree.
12912
12913 if (currentParentIsContainer) {
12914 removeChildFromContainer(currentParent, node.stateNode);
12915 } else {
12916 removeChild(currentParent, node.stateNode);
12917 } // Don't visit children because we already visited them.
12918
12919 } else if (node.tag === HostPortal) {
12920 if (node.child !== null) {
12921 // When we go into a portal, it becomes the parent to remove from.
12922 // We will reassign it back when we pop the portal on the way up.
12923 currentParent = node.stateNode.containerInfo;
12924 currentParentIsContainer = true; // Visit children because portals might contain host components.
12925
12926 node.child.return = node;
12927 node = node.child;
12928 continue;
12929 }
12930 } else {
12931 commitUnmount(finishedRoot, node); // Visit children because we may find more host components below.
12932
12933 if (node.child !== null) {
12934 node.child.return = node;
12935 node = node.child;
12936 continue;
12937 }
12938 }
12939
12940 if (node === current) {
12941 return;
12942 }
12943
12944 while (node.sibling === null) {
12945 if (node.return === null || node.return === current) {
12946 return;
12947 }
12948
12949 node = node.return;
12950
12951 if (node.tag === HostPortal) {
12952 // When we go out of the portal, we need to restore the parent.
12953 // Since we don't keep a stack of them, we will search for it.
12954 currentParentIsValid = false;
12955 }
12956 }
12957
12958 node.sibling.return = node.return;
12959 node = node.sibling;
12960 }
12961 }
12962
12963 function commitDeletion(finishedRoot, current, renderPriorityLevel) {
12964 {
12965 // Recursively delete all host nodes from the parent.
12966 // Detach refs and call componentWillUnmount() on the whole subtree.
12967 unmountHostComponents(finishedRoot, current);
12968 }
12969
12970 var alternate = current.alternate;
12971 detachFiberMutation(current);
12972
12973 if (alternate !== null) {
12974 detachFiberMutation(alternate);
12975 }
12976 }
12977
12978 function commitWork(current, finishedWork) {
12979
12980 switch (finishedWork.tag) {
12981 case FunctionComponent:
12982 case ForwardRef:
12983 case MemoComponent:
12984 case SimpleMemoComponent:
12985 case Block:
12986 {
12987 // Layout effects are destroyed during the mutation phase so that all
12988 // destroy functions for all fibers are called before any create functions.
12989 // This prevents sibling component effects from interfering with each other,
12990 // e.g. a destroy function in one component should never override a ref set
12991 // by a create function in another component during the same commit.
12992 {
12993 commitHookEffectListUnmount(Layout | HasEffect, finishedWork);
12994 }
12995
12996 return;
12997 }
12998
12999 case ClassComponent:
13000 {
13001 return;
13002 }
13003
13004 case HostComponent:
13005 {
13006 var instance = finishedWork.stateNode;
13007
13008 if (instance != null) {
13009 // Commit the work prepared earlier.
13010 var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
13011 // as the newProps. The updatePayload will contain the real change in
13012 // this case.
13013
13014 var oldProps = current !== null ? current.memoizedProps : newProps;
13015 var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components.
13016
13017 var updatePayload = finishedWork.updateQueue;
13018 finishedWork.updateQueue = null;
13019
13020 if (updatePayload !== null) {
13021 commitUpdate(instance, updatePayload, type, oldProps, newProps);
13022 }
13023 }
13024
13025 return;
13026 }
13027
13028 case HostText:
13029 {
13030 if (!(finishedWork.stateNode !== null)) {
13031 {
13032 throw Error( "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." );
13033 }
13034 }
13035
13036 var textInstance = finishedWork.stateNode;
13037 var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
13038 // as the newProps. The updatePayload will contain the real change in
13039 // this case.
13040
13041 var oldText = current !== null ? current.memoizedProps : newText;
13042 return;
13043 }
13044
13045 case HostRoot:
13046 {
13047
13048 return;
13049 }
13050
13051 case Profiler:
13052 {
13053 return;
13054 }
13055
13056 case SuspenseComponent:
13057 {
13058 commitSuspenseComponent(finishedWork);
13059 attachSuspenseRetryListeners(finishedWork);
13060 return;
13061 }
13062
13063 case SuspenseListComponent:
13064 {
13065 attachSuspenseRetryListeners(finishedWork);
13066 return;
13067 }
13068
13069 case IncompleteClassComponent:
13070 {
13071 return;
13072 }
13073
13074 case FundamentalComponent:
13075 {
13076
13077 break;
13078 }
13079
13080 case ScopeComponent:
13081 {
13082
13083 break;
13084 }
13085
13086 case OffscreenComponent:
13087 case LegacyHiddenComponent:
13088 {
13089 var newState = finishedWork.memoizedState;
13090 var isHidden = newState !== null;
13091 hideOrUnhideAllChildren(finishedWork, isHidden);
13092 return;
13093 }
13094 }
13095
13096 {
13097 {
13098 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." );
13099 }
13100 }
13101 }
13102
13103 function commitSuspenseComponent(finishedWork) {
13104 var newState = finishedWork.memoizedState;
13105
13106 if (newState !== null) {
13107 markCommitTimeOfFallback();
13108
13109 {
13110 // Hide the Offscreen component that contains the primary children. TODO:
13111 // Ideally, this effect would have been scheduled on the Offscreen fiber
13112 // itself. That's how unhiding works: the Offscreen component schedules an
13113 // effect on itself. However, in this case, the component didn't complete,
13114 // so the fiber was never added to the effect list in the normal path. We
13115 // could have appended it to the effect list in the Suspense component's
13116 // second pass, but doing it this way is less complicated. This would be
13117 // simpler if we got rid of the effect list and traversed the tree, like
13118 // we're planning to do.
13119 var primaryChildParent = finishedWork.child;
13120 hideOrUnhideAllChildren(primaryChildParent, true);
13121 }
13122 }
13123 }
13124
13125 function attachSuspenseRetryListeners(finishedWork) {
13126 // If this boundary just timed out, then it will have a set of wakeables.
13127 // For each wakeable, attach a listener so that when it resolves, React
13128 // attempts to re-render the boundary in the primary (pre-timeout) state.
13129 var wakeables = finishedWork.updateQueue;
13130
13131 if (wakeables !== null) {
13132 finishedWork.updateQueue = null;
13133 var retryCache = finishedWork.stateNode;
13134
13135 if (retryCache === null) {
13136 retryCache = finishedWork.stateNode = new PossiblyWeakSet();
13137 }
13138
13139 wakeables.forEach(function (wakeable) {
13140 // Memoize using the boundary fiber to prevent redundant listeners.
13141 var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable);
13142
13143 if (!retryCache.has(wakeable)) {
13144 {
13145 if (wakeable.__reactDoNotTraceInteractions !== true) {
13146 retry = unstable_wrap(retry);
13147 }
13148 }
13149
13150 retryCache.add(wakeable);
13151 wakeable.then(retry, retry);
13152 }
13153 });
13154 }
13155 } // This function detects when a Suspense boundary goes from visible to hidden.
13156 // It returns false if the boundary is already hidden.
13157 // TODO: Use an effect tag.
13158
13159
13160 function isSuspenseBoundaryBeingHidden(current, finishedWork) {
13161 if (current !== null) {
13162 var oldState = current.memoizedState;
13163
13164 if (oldState === null || oldState.dehydrated !== null) {
13165 var newState = finishedWork.memoizedState;
13166 return newState !== null && newState.dehydrated === null;
13167 }
13168 }
13169
13170 return false;
13171 }
13172
13173 function commitResetTextContent(current) {
13174
13175 resetTextContent(current.stateNode);
13176 }
13177
13178 var COMPONENT_TYPE = 0;
13179 var HAS_PSEUDO_CLASS_TYPE = 1;
13180 var ROLE_TYPE = 2;
13181 var TEST_NAME_TYPE = 3;
13182 var TEXT_TYPE = 4;
13183
13184 if (typeof Symbol === 'function' && Symbol.for) {
13185 var symbolFor$1 = Symbol.for;
13186 COMPONENT_TYPE = symbolFor$1('selector.component');
13187 HAS_PSEUDO_CLASS_TYPE = symbolFor$1('selector.has_pseudo_class');
13188 ROLE_TYPE = symbolFor$1('selector.role');
13189 TEST_NAME_TYPE = symbolFor$1('selector.test_id');
13190 TEXT_TYPE = symbolFor$1('selector.text');
13191 }
13192
13193 var ceil = Math.ceil;
13194 var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher,
13195 ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner,
13196 IsSomeRendererActing = ReactSharedInternals.IsSomeRendererActing;
13197 var NoContext =
13198 /* */
13199 0;
13200 var BatchedContext =
13201 /* */
13202 1;
13203 var DiscreteEventContext =
13204 /* */
13205 4;
13206 var LegacyUnbatchedContext =
13207 /* */
13208 8;
13209 var RenderContext =
13210 /* */
13211 16;
13212 var CommitContext =
13213 /* */
13214 32;
13215 var RetryAfterError =
13216 /* */
13217 64;
13218 var RootIncomplete = 0;
13219 var RootFatalErrored = 1;
13220 var RootErrored = 2;
13221 var RootSuspended = 3;
13222 var RootSuspendedWithDelay = 4;
13223 var RootCompleted = 5; // Describes where we are in the React execution stack
13224
13225 var executionContext = NoContext; // The root we're working on
13226
13227 var workInProgressRoot = null; // The fiber we're working on
13228
13229 var workInProgress = null; // The lanes we're rendering
13230
13231 var workInProgressRootRenderLanes = NoLanes; // Stack that allows components to change the render lanes for its subtree
13232 // This is a superset of the lanes we started working on at the root. The only
13233 // case where it's different from `workInProgressRootRenderLanes` is when we
13234 // enter a subtree that is hidden and needs to be unhidden: Suspense and
13235 // Offscreen component.
13236 //
13237 // Most things in the work loop should deal with workInProgressRootRenderLanes.
13238 // Most things in begin/complete phases should deal with subtreeRenderLanes.
13239
13240 var subtreeRenderLanes = NoLanes;
13241 var subtreeRenderLanesCursor = createCursor(NoLanes); // Whether to root completed, errored, suspended, etc.
13242
13243 var workInProgressRootExitStatus = RootIncomplete; // A fatal error, if one is thrown
13244
13245 var workInProgressRootFatalError = null; // "Included" lanes refer to lanes that were worked on during this render. It's
13246 // slightly different than `renderLanes` because `renderLanes` can change as you
13247 // enter and exit an Offscreen tree. This value is the combination of all render
13248 // lanes for the entire render phase.
13249
13250 var workInProgressRootIncludedLanes = NoLanes; // The work left over by components that were visited during this render. Only
13251 // includes unprocessed updates, not work in bailed out children.
13252
13253 var workInProgressRootSkippedLanes = NoLanes; // Lanes that were updated (in an interleaved event) during this render.
13254
13255 var workInProgressRootUpdatedLanes = NoLanes; // Lanes that were pinged (in an interleaved event) during this render.
13256
13257 var workInProgressRootPingedLanes = NoLanes;
13258 var mostRecentlyUpdatedRoot = null; // The most recent time we committed a fallback. This lets us ensure a train
13259 // model where we don't commit new loading states in too quick succession.
13260
13261 var globalMostRecentFallbackTime = 0;
13262 var FALLBACK_THROTTLE_MS = 500; // The absolute time for when we should start giving up on rendering
13263 // more and prefer CPU suspense heuristics instead.
13264
13265 var workInProgressRootRenderTargetTime = Infinity; // How long a render is supposed to take before we start following CPU
13266 // suspense heuristics and opt out of rendering more content.
13267
13268 var RENDER_TIMEOUT_MS = 500;
13269
13270 function resetRenderTimer() {
13271 workInProgressRootRenderTargetTime = now() + RENDER_TIMEOUT_MS;
13272 }
13273
13274 function getRenderTargetTime() {
13275 return workInProgressRootRenderTargetTime;
13276 }
13277 var nextEffect = null;
13278 var hasUncaughtError = false;
13279 var firstUncaughtError = null;
13280 var legacyErrorBoundariesThatAlreadyFailed = null;
13281 var rootDoesHavePassiveEffects = false;
13282 var rootWithPendingPassiveEffects = null;
13283 var pendingPassiveEffectsRenderPriority = NoPriority$1;
13284 var pendingPassiveEffectsLanes = NoLanes;
13285 var pendingPassiveHookEffectsMount = [];
13286 var pendingPassiveHookEffectsUnmount = [];
13287 var rootsWithPendingDiscreteUpdates = null; // Use these to prevent an infinite loop of nested updates
13288
13289 var NESTED_UPDATE_LIMIT = 50;
13290 var nestedUpdateCount = 0;
13291 var rootWithNestedUpdates = null;
13292 var NESTED_PASSIVE_UPDATE_LIMIT = 50;
13293 var nestedPassiveUpdateCount = 0; // Marks the need to reschedule pending interactions at these lanes
13294 // during the commit phase. This enables them to be traced across components
13295 // that spawn new work during render. E.g. hidden boundaries, suspended SSR
13296 // hydration or SuspenseList.
13297 // TODO: Can use a bitmask instead of an array
13298
13299 var spawnedWorkDuringRender = null; // If two updates are scheduled within the same event, we should treat their
13300 // event times as simultaneous, even if the actual clock time has advanced
13301 // between the first and second call.
13302
13303 var currentEventTime = NoTimestamp;
13304 var currentEventWipLanes = NoLanes;
13305 var currentEventPendingLanes = NoLanes; // Dev only flag that tracks if passive effects are currently being flushed.
13306 // We warn about state updates for unmounted components differently in this case.
13307
13308 var isFlushingPassiveEffects = false;
13309 var focusedInstanceHandle = null;
13310 var shouldFireAfterActiveInstanceBlur = false;
13311 function getWorkInProgressRoot() {
13312 return workInProgressRoot;
13313 }
13314 function requestEventTime() {
13315 if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
13316 // We're inside React, so it's fine to read the actual time.
13317 return now();
13318 } // We're not inside React, so we may be in the middle of a browser event.
13319
13320
13321 if (currentEventTime !== NoTimestamp) {
13322 // Use the same start time for all updates until we enter React again.
13323 return currentEventTime;
13324 } // This is the first update since React yielded. Compute a new start time.
13325
13326
13327 currentEventTime = now();
13328 return currentEventTime;
13329 }
13330 function requestUpdateLane(fiber) {
13331 // Special cases
13332 var mode = fiber.mode;
13333
13334 if ((mode & BlockingMode) === NoMode) {
13335 return SyncLane;
13336 } else if ((mode & ConcurrentMode) === NoMode) {
13337 return getCurrentPriorityLevel() === ImmediatePriority$1 ? SyncLane : SyncBatchedLane;
13338 } // The algorithm for assigning an update to a lane should be stable for all
13339 // updates at the same priority within the same event. To do this, the inputs
13340 // to the algorithm must be the same. For example, we use the `renderLanes`
13341 // to avoid choosing a lane that is already in the middle of rendering.
13342 //
13343 // However, the "included" lanes could be mutated in between updates in the
13344 // same event, like if you perform an update inside `flushSync`. Or any other
13345 // code path that might call `prepareFreshStack`.
13346 //
13347 // The trick we use is to cache the first of each of these inputs within an
13348 // event. Then reset the cached values once we can be sure the event is over.
13349 // Our heuristic for that is whenever we enter a concurrent work loop.
13350 //
13351 // We'll do the same for `currentEventPendingLanes` below.
13352
13353
13354 if (currentEventWipLanes === NoLanes) {
13355 currentEventWipLanes = workInProgressRootIncludedLanes;
13356 }
13357
13358 var isTransition = requestCurrentTransition() !== NoTransition;
13359
13360 if (isTransition) {
13361 if (currentEventPendingLanes !== NoLanes) {
13362 currentEventPendingLanes = mostRecentlyUpdatedRoot !== null ? mostRecentlyUpdatedRoot.pendingLanes : NoLanes;
13363 }
13364
13365 return findTransitionLane(currentEventWipLanes, currentEventPendingLanes);
13366 } // TODO: Remove this dependency on the Scheduler priority.
13367 // To do that, we're replacing it with an update lane priority.
13368
13369
13370 var schedulerPriority = getCurrentPriorityLevel(); // The old behavior was using the priority level of the Scheduler.
13371 // This couples React to the Scheduler internals, so we're replacing it
13372 // with the currentUpdateLanePriority above. As an example of how this
13373 // could be problematic, if we're not inside `Scheduler.runWithPriority`,
13374 // then we'll get the priority of the current running Scheduler task,
13375 // which is probably not what we want.
13376
13377 var lane;
13378
13379 if ( // TODO: Temporary. We're removing the concept of discrete updates.
13380 (executionContext & DiscreteEventContext) !== NoContext && schedulerPriority === UserBlockingPriority$1) {
13381 lane = findUpdateLane(InputDiscreteLanePriority, currentEventWipLanes);
13382 } else {
13383 var schedulerLanePriority = schedulerPriorityToLanePriority(schedulerPriority);
13384
13385 lane = findUpdateLane(schedulerLanePriority, currentEventWipLanes);
13386 }
13387
13388 return lane;
13389 }
13390
13391 function requestRetryLane(fiber) {
13392 // This is a fork of `requestUpdateLane` designed specifically for Suspense
13393 // "retries" — a special update that attempts to flip a Suspense boundary
13394 // from its placeholder state to its primary/resolved state.
13395 // Special cases
13396 var mode = fiber.mode;
13397
13398 if ((mode & BlockingMode) === NoMode) {
13399 return SyncLane;
13400 } else if ((mode & ConcurrentMode) === NoMode) {
13401 return getCurrentPriorityLevel() === ImmediatePriority$1 ? SyncLane : SyncBatchedLane;
13402 } // See `requestUpdateLane` for explanation of `currentEventWipLanes`
13403
13404
13405 if (currentEventWipLanes === NoLanes) {
13406 currentEventWipLanes = workInProgressRootIncludedLanes;
13407 }
13408
13409 return findRetryLane(currentEventWipLanes);
13410 }
13411
13412 function scheduleUpdateOnFiber(fiber, lane, eventTime) {
13413 checkForNestedUpdates();
13414 warnAboutRenderPhaseUpdatesInDEV(fiber);
13415 var root = markUpdateLaneFromFiberToRoot(fiber, lane);
13416
13417 if (root === null) {
13418 warnAboutUpdateOnUnmountedFiberInDEV(fiber);
13419 return null;
13420 } // Mark that the root has a pending update.
13421
13422
13423 markRootUpdated(root, lane, eventTime);
13424
13425 if (root === workInProgressRoot) {
13426 // Received an update to a tree that's in the middle of rendering. Mark
13427 // that there was an interleaved update work on this root. Unless the
13428 // `deferRenderPhaseUpdateToNextBatch` flag is off and this is a render
13429 // phase update. In that case, we don't treat render phase updates as if
13430 // they were interleaved, for backwards compat reasons.
13431 {
13432 workInProgressRootUpdatedLanes = mergeLanes(workInProgressRootUpdatedLanes, lane);
13433 }
13434
13435 if (workInProgressRootExitStatus === RootSuspendedWithDelay) {
13436 // The root already suspended with a delay, which means this render
13437 // definitely won't finish. Since we have a new update, let's mark it as
13438 // suspended now, right before marking the incoming update. This has the
13439 // effect of interrupting the current render and switching to the update.
13440 // TODO: Make sure this doesn't override pings that happen while we've
13441 // already started rendering.
13442 markRootSuspended$1(root, workInProgressRootRenderLanes);
13443 }
13444 } // TODO: requestUpdateLanePriority also reads the priority. Pass the
13445 // priority as an argument to that function and this one.
13446
13447
13448 var priorityLevel = getCurrentPriorityLevel();
13449
13450 if (lane === SyncLane) {
13451 if ( // Check if we're inside unbatchedUpdates
13452 (executionContext & LegacyUnbatchedContext) !== NoContext && // Check if we're not already rendering
13453 (executionContext & (RenderContext | CommitContext)) === NoContext) {
13454 // Register pending interactions on the root to avoid losing traced interaction data.
13455 schedulePendingInteractions(root, lane); // This is a legacy edge case. The initial mount of a ReactDOM.render-ed
13456 // root inside of batchedUpdates should be synchronous, but layout updates
13457 // should be deferred until the end of the batch.
13458
13459 performSyncWorkOnRoot(root);
13460 } else {
13461 ensureRootIsScheduled(root, eventTime);
13462 schedulePendingInteractions(root, lane);
13463
13464 if (executionContext === NoContext) {
13465 // Flush the synchronous work now, unless we're already working or inside
13466 // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
13467 // scheduleCallbackForFiber to preserve the ability to schedule a callback
13468 // without immediately flushing it. We only do this for user-initiated
13469 // updates, to preserve historical behavior of legacy mode.
13470 resetRenderTimer();
13471 flushSyncCallbackQueue();
13472 }
13473 }
13474 } else {
13475 // Schedule a discrete update but only if it's not Sync.
13476 if ((executionContext & DiscreteEventContext) !== NoContext && ( // Only updates at user-blocking priority or greater are considered
13477 // discrete, even inside a discrete event.
13478 priorityLevel === UserBlockingPriority$1 || priorityLevel === ImmediatePriority$1)) {
13479 // This is the result of a discrete event. Track the lowest priority
13480 // discrete update per root so we can flush them early, if needed.
13481 if (rootsWithPendingDiscreteUpdates === null) {
13482 rootsWithPendingDiscreteUpdates = new Set([root]);
13483 } else {
13484 rootsWithPendingDiscreteUpdates.add(root);
13485 }
13486 } // Schedule other updates after in case the callback is sync.
13487
13488
13489 ensureRootIsScheduled(root, eventTime);
13490 schedulePendingInteractions(root, lane);
13491 } // We use this when assigning a lane for a transition inside
13492 // `requestUpdateLane`. We assume it's the same as the root being updated,
13493 // since in the common case of a single root app it probably is. If it's not
13494 // the same root, then it's not a huge deal, we just might batch more stuff
13495 // together more than necessary.
13496
13497
13498 mostRecentlyUpdatedRoot = root;
13499 } // This is split into a separate function so we can mark a fiber with pending
13500 // work without treating it as a typical update that originates from an event;
13501 // e.g. retrying a Suspense boundary isn't an update, but it does schedule work
13502 // on a fiber.
13503
13504 function markUpdateLaneFromFiberToRoot(sourceFiber, lane) {
13505 // Update the source fiber's lanes
13506 sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane);
13507 var alternate = sourceFiber.alternate;
13508
13509 if (alternate !== null) {
13510 alternate.lanes = mergeLanes(alternate.lanes, lane);
13511 }
13512
13513 {
13514 if (alternate === null && (sourceFiber.flags & (Placement | Hydrating)) !== NoFlags) {
13515 warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
13516 }
13517 } // Walk the parent path to the root and update the child expiration time.
13518
13519
13520 var node = sourceFiber;
13521 var parent = sourceFiber.return;
13522
13523 while (parent !== null) {
13524 parent.childLanes = mergeLanes(parent.childLanes, lane);
13525 alternate = parent.alternate;
13526
13527 if (alternate !== null) {
13528 alternate.childLanes = mergeLanes(alternate.childLanes, lane);
13529 } else {
13530 {
13531 if ((parent.flags & (Placement | Hydrating)) !== NoFlags) {
13532 warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
13533 }
13534 }
13535 }
13536
13537 node = parent;
13538 parent = parent.return;
13539 }
13540
13541 if (node.tag === HostRoot) {
13542 var root = node.stateNode;
13543 return root;
13544 } else {
13545 return null;
13546 }
13547 } // Use this function to schedule a task for a root. There's only one task per
13548 // root; if a task was already scheduled, we'll check to make sure the priority
13549 // of the existing task is the same as the priority of the next level that the
13550 // root has work on. This function is called on every update, and right before
13551 // exiting a task.
13552
13553
13554 function ensureRootIsScheduled(root, currentTime) {
13555 var existingCallbackNode = root.callbackNode; // Check if any lanes are being starved by other work. If so, mark them as
13556 // expired so we know to work on those next.
13557
13558 markStarvedLanesAsExpired(root, currentTime); // Determine the next lanes to work on, and their priority.
13559
13560 var nextLanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); // This returns the priority level computed during the `getNextLanes` call.
13561
13562 var newCallbackPriority = returnNextLanesPriority();
13563
13564 if (nextLanes === NoLanes) {
13565 // Special case: There's nothing to work on.
13566 if (existingCallbackNode !== null) {
13567 cancelCallback(existingCallbackNode);
13568 root.callbackNode = null;
13569 root.callbackPriority = NoLanePriority;
13570 }
13571
13572 return;
13573 } // Check if there's an existing task. We may be able to reuse it.
13574
13575
13576 if (existingCallbackNode !== null) {
13577 var existingCallbackPriority = root.callbackPriority;
13578
13579 if (existingCallbackPriority === newCallbackPriority) {
13580 // The priority hasn't changed. We can reuse the existing task. Exit.
13581 return;
13582 } // The priority changed. Cancel the existing callback. We'll schedule a new
13583 // one below.
13584
13585
13586 cancelCallback(existingCallbackNode);
13587 } // Schedule a new callback.
13588
13589
13590 var newCallbackNode;
13591
13592 if (newCallbackPriority === SyncLanePriority) {
13593 // Special case: Sync React callbacks are scheduled on a special
13594 // internal queue
13595 newCallbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
13596 } else if (newCallbackPriority === SyncBatchedLanePriority) {
13597 newCallbackNode = scheduleCallback(ImmediatePriority$1, performSyncWorkOnRoot.bind(null, root));
13598 } else {
13599 var schedulerPriorityLevel = lanePriorityToSchedulerPriority(newCallbackPriority);
13600 newCallbackNode = scheduleCallback(schedulerPriorityLevel, performConcurrentWorkOnRoot.bind(null, root));
13601 }
13602
13603 root.callbackPriority = newCallbackPriority;
13604 root.callbackNode = newCallbackNode;
13605 } // This is the entry point for every concurrent task, i.e. anything that
13606 // goes through Scheduler.
13607
13608
13609 function performConcurrentWorkOnRoot(root) {
13610 // Since we know we're in a React event, we can clear the current
13611 // event time. The next update will compute a new event time.
13612 currentEventTime = NoTimestamp;
13613 currentEventWipLanes = NoLanes;
13614 currentEventPendingLanes = NoLanes;
13615
13616 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
13617 {
13618 throw Error( "Should not already be working." );
13619 }
13620 } // Flush any pending passive effects before deciding which lanes to work on,
13621 // in case they schedule additional work.
13622
13623
13624 var originalCallbackNode = root.callbackNode;
13625 var didFlushPassiveEffects = flushPassiveEffects();
13626
13627 if (didFlushPassiveEffects) {
13628 // Something in the passive effect phase may have canceled the current task.
13629 // Check if the task node for this root was changed.
13630 if (root.callbackNode !== originalCallbackNode) {
13631 // The current task was canceled. Exit. We don't need to call
13632 // `ensureRootIsScheduled` because the check above implies either that
13633 // there's a new task, or that there's no remaining work on this root.
13634 return null;
13635 }
13636 } // Determine the next expiration time to work on, using the fields stored
13637 // on the root.
13638
13639
13640 var lanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes);
13641
13642 if (lanes === NoLanes) {
13643 // Defensive coding. This is never expected to happen.
13644 return null;
13645 }
13646
13647 var exitStatus = renderRootConcurrent(root, lanes);
13648
13649 if (includesSomeLane(workInProgressRootIncludedLanes, workInProgressRootUpdatedLanes)) {
13650 // The render included lanes that were updated during the render phase.
13651 // For example, when unhiding a hidden tree, we include all the lanes
13652 // that were previously skipped when the tree was hidden. That set of
13653 // lanes is a superset of the lanes we started rendering with.
13654 //
13655 // So we'll throw out the current work and restart.
13656 prepareFreshStack(root, NoLanes);
13657 } else if (exitStatus !== RootIncomplete) {
13658 if (exitStatus === RootErrored) {
13659 executionContext |= RetryAfterError; // If an error occurred during hydration,
13660 // discard server response and fall back to client side render.
13661
13662 if (root.hydrate) {
13663 root.hydrate = false;
13664 clearContainer(root.containerInfo);
13665 } // If something threw an error, try rendering one more time. We'll render
13666 // synchronously to block concurrent data mutations, and we'll includes
13667 // all pending updates are included. If it still fails after the second
13668 // attempt, we'll give up and commit the resulting tree.
13669
13670
13671 lanes = getLanesToRetrySynchronouslyOnError(root);
13672
13673 if (lanes !== NoLanes) {
13674 exitStatus = renderRootSync(root, lanes);
13675 }
13676 }
13677
13678 if (exitStatus === RootFatalErrored) {
13679 var fatalError = workInProgressRootFatalError;
13680 prepareFreshStack(root, NoLanes);
13681 markRootSuspended$1(root, lanes);
13682 ensureRootIsScheduled(root, now());
13683 throw fatalError;
13684 } // We now have a consistent tree. The next step is either to commit it,
13685 // or, if something suspended, wait to commit it after a timeout.
13686
13687
13688 var finishedWork = root.current.alternate;
13689 root.finishedWork = finishedWork;
13690 root.finishedLanes = lanes;
13691 finishConcurrentRender(root, exitStatus, lanes);
13692 }
13693
13694 ensureRootIsScheduled(root, now());
13695
13696 if (root.callbackNode === originalCallbackNode) {
13697 // The task node scheduled for this root is the same one that's
13698 // currently executed. Need to return a continuation.
13699 return performConcurrentWorkOnRoot.bind(null, root);
13700 }
13701
13702 return null;
13703 }
13704
13705 function finishConcurrentRender(root, exitStatus, lanes) {
13706 switch (exitStatus) {
13707 case RootIncomplete:
13708 case RootFatalErrored:
13709 {
13710 {
13711 {
13712 throw Error( "Root did not complete. This is a bug in React." );
13713 }
13714 }
13715 }
13716 // Flow knows about invariant, so it complains if I add a break
13717 // statement, but eslint doesn't know about invariant, so it complains
13718 // if I do. eslint-disable-next-line no-fallthrough
13719
13720 case RootErrored:
13721 {
13722 // We should have already attempted to retry this tree. If we reached
13723 // this point, it errored again. Commit it.
13724 commitRoot(root);
13725 break;
13726 }
13727
13728 case RootSuspended:
13729 {
13730 markRootSuspended$1(root, lanes); // We have an acceptable loading state. We need to figure out if we
13731 // should immediately commit it or wait a bit.
13732
13733 if (includesOnlyRetries(lanes) && // do not delay if we're inside an act() scope
13734 !shouldForceFlushFallbacksInDEV()) {
13735 // This render only included retries, no updates. Throttle committing
13736 // retries so that we don't show too many loading states too quickly.
13737 var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time.
13738
13739 if (msUntilTimeout > 10) {
13740 var nextLanes = getNextLanes(root, NoLanes);
13741
13742 if (nextLanes !== NoLanes) {
13743 // There's additional work on this root.
13744 break;
13745 }
13746
13747 var suspendedLanes = root.suspendedLanes;
13748
13749 if (!isSubsetOfLanes(suspendedLanes, lanes)) {
13750 // We should prefer to render the fallback of at the last
13751 // suspended level. Ping the last suspended level to try
13752 // rendering it again.
13753 // FIXME: What if the suspended lanes are Idle? Should not restart.
13754 var eventTime = requestEventTime();
13755 markRootPinged(root, suspendedLanes);
13756 break;
13757 } // The render is suspended, it hasn't timed out, and there's no
13758 // lower priority work to do. Instead of committing the fallback
13759 // immediately, wait for more data to arrive.
13760
13761
13762 root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), msUntilTimeout);
13763 break;
13764 }
13765 } // The work expired. Commit immediately.
13766
13767
13768 commitRoot(root);
13769 break;
13770 }
13771
13772 case RootSuspendedWithDelay:
13773 {
13774 markRootSuspended$1(root, lanes);
13775
13776 if (includesOnlyTransitions(lanes)) {
13777 // This is a transition, so we should exit without committing a
13778 // placeholder and without scheduling a timeout. Delay indefinitely
13779 // until we receive more data.
13780 break;
13781 }
13782
13783 if (!shouldForceFlushFallbacksInDEV()) {
13784 // This is not a transition, but we did trigger an avoided state.
13785 // Schedule a placeholder to display after a short delay, using the Just
13786 // Noticeable Difference.
13787 // TODO: Is the JND optimization worth the added complexity? If this is
13788 // the only reason we track the event time, then probably not.
13789 // Consider removing.
13790 var mostRecentEventTime = getMostRecentEventTime(root, lanes);
13791 var eventTimeMs = mostRecentEventTime;
13792 var timeElapsedMs = now() - eventTimeMs;
13793
13794 var _msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs; // Don't bother with a very short suspense time.
13795
13796
13797 if (_msUntilTimeout > 10) {
13798 // Instead of committing the fallback immediately, wait for more data
13799 // to arrive.
13800 root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout);
13801 break;
13802 }
13803 } // Commit the placeholder.
13804
13805
13806 commitRoot(root);
13807 break;
13808 }
13809
13810 case RootCompleted:
13811 {
13812 // The work completed. Ready to commit.
13813 commitRoot(root);
13814 break;
13815 }
13816
13817 default:
13818 {
13819 {
13820 {
13821 throw Error( "Unknown root exit status." );
13822 }
13823 }
13824 }
13825 }
13826 }
13827
13828 function markRootSuspended$1(root, suspendedLanes) {
13829 // When suspending, we should always exclude lanes that were pinged or (more
13830 // rarely, since we try to avoid it) updated during the render phase.
13831 // TODO: Lol maybe there's a better way to factor this besides this
13832 // obnoxiously named function :)
13833 suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes);
13834 suspendedLanes = removeLanes(suspendedLanes, workInProgressRootUpdatedLanes);
13835 markRootSuspended(root, suspendedLanes);
13836 } // This is the entry point for synchronous tasks that don't go
13837 // through Scheduler
13838
13839
13840 function performSyncWorkOnRoot(root) {
13841 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
13842 {
13843 throw Error( "Should not already be working." );
13844 }
13845 }
13846
13847 flushPassiveEffects();
13848 var lanes;
13849 var exitStatus;
13850
13851 if (root === workInProgressRoot && includesSomeLane(root.expiredLanes, workInProgressRootRenderLanes)) {
13852 // There's a partial tree, and at least one of its lanes has expired. Finish
13853 // rendering it before rendering the rest of the expired work.
13854 lanes = workInProgressRootRenderLanes;
13855 exitStatus = renderRootSync(root, lanes);
13856
13857 if (includesSomeLane(workInProgressRootIncludedLanes, workInProgressRootUpdatedLanes)) {
13858 // The render included lanes that were updated during the render phase.
13859 // For example, when unhiding a hidden tree, we include all the lanes
13860 // that were previously skipped when the tree was hidden. That set of
13861 // lanes is a superset of the lanes we started rendering with.
13862 //
13863 // Note that this only happens when part of the tree is rendered
13864 // concurrently. If the whole tree is rendered synchronously, then there
13865 // are no interleaved events.
13866 lanes = getNextLanes(root, lanes);
13867 exitStatus = renderRootSync(root, lanes);
13868 }
13869 } else {
13870 lanes = getNextLanes(root, NoLanes);
13871 exitStatus = renderRootSync(root, lanes);
13872 }
13873
13874 if (root.tag !== LegacyRoot && exitStatus === RootErrored) {
13875 executionContext |= RetryAfterError; // If an error occurred during hydration,
13876 // discard server response and fall back to client side render.
13877
13878 if (root.hydrate) {
13879 root.hydrate = false;
13880 clearContainer(root.containerInfo);
13881 } // If something threw an error, try rendering one more time. We'll render
13882 // synchronously to block concurrent data mutations, and we'll includes
13883 // all pending updates are included. If it still fails after the second
13884 // attempt, we'll give up and commit the resulting tree.
13885
13886
13887 lanes = getLanesToRetrySynchronouslyOnError(root);
13888
13889 if (lanes !== NoLanes) {
13890 exitStatus = renderRootSync(root, lanes);
13891 }
13892 }
13893
13894 if (exitStatus === RootFatalErrored) {
13895 var fatalError = workInProgressRootFatalError;
13896 prepareFreshStack(root, NoLanes);
13897 markRootSuspended$1(root, lanes);
13898 ensureRootIsScheduled(root, now());
13899 throw fatalError;
13900 } // We now have a consistent tree. Because this is a sync render, we
13901 // will commit it even if something suspended.
13902
13903
13904 var finishedWork = root.current.alternate;
13905 root.finishedWork = finishedWork;
13906 root.finishedLanes = lanes;
13907 commitRoot(root); // Before exiting, make sure there's a callback scheduled for the next
13908 // pending level.
13909
13910 ensureRootIsScheduled(root, now());
13911 return null;
13912 }
13913 function flushSync(fn, a) {
13914 var prevExecutionContext = executionContext;
13915
13916 if ((prevExecutionContext & (RenderContext | CommitContext)) !== NoContext) {
13917 {
13918 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.');
13919 }
13920
13921 return fn(a);
13922 }
13923
13924 executionContext |= BatchedContext;
13925
13926 {
13927 try {
13928 if (fn) {
13929 return runWithPriority(ImmediatePriority$1, fn.bind(null, a));
13930 } else {
13931 return undefined;
13932 }
13933 } finally {
13934 executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch.
13935 // Note that this will happen even if batchedUpdates is higher up
13936 // the stack.
13937
13938 flushSyncCallbackQueue();
13939 }
13940 }
13941 }
13942 function pushRenderLanes(fiber, lanes) {
13943 push(subtreeRenderLanesCursor, subtreeRenderLanes, fiber);
13944 subtreeRenderLanes = mergeLanes(subtreeRenderLanes, lanes);
13945 workInProgressRootIncludedLanes = mergeLanes(workInProgressRootIncludedLanes, lanes);
13946 }
13947 function popRenderLanes(fiber) {
13948 subtreeRenderLanes = subtreeRenderLanesCursor.current;
13949 pop(subtreeRenderLanesCursor, fiber);
13950 }
13951
13952 function prepareFreshStack(root, lanes) {
13953 root.finishedWork = null;
13954 root.finishedLanes = NoLanes;
13955 var timeoutHandle = root.timeoutHandle;
13956
13957 if (timeoutHandle !== noTimeout) {
13958 // The root previous suspended and scheduled a timeout to commit a fallback
13959 // state. Now that we have additional work, cancel the timeout.
13960 root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
13961
13962 cancelTimeout(timeoutHandle);
13963 }
13964
13965 if (workInProgress !== null) {
13966 var interruptedWork = workInProgress.return;
13967
13968 while (interruptedWork !== null) {
13969 unwindInterruptedWork(interruptedWork);
13970 interruptedWork = interruptedWork.return;
13971 }
13972 }
13973
13974 workInProgressRoot = root;
13975 workInProgress = createWorkInProgress(root.current, null);
13976 workInProgressRootRenderLanes = subtreeRenderLanes = workInProgressRootIncludedLanes = lanes;
13977 workInProgressRootExitStatus = RootIncomplete;
13978 workInProgressRootFatalError = null;
13979 workInProgressRootSkippedLanes = NoLanes;
13980 workInProgressRootUpdatedLanes = NoLanes;
13981 workInProgressRootPingedLanes = NoLanes;
13982
13983 {
13984 spawnedWorkDuringRender = null;
13985 }
13986
13987 {
13988 ReactStrictModeWarnings.discardPendingWarnings();
13989 }
13990 }
13991
13992 function handleError(root, thrownValue) {
13993 do {
13994 var erroredWork = workInProgress;
13995
13996 try {
13997 // Reset module-level state that was set during the render phase.
13998 resetContextDependencies();
13999 resetHooksAfterThrow();
14000 resetCurrentFiber(); // TODO: I found and added this missing line while investigating a
14001 // separate issue. Write a regression test using string refs.
14002
14003 ReactCurrentOwner$2.current = null;
14004
14005 if (erroredWork === null || erroredWork.return === null) {
14006 // Expected to be working on a non-root fiber. This is a fatal error
14007 // because there's no ancestor that can handle it; the root is
14008 // supposed to capture all errors that weren't caught by an error
14009 // boundary.
14010 workInProgressRootExitStatus = RootFatalErrored;
14011 workInProgressRootFatalError = thrownValue; // Set `workInProgress` to null. This represents advancing to the next
14012 // sibling, or the parent if there are no siblings. But since the root
14013 // has no siblings nor a parent, we set it to null. Usually this is
14014 // handled by `completeUnitOfWork` or `unwindWork`, but since we're
14015 // intentionally not calling those, we need set it here.
14016 // TODO: Consider calling `unwindWork` to pop the contexts.
14017
14018 workInProgress = null;
14019 return;
14020 }
14021
14022 if (enableProfilerTimer && erroredWork.mode & ProfileMode) {
14023 // Record the time spent rendering before an error was thrown. This
14024 // avoids inaccurate Profiler durations in the case of a
14025 // suspended render.
14026 stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true);
14027 }
14028
14029 throwException(root, erroredWork.return, erroredWork, thrownValue, workInProgressRootRenderLanes);
14030 completeUnitOfWork(erroredWork);
14031 } catch (yetAnotherThrownValue) {
14032 // Something in the return path also threw.
14033 thrownValue = yetAnotherThrownValue;
14034
14035 if (workInProgress === erroredWork && erroredWork !== null) {
14036 // If this boundary has already errored, then we had trouble processing
14037 // the error. Bubble it to the next boundary.
14038 erroredWork = erroredWork.return;
14039 workInProgress = erroredWork;
14040 } else {
14041 erroredWork = workInProgress;
14042 }
14043
14044 continue;
14045 } // Return to the normal work loop.
14046
14047
14048 return;
14049 } while (true);
14050 }
14051
14052 function pushDispatcher() {
14053 var prevDispatcher = ReactCurrentDispatcher$2.current;
14054 ReactCurrentDispatcher$2.current = ContextOnlyDispatcher;
14055
14056 if (prevDispatcher === null) {
14057 // The React isomorphic package does not include a default dispatcher.
14058 // Instead the first renderer will lazily attach one, in order to give
14059 // nicer error messages.
14060 return ContextOnlyDispatcher;
14061 } else {
14062 return prevDispatcher;
14063 }
14064 }
14065
14066 function popDispatcher(prevDispatcher) {
14067 ReactCurrentDispatcher$2.current = prevDispatcher;
14068 }
14069
14070 function pushInteractions(root) {
14071 {
14072 var prevInteractions = __interactionsRef.current;
14073 __interactionsRef.current = root.memoizedInteractions;
14074 return prevInteractions;
14075 }
14076 }
14077
14078 function popInteractions(prevInteractions) {
14079 {
14080 __interactionsRef.current = prevInteractions;
14081 }
14082 }
14083
14084 function markCommitTimeOfFallback() {
14085 globalMostRecentFallbackTime = now();
14086 }
14087 function markSkippedUpdateLanes(lane) {
14088 workInProgressRootSkippedLanes = mergeLanes(lane, workInProgressRootSkippedLanes);
14089 }
14090 function renderDidSuspend() {
14091 if (workInProgressRootExitStatus === RootIncomplete) {
14092 workInProgressRootExitStatus = RootSuspended;
14093 }
14094 }
14095 function renderDidSuspendDelayIfPossible() {
14096 if (workInProgressRootExitStatus === RootIncomplete || workInProgressRootExitStatus === RootSuspended) {
14097 workInProgressRootExitStatus = RootSuspendedWithDelay;
14098 } // Check if there are updates that we skipped tree that might have unblocked
14099 // this render.
14100
14101
14102 if (workInProgressRoot !== null && (includesNonIdleWork(workInProgressRootSkippedLanes) || includesNonIdleWork(workInProgressRootUpdatedLanes))) {
14103 // Mark the current render as suspended so that we switch to working on
14104 // the updates that were skipped. Usually we only suspend at the end of
14105 // the render phase.
14106 // TODO: We should probably always mark the root as suspended immediately
14107 // (inside this function), since by suspending at the end of the render
14108 // phase introduces a potential mistake where we suspend lanes that were
14109 // pinged or updated while we were rendering.
14110 markRootSuspended$1(workInProgressRoot, workInProgressRootRenderLanes);
14111 }
14112 }
14113 function renderDidError() {
14114 if (workInProgressRootExitStatus !== RootCompleted) {
14115 workInProgressRootExitStatus = RootErrored;
14116 }
14117 } // Called during render to determine if anything has suspended.
14118 // Returns false if we're not sure.
14119
14120 function renderHasNotSuspendedYet() {
14121 // If something errored or completed, we can't really be sure,
14122 // so those are false.
14123 return workInProgressRootExitStatus === RootIncomplete;
14124 }
14125
14126 function renderRootSync(root, lanes) {
14127 var prevExecutionContext = executionContext;
14128 executionContext |= RenderContext;
14129 var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack
14130 // and prepare a fresh one. Otherwise we'll continue where we left off.
14131
14132 if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) {
14133 prepareFreshStack(root, lanes);
14134 startWorkOnPendingInteractions(root, lanes);
14135 }
14136
14137 var prevInteractions = pushInteractions(root);
14138
14139 do {
14140 try {
14141 workLoopSync();
14142 break;
14143 } catch (thrownValue) {
14144 handleError(root, thrownValue);
14145 }
14146 } while (true);
14147
14148 resetContextDependencies();
14149
14150 {
14151 popInteractions(prevInteractions);
14152 }
14153
14154 executionContext = prevExecutionContext;
14155 popDispatcher(prevDispatcher);
14156
14157 if (workInProgress !== null) {
14158 // This is a sync render, so we should have finished the whole tree.
14159 {
14160 {
14161 throw Error( "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." );
14162 }
14163 }
14164 }
14165
14166
14167 workInProgressRoot = null;
14168 workInProgressRootRenderLanes = NoLanes;
14169 return workInProgressRootExitStatus;
14170 } // The work loop is an extremely hot path. Tell Closure not to inline it.
14171
14172 /** @noinline */
14173
14174
14175 function workLoopSync() {
14176 // Already timed out, so perform work without checking if we need to yield.
14177 while (workInProgress !== null) {
14178 performUnitOfWork(workInProgress);
14179 }
14180 }
14181
14182 function renderRootConcurrent(root, lanes) {
14183 var prevExecutionContext = executionContext;
14184 executionContext |= RenderContext;
14185 var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack
14186 // and prepare a fresh one. Otherwise we'll continue where we left off.
14187
14188 if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) {
14189 resetRenderTimer();
14190 prepareFreshStack(root, lanes);
14191 startWorkOnPendingInteractions(root, lanes);
14192 }
14193
14194 var prevInteractions = pushInteractions(root);
14195
14196 do {
14197 try {
14198 workLoopConcurrent();
14199 break;
14200 } catch (thrownValue) {
14201 handleError(root, thrownValue);
14202 }
14203 } while (true);
14204
14205 resetContextDependencies();
14206
14207 {
14208 popInteractions(prevInteractions);
14209 }
14210
14211 popDispatcher(prevDispatcher);
14212 executionContext = prevExecutionContext;
14213
14214
14215 if (workInProgress !== null) {
14216
14217 return RootIncomplete;
14218 } else {
14219
14220
14221 workInProgressRoot = null;
14222 workInProgressRootRenderLanes = NoLanes; // Return the final exit status.
14223
14224 return workInProgressRootExitStatus;
14225 }
14226 }
14227 /** @noinline */
14228
14229
14230 function workLoopConcurrent() {
14231 // Perform work until Scheduler asks us to yield
14232 while (workInProgress !== null && !shouldYield()) {
14233 performUnitOfWork(workInProgress);
14234 }
14235 }
14236
14237 function performUnitOfWork(unitOfWork) {
14238 // The current, flushed, state of this fiber is the alternate. Ideally
14239 // nothing should rely on this, but relying on it here means that we don't
14240 // need an additional field on the work in progress.
14241 var current = unitOfWork.alternate;
14242 setCurrentFiber(unitOfWork);
14243 var next;
14244
14245 if ( (unitOfWork.mode & ProfileMode) !== NoMode) {
14246 startProfilerTimer(unitOfWork);
14247 next = beginWork$1(current, unitOfWork, subtreeRenderLanes);
14248 stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
14249 } else {
14250 next = beginWork$1(current, unitOfWork, subtreeRenderLanes);
14251 }
14252
14253 resetCurrentFiber();
14254 unitOfWork.memoizedProps = unitOfWork.pendingProps;
14255
14256 if (next === null) {
14257 // If this doesn't spawn new work, complete the current work.
14258 completeUnitOfWork(unitOfWork);
14259 } else {
14260 workInProgress = next;
14261 }
14262
14263 ReactCurrentOwner$2.current = null;
14264 }
14265
14266 function completeUnitOfWork(unitOfWork) {
14267 // Attempt to complete the current unit of work, then move to the next
14268 // sibling. If there are no more siblings, return to the parent fiber.
14269 var completedWork = unitOfWork;
14270
14271 do {
14272 // The current, flushed, state of this fiber is the alternate. Ideally
14273 // nothing should rely on this, but relying on it here means that we don't
14274 // need an additional field on the work in progress.
14275 var current = completedWork.alternate;
14276 var returnFiber = completedWork.return; // Check if the work completed or if something threw.
14277
14278 if ((completedWork.flags & Incomplete) === NoFlags) {
14279 setCurrentFiber(completedWork);
14280 var next = void 0;
14281
14282 if ( (completedWork.mode & ProfileMode) === NoMode) {
14283 next = completeWork(current, completedWork, subtreeRenderLanes);
14284 } else {
14285 startProfilerTimer(completedWork);
14286 next = completeWork(current, completedWork, subtreeRenderLanes); // Update render duration assuming we didn't error.
14287
14288 stopProfilerTimerIfRunningAndRecordDelta(completedWork, false);
14289 }
14290
14291 resetCurrentFiber();
14292
14293 if (next !== null) {
14294 // Completing this fiber spawned new work. Work on that next.
14295 workInProgress = next;
14296 return;
14297 }
14298
14299 resetChildLanes(completedWork);
14300
14301 if (returnFiber !== null && // Do not append effects to parents if a sibling failed to complete
14302 (returnFiber.flags & Incomplete) === NoFlags) {
14303 // Append all the effects of the subtree and this fiber onto the effect
14304 // list of the parent. The completion order of the children affects the
14305 // side-effect order.
14306 if (returnFiber.firstEffect === null) {
14307 returnFiber.firstEffect = completedWork.firstEffect;
14308 }
14309
14310 if (completedWork.lastEffect !== null) {
14311 if (returnFiber.lastEffect !== null) {
14312 returnFiber.lastEffect.nextEffect = completedWork.firstEffect;
14313 }
14314
14315 returnFiber.lastEffect = completedWork.lastEffect;
14316 } // If this fiber had side-effects, we append it AFTER the children's
14317 // side-effects. We can perform certain side-effects earlier if needed,
14318 // by doing multiple passes over the effect list. We don't want to
14319 // schedule our own side-effect on our own list because if end up
14320 // reusing children we'll schedule this effect onto itself since we're
14321 // at the end.
14322
14323
14324 var flags = completedWork.flags; // Skip both NoWork and PerformedWork tags when creating the effect
14325 // list. PerformedWork effect is read by React DevTools but shouldn't be
14326 // committed.
14327
14328 if (flags > PerformedWork) {
14329 if (returnFiber.lastEffect !== null) {
14330 returnFiber.lastEffect.nextEffect = completedWork;
14331 } else {
14332 returnFiber.firstEffect = completedWork;
14333 }
14334
14335 returnFiber.lastEffect = completedWork;
14336 }
14337 }
14338 } else {
14339 // This fiber did not complete because something threw. Pop values off
14340 // the stack without entering the complete phase. If this is a boundary,
14341 // capture values if possible.
14342 var _next = unwindWork(completedWork); // Because this fiber did not complete, don't reset its expiration time.
14343
14344
14345 if (_next !== null) {
14346 // If completing this work spawned new work, do that next. We'll come
14347 // back here again.
14348 // Since we're restarting, remove anything that is not a host effect
14349 // from the effect tag.
14350 _next.flags &= HostEffectMask;
14351 workInProgress = _next;
14352 return;
14353 }
14354
14355 if ( (completedWork.mode & ProfileMode) !== NoMode) {
14356 // Record the render duration for the fiber that errored.
14357 stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); // Include the time spent working on failed children before continuing.
14358
14359 var actualDuration = completedWork.actualDuration;
14360 var child = completedWork.child;
14361
14362 while (child !== null) {
14363 actualDuration += child.actualDuration;
14364 child = child.sibling;
14365 }
14366
14367 completedWork.actualDuration = actualDuration;
14368 }
14369
14370 if (returnFiber !== null) {
14371 // Mark the parent fiber as incomplete and clear its effect list.
14372 returnFiber.firstEffect = returnFiber.lastEffect = null;
14373 returnFiber.flags |= Incomplete;
14374 }
14375 }
14376
14377 var siblingFiber = completedWork.sibling;
14378
14379 if (siblingFiber !== null) {
14380 // If there is more work to do in this returnFiber, do that next.
14381 workInProgress = siblingFiber;
14382 return;
14383 } // Otherwise, return to the parent
14384
14385
14386 completedWork = returnFiber; // Update the next thing we're working on in case something throws.
14387
14388 workInProgress = completedWork;
14389 } while (completedWork !== null); // We've reached the root.
14390
14391
14392 if (workInProgressRootExitStatus === RootIncomplete) {
14393 workInProgressRootExitStatus = RootCompleted;
14394 }
14395 }
14396
14397 function resetChildLanes(completedWork) {
14398 if ( // TODO: Move this check out of the hot path by moving `resetChildLanes`
14399 // to switch statement in `completeWork`.
14400 (completedWork.tag === LegacyHiddenComponent || completedWork.tag === OffscreenComponent) && completedWork.memoizedState !== null && !includesSomeLane(subtreeRenderLanes, OffscreenLane) && (completedWork.mode & ConcurrentMode) !== NoLanes) {
14401 // The children of this component are hidden. Don't bubble their
14402 // expiration times.
14403 return;
14404 }
14405
14406 var newChildLanes = NoLanes; // Bubble up the earliest expiration time.
14407
14408 if ( (completedWork.mode & ProfileMode) !== NoMode) {
14409 // In profiling mode, resetChildExpirationTime is also used to reset
14410 // profiler durations.
14411 var actualDuration = completedWork.actualDuration;
14412 var treeBaseDuration = completedWork.selfBaseDuration; // When a fiber is cloned, its actualDuration is reset to 0. This value will
14413 // only be updated if work is done on the fiber (i.e. it doesn't bailout).
14414 // When work is done, it should bubble to the parent's actualDuration. If
14415 // the fiber has not been cloned though, (meaning no work was done), then
14416 // this value will reflect the amount of time spent working on a previous
14417 // render. In that case it should not bubble. We determine whether it was
14418 // cloned by comparing the child pointer.
14419
14420 var shouldBubbleActualDurations = completedWork.alternate === null || completedWork.child !== completedWork.alternate.child;
14421 var child = completedWork.child;
14422
14423 while (child !== null) {
14424 newChildLanes = mergeLanes(newChildLanes, mergeLanes(child.lanes, child.childLanes));
14425
14426 if (shouldBubbleActualDurations) {
14427 actualDuration += child.actualDuration;
14428 }
14429
14430 treeBaseDuration += child.treeBaseDuration;
14431 child = child.sibling;
14432 }
14433
14434 var isTimedOutSuspense = completedWork.tag === SuspenseComponent && completedWork.memoizedState !== null;
14435
14436 if (isTimedOutSuspense) {
14437 // Don't count time spent in a timed out Suspense subtree as part of the base duration.
14438 var primaryChildFragment = completedWork.child;
14439
14440 if (primaryChildFragment !== null) {
14441 treeBaseDuration -= primaryChildFragment.treeBaseDuration;
14442 }
14443 }
14444
14445 completedWork.actualDuration = actualDuration;
14446 completedWork.treeBaseDuration = treeBaseDuration;
14447 } else {
14448 var _child = completedWork.child;
14449
14450 while (_child !== null) {
14451 newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child.lanes, _child.childLanes));
14452 _child = _child.sibling;
14453 }
14454 }
14455
14456 completedWork.childLanes = newChildLanes;
14457 }
14458
14459 function commitRoot(root) {
14460 var renderPriorityLevel = getCurrentPriorityLevel();
14461 runWithPriority(ImmediatePriority$1, commitRootImpl.bind(null, root, renderPriorityLevel));
14462 return null;
14463 }
14464
14465 function commitRootImpl(root, renderPriorityLevel) {
14466 do {
14467 // `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which
14468 // means `flushPassiveEffects` will sometimes result in additional
14469 // passive effects. So we need to keep flushing in a loop until there are
14470 // no more pending effects.
14471 // TODO: Might be better if `flushPassiveEffects` did not automatically
14472 // flush synchronous work at the end, to avoid factoring hazards like this.
14473 flushPassiveEffects();
14474 } while (rootWithPendingPassiveEffects !== null);
14475
14476 flushRenderPhaseStrictModeWarningsInDEV();
14477
14478 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
14479 {
14480 throw Error( "Should not already be working." );
14481 }
14482 }
14483
14484 var finishedWork = root.finishedWork;
14485 var lanes = root.finishedLanes;
14486
14487 if (finishedWork === null) {
14488
14489 return null;
14490 }
14491
14492 root.finishedWork = null;
14493 root.finishedLanes = NoLanes;
14494
14495 if (!(finishedWork !== root.current)) {
14496 {
14497 throw Error( "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." );
14498 }
14499 } // commitRoot never returns a continuation; it always finishes synchronously.
14500 // So we can clear these now to allow a new callback to be scheduled.
14501
14502
14503 root.callbackNode = null; // Update the first and last pending times on this root. The new first
14504 // pending time is whatever is left on the root fiber.
14505
14506 var remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes);
14507 markRootFinished(root, remainingLanes); // Clear already finished discrete updates in case that a later call of
14508 // `flushDiscreteUpdates` starts a useless render pass which may cancels
14509 // a scheduled timeout.
14510
14511 if (rootsWithPendingDiscreteUpdates !== null) {
14512 if (!hasDiscreteLanes(remainingLanes) && rootsWithPendingDiscreteUpdates.has(root)) {
14513 rootsWithPendingDiscreteUpdates.delete(root);
14514 }
14515 }
14516
14517 if (root === workInProgressRoot) {
14518 // We can reset these now that they are finished.
14519 workInProgressRoot = null;
14520 workInProgress = null;
14521 workInProgressRootRenderLanes = NoLanes;
14522 } // Get the list of effects.
14523
14524
14525 var firstEffect;
14526
14527 if (finishedWork.flags > PerformedWork) {
14528 // A fiber's effect list consists only of its children, not itself. So if
14529 // the root has an effect, we need to add it to the end of the list. The
14530 // resulting list is the set that would belong to the root's parent, if it
14531 // had one; that is, all the effects in the tree including the root.
14532 if (finishedWork.lastEffect !== null) {
14533 finishedWork.lastEffect.nextEffect = finishedWork;
14534 firstEffect = finishedWork.firstEffect;
14535 } else {
14536 firstEffect = finishedWork;
14537 }
14538 } else {
14539 // There is no effect on the root.
14540 firstEffect = finishedWork.firstEffect;
14541 }
14542
14543 if (firstEffect !== null) {
14544
14545 var prevExecutionContext = executionContext;
14546 executionContext |= CommitContext;
14547 var prevInteractions = pushInteractions(root); // Reset this to null before calling lifecycles
14548
14549 ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass
14550 // of the effect list for each phase: all mutation effects come before all
14551 // layout effects, and so on.
14552 // The first phase a "before mutation" phase. We use this phase to read the
14553 // state of the host tree right before we mutate it. This is where
14554 // getSnapshotBeforeUpdate is called.
14555
14556 focusedInstanceHandle = prepareForCommit(root.containerInfo);
14557 shouldFireAfterActiveInstanceBlur = false;
14558 nextEffect = firstEffect;
14559
14560 do {
14561 {
14562 invokeGuardedCallback(null, commitBeforeMutationEffects, null);
14563
14564 if (hasCaughtError()) {
14565 if (!(nextEffect !== null)) {
14566 {
14567 throw Error( "Should be working on an effect." );
14568 }
14569 }
14570
14571 var error = clearCaughtError();
14572 captureCommitPhaseError(nextEffect, error);
14573 nextEffect = nextEffect.nextEffect;
14574 }
14575 }
14576 } while (nextEffect !== null); // We no longer need to track the active instance fiber
14577
14578
14579 focusedInstanceHandle = null;
14580
14581 {
14582 // Mark the current commit time to be shared by all Profilers in this
14583 // batch. This enables them to be grouped later.
14584 recordCommitTime();
14585 } // The next phase is the mutation phase, where we mutate the host tree.
14586
14587
14588 nextEffect = firstEffect;
14589
14590 do {
14591 {
14592 invokeGuardedCallback(null, commitMutationEffects, null, root, renderPriorityLevel);
14593
14594 if (hasCaughtError()) {
14595 if (!(nextEffect !== null)) {
14596 {
14597 throw Error( "Should be working on an effect." );
14598 }
14599 }
14600
14601 var _error = clearCaughtError();
14602
14603 captureCommitPhaseError(nextEffect, _error);
14604 nextEffect = nextEffect.nextEffect;
14605 }
14606 }
14607 } while (nextEffect !== null);
14608
14609 resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after
14610 // the mutation phase, so that the previous tree is still current during
14611 // componentWillUnmount, but before the layout phase, so that the finished
14612 // work is current during componentDidMount/Update.
14613
14614 root.current = finishedWork; // The next phase is the layout phase, where we call effects that read
14615 // the host tree after it's been mutated. The idiomatic use case for this is
14616 // layout, but class component lifecycles also fire here for legacy reasons.
14617
14618 nextEffect = firstEffect;
14619
14620 do {
14621 {
14622 invokeGuardedCallback(null, commitLayoutEffects, null, root, lanes);
14623
14624 if (hasCaughtError()) {
14625 if (!(nextEffect !== null)) {
14626 {
14627 throw Error( "Should be working on an effect." );
14628 }
14629 }
14630
14631 var _error2 = clearCaughtError();
14632
14633 captureCommitPhaseError(nextEffect, _error2);
14634 nextEffect = nextEffect.nextEffect;
14635 }
14636 }
14637 } while (nextEffect !== null);
14638
14639 nextEffect = null; // Tell Scheduler to yield at the end of the frame, so the browser has an
14640 // opportunity to paint.
14641
14642 requestPaint();
14643
14644 {
14645 popInteractions(prevInteractions);
14646 }
14647
14648 executionContext = prevExecutionContext;
14649 } else {
14650 // No effects.
14651 root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were
14652 // no effects.
14653 // TODO: Maybe there's a better way to report this.
14654
14655 {
14656 recordCommitTime();
14657 }
14658 }
14659
14660 var rootDidHavePassiveEffects = rootDoesHavePassiveEffects;
14661
14662 if (rootDoesHavePassiveEffects) {
14663 // This commit has passive effects. Stash a reference to them. But don't
14664 // schedule a callback until after flushing layout work.
14665 rootDoesHavePassiveEffects = false;
14666 rootWithPendingPassiveEffects = root;
14667 pendingPassiveEffectsLanes = lanes;
14668 pendingPassiveEffectsRenderPriority = renderPriorityLevel;
14669 } else {
14670 // We are done with the effect chain at this point so let's clear the
14671 // nextEffect pointers to assist with GC. If we have passive effects, we'll
14672 // clear this in flushPassiveEffects.
14673 nextEffect = firstEffect;
14674
14675 while (nextEffect !== null) {
14676 var nextNextEffect = nextEffect.nextEffect;
14677 nextEffect.nextEffect = null;
14678
14679 if (nextEffect.flags & Deletion) {
14680 detachFiberAfterEffects(nextEffect);
14681 }
14682
14683 nextEffect = nextNextEffect;
14684 }
14685 } // Read this again, since an effect might have updated it
14686
14687
14688 remainingLanes = root.pendingLanes; // Check if there's remaining work on this root
14689
14690 if (remainingLanes !== NoLanes) {
14691 {
14692 if (spawnedWorkDuringRender !== null) {
14693 var expirationTimes = spawnedWorkDuringRender;
14694 spawnedWorkDuringRender = null;
14695
14696 for (var i = 0; i < expirationTimes.length; i++) {
14697 scheduleInteractions(root, expirationTimes[i], root.memoizedInteractions);
14698 }
14699 }
14700
14701 schedulePendingInteractions(root, remainingLanes);
14702 }
14703 } else {
14704 // If there's no remaining work, we can clear the set of already failed
14705 // error boundaries.
14706 legacyErrorBoundariesThatAlreadyFailed = null;
14707 }
14708
14709 {
14710 if (!rootDidHavePassiveEffects) {
14711 // If there are no passive effects, then we can complete the pending interactions.
14712 // Otherwise, we'll wait until after the passive effects are flushed.
14713 // Wait to do this until after remaining work has been scheduled,
14714 // so that we don't prematurely signal complete for interactions when there's e.g. hidden work.
14715 finishPendingInteractions(root, lanes);
14716 }
14717 }
14718
14719 if (remainingLanes === SyncLane) {
14720 // Count the number of times the root synchronously re-renders without
14721 // finishing. If there are too many, it indicates an infinite update loop.
14722 if (root === rootWithNestedUpdates) {
14723 nestedUpdateCount++;
14724 } else {
14725 nestedUpdateCount = 0;
14726 rootWithNestedUpdates = root;
14727 }
14728 } else {
14729 nestedUpdateCount = 0;
14730 }
14731
14732 onCommitRoot(finishedWork.stateNode, renderPriorityLevel);
14733 // additional work on this root is scheduled.
14734
14735
14736 ensureRootIsScheduled(root, now());
14737
14738 if (hasUncaughtError) {
14739 hasUncaughtError = false;
14740 var _error3 = firstUncaughtError;
14741 firstUncaughtError = null;
14742 throw _error3;
14743 }
14744
14745 if ((executionContext & LegacyUnbatchedContext) !== NoContext) {
14746 // a ReactDOM.render-ed root inside of batchedUpdates. The commit fired
14747 // synchronously, but layout updates should be deferred until the end
14748 // of the batch.
14749
14750
14751 return null;
14752 } // If layout work was scheduled, flush it now.
14753
14754
14755 flushSyncCallbackQueue();
14756
14757 return null;
14758 }
14759
14760 function commitBeforeMutationEffects() {
14761 while (nextEffect !== null) {
14762 var current = nextEffect.alternate;
14763
14764 if (!shouldFireAfterActiveInstanceBlur && focusedInstanceHandle !== null) {
14765 if ((nextEffect.flags & Deletion) !== NoFlags) {
14766 if (doesFiberContain(nextEffect, focusedInstanceHandle)) {
14767 shouldFireAfterActiveInstanceBlur = true;
14768 }
14769 } else {
14770 // TODO: Move this out of the hot path using a dedicated effect tag.
14771 if (nextEffect.tag === SuspenseComponent && isSuspenseBoundaryBeingHidden(current, nextEffect) && doesFiberContain(nextEffect, focusedInstanceHandle)) {
14772 shouldFireAfterActiveInstanceBlur = true;
14773 }
14774 }
14775 }
14776
14777 var flags = nextEffect.flags;
14778
14779 if ((flags & Snapshot) !== NoFlags) {
14780 setCurrentFiber(nextEffect);
14781 commitBeforeMutationLifeCycles(current, nextEffect);
14782 resetCurrentFiber();
14783 }
14784
14785 if ((flags & Passive) !== NoFlags) {
14786 // If there are passive effects, schedule a callback to flush at
14787 // the earliest opportunity.
14788 if (!rootDoesHavePassiveEffects) {
14789 rootDoesHavePassiveEffects = true;
14790 scheduleCallback(NormalPriority$1, function () {
14791 flushPassiveEffects();
14792 return null;
14793 });
14794 }
14795 }
14796
14797 nextEffect = nextEffect.nextEffect;
14798 }
14799 }
14800
14801 function commitMutationEffects(root, renderPriorityLevel) {
14802 // TODO: Should probably move the bulk of this function to commitWork.
14803 while (nextEffect !== null) {
14804 setCurrentFiber(nextEffect);
14805 var flags = nextEffect.flags;
14806
14807 if (flags & ContentReset) {
14808 commitResetTextContent(nextEffect);
14809 }
14810
14811 if (flags & Ref) {
14812 var current = nextEffect.alternate;
14813
14814 if (current !== null) {
14815 commitDetachRef(current);
14816 }
14817 } // The following switch statement is only concerned about placement,
14818 // updates, and deletions. To avoid needing to add a case for every possible
14819 // bitmap value, we remove the secondary effects from the effect tag and
14820 // switch on that value.
14821
14822
14823 var primaryFlags = flags & (Placement | Update | Deletion | Hydrating);
14824
14825 switch (primaryFlags) {
14826 case Placement:
14827 {
14828 commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is
14829 // inserted, before any life-cycles like componentDidMount gets called.
14830 // TODO: findDOMNode doesn't rely on this any more but isMounted does
14831 // and isMounted is deprecated anyway so we should be able to kill this.
14832
14833 nextEffect.flags &= ~Placement;
14834 break;
14835 }
14836
14837 case PlacementAndUpdate:
14838 {
14839 // Placement
14840 commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is
14841 // inserted, before any life-cycles like componentDidMount gets called.
14842
14843 nextEffect.flags &= ~Placement; // Update
14844
14845 var _current = nextEffect.alternate;
14846 commitWork(_current, nextEffect);
14847 break;
14848 }
14849
14850 case Hydrating:
14851 {
14852 nextEffect.flags &= ~Hydrating;
14853 break;
14854 }
14855
14856 case HydratingAndUpdate:
14857 {
14858 nextEffect.flags &= ~Hydrating; // Update
14859
14860 var _current2 = nextEffect.alternate;
14861 commitWork(_current2, nextEffect);
14862 break;
14863 }
14864
14865 case Update:
14866 {
14867 var _current3 = nextEffect.alternate;
14868 commitWork(_current3, nextEffect);
14869 break;
14870 }
14871
14872 case Deletion:
14873 {
14874 commitDeletion(root, nextEffect);
14875 break;
14876 }
14877 }
14878
14879 resetCurrentFiber();
14880 nextEffect = nextEffect.nextEffect;
14881 }
14882 }
14883
14884 function commitLayoutEffects(root, committedLanes) {
14885
14886
14887 while (nextEffect !== null) {
14888 setCurrentFiber(nextEffect);
14889 var flags = nextEffect.flags;
14890
14891 if (flags & (Update | Callback)) {
14892 var current = nextEffect.alternate;
14893 commitLifeCycles(root, current, nextEffect);
14894 }
14895
14896 {
14897 if (flags & Ref) {
14898 commitAttachRef(nextEffect);
14899 }
14900 }
14901
14902 resetCurrentFiber();
14903 nextEffect = nextEffect.nextEffect;
14904 }
14905 }
14906
14907 function flushPassiveEffects() {
14908 // Returns whether passive effects were flushed.
14909 if (pendingPassiveEffectsRenderPriority !== NoPriority$1) {
14910 var priorityLevel = pendingPassiveEffectsRenderPriority > NormalPriority$1 ? NormalPriority$1 : pendingPassiveEffectsRenderPriority;
14911 pendingPassiveEffectsRenderPriority = NoPriority$1;
14912
14913 {
14914 return runWithPriority(priorityLevel, flushPassiveEffectsImpl);
14915 }
14916 }
14917
14918 return false;
14919 }
14920 function enqueuePendingPassiveHookEffectMount(fiber, effect) {
14921 pendingPassiveHookEffectsMount.push(effect, fiber);
14922
14923 if (!rootDoesHavePassiveEffects) {
14924 rootDoesHavePassiveEffects = true;
14925 scheduleCallback(NormalPriority$1, function () {
14926 flushPassiveEffects();
14927 return null;
14928 });
14929 }
14930 }
14931 function enqueuePendingPassiveHookEffectUnmount(fiber, effect) {
14932 pendingPassiveHookEffectsUnmount.push(effect, fiber);
14933
14934 {
14935 fiber.flags |= PassiveUnmountPendingDev;
14936 var alternate = fiber.alternate;
14937
14938 if (alternate !== null) {
14939 alternate.flags |= PassiveUnmountPendingDev;
14940 }
14941 }
14942
14943 if (!rootDoesHavePassiveEffects) {
14944 rootDoesHavePassiveEffects = true;
14945 scheduleCallback(NormalPriority$1, function () {
14946 flushPassiveEffects();
14947 return null;
14948 });
14949 }
14950 }
14951
14952 function invokePassiveEffectCreate(effect) {
14953 var create = effect.create;
14954 effect.destroy = create();
14955 }
14956
14957 function flushPassiveEffectsImpl() {
14958 if (rootWithPendingPassiveEffects === null) {
14959 return false;
14960 }
14961
14962 var root = rootWithPendingPassiveEffects;
14963 var lanes = pendingPassiveEffectsLanes;
14964 rootWithPendingPassiveEffects = null;
14965 pendingPassiveEffectsLanes = NoLanes;
14966
14967 if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
14968 {
14969 throw Error( "Cannot flush passive effects while already rendering." );
14970 }
14971 }
14972
14973 {
14974 isFlushingPassiveEffects = true;
14975 }
14976
14977 var prevExecutionContext = executionContext;
14978 executionContext |= CommitContext;
14979 var prevInteractions = pushInteractions(root); // It's important that ALL pending passive effect destroy functions are called
14980 // before ANY passive effect create functions are called.
14981 // Otherwise effects in sibling components might interfere with each other.
14982 // e.g. a destroy function in one component may unintentionally override a ref
14983 // value set by a create function in another component.
14984 // Layout effects have the same constraint.
14985 // First pass: Destroy stale passive effects.
14986
14987 var unmountEffects = pendingPassiveHookEffectsUnmount;
14988 pendingPassiveHookEffectsUnmount = [];
14989
14990 for (var i = 0; i < unmountEffects.length; i += 2) {
14991 var _effect = unmountEffects[i];
14992 var fiber = unmountEffects[i + 1];
14993 var destroy = _effect.destroy;
14994 _effect.destroy = undefined;
14995
14996 {
14997 fiber.flags &= ~PassiveUnmountPendingDev;
14998 var alternate = fiber.alternate;
14999
15000 if (alternate !== null) {
15001 alternate.flags &= ~PassiveUnmountPendingDev;
15002 }
15003 }
15004
15005 if (typeof destroy === 'function') {
15006 {
15007 setCurrentFiber(fiber);
15008
15009 {
15010 invokeGuardedCallback(null, destroy, null);
15011 }
15012
15013 if (hasCaughtError()) {
15014 if (!(fiber !== null)) {
15015 {
15016 throw Error( "Should be working on an effect." );
15017 }
15018 }
15019
15020 var error = clearCaughtError();
15021 captureCommitPhaseError(fiber, error);
15022 }
15023
15024 resetCurrentFiber();
15025 }
15026 }
15027 } // Second pass: Create new passive effects.
15028
15029
15030 var mountEffects = pendingPassiveHookEffectsMount;
15031 pendingPassiveHookEffectsMount = [];
15032
15033 for (var _i = 0; _i < mountEffects.length; _i += 2) {
15034 var _effect2 = mountEffects[_i];
15035 var _fiber = mountEffects[_i + 1];
15036
15037 {
15038 setCurrentFiber(_fiber);
15039
15040 {
15041 invokeGuardedCallback(null, invokePassiveEffectCreate, null, _effect2);
15042 }
15043
15044 if (hasCaughtError()) {
15045 if (!(_fiber !== null)) {
15046 {
15047 throw Error( "Should be working on an effect." );
15048 }
15049 }
15050
15051 var _error4 = clearCaughtError();
15052
15053 captureCommitPhaseError(_fiber, _error4);
15054 }
15055
15056 resetCurrentFiber();
15057 }
15058 } // Note: This currently assumes there are no passive effects on the root fiber
15059 // because the root is not part of its own effect list.
15060 // This could change in the future.
15061
15062
15063 var effect = root.current.firstEffect;
15064
15065 while (effect !== null) {
15066 var nextNextEffect = effect.nextEffect; // Remove nextEffect pointer to assist GC
15067
15068 effect.nextEffect = null;
15069
15070 if (effect.flags & Deletion) {
15071 detachFiberAfterEffects(effect);
15072 }
15073
15074 effect = nextNextEffect;
15075 }
15076
15077 {
15078 popInteractions(prevInteractions);
15079 finishPendingInteractions(root, lanes);
15080 }
15081
15082 {
15083 isFlushingPassiveEffects = false;
15084 }
15085
15086 executionContext = prevExecutionContext;
15087 flushSyncCallbackQueue(); // If additional passive effects were scheduled, increment a counter. If this
15088 // exceeds the limit, we'll fire a warning.
15089
15090 nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1;
15091 return true;
15092 }
15093
15094 function isAlreadyFailedLegacyErrorBoundary(instance) {
15095 return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
15096 }
15097 function markLegacyErrorBoundaryAsFailed(instance) {
15098 if (legacyErrorBoundariesThatAlreadyFailed === null) {
15099 legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
15100 } else {
15101 legacyErrorBoundariesThatAlreadyFailed.add(instance);
15102 }
15103 }
15104
15105 function prepareToThrowUncaughtError(error) {
15106 if (!hasUncaughtError) {
15107 hasUncaughtError = true;
15108 firstUncaughtError = error;
15109 }
15110 }
15111
15112 var onUncaughtError = prepareToThrowUncaughtError;
15113
15114 function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
15115 var errorInfo = createCapturedValue(error, sourceFiber);
15116 var update = createRootErrorUpdate(rootFiber, errorInfo, SyncLane);
15117 enqueueUpdate(rootFiber, update);
15118 var eventTime = requestEventTime();
15119 var root = markUpdateLaneFromFiberToRoot(rootFiber, SyncLane);
15120
15121 if (root !== null) {
15122 markRootUpdated(root, SyncLane, eventTime);
15123 ensureRootIsScheduled(root, eventTime);
15124 schedulePendingInteractions(root, SyncLane);
15125 }
15126 }
15127
15128 function captureCommitPhaseError(sourceFiber, error) {
15129 if (sourceFiber.tag === HostRoot) {
15130 // Error was thrown at the root. There is no parent, so the root
15131 // itself should capture it.
15132 captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
15133 return;
15134 }
15135
15136 var fiber = sourceFiber.return;
15137
15138 while (fiber !== null) {
15139 if (fiber.tag === HostRoot) {
15140 captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error);
15141 return;
15142 } else if (fiber.tag === ClassComponent) {
15143 var ctor = fiber.type;
15144 var instance = fiber.stateNode;
15145
15146 if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
15147 var errorInfo = createCapturedValue(error, sourceFiber);
15148 var update = createClassErrorUpdate(fiber, errorInfo, SyncLane);
15149 enqueueUpdate(fiber, update);
15150 var eventTime = requestEventTime();
15151 var root = markUpdateLaneFromFiberToRoot(fiber, SyncLane);
15152
15153 if (root !== null) {
15154 markRootUpdated(root, SyncLane, eventTime);
15155 ensureRootIsScheduled(root, eventTime);
15156 schedulePendingInteractions(root, SyncLane);
15157 } else {
15158 // This component has already been unmounted.
15159 // We can't schedule any follow up work for the root because the fiber is already unmounted,
15160 // but we can still call the log-only boundary so the error isn't swallowed.
15161 //
15162 // TODO This is only a temporary bandaid for the old reconciler fork.
15163 // We can delete this special case once the new fork is merged.
15164 if (typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
15165 try {
15166 instance.componentDidCatch(error, errorInfo);
15167 } catch (errorToIgnore) {// TODO Ignore this error? Rethrow it?
15168 // This is kind of an edge case.
15169 }
15170 }
15171 }
15172
15173 return;
15174 }
15175 }
15176
15177 fiber = fiber.return;
15178 }
15179 }
15180 function pingSuspendedRoot(root, wakeable, pingedLanes) {
15181 var pingCache = root.pingCache;
15182
15183 if (pingCache !== null) {
15184 // The wakeable resolved, so we no longer need to memoize, because it will
15185 // never be thrown again.
15186 pingCache.delete(wakeable);
15187 }
15188
15189 var eventTime = requestEventTime();
15190 markRootPinged(root, pingedLanes);
15191
15192 if (workInProgressRoot === root && isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)) {
15193 // Received a ping at the same priority level at which we're currently
15194 // rendering. We might want to restart this render. This should mirror
15195 // the logic of whether or not a root suspends once it completes.
15196 // TODO: If we're rendering sync either due to Sync, Batched or expired,
15197 // we should probably never restart.
15198 // If we're suspended with delay, or if it's a retry, we'll always suspend
15199 // so we can always restart.
15200 if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && includesOnlyRetries(workInProgressRootRenderLanes) && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) {
15201 // Restart from the root.
15202 prepareFreshStack(root, NoLanes);
15203 } else {
15204 // Even though we can't restart right now, we might get an
15205 // opportunity later. So we mark this render as having a ping.
15206 workInProgressRootPingedLanes = mergeLanes(workInProgressRootPingedLanes, pingedLanes);
15207 }
15208 }
15209
15210 ensureRootIsScheduled(root, eventTime);
15211 schedulePendingInteractions(root, pingedLanes);
15212 }
15213
15214 function retryTimedOutBoundary(boundaryFiber, retryLane) {
15215 // The boundary fiber (a Suspense component or SuspenseList component)
15216 // previously was rendered in its fallback state. One of the promises that
15217 // suspended it has resolved, which means at least part of the tree was
15218 // likely unblocked. Try rendering again, at a new expiration time.
15219 if (retryLane === NoLane) {
15220 retryLane = requestRetryLane(boundaryFiber);
15221 } // TODO: Special case idle priority?
15222
15223
15224 var eventTime = requestEventTime();
15225 var root = markUpdateLaneFromFiberToRoot(boundaryFiber, retryLane);
15226
15227 if (root !== null) {
15228 markRootUpdated(root, retryLane, eventTime);
15229 ensureRootIsScheduled(root, eventTime);
15230 schedulePendingInteractions(root, retryLane);
15231 }
15232 }
15233 function resolveRetryWakeable(boundaryFiber, wakeable) {
15234 var retryLane = NoLane; // Default
15235
15236 var retryCache;
15237
15238 {
15239 retryCache = boundaryFiber.stateNode;
15240 }
15241
15242 if (retryCache !== null) {
15243 // The wakeable resolved, so we no longer need to memoize, because it will
15244 // never be thrown again.
15245 retryCache.delete(wakeable);
15246 }
15247
15248 retryTimedOutBoundary(boundaryFiber, retryLane);
15249 } // Computes the next Just Noticeable Difference (JND) boundary.
15250 // The theory is that a person can't tell the difference between small differences in time.
15251 // Therefore, if we wait a bit longer than necessary that won't translate to a noticeable
15252 // difference in the experience. However, waiting for longer might mean that we can avoid
15253 // showing an intermediate loading state. The longer we have already waited, the harder it
15254 // is to tell small differences in time. Therefore, the longer we've already waited,
15255 // the longer we can wait additionally. At some point we have to give up though.
15256 // We pick a train model where the next boundary commits at a consistent schedule.
15257 // These particular numbers are vague estimates. We expect to adjust them based on research.
15258
15259 function jnd(timeElapsed) {
15260 return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960;
15261 }
15262
15263 function checkForNestedUpdates() {
15264 if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
15265 nestedUpdateCount = 0;
15266 rootWithNestedUpdates = null;
15267
15268 {
15269 {
15270 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." );
15271 }
15272 }
15273 }
15274
15275 {
15276 if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
15277 nestedPassiveUpdateCount = 0;
15278
15279 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.');
15280 }
15281 }
15282 }
15283
15284 function flushRenderPhaseStrictModeWarningsInDEV() {
15285 {
15286 ReactStrictModeWarnings.flushLegacyContextWarning();
15287
15288 {
15289 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
15290 }
15291 }
15292 }
15293
15294 var didWarnStateUpdateForNotYetMountedComponent = null;
15295
15296 function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) {
15297 {
15298 if ((executionContext & RenderContext) !== NoContext) {
15299 // We let the other warning about render phase updates deal with this one.
15300 return;
15301 }
15302
15303 if (!(fiber.mode & (BlockingMode | ConcurrentMode))) {
15304 return;
15305 }
15306
15307 var tag = fiber.tag;
15308
15309 if (tag !== IndeterminateComponent && tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent && tag !== Block) {
15310 // Only warn for user-defined components, not internal ones like Suspense.
15311 return;
15312 } // We show the whole stack but dedupe on the top component's name because
15313 // the problematic code almost always lies inside that component.
15314
15315
15316 var componentName = getComponentName(fiber.type) || 'ReactComponent';
15317
15318 if (didWarnStateUpdateForNotYetMountedComponent !== null) {
15319 if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) {
15320 return;
15321 }
15322
15323 didWarnStateUpdateForNotYetMountedComponent.add(componentName);
15324 } else {
15325 didWarnStateUpdateForNotYetMountedComponent = new Set([componentName]);
15326 }
15327
15328 var previousFiber = current$1;
15329
15330 try {
15331 setCurrentFiber(fiber);
15332
15333 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.');
15334 } finally {
15335 if (previousFiber) {
15336 setCurrentFiber(fiber);
15337 } else {
15338 resetCurrentFiber();
15339 }
15340 }
15341 }
15342 }
15343
15344 var didWarnStateUpdateForUnmountedComponent = null;
15345
15346 function warnAboutUpdateOnUnmountedFiberInDEV(fiber) {
15347 {
15348 var tag = fiber.tag;
15349
15350 if (tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent && tag !== Block) {
15351 // Only warn for user-defined components, not internal ones like Suspense.
15352 return;
15353 } // If there are pending passive effects unmounts for this Fiber,
15354 // we can assume that they would have prevented this update.
15355
15356
15357 if ((fiber.flags & PassiveUnmountPendingDev) !== NoFlags) {
15358 return;
15359 } // We show the whole stack but dedupe on the top component's name because
15360 // the problematic code almost always lies inside that component.
15361
15362
15363 var componentName = getComponentName(fiber.type) || 'ReactComponent';
15364
15365 if (didWarnStateUpdateForUnmountedComponent !== null) {
15366 if (didWarnStateUpdateForUnmountedComponent.has(componentName)) {
15367 return;
15368 }
15369
15370 didWarnStateUpdateForUnmountedComponent.add(componentName);
15371 } else {
15372 didWarnStateUpdateForUnmountedComponent = new Set([componentName]);
15373 }
15374
15375 if (isFlushingPassiveEffects) ; else {
15376 var previousFiber = current$1;
15377
15378 try {
15379 setCurrentFiber(fiber);
15380
15381 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');
15382 } finally {
15383 if (previousFiber) {
15384 setCurrentFiber(fiber);
15385 } else {
15386 resetCurrentFiber();
15387 }
15388 }
15389 }
15390 }
15391 }
15392
15393 var beginWork$1;
15394
15395 {
15396 var dummyFiber = null;
15397
15398 beginWork$1 = function (current, unitOfWork, lanes) {
15399 // If a component throws an error, we replay it again in a synchronously
15400 // dispatched event, so that the debugger will treat it as an uncaught
15401 // error See ReactErrorUtils for more information.
15402 // Before entering the begin phase, copy the work-in-progress onto a dummy
15403 // fiber. If beginWork throws, we'll use this to reset the state.
15404 var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);
15405
15406 try {
15407 return beginWork(current, unitOfWork, lanes);
15408 } catch (originalError) {
15409 if (originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') {
15410 // Don't replay promises. Treat everything else like an error.
15411 throw originalError;
15412 } // Keep this code in sync with handleError; any changes here must have
15413 // corresponding changes there.
15414
15415
15416 resetContextDependencies();
15417 resetHooksAfterThrow(); // Don't reset current debug fiber, since we're about to work on the
15418 // same fiber again.
15419 // Unwind the failed stack frame
15420
15421 unwindInterruptedWork(unitOfWork); // Restore the original properties of the fiber.
15422
15423 assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);
15424
15425 if ( unitOfWork.mode & ProfileMode) {
15426 // Reset the profiler timer.
15427 startProfilerTimer(unitOfWork);
15428 } // Run beginWork again.
15429
15430
15431 invokeGuardedCallback(null, beginWork, null, current, unitOfWork, lanes);
15432
15433 if (hasCaughtError()) {
15434 var replayError = clearCaughtError(); // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.
15435 // Rethrow this error instead of the original one.
15436
15437 throw replayError;
15438 } else {
15439 // This branch is reachable if the render phase is impure.
15440 throw originalError;
15441 }
15442 }
15443 };
15444 }
15445
15446 var didWarnAboutUpdateInRender = false;
15447 var didWarnAboutUpdateInRenderForAnotherComponent;
15448
15449 {
15450 didWarnAboutUpdateInRenderForAnotherComponent = new Set();
15451 }
15452
15453 function warnAboutRenderPhaseUpdatesInDEV(fiber) {
15454 {
15455 if (isRendering && (executionContext & RenderContext) !== NoContext && !getIsUpdatingOpaqueValueInRenderPhaseInDEV()) {
15456 switch (fiber.tag) {
15457 case FunctionComponent:
15458 case ForwardRef:
15459 case SimpleMemoComponent:
15460 {
15461 var renderingComponentName = workInProgress && getComponentName(workInProgress.type) || 'Unknown'; // Dedupe by the rendering component because it's the one that needs to be fixed.
15462
15463 var dedupeKey = renderingComponentName;
15464
15465 if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) {
15466 didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey);
15467 var setStateComponentName = getComponentName(fiber.type) || 'Unknown';
15468
15469 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);
15470 }
15471
15472 break;
15473 }
15474
15475 case ClassComponent:
15476 {
15477 if (!didWarnAboutUpdateInRender) {
15478 error('Cannot update during an existing state transition (such as ' + 'within `render`). Render methods should be a pure ' + 'function of props and state.');
15479
15480 didWarnAboutUpdateInRender = true;
15481 }
15482
15483 break;
15484 }
15485 }
15486 }
15487 }
15488 } // a 'shared' variable that changes when act() opens/closes in tests.
15489
15490 var didWarnAboutUnmockedScheduler = false; // TODO Before we release concurrent mode, revisit this and decide whether a mocked
15491 // scheduler is the actual recommendation. The alternative could be a testing build,
15492 // a new lib, or whatever; we dunno just yet. This message is for early adopters
15493 // to get their tests right.
15494
15495 function warnIfUnmockedScheduler(fiber) {
15496 {
15497 if (didWarnAboutUnmockedScheduler === false && unstable_flushAllWithoutAsserting === undefined) {
15498 if (fiber.mode & BlockingMode || fiber.mode & ConcurrentMode) {
15499 didWarnAboutUnmockedScheduler = true;
15500
15501 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.
15502 "jest.mock('scheduler', () => require" + "('scheduler/unstable_mock'));\n\n" + 'For more info, visit https://reactjs.org/link/mock-scheduler');
15503 }
15504 }
15505 }
15506 }
15507
15508 function computeThreadID(root, lane) {
15509 // Interaction threads are unique per root and expiration time.
15510 // NOTE: Intentionally unsound cast. All that matters is that it's a number
15511 // and it represents a batch of work. Could make a helper function instead,
15512 // but meh this is fine for now.
15513 return lane * 1000 + root.interactionThreadID;
15514 }
15515
15516 function markSpawnedWork(lane) {
15517
15518 if (spawnedWorkDuringRender === null) {
15519 spawnedWorkDuringRender = [lane];
15520 } else {
15521 spawnedWorkDuringRender.push(lane);
15522 }
15523 }
15524
15525 function scheduleInteractions(root, lane, interactions) {
15526
15527 if (interactions.size > 0) {
15528 var pendingInteractionMap = root.pendingInteractionMap;
15529 var pendingInteractions = pendingInteractionMap.get(lane);
15530
15531 if (pendingInteractions != null) {
15532 interactions.forEach(function (interaction) {
15533 if (!pendingInteractions.has(interaction)) {
15534 // Update the pending async work count for previously unscheduled interaction.
15535 interaction.__count++;
15536 }
15537
15538 pendingInteractions.add(interaction);
15539 });
15540 } else {
15541 pendingInteractionMap.set(lane, new Set(interactions)); // Update the pending async work count for the current interactions.
15542
15543 interactions.forEach(function (interaction) {
15544 interaction.__count++;
15545 });
15546 }
15547
15548 var subscriber = __subscriberRef.current;
15549
15550 if (subscriber !== null) {
15551 var threadID = computeThreadID(root, lane);
15552 subscriber.onWorkScheduled(interactions, threadID);
15553 }
15554 }
15555 }
15556
15557 function schedulePendingInteractions(root, lane) {
15558
15559 scheduleInteractions(root, lane, __interactionsRef.current);
15560 }
15561
15562 function startWorkOnPendingInteractions(root, lanes) {
15563 // we can accurately attribute time spent working on it, And so that cascading
15564 // work triggered during the render phase will be associated with it.
15565
15566
15567 var interactions = new Set();
15568 root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledLane) {
15569 if (includesSomeLane(lanes, scheduledLane)) {
15570 scheduledInteractions.forEach(function (interaction) {
15571 return interactions.add(interaction);
15572 });
15573 }
15574 }); // Store the current set of interactions on the FiberRoot for a few reasons:
15575 // We can re-use it in hot functions like performConcurrentWorkOnRoot()
15576 // without having to recalculate it. We will also use it in commitWork() to
15577 // pass to any Profiler onRender() hooks. This also provides DevTools with a
15578 // way to access it when the onCommitRoot() hook is called.
15579
15580 root.memoizedInteractions = interactions;
15581
15582 if (interactions.size > 0) {
15583 var subscriber = __subscriberRef.current;
15584
15585 if (subscriber !== null) {
15586 var threadID = computeThreadID(root, lanes);
15587
15588 try {
15589 subscriber.onWorkStarted(interactions, threadID);
15590 } catch (error) {
15591 // If the subscriber throws, rethrow it in a separate task
15592 scheduleCallback(ImmediatePriority$1, function () {
15593 throw error;
15594 });
15595 }
15596 }
15597 }
15598 }
15599
15600 function finishPendingInteractions(root, committedLanes) {
15601
15602 var remainingLanesAfterCommit = root.pendingLanes;
15603 var subscriber;
15604
15605 try {
15606 subscriber = __subscriberRef.current;
15607
15608 if (subscriber !== null && root.memoizedInteractions.size > 0) {
15609 // FIXME: More than one lane can finish in a single commit.
15610 var threadID = computeThreadID(root, committedLanes);
15611 subscriber.onWorkStopped(root.memoizedInteractions, threadID);
15612 }
15613 } catch (error) {
15614 // If the subscriber throws, rethrow it in a separate task
15615 scheduleCallback(ImmediatePriority$1, function () {
15616 throw error;
15617 });
15618 } finally {
15619 // Clear completed interactions from the pending Map.
15620 // Unless the render was suspended or cascading work was scheduled,
15621 // In which case– leave pending interactions until the subsequent render.
15622 var pendingInteractionMap = root.pendingInteractionMap;
15623 pendingInteractionMap.forEach(function (scheduledInteractions, lane) {
15624 // Only decrement the pending interaction count if we're done.
15625 // If there's still work at the current priority,
15626 // That indicates that we are waiting for suspense data.
15627 if (!includesSomeLane(remainingLanesAfterCommit, lane)) {
15628 pendingInteractionMap.delete(lane);
15629 scheduledInteractions.forEach(function (interaction) {
15630 interaction.__count--;
15631
15632 if (subscriber !== null && interaction.__count === 0) {
15633 try {
15634 subscriber.onInteractionScheduledWorkCompleted(interaction);
15635 } catch (error) {
15636 // If the subscriber throws, rethrow it in a separate task
15637 scheduleCallback(ImmediatePriority$1, function () {
15638 throw error;
15639 });
15640 }
15641 }
15642 });
15643 }
15644 });
15645 }
15646 } // `act` testing API
15647
15648 function shouldForceFlushFallbacksInDEV() {
15649 // Never force flush in production. This function should get stripped out.
15650 return actingUpdatesScopeDepth > 0;
15651 }
15652 // so we can tell if any async act() calls try to run in parallel.
15653
15654
15655 var actingUpdatesScopeDepth = 0;
15656
15657 function detachFiberAfterEffects(fiber) {
15658 fiber.sibling = null;
15659 fiber.stateNode = null;
15660 }
15661
15662 var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below.
15663
15664 var failedBoundaries = null;
15665 var setRefreshHandler = function (handler) {
15666 {
15667 resolveFamily = handler;
15668 }
15669 };
15670 function resolveFunctionForHotReloading(type) {
15671 {
15672 if (resolveFamily === null) {
15673 // Hot reloading is disabled.
15674 return type;
15675 }
15676
15677 var family = resolveFamily(type);
15678
15679 if (family === undefined) {
15680 return type;
15681 } // Use the latest known implementation.
15682
15683
15684 return family.current;
15685 }
15686 }
15687 function resolveClassForHotReloading(type) {
15688 // No implementation differences.
15689 return resolveFunctionForHotReloading(type);
15690 }
15691 function resolveForwardRefForHotReloading(type) {
15692 {
15693 if (resolveFamily === null) {
15694 // Hot reloading is disabled.
15695 return type;
15696 }
15697
15698 var family = resolveFamily(type);
15699
15700 if (family === undefined) {
15701 // Check if we're dealing with a real forwardRef. Don't want to crash early.
15702 if (type !== null && type !== undefined && typeof type.render === 'function') {
15703 // ForwardRef is special because its resolved .type is an object,
15704 // but it's possible that we only have its inner render function in the map.
15705 // If that inner render function is different, we'll build a new forwardRef type.
15706 var currentRender = resolveFunctionForHotReloading(type.render);
15707
15708 if (type.render !== currentRender) {
15709 var syntheticType = {
15710 $$typeof: REACT_FORWARD_REF_TYPE,
15711 render: currentRender
15712 };
15713
15714 if (type.displayName !== undefined) {
15715 syntheticType.displayName = type.displayName;
15716 }
15717
15718 return syntheticType;
15719 }
15720 }
15721
15722 return type;
15723 } // Use the latest known implementation.
15724
15725
15726 return family.current;
15727 }
15728 }
15729 function isCompatibleFamilyForHotReloading(fiber, element) {
15730 {
15731 if (resolveFamily === null) {
15732 // Hot reloading is disabled.
15733 return false;
15734 }
15735
15736 var prevType = fiber.elementType;
15737 var nextType = element.type; // If we got here, we know types aren't === equal.
15738
15739 var needsCompareFamilies = false;
15740 var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null;
15741
15742 switch (fiber.tag) {
15743 case ClassComponent:
15744 {
15745 if (typeof nextType === 'function') {
15746 needsCompareFamilies = true;
15747 }
15748
15749 break;
15750 }
15751
15752 case FunctionComponent:
15753 {
15754 if (typeof nextType === 'function') {
15755 needsCompareFamilies = true;
15756 } else if ($$typeofNextType === REACT_LAZY_TYPE) {
15757 // We don't know the inner type yet.
15758 // We're going to assume that the lazy inner type is stable,
15759 // and so it is sufficient to avoid reconciling it away.
15760 // We're not going to unwrap or actually use the new lazy type.
15761 needsCompareFamilies = true;
15762 }
15763
15764 break;
15765 }
15766
15767 case ForwardRef:
15768 {
15769 if ($$typeofNextType === REACT_FORWARD_REF_TYPE) {
15770 needsCompareFamilies = true;
15771 } else if ($$typeofNextType === REACT_LAZY_TYPE) {
15772 needsCompareFamilies = true;
15773 }
15774
15775 break;
15776 }
15777
15778 case MemoComponent:
15779 case SimpleMemoComponent:
15780 {
15781 if ($$typeofNextType === REACT_MEMO_TYPE) {
15782 // TODO: if it was but can no longer be simple,
15783 // we shouldn't set this.
15784 needsCompareFamilies = true;
15785 } else if ($$typeofNextType === REACT_LAZY_TYPE) {
15786 needsCompareFamilies = true;
15787 }
15788
15789 break;
15790 }
15791
15792 default:
15793 return false;
15794 } // Check if both types have a family and it's the same one.
15795
15796
15797 if (needsCompareFamilies) {
15798 // Note: memo() and forwardRef() we'll compare outer rather than inner type.
15799 // This means both of them need to be registered to preserve state.
15800 // If we unwrapped and compared the inner types for wrappers instead,
15801 // then we would risk falsely saying two separate memo(Foo)
15802 // calls are equivalent because they wrap the same Foo function.
15803 var prevFamily = resolveFamily(prevType);
15804
15805 if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) {
15806 return true;
15807 }
15808 }
15809
15810 return false;
15811 }
15812 }
15813 function markFailedErrorBoundaryForHotReloading(fiber) {
15814 {
15815 if (resolveFamily === null) {
15816 // Hot reloading is disabled.
15817 return;
15818 }
15819
15820 if (typeof WeakSet !== 'function') {
15821 return;
15822 }
15823
15824 if (failedBoundaries === null) {
15825 failedBoundaries = new WeakSet();
15826 }
15827
15828 failedBoundaries.add(fiber);
15829 }
15830 }
15831 var scheduleRefresh = function (root, update) {
15832 {
15833 if (resolveFamily === null) {
15834 // Hot reloading is disabled.
15835 return;
15836 }
15837
15838 var staleFamilies = update.staleFamilies,
15839 updatedFamilies = update.updatedFamilies;
15840 flushPassiveEffects();
15841 flushSync(function () {
15842 scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies);
15843 });
15844 }
15845 };
15846 var scheduleRoot = function (root, element) {
15847 {
15848 if (root.context !== emptyContextObject) {
15849 // Super edge case: root has a legacy _renderSubtree context
15850 // but we don't know the parentComponent so we can't pass it.
15851 // Just ignore. We'll delete this with _renderSubtree code path later.
15852 return;
15853 }
15854
15855 flushPassiveEffects();
15856 flushSync(function () {
15857 updateContainer(element, root, null, null);
15858 });
15859 }
15860 };
15861
15862 function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
15863 {
15864 var alternate = fiber.alternate,
15865 child = fiber.child,
15866 sibling = fiber.sibling,
15867 tag = fiber.tag,
15868 type = fiber.type;
15869 var candidateType = null;
15870
15871 switch (tag) {
15872 case FunctionComponent:
15873 case SimpleMemoComponent:
15874 case ClassComponent:
15875 candidateType = type;
15876 break;
15877
15878 case ForwardRef:
15879 candidateType = type.render;
15880 break;
15881 }
15882
15883 if (resolveFamily === null) {
15884 throw new Error('Expected resolveFamily to be set during hot reload.');
15885 }
15886
15887 var needsRender = false;
15888 var needsRemount = false;
15889
15890 if (candidateType !== null) {
15891 var family = resolveFamily(candidateType);
15892
15893 if (family !== undefined) {
15894 if (staleFamilies.has(family)) {
15895 needsRemount = true;
15896 } else if (updatedFamilies.has(family)) {
15897 if (tag === ClassComponent) {
15898 needsRemount = true;
15899 } else {
15900 needsRender = true;
15901 }
15902 }
15903 }
15904 }
15905
15906 if (failedBoundaries !== null) {
15907 if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) {
15908 needsRemount = true;
15909 }
15910 }
15911
15912 if (needsRemount) {
15913 fiber._debugNeedsRemount = true;
15914 }
15915
15916 if (needsRemount || needsRender) {
15917 scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
15918 }
15919
15920 if (child !== null && !needsRemount) {
15921 scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies);
15922 }
15923
15924 if (sibling !== null) {
15925 scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies);
15926 }
15927 }
15928 }
15929
15930 var findHostInstancesForRefresh = function (root, families) {
15931 {
15932 var hostInstances = new Set();
15933 var types = new Set(families.map(function (family) {
15934 return family.current;
15935 }));
15936 findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances);
15937 return hostInstances;
15938 }
15939 };
15940
15941 function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) {
15942 {
15943 var child = fiber.child,
15944 sibling = fiber.sibling,
15945 tag = fiber.tag,
15946 type = fiber.type;
15947 var candidateType = null;
15948
15949 switch (tag) {
15950 case FunctionComponent:
15951 case SimpleMemoComponent:
15952 case ClassComponent:
15953 candidateType = type;
15954 break;
15955
15956 case ForwardRef:
15957 candidateType = type.render;
15958 break;
15959 }
15960
15961 var didMatch = false;
15962
15963 if (candidateType !== null) {
15964 if (types.has(candidateType)) {
15965 didMatch = true;
15966 }
15967 }
15968
15969 if (didMatch) {
15970 // We have a match. This only drills down to the closest host components.
15971 // There's no need to search deeper because for the purpose of giving
15972 // visual feedback, "flashing" outermost parent rectangles is sufficient.
15973 findHostInstancesForFiberShallowly(fiber, hostInstances);
15974 } else {
15975 // If there's no match, maybe there will be one further down in the child tree.
15976 if (child !== null) {
15977 findHostInstancesForMatchingFibersRecursively(child, types, hostInstances);
15978 }
15979 }
15980
15981 if (sibling !== null) {
15982 findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances);
15983 }
15984 }
15985 }
15986
15987 function findHostInstancesForFiberShallowly(fiber, hostInstances) {
15988 {
15989 var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances);
15990
15991 if (foundHostInstances) {
15992 return;
15993 } // If we didn't find any host children, fallback to closest host parent.
15994
15995
15996 var node = fiber;
15997
15998 while (true) {
15999 switch (node.tag) {
16000 case HostComponent:
16001 hostInstances.add(node.stateNode);
16002 return;
16003
16004 case HostPortal:
16005 hostInstances.add(node.stateNode.containerInfo);
16006 return;
16007
16008 case HostRoot:
16009 hostInstances.add(node.stateNode.containerInfo);
16010 return;
16011 }
16012
16013 if (node.return === null) {
16014 throw new Error('Expected to reach root first.');
16015 }
16016
16017 node = node.return;
16018 }
16019 }
16020 }
16021
16022 function findChildHostInstancesForFiberShallowly(fiber, hostInstances) {
16023 {
16024 var node = fiber;
16025 var foundHostInstances = false;
16026
16027 while (true) {
16028 if (node.tag === HostComponent) {
16029 // We got a match.
16030 foundHostInstances = true;
16031 hostInstances.add(node.stateNode); // There may still be more, so keep searching.
16032 } else if (node.child !== null) {
16033 node.child.return = node;
16034 node = node.child;
16035 continue;
16036 }
16037
16038 if (node === fiber) {
16039 return foundHostInstances;
16040 }
16041
16042 while (node.sibling === null) {
16043 if (node.return === null || node.return === fiber) {
16044 return foundHostInstances;
16045 }
16046
16047 node = node.return;
16048 }
16049
16050 node.sibling.return = node.return;
16051 node = node.sibling;
16052 }
16053 }
16054
16055 return false;
16056 }
16057
16058 var hasBadMapPolyfill;
16059
16060 {
16061 hasBadMapPolyfill = false;
16062
16063 try {
16064 var nonExtensibleObject = Object.preventExtensions({});
16065 /* eslint-disable no-new */
16066
16067 new Map([[nonExtensibleObject, null]]);
16068 new Set([nonExtensibleObject]);
16069 /* eslint-enable no-new */
16070 } catch (e) {
16071 // TODO: Consider warning about bad polyfills
16072 hasBadMapPolyfill = true;
16073 }
16074 }
16075
16076 var debugCounter = 1;
16077
16078 function FiberNode(tag, pendingProps, key, mode) {
16079 // Instance
16080 this.tag = tag;
16081 this.key = key;
16082 this.elementType = null;
16083 this.type = null;
16084 this.stateNode = null; // Fiber
16085
16086 this.return = null;
16087 this.child = null;
16088 this.sibling = null;
16089 this.index = 0;
16090 this.ref = null;
16091 this.pendingProps = pendingProps;
16092 this.memoizedProps = null;
16093 this.updateQueue = null;
16094 this.memoizedState = null;
16095 this.dependencies = null;
16096 this.mode = mode; // Effects
16097
16098 this.flags = NoFlags;
16099 this.nextEffect = null;
16100 this.firstEffect = null;
16101 this.lastEffect = null;
16102 this.lanes = NoLanes;
16103 this.childLanes = NoLanes;
16104 this.alternate = null;
16105
16106 {
16107 // Note: The following is done to avoid a v8 performance cliff.
16108 //
16109 // Initializing the fields below to smis and later updating them with
16110 // double values will cause Fibers to end up having separate shapes.
16111 // This behavior/bug has something to do with Object.preventExtension().
16112 // Fortunately this only impacts DEV builds.
16113 // Unfortunately it makes React unusably slow for some applications.
16114 // To work around this, initialize the fields below with doubles.
16115 //
16116 // Learn more about this here:
16117 // https://github.com/facebook/react/issues/14365
16118 // https://bugs.chromium.org/p/v8/issues/detail?id=8538
16119 this.actualDuration = Number.NaN;
16120 this.actualStartTime = Number.NaN;
16121 this.selfBaseDuration = Number.NaN;
16122 this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization.
16123 // This won't trigger the performance cliff mentioned above,
16124 // and it simplifies other profiler code (including DevTools).
16125
16126 this.actualDuration = 0;
16127 this.actualStartTime = -1;
16128 this.selfBaseDuration = 0;
16129 this.treeBaseDuration = 0;
16130 }
16131
16132 {
16133 // This isn't directly used but is handy for debugging internals:
16134 this._debugID = debugCounter++;
16135 this._debugSource = null;
16136 this._debugOwner = null;
16137 this._debugNeedsRemount = false;
16138 this._debugHookTypes = null;
16139
16140 if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
16141 Object.preventExtensions(this);
16142 }
16143 }
16144 } // This is a constructor function, rather than a POJO constructor, still
16145 // please ensure we do the following:
16146 // 1) Nobody should add any instance methods on this. Instance methods can be
16147 // more difficult to predict when they get optimized and they are almost
16148 // never inlined properly in static compilers.
16149 // 2) Nobody should rely on `instanceof Fiber` for type testing. We should
16150 // always know when it is a fiber.
16151 // 3) We might want to experiment with using numeric keys since they are easier
16152 // to optimize in a non-JIT environment.
16153 // 4) We can easily go from a constructor to a createFiber object literal if that
16154 // is faster.
16155 // 5) It should be easy to port this to a C struct and keep a C implementation
16156 // compatible.
16157
16158
16159 var createFiber = function (tag, pendingProps, key, mode) {
16160 // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
16161 return new FiberNode(tag, pendingProps, key, mode);
16162 };
16163
16164 function shouldConstruct$1(Component) {
16165 var prototype = Component.prototype;
16166 return !!(prototype && prototype.isReactComponent);
16167 }
16168
16169 function isSimpleFunctionComponent(type) {
16170 return typeof type === 'function' && !shouldConstruct$1(type) && type.defaultProps === undefined;
16171 }
16172 function resolveLazyComponentTag(Component) {
16173 if (typeof Component === 'function') {
16174 return shouldConstruct$1(Component) ? ClassComponent : FunctionComponent;
16175 } else if (Component !== undefined && Component !== null) {
16176 var $$typeof = Component.$$typeof;
16177
16178 if ($$typeof === REACT_FORWARD_REF_TYPE) {
16179 return ForwardRef;
16180 }
16181
16182 if ($$typeof === REACT_MEMO_TYPE) {
16183 return MemoComponent;
16184 }
16185 }
16186
16187 return IndeterminateComponent;
16188 } // This is used to create an alternate fiber to do work on.
16189
16190 function createWorkInProgress(current, pendingProps) {
16191 var workInProgress = current.alternate;
16192
16193 if (workInProgress === null) {
16194 // We use a double buffering pooling technique because we know that we'll
16195 // only ever need at most two versions of a tree. We pool the "other" unused
16196 // node that we're free to reuse. This is lazily created to avoid allocating
16197 // extra objects for things that are never updated. It also allow us to
16198 // reclaim the extra memory if needed.
16199 workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
16200 workInProgress.elementType = current.elementType;
16201 workInProgress.type = current.type;
16202 workInProgress.stateNode = current.stateNode;
16203
16204 {
16205 // DEV-only fields
16206 workInProgress._debugID = current._debugID;
16207 workInProgress._debugSource = current._debugSource;
16208 workInProgress._debugOwner = current._debugOwner;
16209 workInProgress._debugHookTypes = current._debugHookTypes;
16210 }
16211
16212 workInProgress.alternate = current;
16213 current.alternate = workInProgress;
16214 } else {
16215 workInProgress.pendingProps = pendingProps; // Needed because Blocks store data on type.
16216
16217 workInProgress.type = current.type; // We already have an alternate.
16218 // Reset the effect tag.
16219
16220 workInProgress.flags = NoFlags; // The effect list is no longer valid.
16221
16222 workInProgress.nextEffect = null;
16223 workInProgress.firstEffect = null;
16224 workInProgress.lastEffect = null;
16225
16226 {
16227 // We intentionally reset, rather than copy, actualDuration & actualStartTime.
16228 // This prevents time from endlessly accumulating in new commits.
16229 // This has the downside of resetting values for different priority renders,
16230 // But works for yielding (the common case) and should support resuming.
16231 workInProgress.actualDuration = 0;
16232 workInProgress.actualStartTime = -1;
16233 }
16234 }
16235
16236 workInProgress.childLanes = current.childLanes;
16237 workInProgress.lanes = current.lanes;
16238 workInProgress.child = current.child;
16239 workInProgress.memoizedProps = current.memoizedProps;
16240 workInProgress.memoizedState = current.memoizedState;
16241 workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
16242 // it cannot be shared with the current fiber.
16243
16244 var currentDependencies = current.dependencies;
16245 workInProgress.dependencies = currentDependencies === null ? null : {
16246 lanes: currentDependencies.lanes,
16247 firstContext: currentDependencies.firstContext
16248 }; // These will be overridden during the parent's reconciliation
16249
16250 workInProgress.sibling = current.sibling;
16251 workInProgress.index = current.index;
16252 workInProgress.ref = current.ref;
16253
16254 {
16255 workInProgress.selfBaseDuration = current.selfBaseDuration;
16256 workInProgress.treeBaseDuration = current.treeBaseDuration;
16257 }
16258
16259 {
16260 workInProgress._debugNeedsRemount = current._debugNeedsRemount;
16261
16262 switch (workInProgress.tag) {
16263 case IndeterminateComponent:
16264 case FunctionComponent:
16265 case SimpleMemoComponent:
16266 workInProgress.type = resolveFunctionForHotReloading(current.type);
16267 break;
16268
16269 case ClassComponent:
16270 workInProgress.type = resolveClassForHotReloading(current.type);
16271 break;
16272
16273 case ForwardRef:
16274 workInProgress.type = resolveForwardRefForHotReloading(current.type);
16275 break;
16276 }
16277 }
16278
16279 return workInProgress;
16280 } // Used to reuse a Fiber for a second pass.
16281
16282 function resetWorkInProgress(workInProgress, renderLanes) {
16283 // This resets the Fiber to what createFiber or createWorkInProgress would
16284 // have set the values to before during the first pass. Ideally this wouldn't
16285 // be necessary but unfortunately many code paths reads from the workInProgress
16286 // when they should be reading from current and writing to workInProgress.
16287 // We assume pendingProps, index, key, ref, return are still untouched to
16288 // avoid doing another reconciliation.
16289 // Reset the effect tag but keep any Placement tags, since that's something
16290 // that child fiber is setting, not the reconciliation.
16291 workInProgress.flags &= Placement; // The effect list is no longer valid.
16292
16293 workInProgress.nextEffect = null;
16294 workInProgress.firstEffect = null;
16295 workInProgress.lastEffect = null;
16296 var current = workInProgress.alternate;
16297
16298 if (current === null) {
16299 // Reset to createFiber's initial values.
16300 workInProgress.childLanes = NoLanes;
16301 workInProgress.lanes = renderLanes;
16302 workInProgress.child = null;
16303 workInProgress.memoizedProps = null;
16304 workInProgress.memoizedState = null;
16305 workInProgress.updateQueue = null;
16306 workInProgress.dependencies = null;
16307 workInProgress.stateNode = null;
16308
16309 {
16310 // Note: We don't reset the actualTime counts. It's useful to accumulate
16311 // actual time across multiple render passes.
16312 workInProgress.selfBaseDuration = 0;
16313 workInProgress.treeBaseDuration = 0;
16314 }
16315 } else {
16316 // Reset to the cloned values that createWorkInProgress would've.
16317 workInProgress.childLanes = current.childLanes;
16318 workInProgress.lanes = current.lanes;
16319 workInProgress.child = current.child;
16320 workInProgress.memoizedProps = current.memoizedProps;
16321 workInProgress.memoizedState = current.memoizedState;
16322 workInProgress.updateQueue = current.updateQueue; // Needed because Blocks store data on type.
16323
16324 workInProgress.type = current.type; // Clone the dependencies object. This is mutated during the render phase, so
16325 // it cannot be shared with the current fiber.
16326
16327 var currentDependencies = current.dependencies;
16328 workInProgress.dependencies = currentDependencies === null ? null : {
16329 lanes: currentDependencies.lanes,
16330 firstContext: currentDependencies.firstContext
16331 };
16332
16333 {
16334 // Note: We don't reset the actualTime counts. It's useful to accumulate
16335 // actual time across multiple render passes.
16336 workInProgress.selfBaseDuration = current.selfBaseDuration;
16337 workInProgress.treeBaseDuration = current.treeBaseDuration;
16338 }
16339 }
16340
16341 return workInProgress;
16342 }
16343 function createHostRootFiber(tag) {
16344 var mode;
16345
16346 if (tag === ConcurrentRoot) {
16347 mode = ConcurrentMode | BlockingMode | StrictMode;
16348 } else if (tag === BlockingRoot) {
16349 mode = BlockingMode | StrictMode;
16350 } else {
16351 mode = NoMode;
16352 }
16353
16354 if ( isDevToolsPresent) {
16355 // Always collect profile timings when DevTools are present.
16356 // This enables DevTools to start capturing timing at any point–
16357 // Without some nodes in the tree having empty base times.
16358 mode |= ProfileMode;
16359 }
16360
16361 return createFiber(HostRoot, null, null, mode);
16362 }
16363 function createFiberFromTypeAndProps(type, // React$ElementType
16364 key, pendingProps, owner, mode, lanes) {
16365 var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
16366
16367 var resolvedType = type;
16368
16369 if (typeof type === 'function') {
16370 if (shouldConstruct$1(type)) {
16371 fiberTag = ClassComponent;
16372
16373 {
16374 resolvedType = resolveClassForHotReloading(resolvedType);
16375 }
16376 } else {
16377 {
16378 resolvedType = resolveFunctionForHotReloading(resolvedType);
16379 }
16380 }
16381 } else if (typeof type === 'string') {
16382 fiberTag = HostComponent;
16383 } else {
16384 getTag: switch (type) {
16385 case REACT_FRAGMENT_TYPE:
16386 return createFiberFromFragment(pendingProps.children, mode, lanes, key);
16387
16388 case REACT_DEBUG_TRACING_MODE_TYPE:
16389 fiberTag = Mode;
16390 mode |= DebugTracingMode;
16391 break;
16392
16393 case REACT_STRICT_MODE_TYPE:
16394 fiberTag = Mode;
16395 mode |= StrictMode;
16396 break;
16397
16398 case REACT_PROFILER_TYPE:
16399 return createFiberFromProfiler(pendingProps, mode, lanes, key);
16400
16401 case REACT_SUSPENSE_TYPE:
16402 return createFiberFromSuspense(pendingProps, mode, lanes, key);
16403
16404 case REACT_SUSPENSE_LIST_TYPE:
16405 return createFiberFromSuspenseList(pendingProps, mode, lanes, key);
16406
16407 case REACT_OFFSCREEN_TYPE:
16408 return createFiberFromOffscreen(pendingProps, mode, lanes, key);
16409
16410 case REACT_LEGACY_HIDDEN_TYPE:
16411 return createFiberFromLegacyHidden(pendingProps, mode, lanes, key);
16412
16413 case REACT_SCOPE_TYPE:
16414
16415 // eslint-disable-next-line no-fallthrough
16416
16417 default:
16418 {
16419 if (typeof type === 'object' && type !== null) {
16420 switch (type.$$typeof) {
16421 case REACT_PROVIDER_TYPE:
16422 fiberTag = ContextProvider;
16423 break getTag;
16424
16425 case REACT_CONTEXT_TYPE:
16426 // This is a consumer
16427 fiberTag = ContextConsumer;
16428 break getTag;
16429
16430 case REACT_FORWARD_REF_TYPE:
16431 fiberTag = ForwardRef;
16432
16433 {
16434 resolvedType = resolveForwardRefForHotReloading(resolvedType);
16435 }
16436
16437 break getTag;
16438
16439 case REACT_MEMO_TYPE:
16440 fiberTag = MemoComponent;
16441 break getTag;
16442
16443 case REACT_LAZY_TYPE:
16444 fiberTag = LazyComponent;
16445 resolvedType = null;
16446 break getTag;
16447
16448 case REACT_BLOCK_TYPE:
16449 fiberTag = Block;
16450 break getTag;
16451 }
16452 }
16453
16454 var info = '';
16455
16456 {
16457 if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
16458 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.';
16459 }
16460
16461 var ownerName = owner ? getComponentName(owner.type) : null;
16462
16463 if (ownerName) {
16464 info += '\n\nCheck the render method of `' + ownerName + '`.';
16465 }
16466 }
16467
16468 {
16469 {
16470 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 );
16471 }
16472 }
16473 }
16474 }
16475 }
16476
16477 var fiber = createFiber(fiberTag, pendingProps, key, mode);
16478 fiber.elementType = type;
16479 fiber.type = resolvedType;
16480 fiber.lanes = lanes;
16481
16482 {
16483 fiber._debugOwner = owner;
16484 }
16485
16486 return fiber;
16487 }
16488 function createFiberFromElement(element, mode, lanes) {
16489 var owner = null;
16490
16491 {
16492 owner = element._owner;
16493 }
16494
16495 var type = element.type;
16496 var key = element.key;
16497 var pendingProps = element.props;
16498 var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes);
16499
16500 {
16501 fiber._debugSource = element._source;
16502 fiber._debugOwner = element._owner;
16503 }
16504
16505 return fiber;
16506 }
16507 function createFiberFromFragment(elements, mode, lanes, key) {
16508 var fiber = createFiber(Fragment, elements, key, mode);
16509 fiber.lanes = lanes;
16510 return fiber;
16511 }
16512
16513 function createFiberFromProfiler(pendingProps, mode, lanes, key) {
16514 {
16515 if (typeof pendingProps.id !== 'string') {
16516 error('Profiler must specify an "id" as a prop');
16517 }
16518 }
16519
16520 var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); // TODO: The Profiler fiber shouldn't have a type. It has a tag.
16521
16522 fiber.elementType = REACT_PROFILER_TYPE;
16523 fiber.type = REACT_PROFILER_TYPE;
16524 fiber.lanes = lanes;
16525
16526 {
16527 fiber.stateNode = {
16528 effectDuration: 0,
16529 passiveEffectDuration: 0
16530 };
16531 }
16532
16533 return fiber;
16534 }
16535
16536 function createFiberFromSuspense(pendingProps, mode, lanes, key) {
16537 var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
16538 // This needs to be fixed in getComponentName so that it relies on the tag
16539 // instead.
16540
16541 fiber.type = REACT_SUSPENSE_TYPE;
16542 fiber.elementType = REACT_SUSPENSE_TYPE;
16543 fiber.lanes = lanes;
16544 return fiber;
16545 }
16546 function createFiberFromSuspenseList(pendingProps, mode, lanes, key) {
16547 var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);
16548
16549 {
16550 // TODO: The SuspenseListComponent fiber shouldn't have a type. It has a tag.
16551 // This needs to be fixed in getComponentName so that it relies on the tag
16552 // instead.
16553 fiber.type = REACT_SUSPENSE_LIST_TYPE;
16554 }
16555
16556 fiber.elementType = REACT_SUSPENSE_LIST_TYPE;
16557 fiber.lanes = lanes;
16558 return fiber;
16559 }
16560 function createFiberFromOffscreen(pendingProps, mode, lanes, key) {
16561 var fiber = createFiber(OffscreenComponent, pendingProps, key, mode); // TODO: The OffscreenComponent fiber shouldn't have a type. It has a tag.
16562 // This needs to be fixed in getComponentName so that it relies on the tag
16563 // instead.
16564
16565 {
16566 fiber.type = REACT_OFFSCREEN_TYPE;
16567 }
16568
16569 fiber.elementType = REACT_OFFSCREEN_TYPE;
16570 fiber.lanes = lanes;
16571 return fiber;
16572 }
16573 function createFiberFromLegacyHidden(pendingProps, mode, lanes, key) {
16574 var fiber = createFiber(LegacyHiddenComponent, pendingProps, key, mode); // TODO: The LegacyHidden fiber shouldn't have a type. It has a tag.
16575 // This needs to be fixed in getComponentName so that it relies on the tag
16576 // instead.
16577
16578 {
16579 fiber.type = REACT_LEGACY_HIDDEN_TYPE;
16580 }
16581
16582 fiber.elementType = REACT_LEGACY_HIDDEN_TYPE;
16583 fiber.lanes = lanes;
16584 return fiber;
16585 }
16586 function createFiberFromText(content, mode, lanes) {
16587 var fiber = createFiber(HostText, content, null, mode);
16588 fiber.lanes = lanes;
16589 return fiber;
16590 }
16591 function createFiberFromPortal(portal, mode, lanes) {
16592 var pendingProps = portal.children !== null ? portal.children : [];
16593 var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
16594 fiber.lanes = lanes;
16595 fiber.stateNode = {
16596 containerInfo: portal.containerInfo,
16597 pendingChildren: null,
16598 // Used by persistent updates
16599 implementation: portal.implementation
16600 };
16601 return fiber;
16602 } // Used for stashing WIP properties to replay failed work in DEV.
16603
16604 function assignFiberPropertiesInDEV(target, source) {
16605 if (target === null) {
16606 // This Fiber's initial properties will always be overwritten.
16607 // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
16608 target = createFiber(IndeterminateComponent, null, null, NoMode);
16609 } // This is intentionally written as a list of all properties.
16610 // We tried to use Object.assign() instead but this is called in
16611 // the hottest path, and Object.assign() was too slow:
16612 // https://github.com/facebook/react/issues/12502
16613 // This code is DEV-only so size is not a concern.
16614
16615
16616 target.tag = source.tag;
16617 target.key = source.key;
16618 target.elementType = source.elementType;
16619 target.type = source.type;
16620 target.stateNode = source.stateNode;
16621 target.return = source.return;
16622 target.child = source.child;
16623 target.sibling = source.sibling;
16624 target.index = source.index;
16625 target.ref = source.ref;
16626 target.pendingProps = source.pendingProps;
16627 target.memoizedProps = source.memoizedProps;
16628 target.updateQueue = source.updateQueue;
16629 target.memoizedState = source.memoizedState;
16630 target.dependencies = source.dependencies;
16631 target.mode = source.mode;
16632 target.flags = source.flags;
16633 target.nextEffect = source.nextEffect;
16634 target.firstEffect = source.firstEffect;
16635 target.lastEffect = source.lastEffect;
16636 target.lanes = source.lanes;
16637 target.childLanes = source.childLanes;
16638 target.alternate = source.alternate;
16639
16640 {
16641 target.actualDuration = source.actualDuration;
16642 target.actualStartTime = source.actualStartTime;
16643 target.selfBaseDuration = source.selfBaseDuration;
16644 target.treeBaseDuration = source.treeBaseDuration;
16645 }
16646
16647 target._debugID = source._debugID;
16648 target._debugSource = source._debugSource;
16649 target._debugOwner = source._debugOwner;
16650 target._debugNeedsRemount = source._debugNeedsRemount;
16651 target._debugHookTypes = source._debugHookTypes;
16652 return target;
16653 }
16654
16655 function FiberRootNode(containerInfo, tag, hydrate) {
16656 this.tag = tag;
16657 this.containerInfo = containerInfo;
16658 this.pendingChildren = null;
16659 this.current = null;
16660 this.pingCache = null;
16661 this.finishedWork = null;
16662 this.timeoutHandle = noTimeout;
16663 this.context = null;
16664 this.pendingContext = null;
16665 this.hydrate = hydrate;
16666 this.callbackNode = null;
16667 this.callbackPriority = NoLanePriority;
16668 this.eventTimes = createLaneMap(NoLanes);
16669 this.expirationTimes = createLaneMap(NoTimestamp);
16670 this.pendingLanes = NoLanes;
16671 this.suspendedLanes = NoLanes;
16672 this.pingedLanes = NoLanes;
16673 this.expiredLanes = NoLanes;
16674 this.mutableReadLanes = NoLanes;
16675 this.finishedLanes = NoLanes;
16676 this.entangledLanes = NoLanes;
16677 this.entanglements = createLaneMap(NoLanes);
16678
16679 {
16680 this.interactionThreadID = unstable_getThreadID();
16681 this.memoizedInteractions = new Set();
16682 this.pendingInteractionMap = new Map();
16683 }
16684
16685 {
16686 switch (tag) {
16687 case BlockingRoot:
16688 this._debugRootType = 'createBlockingRoot()';
16689 break;
16690
16691 case ConcurrentRoot:
16692 this._debugRootType = 'createRoot()';
16693 break;
16694
16695 case LegacyRoot:
16696 this._debugRootType = 'createLegacyRoot()';
16697 break;
16698 }
16699 }
16700 }
16701
16702 function createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks) {
16703 var root = new FiberRootNode(containerInfo, tag, hydrate);
16704 // stateNode is any.
16705
16706
16707 var uninitializedFiber = createHostRootFiber(tag);
16708 root.current = uninitializedFiber;
16709 uninitializedFiber.stateNode = root;
16710 initializeUpdateQueue(uninitializedFiber);
16711 return root;
16712 }
16713
16714 var didWarnAboutNestedUpdates;
16715
16716 {
16717 didWarnAboutNestedUpdates = false;
16718 }
16719
16720 function getContextForSubtree(parentComponent) {
16721 if (!parentComponent) {
16722 return emptyContextObject;
16723 }
16724
16725 var fiber = get(parentComponent);
16726 var parentContext = findCurrentUnmaskedContext(fiber);
16727
16728 if (fiber.tag === ClassComponent) {
16729 var Component = fiber.type;
16730
16731 if (isContextProvider(Component)) {
16732 return processChildContext(fiber, Component, parentContext);
16733 }
16734 }
16735
16736 return parentContext;
16737 }
16738
16739 function createContainer(containerInfo, tag, hydrate, hydrationCallbacks) {
16740 return createFiberRoot(containerInfo, tag, hydrate);
16741 }
16742 function updateContainer(element, container, parentComponent, callback) {
16743 {
16744 onScheduleRoot(container, element);
16745 }
16746
16747 var current = container.current;
16748 var eventTime = requestEventTime();
16749
16750 {
16751 // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
16752 if ('undefined' !== typeof jest) {
16753 warnIfUnmockedScheduler(current);
16754 }
16755 }
16756
16757 var lane = requestUpdateLane(current);
16758
16759 var context = getContextForSubtree(parentComponent);
16760
16761 if (container.context === null) {
16762 container.context = context;
16763 } else {
16764 container.pendingContext = context;
16765 }
16766
16767 {
16768 if (isRendering && current$1 !== null && !didWarnAboutNestedUpdates) {
16769 didWarnAboutNestedUpdates = true;
16770
16771 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$1.type) || 'Unknown');
16772 }
16773 }
16774
16775 var update = createUpdate(eventTime, lane); // Caution: React DevTools currently depends on this property
16776 // being called "element".
16777
16778 update.payload = {
16779 element: element
16780 };
16781 callback = callback === undefined ? null : callback;
16782
16783 if (callback !== null) {
16784 {
16785 if (typeof callback !== 'function') {
16786 error('render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback);
16787 }
16788 }
16789
16790 update.callback = callback;
16791 }
16792
16793 enqueueUpdate(current, update);
16794 scheduleUpdateOnFiber(current, lane, eventTime);
16795 return lane;
16796 }
16797
16798 var shouldSuspendImpl = function (fiber) {
16799 return false;
16800 };
16801
16802 function shouldSuspend(fiber) {
16803 return shouldSuspendImpl(fiber);
16804 }
16805 var overrideHookState = null;
16806 var overrideHookStateDeletePath = null;
16807 var overrideHookStateRenamePath = null;
16808 var overrideProps = null;
16809 var overridePropsDeletePath = null;
16810 var overridePropsRenamePath = null;
16811 var scheduleUpdate = null;
16812 var setSuspenseHandler = null;
16813
16814 {
16815 var copyWithDeleteImpl = function (obj, path, index) {
16816 var key = path[index];
16817 var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj);
16818
16819 if (index + 1 === path.length) {
16820 if (Array.isArray(updated)) {
16821 updated.splice(key, 1);
16822 } else {
16823 delete updated[key];
16824 }
16825
16826 return updated;
16827 } // $FlowFixMe number or string is fine here
16828
16829
16830 updated[key] = copyWithDeleteImpl(obj[key], path, index + 1);
16831 return updated;
16832 };
16833
16834 var copyWithDelete = function (obj, path) {
16835 return copyWithDeleteImpl(obj, path, 0);
16836 };
16837
16838 var copyWithRenameImpl = function (obj, oldPath, newPath, index) {
16839 var oldKey = oldPath[index];
16840 var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj);
16841
16842 if (index + 1 === oldPath.length) {
16843 var newKey = newPath[index]; // $FlowFixMe number or string is fine here
16844
16845 updated[newKey] = updated[oldKey];
16846
16847 if (Array.isArray(updated)) {
16848 updated.splice(oldKey, 1);
16849 } else {
16850 delete updated[oldKey];
16851 }
16852 } else {
16853 // $FlowFixMe number or string is fine here
16854 updated[oldKey] = copyWithRenameImpl( // $FlowFixMe number or string is fine here
16855 obj[oldKey], oldPath, newPath, index + 1);
16856 }
16857
16858 return updated;
16859 };
16860
16861 var copyWithRename = function (obj, oldPath, newPath) {
16862 if (oldPath.length !== newPath.length) {
16863 warn('copyWithRename() expects paths of the same length');
16864
16865 return;
16866 } else {
16867 for (var i = 0; i < newPath.length - 1; i++) {
16868 if (oldPath[i] !== newPath[i]) {
16869 warn('copyWithRename() expects paths to be the same except for the deepest key');
16870
16871 return;
16872 }
16873 }
16874 }
16875
16876 return copyWithRenameImpl(obj, oldPath, newPath, 0);
16877 };
16878
16879 var copyWithSetImpl = function (obj, path, index, value) {
16880 if (index >= path.length) {
16881 return value;
16882 }
16883
16884 var key = path[index];
16885 var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj); // $FlowFixMe number or string is fine here
16886
16887 updated[key] = copyWithSetImpl(obj[key], path, index + 1, value);
16888 return updated;
16889 };
16890
16891 var copyWithSet = function (obj, path, value) {
16892 return copyWithSetImpl(obj, path, 0, value);
16893 };
16894
16895 var findHook = function (fiber, id) {
16896 // For now, the "id" of stateful hooks is just the stateful hook index.
16897 // This may change in the future with e.g. nested hooks.
16898 var currentHook = fiber.memoizedState;
16899
16900 while (currentHook !== null && id > 0) {
16901 currentHook = currentHook.next;
16902 id--;
16903 }
16904
16905 return currentHook;
16906 }; // Support DevTools editable values for useState and useReducer.
16907
16908
16909 overrideHookState = function (fiber, id, path, value) {
16910 var hook = findHook(fiber, id);
16911
16912 if (hook !== null) {
16913 var newState = copyWithSet(hook.memoizedState, path, value);
16914 hook.memoizedState = newState;
16915 hook.baseState = newState; // We aren't actually adding an update to the queue,
16916 // because there is no update we can add for useReducer hooks that won't trigger an error.
16917 // (There's no appropriate action type for DevTools overrides.)
16918 // As a result though, React will see the scheduled update as a noop and bailout.
16919 // Shallow cloning props works as a workaround for now to bypass the bailout check.
16920
16921 fiber.memoizedProps = _assign({}, fiber.memoizedProps);
16922 scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
16923 }
16924 };
16925
16926 overrideHookStateDeletePath = function (fiber, id, path) {
16927 var hook = findHook(fiber, id);
16928
16929 if (hook !== null) {
16930 var newState = copyWithDelete(hook.memoizedState, path);
16931 hook.memoizedState = newState;
16932 hook.baseState = newState; // We aren't actually adding an update to the queue,
16933 // because there is no update we can add for useReducer hooks that won't trigger an error.
16934 // (There's no appropriate action type for DevTools overrides.)
16935 // As a result though, React will see the scheduled update as a noop and bailout.
16936 // Shallow cloning props works as a workaround for now to bypass the bailout check.
16937
16938 fiber.memoizedProps = _assign({}, fiber.memoizedProps);
16939 scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
16940 }
16941 };
16942
16943 overrideHookStateRenamePath = function (fiber, id, oldPath, newPath) {
16944 var hook = findHook(fiber, id);
16945
16946 if (hook !== null) {
16947 var newState = copyWithRename(hook.memoizedState, oldPath, newPath);
16948 hook.memoizedState = newState;
16949 hook.baseState = newState; // We aren't actually adding an update to the queue,
16950 // because there is no update we can add for useReducer hooks that won't trigger an error.
16951 // (There's no appropriate action type for DevTools overrides.)
16952 // As a result though, React will see the scheduled update as a noop and bailout.
16953 // Shallow cloning props works as a workaround for now to bypass the bailout check.
16954
16955 fiber.memoizedProps = _assign({}, fiber.memoizedProps);
16956 scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
16957 }
16958 }; // Support DevTools props for function components, forwardRef, memo, host components, etc.
16959
16960
16961 overrideProps = function (fiber, path, value) {
16962 fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
16963
16964 if (fiber.alternate) {
16965 fiber.alternate.pendingProps = fiber.pendingProps;
16966 }
16967
16968 scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
16969 };
16970
16971 overridePropsDeletePath = function (fiber, path) {
16972 fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path);
16973
16974 if (fiber.alternate) {
16975 fiber.alternate.pendingProps = fiber.pendingProps;
16976 }
16977
16978 scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
16979 };
16980
16981 overridePropsRenamePath = function (fiber, oldPath, newPath) {
16982 fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath);
16983
16984 if (fiber.alternate) {
16985 fiber.alternate.pendingProps = fiber.pendingProps;
16986 }
16987
16988 scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
16989 };
16990
16991 scheduleUpdate = function (fiber) {
16992 scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
16993 };
16994
16995 setSuspenseHandler = function (newShouldSuspendImpl) {
16996 shouldSuspendImpl = newShouldSuspendImpl;
16997 };
16998 }
16999
17000 function findHostInstanceByFiber(fiber) {
17001 var hostFiber = findCurrentHostFiber(fiber);
17002
17003 if (hostFiber === null) {
17004 return null;
17005 }
17006
17007 return hostFiber.stateNode;
17008 }
17009
17010 function emptyFindFiberByHostInstance(instance) {
17011 return null;
17012 }
17013
17014 function getCurrentFiberForDevTools() {
17015 return current$1;
17016 }
17017
17018 function injectIntoDevTools(devToolsConfig) {
17019 var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
17020 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
17021 return injectInternals({
17022 bundleType: devToolsConfig.bundleType,
17023 version: devToolsConfig.version,
17024 rendererPackageName: devToolsConfig.rendererPackageName,
17025 rendererConfig: devToolsConfig.rendererConfig,
17026 overrideHookState: overrideHookState,
17027 overrideHookStateDeletePath: overrideHookStateDeletePath,
17028 overrideHookStateRenamePath: overrideHookStateRenamePath,
17029 overrideProps: overrideProps,
17030 overridePropsDeletePath: overridePropsDeletePath,
17031 overridePropsRenamePath: overridePropsRenamePath,
17032 setSuspenseHandler: setSuspenseHandler,
17033 scheduleUpdate: scheduleUpdate,
17034 currentDispatcherRef: ReactCurrentDispatcher,
17035 findHostInstanceByFiber: findHostInstanceByFiber,
17036 findFiberByHostInstance: findFiberByHostInstance || emptyFindFiberByHostInstance,
17037 // React Refresh
17038 findHostInstancesForRefresh: findHostInstancesForRefresh ,
17039 scheduleRefresh: scheduleRefresh ,
17040 scheduleRoot: scheduleRoot ,
17041 setRefreshHandler: setRefreshHandler ,
17042 // Enables DevTools to append owner stacks to error messages in DEV mode.
17043 getCurrentFiber: getCurrentFiberForDevTools
17044 });
17045 }
17046
17047 var container = _class({
17048
17049 grab: function(){
17050 for (var i = 0; i < arguments.length; i++) arguments[i].inject(this);
17051 return this;
17052 },
17053
17054 empty: function(){
17055 var node;
17056 while (node = this.firstChild) node.eject();
17057 return this;
17058 }
17059
17060 });
17061
17062 function elementFrom(node){
17063 if (node.toElement) return node.toElement();
17064 if (node.getDOMNode) return node.getDOMNode();
17065 if (node.getNode) return node.getNode();
17066 return node;
17067 }
17068
17069 var native_1 = _class({
17070
17071 // conventions
17072
17073 toElement: function(){
17074 return this.element;
17075 },
17076
17077 getDOMNode: function(){
17078 return this.toElement();
17079 },
17080
17081 getNode: function(){
17082 return this.toElement();
17083 },
17084
17085 // placement
17086
17087 inject: function(container){
17088 (container.containerElement || elementFrom(container))
17089 .appendChild(this.element);
17090 return this;
17091 },
17092
17093 injectBefore: function(sibling){
17094 var element = elementFrom(sibling);
17095 element.parentNode.insertBefore(this.element, element);
17096 return this;
17097 },
17098
17099 eject: function(){
17100 var element = this.element, parent = element.parentNode;
17101 if (parent) parent.removeChild(element); // TODO: VML Nodes are dead after being ejected
17102 return this;
17103 },
17104
17105 // events
17106
17107 subscribe: function(type, fn, bind){
17108 if (typeof type != 'string'){ // listen type / fn with object
17109 var subscriptions = [];
17110 for (var t in type) subscriptions.push(this.subscribe(t, type[t]));
17111 return function(){ // unsubscribe
17112 for (var i = 0, l = subscriptions.length; i < l; i++)
17113 subscriptions[i]();
17114 return this;
17115 };
17116 } else { // listen to one
17117 if (!bind) bind = this;
17118 var bound;
17119 if (typeof fn === 'function'){
17120 bound = fn.bind ? fn.bind(bind)
17121 : function(){ return fn.apply(bind, arguments); };
17122 } else {
17123 bound = fn;
17124 }
17125 var element = this.element;
17126 if (element.addEventListener){
17127 element.addEventListener(type, bound, false);
17128 return function(){ // unsubscribe
17129 element.removeEventListener(type, bound, false);
17130 return this;
17131 };
17132 } else {
17133 element.attachEvent('on' + type, bound);
17134 return function(){ // unsubscribe
17135 element.detachEvent('on' + type, bound);
17136 return this;
17137 };
17138 }
17139 }
17140 }
17141
17142 });
17143
17144 var fps = 1000 / 60, invalids = [], renderTimer, renderInvalids = function(){
17145 clearTimeout(renderTimer);
17146 renderTimer = null;
17147 var canvases = invalids;
17148 invalids = [];
17149 for (var i = 0, l = canvases.length; i < l; i++){
17150 var c = canvases[i];
17151 c._valid = true;
17152 c.render();
17153 }
17154 };
17155
17156 var resolution = typeof window !== 'undefined' && window.devicePixelRatio || 1;
17157
17158 var previousHit = null, previousHitSurface = null;
17159
17160 var CanvasSurface = _class(native_1, container, {
17161
17162 initialize: function(width, height, existingElement){
17163 var element = this.element = existingElement || document.createElement('canvas');
17164 var context = this.context = element.getContext('2d');
17165 this._valid = true;
17166 if (width != null && height != null) this.resize(width, height);
17167
17168 element.addEventListener('mousemove', this, false);
17169 element.addEventListener('mouseout', this, false);
17170 element.addEventListener('mouseover', this, false);
17171 element.addEventListener('mouseup', this, false);
17172 element.addEventListener('mousedown', this, false);
17173 element.addEventListener('click', this, false);
17174 },
17175
17176 handleEvent: function(event){
17177 if (event.clientX == null) return;
17178 var element = this.element,
17179 rect = element.getBoundingClientRect(),
17180 x = event.clientX - rect.left - element.clientLeft,
17181 y = event.clientY - rect.top - element.clientTop,
17182 hit = this.hitTest(x, y);
17183
17184 if (hit !== previousHit){
17185 if (previousHit){
17186 previousHit.dispatch({
17187 type: 'mouseout',
17188 target: previousHit,
17189 relatedTarget: hit,
17190 sourceEvent: event
17191 });
17192 }
17193 if (hit){
17194 hit.dispatch({
17195 type: 'mouseover',
17196 target: hit,
17197 relatedTarget: previousHit,
17198 sourceEvent: event
17199 });
17200 }
17201 previousHit = hit;
17202 previousHitSurface = this;
17203 this.refreshCursor();
17204 }
17205
17206 if (hit) hit.dispatch(event);
17207 },
17208
17209 refreshCursor: function(){
17210 if (previousHitSurface !== this) return;
17211 var hit = previousHit, hitCursor = '', hitTooltip = '';
17212 while (hit){
17213 if (!hitCursor && hit._cursor){
17214 hitCursor = hit._cursor;
17215 if (hitTooltip) break;
17216 }
17217 if (!hitTooltip && hit._tooltip){
17218 hitTooltip = hit._tooltip;
17219 if (hitCursor) break;
17220 }
17221 hit = hit.parentNode;
17222 }
17223 // TODO: No way to set cursor/title on the surface
17224 this.element.style.cursor = hitCursor;
17225 this.element.title = hitTooltip;
17226 },
17227
17228 resize: function(width, height){
17229 var element = this.element;
17230 element.setAttribute('width', width * resolution);
17231 element.setAttribute('height', height * resolution);
17232 element.style.width = width + 'px';
17233 element.style.height = height + 'px';
17234 this.width = width;
17235 this.height = height;
17236 return this;
17237 },
17238
17239 invalidate: function(left, top, width, height){
17240 if (this._valid){
17241 this._valid = false;
17242 invalids.push(this);
17243 if (!renderTimer){
17244 if (window.mozRequestAnimationFrame){
17245 renderTimer = true;
17246 window.mozRequestAnimationFrame(renderInvalids);
17247 } else {
17248 renderTimer = setTimeout(renderInvalids, fps);
17249 }
17250 }
17251 }
17252 return this;
17253 },
17254
17255 hitTest: function(x, y){
17256 if (x < 0 || y < 0 || x > this.width || y > this.height) return null;
17257 var node = this.lastChild;
17258 while (node){
17259 var hit = node.hitTest(x, y);
17260 if (hit) return hit;
17261 node = node.previousSibling;
17262 }
17263 return null;
17264 },
17265
17266 render: function(){
17267 var node = this.firstChild, context = this.context;
17268 context.setTransform(resolution, 0, 0, resolution, 0, 0);
17269 context.clearRect(0, 0, this.width, this.height);
17270 while (node){
17271 node.renderTo(context, resolution, 0, 0, resolution, 0, 0);
17272 node = node.nextSibling;
17273 }
17274 this.refreshCursor();
17275 }
17276
17277 });
17278
17279 CanvasSurface.tagName = 'canvas';
17280
17281 var surface = CanvasSurface;
17282
17283 var path = _class({
17284
17285 initialize: function(path){
17286 this.reset().push(path);
17287 },
17288
17289 /* parser */
17290
17291 push: function(){
17292 var p = Array.prototype.join.call(arguments, ' ')
17293 .match(/[a-df-z]|[\-+]?(?:[\d\.]e[\-+]?|[^\s\-+,a-z])+/ig);
17294 if (!p) return this;
17295
17296 var last, cmd = p[0], i = 1;
17297 while (cmd){
17298 switch (cmd){
17299 case 'm': this.move(p[i++], p[i++]); break;
17300 case 'l': this.line(p[i++], p[i++]); break;
17301 case 'c': this.curve(p[i++], p[i++], p[i++], p[i++], p[i++], p[i++]); break;
17302 case 's': this.curve(p[i++], p[i++], null, null, p[i++], p[i++]); break;
17303 case 'q': this.curve(p[i++], p[i++], p[i++], p[i++]); break;
17304 case 't': this.curve(p[i++], p[i++]); break;
17305 case 'a': this.arc(p[i+5], p[i+6], p[i], p[i+1], p[i+3], !+p[i+4], p[i+2]); i += 7; break;
17306 case 'h': this.line(p[i++], 0); break;
17307 case 'v': this.line(0, p[i++]); break;
17308
17309 case 'M': this.moveTo(p[i++], p[i++]); break;
17310 case 'L': this.lineTo(p[i++], p[i++]); break;
17311 case 'C': this.curveTo(p[i++], p[i++], p[i++], p[i++], p[i++], p[i++]); break;
17312 case 'S': this.curveTo(p[i++], p[i++], null, null, p[i++], p[i++]); break;
17313 case 'Q': this.curveTo(p[i++], p[i++], p[i++], p[i++]); break;
17314 case 'T': this.curveTo(p[i++], p[i++]); break;
17315 case 'A': this.arcTo(p[i+5], p[i+6], p[i], p[i+1], p[i+3], !+p[i+4], p[i+2]); i += 7; break;
17316 case 'H': this.lineTo(p[i++], this.penY); break;
17317 case 'V': this.lineTo(this.penX, p[i++]); break;
17318
17319 case 'Z': case 'z': this.close(); break;
17320 default: cmd = last; i--; continue;
17321 }
17322
17323 last = cmd;
17324 if (last == 'm') last = 'l';
17325 else if (last == 'M') last = 'L';
17326 cmd = p[i++];
17327 }
17328 return this;
17329 },
17330
17331 /* utility methods */
17332
17333 reset: function(){
17334 this.penX = this.penY = 0;
17335 this.penDownX = this.penDownY = null;
17336 this._pivotX = this._pivotY = 0;
17337 this.onReset();
17338 return this;
17339 },
17340
17341 move: function(x,y){
17342 this.onMove(this.penX, this.penY, this._pivotX = this.penX += (+x), this._pivotY = this.penY += (+y));
17343 return this;
17344 },
17345 moveTo: function(x,y){
17346 this.onMove(this.penX, this.penY, this._pivotX = this.penX = (+x), this._pivotY = this.penY = (+y));
17347 return this;
17348 },
17349
17350 line: function(x,y){
17351 return this.lineTo(this.penX + (+x), this.penY + (+y));
17352 },
17353 lineTo: function(x,y){
17354 if (this.penDownX == null){ this.penDownX = this.penX; this.penDownY = this.penY; }
17355 this.onLine(this.penX, this.penY, this._pivotX = this.penX = (+x), this._pivotY = this.penY = (+y));
17356 return this;
17357 },
17358
17359 curve: function(c1x, c1y, c2x, c2y, ex, ey){
17360 var x = this.penX, y = this.penY;
17361 return this.curveTo(
17362 x + (+c1x), y + (+c1y),
17363 c2x == null ? null : x + (+c2x),
17364 c2y == null ? null : y + (+c2y),
17365 ex == null ? null : x + (+ex),
17366 ey == null ? null : y + (+ey)
17367 );
17368 },
17369 curveTo: function(c1x, c1y, c2x, c2y, ex, ey){
17370 var x = this.penX, y = this.penY;
17371 if (c2x == null){
17372 c2x = +c1x; c2y = +c1y;
17373 c1x = (x * 2) - (this._pivotX || 0); c1y = (y * 2) - (this._pivotY || 0);
17374 }
17375 if (ex == null){
17376 this._pivotX = +c1x; this._pivotY = +c1y;
17377 ex = +c2x; ey = +c2y;
17378 c2x = (ex + (+c1x) * 2) / 3; c2y = (ey + (+c1y) * 2) / 3;
17379 c1x = (x + (+c1x) * 2) / 3; c1y = (y + (+c1y) * 2) / 3;
17380 } else {
17381 this._pivotX = +c2x; this._pivotY = +c2y;
17382 }
17383 if (this.penDownX == null){ this.penDownX = x; this.penDownY = y; }
17384 this.onBezierCurve(x, y, +c1x, +c1y, +c2x, +c2y, this.penX = +ex, this.penY = +ey);
17385 return this;
17386 },
17387
17388 arc: function(x, y, rx, ry, outer, counterClockwise, rotation){
17389 return this.arcTo(this.penX + (+x), this.penY + (+y), rx, ry, outer, counterClockwise, rotation);
17390 },
17391 arcTo: function(x, y, rx, ry, outer, counterClockwise, rotation){
17392 ry = Math.abs(+ry || +rx || (+y - this.penY));
17393 rx = Math.abs(+rx || (+x - this.penX));
17394
17395 if (!rx || !ry || (x == this.penX && y == this.penY)) return this.lineTo(x, y);
17396
17397 var tX = this.penX, tY = this.penY, clockwise = !+counterClockwise, large = !!+outer;
17398
17399 var rad = rotation ? rotation * Math.PI / 180 : 0, cos = Math.cos(rad), sin = Math.sin(rad);
17400 x -= tX; y -= tY;
17401
17402 // Ellipse Center
17403 var cx = cos * x / 2 + sin * y / 2,
17404 cy = -sin * x / 2 + cos * y / 2,
17405 rxry = rx * rx * ry * ry,
17406 rycx = ry * ry * cx * cx,
17407 rxcy = rx * rx * cy * cy,
17408 a = rxry - rxcy - rycx;
17409
17410 if (a < 0){
17411 a = Math.sqrt(1 - a / rxry);
17412 rx *= a; ry *= a;
17413 cx = x / 2; cy = y / 2;
17414 } else {
17415 a = Math.sqrt(a / (rxcy + rycx));
17416 if (large == clockwise) a = -a;
17417 var cxd = -a * cy * rx / ry,
17418 cyd = a * cx * ry / rx;
17419 cx = cos * cxd - sin * cyd + x / 2;
17420 cy = sin * cxd + cos * cyd + y / 2;
17421 }
17422
17423 // Rotation + Scale Transform
17424 var xx = cos / rx, yx = sin / rx,
17425 xy = -sin / ry, yy = cos / ry;
17426
17427 // Start and End Angle
17428 var sa = Math.atan2(xy * -cx + yy * -cy, xx * -cx + yx * -cy),
17429 ea = Math.atan2(xy * (x - cx) + yy * (y - cy), xx * (x - cx) + yx * (y - cy));
17430
17431 cx += tX; cy += tY;
17432 x += tX; y += tY;
17433
17434 // Circular Arc
17435 if (this.penDownX == null){ this.penDownX = this.penX; this.penDownY = this.penY; }
17436 this.onArc(
17437 tX, tY, this._pivotX = this.penX = x, this._pivotY = this.penY = y,
17438 cx, cy, rx, ry, sa, ea, !clockwise, rotation
17439 );
17440 return this;
17441 },
17442
17443 counterArc: function(x, y, rx, ry, outer){
17444 return this.arc(x, y, rx, ry, outer, true);
17445 },
17446 counterArcTo: function(x, y, rx, ry, outer){
17447 return this.arcTo(x, y, rx, ry, outer, true);
17448 },
17449
17450 close: function(){
17451 if (this.penDownX != null){
17452 this.onClose(this.penX, this.penY, this.penX = this.penDownX, this.penY = this.penDownY);
17453 this.penDownX = null;
17454 }
17455 return this;
17456 },
17457
17458 /* overridable handlers */
17459
17460 onReset: function(){
17461 },
17462
17463 onMove: function(sx, sy, ex, ey){
17464 },
17465
17466 onLine: function(sx, sy, ex, ey){
17467 this.onBezierCurve(sx, sy, sx, sy, ex, ey, ex, ey);
17468 },
17469
17470 onBezierCurve: function(sx, sy, c1x, c1y, c2x, c2y, ex, ey){
17471 var gx = ex - sx, gy = ey - sy,
17472 g = gx * gx + gy * gy,
17473 v1, v2, cx, cy, u;
17474
17475 cx = c1x - sx; cy = c1y - sy;
17476 u = cx * gx + cy * gy;
17477
17478 if (u > g){
17479 cx -= gx;
17480 cy -= gy;
17481 } else if (u > 0 && g != 0){
17482 cx -= u/g * gx;
17483 cy -= u/g * gy;
17484 }
17485
17486 v1 = cx * cx + cy * cy;
17487
17488 cx = c2x - sx; cy = c2y - sy;
17489 u = cx * gx + cy * gy;
17490
17491 if (u > g){
17492 cx -= gx;
17493 cy -= gy;
17494 } else if (u > 0 && g != 0){
17495 cx -= u/g * gx;
17496 cy -= u/g * gy;
17497 }
17498
17499 v2 = cx * cx + cy * cy;
17500
17501 if (v1 < 0.01 && v2 < 0.01){
17502 this.onLine(sx, sy, ex, ey);
17503 return;
17504 }
17505
17506 // Avoid infinite recursion
17507 if (isNaN(v1) || isNaN(v2)){
17508 throw new Error('Bad input');
17509 }
17510
17511 // Split curve
17512 var s1x = (c1x + c2x) * 0.5, s1y = (c1y + c2y) * 0.5,
17513 l1x = (c1x + sx) * 0.5, l1y = (c1y + sy) * 0.5,
17514 l2x = (l1x + s1x) * 0.5, l2y = (l1y + s1y) * 0.5,
17515 r2x = (ex + c2x) * 0.5, r2y = (ey + c2y) * 0.5,
17516 r1x = (r2x + s1x) * 0.5, r1y = (r2y + s1y) * 0.5,
17517 l2r1x = (l2x + r1x) * 0.5, l2r1y = (l2y + r1y) * 0.5;
17518
17519 // TODO: Manual stack if necessary. Currently recursive without tail optimization.
17520 this.onBezierCurve(sx, sy, l1x, l1y, l2x, l2y, l2r1x, l2r1y);
17521 this.onBezierCurve(l2r1x, l2r1y, r1x, r1y, r2x, r2y, ex, ey);
17522 },
17523
17524 onArc: function(sx, sy, ex, ey, cx, cy, rx, ry, sa, ea, ccw, rotation){
17525 // Inverse Rotation + Scale Transform
17526 var rad = rotation ? rotation * Math.PI / 180 : 0, cos = Math.cos(rad), sin = Math.sin(rad),
17527 xx = cos * rx, yx = -sin * ry,
17528 xy = sin * rx, yy = cos * ry;
17529
17530 // Bezier Curve Approximation
17531 var arc = ea - sa;
17532 if (arc < 0 && !ccw) arc += Math.PI * 2;
17533 else if (arc > 0 && ccw) arc -= Math.PI * 2;
17534
17535 var n = Math.ceil(Math.abs(arc / (Math.PI / 2))),
17536 step = arc / n,
17537 k = (4 / 3) * Math.tan(step / 4);
17538
17539 var x = Math.cos(sa), y = Math.sin(sa);
17540
17541 for (var i = 0; i < n; i++){
17542 var cp1x = x - k * y, cp1y = y + k * x;
17543
17544 sa += step;
17545 x = Math.cos(sa); y = Math.sin(sa);
17546
17547 var cp2x = x + k * y, cp2y = y - k * x;
17548
17549 this.onBezierCurve(
17550 sx, sy,
17551 cx + xx * cp1x + yx * cp1y, cy + xy * cp1x + yy * cp1y,
17552 cx + xx * cp2x + yx * cp2y, cy + xy * cp2x + yy * cp2y,
17553 (sx = (cx + xx * x + yx * y)), (sy = (cy + xy * x + yy * y))
17554 );
17555 }
17556 },
17557
17558 onClose: function(sx, sy, ex, ey){
17559 this.onLine(sx, sy, ex, ey);
17560 }
17561
17562 });
17563
17564 var CanvasPath = _class(path, {
17565
17566 initialize: function(path){
17567 this.reset();
17568 if (path instanceof CanvasPath){
17569 this.path = path.path.slice(0);
17570 } else if (path){
17571 if (path.applyToPath)
17572 path.applyToPath(this);
17573 else
17574 this.push(path);
17575 }
17576 },
17577
17578 onReset: function(){
17579 this.path = [];
17580 },
17581
17582 onMove: function(sx, sy, x, y){
17583 this.path.push(function(context){
17584 context.moveTo(x, y);
17585 });
17586 },
17587
17588 onLine: function(sx, sy, x, y){
17589 this.path.push(function(context){
17590 context.lineTo(x, y);
17591 });
17592 },
17593
17594 onBezierCurve: function(sx, sy, p1x, p1y, p2x, p2y, x, y){
17595 this.path.push(function(context){
17596 context.bezierCurveTo(p1x, p1y, p2x, p2y, x, y);
17597 });
17598 },
17599
17600 _arcToBezier: path.prototype.onArc,
17601
17602 onArc: function(sx, sy, ex, ey, cx, cy, rx, ry, sa, ea, ccw, rotation){
17603 if (rx != ry || rotation) return this._arcToBezier(sx, sy, ex, ey, cx, cy, rx, ry, sa, ea, ccw, rotation);
17604 this.path.push(function(context){
17605 context.arc(cx, cy, rx, sa, ea, ccw);
17606 });
17607 },
17608
17609 onClose: function(){
17610 this.path.push(function(context){
17611 context.closePath();
17612 });
17613 },
17614
17615 toCommands: function(){
17616 return this.path.slice(0);
17617 }
17618
17619 });
17620
17621 var path$1 = CanvasPath;
17622
17623 var colors = {
17624 maroon: '#800000', red: '#ff0000', orange: '#ffA500', yellow: '#ffff00', olive: '#808000',
17625 purple: '#800080', fuchsia: "#ff00ff", white: '#ffffff', lime: '#00ff00', green: '#008000',
17626 navy: '#000080', blue: '#0000ff', aqua: '#00ffff', teal: '#008080',
17627 black: '#000000', silver: '#c0c0c0', gray: '#808080'
17628 };
17629
17630 var map = function(array, fn){
17631 var results = [];
17632 for (var i = 0, l = array.length; i < l; i++)
17633 results[i] = fn(array[i], i);
17634 return results;
17635 };
17636
17637 var Color = function(color, type){
17638
17639 if (color.isColor){
17640
17641 this.red = color.red;
17642 this.green = color.green;
17643 this.blue = color.blue;
17644 this.alpha = color.alpha;
17645
17646 } else {
17647
17648 var namedColor = colors[color];
17649 if (namedColor){
17650 color = namedColor;
17651 type = 'hex';
17652 }
17653
17654 switch (typeof color){
17655 case 'string': if (!type) type = (type = color.match(/^rgb|^hsb|^hsl/)) ? type[0] : 'hex'; break;
17656 case 'object': type = type || 'rgb'; color = color.toString(); break;
17657 case 'number': type = 'hex'; color = color.toString(16); break;
17658 }
17659
17660 color = Color['parse' + type.toUpperCase()](color);
17661 this.red = color[0];
17662 this.green = color[1];
17663 this.blue = color[2];
17664 this.alpha = color[3];
17665 }
17666
17667 this.isColor = true;
17668
17669 };
17670
17671 var limit = function(number, min, max){
17672 return Math.min(max, Math.max(min, number));
17673 };
17674
17675 var listMatch = /([-.\d]+\%?)\s*,\s*([-.\d]+\%?)\s*,\s*([-.\d]+\%?)\s*,?\s*([-.\d]*\%?)/;
17676 var hexMatch = /^#?([a-f0-9]{1,2})([a-f0-9]{1,2})([a-f0-9]{1,2})([a-f0-9]{0,2})$/i;
17677
17678 Color.parseRGB = function(color){
17679 return map(color.match(listMatch).slice(1), function(bit, i){
17680 if (bit) bit = parseFloat(bit) * (bit[bit.length - 1] == '%' ? 2.55 : 1);
17681 return (i < 3) ? Math.round(((bit %= 256) < 0) ? bit + 256 : bit) : limit(((bit === '') ? 1 : Number(bit)), 0, 1);
17682 });
17683 };
17684
17685 Color.parseHEX = function(color){
17686 if (color.length == 1) color = color + color + color;
17687 return map(color.match(hexMatch).slice(1), function(bit, i){
17688 if (i == 3) return (bit) ? parseInt(bit, 16) / 255 : 1;
17689 return parseInt((bit.length == 1) ? bit + bit : bit, 16);
17690 });
17691 };
17692
17693 Color.parseHSB = function(color){
17694 var hsb = map(color.match(listMatch).slice(1), function(bit, i){
17695 if (bit) bit = parseFloat(bit);
17696 if (i === 0) return Math.round(((bit %= 360) < 0) ? (bit + 360) : bit);
17697 else if (i < 3) return limit(Math.round(bit), 0, 100);
17698 else return limit(((bit === '') ? 1 : Number(bit)), 0, 1);
17699 });
17700
17701 var a = hsb[3];
17702 var br = Math.round(hsb[2] / 100 * 255);
17703 if (hsb[1] == 0) return [br, br, br, a];
17704
17705 var hue = hsb[0];
17706 var f = hue % 60;
17707 var p = Math.round((hsb[2] * (100 - hsb[1])) / 10000 * 255);
17708 var q = Math.round((hsb[2] * (6000 - hsb[1] * f)) / 600000 * 255);
17709 var t = Math.round((hsb[2] * (6000 - hsb[1] * (60 - f))) / 600000 * 255);
17710
17711 switch (Math.floor(hue / 60)){
17712 case 0: return [br, t, p, a];
17713 case 1: return [q, br, p, a];
17714 case 2: return [p, br, t, a];
17715 case 3: return [p, q, br, a];
17716 case 4: return [t, p, br, a];
17717 default: return [br, p, q, a];
17718 }
17719 };
17720
17721 Color.parseHSL = function(color){
17722 var hsb = map(color.match(listMatch).slice(1), function(bit, i){
17723 if (bit) bit = parseFloat(bit);
17724 if (i === 0) return Math.round(((bit %= 360) < 0) ? (bit + 360) : bit);
17725 else if (i < 3) return limit(Math.round(bit), 0, 100);
17726 else return limit(((bit === '') ? 1 : Number(bit)), 0, 1);
17727 });
17728
17729 var h = hsb[0] / 60;
17730 var s = hsb[1] / 100;
17731 var l = hsb[2] / 100;
17732 var a = hsb[3];
17733
17734 var c = (1 - Math.abs(2 * l - 1)) * s;
17735 var x = c * (1 - Math.abs(h % 2 - 1));
17736 var m = l - c / 2;
17737
17738 var p = Math.round((c + m) * 255);
17739 var q = Math.round((x + m) * 255);
17740 var t = Math.round((m) * 255);
17741
17742 switch (Math.floor(h)){
17743 case 0: return [p, q, t, a];
17744 case 1: return [q, p, t, a];
17745 case 2: return [t, p, q, a];
17746 case 3: return [t, q, p, a];
17747 case 4: return [q, t, p, a];
17748 default: return [p, t, q, a];
17749 }
17750 };
17751
17752 var toString = function(type, array){
17753 if (array[3] != 1) type += 'a';
17754 else array.pop();
17755 return type + '(' + array.join(', ') + ')';
17756 };
17757
17758 Color.prototype = {
17759
17760 toHSB: function(array){
17761 var red = this.red, green = this.green, blue = this.blue, alpha = this.alpha;
17762
17763 var max = Math.max(red, green, blue), min = Math.min(red, green, blue), delta = max - min;
17764 var hue = 0, saturation = (delta != 0) ? delta / max : 0, brightness = max / 255;
17765 if (saturation){
17766 var rr = (max - red) / delta, gr = (max - green) / delta, br = (max - blue) / delta;
17767 hue = (red == max) ? br - gr : (green == max) ? 2 + rr - br : 4 + gr - rr;
17768 if ((hue /= 6) < 0) hue++;
17769 }
17770
17771 var hsb = [Math.round(hue * 360), Math.round(saturation * 100), Math.round(brightness * 100), alpha];
17772
17773 return (array) ? hsb : toString('hsb', hsb);
17774 },
17775
17776 toHSL: function(array){
17777 var red = this.red, green = this.green, blue = this.blue, alpha = this.alpha;
17778
17779 var max = Math.max(red, green, blue), min = Math.min(red, green, blue), delta = max - min;
17780 var hue = 0, saturation = (delta != 0) ? delta / (255 - Math.abs((max + min) - 255)) : 0, lightness = (max + min) / 512;
17781 if (saturation){
17782 var rr = (max - red) / delta, gr = (max - green) / delta, br = (max - blue) / delta;
17783 hue = (red == max) ? br - gr : (green == max) ? 2 + rr - br : 4 + gr - rr;
17784 if ((hue /= 6) < 0) hue++;
17785 }
17786
17787 var hsl = [Math.round(hue * 360), Math.round(saturation * 100), Math.round(lightness * 100), alpha];
17788
17789 return (array) ? hsl : toString('hsl', hsl);
17790 },
17791
17792 toHEX: function(array){
17793
17794 var a = this.alpha;
17795 var alpha = ((a = Math.round((a * 255)).toString(16)).length == 1) ? a + a : a;
17796
17797 var hex = map([this.red, this.green, this.blue], function(bit){
17798 bit = bit.toString(16);
17799 return (bit.length == 1) ? '0' + bit : bit;
17800 });
17801
17802 return (array) ? hex.concat(alpha) : '#' + hex.join('') + ((alpha == 'ff') ? '' : alpha);
17803 },
17804
17805 toRGB: function(array){
17806 var rgb = [this.red, this.green, this.blue, this.alpha];
17807 return (array) ? rgb : toString('rgb', rgb);
17808 }
17809
17810 };
17811
17812 Color.prototype.toString = Color.prototype.toRGB;
17813
17814 Color.hex = function(hex){
17815 return new Color(hex, 'hex');
17816 };
17817
17818 if (commonjsGlobal.hex == null) commonjsGlobal.hex = Color.hex;
17819
17820 Color.hsb = function(h, s, b, a){
17821 return new Color([h || 0, s || 0, b || 0, (a == null) ? 1 : a], 'hsb');
17822 };
17823
17824 if (commonjsGlobal.hsb == null) commonjsGlobal.hsb = Color.hsb;
17825
17826 Color.hsl = function(h, s, l, a){
17827 return new Color([h || 0, s || 0, l || 0, (a == null) ? 1 : a], 'hsl');
17828 };
17829
17830 if (commonjsGlobal.hsl == null) commonjsGlobal.hsl = Color.hsl;
17831
17832 Color.rgb = function(r, g, b, a){
17833 return new Color([r || 0, g || 0, b || 0, (a == null) ? 1 : a], 'rgb');
17834 };
17835
17836 if (commonjsGlobal.rgb == null) commonjsGlobal.rgb = Color.rgb;
17837
17838 Color.detach = function(color){
17839 color = new Color(color);
17840 return [Color.rgb(color.red, color.green, color.blue).toString(), color.alpha];
17841 };
17842
17843 var color = Color;
17844
17845 var dummy = _class({
17846
17847 // placement
17848
17849 _resetPlacement: function(){
17850 var container = this.parentNode;
17851 if (container){
17852 var previous = this.previousSibling, next = this.nextSibling;
17853 if (previous){
17854 previous.nextSibling = next;
17855 } else {
17856 container.firstChild = next;
17857 }
17858 if (next){
17859 next.previousSibling = previous;
17860 } else {
17861 container.lastChild = this.previousSibling;
17862 }
17863 }
17864 this.previousSibling = null;
17865 this.nextSibling = null;
17866 this.parentNode = null;
17867 return this;
17868 },
17869
17870 inject: function(container){
17871 this._resetPlacement();
17872 var last = container.lastChild;
17873 if (last){
17874 last.nextSibling = this;
17875 this.previousSibling = last;
17876 } else {
17877 container.firstChild = this;
17878 }
17879 container.lastChild = this;
17880 this.parentNode = container;
17881 this._place();
17882 return this;
17883 },
17884
17885 injectBefore: function(sibling){
17886 this._resetPlacement();
17887 var container = sibling.parentNode;
17888 if (!container) return this;
17889 var previous = sibling.previousSibling;
17890 if (previous){
17891 previous.nextSibling = this;
17892 this.previousSibling = previous;
17893 } else {
17894 container.firstChild = this;
17895 }
17896 sibling.previousSibling = this;
17897 this.nextSibling = sibling;
17898 this.parentNode = container;
17899 this._place();
17900 return this;
17901 },
17902
17903 eject: function(){
17904 this._resetPlacement();
17905 this._place();
17906 return this;
17907 },
17908
17909 _place: function(){},
17910
17911 // events
17912
17913 dispatch: function(event){
17914 var events = this._events,
17915 listeners = events && events[event.type];
17916 if (listeners){
17917 listeners = listeners.slice(0);
17918 for (var i = 0, l = listeners.length; i < l; i++){
17919 var fn = listeners[i], result;
17920 if (typeof fn == 'function')
17921 result = fn.call(this, event);
17922 else
17923 result = fn.handleEvent(event);
17924 if (result === false) event.preventDefault();
17925 }
17926 }
17927 if (this.parentNode && this.parentNode.dispatch){
17928 this.parentNode.dispatch(event);
17929 }
17930 },
17931
17932 subscribe: function(type, fn, bind){
17933 if (typeof type != 'string'){ // listen type / fn with object
17934 var subscriptions = [];
17935 for (var t in type) subscriptions.push(this.subscribe(t, type[t]));
17936 return function(){ // unsubscribe
17937 for (var i = 0, l = subscriptions.length; i < l; i++)
17938 subscriptions[i]();
17939 return this;
17940 };
17941 } else { // listen to one
17942 var bound = typeof fn === 'function' ? fn.bind(bind || this) : fn,
17943 events = this._events || (this._events = {}),
17944 listeners = events[type] || (events[type] = []);
17945 listeners.push(bound);
17946 return function(){
17947 // unsubscribe
17948 for (var i = 0, l = listeners.length; i < l; i++){
17949 if (listeners[i] === bound){
17950 listeners.splice(i, 1);
17951 break;
17952 }
17953 }
17954 }
17955 }
17956 }
17957
17958 });
17959
17960 var CanvasNode = _class(transform, dummy, {
17961
17962 invalidate: function(){
17963 if (this.parentNode) this.parentNode.invalidate();
17964 if (this._layer) this._layerCache = null;
17965 return this;
17966 },
17967
17968 _place: function(){
17969 this.invalidate();
17970 },
17971
17972 _transform: function(){
17973 this.invalidate();
17974 },
17975
17976 blend: function(opacity){
17977 if (opacity >= 1 && this._layer) this._layer = null;
17978 this._opacity = opacity;
17979 if (this.parentNode) this.parentNode.invalidate();
17980 return this;
17981 },
17982
17983 // visibility
17984
17985 hide: function(){
17986 this._invisible = true;
17987 if (this.parentNode) this.parentNode.invalidate();
17988 return this;
17989 },
17990
17991 show: function(){
17992 this._invisible = false;
17993 if (this.parentNode) this.parentNode.invalidate();
17994 return this;
17995 },
17996
17997 // interaction
17998
17999 indicate: function(cursor, tooltip){
18000 this._cursor = cursor;
18001 this._tooltip = tooltip;
18002 return this.invalidate();
18003 },
18004
18005 hitTest: function(x, y){
18006 if (this._invisible) return null;
18007 var point = this.inversePoint(x, y);
18008 if (!point) return null;
18009 return this.localHitTest(point.x, point.y);
18010 },
18011
18012 // rendering
18013
18014 renderTo: function(context, xx, yx, xy, yy, x, y){
18015 var opacity = this._opacity;
18016 if (opacity == null || opacity >= 1){
18017 return this.renderLayerTo(context, xx, yx, xy, yy, x, y);
18018 }
18019
18020 // Render to a compositing layer and cache it
18021
18022 var layer = this._layer, canvas, isDirty = true,
18023 w = context.canvas.width, h = context.canvas.height;
18024 if (layer){
18025 layer.setTransform(1, 0, 0, 1, 0, 0);
18026 canvas = layer.canvas;
18027 if (canvas.width < w || canvas.height < h){
18028 canvas.width = w;
18029 canvas.height = h;
18030 } else {
18031 var c = this._layerCache;
18032 if (c && c.xx === xx && c.yx === yx && c.xy === xy
18033 && c.yy === yy && c.x === x && c.y === y){
18034 isDirty = false;
18035 } else {
18036 layer.clearRect(0, 0, w, h);
18037 }
18038 }
18039 } else {
18040 canvas = document.createElement('canvas');
18041 canvas.width = w;
18042 canvas.height = h;
18043 this._layer = layer = canvas.getContext('2d');
18044 }
18045
18046 if (isDirty){
18047 this.renderLayerTo(layer, xx, yx, xy, yy, x, y);
18048 this._layerCache = {
18049 xx: xx,
18050 yx: yx,
18051 xy: xy,
18052 yy: yy,
18053 x: x,
18054 y: y
18055 };
18056 }
18057
18058 context.globalAlpha = opacity;
18059 context.setTransform(1, 0, 0, 1, 0, 0);
18060 context.drawImage(
18061 canvas,
18062 0, 0, w, h,
18063 0, 0, w, h
18064 );
18065 context.globalAlpha = 1;
18066 }
18067
18068 });
18069
18070 var node = CanvasNode;
18071
18072 var genericCanvas = typeof document !== 'undefined' && document.createElement('canvas'),
18073 genericContext = genericCanvas && genericCanvas.getContext && genericCanvas.getContext('2d');
18074
18075 function recolorImage(img, color1, color2){
18076 // TODO: Fix this experimental implementation
18077 color1 = color.detach(color1);
18078 color2 = color.detach(color2);
18079 var canvas = document.createElement('canvas'),
18080 context = canvas.getContext('2d');
18081 canvas.width = img.width;
18082 canvas.height = img.height;
18083 context.fillStyle = color2[0];
18084 context.fillRect(0, 0, img.width, img.height);
18085 context.globalCompositeOperation = 'lighter';
18086 context.drawImage(img, 0, 0);
18087 return canvas;
18088 }
18089
18090 var Base = _class(node, {
18091
18092 initialize: function(){
18093 this._fill = null;
18094 this._pendingFill = null;
18095 this._fillTransform = null;
18096 this._stroke = null;
18097 this._strokeCap = null;
18098 this._strokeDash = null;
18099 this._strokeJoin = null;
18100 this._strokeWidth = null;
18101 },
18102
18103 /* styles */
18104
18105 _addColors: function(gradient, stops){
18106 // Enumerate stops, assumes offsets are enumerated in order
18107 // TODO: Sort. Chrome doesn't always enumerate in expected order but requires stops to be specified in order.
18108 if ('length' in stops) for (var i = 0, l = stops.length - 1; i <= l; i++)
18109 gradient.addColorStop(i / l, new color(stops[i]).toString());
18110 else for (var offset in stops)
18111 gradient.addColorStop(offset, new color(stops[offset]).toString());
18112 return gradient;
18113 },
18114
18115
18116 fill: function(color$1){
18117 if (arguments.length > 1) return this.fillLinear(arguments);
18118 if (this._pendingFill) this._pendingFill();
18119 this._fill = color$1 ? new color(color$1).toString() : null;
18120 return this.invalidate();
18121 },
18122
18123 fillRadial: function(stops, focusX, focusY, radiusX, radiusY, centerX, centerY){
18124 if (focusX == null) focusX = (this.left || 0) + (this.width || 0) * 0.5;
18125 if (focusY == null) focusY = (this.top || 0) + (this.height || 0) * 0.5;
18126 if (radiusY == null) radiusY = radiusX || (this.height * 0.5) || 0;
18127 if (radiusX == null) radiusX = (this.width || 0) * 0.5;
18128 if (centerX == null) centerX = focusX;
18129 if (centerY == null) centerY = focusY;
18130
18131 centerX += centerX - focusX;
18132 centerY += centerY - focusY;
18133
18134 if (radiusX === 0 || radiusX === '0') return this.fillLinear(stops);
18135 var ys = radiusY / radiusX;
18136
18137 if (this._pendingFill) this._pendingFill();
18138
18139 var gradient = genericContext.createRadialGradient(focusX, focusY / ys, 0, centerX, centerY / ys, radiusX * 2);
18140
18141 // Double fill radius to simulate repeating gradient
18142 if ('length' in stops) for (var i = 0, l = stops.length - 1; i <= l; i++){
18143 gradient.addColorStop(i / l / 2, new color(stops[i]).toString());
18144 gradient.addColorStop(1 - i / l / 2, new color(stops[i]).toString());
18145 } else for (var offset in stops){
18146 gradient.addColorStop(offset / 2, new color(stops[offset]).toString());
18147 gradient.addColorStop(1- offset / 2, new color(stops[offset]).toString());
18148 }
18149
18150 this._fill = gradient;
18151 this._fillTransform = new transform(1, 0, 0, ys);
18152 return this.invalidate();
18153 },
18154
18155 fillLinear: function(stops, x1, y1, x2, y2){
18156 if (arguments.length < 5){
18157 var angle = ((x1 == null) ? 270 : x1) * Math.PI / 180;
18158
18159 var x = Math.cos(angle), y = -Math.sin(angle),
18160 l = (Math.abs(x) + Math.abs(y)) / 2,
18161 w = this.width || 1, h = this.height || 1;
18162
18163 x *= l; y *= l;
18164
18165 x1 = 0.5 - x;
18166 x2 = 0.5 + x;
18167 y1 = 0.5 - y;
18168 y2 = 0.5 + y;
18169 this._fillTransform = new transform(w, 0, 0, h);
18170 } else {
18171 this._fillTransform = null;
18172 }
18173 if (this._pendingFill) this._pendingFill();
18174 var gradient = genericContext.createLinearGradient(x1, y1, x2, y2);
18175 this._addColors(gradient, stops);
18176 this._fill = gradient;
18177 return this.invalidate();
18178 },
18179
18180 fillImage: function(url, width, height, left, top, color1, color2){
18181 if (this._pendingFill) this._pendingFill();
18182 var img = url;
18183 if (!(img instanceof Image)){
18184 img = new Image();
18185 img.src = url;
18186 }
18187 if (img.width && img.height){
18188 return this._fillImage(img, width, height, left || 0, top || 0, color1, color2);
18189 }
18190
18191 // Not yet loaded
18192 this._fill = null;
18193 var self = this,
18194 callback = function(){
18195 cancel();
18196 self._fillImage(img, width, height, left || 0, top || 0, color1, color2);
18197 },
18198 cancel = function(){
18199 img.removeEventListener('load', callback, false);
18200 self._pendingFill = null;
18201 };
18202 this._pendingFill = cancel;
18203 img.addEventListener('load', callback, false);
18204 return this;
18205 },
18206
18207 _fillImage: function(img, width, height, left, top, color1, color2){
18208 var w = width ? width / img.width : 1,
18209 h = height ? height / img.height : 1;
18210 if (color1 != null) img = recolorImage(img, color1, color2);
18211 this._fill = genericContext.createPattern(img, 'repeat');
18212 this._fillTransform = new transform(w, 0, 0, h, left || 0, top || 0);
18213 return this.invalidate();
18214 },
18215
18216 stroke: function(color$1, width, cap, join, dash){
18217 this._stroke = color$1 ? new color(color$1).toString() : null;
18218 this._strokeWidth = (width != null) ? width : 1;
18219 this._strokeCap = (cap != null) ? cap : 'round';
18220 this._strokeJoin = (join != null) ? join : 'round';
18221 this._strokeDash = dash;
18222 return this.invalidate();
18223 },
18224
18225 // Rendering
18226
18227 element_renderTo: node.prototype.renderTo,
18228
18229 renderTo: function(context, xx, yx, xy, yy, x, y){
18230 var opacity = this._opacity;
18231 if (opacity == null || opacity >= 1){
18232 return this.renderLayerTo(context, xx, yx, xy, yy, x, y);
18233 }
18234 if (this._fill && this._stroke){
18235 return this.element_renderTo(context, xx, yx, xy, yy, x, y);
18236 }
18237 context.globalAlpha = opacity;
18238 var r = this.renderLayerTo(context, xx, yx, xy, yy, x, y);
18239 context.globalAlpha = 1;
18240 return r;
18241 },
18242
18243 renderLayerTo: function(context, xx, yx, xy, yy, x, y){
18244 context.setTransform(xx, yx, xy, yy, x, y);
18245 this.renderShapeTo(context);
18246 }
18247
18248 });
18249
18250 Base._genericContext = genericContext;
18251
18252 var base = Base;
18253
18254 var shape = _class(base, {
18255
18256 base_initialize: base.prototype.initialize,
18257
18258 initialize: function(path, width, height){
18259 this.base_initialize();
18260 this.width = width;
18261 this.height = height;
18262 if (path != null) this.draw(path);
18263 },
18264
18265 draw: function(path, width, height){
18266 if (!(path instanceof path$1)) path = new path$1(path);
18267 this.path = path;
18268 this._commands = path.toCommands();
18269 if (width != null) this.width = width;
18270 if (height != null) this.height = height;
18271 return this.invalidate();
18272 },
18273
18274 localHitTest: function(x, y){
18275 if (!this._fill) return null;
18276 if (this.width == null || this.height == null){
18277 var context = base._genericContext, commands = this._commands;
18278 if (!commands) return null;
18279 context.beginPath();
18280 for (var i = 0, l = commands.length; i < l; i++)
18281 commands[i](context);
18282 return context.isPointInPath(x, y) ? this : null;
18283 }
18284 if (x > 0 && y > 0 && x < this.width && y < this.height){
18285 return this;
18286 }
18287 return null;
18288 },
18289
18290 renderShapeTo: function(context){
18291 if (this._invisible || !this._commands || (!this._fill && !this._stroke)) {
18292 return null;
18293 }
18294 context.transform(this.xx, this.yx, this.xy, this.yy, this.x, this.y);
18295 var commands = this._commands,
18296 fill = this._fill,
18297 stroke = this._stroke,
18298 dash = this._strokeDash;
18299
18300 context.beginPath();
18301
18302 if (dash) {
18303 if (context.setLineDash) {
18304 context.setLineDash(dash);
18305 } else {
18306 // TODO: Remove when FF supports setLineDash.
18307 context.mozDash = dash;
18308 }
18309 // TODO: Create fallback to other browsers.
18310 } else {
18311 if (context.setLineDash) {
18312 context.setLineDash([]);
18313 } else {
18314 context.mozDash = null;
18315 }
18316 }
18317
18318 for (var i = 0, l = commands.length; i < l; i++)
18319 commands[i](context);
18320
18321 if (fill){
18322 var m = this._fillTransform;
18323 if (m){
18324 context.save(); // TODO: Optimize away this by restoring the transform before stroking
18325 context.transform(m.xx, m.yx, m.xy, m.yy, m.x, m.y);
18326 context.fillStyle = fill;
18327 context.fill();
18328 context.restore();
18329 } else {
18330 context.fillStyle = fill;
18331 context.fill();
18332 }
18333 }
18334 if (stroke){
18335 context.strokeStyle = stroke;
18336 context.lineWidth = this._strokeWidth;
18337 context.lineCap = this._strokeCap;
18338 context.lineJoin = this._strokeJoin;
18339 context.stroke();
18340 }
18341 }
18342
18343 });
18344
18345 var group = _class(node, container, {
18346
18347 initialize: function(width, height){
18348 this.width = width;
18349 this.height = height;
18350 },
18351
18352 localHitTest: function(x, y){
18353 var node = this.lastChild;
18354 while (node){
18355 var hit = node.hitTest(x, y);
18356 if (hit) return hit;
18357 node = node.previousSibling;
18358 }
18359 return null;
18360 },
18361
18362 renderLayerTo: function(context, xx, yx, xy, yy, x, y){
18363 if (this._invisible) return;
18364
18365 x = xx * this.x + xy * this.y + x;
18366 y = yx * this.x + yy * this.y + y;
18367
18368 var t = xx;
18369 xx = t * this.xx + xy * this.yx;
18370 xy = t * this.xy + xy * this.yy;
18371 t = yx;
18372 yx = t * this.xx + yy * this.yx;
18373 yy = t * this.xy + yy * this.yy;
18374
18375 var node = this.firstChild;
18376 while (node){
18377 node.renderTo(context, xx, yx, xy, yy, x, y);
18378 node = node.nextSibling;
18379 }
18380 }
18381
18382 });
18383
18384 var clippingrectangle = _class(node, container, {
18385
18386 initialize: function(width, height){
18387 this.width = width;
18388 this.height = height;
18389 },
18390
18391 localHitTest: function(x, y) {
18392 var node = this.lastChild;
18393 while (node){
18394 var hit = node.hitTest(x, y);
18395 if (hit) return hit;
18396 node = node.previousSibling;
18397 }
18398 return null;
18399 },
18400
18401 renderLayerTo: function(context, xx, yx, xy, yy, x, y) {
18402 context.setTransform(xx, yx, xy, yy, x, y);
18403 context.save();
18404 // Need beginPath to fix Firefox bug. See 3354054.
18405 context.beginPath();
18406 context.rect(this.x, this.y, this.width, this.height);
18407 context.clip();
18408
18409 var node = this.firstChild;
18410 while(node) {
18411 node.renderTo(context, xx, yx, xy, yy, x, y);
18412 node = node.nextSibling;
18413 }
18414 context.restore();
18415 }
18416 });
18417
18418 var fontAnchors = { middle: 'center' };
18419
18420 var text = _class(base, {
18421
18422 base_initialize: base.prototype.initialize,
18423
18424 initialize: function(text, font, alignment, path){
18425 this.base_initialize();
18426 this.draw.apply(this, arguments);
18427 },
18428
18429 draw: function(text, font, alignment, path){
18430 var em;
18431 if (typeof font == 'string'){
18432 em = Number(/(\d+)/.exec(font)[0]);
18433 } else if (font){
18434 em = parseFloat(font.fontSize || font['font-size'] || '12');
18435 font = (font.fontStyle || font['font-style'] || '') + ' ' +
18436 (font.fontVariant || font['font-variant'] || '') + ' ' +
18437 (font.fontWeight || font['font-weight'] || '') + ' ' +
18438 em + 'px ' +
18439 (font.fontFamily || font['font-family'] || 'Arial');
18440 } else {
18441 font = this._font;
18442 }
18443
18444 var lines = text && text.split(/\r?\n/);
18445 this._font = font;
18446 this._fontSize = em;
18447 this._text = lines;
18448 this._alignment = fontAnchors[alignment] || alignment || 'left';
18449
18450 var context = base._genericContext;
18451
18452 context.font = this._font;
18453 context.textAlign = this._alignment;
18454 context.textBaseline = 'middle';
18455
18456 lines = this._text;
18457 var l = lines.length, width = 0;
18458 for (var i = 0; i < l; i++){
18459 var w = context.measureText(lines[i]).width;
18460 if (w > width) width = w;
18461 }
18462 this.width = width;
18463 this.height = l ? l * 1.1 * em : 0;
18464 return this.invalidate();
18465 },
18466
18467 // Interaction
18468
18469 localHitTest: function(x, y){
18470 if (!this._fill) return null;
18471 if (x > 0 && y > 0 && x < this.width && y < this.height){
18472 return this;
18473 }
18474 return null;
18475 },
18476
18477 // Rendering
18478
18479 renderShapeTo: function(context){
18480 if (this._invisible || !this._text || (!this._fill && !this._stroke)) {
18481 return null;
18482 }
18483 context.transform(this.xx, this.yx, this.xy, this.yy, this.x, this.y);
18484 var fill = this._fill,
18485 stroke = this._stroke,
18486 text = this._text,
18487 dash = this._strokeDash;
18488
18489 context.font = this._font;
18490 context.textAlign = this._alignment;
18491 context.textBaseline = 'middle';
18492
18493 var em = this._fontSize,
18494 y = em / 2,
18495 lineHeight = 1.1 * em,
18496 lines = text,
18497 l = lines.length;
18498
18499 if (fill){
18500 context.fillStyle = fill;
18501 for (var i = 0; i < l; i++)
18502 context.fillText(lines[i], 0, y + i * lineHeight);
18503 }
18504 if (stroke){
18505 if (dash) {
18506 if (context.setLineDash) {
18507 context.setLineDash(dash);
18508 } else {
18509 // TODO: Remove when FF supports setLineDash.
18510 context.mozDash = dash;
18511 }
18512 // TODO: Create fallback to other browsers.
18513 } else {
18514 if (context.setLineDash) {
18515 context.setLineDash([]);
18516 } else {
18517 context.mozDash = null;
18518 }
18519 }
18520
18521 context.strokeStyle = stroke;
18522 context.lineWidth = this._strokeWidth;
18523 context.lineCap = this._strokeCap;
18524 context.lineJoin = this._strokeJoin;
18525 for (i = 0; i < l; i++)
18526 context.strokeText(lines[i], 0, y + i * lineHeight);
18527 }
18528 }
18529
18530 });
18531
18532 var VMLCSS = 'behavior:url(#default#VML);display:inline-block;position:absolute;left:0px;top:0px;';
18533
18534 var styleSheet, styledTags = {}, styleTag = function(tag){
18535 if (styleSheet) styledTags[tag] = styleSheet.addRule('av\\:' + tag, VMLCSS);
18536 };
18537
18538 var init = function(document){
18539
18540 var namespaces;
18541 try { // IE9 workaround: sometimes it throws here
18542 namespaces = document.namespaces;
18543 } catch (e) {
18544 }
18545 if (!namespaces) return false;
18546
18547 namespaces.add('av', 'urn:schemas-microsoft-com:vml');
18548 namespaces.add('ao', 'urn:schemas-microsoft-com:office:office');
18549
18550 styleSheet = document.createStyleSheet();
18551 styleSheet.addRule('vml', 'display:inline-block;position:relative;overflow:hidden;');
18552 /* styleTag('skew');
18553 styleTag('fill');
18554 styleTag('stroke');
18555 styleTag('path');
18556 styleTag('textpath');
18557 styleTag('group');*/
18558
18559 styleTag('vml');
18560
18561 return true;
18562
18563 };
18564
18565 var createElement = function(tag){
18566 if (!(tag in styledTags)) styleTag(tag);
18567 return document.createElement('av:' + tag);
18568 };
18569
18570 var dom = {
18571 init: init,
18572 createElement: createElement
18573 };
18574
18575 var precision = 100;
18576
18577 var VMLSurface = _class(native_1, container, {
18578
18579 initialize: function VMLSurface(width, height, existingElement){
18580 this.element = existingElement || document.createElement('vml');
18581 this.containerElement = dom.createElement('group');
18582 this.element.appendChild(this.containerElement);
18583 if (width != null && height != null) this.resize(width, height);
18584 },
18585
18586 resize: function(width, height){
18587 this.width = width;
18588 this.height = height;
18589
18590 var style = this.element.style;
18591 style.pixelWidth = width;
18592 style.pixelHeight = height;
18593
18594 style = this.containerElement.style;
18595 style.width = width;
18596 style.height = height;
18597
18598 var halfPixel = (0.5 * precision);
18599
18600 this.containerElement.coordorigin = halfPixel + ',' + halfPixel;
18601 this.containerElement.coordsize = (width * precision) + ',' + (height * precision);
18602
18603 return this;
18604 }
18605
18606 });
18607
18608 VMLSurface.tagName = 'av:vml';
18609
18610 var surface$1 = VMLSurface;
18611
18612 var precision$1 = 100;
18613
18614 var round = Math.round;
18615
18616 var VMLPath = _class(path, {
18617
18618 initialize: function(path){
18619 this.reset();
18620 if (path instanceof VMLPath){
18621 this.path = [Array.prototype.join.call(path.path, ' ')];
18622 } else if (path){
18623 if (path.applyToPath)
18624 path.applyToPath(this);
18625 else
18626 this.push(path);
18627 }
18628 },
18629
18630 onReset: function(){
18631 this.path = [];
18632 },
18633
18634 onMove: function(sx, sy, x, y){
18635 this.path.push('m', round(x * precision$1), round(y * precision$1));
18636 },
18637
18638 onLine: function(sx, sy, x, y){
18639 this.path.push('l', round(x * precision$1), round(y * precision$1));
18640 },
18641
18642 onBezierCurve: function(sx, sy, p1x, p1y, p2x, p2y, x, y){
18643 this.path.push('c',
18644 round(p1x * precision$1), round(p1y * precision$1),
18645 round(p2x * precision$1), round(p2y * precision$1),
18646 round(x * precision$1), round(y * precision$1)
18647 );
18648 },
18649
18650 _arcToBezier: path.prototype.onArc,
18651
18652 onArc: function(sx, sy, ex, ey, cx, cy, rx, ry, sa, ea, ccw, rotation){
18653 if (rx != ry || rotation) return this._arcToBezier(sx, sy, ex, ey, cx, cy, rx, ry, sa, ea, ccw, rotation);
18654 cx *= precision$1;
18655 cy *= precision$1;
18656 rx *= precision$1;
18657 this.path.push(ccw ? 'at' : 'wa',
18658 round(cx - rx), round(cy - rx),
18659 round(cx + rx), round(cy + rx),
18660 round(sx * precision$1), round(sy * precision$1),
18661 round(ex * precision$1), round(ey * precision$1)
18662 );
18663 },
18664
18665 onClose: function(){
18666 this.path.push('x');
18667 },
18668
18669 toVML: function(){
18670 return this.path.join(' ');
18671 }
18672
18673 });
18674
18675 VMLPath.prototype.toString = VMLPath.prototype.toVML;
18676
18677 var path$2 = VMLPath;
18678
18679 var shadow = _class(dummy, native_1, {
18680
18681 dummy_inject: dummy.prototype.inject,
18682 dummy_injectBefore: dummy.prototype.injectBefore,
18683 dummy_eject: dummy.prototype.eject,
18684 native_inject: native_1.prototype.inject,
18685 native_injectBefore: native_1.prototype.injectBefore,
18686 native_eject: native_1.prototype.eject,
18687
18688 inject: function(container){
18689 this.dummy_inject(container);
18690 this.native_inject(container);
18691 return this;
18692 },
18693
18694 injectBefore: function(sibling){
18695 this.dummy_injectBefore(sibling);
18696 this.native_injectBefore(sibling);
18697 return this;
18698 },
18699
18700 eject: function(){
18701 this.dummy_eject();
18702 this.native_eject();
18703 return this;
18704 }
18705
18706 });
18707
18708 var node$1 = _class(shadow, transform, {
18709
18710 initialize: function(tag){
18711 //this.uid = uniqueID();
18712 var element = this.element = dom.createElement(tag);
18713 //element.setAttribute('id', 'e' + this.uid);
18714 },
18715
18716 _place: function(){
18717 if (this.parentNode){
18718 this._transform();
18719 }
18720 },
18721
18722 // visibility
18723
18724 hide: function(){
18725 this.element.style.display = 'none';
18726 return this;
18727 },
18728
18729 show: function(){
18730 this.element.style.display = '';
18731 return this;
18732 },
18733
18734 // interaction
18735
18736 indicate: function(cursor, tooltip){
18737 if (cursor) this.element.style.cursor = cursor;
18738 if (tooltip) this.element.title = tooltip;
18739 return this;
18740 }
18741
18742 });
18743
18744 var precision$2 = 100;
18745
18746 var defaultBox = { left: 0, top: 0, width: 500, height: 500 };
18747
18748 var base$1 = _class(node$1, {
18749
18750 element_initialize: node$1.prototype.initialize,
18751
18752 initialize: function(tag){
18753 this.element_initialize(tag);
18754 var element = this.element;
18755
18756 var skew = this.skewElement = dom.createElement('skew');
18757 skew.on = true;
18758 element.appendChild(skew);
18759
18760 var fill = this.fillElement = dom.createElement('fill');
18761 fill.on = false;
18762 element.appendChild(fill);
18763
18764 var stroke = this.strokeElement = dom.createElement('stroke');
18765 stroke.on = false;
18766 element.appendChild(stroke);
18767 },
18768
18769 /* transform */
18770
18771 _transform: function(){
18772 var container = this.parentNode;
18773
18774 // Active Transformation Matrix
18775 var m = container ? new transform(container._activeTransform).transform(this) : this;
18776
18777 // Box in shape user space
18778
18779 var box = this._boxCoords || this._size || defaultBox;
18780
18781 var originX = box.left || 0,
18782 originY = box.top || 0,
18783 width = box.width || 1,
18784 height = box.height || 1;
18785
18786 // Flipped
18787 var flip = m.yx / m.xx > m.yy / m.xy;
18788 if (m.xx < 0 ? m.xy >= 0 : m.xy < 0) flip = !flip;
18789 flip = flip ? -1 : 1;
18790
18791 m = new transform().scale(flip, 1).transform(m);
18792
18793 // Rotation is approximated based on the transform
18794 var rotation = Math.atan2(-m.xy, m.yy) * 180 / Math.PI;
18795
18796 // Reverse the rotation, leaving the final transform in box space
18797 var rad = rotation * Math.PI / 180, sin = Math.sin(rad), cos = Math.cos(rad);
18798
18799 var transform$1 = new transform(
18800 (m.xx * cos - m.xy * sin),
18801 (m.yx * cos - m.yy * sin) * flip,
18802 (m.xy * cos + m.xx * sin) * flip,
18803 (m.yy * cos + m.yx * sin)
18804 );
18805
18806 var rotationTransform = new transform().rotate(rotation, 0, 0);
18807
18808 var shapeToBox = new transform().rotate(-rotation, 0, 0).transform(m).moveTo(0,0);
18809
18810 // Scale box after reversing rotation
18811 width *= Math.abs(shapeToBox.xx);
18812 height *= Math.abs(shapeToBox.yy);
18813
18814 // Place box
18815 var left = m.x, top = m.y;
18816
18817 // Compensate for offset by center origin rotation
18818 var vx = -width / 2, vy = -height / 2;
18819 var point = rotationTransform.point(vx, vy);
18820 left -= point.x - vx;
18821 top -= point.y - vy;
18822
18823 // Adjust box position based on offset
18824 var rsm = new transform(m).moveTo(0,0);
18825 point = rsm.point(originX, originY);
18826 left += point.x;
18827 top += point.y;
18828
18829 if (flip < 0) left = -left - width;
18830
18831 // Place transformation origin
18832 var point0 = rsm.point(-originX, -originY);
18833 var point1 = rotationTransform.point(width, height);
18834 var point2 = rotationTransform.point(width, 0);
18835 var point3 = rotationTransform.point(0, height);
18836
18837 var minX = Math.min(0, point1.x, point2.x, point3.x),
18838 maxX = Math.max(0, point1.x, point2.x, point3.x),
18839 minY = Math.min(0, point1.y, point2.y, point3.y),
18840 maxY = Math.max(0, point1.y, point2.y, point3.y);
18841
18842 var transformOriginX = (point0.x - point1.x / 2) / (maxX - minX) * flip,
18843 transformOriginY = (point0.y - point1.y / 2) / (maxY - minY);
18844
18845 // Adjust the origin
18846 point = shapeToBox.point(originX, originY);
18847 originX = point.x;
18848 originY = point.y;
18849
18850 // Scale stroke
18851 var strokeWidth = this._strokeWidth;
18852 if (strokeWidth){
18853 // Scale is the hypothenus between the two vectors
18854 // TODO: Use area calculation instead
18855 var vx = m.xx + m.xy, vy = m.yy + m.yx;
18856 strokeWidth *= Math.sqrt(vx * vx + vy * vy) / Math.sqrt(2);
18857 }
18858
18859 // convert to multiplied precision space
18860 originX *= precision$2;
18861 originY *= precision$2;
18862 left *= precision$2;
18863 top *= precision$2;
18864 width *= precision$2;
18865 height *= precision$2;
18866
18867 // Set box
18868 var element = this.element;
18869 element.coordorigin = originX + ',' + originY;
18870 element.coordsize = width + ',' + height;
18871 element.style.left = left + 'px';
18872 element.style.top = top + 'px';
18873 element.style.width = width;
18874 element.style.height = height;
18875 element.style.rotation = rotation.toFixed(8);
18876 element.style.flip = flip < 0 ? 'x' : '';
18877
18878 // Set transform
18879 var skew = this.skewElement;
18880 skew.matrix = [transform$1.xx.toFixed(4), transform$1.xy.toFixed(4), transform$1.yx.toFixed(4), transform$1.yy.toFixed(4), 0, 0];
18881 skew.origin = transformOriginX + ',' + transformOriginY;
18882
18883 // Set stroke
18884 this.strokeElement.weight = strokeWidth + 'px';
18885 },
18886
18887 /* styles */
18888
18889 _createGradient: function(style, stops){
18890 var fill = this.fillElement;
18891
18892 // Temporarily eject the fill from the DOM
18893 this.element.removeChild(fill);
18894
18895 fill.type = style;
18896 fill.method = 'none';
18897 fill.rotate = true;
18898
18899 var colors = [], color1, color2;
18900
18901 var addColor = function(offset, color$1){
18902 color$1 = color.detach(color$1);
18903 if (color1 == null) color1 = color2 = color$1;
18904 else color2 = color$1;
18905 colors.push(offset + ' ' + color$1[0]);
18906 };
18907
18908 // Enumerate stops, assumes offsets are enumerated in order
18909 if ('length' in stops) for (var i = 0, l = stops.length - 1; i <= l; i++) addColor(i / l, stops[i]);
18910 else for (var offset in stops) addColor(offset, stops[offset]);
18911
18912 fill.color = color1[0];
18913 fill.color2 = color2[0];
18914
18915 //if (fill.colors) fill.colors.value = colors; else
18916 fill.colors = colors;
18917
18918 // Opacity order gets flipped when color stops are specified
18919 fill.opacity = color2[1];
18920 fill['ao:opacity2'] = color1[1];
18921
18922 fill.on = true;
18923 this.element.appendChild(fill);
18924 return fill;
18925 },
18926
18927 _setColor: function(type, color$1){
18928 var element = type == 'fill' ? this.fillElement : this.strokeElement;
18929 if (color$1 == null){
18930 element.on = false;
18931 } else {
18932 color$1 = color.detach(color$1);
18933 element.color = color$1[0];
18934 element.opacity = color$1[1];
18935 element.on = true;
18936 }
18937 },
18938
18939 fill: function(color){
18940 if (arguments.length > 1){
18941 this.fillLinear(arguments);
18942 } else {
18943 this._boxCoords = defaultBox;
18944 var fill = this.fillElement;
18945 fill.type = 'solid';
18946 fill.color2 = '';
18947 fill['ao:opacity2'] = '';
18948 if (fill.colors) fill.colors.value = '';
18949 this._setColor('fill', color);
18950 }
18951 return this;
18952 },
18953
18954 fillRadial: function(stops, focusX, focusY, radiusX, radiusY, centerX, centerY){
18955 var fill = this._createGradient('gradientradial', stops);
18956 if (focusX == null) focusX = this.left + this.width * 0.5;
18957 if (focusY == null) focusY = this.top + this.height * 0.5;
18958 if (radiusY == null) radiusY = radiusX || (this.height * 0.5);
18959 if (radiusX == null) radiusX = this.width * 0.5;
18960 if (centerX == null) centerX = focusX;
18961 if (centerY == null) centerY = focusY;
18962
18963 centerX += centerX - focusX;
18964 centerY += centerY - focusY;
18965
18966 var box = this._boxCoords = {
18967 left: centerX - radiusX * 2,
18968 top: centerY - radiusY * 2,
18969 width: radiusX * 4,
18970 height: radiusY * 4
18971 };
18972 focusX -= box.left;
18973 focusY -= box.top;
18974 focusX /= box.width;
18975 focusY /= box.height;
18976
18977 fill.focussize = '0 0';
18978 fill.focusposition = focusX + ',' + focusY;
18979 fill.focus = '50%';
18980
18981 this._transform();
18982
18983 return this;
18984 },
18985
18986 fillLinear: function(stops, x1, y1, x2, y2){
18987 var fill = this._createGradient('gradient', stops);
18988 fill.focus = '100%';
18989 if (arguments.length == 5){
18990 var w = Math.abs(x2 - x1), h = Math.abs(y2 - y1);
18991 this._boxCoords = {
18992 left: Math.min(x1, x2),
18993 top: Math.min(y1, y2),
18994 width: w < 1 ? h : w,
18995 height: h < 1 ? w : h
18996 };
18997 fill.angle = (360 + Math.atan2((x2 - x1) / h, (y2 - y1) / w) * 180 / Math.PI) % 360;
18998 } else {
18999 this._boxCoords = null;
19000 fill.angle = (x1 == null) ? 0 : (90 + x1) % 360;
19001 }
19002 this._transform();
19003 return this;
19004 },
19005
19006 fillImage: function(url, width, height, left, top, color1, color2){
19007 var fill = this.fillElement;
19008 if (color1 != null){
19009 color1 = color.detach(color1);
19010 if (color2 != null) color2 = color.detach(color2);
19011 fill.type = 'pattern';
19012 fill.color = color1[0];
19013 fill.color2 = color2 == null ? color1[0] : color2[0];
19014 fill.opacity = color2 == null ? 0 : color2[1];
19015 fill['ao:opacity2'] = color1[1];
19016 } else {
19017 fill.type = 'tile';
19018 fill.color = '';
19019 fill.color2 = '';
19020 fill.opacity = 1;
19021 fill['ao:opacity2'] = 1;
19022 }
19023 if (fill.colors) fill.colors.value = '';
19024 fill.rotate = true;
19025 fill.src = url;
19026
19027 fill.size = '1,1';
19028 fill.position = '0,0';
19029 fill.origin = '0,0';
19030 fill.aspect = 'ignore'; // ignore, atleast, atmost
19031 fill.on = true;
19032
19033 if (!left) left = 0;
19034 if (!top) top = 0;
19035 this._boxCoords = width ? { left: left + 0.5, top: top + 0.5, width: width, height: height } : null;
19036 this._transform();
19037 return this;
19038 },
19039
19040 /* stroke */
19041
19042 stroke: function(color, width, cap, join){
19043 var stroke = this.strokeElement;
19044 this._strokeWidth = (width != null) ? width : 1;
19045 stroke.weight = (width != null) ? width + 'px' : 1;
19046 stroke.endcap = (cap != null) ? ((cap == 'butt') ? 'flat' : cap) : 'round';
19047 stroke.joinstyle = (join != null) ? join : 'round';
19048
19049 this._setColor('stroke', color);
19050 return this;
19051 }
19052
19053 });
19054
19055 var precision$3 = 100;
19056
19057 var shape$1 = _class(base$1, {
19058
19059 base_initialize: base$1.prototype.initialize,
19060
19061 initialize: function(path, width, height){
19062 this.base_initialize('shape');
19063
19064 var p = this.pathElement = dom.createElement('path');
19065 p.gradientshapeok = true;
19066 this.element.appendChild(p);
19067
19068 this.width = width;
19069 this.height = height;
19070
19071 if (path != null) this.draw(path);
19072 },
19073
19074 // SVG to VML
19075
19076 draw: function(path, width, height){
19077
19078 if (!(path instanceof path$2)) path = new path$2(path);
19079 this._vml = path.toVML();
19080 //this._size = path.measure();
19081
19082 if (width != null) this.width = width;
19083 if (height != null) this.height = height;
19084
19085 if (!this._boxCoords) this._transform();
19086 this._redraw(this._prefix, this._suffix);
19087
19088 return this;
19089 },
19090
19091 // radial gradient workaround
19092
19093 _redraw: function(prefix, suffix){
19094 var vml = this._vml || '';
19095
19096 this._prefix = prefix;
19097 this._suffix = suffix;
19098 if (prefix){
19099 vml = [
19100 prefix, vml, suffix,
19101 // Don't stroke the path with the extra ellipse, redraw the stroked path separately
19102 'ns e', vml, 'nf'
19103 ].join(' ');
19104 }
19105
19106 this.element.path = vml + 'e';
19107 },
19108
19109 fillRadial: function(stops, focusX, focusY, radiusX, radiusY, centerX, centerY){
19110 var fill = this._createGradient('gradientradial', stops);
19111 if (focusX == null) focusX = (this.left || 0) + (this.width || 0) * 0.5;
19112 if (focusY == null) focusY = (this.top || 0) + (this.height || 0) * 0.5;
19113 if (radiusY == null) radiusY = radiusX || (this.height * 0.5) || 0;
19114 if (radiusX == null) radiusX = (this.width || 0) * 0.5;
19115 if (centerX == null) centerX = focusX;
19116 if (centerY == null) centerY = focusY;
19117
19118 centerX += centerX - focusX;
19119 centerY += centerY - focusY;
19120
19121 var cx = Math.round(centerX * precision$3),
19122 cy = Math.round(centerY * precision$3),
19123
19124 rx = Math.round(radiusX * 2 * precision$3),
19125 ry = Math.round(radiusY * 2 * precision$3),
19126
19127 arc = ['wa', cx - rx, cy - ry, cx + rx, cy + ry].join(' ');
19128
19129 this._redraw(
19130 // Resolve rendering bug
19131 ['m', cx, cy - ry, 'l', cx, cy - ry].join(' '),
19132 // Draw an ellipse around the path to force an elliptical gradient on any shape
19133 [
19134 'm', cx, cy - ry,
19135 arc, cx, cy - ry, cx, cy + ry, arc, cx, cy + ry, cx, cy - ry,
19136 arc, cx, cy - ry, cx, cy + ry, arc, cx, cy + ry, cx, cy - ry
19137 ].join(' ')
19138 );
19139
19140 this._boxCoords = { left: focusX - 2, top: focusY - 2, width: 4, height: 4 };
19141
19142 fill.focusposition = '0.5,0.5';
19143 fill.focussize = '0 0';
19144 fill.focus = '50%';
19145
19146 this._transform();
19147
19148 return this;
19149 }
19150
19151 });
19152
19153 var group$1 = _class(node$1, container, {
19154
19155 element_initialize: node$1.prototype.initialize,
19156
19157 initialize: function(width, height){
19158 this.element_initialize('group');
19159 this.width = width;
19160 this.height = height;
19161 },
19162
19163 _transform: function(){
19164 var element = this.element;
19165 element.coordorigin = '0,0';
19166 element.coordsize = '1000,1000';
19167 element.style.left = 0;
19168 element.style.top = 0;
19169 element.style.width = 1000;
19170 element.style.height = 1000;
19171 element.style.rotation = 0;
19172
19173 var container = this.parentNode;
19174 this._activeTransform = container ? new transform(container._activeTransform).transform(this) : this;
19175 var node = this.firstChild;
19176 while (node){
19177 node._transform();
19178 node = node.nextSibling;
19179 }
19180 }
19181
19182 });
19183
19184 var clippingrectangle$1 = _class(node$1, container, {
19185
19186 element_initialize: node$1.prototype.initialize,
19187
19188 initialize: function(width, height){
19189 this.element_initialize('clippingrectangle');
19190 this.width = width;
19191 this.height = height;
19192 },
19193
19194 _transform: function(){
19195 var element = this.element;
19196 element.clip = true;
19197 element.coordorigin = -this.x + ',' + (-1 * this.y);
19198 element.coordsize = this.width + ',' + this.height;
19199 // IE8 doesn't like clipBottom. Don't ask me why.
19200 // element.style.clipBottom = this.height + this.y;
19201 element.style.clipLeft = this.x;
19202 element.style.clipRight = this.width + this.x;
19203 element.style.clipTop = this.y;
19204 element.style.left = -this.x;
19205 element.style.top = -this.y;
19206 element.style.width = this.width + this.x;
19207 element.style.height = this.height + this.y;
19208 element.style.rotation = 0;
19209
19210 var container = this.parentNode;
19211 this._activeTransform = container ? new transform(container._activeTransform).transform(this) : this;
19212 var node = this.firstChild;
19213 while (node){
19214 node._transform();
19215 node = node.nextSibling;
19216 }
19217 }
19218
19219 });
19220
19221 var fontAnchors$1 = { start: 'left', middle: 'center', end: 'right' };
19222
19223 var text$1 = _class(base$1, {
19224
19225 base_initialize: base$1.prototype.initialize,
19226
19227 initialize: function(text, font, alignment, path){
19228 this.base_initialize('shape');
19229
19230 var p = this.pathElement = dom.createElement('path');
19231 p.textpathok = true;
19232 this.element.appendChild(p);
19233
19234 p = this.textPathElement = dom.createElement("textpath");
19235 p.on = true;
19236 p.style['v-text-align'] = 'left';
19237 this.element.appendChild(p);
19238
19239 this.draw.apply(this, arguments);
19240 },
19241
19242 draw: function(text, font, alignment, path){
19243 var element = this.element,
19244 textPath = this.textPathElement,
19245 style = textPath.style;
19246
19247 textPath.string = text;
19248
19249 if (font){
19250 if (typeof font == 'string'){
19251 style.font = font;
19252 } else {
19253 for (var key in font){
19254 var ckey = key.camelCase ? key.camelCase() : key;
19255 if (ckey == 'fontFamily') style[ckey] = "'" + font[key] + "'";
19256 // NOT UNIVERSALLY SUPPORTED OPTIONS
19257 // else if (ckey == 'kerning') style['v-text-kern'] = !!font[key];
19258 // else if (ckey == 'rotateGlyphs') style['v-rotate-letters'] = !!font[key];
19259 // else if (ckey == 'letterSpacing') style['v-text-spacing'] = Number(font[key]) + '';
19260 else style[ckey] = font[key];
19261 }
19262 }
19263 }
19264
19265 if (alignment) style['v-text-align'] = fontAnchors$1[alignment] || alignment;
19266
19267 if (path){
19268 this.currentPath = path = new path$2(path);
19269 this.element.path = path.toVML();
19270 } else if (!this.currentPath){
19271 var i = -1, offsetRows = '\n';
19272 while ((i = text.indexOf('\n', i + 1)) > -1) offsetRows += '\n';
19273 textPath.string = offsetRows + textPath.string;
19274 this.element.path = 'm0,0l1,0';
19275 }
19276
19277 // Measuring the bounding box is currently necessary for gradients etc.
19278
19279 // Clone element because the element is dead once it has been in the DOM
19280 element = element.cloneNode(true);
19281 style = element.style;
19282
19283 // Reset coordinates while measuring
19284 element.coordorigin = '0,0';
19285 element.coordsize = '10000,10000';
19286 style.left = '0px';
19287 style.top = '0px';
19288 style.width = '10000px';
19289 style.height = '10000px';
19290 style.rotation = 0;
19291 element.removeChild(element.firstChild); // Remove skew
19292
19293 // Inject the clone into the document
19294
19295 var canvas = new surface$1(1, 1),
19296 group = new group$1(), // Wrapping it in a group seems to alleviate some client rect weirdness
19297 body = element.ownerDocument.body;
19298
19299 canvas.inject(body);
19300 group.element.appendChild(element);
19301 group.inject(canvas);
19302
19303 var ebb = element.getBoundingClientRect(),
19304 cbb = canvas.toElement().getBoundingClientRect();
19305
19306 canvas.eject();
19307
19308 this.left = ebb.left - cbb.left;
19309 this.top = ebb.top - cbb.top;
19310 this.width = ebb.right - ebb.left;
19311 this.height = ebb.bottom - ebb.top;
19312 this.right = ebb.right - cbb.left;
19313 this.bottom = ebb.bottom - cbb.top;
19314
19315 this._transform();
19316
19317 //this._size = { left: this.left, top: this.top, width: this.width, height: this.height};
19318 return this;
19319 }
19320
19321 });
19322
19323 var fastNoSideEffects = createCommonjsModule(function (module, exports) {
19324 var hasCanvas = function(){
19325
19326 var canvas = document.createElement('canvas');
19327 return canvas && !!canvas.getContext;
19328
19329 };
19330
19331 if (hasCanvas()) {
19332 exports.Surface = surface;
19333 exports.Path = path$1;
19334 exports.Shape = shape;
19335 exports.Group = group;
19336 exports.ClippingRectangle = clippingrectangle;
19337 exports.Text = text;
19338 } else {
19339 exports.Surface = surface$1;
19340 exports.Path = path$2;
19341 exports.Shape = shape$1;
19342 exports.Group = group$1;
19343 exports.ClippingRectangle = clippingrectangle$1;
19344 exports.Text = text$1;
19345
19346 var DOM = dom;
19347 if (typeof document !== 'undefined') DOM.init(document);
19348 }
19349 });
19350 var fastNoSideEffects_1 = fastNoSideEffects.Surface;
19351 var fastNoSideEffects_2 = fastNoSideEffects.Path;
19352 var fastNoSideEffects_3 = fastNoSideEffects.Shape;
19353 var fastNoSideEffects_4 = fastNoSideEffects.Group;
19354 var fastNoSideEffects_5 = fastNoSideEffects.ClippingRectangle;
19355 var fastNoSideEffects_6 = fastNoSideEffects.Text;
19356
19357 current.setCurrent( // Change to 'art/modes/dom' for easier debugging via SVG
19358 fastNoSideEffects);
19359 /** Declarative fill-type objects; API design not finalized */
19360
19361 var slice = Array.prototype.slice;
19362
19363 var LinearGradient = /*#__PURE__*/function () {
19364 function LinearGradient(stops, x1, y1, x2, y2) {
19365 this._args = slice.call(arguments);
19366 }
19367
19368 var _proto = LinearGradient.prototype;
19369
19370 _proto.applyFill = function applyFill(node) {
19371 node.fillLinear.apply(node, this._args);
19372 };
19373
19374 return LinearGradient;
19375 }();
19376
19377 var RadialGradient = /*#__PURE__*/function () {
19378 function RadialGradient(stops, fx, fy, rx, ry, cx, cy) {
19379 this._args = slice.call(arguments);
19380 }
19381
19382 var _proto2 = RadialGradient.prototype;
19383
19384 _proto2.applyFill = function applyFill(node) {
19385 node.fillRadial.apply(node, this._args);
19386 };
19387
19388 return RadialGradient;
19389 }();
19390
19391 var Pattern = /*#__PURE__*/function () {
19392 function Pattern(url, width, height, left, top) {
19393 this._args = slice.call(arguments);
19394 }
19395
19396 var _proto3 = Pattern.prototype;
19397
19398 _proto3.applyFill = function applyFill(node) {
19399 node.fillImage.apply(node, this._args);
19400 };
19401
19402 return Pattern;
19403 }();
19404 /** React Components */
19405
19406
19407 var Surface = /*#__PURE__*/function (_React$Component) {
19408 _inheritsLoose(Surface, _React$Component);
19409
19410 function Surface() {
19411 return _React$Component.apply(this, arguments) || this;
19412 }
19413
19414 var _proto4 = Surface.prototype;
19415
19416 _proto4.componentDidMount = function componentDidMount() {
19417 var _this$props = this.props,
19418 height = _this$props.height,
19419 width = _this$props.width;
19420 this._surface = current.Surface(+width, +height, this._tagRef);
19421 this._mountNode = createContainer(this._surface, LegacyRoot, false);
19422 updateContainer(this.props.children, this._mountNode, this);
19423 };
19424
19425 _proto4.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
19426 var props = this.props;
19427
19428 if (props.height !== prevProps.height || props.width !== prevProps.width) {
19429 this._surface.resize(+props.width, +props.height);
19430 }
19431
19432 updateContainer(this.props.children, this._mountNode, this);
19433
19434 if (this._surface.render) {
19435 this._surface.render();
19436 }
19437 };
19438
19439 _proto4.componentWillUnmount = function componentWillUnmount() {
19440 updateContainer(null, this._mountNode, this);
19441 };
19442
19443 _proto4.render = function render() {
19444 var _this = this;
19445
19446 // This is going to be a placeholder because we don't know what it will
19447 // actually resolve to because ART may render canvas, vml or svg tags here.
19448 // We only allow a subset of properties since others might conflict with
19449 // ART's properties.
19450 var props = this.props; // TODO: ART's Canvas Mode overrides surface title and cursor
19451
19452 var Tag = current.Surface.tagName;
19453 return /*#__PURE__*/React.createElement(Tag, {
19454 ref: function (ref) {
19455 return _this._tagRef = ref;
19456 },
19457 accessKey: props.accessKey,
19458 className: props.className,
19459 draggable: props.draggable,
19460 role: props.role,
19461 style: props.style,
19462 tabIndex: props.tabIndex,
19463 title: props.title
19464 });
19465 };
19466
19467 return Surface;
19468 }(React.Component);
19469
19470 var Text = /*#__PURE__*/function (_React$Component2) {
19471 _inheritsLoose(Text, _React$Component2);
19472
19473 function Text(props) {
19474 var _this2;
19475
19476 _this2 = _React$Component2.call(this, props) || this; // We allow reading these props. Ideally we could expose the Text node as
19477 // ref directly.
19478
19479 ['height', 'width', 'x', 'y'].forEach(function (key) {
19480 Object.defineProperty(_assertThisInitialized(_this2), key, {
19481 get: function () {
19482 return this._text ? this._text[key] : undefined;
19483 }
19484 });
19485 });
19486 return _this2;
19487 }
19488
19489 var _proto5 = Text.prototype;
19490
19491 _proto5.render = function render() {
19492 var _this3 = this;
19493
19494 // This means you can't have children that render into strings...
19495 var T = TYPES.TEXT;
19496 return /*#__PURE__*/React.createElement(T, _extends({}, this.props, {
19497 ref: function (t) {
19498 return _this3._text = t;
19499 }
19500 }), childrenAsString(this.props.children));
19501 };
19502
19503 return Text;
19504 }(React.Component);
19505
19506 injectIntoDevTools({
19507 findFiberByHostInstance: function () {
19508 return null;
19509 },
19510 bundleType: 1 ,
19511 version: ReactVersion,
19512 rendererPackageName: 'react-art'
19513 });
19514 /** API */
19515
19516 var ClippingRectangle = TYPES.CLIPPING_RECTANGLE;
19517 var Group = TYPES.GROUP;
19518 var Shape = TYPES.SHAPE;
19519 var Path = current.Path;
19520
19521 exports.ClippingRectangle = ClippingRectangle;
19522 exports.Group = Group;
19523 exports.LinearGradient = LinearGradient;
19524 exports.Path = Path;
19525 exports.Pattern = Pattern;
19526 exports.RadialGradient = RadialGradient;
19527 exports.Shape = Shape;
19528 exports.Surface = Surface;
19529 exports.Text = Text;
19530 exports.Transform = transform;
19531
19532})));