UNPKG

561 kBJavaScriptView Raw
1/** @license React v16.8.5
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
10'use strict';
11
12(function (global, factory) {
13 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react')) :
14 typeof define === 'function' && define.amd ? define(['react'], factory) :
15 (global.ReactART = factory(global.React));
16}(this, (function (React) { 'use strict';
17
18var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
19
20var _assign = ReactInternals.assign;
21
22// TODO: this is special because it gets imported during build.
23
24var ReactVersion = '16.8.5';
25
26/**
27 * Use invariant() to assert state which your program assumes to be true.
28 *
29 * Provide sprintf-style format (only %s is supported) and arguments
30 * to provide information about what broke and what you were
31 * expecting.
32 *
33 * The invariant message will be stripped in production, but the invariant
34 * will remain to ensure logic does not differ in production.
35 */
36
37var validateFormat = function () {};
38
39{
40 validateFormat = function (format) {
41 if (format === undefined) {
42 throw new Error('invariant requires an error message argument');
43 }
44 };
45}
46
47function invariant(condition, format, a, b, c, d, e, f) {
48 validateFormat(format);
49
50 if (!condition) {
51 var error = void 0;
52 if (format === undefined) {
53 error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
54 } else {
55 var args = [a, b, c, d, e, f];
56 var argIndex = 0;
57 error = new Error(format.replace(/%s/g, function () {
58 return args[argIndex++];
59 }));
60 error.name = 'Invariant Violation';
61 }
62
63 error.framesToPop = 1; // we don't care about invariant's own frame
64 throw error;
65 }
66}
67
68// Relying on the `invariant()` implementation lets us
69// preserve the format and params in the www builds.
70
71/**
72 * Similar to invariant but only logs a warning if the condition is not met.
73 * This can be used to log issues in development environments in critical
74 * paths. Removing the logging code for production environments will keep the
75 * same logic and follow the same code paths.
76 */
77
78var warningWithoutStack = function () {};
79
80{
81 warningWithoutStack = function (condition, format) {
82 for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
83 args[_key - 2] = arguments[_key];
84 }
85
86 if (format === undefined) {
87 throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
88 }
89 if (args.length > 8) {
90 // Check before the condition to catch violations early.
91 throw new Error('warningWithoutStack() currently supports at most 8 arguments.');
92 }
93 if (condition) {
94 return;
95 }
96 if (typeof console !== 'undefined') {
97 var argsWithFormat = args.map(function (item) {
98 return '' + item;
99 });
100 argsWithFormat.unshift('Warning: ' + format);
101
102 // We intentionally don't use spread (or .apply) directly because it
103 // breaks IE9: https://github.com/facebook/react/issues/13610
104 Function.prototype.apply.call(console.error, console, argsWithFormat);
105 }
106 try {
107 // --- Welcome to debugging React ---
108 // This error was thrown as a convenience so that you can use this stack
109 // to find the callsite that caused this warning to fire.
110 var argIndex = 0;
111 var message = 'Warning: ' + format.replace(/%s/g, function () {
112 return args[argIndex++];
113 });
114 throw new Error(message);
115 } catch (x) {}
116 };
117}
118
119var warningWithoutStack$1 = warningWithoutStack;
120
121/**
122 * `ReactInstanceMap` maintains a mapping from a public facing stateful
123 * instance (key) and the internal representation (value). This allows public
124 * methods to accept the user facing instance as an argument and map them back
125 * to internal methods.
126 *
127 * Note that this module is currently shared and assumed to be stateless.
128 * If this becomes an actual Map, that will break.
129 */
130
131/**
132 * This API should be called `delete` but we'd have to make sure to always
133 * transform these to strings for IE support. When this transform is fully
134 * supported we can rename it.
135 */
136
137
138function get(key) {
139 return key._reactInternalFiber;
140}
141
142
143
144function set(key, value) {
145 key._reactInternalFiber = value;
146}
147
148var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
149
150// Prevent newer renderers from RTE when used with older react package versions.
151// Current owner and dispatcher used to share the same ref,
152// but PR #14548 split them out to better support the react-debug-tools package.
153if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {
154 ReactSharedInternals.ReactCurrentDispatcher = {
155 current: null
156 };
157}
158
159// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
160// nor polyfill, then a plain number is used for performance.
161var hasSymbol = typeof Symbol === 'function' && Symbol.for;
162
163var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
164var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
165var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
166var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
167var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
168var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
169var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
170
171var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
172var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
173var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
174var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
175var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
176
177var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
178var FAUX_ITERATOR_SYMBOL = '@@iterator';
179
180function getIteratorFn(maybeIterable) {
181 if (maybeIterable === null || typeof maybeIterable !== 'object') {
182 return null;
183 }
184 var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
185 if (typeof maybeIterator === 'function') {
186 return maybeIterator;
187 }
188 return null;
189}
190
191var Pending = 0;
192var Resolved = 1;
193var Rejected = 2;
194
195function refineResolvedLazyComponent(lazyComponent) {
196 return lazyComponent._status === Resolved ? lazyComponent._result : null;
197}
198
199function getWrappedName(outerType, innerType, wrapperName) {
200 var functionName = innerType.displayName || innerType.name || '';
201 return outerType.displayName || (functionName !== '' ? wrapperName + '(' + functionName + ')' : wrapperName);
202}
203
204function getComponentName(type) {
205 if (type == null) {
206 // Host root, text node or just invalid type.
207 return null;
208 }
209 {
210 if (typeof type.tag === 'number') {
211 warningWithoutStack$1(false, 'Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
212 }
213 }
214 if (typeof type === 'function') {
215 return type.displayName || type.name || null;
216 }
217 if (typeof type === 'string') {
218 return type;
219 }
220 switch (type) {
221 case REACT_CONCURRENT_MODE_TYPE:
222 return 'ConcurrentMode';
223 case REACT_FRAGMENT_TYPE:
224 return 'Fragment';
225 case REACT_PORTAL_TYPE:
226 return 'Portal';
227 case REACT_PROFILER_TYPE:
228 return 'Profiler';
229 case REACT_STRICT_MODE_TYPE:
230 return 'StrictMode';
231 case REACT_SUSPENSE_TYPE:
232 return 'Suspense';
233 }
234 if (typeof type === 'object') {
235 switch (type.$$typeof) {
236 case REACT_CONTEXT_TYPE:
237 return 'Context.Consumer';
238 case REACT_PROVIDER_TYPE:
239 return 'Context.Provider';
240 case REACT_FORWARD_REF_TYPE:
241 return getWrappedName(type, type.render, 'ForwardRef');
242 case REACT_MEMO_TYPE:
243 return getComponentName(type.type);
244 case REACT_LAZY_TYPE:
245 {
246 var thenable = type;
247 var resolvedThenable = refineResolvedLazyComponent(thenable);
248 if (resolvedThenable) {
249 return getComponentName(resolvedThenable);
250 }
251 }
252 }
253 }
254 return null;
255}
256
257var FunctionComponent = 0;
258var ClassComponent = 1;
259var IndeterminateComponent = 2; // Before we know whether it is function or class
260var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
261var HostPortal = 4; // A subtree. Could be an entry point to a different renderer.
262var HostComponent = 5;
263var HostText = 6;
264var Fragment = 7;
265var Mode = 8;
266var ContextConsumer = 9;
267var ContextProvider = 10;
268var ForwardRef = 11;
269var Profiler = 12;
270var SuspenseComponent = 13;
271var MemoComponent = 14;
272var SimpleMemoComponent = 15;
273var LazyComponent = 16;
274var IncompleteClassComponent = 17;
275var DehydratedSuspenseComponent = 18;
276
277// Don't change these two values. They're used by React Dev Tools.
278var NoEffect = /* */0;
279var PerformedWork = /* */1;
280
281// You can change the rest (and add more).
282var Placement = /* */2;
283var Update = /* */4;
284var PlacementAndUpdate = /* */6;
285var Deletion = /* */8;
286var ContentReset = /* */16;
287var Callback = /* */32;
288var DidCapture = /* */64;
289var Ref = /* */128;
290var Snapshot = /* */256;
291var Passive = /* */512;
292
293// Passive & Update & Callback & Ref & Snapshot
294var LifecycleEffectMask = /* */932;
295
296// Union of all host effects
297var HostEffectMask = /* */1023;
298
299var Incomplete = /* */1024;
300var ShouldCapture = /* */2048;
301
302var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
303
304var MOUNTING = 1;
305var MOUNTED = 2;
306var UNMOUNTED = 3;
307
308function isFiberMountedImpl(fiber) {
309 var node = fiber;
310 if (!fiber.alternate) {
311 // If there is no alternate, this might be a new tree that isn't inserted
312 // yet. If it is, then it will have a pending insertion effect on it.
313 if ((node.effectTag & Placement) !== NoEffect) {
314 return MOUNTING;
315 }
316 while (node.return) {
317 node = node.return;
318 if ((node.effectTag & Placement) !== NoEffect) {
319 return MOUNTING;
320 }
321 }
322 } else {
323 while (node.return) {
324 node = node.return;
325 }
326 }
327 if (node.tag === HostRoot) {
328 // TODO: Check if this was a nested HostRoot when used with
329 // renderContainerIntoSubtree.
330 return MOUNTED;
331 }
332 // If we didn't hit the root, that means that we're in an disconnected tree
333 // that has been unmounted.
334 return UNMOUNTED;
335}
336
337function isFiberMounted(fiber) {
338 return isFiberMountedImpl(fiber) === MOUNTED;
339}
340
341function isMounted(component) {
342 {
343 var owner = ReactCurrentOwner.current;
344 if (owner !== null && owner.tag === ClassComponent) {
345 var ownerFiber = owner;
346 var instance = ownerFiber.stateNode;
347 !instance._warnedAboutRefsInRender ? warningWithoutStack$1(false, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(ownerFiber.type) || 'A component') : void 0;
348 instance._warnedAboutRefsInRender = true;
349 }
350 }
351
352 var fiber = get(component);
353 if (!fiber) {
354 return false;
355 }
356 return isFiberMountedImpl(fiber) === MOUNTED;
357}
358
359function assertIsMounted(fiber) {
360 !(isFiberMountedImpl(fiber) === MOUNTED) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
361}
362
363function findCurrentFiberUsingSlowPath(fiber) {
364 var alternate = fiber.alternate;
365 if (!alternate) {
366 // If there is no alternate, then we only need to check if it is mounted.
367 var state = isFiberMountedImpl(fiber);
368 !(state !== UNMOUNTED) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
369 if (state === MOUNTING) {
370 return null;
371 }
372 return fiber;
373 }
374 // If we have two possible branches, we'll walk backwards up to the root
375 // to see what path the root points to. On the way we may hit one of the
376 // special cases and we'll deal with them.
377 var a = fiber;
378 var b = alternate;
379 while (true) {
380 var parentA = a.return;
381 var parentB = parentA ? parentA.alternate : null;
382 if (!parentA || !parentB) {
383 // We're at the root.
384 break;
385 }
386
387 // If both copies of the parent fiber point to the same child, we can
388 // assume that the child is current. This happens when we bailout on low
389 // priority: the bailed out fiber's child reuses the current child.
390 if (parentA.child === parentB.child) {
391 var child = parentA.child;
392 while (child) {
393 if (child === a) {
394 // We've determined that A is the current branch.
395 assertIsMounted(parentA);
396 return fiber;
397 }
398 if (child === b) {
399 // We've determined that B is the current branch.
400 assertIsMounted(parentA);
401 return alternate;
402 }
403 child = child.sibling;
404 }
405 // We should never have an alternate for any mounting node. So the only
406 // way this could possibly happen is if this was unmounted, if at all.
407 invariant(false, 'Unable to find node on an unmounted component.');
408 }
409
410 if (a.return !== b.return) {
411 // The return pointer of A and the return pointer of B point to different
412 // fibers. We assume that return pointers never criss-cross, so A must
413 // belong to the child set of A.return, and B must belong to the child
414 // set of B.return.
415 a = parentA;
416 b = parentB;
417 } else {
418 // The return pointers point to the same fiber. We'll have to use the
419 // default, slow path: scan the child sets of each parent alternate to see
420 // which child belongs to which set.
421 //
422 // Search parent A's child set
423 var didFindChild = false;
424 var _child = parentA.child;
425 while (_child) {
426 if (_child === a) {
427 didFindChild = true;
428 a = parentA;
429 b = parentB;
430 break;
431 }
432 if (_child === b) {
433 didFindChild = true;
434 b = parentA;
435 a = parentB;
436 break;
437 }
438 _child = _child.sibling;
439 }
440 if (!didFindChild) {
441 // Search parent B's child set
442 _child = parentB.child;
443 while (_child) {
444 if (_child === a) {
445 didFindChild = true;
446 a = parentB;
447 b = parentA;
448 break;
449 }
450 if (_child === b) {
451 didFindChild = true;
452 b = parentB;
453 a = parentA;
454 break;
455 }
456 _child = _child.sibling;
457 }
458 !didFindChild ? invariant(false, 'Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.') : void 0;
459 }
460 }
461
462 !(a.alternate === b) ? invariant(false, 'Return fibers should always be each others\' alternates. This error is likely caused by a bug in React. Please file an issue.') : void 0;
463 }
464 // If the root is not a host container, we're in a disconnected tree. I.e.
465 // unmounted.
466 !(a.tag === HostRoot) ? invariant(false, 'Unable to find node on an unmounted component.') : void 0;
467 if (a.stateNode.current === a) {
468 // We've determined that A is the current branch.
469 return fiber;
470 }
471 // Otherwise B has to be current branch.
472 return alternate;
473}
474
475function findCurrentHostFiber(parent) {
476 var currentParent = findCurrentFiberUsingSlowPath(parent);
477 if (!currentParent) {
478 return null;
479 }
480
481 // Next we'll drill down this component to find the first HostComponent/Text.
482 var node = currentParent;
483 while (true) {
484 if (node.tag === HostComponent || node.tag === HostText) {
485 return node;
486 } else if (node.child) {
487 node.child.return = node;
488 node = node.child;
489 continue;
490 }
491 if (node === currentParent) {
492 return null;
493 }
494 while (!node.sibling) {
495 if (!node.return || node.return === currentParent) {
496 return null;
497 }
498 node = node.return;
499 }
500 node.sibling.return = node.return;
501 node = node.sibling;
502 }
503 // Flow needs the return null here, but ESLint complains about it.
504 // eslint-disable-next-line no-unreachable
505 return null;
506}
507
508var ReactInternals$1 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
509
510var _ReactInternals$Sched = ReactInternals$1.Scheduler;
511var unstable_cancelCallback = _ReactInternals$Sched.unstable_cancelCallback;
512var unstable_now = _ReactInternals$Sched.unstable_now;
513var unstable_scheduleCallback = _ReactInternals$Sched.unstable_scheduleCallback;
514var unstable_shouldYield = _ReactInternals$Sched.unstable_shouldYield;
515var unstable_getFirstCallbackNode = _ReactInternals$Sched.unstable_getFirstCallbackNode;
516var unstable_runWithPriority = _ReactInternals$Sched.unstable_runWithPriority;
517var unstable_next = _ReactInternals$Sched.unstable_next;
518var unstable_continueExecution = _ReactInternals$Sched.unstable_continueExecution;
519var unstable_pauseExecution = _ReactInternals$Sched.unstable_pauseExecution;
520var unstable_getCurrentPriorityLevel = _ReactInternals$Sched.unstable_getCurrentPriorityLevel;
521var unstable_ImmediatePriority = _ReactInternals$Sched.unstable_ImmediatePriority;
522var unstable_UserBlockingPriority = _ReactInternals$Sched.unstable_UserBlockingPriority;
523var unstable_NormalPriority = _ReactInternals$Sched.unstable_NormalPriority;
524var unstable_LowPriority = _ReactInternals$Sched.unstable_LowPriority;
525var unstable_IdlePriority = _ReactInternals$Sched.unstable_IdlePriority;
526
527var _class = function(mixins){
528 var proto = {};
529 for (var i = 0, l = arguments.length; i < l; i++){
530 var mixin = arguments[i];
531 if (typeof mixin == 'function') mixin = mixin.prototype;
532 for (var key in mixin) proto[key] = mixin[key];
533 }
534 if (!proto.initialize) proto.initialize = function(){};
535 proto.constructor = function(a,b,c,d,e,f,g,h){
536 return new proto.initialize(a,b,c,d,e,f,g,h);
537 };
538 proto.constructor.prototype = proto.initialize.prototype = proto;
539 return proto.constructor;
540};
541
542function Transform(xx, yx, xy, yy, x, y){
543 if (xx && typeof xx == 'object'){
544 yx = xx.yx; yy = xx.yy; y = xx.y;
545 xy = xx.xy; x = xx.x; xx = xx.xx;
546 }
547 this.xx = xx == null ? 1 : xx;
548 this.yx = yx || 0;
549 this.xy = xy || 0;
550 this.yy = yy == null ? 1 : yy;
551 this.x = (x == null ? this.x : x) || 0;
552 this.y = (y == null ? this.y : y) || 0;
553 this._transform();
554 return this;
555}
556
557var transform = _class({
558
559 initialize: Transform,
560
561 _transform: function(){},
562
563 xx: 1, yx: 0, x: 0,
564 xy: 0, yy: 1, y: 0,
565
566 transform: function(xx, yx, xy, yy, x, y){
567 var m = this;
568 if (xx && typeof xx == 'object'){
569 yx = xx.yx; yy = xx.yy; y = xx.y;
570 xy = xx.xy; x = xx.x; xx = xx.xx;
571 }
572 if (!x) x = 0;
573 if (!y) y = 0;
574 return this.transformTo(
575 m.xx * xx + m.xy * yx,
576 m.yx * xx + m.yy * yx,
577 m.xx * xy + m.xy * yy,
578 m.yx * xy + m.yy * yy,
579 m.xx * x + m.xy * y + m.x,
580 m.yx * x + m.yy * y + m.y
581 );
582 },
583
584 transformTo: Transform,
585
586 translate: function(x, y){
587 return this.transform(1, 0, 0, 1, x, y);
588 },
589
590 move: function(x, y){
591 this.x += x || 0;
592 this.y += y || 0;
593 this._transform();
594 return this;
595 },
596
597 scale: function(x, y){
598 if (y == null) y = x;
599 return this.transform(x, 0, 0, y, 0, 0);
600 },
601
602 rotate: function(deg, x, y){
603 if (x == null || y == null){
604 x = (this.left || 0) + (this.width || 0) / 2;
605 y = (this.top || 0) + (this.height || 0) / 2;
606 }
607
608 var rad = deg * Math.PI / 180, sin = Math.sin(rad), cos = Math.cos(rad);
609
610 this.transform(1, 0, 0, 1, x, y);
611 var m = this;
612
613 return this.transformTo(
614 cos * m.xx - sin * m.yx,
615 sin * m.xx + cos * m.yx,
616 cos * m.xy - sin * m.yy,
617 sin * m.xy + cos * m.yy,
618 m.x,
619 m.y
620 ).transform(1, 0, 0, 1, -x, -y);
621 },
622
623 moveTo: function(x, y){
624 var m = this;
625 return this.transformTo(m.xx, m.yx, m.xy, m.yy, x, y);
626 },
627
628 rotateTo: function(deg, x, y){
629 var m = this;
630 var flip = m.yx / m.xx > m.yy / m.xy ? -1 : 1;
631 if (m.xx < 0 ? m.xy >= 0 : m.xy < 0) flip = -flip;
632 return this.rotate(deg - Math.atan2(flip * m.yx, flip * m.xx) * 180 / Math.PI, x, y);
633 },
634
635 scaleTo: function(x, y){
636 // Normalize
637 var m = this;
638
639 var h = Math.sqrt(m.xx * m.xx + m.yx * m.yx);
640 m.xx /= h; m.yx /= h;
641
642 h = Math.sqrt(m.yy * m.yy + m.xy * m.xy);
643 m.yy /= h; m.xy /= h;
644
645 return this.scale(x, y);
646 },
647
648 resizeTo: function(width, height){
649 var w = this.width, h = this.height;
650 if (!w || !h) return this;
651 return this.scaleTo(width / w, height / h);
652 },
653
654 /*
655 inverse: function(){
656 var a = this.xx, b = this.yx,
657 c = this.xy, d = this.yy,
658 e = this.x, f = this.y;
659 if (a * d - b * c == 0) return null;
660 return new Transform(
661 d/(a * d-b * c), b/(b * c-a * d),
662 c/(b * c-a * d), a/(a * d-b * c),
663 (d * e-c * f)/(b * c-a * d), (b * e-a * f)/(a * d-b * c)
664 );
665 },
666 */
667
668 inversePoint: function(x, y){
669 var a = this.xx, b = this.yx,
670 c = this.xy, d = this.yy,
671 e = this.x, f = this.y;
672 var det = b * c - a * d;
673 if (det == 0) return null;
674 return {
675 x: (d * (e - x) + c * (y - f)) / det,
676 y: (a * (f - y) + b * (x - e)) / det
677 };
678 },
679
680 point: function(x, y){
681 var m = this;
682 return {
683 x: m.xx * x + m.xy * y + m.x,
684 y: m.yx * x + m.yy * y + m.y
685 };
686 }
687
688});
689
690var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
691
692
693
694
695
696function createCommonjsModule(fn, module) {
697 return module = { exports: {} }, fn(module, module.exports), module.exports;
698}
699
700var current = createCommonjsModule(function (module, exports) {
701function warning(){
702 throw new Error('You must require a mode before requiring anything else.');
703}
704
705exports.Surface = warning;
706exports.Path = warning;
707exports.Shape = warning;
708exports.Group = warning;
709exports.ClippingRectangle = warning;
710exports.Text = warning;
711
712exports.setCurrent = function(mode){
713 for (var key in mode){
714 exports[key] = mode[key];
715 }
716};
717});
718
719var current_1 = current.Surface;
720var current_2 = current.Path;
721var current_3 = current.Shape;
722var current_4 = current.Group;
723var current_5 = current.ClippingRectangle;
724var current_6 = current.Text;
725var current_7 = current.setCurrent;
726
727var TYPES = {
728 CLIPPING_RECTANGLE: 'ClippingRectangle',
729 GROUP: 'Group',
730 SHAPE: 'Shape',
731 TEXT: 'Text'
732};
733
734var EVENT_TYPES = {
735 onClick: 'click',
736 onMouseMove: 'mousemove',
737 onMouseOver: 'mouseover',
738 onMouseOut: 'mouseout',
739 onMouseUp: 'mouseup',
740 onMouseDown: 'mousedown'
741};
742
743function childrenAsString(children) {
744 if (!children) {
745 return '';
746 } else if (typeof children === 'string') {
747 return children;
748 } else if (children.length) {
749 return children.join('');
750 } else {
751 return '';
752 }
753}
754
755// Renderers that don't support persistence
756// can re-export everything from this module.
757
758function shim() {
759 invariant(false, 'The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue.');
760}
761
762// Persistence (when unsupported)
763var supportsPersistence = false;
764var cloneInstance = shim;
765var createContainerChildSet = shim;
766var appendChildToContainerChildSet = shim;
767var finalizeContainerChildren = shim;
768var replaceContainerChildren = shim;
769var cloneHiddenInstance = shim;
770var cloneUnhiddenInstance = shim;
771var createHiddenTextInstance = shim;
772
773// Renderers that don't support hydration
774// can re-export everything from this module.
775
776function shim$1() {
777 invariant(false, 'The current renderer does not support hydration. This error is likely caused by a bug in React. Please file an issue.');
778}
779
780// Hydration (when unsupported)
781
782var supportsHydration = false;
783var canHydrateInstance = shim$1;
784var canHydrateTextInstance = shim$1;
785var canHydrateSuspenseInstance = shim$1;
786var getNextHydratableSibling = shim$1;
787var getFirstHydratableChild = shim$1;
788var hydrateInstance = shim$1;
789var hydrateTextInstance = shim$1;
790var getNextHydratableInstanceAfterSuspenseInstance = shim$1;
791var clearSuspenseBoundary = shim$1;
792var clearSuspenseBoundaryFromContainer = shim$1;
793var didNotMatchHydratedContainerTextInstance = shim$1;
794var didNotMatchHydratedTextInstance = shim$1;
795var didNotHydrateContainerInstance = shim$1;
796var didNotHydrateInstance = shim$1;
797var didNotFindHydratableContainerInstance = shim$1;
798var didNotFindHydratableContainerTextInstance = shim$1;
799var didNotFindHydratableContainerSuspenseInstance = shim$1;
800var didNotFindHydratableInstance = shim$1;
801var didNotFindHydratableTextInstance = shim$1;
802var didNotFindHydratableSuspenseInstance = shim$1;
803
804var pooledTransform = new transform();
805
806var NO_CONTEXT = {};
807var UPDATE_SIGNAL = {};
808{
809 Object.freeze(NO_CONTEXT);
810 Object.freeze(UPDATE_SIGNAL);
811}
812
813/** Helper Methods */
814
815function addEventListeners(instance, type, listener) {
816 // We need to explicitly unregister before unmount.
817 // For this reason we need to track subscriptions.
818 if (!instance._listeners) {
819 instance._listeners = {};
820 instance._subscriptions = {};
821 }
822
823 instance._listeners[type] = listener;
824
825 if (listener) {
826 if (!instance._subscriptions[type]) {
827 instance._subscriptions[type] = instance.subscribe(type, createEventHandler(instance), instance);
828 }
829 } else {
830 if (instance._subscriptions[type]) {
831 instance._subscriptions[type]();
832 delete instance._subscriptions[type];
833 }
834 }
835}
836
837function createEventHandler(instance) {
838 return function handleEvent(event) {
839 var listener = instance._listeners[event.type];
840
841 if (!listener) {
842 // Noop
843 } else if (typeof listener === 'function') {
844 listener.call(instance, event);
845 } else if (listener.handleEvent) {
846 listener.handleEvent(event);
847 }
848 };
849}
850
851function destroyEventListeners(instance) {
852 if (instance._subscriptions) {
853 for (var type in instance._subscriptions) {
854 instance._subscriptions[type]();
855 }
856 }
857
858 instance._subscriptions = null;
859 instance._listeners = null;
860}
861
862function getScaleX(props) {
863 if (props.scaleX != null) {
864 return props.scaleX;
865 } else if (props.scale != null) {
866 return props.scale;
867 } else {
868 return 1;
869 }
870}
871
872function getScaleY(props) {
873 if (props.scaleY != null) {
874 return props.scaleY;
875 } else if (props.scale != null) {
876 return props.scale;
877 } else {
878 return 1;
879 }
880}
881
882function isSameFont(oldFont, newFont) {
883 if (oldFont === newFont) {
884 return true;
885 } else if (typeof newFont === 'string' || typeof oldFont === 'string') {
886 return false;
887 } else {
888 return newFont.fontSize === oldFont.fontSize && newFont.fontStyle === oldFont.fontStyle && newFont.fontVariant === oldFont.fontVariant && newFont.fontWeight === oldFont.fontWeight && newFont.fontFamily === oldFont.fontFamily;
889 }
890}
891
892/** Render Methods */
893
894function applyClippingRectangleProps(instance, props) {
895 var prevProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
896
897 applyNodeProps(instance, props, prevProps);
898
899 instance.width = props.width;
900 instance.height = props.height;
901}
902
903function applyGroupProps(instance, props) {
904 var prevProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
905
906 applyNodeProps(instance, props, prevProps);
907
908 instance.width = props.width;
909 instance.height = props.height;
910}
911
912function applyNodeProps(instance, props) {
913 var prevProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
914
915 var scaleX = getScaleX(props);
916 var scaleY = getScaleY(props);
917
918 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);
919
920 if (props.transform != null) {
921 pooledTransform.transform(props.transform);
922 }
923
924 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) {
925 instance.transformTo(pooledTransform);
926 }
927
928 if (props.cursor !== prevProps.cursor || props.title !== prevProps.title) {
929 instance.indicate(props.cursor, props.title);
930 }
931
932 if (instance.blend && props.opacity !== prevProps.opacity) {
933 instance.blend(props.opacity == null ? 1 : props.opacity);
934 }
935
936 if (props.visible !== prevProps.visible) {
937 if (props.visible == null || props.visible) {
938 instance.show();
939 } else {
940 instance.hide();
941 }
942 }
943
944 for (var type in EVENT_TYPES) {
945 addEventListeners(instance, EVENT_TYPES[type], props[type]);
946 }
947}
948
949function applyRenderableNodeProps(instance, props) {
950 var prevProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
951
952 applyNodeProps(instance, props, prevProps);
953
954 if (prevProps.fill !== props.fill) {
955 if (props.fill && props.fill.applyFill) {
956 props.fill.applyFill(instance);
957 } else {
958 instance.fill(props.fill);
959 }
960 }
961 if (prevProps.stroke !== props.stroke || prevProps.strokeWidth !== props.strokeWidth || prevProps.strokeCap !== props.strokeCap || prevProps.strokeJoin !== props.strokeJoin ||
962 // TODO: Consider deep check of stokeDash; may benefit VML in IE.
963 prevProps.strokeDash !== props.strokeDash) {
964 instance.stroke(props.stroke, props.strokeWidth, props.strokeCap, props.strokeJoin, props.strokeDash);
965 }
966}
967
968function applyShapeProps(instance, props) {
969 var prevProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
970
971 applyRenderableNodeProps(instance, props, prevProps);
972
973 var path = props.d || childrenAsString(props.children);
974
975 var prevDelta = instance._prevDelta;
976 var prevPath = instance._prevPath;
977
978 if (path !== prevPath || path.delta !== prevDelta || prevProps.height !== props.height || prevProps.width !== props.width) {
979 instance.draw(path, props.width, props.height);
980
981 instance._prevDelta = path.delta;
982 instance._prevPath = path;
983 }
984}
985
986function applyTextProps(instance, props) {
987 var prevProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
988
989 applyRenderableNodeProps(instance, props, prevProps);
990
991 var string = props.children;
992
993 if (instance._currentString !== string || !isSameFont(props.font, prevProps.font) || props.alignment !== prevProps.alignment || props.path !== prevProps.path) {
994 instance.draw(string, props.font, props.alignment, props.path);
995
996 instance._currentString = string;
997 }
998}
999
1000function appendInitialChild(parentInstance, child) {
1001 if (typeof child === 'string') {
1002 // Noop for string children of Text (eg <Text>{'foo'}{'bar'}</Text>)
1003 invariant(false, 'Text children should already be flattened.');
1004 return;
1005 }
1006
1007 child.inject(parentInstance);
1008}
1009
1010function createInstance(type, props, internalInstanceHandle) {
1011 var instance = void 0;
1012
1013 switch (type) {
1014 case TYPES.CLIPPING_RECTANGLE:
1015 instance = current.ClippingRectangle();
1016 instance._applyProps = applyClippingRectangleProps;
1017 break;
1018 case TYPES.GROUP:
1019 instance = current.Group();
1020 instance._applyProps = applyGroupProps;
1021 break;
1022 case TYPES.SHAPE:
1023 instance = current.Shape();
1024 instance._applyProps = applyShapeProps;
1025 break;
1026 case TYPES.TEXT:
1027 instance = current.Text(props.children, props.font, props.alignment, props.path);
1028 instance._applyProps = applyTextProps;
1029 break;
1030 }
1031
1032 !instance ? invariant(false, 'ReactART does not support the type "%s"', type) : void 0;
1033
1034 instance._applyProps(instance, props);
1035
1036 return instance;
1037}
1038
1039function createTextInstance(text, rootContainerInstance, internalInstanceHandle) {
1040 return text;
1041}
1042
1043function finalizeInitialChildren(domElement, type, props) {
1044 return false;
1045}
1046
1047function getPublicInstance(instance) {
1048 return instance;
1049}
1050
1051function prepareForCommit() {
1052 // Noop
1053}
1054
1055function prepareUpdate(domElement, type, oldProps, newProps) {
1056 return UPDATE_SIGNAL;
1057}
1058
1059function resetAfterCommit() {
1060 // Noop
1061}
1062
1063function resetTextContent(domElement) {
1064 // Noop
1065}
1066
1067function shouldDeprioritizeSubtree(type, props) {
1068 return false;
1069}
1070
1071function getRootHostContext() {
1072 return NO_CONTEXT;
1073}
1074
1075function getChildHostContext() {
1076 return NO_CONTEXT;
1077}
1078
1079var scheduleTimeout = setTimeout;
1080var cancelTimeout = clearTimeout;
1081var noTimeout = -1;
1082var schedulePassiveEffects = unstable_scheduleCallback;
1083var cancelPassiveEffects = unstable_cancelCallback;
1084
1085function shouldSetTextContent(type, props) {
1086 return typeof props.children === 'string' || typeof props.children === 'number';
1087}
1088
1089// The ART renderer is secondary to the React DOM renderer.
1090var isPrimaryRenderer = false;
1091
1092var supportsMutation = true;
1093
1094function appendChild(parentInstance, child) {
1095 if (child.parentNode === parentInstance) {
1096 child.eject();
1097 }
1098 child.inject(parentInstance);
1099}
1100
1101function appendChildToContainer(parentInstance, child) {
1102 if (child.parentNode === parentInstance) {
1103 child.eject();
1104 }
1105 child.inject(parentInstance);
1106}
1107
1108function insertBefore(parentInstance, child, beforeChild) {
1109 !(child !== beforeChild) ? invariant(false, 'ReactART: Can not insert node before itself') : void 0;
1110 child.injectBefore(beforeChild);
1111}
1112
1113function insertInContainerBefore(parentInstance, child, beforeChild) {
1114 !(child !== beforeChild) ? invariant(false, 'ReactART: Can not insert node before itself') : void 0;
1115 child.injectBefore(beforeChild);
1116}
1117
1118function removeChild(parentInstance, child) {
1119 destroyEventListeners(child);
1120 child.eject();
1121}
1122
1123function removeChildFromContainer(parentInstance, child) {
1124 destroyEventListeners(child);
1125 child.eject();
1126}
1127
1128
1129
1130
1131
1132function commitUpdate(instance, updatePayload, type, oldProps, newProps) {
1133 instance._applyProps(instance, newProps, oldProps);
1134}
1135
1136function hideInstance(instance) {
1137 instance.hide();
1138}
1139
1140
1141
1142function unhideInstance(instance, props) {
1143 if (props.visible == null || props.visible) {
1144 instance.show();
1145 }
1146}
1147
1148function unhideTextInstance(textInstance, text) {
1149 // Noop
1150}
1151
1152/**
1153 * Copyright (c) 2013-present, Facebook, Inc.
1154 *
1155 * This source code is licensed under the MIT license found in the
1156 * LICENSE file in the root directory of this source tree.
1157 */
1158
1159
1160
1161var ReactPropTypesSecret$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
1162
1163var ReactPropTypesSecret_1 = ReactPropTypesSecret$1;
1164
1165/**
1166 * Copyright (c) 2013-present, Facebook, Inc.
1167 *
1168 * This source code is licensed under the MIT license found in the
1169 * LICENSE file in the root directory of this source tree.
1170 */
1171
1172
1173
1174var printWarning = function() {};
1175
1176{
1177 var ReactPropTypesSecret = ReactPropTypesSecret_1;
1178 var loggedTypeFailures = {};
1179
1180 printWarning = function(text) {
1181 var message = 'Warning: ' + text;
1182 if (typeof console !== 'undefined') {
1183 console.error(message);
1184 }
1185 try {
1186 // --- Welcome to debugging React ---
1187 // This error was thrown as a convenience so that you can use this stack
1188 // to find the callsite that caused this warning to fire.
1189 throw new Error(message);
1190 } catch (x) {}
1191 };
1192}
1193
1194/**
1195 * Assert that the values match with the type specs.
1196 * Error messages are memorized and will only be shown once.
1197 *
1198 * @param {object} typeSpecs Map of name to a ReactPropType
1199 * @param {object} values Runtime values that need to be type-checked
1200 * @param {string} location e.g. "prop", "context", "child context"
1201 * @param {string} componentName Name of the component for error messages.
1202 * @param {?Function} getStack Returns the component stack.
1203 * @private
1204 */
1205function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
1206 {
1207 for (var typeSpecName in typeSpecs) {
1208 if (typeSpecs.hasOwnProperty(typeSpecName)) {
1209 var error;
1210 // Prop type validation may throw. In case they do, we don't want to
1211 // fail the render phase where it didn't fail before. So we log it.
1212 // After these have been cleaned up, we'll let them throw.
1213 try {
1214 // This is intentionally an invariant that gets caught. It's the same
1215 // behavior as without this statement except with a better message.
1216 if (typeof typeSpecs[typeSpecName] !== 'function') {
1217 var err = Error(
1218 (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
1219 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
1220 );
1221 err.name = 'Invariant Violation';
1222 throw err;
1223 }
1224 error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
1225 } catch (ex) {
1226 error = ex;
1227 }
1228 if (error && !(error instanceof Error)) {
1229 printWarning(
1230 (componentName || 'React class') + ': type specification of ' +
1231 location + ' `' + typeSpecName + '` is invalid; the type checker ' +
1232 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
1233 'You may have forgotten to pass an argument to the type checker ' +
1234 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
1235 'shape all require an argument).'
1236 );
1237
1238 }
1239 if (error instanceof Error && !(error.message in loggedTypeFailures)) {
1240 // Only monitor this failure once because there tends to be a lot of the
1241 // same error.
1242 loggedTypeFailures[error.message] = true;
1243
1244 var stack = getStack ? getStack() : '';
1245
1246 printWarning(
1247 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
1248 );
1249 }
1250 }
1251 }
1252 }
1253}
1254
1255var checkPropTypes_1 = checkPropTypes;
1256
1257var BEFORE_SLASH_RE = /^(.*)[\\\/]/;
1258
1259var describeComponentFrame = function (name, source, ownerName) {
1260 var sourceInfo = '';
1261 if (source) {
1262 var path = source.fileName;
1263 var fileName = path.replace(BEFORE_SLASH_RE, '');
1264 {
1265 // In DEV, include code for a common special case:
1266 // prefer "folder/index.js" instead of just "index.js".
1267 if (/^index\./.test(fileName)) {
1268 var match = path.match(BEFORE_SLASH_RE);
1269 if (match) {
1270 var pathBeforeSlash = match[1];
1271 if (pathBeforeSlash) {
1272 var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
1273 fileName = folderName + '/' + fileName;
1274 }
1275 }
1276 }
1277 }
1278 sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
1279 } else if (ownerName) {
1280 sourceInfo = ' (created by ' + ownerName + ')';
1281 }
1282 return '\n in ' + (name || 'Unknown') + sourceInfo;
1283};
1284
1285var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
1286
1287function describeFiber(fiber) {
1288 switch (fiber.tag) {
1289 case HostRoot:
1290 case HostPortal:
1291 case HostText:
1292 case Fragment:
1293 case ContextProvider:
1294 case ContextConsumer:
1295 return '';
1296 default:
1297 var owner = fiber._debugOwner;
1298 var source = fiber._debugSource;
1299 var name = getComponentName(fiber.type);
1300 var ownerName = null;
1301 if (owner) {
1302 ownerName = getComponentName(owner.type);
1303 }
1304 return describeComponentFrame(name, source, ownerName);
1305 }
1306}
1307
1308function getStackByFiberInDevAndProd(workInProgress) {
1309 var info = '';
1310 var node = workInProgress;
1311 do {
1312 info += describeFiber(node);
1313 node = node.return;
1314 } while (node);
1315 return info;
1316}
1317
1318var current$1 = null;
1319var phase = null;
1320
1321function getCurrentFiberOwnerNameInDevOrNull() {
1322 {
1323 if (current$1 === null) {
1324 return null;
1325 }
1326 var owner = current$1._debugOwner;
1327 if (owner !== null && typeof owner !== 'undefined') {
1328 return getComponentName(owner.type);
1329 }
1330 }
1331 return null;
1332}
1333
1334function getCurrentFiberStackInDev() {
1335 {
1336 if (current$1 === null) {
1337 return '';
1338 }
1339 // Safe because if current fiber exists, we are reconciling,
1340 // and it is guaranteed to be the work-in-progress version.
1341 return getStackByFiberInDevAndProd(current$1);
1342 }
1343 return '';
1344}
1345
1346function resetCurrentFiber() {
1347 {
1348 ReactDebugCurrentFrame.getCurrentStack = null;
1349 current$1 = null;
1350 phase = null;
1351 }
1352}
1353
1354function setCurrentFiber(fiber) {
1355 {
1356 ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev;
1357 current$1 = fiber;
1358 phase = null;
1359 }
1360}
1361
1362function setCurrentPhase(lifeCyclePhase) {
1363 {
1364 phase = lifeCyclePhase;
1365 }
1366}
1367
1368var enableUserTimingAPI = true;
1369
1370// Helps identify side effects in begin-phase lifecycle hooks and setState reducers:
1371var debugRenderPhaseSideEffects = false;
1372
1373// In some cases, StrictMode should also double-render lifecycles.
1374// This can be confusing for tests though,
1375// And it can be bad for performance in production.
1376// This feature flag can be used to control the behavior:
1377var debugRenderPhaseSideEffectsForStrictMode = true;
1378
1379// To preserve the "Pause on caught exceptions" behavior of the debugger, we
1380// replay the begin phase of a failed component inside invokeGuardedCallback.
1381var replayFailedUnitOfWorkWithInvokeGuardedCallback = true;
1382
1383// Warn about deprecated, async-unsafe lifecycles; relates to RFC #6:
1384var warnAboutDeprecatedLifecycles = false;
1385
1386// Gather advanced timing metrics for Profiler subtrees.
1387var enableProfilerTimer = true;
1388
1389// Trace which interactions trigger each commit.
1390var enableSchedulerTracing = true;
1391
1392// Only used in www builds.
1393var enableSuspenseServerRenderer = false; // TODO: true? Here it might just be false.
1394
1395// Only used in www builds.
1396
1397
1398// Only used in www builds.
1399
1400
1401// React Fire: prevent the value and checked attributes from syncing
1402// with their related DOM properties
1403
1404
1405// These APIs will no longer be "unstable" in the upcoming 16.7 release,
1406// Control this behavior with a flag to support 16.6 minor releases in the meanwhile.
1407
1408// Prefix measurements so that it's possible to filter them.
1409// Longer prefixes are hard to read in DevTools.
1410var reactEmoji = '\u269B';
1411var warningEmoji = '\u26D4';
1412var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function';
1413
1414// Keep track of current fiber so that we know the path to unwind on pause.
1415// TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them?
1416var currentFiber = null;
1417// If we're in the middle of user code, which fiber and method is it?
1418// Reusing `currentFiber` would be confusing for this because user code fiber
1419// can change during commit phase too, but we don't need to unwind it (since
1420// lifecycles in the commit phase don't resemble a tree).
1421var currentPhase = null;
1422var currentPhaseFiber = null;
1423// Did lifecycle hook schedule an update? This is often a performance problem,
1424// so we will keep track of it, and include it in the report.
1425// Track commits caused by cascading updates.
1426var isCommitting = false;
1427var hasScheduledUpdateInCurrentCommit = false;
1428var hasScheduledUpdateInCurrentPhase = false;
1429var commitCountInCurrentWorkLoop = 0;
1430var effectCountInCurrentCommit = 0;
1431var isWaitingForCallback = false;
1432// During commits, we only show a measurement once per method name
1433// to avoid stretch the commit phase with measurement overhead.
1434var labelsInCurrentCommit = new Set();
1435
1436var formatMarkName = function (markName) {
1437 return reactEmoji + ' ' + markName;
1438};
1439
1440var formatLabel = function (label, warning) {
1441 var prefix = warning ? warningEmoji + ' ' : reactEmoji + ' ';
1442 var suffix = warning ? ' Warning: ' + warning : '';
1443 return '' + prefix + label + suffix;
1444};
1445
1446var beginMark = function (markName) {
1447 performance.mark(formatMarkName(markName));
1448};
1449
1450var clearMark = function (markName) {
1451 performance.clearMarks(formatMarkName(markName));
1452};
1453
1454var endMark = function (label, markName, warning) {
1455 var formattedMarkName = formatMarkName(markName);
1456 var formattedLabel = formatLabel(label, warning);
1457 try {
1458 performance.measure(formattedLabel, formattedMarkName);
1459 } catch (err) {}
1460 // If previous mark was missing for some reason, this will throw.
1461 // This could only happen if React crashed in an unexpected place earlier.
1462 // Don't pile on with more errors.
1463
1464 // Clear marks immediately to avoid growing buffer.
1465 performance.clearMarks(formattedMarkName);
1466 performance.clearMeasures(formattedLabel);
1467};
1468
1469var getFiberMarkName = function (label, debugID) {
1470 return label + ' (#' + debugID + ')';
1471};
1472
1473var getFiberLabel = function (componentName, isMounted, phase) {
1474 if (phase === null) {
1475 // These are composite component total time measurements.
1476 return componentName + ' [' + (isMounted ? 'update' : 'mount') + ']';
1477 } else {
1478 // Composite component methods.
1479 return componentName + '.' + phase;
1480 }
1481};
1482
1483var beginFiberMark = function (fiber, phase) {
1484 var componentName = getComponentName(fiber.type) || 'Unknown';
1485 var debugID = fiber._debugID;
1486 var isMounted = fiber.alternate !== null;
1487 var label = getFiberLabel(componentName, isMounted, phase);
1488
1489 if (isCommitting && labelsInCurrentCommit.has(label)) {
1490 // During the commit phase, we don't show duplicate labels because
1491 // there is a fixed overhead for every measurement, and we don't
1492 // want to stretch the commit phase beyond necessary.
1493 return false;
1494 }
1495 labelsInCurrentCommit.add(label);
1496
1497 var markName = getFiberMarkName(label, debugID);
1498 beginMark(markName);
1499 return true;
1500};
1501
1502var clearFiberMark = function (fiber, phase) {
1503 var componentName = getComponentName(fiber.type) || 'Unknown';
1504 var debugID = fiber._debugID;
1505 var isMounted = fiber.alternate !== null;
1506 var label = getFiberLabel(componentName, isMounted, phase);
1507 var markName = getFiberMarkName(label, debugID);
1508 clearMark(markName);
1509};
1510
1511var endFiberMark = function (fiber, phase, warning) {
1512 var componentName = getComponentName(fiber.type) || 'Unknown';
1513 var debugID = fiber._debugID;
1514 var isMounted = fiber.alternate !== null;
1515 var label = getFiberLabel(componentName, isMounted, phase);
1516 var markName = getFiberMarkName(label, debugID);
1517 endMark(label, markName, warning);
1518};
1519
1520var shouldIgnoreFiber = function (fiber) {
1521 // Host components should be skipped in the timeline.
1522 // We could check typeof fiber.type, but does this work with RN?
1523 switch (fiber.tag) {
1524 case HostRoot:
1525 case HostComponent:
1526 case HostText:
1527 case HostPortal:
1528 case Fragment:
1529 case ContextProvider:
1530 case ContextConsumer:
1531 case Mode:
1532 return true;
1533 default:
1534 return false;
1535 }
1536};
1537
1538var clearPendingPhaseMeasurement = function () {
1539 if (currentPhase !== null && currentPhaseFiber !== null) {
1540 clearFiberMark(currentPhaseFiber, currentPhase);
1541 }
1542 currentPhaseFiber = null;
1543 currentPhase = null;
1544 hasScheduledUpdateInCurrentPhase = false;
1545};
1546
1547var pauseTimers = function () {
1548 // Stops all currently active measurements so that they can be resumed
1549 // if we continue in a later deferred loop from the same unit of work.
1550 var fiber = currentFiber;
1551 while (fiber) {
1552 if (fiber._debugIsCurrentlyTiming) {
1553 endFiberMark(fiber, null, null);
1554 }
1555 fiber = fiber.return;
1556 }
1557};
1558
1559var resumeTimersRecursively = function (fiber) {
1560 if (fiber.return !== null) {
1561 resumeTimersRecursively(fiber.return);
1562 }
1563 if (fiber._debugIsCurrentlyTiming) {
1564 beginFiberMark(fiber, null);
1565 }
1566};
1567
1568var resumeTimers = function () {
1569 // Resumes all measurements that were active during the last deferred loop.
1570 if (currentFiber !== null) {
1571 resumeTimersRecursively(currentFiber);
1572 }
1573};
1574
1575function recordEffect() {
1576 if (enableUserTimingAPI) {
1577 effectCountInCurrentCommit++;
1578 }
1579}
1580
1581function recordScheduleUpdate() {
1582 if (enableUserTimingAPI) {
1583 if (isCommitting) {
1584 hasScheduledUpdateInCurrentCommit = true;
1585 }
1586 if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') {
1587 hasScheduledUpdateInCurrentPhase = true;
1588 }
1589 }
1590}
1591
1592function startRequestCallbackTimer() {
1593 if (enableUserTimingAPI) {
1594 if (supportsUserTiming && !isWaitingForCallback) {
1595 isWaitingForCallback = true;
1596 beginMark('(Waiting for async callback...)');
1597 }
1598 }
1599}
1600
1601function stopRequestCallbackTimer(didExpire, expirationTime) {
1602 if (enableUserTimingAPI) {
1603 if (supportsUserTiming) {
1604 isWaitingForCallback = false;
1605 var warning = didExpire ? 'React was blocked by main thread' : null;
1606 endMark('(Waiting for async callback... will force flush in ' + expirationTime + ' ms)', '(Waiting for async callback...)', warning);
1607 }
1608 }
1609}
1610
1611function startWorkTimer(fiber) {
1612 if (enableUserTimingAPI) {
1613 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
1614 return;
1615 }
1616 // If we pause, this is the fiber to unwind from.
1617 currentFiber = fiber;
1618 if (!beginFiberMark(fiber, null)) {
1619 return;
1620 }
1621 fiber._debugIsCurrentlyTiming = true;
1622 }
1623}
1624
1625function cancelWorkTimer(fiber) {
1626 if (enableUserTimingAPI) {
1627 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
1628 return;
1629 }
1630 // Remember we shouldn't complete measurement for this fiber.
1631 // Otherwise flamechart will be deep even for small updates.
1632 fiber._debugIsCurrentlyTiming = false;
1633 clearFiberMark(fiber, null);
1634 }
1635}
1636
1637function stopWorkTimer(fiber) {
1638 if (enableUserTimingAPI) {
1639 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
1640 return;
1641 }
1642 // If we pause, its parent is the fiber to unwind from.
1643 currentFiber = fiber.return;
1644 if (!fiber._debugIsCurrentlyTiming) {
1645 return;
1646 }
1647 fiber._debugIsCurrentlyTiming = false;
1648 endFiberMark(fiber, null, null);
1649 }
1650}
1651
1652function stopFailedWorkTimer(fiber) {
1653 if (enableUserTimingAPI) {
1654 if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
1655 return;
1656 }
1657 // If we pause, its parent is the fiber to unwind from.
1658 currentFiber = fiber.return;
1659 if (!fiber._debugIsCurrentlyTiming) {
1660 return;
1661 }
1662 fiber._debugIsCurrentlyTiming = false;
1663 var warning = fiber.tag === SuspenseComponent || fiber.tag === DehydratedSuspenseComponent ? 'Rendering was suspended' : 'An error was thrown inside this error boundary';
1664 endFiberMark(fiber, null, warning);
1665 }
1666}
1667
1668function startPhaseTimer(fiber, phase) {
1669 if (enableUserTimingAPI) {
1670 if (!supportsUserTiming) {
1671 return;
1672 }
1673 clearPendingPhaseMeasurement();
1674 if (!beginFiberMark(fiber, phase)) {
1675 return;
1676 }
1677 currentPhaseFiber = fiber;
1678 currentPhase = phase;
1679 }
1680}
1681
1682function stopPhaseTimer() {
1683 if (enableUserTimingAPI) {
1684 if (!supportsUserTiming) {
1685 return;
1686 }
1687 if (currentPhase !== null && currentPhaseFiber !== null) {
1688 var warning = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null;
1689 endFiberMark(currentPhaseFiber, currentPhase, warning);
1690 }
1691 currentPhase = null;
1692 currentPhaseFiber = null;
1693 }
1694}
1695
1696function startWorkLoopTimer(nextUnitOfWork) {
1697 if (enableUserTimingAPI) {
1698 currentFiber = nextUnitOfWork;
1699 if (!supportsUserTiming) {
1700 return;
1701 }
1702 commitCountInCurrentWorkLoop = 0;
1703 // This is top level call.
1704 // Any other measurements are performed within.
1705 beginMark('(React Tree Reconciliation)');
1706 // Resume any measurements that were in progress during the last loop.
1707 resumeTimers();
1708 }
1709}
1710
1711function stopWorkLoopTimer(interruptedBy, didCompleteRoot) {
1712 if (enableUserTimingAPI) {
1713 if (!supportsUserTiming) {
1714 return;
1715 }
1716 var warning = null;
1717 if (interruptedBy !== null) {
1718 if (interruptedBy.tag === HostRoot) {
1719 warning = 'A top-level update interrupted the previous render';
1720 } else {
1721 var componentName = getComponentName(interruptedBy.type) || 'Unknown';
1722 warning = 'An update to ' + componentName + ' interrupted the previous render';
1723 }
1724 } else if (commitCountInCurrentWorkLoop > 1) {
1725 warning = 'There were cascading updates';
1726 }
1727 commitCountInCurrentWorkLoop = 0;
1728 var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)';
1729 // Pause any measurements until the next loop.
1730 pauseTimers();
1731 endMark(label, '(React Tree Reconciliation)', warning);
1732 }
1733}
1734
1735function startCommitTimer() {
1736 if (enableUserTimingAPI) {
1737 if (!supportsUserTiming) {
1738 return;
1739 }
1740 isCommitting = true;
1741 hasScheduledUpdateInCurrentCommit = false;
1742 labelsInCurrentCommit.clear();
1743 beginMark('(Committing Changes)');
1744 }
1745}
1746
1747function stopCommitTimer() {
1748 if (enableUserTimingAPI) {
1749 if (!supportsUserTiming) {
1750 return;
1751 }
1752
1753 var warning = null;
1754 if (hasScheduledUpdateInCurrentCommit) {
1755 warning = 'Lifecycle hook scheduled a cascading update';
1756 } else if (commitCountInCurrentWorkLoop > 0) {
1757 warning = 'Caused by a cascading update in earlier commit';
1758 }
1759 hasScheduledUpdateInCurrentCommit = false;
1760 commitCountInCurrentWorkLoop++;
1761 isCommitting = false;
1762 labelsInCurrentCommit.clear();
1763
1764 endMark('(Committing Changes)', '(Committing Changes)', warning);
1765 }
1766}
1767
1768function startCommitSnapshotEffectsTimer() {
1769 if (enableUserTimingAPI) {
1770 if (!supportsUserTiming) {
1771 return;
1772 }
1773 effectCountInCurrentCommit = 0;
1774 beginMark('(Committing Snapshot Effects)');
1775 }
1776}
1777
1778function stopCommitSnapshotEffectsTimer() {
1779 if (enableUserTimingAPI) {
1780 if (!supportsUserTiming) {
1781 return;
1782 }
1783 var count = effectCountInCurrentCommit;
1784 effectCountInCurrentCommit = 0;
1785 endMark('(Committing Snapshot Effects: ' + count + ' Total)', '(Committing Snapshot Effects)', null);
1786 }
1787}
1788
1789function startCommitHostEffectsTimer() {
1790 if (enableUserTimingAPI) {
1791 if (!supportsUserTiming) {
1792 return;
1793 }
1794 effectCountInCurrentCommit = 0;
1795 beginMark('(Committing Host Effects)');
1796 }
1797}
1798
1799function stopCommitHostEffectsTimer() {
1800 if (enableUserTimingAPI) {
1801 if (!supportsUserTiming) {
1802 return;
1803 }
1804 var count = effectCountInCurrentCommit;
1805 effectCountInCurrentCommit = 0;
1806 endMark('(Committing Host Effects: ' + count + ' Total)', '(Committing Host Effects)', null);
1807 }
1808}
1809
1810function startCommitLifeCyclesTimer() {
1811 if (enableUserTimingAPI) {
1812 if (!supportsUserTiming) {
1813 return;
1814 }
1815 effectCountInCurrentCommit = 0;
1816 beginMark('(Calling Lifecycle Methods)');
1817 }
1818}
1819
1820function stopCommitLifeCyclesTimer() {
1821 if (enableUserTimingAPI) {
1822 if (!supportsUserTiming) {
1823 return;
1824 }
1825 var count = effectCountInCurrentCommit;
1826 effectCountInCurrentCommit = 0;
1827 endMark('(Calling Lifecycle Methods: ' + count + ' Total)', '(Calling Lifecycle Methods)', null);
1828 }
1829}
1830
1831var valueStack = [];
1832
1833var fiberStack = void 0;
1834
1835{
1836 fiberStack = [];
1837}
1838
1839var index = -1;
1840
1841function createCursor(defaultValue) {
1842 return {
1843 current: defaultValue
1844 };
1845}
1846
1847function pop(cursor, fiber) {
1848 if (index < 0) {
1849 {
1850 warningWithoutStack$1(false, 'Unexpected pop.');
1851 }
1852 return;
1853 }
1854
1855 {
1856 if (fiber !== fiberStack[index]) {
1857 warningWithoutStack$1(false, 'Unexpected Fiber popped.');
1858 }
1859 }
1860
1861 cursor.current = valueStack[index];
1862
1863 valueStack[index] = null;
1864
1865 {
1866 fiberStack[index] = null;
1867 }
1868
1869 index--;
1870}
1871
1872function push(cursor, value, fiber) {
1873 index++;
1874
1875 valueStack[index] = cursor.current;
1876
1877 {
1878 fiberStack[index] = fiber;
1879 }
1880
1881 cursor.current = value;
1882}
1883
1884function checkThatStackIsEmpty() {
1885 {
1886 if (index !== -1) {
1887 warningWithoutStack$1(false, 'Expected an empty stack. Something was not reset properly.');
1888 }
1889 }
1890}
1891
1892function resetStackAfterFatalErrorInDev() {
1893 {
1894 index = -1;
1895 valueStack.length = 0;
1896 fiberStack.length = 0;
1897 }
1898}
1899
1900var warnedAboutMissingGetChildContext = void 0;
1901
1902{
1903 warnedAboutMissingGetChildContext = {};
1904}
1905
1906var emptyContextObject = {};
1907{
1908 Object.freeze(emptyContextObject);
1909}
1910
1911// A cursor to the current merged context object on the stack.
1912var contextStackCursor = createCursor(emptyContextObject);
1913// A cursor to a boolean indicating whether the context has changed.
1914var didPerformWorkStackCursor = createCursor(false);
1915// Keep track of the previous context object that was on the stack.
1916// We use this to get access to the parent context after we have already
1917// pushed the next context provider, and now need to merge their contexts.
1918var previousContext = emptyContextObject;
1919
1920function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
1921 if (didPushOwnContextIfProvider && isContextProvider(Component)) {
1922 // If the fiber is a context provider itself, when we read its context
1923 // we may have already pushed its own child context on the stack. A context
1924 // provider should not "see" its own child context. Therefore we read the
1925 // previous (parent) context instead for a context provider.
1926 return previousContext;
1927 }
1928 return contextStackCursor.current;
1929}
1930
1931function cacheContext(workInProgress, unmaskedContext, maskedContext) {
1932 var instance = workInProgress.stateNode;
1933 instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
1934 instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
1935}
1936
1937function getMaskedContext(workInProgress, unmaskedContext) {
1938 var type = workInProgress.type;
1939 var contextTypes = type.contextTypes;
1940 if (!contextTypes) {
1941 return emptyContextObject;
1942 }
1943
1944 // Avoid recreating masked context unless unmasked context has changed.
1945 // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
1946 // This may trigger infinite loops if componentWillReceiveProps calls setState.
1947 var instance = workInProgress.stateNode;
1948 if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
1949 return instance.__reactInternalMemoizedMaskedChildContext;
1950 }
1951
1952 var context = {};
1953 for (var key in contextTypes) {
1954 context[key] = unmaskedContext[key];
1955 }
1956
1957 {
1958 var name = getComponentName(type) || 'Unknown';
1959 checkPropTypes_1(contextTypes, context, 'context', name, getCurrentFiberStackInDev);
1960 }
1961
1962 // Cache unmasked context so we can avoid recreating masked context unless necessary.
1963 // Context is created before the class component is instantiated so check for instance.
1964 if (instance) {
1965 cacheContext(workInProgress, unmaskedContext, context);
1966 }
1967
1968 return context;
1969}
1970
1971function hasContextChanged() {
1972 return didPerformWorkStackCursor.current;
1973}
1974
1975function isContextProvider(type) {
1976 var childContextTypes = type.childContextTypes;
1977 return childContextTypes !== null && childContextTypes !== undefined;
1978}
1979
1980function popContext(fiber) {
1981 pop(didPerformWorkStackCursor, fiber);
1982 pop(contextStackCursor, fiber);
1983}
1984
1985function popTopLevelContextObject(fiber) {
1986 pop(didPerformWorkStackCursor, fiber);
1987 pop(contextStackCursor, fiber);
1988}
1989
1990function pushTopLevelContextObject(fiber, context, didChange) {
1991 !(contextStackCursor.current === emptyContextObject) ? invariant(false, 'Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue.') : void 0;
1992
1993 push(contextStackCursor, context, fiber);
1994 push(didPerformWorkStackCursor, didChange, fiber);
1995}
1996
1997function processChildContext(fiber, type, parentContext) {
1998 var instance = fiber.stateNode;
1999 var childContextTypes = type.childContextTypes;
2000
2001 // TODO (bvaughn) Replace this behavior with an invariant() in the future.
2002 // It has only been added in Fiber to match the (unintentional) behavior in Stack.
2003 if (typeof instance.getChildContext !== 'function') {
2004 {
2005 var componentName = getComponentName(type) || 'Unknown';
2006
2007 if (!warnedAboutMissingGetChildContext[componentName]) {
2008 warnedAboutMissingGetChildContext[componentName] = true;
2009 warningWithoutStack$1(false, '%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);
2010 }
2011 }
2012 return parentContext;
2013 }
2014
2015 var childContext = void 0;
2016 {
2017 setCurrentPhase('getChildContext');
2018 }
2019 startPhaseTimer(fiber, 'getChildContext');
2020 childContext = instance.getChildContext();
2021 stopPhaseTimer();
2022 {
2023 setCurrentPhase(null);
2024 }
2025 for (var contextKey in childContext) {
2026 !(contextKey in childContextTypes) ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', getComponentName(type) || 'Unknown', contextKey) : void 0;
2027 }
2028 {
2029 var name = getComponentName(type) || 'Unknown';
2030 checkPropTypes_1(childContextTypes, childContext, 'child context', name,
2031 // In practice, there is one case in which we won't get a stack. It's when
2032 // somebody calls unstable_renderSubtreeIntoContainer() and we process
2033 // context from the parent component instance. The stack will be missing
2034 // because it's outside of the reconciliation, and so the pointer has not
2035 // been set. This is rare and doesn't matter. We'll also remove that API.
2036 getCurrentFiberStackInDev);
2037 }
2038
2039 return _assign({}, parentContext, childContext);
2040}
2041
2042function pushContextProvider(workInProgress) {
2043 var instance = workInProgress.stateNode;
2044 // We push the context as early as possible to ensure stack integrity.
2045 // If the instance does not exist yet, we will push null at first,
2046 // and replace it on the stack later when invalidating the context.
2047 var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject;
2048
2049 // Remember the parent context so we can merge with it later.
2050 // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
2051 previousContext = contextStackCursor.current;
2052 push(contextStackCursor, memoizedMergedChildContext, workInProgress);
2053 push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
2054
2055 return true;
2056}
2057
2058function invalidateContextProvider(workInProgress, type, didChange) {
2059 var instance = workInProgress.stateNode;
2060 !instance ? invariant(false, 'Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue.') : void 0;
2061
2062 if (didChange) {
2063 // Merge parent and own context.
2064 // Skip this if we're not updating due to sCU.
2065 // This avoids unnecessarily recomputing memoized values.
2066 var mergedContext = processChildContext(workInProgress, type, previousContext);
2067 instance.__reactInternalMemoizedMergedChildContext = mergedContext;
2068
2069 // Replace the old (or empty) context with the new one.
2070 // It is important to unwind the context in the reverse order.
2071 pop(didPerformWorkStackCursor, workInProgress);
2072 pop(contextStackCursor, workInProgress);
2073 // Now push the new context and mark that it has changed.
2074 push(contextStackCursor, mergedContext, workInProgress);
2075 push(didPerformWorkStackCursor, didChange, workInProgress);
2076 } else {
2077 pop(didPerformWorkStackCursor, workInProgress);
2078 push(didPerformWorkStackCursor, didChange, workInProgress);
2079 }
2080}
2081
2082function findCurrentUnmaskedContext(fiber) {
2083 // Currently this is only used with renderSubtreeIntoContainer; not sure if it
2084 // makes sense elsewhere
2085 !(isFiberMounted(fiber) && fiber.tag === ClassComponent) ? invariant(false, 'Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue.') : void 0;
2086
2087 var node = fiber;
2088 do {
2089 switch (node.tag) {
2090 case HostRoot:
2091 return node.stateNode.context;
2092 case ClassComponent:
2093 {
2094 var Component = node.type;
2095 if (isContextProvider(Component)) {
2096 return node.stateNode.__reactInternalMemoizedMergedChildContext;
2097 }
2098 break;
2099 }
2100 }
2101 node = node.return;
2102 } while (node !== null);
2103 invariant(false, 'Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.');
2104}
2105
2106var onCommitFiberRoot = null;
2107var onCommitFiberUnmount = null;
2108var hasLoggedError = false;
2109
2110function catchErrors(fn) {
2111 return function (arg) {
2112 try {
2113 return fn(arg);
2114 } catch (err) {
2115 if (true && !hasLoggedError) {
2116 hasLoggedError = true;
2117 warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err);
2118 }
2119 }
2120 };
2121}
2122
2123var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
2124
2125function injectInternals(internals) {
2126 if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
2127 // No DevTools
2128 return false;
2129 }
2130 var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
2131 if (hook.isDisabled) {
2132 // This isn't a real property on the hook, but it can be set to opt out
2133 // of DevTools integration and associated warnings and logs.
2134 // https://github.com/facebook/react/issues/3877
2135 return true;
2136 }
2137 if (!hook.supportsFiber) {
2138 {
2139 warningWithoutStack$1(false, 'The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://fb.me/react-devtools');
2140 }
2141 // DevTools exists, even though it doesn't support Fiber.
2142 return true;
2143 }
2144 try {
2145 var rendererID = hook.inject(internals);
2146 // We have successfully injected, so now it is safe to set up hooks.
2147 onCommitFiberRoot = catchErrors(function (root) {
2148 return hook.onCommitFiberRoot(rendererID, root);
2149 });
2150 onCommitFiberUnmount = catchErrors(function (fiber) {
2151 return hook.onCommitFiberUnmount(rendererID, fiber);
2152 });
2153 } catch (err) {
2154 // Catch all errors because it is unsafe to throw during initialization.
2155 {
2156 warningWithoutStack$1(false, 'React DevTools encountered an error: %s.', err);
2157 }
2158 }
2159 // DevTools exists
2160 return true;
2161}
2162
2163function onCommitRoot(root) {
2164 if (typeof onCommitFiberRoot === 'function') {
2165 onCommitFiberRoot(root);
2166 }
2167}
2168
2169function onCommitUnmount(fiber) {
2170 if (typeof onCommitFiberUnmount === 'function') {
2171 onCommitFiberUnmount(fiber);
2172 }
2173}
2174
2175// Max 31 bit integer. The max integer size in V8 for 32-bit systems.
2176// Math.pow(2, 30) - 1
2177// 0b111111111111111111111111111111
2178var maxSigned31BitInt = 1073741823;
2179
2180var NoWork = 0;
2181var Never = 1;
2182var Sync = maxSigned31BitInt;
2183
2184var UNIT_SIZE = 10;
2185var MAGIC_NUMBER_OFFSET = maxSigned31BitInt - 1;
2186
2187// 1 unit of expiration time represents 10ms.
2188function msToExpirationTime(ms) {
2189 // Always add an offset so that we don't clash with the magic number for NoWork.
2190 return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);
2191}
2192
2193function expirationTimeToMs(expirationTime) {
2194 return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE;
2195}
2196
2197function ceiling(num, precision) {
2198 return ((num / precision | 0) + 1) * precision;
2199}
2200
2201function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) {
2202 return MAGIC_NUMBER_OFFSET - ceiling(MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE);
2203}
2204
2205var LOW_PRIORITY_EXPIRATION = 5000;
2206var LOW_PRIORITY_BATCH_SIZE = 250;
2207
2208function computeAsyncExpiration(currentTime) {
2209 return computeExpirationBucket(currentTime, LOW_PRIORITY_EXPIRATION, LOW_PRIORITY_BATCH_SIZE);
2210}
2211
2212// We intentionally set a higher expiration time for interactive updates in
2213// dev than in production.
2214//
2215// If the main thread is being blocked so long that you hit the expiration,
2216// it's a problem that could be solved with better scheduling.
2217//
2218// People will be more likely to notice this and fix it with the long
2219// expiration time in development.
2220//
2221// In production we opt for better UX at the risk of masking scheduling
2222// problems, by expiring fast.
2223var HIGH_PRIORITY_EXPIRATION = 500;
2224var HIGH_PRIORITY_BATCH_SIZE = 100;
2225
2226function computeInteractiveExpiration(currentTime) {
2227 return computeExpirationBucket(currentTime, HIGH_PRIORITY_EXPIRATION, HIGH_PRIORITY_BATCH_SIZE);
2228}
2229
2230var NoContext = 0;
2231var ConcurrentMode = 1;
2232var StrictMode = 2;
2233var ProfileMode = 4;
2234
2235var hasBadMapPolyfill = void 0;
2236
2237{
2238 hasBadMapPolyfill = false;
2239 try {
2240 var nonExtensibleObject = Object.preventExtensions({});
2241 var testMap = new Map([[nonExtensibleObject, null]]);
2242 var testSet = new Set([nonExtensibleObject]);
2243 // This is necessary for Rollup to not consider these unused.
2244 // https://github.com/rollup/rollup/issues/1771
2245 // TODO: we can remove these if Rollup fixes the bug.
2246 testMap.set(0, 0);
2247 testSet.add(0);
2248 } catch (e) {
2249 // TODO: Consider warning about bad polyfills
2250 hasBadMapPolyfill = true;
2251 }
2252}
2253
2254// A Fiber is work on a Component that needs to be done or was done. There can
2255// be more than one per component.
2256
2257
2258var debugCounter = void 0;
2259
2260{
2261 debugCounter = 1;
2262}
2263
2264function FiberNode(tag, pendingProps, key, mode) {
2265 // Instance
2266 this.tag = tag;
2267 this.key = key;
2268 this.elementType = null;
2269 this.type = null;
2270 this.stateNode = null;
2271
2272 // Fiber
2273 this.return = null;
2274 this.child = null;
2275 this.sibling = null;
2276 this.index = 0;
2277
2278 this.ref = null;
2279
2280 this.pendingProps = pendingProps;
2281 this.memoizedProps = null;
2282 this.updateQueue = null;
2283 this.memoizedState = null;
2284 this.contextDependencies = null;
2285
2286 this.mode = mode;
2287
2288 // Effects
2289 this.effectTag = NoEffect;
2290 this.nextEffect = null;
2291
2292 this.firstEffect = null;
2293 this.lastEffect = null;
2294
2295 this.expirationTime = NoWork;
2296 this.childExpirationTime = NoWork;
2297
2298 this.alternate = null;
2299
2300 if (enableProfilerTimer) {
2301 // Note: The following is done to avoid a v8 performance cliff.
2302 //
2303 // Initializing the fields below to smis and later updating them with
2304 // double values will cause Fibers to end up having separate shapes.
2305 // This behavior/bug has something to do with Object.preventExtension().
2306 // Fortunately this only impacts DEV builds.
2307 // Unfortunately it makes React unusably slow for some applications.
2308 // To work around this, initialize the fields below with doubles.
2309 //
2310 // Learn more about this here:
2311 // https://github.com/facebook/react/issues/14365
2312 // https://bugs.chromium.org/p/v8/issues/detail?id=8538
2313 this.actualDuration = Number.NaN;
2314 this.actualStartTime = Number.NaN;
2315 this.selfBaseDuration = Number.NaN;
2316 this.treeBaseDuration = Number.NaN;
2317
2318 // It's okay to replace the initial doubles with smis after initialization.
2319 // This won't trigger the performance cliff mentioned above,
2320 // and it simplifies other profiler code (including DevTools).
2321 this.actualDuration = 0;
2322 this.actualStartTime = -1;
2323 this.selfBaseDuration = 0;
2324 this.treeBaseDuration = 0;
2325 }
2326
2327 {
2328 this._debugID = debugCounter++;
2329 this._debugSource = null;
2330 this._debugOwner = null;
2331 this._debugIsCurrentlyTiming = false;
2332 this._debugHookTypes = null;
2333 if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
2334 Object.preventExtensions(this);
2335 }
2336 }
2337}
2338
2339// This is a constructor function, rather than a POJO constructor, still
2340// please ensure we do the following:
2341// 1) Nobody should add any instance methods on this. Instance methods can be
2342// more difficult to predict when they get optimized and they are almost
2343// never inlined properly in static compilers.
2344// 2) Nobody should rely on `instanceof Fiber` for type testing. We should
2345// always know when it is a fiber.
2346// 3) We might want to experiment with using numeric keys since they are easier
2347// to optimize in a non-JIT environment.
2348// 4) We can easily go from a constructor to a createFiber object literal if that
2349// is faster.
2350// 5) It should be easy to port this to a C struct and keep a C implementation
2351// compatible.
2352var createFiber = function (tag, pendingProps, key, mode) {
2353 // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
2354 return new FiberNode(tag, pendingProps, key, mode);
2355};
2356
2357function shouldConstruct(Component) {
2358 var prototype = Component.prototype;
2359 return !!(prototype && prototype.isReactComponent);
2360}
2361
2362function isSimpleFunctionComponent(type) {
2363 return typeof type === 'function' && !shouldConstruct(type) && type.defaultProps === undefined;
2364}
2365
2366function resolveLazyComponentTag(Component) {
2367 if (typeof Component === 'function') {
2368 return shouldConstruct(Component) ? ClassComponent : FunctionComponent;
2369 } else if (Component !== undefined && Component !== null) {
2370 var $$typeof = Component.$$typeof;
2371 if ($$typeof === REACT_FORWARD_REF_TYPE) {
2372 return ForwardRef;
2373 }
2374 if ($$typeof === REACT_MEMO_TYPE) {
2375 return MemoComponent;
2376 }
2377 }
2378 return IndeterminateComponent;
2379}
2380
2381// This is used to create an alternate fiber to do work on.
2382function createWorkInProgress(current, pendingProps, expirationTime) {
2383 var workInProgress = current.alternate;
2384 if (workInProgress === null) {
2385 // We use a double buffering pooling technique because we know that we'll
2386 // only ever need at most two versions of a tree. We pool the "other" unused
2387 // node that we're free to reuse. This is lazily created to avoid allocating
2388 // extra objects for things that are never updated. It also allow us to
2389 // reclaim the extra memory if needed.
2390 workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
2391 workInProgress.elementType = current.elementType;
2392 workInProgress.type = current.type;
2393 workInProgress.stateNode = current.stateNode;
2394
2395 {
2396 // DEV-only fields
2397 workInProgress._debugID = current._debugID;
2398 workInProgress._debugSource = current._debugSource;
2399 workInProgress._debugOwner = current._debugOwner;
2400 workInProgress._debugHookTypes = current._debugHookTypes;
2401 }
2402
2403 workInProgress.alternate = current;
2404 current.alternate = workInProgress;
2405 } else {
2406 workInProgress.pendingProps = pendingProps;
2407
2408 // We already have an alternate.
2409 // Reset the effect tag.
2410 workInProgress.effectTag = NoEffect;
2411
2412 // The effect list is no longer valid.
2413 workInProgress.nextEffect = null;
2414 workInProgress.firstEffect = null;
2415 workInProgress.lastEffect = null;
2416
2417 if (enableProfilerTimer) {
2418 // We intentionally reset, rather than copy, actualDuration & actualStartTime.
2419 // This prevents time from endlessly accumulating in new commits.
2420 // This has the downside of resetting values for different priority renders,
2421 // But works for yielding (the common case) and should support resuming.
2422 workInProgress.actualDuration = 0;
2423 workInProgress.actualStartTime = -1;
2424 }
2425 }
2426
2427 workInProgress.childExpirationTime = current.childExpirationTime;
2428 workInProgress.expirationTime = current.expirationTime;
2429
2430 workInProgress.child = current.child;
2431 workInProgress.memoizedProps = current.memoizedProps;
2432 workInProgress.memoizedState = current.memoizedState;
2433 workInProgress.updateQueue = current.updateQueue;
2434 workInProgress.contextDependencies = current.contextDependencies;
2435
2436 // These will be overridden during the parent's reconciliation
2437 workInProgress.sibling = current.sibling;
2438 workInProgress.index = current.index;
2439 workInProgress.ref = current.ref;
2440
2441 if (enableProfilerTimer) {
2442 workInProgress.selfBaseDuration = current.selfBaseDuration;
2443 workInProgress.treeBaseDuration = current.treeBaseDuration;
2444 }
2445
2446 return workInProgress;
2447}
2448
2449function createHostRootFiber(isConcurrent) {
2450 var mode = isConcurrent ? ConcurrentMode | StrictMode : NoContext;
2451
2452 if (enableProfilerTimer && isDevToolsPresent) {
2453 // Always collect profile timings when DevTools are present.
2454 // This enables DevTools to start capturing timing at any point–
2455 // Without some nodes in the tree having empty base times.
2456 mode |= ProfileMode;
2457 }
2458
2459 return createFiber(HostRoot, null, null, mode);
2460}
2461
2462function createFiberFromTypeAndProps(type, // React$ElementType
2463key, pendingProps, owner, mode, expirationTime) {
2464 var fiber = void 0;
2465
2466 var fiberTag = IndeterminateComponent;
2467 // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
2468 var resolvedType = type;
2469 if (typeof type === 'function') {
2470 if (shouldConstruct(type)) {
2471 fiberTag = ClassComponent;
2472 }
2473 } else if (typeof type === 'string') {
2474 fiberTag = HostComponent;
2475 } else {
2476 getTag: switch (type) {
2477 case REACT_FRAGMENT_TYPE:
2478 return createFiberFromFragment(pendingProps.children, mode, expirationTime, key);
2479 case REACT_CONCURRENT_MODE_TYPE:
2480 return createFiberFromMode(pendingProps, mode | ConcurrentMode | StrictMode, expirationTime, key);
2481 case REACT_STRICT_MODE_TYPE:
2482 return createFiberFromMode(pendingProps, mode | StrictMode, expirationTime, key);
2483 case REACT_PROFILER_TYPE:
2484 return createFiberFromProfiler(pendingProps, mode, expirationTime, key);
2485 case REACT_SUSPENSE_TYPE:
2486 return createFiberFromSuspense(pendingProps, mode, expirationTime, key);
2487 default:
2488 {
2489 if (typeof type === 'object' && type !== null) {
2490 switch (type.$$typeof) {
2491 case REACT_PROVIDER_TYPE:
2492 fiberTag = ContextProvider;
2493 break getTag;
2494 case REACT_CONTEXT_TYPE:
2495 // This is a consumer
2496 fiberTag = ContextConsumer;
2497 break getTag;
2498 case REACT_FORWARD_REF_TYPE:
2499 fiberTag = ForwardRef;
2500 break getTag;
2501 case REACT_MEMO_TYPE:
2502 fiberTag = MemoComponent;
2503 break getTag;
2504 case REACT_LAZY_TYPE:
2505 fiberTag = LazyComponent;
2506 resolvedType = null;
2507 break getTag;
2508 }
2509 }
2510 var info = '';
2511 {
2512 if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
2513 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.';
2514 }
2515 var ownerName = owner ? getComponentName(owner.type) : null;
2516 if (ownerName) {
2517 info += '\n\nCheck the render method of `' + ownerName + '`.';
2518 }
2519 }
2520 invariant(false, 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s', type == null ? type : typeof type, info);
2521 }
2522 }
2523 }
2524
2525 fiber = createFiber(fiberTag, pendingProps, key, mode);
2526 fiber.elementType = type;
2527 fiber.type = resolvedType;
2528 fiber.expirationTime = expirationTime;
2529
2530 return fiber;
2531}
2532
2533function createFiberFromElement(element, mode, expirationTime) {
2534 var owner = null;
2535 {
2536 owner = element._owner;
2537 }
2538 var type = element.type;
2539 var key = element.key;
2540 var pendingProps = element.props;
2541 var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, expirationTime);
2542 {
2543 fiber._debugSource = element._source;
2544 fiber._debugOwner = element._owner;
2545 }
2546 return fiber;
2547}
2548
2549function createFiberFromFragment(elements, mode, expirationTime, key) {
2550 var fiber = createFiber(Fragment, elements, key, mode);
2551 fiber.expirationTime = expirationTime;
2552 return fiber;
2553}
2554
2555function createFiberFromProfiler(pendingProps, mode, expirationTime, key) {
2556 {
2557 if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') {
2558 warningWithoutStack$1(false, 'Profiler must specify an "id" string and "onRender" function as props');
2559 }
2560 }
2561
2562 var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode);
2563 // TODO: The Profiler fiber shouldn't have a type. It has a tag.
2564 fiber.elementType = REACT_PROFILER_TYPE;
2565 fiber.type = REACT_PROFILER_TYPE;
2566 fiber.expirationTime = expirationTime;
2567
2568 return fiber;
2569}
2570
2571function createFiberFromMode(pendingProps, mode, expirationTime, key) {
2572 var fiber = createFiber(Mode, pendingProps, key, mode);
2573
2574 // TODO: The Mode fiber shouldn't have a type. It has a tag.
2575 var type = (mode & ConcurrentMode) === NoContext ? REACT_STRICT_MODE_TYPE : REACT_CONCURRENT_MODE_TYPE;
2576 fiber.elementType = type;
2577 fiber.type = type;
2578
2579 fiber.expirationTime = expirationTime;
2580 return fiber;
2581}
2582
2583function createFiberFromSuspense(pendingProps, mode, expirationTime, key) {
2584 var fiber = createFiber(SuspenseComponent, pendingProps, key, mode);
2585
2586 // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
2587 var type = REACT_SUSPENSE_TYPE;
2588 fiber.elementType = type;
2589 fiber.type = type;
2590
2591 fiber.expirationTime = expirationTime;
2592 return fiber;
2593}
2594
2595function createFiberFromText(content, mode, expirationTime) {
2596 var fiber = createFiber(HostText, content, null, mode);
2597 fiber.expirationTime = expirationTime;
2598 return fiber;
2599}
2600
2601function createFiberFromHostInstanceForDeletion() {
2602 var fiber = createFiber(HostComponent, null, null, NoContext);
2603 // TODO: These should not need a type.
2604 fiber.elementType = 'DELETED';
2605 fiber.type = 'DELETED';
2606 return fiber;
2607}
2608
2609function createFiberFromPortal(portal, mode, expirationTime) {
2610 var pendingProps = portal.children !== null ? portal.children : [];
2611 var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
2612 fiber.expirationTime = expirationTime;
2613 fiber.stateNode = {
2614 containerInfo: portal.containerInfo,
2615 pendingChildren: null, // Used by persistent updates
2616 implementation: portal.implementation
2617 };
2618 return fiber;
2619}
2620
2621// Used for stashing WIP properties to replay failed work in DEV.
2622function assignFiberPropertiesInDEV(target, source) {
2623 if (target === null) {
2624 // This Fiber's initial properties will always be overwritten.
2625 // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
2626 target = createFiber(IndeterminateComponent, null, null, NoContext);
2627 }
2628
2629 // This is intentionally written as a list of all properties.
2630 // We tried to use Object.assign() instead but this is called in
2631 // the hottest path, and Object.assign() was too slow:
2632 // https://github.com/facebook/react/issues/12502
2633 // This code is DEV-only so size is not a concern.
2634
2635 target.tag = source.tag;
2636 target.key = source.key;
2637 target.elementType = source.elementType;
2638 target.type = source.type;
2639 target.stateNode = source.stateNode;
2640 target.return = source.return;
2641 target.child = source.child;
2642 target.sibling = source.sibling;
2643 target.index = source.index;
2644 target.ref = source.ref;
2645 target.pendingProps = source.pendingProps;
2646 target.memoizedProps = source.memoizedProps;
2647 target.updateQueue = source.updateQueue;
2648 target.memoizedState = source.memoizedState;
2649 target.contextDependencies = source.contextDependencies;
2650 target.mode = source.mode;
2651 target.effectTag = source.effectTag;
2652 target.nextEffect = source.nextEffect;
2653 target.firstEffect = source.firstEffect;
2654 target.lastEffect = source.lastEffect;
2655 target.expirationTime = source.expirationTime;
2656 target.childExpirationTime = source.childExpirationTime;
2657 target.alternate = source.alternate;
2658 if (enableProfilerTimer) {
2659 target.actualDuration = source.actualDuration;
2660 target.actualStartTime = source.actualStartTime;
2661 target.selfBaseDuration = source.selfBaseDuration;
2662 target.treeBaseDuration = source.treeBaseDuration;
2663 }
2664 target._debugID = source._debugID;
2665 target._debugSource = source._debugSource;
2666 target._debugOwner = source._debugOwner;
2667 target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
2668 target._debugHookTypes = source._debugHookTypes;
2669 return target;
2670}
2671
2672var ReactInternals$2 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
2673
2674var _ReactInternals$Sched$1 = ReactInternals$2.SchedulerTracing;
2675var __interactionsRef = _ReactInternals$Sched$1.__interactionsRef;
2676var __subscriberRef = _ReactInternals$Sched$1.__subscriberRef;
2677var unstable_clear = _ReactInternals$Sched$1.unstable_clear;
2678var unstable_getCurrent = _ReactInternals$Sched$1.unstable_getCurrent;
2679var unstable_getThreadID = _ReactInternals$Sched$1.unstable_getThreadID;
2680var unstable_subscribe = _ReactInternals$Sched$1.unstable_subscribe;
2681var unstable_trace = _ReactInternals$Sched$1.unstable_trace;
2682var unstable_unsubscribe = _ReactInternals$Sched$1.unstable_unsubscribe;
2683var unstable_wrap = _ReactInternals$Sched$1.unstable_wrap;
2684
2685// TODO: This should be lifted into the renderer.
2686
2687
2688// The following attributes are only used by interaction tracing builds.
2689// They enable interactions to be associated with their async work,
2690// And expose interaction metadata to the React DevTools Profiler plugin.
2691// Note that these attributes are only defined when the enableSchedulerTracing flag is enabled.
2692
2693
2694// Exported FiberRoot type includes all properties,
2695// To avoid requiring potentially error-prone :any casts throughout the project.
2696// Profiling properties are only safe to access in profiling builds (when enableSchedulerTracing is true).
2697// The types are defined separately within this file to ensure they stay in sync.
2698// (We don't have to use an inline :any cast when enableSchedulerTracing is disabled.)
2699
2700
2701function createFiberRoot(containerInfo, isConcurrent, hydrate) {
2702 // Cyclic construction. This cheats the type system right now because
2703 // stateNode is any.
2704 var uninitializedFiber = createHostRootFiber(isConcurrent);
2705
2706 var root = void 0;
2707 if (enableSchedulerTracing) {
2708 root = {
2709 current: uninitializedFiber,
2710 containerInfo: containerInfo,
2711 pendingChildren: null,
2712
2713 earliestPendingTime: NoWork,
2714 latestPendingTime: NoWork,
2715 earliestSuspendedTime: NoWork,
2716 latestSuspendedTime: NoWork,
2717 latestPingedTime: NoWork,
2718
2719 pingCache: null,
2720
2721 didError: false,
2722
2723 pendingCommitExpirationTime: NoWork,
2724 finishedWork: null,
2725 timeoutHandle: noTimeout,
2726 context: null,
2727 pendingContext: null,
2728 hydrate: hydrate,
2729 nextExpirationTimeToWorkOn: NoWork,
2730 expirationTime: NoWork,
2731 firstBatch: null,
2732 nextScheduledRoot: null,
2733
2734 interactionThreadID: unstable_getThreadID(),
2735 memoizedInteractions: new Set(),
2736 pendingInteractionMap: new Map()
2737 };
2738 } else {
2739 root = {
2740 current: uninitializedFiber,
2741 containerInfo: containerInfo,
2742 pendingChildren: null,
2743
2744 pingCache: null,
2745
2746 earliestPendingTime: NoWork,
2747 latestPendingTime: NoWork,
2748 earliestSuspendedTime: NoWork,
2749 latestSuspendedTime: NoWork,
2750 latestPingedTime: NoWork,
2751
2752 didError: false,
2753
2754 pendingCommitExpirationTime: NoWork,
2755 finishedWork: null,
2756 timeoutHandle: noTimeout,
2757 context: null,
2758 pendingContext: null,
2759 hydrate: hydrate,
2760 nextExpirationTimeToWorkOn: NoWork,
2761 expirationTime: NoWork,
2762 firstBatch: null,
2763 nextScheduledRoot: null
2764 };
2765 }
2766
2767 uninitializedFiber.stateNode = root;
2768
2769 // The reason for the way the Flow types are structured in this file,
2770 // Is to avoid needing :any casts everywhere interaction tracing fields are used.
2771 // Unfortunately that requires an :any cast for non-interaction tracing capable builds.
2772 // $FlowFixMe Remove this :any cast and replace it with something better.
2773 return root;
2774}
2775
2776var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) {
2777 var funcArgs = Array.prototype.slice.call(arguments, 3);
2778 try {
2779 func.apply(context, funcArgs);
2780 } catch (error) {
2781 this.onError(error);
2782 }
2783};
2784
2785{
2786 // In DEV mode, we swap out invokeGuardedCallback for a special version
2787 // that plays more nicely with the browser's DevTools. The idea is to preserve
2788 // "Pause on exceptions" behavior. Because React wraps all user-provided
2789 // functions in invokeGuardedCallback, and the production version of
2790 // invokeGuardedCallback uses a try-catch, all user exceptions are treated
2791 // like caught exceptions, and the DevTools won't pause unless the developer
2792 // takes the extra step of enabling pause on caught exceptions. This is
2793 // unintuitive, though, because even though React has caught the error, from
2794 // the developer's perspective, the error is uncaught.
2795 //
2796 // To preserve the expected "Pause on exceptions" behavior, we don't use a
2797 // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
2798 // DOM node, and call the user-provided callback from inside an event handler
2799 // for that fake event. If the callback throws, the error is "captured" using
2800 // a global event handler. But because the error happens in a different
2801 // event loop context, it does not interrupt the normal program flow.
2802 // Effectively, this gives us try-catch behavior without actually using
2803 // try-catch. Neat!
2804
2805 // Check that the browser supports the APIs we need to implement our special
2806 // DEV version of invokeGuardedCallback
2807 if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
2808 var fakeNode = document.createElement('react');
2809
2810 var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) {
2811 // If document doesn't exist we know for sure we will crash in this method
2812 // when we call document.createEvent(). However this can cause confusing
2813 // errors: https://github.com/facebookincubator/create-react-app/issues/3482
2814 // So we preemptively throw with a better message instead.
2815 !(typeof document !== 'undefined') ? invariant(false, 'The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous.') : void 0;
2816 var evt = document.createEvent('Event');
2817
2818 // Keeps track of whether the user-provided callback threw an error. We
2819 // set this to true at the beginning, then set it to false right after
2820 // calling the function. If the function errors, `didError` will never be
2821 // set to false. This strategy works even if the browser is flaky and
2822 // fails to call our global error handler, because it doesn't rely on
2823 // the error event at all.
2824 var didError = true;
2825
2826 // Keeps track of the value of window.event so that we can reset it
2827 // during the callback to let user code access window.event in the
2828 // browsers that support it.
2829 var windowEvent = window.event;
2830
2831 // Keeps track of the descriptor of window.event to restore it after event
2832 // dispatching: https://github.com/facebook/react/issues/13688
2833 var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event');
2834
2835 // Create an event handler for our fake event. We will synchronously
2836 // dispatch our fake event using `dispatchEvent`. Inside the handler, we
2837 // call the user-provided callback.
2838 var funcArgs = Array.prototype.slice.call(arguments, 3);
2839 function callCallback() {
2840 // We immediately remove the callback from event listeners so that
2841 // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
2842 // nested call would trigger the fake event handlers of any call higher
2843 // in the stack.
2844 fakeNode.removeEventListener(evtType, callCallback, false);
2845
2846 // We check for window.hasOwnProperty('event') to prevent the
2847 // window.event assignment in both IE <= 10 as they throw an error
2848 // "Member not found" in strict mode, and in Firefox which does not
2849 // support window.event.
2850 if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
2851 window.event = windowEvent;
2852 }
2853
2854 func.apply(context, funcArgs);
2855 didError = false;
2856 }
2857
2858 // Create a global error event handler. We use this to capture the value
2859 // that was thrown. It's possible that this error handler will fire more
2860 // than once; for example, if non-React code also calls `dispatchEvent`
2861 // and a handler for that event throws. We should be resilient to most of
2862 // those cases. Even if our error event handler fires more than once, the
2863 // last error event is always used. If the callback actually does error,
2864 // we know that the last error event is the correct one, because it's not
2865 // possible for anything else to have happened in between our callback
2866 // erroring and the code that follows the `dispatchEvent` call below. If
2867 // the callback doesn't error, but the error event was fired, we know to
2868 // ignore it because `didError` will be false, as described above.
2869 var error = void 0;
2870 // Use this to track whether the error event is ever called.
2871 var didSetError = false;
2872 var isCrossOriginError = false;
2873
2874 function handleWindowError(event) {
2875 error = event.error;
2876 didSetError = true;
2877 if (error === null && event.colno === 0 && event.lineno === 0) {
2878 isCrossOriginError = true;
2879 }
2880 if (event.defaultPrevented) {
2881 // Some other error handler has prevented default.
2882 // Browsers silence the error report if this happens.
2883 // We'll remember this to later decide whether to log it or not.
2884 if (error != null && typeof error === 'object') {
2885 try {
2886 error._suppressLogging = true;
2887 } catch (inner) {
2888 // Ignore.
2889 }
2890 }
2891 }
2892 }
2893
2894 // Create a fake event type.
2895 var evtType = 'react-' + (name ? name : 'invokeguardedcallback');
2896
2897 // Attach our event handlers
2898 window.addEventListener('error', handleWindowError);
2899 fakeNode.addEventListener(evtType, callCallback, false);
2900
2901 // Synchronously dispatch our fake event. If the user-provided function
2902 // errors, it will trigger our global error handler.
2903 evt.initEvent(evtType, false, false);
2904 fakeNode.dispatchEvent(evt);
2905
2906 if (windowEventDescriptor) {
2907 Object.defineProperty(window, 'event', windowEventDescriptor);
2908 }
2909
2910 if (didError) {
2911 if (!didSetError) {
2912 // The callback errored, but the error event never fired.
2913 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.');
2914 } else if (isCrossOriginError) {
2915 error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://fb.me/react-crossorigin-error for more information.');
2916 }
2917 this.onError(error);
2918 }
2919
2920 // Remove our event listeners
2921 window.removeEventListener('error', handleWindowError);
2922 };
2923
2924 invokeGuardedCallbackImpl = invokeGuardedCallbackDev;
2925 }
2926}
2927
2928var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
2929
2930// Used by Fiber to simulate a try-catch.
2931var hasError = false;
2932var caughtError = null;
2933
2934var reporter = {
2935 onError: function (error) {
2936 hasError = true;
2937 caughtError = error;
2938 }
2939};
2940
2941/**
2942 * Call a function while guarding against errors that happens within it.
2943 * Returns an error if it throws, otherwise null.
2944 *
2945 * In production, this is implemented using a try-catch. The reason we don't
2946 * use a try-catch directly is so that we can swap out a different
2947 * implementation in DEV mode.
2948 *
2949 * @param {String} name of the guard to use for logging or debugging
2950 * @param {Function} func The function to invoke
2951 * @param {*} context The context to use when calling the function
2952 * @param {...*} args Arguments for function
2953 */
2954function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
2955 hasError = false;
2956 caughtError = null;
2957 invokeGuardedCallbackImpl$1.apply(reporter, arguments);
2958}
2959
2960/**
2961 * Same as invokeGuardedCallback, but instead of returning an error, it stores
2962 * it in a global so it can be rethrown by `rethrowCaughtError` later.
2963 * TODO: See if caughtError and rethrowError can be unified.
2964 *
2965 * @param {String} name of the guard to use for logging or debugging
2966 * @param {Function} func The function to invoke
2967 * @param {*} context The context to use when calling the function
2968 * @param {...*} args Arguments for function
2969 */
2970
2971
2972/**
2973 * During execution of guarded functions we will capture the first error which
2974 * we will rethrow to be handled by the top level error handler.
2975 */
2976
2977
2978function hasCaughtError() {
2979 return hasError;
2980}
2981
2982function clearCaughtError() {
2983 if (hasError) {
2984 var error = caughtError;
2985 hasError = false;
2986 caughtError = null;
2987 return error;
2988 } else {
2989 invariant(false, 'clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.');
2990 }
2991}
2992
2993/**
2994 * Forked from fbjs/warning:
2995 * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
2996 *
2997 * Only change is we use console.warn instead of console.error,
2998 * and do nothing when 'console' is not supported.
2999 * This really simplifies the code.
3000 * ---
3001 * Similar to invariant but only logs a warning if the condition is not met.
3002 * This can be used to log issues in development environments in critical
3003 * paths. Removing the logging code for production environments will keep the
3004 * same logic and follow the same code paths.
3005 */
3006
3007var lowPriorityWarning = function () {};
3008
3009{
3010 var printWarning$1 = function (format) {
3011 for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
3012 args[_key - 1] = arguments[_key];
3013 }
3014
3015 var argIndex = 0;
3016 var message = 'Warning: ' + format.replace(/%s/g, function () {
3017 return args[argIndex++];
3018 });
3019 if (typeof console !== 'undefined') {
3020 console.warn(message);
3021 }
3022 try {
3023 // --- Welcome to debugging React ---
3024 // This error was thrown as a convenience so that you can use this stack
3025 // to find the callsite that caused this warning to fire.
3026 throw new Error(message);
3027 } catch (x) {}
3028 };
3029
3030 lowPriorityWarning = function (condition, format) {
3031 if (format === undefined) {
3032 throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument');
3033 }
3034 if (!condition) {
3035 for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
3036 args[_key2 - 2] = arguments[_key2];
3037 }
3038
3039 printWarning$1.apply(undefined, [format].concat(args));
3040 }
3041 };
3042}
3043
3044var lowPriorityWarning$1 = lowPriorityWarning;
3045
3046var ReactStrictModeWarnings = {
3047 discardPendingWarnings: function () {},
3048 flushPendingDeprecationWarnings: function () {},
3049 flushPendingUnsafeLifecycleWarnings: function () {},
3050 recordDeprecationWarnings: function (fiber, instance) {},
3051 recordUnsafeLifecycleWarnings: function (fiber, instance) {},
3052 recordLegacyContextWarning: function (fiber, instance) {},
3053 flushLegacyContextWarning: function () {}
3054};
3055
3056{
3057 var LIFECYCLE_SUGGESTIONS = {
3058 UNSAFE_componentWillMount: 'componentDidMount',
3059 UNSAFE_componentWillReceiveProps: 'static getDerivedStateFromProps',
3060 UNSAFE_componentWillUpdate: 'componentDidUpdate'
3061 };
3062
3063 var pendingComponentWillMountWarnings = [];
3064 var pendingComponentWillReceivePropsWarnings = [];
3065 var pendingComponentWillUpdateWarnings = [];
3066 var pendingUnsafeLifecycleWarnings = new Map();
3067 var pendingLegacyContextWarning = new Map();
3068
3069 // Tracks components we have already warned about.
3070 var didWarnAboutDeprecatedLifecycles = new Set();
3071 var didWarnAboutUnsafeLifecycles = new Set();
3072 var didWarnAboutLegacyContext = new Set();
3073
3074 var setToSortedString = function (set) {
3075 var array = [];
3076 set.forEach(function (value) {
3077 array.push(value);
3078 });
3079 return array.sort().join(', ');
3080 };
3081
3082 ReactStrictModeWarnings.discardPendingWarnings = function () {
3083 pendingComponentWillMountWarnings = [];
3084 pendingComponentWillReceivePropsWarnings = [];
3085 pendingComponentWillUpdateWarnings = [];
3086 pendingUnsafeLifecycleWarnings = new Map();
3087 pendingLegacyContextWarning = new Map();
3088 };
3089
3090 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
3091 pendingUnsafeLifecycleWarnings.forEach(function (lifecycleWarningsMap, strictRoot) {
3092 var lifecyclesWarningMessages = [];
3093
3094 Object.keys(lifecycleWarningsMap).forEach(function (lifecycle) {
3095 var lifecycleWarnings = lifecycleWarningsMap[lifecycle];
3096 if (lifecycleWarnings.length > 0) {
3097 var componentNames = new Set();
3098 lifecycleWarnings.forEach(function (fiber) {
3099 componentNames.add(getComponentName(fiber.type) || 'Component');
3100 didWarnAboutUnsafeLifecycles.add(fiber.type);
3101 });
3102
3103 var formatted = lifecycle.replace('UNSAFE_', '');
3104 var suggestion = LIFECYCLE_SUGGESTIONS[lifecycle];
3105 var sortedComponentNames = setToSortedString(componentNames);
3106
3107 lifecyclesWarningMessages.push(formatted + ': Please update the following components to use ' + (suggestion + ' instead: ' + sortedComponentNames));
3108 }
3109 });
3110
3111 if (lifecyclesWarningMessages.length > 0) {
3112 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
3113
3114 warningWithoutStack$1(false, 'Unsafe lifecycle methods were found within a strict-mode tree:%s' + '\n\n%s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-strict-mode-warnings', strictRootComponentStack, lifecyclesWarningMessages.join('\n\n'));
3115 }
3116 });
3117
3118 pendingUnsafeLifecycleWarnings = new Map();
3119 };
3120
3121 var findStrictRoot = function (fiber) {
3122 var maybeStrictRoot = null;
3123
3124 var node = fiber;
3125 while (node !== null) {
3126 if (node.mode & StrictMode) {
3127 maybeStrictRoot = node;
3128 }
3129 node = node.return;
3130 }
3131
3132 return maybeStrictRoot;
3133 };
3134
3135 ReactStrictModeWarnings.flushPendingDeprecationWarnings = function () {
3136 if (pendingComponentWillMountWarnings.length > 0) {
3137 var uniqueNames = new Set();
3138 pendingComponentWillMountWarnings.forEach(function (fiber) {
3139 uniqueNames.add(getComponentName(fiber.type) || 'Component');
3140 didWarnAboutDeprecatedLifecycles.add(fiber.type);
3141 });
3142
3143 var sortedNames = setToSortedString(uniqueNames);
3144
3145 lowPriorityWarning$1(false, 'componentWillMount is deprecated and will be removed in the next major version. ' + 'Use componentDidMount instead. As a temporary workaround, ' + 'you can rename to UNSAFE_componentWillMount.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-async-component-lifecycle-hooks', sortedNames);
3146
3147 pendingComponentWillMountWarnings = [];
3148 }
3149
3150 if (pendingComponentWillReceivePropsWarnings.length > 0) {
3151 var _uniqueNames = new Set();
3152 pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
3153 _uniqueNames.add(getComponentName(fiber.type) || 'Component');
3154 didWarnAboutDeprecatedLifecycles.add(fiber.type);
3155 });
3156
3157 var _sortedNames = setToSortedString(_uniqueNames);
3158
3159 lowPriorityWarning$1(false, 'componentWillReceiveProps is deprecated and will be removed in the next major version. ' + 'Use static getDerivedStateFromProps instead.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-async-component-lifecycle-hooks', _sortedNames);
3160
3161 pendingComponentWillReceivePropsWarnings = [];
3162 }
3163
3164 if (pendingComponentWillUpdateWarnings.length > 0) {
3165 var _uniqueNames2 = new Set();
3166 pendingComponentWillUpdateWarnings.forEach(function (fiber) {
3167 _uniqueNames2.add(getComponentName(fiber.type) || 'Component');
3168 didWarnAboutDeprecatedLifecycles.add(fiber.type);
3169 });
3170
3171 var _sortedNames2 = setToSortedString(_uniqueNames2);
3172
3173 lowPriorityWarning$1(false, 'componentWillUpdate is deprecated and will be removed in the next major version. ' + 'Use componentDidUpdate instead. As a temporary workaround, ' + 'you can rename to UNSAFE_componentWillUpdate.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-async-component-lifecycle-hooks', _sortedNames2);
3174
3175 pendingComponentWillUpdateWarnings = [];
3176 }
3177 };
3178
3179 ReactStrictModeWarnings.recordDeprecationWarnings = function (fiber, instance) {
3180 // Dedup strategy: Warn once per component.
3181 if (didWarnAboutDeprecatedLifecycles.has(fiber.type)) {
3182 return;
3183 }
3184
3185 // Don't warn about react-lifecycles-compat polyfilled components.
3186 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
3187 pendingComponentWillMountWarnings.push(fiber);
3188 }
3189 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
3190 pendingComponentWillReceivePropsWarnings.push(fiber);
3191 }
3192 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
3193 pendingComponentWillUpdateWarnings.push(fiber);
3194 }
3195 };
3196
3197 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
3198 var strictRoot = findStrictRoot(fiber);
3199 if (strictRoot === null) {
3200 warningWithoutStack$1(false, 'Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.');
3201 return;
3202 }
3203
3204 // Dedup strategy: Warn once per component.
3205 // This is difficult to track any other way since component names
3206 // are often vague and are likely to collide between 3rd party libraries.
3207 // An expand property is probably okay to use here since it's DEV-only,
3208 // and will only be set in the event of serious warnings.
3209 if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
3210 return;
3211 }
3212
3213 var warningsForRoot = void 0;
3214 if (!pendingUnsafeLifecycleWarnings.has(strictRoot)) {
3215 warningsForRoot = {
3216 UNSAFE_componentWillMount: [],
3217 UNSAFE_componentWillReceiveProps: [],
3218 UNSAFE_componentWillUpdate: []
3219 };
3220
3221 pendingUnsafeLifecycleWarnings.set(strictRoot, warningsForRoot);
3222 } else {
3223 warningsForRoot = pendingUnsafeLifecycleWarnings.get(strictRoot);
3224 }
3225
3226 var unsafeLifecycles = [];
3227 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillMount === 'function') {
3228 unsafeLifecycles.push('UNSAFE_componentWillMount');
3229 }
3230 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
3231 unsafeLifecycles.push('UNSAFE_componentWillReceiveProps');
3232 }
3233 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillUpdate === 'function') {
3234 unsafeLifecycles.push('UNSAFE_componentWillUpdate');
3235 }
3236
3237 if (unsafeLifecycles.length > 0) {
3238 unsafeLifecycles.forEach(function (lifecycle) {
3239 warningsForRoot[lifecycle].push(fiber);
3240 });
3241 }
3242 };
3243
3244 ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
3245 var strictRoot = findStrictRoot(fiber);
3246 if (strictRoot === null) {
3247 warningWithoutStack$1(false, 'Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.');
3248 return;
3249 }
3250
3251 // Dedup strategy: Warn once per component.
3252 if (didWarnAboutLegacyContext.has(fiber.type)) {
3253 return;
3254 }
3255
3256 var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
3257
3258 if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
3259 if (warningsForRoot === undefined) {
3260 warningsForRoot = [];
3261 pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
3262 }
3263 warningsForRoot.push(fiber);
3264 }
3265 };
3266
3267 ReactStrictModeWarnings.flushLegacyContextWarning = function () {
3268 pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
3269 var uniqueNames = new Set();
3270 fiberArray.forEach(function (fiber) {
3271 uniqueNames.add(getComponentName(fiber.type) || 'Component');
3272 didWarnAboutLegacyContext.add(fiber.type);
3273 });
3274
3275 var sortedNames = setToSortedString(uniqueNames);
3276 var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot);
3277
3278 warningWithoutStack$1(false, 'Legacy context API has been detected within a strict-mode tree: %s' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-strict-mode-warnings', strictRootComponentStack, sortedNames);
3279 });
3280 };
3281}
3282
3283// This lets us hook into Fiber to debug what it's doing.
3284// See https://github.com/facebook/react/pull/8033.
3285// This is not part of the public API, not even for React DevTools.
3286// You may only inject a debugTool if you work on React Fiber itself.
3287var ReactFiberInstrumentation = {
3288 debugTool: null
3289};
3290
3291var ReactFiberInstrumentation_1 = ReactFiberInstrumentation;
3292
3293// TODO: Offscreen updates should never suspend. However, a promise that
3294// suspended inside an offscreen subtree should be able to ping at the priority
3295// of the outer render.
3296
3297function markPendingPriorityLevel(root, expirationTime) {
3298 // If there's a gap between completing a failed root and retrying it,
3299 // additional updates may be scheduled. Clear `didError`, in case the update
3300 // is sufficient to fix the error.
3301 root.didError = false;
3302
3303 // Update the latest and earliest pending times
3304 var earliestPendingTime = root.earliestPendingTime;
3305 if (earliestPendingTime === NoWork) {
3306 // No other pending updates.
3307 root.earliestPendingTime = root.latestPendingTime = expirationTime;
3308 } else {
3309 if (earliestPendingTime < expirationTime) {
3310 // This is the earliest pending update.
3311 root.earliestPendingTime = expirationTime;
3312 } else {
3313 var latestPendingTime = root.latestPendingTime;
3314 if (latestPendingTime > expirationTime) {
3315 // This is the latest pending update
3316 root.latestPendingTime = expirationTime;
3317 }
3318 }
3319 }
3320 findNextExpirationTimeToWorkOn(expirationTime, root);
3321}
3322
3323function markCommittedPriorityLevels(root, earliestRemainingTime) {
3324 root.didError = false;
3325
3326 if (earliestRemainingTime === NoWork) {
3327 // Fast path. There's no remaining work. Clear everything.
3328 root.earliestPendingTime = NoWork;
3329 root.latestPendingTime = NoWork;
3330 root.earliestSuspendedTime = NoWork;
3331 root.latestSuspendedTime = NoWork;
3332 root.latestPingedTime = NoWork;
3333 findNextExpirationTimeToWorkOn(NoWork, root);
3334 return;
3335 }
3336
3337 if (earliestRemainingTime < root.latestPingedTime) {
3338 root.latestPingedTime = NoWork;
3339 }
3340
3341 // Let's see if the previous latest known pending level was just flushed.
3342 var latestPendingTime = root.latestPendingTime;
3343 if (latestPendingTime !== NoWork) {
3344 if (latestPendingTime > earliestRemainingTime) {
3345 // We've flushed all the known pending levels.
3346 root.earliestPendingTime = root.latestPendingTime = NoWork;
3347 } else {
3348 var earliestPendingTime = root.earliestPendingTime;
3349 if (earliestPendingTime > earliestRemainingTime) {
3350 // We've flushed the earliest known pending level. Set this to the
3351 // latest pending time.
3352 root.earliestPendingTime = root.latestPendingTime;
3353 }
3354 }
3355 }
3356
3357 // Now let's handle the earliest remaining level in the whole tree. We need to
3358 // decide whether to treat it as a pending level or as suspended. Check
3359 // it falls within the range of known suspended levels.
3360
3361 var earliestSuspendedTime = root.earliestSuspendedTime;
3362 if (earliestSuspendedTime === NoWork) {
3363 // There's no suspended work. Treat the earliest remaining level as a
3364 // pending level.
3365 markPendingPriorityLevel(root, earliestRemainingTime);
3366 findNextExpirationTimeToWorkOn(NoWork, root);
3367 return;
3368 }
3369
3370 var latestSuspendedTime = root.latestSuspendedTime;
3371 if (earliestRemainingTime < latestSuspendedTime) {
3372 // The earliest remaining level is later than all the suspended work. That
3373 // means we've flushed all the suspended work.
3374 root.earliestSuspendedTime = NoWork;
3375 root.latestSuspendedTime = NoWork;
3376 root.latestPingedTime = NoWork;
3377
3378 // There's no suspended work. Treat the earliest remaining level as a
3379 // pending level.
3380 markPendingPriorityLevel(root, earliestRemainingTime);
3381 findNextExpirationTimeToWorkOn(NoWork, root);
3382 return;
3383 }
3384
3385 if (earliestRemainingTime > earliestSuspendedTime) {
3386 // The earliest remaining time is earlier than all the suspended work.
3387 // Treat it as a pending update.
3388 markPendingPriorityLevel(root, earliestRemainingTime);
3389 findNextExpirationTimeToWorkOn(NoWork, root);
3390 return;
3391 }
3392
3393 // The earliest remaining time falls within the range of known suspended
3394 // levels. We should treat this as suspended work.
3395 findNextExpirationTimeToWorkOn(NoWork, root);
3396}
3397
3398function hasLowerPriorityWork(root, erroredExpirationTime) {
3399 var latestPendingTime = root.latestPendingTime;
3400 var latestSuspendedTime = root.latestSuspendedTime;
3401 var latestPingedTime = root.latestPingedTime;
3402 return latestPendingTime !== NoWork && latestPendingTime < erroredExpirationTime || latestSuspendedTime !== NoWork && latestSuspendedTime < erroredExpirationTime || latestPingedTime !== NoWork && latestPingedTime < erroredExpirationTime;
3403}
3404
3405function isPriorityLevelSuspended(root, expirationTime) {
3406 var earliestSuspendedTime = root.earliestSuspendedTime;
3407 var latestSuspendedTime = root.latestSuspendedTime;
3408 return earliestSuspendedTime !== NoWork && expirationTime <= earliestSuspendedTime && expirationTime >= latestSuspendedTime;
3409}
3410
3411function markSuspendedPriorityLevel(root, suspendedTime) {
3412 root.didError = false;
3413 clearPing(root, suspendedTime);
3414
3415 // First, check the known pending levels and update them if needed.
3416 var earliestPendingTime = root.earliestPendingTime;
3417 var latestPendingTime = root.latestPendingTime;
3418 if (earliestPendingTime === suspendedTime) {
3419 if (latestPendingTime === suspendedTime) {
3420 // Both known pending levels were suspended. Clear them.
3421 root.earliestPendingTime = root.latestPendingTime = NoWork;
3422 } else {
3423 // The earliest pending level was suspended. Clear by setting it to the
3424 // latest pending level.
3425 root.earliestPendingTime = latestPendingTime;
3426 }
3427 } else if (latestPendingTime === suspendedTime) {
3428 // The latest pending level was suspended. Clear by setting it to the
3429 // latest pending level.
3430 root.latestPendingTime = earliestPendingTime;
3431 }
3432
3433 // Finally, update the known suspended levels.
3434 var earliestSuspendedTime = root.earliestSuspendedTime;
3435 var latestSuspendedTime = root.latestSuspendedTime;
3436 if (earliestSuspendedTime === NoWork) {
3437 // No other suspended levels.
3438 root.earliestSuspendedTime = root.latestSuspendedTime = suspendedTime;
3439 } else {
3440 if (earliestSuspendedTime < suspendedTime) {
3441 // This is the earliest suspended level.
3442 root.earliestSuspendedTime = suspendedTime;
3443 } else if (latestSuspendedTime > suspendedTime) {
3444 // This is the latest suspended level
3445 root.latestSuspendedTime = suspendedTime;
3446 }
3447 }
3448
3449 findNextExpirationTimeToWorkOn(suspendedTime, root);
3450}
3451
3452function markPingedPriorityLevel(root, pingedTime) {
3453 root.didError = false;
3454
3455 // TODO: When we add back resuming, we need to ensure the progressed work
3456 // is thrown out and not reused during the restarted render. One way to
3457 // invalidate the progressed work is to restart at expirationTime + 1.
3458 var latestPingedTime = root.latestPingedTime;
3459 if (latestPingedTime === NoWork || latestPingedTime > pingedTime) {
3460 root.latestPingedTime = pingedTime;
3461 }
3462 findNextExpirationTimeToWorkOn(pingedTime, root);
3463}
3464
3465function clearPing(root, completedTime) {
3466 var latestPingedTime = root.latestPingedTime;
3467 if (latestPingedTime >= completedTime) {
3468 root.latestPingedTime = NoWork;
3469 }
3470}
3471
3472function findEarliestOutstandingPriorityLevel(root, renderExpirationTime) {
3473 var earliestExpirationTime = renderExpirationTime;
3474
3475 var earliestPendingTime = root.earliestPendingTime;
3476 var earliestSuspendedTime = root.earliestSuspendedTime;
3477 if (earliestPendingTime > earliestExpirationTime) {
3478 earliestExpirationTime = earliestPendingTime;
3479 }
3480 if (earliestSuspendedTime > earliestExpirationTime) {
3481 earliestExpirationTime = earliestSuspendedTime;
3482 }
3483 return earliestExpirationTime;
3484}
3485
3486function didExpireAtExpirationTime(root, currentTime) {
3487 var expirationTime = root.expirationTime;
3488 if (expirationTime !== NoWork && currentTime <= expirationTime) {
3489 // The root has expired. Flush all work up to the current time.
3490 root.nextExpirationTimeToWorkOn = currentTime;
3491 }
3492}
3493
3494function findNextExpirationTimeToWorkOn(completedExpirationTime, root) {
3495 var earliestSuspendedTime = root.earliestSuspendedTime;
3496 var latestSuspendedTime = root.latestSuspendedTime;
3497 var earliestPendingTime = root.earliestPendingTime;
3498 var latestPingedTime = root.latestPingedTime;
3499
3500 // Work on the earliest pending time. Failing that, work on the latest
3501 // pinged time.
3502 var nextExpirationTimeToWorkOn = earliestPendingTime !== NoWork ? earliestPendingTime : latestPingedTime;
3503
3504 // If there is no pending or pinged work, check if there's suspended work
3505 // that's lower priority than what we just completed.
3506 if (nextExpirationTimeToWorkOn === NoWork && (completedExpirationTime === NoWork || latestSuspendedTime < completedExpirationTime)) {
3507 // The lowest priority suspended work is the work most likely to be
3508 // committed next. Let's start rendering it again, so that if it times out,
3509 // it's ready to commit.
3510 nextExpirationTimeToWorkOn = latestSuspendedTime;
3511 }
3512
3513 var expirationTime = nextExpirationTimeToWorkOn;
3514 if (expirationTime !== NoWork && earliestSuspendedTime > expirationTime) {
3515 // Expire using the earliest known expiration time.
3516 expirationTime = earliestSuspendedTime;
3517 }
3518
3519 root.nextExpirationTimeToWorkOn = nextExpirationTimeToWorkOn;
3520 root.expirationTime = expirationTime;
3521}
3522
3523/**
3524 * Similar to invariant but only logs a warning if the condition is not met.
3525 * This can be used to log issues in development environments in critical
3526 * paths. Removing the logging code for production environments will keep the
3527 * same logic and follow the same code paths.
3528 */
3529
3530var warning = warningWithoutStack$1;
3531
3532{
3533 warning = function (condition, format) {
3534 if (condition) {
3535 return;
3536 }
3537 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
3538 var stack = ReactDebugCurrentFrame.getStackAddendum();
3539 // eslint-disable-next-line react-internal/warning-and-invariant-args
3540
3541 for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
3542 args[_key - 2] = arguments[_key];
3543 }
3544
3545 warningWithoutStack$1.apply(undefined, [false, format + '%s'].concat(args, [stack]));
3546 };
3547}
3548
3549var warning$1 = warning;
3550
3551/**
3552 * inlined Object.is polyfill to avoid requiring consumers ship their own
3553 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
3554 */
3555function is(x, y) {
3556 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
3557 ;
3558}
3559
3560var hasOwnProperty = Object.prototype.hasOwnProperty;
3561
3562/**
3563 * Performs equality by iterating through keys on an object and returning false
3564 * when any key has values which are not strictly equal between the arguments.
3565 * Returns true when the values of all keys are strictly equal.
3566 */
3567function shallowEqual(objA, objB) {
3568 if (is(objA, objB)) {
3569 return true;
3570 }
3571
3572 if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
3573 return false;
3574 }
3575
3576 var keysA = Object.keys(objA);
3577 var keysB = Object.keys(objB);
3578
3579 if (keysA.length !== keysB.length) {
3580 return false;
3581 }
3582
3583 // Test for A's keys different from B.
3584 for (var i = 0; i < keysA.length; i++) {
3585 if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
3586 return false;
3587 }
3588 }
3589
3590 return true;
3591}
3592
3593function resolveDefaultProps(Component, baseProps) {
3594 if (Component && Component.defaultProps) {
3595 // Resolve default props. Taken from ReactElement
3596 var props = _assign({}, baseProps);
3597 var defaultProps = Component.defaultProps;
3598 for (var propName in defaultProps) {
3599 if (props[propName] === undefined) {
3600 props[propName] = defaultProps[propName];
3601 }
3602 }
3603 return props;
3604 }
3605 return baseProps;
3606}
3607
3608function readLazyComponentType(lazyComponent) {
3609 var status = lazyComponent._status;
3610 var result = lazyComponent._result;
3611 switch (status) {
3612 case Resolved:
3613 {
3614 var Component = result;
3615 return Component;
3616 }
3617 case Rejected:
3618 {
3619 var error = result;
3620 throw error;
3621 }
3622 case Pending:
3623 {
3624 var thenable = result;
3625 throw thenable;
3626 }
3627 default:
3628 {
3629 lazyComponent._status = Pending;
3630 var ctor = lazyComponent._ctor;
3631 var _thenable = ctor();
3632 _thenable.then(function (moduleObject) {
3633 if (lazyComponent._status === Pending) {
3634 var defaultExport = moduleObject.default;
3635 {
3636 if (defaultExport === undefined) {
3637 warning$1(false, 'lazy: Expected the result of a dynamic import() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + "const MyComponent = lazy(() => import('./MyComponent'))", moduleObject);
3638 }
3639 }
3640 lazyComponent._status = Resolved;
3641 lazyComponent._result = defaultExport;
3642 }
3643 }, function (error) {
3644 if (lazyComponent._status === Pending) {
3645 lazyComponent._status = Rejected;
3646 lazyComponent._result = error;
3647 }
3648 });
3649 // Handle synchronous thenables.
3650 switch (lazyComponent._status) {
3651 case Resolved:
3652 return lazyComponent._result;
3653 case Rejected:
3654 throw lazyComponent._result;
3655 }
3656 lazyComponent._result = _thenable;
3657 throw _thenable;
3658 }
3659 }
3660}
3661
3662var fakeInternalInstance = {};
3663var isArray$1 = Array.isArray;
3664
3665// React.Component uses a shared frozen object by default.
3666// We'll use it to determine whether we need to initialize legacy refs.
3667var emptyRefsObject = new React.Component().refs;
3668
3669var didWarnAboutStateAssignmentForComponent = void 0;
3670var didWarnAboutUninitializedState = void 0;
3671var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = void 0;
3672var didWarnAboutLegacyLifecyclesAndDerivedState = void 0;
3673var didWarnAboutUndefinedDerivedState = void 0;
3674var warnOnUndefinedDerivedState = void 0;
3675var warnOnInvalidCallback = void 0;
3676var didWarnAboutDirectlyAssigningPropsToState = void 0;
3677var didWarnAboutContextTypeAndContextTypes = void 0;
3678var didWarnAboutInvalidateContextType = void 0;
3679
3680{
3681 didWarnAboutStateAssignmentForComponent = new Set();
3682 didWarnAboutUninitializedState = new Set();
3683 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
3684 didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
3685 didWarnAboutDirectlyAssigningPropsToState = new Set();
3686 didWarnAboutUndefinedDerivedState = new Set();
3687 didWarnAboutContextTypeAndContextTypes = new Set();
3688 didWarnAboutInvalidateContextType = new Set();
3689
3690 var didWarnOnInvalidCallback = new Set();
3691
3692 warnOnInvalidCallback = function (callback, callerName) {
3693 if (callback === null || typeof callback === 'function') {
3694 return;
3695 }
3696 var key = callerName + '_' + callback;
3697 if (!didWarnOnInvalidCallback.has(key)) {
3698 didWarnOnInvalidCallback.add(key);
3699 warningWithoutStack$1(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
3700 }
3701 };
3702
3703 warnOnUndefinedDerivedState = function (type, partialState) {
3704 if (partialState === undefined) {
3705 var componentName = getComponentName(type) || 'Component';
3706 if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
3707 didWarnAboutUndefinedDerivedState.add(componentName);
3708 warningWithoutStack$1(false, '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
3709 }
3710 }
3711 };
3712
3713 // This is so gross but it's at least non-critical and can be removed if
3714 // it causes problems. This is meant to give a nicer error message for
3715 // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
3716 // ...)) which otherwise throws a "_processChildContext is not a function"
3717 // exception.
3718 Object.defineProperty(fakeInternalInstance, '_processChildContext', {
3719 enumerable: false,
3720 value: function () {
3721 invariant(false, '_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn\'t supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal).');
3722 }
3723 });
3724 Object.freeze(fakeInternalInstance);
3725}
3726
3727function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
3728 var prevState = workInProgress.memoizedState;
3729
3730 {
3731 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
3732 // Invoke the function an extra time to help detect side-effects.
3733 getDerivedStateFromProps(nextProps, prevState);
3734 }
3735 }
3736
3737 var partialState = getDerivedStateFromProps(nextProps, prevState);
3738
3739 {
3740 warnOnUndefinedDerivedState(ctor, partialState);
3741 }
3742 // Merge the partial state and the previous state.
3743 var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
3744 workInProgress.memoizedState = memoizedState;
3745
3746 // Once the update queue is empty, persist the derived state onto the
3747 // base state.
3748 var updateQueue = workInProgress.updateQueue;
3749 if (updateQueue !== null && workInProgress.expirationTime === NoWork) {
3750 updateQueue.baseState = memoizedState;
3751 }
3752}
3753
3754var classComponentUpdater = {
3755 isMounted: isMounted,
3756 enqueueSetState: function (inst, payload, callback) {
3757 var fiber = get(inst);
3758 var currentTime = requestCurrentTime();
3759 var expirationTime = computeExpirationForFiber(currentTime, fiber);
3760
3761 var update = createUpdate(expirationTime);
3762 update.payload = payload;
3763 if (callback !== undefined && callback !== null) {
3764 {
3765 warnOnInvalidCallback(callback, 'setState');
3766 }
3767 update.callback = callback;
3768 }
3769
3770 flushPassiveEffects();
3771 enqueueUpdate(fiber, update);
3772 scheduleWork(fiber, expirationTime);
3773 },
3774 enqueueReplaceState: function (inst, payload, callback) {
3775 var fiber = get(inst);
3776 var currentTime = requestCurrentTime();
3777 var expirationTime = computeExpirationForFiber(currentTime, fiber);
3778
3779 var update = createUpdate(expirationTime);
3780 update.tag = ReplaceState;
3781 update.payload = payload;
3782
3783 if (callback !== undefined && callback !== null) {
3784 {
3785 warnOnInvalidCallback(callback, 'replaceState');
3786 }
3787 update.callback = callback;
3788 }
3789
3790 flushPassiveEffects();
3791 enqueueUpdate(fiber, update);
3792 scheduleWork(fiber, expirationTime);
3793 },
3794 enqueueForceUpdate: function (inst, callback) {
3795 var fiber = get(inst);
3796 var currentTime = requestCurrentTime();
3797 var expirationTime = computeExpirationForFiber(currentTime, fiber);
3798
3799 var update = createUpdate(expirationTime);
3800 update.tag = ForceUpdate;
3801
3802 if (callback !== undefined && callback !== null) {
3803 {
3804 warnOnInvalidCallback(callback, 'forceUpdate');
3805 }
3806 update.callback = callback;
3807 }
3808
3809 flushPassiveEffects();
3810 enqueueUpdate(fiber, update);
3811 scheduleWork(fiber, expirationTime);
3812 }
3813};
3814
3815function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
3816 var instance = workInProgress.stateNode;
3817 if (typeof instance.shouldComponentUpdate === 'function') {
3818 startPhaseTimer(workInProgress, 'shouldComponentUpdate');
3819 var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
3820 stopPhaseTimer();
3821
3822 {
3823 !(shouldUpdate !== undefined) ? warningWithoutStack$1(false, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentName(ctor) || 'Component') : void 0;
3824 }
3825
3826 return shouldUpdate;
3827 }
3828
3829 if (ctor.prototype && ctor.prototype.isPureReactComponent) {
3830 return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
3831 }
3832
3833 return true;
3834}
3835
3836function checkClassInstance(workInProgress, ctor, newProps) {
3837 var instance = workInProgress.stateNode;
3838 {
3839 var name = getComponentName(ctor) || 'Component';
3840 var renderPresent = instance.render;
3841
3842 if (!renderPresent) {
3843 if (ctor.prototype && typeof ctor.prototype.render === 'function') {
3844 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
3845 } else {
3846 warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
3847 }
3848 }
3849
3850 var noGetInitialStateOnES6 = !instance.getInitialState || instance.getInitialState.isReactClassApproved || instance.state;
3851 !noGetInitialStateOnES6 ? warningWithoutStack$1(false, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name) : void 0;
3852 var noGetDefaultPropsOnES6 = !instance.getDefaultProps || instance.getDefaultProps.isReactClassApproved;
3853 !noGetDefaultPropsOnES6 ? warningWithoutStack$1(false, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name) : void 0;
3854 var noInstancePropTypes = !instance.propTypes;
3855 !noInstancePropTypes ? warningWithoutStack$1(false, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name) : void 0;
3856 var noInstanceContextType = !instance.contextType;
3857 !noInstanceContextType ? warningWithoutStack$1(false, 'contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name) : void 0;
3858 var noInstanceContextTypes = !instance.contextTypes;
3859 !noInstanceContextTypes ? warningWithoutStack$1(false, 'contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name) : void 0;
3860
3861 if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
3862 didWarnAboutContextTypeAndContextTypes.add(ctor);
3863 warningWithoutStack$1(false, '%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
3864 }
3865
3866 var noComponentShouldUpdate = typeof instance.componentShouldUpdate !== 'function';
3867 !noComponentShouldUpdate ? warningWithoutStack$1(false, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name) : void 0;
3868 if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
3869 warningWithoutStack$1(false, '%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentName(ctor) || 'A pure component');
3870 }
3871 var noComponentDidUnmount = typeof instance.componentDidUnmount !== 'function';
3872 !noComponentDidUnmount ? warningWithoutStack$1(false, '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name) : void 0;
3873 var noComponentDidReceiveProps = typeof instance.componentDidReceiveProps !== 'function';
3874 !noComponentDidReceiveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name) : void 0;
3875 var noComponentWillRecieveProps = typeof instance.componentWillRecieveProps !== 'function';
3876 !noComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name) : void 0;
3877 var noUnsafeComponentWillRecieveProps = typeof instance.UNSAFE_componentWillRecieveProps !== 'function';
3878 !noUnsafeComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name) : void 0;
3879 var hasMutatedProps = instance.props !== newProps;
3880 !(instance.props === undefined || !hasMutatedProps) ? warningWithoutStack$1(false, '%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name) : void 0;
3881 var noInstanceDefaultProps = !instance.defaultProps;
3882 !noInstanceDefaultProps ? warningWithoutStack$1(false, 'Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name) : void 0;
3883
3884 if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
3885 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
3886 warningWithoutStack$1(false, '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor));
3887 }
3888
3889 var noInstanceGetDerivedStateFromProps = typeof instance.getDerivedStateFromProps !== 'function';
3890 !noInstanceGetDerivedStateFromProps ? warningWithoutStack$1(false, '%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name) : void 0;
3891 var noInstanceGetDerivedStateFromCatch = typeof instance.getDerivedStateFromError !== 'function';
3892 !noInstanceGetDerivedStateFromCatch ? warningWithoutStack$1(false, '%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name) : void 0;
3893 var noStaticGetSnapshotBeforeUpdate = typeof ctor.getSnapshotBeforeUpdate !== 'function';
3894 !noStaticGetSnapshotBeforeUpdate ? warningWithoutStack$1(false, '%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name) : void 0;
3895 var _state = instance.state;
3896 if (_state && (typeof _state !== 'object' || isArray$1(_state))) {
3897 warningWithoutStack$1(false, '%s.state: must be set to an object or null', name);
3898 }
3899 if (typeof instance.getChildContext === 'function') {
3900 !(typeof ctor.childContextTypes === 'object') ? warningWithoutStack$1(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name) : void 0;
3901 }
3902 }
3903}
3904
3905function adoptClassInstance(workInProgress, instance) {
3906 instance.updater = classComponentUpdater;
3907 workInProgress.stateNode = instance;
3908 // The instance needs access to the fiber so that it can schedule updates
3909 set(instance, workInProgress);
3910 {
3911 instance._reactInternalInstance = fakeInternalInstance;
3912 }
3913}
3914
3915function constructClassInstance(workInProgress, ctor, props, renderExpirationTime) {
3916 var isLegacyContextConsumer = false;
3917 var unmaskedContext = emptyContextObject;
3918 var context = null;
3919 var contextType = ctor.contextType;
3920 if (typeof contextType === 'object' && contextType !== null) {
3921 {
3922 if (contextType.$$typeof !== REACT_CONTEXT_TYPE && !didWarnAboutInvalidateContextType.has(ctor)) {
3923 didWarnAboutInvalidateContextType.add(ctor);
3924 warningWithoutStack$1(false, '%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext(). ' + 'Did you accidentally pass the Context.Provider instead?', getComponentName(ctor) || 'Component');
3925 }
3926 }
3927
3928 context = readContext(contextType);
3929 } else {
3930 unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
3931 var contextTypes = ctor.contextTypes;
3932 isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
3933 context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
3934 }
3935
3936 // Instantiate twice to help detect side-effects.
3937 {
3938 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
3939 new ctor(props, context); // eslint-disable-line no-new
3940 }
3941 }
3942
3943 var instance = new ctor(props, context);
3944 var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
3945 adoptClassInstance(workInProgress, instance);
3946
3947 {
3948 if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
3949 var componentName = getComponentName(ctor) || 'Component';
3950 if (!didWarnAboutUninitializedState.has(componentName)) {
3951 didWarnAboutUninitializedState.add(componentName);
3952 warningWithoutStack$1(false, '`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);
3953 }
3954 }
3955
3956 // If new component APIs are defined, "unsafe" lifecycles won't be called.
3957 // Warn about these lifecycles if they are present.
3958 // Don't warn about react-lifecycles-compat polyfilled methods though.
3959 if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
3960 var foundWillMountName = null;
3961 var foundWillReceivePropsName = null;
3962 var foundWillUpdateName = null;
3963 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
3964 foundWillMountName = 'componentWillMount';
3965 } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
3966 foundWillMountName = 'UNSAFE_componentWillMount';
3967 }
3968 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
3969 foundWillReceivePropsName = 'componentWillReceiveProps';
3970 } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
3971 foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
3972 }
3973 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
3974 foundWillUpdateName = 'componentWillUpdate';
3975 } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
3976 foundWillUpdateName = 'UNSAFE_componentWillUpdate';
3977 }
3978 if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
3979 var _componentName = getComponentName(ctor) || 'Component';
3980 var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
3981 if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
3982 didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
3983 warningWithoutStack$1(false, 'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://fb.me/react-async-component-lifecycle-hooks', _componentName, newApiName, foundWillMountName !== null ? '\n ' + foundWillMountName : '', foundWillReceivePropsName !== null ? '\n ' + foundWillReceivePropsName : '', foundWillUpdateName !== null ? '\n ' + foundWillUpdateName : '');
3984 }
3985 }
3986 }
3987 }
3988
3989 // Cache unmasked context so we can avoid recreating masked context unless necessary.
3990 // ReactFiberContext usually updates this cache but can't for newly-created instances.
3991 if (isLegacyContextConsumer) {
3992 cacheContext(workInProgress, unmaskedContext, context);
3993 }
3994
3995 return instance;
3996}
3997
3998function callComponentWillMount(workInProgress, instance) {
3999 startPhaseTimer(workInProgress, 'componentWillMount');
4000 var oldState = instance.state;
4001
4002 if (typeof instance.componentWillMount === 'function') {
4003 instance.componentWillMount();
4004 }
4005 if (typeof instance.UNSAFE_componentWillMount === 'function') {
4006 instance.UNSAFE_componentWillMount();
4007 }
4008
4009 stopPhaseTimer();
4010
4011 if (oldState !== instance.state) {
4012 {
4013 warningWithoutStack$1(false, '%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentName(workInProgress.type) || 'Component');
4014 }
4015 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
4016 }
4017}
4018
4019function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
4020 var oldState = instance.state;
4021 startPhaseTimer(workInProgress, 'componentWillReceiveProps');
4022 if (typeof instance.componentWillReceiveProps === 'function') {
4023 instance.componentWillReceiveProps(newProps, nextContext);
4024 }
4025 if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
4026 instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
4027 }
4028 stopPhaseTimer();
4029
4030 if (instance.state !== oldState) {
4031 {
4032 var componentName = getComponentName(workInProgress.type) || 'Component';
4033 if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
4034 didWarnAboutStateAssignmentForComponent.add(componentName);
4035 warningWithoutStack$1(false, '%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
4036 }
4037 }
4038 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
4039 }
4040}
4041
4042// Invokes the mount life-cycles on a previously never rendered instance.
4043function mountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
4044 {
4045 checkClassInstance(workInProgress, ctor, newProps);
4046 }
4047
4048 var instance = workInProgress.stateNode;
4049 instance.props = newProps;
4050 instance.state = workInProgress.memoizedState;
4051 instance.refs = emptyRefsObject;
4052
4053 var contextType = ctor.contextType;
4054 if (typeof contextType === 'object' && contextType !== null) {
4055 instance.context = readContext(contextType);
4056 } else {
4057 var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
4058 instance.context = getMaskedContext(workInProgress, unmaskedContext);
4059 }
4060
4061 {
4062 if (instance.state === newProps) {
4063 var componentName = getComponentName(ctor) || 'Component';
4064 if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
4065 didWarnAboutDirectlyAssigningPropsToState.add(componentName);
4066 warningWithoutStack$1(false, '%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName);
4067 }
4068 }
4069
4070 if (workInProgress.mode & StrictMode) {
4071 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
4072
4073 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
4074 }
4075
4076 if (warnAboutDeprecatedLifecycles) {
4077 ReactStrictModeWarnings.recordDeprecationWarnings(workInProgress, instance);
4078 }
4079 }
4080
4081 var updateQueue = workInProgress.updateQueue;
4082 if (updateQueue !== null) {
4083 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
4084 instance.state = workInProgress.memoizedState;
4085 }
4086
4087 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
4088 if (typeof getDerivedStateFromProps === 'function') {
4089 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
4090 instance.state = workInProgress.memoizedState;
4091 }
4092
4093 // In order to support react-lifecycles-compat polyfilled components,
4094 // Unsafe lifecycles should not be invoked for components using the new APIs.
4095 if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
4096 callComponentWillMount(workInProgress, instance);
4097 // If we had additional state updates during this life-cycle, let's
4098 // process them now.
4099 updateQueue = workInProgress.updateQueue;
4100 if (updateQueue !== null) {
4101 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
4102 instance.state = workInProgress.memoizedState;
4103 }
4104 }
4105
4106 if (typeof instance.componentDidMount === 'function') {
4107 workInProgress.effectTag |= Update;
4108 }
4109}
4110
4111function resumeMountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
4112 var instance = workInProgress.stateNode;
4113
4114 var oldProps = workInProgress.memoizedProps;
4115 instance.props = oldProps;
4116
4117 var oldContext = instance.context;
4118 var contextType = ctor.contextType;
4119 var nextContext = void 0;
4120 if (typeof contextType === 'object' && contextType !== null) {
4121 nextContext = readContext(contextType);
4122 } else {
4123 var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
4124 nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
4125 }
4126
4127 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
4128 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';
4129
4130 // Note: During these life-cycles, instance.props/instance.state are what
4131 // ever the previously attempted to render - not the "current". However,
4132 // during componentDidUpdate we pass the "current" props.
4133
4134 // In order to support react-lifecycles-compat polyfilled components,
4135 // Unsafe lifecycles should not be invoked for components using the new APIs.
4136 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
4137 if (oldProps !== newProps || oldContext !== nextContext) {
4138 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
4139 }
4140 }
4141
4142 resetHasForceUpdateBeforeProcessing();
4143
4144 var oldState = workInProgress.memoizedState;
4145 var newState = instance.state = oldState;
4146 var updateQueue = workInProgress.updateQueue;
4147 if (updateQueue !== null) {
4148 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
4149 newState = workInProgress.memoizedState;
4150 }
4151 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
4152 // If an update was already in progress, we should schedule an Update
4153 // effect even though we're bailing out, so that cWU/cDU are called.
4154 if (typeof instance.componentDidMount === 'function') {
4155 workInProgress.effectTag |= Update;
4156 }
4157 return false;
4158 }
4159
4160 if (typeof getDerivedStateFromProps === 'function') {
4161 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
4162 newState = workInProgress.memoizedState;
4163 }
4164
4165 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
4166
4167 if (shouldUpdate) {
4168 // In order to support react-lifecycles-compat polyfilled components,
4169 // Unsafe lifecycles should not be invoked for components using the new APIs.
4170 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
4171 startPhaseTimer(workInProgress, 'componentWillMount');
4172 if (typeof instance.componentWillMount === 'function') {
4173 instance.componentWillMount();
4174 }
4175 if (typeof instance.UNSAFE_componentWillMount === 'function') {
4176 instance.UNSAFE_componentWillMount();
4177 }
4178 stopPhaseTimer();
4179 }
4180 if (typeof instance.componentDidMount === 'function') {
4181 workInProgress.effectTag |= Update;
4182 }
4183 } else {
4184 // If an update was already in progress, we should schedule an Update
4185 // effect even though we're bailing out, so that cWU/cDU are called.
4186 if (typeof instance.componentDidMount === 'function') {
4187 workInProgress.effectTag |= Update;
4188 }
4189
4190 // If shouldComponentUpdate returned false, we should still update the
4191 // memoized state to indicate that this work can be reused.
4192 workInProgress.memoizedProps = newProps;
4193 workInProgress.memoizedState = newState;
4194 }
4195
4196 // Update the existing instance's state, props, and context pointers even
4197 // if shouldComponentUpdate returns false.
4198 instance.props = newProps;
4199 instance.state = newState;
4200 instance.context = nextContext;
4201
4202 return shouldUpdate;
4203}
4204
4205// Invokes the update life-cycles and returns false if it shouldn't rerender.
4206function updateClassInstance(current, workInProgress, ctor, newProps, renderExpirationTime) {
4207 var instance = workInProgress.stateNode;
4208
4209 var oldProps = workInProgress.memoizedProps;
4210 instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps);
4211
4212 var oldContext = instance.context;
4213 var contextType = ctor.contextType;
4214 var nextContext = void 0;
4215 if (typeof contextType === 'object' && contextType !== null) {
4216 nextContext = readContext(contextType);
4217 } else {
4218 var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
4219 nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
4220 }
4221
4222 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
4223 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function';
4224
4225 // Note: During these life-cycles, instance.props/instance.state are what
4226 // ever the previously attempted to render - not the "current". However,
4227 // during componentDidUpdate we pass the "current" props.
4228
4229 // In order to support react-lifecycles-compat polyfilled components,
4230 // Unsafe lifecycles should not be invoked for components using the new APIs.
4231 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
4232 if (oldProps !== newProps || oldContext !== nextContext) {
4233 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
4234 }
4235 }
4236
4237 resetHasForceUpdateBeforeProcessing();
4238
4239 var oldState = workInProgress.memoizedState;
4240 var newState = instance.state = oldState;
4241 var updateQueue = workInProgress.updateQueue;
4242 if (updateQueue !== null) {
4243 processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime);
4244 newState = workInProgress.memoizedState;
4245 }
4246
4247 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
4248 // If an update was already in progress, we should schedule an Update
4249 // effect even though we're bailing out, so that cWU/cDU are called.
4250 if (typeof instance.componentDidUpdate === 'function') {
4251 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
4252 workInProgress.effectTag |= Update;
4253 }
4254 }
4255 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
4256 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
4257 workInProgress.effectTag |= Snapshot;
4258 }
4259 }
4260 return false;
4261 }
4262
4263 if (typeof getDerivedStateFromProps === 'function') {
4264 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
4265 newState = workInProgress.memoizedState;
4266 }
4267
4268 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
4269
4270 if (shouldUpdate) {
4271 // In order to support react-lifecycles-compat polyfilled components,
4272 // Unsafe lifecycles should not be invoked for components using the new APIs.
4273 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
4274 startPhaseTimer(workInProgress, 'componentWillUpdate');
4275 if (typeof instance.componentWillUpdate === 'function') {
4276 instance.componentWillUpdate(newProps, newState, nextContext);
4277 }
4278 if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
4279 instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
4280 }
4281 stopPhaseTimer();
4282 }
4283 if (typeof instance.componentDidUpdate === 'function') {
4284 workInProgress.effectTag |= Update;
4285 }
4286 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
4287 workInProgress.effectTag |= Snapshot;
4288 }
4289 } else {
4290 // If an update was already in progress, we should schedule an Update
4291 // effect even though we're bailing out, so that cWU/cDU are called.
4292 if (typeof instance.componentDidUpdate === 'function') {
4293 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
4294 workInProgress.effectTag |= Update;
4295 }
4296 }
4297 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
4298 if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
4299 workInProgress.effectTag |= Snapshot;
4300 }
4301 }
4302
4303 // If shouldComponentUpdate returned false, we should still update the
4304 // memoized props/state to indicate that this work can be reused.
4305 workInProgress.memoizedProps = newProps;
4306 workInProgress.memoizedState = newState;
4307 }
4308
4309 // Update the existing instance's state, props, and context pointers even
4310 // if shouldComponentUpdate returns false.
4311 instance.props = newProps;
4312 instance.state = newState;
4313 instance.context = nextContext;
4314
4315 return shouldUpdate;
4316}
4317
4318var didWarnAboutMaps = void 0;
4319var didWarnAboutGenerators = void 0;
4320var didWarnAboutStringRefInStrictMode = void 0;
4321var ownerHasKeyUseWarning = void 0;
4322var ownerHasFunctionTypeWarning = void 0;
4323var warnForMissingKey = function (child) {};
4324
4325{
4326 didWarnAboutMaps = false;
4327 didWarnAboutGenerators = false;
4328 didWarnAboutStringRefInStrictMode = {};
4329
4330 /**
4331 * Warn if there's no key explicitly set on dynamic arrays of children or
4332 * object keys are not valid. This allows us to keep track of children between
4333 * updates.
4334 */
4335 ownerHasKeyUseWarning = {};
4336 ownerHasFunctionTypeWarning = {};
4337
4338 warnForMissingKey = function (child) {
4339 if (child === null || typeof child !== 'object') {
4340 return;
4341 }
4342 if (!child._store || child._store.validated || child.key != null) {
4343 return;
4344 }
4345 !(typeof child._store === 'object') ? invariant(false, 'React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue.') : void 0;
4346 child._store.validated = true;
4347
4348 var currentComponentErrorInfo = 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + getCurrentFiberStackInDev();
4349 if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
4350 return;
4351 }
4352 ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
4353
4354 warning$1(false, 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.');
4355 };
4356}
4357
4358var isArray = Array.isArray;
4359
4360function coerceRef(returnFiber, current, element) {
4361 var mixedRef = element.ref;
4362 if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
4363 {
4364 if (returnFiber.mode & StrictMode) {
4365 var componentName = getComponentName(returnFiber.type) || 'Component';
4366 if (!didWarnAboutStringRefInStrictMode[componentName]) {
4367 warningWithoutStack$1(false, 'A string ref, "%s", has been found within a strict mode tree. ' + 'String refs are a source of potential bugs and should be avoided. ' + 'We recommend using createRef() instead.' + '\n%s' + '\n\nLearn more about using refs safely here:' + '\nhttps://fb.me/react-strict-mode-string-ref', mixedRef, getStackByFiberInDevAndProd(returnFiber));
4368 didWarnAboutStringRefInStrictMode[componentName] = true;
4369 }
4370 }
4371 }
4372
4373 if (element._owner) {
4374 var owner = element._owner;
4375 var inst = void 0;
4376 if (owner) {
4377 var ownerFiber = owner;
4378 !(ownerFiber.tag === ClassComponent) ? invariant(false, 'Function components cannot have refs. Did you mean to use React.forwardRef()?') : void 0;
4379 inst = ownerFiber.stateNode;
4380 }
4381 !inst ? invariant(false, 'Missing owner for string ref %s. This error is likely caused by a bug in React. Please file an issue.', mixedRef) : void 0;
4382 var stringRef = '' + mixedRef;
4383 // Check if previous string ref matches new string ref
4384 if (current !== null && current.ref !== null && typeof current.ref === 'function' && current.ref._stringRef === stringRef) {
4385 return current.ref;
4386 }
4387 var ref = function (value) {
4388 var refs = inst.refs;
4389 if (refs === emptyRefsObject) {
4390 // This is a lazy pooled frozen object, so we need to initialize.
4391 refs = inst.refs = {};
4392 }
4393 if (value === null) {
4394 delete refs[stringRef];
4395 } else {
4396 refs[stringRef] = value;
4397 }
4398 };
4399 ref._stringRef = stringRef;
4400 return ref;
4401 } else {
4402 !(typeof mixedRef === 'string') ? invariant(false, 'Expected ref to be a function, a string, an object returned by React.createRef(), or null.') : void 0;
4403 !element._owner ? invariant(false, 'Element ref was specified as a string (%s) but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component\'s render method\n3. You have multiple copies of React loaded\nSee https://fb.me/react-refs-must-have-owner for more information.', mixedRef) : void 0;
4404 }
4405 }
4406 return mixedRef;
4407}
4408
4409function throwOnInvalidObjectType(returnFiber, newChild) {
4410 if (returnFiber.type !== 'textarea') {
4411 var addendum = '';
4412 {
4413 addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + getCurrentFiberStackInDev();
4414 }
4415 invariant(false, 'Objects are not valid as a React child (found: %s).%s', Object.prototype.toString.call(newChild) === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : newChild, addendum);
4416 }
4417}
4418
4419function warnOnFunctionType() {
4420 var currentComponentErrorInfo = 'Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.' + getCurrentFiberStackInDev();
4421
4422 if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) {
4423 return;
4424 }
4425 ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true;
4426
4427 warning$1(false, 'Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.');
4428}
4429
4430// This wrapper function exists because I expect to clone the code in each path
4431// to be able to optimize each path individually by branching early. This needs
4432// a compiler or we can do it manually. Helpers that don't need this branching
4433// live outside of this function.
4434function ChildReconciler(shouldTrackSideEffects) {
4435 function deleteChild(returnFiber, childToDelete) {
4436 if (!shouldTrackSideEffects) {
4437 // Noop.
4438 return;
4439 }
4440 // Deletions are added in reversed order so we add it to the front.
4441 // At this point, the return fiber's effect list is empty except for
4442 // deletions, so we can just append the deletion to the list. The remaining
4443 // effects aren't added until the complete phase. Once we implement
4444 // resuming, this may not be true.
4445 var last = returnFiber.lastEffect;
4446 if (last !== null) {
4447 last.nextEffect = childToDelete;
4448 returnFiber.lastEffect = childToDelete;
4449 } else {
4450 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
4451 }
4452 childToDelete.nextEffect = null;
4453 childToDelete.effectTag = Deletion;
4454 }
4455
4456 function deleteRemainingChildren(returnFiber, currentFirstChild) {
4457 if (!shouldTrackSideEffects) {
4458 // Noop.
4459 return null;
4460 }
4461
4462 // TODO: For the shouldClone case, this could be micro-optimized a bit by
4463 // assuming that after the first child we've already added everything.
4464 var childToDelete = currentFirstChild;
4465 while (childToDelete !== null) {
4466 deleteChild(returnFiber, childToDelete);
4467 childToDelete = childToDelete.sibling;
4468 }
4469 return null;
4470 }
4471
4472 function mapRemainingChildren(returnFiber, currentFirstChild) {
4473 // Add the remaining children to a temporary map so that we can find them by
4474 // keys quickly. Implicit (null) keys get added to this set with their index
4475 var existingChildren = new Map();
4476
4477 var existingChild = currentFirstChild;
4478 while (existingChild !== null) {
4479 if (existingChild.key !== null) {
4480 existingChildren.set(existingChild.key, existingChild);
4481 } else {
4482 existingChildren.set(existingChild.index, existingChild);
4483 }
4484 existingChild = existingChild.sibling;
4485 }
4486 return existingChildren;
4487 }
4488
4489 function useFiber(fiber, pendingProps, expirationTime) {
4490 // We currently set sibling to null and index to 0 here because it is easy
4491 // to forget to do before returning it. E.g. for the single child case.
4492 var clone = createWorkInProgress(fiber, pendingProps, expirationTime);
4493 clone.index = 0;
4494 clone.sibling = null;
4495 return clone;
4496 }
4497
4498 function placeChild(newFiber, lastPlacedIndex, newIndex) {
4499 newFiber.index = newIndex;
4500 if (!shouldTrackSideEffects) {
4501 // Noop.
4502 return lastPlacedIndex;
4503 }
4504 var current = newFiber.alternate;
4505 if (current !== null) {
4506 var oldIndex = current.index;
4507 if (oldIndex < lastPlacedIndex) {
4508 // This is a move.
4509 newFiber.effectTag = Placement;
4510 return lastPlacedIndex;
4511 } else {
4512 // This item can stay in place.
4513 return oldIndex;
4514 }
4515 } else {
4516 // This is an insertion.
4517 newFiber.effectTag = Placement;
4518 return lastPlacedIndex;
4519 }
4520 }
4521
4522 function placeSingleChild(newFiber) {
4523 // This is simpler for the single child case. We only need to do a
4524 // placement for inserting new children.
4525 if (shouldTrackSideEffects && newFiber.alternate === null) {
4526 newFiber.effectTag = Placement;
4527 }
4528 return newFiber;
4529 }
4530
4531 function updateTextNode(returnFiber, current, textContent, expirationTime) {
4532 if (current === null || current.tag !== HostText) {
4533 // Insert
4534 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
4535 created.return = returnFiber;
4536 return created;
4537 } else {
4538 // Update
4539 var existing = useFiber(current, textContent, expirationTime);
4540 existing.return = returnFiber;
4541 return existing;
4542 }
4543 }
4544
4545 function updateElement(returnFiber, current, element, expirationTime) {
4546 if (current !== null && current.elementType === element.type) {
4547 // Move based on index
4548 var existing = useFiber(current, element.props, expirationTime);
4549 existing.ref = coerceRef(returnFiber, current, element);
4550 existing.return = returnFiber;
4551 {
4552 existing._debugSource = element._source;
4553 existing._debugOwner = element._owner;
4554 }
4555 return existing;
4556 } else {
4557 // Insert
4558 var created = createFiberFromElement(element, returnFiber.mode, expirationTime);
4559 created.ref = coerceRef(returnFiber, current, element);
4560 created.return = returnFiber;
4561 return created;
4562 }
4563 }
4564
4565 function updatePortal(returnFiber, current, portal, expirationTime) {
4566 if (current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) {
4567 // Insert
4568 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
4569 created.return = returnFiber;
4570 return created;
4571 } else {
4572 // Update
4573 var existing = useFiber(current, portal.children || [], expirationTime);
4574 existing.return = returnFiber;
4575 return existing;
4576 }
4577 }
4578
4579 function updateFragment(returnFiber, current, fragment, expirationTime, key) {
4580 if (current === null || current.tag !== Fragment) {
4581 // Insert
4582 var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key);
4583 created.return = returnFiber;
4584 return created;
4585 } else {
4586 // Update
4587 var existing = useFiber(current, fragment, expirationTime);
4588 existing.return = returnFiber;
4589 return existing;
4590 }
4591 }
4592
4593 function createChild(returnFiber, newChild, expirationTime) {
4594 if (typeof newChild === 'string' || typeof newChild === 'number') {
4595 // Text nodes don't have keys. If the previous node is implicitly keyed
4596 // we can continue to replace it without aborting even if it is not a text
4597 // node.
4598 var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime);
4599 created.return = returnFiber;
4600 return created;
4601 }
4602
4603 if (typeof newChild === 'object' && newChild !== null) {
4604 switch (newChild.$$typeof) {
4605 case REACT_ELEMENT_TYPE:
4606 {
4607 var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime);
4608 _created.ref = coerceRef(returnFiber, null, newChild);
4609 _created.return = returnFiber;
4610 return _created;
4611 }
4612 case REACT_PORTAL_TYPE:
4613 {
4614 var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime);
4615 _created2.return = returnFiber;
4616 return _created2;
4617 }
4618 }
4619
4620 if (isArray(newChild) || getIteratorFn(newChild)) {
4621 var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null);
4622 _created3.return = returnFiber;
4623 return _created3;
4624 }
4625
4626 throwOnInvalidObjectType(returnFiber, newChild);
4627 }
4628
4629 {
4630 if (typeof newChild === 'function') {
4631 warnOnFunctionType();
4632 }
4633 }
4634
4635 return null;
4636 }
4637
4638 function updateSlot(returnFiber, oldFiber, newChild, expirationTime) {
4639 // Update the fiber if the keys match, otherwise return null.
4640
4641 var key = oldFiber !== null ? oldFiber.key : null;
4642
4643 if (typeof newChild === 'string' || typeof newChild === 'number') {
4644 // Text nodes don't have keys. If the previous node is implicitly keyed
4645 // we can continue to replace it without aborting even if it is not a text
4646 // node.
4647 if (key !== null) {
4648 return null;
4649 }
4650 return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime);
4651 }
4652
4653 if (typeof newChild === 'object' && newChild !== null) {
4654 switch (newChild.$$typeof) {
4655 case REACT_ELEMENT_TYPE:
4656 {
4657 if (newChild.key === key) {
4658 if (newChild.type === REACT_FRAGMENT_TYPE) {
4659 return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key);
4660 }
4661 return updateElement(returnFiber, oldFiber, newChild, expirationTime);
4662 } else {
4663 return null;
4664 }
4665 }
4666 case REACT_PORTAL_TYPE:
4667 {
4668 if (newChild.key === key) {
4669 return updatePortal(returnFiber, oldFiber, newChild, expirationTime);
4670 } else {
4671 return null;
4672 }
4673 }
4674 }
4675
4676 if (isArray(newChild) || getIteratorFn(newChild)) {
4677 if (key !== null) {
4678 return null;
4679 }
4680
4681 return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null);
4682 }
4683
4684 throwOnInvalidObjectType(returnFiber, newChild);
4685 }
4686
4687 {
4688 if (typeof newChild === 'function') {
4689 warnOnFunctionType();
4690 }
4691 }
4692
4693 return null;
4694 }
4695
4696 function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) {
4697 if (typeof newChild === 'string' || typeof newChild === 'number') {
4698 // Text nodes don't have keys, so we neither have to check the old nor
4699 // new node for the key. If both are text nodes, they match.
4700 var matchedFiber = existingChildren.get(newIdx) || null;
4701 return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime);
4702 }
4703
4704 if (typeof newChild === 'object' && newChild !== null) {
4705 switch (newChild.$$typeof) {
4706 case REACT_ELEMENT_TYPE:
4707 {
4708 var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
4709 if (newChild.type === REACT_FRAGMENT_TYPE) {
4710 return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key);
4711 }
4712 return updateElement(returnFiber, _matchedFiber, newChild, expirationTime);
4713 }
4714 case REACT_PORTAL_TYPE:
4715 {
4716 var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
4717 return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime);
4718 }
4719 }
4720
4721 if (isArray(newChild) || getIteratorFn(newChild)) {
4722 var _matchedFiber3 = existingChildren.get(newIdx) || null;
4723 return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null);
4724 }
4725
4726 throwOnInvalidObjectType(returnFiber, newChild);
4727 }
4728
4729 {
4730 if (typeof newChild === 'function') {
4731 warnOnFunctionType();
4732 }
4733 }
4734
4735 return null;
4736 }
4737
4738 /**
4739 * Warns if there is a duplicate or missing key
4740 */
4741 function warnOnInvalidKey(child, knownKeys) {
4742 {
4743 if (typeof child !== 'object' || child === null) {
4744 return knownKeys;
4745 }
4746 switch (child.$$typeof) {
4747 case REACT_ELEMENT_TYPE:
4748 case REACT_PORTAL_TYPE:
4749 warnForMissingKey(child);
4750 var key = child.key;
4751 if (typeof key !== 'string') {
4752 break;
4753 }
4754 if (knownKeys === null) {
4755 knownKeys = new Set();
4756 knownKeys.add(key);
4757 break;
4758 }
4759 if (!knownKeys.has(key)) {
4760 knownKeys.add(key);
4761 break;
4762 }
4763 warning$1(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key);
4764 break;
4765 default:
4766 break;
4767 }
4768 }
4769 return knownKeys;
4770 }
4771
4772 function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) {
4773 // This algorithm can't optimize by searching from both ends since we
4774 // don't have backpointers on fibers. I'm trying to see how far we can get
4775 // with that model. If it ends up not being worth the tradeoffs, we can
4776 // add it later.
4777
4778 // Even with a two ended optimization, we'd want to optimize for the case
4779 // where there are few changes and brute force the comparison instead of
4780 // going for the Map. It'd like to explore hitting that path first in
4781 // forward-only mode and only go for the Map once we notice that we need
4782 // lots of look ahead. This doesn't handle reversal as well as two ended
4783 // search but that's unusual. Besides, for the two ended optimization to
4784 // work on Iterables, we'd need to copy the whole set.
4785
4786 // In this first iteration, we'll just live with hitting the bad case
4787 // (adding everything to a Map) in for every insert/move.
4788
4789 // If you change this code, also update reconcileChildrenIterator() which
4790 // uses the same algorithm.
4791
4792 {
4793 // First, validate keys.
4794 var knownKeys = null;
4795 for (var i = 0; i < newChildren.length; i++) {
4796 var child = newChildren[i];
4797 knownKeys = warnOnInvalidKey(child, knownKeys);
4798 }
4799 }
4800
4801 var resultingFirstChild = null;
4802 var previousNewFiber = null;
4803
4804 var oldFiber = currentFirstChild;
4805 var lastPlacedIndex = 0;
4806 var newIdx = 0;
4807 var nextOldFiber = null;
4808 for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
4809 if (oldFiber.index > newIdx) {
4810 nextOldFiber = oldFiber;
4811 oldFiber = null;
4812 } else {
4813 nextOldFiber = oldFiber.sibling;
4814 }
4815 var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime);
4816 if (newFiber === null) {
4817 // TODO: This breaks on empty slots like null children. That's
4818 // unfortunate because it triggers the slow path all the time. We need
4819 // a better way to communicate whether this was a miss or null,
4820 // boolean, undefined, etc.
4821 if (oldFiber === null) {
4822 oldFiber = nextOldFiber;
4823 }
4824 break;
4825 }
4826 if (shouldTrackSideEffects) {
4827 if (oldFiber && newFiber.alternate === null) {
4828 // We matched the slot, but we didn't reuse the existing fiber, so we
4829 // need to delete the existing child.
4830 deleteChild(returnFiber, oldFiber);
4831 }
4832 }
4833 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
4834 if (previousNewFiber === null) {
4835 // TODO: Move out of the loop. This only happens for the first run.
4836 resultingFirstChild = newFiber;
4837 } else {
4838 // TODO: Defer siblings if we're not at the right index for this slot.
4839 // I.e. if we had null values before, then we want to defer this
4840 // for each null value. However, we also don't want to call updateSlot
4841 // with the previous one.
4842 previousNewFiber.sibling = newFiber;
4843 }
4844 previousNewFiber = newFiber;
4845 oldFiber = nextOldFiber;
4846 }
4847
4848 if (newIdx === newChildren.length) {
4849 // We've reached the end of the new children. We can delete the rest.
4850 deleteRemainingChildren(returnFiber, oldFiber);
4851 return resultingFirstChild;
4852 }
4853
4854 if (oldFiber === null) {
4855 // If we don't have any more existing children we can choose a fast path
4856 // since the rest will all be insertions.
4857 for (; newIdx < newChildren.length; newIdx++) {
4858 var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime);
4859 if (!_newFiber) {
4860 continue;
4861 }
4862 lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
4863 if (previousNewFiber === null) {
4864 // TODO: Move out of the loop. This only happens for the first run.
4865 resultingFirstChild = _newFiber;
4866 } else {
4867 previousNewFiber.sibling = _newFiber;
4868 }
4869 previousNewFiber = _newFiber;
4870 }
4871 return resultingFirstChild;
4872 }
4873
4874 // Add all children to a key map for quick lookups.
4875 var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
4876
4877 // Keep scanning and use the map to restore deleted items as moves.
4878 for (; newIdx < newChildren.length; newIdx++) {
4879 var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime);
4880 if (_newFiber2) {
4881 if (shouldTrackSideEffects) {
4882 if (_newFiber2.alternate !== null) {
4883 // The new fiber is a work in progress, but if there exists a
4884 // current, that means that we reused the fiber. We need to delete
4885 // it from the child list so that we don't add it to the deletion
4886 // list.
4887 existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
4888 }
4889 }
4890 lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
4891 if (previousNewFiber === null) {
4892 resultingFirstChild = _newFiber2;
4893 } else {
4894 previousNewFiber.sibling = _newFiber2;
4895 }
4896 previousNewFiber = _newFiber2;
4897 }
4898 }
4899
4900 if (shouldTrackSideEffects) {
4901 // Any existing children that weren't consumed above were deleted. We need
4902 // to add them to the deletion list.
4903 existingChildren.forEach(function (child) {
4904 return deleteChild(returnFiber, child);
4905 });
4906 }
4907
4908 return resultingFirstChild;
4909 }
4910
4911 function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) {
4912 // This is the same implementation as reconcileChildrenArray(),
4913 // but using the iterator instead.
4914
4915 var iteratorFn = getIteratorFn(newChildrenIterable);
4916 !(typeof iteratorFn === 'function') ? invariant(false, 'An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.') : void 0;
4917
4918 {
4919 // We don't support rendering Generators because it's a mutation.
4920 // See https://github.com/facebook/react/issues/12995
4921 if (typeof Symbol === 'function' &&
4922 // $FlowFixMe Flow doesn't know about toStringTag
4923 newChildrenIterable[Symbol.toStringTag] === 'Generator') {
4924 !didWarnAboutGenerators ? warning$1(false, 'Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.') : void 0;
4925 didWarnAboutGenerators = true;
4926 }
4927
4928 // Warn about using Maps as children
4929 if (newChildrenIterable.entries === iteratorFn) {
4930 !didWarnAboutMaps ? warning$1(false, 'Using Maps as children is unsupported and will likely yield ' + 'unexpected results. Convert it to a sequence/iterable of keyed ' + 'ReactElements instead.') : void 0;
4931 didWarnAboutMaps = true;
4932 }
4933
4934 // First, validate keys.
4935 // We'll get a different iterator later for the main pass.
4936 var _newChildren = iteratorFn.call(newChildrenIterable);
4937 if (_newChildren) {
4938 var knownKeys = null;
4939 var _step = _newChildren.next();
4940 for (; !_step.done; _step = _newChildren.next()) {
4941 var child = _step.value;
4942 knownKeys = warnOnInvalidKey(child, knownKeys);
4943 }
4944 }
4945 }
4946
4947 var newChildren = iteratorFn.call(newChildrenIterable);
4948 !(newChildren != null) ? invariant(false, 'An iterable object provided no iterator.') : void 0;
4949
4950 var resultingFirstChild = null;
4951 var previousNewFiber = null;
4952
4953 var oldFiber = currentFirstChild;
4954 var lastPlacedIndex = 0;
4955 var newIdx = 0;
4956 var nextOldFiber = null;
4957
4958 var step = newChildren.next();
4959 for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
4960 if (oldFiber.index > newIdx) {
4961 nextOldFiber = oldFiber;
4962 oldFiber = null;
4963 } else {
4964 nextOldFiber = oldFiber.sibling;
4965 }
4966 var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime);
4967 if (newFiber === null) {
4968 // TODO: This breaks on empty slots like null children. That's
4969 // unfortunate because it triggers the slow path all the time. We need
4970 // a better way to communicate whether this was a miss or null,
4971 // boolean, undefined, etc.
4972 if (!oldFiber) {
4973 oldFiber = nextOldFiber;
4974 }
4975 break;
4976 }
4977 if (shouldTrackSideEffects) {
4978 if (oldFiber && newFiber.alternate === null) {
4979 // We matched the slot, but we didn't reuse the existing fiber, so we
4980 // need to delete the existing child.
4981 deleteChild(returnFiber, oldFiber);
4982 }
4983 }
4984 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
4985 if (previousNewFiber === null) {
4986 // TODO: Move out of the loop. This only happens for the first run.
4987 resultingFirstChild = newFiber;
4988 } else {
4989 // TODO: Defer siblings if we're not at the right index for this slot.
4990 // I.e. if we had null values before, then we want to defer this
4991 // for each null value. However, we also don't want to call updateSlot
4992 // with the previous one.
4993 previousNewFiber.sibling = newFiber;
4994 }
4995 previousNewFiber = newFiber;
4996 oldFiber = nextOldFiber;
4997 }
4998
4999 if (step.done) {
5000 // We've reached the end of the new children. We can delete the rest.
5001 deleteRemainingChildren(returnFiber, oldFiber);
5002 return resultingFirstChild;
5003 }
5004
5005 if (oldFiber === null) {
5006 // If we don't have any more existing children we can choose a fast path
5007 // since the rest will all be insertions.
5008 for (; !step.done; newIdx++, step = newChildren.next()) {
5009 var _newFiber3 = createChild(returnFiber, step.value, expirationTime);
5010 if (_newFiber3 === null) {
5011 continue;
5012 }
5013 lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
5014 if (previousNewFiber === null) {
5015 // TODO: Move out of the loop. This only happens for the first run.
5016 resultingFirstChild = _newFiber3;
5017 } else {
5018 previousNewFiber.sibling = _newFiber3;
5019 }
5020 previousNewFiber = _newFiber3;
5021 }
5022 return resultingFirstChild;
5023 }
5024
5025 // Add all children to a key map for quick lookups.
5026 var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
5027
5028 // Keep scanning and use the map to restore deleted items as moves.
5029 for (; !step.done; newIdx++, step = newChildren.next()) {
5030 var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime);
5031 if (_newFiber4 !== null) {
5032 if (shouldTrackSideEffects) {
5033 if (_newFiber4.alternate !== null) {
5034 // The new fiber is a work in progress, but if there exists a
5035 // current, that means that we reused the fiber. We need to delete
5036 // it from the child list so that we don't add it to the deletion
5037 // list.
5038 existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
5039 }
5040 }
5041 lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
5042 if (previousNewFiber === null) {
5043 resultingFirstChild = _newFiber4;
5044 } else {
5045 previousNewFiber.sibling = _newFiber4;
5046 }
5047 previousNewFiber = _newFiber4;
5048 }
5049 }
5050
5051 if (shouldTrackSideEffects) {
5052 // Any existing children that weren't consumed above were deleted. We need
5053 // to add them to the deletion list.
5054 existingChildren.forEach(function (child) {
5055 return deleteChild(returnFiber, child);
5056 });
5057 }
5058
5059 return resultingFirstChild;
5060 }
5061
5062 function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) {
5063 // There's no need to check for keys on text nodes since we don't have a
5064 // way to define them.
5065 if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
5066 // We already have an existing node so let's just update it and delete
5067 // the rest.
5068 deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
5069 var existing = useFiber(currentFirstChild, textContent, expirationTime);
5070 existing.return = returnFiber;
5071 return existing;
5072 }
5073 // The existing first child is not a text node so we need to create one
5074 // and delete the existing ones.
5075 deleteRemainingChildren(returnFiber, currentFirstChild);
5076 var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
5077 created.return = returnFiber;
5078 return created;
5079 }
5080
5081 function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) {
5082 var key = element.key;
5083 var child = currentFirstChild;
5084 while (child !== null) {
5085 // TODO: If key === null and child.key === null, then this only applies to
5086 // the first item in the list.
5087 if (child.key === key) {
5088 if (child.tag === Fragment ? element.type === REACT_FRAGMENT_TYPE : child.elementType === element.type) {
5089 deleteRemainingChildren(returnFiber, child.sibling);
5090 var existing = useFiber(child, element.type === REACT_FRAGMENT_TYPE ? element.props.children : element.props, expirationTime);
5091 existing.ref = coerceRef(returnFiber, child, element);
5092 existing.return = returnFiber;
5093 {
5094 existing._debugSource = element._source;
5095 existing._debugOwner = element._owner;
5096 }
5097 return existing;
5098 } else {
5099 deleteRemainingChildren(returnFiber, child);
5100 break;
5101 }
5102 } else {
5103 deleteChild(returnFiber, child);
5104 }
5105 child = child.sibling;
5106 }
5107
5108 if (element.type === REACT_FRAGMENT_TYPE) {
5109 var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key);
5110 created.return = returnFiber;
5111 return created;
5112 } else {
5113 var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime);
5114 _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
5115 _created4.return = returnFiber;
5116 return _created4;
5117 }
5118 }
5119
5120 function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) {
5121 var key = portal.key;
5122 var child = currentFirstChild;
5123 while (child !== null) {
5124 // TODO: If key === null and child.key === null, then this only applies to
5125 // the first item in the list.
5126 if (child.key === key) {
5127 if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
5128 deleteRemainingChildren(returnFiber, child.sibling);
5129 var existing = useFiber(child, portal.children || [], expirationTime);
5130 existing.return = returnFiber;
5131 return existing;
5132 } else {
5133 deleteRemainingChildren(returnFiber, child);
5134 break;
5135 }
5136 } else {
5137 deleteChild(returnFiber, child);
5138 }
5139 child = child.sibling;
5140 }
5141
5142 var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
5143 created.return = returnFiber;
5144 return created;
5145 }
5146
5147 // This API will tag the children with the side-effect of the reconciliation
5148 // itself. They will be added to the side-effect list as we pass through the
5149 // children and the parent.
5150 function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) {
5151 // This function is not recursive.
5152 // If the top level item is an array, we treat it as a set of children,
5153 // not as a fragment. Nested arrays on the other hand will be treated as
5154 // fragment nodes. Recursion happens at the normal flow.
5155
5156 // Handle top level unkeyed fragments as if they were arrays.
5157 // This leads to an ambiguity between <>{[...]}</> and <>...</>.
5158 // We treat the ambiguous cases above the same.
5159 var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
5160 if (isUnkeyedTopLevelFragment) {
5161 newChild = newChild.props.children;
5162 }
5163
5164 // Handle object types
5165 var isObject = typeof newChild === 'object' && newChild !== null;
5166
5167 if (isObject) {
5168 switch (newChild.$$typeof) {
5169 case REACT_ELEMENT_TYPE:
5170 return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime));
5171 case REACT_PORTAL_TYPE:
5172 return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime));
5173 }
5174 }
5175
5176 if (typeof newChild === 'string' || typeof newChild === 'number') {
5177 return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime));
5178 }
5179
5180 if (isArray(newChild)) {
5181 return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime);
5182 }
5183
5184 if (getIteratorFn(newChild)) {
5185 return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime);
5186 }
5187
5188 if (isObject) {
5189 throwOnInvalidObjectType(returnFiber, newChild);
5190 }
5191
5192 {
5193 if (typeof newChild === 'function') {
5194 warnOnFunctionType();
5195 }
5196 }
5197 if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {
5198 // If the new child is undefined, and the return fiber is a composite
5199 // component, throw an error. If Fiber return types are disabled,
5200 // we already threw above.
5201 switch (returnFiber.tag) {
5202 case ClassComponent:
5203 {
5204 {
5205 var instance = returnFiber.stateNode;
5206 if (instance.render._isMockFunction) {
5207 // We allow auto-mocks to proceed as if they're returning null.
5208 break;
5209 }
5210 }
5211 }
5212 // Intentionally fall through to the next case, which handles both
5213 // functions and classes
5214 // eslint-disable-next-lined no-fallthrough
5215 case FunctionComponent:
5216 {
5217 var Component = returnFiber.type;
5218 invariant(false, '%s(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.', Component.displayName || Component.name || 'Component');
5219 }
5220 }
5221 }
5222
5223 // Remaining cases are all treated as empty.
5224 return deleteRemainingChildren(returnFiber, currentFirstChild);
5225 }
5226
5227 return reconcileChildFibers;
5228}
5229
5230var reconcileChildFibers = ChildReconciler(true);
5231var mountChildFibers = ChildReconciler(false);
5232
5233function cloneChildFibers(current, workInProgress) {
5234 !(current === null || workInProgress.child === current.child) ? invariant(false, 'Resuming work not yet implemented.') : void 0;
5235
5236 if (workInProgress.child === null) {
5237 return;
5238 }
5239
5240 var currentChild = workInProgress.child;
5241 var newChild = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
5242 workInProgress.child = newChild;
5243
5244 newChild.return = workInProgress;
5245 while (currentChild.sibling !== null) {
5246 currentChild = currentChild.sibling;
5247 newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime);
5248 newChild.return = workInProgress;
5249 }
5250 newChild.sibling = null;
5251}
5252
5253var NO_CONTEXT$1 = {};
5254
5255var contextStackCursor$1 = createCursor(NO_CONTEXT$1);
5256var contextFiberStackCursor = createCursor(NO_CONTEXT$1);
5257var rootInstanceStackCursor = createCursor(NO_CONTEXT$1);
5258
5259function requiredContext(c) {
5260 !(c !== NO_CONTEXT$1) ? invariant(false, 'Expected host context to exist. This error is likely caused by a bug in React. Please file an issue.') : void 0;
5261 return c;
5262}
5263
5264function getRootHostContainer() {
5265 var rootInstance = requiredContext(rootInstanceStackCursor.current);
5266 return rootInstance;
5267}
5268
5269function pushHostContainer(fiber, nextRootInstance) {
5270 // Push current root instance onto the stack;
5271 // This allows us to reset root when portals are popped.
5272 push(rootInstanceStackCursor, nextRootInstance, fiber);
5273 // Track the context and the Fiber that provided it.
5274 // This enables us to pop only Fibers that provide unique contexts.
5275 push(contextFiberStackCursor, fiber, fiber);
5276
5277 // Finally, we need to push the host context to the stack.
5278 // However, we can't just call getRootHostContext() and push it because
5279 // we'd have a different number of entries on the stack depending on
5280 // whether getRootHostContext() throws somewhere in renderer code or not.
5281 // So we push an empty value first. This lets us safely unwind on errors.
5282 push(contextStackCursor$1, NO_CONTEXT$1, fiber);
5283 var nextRootContext = getRootHostContext(nextRootInstance);
5284 // Now that we know this function doesn't throw, replace it.
5285 pop(contextStackCursor$1, fiber);
5286 push(contextStackCursor$1, nextRootContext, fiber);
5287}
5288
5289function popHostContainer(fiber) {
5290 pop(contextStackCursor$1, fiber);
5291 pop(contextFiberStackCursor, fiber);
5292 pop(rootInstanceStackCursor, fiber);
5293}
5294
5295function getHostContext() {
5296 var context = requiredContext(contextStackCursor$1.current);
5297 return context;
5298}
5299
5300function pushHostContext(fiber) {
5301 var rootInstance = requiredContext(rootInstanceStackCursor.current);
5302 var context = requiredContext(contextStackCursor$1.current);
5303 var nextContext = getChildHostContext(context, fiber.type, rootInstance);
5304
5305 // Don't push this Fiber's context unless it's unique.
5306 if (context === nextContext) {
5307 return;
5308 }
5309
5310 // Track the context and the Fiber that provided it.
5311 // This enables us to pop only Fibers that provide unique contexts.
5312 push(contextFiberStackCursor, fiber, fiber);
5313 push(contextStackCursor$1, nextContext, fiber);
5314}
5315
5316function popHostContext(fiber) {
5317 // Do not pop unless this Fiber provided the current context.
5318 // pushHostContext() only pushes Fibers that provide unique contexts.
5319 if (contextFiberStackCursor.current !== fiber) {
5320 return;
5321 }
5322
5323 pop(contextStackCursor$1, fiber);
5324 pop(contextFiberStackCursor, fiber);
5325}
5326
5327var NoEffect$1 = /* */0;
5328var UnmountSnapshot = /* */2;
5329var UnmountMutation = /* */4;
5330var MountMutation = /* */8;
5331var UnmountLayout = /* */16;
5332var MountLayout = /* */32;
5333var MountPassive = /* */64;
5334var UnmountPassive = /* */128;
5335
5336var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
5337
5338
5339var didWarnAboutMismatchedHooksForComponent = void 0;
5340{
5341 didWarnAboutMismatchedHooksForComponent = new Set();
5342}
5343
5344// These are set right before calling the component.
5345var renderExpirationTime = NoWork;
5346// The work-in-progress fiber. I've named it differently to distinguish it from
5347// the work-in-progress hook.
5348var currentlyRenderingFiber$1 = null;
5349
5350// Hooks are stored as a linked list on the fiber's memoizedState field. The
5351// current hook list is the list that belongs to the current fiber. The
5352// work-in-progress hook list is a new list that will be added to the
5353// work-in-progress fiber.
5354var currentHook = null;
5355var nextCurrentHook = null;
5356var firstWorkInProgressHook = null;
5357var workInProgressHook = null;
5358var nextWorkInProgressHook = null;
5359
5360var remainingExpirationTime = NoWork;
5361var componentUpdateQueue = null;
5362var sideEffectTag = 0;
5363
5364// Updates scheduled during render will trigger an immediate re-render at the
5365// end of the current pass. We can't store these updates on the normal queue,
5366// because if the work is aborted, they should be discarded. Because this is
5367// a relatively rare case, we also don't want to add an additional field to
5368// either the hook or queue object types. So we store them in a lazily create
5369// map of queue -> render-phase updates, which are discarded once the component
5370// completes without re-rendering.
5371
5372// Whether an update was scheduled during the currently executing render pass.
5373var didScheduleRenderPhaseUpdate = false;
5374// Lazily created map of render-phase updates
5375var renderPhaseUpdates = null;
5376// Counter to prevent infinite loops.
5377var numberOfReRenders = 0;
5378var RE_RENDER_LIMIT = 25;
5379
5380// In DEV, this is the name of the currently executing primitive hook
5381var currentHookNameInDev = null;
5382
5383// In DEV, this list ensures that hooks are called in the same order between renders.
5384// The list stores the order of hooks used during the initial render (mount).
5385// Subsequent renders (updates) reference this list.
5386var hookTypesDev = null;
5387var hookTypesUpdateIndexDev = -1;
5388
5389function mountHookTypesDev() {
5390 {
5391 var hookName = currentHookNameInDev;
5392
5393 if (hookTypesDev === null) {
5394 hookTypesDev = [hookName];
5395 } else {
5396 hookTypesDev.push(hookName);
5397 }
5398 }
5399}
5400
5401function updateHookTypesDev() {
5402 {
5403 var hookName = currentHookNameInDev;
5404
5405 if (hookTypesDev !== null) {
5406 hookTypesUpdateIndexDev++;
5407 if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
5408 warnOnHookMismatchInDev(hookName);
5409 }
5410 }
5411 }
5412}
5413
5414function warnOnHookMismatchInDev(currentHookName) {
5415 {
5416 var componentName = getComponentName(currentlyRenderingFiber$1.type);
5417 if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
5418 didWarnAboutMismatchedHooksForComponent.add(componentName);
5419
5420 if (hookTypesDev !== null) {
5421 var table = '';
5422
5423 var secondColumnStart = 30;
5424
5425 for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {
5426 var oldHookName = hookTypesDev[i];
5427 var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
5428
5429 var row = i + 1 + '. ' + oldHookName;
5430
5431 // Extra space so second column lines up
5432 // lol @ IE not supporting String#repeat
5433 while (row.length < secondColumnStart) {
5434 row += ' ';
5435 }
5436
5437 row += newHookName + '\n';
5438
5439 table += row;
5440 }
5441
5442 warning$1(false, 'React has detected a change in the order of Hooks called by %s. ' + 'This will lead to bugs and errors if not fixed. ' + 'For more information, read the Rules of Hooks: https://fb.me/rules-of-hooks\n\n' + ' Previous render Next render\n' + ' ------------------------------------------------------\n' + '%s' + ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n', componentName, table);
5443 }
5444 }
5445 }
5446}
5447
5448function throwInvalidHookError() {
5449 invariant(false, 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.');
5450}
5451
5452function areHookInputsEqual(nextDeps, prevDeps) {
5453 if (prevDeps === null) {
5454 {
5455 warning$1(false, '%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);
5456 }
5457 return false;
5458 }
5459
5460 {
5461 // Don't bother comparing lengths in prod because these arrays should be
5462 // passed inline.
5463 if (nextDeps.length !== prevDeps.length) {
5464 warning$1(false, 'The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, '[' + nextDeps.join(', ') + ']', '[' + prevDeps.join(', ') + ']');
5465 }
5466 }
5467 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
5468 if (is(nextDeps[i], prevDeps[i])) {
5469 continue;
5470 }
5471 return false;
5472 }
5473 return true;
5474}
5475
5476function renderWithHooks(current, workInProgress, Component, props, refOrContext, nextRenderExpirationTime) {
5477 renderExpirationTime = nextRenderExpirationTime;
5478 currentlyRenderingFiber$1 = workInProgress;
5479 nextCurrentHook = current !== null ? current.memoizedState : null;
5480
5481 {
5482 hookTypesDev = current !== null ? current._debugHookTypes : null;
5483 hookTypesUpdateIndexDev = -1;
5484 }
5485
5486 // The following should have already been reset
5487 // currentHook = null;
5488 // workInProgressHook = null;
5489
5490 // remainingExpirationTime = NoWork;
5491 // componentUpdateQueue = null;
5492
5493 // didScheduleRenderPhaseUpdate = false;
5494 // renderPhaseUpdates = null;
5495 // numberOfReRenders = 0;
5496 // sideEffectTag = 0;
5497
5498 // TODO Warn if no hooks are used at all during mount, then some are used during update.
5499 // Currently we will identify the update render as a mount because nextCurrentHook === null.
5500 // This is tricky because it's valid for certain types of components (e.g. React.lazy)
5501
5502 // Using nextCurrentHook to differentiate between mount/update only works if at least one stateful hook is used.
5503 // Non-stateful hooks (e.g. context) don't get added to memoizedState,
5504 // so nextCurrentHook would be null during updates and mounts.
5505 {
5506 if (nextCurrentHook !== null) {
5507 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
5508 } else if (hookTypesDev !== null) {
5509 // This dispatcher handles an edge case where a component is updating,
5510 // but no stateful hooks have been used.
5511 // We want to match the production code behavior (which will use HooksDispatcherOnMount),
5512 // but with the extra DEV validation to ensure hooks ordering hasn't changed.
5513 // This dispatcher does that.
5514 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV;
5515 } else {
5516 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV;
5517 }
5518 }
5519
5520 var children = Component(props, refOrContext);
5521
5522 if (didScheduleRenderPhaseUpdate) {
5523 do {
5524 didScheduleRenderPhaseUpdate = false;
5525 numberOfReRenders += 1;
5526
5527 // Start over from the beginning of the list
5528 nextCurrentHook = current !== null ? current.memoizedState : null;
5529 nextWorkInProgressHook = firstWorkInProgressHook;
5530
5531 currentHook = null;
5532 workInProgressHook = null;
5533 componentUpdateQueue = null;
5534
5535 {
5536 // Also validate hook order for cascading updates.
5537 hookTypesUpdateIndexDev = -1;
5538 }
5539
5540 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
5541
5542 children = Component(props, refOrContext);
5543 } while (didScheduleRenderPhaseUpdate);
5544
5545 renderPhaseUpdates = null;
5546 numberOfReRenders = 0;
5547 }
5548
5549 // We can assume the previous dispatcher is always this one, since we set it
5550 // at the beginning of the render phase and there's no re-entrancy.
5551 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
5552
5553 var renderedWork = currentlyRenderingFiber$1;
5554
5555 renderedWork.memoizedState = firstWorkInProgressHook;
5556 renderedWork.expirationTime = remainingExpirationTime;
5557 renderedWork.updateQueue = componentUpdateQueue;
5558 renderedWork.effectTag |= sideEffectTag;
5559
5560 {
5561 renderedWork._debugHookTypes = hookTypesDev;
5562 }
5563
5564 // This check uses currentHook so that it works the same in DEV and prod bundles.
5565 // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.
5566 var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
5567
5568 renderExpirationTime = NoWork;
5569 currentlyRenderingFiber$1 = null;
5570
5571 currentHook = null;
5572 nextCurrentHook = null;
5573 firstWorkInProgressHook = null;
5574 workInProgressHook = null;
5575 nextWorkInProgressHook = null;
5576
5577 {
5578 currentHookNameInDev = null;
5579 hookTypesDev = null;
5580 hookTypesUpdateIndexDev = -1;
5581 }
5582
5583 remainingExpirationTime = NoWork;
5584 componentUpdateQueue = null;
5585 sideEffectTag = 0;
5586
5587 // These were reset above
5588 // didScheduleRenderPhaseUpdate = false;
5589 // renderPhaseUpdates = null;
5590 // numberOfReRenders = 0;
5591
5592 !!didRenderTooFewHooks ? invariant(false, 'Rendered fewer hooks than expected. This may be caused by an accidental early return statement.') : void 0;
5593
5594 return children;
5595}
5596
5597function bailoutHooks(current, workInProgress, expirationTime) {
5598 workInProgress.updateQueue = current.updateQueue;
5599 workInProgress.effectTag &= ~(Passive | Update);
5600 if (current.expirationTime <= expirationTime) {
5601 current.expirationTime = NoWork;
5602 }
5603}
5604
5605function resetHooks() {
5606 // We can assume the previous dispatcher is always this one, since we set it
5607 // at the beginning of the render phase and there's no re-entrancy.
5608 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
5609
5610 // This is used to reset the state of this module when a component throws.
5611 // It's also called inside mountIndeterminateComponent if we determine the
5612 // component is a module-style component.
5613 renderExpirationTime = NoWork;
5614 currentlyRenderingFiber$1 = null;
5615
5616 currentHook = null;
5617 nextCurrentHook = null;
5618 firstWorkInProgressHook = null;
5619 workInProgressHook = null;
5620 nextWorkInProgressHook = null;
5621
5622 {
5623 hookTypesDev = null;
5624 hookTypesUpdateIndexDev = -1;
5625
5626 currentHookNameInDev = null;
5627 }
5628
5629 remainingExpirationTime = NoWork;
5630 componentUpdateQueue = null;
5631 sideEffectTag = 0;
5632
5633 didScheduleRenderPhaseUpdate = false;
5634 renderPhaseUpdates = null;
5635 numberOfReRenders = 0;
5636}
5637
5638function mountWorkInProgressHook() {
5639 var hook = {
5640 memoizedState: null,
5641
5642 baseState: null,
5643 queue: null,
5644 baseUpdate: null,
5645
5646 next: null
5647 };
5648
5649 if (workInProgressHook === null) {
5650 // This is the first hook in the list
5651 firstWorkInProgressHook = workInProgressHook = hook;
5652 } else {
5653 // Append to the end of the list
5654 workInProgressHook = workInProgressHook.next = hook;
5655 }
5656 return workInProgressHook;
5657}
5658
5659function updateWorkInProgressHook() {
5660 // This function is used both for updates and for re-renders triggered by a
5661 // render phase update. It assumes there is either a current hook we can
5662 // clone, or a work-in-progress hook from a previous render pass that we can
5663 // use as a base. When we reach the end of the base list, we must switch to
5664 // the dispatcher used for mounts.
5665 if (nextWorkInProgressHook !== null) {
5666 // There's already a work-in-progress. Reuse it.
5667 workInProgressHook = nextWorkInProgressHook;
5668 nextWorkInProgressHook = workInProgressHook.next;
5669
5670 currentHook = nextCurrentHook;
5671 nextCurrentHook = currentHook !== null ? currentHook.next : null;
5672 } else {
5673 // Clone from the current hook.
5674 !(nextCurrentHook !== null) ? invariant(false, 'Rendered more hooks than during the previous render.') : void 0;
5675 currentHook = nextCurrentHook;
5676
5677 var newHook = {
5678 memoizedState: currentHook.memoizedState,
5679
5680 baseState: currentHook.baseState,
5681 queue: currentHook.queue,
5682 baseUpdate: currentHook.baseUpdate,
5683
5684 next: null
5685 };
5686
5687 if (workInProgressHook === null) {
5688 // This is the first hook in the list.
5689 workInProgressHook = firstWorkInProgressHook = newHook;
5690 } else {
5691 // Append to the end of the list.
5692 workInProgressHook = workInProgressHook.next = newHook;
5693 }
5694 nextCurrentHook = currentHook.next;
5695 }
5696 return workInProgressHook;
5697}
5698
5699function createFunctionComponentUpdateQueue() {
5700 return {
5701 lastEffect: null
5702 };
5703}
5704
5705function basicStateReducer(state, action) {
5706 return typeof action === 'function' ? action(state) : action;
5707}
5708
5709function mountReducer(reducer, initialArg, init) {
5710 var hook = mountWorkInProgressHook();
5711 var initialState = void 0;
5712 if (init !== undefined) {
5713 initialState = init(initialArg);
5714 } else {
5715 initialState = initialArg;
5716 }
5717 hook.memoizedState = hook.baseState = initialState;
5718 var queue = hook.queue = {
5719 last: null,
5720 dispatch: null,
5721 eagerReducer: reducer,
5722 eagerState: initialState
5723 };
5724 var dispatch = queue.dispatch = dispatchAction.bind(null,
5725 // Flow doesn't know this is non-null, but we do.
5726 currentlyRenderingFiber$1, queue);
5727 return [hook.memoizedState, dispatch];
5728}
5729
5730function updateReducer(reducer, initialArg, init) {
5731 var hook = updateWorkInProgressHook();
5732 var queue = hook.queue;
5733 !(queue !== null) ? invariant(false, 'Should have a queue. This is likely a bug in React. Please file an issue.') : void 0;
5734
5735 if (numberOfReRenders > 0) {
5736 // This is a re-render. Apply the new render phase updates to the previous
5737 var _dispatch = queue.dispatch;
5738 if (renderPhaseUpdates !== null) {
5739 // Render phase updates are stored in a map of queue -> linked list
5740 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
5741 if (firstRenderPhaseUpdate !== undefined) {
5742 renderPhaseUpdates.delete(queue);
5743 var newState = hook.memoizedState;
5744 var update = firstRenderPhaseUpdate;
5745 do {
5746 // Process this render phase update. We don't have to check the
5747 // priority because it will always be the same as the current
5748 // render's.
5749 var _action = update.action;
5750 newState = reducer(newState, _action);
5751 update = update.next;
5752 } while (update !== null);
5753
5754 // Mark that the fiber performed work, but only if the new state is
5755 // different from the current state.
5756 if (!is(newState, hook.memoizedState)) {
5757 markWorkInProgressReceivedUpdate();
5758 }
5759
5760 hook.memoizedState = newState;
5761 // Don't persist the state accumlated from the render phase updates to
5762 // the base state unless the queue is empty.
5763 // TODO: Not sure if this is the desired semantics, but it's what we
5764 // do for gDSFP. I can't remember why.
5765 if (hook.baseUpdate === queue.last) {
5766 hook.baseState = newState;
5767 }
5768
5769 queue.eagerReducer = reducer;
5770 queue.eagerState = newState;
5771
5772 return [newState, _dispatch];
5773 }
5774 }
5775 return [hook.memoizedState, _dispatch];
5776 }
5777
5778 // The last update in the entire queue
5779 var last = queue.last;
5780 // The last update that is part of the base state.
5781 var baseUpdate = hook.baseUpdate;
5782 var baseState = hook.baseState;
5783
5784 // Find the first unprocessed update.
5785 var first = void 0;
5786 if (baseUpdate !== null) {
5787 if (last !== null) {
5788 // For the first update, the queue is a circular linked list where
5789 // `queue.last.next = queue.first`. Once the first update commits, and
5790 // the `baseUpdate` is no longer empty, we can unravel the list.
5791 last.next = null;
5792 }
5793 first = baseUpdate.next;
5794 } else {
5795 first = last !== null ? last.next : null;
5796 }
5797 if (first !== null) {
5798 var _newState = baseState;
5799 var newBaseState = null;
5800 var newBaseUpdate = null;
5801 var prevUpdate = baseUpdate;
5802 var _update = first;
5803 var didSkip = false;
5804 do {
5805 var updateExpirationTime = _update.expirationTime;
5806 if (updateExpirationTime < renderExpirationTime) {
5807 // Priority is insufficient. Skip this update. If this is the first
5808 // skipped update, the previous update/state is the new base
5809 // update/state.
5810 if (!didSkip) {
5811 didSkip = true;
5812 newBaseUpdate = prevUpdate;
5813 newBaseState = _newState;
5814 }
5815 // Update the remaining priority in the queue.
5816 if (updateExpirationTime > remainingExpirationTime) {
5817 remainingExpirationTime = updateExpirationTime;
5818 }
5819 } else {
5820 // Process this update.
5821 if (_update.eagerReducer === reducer) {
5822 // If this update was processed eagerly, and its reducer matches the
5823 // current reducer, we can use the eagerly computed state.
5824 _newState = _update.eagerState;
5825 } else {
5826 var _action2 = _update.action;
5827 _newState = reducer(_newState, _action2);
5828 }
5829 }
5830 prevUpdate = _update;
5831 _update = _update.next;
5832 } while (_update !== null && _update !== first);
5833
5834 if (!didSkip) {
5835 newBaseUpdate = prevUpdate;
5836 newBaseState = _newState;
5837 }
5838
5839 // Mark that the fiber performed work, but only if the new state is
5840 // different from the current state.
5841 if (!is(_newState, hook.memoizedState)) {
5842 markWorkInProgressReceivedUpdate();
5843 }
5844
5845 hook.memoizedState = _newState;
5846 hook.baseUpdate = newBaseUpdate;
5847 hook.baseState = newBaseState;
5848
5849 queue.eagerReducer = reducer;
5850 queue.eagerState = _newState;
5851 }
5852
5853 var dispatch = queue.dispatch;
5854 return [hook.memoizedState, dispatch];
5855}
5856
5857function mountState(initialState) {
5858 var hook = mountWorkInProgressHook();
5859 if (typeof initialState === 'function') {
5860 initialState = initialState();
5861 }
5862 hook.memoizedState = hook.baseState = initialState;
5863 var queue = hook.queue = {
5864 last: null,
5865 dispatch: null,
5866 eagerReducer: basicStateReducer,
5867 eagerState: initialState
5868 };
5869 var dispatch = queue.dispatch = dispatchAction.bind(null,
5870 // Flow doesn't know this is non-null, but we do.
5871 currentlyRenderingFiber$1, queue);
5872 return [hook.memoizedState, dispatch];
5873}
5874
5875function updateState(initialState) {
5876 return updateReducer(basicStateReducer, initialState);
5877}
5878
5879function pushEffect(tag, create, destroy, deps) {
5880 var effect = {
5881 tag: tag,
5882 create: create,
5883 destroy: destroy,
5884 deps: deps,
5885 // Circular
5886 next: null
5887 };
5888 if (componentUpdateQueue === null) {
5889 componentUpdateQueue = createFunctionComponentUpdateQueue();
5890 componentUpdateQueue.lastEffect = effect.next = effect;
5891 } else {
5892 var _lastEffect = componentUpdateQueue.lastEffect;
5893 if (_lastEffect === null) {
5894 componentUpdateQueue.lastEffect = effect.next = effect;
5895 } else {
5896 var firstEffect = _lastEffect.next;
5897 _lastEffect.next = effect;
5898 effect.next = firstEffect;
5899 componentUpdateQueue.lastEffect = effect;
5900 }
5901 }
5902 return effect;
5903}
5904
5905function mountRef(initialValue) {
5906 var hook = mountWorkInProgressHook();
5907 var ref = { current: initialValue };
5908 {
5909 Object.seal(ref);
5910 }
5911 hook.memoizedState = ref;
5912 return ref;
5913}
5914
5915function updateRef(initialValue) {
5916 var hook = updateWorkInProgressHook();
5917 return hook.memoizedState;
5918}
5919
5920function mountEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
5921 var hook = mountWorkInProgressHook();
5922 var nextDeps = deps === undefined ? null : deps;
5923 sideEffectTag |= fiberEffectTag;
5924 hook.memoizedState = pushEffect(hookEffectTag, create, undefined, nextDeps);
5925}
5926
5927function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
5928 var hook = updateWorkInProgressHook();
5929 var nextDeps = deps === undefined ? null : deps;
5930 var destroy = undefined;
5931
5932 if (currentHook !== null) {
5933 var prevEffect = currentHook.memoizedState;
5934 destroy = prevEffect.destroy;
5935 if (nextDeps !== null) {
5936 var prevDeps = prevEffect.deps;
5937 if (areHookInputsEqual(nextDeps, prevDeps)) {
5938 pushEffect(NoEffect$1, create, destroy, nextDeps);
5939 return;
5940 }
5941 }
5942 }
5943
5944 sideEffectTag |= fiberEffectTag;
5945 hook.memoizedState = pushEffect(hookEffectTag, create, destroy, nextDeps);
5946}
5947
5948function mountEffect(create, deps) {
5949 return mountEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
5950}
5951
5952function updateEffect(create, deps) {
5953 return updateEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps);
5954}
5955
5956function mountLayoutEffect(create, deps) {
5957 return mountEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
5958}
5959
5960function updateLayoutEffect(create, deps) {
5961 return updateEffectImpl(Update, UnmountMutation | MountLayout, create, deps);
5962}
5963
5964function imperativeHandleEffect(create, ref) {
5965 if (typeof ref === 'function') {
5966 var refCallback = ref;
5967 var _inst = create();
5968 refCallback(_inst);
5969 return function () {
5970 refCallback(null);
5971 };
5972 } else if (ref !== null && ref !== undefined) {
5973 var refObject = ref;
5974 {
5975 !refObject.hasOwnProperty('current') ? warning$1(false, 'Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}') : void 0;
5976 }
5977 var _inst2 = create();
5978 refObject.current = _inst2;
5979 return function () {
5980 refObject.current = null;
5981 };
5982 }
5983}
5984
5985function mountImperativeHandle(ref, create, deps) {
5986 {
5987 !(typeof create === 'function') ? warning$1(false, 'Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null') : void 0;
5988 }
5989
5990 // TODO: If deps are provided, should we skip comparing the ref itself?
5991 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
5992
5993 return mountEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
5994}
5995
5996function updateImperativeHandle(ref, create, deps) {
5997 {
5998 !(typeof create === 'function') ? warning$1(false, 'Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null') : void 0;
5999 }
6000
6001 // TODO: If deps are provided, should we skip comparing the ref itself?
6002 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
6003
6004 return updateEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
6005}
6006
6007function mountDebugValue(value, formatterFn) {
6008 // This hook is normally a no-op.
6009 // The react-debug-hooks package injects its own implementation
6010 // so that e.g. DevTools can display custom hook values.
6011}
6012
6013var updateDebugValue = mountDebugValue;
6014
6015function mountCallback(callback, deps) {
6016 var hook = mountWorkInProgressHook();
6017 var nextDeps = deps === undefined ? null : deps;
6018 hook.memoizedState = [callback, nextDeps];
6019 return callback;
6020}
6021
6022function updateCallback(callback, deps) {
6023 var hook = updateWorkInProgressHook();
6024 var nextDeps = deps === undefined ? null : deps;
6025 var prevState = hook.memoizedState;
6026 if (prevState !== null) {
6027 if (nextDeps !== null) {
6028 var prevDeps = prevState[1];
6029 if (areHookInputsEqual(nextDeps, prevDeps)) {
6030 return prevState[0];
6031 }
6032 }
6033 }
6034 hook.memoizedState = [callback, nextDeps];
6035 return callback;
6036}
6037
6038function mountMemo(nextCreate, deps) {
6039 var hook = mountWorkInProgressHook();
6040 var nextDeps = deps === undefined ? null : deps;
6041 var nextValue = nextCreate();
6042 hook.memoizedState = [nextValue, nextDeps];
6043 return nextValue;
6044}
6045
6046function updateMemo(nextCreate, deps) {
6047 var hook = updateWorkInProgressHook();
6048 var nextDeps = deps === undefined ? null : deps;
6049 var prevState = hook.memoizedState;
6050 if (prevState !== null) {
6051 // Assume these are defined. If they're not, areHookInputsEqual will warn.
6052 if (nextDeps !== null) {
6053 var prevDeps = prevState[1];
6054 if (areHookInputsEqual(nextDeps, prevDeps)) {
6055 return prevState[0];
6056 }
6057 }
6058 }
6059 var nextValue = nextCreate();
6060 hook.memoizedState = [nextValue, nextDeps];
6061 return nextValue;
6062}
6063
6064// in a test-like environment, we want to warn if dispatchAction()
6065// is called outside of a batchedUpdates/TestUtils.act(...) call.
6066var shouldWarnForUnbatchedSetState = false;
6067
6068{
6069 // jest isn't a 'global', it's just exposed to tests via a wrapped function
6070 // further, this isn't a test file, so flow doesn't recognize the symbol. So...
6071 // $FlowExpectedError - because requirements don't give a damn about your type sigs.
6072 if ('undefined' !== typeof jest) {
6073 shouldWarnForUnbatchedSetState = true;
6074 }
6075}
6076
6077function dispatchAction(fiber, queue, action) {
6078 !(numberOfReRenders < RE_RENDER_LIMIT) ? invariant(false, 'Too many re-renders. React limits the number of renders to prevent an infinite loop.') : void 0;
6079
6080 {
6081 !(arguments.length <= 3) ? warning$1(false, "State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().') : void 0;
6082 }
6083
6084 var alternate = fiber.alternate;
6085 if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {
6086 // This is a render phase update. Stash it in a lazily-created map of
6087 // queue -> linked list of updates. After this render pass, we'll restart
6088 // and apply the stashed updates on top of the work-in-progress hook.
6089 didScheduleRenderPhaseUpdate = true;
6090 var update = {
6091 expirationTime: renderExpirationTime,
6092 action: action,
6093 eagerReducer: null,
6094 eagerState: null,
6095 next: null
6096 };
6097 if (renderPhaseUpdates === null) {
6098 renderPhaseUpdates = new Map();
6099 }
6100 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
6101 if (firstRenderPhaseUpdate === undefined) {
6102 renderPhaseUpdates.set(queue, update);
6103 } else {
6104 // Append the update to the end of the list.
6105 var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
6106 while (lastRenderPhaseUpdate.next !== null) {
6107 lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
6108 }
6109 lastRenderPhaseUpdate.next = update;
6110 }
6111 } else {
6112 flushPassiveEffects();
6113
6114 var currentTime = requestCurrentTime();
6115 var _expirationTime = computeExpirationForFiber(currentTime, fiber);
6116
6117 var _update2 = {
6118 expirationTime: _expirationTime,
6119 action: action,
6120 eagerReducer: null,
6121 eagerState: null,
6122 next: null
6123 };
6124
6125 // Append the update to the end of the list.
6126 var _last = queue.last;
6127 if (_last === null) {
6128 // This is the first update. Create a circular list.
6129 _update2.next = _update2;
6130 } else {
6131 var first = _last.next;
6132 if (first !== null) {
6133 // Still circular.
6134 _update2.next = first;
6135 }
6136 _last.next = _update2;
6137 }
6138 queue.last = _update2;
6139
6140 if (fiber.expirationTime === NoWork && (alternate === null || alternate.expirationTime === NoWork)) {
6141 // The queue is currently empty, which means we can eagerly compute the
6142 // next state before entering the render phase. If the new state is the
6143 // same as the current state, we may be able to bail out entirely.
6144 var _eagerReducer = queue.eagerReducer;
6145 if (_eagerReducer !== null) {
6146 var prevDispatcher = void 0;
6147 {
6148 prevDispatcher = ReactCurrentDispatcher$1.current;
6149 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
6150 }
6151 try {
6152 var currentState = queue.eagerState;
6153 var _eagerState = _eagerReducer(currentState, action);
6154 // Stash the eagerly computed state, and the reducer used to compute
6155 // it, on the update object. If the reducer hasn't changed by the
6156 // time we enter the render phase, then the eager state can be used
6157 // without calling the reducer again.
6158 _update2.eagerReducer = _eagerReducer;
6159 _update2.eagerState = _eagerState;
6160 if (is(_eagerState, currentState)) {
6161 // Fast path. We can bail out without scheduling React to re-render.
6162 // It's still possible that we'll need to rebase this update later,
6163 // if the component re-renders for a different reason and by that
6164 // time the reducer has changed.
6165 return;
6166 }
6167 } catch (error) {
6168 // Suppress the error. It will throw again in the render phase.
6169 } finally {
6170 {
6171 ReactCurrentDispatcher$1.current = prevDispatcher;
6172 }
6173 }
6174 }
6175 }
6176 {
6177 if (shouldWarnForUnbatchedSetState === true) {
6178 warnIfNotCurrentlyBatchingInDev(fiber);
6179 }
6180 }
6181 scheduleWork(fiber, _expirationTime);
6182 }
6183}
6184
6185var ContextOnlyDispatcher = {
6186 readContext: readContext,
6187
6188 useCallback: throwInvalidHookError,
6189 useContext: throwInvalidHookError,
6190 useEffect: throwInvalidHookError,
6191 useImperativeHandle: throwInvalidHookError,
6192 useLayoutEffect: throwInvalidHookError,
6193 useMemo: throwInvalidHookError,
6194 useReducer: throwInvalidHookError,
6195 useRef: throwInvalidHookError,
6196 useState: throwInvalidHookError,
6197 useDebugValue: throwInvalidHookError
6198};
6199
6200var HooksDispatcherOnMountInDEV = null;
6201var HooksDispatcherOnMountWithHookTypesInDEV = null;
6202var HooksDispatcherOnUpdateInDEV = null;
6203var InvalidNestedHooksDispatcherOnMountInDEV = null;
6204var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
6205
6206{
6207 var warnInvalidContextAccess = function () {
6208 warning$1(false, 'Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
6209 };
6210
6211 var warnInvalidHookAccess = function () {
6212 warning$1(false, 'Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://fb.me/rules-of-hooks');
6213 };
6214
6215 HooksDispatcherOnMountInDEV = {
6216 readContext: function (context, observedBits) {
6217 return readContext(context, observedBits);
6218 },
6219 useCallback: function (callback, deps) {
6220 currentHookNameInDev = 'useCallback';
6221 mountHookTypesDev();
6222 return mountCallback(callback, deps);
6223 },
6224 useContext: function (context, observedBits) {
6225 currentHookNameInDev = 'useContext';
6226 mountHookTypesDev();
6227 return readContext(context, observedBits);
6228 },
6229 useEffect: function (create, deps) {
6230 currentHookNameInDev = 'useEffect';
6231 mountHookTypesDev();
6232 return mountEffect(create, deps);
6233 },
6234 useImperativeHandle: function (ref, create, deps) {
6235 currentHookNameInDev = 'useImperativeHandle';
6236 mountHookTypesDev();
6237 return mountImperativeHandle(ref, create, deps);
6238 },
6239 useLayoutEffect: function (create, deps) {
6240 currentHookNameInDev = 'useLayoutEffect';
6241 mountHookTypesDev();
6242 return mountLayoutEffect(create, deps);
6243 },
6244 useMemo: function (create, deps) {
6245 currentHookNameInDev = 'useMemo';
6246 mountHookTypesDev();
6247 var prevDispatcher = ReactCurrentDispatcher$1.current;
6248 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
6249 try {
6250 return mountMemo(create, deps);
6251 } finally {
6252 ReactCurrentDispatcher$1.current = prevDispatcher;
6253 }
6254 },
6255 useReducer: function (reducer, initialArg, init) {
6256 currentHookNameInDev = 'useReducer';
6257 mountHookTypesDev();
6258 var prevDispatcher = ReactCurrentDispatcher$1.current;
6259 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
6260 try {
6261 return mountReducer(reducer, initialArg, init);
6262 } finally {
6263 ReactCurrentDispatcher$1.current = prevDispatcher;
6264 }
6265 },
6266 useRef: function (initialValue) {
6267 currentHookNameInDev = 'useRef';
6268 mountHookTypesDev();
6269 return mountRef(initialValue);
6270 },
6271 useState: function (initialState) {
6272 currentHookNameInDev = 'useState';
6273 mountHookTypesDev();
6274 var prevDispatcher = ReactCurrentDispatcher$1.current;
6275 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
6276 try {
6277 return mountState(initialState);
6278 } finally {
6279 ReactCurrentDispatcher$1.current = prevDispatcher;
6280 }
6281 },
6282 useDebugValue: function (value, formatterFn) {
6283 currentHookNameInDev = 'useDebugValue';
6284 mountHookTypesDev();
6285 return mountDebugValue(value, formatterFn);
6286 }
6287 };
6288
6289 HooksDispatcherOnMountWithHookTypesInDEV = {
6290 readContext: function (context, observedBits) {
6291 return readContext(context, observedBits);
6292 },
6293 useCallback: function (callback, deps) {
6294 currentHookNameInDev = 'useCallback';
6295 updateHookTypesDev();
6296 return mountCallback(callback, deps);
6297 },
6298 useContext: function (context, observedBits) {
6299 currentHookNameInDev = 'useContext';
6300 updateHookTypesDev();
6301 return readContext(context, observedBits);
6302 },
6303 useEffect: function (create, deps) {
6304 currentHookNameInDev = 'useEffect';
6305 updateHookTypesDev();
6306 return mountEffect(create, deps);
6307 },
6308 useImperativeHandle: function (ref, create, deps) {
6309 currentHookNameInDev = 'useImperativeHandle';
6310 updateHookTypesDev();
6311 return mountImperativeHandle(ref, create, deps);
6312 },
6313 useLayoutEffect: function (create, deps) {
6314 currentHookNameInDev = 'useLayoutEffect';
6315 updateHookTypesDev();
6316 return mountLayoutEffect(create, deps);
6317 },
6318 useMemo: function (create, deps) {
6319 currentHookNameInDev = 'useMemo';
6320 updateHookTypesDev();
6321 var prevDispatcher = ReactCurrentDispatcher$1.current;
6322 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
6323 try {
6324 return mountMemo(create, deps);
6325 } finally {
6326 ReactCurrentDispatcher$1.current = prevDispatcher;
6327 }
6328 },
6329 useReducer: function (reducer, initialArg, init) {
6330 currentHookNameInDev = 'useReducer';
6331 updateHookTypesDev();
6332 var prevDispatcher = ReactCurrentDispatcher$1.current;
6333 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
6334 try {
6335 return mountReducer(reducer, initialArg, init);
6336 } finally {
6337 ReactCurrentDispatcher$1.current = prevDispatcher;
6338 }
6339 },
6340 useRef: function (initialValue) {
6341 currentHookNameInDev = 'useRef';
6342 updateHookTypesDev();
6343 return mountRef(initialValue);
6344 },
6345 useState: function (initialState) {
6346 currentHookNameInDev = 'useState';
6347 updateHookTypesDev();
6348 var prevDispatcher = ReactCurrentDispatcher$1.current;
6349 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
6350 try {
6351 return mountState(initialState);
6352 } finally {
6353 ReactCurrentDispatcher$1.current = prevDispatcher;
6354 }
6355 },
6356 useDebugValue: function (value, formatterFn) {
6357 currentHookNameInDev = 'useDebugValue';
6358 updateHookTypesDev();
6359 return mountDebugValue(value, formatterFn);
6360 }
6361 };
6362
6363 HooksDispatcherOnUpdateInDEV = {
6364 readContext: function (context, observedBits) {
6365 return readContext(context, observedBits);
6366 },
6367 useCallback: function (callback, deps) {
6368 currentHookNameInDev = 'useCallback';
6369 updateHookTypesDev();
6370 return updateCallback(callback, deps);
6371 },
6372 useContext: function (context, observedBits) {
6373 currentHookNameInDev = 'useContext';
6374 updateHookTypesDev();
6375 return readContext(context, observedBits);
6376 },
6377 useEffect: function (create, deps) {
6378 currentHookNameInDev = 'useEffect';
6379 updateHookTypesDev();
6380 return updateEffect(create, deps);
6381 },
6382 useImperativeHandle: function (ref, create, deps) {
6383 currentHookNameInDev = 'useImperativeHandle';
6384 updateHookTypesDev();
6385 return updateImperativeHandle(ref, create, deps);
6386 },
6387 useLayoutEffect: function (create, deps) {
6388 currentHookNameInDev = 'useLayoutEffect';
6389 updateHookTypesDev();
6390 return updateLayoutEffect(create, deps);
6391 },
6392 useMemo: function (create, deps) {
6393 currentHookNameInDev = 'useMemo';
6394 updateHookTypesDev();
6395 var prevDispatcher = ReactCurrentDispatcher$1.current;
6396 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
6397 try {
6398 return updateMemo(create, deps);
6399 } finally {
6400 ReactCurrentDispatcher$1.current = prevDispatcher;
6401 }
6402 },
6403 useReducer: function (reducer, initialArg, init) {
6404 currentHookNameInDev = 'useReducer';
6405 updateHookTypesDev();
6406 var prevDispatcher = ReactCurrentDispatcher$1.current;
6407 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
6408 try {
6409 return updateReducer(reducer, initialArg, init);
6410 } finally {
6411 ReactCurrentDispatcher$1.current = prevDispatcher;
6412 }
6413 },
6414 useRef: function (initialValue) {
6415 currentHookNameInDev = 'useRef';
6416 updateHookTypesDev();
6417 return updateRef(initialValue);
6418 },
6419 useState: function (initialState) {
6420 currentHookNameInDev = 'useState';
6421 updateHookTypesDev();
6422 var prevDispatcher = ReactCurrentDispatcher$1.current;
6423 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
6424 try {
6425 return updateState(initialState);
6426 } finally {
6427 ReactCurrentDispatcher$1.current = prevDispatcher;
6428 }
6429 },
6430 useDebugValue: function (value, formatterFn) {
6431 currentHookNameInDev = 'useDebugValue';
6432 updateHookTypesDev();
6433 return updateDebugValue(value, formatterFn);
6434 }
6435 };
6436
6437 InvalidNestedHooksDispatcherOnMountInDEV = {
6438 readContext: function (context, observedBits) {
6439 warnInvalidContextAccess();
6440 return readContext(context, observedBits);
6441 },
6442 useCallback: function (callback, deps) {
6443 currentHookNameInDev = 'useCallback';
6444 warnInvalidHookAccess();
6445 mountHookTypesDev();
6446 return mountCallback(callback, deps);
6447 },
6448 useContext: function (context, observedBits) {
6449 currentHookNameInDev = 'useContext';
6450 warnInvalidHookAccess();
6451 mountHookTypesDev();
6452 return readContext(context, observedBits);
6453 },
6454 useEffect: function (create, deps) {
6455 currentHookNameInDev = 'useEffect';
6456 warnInvalidHookAccess();
6457 mountHookTypesDev();
6458 return mountEffect(create, deps);
6459 },
6460 useImperativeHandle: function (ref, create, deps) {
6461 currentHookNameInDev = 'useImperativeHandle';
6462 warnInvalidHookAccess();
6463 mountHookTypesDev();
6464 return mountImperativeHandle(ref, create, deps);
6465 },
6466 useLayoutEffect: function (create, deps) {
6467 currentHookNameInDev = 'useLayoutEffect';
6468 warnInvalidHookAccess();
6469 mountHookTypesDev();
6470 return mountLayoutEffect(create, deps);
6471 },
6472 useMemo: function (create, deps) {
6473 currentHookNameInDev = 'useMemo';
6474 warnInvalidHookAccess();
6475 mountHookTypesDev();
6476 var prevDispatcher = ReactCurrentDispatcher$1.current;
6477 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
6478 try {
6479 return mountMemo(create, deps);
6480 } finally {
6481 ReactCurrentDispatcher$1.current = prevDispatcher;
6482 }
6483 },
6484 useReducer: function (reducer, initialArg, init) {
6485 currentHookNameInDev = 'useReducer';
6486 warnInvalidHookAccess();
6487 mountHookTypesDev();
6488 var prevDispatcher = ReactCurrentDispatcher$1.current;
6489 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
6490 try {
6491 return mountReducer(reducer, initialArg, init);
6492 } finally {
6493 ReactCurrentDispatcher$1.current = prevDispatcher;
6494 }
6495 },
6496 useRef: function (initialValue) {
6497 currentHookNameInDev = 'useRef';
6498 warnInvalidHookAccess();
6499 mountHookTypesDev();
6500 return mountRef(initialValue);
6501 },
6502 useState: function (initialState) {
6503 currentHookNameInDev = 'useState';
6504 warnInvalidHookAccess();
6505 mountHookTypesDev();
6506 var prevDispatcher = ReactCurrentDispatcher$1.current;
6507 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
6508 try {
6509 return mountState(initialState);
6510 } finally {
6511 ReactCurrentDispatcher$1.current = prevDispatcher;
6512 }
6513 },
6514 useDebugValue: function (value, formatterFn) {
6515 currentHookNameInDev = 'useDebugValue';
6516 warnInvalidHookAccess();
6517 mountHookTypesDev();
6518 return mountDebugValue(value, formatterFn);
6519 }
6520 };
6521
6522 InvalidNestedHooksDispatcherOnUpdateInDEV = {
6523 readContext: function (context, observedBits) {
6524 warnInvalidContextAccess();
6525 return readContext(context, observedBits);
6526 },
6527 useCallback: function (callback, deps) {
6528 currentHookNameInDev = 'useCallback';
6529 warnInvalidHookAccess();
6530 updateHookTypesDev();
6531 return updateCallback(callback, deps);
6532 },
6533 useContext: function (context, observedBits) {
6534 currentHookNameInDev = 'useContext';
6535 warnInvalidHookAccess();
6536 updateHookTypesDev();
6537 return readContext(context, observedBits);
6538 },
6539 useEffect: function (create, deps) {
6540 currentHookNameInDev = 'useEffect';
6541 warnInvalidHookAccess();
6542 updateHookTypesDev();
6543 return updateEffect(create, deps);
6544 },
6545 useImperativeHandle: function (ref, create, deps) {
6546 currentHookNameInDev = 'useImperativeHandle';
6547 warnInvalidHookAccess();
6548 updateHookTypesDev();
6549 return updateImperativeHandle(ref, create, deps);
6550 },
6551 useLayoutEffect: function (create, deps) {
6552 currentHookNameInDev = 'useLayoutEffect';
6553 warnInvalidHookAccess();
6554 updateHookTypesDev();
6555 return updateLayoutEffect(create, deps);
6556 },
6557 useMemo: function (create, deps) {
6558 currentHookNameInDev = 'useMemo';
6559 warnInvalidHookAccess();
6560 updateHookTypesDev();
6561 var prevDispatcher = ReactCurrentDispatcher$1.current;
6562 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
6563 try {
6564 return updateMemo(create, deps);
6565 } finally {
6566 ReactCurrentDispatcher$1.current = prevDispatcher;
6567 }
6568 },
6569 useReducer: function (reducer, initialArg, init) {
6570 currentHookNameInDev = 'useReducer';
6571 warnInvalidHookAccess();
6572 updateHookTypesDev();
6573 var prevDispatcher = ReactCurrentDispatcher$1.current;
6574 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
6575 try {
6576 return updateReducer(reducer, initialArg, init);
6577 } finally {
6578 ReactCurrentDispatcher$1.current = prevDispatcher;
6579 }
6580 },
6581 useRef: function (initialValue) {
6582 currentHookNameInDev = 'useRef';
6583 warnInvalidHookAccess();
6584 updateHookTypesDev();
6585 return updateRef(initialValue);
6586 },
6587 useState: function (initialState) {
6588 currentHookNameInDev = 'useState';
6589 warnInvalidHookAccess();
6590 updateHookTypesDev();
6591 var prevDispatcher = ReactCurrentDispatcher$1.current;
6592 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
6593 try {
6594 return updateState(initialState);
6595 } finally {
6596 ReactCurrentDispatcher$1.current = prevDispatcher;
6597 }
6598 },
6599 useDebugValue: function (value, formatterFn) {
6600 currentHookNameInDev = 'useDebugValue';
6601 warnInvalidHookAccess();
6602 updateHookTypesDev();
6603 return updateDebugValue(value, formatterFn);
6604 }
6605 };
6606}
6607
6608var commitTime = 0;
6609var profilerStartTime = -1;
6610
6611function getCommitTime() {
6612 return commitTime;
6613}
6614
6615function recordCommitTime() {
6616 if (!enableProfilerTimer) {
6617 return;
6618 }
6619 commitTime = unstable_now();
6620}
6621
6622function startProfilerTimer(fiber) {
6623 if (!enableProfilerTimer) {
6624 return;
6625 }
6626
6627 profilerStartTime = unstable_now();
6628
6629 if (fiber.actualStartTime < 0) {
6630 fiber.actualStartTime = unstable_now();
6631 }
6632}
6633
6634function stopProfilerTimerIfRunning(fiber) {
6635 if (!enableProfilerTimer) {
6636 return;
6637 }
6638 profilerStartTime = -1;
6639}
6640
6641function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
6642 if (!enableProfilerTimer) {
6643 return;
6644 }
6645
6646 if (profilerStartTime >= 0) {
6647 var elapsedTime = unstable_now() - profilerStartTime;
6648 fiber.actualDuration += elapsedTime;
6649 if (overrideBaseTime) {
6650 fiber.selfBaseDuration = elapsedTime;
6651 }
6652 profilerStartTime = -1;
6653 }
6654}
6655
6656// The deepest Fiber on the stack involved in a hydration context.
6657// This may have been an insertion or a hydration.
6658var hydrationParentFiber = null;
6659var nextHydratableInstance = null;
6660var isHydrating = false;
6661
6662function enterHydrationState(fiber) {
6663 if (!supportsHydration) {
6664 return false;
6665 }
6666
6667 var parentInstance = fiber.stateNode.containerInfo;
6668 nextHydratableInstance = getFirstHydratableChild(parentInstance);
6669 hydrationParentFiber = fiber;
6670 isHydrating = true;
6671 return true;
6672}
6673
6674function reenterHydrationStateFromDehydratedSuspenseInstance(fiber) {
6675 if (!supportsHydration) {
6676 return false;
6677 }
6678
6679 var suspenseInstance = fiber.stateNode;
6680 nextHydratableInstance = getNextHydratableSibling(suspenseInstance);
6681 popToNextHostParent(fiber);
6682 isHydrating = true;
6683 return true;
6684}
6685
6686function deleteHydratableInstance(returnFiber, instance) {
6687 {
6688 switch (returnFiber.tag) {
6689 case HostRoot:
6690 didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance);
6691 break;
6692 case HostComponent:
6693 didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance);
6694 break;
6695 }
6696 }
6697
6698 var childToDelete = createFiberFromHostInstanceForDeletion();
6699 childToDelete.stateNode = instance;
6700 childToDelete.return = returnFiber;
6701 childToDelete.effectTag = Deletion;
6702
6703 // This might seem like it belongs on progressedFirstDeletion. However,
6704 // these children are not part of the reconciliation list of children.
6705 // Even if we abort and rereconcile the children, that will try to hydrate
6706 // again and the nodes are still in the host tree so these will be
6707 // recreated.
6708 if (returnFiber.lastEffect !== null) {
6709 returnFiber.lastEffect.nextEffect = childToDelete;
6710 returnFiber.lastEffect = childToDelete;
6711 } else {
6712 returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
6713 }
6714}
6715
6716function insertNonHydratedInstance(returnFiber, fiber) {
6717 fiber.effectTag |= Placement;
6718 {
6719 switch (returnFiber.tag) {
6720 case HostRoot:
6721 {
6722 var parentContainer = returnFiber.stateNode.containerInfo;
6723 switch (fiber.tag) {
6724 case HostComponent:
6725 var type = fiber.type;
6726 var props = fiber.pendingProps;
6727 didNotFindHydratableContainerInstance(parentContainer, type, props);
6728 break;
6729 case HostText:
6730 var text = fiber.pendingProps;
6731 didNotFindHydratableContainerTextInstance(parentContainer, text);
6732 break;
6733 case SuspenseComponent:
6734 didNotFindHydratableContainerSuspenseInstance(parentContainer);
6735 break;
6736 }
6737 break;
6738 }
6739 case HostComponent:
6740 {
6741 var parentType = returnFiber.type;
6742 var parentProps = returnFiber.memoizedProps;
6743 var parentInstance = returnFiber.stateNode;
6744 switch (fiber.tag) {
6745 case HostComponent:
6746 var _type = fiber.type;
6747 var _props = fiber.pendingProps;
6748 didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props);
6749 break;
6750 case HostText:
6751 var _text = fiber.pendingProps;
6752 didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text);
6753 break;
6754 case SuspenseComponent:
6755 didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance);
6756 break;
6757 }
6758 break;
6759 }
6760 default:
6761 return;
6762 }
6763 }
6764}
6765
6766function tryHydrate(fiber, nextInstance) {
6767 switch (fiber.tag) {
6768 case HostComponent:
6769 {
6770 var type = fiber.type;
6771 var props = fiber.pendingProps;
6772 var instance = canHydrateInstance(nextInstance, type, props);
6773 if (instance !== null) {
6774 fiber.stateNode = instance;
6775 return true;
6776 }
6777 return false;
6778 }
6779 case HostText:
6780 {
6781 var text = fiber.pendingProps;
6782 var textInstance = canHydrateTextInstance(nextInstance, text);
6783 if (textInstance !== null) {
6784 fiber.stateNode = textInstance;
6785 return true;
6786 }
6787 return false;
6788 }
6789 case SuspenseComponent:
6790 {
6791 if (enableSuspenseServerRenderer) {
6792 var suspenseInstance = canHydrateSuspenseInstance(nextInstance);
6793 if (suspenseInstance !== null) {
6794 // Downgrade the tag to a dehydrated component until we've hydrated it.
6795 fiber.tag = DehydratedSuspenseComponent;
6796 fiber.stateNode = suspenseInstance;
6797 return true;
6798 }
6799 }
6800 return false;
6801 }
6802 default:
6803 return false;
6804 }
6805}
6806
6807function tryToClaimNextHydratableInstance(fiber) {
6808 if (!isHydrating) {
6809 return;
6810 }
6811 var nextInstance = nextHydratableInstance;
6812 if (!nextInstance) {
6813 // Nothing to hydrate. Make it an insertion.
6814 insertNonHydratedInstance(hydrationParentFiber, fiber);
6815 isHydrating = false;
6816 hydrationParentFiber = fiber;
6817 return;
6818 }
6819 var firstAttemptedInstance = nextInstance;
6820 if (!tryHydrate(fiber, nextInstance)) {
6821 // If we can't hydrate this instance let's try the next one.
6822 // We use this as a heuristic. It's based on intuition and not data so it
6823 // might be flawed or unnecessary.
6824 nextInstance = getNextHydratableSibling(firstAttemptedInstance);
6825 if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
6826 // Nothing to hydrate. Make it an insertion.
6827 insertNonHydratedInstance(hydrationParentFiber, fiber);
6828 isHydrating = false;
6829 hydrationParentFiber = fiber;
6830 return;
6831 }
6832 // We matched the next one, we'll now assume that the first one was
6833 // superfluous and we'll delete it. Since we can't eagerly delete it
6834 // we'll have to schedule a deletion. To do that, this node needs a dummy
6835 // fiber associated with it.
6836 deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance);
6837 }
6838 hydrationParentFiber = fiber;
6839 nextHydratableInstance = getFirstHydratableChild(nextInstance);
6840}
6841
6842function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
6843 if (!supportsHydration) {
6844 invariant(false, 'Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
6845 }
6846
6847 var instance = fiber.stateNode;
6848 var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber);
6849 // TODO: Type this specific to this type of component.
6850 fiber.updateQueue = updatePayload;
6851 // If the update payload indicates that there is a change or if there
6852 // is a new ref we mark this as an update.
6853 if (updatePayload !== null) {
6854 return true;
6855 }
6856 return false;
6857}
6858
6859function prepareToHydrateHostTextInstance(fiber) {
6860 if (!supportsHydration) {
6861 invariant(false, 'Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
6862 }
6863
6864 var textInstance = fiber.stateNode;
6865 var textContent = fiber.memoizedProps;
6866 var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
6867 {
6868 if (shouldUpdate) {
6869 // We assume that prepareToHydrateHostTextInstance is called in a context where the
6870 // hydration parent is the parent host component of this host text.
6871 var returnFiber = hydrationParentFiber;
6872 if (returnFiber !== null) {
6873 switch (returnFiber.tag) {
6874 case HostRoot:
6875 {
6876 var parentContainer = returnFiber.stateNode.containerInfo;
6877 didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent);
6878 break;
6879 }
6880 case HostComponent:
6881 {
6882 var parentType = returnFiber.type;
6883 var parentProps = returnFiber.memoizedProps;
6884 var parentInstance = returnFiber.stateNode;
6885 didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent);
6886 break;
6887 }
6888 }
6889 }
6890 }
6891 }
6892 return shouldUpdate;
6893}
6894
6895function skipPastDehydratedSuspenseInstance(fiber) {
6896 if (!supportsHydration) {
6897 invariant(false, 'Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.');
6898 }
6899 var suspenseInstance = fiber.stateNode;
6900 !suspenseInstance ? invariant(false, 'Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.') : void 0;
6901 nextHydratableInstance = getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
6902}
6903
6904function popToNextHostParent(fiber) {
6905 var parent = fiber.return;
6906 while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== DehydratedSuspenseComponent) {
6907 parent = parent.return;
6908 }
6909 hydrationParentFiber = parent;
6910}
6911
6912function popHydrationState(fiber) {
6913 if (!supportsHydration) {
6914 return false;
6915 }
6916 if (fiber !== hydrationParentFiber) {
6917 // We're deeper than the current hydration context, inside an inserted
6918 // tree.
6919 return false;
6920 }
6921 if (!isHydrating) {
6922 // If we're not currently hydrating but we're in a hydration context, then
6923 // we were an insertion and now need to pop up reenter hydration of our
6924 // siblings.
6925 popToNextHostParent(fiber);
6926 isHydrating = true;
6927 return false;
6928 }
6929
6930 var type = fiber.type;
6931
6932 // If we have any remaining hydratable nodes, we need to delete them now.
6933 // We only do this deeper than head and body since they tend to have random
6934 // other nodes in them. We also ignore components with pure text content in
6935 // side of them.
6936 // TODO: Better heuristic.
6937 if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) {
6938 var nextInstance = nextHydratableInstance;
6939 while (nextInstance) {
6940 deleteHydratableInstance(fiber, nextInstance);
6941 nextInstance = getNextHydratableSibling(nextInstance);
6942 }
6943 }
6944
6945 popToNextHostParent(fiber);
6946 nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
6947 return true;
6948}
6949
6950function resetHydrationState() {
6951 if (!supportsHydration) {
6952 return;
6953 }
6954
6955 hydrationParentFiber = null;
6956 nextHydratableInstance = null;
6957 isHydrating = false;
6958}
6959
6960var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner;
6961
6962var didReceiveUpdate = false;
6963
6964var didWarnAboutBadClass = void 0;
6965var didWarnAboutContextTypeOnFunctionComponent = void 0;
6966var didWarnAboutGetDerivedStateOnFunctionComponent = void 0;
6967var didWarnAboutFunctionRefs = void 0;
6968var didWarnAboutReassigningProps = void 0;
6969
6970{
6971 didWarnAboutBadClass = {};
6972 didWarnAboutContextTypeOnFunctionComponent = {};
6973 didWarnAboutGetDerivedStateOnFunctionComponent = {};
6974 didWarnAboutFunctionRefs = {};
6975 didWarnAboutReassigningProps = false;
6976}
6977
6978function reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime) {
6979 if (current === null) {
6980 // If this is a fresh new component that hasn't been rendered yet, we
6981 // won't update its child set by applying minimal side-effects. Instead,
6982 // we will add them all to the child before it gets rendered. That means
6983 // we can optimize this reconciliation pass by not tracking side-effects.
6984 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
6985 } else {
6986 // If the current child is the same as the work in progress, it means that
6987 // we haven't yet started any work on these children. Therefore, we use
6988 // the clone algorithm to create a copy of all the current children.
6989
6990 // If we had any progressed work already, that is invalid at this point so
6991 // let's throw it out.
6992 workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren, renderExpirationTime);
6993 }
6994}
6995
6996function forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderExpirationTime) {
6997 // This function is fork of reconcileChildren. It's used in cases where we
6998 // want to reconcile without matching against the existing set. This has the
6999 // effect of all current children being unmounted; even if the type and key
7000 // are the same, the old child is unmounted and a new child is created.
7001 //
7002 // To do this, we're going to go through the reconcile algorithm twice. In
7003 // the first pass, we schedule a deletion for all the current children by
7004 // passing null.
7005 workInProgress.child = reconcileChildFibers(workInProgress, current.child, null, renderExpirationTime);
7006 // In the second pass, we mount the new children. The trick here is that we
7007 // pass null in place of where we usually pass the current child set. This has
7008 // the effect of remounting all children regardless of whether their their
7009 // identity matches.
7010 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
7011}
7012
7013function updateForwardRef(current, workInProgress, Component, nextProps, renderExpirationTime) {
7014 // TODO: current can be non-null here even if the component
7015 // hasn't yet mounted. This happens after the first render suspends.
7016 // We'll need to figure out if this is fine or can cause issues.
7017
7018 {
7019 if (workInProgress.type !== workInProgress.elementType) {
7020 // Lazy component props can't be validated in createElement
7021 // because they're only guaranteed to be resolved here.
7022 var innerPropTypes = Component.propTypes;
7023 if (innerPropTypes) {
7024 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
7025 'prop', getComponentName(Component), getCurrentFiberStackInDev);
7026 }
7027 }
7028 }
7029
7030 var render = Component.render;
7031 var ref = workInProgress.ref;
7032
7033 // The rest is a fork of updateFunctionComponent
7034 var nextChildren = void 0;
7035 prepareToReadContext(workInProgress, renderExpirationTime);
7036 {
7037 ReactCurrentOwner$2.current = workInProgress;
7038 setCurrentPhase('render');
7039 nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderExpirationTime);
7040 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
7041 // Only double-render components with Hooks
7042 if (workInProgress.memoizedState !== null) {
7043 nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderExpirationTime);
7044 }
7045 }
7046 setCurrentPhase(null);
7047 }
7048
7049 if (current !== null && !didReceiveUpdate) {
7050 bailoutHooks(current, workInProgress, renderExpirationTime);
7051 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
7052 }
7053
7054 // React DevTools reads this flag.
7055 workInProgress.effectTag |= PerformedWork;
7056 reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
7057 return workInProgress.child;
7058}
7059
7060function updateMemoComponent(current, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
7061 if (current === null) {
7062 var type = Component.type;
7063 if (isSimpleFunctionComponent(type) && Component.compare === null &&
7064 // SimpleMemoComponent codepath doesn't resolve outer props either.
7065 Component.defaultProps === undefined) {
7066 // If this is a plain function component without default props,
7067 // and with only the default shallow comparison, we upgrade it
7068 // to a SimpleMemoComponent to allow fast path updates.
7069 workInProgress.tag = SimpleMemoComponent;
7070 workInProgress.type = type;
7071 {
7072 validateFunctionComponentInDev(workInProgress, type);
7073 }
7074 return updateSimpleMemoComponent(current, workInProgress, type, nextProps, updateExpirationTime, renderExpirationTime);
7075 }
7076 {
7077 var innerPropTypes = type.propTypes;
7078 if (innerPropTypes) {
7079 // Inner memo component props aren't currently validated in createElement.
7080 // We could move it there, but we'd still need this for lazy code path.
7081 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
7082 'prop', getComponentName(type), getCurrentFiberStackInDev);
7083 }
7084 }
7085 var child = createFiberFromTypeAndProps(Component.type, null, nextProps, null, workInProgress.mode, renderExpirationTime);
7086 child.ref = workInProgress.ref;
7087 child.return = workInProgress;
7088 workInProgress.child = child;
7089 return child;
7090 }
7091 {
7092 var _type = Component.type;
7093 var _innerPropTypes = _type.propTypes;
7094 if (_innerPropTypes) {
7095 // Inner memo component props aren't currently validated in createElement.
7096 // We could move it there, but we'd still need this for lazy code path.
7097 checkPropTypes_1(_innerPropTypes, nextProps, // Resolved props
7098 'prop', getComponentName(_type), getCurrentFiberStackInDev);
7099 }
7100 }
7101 var currentChild = current.child; // This is always exactly one child
7102 if (updateExpirationTime < renderExpirationTime) {
7103 // This will be the props with resolved defaultProps,
7104 // unlike current.memoizedProps which will be the unresolved ones.
7105 var prevProps = currentChild.memoizedProps;
7106 // Default to shallow comparison
7107 var compare = Component.compare;
7108 compare = compare !== null ? compare : shallowEqual;
7109 if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) {
7110 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
7111 }
7112 }
7113 // React DevTools reads this flag.
7114 workInProgress.effectTag |= PerformedWork;
7115 var newChild = createWorkInProgress(currentChild, nextProps, renderExpirationTime);
7116 newChild.ref = workInProgress.ref;
7117 newChild.return = workInProgress;
7118 workInProgress.child = newChild;
7119 return newChild;
7120}
7121
7122function updateSimpleMemoComponent(current, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
7123 // TODO: current can be non-null here even if the component
7124 // hasn't yet mounted. This happens when the inner render suspends.
7125 // We'll need to figure out if this is fine or can cause issues.
7126
7127 {
7128 if (workInProgress.type !== workInProgress.elementType) {
7129 // Lazy component props can't be validated in createElement
7130 // because they're only guaranteed to be resolved here.
7131 var outerMemoType = workInProgress.elementType;
7132 if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
7133 // We warn when you define propTypes on lazy()
7134 // so let's just skip over it to find memo() outer wrapper.
7135 // Inner props for memo are validated later.
7136 outerMemoType = refineResolvedLazyComponent(outerMemoType);
7137 }
7138 var outerPropTypes = outerMemoType && outerMemoType.propTypes;
7139 if (outerPropTypes) {
7140 checkPropTypes_1(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
7141 'prop', getComponentName(outerMemoType), getCurrentFiberStackInDev);
7142 }
7143 // Inner propTypes will be validated in the function component path.
7144 }
7145 }
7146 if (current !== null) {
7147 var prevProps = current.memoizedProps;
7148 if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress.ref) {
7149 didReceiveUpdate = false;
7150 if (updateExpirationTime < renderExpirationTime) {
7151 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
7152 }
7153 }
7154 }
7155 return updateFunctionComponent(current, workInProgress, Component, nextProps, renderExpirationTime);
7156}
7157
7158function updateFragment(current, workInProgress, renderExpirationTime) {
7159 var nextChildren = workInProgress.pendingProps;
7160 reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
7161 return workInProgress.child;
7162}
7163
7164function updateMode(current, workInProgress, renderExpirationTime) {
7165 var nextChildren = workInProgress.pendingProps.children;
7166 reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
7167 return workInProgress.child;
7168}
7169
7170function updateProfiler(current, workInProgress, renderExpirationTime) {
7171 if (enableProfilerTimer) {
7172 workInProgress.effectTag |= Update;
7173 }
7174 var nextProps = workInProgress.pendingProps;
7175 var nextChildren = nextProps.children;
7176 reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
7177 return workInProgress.child;
7178}
7179
7180function markRef(current, workInProgress) {
7181 var ref = workInProgress.ref;
7182 if (current === null && ref !== null || current !== null && current.ref !== ref) {
7183 // Schedule a Ref effect
7184 workInProgress.effectTag |= Ref;
7185 }
7186}
7187
7188function updateFunctionComponent(current, workInProgress, Component, nextProps, renderExpirationTime) {
7189 {
7190 if (workInProgress.type !== workInProgress.elementType) {
7191 // Lazy component props can't be validated in createElement
7192 // because they're only guaranteed to be resolved here.
7193 var innerPropTypes = Component.propTypes;
7194 if (innerPropTypes) {
7195 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
7196 'prop', getComponentName(Component), getCurrentFiberStackInDev);
7197 }
7198 }
7199 }
7200
7201 var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
7202 var context = getMaskedContext(workInProgress, unmaskedContext);
7203
7204 var nextChildren = void 0;
7205 prepareToReadContext(workInProgress, renderExpirationTime);
7206 {
7207 ReactCurrentOwner$2.current = workInProgress;
7208 setCurrentPhase('render');
7209 nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderExpirationTime);
7210 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
7211 // Only double-render components with Hooks
7212 if (workInProgress.memoizedState !== null) {
7213 nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderExpirationTime);
7214 }
7215 }
7216 setCurrentPhase(null);
7217 }
7218
7219 if (current !== null && !didReceiveUpdate) {
7220 bailoutHooks(current, workInProgress, renderExpirationTime);
7221 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
7222 }
7223
7224 // React DevTools reads this flag.
7225 workInProgress.effectTag |= PerformedWork;
7226 reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
7227 return workInProgress.child;
7228}
7229
7230function updateClassComponent(current, workInProgress, Component, nextProps, renderExpirationTime) {
7231 {
7232 if (workInProgress.type !== workInProgress.elementType) {
7233 // Lazy component props can't be validated in createElement
7234 // because they're only guaranteed to be resolved here.
7235 var innerPropTypes = Component.propTypes;
7236 if (innerPropTypes) {
7237 checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
7238 'prop', getComponentName(Component), getCurrentFiberStackInDev);
7239 }
7240 }
7241 }
7242
7243 // Push context providers early to prevent context stack mismatches.
7244 // During mounting we don't know the child context yet as the instance doesn't exist.
7245 // We will invalidate the child context in finishClassComponent() right after rendering.
7246 var hasContext = void 0;
7247 if (isContextProvider(Component)) {
7248 hasContext = true;
7249 pushContextProvider(workInProgress);
7250 } else {
7251 hasContext = false;
7252 }
7253 prepareToReadContext(workInProgress, renderExpirationTime);
7254
7255 var instance = workInProgress.stateNode;
7256 var shouldUpdate = void 0;
7257 if (instance === null) {
7258 if (current !== null) {
7259 // An class component without an instance only mounts if it suspended
7260 // inside a non- concurrent tree, in an inconsistent state. We want to
7261 // tree it like a new mount, even though an empty version of it already
7262 // committed. Disconnect the alternate pointers.
7263 current.alternate = null;
7264 workInProgress.alternate = null;
7265 // Since this is conceptually a new fiber, schedule a Placement effect
7266 workInProgress.effectTag |= Placement;
7267 }
7268 // In the initial pass we might need to construct the instance.
7269 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
7270 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
7271 shouldUpdate = true;
7272 } else if (current === null) {
7273 // In a resume, we'll already have an instance we can reuse.
7274 shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
7275 } else {
7276 shouldUpdate = updateClassInstance(current, workInProgress, Component, nextProps, renderExpirationTime);
7277 }
7278 var nextUnitOfWork = finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime);
7279 {
7280 var inst = workInProgress.stateNode;
7281 if (inst.props !== nextProps) {
7282 !didWarnAboutReassigningProps ? warning$1(false, 'It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentName(workInProgress.type) || 'a component') : void 0;
7283 didWarnAboutReassigningProps = true;
7284 }
7285 }
7286 return nextUnitOfWork;
7287}
7288
7289function finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime) {
7290 // Refs should update even if shouldComponentUpdate returns false
7291 markRef(current, workInProgress);
7292
7293 var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;
7294
7295 if (!shouldUpdate && !didCaptureError) {
7296 // Context providers should defer to sCU for rendering
7297 if (hasContext) {
7298 invalidateContextProvider(workInProgress, Component, false);
7299 }
7300
7301 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
7302 }
7303
7304 var instance = workInProgress.stateNode;
7305
7306 // Rerender
7307 ReactCurrentOwner$2.current = workInProgress;
7308 var nextChildren = void 0;
7309 if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
7310 // If we captured an error, but getDerivedStateFrom catch is not defined,
7311 // unmount all the children. componentDidCatch will schedule an update to
7312 // re-render a fallback. This is temporary until we migrate everyone to
7313 // the new API.
7314 // TODO: Warn in a future release.
7315 nextChildren = null;
7316
7317 if (enableProfilerTimer) {
7318 stopProfilerTimerIfRunning(workInProgress);
7319 }
7320 } else {
7321 {
7322 setCurrentPhase('render');
7323 nextChildren = instance.render();
7324 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
7325 instance.render();
7326 }
7327 setCurrentPhase(null);
7328 }
7329 }
7330
7331 // React DevTools reads this flag.
7332 workInProgress.effectTag |= PerformedWork;
7333 if (current !== null && didCaptureError) {
7334 // If we're recovering from an error, reconcile without reusing any of
7335 // the existing children. Conceptually, the normal children and the children
7336 // that are shown on error are two different sets, so we shouldn't reuse
7337 // normal children even if their identities match.
7338 forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderExpirationTime);
7339 } else {
7340 reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
7341 }
7342
7343 // Memoize state using the values we just used to render.
7344 // TODO: Restructure so we never read values from the instance.
7345 workInProgress.memoizedState = instance.state;
7346
7347 // The context might have changed so we need to recalculate it.
7348 if (hasContext) {
7349 invalidateContextProvider(workInProgress, Component, true);
7350 }
7351
7352 return workInProgress.child;
7353}
7354
7355function pushHostRootContext(workInProgress) {
7356 var root = workInProgress.stateNode;
7357 if (root.pendingContext) {
7358 pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
7359 } else if (root.context) {
7360 // Should always be set
7361 pushTopLevelContextObject(workInProgress, root.context, false);
7362 }
7363 pushHostContainer(workInProgress, root.containerInfo);
7364}
7365
7366function updateHostRoot(current, workInProgress, renderExpirationTime) {
7367 pushHostRootContext(workInProgress);
7368 var updateQueue = workInProgress.updateQueue;
7369 !(updateQueue !== null) ? invariant(false, 'If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue.') : void 0;
7370 var nextProps = workInProgress.pendingProps;
7371 var prevState = workInProgress.memoizedState;
7372 var prevChildren = prevState !== null ? prevState.element : null;
7373 processUpdateQueue(workInProgress, updateQueue, nextProps, null, renderExpirationTime);
7374 var nextState = workInProgress.memoizedState;
7375 // Caution: React DevTools currently depends on this property
7376 // being called "element".
7377 var nextChildren = nextState.element;
7378 if (nextChildren === prevChildren) {
7379 // If the state is the same as before, that's a bailout because we had
7380 // no work that expires at this time.
7381 resetHydrationState();
7382 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
7383 }
7384 var root = workInProgress.stateNode;
7385 if ((current === null || current.child === null) && root.hydrate && enterHydrationState(workInProgress)) {
7386 // If we don't have any current children this might be the first pass.
7387 // We always try to hydrate. If this isn't a hydration pass there won't
7388 // be any children to hydrate which is effectively the same thing as
7389 // not hydrating.
7390
7391 // This is a bit of a hack. We track the host root as a placement to
7392 // know that we're currently in a mounting state. That way isMounted
7393 // works as expected. We must reset this before committing.
7394 // TODO: Delete this when we delete isMounted and findDOMNode.
7395 workInProgress.effectTag |= Placement;
7396
7397 // Ensure that children mount into this root without tracking
7398 // side-effects. This ensures that we don't store Placement effects on
7399 // nodes that will be hydrated.
7400 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
7401 } else {
7402 // Otherwise reset hydration state in case we aborted and resumed another
7403 // root.
7404 reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
7405 resetHydrationState();
7406 }
7407 return workInProgress.child;
7408}
7409
7410function updateHostComponent(current, workInProgress, renderExpirationTime) {
7411 pushHostContext(workInProgress);
7412
7413 if (current === null) {
7414 tryToClaimNextHydratableInstance(workInProgress);
7415 }
7416
7417 var type = workInProgress.type;
7418 var nextProps = workInProgress.pendingProps;
7419 var prevProps = current !== null ? current.memoizedProps : null;
7420
7421 var nextChildren = nextProps.children;
7422 var isDirectTextChild = shouldSetTextContent(type, nextProps);
7423
7424 if (isDirectTextChild) {
7425 // We special case a direct text child of a host node. This is a common
7426 // case. We won't handle it as a reified child. We will instead handle
7427 // this in the host environment that also have access to this prop. That
7428 // avoids allocating another HostText fiber and traversing it.
7429 nextChildren = null;
7430 } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
7431 // If we're switching from a direct text child to a normal child, or to
7432 // empty, we need to schedule the text content to be reset.
7433 workInProgress.effectTag |= ContentReset;
7434 }
7435
7436 markRef(current, workInProgress);
7437
7438 // Check the host config to see if the children are offscreen/hidden.
7439 if (renderExpirationTime !== Never && workInProgress.mode & ConcurrentMode && shouldDeprioritizeSubtree(type, nextProps)) {
7440 // Schedule this fiber to re-render at offscreen priority. Then bailout.
7441 workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
7442 return null;
7443 }
7444
7445 reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
7446 return workInProgress.child;
7447}
7448
7449function updateHostText(current, workInProgress) {
7450 if (current === null) {
7451 tryToClaimNextHydratableInstance(workInProgress);
7452 }
7453 // Nothing to do here. This is terminal. We'll do the completion step
7454 // immediately after.
7455 return null;
7456}
7457
7458function mountLazyComponent(_current, workInProgress, elementType, updateExpirationTime, renderExpirationTime) {
7459 if (_current !== null) {
7460 // An lazy component only mounts if it suspended inside a non-
7461 // concurrent tree, in an inconsistent state. We want to treat it like
7462 // a new mount, even though an empty version of it already committed.
7463 // Disconnect the alternate pointers.
7464 _current.alternate = null;
7465 workInProgress.alternate = null;
7466 // Since this is conceptually a new fiber, schedule a Placement effect
7467 workInProgress.effectTag |= Placement;
7468 }
7469
7470 var props = workInProgress.pendingProps;
7471 // We can't start a User Timing measurement with correct label yet.
7472 // Cancel and resume right after we know the tag.
7473 cancelWorkTimer(workInProgress);
7474 var Component = readLazyComponentType(elementType);
7475 // Store the unwrapped component in the type.
7476 workInProgress.type = Component;
7477 var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
7478 startWorkTimer(workInProgress);
7479 var resolvedProps = resolveDefaultProps(Component, props);
7480 var child = void 0;
7481 switch (resolvedTag) {
7482 case FunctionComponent:
7483 {
7484 {
7485 validateFunctionComponentInDev(workInProgress, Component);
7486 }
7487 child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
7488 break;
7489 }
7490 case ClassComponent:
7491 {
7492 child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
7493 break;
7494 }
7495 case ForwardRef:
7496 {
7497 child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderExpirationTime);
7498 break;
7499 }
7500 case MemoComponent:
7501 {
7502 {
7503 if (workInProgress.type !== workInProgress.elementType) {
7504 var outerPropTypes = Component.propTypes;
7505 if (outerPropTypes) {
7506 checkPropTypes_1(outerPropTypes, resolvedProps, // Resolved for outer only
7507 'prop', getComponentName(Component), getCurrentFiberStackInDev);
7508 }
7509 }
7510 }
7511 child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
7512 updateExpirationTime, renderExpirationTime);
7513 break;
7514 }
7515 default:
7516 {
7517 var hint = '';
7518 {
7519 if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
7520 hint = ' Did you wrap a component in React.lazy() more than once?';
7521 }
7522 }
7523 // This message intentionally doesn't mention ForwardRef or MemoComponent
7524 // because the fact that it's a separate type of work is an
7525 // implementation detail.
7526 invariant(false, 'Element type is invalid. Received a promise that resolves to: %s. Lazy element type must resolve to a class or function.%s', Component, hint);
7527 }
7528 }
7529 return child;
7530}
7531
7532function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderExpirationTime) {
7533 if (_current !== null) {
7534 // An incomplete component only mounts if it suspended inside a non-
7535 // concurrent tree, in an inconsistent state. We want to treat it like
7536 // a new mount, even though an empty version of it already committed.
7537 // Disconnect the alternate pointers.
7538 _current.alternate = null;
7539 workInProgress.alternate = null;
7540 // Since this is conceptually a new fiber, schedule a Placement effect
7541 workInProgress.effectTag |= Placement;
7542 }
7543
7544 // Promote the fiber to a class and try rendering again.
7545 workInProgress.tag = ClassComponent;
7546
7547 // The rest of this function is a fork of `updateClassComponent`
7548
7549 // Push context providers early to prevent context stack mismatches.
7550 // During mounting we don't know the child context yet as the instance doesn't exist.
7551 // We will invalidate the child context in finishClassComponent() right after rendering.
7552 var hasContext = void 0;
7553 if (isContextProvider(Component)) {
7554 hasContext = true;
7555 pushContextProvider(workInProgress);
7556 } else {
7557 hasContext = false;
7558 }
7559 prepareToReadContext(workInProgress, renderExpirationTime);
7560
7561 constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
7562 mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
7563
7564 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
7565}
7566
7567function mountIndeterminateComponent(_current, workInProgress, Component, renderExpirationTime) {
7568 if (_current !== null) {
7569 // An indeterminate component only mounts if it suspended inside a non-
7570 // concurrent tree, in an inconsistent state. We want to treat it like
7571 // a new mount, even though an empty version of it already committed.
7572 // Disconnect the alternate pointers.
7573 _current.alternate = null;
7574 workInProgress.alternate = null;
7575 // Since this is conceptually a new fiber, schedule a Placement effect
7576 workInProgress.effectTag |= Placement;
7577 }
7578
7579 var props = workInProgress.pendingProps;
7580 var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
7581 var context = getMaskedContext(workInProgress, unmaskedContext);
7582
7583 prepareToReadContext(workInProgress, renderExpirationTime);
7584
7585 var value = void 0;
7586
7587 {
7588 if (Component.prototype && typeof Component.prototype.render === 'function') {
7589 var componentName = getComponentName(Component) || 'Unknown';
7590
7591 if (!didWarnAboutBadClass[componentName]) {
7592 warningWithoutStack$1(false, "The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);
7593 didWarnAboutBadClass[componentName] = true;
7594 }
7595 }
7596
7597 if (workInProgress.mode & StrictMode) {
7598 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
7599 }
7600
7601 ReactCurrentOwner$2.current = workInProgress;
7602 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
7603 }
7604 // React DevTools reads this flag.
7605 workInProgress.effectTag |= PerformedWork;
7606
7607 if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
7608 // Proceed under the assumption that this is a class instance
7609 workInProgress.tag = ClassComponent;
7610
7611 // Throw out any hooks that were used.
7612 resetHooks();
7613
7614 // Push context providers early to prevent context stack mismatches.
7615 // During mounting we don't know the child context yet as the instance doesn't exist.
7616 // We will invalidate the child context in finishClassComponent() right after rendering.
7617 var hasContext = false;
7618 if (isContextProvider(Component)) {
7619 hasContext = true;
7620 pushContextProvider(workInProgress);
7621 } else {
7622 hasContext = false;
7623 }
7624
7625 workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
7626
7627 var getDerivedStateFromProps = Component.getDerivedStateFromProps;
7628 if (typeof getDerivedStateFromProps === 'function') {
7629 applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);
7630 }
7631
7632 adoptClassInstance(workInProgress, value);
7633 mountClassInstance(workInProgress, Component, props, renderExpirationTime);
7634 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
7635 } else {
7636 // Proceed under the assumption that this is a function component
7637 workInProgress.tag = FunctionComponent;
7638 {
7639 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
7640 // Only double-render components with Hooks
7641 if (workInProgress.memoizedState !== null) {
7642 value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
7643 }
7644 }
7645 }
7646 reconcileChildren(null, workInProgress, value, renderExpirationTime);
7647 {
7648 validateFunctionComponentInDev(workInProgress, Component);
7649 }
7650 return workInProgress.child;
7651 }
7652}
7653
7654function validateFunctionComponentInDev(workInProgress, Component) {
7655 if (Component) {
7656 !!Component.childContextTypes ? warningWithoutStack$1(false, '%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component') : void 0;
7657 }
7658 if (workInProgress.ref !== null) {
7659 var info = '';
7660 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
7661 if (ownerName) {
7662 info += '\n\nCheck the render method of `' + ownerName + '`.';
7663 }
7664
7665 var warningKey = ownerName || workInProgress._debugID || '';
7666 var debugSource = workInProgress._debugSource;
7667 if (debugSource) {
7668 warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
7669 }
7670 if (!didWarnAboutFunctionRefs[warningKey]) {
7671 didWarnAboutFunctionRefs[warningKey] = true;
7672 warning$1(false, 'Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info);
7673 }
7674 }
7675
7676 if (typeof Component.getDerivedStateFromProps === 'function') {
7677 var componentName = getComponentName(Component) || 'Unknown';
7678
7679 if (!didWarnAboutGetDerivedStateOnFunctionComponent[componentName]) {
7680 warningWithoutStack$1(false, '%s: Function components do not support getDerivedStateFromProps.', componentName);
7681 didWarnAboutGetDerivedStateOnFunctionComponent[componentName] = true;
7682 }
7683 }
7684
7685 if (typeof Component.contextType === 'object' && Component.contextType !== null) {
7686 var _componentName = getComponentName(Component) || 'Unknown';
7687
7688 if (!didWarnAboutContextTypeOnFunctionComponent[_componentName]) {
7689 warningWithoutStack$1(false, '%s: Function components do not support contextType.', _componentName);
7690 didWarnAboutContextTypeOnFunctionComponent[_componentName] = true;
7691 }
7692 }
7693}
7694
7695function updateSuspenseComponent(current, workInProgress, renderExpirationTime) {
7696 var mode = workInProgress.mode;
7697 var nextProps = workInProgress.pendingProps;
7698
7699 // We should attempt to render the primary children unless this boundary
7700 // already suspended during this render (`alreadyCaptured` is true).
7701 var nextState = workInProgress.memoizedState;
7702
7703 var nextDidTimeout = void 0;
7704 if ((workInProgress.effectTag & DidCapture) === NoEffect) {
7705 // This is the first attempt.
7706 nextState = null;
7707 nextDidTimeout = false;
7708 } else {
7709 // Something in this boundary's subtree already suspended. Switch to
7710 // rendering the fallback children.
7711 nextState = {
7712 timedOutAt: nextState !== null ? nextState.timedOutAt : NoWork
7713 };
7714 nextDidTimeout = true;
7715 workInProgress.effectTag &= ~DidCapture;
7716 }
7717
7718 // This next part is a bit confusing. If the children timeout, we switch to
7719 // showing the fallback children in place of the "primary" children.
7720 // However, we don't want to delete the primary children because then their
7721 // state will be lost (both the React state and the host state, e.g.
7722 // uncontrolled form inputs). Instead we keep them mounted and hide them.
7723 // Both the fallback children AND the primary children are rendered at the
7724 // same time. Once the primary children are un-suspended, we can delete
7725 // the fallback children — don't need to preserve their state.
7726 //
7727 // The two sets of children are siblings in the host environment, but
7728 // semantically, for purposes of reconciliation, they are two separate sets.
7729 // So we store them using two fragment fibers.
7730 //
7731 // However, we want to avoid allocating extra fibers for every placeholder.
7732 // They're only necessary when the children time out, because that's the
7733 // only time when both sets are mounted.
7734 //
7735 // So, the extra fragment fibers are only used if the children time out.
7736 // Otherwise, we render the primary children directly. This requires some
7737 // custom reconciliation logic to preserve the state of the primary
7738 // children. It's essentially a very basic form of re-parenting.
7739
7740 // `child` points to the child fiber. In the normal case, this is the first
7741 // fiber of the primary children set. In the timed-out case, it's a
7742 // a fragment fiber containing the primary children.
7743 var child = void 0;
7744 // `next` points to the next fiber React should render. In the normal case,
7745 // it's the same as `child`: the first fiber of the primary children set.
7746 // In the timed-out case, it's a fragment fiber containing the *fallback*
7747 // children -- we skip over the primary children entirely.
7748 var next = void 0;
7749 if (current === null) {
7750 if (enableSuspenseServerRenderer) {
7751 // If we're currently hydrating, try to hydrate this boundary.
7752 // But only if this has a fallback.
7753 if (nextProps.fallback !== undefined) {
7754 tryToClaimNextHydratableInstance(workInProgress);
7755 // This could've changed the tag if this was a dehydrated suspense component.
7756 if (workInProgress.tag === DehydratedSuspenseComponent) {
7757 return updateDehydratedSuspenseComponent(null, workInProgress, renderExpirationTime);
7758 }
7759 }
7760 }
7761
7762 // This is the initial mount. This branch is pretty simple because there's
7763 // no previous state that needs to be preserved.
7764 if (nextDidTimeout) {
7765 // Mount separate fragments for primary and fallback children.
7766 var nextFallbackChildren = nextProps.fallback;
7767 var primaryChildFragment = createFiberFromFragment(null, mode, NoWork, null);
7768
7769 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
7770 // Outside of concurrent mode, we commit the effects from the
7771 var progressedState = workInProgress.memoizedState;
7772 var progressedPrimaryChild = progressedState !== null ? workInProgress.child.child : workInProgress.child;
7773 primaryChildFragment.child = progressedPrimaryChild;
7774 }
7775
7776 var fallbackChildFragment = createFiberFromFragment(nextFallbackChildren, mode, renderExpirationTime, null);
7777 primaryChildFragment.sibling = fallbackChildFragment;
7778 child = primaryChildFragment;
7779 // Skip the primary children, and continue working on the
7780 // fallback children.
7781 next = fallbackChildFragment;
7782 child.return = next.return = workInProgress;
7783 } else {
7784 // Mount the primary children without an intermediate fragment fiber.
7785 var nextPrimaryChildren = nextProps.children;
7786 child = next = mountChildFibers(workInProgress, null, nextPrimaryChildren, renderExpirationTime);
7787 }
7788 } else {
7789 // This is an update. This branch is more complicated because we need to
7790 // ensure the state of the primary children is preserved.
7791 var prevState = current.memoizedState;
7792 var prevDidTimeout = prevState !== null;
7793 if (prevDidTimeout) {
7794 // The current tree already timed out. That means each child set is
7795 var currentPrimaryChildFragment = current.child;
7796 var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
7797 if (nextDidTimeout) {
7798 // Still timed out. Reuse the current primary children by cloning
7799 // its fragment. We're going to skip over these entirely.
7800 var _nextFallbackChildren = nextProps.fallback;
7801 var _primaryChildFragment = createWorkInProgress(currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps, NoWork);
7802
7803 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
7804 // Outside of concurrent mode, we commit the effects from the
7805 var _progressedState = workInProgress.memoizedState;
7806 var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child;
7807 if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) {
7808 _primaryChildFragment.child = _progressedPrimaryChild;
7809 }
7810 }
7811
7812 // Because primaryChildFragment is a new fiber that we're inserting as the
7813 // parent of a new tree, we need to set its treeBaseDuration.
7814 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
7815 // treeBaseDuration is the sum of all the child tree base durations.
7816 var treeBaseDuration = 0;
7817 var hiddenChild = _primaryChildFragment.child;
7818 while (hiddenChild !== null) {
7819 treeBaseDuration += hiddenChild.treeBaseDuration;
7820 hiddenChild = hiddenChild.sibling;
7821 }
7822 _primaryChildFragment.treeBaseDuration = treeBaseDuration;
7823 }
7824
7825 // Clone the fallback child fragment, too. These we'll continue
7826 // working on.
7827 var _fallbackChildFragment = _primaryChildFragment.sibling = createWorkInProgress(currentFallbackChildFragment, _nextFallbackChildren, currentFallbackChildFragment.expirationTime);
7828 child = _primaryChildFragment;
7829 _primaryChildFragment.childExpirationTime = NoWork;
7830 // Skip the primary children, and continue working on the
7831 // fallback children.
7832 next = _fallbackChildFragment;
7833 child.return = next.return = workInProgress;
7834 } else {
7835 // No longer suspended. Switch back to showing the primary children,
7836 // and remove the intermediate fragment fiber.
7837 var _nextPrimaryChildren = nextProps.children;
7838 var currentPrimaryChild = currentPrimaryChildFragment.child;
7839 var primaryChild = reconcileChildFibers(workInProgress, currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime);
7840
7841 // If this render doesn't suspend, we need to delete the fallback
7842 // children. Wait until the complete phase, after we've confirmed the
7843 // fallback is no longer needed.
7844 // TODO: Would it be better to store the fallback fragment on
7845 // the stateNode?
7846
7847 // Continue rendering the children, like we normally do.
7848 child = next = primaryChild;
7849 }
7850 } else {
7851 // The current tree has not already timed out. That means the primary
7852 // children are not wrapped in a fragment fiber.
7853 var _currentPrimaryChild = current.child;
7854 if (nextDidTimeout) {
7855 // Timed out. Wrap the children in a fragment fiber to keep them
7856 // separate from the fallback children.
7857 var _nextFallbackChildren2 = nextProps.fallback;
7858 var _primaryChildFragment2 = createFiberFromFragment(
7859 // It shouldn't matter what the pending props are because we aren't
7860 // going to render this fragment.
7861 null, mode, NoWork, null);
7862 _primaryChildFragment2.child = _currentPrimaryChild;
7863
7864 // Even though we're creating a new fiber, there are no new children,
7865 // because we're reusing an already mounted tree. So we don't need to
7866 // schedule a placement.
7867 // primaryChildFragment.effectTag |= Placement;
7868
7869 if ((workInProgress.mode & ConcurrentMode) === NoContext) {
7870 // Outside of concurrent mode, we commit the effects from the
7871 var _progressedState2 = workInProgress.memoizedState;
7872 var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child;
7873 _primaryChildFragment2.child = _progressedPrimaryChild2;
7874 }
7875
7876 // Because primaryChildFragment is a new fiber that we're inserting as the
7877 // parent of a new tree, we need to set its treeBaseDuration.
7878 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
7879 // treeBaseDuration is the sum of all the child tree base durations.
7880 var _treeBaseDuration = 0;
7881 var _hiddenChild = _primaryChildFragment2.child;
7882 while (_hiddenChild !== null) {
7883 _treeBaseDuration += _hiddenChild.treeBaseDuration;
7884 _hiddenChild = _hiddenChild.sibling;
7885 }
7886 _primaryChildFragment2.treeBaseDuration = _treeBaseDuration;
7887 }
7888
7889 // Create a fragment from the fallback children, too.
7890 var _fallbackChildFragment2 = _primaryChildFragment2.sibling = createFiberFromFragment(_nextFallbackChildren2, mode, renderExpirationTime, null);
7891 _fallbackChildFragment2.effectTag |= Placement;
7892 child = _primaryChildFragment2;
7893 _primaryChildFragment2.childExpirationTime = NoWork;
7894 // Skip the primary children, and continue working on the
7895 // fallback children.
7896 next = _fallbackChildFragment2;
7897 child.return = next.return = workInProgress;
7898 } else {
7899 // Still haven't timed out. Continue rendering the children, like we
7900 // normally do.
7901 var _nextPrimaryChildren2 = nextProps.children;
7902 next = child = reconcileChildFibers(workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime);
7903 }
7904 }
7905 workInProgress.stateNode = current.stateNode;
7906 }
7907
7908 workInProgress.memoizedState = nextState;
7909 workInProgress.child = child;
7910 return next;
7911}
7912
7913function updateDehydratedSuspenseComponent(current, workInProgress, renderExpirationTime) {
7914 if (current === null) {
7915 // During the first pass, we'll bail out and not drill into the children.
7916 // Instead, we'll leave the content in place and try to hydrate it later.
7917 workInProgress.expirationTime = Never;
7918 return null;
7919 }
7920 // We use childExpirationTime to indicate that a child might depend on context, so if
7921 // any context has changed, we need to treat is as if the input might have changed.
7922 var hasContextChanged$$1 = current.childExpirationTime >= renderExpirationTime;
7923 if (didReceiveUpdate || hasContextChanged$$1) {
7924 // This boundary has changed since the first render. This means that we are now unable to
7925 // hydrate it. We might still be able to hydrate it using an earlier expiration time but
7926 // during this render we can't. Instead, we're going to delete the whole subtree and
7927 // instead inject a new real Suspense boundary to take its place, which may render content
7928 // or fallback. The real Suspense boundary will suspend for a while so we have some time
7929 // to ensure it can produce real content, but all state and pending events will be lost.
7930
7931 // Detach from the current dehydrated boundary.
7932 current.alternate = null;
7933 workInProgress.alternate = null;
7934
7935 // Insert a deletion in the effect list.
7936 var returnFiber = workInProgress.return;
7937 !(returnFiber !== null) ? invariant(false, 'Suspense boundaries are never on the root. This is probably a bug in React.') : void 0;
7938 var last = returnFiber.lastEffect;
7939 if (last !== null) {
7940 last.nextEffect = current;
7941 returnFiber.lastEffect = current;
7942 } else {
7943 returnFiber.firstEffect = returnFiber.lastEffect = current;
7944 }
7945 current.nextEffect = null;
7946 current.effectTag = Deletion;
7947
7948 // Upgrade this work in progress to a real Suspense component.
7949 workInProgress.tag = SuspenseComponent;
7950 workInProgress.stateNode = null;
7951 workInProgress.memoizedState = null;
7952 // This is now an insertion.
7953 workInProgress.effectTag |= Placement;
7954 // Retry as a real Suspense component.
7955 return updateSuspenseComponent(null, workInProgress, renderExpirationTime);
7956 }
7957 if ((workInProgress.effectTag & DidCapture) === NoEffect) {
7958 // This is the first attempt.
7959 reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress);
7960 var nextProps = workInProgress.pendingProps;
7961 var nextChildren = nextProps.children;
7962 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
7963 return workInProgress.child;
7964 } else {
7965 // Something suspended. Leave the existing children in place.
7966 // TODO: In non-concurrent mode, should we commit the nodes we have hydrated so far?
7967 workInProgress.child = null;
7968 return null;
7969 }
7970}
7971
7972function updatePortalComponent(current, workInProgress, renderExpirationTime) {
7973 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
7974 var nextChildren = workInProgress.pendingProps;
7975 if (current === null) {
7976 // Portals are special because we don't append the children during mount
7977 // but at commit. Therefore we need to track insertions which the normal
7978 // flow doesn't do during mount. This doesn't happen at the root because
7979 // the root always starts with a "current" with a null child.
7980 // TODO: Consider unifying this with how the root works.
7981 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
7982 } else {
7983 reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
7984 }
7985 return workInProgress.child;
7986}
7987
7988function updateContextProvider(current, workInProgress, renderExpirationTime) {
7989 var providerType = workInProgress.type;
7990 var context = providerType._context;
7991
7992 var newProps = workInProgress.pendingProps;
7993 var oldProps = workInProgress.memoizedProps;
7994
7995 var newValue = newProps.value;
7996
7997 {
7998 var providerPropTypes = workInProgress.type.propTypes;
7999
8000 if (providerPropTypes) {
8001 checkPropTypes_1(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackInDev);
8002 }
8003 }
8004
8005 pushProvider(workInProgress, newValue);
8006
8007 if (oldProps !== null) {
8008 var oldValue = oldProps.value;
8009 var changedBits = calculateChangedBits(context, newValue, oldValue);
8010 if (changedBits === 0) {
8011 // No change. Bailout early if children are the same.
8012 if (oldProps.children === newProps.children && !hasContextChanged()) {
8013 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
8014 }
8015 } else {
8016 // The context value changed. Search for matching consumers and schedule
8017 // them to update.
8018 propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);
8019 }
8020 }
8021
8022 var newChildren = newProps.children;
8023 reconcileChildren(current, workInProgress, newChildren, renderExpirationTime);
8024 return workInProgress.child;
8025}
8026
8027var hasWarnedAboutUsingContextAsConsumer = false;
8028
8029function updateContextConsumer(current, workInProgress, renderExpirationTime) {
8030 var context = workInProgress.type;
8031 // The logic below for Context differs depending on PROD or DEV mode. In
8032 // DEV mode, we create a separate object for Context.Consumer that acts
8033 // like a proxy to Context. This proxy object adds unnecessary code in PROD
8034 // so we use the old behaviour (Context.Consumer references Context) to
8035 // reduce size and overhead. The separate object references context via
8036 // a property called "_context", which also gives us the ability to check
8037 // in DEV mode if this property exists or not and warn if it does not.
8038 {
8039 if (context._context === undefined) {
8040 // This may be because it's a Context (rather than a Consumer).
8041 // Or it may be because it's older React where they're the same thing.
8042 // We only want to warn if we're sure it's a new React.
8043 if (context !== context.Consumer) {
8044 if (!hasWarnedAboutUsingContextAsConsumer) {
8045 hasWarnedAboutUsingContextAsConsumer = true;
8046 warning$1(false, 'Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
8047 }
8048 }
8049 } else {
8050 context = context._context;
8051 }
8052 }
8053 var newProps = workInProgress.pendingProps;
8054 var render = newProps.children;
8055
8056 {
8057 !(typeof render === 'function') ? warningWithoutStack$1(false, 'A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.') : void 0;
8058 }
8059
8060 prepareToReadContext(workInProgress, renderExpirationTime);
8061 var newValue = readContext(context, newProps.unstable_observedBits);
8062 var newChildren = void 0;
8063 {
8064 ReactCurrentOwner$2.current = workInProgress;
8065 setCurrentPhase('render');
8066 newChildren = render(newValue);
8067 setCurrentPhase(null);
8068 }
8069
8070 // React DevTools reads this flag.
8071 workInProgress.effectTag |= PerformedWork;
8072 reconcileChildren(current, workInProgress, newChildren, renderExpirationTime);
8073 return workInProgress.child;
8074}
8075
8076function markWorkInProgressReceivedUpdate() {
8077 didReceiveUpdate = true;
8078}
8079
8080function bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime) {
8081 cancelWorkTimer(workInProgress);
8082
8083 if (current !== null) {
8084 // Reuse previous context list
8085 workInProgress.contextDependencies = current.contextDependencies;
8086 }
8087
8088 if (enableProfilerTimer) {
8089 // Don't update "base" render times for bailouts.
8090 stopProfilerTimerIfRunning(workInProgress);
8091 }
8092
8093 // Check if the children have any pending work.
8094 var childExpirationTime = workInProgress.childExpirationTime;
8095 if (childExpirationTime < renderExpirationTime) {
8096 // The children don't have any work either. We can skip them.
8097 // TODO: Once we add back resuming, we should check if the children are
8098 // a work-in-progress set. If so, we need to transfer their effects.
8099 return null;
8100 } else {
8101 // This fiber doesn't have work, but its subtree does. Clone the child
8102 // fibers and continue.
8103 cloneChildFibers(current, workInProgress);
8104 return workInProgress.child;
8105 }
8106}
8107
8108function beginWork(current, workInProgress, renderExpirationTime) {
8109 var updateExpirationTime = workInProgress.expirationTime;
8110
8111 if (current !== null) {
8112 var oldProps = current.memoizedProps;
8113 var newProps = workInProgress.pendingProps;
8114
8115 if (oldProps !== newProps || hasContextChanged()) {
8116 // If props or context changed, mark the fiber as having performed work.
8117 // This may be unset if the props are determined to be equal later (memo).
8118 didReceiveUpdate = true;
8119 } else if (updateExpirationTime < renderExpirationTime) {
8120 didReceiveUpdate = false;
8121 // This fiber does not have any pending work. Bailout without entering
8122 // the begin phase. There's still some bookkeeping we that needs to be done
8123 // in this optimized path, mostly pushing stuff onto the stack.
8124 switch (workInProgress.tag) {
8125 case HostRoot:
8126 pushHostRootContext(workInProgress);
8127 resetHydrationState();
8128 break;
8129 case HostComponent:
8130 pushHostContext(workInProgress);
8131 break;
8132 case ClassComponent:
8133 {
8134 var Component = workInProgress.type;
8135 if (isContextProvider(Component)) {
8136 pushContextProvider(workInProgress);
8137 }
8138 break;
8139 }
8140 case HostPortal:
8141 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
8142 break;
8143 case ContextProvider:
8144 {
8145 var newValue = workInProgress.memoizedProps.value;
8146 pushProvider(workInProgress, newValue);
8147 break;
8148 }
8149 case Profiler:
8150 if (enableProfilerTimer) {
8151 workInProgress.effectTag |= Update;
8152 }
8153 break;
8154 case SuspenseComponent:
8155 {
8156 var state = workInProgress.memoizedState;
8157 var didTimeout = state !== null;
8158 if (didTimeout) {
8159 // If this boundary is currently timed out, we need to decide
8160 // whether to retry the primary children, or to skip over it and
8161 // go straight to the fallback. Check the priority of the primary
8162 var primaryChildFragment = workInProgress.child;
8163 var primaryChildExpirationTime = primaryChildFragment.childExpirationTime;
8164 if (primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime) {
8165 // The primary children have pending work. Use the normal path
8166 // to attempt to render the primary children again.
8167 return updateSuspenseComponent(current, workInProgress, renderExpirationTime);
8168 } else {
8169 // The primary children do not have pending work with sufficient
8170 // priority. Bailout.
8171 var child = bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
8172 if (child !== null) {
8173 // The fallback children have pending work. Skip over the
8174 // primary children and work on the fallback.
8175 return child.sibling;
8176 } else {
8177 return null;
8178 }
8179 }
8180 }
8181 break;
8182 }
8183 case DehydratedSuspenseComponent:
8184 {
8185 if (enableSuspenseServerRenderer) {
8186 // We know that this component will suspend again because if it has
8187 // been unsuspended it has committed as a regular Suspense component.
8188 // If it needs to be retried, it should have work scheduled on it.
8189 workInProgress.effectTag |= DidCapture;
8190 break;
8191 }
8192 }
8193 }
8194 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
8195 }
8196 } else {
8197 didReceiveUpdate = false;
8198 }
8199
8200 // Before entering the begin phase, clear the expiration time.
8201 workInProgress.expirationTime = NoWork;
8202
8203 switch (workInProgress.tag) {
8204 case IndeterminateComponent:
8205 {
8206 var elementType = workInProgress.elementType;
8207 return mountIndeterminateComponent(current, workInProgress, elementType, renderExpirationTime);
8208 }
8209 case LazyComponent:
8210 {
8211 var _elementType = workInProgress.elementType;
8212 return mountLazyComponent(current, workInProgress, _elementType, updateExpirationTime, renderExpirationTime);
8213 }
8214 case FunctionComponent:
8215 {
8216 var _Component = workInProgress.type;
8217 var unresolvedProps = workInProgress.pendingProps;
8218 var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
8219 return updateFunctionComponent(current, workInProgress, _Component, resolvedProps, renderExpirationTime);
8220 }
8221 case ClassComponent:
8222 {
8223 var _Component2 = workInProgress.type;
8224 var _unresolvedProps = workInProgress.pendingProps;
8225 var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);
8226 return updateClassComponent(current, workInProgress, _Component2, _resolvedProps, renderExpirationTime);
8227 }
8228 case HostRoot:
8229 return updateHostRoot(current, workInProgress, renderExpirationTime);
8230 case HostComponent:
8231 return updateHostComponent(current, workInProgress, renderExpirationTime);
8232 case HostText:
8233 return updateHostText(current, workInProgress);
8234 case SuspenseComponent:
8235 return updateSuspenseComponent(current, workInProgress, renderExpirationTime);
8236 case HostPortal:
8237 return updatePortalComponent(current, workInProgress, renderExpirationTime);
8238 case ForwardRef:
8239 {
8240 var type = workInProgress.type;
8241 var _unresolvedProps2 = workInProgress.pendingProps;
8242 var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
8243 return updateForwardRef(current, workInProgress, type, _resolvedProps2, renderExpirationTime);
8244 }
8245 case Fragment:
8246 return updateFragment(current, workInProgress, renderExpirationTime);
8247 case Mode:
8248 return updateMode(current, workInProgress, renderExpirationTime);
8249 case Profiler:
8250 return updateProfiler(current, workInProgress, renderExpirationTime);
8251 case ContextProvider:
8252 return updateContextProvider(current, workInProgress, renderExpirationTime);
8253 case ContextConsumer:
8254 return updateContextConsumer(current, workInProgress, renderExpirationTime);
8255 case MemoComponent:
8256 {
8257 var _type2 = workInProgress.type;
8258 var _unresolvedProps3 = workInProgress.pendingProps;
8259 // Resolve outer props first, then resolve inner props.
8260 var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
8261 {
8262 if (workInProgress.type !== workInProgress.elementType) {
8263 var outerPropTypes = _type2.propTypes;
8264 if (outerPropTypes) {
8265 checkPropTypes_1(outerPropTypes, _resolvedProps3, // Resolved for outer only
8266 'prop', getComponentName(_type2), getCurrentFiberStackInDev);
8267 }
8268 }
8269 }
8270 _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
8271 return updateMemoComponent(current, workInProgress, _type2, _resolvedProps3, updateExpirationTime, renderExpirationTime);
8272 }
8273 case SimpleMemoComponent:
8274 {
8275 return updateSimpleMemoComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps, updateExpirationTime, renderExpirationTime);
8276 }
8277 case IncompleteClassComponent:
8278 {
8279 var _Component3 = workInProgress.type;
8280 var _unresolvedProps4 = workInProgress.pendingProps;
8281 var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);
8282 return mountIncompleteClassComponent(current, workInProgress, _Component3, _resolvedProps4, renderExpirationTime);
8283 }
8284 case DehydratedSuspenseComponent:
8285 {
8286 if (enableSuspenseServerRenderer) {
8287 return updateDehydratedSuspenseComponent(current, workInProgress, renderExpirationTime);
8288 }
8289 break;
8290 }
8291 }
8292 invariant(false, 'Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
8293}
8294
8295var valueCursor = createCursor(null);
8296
8297var rendererSigil = void 0;
8298{
8299 // Use this to detect multiple renderers using the same context
8300 rendererSigil = {};
8301}
8302
8303var currentlyRenderingFiber = null;
8304var lastContextDependency = null;
8305var lastContextWithAllBitsObserved = null;
8306
8307var isDisallowedContextReadInDEV = false;
8308
8309function resetContextDependences() {
8310 // This is called right before React yields execution, to ensure `readContext`
8311 // cannot be called outside the render phase.
8312 currentlyRenderingFiber = null;
8313 lastContextDependency = null;
8314 lastContextWithAllBitsObserved = null;
8315 {
8316 isDisallowedContextReadInDEV = false;
8317 }
8318}
8319
8320function enterDisallowedContextReadInDEV() {
8321 {
8322 isDisallowedContextReadInDEV = true;
8323 }
8324}
8325
8326function exitDisallowedContextReadInDEV() {
8327 {
8328 isDisallowedContextReadInDEV = false;
8329 }
8330}
8331
8332function pushProvider(providerFiber, nextValue) {
8333 var context = providerFiber.type._context;
8334
8335 if (isPrimaryRenderer) {
8336 push(valueCursor, context._currentValue, providerFiber);
8337
8338 context._currentValue = nextValue;
8339 {
8340 !(context._currentRenderer === undefined || context._currentRenderer === null || context._currentRenderer === rendererSigil) ? warningWithoutStack$1(false, 'Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.') : void 0;
8341 context._currentRenderer = rendererSigil;
8342 }
8343 } else {
8344 push(valueCursor, context._currentValue2, providerFiber);
8345
8346 context._currentValue2 = nextValue;
8347 {
8348 !(context._currentRenderer2 === undefined || context._currentRenderer2 === null || context._currentRenderer2 === rendererSigil) ? warningWithoutStack$1(false, 'Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.') : void 0;
8349 context._currentRenderer2 = rendererSigil;
8350 }
8351 }
8352}
8353
8354function popProvider(providerFiber) {
8355 var currentValue = valueCursor.current;
8356
8357 pop(valueCursor, providerFiber);
8358
8359 var context = providerFiber.type._context;
8360 if (isPrimaryRenderer) {
8361 context._currentValue = currentValue;
8362 } else {
8363 context._currentValue2 = currentValue;
8364 }
8365}
8366
8367function calculateChangedBits(context, newValue, oldValue) {
8368 if (is(oldValue, newValue)) {
8369 // No change
8370 return 0;
8371 } else {
8372 var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : maxSigned31BitInt;
8373
8374 {
8375 !((changedBits & maxSigned31BitInt) === changedBits) ? warning$1(false, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits) : void 0;
8376 }
8377 return changedBits | 0;
8378 }
8379}
8380
8381function scheduleWorkOnParentPath(parent, renderExpirationTime) {
8382 // Update the child expiration time of all the ancestors, including
8383 // the alternates.
8384 var node = parent;
8385 while (node !== null) {
8386 var alternate = node.alternate;
8387 if (node.childExpirationTime < renderExpirationTime) {
8388 node.childExpirationTime = renderExpirationTime;
8389 if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
8390 alternate.childExpirationTime = renderExpirationTime;
8391 }
8392 } else if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
8393 alternate.childExpirationTime = renderExpirationTime;
8394 } else {
8395 // Neither alternate was updated, which means the rest of the
8396 // ancestor path already has sufficient priority.
8397 break;
8398 }
8399 node = node.return;
8400 }
8401}
8402
8403function propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) {
8404 var fiber = workInProgress.child;
8405 if (fiber !== null) {
8406 // Set the return pointer of the child to the work-in-progress fiber.
8407 fiber.return = workInProgress;
8408 }
8409 while (fiber !== null) {
8410 var nextFiber = void 0;
8411
8412 // Visit this fiber.
8413 var list = fiber.contextDependencies;
8414 if (list !== null) {
8415 nextFiber = fiber.child;
8416
8417 var dependency = list.first;
8418 while (dependency !== null) {
8419 // Check if the context matches.
8420 if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {
8421 // Match! Schedule an update on this fiber.
8422
8423 if (fiber.tag === ClassComponent) {
8424 // Schedule a force update on the work-in-progress.
8425 var update = createUpdate(renderExpirationTime);
8426 update.tag = ForceUpdate;
8427 // TODO: Because we don't have a work-in-progress, this will add the
8428 // update to the current fiber, too, which means it will persist even if
8429 // this render is thrown away. Since it's a race condition, not sure it's
8430 // worth fixing.
8431 enqueueUpdate(fiber, update);
8432 }
8433
8434 if (fiber.expirationTime < renderExpirationTime) {
8435 fiber.expirationTime = renderExpirationTime;
8436 }
8437 var alternate = fiber.alternate;
8438 if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
8439 alternate.expirationTime = renderExpirationTime;
8440 }
8441
8442 scheduleWorkOnParentPath(fiber.return, renderExpirationTime);
8443
8444 // Mark the expiration time on the list, too.
8445 if (list.expirationTime < renderExpirationTime) {
8446 list.expirationTime = renderExpirationTime;
8447 }
8448
8449 // Since we already found a match, we can stop traversing the
8450 // dependency list.
8451 break;
8452 }
8453 dependency = dependency.next;
8454 }
8455 } else if (fiber.tag === ContextProvider) {
8456 // Don't scan deeper if this is a matching provider
8457 nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
8458 } else if (enableSuspenseServerRenderer && fiber.tag === DehydratedSuspenseComponent) {
8459 // If a dehydrated suspense component is in this subtree, we don't know
8460 // if it will have any context consumers in it. The best we can do is
8461 // mark it as having updates on its children.
8462 if (fiber.expirationTime < renderExpirationTime) {
8463 fiber.expirationTime = renderExpirationTime;
8464 }
8465 var _alternate = fiber.alternate;
8466 if (_alternate !== null && _alternate.expirationTime < renderExpirationTime) {
8467 _alternate.expirationTime = renderExpirationTime;
8468 }
8469 // This is intentionally passing this fiber as the parent
8470 // because we want to schedule this fiber as having work
8471 // on its children. We'll use the childExpirationTime on
8472 // this fiber to indicate that a context has changed.
8473 scheduleWorkOnParentPath(fiber, renderExpirationTime);
8474 nextFiber = fiber.sibling;
8475 } else {
8476 // Traverse down.
8477 nextFiber = fiber.child;
8478 }
8479
8480 if (nextFiber !== null) {
8481 // Set the return pointer of the child to the work-in-progress fiber.
8482 nextFiber.return = fiber;
8483 } else {
8484 // No child. Traverse to next sibling.
8485 nextFiber = fiber;
8486 while (nextFiber !== null) {
8487 if (nextFiber === workInProgress) {
8488 // We're back to the root of this subtree. Exit.
8489 nextFiber = null;
8490 break;
8491 }
8492 var sibling = nextFiber.sibling;
8493 if (sibling !== null) {
8494 // Set the return pointer of the sibling to the work-in-progress fiber.
8495 sibling.return = nextFiber.return;
8496 nextFiber = sibling;
8497 break;
8498 }
8499 // No more siblings. Traverse up.
8500 nextFiber = nextFiber.return;
8501 }
8502 }
8503 fiber = nextFiber;
8504 }
8505}
8506
8507function prepareToReadContext(workInProgress, renderExpirationTime) {
8508 currentlyRenderingFiber = workInProgress;
8509 lastContextDependency = null;
8510 lastContextWithAllBitsObserved = null;
8511
8512 var currentDependencies = workInProgress.contextDependencies;
8513 if (currentDependencies !== null && currentDependencies.expirationTime >= renderExpirationTime) {
8514 // Context list has a pending update. Mark that this fiber performed work.
8515 markWorkInProgressReceivedUpdate();
8516 }
8517
8518 // Reset the work-in-progress list
8519 workInProgress.contextDependencies = null;
8520}
8521
8522function readContext(context, observedBits) {
8523 {
8524 // This warning would fire if you read context inside a Hook like useMemo.
8525 // Unlike the class check below, it's not enforced in production for perf.
8526 !!isDisallowedContextReadInDEV ? warning$1(false, 'Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().') : void 0;
8527 }
8528
8529 if (lastContextWithAllBitsObserved === context) {
8530 // Nothing to do. We already observe everything in this context.
8531 } else if (observedBits === false || observedBits === 0) {
8532 // Do not observe any updates.
8533 } else {
8534 var resolvedObservedBits = void 0; // Avoid deopting on observable arguments or heterogeneous types.
8535 if (typeof observedBits !== 'number' || observedBits === maxSigned31BitInt) {
8536 // Observe all updates.
8537 lastContextWithAllBitsObserved = context;
8538 resolvedObservedBits = maxSigned31BitInt;
8539 } else {
8540 resolvedObservedBits = observedBits;
8541 }
8542
8543 var contextItem = {
8544 context: context,
8545 observedBits: resolvedObservedBits,
8546 next: null
8547 };
8548
8549 if (lastContextDependency === null) {
8550 !(currentlyRenderingFiber !== null) ? invariant(false, 'Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo().') : void 0;
8551
8552 // This is the first dependency for this component. Create a new list.
8553 lastContextDependency = contextItem;
8554 currentlyRenderingFiber.contextDependencies = {
8555 first: contextItem,
8556 expirationTime: NoWork
8557 };
8558 } else {
8559 // Append a new context item.
8560 lastContextDependency = lastContextDependency.next = contextItem;
8561 }
8562 }
8563 return isPrimaryRenderer ? context._currentValue : context._currentValue2;
8564}
8565
8566// UpdateQueue is a linked list of prioritized updates.
8567//
8568// Like fibers, update queues come in pairs: a current queue, which represents
8569// the visible state of the screen, and a work-in-progress queue, which can be
8570// mutated and processed asynchronously before it is committed — a form of
8571// double buffering. If a work-in-progress render is discarded before finishing,
8572// we create a new work-in-progress by cloning the current queue.
8573//
8574// Both queues share a persistent, singly-linked list structure. To schedule an
8575// update, we append it to the end of both queues. Each queue maintains a
8576// pointer to first update in the persistent list that hasn't been processed.
8577// The work-in-progress pointer always has a position equal to or greater than
8578// the current queue, since we always work on that one. The current queue's
8579// pointer is only updated during the commit phase, when we swap in the
8580// work-in-progress.
8581//
8582// For example:
8583//
8584// Current pointer: A - B - C - D - E - F
8585// Work-in-progress pointer: D - E - F
8586// ^
8587// The work-in-progress queue has
8588// processed more updates than current.
8589//
8590// The reason we append to both queues is because otherwise we might drop
8591// updates without ever processing them. For example, if we only add updates to
8592// the work-in-progress queue, some updates could be lost whenever a work-in
8593// -progress render restarts by cloning from current. Similarly, if we only add
8594// updates to the current queue, the updates will be lost whenever an already
8595// in-progress queue commits and swaps with the current queue. However, by
8596// adding to both queues, we guarantee that the update will be part of the next
8597// work-in-progress. (And because the work-in-progress queue becomes the
8598// current queue once it commits, there's no danger of applying the same
8599// update twice.)
8600//
8601// Prioritization
8602// --------------
8603//
8604// Updates are not sorted by priority, but by insertion; new updates are always
8605// appended to the end of the list.
8606//
8607// The priority is still important, though. When processing the update queue
8608// during the render phase, only the updates with sufficient priority are
8609// included in the result. If we skip an update because it has insufficient
8610// priority, it remains in the queue to be processed later, during a lower
8611// priority render. Crucially, all updates subsequent to a skipped update also
8612// remain in the queue *regardless of their priority*. That means high priority
8613// updates are sometimes processed twice, at two separate priorities. We also
8614// keep track of a base state, that represents the state before the first
8615// update in the queue is applied.
8616//
8617// For example:
8618//
8619// Given a base state of '', and the following queue of updates
8620//
8621// A1 - B2 - C1 - D2
8622//
8623// where the number indicates the priority, and the update is applied to the
8624// previous state by appending a letter, React will process these updates as
8625// two separate renders, one per distinct priority level:
8626//
8627// First render, at priority 1:
8628// Base state: ''
8629// Updates: [A1, C1]
8630// Result state: 'AC'
8631//
8632// Second render, at priority 2:
8633// Base state: 'A' <- The base state does not include C1,
8634// because B2 was skipped.
8635// Updates: [B2, C1, D2] <- C1 was rebased on top of B2
8636// Result state: 'ABCD'
8637//
8638// Because we process updates in insertion order, and rebase high priority
8639// updates when preceding updates are skipped, the final result is deterministic
8640// regardless of priority. Intermediate state may vary according to system
8641// resources, but the final state is always the same.
8642
8643var UpdateState = 0;
8644var ReplaceState = 1;
8645var ForceUpdate = 2;
8646var CaptureUpdate = 3;
8647
8648// Global state that is reset at the beginning of calling `processUpdateQueue`.
8649// It should only be read right after calling `processUpdateQueue`, via
8650// `checkHasForceUpdateAfterProcessing`.
8651var hasForceUpdate = false;
8652
8653var didWarnUpdateInsideUpdate = void 0;
8654var currentlyProcessingQueue = void 0;
8655var resetCurrentlyProcessingQueue = void 0;
8656{
8657 didWarnUpdateInsideUpdate = false;
8658 currentlyProcessingQueue = null;
8659 resetCurrentlyProcessingQueue = function () {
8660 currentlyProcessingQueue = null;
8661 };
8662}
8663
8664function createUpdateQueue(baseState) {
8665 var queue = {
8666 baseState: baseState,
8667 firstUpdate: null,
8668 lastUpdate: null,
8669 firstCapturedUpdate: null,
8670 lastCapturedUpdate: null,
8671 firstEffect: null,
8672 lastEffect: null,
8673 firstCapturedEffect: null,
8674 lastCapturedEffect: null
8675 };
8676 return queue;
8677}
8678
8679function cloneUpdateQueue(currentQueue) {
8680 var queue = {
8681 baseState: currentQueue.baseState,
8682 firstUpdate: currentQueue.firstUpdate,
8683 lastUpdate: currentQueue.lastUpdate,
8684
8685 // TODO: With resuming, if we bail out and resuse the child tree, we should
8686 // keep these effects.
8687 firstCapturedUpdate: null,
8688 lastCapturedUpdate: null,
8689
8690 firstEffect: null,
8691 lastEffect: null,
8692
8693 firstCapturedEffect: null,
8694 lastCapturedEffect: null
8695 };
8696 return queue;
8697}
8698
8699function createUpdate(expirationTime) {
8700 return {
8701 expirationTime: expirationTime,
8702
8703 tag: UpdateState,
8704 payload: null,
8705 callback: null,
8706
8707 next: null,
8708 nextEffect: null
8709 };
8710}
8711
8712function appendUpdateToQueue(queue, update) {
8713 // Append the update to the end of the list.
8714 if (queue.lastUpdate === null) {
8715 // Queue is empty
8716 queue.firstUpdate = queue.lastUpdate = update;
8717 } else {
8718 queue.lastUpdate.next = update;
8719 queue.lastUpdate = update;
8720 }
8721}
8722
8723function enqueueUpdate(fiber, update) {
8724 // Update queues are created lazily.
8725 var alternate = fiber.alternate;
8726 var queue1 = void 0;
8727 var queue2 = void 0;
8728 if (alternate === null) {
8729 // There's only one fiber.
8730 queue1 = fiber.updateQueue;
8731 queue2 = null;
8732 if (queue1 === null) {
8733 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
8734 }
8735 } else {
8736 // There are two owners.
8737 queue1 = fiber.updateQueue;
8738 queue2 = alternate.updateQueue;
8739 if (queue1 === null) {
8740 if (queue2 === null) {
8741 // Neither fiber has an update queue. Create new ones.
8742 queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState);
8743 queue2 = alternate.updateQueue = createUpdateQueue(alternate.memoizedState);
8744 } else {
8745 // Only one fiber has an update queue. Clone to create a new one.
8746 queue1 = fiber.updateQueue = cloneUpdateQueue(queue2);
8747 }
8748 } else {
8749 if (queue2 === null) {
8750 // Only one fiber has an update queue. Clone to create a new one.
8751 queue2 = alternate.updateQueue = cloneUpdateQueue(queue1);
8752 } else {
8753 // Both owners have an update queue.
8754 }
8755 }
8756 }
8757 if (queue2 === null || queue1 === queue2) {
8758 // There's only a single queue.
8759 appendUpdateToQueue(queue1, update);
8760 } else {
8761 // There are two queues. We need to append the update to both queues,
8762 // while accounting for the persistent structure of the list — we don't
8763 // want the same update to be added multiple times.
8764 if (queue1.lastUpdate === null || queue2.lastUpdate === null) {
8765 // One of the queues is not empty. We must add the update to both queues.
8766 appendUpdateToQueue(queue1, update);
8767 appendUpdateToQueue(queue2, update);
8768 } else {
8769 // Both queues are non-empty. The last update is the same in both lists,
8770 // because of structural sharing. So, only append to one of the lists.
8771 appendUpdateToQueue(queue1, update);
8772 // But we still need to update the `lastUpdate` pointer of queue2.
8773 queue2.lastUpdate = update;
8774 }
8775 }
8776
8777 {
8778 if (fiber.tag === ClassComponent && (currentlyProcessingQueue === queue1 || queue2 !== null && currentlyProcessingQueue === queue2) && !didWarnUpdateInsideUpdate) {
8779 warningWithoutStack$1(false, 'An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.');
8780 didWarnUpdateInsideUpdate = true;
8781 }
8782 }
8783}
8784
8785function enqueueCapturedUpdate(workInProgress, update) {
8786 // Captured updates go into a separate list, and only on the work-in-
8787 // progress queue.
8788 var workInProgressQueue = workInProgress.updateQueue;
8789 if (workInProgressQueue === null) {
8790 workInProgressQueue = workInProgress.updateQueue = createUpdateQueue(workInProgress.memoizedState);
8791 } else {
8792 // TODO: I put this here rather than createWorkInProgress so that we don't
8793 // clone the queue unnecessarily. There's probably a better way to
8794 // structure this.
8795 workInProgressQueue = ensureWorkInProgressQueueIsAClone(workInProgress, workInProgressQueue);
8796 }
8797
8798 // Append the update to the end of the list.
8799 if (workInProgressQueue.lastCapturedUpdate === null) {
8800 // This is the first render phase update
8801 workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update;
8802 } else {
8803 workInProgressQueue.lastCapturedUpdate.next = update;
8804 workInProgressQueue.lastCapturedUpdate = update;
8805 }
8806}
8807
8808function ensureWorkInProgressQueueIsAClone(workInProgress, queue) {
8809 var current = workInProgress.alternate;
8810 if (current !== null) {
8811 // If the work-in-progress queue is equal to the current queue,
8812 // we need to clone it first.
8813 if (queue === current.updateQueue) {
8814 queue = workInProgress.updateQueue = cloneUpdateQueue(queue);
8815 }
8816 }
8817 return queue;
8818}
8819
8820function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
8821 switch (update.tag) {
8822 case ReplaceState:
8823 {
8824 var _payload = update.payload;
8825 if (typeof _payload === 'function') {
8826 // Updater function
8827 {
8828 enterDisallowedContextReadInDEV();
8829 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
8830 _payload.call(instance, prevState, nextProps);
8831 }
8832 }
8833 var nextState = _payload.call(instance, prevState, nextProps);
8834 {
8835 exitDisallowedContextReadInDEV();
8836 }
8837 return nextState;
8838 }
8839 // State object
8840 return _payload;
8841 }
8842 case CaptureUpdate:
8843 {
8844 workInProgress.effectTag = workInProgress.effectTag & ~ShouldCapture | DidCapture;
8845 }
8846 // Intentional fallthrough
8847 case UpdateState:
8848 {
8849 var _payload2 = update.payload;
8850 var partialState = void 0;
8851 if (typeof _payload2 === 'function') {
8852 // Updater function
8853 {
8854 enterDisallowedContextReadInDEV();
8855 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
8856 _payload2.call(instance, prevState, nextProps);
8857 }
8858 }
8859 partialState = _payload2.call(instance, prevState, nextProps);
8860 {
8861 exitDisallowedContextReadInDEV();
8862 }
8863 } else {
8864 // Partial state object
8865 partialState = _payload2;
8866 }
8867 if (partialState === null || partialState === undefined) {
8868 // Null and undefined are treated as no-ops.
8869 return prevState;
8870 }
8871 // Merge the partial state and the previous state.
8872 return _assign({}, prevState, partialState);
8873 }
8874 case ForceUpdate:
8875 {
8876 hasForceUpdate = true;
8877 return prevState;
8878 }
8879 }
8880 return prevState;
8881}
8882
8883function processUpdateQueue(workInProgress, queue, props, instance, renderExpirationTime) {
8884 hasForceUpdate = false;
8885
8886 queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue);
8887
8888 {
8889 currentlyProcessingQueue = queue;
8890 }
8891
8892 // These values may change as we process the queue.
8893 var newBaseState = queue.baseState;
8894 var newFirstUpdate = null;
8895 var newExpirationTime = NoWork;
8896
8897 // Iterate through the list of updates to compute the result.
8898 var update = queue.firstUpdate;
8899 var resultState = newBaseState;
8900 while (update !== null) {
8901 var updateExpirationTime = update.expirationTime;
8902 if (updateExpirationTime < renderExpirationTime) {
8903 // This update does not have sufficient priority. Skip it.
8904 if (newFirstUpdate === null) {
8905 // This is the first skipped update. It will be the first update in
8906 // the new list.
8907 newFirstUpdate = update;
8908 // Since this is the first update that was skipped, the current result
8909 // is the new base state.
8910 newBaseState = resultState;
8911 }
8912 // Since this update will remain in the list, update the remaining
8913 // expiration time.
8914 if (newExpirationTime < updateExpirationTime) {
8915 newExpirationTime = updateExpirationTime;
8916 }
8917 } else {
8918 // This update does have sufficient priority. Process it and compute
8919 // a new result.
8920 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
8921 var _callback = update.callback;
8922 if (_callback !== null) {
8923 workInProgress.effectTag |= Callback;
8924 // Set this to null, in case it was mutated during an aborted render.
8925 update.nextEffect = null;
8926 if (queue.lastEffect === null) {
8927 queue.firstEffect = queue.lastEffect = update;
8928 } else {
8929 queue.lastEffect.nextEffect = update;
8930 queue.lastEffect = update;
8931 }
8932 }
8933 }
8934 // Continue to the next update.
8935 update = update.next;
8936 }
8937
8938 // Separately, iterate though the list of captured updates.
8939 var newFirstCapturedUpdate = null;
8940 update = queue.firstCapturedUpdate;
8941 while (update !== null) {
8942 var _updateExpirationTime = update.expirationTime;
8943 if (_updateExpirationTime < renderExpirationTime) {
8944 // This update does not have sufficient priority. Skip it.
8945 if (newFirstCapturedUpdate === null) {
8946 // This is the first skipped captured update. It will be the first
8947 // update in the new list.
8948 newFirstCapturedUpdate = update;
8949 // If this is the first update that was skipped, the current result is
8950 // the new base state.
8951 if (newFirstUpdate === null) {
8952 newBaseState = resultState;
8953 }
8954 }
8955 // Since this update will remain in the list, update the remaining
8956 // expiration time.
8957 if (newExpirationTime < _updateExpirationTime) {
8958 newExpirationTime = _updateExpirationTime;
8959 }
8960 } else {
8961 // This update does have sufficient priority. Process it and compute
8962 // a new result.
8963 resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance);
8964 var _callback2 = update.callback;
8965 if (_callback2 !== null) {
8966 workInProgress.effectTag |= Callback;
8967 // Set this to null, in case it was mutated during an aborted render.
8968 update.nextEffect = null;
8969 if (queue.lastCapturedEffect === null) {
8970 queue.firstCapturedEffect = queue.lastCapturedEffect = update;
8971 } else {
8972 queue.lastCapturedEffect.nextEffect = update;
8973 queue.lastCapturedEffect = update;
8974 }
8975 }
8976 }
8977 update = update.next;
8978 }
8979
8980 if (newFirstUpdate === null) {
8981 queue.lastUpdate = null;
8982 }
8983 if (newFirstCapturedUpdate === null) {
8984 queue.lastCapturedUpdate = null;
8985 } else {
8986 workInProgress.effectTag |= Callback;
8987 }
8988 if (newFirstUpdate === null && newFirstCapturedUpdate === null) {
8989 // We processed every update, without skipping. That means the new base
8990 // state is the same as the result state.
8991 newBaseState = resultState;
8992 }
8993
8994 queue.baseState = newBaseState;
8995 queue.firstUpdate = newFirstUpdate;
8996 queue.firstCapturedUpdate = newFirstCapturedUpdate;
8997
8998 // Set the remaining expiration time to be whatever is remaining in the queue.
8999 // This should be fine because the only two other things that contribute to
9000 // expiration time are props and context. We're already in the middle of the
9001 // begin phase by the time we start processing the queue, so we've already
9002 // dealt with the props. Context in components that specify
9003 // shouldComponentUpdate is tricky; but we'll have to account for
9004 // that regardless.
9005 workInProgress.expirationTime = newExpirationTime;
9006 workInProgress.memoizedState = resultState;
9007
9008 {
9009 currentlyProcessingQueue = null;
9010 }
9011}
9012
9013function callCallback(callback, context) {
9014 !(typeof callback === 'function') ? invariant(false, 'Invalid argument passed as callback. Expected a function. Instead received: %s', callback) : void 0;
9015 callback.call(context);
9016}
9017
9018function resetHasForceUpdateBeforeProcessing() {
9019 hasForceUpdate = false;
9020}
9021
9022function checkHasForceUpdateAfterProcessing() {
9023 return hasForceUpdate;
9024}
9025
9026function commitUpdateQueue(finishedWork, finishedQueue, instance, renderExpirationTime) {
9027 // If the finished render included captured updates, and there are still
9028 // lower priority updates left over, we need to keep the captured updates
9029 // in the queue so that they are rebased and not dropped once we process the
9030 // queue again at the lower priority.
9031 if (finishedQueue.firstCapturedUpdate !== null) {
9032 // Join the captured update list to the end of the normal list.
9033 if (finishedQueue.lastUpdate !== null) {
9034 finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate;
9035 finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate;
9036 }
9037 // Clear the list of captured updates.
9038 finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null;
9039 }
9040
9041 // Commit the effects
9042 commitUpdateEffects(finishedQueue.firstEffect, instance);
9043 finishedQueue.firstEffect = finishedQueue.lastEffect = null;
9044
9045 commitUpdateEffects(finishedQueue.firstCapturedEffect, instance);
9046 finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null;
9047}
9048
9049function commitUpdateEffects(effect, instance) {
9050 while (effect !== null) {
9051 var _callback3 = effect.callback;
9052 if (_callback3 !== null) {
9053 effect.callback = null;
9054 callCallback(_callback3, instance);
9055 }
9056 effect = effect.nextEffect;
9057 }
9058}
9059
9060function createCapturedValue(value, source) {
9061 // If the value is an error, call this function immediately after it is thrown
9062 // so the stack is accurate.
9063 return {
9064 value: value,
9065 source: source,
9066 stack: getStackByFiberInDevAndProd(source)
9067 };
9068}
9069
9070function markUpdate(workInProgress) {
9071 // Tag the fiber with an update effect. This turns a Placement into
9072 // a PlacementAndUpdate.
9073 workInProgress.effectTag |= Update;
9074}
9075
9076function markRef$1(workInProgress) {
9077 workInProgress.effectTag |= Ref;
9078}
9079
9080var appendAllChildren = void 0;
9081var updateHostContainer = void 0;
9082var updateHostComponent$1 = void 0;
9083var updateHostText$1 = void 0;
9084if (supportsMutation) {
9085 // Mutation mode
9086
9087 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
9088 // We only have the top Fiber that was created but we need recurse down its
9089 // children to find all the terminal nodes.
9090 var node = workInProgress.child;
9091 while (node !== null) {
9092 if (node.tag === HostComponent || node.tag === HostText) {
9093 appendInitialChild(parent, node.stateNode);
9094 } else if (node.tag === HostPortal) {
9095 // If we have a portal child, then we don't want to traverse
9096 // down its children. Instead, we'll get insertions from each child in
9097 // the portal directly.
9098 } else if (node.child !== null) {
9099 node.child.return = node;
9100 node = node.child;
9101 continue;
9102 }
9103 if (node === workInProgress) {
9104 return;
9105 }
9106 while (node.sibling === null) {
9107 if (node.return === null || node.return === workInProgress) {
9108 return;
9109 }
9110 node = node.return;
9111 }
9112 node.sibling.return = node.return;
9113 node = node.sibling;
9114 }
9115 };
9116
9117 updateHostContainer = function (workInProgress) {
9118 // Noop
9119 };
9120 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
9121 // If we have an alternate, that means this is an update and we need to
9122 // schedule a side-effect to do the updates.
9123 var oldProps = current.memoizedProps;
9124 if (oldProps === newProps) {
9125 // In mutation mode, this is sufficient for a bailout because
9126 // we won't touch this node even if children changed.
9127 return;
9128 }
9129
9130 // If we get updated because one of our children updated, we don't
9131 // have newProps so we'll have to reuse them.
9132 // TODO: Split the update API as separate for the props vs. children.
9133 // Even better would be if children weren't special cased at all tho.
9134 var instance = workInProgress.stateNode;
9135 var currentHostContext = getHostContext();
9136 // TODO: Experiencing an error where oldProps is null. Suggests a host
9137 // component is hitting the resume path. Figure out why. Possibly
9138 // related to `hidden`.
9139 var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
9140 // TODO: Type this specific to this type of component.
9141 workInProgress.updateQueue = updatePayload;
9142 // If the update payload indicates that there is a change or if there
9143 // is a new ref we mark this as an update. All the work is done in commitWork.
9144 if (updatePayload) {
9145 markUpdate(workInProgress);
9146 }
9147 };
9148 updateHostText$1 = function (current, workInProgress, oldText, newText) {
9149 // If the text differs, mark it as an update. All the work in done in commitWork.
9150 if (oldText !== newText) {
9151 markUpdate(workInProgress);
9152 }
9153 };
9154} else if (supportsPersistence) {
9155 // Persistent host tree mode
9156
9157 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
9158 // We only have the top Fiber that was created but we need recurse down its
9159 // children to find all the terminal nodes.
9160 var node = workInProgress.child;
9161 while (node !== null) {
9162 // eslint-disable-next-line no-labels
9163 branches: if (node.tag === HostComponent) {
9164 var instance = node.stateNode;
9165 if (needsVisibilityToggle) {
9166 var props = node.memoizedProps;
9167 var type = node.type;
9168 if (isHidden) {
9169 // This child is inside a timed out tree. Hide it.
9170 instance = cloneHiddenInstance(instance, type, props, node);
9171 } else {
9172 // This child was previously inside a timed out tree. If it was not
9173 // updated during this render, it may need to be unhidden. Clone
9174 // again to be sure.
9175 instance = cloneUnhiddenInstance(instance, type, props, node);
9176 }
9177 node.stateNode = instance;
9178 }
9179 appendInitialChild(parent, instance);
9180 } else if (node.tag === HostText) {
9181 var _instance = node.stateNode;
9182 if (needsVisibilityToggle) {
9183 var text = node.memoizedProps;
9184 var rootContainerInstance = getRootHostContainer();
9185 var currentHostContext = getHostContext();
9186 if (isHidden) {
9187 _instance = createHiddenTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
9188 } else {
9189 _instance = createTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
9190 }
9191 node.stateNode = _instance;
9192 }
9193 appendInitialChild(parent, _instance);
9194 } else if (node.tag === HostPortal) {
9195 // If we have a portal child, then we don't want to traverse
9196 // down its children. Instead, we'll get insertions from each child in
9197 // the portal directly.
9198 } else if (node.tag === SuspenseComponent) {
9199 var current = node.alternate;
9200 if (current !== null) {
9201 var oldState = current.memoizedState;
9202 var newState = node.memoizedState;
9203 var oldIsHidden = oldState !== null;
9204 var newIsHidden = newState !== null;
9205 if (oldIsHidden !== newIsHidden) {
9206 // The placeholder either just timed out or switched back to the normal
9207 // children after having previously timed out. Toggle the visibility of
9208 // the direct host children.
9209 var primaryChildParent = newIsHidden ? node.child : node;
9210 if (primaryChildParent !== null) {
9211 appendAllChildren(parent, primaryChildParent, true, newIsHidden);
9212 }
9213 // eslint-disable-next-line no-labels
9214 break branches;
9215 }
9216 }
9217 if (node.child !== null) {
9218 // Continue traversing like normal
9219 node.child.return = node;
9220 node = node.child;
9221 continue;
9222 }
9223 } else if (node.child !== null) {
9224 node.child.return = node;
9225 node = node.child;
9226 continue;
9227 }
9228 // $FlowFixMe This is correct but Flow is confused by the labeled break.
9229 node = node;
9230 if (node === workInProgress) {
9231 return;
9232 }
9233 while (node.sibling === null) {
9234 if (node.return === null || node.return === workInProgress) {
9235 return;
9236 }
9237 node = node.return;
9238 }
9239 node.sibling.return = node.return;
9240 node = node.sibling;
9241 }
9242 };
9243
9244 // An unfortunate fork of appendAllChildren because we have two different parent types.
9245 var appendAllChildrenToContainer = function (containerChildSet, workInProgress, needsVisibilityToggle, isHidden) {
9246 // We only have the top Fiber that was created but we need recurse down its
9247 // children to find all the terminal nodes.
9248 var node = workInProgress.child;
9249 while (node !== null) {
9250 // eslint-disable-next-line no-labels
9251 branches: if (node.tag === HostComponent) {
9252 var instance = node.stateNode;
9253 if (needsVisibilityToggle) {
9254 var props = node.memoizedProps;
9255 var type = node.type;
9256 if (isHidden) {
9257 // This child is inside a timed out tree. Hide it.
9258 instance = cloneHiddenInstance(instance, type, props, node);
9259 } else {
9260 // This child was previously inside a timed out tree. If it was not
9261 // updated during this render, it may need to be unhidden. Clone
9262 // again to be sure.
9263 instance = cloneUnhiddenInstance(instance, type, props, node);
9264 }
9265 node.stateNode = instance;
9266 }
9267 appendChildToContainerChildSet(containerChildSet, instance);
9268 } else if (node.tag === HostText) {
9269 var _instance2 = node.stateNode;
9270 if (needsVisibilityToggle) {
9271 var text = node.memoizedProps;
9272 var rootContainerInstance = getRootHostContainer();
9273 var currentHostContext = getHostContext();
9274 if (isHidden) {
9275 _instance2 = createHiddenTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
9276 } else {
9277 _instance2 = createTextInstance(text, rootContainerInstance, currentHostContext, workInProgress);
9278 }
9279 node.stateNode = _instance2;
9280 }
9281 appendChildToContainerChildSet(containerChildSet, _instance2);
9282 } else if (node.tag === HostPortal) {
9283 // If we have a portal child, then we don't want to traverse
9284 // down its children. Instead, we'll get insertions from each child in
9285 // the portal directly.
9286 } else if (node.tag === SuspenseComponent) {
9287 var current = node.alternate;
9288 if (current !== null) {
9289 var oldState = current.memoizedState;
9290 var newState = node.memoizedState;
9291 var oldIsHidden = oldState !== null;
9292 var newIsHidden = newState !== null;
9293 if (oldIsHidden !== newIsHidden) {
9294 // The placeholder either just timed out or switched back to the normal
9295 // children after having previously timed out. Toggle the visibility of
9296 // the direct host children.
9297 var primaryChildParent = newIsHidden ? node.child : node;
9298 if (primaryChildParent !== null) {
9299 appendAllChildrenToContainer(containerChildSet, primaryChildParent, true, newIsHidden);
9300 }
9301 // eslint-disable-next-line no-labels
9302 break branches;
9303 }
9304 }
9305 if (node.child !== null) {
9306 // Continue traversing like normal
9307 node.child.return = node;
9308 node = node.child;
9309 continue;
9310 }
9311 } else if (node.child !== null) {
9312 node.child.return = node;
9313 node = node.child;
9314 continue;
9315 }
9316 // $FlowFixMe This is correct but Flow is confused by the labeled break.
9317 node = node;
9318 if (node === workInProgress) {
9319 return;
9320 }
9321 while (node.sibling === null) {
9322 if (node.return === null || node.return === workInProgress) {
9323 return;
9324 }
9325 node = node.return;
9326 }
9327 node.sibling.return = node.return;
9328 node = node.sibling;
9329 }
9330 };
9331 updateHostContainer = function (workInProgress) {
9332 var portalOrRoot = workInProgress.stateNode;
9333 var childrenUnchanged = workInProgress.firstEffect === null;
9334 if (childrenUnchanged) {
9335 // No changes, just reuse the existing instance.
9336 } else {
9337 var container = portalOrRoot.containerInfo;
9338 var newChildSet = createContainerChildSet(container);
9339 // If children might have changed, we have to add them all to the set.
9340 appendAllChildrenToContainer(newChildSet, workInProgress, false, false);
9341 portalOrRoot.pendingChildren = newChildSet;
9342 // Schedule an update on the container to swap out the container.
9343 markUpdate(workInProgress);
9344 finalizeContainerChildren(container, newChildSet);
9345 }
9346 };
9347 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
9348 var currentInstance = current.stateNode;
9349 var oldProps = current.memoizedProps;
9350 // If there are no effects associated with this node, then none of our children had any updates.
9351 // This guarantees that we can reuse all of them.
9352 var childrenUnchanged = workInProgress.firstEffect === null;
9353 if (childrenUnchanged && oldProps === newProps) {
9354 // No changes, just reuse the existing instance.
9355 // Note that this might release a previous clone.
9356 workInProgress.stateNode = currentInstance;
9357 return;
9358 }
9359 var recyclableInstance = workInProgress.stateNode;
9360 var currentHostContext = getHostContext();
9361 var updatePayload = null;
9362 if (oldProps !== newProps) {
9363 updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
9364 }
9365 if (childrenUnchanged && updatePayload === null) {
9366 // No changes, just reuse the existing instance.
9367 // Note that this might release a previous clone.
9368 workInProgress.stateNode = currentInstance;
9369 return;
9370 }
9371 var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance);
9372 if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) {
9373 markUpdate(workInProgress);
9374 }
9375 workInProgress.stateNode = newInstance;
9376 if (childrenUnchanged) {
9377 // If there are no other effects in this tree, we need to flag this node as having one.
9378 // Even though we're not going to use it for anything.
9379 // Otherwise parents won't know that there are new children to propagate upwards.
9380 markUpdate(workInProgress);
9381 } else {
9382 // If children might have changed, we have to add them all to the set.
9383 appendAllChildren(newInstance, workInProgress, false, false);
9384 }
9385 };
9386 updateHostText$1 = function (current, workInProgress, oldText, newText) {
9387 if (oldText !== newText) {
9388 // If the text content differs, we'll create a new text instance for it.
9389 var rootContainerInstance = getRootHostContainer();
9390 var currentHostContext = getHostContext();
9391 workInProgress.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress);
9392 // We'll have to mark it as having an effect, even though we won't use the effect for anything.
9393 // This lets the parents know that at least one of their children has changed.
9394 markUpdate(workInProgress);
9395 }
9396 };
9397} else {
9398 // No host operations
9399 updateHostContainer = function (workInProgress) {
9400 // Noop
9401 };
9402 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
9403 // Noop
9404 };
9405 updateHostText$1 = function (current, workInProgress, oldText, newText) {
9406 // Noop
9407 };
9408}
9409
9410function completeWork(current, workInProgress, renderExpirationTime) {
9411 var newProps = workInProgress.pendingProps;
9412
9413 switch (workInProgress.tag) {
9414 case IndeterminateComponent:
9415 break;
9416 case LazyComponent:
9417 break;
9418 case SimpleMemoComponent:
9419 case FunctionComponent:
9420 break;
9421 case ClassComponent:
9422 {
9423 var Component = workInProgress.type;
9424 if (isContextProvider(Component)) {
9425 popContext(workInProgress);
9426 }
9427 break;
9428 }
9429 case HostRoot:
9430 {
9431 popHostContainer(workInProgress);
9432 popTopLevelContextObject(workInProgress);
9433 var fiberRoot = workInProgress.stateNode;
9434 if (fiberRoot.pendingContext) {
9435 fiberRoot.context = fiberRoot.pendingContext;
9436 fiberRoot.pendingContext = null;
9437 }
9438 if (current === null || current.child === null) {
9439 // If we hydrated, pop so that we can delete any remaining children
9440 // that weren't hydrated.
9441 popHydrationState(workInProgress);
9442 // This resets the hacky state to fix isMounted before committing.
9443 // TODO: Delete this when we delete isMounted and findDOMNode.
9444 workInProgress.effectTag &= ~Placement;
9445 }
9446 updateHostContainer(workInProgress);
9447 break;
9448 }
9449 case HostComponent:
9450 {
9451 popHostContext(workInProgress);
9452 var rootContainerInstance = getRootHostContainer();
9453 var type = workInProgress.type;
9454 if (current !== null && workInProgress.stateNode != null) {
9455 updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);
9456
9457 if (current.ref !== workInProgress.ref) {
9458 markRef$1(workInProgress);
9459 }
9460 } else {
9461 if (!newProps) {
9462 !(workInProgress.stateNode !== null) ? invariant(false, 'We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.') : void 0;
9463 // This can happen when we abort work.
9464 break;
9465 }
9466
9467 var currentHostContext = getHostContext();
9468 // TODO: Move createInstance to beginWork and keep it on a context
9469 // "stack" as the parent. Then append children as we go in beginWork
9470 // or completeWork depending on we want to add then top->down or
9471 // bottom->up. Top->down is faster in IE11.
9472 var wasHydrated = popHydrationState(workInProgress);
9473 if (wasHydrated) {
9474 // TODO: Move this and createInstance step into the beginPhase
9475 // to consolidate.
9476 if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
9477 // If changes to the hydrated node needs to be applied at the
9478 // commit-phase we mark this as such.
9479 markUpdate(workInProgress);
9480 }
9481 } else {
9482 var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
9483
9484 appendAllChildren(instance, workInProgress, false, false);
9485
9486 // Certain renderers require commit-time effects for initial mount.
9487 // (eg DOM renderer supports auto-focus for certain elements).
9488 // Make sure such renderers get scheduled for later work.
9489 if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) {
9490 markUpdate(workInProgress);
9491 }
9492 workInProgress.stateNode = instance;
9493 }
9494
9495 if (workInProgress.ref !== null) {
9496 // If there is a ref on a host node we need to schedule a callback
9497 markRef$1(workInProgress);
9498 }
9499 }
9500 break;
9501 }
9502 case HostText:
9503 {
9504 var newText = newProps;
9505 if (current && workInProgress.stateNode != null) {
9506 var oldText = current.memoizedProps;
9507 // If we have an alternate, that means this is an update and we need
9508 // to schedule a side-effect to do the updates.
9509 updateHostText$1(current, workInProgress, oldText, newText);
9510 } else {
9511 if (typeof newText !== 'string') {
9512 !(workInProgress.stateNode !== null) ? invariant(false, 'We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.') : void 0;
9513 // This can happen when we abort work.
9514 }
9515 var _rootContainerInstance = getRootHostContainer();
9516 var _currentHostContext = getHostContext();
9517 var _wasHydrated = popHydrationState(workInProgress);
9518 if (_wasHydrated) {
9519 if (prepareToHydrateHostTextInstance(workInProgress)) {
9520 markUpdate(workInProgress);
9521 }
9522 } else {
9523 workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
9524 }
9525 }
9526 break;
9527 }
9528 case ForwardRef:
9529 break;
9530 case SuspenseComponent:
9531 {
9532 var nextState = workInProgress.memoizedState;
9533 if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
9534 // Something suspended. Re-render with the fallback children.
9535 workInProgress.expirationTime = renderExpirationTime;
9536 // Do not reset the effect list.
9537 return workInProgress;
9538 }
9539
9540 var nextDidTimeout = nextState !== null;
9541 var prevDidTimeout = current !== null && current.memoizedState !== null;
9542
9543 if (current !== null && !nextDidTimeout && prevDidTimeout) {
9544 // We just switched from the fallback to the normal children. Delete
9545 // the fallback.
9546 // TODO: Would it be better to store the fallback fragment on
9547 var currentFallbackChild = current.child.sibling;
9548 if (currentFallbackChild !== null) {
9549 // Deletions go at the beginning of the return fiber's effect list
9550 var first = workInProgress.firstEffect;
9551 if (first !== null) {
9552 workInProgress.firstEffect = currentFallbackChild;
9553 currentFallbackChild.nextEffect = first;
9554 } else {
9555 workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;
9556 currentFallbackChild.nextEffect = null;
9557 }
9558 currentFallbackChild.effectTag = Deletion;
9559 }
9560 }
9561
9562 if (nextDidTimeout || prevDidTimeout) {
9563 // If the children are hidden, or if they were previous hidden, schedule
9564 // an effect to toggle their visibility. This is also used to attach a
9565 // retry listener to the promise.
9566 workInProgress.effectTag |= Update;
9567 }
9568 break;
9569 }
9570 case Fragment:
9571 break;
9572 case Mode:
9573 break;
9574 case Profiler:
9575 break;
9576 case HostPortal:
9577 popHostContainer(workInProgress);
9578 updateHostContainer(workInProgress);
9579 break;
9580 case ContextProvider:
9581 // Pop provider fiber
9582 popProvider(workInProgress);
9583 break;
9584 case ContextConsumer:
9585 break;
9586 case MemoComponent:
9587 break;
9588 case IncompleteClassComponent:
9589 {
9590 // Same as class component case. I put it down here so that the tags are
9591 // sequential to ensure this switch is compiled to a jump table.
9592 var _Component = workInProgress.type;
9593 if (isContextProvider(_Component)) {
9594 popContext(workInProgress);
9595 }
9596 break;
9597 }
9598 case DehydratedSuspenseComponent:
9599 {
9600 if (enableSuspenseServerRenderer) {
9601 if (current === null) {
9602 var _wasHydrated2 = popHydrationState(workInProgress);
9603 !_wasHydrated2 ? invariant(false, 'A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React.') : void 0;
9604 skipPastDehydratedSuspenseInstance(workInProgress);
9605 } else if ((workInProgress.effectTag & DidCapture) === NoEffect) {
9606 // This boundary did not suspend so it's now hydrated.
9607 // To handle any future suspense cases, we're going to now upgrade it
9608 // to a Suspense component. We detach it from the existing current fiber.
9609 current.alternate = null;
9610 workInProgress.alternate = null;
9611 workInProgress.tag = SuspenseComponent;
9612 workInProgress.memoizedState = null;
9613 workInProgress.stateNode = null;
9614 }
9615 }
9616 break;
9617 }
9618 default:
9619 invariant(false, 'Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.');
9620 }
9621
9622 return null;
9623}
9624
9625function shouldCaptureSuspense(workInProgress) {
9626 // In order to capture, the Suspense component must have a fallback prop.
9627 if (workInProgress.memoizedProps.fallback === undefined) {
9628 return false;
9629 }
9630 // If it was the primary children that just suspended, capture and render the
9631 // fallback. Otherwise, don't capture and bubble to the next boundary.
9632 var nextState = workInProgress.memoizedState;
9633 return nextState === null;
9634}
9635
9636// This module is forked in different environments.
9637// By default, return `true` to log errors to the console.
9638// Forks can return `false` if this isn't desirable.
9639function showErrorDialog(capturedError) {
9640 return true;
9641}
9642
9643function logCapturedError(capturedError) {
9644 var logError = showErrorDialog(capturedError);
9645
9646 // Allow injected showErrorDialog() to prevent default console.error logging.
9647 // This enables renderers like ReactNative to better manage redbox behavior.
9648 if (logError === false) {
9649 return;
9650 }
9651
9652 var error = capturedError.error;
9653 {
9654 var componentName = capturedError.componentName,
9655 componentStack = capturedError.componentStack,
9656 errorBoundaryName = capturedError.errorBoundaryName,
9657 errorBoundaryFound = capturedError.errorBoundaryFound,
9658 willRetry = capturedError.willRetry;
9659
9660 // Browsers support silencing uncaught errors by calling
9661 // `preventDefault()` in window `error` handler.
9662 // We record this information as an expando on the error.
9663
9664 if (error != null && error._suppressLogging) {
9665 if (errorBoundaryFound && willRetry) {
9666 // The error is recoverable and was silenced.
9667 // Ignore it and don't print the stack addendum.
9668 // This is handy for testing error boundaries without noise.
9669 return;
9670 }
9671 // The error is fatal. Since the silencing might have
9672 // been accidental, we'll surface it anyway.
9673 // However, the browser would have silenced the original error
9674 // so we'll print it first, and then print the stack addendum.
9675 console.error(error);
9676 // For a more detailed description of this block, see:
9677 // https://github.com/facebook/react/pull/13384
9678 }
9679
9680 var componentNameMessage = componentName ? 'The above error occurred in the <' + componentName + '> component:' : 'The above error occurred in one of your React components:';
9681
9682 var errorBoundaryMessage = void 0;
9683 // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.
9684 if (errorBoundaryFound && errorBoundaryName) {
9685 if (willRetry) {
9686 errorBoundaryMessage = 'React will try to recreate this component tree from scratch ' + ('using the error boundary you provided, ' + errorBoundaryName + '.');
9687 } else {
9688 errorBoundaryMessage = 'This error was initially handled by the error boundary ' + errorBoundaryName + '.\n' + 'Recreating the tree from scratch failed so React will unmount the tree.';
9689 }
9690 } else {
9691 errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\n' + 'Visit https://fb.me/react-error-boundaries to learn more about error boundaries.';
9692 }
9693 var combinedMessage = '' + componentNameMessage + componentStack + '\n\n' + ('' + errorBoundaryMessage);
9694
9695 // In development, we provide our own message with just the component stack.
9696 // We don't include the original error message and JS stack because the browser
9697 // has already printed it. Even if the application swallows the error, it is still
9698 // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
9699 console.error(combinedMessage);
9700 }
9701}
9702
9703var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
9704{
9705 didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
9706}
9707
9708var PossiblyWeakSet$1 = typeof WeakSet === 'function' ? WeakSet : Set;
9709
9710function logError(boundary, errorInfo) {
9711 var source = errorInfo.source;
9712 var stack = errorInfo.stack;
9713 if (stack === null && source !== null) {
9714 stack = getStackByFiberInDevAndProd(source);
9715 }
9716
9717 var capturedError = {
9718 componentName: source !== null ? getComponentName(source.type) : null,
9719 componentStack: stack !== null ? stack : '',
9720 error: errorInfo.value,
9721 errorBoundary: null,
9722 errorBoundaryName: null,
9723 errorBoundaryFound: false,
9724 willRetry: false
9725 };
9726
9727 if (boundary !== null && boundary.tag === ClassComponent) {
9728 capturedError.errorBoundary = boundary.stateNode;
9729 capturedError.errorBoundaryName = getComponentName(boundary.type);
9730 capturedError.errorBoundaryFound = true;
9731 capturedError.willRetry = true;
9732 }
9733
9734 try {
9735 logCapturedError(capturedError);
9736 } catch (e) {
9737 // This method must not throw, or React internal state will get messed up.
9738 // If console.error is overridden, or logCapturedError() shows a dialog that throws,
9739 // we want to report this error outside of the normal stack as a last resort.
9740 // https://github.com/facebook/react/issues/13188
9741 setTimeout(function () {
9742 throw e;
9743 });
9744 }
9745}
9746
9747var callComponentWillUnmountWithTimer = function (current, instance) {
9748 startPhaseTimer(current, 'componentWillUnmount');
9749 instance.props = current.memoizedProps;
9750 instance.state = current.memoizedState;
9751 instance.componentWillUnmount();
9752 stopPhaseTimer();
9753};
9754
9755// Capture errors so they don't interrupt unmounting.
9756function safelyCallComponentWillUnmount(current, instance) {
9757 {
9758 invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current, instance);
9759 if (hasCaughtError()) {
9760 var unmountError = clearCaughtError();
9761 captureCommitPhaseError(current, unmountError);
9762 }
9763 }
9764}
9765
9766function safelyDetachRef(current) {
9767 var ref = current.ref;
9768 if (ref !== null) {
9769 if (typeof ref === 'function') {
9770 {
9771 invokeGuardedCallback(null, ref, null, null);
9772 if (hasCaughtError()) {
9773 var refError = clearCaughtError();
9774 captureCommitPhaseError(current, refError);
9775 }
9776 }
9777 } else {
9778 ref.current = null;
9779 }
9780 }
9781}
9782
9783function safelyCallDestroy(current, destroy) {
9784 {
9785 invokeGuardedCallback(null, destroy, null);
9786 if (hasCaughtError()) {
9787 var error = clearCaughtError();
9788 captureCommitPhaseError(current, error);
9789 }
9790 }
9791}
9792
9793function commitBeforeMutationLifeCycles(current, finishedWork) {
9794 switch (finishedWork.tag) {
9795 case FunctionComponent:
9796 case ForwardRef:
9797 case SimpleMemoComponent:
9798 {
9799 commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork);
9800 return;
9801 }
9802 case ClassComponent:
9803 {
9804 if (finishedWork.effectTag & Snapshot) {
9805 if (current !== null) {
9806 var prevProps = current.memoizedProps;
9807 var prevState = current.memoizedState;
9808 startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');
9809 var instance = finishedWork.stateNode;
9810 // We could update instance props and state here,
9811 // but instead we rely on them being set during last render.
9812 // TODO: revisit this when we implement resuming.
9813 {
9814 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
9815 !(instance.props === finishedWork.memoizedProps) ? warning$1(false, 'Expected %s props to match memoized props before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
9816 !(instance.state === finishedWork.memoizedState) ? warning$1(false, 'Expected %s state to match memoized state before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
9817 }
9818 }
9819 var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
9820 {
9821 var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
9822 if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
9823 didWarnSet.add(finishedWork.type);
9824 warningWithoutStack$1(false, '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));
9825 }
9826 }
9827 instance.__reactInternalSnapshotBeforeUpdate = snapshot;
9828 stopPhaseTimer();
9829 }
9830 }
9831 return;
9832 }
9833 case HostRoot:
9834 case HostComponent:
9835 case HostText:
9836 case HostPortal:
9837 case IncompleteClassComponent:
9838 // Nothing to do for these component types
9839 return;
9840 default:
9841 {
9842 invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
9843 }
9844 }
9845}
9846
9847function commitHookEffectList(unmountTag, mountTag, finishedWork) {
9848 var updateQueue = finishedWork.updateQueue;
9849 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
9850 if (lastEffect !== null) {
9851 var firstEffect = lastEffect.next;
9852 var effect = firstEffect;
9853 do {
9854 if ((effect.tag & unmountTag) !== NoEffect$1) {
9855 // Unmount
9856 var destroy = effect.destroy;
9857 effect.destroy = undefined;
9858 if (destroy !== undefined) {
9859 destroy();
9860 }
9861 }
9862 if ((effect.tag & mountTag) !== NoEffect$1) {
9863 // Mount
9864 var create = effect.create;
9865 effect.destroy = create();
9866
9867 {
9868 var _destroy = effect.destroy;
9869 if (_destroy !== undefined && typeof _destroy !== 'function') {
9870 var addendum = void 0;
9871 if (_destroy === null) {
9872 addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
9873 } else if (typeof _destroy.then === 'function') {
9874 addendum = '\n\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + 'useEffect(() => {\n' + ' async function fetchData() {\n' + ' // You can await here\n' + ' const response = await MyAPI.getData(someId);\n' + ' // ...\n' + ' }\n' + ' fetchData();\n' + '}, [someId]); // Or [] if effect doesn\'t need props or state\n\n' + 'Learn more about data fetching with Hooks: https://fb.me/react-hooks-data-fetching';
9875 } else {
9876 addendum = ' You returned: ' + _destroy;
9877 }
9878 warningWithoutStack$1(false, 'An effect function must not return anything besides a function, ' + 'which is used for clean-up.%s%s', addendum, getStackByFiberInDevAndProd(finishedWork));
9879 }
9880 }
9881 }
9882 effect = effect.next;
9883 } while (effect !== firstEffect);
9884 }
9885}
9886
9887function commitPassiveHookEffects(finishedWork) {
9888 commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork);
9889 commitHookEffectList(NoEffect$1, MountPassive, finishedWork);
9890}
9891
9892function commitLifeCycles(finishedRoot, current, finishedWork, committedExpirationTime) {
9893 switch (finishedWork.tag) {
9894 case FunctionComponent:
9895 case ForwardRef:
9896 case SimpleMemoComponent:
9897 {
9898 commitHookEffectList(UnmountLayout, MountLayout, finishedWork);
9899 break;
9900 }
9901 case ClassComponent:
9902 {
9903 var instance = finishedWork.stateNode;
9904 if (finishedWork.effectTag & Update) {
9905 if (current === null) {
9906 startPhaseTimer(finishedWork, 'componentDidMount');
9907 // We could update instance props and state here,
9908 // but instead we rely on them being set during last render.
9909 // TODO: revisit this when we implement resuming.
9910 {
9911 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
9912 !(instance.props === finishedWork.memoizedProps) ? warning$1(false, 'Expected %s props to match memoized props before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
9913 !(instance.state === finishedWork.memoizedState) ? warning$1(false, 'Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
9914 }
9915 }
9916 instance.componentDidMount();
9917 stopPhaseTimer();
9918 } else {
9919 var prevProps = finishedWork.elementType === finishedWork.type ? current.memoizedProps : resolveDefaultProps(finishedWork.type, current.memoizedProps);
9920 var prevState = current.memoizedState;
9921 startPhaseTimer(finishedWork, 'componentDidUpdate');
9922 // We could update instance props and state here,
9923 // but instead we rely on them being set during last render.
9924 // TODO: revisit this when we implement resuming.
9925 {
9926 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
9927 !(instance.props === finishedWork.memoizedProps) ? warning$1(false, 'Expected %s props to match memoized props before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
9928 !(instance.state === finishedWork.memoizedState) ? warning$1(false, 'Expected %s state to match memoized state before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
9929 }
9930 }
9931 instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
9932 stopPhaseTimer();
9933 }
9934 }
9935 var updateQueue = finishedWork.updateQueue;
9936 if (updateQueue !== null) {
9937 {
9938 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
9939 !(instance.props === finishedWork.memoizedProps) ? warning$1(false, 'Expected %s props to match memoized props before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
9940 !(instance.state === finishedWork.memoizedState) ? warning$1(false, 'Expected %s state to match memoized state before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
9941 }
9942 }
9943 // We could update instance props and state here,
9944 // but instead we rely on them being set during last render.
9945 // TODO: revisit this when we implement resuming.
9946 commitUpdateQueue(finishedWork, updateQueue, instance, committedExpirationTime);
9947 }
9948 return;
9949 }
9950 case HostRoot:
9951 {
9952 var _updateQueue = finishedWork.updateQueue;
9953 if (_updateQueue !== null) {
9954 var _instance = null;
9955 if (finishedWork.child !== null) {
9956 switch (finishedWork.child.tag) {
9957 case HostComponent:
9958 _instance = getPublicInstance(finishedWork.child.stateNode);
9959 break;
9960 case ClassComponent:
9961 _instance = finishedWork.child.stateNode;
9962 break;
9963 }
9964 }
9965 commitUpdateQueue(finishedWork, _updateQueue, _instance, committedExpirationTime);
9966 }
9967 return;
9968 }
9969 case HostComponent:
9970 {
9971 var _instance2 = finishedWork.stateNode;
9972
9973 // Renderers may schedule work to be done after host components are mounted
9974 // (eg DOM renderer may schedule auto-focus for inputs and form controls).
9975 // These effects should only be committed when components are first mounted,
9976 // aka when there is no current/alternate.
9977 if (current === null && finishedWork.effectTag & Update) {
9978 var type = finishedWork.type;
9979 var props = finishedWork.memoizedProps;
9980
9981 }
9982
9983 return;
9984 }
9985 case HostText:
9986 {
9987 // We have no life-cycles associated with text.
9988 return;
9989 }
9990 case HostPortal:
9991 {
9992 // We have no life-cycles associated with portals.
9993 return;
9994 }
9995 case Profiler:
9996 {
9997 if (enableProfilerTimer) {
9998 var onRender = finishedWork.memoizedProps.onRender;
9999
10000 if (enableSchedulerTracing) {
10001 onRender(finishedWork.memoizedProps.id, current === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime(), finishedRoot.memoizedInteractions);
10002 } else {
10003 onRender(finishedWork.memoizedProps.id, current === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime());
10004 }
10005 }
10006 return;
10007 }
10008 case SuspenseComponent:
10009 break;
10010 case IncompleteClassComponent:
10011 break;
10012 default:
10013 {
10014 invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
10015 }
10016 }
10017}
10018
10019function hideOrUnhideAllChildren(finishedWork, isHidden) {
10020 if (supportsMutation) {
10021 // We only have the top Fiber that was inserted but we need to recurse down its
10022 var node = finishedWork;
10023 while (true) {
10024 if (node.tag === HostComponent) {
10025 var instance = node.stateNode;
10026 if (isHidden) {
10027 hideInstance(instance);
10028 } else {
10029 unhideInstance(node.stateNode, node.memoizedProps);
10030 }
10031 } else if (node.tag === HostText) {
10032 var _instance3 = node.stateNode;
10033 if (isHidden) {
10034
10035 } else {
10036 unhideTextInstance(_instance3, node.memoizedProps);
10037 }
10038 } else if (node.tag === SuspenseComponent && node.memoizedState !== null) {
10039 // Found a nested Suspense component that timed out. Skip over the
10040 var fallbackChildFragment = node.child.sibling;
10041 fallbackChildFragment.return = node;
10042 node = fallbackChildFragment;
10043 continue;
10044 } else if (node.child !== null) {
10045 node.child.return = node;
10046 node = node.child;
10047 continue;
10048 }
10049 if (node === finishedWork) {
10050 return;
10051 }
10052 while (node.sibling === null) {
10053 if (node.return === null || node.return === finishedWork) {
10054 return;
10055 }
10056 node = node.return;
10057 }
10058 node.sibling.return = node.return;
10059 node = node.sibling;
10060 }
10061 }
10062}
10063
10064function commitAttachRef(finishedWork) {
10065 var ref = finishedWork.ref;
10066 if (ref !== null) {
10067 var instance = finishedWork.stateNode;
10068 var instanceToUse = void 0;
10069 switch (finishedWork.tag) {
10070 case HostComponent:
10071 instanceToUse = getPublicInstance(instance);
10072 break;
10073 default:
10074 instanceToUse = instance;
10075 }
10076 if (typeof ref === 'function') {
10077 ref(instanceToUse);
10078 } else {
10079 {
10080 if (!ref.hasOwnProperty('current')) {
10081 warningWithoutStack$1(false, 'Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork));
10082 }
10083 }
10084
10085 ref.current = instanceToUse;
10086 }
10087 }
10088}
10089
10090function commitDetachRef(current) {
10091 var currentRef = current.ref;
10092 if (currentRef !== null) {
10093 if (typeof currentRef === 'function') {
10094 currentRef(null);
10095 } else {
10096 currentRef.current = null;
10097 }
10098 }
10099}
10100
10101// User-originating errors (lifecycles and refs) should not interrupt
10102// deletion, so don't let them throw. Host-originating errors should
10103// interrupt deletion, so it's okay
10104function commitUnmount(current) {
10105 onCommitUnmount(current);
10106
10107 switch (current.tag) {
10108 case FunctionComponent:
10109 case ForwardRef:
10110 case MemoComponent:
10111 case SimpleMemoComponent:
10112 {
10113 var updateQueue = current.updateQueue;
10114 if (updateQueue !== null) {
10115 var lastEffect = updateQueue.lastEffect;
10116 if (lastEffect !== null) {
10117 var firstEffect = lastEffect.next;
10118 var effect = firstEffect;
10119 do {
10120 var destroy = effect.destroy;
10121 if (destroy !== undefined) {
10122 safelyCallDestroy(current, destroy);
10123 }
10124 effect = effect.next;
10125 } while (effect !== firstEffect);
10126 }
10127 }
10128 break;
10129 }
10130 case ClassComponent:
10131 {
10132 safelyDetachRef(current);
10133 var instance = current.stateNode;
10134 if (typeof instance.componentWillUnmount === 'function') {
10135 safelyCallComponentWillUnmount(current, instance);
10136 }
10137 return;
10138 }
10139 case HostComponent:
10140 {
10141 safelyDetachRef(current);
10142 return;
10143 }
10144 case HostPortal:
10145 {
10146 // TODO: this is recursive.
10147 // We are also not using this parent because
10148 // the portal will get pushed immediately.
10149 if (supportsMutation) {
10150 unmountHostComponents(current);
10151 } else if (supportsPersistence) {
10152 emptyPortalContainer(current);
10153 }
10154 return;
10155 }
10156 }
10157}
10158
10159function commitNestedUnmounts(root) {
10160 // While we're inside a removed host node we don't want to call
10161 // removeChild on the inner nodes because they're removed by the top
10162 // call anyway. We also want to call componentWillUnmount on all
10163 // composites before this host node is removed from the tree. Therefore
10164 var node = root;
10165 while (true) {
10166 commitUnmount(node);
10167 // Visit children because they may contain more composite or host nodes.
10168 // Skip portals because commitUnmount() currently visits them recursively.
10169 if (node.child !== null && (
10170 // If we use mutation we drill down into portals using commitUnmount above.
10171 // If we don't use mutation we drill down into portals here instead.
10172 !supportsMutation || node.tag !== HostPortal)) {
10173 node.child.return = node;
10174 node = node.child;
10175 continue;
10176 }
10177 if (node === root) {
10178 return;
10179 }
10180 while (node.sibling === null) {
10181 if (node.return === null || node.return === root) {
10182 return;
10183 }
10184 node = node.return;
10185 }
10186 node.sibling.return = node.return;
10187 node = node.sibling;
10188 }
10189}
10190
10191function detachFiber(current) {
10192 // Cut off the return pointers to disconnect it from the tree. Ideally, we
10193 // should clear the child pointer of the parent alternate to let this
10194 // get GC:ed but we don't know which for sure which parent is the current
10195 // one so we'll settle for GC:ing the subtree of this child. This child
10196 // itself will be GC:ed when the parent updates the next time.
10197 current.return = null;
10198 current.child = null;
10199 current.memoizedState = null;
10200 current.updateQueue = null;
10201 var alternate = current.alternate;
10202 if (alternate !== null) {
10203 alternate.return = null;
10204 alternate.child = null;
10205 alternate.memoizedState = null;
10206 alternate.updateQueue = null;
10207 }
10208}
10209
10210function emptyPortalContainer(current) {
10211 if (!supportsPersistence) {
10212 return;
10213 }
10214
10215 var portal = current.stateNode;
10216 var containerInfo = portal.containerInfo;
10217
10218 var emptyChildSet = createContainerChildSet(containerInfo);
10219 replaceContainerChildren(containerInfo, emptyChildSet);
10220}
10221
10222function commitContainer(finishedWork) {
10223 if (!supportsPersistence) {
10224 return;
10225 }
10226
10227 switch (finishedWork.tag) {
10228 case ClassComponent:
10229 {
10230 return;
10231 }
10232 case HostComponent:
10233 {
10234 return;
10235 }
10236 case HostText:
10237 {
10238 return;
10239 }
10240 case HostRoot:
10241 case HostPortal:
10242 {
10243 var portalOrRoot = finishedWork.stateNode;
10244 var containerInfo = portalOrRoot.containerInfo,
10245 _pendingChildren = portalOrRoot.pendingChildren;
10246
10247 replaceContainerChildren(containerInfo, _pendingChildren);
10248 return;
10249 }
10250 default:
10251 {
10252 invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
10253 }
10254 }
10255}
10256
10257function getHostParentFiber(fiber) {
10258 var parent = fiber.return;
10259 while (parent !== null) {
10260 if (isHostParent(parent)) {
10261 return parent;
10262 }
10263 parent = parent.return;
10264 }
10265 invariant(false, 'Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.');
10266}
10267
10268function isHostParent(fiber) {
10269 return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
10270}
10271
10272function getHostSibling(fiber) {
10273 // We're going to search forward into the tree until we find a sibling host
10274 // node. Unfortunately, if multiple insertions are done in a row we have to
10275 // search past them. This leads to exponential search for the next sibling.
10276 var node = fiber;
10277 siblings: while (true) {
10278 // If we didn't find anything, let's try the next sibling.
10279 while (node.sibling === null) {
10280 if (node.return === null || isHostParent(node.return)) {
10281 // If we pop out of the root or hit the parent the fiber we are the
10282 // last sibling.
10283 return null;
10284 }
10285 node = node.return;
10286 }
10287 node.sibling.return = node.return;
10288 node = node.sibling;
10289 while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedSuspenseComponent) {
10290 // If it is not host node and, we might have a host node inside it.
10291 // Try to search down until we find one.
10292 if (node.effectTag & Placement) {
10293 // If we don't have a child, try the siblings instead.
10294 continue siblings;
10295 }
10296 // If we don't have a child, try the siblings instead.
10297 // We also skip portals because they are not part of this host tree.
10298 if (node.child === null || node.tag === HostPortal) {
10299 continue siblings;
10300 } else {
10301 node.child.return = node;
10302 node = node.child;
10303 }
10304 }
10305 // Check if this host node is stable or about to be placed.
10306 if (!(node.effectTag & Placement)) {
10307 // Found it!
10308 return node.stateNode;
10309 }
10310 }
10311}
10312
10313function commitPlacement(finishedWork) {
10314 if (!supportsMutation) {
10315 return;
10316 }
10317
10318 // Recursively insert all host nodes into the parent.
10319 var parentFiber = getHostParentFiber(finishedWork);
10320
10321 // Note: these two variables *must* always be updated together.
10322 var parent = void 0;
10323 var isContainer = void 0;
10324
10325 switch (parentFiber.tag) {
10326 case HostComponent:
10327 parent = parentFiber.stateNode;
10328 isContainer = false;
10329 break;
10330 case HostRoot:
10331 parent = parentFiber.stateNode.containerInfo;
10332 isContainer = true;
10333 break;
10334 case HostPortal:
10335 parent = parentFiber.stateNode.containerInfo;
10336 isContainer = true;
10337 break;
10338 default:
10339 invariant(false, 'Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.');
10340 }
10341 if (parentFiber.effectTag & ContentReset) {
10342 // Reset the text content of the parent before doing any insertions
10343 parentFiber.effectTag &= ~ContentReset;
10344 }
10345
10346 var before = getHostSibling(finishedWork);
10347 // We only have the top Fiber that was inserted but we need to recurse down its
10348 // children to find all the terminal nodes.
10349 var node = finishedWork;
10350 while (true) {
10351 if (node.tag === HostComponent || node.tag === HostText) {
10352 if (before) {
10353 if (isContainer) {
10354 insertInContainerBefore(parent, node.stateNode, before);
10355 } else {
10356 insertBefore(parent, node.stateNode, before);
10357 }
10358 } else {
10359 if (isContainer) {
10360 appendChildToContainer(parent, node.stateNode);
10361 } else {
10362 appendChild(parent, node.stateNode);
10363 }
10364 }
10365 } else if (node.tag === HostPortal) {
10366 // If the insertion itself is a portal, then we don't want to traverse
10367 // down its children. Instead, we'll get insertions from each child in
10368 // the portal directly.
10369 } else if (node.child !== null) {
10370 node.child.return = node;
10371 node = node.child;
10372 continue;
10373 }
10374 if (node === finishedWork) {
10375 return;
10376 }
10377 while (node.sibling === null) {
10378 if (node.return === null || node.return === finishedWork) {
10379 return;
10380 }
10381 node = node.return;
10382 }
10383 node.sibling.return = node.return;
10384 node = node.sibling;
10385 }
10386}
10387
10388function unmountHostComponents(current) {
10389 // We only have the top Fiber that was deleted but we need to recurse down its
10390 var node = current;
10391
10392 // Each iteration, currentParent is populated with node's host parent if not
10393 // currentParentIsValid.
10394 var currentParentIsValid = false;
10395
10396 // Note: these two variables *must* always be updated together.
10397 var currentParent = void 0;
10398 var currentParentIsContainer = void 0;
10399
10400 while (true) {
10401 if (!currentParentIsValid) {
10402 var parent = node.return;
10403 findParent: while (true) {
10404 !(parent !== null) ? invariant(false, 'Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.') : void 0;
10405 switch (parent.tag) {
10406 case HostComponent:
10407 currentParent = parent.stateNode;
10408 currentParentIsContainer = false;
10409 break findParent;
10410 case HostRoot:
10411 currentParent = parent.stateNode.containerInfo;
10412 currentParentIsContainer = true;
10413 break findParent;
10414 case HostPortal:
10415 currentParent = parent.stateNode.containerInfo;
10416 currentParentIsContainer = true;
10417 break findParent;
10418 }
10419 parent = parent.return;
10420 }
10421 currentParentIsValid = true;
10422 }
10423
10424 if (node.tag === HostComponent || node.tag === HostText) {
10425 commitNestedUnmounts(node);
10426 // After all the children have unmounted, it is now safe to remove the
10427 // node from the tree.
10428 if (currentParentIsContainer) {
10429 removeChildFromContainer(currentParent, node.stateNode);
10430 } else {
10431 removeChild(currentParent, node.stateNode);
10432 }
10433 // Don't visit children because we already visited them.
10434 } else if (enableSuspenseServerRenderer && node.tag === DehydratedSuspenseComponent) {
10435 // Delete the dehydrated suspense boundary and all of its content.
10436 if (currentParentIsContainer) {
10437 clearSuspenseBoundaryFromContainer(currentParent, node.stateNode);
10438 } else {
10439 clearSuspenseBoundary(currentParent, node.stateNode);
10440 }
10441 } else if (node.tag === HostPortal) {
10442 if (node.child !== null) {
10443 // When we go into a portal, it becomes the parent to remove from.
10444 // We will reassign it back when we pop the portal on the way up.
10445 currentParent = node.stateNode.containerInfo;
10446 currentParentIsContainer = true;
10447 // Visit children because portals might contain host components.
10448 node.child.return = node;
10449 node = node.child;
10450 continue;
10451 }
10452 } else {
10453 commitUnmount(node);
10454 // Visit children because we may find more host components below.
10455 if (node.child !== null) {
10456 node.child.return = node;
10457 node = node.child;
10458 continue;
10459 }
10460 }
10461 if (node === current) {
10462 return;
10463 }
10464 while (node.sibling === null) {
10465 if (node.return === null || node.return === current) {
10466 return;
10467 }
10468 node = node.return;
10469 if (node.tag === HostPortal) {
10470 // When we go out of the portal, we need to restore the parent.
10471 // Since we don't keep a stack of them, we will search for it.
10472 currentParentIsValid = false;
10473 }
10474 }
10475 node.sibling.return = node.return;
10476 node = node.sibling;
10477 }
10478}
10479
10480function commitDeletion(current) {
10481 if (supportsMutation) {
10482 // Recursively delete all host nodes from the parent.
10483 // Detach refs and call componentWillUnmount() on the whole subtree.
10484 unmountHostComponents(current);
10485 } else {
10486 // Detach refs and call componentWillUnmount() on the whole subtree.
10487 commitNestedUnmounts(current);
10488 }
10489 detachFiber(current);
10490}
10491
10492function commitWork(current, finishedWork) {
10493 if (!supportsMutation) {
10494 switch (finishedWork.tag) {
10495 case FunctionComponent:
10496 case ForwardRef:
10497 case MemoComponent:
10498 case SimpleMemoComponent:
10499 {
10500 // Note: We currently never use MountMutation, but useLayout uses
10501 // UnmountMutation.
10502 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
10503 return;
10504 }
10505 }
10506
10507 commitContainer(finishedWork);
10508 return;
10509 }
10510
10511 switch (finishedWork.tag) {
10512 case FunctionComponent:
10513 case ForwardRef:
10514 case MemoComponent:
10515 case SimpleMemoComponent:
10516 {
10517 // Note: We currently never use MountMutation, but useLayout uses
10518 // UnmountMutation.
10519 commitHookEffectList(UnmountMutation, MountMutation, finishedWork);
10520 return;
10521 }
10522 case ClassComponent:
10523 {
10524 return;
10525 }
10526 case HostComponent:
10527 {
10528 var instance = finishedWork.stateNode;
10529 if (instance != null) {
10530 // Commit the work prepared earlier.
10531 var newProps = finishedWork.memoizedProps;
10532 // For hydration we reuse the update path but we treat the oldProps
10533 // as the newProps. The updatePayload will contain the real change in
10534 // this case.
10535 var oldProps = current !== null ? current.memoizedProps : newProps;
10536 var type = finishedWork.type;
10537 // TODO: Type the updateQueue to be specific to host components.
10538 var updatePayload = finishedWork.updateQueue;
10539 finishedWork.updateQueue = null;
10540 if (updatePayload !== null) {
10541 commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork);
10542 }
10543 }
10544 return;
10545 }
10546 case HostText:
10547 {
10548 !(finishedWork.stateNode !== null) ? invariant(false, 'This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.') : void 0;
10549 var textInstance = finishedWork.stateNode;
10550 var newText = finishedWork.memoizedProps;
10551 // For hydration we reuse the update path but we treat the oldProps
10552 // as the newProps. The updatePayload will contain the real change in
10553 // this case.
10554 var oldText = current !== null ? current.memoizedProps : newText;
10555 return;
10556 }
10557 case HostRoot:
10558 {
10559 return;
10560 }
10561 case Profiler:
10562 {
10563 return;
10564 }
10565 case SuspenseComponent:
10566 {
10567 var newState = finishedWork.memoizedState;
10568
10569 var newDidTimeout = void 0;
10570 var primaryChildParent = finishedWork;
10571 if (newState === null) {
10572 newDidTimeout = false;
10573 } else {
10574 newDidTimeout = true;
10575 primaryChildParent = finishedWork.child;
10576 if (newState.timedOutAt === NoWork) {
10577 // If the children had not already timed out, record the time.
10578 // This is used to compute the elapsed time during subsequent
10579 // attempts to render the children.
10580 newState.timedOutAt = requestCurrentTime();
10581 }
10582 }
10583
10584 if (primaryChildParent !== null) {
10585 hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);
10586 }
10587
10588 // If this boundary just timed out, then it will have a set of thenables.
10589 // For each thenable, attach a listener so that when it resolves, React
10590 // attempts to re-render the boundary in the primary (pre-timeout) state.
10591 var thenables = finishedWork.updateQueue;
10592 if (thenables !== null) {
10593 finishedWork.updateQueue = null;
10594 var retryCache = finishedWork.stateNode;
10595 if (retryCache === null) {
10596 retryCache = finishedWork.stateNode = new PossiblyWeakSet$1();
10597 }
10598 thenables.forEach(function (thenable) {
10599 // Memoize using the boundary fiber to prevent redundant listeners.
10600 var retry = retryTimedOutBoundary.bind(null, finishedWork, thenable);
10601 if (enableSchedulerTracing) {
10602 retry = unstable_wrap(retry);
10603 }
10604 if (!retryCache.has(thenable)) {
10605 retryCache.add(thenable);
10606 thenable.then(retry, retry);
10607 }
10608 });
10609 }
10610
10611 return;
10612 }
10613 case IncompleteClassComponent:
10614 {
10615 return;
10616 }
10617 default:
10618 {
10619 invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.');
10620 }
10621 }
10622}
10623
10624function commitResetTextContent(current) {
10625 if (!supportsMutation) {
10626 return;
10627 }
10628 resetTextContent(current.stateNode);
10629}
10630
10631var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
10632var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
10633
10634function createRootErrorUpdate(fiber, errorInfo, expirationTime) {
10635 var update = createUpdate(expirationTime);
10636 // Unmount the root by rendering null.
10637 update.tag = CaptureUpdate;
10638 // Caution: React DevTools currently depends on this property
10639 // being called "element".
10640 update.payload = { element: null };
10641 var error = errorInfo.value;
10642 update.callback = function () {
10643 onUncaughtError(error);
10644 logError(fiber, errorInfo);
10645 };
10646 return update;
10647}
10648
10649function createClassErrorUpdate(fiber, errorInfo, expirationTime) {
10650 var update = createUpdate(expirationTime);
10651 update.tag = CaptureUpdate;
10652 var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
10653 if (typeof getDerivedStateFromError === 'function') {
10654 var error = errorInfo.value;
10655 update.payload = function () {
10656 return getDerivedStateFromError(error);
10657 };
10658 }
10659
10660 var inst = fiber.stateNode;
10661 if (inst !== null && typeof inst.componentDidCatch === 'function') {
10662 update.callback = function callback() {
10663 if (typeof getDerivedStateFromError !== 'function') {
10664 // To preserve the preexisting retry behavior of error boundaries,
10665 // we keep track of which ones already failed during this batch.
10666 // This gets reset before we yield back to the browser.
10667 // TODO: Warn in strict mode if getDerivedStateFromError is
10668 // not defined.
10669 markLegacyErrorBoundaryAsFailed(this);
10670 }
10671 var error = errorInfo.value;
10672 var stack = errorInfo.stack;
10673 logError(fiber, errorInfo);
10674 this.componentDidCatch(error, {
10675 componentStack: stack !== null ? stack : ''
10676 });
10677 {
10678 if (typeof getDerivedStateFromError !== 'function') {
10679 // If componentDidCatch is the only error boundary method defined,
10680 // then it needs to call setState to recover from errors.
10681 // If no state update is scheduled then the boundary will swallow the error.
10682 !(fiber.expirationTime === Sync) ? warningWithoutStack$1(false, '%s: Error boundaries should implement getDerivedStateFromError(). ' + 'In that method, return a state update to display an error message or fallback UI.', getComponentName(fiber.type) || 'Unknown') : void 0;
10683 }
10684 }
10685 };
10686 }
10687 return update;
10688}
10689
10690function attachPingListener(root, renderExpirationTime, thenable) {
10691 // Attach a listener to the promise to "ping" the root and retry. But
10692 // only if one does not already exist for the current render expiration
10693 // time (which acts like a "thread ID" here).
10694 var pingCache = root.pingCache;
10695 var threadIDs = void 0;
10696 if (pingCache === null) {
10697 pingCache = root.pingCache = new PossiblyWeakMap();
10698 threadIDs = new Set();
10699 pingCache.set(thenable, threadIDs);
10700 } else {
10701 threadIDs = pingCache.get(thenable);
10702 if (threadIDs === undefined) {
10703 threadIDs = new Set();
10704 pingCache.set(thenable, threadIDs);
10705 }
10706 }
10707 if (!threadIDs.has(renderExpirationTime)) {
10708 // Memoize using the thread ID to prevent redundant listeners.
10709 threadIDs.add(renderExpirationTime);
10710 var ping = pingSuspendedRoot.bind(null, root, thenable, renderExpirationTime);
10711 if (enableSchedulerTracing) {
10712 ping = unstable_wrap(ping);
10713 }
10714 thenable.then(ping, ping);
10715 }
10716}
10717
10718function throwException(root, returnFiber, sourceFiber, value, renderExpirationTime) {
10719 // The source fiber did not complete.
10720 sourceFiber.effectTag |= Incomplete;
10721 // Its effect list is no longer valid.
10722 sourceFiber.firstEffect = sourceFiber.lastEffect = null;
10723
10724 if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
10725 // This is a thenable.
10726 var thenable = value;
10727
10728 // Find the earliest timeout threshold of all the placeholders in the
10729 // ancestor path. We could avoid this traversal by storing the thresholds on
10730 // the stack, but we choose not to because we only hit this path if we're
10731 // IO-bound (i.e. if something suspends). Whereas the stack is used even in
10732 // the non-IO- bound case.
10733 var _workInProgress = returnFiber;
10734 var earliestTimeoutMs = -1;
10735 var startTimeMs = -1;
10736 do {
10737 if (_workInProgress.tag === SuspenseComponent) {
10738 var current = _workInProgress.alternate;
10739 if (current !== null) {
10740 var currentState = current.memoizedState;
10741 if (currentState !== null) {
10742 // Reached a boundary that already timed out. Do not search
10743 // any further.
10744 var timedOutAt = currentState.timedOutAt;
10745 startTimeMs = expirationTimeToMs(timedOutAt);
10746 // Do not search any further.
10747 break;
10748 }
10749 }
10750 var timeoutPropMs = _workInProgress.pendingProps.maxDuration;
10751 if (typeof timeoutPropMs === 'number') {
10752 if (timeoutPropMs <= 0) {
10753 earliestTimeoutMs = 0;
10754 } else if (earliestTimeoutMs === -1 || timeoutPropMs < earliestTimeoutMs) {
10755 earliestTimeoutMs = timeoutPropMs;
10756 }
10757 }
10758 }
10759 // If there is a DehydratedSuspenseComponent we don't have to do anything because
10760 // if something suspends inside it, we will simply leave that as dehydrated. It
10761 // will never timeout.
10762 _workInProgress = _workInProgress.return;
10763 } while (_workInProgress !== null);
10764
10765 // Schedule the nearest Suspense to re-render the timed out view.
10766 _workInProgress = returnFiber;
10767 do {
10768 if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress)) {
10769 // Found the nearest boundary.
10770
10771 // Stash the promise on the boundary fiber. If the boundary times out, we'll
10772 var thenables = _workInProgress.updateQueue;
10773 if (thenables === null) {
10774 var updateQueue = new Set();
10775 updateQueue.add(thenable);
10776 _workInProgress.updateQueue = updateQueue;
10777 } else {
10778 thenables.add(thenable);
10779 }
10780
10781 // If the boundary is outside of concurrent mode, we should *not*
10782 // suspend the commit. Pretend as if the suspended component rendered
10783 // null and keep rendering. In the commit phase, we'll schedule a
10784 // subsequent synchronous update to re-render the Suspense.
10785 //
10786 // Note: It doesn't matter whether the component that suspended was
10787 // inside a concurrent mode tree. If the Suspense is outside of it, we
10788 // should *not* suspend the commit.
10789 if ((_workInProgress.mode & ConcurrentMode) === NoEffect) {
10790 _workInProgress.effectTag |= DidCapture;
10791
10792 // We're going to commit this fiber even though it didn't complete.
10793 // But we shouldn't call any lifecycle methods or callbacks. Remove
10794 // all lifecycle effect tags.
10795 sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete);
10796
10797 if (sourceFiber.tag === ClassComponent) {
10798 var currentSourceFiber = sourceFiber.alternate;
10799 if (currentSourceFiber === null) {
10800 // This is a new mount. Change the tag so it's not mistaken for a
10801 // completed class component. For example, we should not call
10802 // componentWillUnmount if it is deleted.
10803 sourceFiber.tag = IncompleteClassComponent;
10804 } else {
10805 // When we try rendering again, we should not reuse the current fiber,
10806 // since it's known to be in an inconsistent state. Use a force updte to
10807 // prevent a bail out.
10808 var update = createUpdate(Sync);
10809 update.tag = ForceUpdate;
10810 enqueueUpdate(sourceFiber, update);
10811 }
10812 }
10813
10814 // The source fiber did not complete. Mark it with Sync priority to
10815 // indicate that it still has pending work.
10816 sourceFiber.expirationTime = Sync;
10817
10818 // Exit without suspending.
10819 return;
10820 }
10821
10822 // Confirmed that the boundary is in a concurrent mode tree. Continue
10823 // with the normal suspend path.
10824
10825 attachPingListener(root, renderExpirationTime, thenable);
10826
10827 var absoluteTimeoutMs = void 0;
10828 if (earliestTimeoutMs === -1) {
10829 // If no explicit threshold is given, default to an arbitrarily large
10830 // value. The actual size doesn't matter because the threshold for the
10831 // whole tree will be clamped to the expiration time.
10832 absoluteTimeoutMs = maxSigned31BitInt;
10833 } else {
10834 if (startTimeMs === -1) {
10835 // This suspend happened outside of any already timed-out
10836 // placeholders. We don't know exactly when the update was
10837 // scheduled, but we can infer an approximate start time from the
10838 // expiration time. First, find the earliest uncommitted expiration
10839 // time in the tree, including work that is suspended. Then subtract
10840 // the offset used to compute an async update's expiration time.
10841 // This will cause high priority (interactive) work to expire
10842 // earlier than necessary, but we can account for this by adjusting
10843 // for the Just Noticeable Difference.
10844 var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, renderExpirationTime);
10845 var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime);
10846 startTimeMs = earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;
10847 }
10848 absoluteTimeoutMs = startTimeMs + earliestTimeoutMs;
10849 }
10850
10851 // Mark the earliest timeout in the suspended fiber's ancestor path.
10852 // After completing the root, we'll take the largest of all the
10853 // suspended fiber's timeouts and use it to compute a timeout for the
10854 // whole tree.
10855 renderDidSuspend(root, absoluteTimeoutMs, renderExpirationTime);
10856
10857 _workInProgress.effectTag |= ShouldCapture;
10858 _workInProgress.expirationTime = renderExpirationTime;
10859 return;
10860 } else if (enableSuspenseServerRenderer && _workInProgress.tag === DehydratedSuspenseComponent) {
10861 attachPingListener(root, renderExpirationTime, thenable);
10862
10863 // Since we already have a current fiber, we can eagerly add a retry listener.
10864 var retryCache = _workInProgress.memoizedState;
10865 if (retryCache === null) {
10866 retryCache = _workInProgress.memoizedState = new PossiblyWeakSet();
10867 var _current = _workInProgress.alternate;
10868 !_current ? invariant(false, 'A dehydrated suspense boundary must commit before trying to render. This is probably a bug in React.') : void 0;
10869 _current.memoizedState = retryCache;
10870 }
10871 // Memoize using the boundary fiber to prevent redundant listeners.
10872 if (!retryCache.has(thenable)) {
10873 retryCache.add(thenable);
10874 var retry = retryTimedOutBoundary.bind(null, _workInProgress, thenable);
10875 if (enableSchedulerTracing) {
10876 retry = unstable_wrap(retry);
10877 }
10878 thenable.then(retry, retry);
10879 }
10880 _workInProgress.effectTag |= ShouldCapture;
10881 _workInProgress.expirationTime = renderExpirationTime;
10882 return;
10883 }
10884 // This boundary already captured during this render. Continue to the next
10885 // boundary.
10886 _workInProgress = _workInProgress.return;
10887 } while (_workInProgress !== null);
10888 // No boundary was found. Fallthrough to error mode.
10889 // TODO: Use invariant so the message is stripped in prod?
10890 value = new Error((getComponentName(sourceFiber.type) || 'A React component') + ' suspended while rendering, but no fallback UI was specified.\n' + '\n' + 'Add a <Suspense fallback=...> component higher in the tree to ' + 'provide a loading indicator or placeholder to display.' + getStackByFiberInDevAndProd(sourceFiber));
10891 }
10892
10893 // We didn't find a boundary that could handle this type of exception. Start
10894 // over and traverse parent path again, this time treating the exception
10895 // as an error.
10896 renderDidError();
10897 value = createCapturedValue(value, sourceFiber);
10898 var workInProgress = returnFiber;
10899 do {
10900 switch (workInProgress.tag) {
10901 case HostRoot:
10902 {
10903 var _errorInfo = value;
10904 workInProgress.effectTag |= ShouldCapture;
10905 workInProgress.expirationTime = renderExpirationTime;
10906 var _update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime);
10907 enqueueCapturedUpdate(workInProgress, _update);
10908 return;
10909 }
10910 case ClassComponent:
10911 // Capture and retry
10912 var errorInfo = value;
10913 var ctor = workInProgress.type;
10914 var instance = workInProgress.stateNode;
10915 if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
10916 workInProgress.effectTag |= ShouldCapture;
10917 workInProgress.expirationTime = renderExpirationTime;
10918 // Schedule the error boundary to re-render using updated state
10919 var _update2 = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime);
10920 enqueueCapturedUpdate(workInProgress, _update2);
10921 return;
10922 }
10923 break;
10924 default:
10925 break;
10926 }
10927 workInProgress = workInProgress.return;
10928 } while (workInProgress !== null);
10929}
10930
10931function unwindWork(workInProgress, renderExpirationTime) {
10932 switch (workInProgress.tag) {
10933 case ClassComponent:
10934 {
10935 var Component = workInProgress.type;
10936 if (isContextProvider(Component)) {
10937 popContext(workInProgress);
10938 }
10939 var effectTag = workInProgress.effectTag;
10940 if (effectTag & ShouldCapture) {
10941 workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture;
10942 return workInProgress;
10943 }
10944 return null;
10945 }
10946 case HostRoot:
10947 {
10948 popHostContainer(workInProgress);
10949 popTopLevelContextObject(workInProgress);
10950 var _effectTag = workInProgress.effectTag;
10951 !((_effectTag & DidCapture) === NoEffect) ? invariant(false, 'The root failed to unmount after an error. This is likely a bug in React. Please file an issue.') : void 0;
10952 workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture;
10953 return workInProgress;
10954 }
10955 case HostComponent:
10956 {
10957 // TODO: popHydrationState
10958 popHostContext(workInProgress);
10959 return null;
10960 }
10961 case SuspenseComponent:
10962 {
10963 var _effectTag2 = workInProgress.effectTag;
10964 if (_effectTag2 & ShouldCapture) {
10965 workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture;
10966 // Captured a suspense effect. Re-render the boundary.
10967 return workInProgress;
10968 }
10969 return null;
10970 }
10971 case DehydratedSuspenseComponent:
10972 {
10973 if (enableSuspenseServerRenderer) {
10974 // TODO: popHydrationState
10975 var _effectTag3 = workInProgress.effectTag;
10976 if (_effectTag3 & ShouldCapture) {
10977 workInProgress.effectTag = _effectTag3 & ~ShouldCapture | DidCapture;
10978 // Captured a suspense effect. Re-render the boundary.
10979 return workInProgress;
10980 }
10981 }
10982 return null;
10983 }
10984 case HostPortal:
10985 popHostContainer(workInProgress);
10986 return null;
10987 case ContextProvider:
10988 popProvider(workInProgress);
10989 return null;
10990 default:
10991 return null;
10992 }
10993}
10994
10995function unwindInterruptedWork(interruptedWork) {
10996 switch (interruptedWork.tag) {
10997 case ClassComponent:
10998 {
10999 var childContextTypes = interruptedWork.type.childContextTypes;
11000 if (childContextTypes !== null && childContextTypes !== undefined) {
11001 popContext(interruptedWork);
11002 }
11003 break;
11004 }
11005 case HostRoot:
11006 {
11007 popHostContainer(interruptedWork);
11008 popTopLevelContextObject(interruptedWork);
11009 break;
11010 }
11011 case HostComponent:
11012 {
11013 popHostContext(interruptedWork);
11014 break;
11015 }
11016 case HostPortal:
11017 popHostContainer(interruptedWork);
11018 break;
11019 case ContextProvider:
11020 popProvider(interruptedWork);
11021 break;
11022 default:
11023 break;
11024 }
11025}
11026
11027var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
11028var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
11029
11030
11031var didWarnAboutStateTransition = void 0;
11032var didWarnSetStateChildContext = void 0;
11033var warnAboutUpdateOnUnmounted = void 0;
11034var warnAboutInvalidUpdates = void 0;
11035
11036if (enableSchedulerTracing) {
11037 // Provide explicit error message when production+profiling bundle of e.g. react-dom
11038 // is used with production (non-profiling) bundle of scheduler/tracing
11039 !(__interactionsRef != null && __interactionsRef.current != null) ? invariant(false, 'It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at http://fb.me/react-profiling') : void 0;
11040}
11041
11042{
11043 didWarnAboutStateTransition = false;
11044 didWarnSetStateChildContext = false;
11045 var didWarnStateUpdateForUnmountedComponent = {};
11046
11047 warnAboutUpdateOnUnmounted = function (fiber, isClass) {
11048 // We show the whole stack but dedupe on the top component's name because
11049 // the problematic code almost always lies inside that component.
11050 var componentName = getComponentName(fiber.type) || 'ReactComponent';
11051 if (didWarnStateUpdateForUnmountedComponent[componentName]) {
11052 return;
11053 }
11054 warningWithoutStack$1(false, "Can't perform a React state update on an unmounted component. This " + 'is a no-op, but it indicates a memory leak in your application. To ' + 'fix, cancel all subscriptions and asynchronous tasks in %s.%s', isClass ? 'the componentWillUnmount method' : 'a useEffect cleanup function', getStackByFiberInDevAndProd(fiber));
11055 didWarnStateUpdateForUnmountedComponent[componentName] = true;
11056 };
11057
11058 warnAboutInvalidUpdates = function (instance) {
11059 switch (phase) {
11060 case 'getChildContext':
11061 if (didWarnSetStateChildContext) {
11062 return;
11063 }
11064 warningWithoutStack$1(false, 'setState(...): Cannot call setState() inside getChildContext()');
11065 didWarnSetStateChildContext = true;
11066 break;
11067 case 'render':
11068 if (didWarnAboutStateTransition) {
11069 return;
11070 }
11071 warningWithoutStack$1(false, 'Cannot update during an existing state transition (such as within ' + '`render`). Render methods should be a pure function of props and state.');
11072 didWarnAboutStateTransition = true;
11073 break;
11074 }
11075 };
11076}
11077
11078var isWorking = false;
11079
11080// The next work in progress fiber that we're currently working on.
11081var nextUnitOfWork = null;
11082var nextRoot = null;
11083// The time at which we're currently rendering work.
11084var nextRenderExpirationTime = NoWork;
11085var nextLatestAbsoluteTimeoutMs = -1;
11086var nextRenderDidError = false;
11087
11088// The next fiber with an effect that we're currently committing.
11089var nextEffect = null;
11090
11091var isCommitting$1 = false;
11092var rootWithPendingPassiveEffects = null;
11093var passiveEffectCallbackHandle = null;
11094var passiveEffectCallback = null;
11095
11096var legacyErrorBoundariesThatAlreadyFailed = null;
11097
11098// Used for performance tracking.
11099var interruptedBy = null;
11100
11101var stashedWorkInProgressProperties = void 0;
11102var replayUnitOfWork = void 0;
11103var mayReplayFailedUnitOfWork = void 0;
11104var isReplayingFailedUnitOfWork = void 0;
11105var originalReplayError = void 0;
11106var rethrowOriginalError = void 0;
11107if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
11108 stashedWorkInProgressProperties = null;
11109 mayReplayFailedUnitOfWork = true;
11110 isReplayingFailedUnitOfWork = false;
11111 originalReplayError = null;
11112 replayUnitOfWork = function (failedUnitOfWork, thrownValue, isYieldy) {
11113 if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') {
11114 // Don't replay promises. Treat everything else like an error.
11115 // TODO: Need to figure out a different strategy if/when we add
11116 // support for catching other types.
11117 return;
11118 }
11119
11120 // Restore the original state of the work-in-progress
11121 if (stashedWorkInProgressProperties === null) {
11122 // This should never happen. Don't throw because this code is DEV-only.
11123 warningWithoutStack$1(false, 'Could not replay rendering after an error. This is likely a bug in React. ' + 'Please file an issue.');
11124 return;
11125 }
11126 assignFiberPropertiesInDEV(failedUnitOfWork, stashedWorkInProgressProperties);
11127
11128 switch (failedUnitOfWork.tag) {
11129 case HostRoot:
11130 popHostContainer(failedUnitOfWork);
11131 popTopLevelContextObject(failedUnitOfWork);
11132 break;
11133 case HostComponent:
11134 popHostContext(failedUnitOfWork);
11135 break;
11136 case ClassComponent:
11137 {
11138 var Component = failedUnitOfWork.type;
11139 if (isContextProvider(Component)) {
11140 popContext(failedUnitOfWork);
11141 }
11142 break;
11143 }
11144 case HostPortal:
11145 popHostContainer(failedUnitOfWork);
11146 break;
11147 case ContextProvider:
11148 popProvider(failedUnitOfWork);
11149 break;
11150 }
11151 // Replay the begin phase.
11152 isReplayingFailedUnitOfWork = true;
11153 originalReplayError = thrownValue;
11154 invokeGuardedCallback(null, workLoop, null, isYieldy);
11155 isReplayingFailedUnitOfWork = false;
11156 originalReplayError = null;
11157 if (hasCaughtError()) {
11158 var replayError = clearCaughtError();
11159 if (replayError != null && thrownValue != null) {
11160 try {
11161 // Reading the expando property is intentionally
11162 // inside `try` because it might be a getter or Proxy.
11163 if (replayError._suppressLogging) {
11164 // Also suppress logging for the original error.
11165 thrownValue._suppressLogging = true;
11166 }
11167 } catch (inner) {
11168 // Ignore.
11169 }
11170 }
11171 } else {
11172 // If the begin phase did not fail the second time, set this pointer
11173 // back to the original value.
11174 nextUnitOfWork = failedUnitOfWork;
11175 }
11176 };
11177 rethrowOriginalError = function () {
11178 throw originalReplayError;
11179 };
11180}
11181
11182function resetStack() {
11183 if (nextUnitOfWork !== null) {
11184 var interruptedWork = nextUnitOfWork.return;
11185 while (interruptedWork !== null) {
11186 unwindInterruptedWork(interruptedWork);
11187 interruptedWork = interruptedWork.return;
11188 }
11189 }
11190
11191 {
11192 ReactStrictModeWarnings.discardPendingWarnings();
11193 checkThatStackIsEmpty();
11194 }
11195
11196 nextRoot = null;
11197 nextRenderExpirationTime = NoWork;
11198 nextLatestAbsoluteTimeoutMs = -1;
11199 nextRenderDidError = false;
11200 nextUnitOfWork = null;
11201}
11202
11203function commitAllHostEffects() {
11204 while (nextEffect !== null) {
11205 {
11206 setCurrentFiber(nextEffect);
11207 }
11208 recordEffect();
11209
11210 var effectTag = nextEffect.effectTag;
11211
11212 if (effectTag & ContentReset) {
11213 commitResetTextContent(nextEffect);
11214 }
11215
11216 if (effectTag & Ref) {
11217 var current = nextEffect.alternate;
11218 if (current !== null) {
11219 commitDetachRef(current);
11220 }
11221 }
11222
11223 // The following switch statement is only concerned about placement,
11224 // updates, and deletions. To avoid needing to add a case for every
11225 // possible bitmap value, we remove the secondary effects from the
11226 // effect tag and switch on that value.
11227 var primaryEffectTag = effectTag & (Placement | Update | Deletion);
11228 switch (primaryEffectTag) {
11229 case Placement:
11230 {
11231 commitPlacement(nextEffect);
11232 // Clear the "placement" from effect tag so that we know that this is inserted, before
11233 // any life-cycles like componentDidMount gets called.
11234 // TODO: findDOMNode doesn't rely on this any more but isMounted
11235 // does and isMounted is deprecated anyway so we should be able
11236 // to kill this.
11237 nextEffect.effectTag &= ~Placement;
11238 break;
11239 }
11240 case PlacementAndUpdate:
11241 {
11242 // Placement
11243 commitPlacement(nextEffect);
11244 // Clear the "placement" from effect tag so that we know that this is inserted, before
11245 // any life-cycles like componentDidMount gets called.
11246 nextEffect.effectTag &= ~Placement;
11247
11248 // Update
11249 var _current = nextEffect.alternate;
11250 commitWork(_current, nextEffect);
11251 break;
11252 }
11253 case Update:
11254 {
11255 var _current2 = nextEffect.alternate;
11256 commitWork(_current2, nextEffect);
11257 break;
11258 }
11259 case Deletion:
11260 {
11261 commitDeletion(nextEffect);
11262 break;
11263 }
11264 }
11265 nextEffect = nextEffect.nextEffect;
11266 }
11267
11268 {
11269 resetCurrentFiber();
11270 }
11271}
11272
11273function commitBeforeMutationLifecycles() {
11274 while (nextEffect !== null) {
11275 {
11276 setCurrentFiber(nextEffect);
11277 }
11278
11279 var effectTag = nextEffect.effectTag;
11280 if (effectTag & Snapshot) {
11281 recordEffect();
11282 var current = nextEffect.alternate;
11283 commitBeforeMutationLifeCycles(current, nextEffect);
11284 }
11285
11286 nextEffect = nextEffect.nextEffect;
11287 }
11288
11289 {
11290 resetCurrentFiber();
11291 }
11292}
11293
11294function commitAllLifeCycles(finishedRoot, committedExpirationTime) {
11295 {
11296 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
11297 ReactStrictModeWarnings.flushLegacyContextWarning();
11298
11299 if (warnAboutDeprecatedLifecycles) {
11300 ReactStrictModeWarnings.flushPendingDeprecationWarnings();
11301 }
11302 }
11303 while (nextEffect !== null) {
11304 {
11305 setCurrentFiber(nextEffect);
11306 }
11307 var effectTag = nextEffect.effectTag;
11308
11309 if (effectTag & (Update | Callback)) {
11310 recordEffect();
11311 var current = nextEffect.alternate;
11312 commitLifeCycles(finishedRoot, current, nextEffect, committedExpirationTime);
11313 }
11314
11315 if (effectTag & Ref) {
11316 recordEffect();
11317 commitAttachRef(nextEffect);
11318 }
11319
11320 if (effectTag & Passive) {
11321 rootWithPendingPassiveEffects = finishedRoot;
11322 }
11323
11324 nextEffect = nextEffect.nextEffect;
11325 }
11326 {
11327 resetCurrentFiber();
11328 }
11329}
11330
11331function commitPassiveEffects(root, firstEffect) {
11332 rootWithPendingPassiveEffects = null;
11333 passiveEffectCallbackHandle = null;
11334 passiveEffectCallback = null;
11335
11336 // Set this to true to prevent re-entrancy
11337 var previousIsRendering = isRendering;
11338 isRendering = true;
11339
11340 var effect = firstEffect;
11341 do {
11342 {
11343 setCurrentFiber(effect);
11344 }
11345
11346 if (effect.effectTag & Passive) {
11347 var didError = false;
11348 var error = void 0;
11349 {
11350 invokeGuardedCallback(null, commitPassiveHookEffects, null, effect);
11351 if (hasCaughtError()) {
11352 didError = true;
11353 error = clearCaughtError();
11354 }
11355 }
11356 if (didError) {
11357 captureCommitPhaseError(effect, error);
11358 }
11359 }
11360 effect = effect.nextEffect;
11361 } while (effect !== null);
11362 {
11363 resetCurrentFiber();
11364 }
11365
11366 isRendering = previousIsRendering;
11367
11368 // Check if work was scheduled by one of the effects
11369 var rootExpirationTime = root.expirationTime;
11370 if (rootExpirationTime !== NoWork) {
11371 requestWork(root, rootExpirationTime);
11372 }
11373 // Flush any sync work that was scheduled by effects
11374 if (!isBatchingUpdates && !isRendering) {
11375 performSyncWork();
11376 }
11377}
11378
11379function isAlreadyFailedLegacyErrorBoundary(instance) {
11380 return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
11381}
11382
11383function markLegacyErrorBoundaryAsFailed(instance) {
11384 if (legacyErrorBoundariesThatAlreadyFailed === null) {
11385 legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
11386 } else {
11387 legacyErrorBoundariesThatAlreadyFailed.add(instance);
11388 }
11389}
11390
11391function flushPassiveEffects() {
11392 if (passiveEffectCallbackHandle !== null) {
11393 cancelPassiveEffects(passiveEffectCallbackHandle);
11394 }
11395 if (passiveEffectCallback !== null) {
11396 // We call the scheduled callback instead of commitPassiveEffects directly
11397 // to ensure tracing works correctly.
11398 passiveEffectCallback();
11399 }
11400}
11401
11402function commitRoot(root, finishedWork) {
11403 isWorking = true;
11404 isCommitting$1 = true;
11405 startCommitTimer();
11406
11407 !(root.current !== finishedWork) ? invariant(false, 'Cannot commit the same tree as before. This is probably a bug related to the return field. This error is likely caused by a bug in React. Please file an issue.') : void 0;
11408 var committedExpirationTime = root.pendingCommitExpirationTime;
11409 !(committedExpirationTime !== NoWork) ? invariant(false, 'Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue.') : void 0;
11410 root.pendingCommitExpirationTime = NoWork;
11411
11412 // Update the pending priority levels to account for the work that we are
11413 // about to commit. This needs to happen before calling the lifecycles, since
11414 // they may schedule additional updates.
11415 var updateExpirationTimeBeforeCommit = finishedWork.expirationTime;
11416 var childExpirationTimeBeforeCommit = finishedWork.childExpirationTime;
11417 var earliestRemainingTimeBeforeCommit = childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit ? childExpirationTimeBeforeCommit : updateExpirationTimeBeforeCommit;
11418 markCommittedPriorityLevels(root, earliestRemainingTimeBeforeCommit);
11419
11420 var prevInteractions = null;
11421 if (enableSchedulerTracing) {
11422 // Restore any pending interactions at this point,
11423 // So that cascading work triggered during the render phase will be accounted for.
11424 prevInteractions = __interactionsRef.current;
11425 __interactionsRef.current = root.memoizedInteractions;
11426 }
11427
11428 // Reset this to null before calling lifecycles
11429 ReactCurrentOwner$1.current = null;
11430
11431 var firstEffect = void 0;
11432 if (finishedWork.effectTag > PerformedWork) {
11433 // A fiber's effect list consists only of its children, not itself. So if
11434 // the root has an effect, we need to add it to the end of the list. The
11435 // resulting list is the set that would belong to the root's parent, if
11436 // it had one; that is, all the effects in the tree including the root.
11437 if (finishedWork.lastEffect !== null) {
11438 finishedWork.lastEffect.nextEffect = finishedWork;
11439 firstEffect = finishedWork.firstEffect;
11440 } else {
11441 firstEffect = finishedWork;
11442 }
11443 } else {
11444 // There is no effect on the root.
11445 firstEffect = finishedWork.firstEffect;
11446 }
11447
11448 prepareForCommit(root.containerInfo);
11449
11450 // Invoke instances of getSnapshotBeforeUpdate before mutation.
11451 nextEffect = firstEffect;
11452 startCommitSnapshotEffectsTimer();
11453 while (nextEffect !== null) {
11454 var didError = false;
11455 var error = void 0;
11456 {
11457 invokeGuardedCallback(null, commitBeforeMutationLifecycles, null);
11458 if (hasCaughtError()) {
11459 didError = true;
11460 error = clearCaughtError();
11461 }
11462 }
11463 if (didError) {
11464 !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
11465 captureCommitPhaseError(nextEffect, error);
11466 // Clean-up
11467 if (nextEffect !== null) {
11468 nextEffect = nextEffect.nextEffect;
11469 }
11470 }
11471 }
11472 stopCommitSnapshotEffectsTimer();
11473
11474 if (enableProfilerTimer) {
11475 // Mark the current commit time to be shared by all Profilers in this batch.
11476 // This enables them to be grouped later.
11477 recordCommitTime();
11478 }
11479
11480 // Commit all the side-effects within a tree. We'll do this in two passes.
11481 // The first pass performs all the host insertions, updates, deletions and
11482 // ref unmounts.
11483 nextEffect = firstEffect;
11484 startCommitHostEffectsTimer();
11485 while (nextEffect !== null) {
11486 var _didError = false;
11487 var _error = void 0;
11488 {
11489 invokeGuardedCallback(null, commitAllHostEffects, null);
11490 if (hasCaughtError()) {
11491 _didError = true;
11492 _error = clearCaughtError();
11493 }
11494 }
11495 if (_didError) {
11496 !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
11497 captureCommitPhaseError(nextEffect, _error);
11498 // Clean-up
11499 if (nextEffect !== null) {
11500 nextEffect = nextEffect.nextEffect;
11501 }
11502 }
11503 }
11504 stopCommitHostEffectsTimer();
11505
11506 resetAfterCommit(root.containerInfo);
11507
11508 // The work-in-progress tree is now the current tree. This must come after
11509 // the first pass of the commit phase, so that the previous tree is still
11510 // current during componentWillUnmount, but before the second pass, so that
11511 // the finished work is current during componentDidMount/Update.
11512 root.current = finishedWork;
11513
11514 // In the second pass we'll perform all life-cycles and ref callbacks.
11515 // Life-cycles happen as a separate pass so that all placements, updates,
11516 // and deletions in the entire tree have already been invoked.
11517 // This pass also triggers any renderer-specific initial effects.
11518 nextEffect = firstEffect;
11519 startCommitLifeCyclesTimer();
11520 while (nextEffect !== null) {
11521 var _didError2 = false;
11522 var _error2 = void 0;
11523 {
11524 invokeGuardedCallback(null, commitAllLifeCycles, null, root, committedExpirationTime);
11525 if (hasCaughtError()) {
11526 _didError2 = true;
11527 _error2 = clearCaughtError();
11528 }
11529 }
11530 if (_didError2) {
11531 !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0;
11532 captureCommitPhaseError(nextEffect, _error2);
11533 if (nextEffect !== null) {
11534 nextEffect = nextEffect.nextEffect;
11535 }
11536 }
11537 }
11538
11539 if (firstEffect !== null && rootWithPendingPassiveEffects !== null) {
11540 // This commit included a passive effect. These do not need to fire until
11541 // after the next paint. Schedule an callback to fire them in an async
11542 // event. To ensure serial execution, the callback will be flushed early if
11543 // we enter rootWithPendingPassiveEffects commit phase before then.
11544 var callback = commitPassiveEffects.bind(null, root, firstEffect);
11545 if (enableSchedulerTracing) {
11546 // TODO: Avoid this extra callback by mutating the tracing ref directly,
11547 // like we do at the beginning of commitRoot. I've opted not to do that
11548 // here because that code is still in flux.
11549 callback = unstable_wrap(callback);
11550 }
11551 passiveEffectCallbackHandle = unstable_runWithPriority(unstable_NormalPriority, function () {
11552 return schedulePassiveEffects(callback);
11553 });
11554 passiveEffectCallback = callback;
11555 }
11556
11557 isCommitting$1 = false;
11558 isWorking = false;
11559 stopCommitLifeCyclesTimer();
11560 stopCommitTimer();
11561 onCommitRoot(finishedWork.stateNode);
11562 if (true && ReactFiberInstrumentation_1.debugTool) {
11563 ReactFiberInstrumentation_1.debugTool.onCommitWork(finishedWork);
11564 }
11565
11566 var updateExpirationTimeAfterCommit = finishedWork.expirationTime;
11567 var childExpirationTimeAfterCommit = finishedWork.childExpirationTime;
11568 var earliestRemainingTimeAfterCommit = childExpirationTimeAfterCommit > updateExpirationTimeAfterCommit ? childExpirationTimeAfterCommit : updateExpirationTimeAfterCommit;
11569 if (earliestRemainingTimeAfterCommit === NoWork) {
11570 // If there's no remaining work, we can clear the set of already failed
11571 // error boundaries.
11572 legacyErrorBoundariesThatAlreadyFailed = null;
11573 }
11574 onCommit(root, earliestRemainingTimeAfterCommit);
11575
11576 if (enableSchedulerTracing) {
11577 __interactionsRef.current = prevInteractions;
11578
11579 var subscriber = void 0;
11580
11581 try {
11582 subscriber = __subscriberRef.current;
11583 if (subscriber !== null && root.memoizedInteractions.size > 0) {
11584 var threadID = computeThreadID(committedExpirationTime, root.interactionThreadID);
11585 subscriber.onWorkStopped(root.memoizedInteractions, threadID);
11586 }
11587 } catch (error) {
11588 // It's not safe for commitRoot() to throw.
11589 // Store the error for now and we'll re-throw in finishRendering().
11590 if (!hasUnhandledError) {
11591 hasUnhandledError = true;
11592 unhandledError = error;
11593 }
11594 } finally {
11595 // Clear completed interactions from the pending Map.
11596 // Unless the render was suspended or cascading work was scheduled,
11597 // In which case– leave pending interactions until the subsequent render.
11598 var pendingInteractionMap = root.pendingInteractionMap;
11599 pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
11600 // Only decrement the pending interaction count if we're done.
11601 // If there's still work at the current priority,
11602 // That indicates that we are waiting for suspense data.
11603 if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {
11604 pendingInteractionMap.delete(scheduledExpirationTime);
11605
11606 scheduledInteractions.forEach(function (interaction) {
11607 interaction.__count--;
11608
11609 if (subscriber !== null && interaction.__count === 0) {
11610 try {
11611 subscriber.onInteractionScheduledWorkCompleted(interaction);
11612 } catch (error) {
11613 // It's not safe for commitRoot() to throw.
11614 // Store the error for now and we'll re-throw in finishRendering().
11615 if (!hasUnhandledError) {
11616 hasUnhandledError = true;
11617 unhandledError = error;
11618 }
11619 }
11620 }
11621 });
11622 }
11623 });
11624 }
11625 }
11626}
11627
11628function resetChildExpirationTime(workInProgress, renderTime) {
11629 if (renderTime !== Never && workInProgress.childExpirationTime === Never) {
11630 // The children of this component are hidden. Don't bubble their
11631 // expiration times.
11632 return;
11633 }
11634
11635 var newChildExpirationTime = NoWork;
11636
11637 // Bubble up the earliest expiration time.
11638 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
11639 // We're in profiling mode.
11640 // Let's use this same traversal to update the render durations.
11641 var actualDuration = workInProgress.actualDuration;
11642 var treeBaseDuration = workInProgress.selfBaseDuration;
11643
11644 // When a fiber is cloned, its actualDuration is reset to 0.
11645 // This value will only be updated if work is done on the fiber (i.e. it doesn't bailout).
11646 // When work is done, it should bubble to the parent's actualDuration.
11647 // If the fiber has not been cloned though, (meaning no work was done),
11648 // Then this value will reflect the amount of time spent working on a previous render.
11649 // In that case it should not bubble.
11650 // We determine whether it was cloned by comparing the child pointer.
11651 var shouldBubbleActualDurations = workInProgress.alternate === null || workInProgress.child !== workInProgress.alternate.child;
11652
11653 var child = workInProgress.child;
11654 while (child !== null) {
11655 var childUpdateExpirationTime = child.expirationTime;
11656 var childChildExpirationTime = child.childExpirationTime;
11657 if (childUpdateExpirationTime > newChildExpirationTime) {
11658 newChildExpirationTime = childUpdateExpirationTime;
11659 }
11660 if (childChildExpirationTime > newChildExpirationTime) {
11661 newChildExpirationTime = childChildExpirationTime;
11662 }
11663 if (shouldBubbleActualDurations) {
11664 actualDuration += child.actualDuration;
11665 }
11666 treeBaseDuration += child.treeBaseDuration;
11667 child = child.sibling;
11668 }
11669 workInProgress.actualDuration = actualDuration;
11670 workInProgress.treeBaseDuration = treeBaseDuration;
11671 } else {
11672 var _child = workInProgress.child;
11673 while (_child !== null) {
11674 var _childUpdateExpirationTime = _child.expirationTime;
11675 var _childChildExpirationTime = _child.childExpirationTime;
11676 if (_childUpdateExpirationTime > newChildExpirationTime) {
11677 newChildExpirationTime = _childUpdateExpirationTime;
11678 }
11679 if (_childChildExpirationTime > newChildExpirationTime) {
11680 newChildExpirationTime = _childChildExpirationTime;
11681 }
11682 _child = _child.sibling;
11683 }
11684 }
11685
11686 workInProgress.childExpirationTime = newChildExpirationTime;
11687}
11688
11689function completeUnitOfWork(workInProgress) {
11690 // Attempt to complete the current unit of work, then move to the
11691 // next sibling. If there are no more siblings, return to the
11692 // parent fiber.
11693 while (true) {
11694 // The current, flushed, state of this fiber is the alternate.
11695 // Ideally nothing should rely on this, but relying on it here
11696 // means that we don't need an additional field on the work in
11697 // progress.
11698 var current = workInProgress.alternate;
11699 {
11700 setCurrentFiber(workInProgress);
11701 }
11702
11703 var returnFiber = workInProgress.return;
11704 var siblingFiber = workInProgress.sibling;
11705
11706 if ((workInProgress.effectTag & Incomplete) === NoEffect) {
11707 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
11708 // Don't replay if it fails during completion phase.
11709 mayReplayFailedUnitOfWork = false;
11710 }
11711 // This fiber completed.
11712 // Remember we're completing this unit so we can find a boundary if it fails.
11713 nextUnitOfWork = workInProgress;
11714 if (enableProfilerTimer) {
11715 if (workInProgress.mode & ProfileMode) {
11716 startProfilerTimer(workInProgress);
11717 }
11718 nextUnitOfWork = completeWork(current, workInProgress, nextRenderExpirationTime);
11719 if (workInProgress.mode & ProfileMode) {
11720 // Update render duration assuming we didn't error.
11721 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
11722 }
11723 } else {
11724 nextUnitOfWork = completeWork(current, workInProgress, nextRenderExpirationTime);
11725 }
11726 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
11727 // We're out of completion phase so replaying is fine now.
11728 mayReplayFailedUnitOfWork = true;
11729 }
11730 stopWorkTimer(workInProgress);
11731 resetChildExpirationTime(workInProgress, nextRenderExpirationTime);
11732 {
11733 resetCurrentFiber();
11734 }
11735
11736 if (nextUnitOfWork !== null) {
11737 // Completing this fiber spawned new work. Work on that next.
11738 return nextUnitOfWork;
11739 }
11740
11741 if (returnFiber !== null &&
11742 // Do not append effects to parents if a sibling failed to complete
11743 (returnFiber.effectTag & Incomplete) === NoEffect) {
11744 // Append all the effects of the subtree and this fiber onto the effect
11745 // list of the parent. The completion order of the children affects the
11746 // side-effect order.
11747 if (returnFiber.firstEffect === null) {
11748 returnFiber.firstEffect = workInProgress.firstEffect;
11749 }
11750 if (workInProgress.lastEffect !== null) {
11751 if (returnFiber.lastEffect !== null) {
11752 returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
11753 }
11754 returnFiber.lastEffect = workInProgress.lastEffect;
11755 }
11756
11757 // If this fiber had side-effects, we append it AFTER the children's
11758 // side-effects. We can perform certain side-effects earlier if
11759 // needed, by doing multiple passes over the effect list. We don't want
11760 // to schedule our own side-effect on our own list because if end up
11761 // reusing children we'll schedule this effect onto itself since we're
11762 // at the end.
11763 var effectTag = workInProgress.effectTag;
11764 // Skip both NoWork and PerformedWork tags when creating the effect list.
11765 // PerformedWork effect is read by React DevTools but shouldn't be committed.
11766 if (effectTag > PerformedWork) {
11767 if (returnFiber.lastEffect !== null) {
11768 returnFiber.lastEffect.nextEffect = workInProgress;
11769 } else {
11770 returnFiber.firstEffect = workInProgress;
11771 }
11772 returnFiber.lastEffect = workInProgress;
11773 }
11774 }
11775
11776 if (true && ReactFiberInstrumentation_1.debugTool) {
11777 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
11778 }
11779
11780 if (siblingFiber !== null) {
11781 // If there is more work to do in this returnFiber, do that next.
11782 return siblingFiber;
11783 } else if (returnFiber !== null) {
11784 // If there's no more work in this returnFiber. Complete the returnFiber.
11785 workInProgress = returnFiber;
11786 continue;
11787 } else {
11788 // We've reached the root.
11789 return null;
11790 }
11791 } else {
11792 if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
11793 // Record the render duration for the fiber that errored.
11794 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
11795
11796 // Include the time spent working on failed children before continuing.
11797 var actualDuration = workInProgress.actualDuration;
11798 var child = workInProgress.child;
11799 while (child !== null) {
11800 actualDuration += child.actualDuration;
11801 child = child.sibling;
11802 }
11803 workInProgress.actualDuration = actualDuration;
11804 }
11805
11806 // This fiber did not complete because something threw. Pop values off
11807 // the stack without entering the complete phase. If this is a boundary,
11808 // capture values if possible.
11809 var next = unwindWork(workInProgress, nextRenderExpirationTime);
11810 // Because this fiber did not complete, don't reset its expiration time.
11811 if (workInProgress.effectTag & DidCapture) {
11812 // Restarting an error boundary
11813 stopFailedWorkTimer(workInProgress);
11814 } else {
11815 stopWorkTimer(workInProgress);
11816 }
11817
11818 {
11819 resetCurrentFiber();
11820 }
11821
11822 if (next !== null) {
11823 stopWorkTimer(workInProgress);
11824 if (true && ReactFiberInstrumentation_1.debugTool) {
11825 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
11826 }
11827
11828 // If completing this work spawned new work, do that next. We'll come
11829 // back here again.
11830 // Since we're restarting, remove anything that is not a host effect
11831 // from the effect tag.
11832 next.effectTag &= HostEffectMask;
11833 return next;
11834 }
11835
11836 if (returnFiber !== null) {
11837 // Mark the parent fiber as incomplete and clear its effect list.
11838 returnFiber.firstEffect = returnFiber.lastEffect = null;
11839 returnFiber.effectTag |= Incomplete;
11840 }
11841
11842 if (true && ReactFiberInstrumentation_1.debugTool) {
11843 ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress);
11844 }
11845
11846 if (siblingFiber !== null) {
11847 // If there is more work to do in this returnFiber, do that next.
11848 return siblingFiber;
11849 } else if (returnFiber !== null) {
11850 // If there's no more work in this returnFiber. Complete the returnFiber.
11851 workInProgress = returnFiber;
11852 continue;
11853 } else {
11854 return null;
11855 }
11856 }
11857 }
11858
11859 // Without this explicit null return Flow complains of invalid return type
11860 // TODO Remove the above while(true) loop
11861 // eslint-disable-next-line no-unreachable
11862 return null;
11863}
11864
11865function performUnitOfWork(workInProgress) {
11866 // The current, flushed, state of this fiber is the alternate.
11867 // Ideally nothing should rely on this, but relying on it here
11868 // means that we don't need an additional field on the work in
11869 // progress.
11870 var current = workInProgress.alternate;
11871
11872 // See if beginning this work spawns more work.
11873 startWorkTimer(workInProgress);
11874 {
11875 setCurrentFiber(workInProgress);
11876 }
11877
11878 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
11879 stashedWorkInProgressProperties = assignFiberPropertiesInDEV(stashedWorkInProgressProperties, workInProgress);
11880 }
11881
11882 var next = void 0;
11883 if (enableProfilerTimer) {
11884 if (workInProgress.mode & ProfileMode) {
11885 startProfilerTimer(workInProgress);
11886 }
11887
11888 next = beginWork(current, workInProgress, nextRenderExpirationTime);
11889 workInProgress.memoizedProps = workInProgress.pendingProps;
11890
11891 if (workInProgress.mode & ProfileMode) {
11892 // Record the render duration assuming we didn't bailout (or error).
11893 stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true);
11894 }
11895 } else {
11896 next = beginWork(current, workInProgress, nextRenderExpirationTime);
11897 workInProgress.memoizedProps = workInProgress.pendingProps;
11898 }
11899
11900 {
11901 resetCurrentFiber();
11902 if (isReplayingFailedUnitOfWork) {
11903 // Currently replaying a failed unit of work. This should be unreachable,
11904 // because the render phase is meant to be idempotent, and it should
11905 // have thrown again. Since it didn't, rethrow the original error, so
11906 // React's internal stack is not misaligned.
11907 rethrowOriginalError();
11908 }
11909 }
11910 if (true && ReactFiberInstrumentation_1.debugTool) {
11911 ReactFiberInstrumentation_1.debugTool.onBeginWork(workInProgress);
11912 }
11913
11914 if (next === null) {
11915 // If this doesn't spawn new work, complete the current work.
11916 next = completeUnitOfWork(workInProgress);
11917 }
11918
11919 ReactCurrentOwner$1.current = null;
11920
11921 return next;
11922}
11923
11924function workLoop(isYieldy) {
11925 if (!isYieldy) {
11926 // Flush work without yielding
11927 while (nextUnitOfWork !== null) {
11928 nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
11929 }
11930 } else {
11931 // Flush asynchronous work until there's a higher priority event
11932 while (nextUnitOfWork !== null && !shouldYieldToRenderer()) {
11933 nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
11934 }
11935 }
11936}
11937
11938function renderRoot(root, isYieldy) {
11939 !!isWorking ? invariant(false, 'renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.') : void 0;
11940
11941 flushPassiveEffects();
11942
11943 isWorking = true;
11944 var previousDispatcher = ReactCurrentDispatcher.current;
11945 ReactCurrentDispatcher.current = ContextOnlyDispatcher;
11946
11947 var expirationTime = root.nextExpirationTimeToWorkOn;
11948
11949 // Check if we're starting from a fresh stack, or if we're resuming from
11950 // previously yielded work.
11951 if (expirationTime !== nextRenderExpirationTime || root !== nextRoot || nextUnitOfWork === null) {
11952 // Reset the stack and start working from the root.
11953 resetStack();
11954 nextRoot = root;
11955 nextRenderExpirationTime = expirationTime;
11956 nextUnitOfWork = createWorkInProgress(nextRoot.current, null, nextRenderExpirationTime);
11957 root.pendingCommitExpirationTime = NoWork;
11958
11959 if (enableSchedulerTracing) {
11960 // Determine which interactions this batch of work currently includes,
11961 // So that we can accurately attribute time spent working on it,
11962 var interactions = new Set();
11963 root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
11964 if (scheduledExpirationTime >= expirationTime) {
11965 scheduledInteractions.forEach(function (interaction) {
11966 return interactions.add(interaction);
11967 });
11968 }
11969 });
11970
11971 // Store the current set of interactions on the FiberRoot for a few reasons:
11972 // We can re-use it in hot functions like renderRoot() without having to recalculate it.
11973 // We will also use it in commitWork() to pass to any Profiler onRender() hooks.
11974 // This also provides DevTools with a way to access it when the onCommitRoot() hook is called.
11975 root.memoizedInteractions = interactions;
11976
11977 if (interactions.size > 0) {
11978 var subscriber = __subscriberRef.current;
11979 if (subscriber !== null) {
11980 var threadID = computeThreadID(expirationTime, root.interactionThreadID);
11981 try {
11982 subscriber.onWorkStarted(interactions, threadID);
11983 } catch (error) {
11984 // Work thrown by an interaction tracing subscriber should be rethrown,
11985 // But only once it's safe (to avoid leaving the scheduler in an invalid state).
11986 // Store the error for now and we'll re-throw in finishRendering().
11987 if (!hasUnhandledError) {
11988 hasUnhandledError = true;
11989 unhandledError = error;
11990 }
11991 }
11992 }
11993 }
11994 }
11995 }
11996
11997 var prevInteractions = null;
11998 if (enableSchedulerTracing) {
11999 // We're about to start new traced work.
12000 // Restore pending interactions so cascading work triggered during the render phase will be accounted for.
12001 prevInteractions = __interactionsRef.current;
12002 __interactionsRef.current = root.memoizedInteractions;
12003 }
12004
12005 var didFatal = false;
12006
12007 startWorkLoopTimer(nextUnitOfWork);
12008
12009 do {
12010 try {
12011 workLoop(isYieldy);
12012 } catch (thrownValue) {
12013 resetContextDependences();
12014 resetHooks();
12015
12016 // Reset in case completion throws.
12017 // This is only used in DEV and when replaying is on.
12018 var mayReplay = void 0;
12019 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
12020 mayReplay = mayReplayFailedUnitOfWork;
12021 mayReplayFailedUnitOfWork = true;
12022 }
12023
12024 if (nextUnitOfWork === null) {
12025 // This is a fatal error.
12026 didFatal = true;
12027 onUncaughtError(thrownValue);
12028 } else {
12029 if (enableProfilerTimer && nextUnitOfWork.mode & ProfileMode) {
12030 // Record the time spent rendering before an error was thrown.
12031 // This avoids inaccurate Profiler durations in the case of a suspended render.
12032 stopProfilerTimerIfRunningAndRecordDelta(nextUnitOfWork, true);
12033 }
12034
12035 {
12036 // Reset global debug state
12037 // We assume this is defined in DEV
12038 resetCurrentlyProcessingQueue();
12039 }
12040
12041 if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) {
12042 if (mayReplay) {
12043 var failedUnitOfWork = nextUnitOfWork;
12044 replayUnitOfWork(failedUnitOfWork, thrownValue, isYieldy);
12045 }
12046 }
12047
12048 // TODO: we already know this isn't true in some cases.
12049 // At least this shows a nicer error message until we figure out the cause.
12050 // https://github.com/facebook/react/issues/12449#issuecomment-386727431
12051 !(nextUnitOfWork !== null) ? invariant(false, 'Failed to replay rendering after an error. This is likely caused by a bug in React. Please file an issue with a reproducing case to help us find it.') : void 0;
12052
12053 var sourceFiber = nextUnitOfWork;
12054 var returnFiber = sourceFiber.return;
12055 if (returnFiber === null) {
12056 // This is the root. The root could capture its own errors. However,
12057 // we don't know if it errors before or after we pushed the host
12058 // context. This information is needed to avoid a stack mismatch.
12059 // Because we're not sure, treat this as a fatal error. We could track
12060 // which phase it fails in, but doesn't seem worth it. At least
12061 // for now.
12062 didFatal = true;
12063 onUncaughtError(thrownValue);
12064 } else {
12065 throwException(root, returnFiber, sourceFiber, thrownValue, nextRenderExpirationTime);
12066 nextUnitOfWork = completeUnitOfWork(sourceFiber);
12067 continue;
12068 }
12069 }
12070 }
12071 break;
12072 } while (true);
12073
12074 if (enableSchedulerTracing) {
12075 // Traced work is done for now; restore the previous interactions.
12076 __interactionsRef.current = prevInteractions;
12077 }
12078
12079 // We're done performing work. Time to clean up.
12080 isWorking = false;
12081 ReactCurrentDispatcher.current = previousDispatcher;
12082 resetContextDependences();
12083 resetHooks();
12084
12085 // Yield back to main thread.
12086 if (didFatal) {
12087 var _didCompleteRoot = false;
12088 stopWorkLoopTimer(interruptedBy, _didCompleteRoot);
12089 interruptedBy = null;
12090 // There was a fatal error.
12091 {
12092 resetStackAfterFatalErrorInDev();
12093 }
12094 // `nextRoot` points to the in-progress root. A non-null value indicates
12095 // that we're in the middle of an async render. Set it to null to indicate
12096 // there's no more work to be done in the current batch.
12097 nextRoot = null;
12098 onFatal(root);
12099 return;
12100 }
12101
12102 if (nextUnitOfWork !== null) {
12103 // There's still remaining async work in this tree, but we ran out of time
12104 // in the current frame. Yield back to the renderer. Unless we're
12105 // interrupted by a higher priority update, we'll continue later from where
12106 // we left off.
12107 var _didCompleteRoot2 = false;
12108 stopWorkLoopTimer(interruptedBy, _didCompleteRoot2);
12109 interruptedBy = null;
12110 onYield(root);
12111 return;
12112 }
12113
12114 // We completed the whole tree.
12115 var didCompleteRoot = true;
12116 stopWorkLoopTimer(interruptedBy, didCompleteRoot);
12117 var rootWorkInProgress = root.current.alternate;
12118 !(rootWorkInProgress !== null) ? invariant(false, 'Finished root should have a work-in-progress. This error is likely caused by a bug in React. Please file an issue.') : void 0;
12119
12120 // `nextRoot` points to the in-progress root. A non-null value indicates
12121 // that we're in the middle of an async render. Set it to null to indicate
12122 // there's no more work to be done in the current batch.
12123 nextRoot = null;
12124 interruptedBy = null;
12125
12126 if (nextRenderDidError) {
12127 // There was an error
12128 if (hasLowerPriorityWork(root, expirationTime)) {
12129 // There's lower priority work. If so, it may have the effect of fixing
12130 // the exception that was just thrown. Exit without committing. This is
12131 // similar to a suspend, but without a timeout because we're not waiting
12132 // for a promise to resolve. React will restart at the lower
12133 // priority level.
12134 markSuspendedPriorityLevel(root, expirationTime);
12135 var suspendedExpirationTime = expirationTime;
12136 var rootExpirationTime = root.expirationTime;
12137 onSuspend(root, rootWorkInProgress, suspendedExpirationTime, rootExpirationTime, -1 // Indicates no timeout
12138 );
12139 return;
12140 } else if (
12141 // There's no lower priority work, but we're rendering asynchronously.
12142 // Synchronously attempt to render the same level one more time. This is
12143 // similar to a suspend, but without a timeout because we're not waiting
12144 // for a promise to resolve.
12145 !root.didError && isYieldy) {
12146 root.didError = true;
12147 var _suspendedExpirationTime = root.nextExpirationTimeToWorkOn = expirationTime;
12148 var _rootExpirationTime = root.expirationTime = Sync;
12149 onSuspend(root, rootWorkInProgress, _suspendedExpirationTime, _rootExpirationTime, -1 // Indicates no timeout
12150 );
12151 return;
12152 }
12153 }
12154
12155 if (isYieldy && nextLatestAbsoluteTimeoutMs !== -1) {
12156 // The tree was suspended.
12157 var _suspendedExpirationTime2 = expirationTime;
12158 markSuspendedPriorityLevel(root, _suspendedExpirationTime2);
12159
12160 // Find the earliest uncommitted expiration time in the tree, including
12161 // work that is suspended. The timeout threshold cannot be longer than
12162 // the overall expiration.
12163 var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, expirationTime);
12164 var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime);
12165 if (earliestExpirationTimeMs < nextLatestAbsoluteTimeoutMs) {
12166 nextLatestAbsoluteTimeoutMs = earliestExpirationTimeMs;
12167 }
12168
12169 // Subtract the current time from the absolute timeout to get the number
12170 // of milliseconds until the timeout. In other words, convert an absolute
12171 // timestamp to a relative time. This is the value that is passed
12172 // to `setTimeout`.
12173 var currentTimeMs = expirationTimeToMs(requestCurrentTime());
12174 var msUntilTimeout = nextLatestAbsoluteTimeoutMs - currentTimeMs;
12175 msUntilTimeout = msUntilTimeout < 0 ? 0 : msUntilTimeout;
12176
12177 // TODO: Account for the Just Noticeable Difference
12178
12179 var _rootExpirationTime2 = root.expirationTime;
12180 onSuspend(root, rootWorkInProgress, _suspendedExpirationTime2, _rootExpirationTime2, msUntilTimeout);
12181 return;
12182 }
12183
12184 // Ready to commit.
12185 onComplete(root, rootWorkInProgress, expirationTime);
12186}
12187
12188function captureCommitPhaseError(sourceFiber, value) {
12189 var expirationTime = Sync;
12190 var fiber = sourceFiber.return;
12191 while (fiber !== null) {
12192 switch (fiber.tag) {
12193 case ClassComponent:
12194 var ctor = fiber.type;
12195 var instance = fiber.stateNode;
12196 if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
12197 var errorInfo = createCapturedValue(value, sourceFiber);
12198 var update = createClassErrorUpdate(fiber, errorInfo, expirationTime);
12199 enqueueUpdate(fiber, update);
12200 scheduleWork(fiber, expirationTime);
12201 return;
12202 }
12203 break;
12204 case HostRoot:
12205 {
12206 var _errorInfo = createCapturedValue(value, sourceFiber);
12207 var _update = createRootErrorUpdate(fiber, _errorInfo, expirationTime);
12208 enqueueUpdate(fiber, _update);
12209 scheduleWork(fiber, expirationTime);
12210 return;
12211 }
12212 }
12213 fiber = fiber.return;
12214 }
12215
12216 if (sourceFiber.tag === HostRoot) {
12217 // Error was thrown at the root. There is no parent, so the root
12218 // itself should capture it.
12219 var rootFiber = sourceFiber;
12220 var _errorInfo2 = createCapturedValue(value, rootFiber);
12221 var _update2 = createRootErrorUpdate(rootFiber, _errorInfo2, expirationTime);
12222 enqueueUpdate(rootFiber, _update2);
12223 scheduleWork(rootFiber, expirationTime);
12224 }
12225}
12226
12227function computeThreadID(expirationTime, interactionThreadID) {
12228 // Interaction threads are unique per root and expiration time.
12229 return expirationTime * 1000 + interactionThreadID;
12230}
12231
12232function computeExpirationForFiber(currentTime, fiber) {
12233 var priorityLevel = unstable_getCurrentPriorityLevel();
12234
12235 var expirationTime = void 0;
12236 if ((fiber.mode & ConcurrentMode) === NoContext) {
12237 // Outside of concurrent mode, updates are always synchronous.
12238 expirationTime = Sync;
12239 } else if (isWorking && !isCommitting$1) {
12240 // During render phase, updates expire during as the current render.
12241 expirationTime = nextRenderExpirationTime;
12242 } else {
12243 switch (priorityLevel) {
12244 case unstable_ImmediatePriority:
12245 expirationTime = Sync;
12246 break;
12247 case unstable_UserBlockingPriority:
12248 expirationTime = computeInteractiveExpiration(currentTime);
12249 break;
12250 case unstable_NormalPriority:
12251 // This is a normal, concurrent update
12252 expirationTime = computeAsyncExpiration(currentTime);
12253 break;
12254 case unstable_LowPriority:
12255 case unstable_IdlePriority:
12256 expirationTime = Never;
12257 break;
12258 default:
12259 invariant(false, 'Unknown priority level. This error is likely caused by a bug in React. Please file an issue.');
12260 }
12261
12262 // If we're in the middle of rendering a tree, do not update at the same
12263 // expiration time that is already rendering.
12264 if (nextRoot !== null && expirationTime === nextRenderExpirationTime) {
12265 expirationTime -= 1;
12266 }
12267 }
12268
12269 // Keep track of the lowest pending interactive expiration time. This
12270 // allows us to synchronously flush all interactive updates
12271 // when needed.
12272 // TODO: Move this to renderer?
12273 return expirationTime;
12274}
12275
12276function renderDidSuspend(root, absoluteTimeoutMs, suspendedTime) {
12277 // Schedule the timeout.
12278 if (absoluteTimeoutMs >= 0 && nextLatestAbsoluteTimeoutMs < absoluteTimeoutMs) {
12279 nextLatestAbsoluteTimeoutMs = absoluteTimeoutMs;
12280 }
12281}
12282
12283function renderDidError() {
12284 nextRenderDidError = true;
12285}
12286
12287function pingSuspendedRoot(root, thenable, pingTime) {
12288 // A promise that previously suspended React from committing has resolved.
12289 // If React is still suspended, try again at the previous level (pingTime).
12290
12291 var pingCache = root.pingCache;
12292 if (pingCache !== null) {
12293 // The thenable resolved, so we no longer need to memoize, because it will
12294 // never be thrown again.
12295 pingCache.delete(thenable);
12296 }
12297
12298 if (nextRoot !== null && nextRenderExpirationTime === pingTime) {
12299 // Received a ping at the same priority level at which we're currently
12300 // rendering. Restart from the root.
12301 nextRoot = null;
12302 } else {
12303 // Confirm that the root is still suspended at this level. Otherwise exit.
12304 if (isPriorityLevelSuspended(root, pingTime)) {
12305 // Ping at the original level
12306 markPingedPriorityLevel(root, pingTime);
12307 var rootExpirationTime = root.expirationTime;
12308 if (rootExpirationTime !== NoWork) {
12309 requestWork(root, rootExpirationTime);
12310 }
12311 }
12312 }
12313}
12314
12315function retryTimedOutBoundary(boundaryFiber, thenable) {
12316 // The boundary fiber (a Suspense component) previously timed out and was
12317 // rendered in its fallback state. One of the promises that suspended it has
12318 // resolved, which means at least part of the tree was likely unblocked. Try
12319 var retryCache = void 0;
12320 if (enableSuspenseServerRenderer) {
12321 switch (boundaryFiber.tag) {
12322 case SuspenseComponent:
12323 retryCache = boundaryFiber.stateNode;
12324 break;
12325 case DehydratedSuspenseComponent:
12326 retryCache = boundaryFiber.memoizedState;
12327 break;
12328 default:
12329 invariant(false, 'Pinged unknown suspense boundary type. This is probably a bug in React.');
12330 }
12331 } else {
12332 retryCache = boundaryFiber.stateNode;
12333 }
12334 if (retryCache !== null) {
12335 // The thenable resolved, so we no longer need to memoize, because it will
12336 // never be thrown again.
12337 retryCache.delete(thenable);
12338 }
12339
12340 var currentTime = requestCurrentTime();
12341 var retryTime = computeExpirationForFiber(currentTime, boundaryFiber);
12342 var root = scheduleWorkToRoot(boundaryFiber, retryTime);
12343 if (root !== null) {
12344 markPendingPriorityLevel(root, retryTime);
12345 var rootExpirationTime = root.expirationTime;
12346 if (rootExpirationTime !== NoWork) {
12347 requestWork(root, rootExpirationTime);
12348 }
12349 }
12350}
12351
12352function scheduleWorkToRoot(fiber, expirationTime) {
12353 recordScheduleUpdate();
12354
12355 {
12356 if (fiber.tag === ClassComponent) {
12357 var instance = fiber.stateNode;
12358 warnAboutInvalidUpdates(instance);
12359 }
12360 }
12361
12362 // Update the source fiber's expiration time
12363 if (fiber.expirationTime < expirationTime) {
12364 fiber.expirationTime = expirationTime;
12365 }
12366 var alternate = fiber.alternate;
12367 if (alternate !== null && alternate.expirationTime < expirationTime) {
12368 alternate.expirationTime = expirationTime;
12369 }
12370 // Walk the parent path to the root and update the child expiration time.
12371 var node = fiber.return;
12372 var root = null;
12373 if (node === null && fiber.tag === HostRoot) {
12374 root = fiber.stateNode;
12375 } else {
12376 while (node !== null) {
12377 alternate = node.alternate;
12378 if (node.childExpirationTime < expirationTime) {
12379 node.childExpirationTime = expirationTime;
12380 if (alternate !== null && alternate.childExpirationTime < expirationTime) {
12381 alternate.childExpirationTime = expirationTime;
12382 }
12383 } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {
12384 alternate.childExpirationTime = expirationTime;
12385 }
12386 if (node.return === null && node.tag === HostRoot) {
12387 root = node.stateNode;
12388 break;
12389 }
12390 node = node.return;
12391 }
12392 }
12393
12394 if (enableSchedulerTracing) {
12395 if (root !== null) {
12396 var interactions = __interactionsRef.current;
12397 if (interactions.size > 0) {
12398 var pendingInteractionMap = root.pendingInteractionMap;
12399 var pendingInteractions = pendingInteractionMap.get(expirationTime);
12400 if (pendingInteractions != null) {
12401 interactions.forEach(function (interaction) {
12402 if (!pendingInteractions.has(interaction)) {
12403 // Update the pending async work count for previously unscheduled interaction.
12404 interaction.__count++;
12405 }
12406
12407 pendingInteractions.add(interaction);
12408 });
12409 } else {
12410 pendingInteractionMap.set(expirationTime, new Set(interactions));
12411
12412 // Update the pending async work count for the current interactions.
12413 interactions.forEach(function (interaction) {
12414 interaction.__count++;
12415 });
12416 }
12417
12418 var subscriber = __subscriberRef.current;
12419 if (subscriber !== null) {
12420 var threadID = computeThreadID(expirationTime, root.interactionThreadID);
12421 subscriber.onWorkScheduled(interactions, threadID);
12422 }
12423 }
12424 }
12425 }
12426 return root;
12427}
12428
12429function warnIfNotCurrentlyBatchingInDev(fiber) {
12430 {
12431 if (isRendering === false && isBatchingUpdates === false) {
12432 warningWithoutStack$1(false, 'An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be wrapped into act(...):\n\n' + 'act(() => {\n' + ' /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see in the browser." + ' Learn more at https://fb.me/react-wrap-tests-with-act' + '%s', getComponentName(fiber.type), getStackByFiberInDevAndProd(fiber));
12433 }
12434 }
12435}
12436
12437function scheduleWork(fiber, expirationTime) {
12438 var root = scheduleWorkToRoot(fiber, expirationTime);
12439 if (root === null) {
12440 {
12441 switch (fiber.tag) {
12442 case ClassComponent:
12443 warnAboutUpdateOnUnmounted(fiber, true);
12444 break;
12445 case FunctionComponent:
12446 case ForwardRef:
12447 case MemoComponent:
12448 case SimpleMemoComponent:
12449 warnAboutUpdateOnUnmounted(fiber, false);
12450 break;
12451 }
12452 }
12453 return;
12454 }
12455
12456 if (!isWorking && nextRenderExpirationTime !== NoWork && expirationTime > nextRenderExpirationTime) {
12457 // This is an interruption. (Used for performance tracking.)
12458 interruptedBy = fiber;
12459 resetStack();
12460 }
12461 markPendingPriorityLevel(root, expirationTime);
12462 if (
12463 // If we're in the render phase, we don't need to schedule this root
12464 // for an update, because we'll do it before we exit...
12465 !isWorking || isCommitting$1 ||
12466 // ...unless this is a different root than the one we're rendering.
12467 nextRoot !== root) {
12468 var rootExpirationTime = root.expirationTime;
12469 requestWork(root, rootExpirationTime);
12470 }
12471 if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
12472 // Reset this back to zero so subsequent updates don't throw.
12473 nestedUpdateCount = 0;
12474 invariant(false, 'Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.');
12475 }
12476}
12477
12478// TODO: Everything below this is written as if it has been lifted to the
12479// renderers. I'll do this in a follow-up.
12480
12481// Linked-list of roots
12482var firstScheduledRoot = null;
12483var lastScheduledRoot = null;
12484
12485var callbackExpirationTime = NoWork;
12486var callbackID = void 0;
12487var isRendering = false;
12488var nextFlushedRoot = null;
12489var nextFlushedExpirationTime = NoWork;
12490var hasUnhandledError = false;
12491var unhandledError = null;
12492
12493var isBatchingUpdates = false;
12494var isUnbatchingUpdates = false;
12495
12496var completedBatches = null;
12497
12498var originalStartTimeMs = unstable_now();
12499var currentRendererTime = msToExpirationTime(originalStartTimeMs);
12500var currentSchedulerTime = currentRendererTime;
12501
12502// Use these to prevent an infinite loop of nested updates
12503var NESTED_UPDATE_LIMIT = 50;
12504var nestedUpdateCount = 0;
12505var lastCommittedRootDuringThisBatch = null;
12506
12507function recomputeCurrentRendererTime() {
12508 var currentTimeMs = unstable_now() - originalStartTimeMs;
12509 currentRendererTime = msToExpirationTime(currentTimeMs);
12510}
12511
12512function scheduleCallbackWithExpirationTime(root, expirationTime) {
12513 if (callbackExpirationTime !== NoWork) {
12514 // A callback is already scheduled. Check its expiration time (timeout).
12515 if (expirationTime < callbackExpirationTime) {
12516 // Existing callback has sufficient timeout. Exit.
12517 return;
12518 } else {
12519 if (callbackID !== null) {
12520 // Existing callback has insufficient timeout. Cancel and schedule a
12521 // new one.
12522 unstable_cancelCallback(callbackID);
12523 }
12524 }
12525 // The request callback timer is already running. Don't start a new one.
12526 } else {
12527 startRequestCallbackTimer();
12528 }
12529
12530 callbackExpirationTime = expirationTime;
12531 var currentMs = unstable_now() - originalStartTimeMs;
12532 var expirationTimeMs = expirationTimeToMs(expirationTime);
12533 var timeout = expirationTimeMs - currentMs;
12534 callbackID = unstable_scheduleCallback(performAsyncWork, { timeout: timeout });
12535}
12536
12537// For every call to renderRoot, one of onFatal, onComplete, onSuspend, and
12538// onYield is called upon exiting. We use these in lieu of returning a tuple.
12539// I've also chosen not to inline them into renderRoot because these will
12540// eventually be lifted into the renderer.
12541function onFatal(root) {
12542 root.finishedWork = null;
12543}
12544
12545function onComplete(root, finishedWork, expirationTime) {
12546 root.pendingCommitExpirationTime = expirationTime;
12547 root.finishedWork = finishedWork;
12548}
12549
12550function onSuspend(root, finishedWork, suspendedExpirationTime, rootExpirationTime, msUntilTimeout) {
12551 root.expirationTime = rootExpirationTime;
12552 if (msUntilTimeout === 0 && !shouldYieldToRenderer()) {
12553 // Don't wait an additional tick. Commit the tree immediately.
12554 root.pendingCommitExpirationTime = suspendedExpirationTime;
12555 root.finishedWork = finishedWork;
12556 } else if (msUntilTimeout > 0) {
12557 // Wait `msUntilTimeout` milliseconds before committing.
12558 root.timeoutHandle = scheduleTimeout(onTimeout.bind(null, root, finishedWork, suspendedExpirationTime), msUntilTimeout);
12559 }
12560}
12561
12562function onYield(root) {
12563 root.finishedWork = null;
12564}
12565
12566function onTimeout(root, finishedWork, suspendedExpirationTime) {
12567 // The root timed out. Commit it.
12568 root.pendingCommitExpirationTime = suspendedExpirationTime;
12569 root.finishedWork = finishedWork;
12570 // Read the current time before entering the commit phase. We can be
12571 // certain this won't cause tearing related to batching of event updates
12572 // because we're at the top of a timer event.
12573 recomputeCurrentRendererTime();
12574 currentSchedulerTime = currentRendererTime;
12575 flushRoot(root, suspendedExpirationTime);
12576}
12577
12578function onCommit(root, expirationTime) {
12579 root.expirationTime = expirationTime;
12580 root.finishedWork = null;
12581}
12582
12583function requestCurrentTime() {
12584 // requestCurrentTime is called by the scheduler to compute an expiration
12585 // time.
12586 //
12587 // Expiration times are computed by adding to the current time (the start
12588 // time). However, if two updates are scheduled within the same event, we
12589 // should treat their start times as simultaneous, even if the actual clock
12590 // time has advanced between the first and second call.
12591
12592 // In other words, because expiration times determine how updates are batched,
12593 // we want all updates of like priority that occur within the same event to
12594 // receive the same expiration time. Otherwise we get tearing.
12595 //
12596 // We keep track of two separate times: the current "renderer" time and the
12597 // current "scheduler" time. The renderer time can be updated whenever; it
12598 // only exists to minimize the calls performance.now.
12599 //
12600 // But the scheduler time can only be updated if there's no pending work, or
12601 // if we know for certain that we're not in the middle of an event.
12602
12603 if (isRendering) {
12604 // We're already rendering. Return the most recently read time.
12605 return currentSchedulerTime;
12606 }
12607 // Check if there's pending work.
12608 findHighestPriorityRoot();
12609 if (nextFlushedExpirationTime === NoWork || nextFlushedExpirationTime === Never) {
12610 // If there's no pending work, or if the pending work is offscreen, we can
12611 // read the current time without risk of tearing.
12612 recomputeCurrentRendererTime();
12613 currentSchedulerTime = currentRendererTime;
12614 return currentSchedulerTime;
12615 }
12616 // There's already pending work. We might be in the middle of a browser
12617 // event. If we were to read the current time, it could cause multiple updates
12618 // within the same event to receive different expiration times, leading to
12619 // tearing. Return the last read time. During the next idle callback, the
12620 // time will be updated.
12621 return currentSchedulerTime;
12622}
12623
12624// requestWork is called by the scheduler whenever a root receives an update.
12625// It's up to the renderer to call renderRoot at some point in the future.
12626function requestWork(root, expirationTime) {
12627 addRootToSchedule(root, expirationTime);
12628 if (isRendering) {
12629 // Prevent reentrancy. Remaining work will be scheduled at the end of
12630 // the currently rendering batch.
12631 return;
12632 }
12633
12634 if (isBatchingUpdates) {
12635 // Flush work at the end of the batch.
12636 if (isUnbatchingUpdates) {
12637 // ...unless we're inside unbatchedUpdates, in which case we should
12638 // flush it now.
12639 nextFlushedRoot = root;
12640 nextFlushedExpirationTime = Sync;
12641 performWorkOnRoot(root, Sync, false);
12642 }
12643 return;
12644 }
12645
12646 // TODO: Get rid of Sync and use current time?
12647 if (expirationTime === Sync) {
12648 performSyncWork();
12649 } else {
12650 scheduleCallbackWithExpirationTime(root, expirationTime);
12651 }
12652}
12653
12654function addRootToSchedule(root, expirationTime) {
12655 // Add the root to the schedule.
12656 // Check if this root is already part of the schedule.
12657 if (root.nextScheduledRoot === null) {
12658 // This root is not already scheduled. Add it.
12659 root.expirationTime = expirationTime;
12660 if (lastScheduledRoot === null) {
12661 firstScheduledRoot = lastScheduledRoot = root;
12662 root.nextScheduledRoot = root;
12663 } else {
12664 lastScheduledRoot.nextScheduledRoot = root;
12665 lastScheduledRoot = root;
12666 lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
12667 }
12668 } else {
12669 // This root is already scheduled, but its priority may have increased.
12670 var remainingExpirationTime = root.expirationTime;
12671 if (expirationTime > remainingExpirationTime) {
12672 // Update the priority.
12673 root.expirationTime = expirationTime;
12674 }
12675 }
12676}
12677
12678function findHighestPriorityRoot() {
12679 var highestPriorityWork = NoWork;
12680 var highestPriorityRoot = null;
12681 if (lastScheduledRoot !== null) {
12682 var previousScheduledRoot = lastScheduledRoot;
12683 var root = firstScheduledRoot;
12684 while (root !== null) {
12685 var remainingExpirationTime = root.expirationTime;
12686 if (remainingExpirationTime === NoWork) {
12687 // This root no longer has work. Remove it from the scheduler.
12688
12689 // TODO: This check is redudant, but Flow is confused by the branch
12690 // below where we set lastScheduledRoot to null, even though we break
12691 // from the loop right after.
12692 !(previousScheduledRoot !== null && lastScheduledRoot !== null) ? invariant(false, 'Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue.') : void 0;
12693 if (root === root.nextScheduledRoot) {
12694 // This is the only root in the list.
12695 root.nextScheduledRoot = null;
12696 firstScheduledRoot = lastScheduledRoot = null;
12697 break;
12698 } else if (root === firstScheduledRoot) {
12699 // This is the first root in the list.
12700 var next = root.nextScheduledRoot;
12701 firstScheduledRoot = next;
12702 lastScheduledRoot.nextScheduledRoot = next;
12703 root.nextScheduledRoot = null;
12704 } else if (root === lastScheduledRoot) {
12705 // This is the last root in the list.
12706 lastScheduledRoot = previousScheduledRoot;
12707 lastScheduledRoot.nextScheduledRoot = firstScheduledRoot;
12708 root.nextScheduledRoot = null;
12709 break;
12710 } else {
12711 previousScheduledRoot.nextScheduledRoot = root.nextScheduledRoot;
12712 root.nextScheduledRoot = null;
12713 }
12714 root = previousScheduledRoot.nextScheduledRoot;
12715 } else {
12716 if (remainingExpirationTime > highestPriorityWork) {
12717 // Update the priority, if it's higher
12718 highestPriorityWork = remainingExpirationTime;
12719 highestPriorityRoot = root;
12720 }
12721 if (root === lastScheduledRoot) {
12722 break;
12723 }
12724 if (highestPriorityWork === Sync) {
12725 // Sync is highest priority by definition so
12726 // we can stop searching.
12727 break;
12728 }
12729 previousScheduledRoot = root;
12730 root = root.nextScheduledRoot;
12731 }
12732 }
12733 }
12734
12735 nextFlushedRoot = highestPriorityRoot;
12736 nextFlushedExpirationTime = highestPriorityWork;
12737}
12738
12739// TODO: This wrapper exists because many of the older tests (the ones that use
12740// flushDeferredPri) rely on the number of times `shouldYield` is called. We
12741// should get rid of it.
12742var didYield = false;
12743function shouldYieldToRenderer() {
12744 if (didYield) {
12745 return true;
12746 }
12747 if (unstable_shouldYield()) {
12748 didYield = true;
12749 return true;
12750 }
12751 return false;
12752}
12753
12754function performAsyncWork() {
12755 try {
12756 if (!shouldYieldToRenderer()) {
12757 // The callback timed out. That means at least one update has expired.
12758 // Iterate through the root schedule. If they contain expired work, set
12759 // the next render expiration time to the current time. This has the effect
12760 // of flushing all expired work in a single batch, instead of flushing each
12761 // level one at a time.
12762 if (firstScheduledRoot !== null) {
12763 recomputeCurrentRendererTime();
12764 var root = firstScheduledRoot;
12765 do {
12766 didExpireAtExpirationTime(root, currentRendererTime);
12767 // The root schedule is circular, so this is never null.
12768 root = root.nextScheduledRoot;
12769 } while (root !== firstScheduledRoot);
12770 }
12771 }
12772 performWork(NoWork, true);
12773 } finally {
12774 didYield = false;
12775 }
12776}
12777
12778function performSyncWork() {
12779 performWork(Sync, false);
12780}
12781
12782function performWork(minExpirationTime, isYieldy) {
12783 // Keep working on roots until there's no more work, or until there's a higher
12784 // priority event.
12785 findHighestPriorityRoot();
12786
12787 if (isYieldy) {
12788 recomputeCurrentRendererTime();
12789 currentSchedulerTime = currentRendererTime;
12790
12791 if (enableUserTimingAPI) {
12792 var didExpire = nextFlushedExpirationTime > currentRendererTime;
12793 var timeout = expirationTimeToMs(nextFlushedExpirationTime);
12794 stopRequestCallbackTimer(didExpire, timeout);
12795 }
12796
12797 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && minExpirationTime <= nextFlushedExpirationTime && !(didYield && currentRendererTime > nextFlushedExpirationTime)) {
12798 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, currentRendererTime > nextFlushedExpirationTime);
12799 findHighestPriorityRoot();
12800 recomputeCurrentRendererTime();
12801 currentSchedulerTime = currentRendererTime;
12802 }
12803 } else {
12804 while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && minExpirationTime <= nextFlushedExpirationTime) {
12805 performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false);
12806 findHighestPriorityRoot();
12807 }
12808 }
12809
12810 // We're done flushing work. Either we ran out of time in this callback,
12811 // or there's no more work left with sufficient priority.
12812
12813 // If we're inside a callback, set this to false since we just completed it.
12814 if (isYieldy) {
12815 callbackExpirationTime = NoWork;
12816 callbackID = null;
12817 }
12818 // If there's work left over, schedule a new callback.
12819 if (nextFlushedExpirationTime !== NoWork) {
12820 scheduleCallbackWithExpirationTime(nextFlushedRoot, nextFlushedExpirationTime);
12821 }
12822
12823 // Clean-up.
12824 finishRendering();
12825}
12826
12827function flushRoot(root, expirationTime) {
12828 !!isRendering ? invariant(false, 'work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method.') : void 0;
12829 // Perform work on root as if the given expiration time is the current time.
12830 // This has the effect of synchronously flushing all work up to and
12831 // including the given time.
12832 nextFlushedRoot = root;
12833 nextFlushedExpirationTime = expirationTime;
12834 performWorkOnRoot(root, expirationTime, false);
12835 // Flush any sync work that was scheduled by lifecycles
12836 performSyncWork();
12837}
12838
12839function finishRendering() {
12840 nestedUpdateCount = 0;
12841 lastCommittedRootDuringThisBatch = null;
12842
12843 if (completedBatches !== null) {
12844 var batches = completedBatches;
12845 completedBatches = null;
12846 for (var i = 0; i < batches.length; i++) {
12847 var batch = batches[i];
12848 try {
12849 batch._onComplete();
12850 } catch (error) {
12851 if (!hasUnhandledError) {
12852 hasUnhandledError = true;
12853 unhandledError = error;
12854 }
12855 }
12856 }
12857 }
12858
12859 if (hasUnhandledError) {
12860 var error = unhandledError;
12861 unhandledError = null;
12862 hasUnhandledError = false;
12863 throw error;
12864 }
12865}
12866
12867function performWorkOnRoot(root, expirationTime, isYieldy) {
12868 !!isRendering ? invariant(false, 'performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.') : void 0;
12869
12870 isRendering = true;
12871
12872 // Check if this is async work or sync/expired work.
12873 if (!isYieldy) {
12874 // Flush work without yielding.
12875 // TODO: Non-yieldy work does not necessarily imply expired work. A renderer
12876 // may want to perform some work without yielding, but also without
12877 // requiring the root to complete (by triggering placeholders).
12878
12879 var finishedWork = root.finishedWork;
12880 if (finishedWork !== null) {
12881 // This root is already complete. We can commit it.
12882 completeRoot(root, finishedWork, expirationTime);
12883 } else {
12884 root.finishedWork = null;
12885 // If this root previously suspended, clear its existing timeout, since
12886 // we're about to try rendering again.
12887 var timeoutHandle = root.timeoutHandle;
12888 if (timeoutHandle !== noTimeout) {
12889 root.timeoutHandle = noTimeout;
12890 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
12891 cancelTimeout(timeoutHandle);
12892 }
12893 renderRoot(root, isYieldy);
12894 finishedWork = root.finishedWork;
12895 if (finishedWork !== null) {
12896 // We've completed the root. Commit it.
12897 completeRoot(root, finishedWork, expirationTime);
12898 }
12899 }
12900 } else {
12901 // Flush async work.
12902 var _finishedWork = root.finishedWork;
12903 if (_finishedWork !== null) {
12904 // This root is already complete. We can commit it.
12905 completeRoot(root, _finishedWork, expirationTime);
12906 } else {
12907 root.finishedWork = null;
12908 // If this root previously suspended, clear its existing timeout, since
12909 // we're about to try rendering again.
12910 var _timeoutHandle = root.timeoutHandle;
12911 if (_timeoutHandle !== noTimeout) {
12912 root.timeoutHandle = noTimeout;
12913 // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
12914 cancelTimeout(_timeoutHandle);
12915 }
12916 renderRoot(root, isYieldy);
12917 _finishedWork = root.finishedWork;
12918 if (_finishedWork !== null) {
12919 // We've completed the root. Check the if we should yield one more time
12920 // before committing.
12921 if (!shouldYieldToRenderer()) {
12922 // Still time left. Commit the root.
12923 completeRoot(root, _finishedWork, expirationTime);
12924 } else {
12925 // There's no time left. Mark this root as complete. We'll come
12926 // back and commit it later.
12927 root.finishedWork = _finishedWork;
12928 }
12929 }
12930 }
12931 }
12932
12933 isRendering = false;
12934}
12935
12936function completeRoot(root, finishedWork, expirationTime) {
12937 // Check if there's a batch that matches this expiration time.
12938 var firstBatch = root.firstBatch;
12939 if (firstBatch !== null && firstBatch._expirationTime >= expirationTime) {
12940 if (completedBatches === null) {
12941 completedBatches = [firstBatch];
12942 } else {
12943 completedBatches.push(firstBatch);
12944 }
12945 if (firstBatch._defer) {
12946 // This root is blocked from committing by a batch. Unschedule it until
12947 // we receive another update.
12948 root.finishedWork = finishedWork;
12949 root.expirationTime = NoWork;
12950 return;
12951 }
12952 }
12953
12954 // Commit the root.
12955 root.finishedWork = null;
12956
12957 // Check if this is a nested update (a sync update scheduled during the
12958 // commit phase).
12959 if (root === lastCommittedRootDuringThisBatch) {
12960 // If the next root is the same as the previous root, this is a nested
12961 // update. To prevent an infinite loop, increment the nested update count.
12962 nestedUpdateCount++;
12963 } else {
12964 // Reset whenever we switch roots.
12965 lastCommittedRootDuringThisBatch = root;
12966 nestedUpdateCount = 0;
12967 }
12968 unstable_runWithPriority(unstable_ImmediatePriority, function () {
12969 commitRoot(root, finishedWork);
12970 });
12971}
12972
12973function onUncaughtError(error) {
12974 !(nextFlushedRoot !== null) ? invariant(false, 'Should be working on a root. This error is likely caused by a bug in React. Please file an issue.') : void 0;
12975 // Unschedule this root so we don't work on it again until there's
12976 // another update.
12977 nextFlushedRoot.expirationTime = NoWork;
12978 if (!hasUnhandledError) {
12979 hasUnhandledError = true;
12980 unhandledError = error;
12981 }
12982}
12983
12984// 0 is PROD, 1 is DEV.
12985// Might add PROFILE later.
12986
12987
12988var didWarnAboutNestedUpdates = void 0;
12989{
12990 didWarnAboutNestedUpdates = false;
12991
12992}
12993
12994function getContextForSubtree(parentComponent) {
12995 if (!parentComponent) {
12996 return emptyContextObject;
12997 }
12998
12999 var fiber = get(parentComponent);
13000 var parentContext = findCurrentUnmaskedContext(fiber);
13001
13002 if (fiber.tag === ClassComponent) {
13003 var Component = fiber.type;
13004 if (isContextProvider(Component)) {
13005 return processChildContext(fiber, Component, parentContext);
13006 }
13007 }
13008
13009 return parentContext;
13010}
13011
13012function scheduleRootUpdate(current$$1, element, expirationTime, callback) {
13013 {
13014 if (phase === 'render' && current$1 !== null && !didWarnAboutNestedUpdates) {
13015 didWarnAboutNestedUpdates = true;
13016 warningWithoutStack$1(false, 'Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentName(current$1.type) || 'Unknown');
13017 }
13018 }
13019
13020 var update = createUpdate(expirationTime);
13021 // Caution: React DevTools currently depends on this property
13022 // being called "element".
13023 update.payload = { element: element };
13024
13025 callback = callback === undefined ? null : callback;
13026 if (callback !== null) {
13027 !(typeof callback === 'function') ? warningWithoutStack$1(false, 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback) : void 0;
13028 update.callback = callback;
13029 }
13030
13031 flushPassiveEffects();
13032 enqueueUpdate(current$$1, update);
13033 scheduleWork(current$$1, expirationTime);
13034
13035 return expirationTime;
13036}
13037
13038function updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback) {
13039 // TODO: If this is a nested container, this won't be the root.
13040 var current$$1 = container.current;
13041
13042 {
13043 if (ReactFiberInstrumentation_1.debugTool) {
13044 if (current$$1.alternate === null) {
13045 ReactFiberInstrumentation_1.debugTool.onMountContainer(container);
13046 } else if (element === null) {
13047 ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container);
13048 } else {
13049 ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container);
13050 }
13051 }
13052 }
13053
13054 var context = getContextForSubtree(parentComponent);
13055 if (container.context === null) {
13056 container.context = context;
13057 } else {
13058 container.pendingContext = context;
13059 }
13060
13061 return scheduleRootUpdate(current$$1, element, expirationTime, callback);
13062}
13063
13064function createContainer(containerInfo, isConcurrent, hydrate) {
13065 return createFiberRoot(containerInfo, isConcurrent, hydrate);
13066}
13067
13068function updateContainer(element, container, parentComponent, callback) {
13069 var current$$1 = container.current;
13070 var currentTime = requestCurrentTime();
13071 var expirationTime = computeExpirationForFiber(currentTime, current$$1);
13072 return updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback);
13073}
13074
13075
13076
13077
13078
13079var overrideProps = null;
13080
13081{
13082 var copyWithSetImpl = function (obj, path, idx, value) {
13083 if (idx >= path.length) {
13084 return value;
13085 }
13086 var key = path[idx];
13087 var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj);
13088 // $FlowFixMe number or string is fine here
13089 updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value);
13090 return updated;
13091 };
13092
13093 var copyWithSet = function (obj, path, value) {
13094 return copyWithSetImpl(obj, path, 0, value);
13095 };
13096
13097 // Support DevTools props for function components, forwardRef, memo, host components, etc.
13098 overrideProps = function (fiber, path, value) {
13099 flushPassiveEffects();
13100 fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
13101 if (fiber.alternate) {
13102 fiber.alternate.pendingProps = fiber.pendingProps;
13103 }
13104 scheduleWork(fiber, Sync);
13105 };
13106}
13107
13108function injectIntoDevTools(devToolsConfig) {
13109 var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
13110 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
13111
13112
13113 return injectInternals(_assign({}, devToolsConfig, {
13114 overrideProps: overrideProps,
13115 currentDispatcherRef: ReactCurrentDispatcher,
13116 findHostInstanceByFiber: function (fiber) {
13117 var hostFiber = findCurrentHostFiber(fiber);
13118 if (hostFiber === null) {
13119 return null;
13120 }
13121 return hostFiber.stateNode;
13122 },
13123 findFiberByHostInstance: function (instance) {
13124 if (!findFiberByHostInstance) {
13125 // Might not be implemented by the renderer.
13126 return null;
13127 }
13128 return findFiberByHostInstance(instance);
13129 }
13130 }));
13131}
13132
13133// This file intentionally does *not* have the Flow annotation.
13134// Don't add it. See `./inline-typed.js` for an explanation.
13135
13136var container = _class({
13137
13138 grab: function(){
13139 for (var i = 0; i < arguments.length; i++) arguments[i].inject(this);
13140 return this;
13141 },
13142
13143 empty: function(){
13144 var node;
13145 while (node = this.firstChild) node.eject();
13146 return this;
13147 }
13148
13149});
13150
13151function elementFrom(node){
13152 if (node.toElement) return node.toElement();
13153 if (node.getDOMNode) return node.getDOMNode();
13154 if (node.getNode) return node.getNode();
13155 return node;
13156}
13157
13158var native_1 = _class({
13159
13160 // conventions
13161
13162 toElement: function(){
13163 return this.element;
13164 },
13165
13166 getDOMNode: function(){
13167 return this.toElement();
13168 },
13169
13170 getNode: function(){
13171 return this.toElement();
13172 },
13173
13174 // placement
13175
13176 inject: function(container){
13177 (container.containerElement || elementFrom(container))
13178 .appendChild(this.element);
13179 return this;
13180 },
13181
13182 injectBefore: function(sibling){
13183 var element = elementFrom(sibling);
13184 element.parentNode.insertBefore(this.element, element);
13185 return this;
13186 },
13187
13188 eject: function(){
13189 var element = this.element, parent = element.parentNode;
13190 if (parent) parent.removeChild(element); // TODO: VML Nodes are dead after being ejected
13191 return this;
13192 },
13193
13194 // events
13195
13196 subscribe: function(type, fn, bind){
13197 if (typeof type != 'string'){ // listen type / fn with object
13198 var subscriptions = [];
13199 for (var t in type) subscriptions.push(this.subscribe(t, type[t]));
13200 return function(){ // unsubscribe
13201 for (var i = 0, l = subscriptions.length; i < l; i++)
13202 subscriptions[i]();
13203 return this;
13204 };
13205 } else { // listen to one
13206 if (!bind) bind = this;
13207 var bound;
13208 if (typeof fn === 'function'){
13209 bound = fn.bind ? fn.bind(bind)
13210 : function(){ return fn.apply(bind, arguments); };
13211 } else {
13212 bound = fn;
13213 }
13214 var element = this.element;
13215 if (element.addEventListener){
13216 element.addEventListener(type, bound, false);
13217 return function(){ // unsubscribe
13218 element.removeEventListener(type, bound, false);
13219 return this;
13220 };
13221 } else {
13222 element.attachEvent('on' + type, bound);
13223 return function(){ // unsubscribe
13224 element.detachEvent('on' + type, bound);
13225 return this;
13226 };
13227 }
13228 }
13229 }
13230
13231});
13232
13233var fps = 1000 / 60;
13234var invalids = [];
13235var renderTimer;
13236var renderInvalids = function(){
13237 clearTimeout(renderTimer);
13238 renderTimer = null;
13239 var canvases = invalids;
13240 invalids = [];
13241 for (var i = 0, l = canvases.length; i < l; i++){
13242 var c = canvases[i];
13243 c._valid = true;
13244 c.render();
13245 }
13246};
13247
13248var resolution = typeof window !== 'undefined' && window.devicePixelRatio || 1;
13249
13250var previousHit = null;
13251var previousHitSurface = null;
13252
13253var CanvasSurface = _class(native_1, container, {
13254
13255 initialize: function(width, height, existingElement){
13256 var element = this.element = existingElement || document.createElement('canvas');
13257 var context = this.context = element.getContext('2d');
13258 this._valid = true;
13259 if (width != null && height != null) this.resize(width, height);
13260
13261 element.addEventListener('mousemove', this, false);
13262 element.addEventListener('mouseout', this, false);
13263 element.addEventListener('mouseover', this, false);
13264 element.addEventListener('mouseup', this, false);
13265 element.addEventListener('mousedown', this, false);
13266 element.addEventListener('click', this, false);
13267 },
13268
13269 handleEvent: function(event){
13270 if (event.clientX == null) return;
13271 var element = this.element,
13272 rect = element.getBoundingClientRect(),
13273 x = event.clientX - rect.left - element.clientLeft,
13274 y = event.clientY - rect.top - element.clientTop,
13275 hit = this.hitTest(x, y);
13276
13277 if (hit !== previousHit){
13278 if (previousHit){
13279 previousHit.dispatch({
13280 type: 'mouseout',
13281 target: previousHit,
13282 relatedTarget: hit,
13283 sourceEvent: event
13284 });
13285 }
13286 if (hit){
13287 hit.dispatch({
13288 type: 'mouseover',
13289 target: hit,
13290 relatedTarget: previousHit,
13291 sourceEvent: event
13292 });
13293 }
13294 previousHit = hit;
13295 previousHitSurface = this;
13296 this.refreshCursor();
13297 }
13298
13299 if (hit) hit.dispatch(event);
13300 },
13301
13302 refreshCursor: function(){
13303 if (previousHitSurface !== this) return;
13304 var hit = previousHit, hitCursor = '', hitTooltip = '';
13305 while (hit){
13306 if (!hitCursor && hit._cursor){
13307 hitCursor = hit._cursor;
13308 if (hitTooltip) break;
13309 }
13310 if (!hitTooltip && hit._tooltip){
13311 hitTooltip = hit._tooltip;
13312 if (hitCursor) break;
13313 }
13314 hit = hit.parentNode;
13315 }
13316 // TODO: No way to set cursor/title on the surface
13317 this.element.style.cursor = hitCursor;
13318 this.element.title = hitTooltip;
13319 },
13320
13321 resize: function(width, height){
13322 var element = this.element;
13323 element.setAttribute('width', width * resolution);
13324 element.setAttribute('height', height * resolution);
13325 element.style.width = width + 'px';
13326 element.style.height = height + 'px';
13327 this.width = width;
13328 this.height = height;
13329 return this;
13330 },
13331
13332 invalidate: function(left, top, width, height){
13333 if (this._valid){
13334 this._valid = false;
13335 invalids.push(this);
13336 if (!renderTimer){
13337 if (window.mozRequestAnimationFrame){
13338 renderTimer = true;
13339 window.mozRequestAnimationFrame(renderInvalids);
13340 } else {
13341 renderTimer = setTimeout(renderInvalids, fps);
13342 }
13343 }
13344 }
13345 return this;
13346 },
13347
13348 hitTest: function(x, y){
13349 if (x < 0 || y < 0 || x > this.width || y > this.height) return null;
13350 var node = this.lastChild;
13351 while (node){
13352 var hit = node.hitTest(x, y);
13353 if (hit) return hit;
13354 node = node.previousSibling;
13355 }
13356 return null;
13357 },
13358
13359 render: function(){
13360 var node = this.firstChild, context = this.context;
13361 context.setTransform(resolution, 0, 0, resolution, 0, 0);
13362 context.clearRect(0, 0, this.width, this.height);
13363 while (node){
13364 node.renderTo(context, resolution, 0, 0, resolution, 0, 0);
13365 node = node.nextSibling;
13366 }
13367 this.refreshCursor();
13368 }
13369
13370});
13371
13372CanvasSurface.tagName = 'canvas';
13373
13374var surface = CanvasSurface;
13375
13376var path$2 = _class({
13377
13378 initialize: function(path){
13379 this.reset().push(path);
13380 },
13381
13382 /* parser */
13383
13384 push: function(){
13385 var p = Array.prototype.join.call(arguments, ' ')
13386 .match(/[a-df-z]|[\-+]?(?:[\d\.]e[\-+]?|[^\s\-+,a-z])+/ig);
13387 if (!p) return this;
13388
13389 var last, cmd = p[0], i = 1;
13390 while (cmd){
13391 switch (cmd){
13392 case 'm': this.move(p[i++], p[i++]); break;
13393 case 'l': this.line(p[i++], p[i++]); break;
13394 case 'c': this.curve(p[i++], p[i++], p[i++], p[i++], p[i++], p[i++]); break;
13395 case 's': this.curve(p[i++], p[i++], null, null, p[i++], p[i++]); break;
13396 case 'q': this.curve(p[i++], p[i++], p[i++], p[i++]); break;
13397 case 't': this.curve(p[i++], p[i++]); break;
13398 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;
13399 case 'h': this.line(p[i++], 0); break;
13400 case 'v': this.line(0, p[i++]); break;
13401
13402 case 'M': this.moveTo(p[i++], p[i++]); break;
13403 case 'L': this.lineTo(p[i++], p[i++]); break;
13404 case 'C': this.curveTo(p[i++], p[i++], p[i++], p[i++], p[i++], p[i++]); break;
13405 case 'S': this.curveTo(p[i++], p[i++], null, null, p[i++], p[i++]); break;
13406 case 'Q': this.curveTo(p[i++], p[i++], p[i++], p[i++]); break;
13407 case 'T': this.curveTo(p[i++], p[i++]); break;
13408 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;
13409 case 'H': this.lineTo(p[i++], this.penY); break;
13410 case 'V': this.lineTo(this.penX, p[i++]); break;
13411
13412 case 'Z': case 'z': this.close(); break;
13413 default: cmd = last; i--; continue;
13414 }
13415
13416 last = cmd;
13417 if (last == 'm') last = 'l';
13418 else if (last == 'M') last = 'L';
13419 cmd = p[i++];
13420 }
13421 return this;
13422 },
13423
13424 /* utility methods */
13425
13426 reset: function(){
13427 this.penX = this.penY = 0;
13428 this.penDownX = this.penDownY = null;
13429 this._pivotX = this._pivotY = 0;
13430 this.onReset();
13431 return this;
13432 },
13433
13434 move: function(x,y){
13435 this.onMove(this.penX, this.penY, this._pivotX = this.penX += (+x), this._pivotY = this.penY += (+y));
13436 return this;
13437 },
13438 moveTo: function(x,y){
13439 this.onMove(this.penX, this.penY, this._pivotX = this.penX = (+x), this._pivotY = this.penY = (+y));
13440 return this;
13441 },
13442
13443 line: function(x,y){
13444 return this.lineTo(this.penX + (+x), this.penY + (+y));
13445 },
13446 lineTo: function(x,y){
13447 if (this.penDownX == null){ this.penDownX = this.penX; this.penDownY = this.penY; }
13448 this.onLine(this.penX, this.penY, this._pivotX = this.penX = (+x), this._pivotY = this.penY = (+y));
13449 return this;
13450 },
13451
13452 curve: function(c1x, c1y, c2x, c2y, ex, ey){
13453 var x = this.penX, y = this.penY;
13454 return this.curveTo(
13455 x + (+c1x), y + (+c1y),
13456 c2x == null ? null : x + (+c2x),
13457 c2y == null ? null : y + (+c2y),
13458 ex == null ? null : x + (+ex),
13459 ey == null ? null : y + (+ey)
13460 );
13461 },
13462 curveTo: function(c1x, c1y, c2x, c2y, ex, ey){
13463 var x = this.penX, y = this.penY;
13464 if (c2x == null){
13465 c2x = +c1x; c2y = +c1y;
13466 c1x = (x * 2) - (this._pivotX || 0); c1y = (y * 2) - (this._pivotY || 0);
13467 }
13468 if (ex == null){
13469 this._pivotX = +c1x; this._pivotY = +c1y;
13470 ex = +c2x; ey = +c2y;
13471 c2x = (ex + (+c1x) * 2) / 3; c2y = (ey + (+c1y) * 2) / 3;
13472 c1x = (x + (+c1x) * 2) / 3; c1y = (y + (+c1y) * 2) / 3;
13473 } else {
13474 this._pivotX = +c2x; this._pivotY = +c2y;
13475 }
13476 if (this.penDownX == null){ this.penDownX = x; this.penDownY = y; }
13477 this.onBezierCurve(x, y, +c1x, +c1y, +c2x, +c2y, this.penX = +ex, this.penY = +ey);
13478 return this;
13479 },
13480
13481 arc: function(x, y, rx, ry, outer, counterClockwise, rotation){
13482 return this.arcTo(this.penX + (+x), this.penY + (+y), rx, ry, outer, counterClockwise, rotation);
13483 },
13484 arcTo: function(x, y, rx, ry, outer, counterClockwise, rotation){
13485 ry = Math.abs(+ry || +rx || (+y - this.penY));
13486 rx = Math.abs(+rx || (+x - this.penX));
13487
13488 if (!rx || !ry || (x == this.penX && y == this.penY)) return this.lineTo(x, y);
13489
13490 var tX = this.penX, tY = this.penY, clockwise = !+counterClockwise, large = !!+outer;
13491
13492 var rad = rotation ? rotation * Math.PI / 180 : 0, cos = Math.cos(rad), sin = Math.sin(rad);
13493 x -= tX; y -= tY;
13494
13495 // Ellipse Center
13496 var cx = cos * x / 2 + sin * y / 2,
13497 cy = -sin * x / 2 + cos * y / 2,
13498 rxry = rx * rx * ry * ry,
13499 rycx = ry * ry * cx * cx,
13500 rxcy = rx * rx * cy * cy,
13501 a = rxry - rxcy - rycx;
13502
13503 if (a < 0){
13504 a = Math.sqrt(1 - a / rxry);
13505 rx *= a; ry *= a;
13506 cx = x / 2; cy = y / 2;
13507 } else {
13508 a = Math.sqrt(a / (rxcy + rycx));
13509 if (large == clockwise) a = -a;
13510 var cxd = -a * cy * rx / ry,
13511 cyd = a * cx * ry / rx;
13512 cx = cos * cxd - sin * cyd + x / 2;
13513 cy = sin * cxd + cos * cyd + y / 2;
13514 }
13515
13516 // Rotation + Scale Transform
13517 var xx = cos / rx, yx = sin / rx,
13518 xy = -sin / ry, yy = cos / ry;
13519
13520 // Start and End Angle
13521 var sa = Math.atan2(xy * -cx + yy * -cy, xx * -cx + yx * -cy),
13522 ea = Math.atan2(xy * (x - cx) + yy * (y - cy), xx * (x - cx) + yx * (y - cy));
13523
13524 cx += tX; cy += tY;
13525 x += tX; y += tY;
13526
13527 // Circular Arc
13528 if (this.penDownX == null){ this.penDownX = this.penX; this.penDownY = this.penY; }
13529 this.onArc(
13530 tX, tY, this._pivotX = this.penX = x, this._pivotY = this.penY = y,
13531 cx, cy, rx, ry, sa, ea, !clockwise, rotation
13532 );
13533 return this;
13534 },
13535
13536 counterArc: function(x, y, rx, ry, outer){
13537 return this.arc(x, y, rx, ry, outer, true);
13538 },
13539 counterArcTo: function(x, y, rx, ry, outer){
13540 return this.arcTo(x, y, rx, ry, outer, true);
13541 },
13542
13543 close: function(){
13544 if (this.penDownX != null){
13545 this.onClose(this.penX, this.penY, this.penX = this.penDownX, this.penY = this.penDownY);
13546 this.penDownX = null;
13547 }
13548 return this;
13549 },
13550
13551 /* overridable handlers */
13552
13553 onReset: function(){
13554 },
13555
13556 onMove: function(sx, sy, ex, ey){
13557 },
13558
13559 onLine: function(sx, sy, ex, ey){
13560 this.onBezierCurve(sx, sy, sx, sy, ex, ey, ex, ey);
13561 },
13562
13563 onBezierCurve: function(sx, sy, c1x, c1y, c2x, c2y, ex, ey){
13564 var gx = ex - sx, gy = ey - sy,
13565 g = gx * gx + gy * gy,
13566 v1, v2, cx, cy, u;
13567
13568 cx = c1x - sx; cy = c1y - sy;
13569 u = cx * gx + cy * gy;
13570
13571 if (u > g){
13572 cx -= gx;
13573 cy -= gy;
13574 } else if (u > 0 && g != 0){
13575 cx -= u/g * gx;
13576 cy -= u/g * gy;
13577 }
13578
13579 v1 = cx * cx + cy * cy;
13580
13581 cx = c2x - sx; cy = c2y - sy;
13582 u = cx * gx + cy * gy;
13583
13584 if (u > g){
13585 cx -= gx;
13586 cy -= gy;
13587 } else if (u > 0 && g != 0){
13588 cx -= u/g * gx;
13589 cy -= u/g * gy;
13590 }
13591
13592 v2 = cx * cx + cy * cy;
13593
13594 if (v1 < 0.01 && v2 < 0.01){
13595 this.onLine(sx, sy, ex, ey);
13596 return;
13597 }
13598
13599 // Avoid infinite recursion
13600 if (isNaN(v1) || isNaN(v2)){
13601 throw new Error('Bad input');
13602 }
13603
13604 // Split curve
13605 var s1x = (c1x + c2x) * 0.5, s1y = (c1y + c2y) * 0.5,
13606 l1x = (c1x + sx) * 0.5, l1y = (c1y + sy) * 0.5,
13607 l2x = (l1x + s1x) * 0.5, l2y = (l1y + s1y) * 0.5,
13608 r2x = (ex + c2x) * 0.5, r2y = (ey + c2y) * 0.5,
13609 r1x = (r2x + s1x) * 0.5, r1y = (r2y + s1y) * 0.5,
13610 l2r1x = (l2x + r1x) * 0.5, l2r1y = (l2y + r1y) * 0.5;
13611
13612 // TODO: Manual stack if necessary. Currently recursive without tail optimization.
13613 this.onBezierCurve(sx, sy, l1x, l1y, l2x, l2y, l2r1x, l2r1y);
13614 this.onBezierCurve(l2r1x, l2r1y, r1x, r1y, r2x, r2y, ex, ey);
13615 },
13616
13617 onArc: function(sx, sy, ex, ey, cx, cy, rx, ry, sa, ea, ccw, rotation){
13618 // Inverse Rotation + Scale Transform
13619 var rad = rotation ? rotation * Math.PI / 180 : 0, cos = Math.cos(rad), sin = Math.sin(rad),
13620 xx = cos * rx, yx = -sin * ry,
13621 xy = sin * rx, yy = cos * ry;
13622
13623 // Bezier Curve Approximation
13624 var arc = ea - sa;
13625 if (arc < 0 && !ccw) arc += Math.PI * 2;
13626 else if (arc > 0 && ccw) arc -= Math.PI * 2;
13627
13628 var n = Math.ceil(Math.abs(arc / (Math.PI / 2))),
13629 step = arc / n,
13630 k = (4 / 3) * Math.tan(step / 4);
13631
13632 var x = Math.cos(sa), y = Math.sin(sa);
13633
13634 for (var i = 0; i < n; i++){
13635 var cp1x = x - k * y, cp1y = y + k * x;
13636
13637 sa += step;
13638 x = Math.cos(sa); y = Math.sin(sa);
13639
13640 var cp2x = x + k * y, cp2y = y - k * x;
13641
13642 this.onBezierCurve(
13643 sx, sy,
13644 cx + xx * cp1x + yx * cp1y, cy + xy * cp1x + yy * cp1y,
13645 cx + xx * cp2x + yx * cp2y, cy + xy * cp2x + yy * cp2y,
13646 (sx = (cx + xx * x + yx * y)), (sy = (cy + xy * x + yy * y))
13647 );
13648 }
13649 },
13650
13651 onClose: function(sx, sy, ex, ey){
13652 this.onLine(sx, sy, ex, ey);
13653 }
13654
13655});
13656
13657var CanvasPath = _class(path$2, {
13658
13659 initialize: function(path){
13660 this.reset();
13661 if (path instanceof CanvasPath){
13662 this.path = path.path.slice(0);
13663 } else if (path){
13664 if (path.applyToPath)
13665 path.applyToPath(this);
13666 else
13667 this.push(path);
13668 }
13669 },
13670
13671 onReset: function(){
13672 this.path = [];
13673 },
13674
13675 onMove: function(sx, sy, x, y){
13676 this.path.push(function(context){
13677 context.moveTo(x, y);
13678 });
13679 },
13680
13681 onLine: function(sx, sy, x, y){
13682 this.path.push(function(context){
13683 context.lineTo(x, y);
13684 });
13685 },
13686
13687 onBezierCurve: function(sx, sy, p1x, p1y, p2x, p2y, x, y){
13688 this.path.push(function(context){
13689 context.bezierCurveTo(p1x, p1y, p2x, p2y, x, y);
13690 });
13691 },
13692
13693 _arcToBezier: path$2.prototype.onArc,
13694
13695 onArc: function(sx, sy, ex, ey, cx, cy, rx, ry, sa, ea, ccw, rotation){
13696 if (rx != ry || rotation) return this._arcToBezier(sx, sy, ex, ey, cx, cy, rx, ry, sa, ea, ccw, rotation);
13697 this.path.push(function(context){
13698 context.arc(cx, cy, rx, sa, ea, ccw);
13699 });
13700 },
13701
13702 onClose: function(){
13703 this.path.push(function(context){
13704 context.closePath();
13705 });
13706 },
13707
13708 toCommands: function(){
13709 return this.path.slice(0);
13710 }
13711
13712});
13713
13714var path = CanvasPath;
13715
13716var colors = {
13717 maroon: '#800000', red: '#ff0000', orange: '#ffA500', yellow: '#ffff00', olive: '#808000',
13718 purple: '#800080', fuchsia: "#ff00ff", white: '#ffffff', lime: '#00ff00', green: '#008000',
13719 navy: '#000080', blue: '#0000ff', aqua: '#00ffff', teal: '#008080',
13720 black: '#000000', silver: '#c0c0c0', gray: '#808080'
13721};
13722
13723var map = function(array, fn){
13724 var results = [];
13725 for (var i = 0, l = array.length; i < l; i++)
13726 results[i] = fn(array[i], i);
13727 return results;
13728};
13729
13730var Color = function(color, type){
13731
13732 if (color.isColor){
13733
13734 this.red = color.red;
13735 this.green = color.green;
13736 this.blue = color.blue;
13737 this.alpha = color.alpha;
13738
13739 } else {
13740
13741 var namedColor = colors[color];
13742 if (namedColor){
13743 color = namedColor;
13744 type = 'hex';
13745 }
13746
13747 switch (typeof color){
13748 case 'string': if (!type) type = (type = color.match(/^rgb|^hsb|^hsl/)) ? type[0] : 'hex'; break;
13749 case 'object': type = type || 'rgb'; color = color.toString(); break;
13750 case 'number': type = 'hex'; color = color.toString(16); break;
13751 }
13752
13753 color = Color['parse' + type.toUpperCase()](color);
13754 this.red = color[0];
13755 this.green = color[1];
13756 this.blue = color[2];
13757 this.alpha = color[3];
13758 }
13759
13760 this.isColor = true;
13761
13762};
13763
13764var limit = function(number, min, max){
13765 return Math.min(max, Math.max(min, number));
13766};
13767
13768var listMatch = /([-.\d]+\%?)\s*,\s*([-.\d]+\%?)\s*,\s*([-.\d]+\%?)\s*,?\s*([-.\d]*\%?)/;
13769var hexMatch = /^#?([a-f0-9]{1,2})([a-f0-9]{1,2})([a-f0-9]{1,2})([a-f0-9]{0,2})$/i;
13770
13771Color.parseRGB = function(color){
13772 return map(color.match(listMatch).slice(1), function(bit, i){
13773 if (bit) bit = parseFloat(bit) * (bit[bit.length - 1] == '%' ? 2.55 : 1);
13774 return (i < 3) ? Math.round(((bit %= 256) < 0) ? bit + 256 : bit) : limit(((bit === '') ? 1 : Number(bit)), 0, 1);
13775 });
13776};
13777
13778Color.parseHEX = function(color){
13779 if (color.length == 1) color = color + color + color;
13780 return map(color.match(hexMatch).slice(1), function(bit, i){
13781 if (i == 3) return (bit) ? parseInt(bit, 16) / 255 : 1;
13782 return parseInt((bit.length == 1) ? bit + bit : bit, 16);
13783 });
13784};
13785
13786Color.parseHSB = function(color){
13787 var hsb = map(color.match(listMatch).slice(1), function(bit, i){
13788 if (bit) bit = parseFloat(bit);
13789 if (i === 0) return Math.round(((bit %= 360) < 0) ? (bit + 360) : bit);
13790 else if (i < 3) return limit(Math.round(bit), 0, 100);
13791 else return limit(((bit === '') ? 1 : Number(bit)), 0, 1);
13792 });
13793
13794 var a = hsb[3];
13795 var br = Math.round(hsb[2] / 100 * 255);
13796 if (hsb[1] == 0) return [br, br, br, a];
13797
13798 var hue = hsb[0];
13799 var f = hue % 60;
13800 var p = Math.round((hsb[2] * (100 - hsb[1])) / 10000 * 255);
13801 var q = Math.round((hsb[2] * (6000 - hsb[1] * f)) / 600000 * 255);
13802 var t = Math.round((hsb[2] * (6000 - hsb[1] * (60 - f))) / 600000 * 255);
13803
13804 switch (Math.floor(hue / 60)){
13805 case 0: return [br, t, p, a];
13806 case 1: return [q, br, p, a];
13807 case 2: return [p, br, t, a];
13808 case 3: return [p, q, br, a];
13809 case 4: return [t, p, br, a];
13810 default: return [br, p, q, a];
13811 }
13812};
13813
13814Color.parseHSL = function(color){
13815 var hsb = map(color.match(listMatch).slice(1), function(bit, i){
13816 if (bit) bit = parseFloat(bit);
13817 if (i === 0) return Math.round(((bit %= 360) < 0) ? (bit + 360) : bit);
13818 else if (i < 3) return limit(Math.round(bit), 0, 100);
13819 else return limit(((bit === '') ? 1 : Number(bit)), 0, 1);
13820 });
13821
13822 var h = hsb[0] / 60;
13823 var s = hsb[1] / 100;
13824 var l = hsb[2] / 100;
13825 var a = hsb[3];
13826
13827 var c = (1 - Math.abs(2 * l - 1)) * s;
13828 var x = c * (1 - Math.abs(h % 2 - 1));
13829 var m = l - c / 2;
13830
13831 var p = Math.round((c + m) * 255);
13832 var q = Math.round((x + m) * 255);
13833 var t = Math.round((m) * 255);
13834
13835 switch (Math.floor(h)){
13836 case 0: return [p, q, t, a];
13837 case 1: return [q, p, t, a];
13838 case 2: return [t, p, q, a];
13839 case 3: return [t, q, p, a];
13840 case 4: return [q, t, p, a];
13841 default: return [p, t, q, a];
13842 }
13843};
13844
13845var toString = function(type, array){
13846 if (array[3] != 1) type += 'a';
13847 else array.pop();
13848 return type + '(' + array.join(', ') + ')';
13849};
13850
13851Color.prototype = {
13852
13853 toHSB: function(array){
13854 var red = this.red, green = this.green, blue = this.blue, alpha = this.alpha;
13855
13856 var max = Math.max(red, green, blue), min = Math.min(red, green, blue), delta = max - min;
13857 var hue = 0, saturation = (delta != 0) ? delta / max : 0, brightness = max / 255;
13858 if (saturation){
13859 var rr = (max - red) / delta, gr = (max - green) / delta, br = (max - blue) / delta;
13860 hue = (red == max) ? br - gr : (green == max) ? 2 + rr - br : 4 + gr - rr;
13861 if ((hue /= 6) < 0) hue++;
13862 }
13863
13864 var hsb = [Math.round(hue * 360), Math.round(saturation * 100), Math.round(brightness * 100), alpha];
13865
13866 return (array) ? hsb : toString('hsb', hsb);
13867 },
13868
13869 toHSL: function(array){
13870 var red = this.red, green = this.green, blue = this.blue, alpha = this.alpha;
13871
13872 var max = Math.max(red, green, blue), min = Math.min(red, green, blue), delta = max - min;
13873 var hue = 0, saturation = (delta != 0) ? delta / (255 - Math.abs((max + min) - 255)) : 0, lightness = (max + min) / 512;
13874 if (saturation){
13875 var rr = (max - red) / delta, gr = (max - green) / delta, br = (max - blue) / delta;
13876 hue = (red == max) ? br - gr : (green == max) ? 2 + rr - br : 4 + gr - rr;
13877 if ((hue /= 6) < 0) hue++;
13878 }
13879
13880 var hsl = [Math.round(hue * 360), Math.round(saturation * 100), Math.round(lightness * 100), alpha];
13881
13882 return (array) ? hsl : toString('hsl', hsl);
13883 },
13884
13885 toHEX: function(array){
13886
13887 var a = this.alpha;
13888 var alpha = ((a = Math.round((a * 255)).toString(16)).length == 1) ? a + a : a;
13889
13890 var hex = map([this.red, this.green, this.blue], function(bit){
13891 bit = bit.toString(16);
13892 return (bit.length == 1) ? '0' + bit : bit;
13893 });
13894
13895 return (array) ? hex.concat(alpha) : '#' + hex.join('') + ((alpha == 'ff') ? '' : alpha);
13896 },
13897
13898 toRGB: function(array){
13899 var rgb = [this.red, this.green, this.blue, this.alpha];
13900 return (array) ? rgb : toString('rgb', rgb);
13901 }
13902
13903};
13904
13905Color.prototype.toString = Color.prototype.toRGB;
13906
13907Color.hex = function(hex){
13908 return new Color(hex, 'hex');
13909};
13910
13911if (commonjsGlobal.hex == null) commonjsGlobal.hex = Color.hex;
13912
13913Color.hsb = function(h, s, b, a){
13914 return new Color([h || 0, s || 0, b || 0, (a == null) ? 1 : a], 'hsb');
13915};
13916
13917if (commonjsGlobal.hsb == null) commonjsGlobal.hsb = Color.hsb;
13918
13919Color.hsl = function(h, s, l, a){
13920 return new Color([h || 0, s || 0, l || 0, (a == null) ? 1 : a], 'hsl');
13921};
13922
13923if (commonjsGlobal.hsl == null) commonjsGlobal.hsl = Color.hsl;
13924
13925Color.rgb = function(r, g, b, a){
13926 return new Color([r || 0, g || 0, b || 0, (a == null) ? 1 : a], 'rgb');
13927};
13928
13929if (commonjsGlobal.rgb == null) commonjsGlobal.rgb = Color.rgb;
13930
13931Color.detach = function(color){
13932 color = new Color(color);
13933 return [Color.rgb(color.red, color.green, color.blue).toString(), color.alpha];
13934};
13935
13936var color = Color;
13937
13938var dummy = _class({
13939
13940 // placement
13941
13942 _resetPlacement: function(){
13943 var container = this.parentNode;
13944 if (container){
13945 var previous = this.previousSibling, next = this.nextSibling;
13946 if (previous){
13947 previous.nextSibling = next;
13948 } else {
13949 container.firstChild = next;
13950 }
13951 if (next){
13952 next.previousSibling = previous;
13953 } else {
13954 container.lastChild = this.previousSibling;
13955 }
13956 }
13957 this.previousSibling = null;
13958 this.nextSibling = null;
13959 this.parentNode = null;
13960 return this;
13961 },
13962
13963 inject: function(container){
13964 this._resetPlacement();
13965 var last = container.lastChild;
13966 if (last){
13967 last.nextSibling = this;
13968 this.previousSibling = last;
13969 } else {
13970 container.firstChild = this;
13971 }
13972 container.lastChild = this;
13973 this.parentNode = container;
13974 this._place();
13975 return this;
13976 },
13977
13978 injectBefore: function(sibling){
13979 this._resetPlacement();
13980 var container = sibling.parentNode;
13981 if (!container) return this;
13982 var previous = sibling.previousSibling;
13983 if (previous){
13984 previous.nextSibling = this;
13985 this.previousSibling = previous;
13986 } else {
13987 container.firstChild = this;
13988 }
13989 sibling.previousSibling = this;
13990 this.nextSibling = sibling;
13991 this.parentNode = container;
13992 this._place();
13993 return this;
13994 },
13995
13996 eject: function(){
13997 this._resetPlacement();
13998 this._place();
13999 return this;
14000 },
14001
14002 _place: function(){},
14003
14004 // events
14005
14006 dispatch: function(event){
14007 var events = this._events,
14008 listeners = events && events[event.type];
14009 if (listeners){
14010 listeners = listeners.slice(0);
14011 for (var i = 0, l = listeners.length; i < l; i++){
14012 var fn = listeners[i], result;
14013 if (typeof fn == 'function')
14014 result = fn.call(this, event);
14015 else
14016 result = fn.handleEvent(event);
14017 if (result === false) event.preventDefault();
14018 }
14019 }
14020 if (this.parentNode && this.parentNode.dispatch){
14021 this.parentNode.dispatch(event);
14022 }
14023 },
14024
14025 subscribe: function(type, fn, bind){
14026 if (typeof type != 'string'){ // listen type / fn with object
14027 var subscriptions = [];
14028 for (var t in type) subscriptions.push(this.subscribe(t, type[t]));
14029 return function(){ // unsubscribe
14030 for (var i = 0, l = subscriptions.length; i < l; i++)
14031 subscriptions[i]();
14032 return this;
14033 };
14034 } else { // listen to one
14035 var bound = typeof fn === 'function' ? fn.bind(bind || this) : fn,
14036 events = this._events || (this._events = {}),
14037 listeners = events[type] || (events[type] = []);
14038 listeners.push(bound);
14039 return function(){
14040 // unsubscribe
14041 for (var i = 0, l = listeners.length; i < l; i++){
14042 if (listeners[i] === bound){
14043 listeners.splice(i, 1);
14044 break;
14045 }
14046 }
14047 }
14048 }
14049 }
14050
14051});
14052
14053var CanvasNode = _class(transform, dummy, {
14054
14055 invalidate: function(){
14056 if (this.parentNode) this.parentNode.invalidate();
14057 if (this._layer) this._layerCache = null;
14058 return this;
14059 },
14060
14061 _place: function(){
14062 this.invalidate();
14063 },
14064
14065 _transform: function(){
14066 this.invalidate();
14067 },
14068
14069 blend: function(opacity){
14070 if (opacity >= 1 && this._layer) this._layer = null;
14071 this._opacity = opacity;
14072 if (this.parentNode) this.parentNode.invalidate();
14073 return this;
14074 },
14075
14076 // visibility
14077
14078 hide: function(){
14079 this._invisible = true;
14080 if (this.parentNode) this.parentNode.invalidate();
14081 return this;
14082 },
14083
14084 show: function(){
14085 this._invisible = false;
14086 if (this.parentNode) this.parentNode.invalidate();
14087 return this;
14088 },
14089
14090 // interaction
14091
14092 indicate: function(cursor, tooltip){
14093 this._cursor = cursor;
14094 this._tooltip = tooltip;
14095 return this.invalidate();
14096 },
14097
14098 hitTest: function(x, y){
14099 if (this._invisible) return null;
14100 var point = this.inversePoint(x, y);
14101 if (!point) return null;
14102 return this.localHitTest(point.x, point.y);
14103 },
14104
14105 // rendering
14106
14107 renderTo: function(context, xx, yx, xy, yy, x, y){
14108 var opacity = this._opacity;
14109 if (opacity == null || opacity >= 1){
14110 return this.renderLayerTo(context, xx, yx, xy, yy, x, y);
14111 }
14112
14113 // Render to a compositing layer and cache it
14114
14115 var layer = this._layer, canvas, isDirty = true,
14116 w = context.canvas.width, h = context.canvas.height;
14117 if (layer){
14118 layer.setTransform(1, 0, 0, 1, 0, 0);
14119 canvas = layer.canvas;
14120 if (canvas.width < w || canvas.height < h){
14121 canvas.width = w;
14122 canvas.height = h;
14123 } else {
14124 var c = this._layerCache;
14125 if (c && c.xx === xx && c.yx === yx && c.xy === xy
14126 && c.yy === yy && c.x === x && c.y === y){
14127 isDirty = false;
14128 } else {
14129 layer.clearRect(0, 0, w, h);
14130 }
14131 }
14132 } else {
14133 canvas = document.createElement('canvas');
14134 canvas.width = w;
14135 canvas.height = h;
14136 this._layer = layer = canvas.getContext('2d');
14137 }
14138
14139 if (isDirty){
14140 this.renderLayerTo(layer, xx, yx, xy, yy, x, y);
14141 this._layerCache = {
14142 xx: xx,
14143 yx: yx,
14144 xy: xy,
14145 yy: yy,
14146 x: x,
14147 y: y
14148 };
14149 }
14150
14151 context.globalAlpha = opacity;
14152 context.setTransform(1, 0, 0, 1, 0, 0);
14153 context.drawImage(
14154 canvas,
14155 0, 0, w, h,
14156 0, 0, w, h
14157 );
14158 context.globalAlpha = 1;
14159 }
14160
14161});
14162
14163var node = CanvasNode;
14164
14165var genericCanvas = typeof document !== 'undefined' && document.createElement('canvas');
14166var genericContext = genericCanvas && genericCanvas.getContext && genericCanvas.getContext('2d');
14167
14168function recolorImage(img, color1, color2){
14169 // TODO: Fix this experimental implementation
14170 color1 = color.detach(color1);
14171 color2 = color.detach(color2);
14172 var canvas = document.createElement('canvas'),
14173 context = canvas.getContext('2d');
14174 canvas.width = img.width;
14175 canvas.height = img.height;
14176 context.fillStyle = color2[0];
14177 context.fillRect(0, 0, img.width, img.height);
14178 context.globalCompositeOperation = 'lighter';
14179 context.drawImage(img, 0, 0);
14180 return canvas;
14181}
14182
14183var Base = _class(node, {
14184
14185 initialize: function(){
14186 this._fill = null;
14187 this._pendingFill = null;
14188 this._fillTransform = null;
14189 this._stroke = null;
14190 this._strokeCap = null;
14191 this._strokeDash = null;
14192 this._strokeJoin = null;
14193 this._strokeWidth = null;
14194 },
14195
14196 /* styles */
14197
14198 _addColors: function(gradient, stops){
14199 // Enumerate stops, assumes offsets are enumerated in order
14200 // TODO: Sort. Chrome doesn't always enumerate in expected order but requires stops to be specified in order.
14201 if ('length' in stops) for (var i = 0, l = stops.length - 1; i <= l; i++)
14202 gradient.addColorStop(i / l, new color(stops[i]).toString());
14203 else for (var offset in stops)
14204 gradient.addColorStop(offset, new color(stops[offset]).toString());
14205 return gradient;
14206 },
14207
14208
14209 fill: function(color$$1){
14210 if (arguments.length > 1) return this.fillLinear(arguments);
14211 if (this._pendingFill) this._pendingFill();
14212 this._fill = color$$1 ? new color(color$$1).toString() : null;
14213 return this.invalidate();
14214 },
14215
14216 fillRadial: function(stops, focusX, focusY, radiusX, radiusY, centerX, centerY){
14217 if (focusX == null) focusX = (this.left || 0) + (this.width || 0) * 0.5;
14218 if (focusY == null) focusY = (this.top || 0) + (this.height || 0) * 0.5;
14219 if (radiusY == null) radiusY = radiusX || (this.height * 0.5) || 0;
14220 if (radiusX == null) radiusX = (this.width || 0) * 0.5;
14221 if (centerX == null) centerX = focusX;
14222 if (centerY == null) centerY = focusY;
14223
14224 centerX += centerX - focusX;
14225 centerY += centerY - focusY;
14226
14227 if (radiusX === 0 || radiusX === '0') return this.fillLinear(stops);
14228 var ys = radiusY / radiusX;
14229
14230 if (this._pendingFill) this._pendingFill();
14231
14232 var gradient = genericContext.createRadialGradient(focusX, focusY / ys, 0, centerX, centerY / ys, radiusX * 2);
14233
14234 // Double fill radius to simulate repeating gradient
14235 if ('length' in stops) for (var i = 0, l = stops.length - 1; i <= l; i++){
14236 gradient.addColorStop(i / l / 2, new color(stops[i]).toString());
14237 gradient.addColorStop(1 - i / l / 2, new color(stops[i]).toString());
14238 } else for (var offset in stops){
14239 gradient.addColorStop(offset / 2, new color(stops[offset]).toString());
14240 gradient.addColorStop(1- offset / 2, new color(stops[offset]).toString());
14241 }
14242
14243 this._fill = gradient;
14244 this._fillTransform = new transform(1, 0, 0, ys);
14245 return this.invalidate();
14246 },
14247
14248 fillLinear: function(stops, x1, y1, x2, y2){
14249 if (arguments.length < 5){
14250 var angle = ((x1 == null) ? 270 : x1) * Math.PI / 180;
14251
14252 var x = Math.cos(angle), y = -Math.sin(angle),
14253 l = (Math.abs(x) + Math.abs(y)) / 2,
14254 w = this.width || 1, h = this.height || 1;
14255
14256 x *= l; y *= l;
14257
14258 x1 = 0.5 - x;
14259 x2 = 0.5 + x;
14260 y1 = 0.5 - y;
14261 y2 = 0.5 + y;
14262 this._fillTransform = new transform(w, 0, 0, h);
14263 } else {
14264 this._fillTransform = null;
14265 }
14266 if (this._pendingFill) this._pendingFill();
14267 var gradient = genericContext.createLinearGradient(x1, y1, x2, y2);
14268 this._addColors(gradient, stops);
14269 this._fill = gradient;
14270 return this.invalidate();
14271 },
14272
14273 fillImage: function(url, width, height, left, top, color1, color2){
14274 if (this._pendingFill) this._pendingFill();
14275 var img = url;
14276 if (!(img instanceof Image)){
14277 img = new Image();
14278 img.src = url;
14279 }
14280 if (img.width && img.height){
14281 return this._fillImage(img, width, height, left || 0, top || 0, color1, color2);
14282 }
14283
14284 // Not yet loaded
14285 this._fill = null;
14286 var self = this,
14287 callback = function(){
14288 cancel();
14289 self._fillImage(img, width, height, left || 0, top || 0, color1, color2);
14290 },
14291 cancel = function(){
14292 img.removeEventListener('load', callback, false);
14293 self._pendingFill = null;
14294 };
14295 this._pendingFill = cancel;
14296 img.addEventListener('load', callback, false);
14297 return this;
14298 },
14299
14300 _fillImage: function(img, width, height, left, top, color1, color2){
14301 var w = width ? width / img.width : 1,
14302 h = height ? height / img.height : 1;
14303 if (color1 != null) img = recolorImage(img, color1, color2);
14304 this._fill = genericContext.createPattern(img, 'repeat');
14305 this._fillTransform = new transform(w, 0, 0, h, left || 0, top || 0);
14306 return this.invalidate();
14307 },
14308
14309 stroke: function(color$$1, width, cap, join, dash){
14310 this._stroke = color$$1 ? new color(color$$1).toString() : null;
14311 this._strokeWidth = (width != null) ? width : 1;
14312 this._strokeCap = (cap != null) ? cap : 'round';
14313 this._strokeJoin = (join != null) ? join : 'round';
14314 this._strokeDash = dash;
14315 return this.invalidate();
14316 },
14317
14318 // Rendering
14319
14320 element_renderTo: node.prototype.renderTo,
14321
14322 renderTo: function(context, xx, yx, xy, yy, x, y){
14323 var opacity = this._opacity;
14324 if (opacity == null || opacity >= 1){
14325 return this.renderLayerTo(context, xx, yx, xy, yy, x, y);
14326 }
14327 if (this._fill && this._stroke){
14328 return this.element_renderTo(context, xx, yx, xy, yy, x, y);
14329 }
14330 context.globalAlpha = opacity;
14331 var r = this.renderLayerTo(context, xx, yx, xy, yy, x, y);
14332 context.globalAlpha = 1;
14333 return r;
14334 },
14335
14336 renderLayerTo: function(context, xx, yx, xy, yy, x, y){
14337 context.setTransform(xx, yx, xy, yy, x, y);
14338 this.renderShapeTo(context);
14339 }
14340
14341});
14342
14343Base._genericContext = genericContext;
14344
14345var base = Base;
14346
14347var shape = _class(base, {
14348
14349 base_initialize: base.prototype.initialize,
14350
14351 initialize: function(path$$1, width, height){
14352 this.base_initialize();
14353 this.width = width;
14354 this.height = height;
14355 if (path$$1 != null) this.draw(path$$1);
14356 },
14357
14358 draw: function(path$$1, width, height){
14359 if (!(path$$1 instanceof path)) path$$1 = new path(path$$1);
14360 this.path = path$$1;
14361 this._commands = path$$1.toCommands();
14362 if (width != null) this.width = width;
14363 if (height != null) this.height = height;
14364 return this.invalidate();
14365 },
14366
14367 localHitTest: function(x, y){
14368 if (!this._fill) return null;
14369 if (this.width == null || this.height == null){
14370 var context = base._genericContext, commands = this._commands;
14371 if (!commands) return null;
14372 context.beginPath();
14373 for (var i = 0, l = commands.length; i < l; i++)
14374 commands[i](context);
14375 return context.isPointInPath(x, y) ? this : null;
14376 }
14377 if (x > 0 && y > 0 && x < this.width && y < this.height){
14378 return this;
14379 }
14380 return null;
14381 },
14382
14383 renderShapeTo: function(context){
14384 if (this._invisible || !this._commands || (!this._fill && !this._stroke)) {
14385 return null;
14386 }
14387 context.transform(this.xx, this.yx, this.xy, this.yy, this.x, this.y);
14388 var commands = this._commands,
14389 fill = this._fill,
14390 stroke = this._stroke,
14391 dash = this._strokeDash;
14392
14393 context.beginPath();
14394
14395 if (dash) {
14396 if (context.setLineDash) {
14397 context.setLineDash(dash);
14398 } else {
14399 // TODO: Remove when FF supports setLineDash.
14400 context.mozDash = dash;
14401 }
14402 // TODO: Create fallback to other browsers.
14403 } else {
14404 if (context.setLineDash) {
14405 context.setLineDash([]);
14406 } else {
14407 context.mozDash = null;
14408 }
14409 }
14410
14411 for (var i = 0, l = commands.length; i < l; i++)
14412 commands[i](context);
14413
14414 if (fill){
14415 var m = this._fillTransform;
14416 if (m){
14417 context.save(); // TODO: Optimize away this by restoring the transform before stroking
14418 context.transform(m.xx, m.yx, m.xy, m.yy, m.x, m.y);
14419 context.fillStyle = fill;
14420 context.fill();
14421 context.restore();
14422 } else {
14423 context.fillStyle = fill;
14424 context.fill();
14425 }
14426 }
14427 if (stroke){
14428 context.strokeStyle = stroke;
14429 context.lineWidth = this._strokeWidth;
14430 context.lineCap = this._strokeCap;
14431 context.lineJoin = this._strokeJoin;
14432 context.stroke();
14433 }
14434 }
14435
14436});
14437
14438var group = _class(node, container, {
14439
14440 initialize: function(width, height){
14441 this.width = width;
14442 this.height = height;
14443 },
14444
14445 localHitTest: function(x, y){
14446 var node$$2 = this.lastChild;
14447 while (node$$2){
14448 var hit = node$$2.hitTest(x, y);
14449 if (hit) return hit;
14450 node$$2 = node$$2.previousSibling;
14451 }
14452 return null;
14453 },
14454
14455 renderLayerTo: function(context, xx, yx, xy, yy, x, y){
14456 if (this._invisible) return;
14457
14458 x = xx * this.x + xy * this.y + x;
14459 y = yx * this.x + yy * this.y + y;
14460
14461 var t = xx;
14462 xx = t * this.xx + xy * this.yx;
14463 xy = t * this.xy + xy * this.yy;
14464 t = yx;
14465 yx = t * this.xx + yy * this.yx;
14466 yy = t * this.xy + yy * this.yy;
14467
14468 var node$$2 = this.firstChild;
14469 while (node$$2){
14470 node$$2.renderTo(context, xx, yx, xy, yy, x, y);
14471 node$$2 = node$$2.nextSibling;
14472 }
14473 }
14474
14475});
14476
14477var clippingrectangle = _class(node, container, {
14478
14479 initialize: function(width, height){
14480 this.width = width;
14481 this.height = height;
14482 },
14483
14484 localHitTest: function(x, y) {
14485 var node$$2 = this.lastChild;
14486 while (node$$2){
14487 var hit = node$$2.hitTest(x, y);
14488 if (hit) return hit;
14489 node$$2 = node$$2.previousSibling;
14490 }
14491 return null;
14492 },
14493
14494 renderLayerTo: function(context, xx, yx, xy, yy, x, y) {
14495 context.setTransform(xx, yx, xy, yy, x, y);
14496 context.save();
14497 // Need beginPath to fix Firefox bug. See 3354054.
14498 context.beginPath();
14499 context.rect(this.x, this.y, this.width, this.height);
14500 context.clip();
14501
14502 var node$$2 = this.firstChild;
14503 while(node$$2) {
14504 node$$2.renderTo(context, xx, yx, xy, yy, x, y);
14505 node$$2 = node$$2.nextSibling;
14506 }
14507 context.restore();
14508 }
14509});
14510
14511var fontAnchors = { middle: 'center' };
14512
14513var text = _class(base, {
14514
14515 base_initialize: base.prototype.initialize,
14516
14517 initialize: function(text, font, alignment, path){
14518 this.base_initialize();
14519 this.draw.apply(this, arguments);
14520 },
14521
14522 draw: function(text, font, alignment, path){
14523 var em;
14524 if (typeof font == 'string'){
14525 em = Number(/(\d+)/.exec(font)[0]);
14526 } else if (font){
14527 em = parseFloat(font.fontSize || font['font-size'] || '12');
14528 font = (font.fontStyle || font['font-style'] || '') + ' ' +
14529 (font.fontVariant || font['font-variant'] || '') + ' ' +
14530 (font.fontWeight || font['font-weight'] || '') + ' ' +
14531 em + 'px ' +
14532 (font.fontFamily || font['font-family'] || 'Arial');
14533 } else {
14534 font = this._font;
14535 }
14536
14537 var lines = text && text.split(/\r?\n/);
14538 this._font = font;
14539 this._fontSize = em;
14540 this._text = lines;
14541 this._alignment = fontAnchors[alignment] || alignment || 'left';
14542
14543 var context = base._genericContext;
14544
14545 context.font = this._font;
14546 context.textAlign = this._alignment;
14547 context.textBaseline = 'middle';
14548
14549 lines = this._text;
14550 var l = lines.length, width = 0;
14551 for (var i = 0; i < l; i++){
14552 var w = context.measureText(lines[i]).width;
14553 if (w > width) width = w;
14554 }
14555 this.width = width;
14556 this.height = l ? l * 1.1 * em : 0;
14557 return this.invalidate();
14558 },
14559
14560 // Interaction
14561
14562 localHitTest: function(x, y){
14563 if (!this._fill) return null;
14564 if (x > 0 && y > 0 && x < this.width && y < this.height){
14565 return this;
14566 }
14567 return null;
14568 },
14569
14570 // Rendering
14571
14572 renderShapeTo: function(context){
14573 if (this._invisible || !this._text || (!this._fill && !this._stroke)) {
14574 return null;
14575 }
14576 context.transform(this.xx, this.yx, this.xy, this.yy, this.x, this.y);
14577 var fill = this._fill,
14578 stroke = this._stroke,
14579 text = this._text,
14580 dash = this._strokeDash;
14581
14582 context.font = this._font;
14583 context.textAlign = this._alignment;
14584 context.textBaseline = 'middle';
14585
14586 var em = this._fontSize,
14587 y = em / 2,
14588 lineHeight = 1.1 * em,
14589 lines = text,
14590 l = lines.length;
14591
14592 if (fill){
14593 context.fillStyle = fill;
14594 for (var i = 0; i < l; i++)
14595 context.fillText(lines[i], 0, y + i * lineHeight);
14596 }
14597 if (stroke){
14598 if (dash) {
14599 if (context.setLineDash) {
14600 context.setLineDash(dash);
14601 } else {
14602 // TODO: Remove when FF supports setLineDash.
14603 context.mozDash = dash;
14604 }
14605 // TODO: Create fallback to other browsers.
14606 } else {
14607 if (context.setLineDash) {
14608 context.setLineDash([]);
14609 } else {
14610 context.mozDash = null;
14611 }
14612 }
14613
14614 context.strokeStyle = stroke;
14615 context.lineWidth = this._strokeWidth;
14616 context.lineCap = this._strokeCap;
14617 context.lineJoin = this._strokeJoin;
14618 for (i = 0; i < l; i++)
14619 context.strokeText(lines[i], 0, y + i * lineHeight);
14620 }
14621 }
14622
14623});
14624
14625var VMLCSS = 'behavior:url(#default#VML);display:inline-block;position:absolute;left:0px;top:0px;';
14626
14627var styleSheet;
14628var styledTags = {};
14629var styleTag = function(tag){
14630 if (styleSheet) styledTags[tag] = styleSheet.addRule('av\\:' + tag, VMLCSS);
14631};
14632
14633var init = function(document){
14634
14635 var namespaces;
14636 try { // IE9 workaround: sometimes it throws here
14637 namespaces = document.namespaces;
14638 } catch (e) {
14639 }
14640 if (!namespaces) return false;
14641
14642 namespaces.add('av', 'urn:schemas-microsoft-com:vml');
14643 namespaces.add('ao', 'urn:schemas-microsoft-com:office:office');
14644
14645 styleSheet = document.createStyleSheet();
14646 styleSheet.addRule('vml', 'display:inline-block;position:relative;overflow:hidden;');
14647/* styleTag('skew');
14648 styleTag('fill');
14649 styleTag('stroke');
14650 styleTag('path');
14651 styleTag('textpath');
14652 styleTag('group');*/
14653
14654 styleTag('vml');
14655
14656 return true;
14657
14658};
14659
14660var createElement = function(tag){
14661 if (!(tag in styledTags)) styleTag(tag);
14662 return document.createElement('av:' + tag);
14663};
14664
14665var dom = {
14666 init: init,
14667 createElement: createElement
14668};
14669
14670var precision = 100;
14671
14672var VMLSurface = _class(native_1, container, {
14673
14674 initialize: function VMLSurface(width, height, existingElement){
14675 this.element = existingElement || document.createElement('vml');
14676 this.containerElement = dom.createElement('group');
14677 this.element.appendChild(this.containerElement);
14678 if (width != null && height != null) this.resize(width, height);
14679 },
14680
14681 resize: function(width, height){
14682 this.width = width;
14683 this.height = height;
14684
14685 var style = this.element.style;
14686 style.pixelWidth = width;
14687 style.pixelHeight = height;
14688
14689 style = this.containerElement.style;
14690 style.width = width;
14691 style.height = height;
14692
14693 var halfPixel = (0.5 * precision);
14694
14695 this.containerElement.coordorigin = halfPixel + ',' + halfPixel;
14696 this.containerElement.coordsize = (width * precision) + ',' + (height * precision);
14697
14698 return this;
14699 }
14700
14701});
14702
14703VMLSurface.tagName = 'av:vml';
14704
14705var surface$2 = VMLSurface;
14706
14707var precision$1 = 100;
14708
14709var round = Math.round;
14710
14711var VMLPath = _class(path$2, {
14712
14713 initialize: function(path){
14714 this.reset();
14715 if (path instanceof VMLPath){
14716 this.path = [Array.prototype.join.call(path.path, ' ')];
14717 } else if (path){
14718 if (path.applyToPath)
14719 path.applyToPath(this);
14720 else
14721 this.push(path);
14722 }
14723 },
14724
14725 onReset: function(){
14726 this.path = [];
14727 },
14728
14729 onMove: function(sx, sy, x, y){
14730 this.path.push('m', round(x * precision$1), round(y * precision$1));
14731 },
14732
14733 onLine: function(sx, sy, x, y){
14734 this.path.push('l', round(x * precision$1), round(y * precision$1));
14735 },
14736
14737 onBezierCurve: function(sx, sy, p1x, p1y, p2x, p2y, x, y){
14738 this.path.push('c',
14739 round(p1x * precision$1), round(p1y * precision$1),
14740 round(p2x * precision$1), round(p2y * precision$1),
14741 round(x * precision$1), round(y * precision$1)
14742 );
14743 },
14744
14745 _arcToBezier: path$2.prototype.onArc,
14746
14747 onArc: function(sx, sy, ex, ey, cx, cy, rx, ry, sa, ea, ccw, rotation){
14748 if (rx != ry || rotation) return this._arcToBezier(sx, sy, ex, ey, cx, cy, rx, ry, sa, ea, ccw, rotation);
14749 cx *= precision$1;
14750 cy *= precision$1;
14751 rx *= precision$1;
14752 this.path.push(ccw ? 'at' : 'wa',
14753 round(cx - rx), round(cy - rx),
14754 round(cx + rx), round(cy + rx),
14755 round(sx * precision$1), round(sy * precision$1),
14756 round(ex * precision$1), round(ey * precision$1)
14757 );
14758 },
14759
14760 onClose: function(){
14761 this.path.push('x');
14762 },
14763
14764 toVML: function(){
14765 return this.path.join(' ');
14766 }
14767
14768});
14769
14770VMLPath.prototype.toString = VMLPath.prototype.toVML;
14771
14772var path$4 = VMLPath;
14773
14774var shadow = _class(dummy, native_1, {
14775
14776 dummy_inject: dummy.prototype.inject,
14777 dummy_injectBefore: dummy.prototype.injectBefore,
14778 dummy_eject: dummy.prototype.eject,
14779 native_inject: native_1.prototype.inject,
14780 native_injectBefore: native_1.prototype.injectBefore,
14781 native_eject: native_1.prototype.eject,
14782
14783 inject: function(container){
14784 this.dummy_inject(container);
14785 this.native_inject(container);
14786 return this;
14787 },
14788
14789 injectBefore: function(sibling){
14790 this.dummy_injectBefore(sibling);
14791 this.native_injectBefore(sibling);
14792 return this;
14793 },
14794
14795 eject: function(){
14796 this.dummy_eject();
14797 this.native_eject();
14798 return this;
14799 }
14800
14801});
14802
14803var node$2 = _class(shadow, transform, {
14804
14805 initialize: function(tag){
14806 //this.uid = uniqueID();
14807 var element = this.element = dom.createElement(tag);
14808 //element.setAttribute('id', 'e' + this.uid);
14809 },
14810
14811 _place: function(){
14812 if (this.parentNode){
14813 this._transform();
14814 }
14815 },
14816
14817 // visibility
14818
14819 hide: function(){
14820 this.element.style.display = 'none';
14821 return this;
14822 },
14823
14824 show: function(){
14825 this.element.style.display = '';
14826 return this;
14827 },
14828
14829 // interaction
14830
14831 indicate: function(cursor, tooltip){
14832 if (cursor) this.element.style.cursor = cursor;
14833 if (tooltip) this.element.title = tooltip;
14834 return this;
14835 }
14836
14837});
14838
14839var precision$3 = 100;
14840
14841var defaultBox = { left: 0, top: 0, width: 500, height: 500 };
14842
14843var base$2 = _class(node$2, {
14844
14845 element_initialize: node$2.prototype.initialize,
14846
14847 initialize: function(tag){
14848 this.element_initialize(tag);
14849 var element = this.element;
14850
14851 var skew = this.skewElement = dom.createElement('skew');
14852 skew.on = true;
14853 element.appendChild(skew);
14854
14855 var fill = this.fillElement = dom.createElement('fill');
14856 fill.on = false;
14857 element.appendChild(fill);
14858
14859 var stroke = this.strokeElement = dom.createElement('stroke');
14860 stroke.on = false;
14861 element.appendChild(stroke);
14862 },
14863
14864 /* transform */
14865
14866 _transform: function(){
14867 var container = this.parentNode;
14868
14869 // Active Transformation Matrix
14870 var m = container ? new transform(container._activeTransform).transform(this) : this;
14871
14872 // Box in shape user space
14873
14874 var box = this._boxCoords || this._size || defaultBox;
14875
14876 var originX = box.left || 0,
14877 originY = box.top || 0,
14878 width = box.width || 1,
14879 height = box.height || 1;
14880
14881 // Flipped
14882 var flip = m.yx / m.xx > m.yy / m.xy;
14883 if (m.xx < 0 ? m.xy >= 0 : m.xy < 0) flip = !flip;
14884 flip = flip ? -1 : 1;
14885
14886 m = new transform().scale(flip, 1).transform(m);
14887
14888 // Rotation is approximated based on the transform
14889 var rotation = Math.atan2(-m.xy, m.yy) * 180 / Math.PI;
14890
14891 // Reverse the rotation, leaving the final transform in box space
14892 var rad = rotation * Math.PI / 180, sin = Math.sin(rad), cos = Math.cos(rad);
14893
14894 var transform$$2 = new transform(
14895 (m.xx * cos - m.xy * sin),
14896 (m.yx * cos - m.yy * sin) * flip,
14897 (m.xy * cos + m.xx * sin) * flip,
14898 (m.yy * cos + m.yx * sin)
14899 );
14900
14901 var rotationTransform = new transform().rotate(rotation, 0, 0);
14902
14903 var shapeToBox = new transform().rotate(-rotation, 0, 0).transform(m).moveTo(0,0);
14904
14905 // Scale box after reversing rotation
14906 width *= Math.abs(shapeToBox.xx);
14907 height *= Math.abs(shapeToBox.yy);
14908
14909 // Place box
14910 var left = m.x, top = m.y;
14911
14912 // Compensate for offset by center origin rotation
14913 var vx = -width / 2, vy = -height / 2;
14914 var point = rotationTransform.point(vx, vy);
14915 left -= point.x - vx;
14916 top -= point.y - vy;
14917
14918 // Adjust box position based on offset
14919 var rsm = new transform(m).moveTo(0,0);
14920 point = rsm.point(originX, originY);
14921 left += point.x;
14922 top += point.y;
14923
14924 if (flip < 0) left = -left - width;
14925
14926 // Place transformation origin
14927 var point0 = rsm.point(-originX, -originY);
14928 var point1 = rotationTransform.point(width, height);
14929 var point2 = rotationTransform.point(width, 0);
14930 var point3 = rotationTransform.point(0, height);
14931
14932 var minX = Math.min(0, point1.x, point2.x, point3.x),
14933 maxX = Math.max(0, point1.x, point2.x, point3.x),
14934 minY = Math.min(0, point1.y, point2.y, point3.y),
14935 maxY = Math.max(0, point1.y, point2.y, point3.y);
14936
14937 var transformOriginX = (point0.x - point1.x / 2) / (maxX - minX) * flip,
14938 transformOriginY = (point0.y - point1.y / 2) / (maxY - minY);
14939
14940 // Adjust the origin
14941 point = shapeToBox.point(originX, originY);
14942 originX = point.x;
14943 originY = point.y;
14944
14945 // Scale stroke
14946 var strokeWidth = this._strokeWidth;
14947 if (strokeWidth){
14948 // Scale is the hypothenus between the two vectors
14949 // TODO: Use area calculation instead
14950 var vx = m.xx + m.xy, vy = m.yy + m.yx;
14951 strokeWidth *= Math.sqrt(vx * vx + vy * vy) / Math.sqrt(2);
14952 }
14953
14954 // convert to multiplied precision space
14955 originX *= precision$3;
14956 originY *= precision$3;
14957 left *= precision$3;
14958 top *= precision$3;
14959 width *= precision$3;
14960 height *= precision$3;
14961
14962 // Set box
14963 var element = this.element;
14964 element.coordorigin = originX + ',' + originY;
14965 element.coordsize = width + ',' + height;
14966 element.style.left = left + 'px';
14967 element.style.top = top + 'px';
14968 element.style.width = width;
14969 element.style.height = height;
14970 element.style.rotation = rotation.toFixed(8);
14971 element.style.flip = flip < 0 ? 'x' : '';
14972
14973 // Set transform
14974 var skew = this.skewElement;
14975 skew.matrix = [transform$$2.xx.toFixed(4), transform$$2.xy.toFixed(4), transform$$2.yx.toFixed(4), transform$$2.yy.toFixed(4), 0, 0];
14976 skew.origin = transformOriginX + ',' + transformOriginY;
14977
14978 // Set stroke
14979 this.strokeElement.weight = strokeWidth + 'px';
14980 },
14981
14982 /* styles */
14983
14984 _createGradient: function(style, stops){
14985 var fill = this.fillElement;
14986
14987 // Temporarily eject the fill from the DOM
14988 this.element.removeChild(fill);
14989
14990 fill.type = style;
14991 fill.method = 'none';
14992 fill.rotate = true;
14993
14994 var colors = [], color1, color2;
14995
14996 var addColor = function(offset, color$$2){
14997 color$$2 = color.detach(color$$2);
14998 if (color1 == null) color1 = color2 = color$$2;
14999 else color2 = color$$2;
15000 colors.push(offset + ' ' + color$$2[0]);
15001 };
15002
15003 // Enumerate stops, assumes offsets are enumerated in order
15004 if ('length' in stops) for (var i = 0, l = stops.length - 1; i <= l; i++) addColor(i / l, stops[i]);
15005 else for (var offset in stops) addColor(offset, stops[offset]);
15006
15007 fill.color = color1[0];
15008 fill.color2 = color2[0];
15009
15010 //if (fill.colors) fill.colors.value = colors; else
15011 fill.colors = colors;
15012
15013 // Opacity order gets flipped when color stops are specified
15014 fill.opacity = color2[1];
15015 fill['ao:opacity2'] = color1[1];
15016
15017 fill.on = true;
15018 this.element.appendChild(fill);
15019 return fill;
15020 },
15021
15022 _setColor: function(type, color$$2){
15023 var element = type == 'fill' ? this.fillElement : this.strokeElement;
15024 if (color$$2 == null){
15025 element.on = false;
15026 } else {
15027 color$$2 = color.detach(color$$2);
15028 element.color = color$$2[0];
15029 element.opacity = color$$2[1];
15030 element.on = true;
15031 }
15032 },
15033
15034 fill: function(color$$2){
15035 if (arguments.length > 1){
15036 this.fillLinear(arguments);
15037 } else {
15038 this._boxCoords = defaultBox;
15039 var fill = this.fillElement;
15040 fill.type = 'solid';
15041 fill.color2 = '';
15042 fill['ao:opacity2'] = '';
15043 if (fill.colors) fill.colors.value = '';
15044 this._setColor('fill', color$$2);
15045 }
15046 return this;
15047 },
15048
15049 fillRadial: function(stops, focusX, focusY, radiusX, radiusY, centerX, centerY){
15050 var fill = this._createGradient('gradientradial', stops);
15051 if (focusX == null) focusX = this.left + this.width * 0.5;
15052 if (focusY == null) focusY = this.top + this.height * 0.5;
15053 if (radiusY == null) radiusY = radiusX || (this.height * 0.5);
15054 if (radiusX == null) radiusX = this.width * 0.5;
15055 if (centerX == null) centerX = focusX;
15056 if (centerY == null) centerY = focusY;
15057
15058 centerX += centerX - focusX;
15059 centerY += centerY - focusY;
15060
15061 var box = this._boxCoords = {
15062 left: centerX - radiusX * 2,
15063 top: centerY - radiusY * 2,
15064 width: radiusX * 4,
15065 height: radiusY * 4
15066 };
15067 focusX -= box.left;
15068 focusY -= box.top;
15069 focusX /= box.width;
15070 focusY /= box.height;
15071
15072 fill.focussize = '0 0';
15073 fill.focusposition = focusX + ',' + focusY;
15074 fill.focus = '50%';
15075
15076 this._transform();
15077
15078 return this;
15079 },
15080
15081 fillLinear: function(stops, x1, y1, x2, y2){
15082 var fill = this._createGradient('gradient', stops);
15083 fill.focus = '100%';
15084 if (arguments.length == 5){
15085 var w = Math.abs(x2 - x1), h = Math.abs(y2 - y1);
15086 this._boxCoords = {
15087 left: Math.min(x1, x2),
15088 top: Math.min(y1, y2),
15089 width: w < 1 ? h : w,
15090 height: h < 1 ? w : h
15091 };
15092 fill.angle = (360 + Math.atan2((x2 - x1) / h, (y2 - y1) / w) * 180 / Math.PI) % 360;
15093 } else {
15094 this._boxCoords = null;
15095 fill.angle = (x1 == null) ? 0 : (90 + x1) % 360;
15096 }
15097 this._transform();
15098 return this;
15099 },
15100
15101 fillImage: function(url, width, height, left, top, color1, color2){
15102 var fill = this.fillElement;
15103 if (color1 != null){
15104 color1 = color.detach(color1);
15105 if (color2 != null) color2 = color.detach(color2);
15106 fill.type = 'pattern';
15107 fill.color = color1[0];
15108 fill.color2 = color2 == null ? color1[0] : color2[0];
15109 fill.opacity = color2 == null ? 0 : color2[1];
15110 fill['ao:opacity2'] = color1[1];
15111 } else {
15112 fill.type = 'tile';
15113 fill.color = '';
15114 fill.color2 = '';
15115 fill.opacity = 1;
15116 fill['ao:opacity2'] = 1;
15117 }
15118 if (fill.colors) fill.colors.value = '';
15119 fill.rotate = true;
15120 fill.src = url;
15121
15122 fill.size = '1,1';
15123 fill.position = '0,0';
15124 fill.origin = '0,0';
15125 fill.aspect = 'ignore'; // ignore, atleast, atmost
15126 fill.on = true;
15127
15128 if (!left) left = 0;
15129 if (!top) top = 0;
15130 this._boxCoords = width ? { left: left + 0.5, top: top + 0.5, width: width, height: height } : null;
15131 this._transform();
15132 return this;
15133 },
15134
15135 /* stroke */
15136
15137 stroke: function(color$$2, width, cap, join){
15138 var stroke = this.strokeElement;
15139 this._strokeWidth = (width != null) ? width : 1;
15140 stroke.weight = (width != null) ? width + 'px' : 1;
15141 stroke.endcap = (cap != null) ? ((cap == 'butt') ? 'flat' : cap) : 'round';
15142 stroke.joinstyle = (join != null) ? join : 'round';
15143
15144 this._setColor('stroke', color$$2);
15145 return this;
15146 }
15147
15148});
15149
15150var precision$2 = 100;
15151
15152var shape$2 = _class(base$2, {
15153
15154 base_initialize: base$2.prototype.initialize,
15155
15156 initialize: function(path, width, height){
15157 this.base_initialize('shape');
15158
15159 var p = this.pathElement = dom.createElement('path');
15160 p.gradientshapeok = true;
15161 this.element.appendChild(p);
15162
15163 this.width = width;
15164 this.height = height;
15165
15166 if (path != null) this.draw(path);
15167 },
15168
15169 // SVG to VML
15170
15171 draw: function(path, width, height){
15172
15173 if (!(path instanceof path$4)) path = new path$4(path);
15174 this._vml = path.toVML();
15175 //this._size = path.measure();
15176
15177 if (width != null) this.width = width;
15178 if (height != null) this.height = height;
15179
15180 if (!this._boxCoords) this._transform();
15181 this._redraw(this._prefix, this._suffix);
15182
15183 return this;
15184 },
15185
15186 // radial gradient workaround
15187
15188 _redraw: function(prefix, suffix){
15189 var vml = this._vml || '';
15190
15191 this._prefix = prefix;
15192 this._suffix = suffix;
15193 if (prefix){
15194 vml = [
15195 prefix, vml, suffix,
15196 // Don't stroke the path with the extra ellipse, redraw the stroked path separately
15197 'ns e', vml, 'nf'
15198 ].join(' ');
15199 }
15200
15201 this.element.path = vml + 'e';
15202 },
15203
15204 fillRadial: function(stops, focusX, focusY, radiusX, radiusY, centerX, centerY){
15205 var fill = this._createGradient('gradientradial', stops);
15206 if (focusX == null) focusX = (this.left || 0) + (this.width || 0) * 0.5;
15207 if (focusY == null) focusY = (this.top || 0) + (this.height || 0) * 0.5;
15208 if (radiusY == null) radiusY = radiusX || (this.height * 0.5) || 0;
15209 if (radiusX == null) radiusX = (this.width || 0) * 0.5;
15210 if (centerX == null) centerX = focusX;
15211 if (centerY == null) centerY = focusY;
15212
15213 centerX += centerX - focusX;
15214 centerY += centerY - focusY;
15215
15216 var cx = Math.round(centerX * precision$2),
15217 cy = Math.round(centerY * precision$2),
15218
15219 rx = Math.round(radiusX * 2 * precision$2),
15220 ry = Math.round(radiusY * 2 * precision$2),
15221
15222 arc = ['wa', cx - rx, cy - ry, cx + rx, cy + ry].join(' ');
15223
15224 this._redraw(
15225 // Resolve rendering bug
15226 ['m', cx, cy - ry, 'l', cx, cy - ry].join(' '),
15227 // Draw an ellipse around the path to force an elliptical gradient on any shape
15228 [
15229 'm', cx, cy - ry,
15230 arc, cx, cy - ry, cx, cy + ry, arc, cx, cy + ry, cx, cy - ry,
15231 arc, cx, cy - ry, cx, cy + ry, arc, cx, cy + ry, cx, cy - ry
15232 ].join(' ')
15233 );
15234
15235 this._boxCoords = { left: focusX - 2, top: focusY - 2, width: 4, height: 4 };
15236
15237 fill.focusposition = '0.5,0.5';
15238 fill.focussize = '0 0';
15239 fill.focus = '50%';
15240
15241 this._transform();
15242
15243 return this;
15244 }
15245
15246});
15247
15248var group$2 = _class(node$2, container, {
15249
15250 element_initialize: node$2.prototype.initialize,
15251
15252 initialize: function(width, height){
15253 this.element_initialize('group');
15254 this.width = width;
15255 this.height = height;
15256 },
15257
15258 _transform: function(){
15259 var element = this.element;
15260 element.coordorigin = '0,0';
15261 element.coordsize = '1000,1000';
15262 element.style.left = 0;
15263 element.style.top = 0;
15264 element.style.width = 1000;
15265 element.style.height = 1000;
15266 element.style.rotation = 0;
15267
15268 var container$$2 = this.parentNode;
15269 this._activeTransform = container$$2 ? new transform(container$$2._activeTransform).transform(this) : this;
15270 var node = this.firstChild;
15271 while (node){
15272 node._transform();
15273 node = node.nextSibling;
15274 }
15275 }
15276
15277});
15278
15279var clippingrectangle$2 = _class(node$2, container, {
15280
15281 element_initialize: node$2.prototype.initialize,
15282
15283 initialize: function(width, height){
15284 this.element_initialize('clippingrectangle');
15285 this.width = width;
15286 this.height = height;
15287 },
15288
15289 _transform: function(){
15290 var element = this.element;
15291 element.clip = true;
15292 element.coordorigin = -this.x + ',' + (-1 * this.y);
15293 element.coordsize = this.width + ',' + this.height;
15294 // IE8 doesn't like clipBottom. Don't ask me why.
15295 // element.style.clipBottom = this.height + this.y;
15296 element.style.clipLeft = this.x;
15297 element.style.clipRight = this.width + this.x;
15298 element.style.clipTop = this.y;
15299 element.style.left = -this.x;
15300 element.style.top = -this.y;
15301 element.style.width = this.width + this.x;
15302 element.style.height = this.height + this.y;
15303 element.style.rotation = 0;
15304
15305 var container$$2 = this.parentNode;
15306 this._activeTransform = container$$2 ? new transform(container$$2._activeTransform).transform(this) : this;
15307 var node = this.firstChild;
15308 while (node){
15309 node._transform();
15310 node = node.nextSibling;
15311 }
15312 }
15313
15314});
15315
15316var fontAnchors$1 = { start: 'left', middle: 'center', end: 'right' };
15317
15318var text$2 = _class(base$2, {
15319
15320 base_initialize: base$2.prototype.initialize,
15321
15322 initialize: function(text, font, alignment, path){
15323 this.base_initialize('shape');
15324
15325 var p = this.pathElement = dom.createElement('path');
15326 p.textpathok = true;
15327 this.element.appendChild(p);
15328
15329 p = this.textPathElement = dom.createElement("textpath");
15330 p.on = true;
15331 p.style['v-text-align'] = 'left';
15332 this.element.appendChild(p);
15333
15334 this.draw.apply(this, arguments);
15335 },
15336
15337 draw: function(text, font, alignment, path){
15338 var element = this.element,
15339 textPath = this.textPathElement,
15340 style = textPath.style;
15341
15342 textPath.string = text;
15343
15344 if (font){
15345 if (typeof font == 'string'){
15346 style.font = font;
15347 } else {
15348 for (var key in font){
15349 var ckey = key.camelCase ? key.camelCase() : key;
15350 if (ckey == 'fontFamily') style[ckey] = "'" + font[key] + "'";
15351 // NOT UNIVERSALLY SUPPORTED OPTIONS
15352 // else if (ckey == 'kerning') style['v-text-kern'] = !!font[key];
15353 // else if (ckey == 'rotateGlyphs') style['v-rotate-letters'] = !!font[key];
15354 // else if (ckey == 'letterSpacing') style['v-text-spacing'] = Number(font[key]) + '';
15355 else style[ckey] = font[key];
15356 }
15357 }
15358 }
15359
15360 if (alignment) style['v-text-align'] = fontAnchors$1[alignment] || alignment;
15361
15362 if (path){
15363 this.currentPath = path = new path$4(path);
15364 this.element.path = path.toVML();
15365 } else if (!this.currentPath){
15366 var i = -1, offsetRows = '\n';
15367 while ((i = text.indexOf('\n', i + 1)) > -1) offsetRows += '\n';
15368 textPath.string = offsetRows + textPath.string;
15369 this.element.path = 'm0,0l1,0';
15370 }
15371
15372 // Measuring the bounding box is currently necessary for gradients etc.
15373
15374 // Clone element because the element is dead once it has been in the DOM
15375 element = element.cloneNode(true);
15376 style = element.style;
15377
15378 // Reset coordinates while measuring
15379 element.coordorigin = '0,0';
15380 element.coordsize = '10000,10000';
15381 style.left = '0px';
15382 style.top = '0px';
15383 style.width = '10000px';
15384 style.height = '10000px';
15385 style.rotation = 0;
15386 element.removeChild(element.firstChild); // Remove skew
15387
15388 // Inject the clone into the document
15389
15390 var canvas = new surface$2(1, 1),
15391 group = new group$2(), // Wrapping it in a group seems to alleviate some client rect weirdness
15392 body = element.ownerDocument.body;
15393
15394 canvas.inject(body);
15395 group.element.appendChild(element);
15396 group.inject(canvas);
15397
15398 var ebb = element.getBoundingClientRect(),
15399 cbb = canvas.toElement().getBoundingClientRect();
15400
15401 canvas.eject();
15402
15403 this.left = ebb.left - cbb.left;
15404 this.top = ebb.top - cbb.top;
15405 this.width = ebb.right - ebb.left;
15406 this.height = ebb.bottom - ebb.top;
15407 this.right = ebb.right - cbb.left;
15408 this.bottom = ebb.bottom - cbb.top;
15409
15410 this._transform();
15411
15412 //this._size = { left: this.left, top: this.top, width: this.width, height: this.height};
15413 return this;
15414 }
15415
15416});
15417
15418var fastNoSideEffects = createCommonjsModule(function (module, exports) {
15419var hasCanvas = function(){
15420
15421 var canvas = document.createElement('canvas');
15422 return canvas && !!canvas.getContext;
15423
15424};
15425
15426if (hasCanvas()) {
15427 exports.Surface = surface;
15428 exports.Path = path;
15429 exports.Shape = shape;
15430 exports.Group = group;
15431 exports.ClippingRectangle = clippingrectangle;
15432 exports.Text = text;
15433} else {
15434 exports.Surface = surface$2;
15435 exports.Path = path$4;
15436 exports.Shape = shape$2;
15437 exports.Group = group$2;
15438 exports.ClippingRectangle = clippingrectangle$2;
15439 exports.Text = text$2;
15440
15441 var DOM$$1 = dom;
15442 if (typeof document !== 'undefined') DOM$$1.init(document);
15443}
15444});
15445
15446var fastNoSideEffects_1 = fastNoSideEffects.Surface;
15447var fastNoSideEffects_2 = fastNoSideEffects.Path;
15448var fastNoSideEffects_3 = fastNoSideEffects.Shape;
15449var fastNoSideEffects_4 = fastNoSideEffects.Group;
15450var fastNoSideEffects_5 = fastNoSideEffects.ClippingRectangle;
15451var fastNoSideEffects_6 = fastNoSideEffects.Text;
15452
15453var _extends = _assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
15454
15455function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
15456
15457function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
15458
15459function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
15460
15461current.setCurrent(
15462// Change to 'art/modes/dom' for easier debugging via SVG
15463fastNoSideEffects);
15464
15465/** Declarative fill-type objects; API design not finalized */
15466
15467var slice = Array.prototype.slice;
15468
15469var LinearGradient = function () {
15470 function LinearGradient(stops, x1, y1, x2, y2) {
15471 _classCallCheck(this, LinearGradient);
15472
15473 this._args = slice.call(arguments);
15474 }
15475
15476 LinearGradient.prototype.applyFill = function applyFill(node) {
15477 node.fillLinear.apply(node, this._args);
15478 };
15479
15480 return LinearGradient;
15481}();
15482
15483var RadialGradient = function () {
15484 function RadialGradient(stops, fx, fy, rx, ry, cx, cy) {
15485 _classCallCheck(this, RadialGradient);
15486
15487 this._args = slice.call(arguments);
15488 }
15489
15490 RadialGradient.prototype.applyFill = function applyFill(node) {
15491 node.fillRadial.apply(node, this._args);
15492 };
15493
15494 return RadialGradient;
15495}();
15496
15497var Pattern = function () {
15498 function Pattern(url, width, height, left, top) {
15499 _classCallCheck(this, Pattern);
15500
15501 this._args = slice.call(arguments);
15502 }
15503
15504 Pattern.prototype.applyFill = function applyFill(node) {
15505 node.fillImage.apply(node, this._args);
15506 };
15507
15508 return Pattern;
15509}();
15510
15511/** React Components */
15512
15513var Surface = function (_React$Component) {
15514 _inherits(Surface, _React$Component);
15515
15516 function Surface() {
15517 _classCallCheck(this, Surface);
15518
15519 return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
15520 }
15521
15522 Surface.prototype.componentDidMount = function componentDidMount() {
15523 var _props = this.props,
15524 height = _props.height,
15525 width = _props.width;
15526
15527
15528 this._surface = current.Surface(+width, +height, this._tagRef);
15529
15530 this._mountNode = createContainer(this._surface);
15531 updateContainer(this.props.children, this._mountNode, this);
15532 };
15533
15534 Surface.prototype.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
15535 var props = this.props;
15536
15537 if (props.height !== prevProps.height || props.width !== prevProps.width) {
15538 this._surface.resize(+props.width, +props.height);
15539 }
15540
15541 updateContainer(this.props.children, this._mountNode, this);
15542
15543 if (this._surface.render) {
15544 this._surface.render();
15545 }
15546 };
15547
15548 Surface.prototype.componentWillUnmount = function componentWillUnmount() {
15549 updateContainer(null, this._mountNode, this);
15550 };
15551
15552 Surface.prototype.render = function render() {
15553 var _this2 = this;
15554
15555 // This is going to be a placeholder because we don't know what it will
15556 // actually resolve to because ART may render canvas, vml or svg tags here.
15557 // We only allow a subset of properties since others might conflict with
15558 // ART's properties.
15559 var props = this.props;
15560
15561 // TODO: ART's Canvas Mode overrides surface title and cursor
15562 var Tag = current.Surface.tagName;
15563
15564 return React.createElement(Tag, {
15565 ref: function (ref) {
15566 return _this2._tagRef = ref;
15567 },
15568 accessKey: props.accessKey,
15569 className: props.className,
15570 draggable: props.draggable,
15571 role: props.role,
15572 style: props.style,
15573 tabIndex: props.tabIndex,
15574 title: props.title
15575 });
15576 };
15577
15578 return Surface;
15579}(React.Component);
15580
15581var Text = function (_React$Component2) {
15582 _inherits(Text, _React$Component2);
15583
15584 function Text(props) {
15585 _classCallCheck(this, Text);
15586
15587 // We allow reading these props. Ideally we could expose the Text node as
15588 // ref directly.
15589 var _this3 = _possibleConstructorReturn(this, _React$Component2.call(this, props));
15590
15591 ['height', 'width', 'x', 'y'].forEach(function (key) {
15592 Object.defineProperty(_this3, key, {
15593 get: function () {
15594 return this._text ? this._text[key] : undefined;
15595 }
15596 });
15597 });
15598 return _this3;
15599 }
15600
15601 Text.prototype.render = function render() {
15602 var _this4 = this;
15603
15604 // This means you can't have children that render into strings...
15605 var T = TYPES.TEXT;
15606 return React.createElement(
15607 T,
15608 _extends({}, this.props, { ref: function (t) {
15609 return _this4._text = t;
15610 } }),
15611 childrenAsString(this.props.children)
15612 );
15613 };
15614
15615 return Text;
15616}(React.Component);
15617
15618injectIntoDevTools({
15619 findFiberByHostInstance: function () {
15620 return null;
15621 },
15622 bundleType: 1,
15623 version: ReactVersion,
15624 rendererPackageName: 'react-art'
15625});
15626
15627/** API */
15628
15629var ClippingRectangle = TYPES.CLIPPING_RECTANGLE;
15630var Group = TYPES.GROUP;
15631var Shape = TYPES.SHAPE;
15632var Path = current.Path;
15633
15634
15635var ReactART = Object.freeze({
15636 ClippingRectangle: ClippingRectangle,
15637 Group: Group,
15638 Shape: Shape,
15639 Path: Path,
15640 LinearGradient: LinearGradient,
15641 Pattern: Pattern,
15642 RadialGradient: RadialGradient,
15643 Surface: Surface,
15644 Text: Text,
15645 Transform: transform
15646});
15647
15648var reactArt = ReactART;
15649
15650return reactArt;
15651
15652})));