UNPKG

242 kBJavaScriptView Raw
1/**
2 * @license React
3 * react-dom-server-legacy.browser.development.js
4 *
5 * Copyright (c) Facebook, Inc. and its affiliates.
6 *
7 * This source code is licensed under the MIT license found in the
8 * LICENSE file in the root directory of this source tree.
9 */
10(function (global, factory) {
11 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
12 typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
13 (global = global || self, factory(global.ReactDOMServer = {}, global.React));
14}(this, (function (exports, React) { 'use strict';
15
16 var ReactVersion = '18.0.0-fc46dba67-20220329';
17
18 var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
19
20 // by calls to these methods by a Babel plugin.
21 //
22 // In PROD (or in packages without access to React internals),
23 // they are left as they are instead.
24
25 function warn(format) {
26 {
27 {
28 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
29 args[_key - 1] = arguments[_key];
30 }
31
32 printWarning('warn', format, args);
33 }
34 }
35 }
36 function error(format) {
37 {
38 {
39 for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
40 args[_key2 - 1] = arguments[_key2];
41 }
42
43 printWarning('error', format, args);
44 }
45 }
46 }
47
48 function printWarning(level, format, args) {
49 // When changing this logic, you might want to also
50 // update consoleWithStackDev.www.js as well.
51 {
52 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
53 var stack = ReactDebugCurrentFrame.getStackAddendum();
54
55 if (stack !== '') {
56 format += '%s';
57 args = args.concat([stack]);
58 } // eslint-disable-next-line react-internal/safe-string-coercion
59
60
61 var argsWithFormat = args.map(function (item) {
62 return String(item);
63 }); // Careful: RN currently depends on this prefix
64
65 argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
66 // breaks IE9: https://github.com/facebook/react/issues/13610
67 // eslint-disable-next-line react-internal/no-production-logging
68
69 Function.prototype.apply.call(console[level], console, argsWithFormat);
70 }
71 }
72
73 function scheduleWork(callback) {
74 callback();
75 }
76 function beginWriting(destination) {}
77 var prevWasCommentSegmenter = false;
78 function writeChunk(destination, chunk) {
79 writeChunkAndReturn(destination, chunk);
80 }
81 function writeChunkAndReturn(destination, chunk) {
82 if (prevWasCommentSegmenter) {
83 prevWasCommentSegmenter = false;
84
85 if (chunk[0] !== '<') {
86 destination.push('<!-- -->');
87 }
88 }
89
90 if (chunk === '<!-- -->') {
91 prevWasCommentSegmenter = true;
92 return true;
93 }
94
95 return destination.push(chunk);
96 }
97 function completeWriting(destination) {}
98 function close(destination) {
99 destination.push(null);
100 }
101 function stringToChunk(content) {
102 return content;
103 }
104 function stringToPrecomputedChunk(content) {
105 return content;
106 }
107 function closeWithError(destination, error) {
108 // $FlowFixMe: This is an Error object or the destination accepts other types.
109 destination.destroy(error);
110 }
111
112 /*
113 * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
114 * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
115 *
116 * The functions in this module will throw an easier-to-understand,
117 * easier-to-debug exception with a clear errors message message explaining the
118 * problem. (Instead of a confusing exception thrown inside the implementation
119 * of the `value` object).
120 */
121 // $FlowFixMe only called in DEV, so void return is not possible.
122 function typeName(value) {
123 {
124 // toStringTag is needed for namespaced types like Temporal.Instant
125 var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
126 var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
127 return type;
128 }
129 } // $FlowFixMe only called in DEV, so void return is not possible.
130
131
132 function willCoercionThrow(value) {
133 {
134 try {
135 testStringCoercion(value);
136 return false;
137 } catch (e) {
138 return true;
139 }
140 }
141 }
142
143 function testStringCoercion(value) {
144 // If you ended up here by following an exception call stack, here's what's
145 // happened: you supplied an object or symbol value to React (as a prop, key,
146 // DOM attribute, CSS property, string ref, etc.) and when React tried to
147 // coerce it to a string using `'' + value`, an exception was thrown.
148 //
149 // The most common types that will cause this exception are `Symbol` instances
150 // and Temporal objects like `Temporal.Instant`. But any object that has a
151 // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
152 // exception. (Library authors do this to prevent users from using built-in
153 // numeric operators like `+` or comparison operators like `>=` because custom
154 // methods are needed to perform accurate arithmetic or comparison.)
155 //
156 // To fix the problem, coerce this object or symbol value to a string before
157 // passing it to React. The most reliable way is usually `String(value)`.
158 //
159 // To find which value is throwing, check the browser or debugger console.
160 // Before this exception was thrown, there should be `console.error` output
161 // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
162 // problem and how that type was used: key, atrribute, input value prop, etc.
163 // In most cases, this console output also shows the component and its
164 // ancestor components where the exception happened.
165 //
166 // eslint-disable-next-line react-internal/safe-string-coercion
167 return '' + value;
168 }
169
170 function checkAttributeStringCoercion(value, attributeName) {
171 {
172 if (willCoercionThrow(value)) {
173 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));
174
175 return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
176 }
177 }
178 }
179 function checkCSSPropertyStringCoercion(value, propName) {
180 {
181 if (willCoercionThrow(value)) {
182 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));
183
184 return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
185 }
186 }
187 }
188 function checkHtmlStringCoercion(value) {
189 {
190 if (willCoercionThrow(value)) {
191 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));
192
193 return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
194 }
195 }
196 }
197
198 var hasOwnProperty = Object.prototype.hasOwnProperty;
199
200 // A reserved attribute.
201 // It is handled by React separately and shouldn't be written to the DOM.
202 var RESERVED = 0; // A simple string attribute.
203 // Attributes that aren't in the filter are presumed to have this type.
204
205 var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called
206 // "enumerated" attributes with "true" and "false" as possible values.
207 // When true, it should be set to a "true" string.
208 // When false, it should be set to a "false" string.
209
210 var BOOLEANISH_STRING = 2; // A real boolean attribute.
211 // When true, it should be present (set either to an empty string or its name).
212 // When false, it should be omitted.
213
214 var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.
215 // When true, it should be present (set either to an empty string or its name).
216 // When false, it should be omitted.
217 // For any other value, should be present with that value.
218
219 var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.
220 // When falsy, it should be removed.
221
222 var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.
223 // When falsy, it should be removed.
224
225 var POSITIVE_NUMERIC = 6;
226
227 /* eslint-disable max-len */
228 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";
229 /* eslint-enable max-len */
230
231 var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
232 var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
233 var illegalAttributeNameCache = {};
234 var validatedAttributeNameCache = {};
235 function isAttributeNameSafe(attributeName) {
236 if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
237 return true;
238 }
239
240 if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
241 return false;
242 }
243
244 if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
245 validatedAttributeNameCache[attributeName] = true;
246 return true;
247 }
248
249 illegalAttributeNameCache[attributeName] = true;
250
251 {
252 error('Invalid attribute name: `%s`', attributeName);
253 }
254
255 return false;
256 }
257 function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
258 if (propertyInfo !== null && propertyInfo.type === RESERVED) {
259 return false;
260 }
261
262 switch (typeof value) {
263 case 'function': // $FlowIssue symbol is perfectly valid here
264
265 case 'symbol':
266 // eslint-disable-line
267 return true;
268
269 case 'boolean':
270 {
271 if (isCustomComponentTag) {
272 return false;
273 }
274
275 if (propertyInfo !== null) {
276 return !propertyInfo.acceptsBooleans;
277 } else {
278 var prefix = name.toLowerCase().slice(0, 5);
279 return prefix !== 'data-' && prefix !== 'aria-';
280 }
281 }
282
283 default:
284 return false;
285 }
286 }
287 function getPropertyInfo(name) {
288 return properties.hasOwnProperty(name) ? properties[name] : null;
289 }
290
291 function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) {
292 this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
293 this.attributeName = attributeName;
294 this.attributeNamespace = attributeNamespace;
295 this.mustUseProperty = mustUseProperty;
296 this.propertyName = name;
297 this.type = type;
298 this.sanitizeURL = sanitizeURL;
299 this.removeEmptyString = removeEmptyString;
300 } // When adding attributes to this list, be sure to also add them to
301 // the `possibleStandardNames` module to ensure casing and incorrect
302 // name warnings.
303
304
305 var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.
306
307 var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular
308 // elements (not just inputs). Now that ReactDOMInput assigns to the
309 // defaultValue property -- do we need this?
310 'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'];
311
312 reservedProps.forEach(function (name) {
313 properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
314 name, // attributeName
315 null, // attributeNamespace
316 false, // sanitizeURL
317 false);
318 }); // A few React string attributes have a different name.
319 // This is a mapping from React prop names to the attribute names.
320
321 [['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
322 var name = _ref[0],
323 attributeName = _ref[1];
324 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
325 attributeName, // attributeName
326 null, // attributeNamespace
327 false, // sanitizeURL
328 false);
329 }); // These are "enumerated" HTML attributes that accept "true" and "false".
330 // In React, we let users pass `true` and `false` even though technically
331 // these aren't boolean attributes (they are coerced to strings).
332
333 ['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
334 properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
335 name.toLowerCase(), // attributeName
336 null, // attributeNamespace
337 false, // sanitizeURL
338 false);
339 }); // These are "enumerated" SVG attributes that accept "true" and "false".
340 // In React, we let users pass `true` and `false` even though technically
341 // these aren't boolean attributes (they are coerced to strings).
342 // Since these are SVG attributes, their attribute names are case-sensitive.
343
344 ['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
345 properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
346 name, // attributeName
347 null, // attributeNamespace
348 false, // sanitizeURL
349 false);
350 }); // These are HTML boolean attributes.
351
352 ['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM
353 // on the client side because the browsers are inconsistent. Instead we call focus().
354 'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata
355 'itemScope'].forEach(function (name) {
356 properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
357 name.toLowerCase(), // attributeName
358 null, // attributeNamespace
359 false, // sanitizeURL
360 false);
361 }); // These are the few React props that we set as DOM properties
362 // rather than attributes. These are all booleans.
363
364 ['checked', // Note: `option.selected` is not updated if `select.multiple` is
365 // disabled with `removeAttribute`. We have special logic for handling this.
366 'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list,
367 // you'll need to set attributeName to name.toLowerCase()
368 // instead in the assignment below.
369 ].forEach(function (name) {
370 properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
371 name, // attributeName
372 null, // attributeNamespace
373 false, // sanitizeURL
374 false);
375 }); // These are HTML attributes that are "overloaded booleans": they behave like
376 // booleans, but can also accept a string value.
377
378 ['capture', 'download' // NOTE: if you add a camelCased prop to this list,
379 // you'll need to set attributeName to name.toLowerCase()
380 // instead in the assignment below.
381 ].forEach(function (name) {
382 properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
383 name, // attributeName
384 null, // attributeNamespace
385 false, // sanitizeURL
386 false);
387 }); // These are HTML attributes that must be positive numbers.
388
389 ['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list,
390 // you'll need to set attributeName to name.toLowerCase()
391 // instead in the assignment below.
392 ].forEach(function (name) {
393 properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
394 name, // attributeName
395 null, // attributeNamespace
396 false, // sanitizeURL
397 false);
398 }); // These are HTML attributes that must be numbers.
399
400 ['rowSpan', 'start'].forEach(function (name) {
401 properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
402 name.toLowerCase(), // attributeName
403 null, // attributeNamespace
404 false, // sanitizeURL
405 false);
406 });
407 var CAMELIZE = /[\-\:]([a-z])/g;
408
409 var capitalize = function (token) {
410 return token[1].toUpperCase();
411 }; // This is a list of all SVG attributes that need special casing, namespacing,
412 // or boolean value assignment. Regular attributes that just accept strings
413 // and have the same names are omitted, just like in the HTML attribute filter.
414 // Some of these attributes can be hard to find. This list was created by
415 // scraping the MDN documentation.
416
417
418 ['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,
419 // you'll need to set attributeName to name.toLowerCase()
420 // instead in the assignment below.
421 ].forEach(function (attributeName) {
422 var name = attributeName.replace(CAMELIZE, capitalize);
423 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
424 attributeName, null, // attributeNamespace
425 false, // sanitizeURL
426 false);
427 }); // String SVG attributes with the xlink namespace.
428
429 ['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list,
430 // you'll need to set attributeName to name.toLowerCase()
431 // instead in the assignment below.
432 ].forEach(function (attributeName) {
433 var name = attributeName.replace(CAMELIZE, capitalize);
434 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
435 attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL
436 false);
437 }); // String SVG attributes with the xml namespace.
438
439 ['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list,
440 // you'll need to set attributeName to name.toLowerCase()
441 // instead in the assignment below.
442 ].forEach(function (attributeName) {
443 var name = attributeName.replace(CAMELIZE, capitalize);
444 properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
445 attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL
446 false);
447 }); // These attribute exists both in HTML and SVG.
448 // The attribute name is case-sensitive in SVG so we can't just use
449 // the React name like we do for attributes that exist only in HTML.
450
451 ['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
452 properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
453 attributeName.toLowerCase(), // attributeName
454 null, // attributeNamespace
455 false, // sanitizeURL
456 false);
457 }); // These attributes accept URLs. These must not allow javascript: URLS.
458 // These will also need to accept Trusted Types object in the future.
459
460 var xlinkHref = 'xlinkHref';
461 properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty
462 'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL
463 false);
464 ['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {
465 properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
466 attributeName.toLowerCase(), // attributeName
467 null, // attributeNamespace
468 true, // sanitizeURL
469 true);
470 });
471
472 /**
473 * CSS properties which accept numbers but are not in units of "px".
474 */
475 var isUnitlessNumber = {
476 animationIterationCount: true,
477 aspectRatio: true,
478 borderImageOutset: true,
479 borderImageSlice: true,
480 borderImageWidth: true,
481 boxFlex: true,
482 boxFlexGroup: true,
483 boxOrdinalGroup: true,
484 columnCount: true,
485 columns: true,
486 flex: true,
487 flexGrow: true,
488 flexPositive: true,
489 flexShrink: true,
490 flexNegative: true,
491 flexOrder: true,
492 gridArea: true,
493 gridRow: true,
494 gridRowEnd: true,
495 gridRowSpan: true,
496 gridRowStart: true,
497 gridColumn: true,
498 gridColumnEnd: true,
499 gridColumnSpan: true,
500 gridColumnStart: true,
501 fontWeight: true,
502 lineClamp: true,
503 lineHeight: true,
504 opacity: true,
505 order: true,
506 orphans: true,
507 tabSize: true,
508 widows: true,
509 zIndex: true,
510 zoom: true,
511 // SVG-related properties
512 fillOpacity: true,
513 floodOpacity: true,
514 stopOpacity: true,
515 strokeDasharray: true,
516 strokeDashoffset: true,
517 strokeMiterlimit: true,
518 strokeOpacity: true,
519 strokeWidth: true
520 };
521 /**
522 * @param {string} prefix vendor-specific prefix, eg: Webkit
523 * @param {string} key style name, eg: transitionDuration
524 * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
525 * WebkitTransitionDuration
526 */
527
528 function prefixKey(prefix, key) {
529 return prefix + key.charAt(0).toUpperCase() + key.substring(1);
530 }
531 /**
532 * Support style names that may come passed in prefixed by adding permutations
533 * of vendor prefixes.
534 */
535
536
537 var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
538 // infinite loop, because it iterates over the newly added props too.
539
540 Object.keys(isUnitlessNumber).forEach(function (prop) {
541 prefixes.forEach(function (prefix) {
542 isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
543 });
544 });
545
546 var hasReadOnlyValue = {
547 button: true,
548 checkbox: true,
549 image: true,
550 hidden: true,
551 radio: true,
552 reset: true,
553 submit: true
554 };
555 function checkControlledValueProps(tagName, props) {
556 {
557 if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) {
558 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`.');
559 }
560
561 if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) {
562 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`.');
563 }
564 }
565 }
566
567 function isCustomComponent(tagName, props) {
568 if (tagName.indexOf('-') === -1) {
569 return typeof props.is === 'string';
570 }
571
572 switch (tagName) {
573 // These are reserved SVG and MathML elements.
574 // We don't mind this list too much because we expect it to never grow.
575 // The alternative is to track the namespace in a few places which is convoluted.
576 // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
577 case 'annotation-xml':
578 case 'color-profile':
579 case 'font-face':
580 case 'font-face-src':
581 case 'font-face-uri':
582 case 'font-face-format':
583 case 'font-face-name':
584 case 'missing-glyph':
585 return false;
586
587 default:
588 return true;
589 }
590 }
591
592 var ariaProperties = {
593 'aria-current': 0,
594 // state
595 'aria-description': 0,
596 'aria-details': 0,
597 'aria-disabled': 0,
598 // state
599 'aria-hidden': 0,
600 // state
601 'aria-invalid': 0,
602 // state
603 'aria-keyshortcuts': 0,
604 'aria-label': 0,
605 'aria-roledescription': 0,
606 // Widget Attributes
607 'aria-autocomplete': 0,
608 'aria-checked': 0,
609 'aria-expanded': 0,
610 'aria-haspopup': 0,
611 'aria-level': 0,
612 'aria-modal': 0,
613 'aria-multiline': 0,
614 'aria-multiselectable': 0,
615 'aria-orientation': 0,
616 'aria-placeholder': 0,
617 'aria-pressed': 0,
618 'aria-readonly': 0,
619 'aria-required': 0,
620 'aria-selected': 0,
621 'aria-sort': 0,
622 'aria-valuemax': 0,
623 'aria-valuemin': 0,
624 'aria-valuenow': 0,
625 'aria-valuetext': 0,
626 // Live Region Attributes
627 'aria-atomic': 0,
628 'aria-busy': 0,
629 'aria-live': 0,
630 'aria-relevant': 0,
631 // Drag-and-Drop Attributes
632 'aria-dropeffect': 0,
633 'aria-grabbed': 0,
634 // Relationship Attributes
635 'aria-activedescendant': 0,
636 'aria-colcount': 0,
637 'aria-colindex': 0,
638 'aria-colspan': 0,
639 'aria-controls': 0,
640 'aria-describedby': 0,
641 'aria-errormessage': 0,
642 'aria-flowto': 0,
643 'aria-labelledby': 0,
644 'aria-owns': 0,
645 'aria-posinset': 0,
646 'aria-rowcount': 0,
647 'aria-rowindex': 0,
648 'aria-rowspan': 0,
649 'aria-setsize': 0
650 };
651
652 var warnedProperties = {};
653 var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
654 var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
655
656 function validateProperty(tagName, name) {
657 {
658 if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) {
659 return true;
660 }
661
662 if (rARIACamel.test(name)) {
663 var ariaName = 'aria-' + name.slice(4).toLowerCase();
664 var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM
665 // DOM properties, then it is an invalid aria-* attribute.
666
667 if (correctName == null) {
668 error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);
669
670 warnedProperties[name] = true;
671 return true;
672 } // aria-* attributes should be lowercase; suggest the lowercase version.
673
674
675 if (name !== correctName) {
676 error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);
677
678 warnedProperties[name] = true;
679 return true;
680 }
681 }
682
683 if (rARIA.test(name)) {
684 var lowerCasedName = name.toLowerCase();
685 var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM
686 // DOM properties, then it is an invalid aria-* attribute.
687
688 if (standardName == null) {
689 warnedProperties[name] = true;
690 return false;
691 } // aria-* attributes should be lowercase; suggest the lowercase version.
692
693
694 if (name !== standardName) {
695 error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);
696
697 warnedProperties[name] = true;
698 return true;
699 }
700 }
701 }
702
703 return true;
704 }
705
706 function warnInvalidARIAProps(type, props) {
707 {
708 var invalidProps = [];
709
710 for (var key in props) {
711 var isValid = validateProperty(type, key);
712
713 if (!isValid) {
714 invalidProps.push(key);
715 }
716 }
717
718 var unknownPropString = invalidProps.map(function (prop) {
719 return '`' + prop + '`';
720 }).join(', ');
721
722 if (invalidProps.length === 1) {
723 error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
724 } else if (invalidProps.length > 1) {
725 error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);
726 }
727 }
728 }
729
730 function validateProperties(type, props) {
731 if (isCustomComponent(type, props)) {
732 return;
733 }
734
735 warnInvalidARIAProps(type, props);
736 }
737
738 var didWarnValueNull = false;
739 function validateProperties$1(type, props) {
740 {
741 if (type !== 'input' && type !== 'textarea' && type !== 'select') {
742 return;
743 }
744
745 if (props != null && props.value === null && !didWarnValueNull) {
746 didWarnValueNull = true;
747
748 if (type === 'select' && props.multiple) {
749 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);
750 } else {
751 error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type);
752 }
753 }
754 }
755 }
756
757 // When adding attributes to the HTML or SVG allowed attribute list, be sure to
758 // also add them to this module to ensure casing and incorrect name
759 // warnings.
760 var possibleStandardNames = {
761 // HTML
762 accept: 'accept',
763 acceptcharset: 'acceptCharset',
764 'accept-charset': 'acceptCharset',
765 accesskey: 'accessKey',
766 action: 'action',
767 allowfullscreen: 'allowFullScreen',
768 alt: 'alt',
769 as: 'as',
770 async: 'async',
771 autocapitalize: 'autoCapitalize',
772 autocomplete: 'autoComplete',
773 autocorrect: 'autoCorrect',
774 autofocus: 'autoFocus',
775 autoplay: 'autoPlay',
776 autosave: 'autoSave',
777 capture: 'capture',
778 cellpadding: 'cellPadding',
779 cellspacing: 'cellSpacing',
780 challenge: 'challenge',
781 charset: 'charSet',
782 checked: 'checked',
783 children: 'children',
784 cite: 'cite',
785 class: 'className',
786 classid: 'classID',
787 classname: 'className',
788 cols: 'cols',
789 colspan: 'colSpan',
790 content: 'content',
791 contenteditable: 'contentEditable',
792 contextmenu: 'contextMenu',
793 controls: 'controls',
794 controlslist: 'controlsList',
795 coords: 'coords',
796 crossorigin: 'crossOrigin',
797 dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
798 data: 'data',
799 datetime: 'dateTime',
800 default: 'default',
801 defaultchecked: 'defaultChecked',
802 defaultvalue: 'defaultValue',
803 defer: 'defer',
804 dir: 'dir',
805 disabled: 'disabled',
806 disablepictureinpicture: 'disablePictureInPicture',
807 disableremoteplayback: 'disableRemotePlayback',
808 download: 'download',
809 draggable: 'draggable',
810 enctype: 'encType',
811 enterkeyhint: 'enterKeyHint',
812 for: 'htmlFor',
813 form: 'form',
814 formmethod: 'formMethod',
815 formaction: 'formAction',
816 formenctype: 'formEncType',
817 formnovalidate: 'formNoValidate',
818 formtarget: 'formTarget',
819 frameborder: 'frameBorder',
820 headers: 'headers',
821 height: 'height',
822 hidden: 'hidden',
823 high: 'high',
824 href: 'href',
825 hreflang: 'hrefLang',
826 htmlfor: 'htmlFor',
827 httpequiv: 'httpEquiv',
828 'http-equiv': 'httpEquiv',
829 icon: 'icon',
830 id: 'id',
831 imagesizes: 'imageSizes',
832 imagesrcset: 'imageSrcSet',
833 innerhtml: 'innerHTML',
834 inputmode: 'inputMode',
835 integrity: 'integrity',
836 is: 'is',
837 itemid: 'itemID',
838 itemprop: 'itemProp',
839 itemref: 'itemRef',
840 itemscope: 'itemScope',
841 itemtype: 'itemType',
842 keyparams: 'keyParams',
843 keytype: 'keyType',
844 kind: 'kind',
845 label: 'label',
846 lang: 'lang',
847 list: 'list',
848 loop: 'loop',
849 low: 'low',
850 manifest: 'manifest',
851 marginwidth: 'marginWidth',
852 marginheight: 'marginHeight',
853 max: 'max',
854 maxlength: 'maxLength',
855 media: 'media',
856 mediagroup: 'mediaGroup',
857 method: 'method',
858 min: 'min',
859 minlength: 'minLength',
860 multiple: 'multiple',
861 muted: 'muted',
862 name: 'name',
863 nomodule: 'noModule',
864 nonce: 'nonce',
865 novalidate: 'noValidate',
866 open: 'open',
867 optimum: 'optimum',
868 pattern: 'pattern',
869 placeholder: 'placeholder',
870 playsinline: 'playsInline',
871 poster: 'poster',
872 preload: 'preload',
873 profile: 'profile',
874 radiogroup: 'radioGroup',
875 readonly: 'readOnly',
876 referrerpolicy: 'referrerPolicy',
877 rel: 'rel',
878 required: 'required',
879 reversed: 'reversed',
880 role: 'role',
881 rows: 'rows',
882 rowspan: 'rowSpan',
883 sandbox: 'sandbox',
884 scope: 'scope',
885 scoped: 'scoped',
886 scrolling: 'scrolling',
887 seamless: 'seamless',
888 selected: 'selected',
889 shape: 'shape',
890 size: 'size',
891 sizes: 'sizes',
892 span: 'span',
893 spellcheck: 'spellCheck',
894 src: 'src',
895 srcdoc: 'srcDoc',
896 srclang: 'srcLang',
897 srcset: 'srcSet',
898 start: 'start',
899 step: 'step',
900 style: 'style',
901 summary: 'summary',
902 tabindex: 'tabIndex',
903 target: 'target',
904 title: 'title',
905 type: 'type',
906 usemap: 'useMap',
907 value: 'value',
908 width: 'width',
909 wmode: 'wmode',
910 wrap: 'wrap',
911 // SVG
912 about: 'about',
913 accentheight: 'accentHeight',
914 'accent-height': 'accentHeight',
915 accumulate: 'accumulate',
916 additive: 'additive',
917 alignmentbaseline: 'alignmentBaseline',
918 'alignment-baseline': 'alignmentBaseline',
919 allowreorder: 'allowReorder',
920 alphabetic: 'alphabetic',
921 amplitude: 'amplitude',
922 arabicform: 'arabicForm',
923 'arabic-form': 'arabicForm',
924 ascent: 'ascent',
925 attributename: 'attributeName',
926 attributetype: 'attributeType',
927 autoreverse: 'autoReverse',
928 azimuth: 'azimuth',
929 basefrequency: 'baseFrequency',
930 baselineshift: 'baselineShift',
931 'baseline-shift': 'baselineShift',
932 baseprofile: 'baseProfile',
933 bbox: 'bbox',
934 begin: 'begin',
935 bias: 'bias',
936 by: 'by',
937 calcmode: 'calcMode',
938 capheight: 'capHeight',
939 'cap-height': 'capHeight',
940 clip: 'clip',
941 clippath: 'clipPath',
942 'clip-path': 'clipPath',
943 clippathunits: 'clipPathUnits',
944 cliprule: 'clipRule',
945 'clip-rule': 'clipRule',
946 color: 'color',
947 colorinterpolation: 'colorInterpolation',
948 'color-interpolation': 'colorInterpolation',
949 colorinterpolationfilters: 'colorInterpolationFilters',
950 'color-interpolation-filters': 'colorInterpolationFilters',
951 colorprofile: 'colorProfile',
952 'color-profile': 'colorProfile',
953 colorrendering: 'colorRendering',
954 'color-rendering': 'colorRendering',
955 contentscripttype: 'contentScriptType',
956 contentstyletype: 'contentStyleType',
957 cursor: 'cursor',
958 cx: 'cx',
959 cy: 'cy',
960 d: 'd',
961 datatype: 'datatype',
962 decelerate: 'decelerate',
963 descent: 'descent',
964 diffuseconstant: 'diffuseConstant',
965 direction: 'direction',
966 display: 'display',
967 divisor: 'divisor',
968 dominantbaseline: 'dominantBaseline',
969 'dominant-baseline': 'dominantBaseline',
970 dur: 'dur',
971 dx: 'dx',
972 dy: 'dy',
973 edgemode: 'edgeMode',
974 elevation: 'elevation',
975 enablebackground: 'enableBackground',
976 'enable-background': 'enableBackground',
977 end: 'end',
978 exponent: 'exponent',
979 externalresourcesrequired: 'externalResourcesRequired',
980 fill: 'fill',
981 fillopacity: 'fillOpacity',
982 'fill-opacity': 'fillOpacity',
983 fillrule: 'fillRule',
984 'fill-rule': 'fillRule',
985 filter: 'filter',
986 filterres: 'filterRes',
987 filterunits: 'filterUnits',
988 floodopacity: 'floodOpacity',
989 'flood-opacity': 'floodOpacity',
990 floodcolor: 'floodColor',
991 'flood-color': 'floodColor',
992 focusable: 'focusable',
993 fontfamily: 'fontFamily',
994 'font-family': 'fontFamily',
995 fontsize: 'fontSize',
996 'font-size': 'fontSize',
997 fontsizeadjust: 'fontSizeAdjust',
998 'font-size-adjust': 'fontSizeAdjust',
999 fontstretch: 'fontStretch',
1000 'font-stretch': 'fontStretch',
1001 fontstyle: 'fontStyle',
1002 'font-style': 'fontStyle',
1003 fontvariant: 'fontVariant',
1004 'font-variant': 'fontVariant',
1005 fontweight: 'fontWeight',
1006 'font-weight': 'fontWeight',
1007 format: 'format',
1008 from: 'from',
1009 fx: 'fx',
1010 fy: 'fy',
1011 g1: 'g1',
1012 g2: 'g2',
1013 glyphname: 'glyphName',
1014 'glyph-name': 'glyphName',
1015 glyphorientationhorizontal: 'glyphOrientationHorizontal',
1016 'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
1017 glyphorientationvertical: 'glyphOrientationVertical',
1018 'glyph-orientation-vertical': 'glyphOrientationVertical',
1019 glyphref: 'glyphRef',
1020 gradienttransform: 'gradientTransform',
1021 gradientunits: 'gradientUnits',
1022 hanging: 'hanging',
1023 horizadvx: 'horizAdvX',
1024 'horiz-adv-x': 'horizAdvX',
1025 horizoriginx: 'horizOriginX',
1026 'horiz-origin-x': 'horizOriginX',
1027 ideographic: 'ideographic',
1028 imagerendering: 'imageRendering',
1029 'image-rendering': 'imageRendering',
1030 in2: 'in2',
1031 in: 'in',
1032 inlist: 'inlist',
1033 intercept: 'intercept',
1034 k1: 'k1',
1035 k2: 'k2',
1036 k3: 'k3',
1037 k4: 'k4',
1038 k: 'k',
1039 kernelmatrix: 'kernelMatrix',
1040 kernelunitlength: 'kernelUnitLength',
1041 kerning: 'kerning',
1042 keypoints: 'keyPoints',
1043 keysplines: 'keySplines',
1044 keytimes: 'keyTimes',
1045 lengthadjust: 'lengthAdjust',
1046 letterspacing: 'letterSpacing',
1047 'letter-spacing': 'letterSpacing',
1048 lightingcolor: 'lightingColor',
1049 'lighting-color': 'lightingColor',
1050 limitingconeangle: 'limitingConeAngle',
1051 local: 'local',
1052 markerend: 'markerEnd',
1053 'marker-end': 'markerEnd',
1054 markerheight: 'markerHeight',
1055 markermid: 'markerMid',
1056 'marker-mid': 'markerMid',
1057 markerstart: 'markerStart',
1058 'marker-start': 'markerStart',
1059 markerunits: 'markerUnits',
1060 markerwidth: 'markerWidth',
1061 mask: 'mask',
1062 maskcontentunits: 'maskContentUnits',
1063 maskunits: 'maskUnits',
1064 mathematical: 'mathematical',
1065 mode: 'mode',
1066 numoctaves: 'numOctaves',
1067 offset: 'offset',
1068 opacity: 'opacity',
1069 operator: 'operator',
1070 order: 'order',
1071 orient: 'orient',
1072 orientation: 'orientation',
1073 origin: 'origin',
1074 overflow: 'overflow',
1075 overlineposition: 'overlinePosition',
1076 'overline-position': 'overlinePosition',
1077 overlinethickness: 'overlineThickness',
1078 'overline-thickness': 'overlineThickness',
1079 paintorder: 'paintOrder',
1080 'paint-order': 'paintOrder',
1081 panose1: 'panose1',
1082 'panose-1': 'panose1',
1083 pathlength: 'pathLength',
1084 patterncontentunits: 'patternContentUnits',
1085 patterntransform: 'patternTransform',
1086 patternunits: 'patternUnits',
1087 pointerevents: 'pointerEvents',
1088 'pointer-events': 'pointerEvents',
1089 points: 'points',
1090 pointsatx: 'pointsAtX',
1091 pointsaty: 'pointsAtY',
1092 pointsatz: 'pointsAtZ',
1093 prefix: 'prefix',
1094 preservealpha: 'preserveAlpha',
1095 preserveaspectratio: 'preserveAspectRatio',
1096 primitiveunits: 'primitiveUnits',
1097 property: 'property',
1098 r: 'r',
1099 radius: 'radius',
1100 refx: 'refX',
1101 refy: 'refY',
1102 renderingintent: 'renderingIntent',
1103 'rendering-intent': 'renderingIntent',
1104 repeatcount: 'repeatCount',
1105 repeatdur: 'repeatDur',
1106 requiredextensions: 'requiredExtensions',
1107 requiredfeatures: 'requiredFeatures',
1108 resource: 'resource',
1109 restart: 'restart',
1110 result: 'result',
1111 results: 'results',
1112 rotate: 'rotate',
1113 rx: 'rx',
1114 ry: 'ry',
1115 scale: 'scale',
1116 security: 'security',
1117 seed: 'seed',
1118 shaperendering: 'shapeRendering',
1119 'shape-rendering': 'shapeRendering',
1120 slope: 'slope',
1121 spacing: 'spacing',
1122 specularconstant: 'specularConstant',
1123 specularexponent: 'specularExponent',
1124 speed: 'speed',
1125 spreadmethod: 'spreadMethod',
1126 startoffset: 'startOffset',
1127 stddeviation: 'stdDeviation',
1128 stemh: 'stemh',
1129 stemv: 'stemv',
1130 stitchtiles: 'stitchTiles',
1131 stopcolor: 'stopColor',
1132 'stop-color': 'stopColor',
1133 stopopacity: 'stopOpacity',
1134 'stop-opacity': 'stopOpacity',
1135 strikethroughposition: 'strikethroughPosition',
1136 'strikethrough-position': 'strikethroughPosition',
1137 strikethroughthickness: 'strikethroughThickness',
1138 'strikethrough-thickness': 'strikethroughThickness',
1139 string: 'string',
1140 stroke: 'stroke',
1141 strokedasharray: 'strokeDasharray',
1142 'stroke-dasharray': 'strokeDasharray',
1143 strokedashoffset: 'strokeDashoffset',
1144 'stroke-dashoffset': 'strokeDashoffset',
1145 strokelinecap: 'strokeLinecap',
1146 'stroke-linecap': 'strokeLinecap',
1147 strokelinejoin: 'strokeLinejoin',
1148 'stroke-linejoin': 'strokeLinejoin',
1149 strokemiterlimit: 'strokeMiterlimit',
1150 'stroke-miterlimit': 'strokeMiterlimit',
1151 strokewidth: 'strokeWidth',
1152 'stroke-width': 'strokeWidth',
1153 strokeopacity: 'strokeOpacity',
1154 'stroke-opacity': 'strokeOpacity',
1155 suppresscontenteditablewarning: 'suppressContentEditableWarning',
1156 suppresshydrationwarning: 'suppressHydrationWarning',
1157 surfacescale: 'surfaceScale',
1158 systemlanguage: 'systemLanguage',
1159 tablevalues: 'tableValues',
1160 targetx: 'targetX',
1161 targety: 'targetY',
1162 textanchor: 'textAnchor',
1163 'text-anchor': 'textAnchor',
1164 textdecoration: 'textDecoration',
1165 'text-decoration': 'textDecoration',
1166 textlength: 'textLength',
1167 textrendering: 'textRendering',
1168 'text-rendering': 'textRendering',
1169 to: 'to',
1170 transform: 'transform',
1171 typeof: 'typeof',
1172 u1: 'u1',
1173 u2: 'u2',
1174 underlineposition: 'underlinePosition',
1175 'underline-position': 'underlinePosition',
1176 underlinethickness: 'underlineThickness',
1177 'underline-thickness': 'underlineThickness',
1178 unicode: 'unicode',
1179 unicodebidi: 'unicodeBidi',
1180 'unicode-bidi': 'unicodeBidi',
1181 unicoderange: 'unicodeRange',
1182 'unicode-range': 'unicodeRange',
1183 unitsperem: 'unitsPerEm',
1184 'units-per-em': 'unitsPerEm',
1185 unselectable: 'unselectable',
1186 valphabetic: 'vAlphabetic',
1187 'v-alphabetic': 'vAlphabetic',
1188 values: 'values',
1189 vectoreffect: 'vectorEffect',
1190 'vector-effect': 'vectorEffect',
1191 version: 'version',
1192 vertadvy: 'vertAdvY',
1193 'vert-adv-y': 'vertAdvY',
1194 vertoriginx: 'vertOriginX',
1195 'vert-origin-x': 'vertOriginX',
1196 vertoriginy: 'vertOriginY',
1197 'vert-origin-y': 'vertOriginY',
1198 vhanging: 'vHanging',
1199 'v-hanging': 'vHanging',
1200 videographic: 'vIdeographic',
1201 'v-ideographic': 'vIdeographic',
1202 viewbox: 'viewBox',
1203 viewtarget: 'viewTarget',
1204 visibility: 'visibility',
1205 vmathematical: 'vMathematical',
1206 'v-mathematical': 'vMathematical',
1207 vocab: 'vocab',
1208 widths: 'widths',
1209 wordspacing: 'wordSpacing',
1210 'word-spacing': 'wordSpacing',
1211 writingmode: 'writingMode',
1212 'writing-mode': 'writingMode',
1213 x1: 'x1',
1214 x2: 'x2',
1215 x: 'x',
1216 xchannelselector: 'xChannelSelector',
1217 xheight: 'xHeight',
1218 'x-height': 'xHeight',
1219 xlinkactuate: 'xlinkActuate',
1220 'xlink:actuate': 'xlinkActuate',
1221 xlinkarcrole: 'xlinkArcrole',
1222 'xlink:arcrole': 'xlinkArcrole',
1223 xlinkhref: 'xlinkHref',
1224 'xlink:href': 'xlinkHref',
1225 xlinkrole: 'xlinkRole',
1226 'xlink:role': 'xlinkRole',
1227 xlinkshow: 'xlinkShow',
1228 'xlink:show': 'xlinkShow',
1229 xlinktitle: 'xlinkTitle',
1230 'xlink:title': 'xlinkTitle',
1231 xlinktype: 'xlinkType',
1232 'xlink:type': 'xlinkType',
1233 xmlbase: 'xmlBase',
1234 'xml:base': 'xmlBase',
1235 xmllang: 'xmlLang',
1236 'xml:lang': 'xmlLang',
1237 xmlns: 'xmlns',
1238 'xml:space': 'xmlSpace',
1239 xmlnsxlink: 'xmlnsXlink',
1240 'xmlns:xlink': 'xmlnsXlink',
1241 xmlspace: 'xmlSpace',
1242 y1: 'y1',
1243 y2: 'y2',
1244 y: 'y',
1245 ychannelselector: 'yChannelSelector',
1246 z: 'z',
1247 zoomandpan: 'zoomAndPan'
1248 };
1249
1250 var validateProperty$1 = function () {};
1251
1252 {
1253 var warnedProperties$1 = {};
1254 var EVENT_NAME_REGEX = /^on./;
1255 var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
1256 var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
1257 var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
1258
1259 validateProperty$1 = function (tagName, name, value, eventRegistry) {
1260 if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
1261 return true;
1262 }
1263
1264 var lowerCasedName = name.toLowerCase();
1265
1266 if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
1267 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.');
1268
1269 warnedProperties$1[name] = true;
1270 return true;
1271 } // We can't rely on the event system being injected on the server.
1272
1273
1274 if (eventRegistry != null) {
1275 var registrationNameDependencies = eventRegistry.registrationNameDependencies,
1276 possibleRegistrationNames = eventRegistry.possibleRegistrationNames;
1277
1278 if (registrationNameDependencies.hasOwnProperty(name)) {
1279 return true;
1280 }
1281
1282 var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;
1283
1284 if (registrationName != null) {
1285 error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);
1286
1287 warnedProperties$1[name] = true;
1288 return true;
1289 }
1290
1291 if (EVENT_NAME_REGEX.test(name)) {
1292 error('Unknown event handler property `%s`. It will be ignored.', name);
1293
1294 warnedProperties$1[name] = true;
1295 return true;
1296 }
1297 } else if (EVENT_NAME_REGEX.test(name)) {
1298 // If no event plugins have been injected, we are in a server environment.
1299 // So we can't tell if the event name is correct for sure, but we can filter
1300 // out known bad ones like `onclick`. We can't suggest a specific replacement though.
1301 if (INVALID_EVENT_NAME_REGEX.test(name)) {
1302 error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
1303 }
1304
1305 warnedProperties$1[name] = true;
1306 return true;
1307 } // Let the ARIA attribute hook validate ARIA attributes
1308
1309
1310 if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
1311 return true;
1312 }
1313
1314 if (lowerCasedName === 'innerhtml') {
1315 error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');
1316
1317 warnedProperties$1[name] = true;
1318 return true;
1319 }
1320
1321 if (lowerCasedName === 'aria') {
1322 error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');
1323
1324 warnedProperties$1[name] = true;
1325 return true;
1326 }
1327
1328 if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
1329 error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);
1330
1331 warnedProperties$1[name] = true;
1332 return true;
1333 }
1334
1335 if (typeof value === 'number' && isNaN(value)) {
1336 error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);
1337
1338 warnedProperties$1[name] = true;
1339 return true;
1340 }
1341
1342 var propertyInfo = getPropertyInfo(name);
1343 var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.
1344
1345 if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
1346 var standardName = possibleStandardNames[lowerCasedName];
1347
1348 if (standardName !== name) {
1349 error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);
1350
1351 warnedProperties$1[name] = true;
1352 return true;
1353 }
1354 } else if (!isReserved && name !== lowerCasedName) {
1355 // Unknown attributes should have lowercase casing since that's how they
1356 // will be cased anyway with server rendering.
1357 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);
1358
1359 warnedProperties$1[name] = true;
1360 return true;
1361 }
1362
1363 if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
1364 if (value) {
1365 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);
1366 } else {
1367 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);
1368 }
1369
1370 warnedProperties$1[name] = true;
1371 return true;
1372 } // Now that we've validated casing, do not validate
1373 // data types for reserved props
1374
1375
1376 if (isReserved) {
1377 return true;
1378 } // Warn when a known attribute is a bad type
1379
1380
1381 if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
1382 warnedProperties$1[name] = true;
1383 return false;
1384 } // Warn when passing the strings 'false' or 'true' into a boolean prop
1385
1386
1387 if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
1388 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);
1389
1390 warnedProperties$1[name] = true;
1391 return true;
1392 }
1393
1394 return true;
1395 };
1396 }
1397
1398 var warnUnknownProperties = function (type, props, eventRegistry) {
1399 {
1400 var unknownProps = [];
1401
1402 for (var key in props) {
1403 var isValid = validateProperty$1(type, key, props[key], eventRegistry);
1404
1405 if (!isValid) {
1406 unknownProps.push(key);
1407 }
1408 }
1409
1410 var unknownPropString = unknownProps.map(function (prop) {
1411 return '`' + prop + '`';
1412 }).join(', ');
1413
1414 if (unknownProps.length === 1) {
1415 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);
1416 } else if (unknownProps.length > 1) {
1417 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);
1418 }
1419 }
1420 };
1421
1422 function validateProperties$2(type, props, eventRegistry) {
1423 if (isCustomComponent(type, props)) {
1424 return;
1425 }
1426
1427 warnUnknownProperties(type, props, eventRegistry);
1428 }
1429
1430 var warnValidStyle = function () {};
1431
1432 {
1433 // 'msTransform' is correct, but the other prefixes should be capitalized
1434 var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
1435 var msPattern = /^-ms-/;
1436 var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon
1437
1438 var badStyleValueWithSemicolonPattern = /;\s*$/;
1439 var warnedStyleNames = {};
1440 var warnedStyleValues = {};
1441 var warnedForNaNValue = false;
1442 var warnedForInfinityValue = false;
1443
1444 var camelize = function (string) {
1445 return string.replace(hyphenPattern, function (_, character) {
1446 return character.toUpperCase();
1447 });
1448 };
1449
1450 var warnHyphenatedStyleName = function (name) {
1451 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
1452 return;
1453 }
1454
1455 warnedStyleNames[name] = true;
1456
1457 error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests
1458 // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
1459 // is converted to lowercase `ms`.
1460 camelize(name.replace(msPattern, 'ms-')));
1461 };
1462
1463 var warnBadVendoredStyleName = function (name) {
1464 if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
1465 return;
1466 }
1467
1468 warnedStyleNames[name] = true;
1469
1470 error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
1471 };
1472
1473 var warnStyleValueWithSemicolon = function (name, value) {
1474 if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
1475 return;
1476 }
1477
1478 warnedStyleValues[value] = true;
1479
1480 error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
1481 };
1482
1483 var warnStyleValueIsNaN = function (name, value) {
1484 if (warnedForNaNValue) {
1485 return;
1486 }
1487
1488 warnedForNaNValue = true;
1489
1490 error('`NaN` is an invalid value for the `%s` css style property.', name);
1491 };
1492
1493 var warnStyleValueIsInfinity = function (name, value) {
1494 if (warnedForInfinityValue) {
1495 return;
1496 }
1497
1498 warnedForInfinityValue = true;
1499
1500 error('`Infinity` is an invalid value for the `%s` css style property.', name);
1501 };
1502
1503 warnValidStyle = function (name, value) {
1504 if (name.indexOf('-') > -1) {
1505 warnHyphenatedStyleName(name);
1506 } else if (badVendoredStyleNamePattern.test(name)) {
1507 warnBadVendoredStyleName(name);
1508 } else if (badStyleValueWithSemicolonPattern.test(value)) {
1509 warnStyleValueWithSemicolon(name, value);
1510 }
1511
1512 if (typeof value === 'number') {
1513 if (isNaN(value)) {
1514 warnStyleValueIsNaN(name, value);
1515 } else if (!isFinite(value)) {
1516 warnStyleValueIsInfinity(name, value);
1517 }
1518 }
1519 };
1520 }
1521
1522 var warnValidStyle$1 = warnValidStyle;
1523
1524 // code copied and modified from escape-html
1525 var matchHtmlRegExp = /["'&<>]/;
1526 /**
1527 * Escapes special characters and HTML entities in a given html string.
1528 *
1529 * @param {string} string HTML string to escape for later insertion
1530 * @return {string}
1531 * @public
1532 */
1533
1534 function escapeHtml(string) {
1535 {
1536 checkHtmlStringCoercion(string);
1537 }
1538
1539 var str = '' + string;
1540 var match = matchHtmlRegExp.exec(str);
1541
1542 if (!match) {
1543 return str;
1544 }
1545
1546 var escape;
1547 var html = '';
1548 var index;
1549 var lastIndex = 0;
1550
1551 for (index = match.index; index < str.length; index++) {
1552 switch (str.charCodeAt(index)) {
1553 case 34:
1554 // "
1555 escape = '&quot;';
1556 break;
1557
1558 case 38:
1559 // &
1560 escape = '&amp;';
1561 break;
1562
1563 case 39:
1564 // '
1565 escape = '&#x27;'; // modified from escape-html; used to be '&#39'
1566
1567 break;
1568
1569 case 60:
1570 // <
1571 escape = '&lt;';
1572 break;
1573
1574 case 62:
1575 // >
1576 escape = '&gt;';
1577 break;
1578
1579 default:
1580 continue;
1581 }
1582
1583 if (lastIndex !== index) {
1584 html += str.substring(lastIndex, index);
1585 }
1586
1587 lastIndex = index + 1;
1588 html += escape;
1589 }
1590
1591 return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
1592 } // end code copied and modified from escape-html
1593
1594 /**
1595 * Escapes text to prevent scripting attacks.
1596 *
1597 * @param {*} text Text value to escape.
1598 * @return {string} An escaped string.
1599 */
1600
1601
1602 function escapeTextForBrowser(text) {
1603 if (typeof text === 'boolean' || typeof text === 'number') {
1604 // this shortcircuit helps perf for types that we know will never have
1605 // special characters, especially given that this function is used often
1606 // for numeric dom ids.
1607 return '' + text;
1608 }
1609
1610 return escapeHtml(text);
1611 }
1612
1613 var uppercasePattern = /([A-Z])/g;
1614 var msPattern$1 = /^ms-/;
1615 /**
1616 * Hyphenates a camelcased CSS property name, for example:
1617 *
1618 * > hyphenateStyleName('backgroundColor')
1619 * < "background-color"
1620 * > hyphenateStyleName('MozTransition')
1621 * < "-moz-transition"
1622 * > hyphenateStyleName('msTransition')
1623 * < "-ms-transition"
1624 *
1625 * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
1626 * is converted to `-ms-`.
1627 */
1628
1629 function hyphenateStyleName(name) {
1630 return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern$1, '-ms-');
1631 }
1632
1633 // and any newline or tab are filtered out as if they're not part of the URL.
1634 // https://url.spec.whatwg.org/#url-parsing
1635 // Tab or newline are defined as \r\n\t:
1636 // https://infra.spec.whatwg.org/#ascii-tab-or-newline
1637 // A C0 control is a code point in the range \u0000 NULL to \u001F
1638 // INFORMATION SEPARATOR ONE, inclusive:
1639 // https://infra.spec.whatwg.org/#c0-control-or-space
1640
1641 /* eslint-disable max-len */
1642
1643 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;
1644 var didWarn = false;
1645
1646 function sanitizeURL(url) {
1647 {
1648 if (!didWarn && isJavaScriptProtocol.test(url)) {
1649 didWarn = true;
1650
1651 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));
1652 }
1653 }
1654 }
1655
1656 var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
1657
1658 function isArray(a) {
1659 return isArrayImpl(a);
1660 }
1661
1662 var startInlineScript = stringToPrecomputedChunk('<script>');
1663 var endInlineScript = stringToPrecomputedChunk('</script>');
1664 var startScriptSrc = stringToPrecomputedChunk('<script src="');
1665 var startModuleSrc = stringToPrecomputedChunk('<script type="module" src="');
1666 var endAsyncScript = stringToPrecomputedChunk('" async=""></script>'); // Allows us to keep track of what we've already written so we can refer back to it.
1667
1668 function createResponseState(identifierPrefix, nonce, bootstrapScriptContent, bootstrapScripts, bootstrapModules) {
1669 var idPrefix = identifierPrefix === undefined ? '' : identifierPrefix;
1670 var inlineScriptWithNonce = nonce === undefined ? startInlineScript : stringToPrecomputedChunk('<script nonce="' + escapeTextForBrowser(nonce) + '">');
1671 var bootstrapChunks = [];
1672
1673 if (bootstrapScriptContent !== undefined) {
1674 bootstrapChunks.push(inlineScriptWithNonce, stringToChunk(escapeTextForBrowser(bootstrapScriptContent)), endInlineScript);
1675 }
1676
1677 if (bootstrapScripts !== undefined) {
1678 for (var i = 0; i < bootstrapScripts.length; i++) {
1679 bootstrapChunks.push(startScriptSrc, stringToChunk(escapeTextForBrowser(bootstrapScripts[i])), endAsyncScript);
1680 }
1681 }
1682
1683 if (bootstrapModules !== undefined) {
1684 for (var _i = 0; _i < bootstrapModules.length; _i++) {
1685 bootstrapChunks.push(startModuleSrc, stringToChunk(escapeTextForBrowser(bootstrapModules[_i])), endAsyncScript);
1686 }
1687 }
1688
1689 return {
1690 bootstrapChunks: bootstrapChunks,
1691 startInlineScript: inlineScriptWithNonce,
1692 placeholderPrefix: stringToPrecomputedChunk(idPrefix + 'P:'),
1693 segmentPrefix: stringToPrecomputedChunk(idPrefix + 'S:'),
1694 boundaryPrefix: idPrefix + 'B:',
1695 idPrefix: idPrefix,
1696 nextSuspenseID: 0,
1697 sentCompleteSegmentFunction: false,
1698 sentCompleteBoundaryFunction: false,
1699 sentClientRenderFunction: false
1700 };
1701 } // Constants for the insertion mode we're currently writing in. We don't encode all HTML5 insertion
1702 // modes. We only include the variants as they matter for the sake of our purposes.
1703 // We don't actually provide the namespace therefore we use constants instead of the string.
1704
1705 var ROOT_HTML_MODE = 0; // Used for the root most element tag.
1706
1707 var HTML_MODE = 1;
1708 var SVG_MODE = 2;
1709 var MATHML_MODE = 3;
1710 var HTML_TABLE_MODE = 4;
1711 var HTML_TABLE_BODY_MODE = 5;
1712 var HTML_TABLE_ROW_MODE = 6;
1713 var HTML_COLGROUP_MODE = 7; // We have a greater than HTML_TABLE_MODE check elsewhere. If you add more cases here, make sure it
1714 // still makes sense
1715
1716 function createFormatContext(insertionMode, selectedValue) {
1717 return {
1718 insertionMode: insertionMode,
1719 selectedValue: selectedValue
1720 };
1721 }
1722 function getChildFormatContext(parentContext, type, props) {
1723 switch (type) {
1724 case 'select':
1725 return createFormatContext(HTML_MODE, props.value != null ? props.value : props.defaultValue);
1726
1727 case 'svg':
1728 return createFormatContext(SVG_MODE, null);
1729
1730 case 'math':
1731 return createFormatContext(MATHML_MODE, null);
1732
1733 case 'foreignObject':
1734 return createFormatContext(HTML_MODE, null);
1735 // Table parents are special in that their children can only be created at all if they're
1736 // wrapped in a table parent. So we need to encode that we're entering this mode.
1737
1738 case 'table':
1739 return createFormatContext(HTML_TABLE_MODE, null);
1740
1741 case 'thead':
1742 case 'tbody':
1743 case 'tfoot':
1744 return createFormatContext(HTML_TABLE_BODY_MODE, null);
1745
1746 case 'colgroup':
1747 return createFormatContext(HTML_COLGROUP_MODE, null);
1748
1749 case 'tr':
1750 return createFormatContext(HTML_TABLE_ROW_MODE, null);
1751 }
1752
1753 if (parentContext.insertionMode >= HTML_TABLE_MODE) {
1754 // Whatever tag this was, it wasn't a table parent or other special parent, so we must have
1755 // entered plain HTML again.
1756 return createFormatContext(HTML_MODE, null);
1757 }
1758
1759 if (parentContext.insertionMode === ROOT_HTML_MODE) {
1760 // We've emitted the root and is now in plain HTML mode.
1761 return createFormatContext(HTML_MODE, null);
1762 }
1763
1764 return parentContext;
1765 }
1766 var UNINITIALIZED_SUSPENSE_BOUNDARY_ID = null;
1767 function assignSuspenseBoundaryID(responseState) {
1768 var generatedID = responseState.nextSuspenseID++;
1769 return stringToPrecomputedChunk(responseState.boundaryPrefix + generatedID.toString(16));
1770 }
1771 function makeId(responseState, treeId, localId) {
1772 var idPrefix = responseState.idPrefix;
1773 var id = ':' + idPrefix + 'R' + treeId; // Unless this is the first id at this level, append a number at the end
1774 // that represents the position of this useId hook among all the useId
1775 // hooks for this fiber.
1776
1777 if (localId > 0) {
1778 id += 'H' + localId.toString(32);
1779 }
1780
1781 return id + ':';
1782 }
1783
1784 function encodeHTMLTextNode(text) {
1785 return escapeTextForBrowser(text);
1786 }
1787
1788 var textSeparator = stringToPrecomputedChunk('<!-- -->');
1789 function pushTextInstance(target, text, responseState) {
1790 if (text === '') {
1791 // Empty text doesn't have a DOM node representation and the hydration is aware of this.
1792 return;
1793 } // TODO: Avoid adding a text separator in common cases.
1794
1795
1796 target.push(stringToChunk(encodeHTMLTextNode(text)), textSeparator);
1797 }
1798 var styleNameCache = new Map();
1799
1800 function processStyleName(styleName) {
1801 var chunk = styleNameCache.get(styleName);
1802
1803 if (chunk !== undefined) {
1804 return chunk;
1805 }
1806
1807 var result = stringToPrecomputedChunk(escapeTextForBrowser(hyphenateStyleName(styleName)));
1808 styleNameCache.set(styleName, result);
1809 return result;
1810 }
1811
1812 var styleAttributeStart = stringToPrecomputedChunk(' style="');
1813 var styleAssign = stringToPrecomputedChunk(':');
1814 var styleSeparator = stringToPrecomputedChunk(';');
1815
1816 function pushStyle(target, responseState, style) {
1817 if (typeof style !== 'object') {
1818 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.');
1819 }
1820
1821 var isFirst = true;
1822
1823 for (var styleName in style) {
1824 if (!hasOwnProperty.call(style, styleName)) {
1825 continue;
1826 } // If you provide unsafe user data here they can inject arbitrary CSS
1827 // which may be problematic (I couldn't repro this):
1828 // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
1829 // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
1830 // This is not an XSS hole but instead a potential CSS injection issue
1831 // which has lead to a greater discussion about how we're going to
1832 // trust URLs moving forward. See #2115901
1833
1834
1835 var styleValue = style[styleName];
1836
1837 if (styleValue == null || typeof styleValue === 'boolean' || styleValue === '') {
1838 // TODO: We used to set empty string as a style with an empty value. Does that ever make sense?
1839 continue;
1840 }
1841
1842 var nameChunk = void 0;
1843 var valueChunk = void 0;
1844 var isCustomProperty = styleName.indexOf('--') === 0;
1845
1846 if (isCustomProperty) {
1847 nameChunk = stringToChunk(escapeTextForBrowser(styleName));
1848
1849 {
1850 checkCSSPropertyStringCoercion(styleValue, styleName);
1851 }
1852
1853 valueChunk = stringToChunk(escapeTextForBrowser(('' + styleValue).trim()));
1854 } else {
1855 {
1856 warnValidStyle$1(styleName, styleValue);
1857 }
1858
1859 nameChunk = processStyleName(styleName);
1860
1861 if (typeof styleValue === 'number') {
1862 if (styleValue !== 0 && !hasOwnProperty.call(isUnitlessNumber, styleName)) {
1863 valueChunk = stringToChunk(styleValue + 'px'); // Presumes implicit 'px' suffix for unitless numbers
1864 } else {
1865 valueChunk = stringToChunk('' + styleValue);
1866 }
1867 } else {
1868 {
1869 checkCSSPropertyStringCoercion(styleValue, styleName);
1870 }
1871
1872 valueChunk = stringToChunk(escapeTextForBrowser(('' + styleValue).trim()));
1873 }
1874 }
1875
1876 if (isFirst) {
1877 isFirst = false; // If it's first, we don't need any separators prefixed.
1878
1879 target.push(styleAttributeStart, nameChunk, styleAssign, valueChunk);
1880 } else {
1881 target.push(styleSeparator, nameChunk, styleAssign, valueChunk);
1882 }
1883 }
1884
1885 if (!isFirst) {
1886 target.push(attributeEnd);
1887 }
1888 }
1889
1890 var attributeSeparator = stringToPrecomputedChunk(' ');
1891 var attributeAssign = stringToPrecomputedChunk('="');
1892 var attributeEnd = stringToPrecomputedChunk('"');
1893 var attributeEmptyString = stringToPrecomputedChunk('=""');
1894
1895 function pushAttribute(target, responseState, name, value) {
1896 switch (name) {
1897 case 'style':
1898 {
1899 pushStyle(target, responseState, value);
1900 return;
1901 }
1902
1903 case 'defaultValue':
1904 case 'defaultChecked': // These shouldn't be set as attributes on generic HTML elements.
1905
1906 case 'innerHTML': // Must use dangerouslySetInnerHTML instead.
1907
1908 case 'suppressContentEditableWarning':
1909 case 'suppressHydrationWarning':
1910 // Ignored. These are built-in to React on the client.
1911 return;
1912 }
1913
1914 if ( // shouldIgnoreAttribute
1915 // We have already filtered out null/undefined and reserved words.
1916 name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
1917 return;
1918 }
1919
1920 var propertyInfo = getPropertyInfo(name);
1921
1922 if (propertyInfo !== null) {
1923 // shouldRemoveAttribute
1924 switch (typeof value) {
1925 case 'function': // $FlowIssue symbol is perfectly valid here
1926
1927 case 'symbol':
1928 // eslint-disable-line
1929 return;
1930
1931 case 'boolean':
1932 {
1933 if (!propertyInfo.acceptsBooleans) {
1934 return;
1935 }
1936 }
1937 }
1938
1939 var attributeName = propertyInfo.attributeName;
1940 var attributeNameChunk = stringToChunk(attributeName); // TODO: If it's known we can cache the chunk.
1941
1942 switch (propertyInfo.type) {
1943 case BOOLEAN:
1944 if (value) {
1945 target.push(attributeSeparator, attributeNameChunk, attributeEmptyString);
1946 }
1947
1948 return;
1949
1950 case OVERLOADED_BOOLEAN:
1951 if (value === true) {
1952 target.push(attributeSeparator, attributeNameChunk, attributeEmptyString);
1953 } else if (value === false) ; else {
1954 target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
1955 }
1956
1957 return;
1958
1959 case NUMERIC:
1960 if (!isNaN(value)) {
1961 target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
1962 }
1963
1964 break;
1965
1966 case POSITIVE_NUMERIC:
1967 if (!isNaN(value) && value >= 1) {
1968 target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
1969 }
1970
1971 break;
1972
1973 default:
1974 if (propertyInfo.sanitizeURL) {
1975 {
1976 checkAttributeStringCoercion(value, attributeName);
1977 }
1978
1979 value = '' + value;
1980 sanitizeURL(value);
1981 }
1982
1983 target.push(attributeSeparator, attributeNameChunk, attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
1984 }
1985 } else if (isAttributeNameSafe(name)) {
1986 // shouldRemoveAttribute
1987 switch (typeof value) {
1988 case 'function': // $FlowIssue symbol is perfectly valid here
1989
1990 case 'symbol':
1991 // eslint-disable-line
1992 return;
1993
1994 case 'boolean':
1995 {
1996 var prefix = name.toLowerCase().slice(0, 5);
1997
1998 if (prefix !== 'data-' && prefix !== 'aria-') {
1999 return;
2000 }
2001 }
2002 }
2003
2004 target.push(attributeSeparator, stringToChunk(name), attributeAssign, stringToChunk(escapeTextForBrowser(value)), attributeEnd);
2005 }
2006 }
2007
2008 var endOfStartTag = stringToPrecomputedChunk('>');
2009 var endOfStartTagSelfClosing = stringToPrecomputedChunk('/>');
2010
2011 function pushInnerHTML(target, innerHTML, children) {
2012 if (innerHTML != null) {
2013 if (children != null) {
2014 throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
2015 }
2016
2017 if (typeof innerHTML !== 'object' || !('__html' in innerHTML)) {
2018 throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.');
2019 }
2020
2021 var html = innerHTML.__html;
2022
2023 if (html !== null && html !== undefined) {
2024 {
2025 checkHtmlStringCoercion(html);
2026 }
2027
2028 target.push(stringToChunk('' + html));
2029 }
2030 }
2031 } // TODO: Move these to ResponseState so that we warn for every request.
2032 // It would help debugging in stateful servers (e.g. service worker).
2033
2034
2035 var didWarnDefaultInputValue = false;
2036 var didWarnDefaultChecked = false;
2037 var didWarnDefaultSelectValue = false;
2038 var didWarnDefaultTextareaValue = false;
2039 var didWarnInvalidOptionChildren = false;
2040 var didWarnInvalidOptionInnerHTML = false;
2041 var didWarnSelectedSetOnOption = false;
2042
2043 function checkSelectProp(props, propName) {
2044 {
2045 var value = props[propName];
2046
2047 if (value != null) {
2048 var array = isArray(value);
2049
2050 if (props.multiple && !array) {
2051 error('The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.', propName);
2052 } else if (!props.multiple && array) {
2053 error('The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.', propName);
2054 }
2055 }
2056 }
2057 }
2058
2059 function pushStartSelect(target, props, responseState) {
2060 {
2061 checkControlledValueProps('select', props);
2062 checkSelectProp(props, 'value');
2063 checkSelectProp(props, 'defaultValue');
2064
2065 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultSelectValue) {
2066 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');
2067
2068 didWarnDefaultSelectValue = true;
2069 }
2070 }
2071
2072 target.push(startChunkForTag('select'));
2073 var children = null;
2074 var innerHTML = null;
2075
2076 for (var propKey in props) {
2077 if (hasOwnProperty.call(props, propKey)) {
2078 var propValue = props[propKey];
2079
2080 if (propValue == null) {
2081 continue;
2082 }
2083
2084 switch (propKey) {
2085 case 'children':
2086 children = propValue;
2087 break;
2088
2089 case 'dangerouslySetInnerHTML':
2090 // TODO: This doesn't really make sense for select since it can't use the controlled
2091 // value in the innerHTML.
2092 innerHTML = propValue;
2093 break;
2094
2095 case 'defaultValue':
2096 case 'value':
2097 // These are set on the Context instead and applied to the nested options.
2098 break;
2099
2100 default:
2101 pushAttribute(target, responseState, propKey, propValue);
2102 break;
2103 }
2104 }
2105 }
2106
2107 target.push(endOfStartTag);
2108 pushInnerHTML(target, innerHTML, children);
2109 return children;
2110 }
2111
2112 function flattenOptionChildren(children) {
2113 var content = ''; // Flatten children and warn if they aren't strings or numbers;
2114 // invalid types are ignored.
2115
2116 React.Children.forEach(children, function (child) {
2117 if (child == null) {
2118 return;
2119 }
2120
2121 content += child;
2122
2123 {
2124 if (!didWarnInvalidOptionChildren && typeof child !== 'string' && typeof child !== 'number') {
2125 didWarnInvalidOptionChildren = true;
2126
2127 error('Cannot infer the option value of complex children. ' + 'Pass a `value` prop or use a plain string as children to <option>.');
2128 }
2129 }
2130 });
2131 return content;
2132 }
2133
2134 var selectedMarkerAttribute = stringToPrecomputedChunk(' selected=""');
2135
2136 function pushStartOption(target, props, responseState, formatContext) {
2137 var selectedValue = formatContext.selectedValue;
2138 target.push(startChunkForTag('option'));
2139 var children = null;
2140 var value = null;
2141 var selected = null;
2142 var innerHTML = null;
2143
2144 for (var propKey in props) {
2145 if (hasOwnProperty.call(props, propKey)) {
2146 var propValue = props[propKey];
2147
2148 if (propValue == null) {
2149 continue;
2150 }
2151
2152 switch (propKey) {
2153 case 'children':
2154 children = propValue;
2155 break;
2156
2157 case 'selected':
2158 // ignore
2159 selected = propValue;
2160
2161 {
2162 // TODO: Remove support for `selected` in <option>.
2163 if (!didWarnSelectedSetOnOption) {
2164 error('Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');
2165
2166 didWarnSelectedSetOnOption = true;
2167 }
2168 }
2169
2170 break;
2171
2172 case 'dangerouslySetInnerHTML':
2173 innerHTML = propValue;
2174 break;
2175 // eslint-disable-next-line-no-fallthrough
2176
2177 case 'value':
2178 value = propValue;
2179 // We intentionally fallthrough to also set the attribute on the node.
2180 // eslint-disable-next-line-no-fallthrough
2181
2182 default:
2183 pushAttribute(target, responseState, propKey, propValue);
2184 break;
2185 }
2186 }
2187 }
2188
2189 if (selectedValue != null) {
2190 var stringValue;
2191
2192 if (value !== null) {
2193 {
2194 checkAttributeStringCoercion(value, 'value');
2195 }
2196
2197 stringValue = '' + value;
2198 } else {
2199 {
2200 if (innerHTML !== null) {
2201 if (!didWarnInvalidOptionInnerHTML) {
2202 didWarnInvalidOptionInnerHTML = true;
2203
2204 error('Pass a `value` prop if you set dangerouslyInnerHTML so React knows ' + 'which value should be selected.');
2205 }
2206 }
2207 }
2208
2209 stringValue = flattenOptionChildren(children);
2210 }
2211
2212 if (isArray(selectedValue)) {
2213 // multiple
2214 for (var i = 0; i < selectedValue.length; i++) {
2215 {
2216 checkAttributeStringCoercion(selectedValue[i], 'value');
2217 }
2218
2219 var v = '' + selectedValue[i];
2220
2221 if (v === stringValue) {
2222 target.push(selectedMarkerAttribute);
2223 break;
2224 }
2225 }
2226 } else {
2227 {
2228 checkAttributeStringCoercion(selectedValue, 'select.value');
2229 }
2230
2231 if ('' + selectedValue === stringValue) {
2232 target.push(selectedMarkerAttribute);
2233 }
2234 }
2235 } else if (selected) {
2236 target.push(selectedMarkerAttribute);
2237 }
2238
2239 target.push(endOfStartTag);
2240 pushInnerHTML(target, innerHTML, children);
2241 return children;
2242 }
2243
2244 function pushInput(target, props, responseState) {
2245 {
2246 checkControlledValueProps('input', props);
2247
2248 if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnDefaultChecked) {
2249 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', 'A component', props.type);
2250
2251 didWarnDefaultChecked = true;
2252 }
2253
2254 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultInputValue) {
2255 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', 'A component', props.type);
2256
2257 didWarnDefaultInputValue = true;
2258 }
2259 }
2260
2261 target.push(startChunkForTag('input'));
2262 var value = null;
2263 var defaultValue = null;
2264 var checked = null;
2265 var defaultChecked = null;
2266
2267 for (var propKey in props) {
2268 if (hasOwnProperty.call(props, propKey)) {
2269 var propValue = props[propKey];
2270
2271 if (propValue == null) {
2272 continue;
2273 }
2274
2275 switch (propKey) {
2276 case 'children':
2277 case 'dangerouslySetInnerHTML':
2278 throw new Error('input' + " is a self-closing tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
2279 // eslint-disable-next-line-no-fallthrough
2280
2281 case 'defaultChecked':
2282 defaultChecked = propValue;
2283 break;
2284
2285 case 'defaultValue':
2286 defaultValue = propValue;
2287 break;
2288
2289 case 'checked':
2290 checked = propValue;
2291 break;
2292
2293 case 'value':
2294 value = propValue;
2295 break;
2296
2297 default:
2298 pushAttribute(target, responseState, propKey, propValue);
2299 break;
2300 }
2301 }
2302 }
2303
2304 if (checked !== null) {
2305 pushAttribute(target, responseState, 'checked', checked);
2306 } else if (defaultChecked !== null) {
2307 pushAttribute(target, responseState, 'checked', defaultChecked);
2308 }
2309
2310 if (value !== null) {
2311 pushAttribute(target, responseState, 'value', value);
2312 } else if (defaultValue !== null) {
2313 pushAttribute(target, responseState, 'value', defaultValue);
2314 }
2315
2316 target.push(endOfStartTagSelfClosing);
2317 return null;
2318 }
2319
2320 function pushStartTextArea(target, props, responseState) {
2321 {
2322 checkControlledValueProps('textarea', props);
2323
2324 if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultTextareaValue) {
2325 error('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');
2326
2327 didWarnDefaultTextareaValue = true;
2328 }
2329 }
2330
2331 target.push(startChunkForTag('textarea'));
2332 var value = null;
2333 var defaultValue = null;
2334 var children = null;
2335
2336 for (var propKey in props) {
2337 if (hasOwnProperty.call(props, propKey)) {
2338 var propValue = props[propKey];
2339
2340 if (propValue == null) {
2341 continue;
2342 }
2343
2344 switch (propKey) {
2345 case 'children':
2346 children = propValue;
2347 break;
2348
2349 case 'value':
2350 value = propValue;
2351 break;
2352
2353 case 'defaultValue':
2354 defaultValue = propValue;
2355 break;
2356
2357 case 'dangerouslySetInnerHTML':
2358 throw new Error('`dangerouslySetInnerHTML` does not make sense on <textarea>.');
2359 // eslint-disable-next-line-no-fallthrough
2360
2361 default:
2362 pushAttribute(target, responseState, propKey, propValue);
2363 break;
2364 }
2365 }
2366 }
2367
2368 if (value === null && defaultValue !== null) {
2369 value = defaultValue;
2370 }
2371
2372 target.push(endOfStartTag); // TODO (yungsters): Remove support for children content in <textarea>.
2373
2374 if (children != null) {
2375 {
2376 error('Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
2377 }
2378
2379 if (value != null) {
2380 throw new Error('If you supply `defaultValue` on a <textarea>, do not pass children.');
2381 }
2382
2383 if (isArray(children)) {
2384 if (children.length > 1) {
2385 throw new Error('<textarea> can only have at most one child.');
2386 } // TODO: remove the coercion and the DEV check below because it will
2387 // always be overwritten by the coercion several lines below it. #22309
2388
2389
2390 {
2391 checkHtmlStringCoercion(children[0]);
2392 }
2393
2394 value = '' + children[0];
2395 }
2396
2397 {
2398 checkHtmlStringCoercion(children);
2399 }
2400
2401 value = '' + children;
2402 }
2403
2404 if (typeof value === 'string' && value[0] === '\n') {
2405 // text/html ignores the first character in these tags if it's a newline
2406 // Prefer to break application/xml over text/html (for now) by adding
2407 // a newline specifically to get eaten by the parser. (Alternately for
2408 // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
2409 // \r is normalized out by HTMLTextAreaElement#value.)
2410 // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
2411 // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
2412 // See: <http://www.w3.org/TR/html5/syntax.html#newlines>
2413 // See: Parsing of "textarea" "listing" and "pre" elements
2414 // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
2415 target.push(leadingNewline);
2416 } // ToString and push directly instead of recurse over children.
2417 // We don't really support complex children in the value anyway.
2418 // This also currently avoids a trailing comment node which breaks textarea.
2419
2420
2421 if (value !== null) {
2422 {
2423 checkAttributeStringCoercion(value, 'value');
2424 }
2425
2426 target.push(stringToChunk(encodeHTMLTextNode('' + value)));
2427 }
2428
2429 return null;
2430 }
2431
2432 function pushSelfClosing(target, props, tag, responseState) {
2433 target.push(startChunkForTag(tag));
2434
2435 for (var propKey in props) {
2436 if (hasOwnProperty.call(props, propKey)) {
2437 var propValue = props[propKey];
2438
2439 if (propValue == null) {
2440 continue;
2441 }
2442
2443 switch (propKey) {
2444 case 'children':
2445 case 'dangerouslySetInnerHTML':
2446 throw new Error(tag + " is a self-closing tag and must neither have `children` nor " + 'use `dangerouslySetInnerHTML`.');
2447 // eslint-disable-next-line-no-fallthrough
2448
2449 default:
2450 pushAttribute(target, responseState, propKey, propValue);
2451 break;
2452 }
2453 }
2454 }
2455
2456 target.push(endOfStartTagSelfClosing);
2457 return null;
2458 }
2459
2460 function pushStartMenuItem(target, props, responseState) {
2461 target.push(startChunkForTag('menuitem'));
2462
2463 for (var propKey in props) {
2464 if (hasOwnProperty.call(props, propKey)) {
2465 var propValue = props[propKey];
2466
2467 if (propValue == null) {
2468 continue;
2469 }
2470
2471 switch (propKey) {
2472 case 'children':
2473 case 'dangerouslySetInnerHTML':
2474 throw new Error('menuitems cannot have `children` nor `dangerouslySetInnerHTML`.');
2475 // eslint-disable-next-line-no-fallthrough
2476
2477 default:
2478 pushAttribute(target, responseState, propKey, propValue);
2479 break;
2480 }
2481 }
2482 }
2483
2484 target.push(endOfStartTag);
2485 return null;
2486 }
2487
2488 function pushStartGenericElement(target, props, tag, responseState) {
2489 target.push(startChunkForTag(tag));
2490 var children = null;
2491 var innerHTML = null;
2492
2493 for (var propKey in props) {
2494 if (hasOwnProperty.call(props, propKey)) {
2495 var propValue = props[propKey];
2496
2497 if (propValue == null) {
2498 continue;
2499 }
2500
2501 switch (propKey) {
2502 case 'children':
2503 children = propValue;
2504 break;
2505
2506 case 'dangerouslySetInnerHTML':
2507 innerHTML = propValue;
2508 break;
2509
2510 default:
2511 pushAttribute(target, responseState, propKey, propValue);
2512 break;
2513 }
2514 }
2515 }
2516
2517 target.push(endOfStartTag);
2518 pushInnerHTML(target, innerHTML, children);
2519
2520 if (typeof children === 'string') {
2521 // Special case children as a string to avoid the unnecessary comment.
2522 // TODO: Remove this special case after the general optimization is in place.
2523 target.push(stringToChunk(encodeHTMLTextNode(children)));
2524 return null;
2525 }
2526
2527 return children;
2528 }
2529
2530 function pushStartCustomElement(target, props, tag, responseState) {
2531 target.push(startChunkForTag(tag));
2532 var children = null;
2533 var innerHTML = null;
2534
2535 for (var propKey in props) {
2536 if (hasOwnProperty.call(props, propKey)) {
2537 var propValue = props[propKey];
2538
2539 if (propValue == null) {
2540 continue;
2541 }
2542
2543 switch (propKey) {
2544 case 'children':
2545 children = propValue;
2546 break;
2547
2548 case 'dangerouslySetInnerHTML':
2549 innerHTML = propValue;
2550 break;
2551
2552 case 'style':
2553 pushStyle(target, responseState, propValue);
2554 break;
2555
2556 case 'suppressContentEditableWarning':
2557 case 'suppressHydrationWarning':
2558 // Ignored. These are built-in to React on the client.
2559 break;
2560
2561 default:
2562 if (isAttributeNameSafe(propKey) && typeof propValue !== 'function' && typeof propValue !== 'symbol') {
2563 target.push(attributeSeparator, stringToChunk(propKey), attributeAssign, stringToChunk(escapeTextForBrowser(propValue)), attributeEnd);
2564 }
2565
2566 break;
2567 }
2568 }
2569 }
2570
2571 target.push(endOfStartTag);
2572 pushInnerHTML(target, innerHTML, children);
2573 return children;
2574 }
2575
2576 var leadingNewline = stringToPrecomputedChunk('\n');
2577
2578 function pushStartPreformattedElement(target, props, tag, responseState) {
2579 target.push(startChunkForTag(tag));
2580 var children = null;
2581 var innerHTML = null;
2582
2583 for (var propKey in props) {
2584 if (hasOwnProperty.call(props, propKey)) {
2585 var propValue = props[propKey];
2586
2587 if (propValue == null) {
2588 continue;
2589 }
2590
2591 switch (propKey) {
2592 case 'children':
2593 children = propValue;
2594 break;
2595
2596 case 'dangerouslySetInnerHTML':
2597 innerHTML = propValue;
2598 break;
2599
2600 default:
2601 pushAttribute(target, responseState, propKey, propValue);
2602 break;
2603 }
2604 }
2605 }
2606
2607 target.push(endOfStartTag); // text/html ignores the first character in these tags if it's a newline
2608 // Prefer to break application/xml over text/html (for now) by adding
2609 // a newline specifically to get eaten by the parser. (Alternately for
2610 // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
2611 // \r is normalized out by HTMLTextAreaElement#value.)
2612 // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
2613 // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
2614 // See: <http://www.w3.org/TR/html5/syntax.html#newlines>
2615 // See: Parsing of "textarea" "listing" and "pre" elements
2616 // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
2617 // TODO: This doesn't deal with the case where the child is an array
2618 // or component that returns a string.
2619
2620 if (innerHTML != null) {
2621 if (children != null) {
2622 throw new Error('Can only set one of `children` or `props.dangerouslySetInnerHTML`.');
2623 }
2624
2625 if (typeof innerHTML !== 'object' || !('__html' in innerHTML)) {
2626 throw new Error('`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://reactjs.org/link/dangerously-set-inner-html ' + 'for more information.');
2627 }
2628
2629 var html = innerHTML.__html;
2630
2631 if (html !== null && html !== undefined) {
2632 if (typeof html === 'string' && html.length > 0 && html[0] === '\n') {
2633 target.push(leadingNewline, stringToChunk(html));
2634 } else {
2635 {
2636 checkHtmlStringCoercion(html);
2637 }
2638
2639 target.push(stringToChunk('' + html));
2640 }
2641 }
2642 }
2643
2644 if (typeof children === 'string' && children[0] === '\n') {
2645 target.push(leadingNewline);
2646 }
2647
2648 return children;
2649 } // We accept any tag to be rendered but since this gets injected into arbitrary
2650 // HTML, we want to make sure that it's a safe tag.
2651 // http://www.w3.org/TR/REC-xml/#NT-Name
2652
2653
2654 var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset
2655
2656 var validatedTagCache = new Map();
2657
2658 function startChunkForTag(tag) {
2659 var tagStartChunk = validatedTagCache.get(tag);
2660
2661 if (tagStartChunk === undefined) {
2662 if (!VALID_TAG_REGEX.test(tag)) {
2663 throw new Error("Invalid tag: " + tag);
2664 }
2665
2666 tagStartChunk = stringToPrecomputedChunk('<' + tag);
2667 validatedTagCache.set(tag, tagStartChunk);
2668 }
2669
2670 return tagStartChunk;
2671 }
2672
2673 var DOCTYPE = stringToPrecomputedChunk('<!DOCTYPE html>');
2674 function pushStartInstance(target, type, props, responseState, formatContext) {
2675 {
2676 validateProperties(type, props);
2677 validateProperties$1(type, props);
2678 validateProperties$2(type, props, null);
2679
2680 if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) {
2681 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.');
2682 }
2683
2684 if (formatContext.insertionMode !== SVG_MODE && formatContext.insertionMode !== MATHML_MODE) {
2685 if (type.indexOf('-') === -1 && typeof props.is !== 'string' && type.toLowerCase() !== type) {
2686 error('<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type);
2687 }
2688 }
2689 }
2690
2691 switch (type) {
2692 // Special tags
2693 case 'select':
2694 return pushStartSelect(target, props, responseState);
2695
2696 case 'option':
2697 return pushStartOption(target, props, responseState, formatContext);
2698
2699 case 'textarea':
2700 return pushStartTextArea(target, props, responseState);
2701
2702 case 'input':
2703 return pushInput(target, props, responseState);
2704
2705 case 'menuitem':
2706 return pushStartMenuItem(target, props, responseState);
2707 // Newline eating tags
2708
2709 case 'listing':
2710 case 'pre':
2711 {
2712 return pushStartPreformattedElement(target, props, type, responseState);
2713 }
2714 // Omitted close tags
2715
2716 case 'area':
2717 case 'base':
2718 case 'br':
2719 case 'col':
2720 case 'embed':
2721 case 'hr':
2722 case 'img':
2723 case 'keygen':
2724 case 'link':
2725 case 'meta':
2726 case 'param':
2727 case 'source':
2728 case 'track':
2729 case 'wbr':
2730 {
2731 return pushSelfClosing(target, props, type, responseState);
2732 }
2733 // These are reserved SVG and MathML elements, that are never custom elements.
2734 // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
2735
2736 case 'annotation-xml':
2737 case 'color-profile':
2738 case 'font-face':
2739 case 'font-face-src':
2740 case 'font-face-uri':
2741 case 'font-face-format':
2742 case 'font-face-name':
2743 case 'missing-glyph':
2744 {
2745 return pushStartGenericElement(target, props, type, responseState);
2746 }
2747
2748 case 'html':
2749 {
2750 if (formatContext.insertionMode === ROOT_HTML_MODE) {
2751 // If we're rendering the html tag and we're at the root (i.e. not in foreignObject)
2752 // then we also emit the DOCTYPE as part of the root content as a convenience for
2753 // rendering the whole document.
2754 target.push(DOCTYPE);
2755 }
2756
2757 return pushStartGenericElement(target, props, type, responseState);
2758 }
2759
2760 default:
2761 {
2762 if (type.indexOf('-') === -1 && typeof props.is !== 'string') {
2763 // Generic element
2764 return pushStartGenericElement(target, props, type, responseState);
2765 } else {
2766 // Custom element
2767 return pushStartCustomElement(target, props, type, responseState);
2768 }
2769 }
2770 }
2771 }
2772 var endTag1 = stringToPrecomputedChunk('</');
2773 var endTag2 = stringToPrecomputedChunk('>');
2774 function pushEndInstance(target, type, props) {
2775 switch (type) {
2776 // Omitted close tags
2777 // TODO: Instead of repeating this switch we could try to pass a flag from above.
2778 // That would require returning a tuple. Which might be ok if it gets inlined.
2779 case 'area':
2780 case 'base':
2781 case 'br':
2782 case 'col':
2783 case 'embed':
2784 case 'hr':
2785 case 'img':
2786 case 'input':
2787 case 'keygen':
2788 case 'link':
2789 case 'meta':
2790 case 'param':
2791 case 'source':
2792 case 'track':
2793 case 'wbr':
2794 {
2795 // No close tag needed.
2796 break;
2797 }
2798
2799 default:
2800 {
2801 target.push(endTag1, stringToChunk(type), endTag2);
2802 }
2803 }
2804 }
2805 function writeCompletedRoot(destination, responseState) {
2806 var bootstrapChunks = responseState.bootstrapChunks;
2807 var i = 0;
2808
2809 for (; i < bootstrapChunks.length - 1; i++) {
2810 writeChunk(destination, bootstrapChunks[i]);
2811 }
2812
2813 if (i < bootstrapChunks.length) {
2814 return writeChunkAndReturn(destination, bootstrapChunks[i]);
2815 }
2816
2817 return true;
2818 } // Structural Nodes
2819 // A placeholder is a node inside a hidden partial tree that can be filled in later, but before
2820 // display. It's never visible to users. We use the template tag because it can be used in every
2821 // type of parent. <script> tags also work in every other tag except <colgroup>.
2822
2823 var placeholder1 = stringToPrecomputedChunk('<template id="');
2824 var placeholder2 = stringToPrecomputedChunk('"></template>');
2825 function writePlaceholder(destination, responseState, id) {
2826 writeChunk(destination, placeholder1);
2827 writeChunk(destination, responseState.placeholderPrefix);
2828 var formattedID = stringToChunk(id.toString(16));
2829 writeChunk(destination, formattedID);
2830 return writeChunkAndReturn(destination, placeholder2);
2831 } // Suspense boundaries are encoded as comments.
2832
2833 var startCompletedSuspenseBoundary = stringToPrecomputedChunk('<!--$-->');
2834 var startPendingSuspenseBoundary1 = stringToPrecomputedChunk('<!--$?--><template id="');
2835 var startPendingSuspenseBoundary2 = stringToPrecomputedChunk('"></template>');
2836 var startClientRenderedSuspenseBoundary = stringToPrecomputedChunk('<!--$!-->');
2837 var endSuspenseBoundary = stringToPrecomputedChunk('<!--/$-->');
2838 function writeStartCompletedSuspenseBoundary(destination, responseState) {
2839 return writeChunkAndReturn(destination, startCompletedSuspenseBoundary);
2840 }
2841 function writeStartPendingSuspenseBoundary(destination, responseState, id) {
2842 writeChunk(destination, startPendingSuspenseBoundary1);
2843
2844 if (id === null) {
2845 throw new Error('An ID must have been assigned before we can complete the boundary.');
2846 }
2847
2848 writeChunk(destination, id);
2849 return writeChunkAndReturn(destination, startPendingSuspenseBoundary2);
2850 }
2851 function writeStartClientRenderedSuspenseBoundary(destination, responseState) {
2852 return writeChunkAndReturn(destination, startClientRenderedSuspenseBoundary);
2853 }
2854 function writeEndCompletedSuspenseBoundary(destination, responseState) {
2855 return writeChunkAndReturn(destination, endSuspenseBoundary);
2856 }
2857 function writeEndPendingSuspenseBoundary(destination, responseState) {
2858 return writeChunkAndReturn(destination, endSuspenseBoundary);
2859 }
2860 function writeEndClientRenderedSuspenseBoundary(destination, responseState) {
2861 return writeChunkAndReturn(destination, endSuspenseBoundary);
2862 }
2863 var startSegmentHTML = stringToPrecomputedChunk('<div hidden id="');
2864 var startSegmentHTML2 = stringToPrecomputedChunk('">');
2865 var endSegmentHTML = stringToPrecomputedChunk('</div>');
2866 var startSegmentSVG = stringToPrecomputedChunk('<svg aria-hidden="true" style="display:none" id="');
2867 var startSegmentSVG2 = stringToPrecomputedChunk('">');
2868 var endSegmentSVG = stringToPrecomputedChunk('</svg>');
2869 var startSegmentMathML = stringToPrecomputedChunk('<math aria-hidden="true" style="display:none" id="');
2870 var startSegmentMathML2 = stringToPrecomputedChunk('">');
2871 var endSegmentMathML = stringToPrecomputedChunk('</math>');
2872 var startSegmentTable = stringToPrecomputedChunk('<table hidden id="');
2873 var startSegmentTable2 = stringToPrecomputedChunk('">');
2874 var endSegmentTable = stringToPrecomputedChunk('</table>');
2875 var startSegmentTableBody = stringToPrecomputedChunk('<table hidden><tbody id="');
2876 var startSegmentTableBody2 = stringToPrecomputedChunk('">');
2877 var endSegmentTableBody = stringToPrecomputedChunk('</tbody></table>');
2878 var startSegmentTableRow = stringToPrecomputedChunk('<table hidden><tr id="');
2879 var startSegmentTableRow2 = stringToPrecomputedChunk('">');
2880 var endSegmentTableRow = stringToPrecomputedChunk('</tr></table>');
2881 var startSegmentColGroup = stringToPrecomputedChunk('<table hidden><colgroup id="');
2882 var startSegmentColGroup2 = stringToPrecomputedChunk('">');
2883 var endSegmentColGroup = stringToPrecomputedChunk('</colgroup></table>');
2884 function writeStartSegment(destination, responseState, formatContext, id) {
2885 switch (formatContext.insertionMode) {
2886 case ROOT_HTML_MODE:
2887 case HTML_MODE:
2888 {
2889 writeChunk(destination, startSegmentHTML);
2890 writeChunk(destination, responseState.segmentPrefix);
2891 writeChunk(destination, stringToChunk(id.toString(16)));
2892 return writeChunkAndReturn(destination, startSegmentHTML2);
2893 }
2894
2895 case SVG_MODE:
2896 {
2897 writeChunk(destination, startSegmentSVG);
2898 writeChunk(destination, responseState.segmentPrefix);
2899 writeChunk(destination, stringToChunk(id.toString(16)));
2900 return writeChunkAndReturn(destination, startSegmentSVG2);
2901 }
2902
2903 case MATHML_MODE:
2904 {
2905 writeChunk(destination, startSegmentMathML);
2906 writeChunk(destination, responseState.segmentPrefix);
2907 writeChunk(destination, stringToChunk(id.toString(16)));
2908 return writeChunkAndReturn(destination, startSegmentMathML2);
2909 }
2910
2911 case HTML_TABLE_MODE:
2912 {
2913 writeChunk(destination, startSegmentTable);
2914 writeChunk(destination, responseState.segmentPrefix);
2915 writeChunk(destination, stringToChunk(id.toString(16)));
2916 return writeChunkAndReturn(destination, startSegmentTable2);
2917 }
2918 // TODO: For the rest of these, there will be extra wrapper nodes that never
2919 // get deleted from the document. We need to delete the table too as part
2920 // of the injected scripts. They are invisible though so it's not too terrible
2921 // and it's kind of an edge case to suspend in a table. Totally supported though.
2922
2923 case HTML_TABLE_BODY_MODE:
2924 {
2925 writeChunk(destination, startSegmentTableBody);
2926 writeChunk(destination, responseState.segmentPrefix);
2927 writeChunk(destination, stringToChunk(id.toString(16)));
2928 return writeChunkAndReturn(destination, startSegmentTableBody2);
2929 }
2930
2931 case HTML_TABLE_ROW_MODE:
2932 {
2933 writeChunk(destination, startSegmentTableRow);
2934 writeChunk(destination, responseState.segmentPrefix);
2935 writeChunk(destination, stringToChunk(id.toString(16)));
2936 return writeChunkAndReturn(destination, startSegmentTableRow2);
2937 }
2938
2939 case HTML_COLGROUP_MODE:
2940 {
2941 writeChunk(destination, startSegmentColGroup);
2942 writeChunk(destination, responseState.segmentPrefix);
2943 writeChunk(destination, stringToChunk(id.toString(16)));
2944 return writeChunkAndReturn(destination, startSegmentColGroup2);
2945 }
2946
2947 default:
2948 {
2949 throw new Error('Unknown insertion mode. This is a bug in React.');
2950 }
2951 }
2952 }
2953 function writeEndSegment(destination, formatContext) {
2954 switch (formatContext.insertionMode) {
2955 case ROOT_HTML_MODE:
2956 case HTML_MODE:
2957 {
2958 return writeChunkAndReturn(destination, endSegmentHTML);
2959 }
2960
2961 case SVG_MODE:
2962 {
2963 return writeChunkAndReturn(destination, endSegmentSVG);
2964 }
2965
2966 case MATHML_MODE:
2967 {
2968 return writeChunkAndReturn(destination, endSegmentMathML);
2969 }
2970
2971 case HTML_TABLE_MODE:
2972 {
2973 return writeChunkAndReturn(destination, endSegmentTable);
2974 }
2975
2976 case HTML_TABLE_BODY_MODE:
2977 {
2978 return writeChunkAndReturn(destination, endSegmentTableBody);
2979 }
2980
2981 case HTML_TABLE_ROW_MODE:
2982 {
2983 return writeChunkAndReturn(destination, endSegmentTableRow);
2984 }
2985
2986 case HTML_COLGROUP_MODE:
2987 {
2988 return writeChunkAndReturn(destination, endSegmentColGroup);
2989 }
2990
2991 default:
2992 {
2993 throw new Error('Unknown insertion mode. This is a bug in React.');
2994 }
2995 }
2996 } // Instruction Set
2997 // The following code is the source scripts that we then minify and inline below,
2998 // with renamed function names that we hope don't collide:
2999 // const COMMENT_NODE = 8;
3000 // const SUSPENSE_START_DATA = '$';
3001 // const SUSPENSE_END_DATA = '/$';
3002 // const SUSPENSE_PENDING_START_DATA = '$?';
3003 // const SUSPENSE_FALLBACK_START_DATA = '$!';
3004 //
3005 // function clientRenderBoundary(suspenseBoundaryID) {
3006 // // Find the fallback's first element.
3007 // const suspenseIdNode = document.getElementById(suspenseBoundaryID);
3008 // if (!suspenseIdNode) {
3009 // // The user must have already navigated away from this tree.
3010 // // E.g. because the parent was hydrated.
3011 // return;
3012 // }
3013 // // Find the boundary around the fallback. This is always the previous node.
3014 // const suspenseNode = suspenseIdNode.previousSibling;
3015 // // Tag it to be client rendered.
3016 // suspenseNode.data = SUSPENSE_FALLBACK_START_DATA;
3017 // // Tell React to retry it if the parent already hydrated.
3018 // if (suspenseNode._reactRetry) {
3019 // suspenseNode._reactRetry();
3020 // }
3021 // }
3022 //
3023 // function completeBoundary(suspenseBoundaryID, contentID) {
3024 // // Find the fallback's first element.
3025 // const suspenseIdNode = document.getElementById(suspenseBoundaryID);
3026 // const contentNode = document.getElementById(contentID);
3027 // // We'll detach the content node so that regardless of what happens next we don't leave in the tree.
3028 // // This might also help by not causing recalcing each time we move a child from here to the target.
3029 // contentNode.parentNode.removeChild(contentNode);
3030 // if (!suspenseIdNode) {
3031 // // The user must have already navigated away from this tree.
3032 // // E.g. because the parent was hydrated. That's fine there's nothing to do
3033 // // but we have to make sure that we already deleted the container node.
3034 // return;
3035 // }
3036 // // Find the boundary around the fallback. This is always the previous node.
3037 // const suspenseNode = suspenseIdNode.previousSibling;
3038 //
3039 // // Clear all the existing children. This is complicated because
3040 // // there can be embedded Suspense boundaries in the fallback.
3041 // // This is similar to clearSuspenseBoundary in ReactDOMHostConfig.
3042 // // TODO: We could avoid this if we never emitted suspense boundaries in fallback trees.
3043 // // They never hydrate anyway. However, currently we support incrementally loading the fallback.
3044 // const parentInstance = suspenseNode.parentNode;
3045 // let node = suspenseNode.nextSibling;
3046 // let depth = 0;
3047 // do {
3048 // if (node && node.nodeType === COMMENT_NODE) {
3049 // const data = node.data;
3050 // if (data === SUSPENSE_END_DATA) {
3051 // if (depth === 0) {
3052 // break;
3053 // } else {
3054 // depth--;
3055 // }
3056 // } else if (
3057 // data === SUSPENSE_START_DATA ||
3058 // data === SUSPENSE_PENDING_START_DATA ||
3059 // data === SUSPENSE_FALLBACK_START_DATA
3060 // ) {
3061 // depth++;
3062 // }
3063 // }
3064 //
3065 // const nextNode = node.nextSibling;
3066 // parentInstance.removeChild(node);
3067 // node = nextNode;
3068 // } while (node);
3069 //
3070 // const endOfBoundary = node;
3071 //
3072 // // Insert all the children from the contentNode between the start and end of suspense boundary.
3073 // while (contentNode.firstChild) {
3074 // parentInstance.insertBefore(contentNode.firstChild, endOfBoundary);
3075 // }
3076 // suspenseNode.data = SUSPENSE_START_DATA;
3077 // if (suspenseNode._reactRetry) {
3078 // suspenseNode._reactRetry();
3079 // }
3080 // }
3081 //
3082 // function completeSegment(containerID, placeholderID) {
3083 // const segmentContainer = document.getElementById(containerID);
3084 // const placeholderNode = document.getElementById(placeholderID);
3085 // // We always expect both nodes to exist here because, while we might
3086 // // have navigated away from the main tree, we still expect the detached
3087 // // tree to exist.
3088 // segmentContainer.parentNode.removeChild(segmentContainer);
3089 // while (segmentContainer.firstChild) {
3090 // placeholderNode.parentNode.insertBefore(
3091 // segmentContainer.firstChild,
3092 // placeholderNode,
3093 // );
3094 // }
3095 // placeholderNode.parentNode.removeChild(placeholderNode);
3096 // }
3097
3098 var completeSegmentFunction = 'function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)}';
3099 var completeBoundaryFunction = 'function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}}';
3100 var clientRenderFunction = 'function $RX(a){if(a=document.getElementById(a))a=a.previousSibling,a.data="$!",a._reactRetry&&a._reactRetry()}';
3101 var completeSegmentScript1Full = stringToPrecomputedChunk(completeSegmentFunction + ';$RS("');
3102 var completeSegmentScript1Partial = stringToPrecomputedChunk('$RS("');
3103 var completeSegmentScript2 = stringToPrecomputedChunk('","');
3104 var completeSegmentScript3 = stringToPrecomputedChunk('")</script>');
3105 function writeCompletedSegmentInstruction(destination, responseState, contentSegmentID) {
3106 writeChunk(destination, responseState.startInlineScript);
3107
3108 if (!responseState.sentCompleteSegmentFunction) {
3109 // The first time we write this, we'll need to include the full implementation.
3110 responseState.sentCompleteSegmentFunction = true;
3111 writeChunk(destination, completeSegmentScript1Full);
3112 } else {
3113 // Future calls can just reuse the same function.
3114 writeChunk(destination, completeSegmentScript1Partial);
3115 }
3116
3117 writeChunk(destination, responseState.segmentPrefix);
3118 var formattedID = stringToChunk(contentSegmentID.toString(16));
3119 writeChunk(destination, formattedID);
3120 writeChunk(destination, completeSegmentScript2);
3121 writeChunk(destination, responseState.placeholderPrefix);
3122 writeChunk(destination, formattedID);
3123 return writeChunkAndReturn(destination, completeSegmentScript3);
3124 }
3125 var completeBoundaryScript1Full = stringToPrecomputedChunk(completeBoundaryFunction + ';$RC("');
3126 var completeBoundaryScript1Partial = stringToPrecomputedChunk('$RC("');
3127 var completeBoundaryScript2 = stringToPrecomputedChunk('","');
3128 var completeBoundaryScript3 = stringToPrecomputedChunk('")</script>');
3129 function writeCompletedBoundaryInstruction(destination, responseState, boundaryID, contentSegmentID) {
3130 writeChunk(destination, responseState.startInlineScript);
3131
3132 if (!responseState.sentCompleteBoundaryFunction) {
3133 // The first time we write this, we'll need to include the full implementation.
3134 responseState.sentCompleteBoundaryFunction = true;
3135 writeChunk(destination, completeBoundaryScript1Full);
3136 } else {
3137 // Future calls can just reuse the same function.
3138 writeChunk(destination, completeBoundaryScript1Partial);
3139 }
3140
3141 if (boundaryID === null) {
3142 throw new Error('An ID must have been assigned before we can complete the boundary.');
3143 }
3144
3145 var formattedContentID = stringToChunk(contentSegmentID.toString(16));
3146 writeChunk(destination, boundaryID);
3147 writeChunk(destination, completeBoundaryScript2);
3148 writeChunk(destination, responseState.segmentPrefix);
3149 writeChunk(destination, formattedContentID);
3150 return writeChunkAndReturn(destination, completeBoundaryScript3);
3151 }
3152 var clientRenderScript1Full = stringToPrecomputedChunk(clientRenderFunction + ';$RX("');
3153 var clientRenderScript1Partial = stringToPrecomputedChunk('$RX("');
3154 var clientRenderScript2 = stringToPrecomputedChunk('")</script>');
3155 function writeClientRenderBoundaryInstruction(destination, responseState, boundaryID) {
3156 writeChunk(destination, responseState.startInlineScript);
3157
3158 if (!responseState.sentClientRenderFunction) {
3159 // The first time we write this, we'll need to include the full implementation.
3160 responseState.sentClientRenderFunction = true;
3161 writeChunk(destination, clientRenderScript1Full);
3162 } else {
3163 // Future calls can just reuse the same function.
3164 writeChunk(destination, clientRenderScript1Partial);
3165 }
3166
3167 if (boundaryID === null) {
3168 throw new Error('An ID must have been assigned before we can complete the boundary.');
3169 }
3170
3171 writeChunk(destination, boundaryID);
3172 return writeChunkAndReturn(destination, clientRenderScript2);
3173 }
3174
3175 function createResponseState$1(generateStaticMarkup, identifierPrefix) {
3176 var responseState = createResponseState(identifierPrefix, undefined);
3177 return {
3178 // Keep this in sync with ReactDOMServerFormatConfig
3179 bootstrapChunks: responseState.bootstrapChunks,
3180 startInlineScript: responseState.startInlineScript,
3181 placeholderPrefix: responseState.placeholderPrefix,
3182 segmentPrefix: responseState.segmentPrefix,
3183 boundaryPrefix: responseState.boundaryPrefix,
3184 idPrefix: responseState.idPrefix,
3185 nextSuspenseID: responseState.nextSuspenseID,
3186 sentCompleteSegmentFunction: responseState.sentCompleteSegmentFunction,
3187 sentCompleteBoundaryFunction: responseState.sentCompleteBoundaryFunction,
3188 sentClientRenderFunction: responseState.sentClientRenderFunction,
3189 // This is an extra field for the legacy renderer
3190 generateStaticMarkup: generateStaticMarkup
3191 };
3192 }
3193 function createRootFormatContext() {
3194 return {
3195 insertionMode: HTML_MODE,
3196 // We skip the root mode because we don't want to emit the DOCTYPE in legacy mode.
3197 selectedValue: null
3198 };
3199 }
3200 function pushTextInstance$1(target, text, responseState) {
3201 if (responseState.generateStaticMarkup) {
3202 target.push(stringToChunk(escapeTextForBrowser(text)));
3203 } else {
3204 pushTextInstance(target, text);
3205 }
3206 }
3207 function writeStartCompletedSuspenseBoundary$1(destination, responseState) {
3208 if (responseState.generateStaticMarkup) {
3209 // A completed boundary is done and doesn't need a representation in the HTML
3210 // if we're not going to be hydrating it.
3211 return true;
3212 }
3213
3214 return writeStartCompletedSuspenseBoundary(destination);
3215 }
3216 function writeStartClientRenderedSuspenseBoundary$1(destination, responseState) {
3217 if (responseState.generateStaticMarkup) {
3218 // A client rendered boundary is done and doesn't need a representation in the HTML
3219 // since we'll never hydrate it. This is arguably an error in static generation.
3220 return true;
3221 }
3222
3223 return writeStartClientRenderedSuspenseBoundary(destination);
3224 }
3225 function writeEndCompletedSuspenseBoundary$1(destination, responseState) {
3226 if (responseState.generateStaticMarkup) {
3227 return true;
3228 }
3229
3230 return writeEndCompletedSuspenseBoundary(destination);
3231 }
3232 function writeEndClientRenderedSuspenseBoundary$1(destination, responseState) {
3233 if (responseState.generateStaticMarkup) {
3234 return true;
3235 }
3236
3237 return writeEndClientRenderedSuspenseBoundary(destination);
3238 }
3239
3240 var assign = Object.assign;
3241
3242 // ATTENTION
3243 // When adding new symbols to this file,
3244 // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
3245 // The Symbol used to tag the ReactElement-like types.
3246 var REACT_ELEMENT_TYPE = Symbol.for('react.element');
3247 var REACT_PORTAL_TYPE = Symbol.for('react.portal');
3248 var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
3249 var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
3250 var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
3251 var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
3252 var REACT_CONTEXT_TYPE = Symbol.for('react.context');
3253 var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
3254 var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
3255 var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
3256 var REACT_MEMO_TYPE = Symbol.for('react.memo');
3257 var REACT_LAZY_TYPE = Symbol.for('react.lazy');
3258 var REACT_SCOPE_TYPE = Symbol.for('react.scope');
3259 var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode');
3260 var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden');
3261 var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value');
3262 var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
3263 var FAUX_ITERATOR_SYMBOL = '@@iterator';
3264 function getIteratorFn(maybeIterable) {
3265 if (maybeIterable === null || typeof maybeIterable !== 'object') {
3266 return null;
3267 }
3268
3269 var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
3270
3271 if (typeof maybeIterator === 'function') {
3272 return maybeIterator;
3273 }
3274
3275 return null;
3276 }
3277
3278 function getWrappedName(outerType, innerType, wrapperName) {
3279 var displayName = outerType.displayName;
3280
3281 if (displayName) {
3282 return displayName;
3283 }
3284
3285 var functionName = innerType.displayName || innerType.name || '';
3286 return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
3287 } // Keep in sync with react-reconciler/getComponentNameFromFiber
3288
3289
3290 function getContextName(type) {
3291 return type.displayName || 'Context';
3292 } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
3293
3294
3295 function getComponentNameFromType(type) {
3296 if (type == null) {
3297 // Host root, text node or just invalid type.
3298 return null;
3299 }
3300
3301 {
3302 if (typeof type.tag === 'number') {
3303 error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
3304 }
3305 }
3306
3307 if (typeof type === 'function') {
3308 return type.displayName || type.name || null;
3309 }
3310
3311 if (typeof type === 'string') {
3312 return type;
3313 }
3314
3315 switch (type) {
3316 case REACT_FRAGMENT_TYPE:
3317 return 'Fragment';
3318
3319 case REACT_PORTAL_TYPE:
3320 return 'Portal';
3321
3322 case REACT_PROFILER_TYPE:
3323 return 'Profiler';
3324
3325 case REACT_STRICT_MODE_TYPE:
3326 return 'StrictMode';
3327
3328 case REACT_SUSPENSE_TYPE:
3329 return 'Suspense';
3330
3331 case REACT_SUSPENSE_LIST_TYPE:
3332 return 'SuspenseList';
3333
3334 }
3335
3336 if (typeof type === 'object') {
3337 switch (type.$$typeof) {
3338 case REACT_CONTEXT_TYPE:
3339 var context = type;
3340 return getContextName(context) + '.Consumer';
3341
3342 case REACT_PROVIDER_TYPE:
3343 var provider = type;
3344 return getContextName(provider._context) + '.Provider';
3345
3346 case REACT_FORWARD_REF_TYPE:
3347 return getWrappedName(type, type.render, 'ForwardRef');
3348
3349 case REACT_MEMO_TYPE:
3350 var outerName = type.displayName || null;
3351
3352 if (outerName !== null) {
3353 return outerName;
3354 }
3355
3356 return getComponentNameFromType(type.type) || 'Memo';
3357
3358 case REACT_LAZY_TYPE:
3359 {
3360 var lazyComponent = type;
3361 var payload = lazyComponent._payload;
3362 var init = lazyComponent._init;
3363
3364 try {
3365 return getComponentNameFromType(init(payload));
3366 } catch (x) {
3367 return null;
3368 }
3369 }
3370
3371 // eslint-disable-next-line no-fallthrough
3372 }
3373 }
3374
3375 return null;
3376 }
3377
3378 // Helpers to patch console.logs to avoid logging during side-effect free
3379 // replaying on render function. This currently only patches the object
3380 // lazily which won't cover if the log function was extracted eagerly.
3381 // We could also eagerly patch the method.
3382 var disabledDepth = 0;
3383 var prevLog;
3384 var prevInfo;
3385 var prevWarn;
3386 var prevError;
3387 var prevGroup;
3388 var prevGroupCollapsed;
3389 var prevGroupEnd;
3390
3391 function disabledLog() {}
3392
3393 disabledLog.__reactDisabledLog = true;
3394 function disableLogs() {
3395 {
3396 if (disabledDepth === 0) {
3397 /* eslint-disable react-internal/no-production-logging */
3398 prevLog = console.log;
3399 prevInfo = console.info;
3400 prevWarn = console.warn;
3401 prevError = console.error;
3402 prevGroup = console.group;
3403 prevGroupCollapsed = console.groupCollapsed;
3404 prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
3405
3406 var props = {
3407 configurable: true,
3408 enumerable: true,
3409 value: disabledLog,
3410 writable: true
3411 }; // $FlowFixMe Flow thinks console is immutable.
3412
3413 Object.defineProperties(console, {
3414 info: props,
3415 log: props,
3416 warn: props,
3417 error: props,
3418 group: props,
3419 groupCollapsed: props,
3420 groupEnd: props
3421 });
3422 /* eslint-enable react-internal/no-production-logging */
3423 }
3424
3425 disabledDepth++;
3426 }
3427 }
3428 function reenableLogs() {
3429 {
3430 disabledDepth--;
3431
3432 if (disabledDepth === 0) {
3433 /* eslint-disable react-internal/no-production-logging */
3434 var props = {
3435 configurable: true,
3436 enumerable: true,
3437 writable: true
3438 }; // $FlowFixMe Flow thinks console is immutable.
3439
3440 Object.defineProperties(console, {
3441 log: assign({}, props, {
3442 value: prevLog
3443 }),
3444 info: assign({}, props, {
3445 value: prevInfo
3446 }),
3447 warn: assign({}, props, {
3448 value: prevWarn
3449 }),
3450 error: assign({}, props, {
3451 value: prevError
3452 }),
3453 group: assign({}, props, {
3454 value: prevGroup
3455 }),
3456 groupCollapsed: assign({}, props, {
3457 value: prevGroupCollapsed
3458 }),
3459 groupEnd: assign({}, props, {
3460 value: prevGroupEnd
3461 })
3462 });
3463 /* eslint-enable react-internal/no-production-logging */
3464 }
3465
3466 if (disabledDepth < 0) {
3467 error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
3468 }
3469 }
3470 }
3471
3472 var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
3473 var prefix;
3474 function describeBuiltInComponentFrame(name, source, ownerFn) {
3475 {
3476 if (prefix === undefined) {
3477 // Extract the VM specific prefix used by each line.
3478 try {
3479 throw Error();
3480 } catch (x) {
3481 var match = x.stack.trim().match(/\n( *(at )?)/);
3482 prefix = match && match[1] || '';
3483 }
3484 } // We use the prefix to ensure our stacks line up with native stack frames.
3485
3486
3487 return '\n' + prefix + name;
3488 }
3489 }
3490 var reentry = false;
3491 var componentFrameCache;
3492
3493 {
3494 var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
3495 componentFrameCache = new PossiblyWeakMap();
3496 }
3497
3498 function describeNativeComponentFrame(fn, construct) {
3499 // If something asked for a stack inside a fake render, it should get ignored.
3500 if ( !fn || reentry) {
3501 return '';
3502 }
3503
3504 {
3505 var frame = componentFrameCache.get(fn);
3506
3507 if (frame !== undefined) {
3508 return frame;
3509 }
3510 }
3511
3512 var control;
3513 reentry = true;
3514 var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
3515
3516 Error.prepareStackTrace = undefined;
3517 var previousDispatcher;
3518
3519 {
3520 previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
3521 // for warnings.
3522
3523 ReactCurrentDispatcher.current = null;
3524 disableLogs();
3525 }
3526
3527 try {
3528 // This should throw.
3529 if (construct) {
3530 // Something should be setting the props in the constructor.
3531 var Fake = function () {
3532 throw Error();
3533 }; // $FlowFixMe
3534
3535
3536 Object.defineProperty(Fake.prototype, 'props', {
3537 set: function () {
3538 // We use a throwing setter instead of frozen or non-writable props
3539 // because that won't throw in a non-strict mode function.
3540 throw Error();
3541 }
3542 });
3543
3544 if (typeof Reflect === 'object' && Reflect.construct) {
3545 // We construct a different control for this case to include any extra
3546 // frames added by the construct call.
3547 try {
3548 Reflect.construct(Fake, []);
3549 } catch (x) {
3550 control = x;
3551 }
3552
3553 Reflect.construct(fn, [], Fake);
3554 } else {
3555 try {
3556 Fake.call();
3557 } catch (x) {
3558 control = x;
3559 }
3560
3561 fn.call(Fake.prototype);
3562 }
3563 } else {
3564 try {
3565 throw Error();
3566 } catch (x) {
3567 control = x;
3568 }
3569
3570 fn();
3571 }
3572 } catch (sample) {
3573 // This is inlined manually because closure doesn't do it for us.
3574 if (sample && control && typeof sample.stack === 'string') {
3575 // This extracts the first frame from the sample that isn't also in the control.
3576 // Skipping one frame that we assume is the frame that calls the two.
3577 var sampleLines = sample.stack.split('\n');
3578 var controlLines = control.stack.split('\n');
3579 var s = sampleLines.length - 1;
3580 var c = controlLines.length - 1;
3581
3582 while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
3583 // We expect at least one stack frame to be shared.
3584 // Typically this will be the root most one. However, stack frames may be
3585 // cut off due to maximum stack limits. In this case, one maybe cut off
3586 // earlier than the other. We assume that the sample is longer or the same
3587 // and there for cut off earlier. So we should find the root most frame in
3588 // the sample somewhere in the control.
3589 c--;
3590 }
3591
3592 for (; s >= 1 && c >= 0; s--, c--) {
3593 // Next we find the first one that isn't the same which should be the
3594 // frame that called our sample function and the control.
3595 if (sampleLines[s] !== controlLines[c]) {
3596 // In V8, the first line is describing the message but other VMs don't.
3597 // If we're about to return the first line, and the control is also on the same
3598 // line, that's a pretty good indicator that our sample threw at same line as
3599 // the control. I.e. before we entered the sample frame. So we ignore this result.
3600 // This can happen if you passed a class to function component, or non-function.
3601 if (s !== 1 || c !== 1) {
3602 do {
3603 s--;
3604 c--; // We may still have similar intermediate frames from the construct call.
3605 // The next one that isn't the same should be our match though.
3606
3607 if (c < 0 || sampleLines[s] !== controlLines[c]) {
3608 // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
3609 var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
3610 // but we have a user-provided "displayName"
3611 // splice it in to make the stack more readable.
3612
3613
3614 if (fn.displayName && _frame.includes('<anonymous>')) {
3615 _frame = _frame.replace('<anonymous>', fn.displayName);
3616 }
3617
3618 {
3619 if (typeof fn === 'function') {
3620 componentFrameCache.set(fn, _frame);
3621 }
3622 } // Return the line we found.
3623
3624
3625 return _frame;
3626 }
3627 } while (s >= 1 && c >= 0);
3628 }
3629
3630 break;
3631 }
3632 }
3633 }
3634 } finally {
3635 reentry = false;
3636
3637 {
3638 ReactCurrentDispatcher.current = previousDispatcher;
3639 reenableLogs();
3640 }
3641
3642 Error.prepareStackTrace = previousPrepareStackTrace;
3643 } // Fallback to just using the name if we couldn't make it throw.
3644
3645
3646 var name = fn ? fn.displayName || fn.name : '';
3647 var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
3648
3649 {
3650 if (typeof fn === 'function') {
3651 componentFrameCache.set(fn, syntheticFrame);
3652 }
3653 }
3654
3655 return syntheticFrame;
3656 }
3657
3658 function describeClassComponentFrame(ctor, source, ownerFn) {
3659 {
3660 return describeNativeComponentFrame(ctor, true);
3661 }
3662 }
3663 function describeFunctionComponentFrame(fn, source, ownerFn) {
3664 {
3665 return describeNativeComponentFrame(fn, false);
3666 }
3667 }
3668
3669 function shouldConstruct(Component) {
3670 var prototype = Component.prototype;
3671 return !!(prototype && prototype.isReactComponent);
3672 }
3673
3674 function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
3675
3676 if (type == null) {
3677 return '';
3678 }
3679
3680 if (typeof type === 'function') {
3681 {
3682 return describeNativeComponentFrame(type, shouldConstruct(type));
3683 }
3684 }
3685
3686 if (typeof type === 'string') {
3687 return describeBuiltInComponentFrame(type);
3688 }
3689
3690 switch (type) {
3691 case REACT_SUSPENSE_TYPE:
3692 return describeBuiltInComponentFrame('Suspense');
3693
3694 case REACT_SUSPENSE_LIST_TYPE:
3695 return describeBuiltInComponentFrame('SuspenseList');
3696 }
3697
3698 if (typeof type === 'object') {
3699 switch (type.$$typeof) {
3700 case REACT_FORWARD_REF_TYPE:
3701 return describeFunctionComponentFrame(type.render);
3702
3703 case REACT_MEMO_TYPE:
3704 // Memo may contain any component type so we recursively resolve it.
3705 return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
3706
3707 case REACT_LAZY_TYPE:
3708 {
3709 var lazyComponent = type;
3710 var payload = lazyComponent._payload;
3711 var init = lazyComponent._init;
3712
3713 try {
3714 // Lazy may contain any component type so we recursively resolve it.
3715 return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
3716 } catch (x) {}
3717 }
3718 }
3719 }
3720
3721 return '';
3722 }
3723
3724 var loggedTypeFailures = {};
3725 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
3726
3727 function setCurrentlyValidatingElement(element) {
3728 {
3729 if (element) {
3730 var owner = element._owner;
3731 var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
3732 ReactDebugCurrentFrame.setExtraStackFrame(stack);
3733 } else {
3734 ReactDebugCurrentFrame.setExtraStackFrame(null);
3735 }
3736 }
3737 }
3738
3739 function checkPropTypes(typeSpecs, values, location, componentName, element) {
3740 {
3741 // $FlowFixMe This is okay but Flow doesn't know it.
3742 var has = Function.call.bind(hasOwnProperty);
3743
3744 for (var typeSpecName in typeSpecs) {
3745 if (has(typeSpecs, typeSpecName)) {
3746 var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
3747 // fail the render phase where it didn't fail before. So we log it.
3748 // After these have been cleaned up, we'll let them throw.
3749
3750 try {
3751 // This is intentionally an invariant that gets caught. It's the same
3752 // behavior as without this statement except with a better message.
3753 if (typeof typeSpecs[typeSpecName] !== 'function') {
3754 // eslint-disable-next-line react-internal/prod-error-codes
3755 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`.');
3756 err.name = 'Invariant Violation';
3757 throw err;
3758 }
3759
3760 error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
3761 } catch (ex) {
3762 error$1 = ex;
3763 }
3764
3765 if (error$1 && !(error$1 instanceof Error)) {
3766 setCurrentlyValidatingElement(element);
3767
3768 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);
3769
3770 setCurrentlyValidatingElement(null);
3771 }
3772
3773 if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
3774 // Only monitor this failure once because there tends to be a lot of the
3775 // same error.
3776 loggedTypeFailures[error$1.message] = true;
3777 setCurrentlyValidatingElement(element);
3778
3779 error('Failed %s type: %s', location, error$1.message);
3780
3781 setCurrentlyValidatingElement(null);
3782 }
3783 }
3784 }
3785 }
3786 }
3787
3788 var warnedAboutMissingGetChildContext;
3789
3790 {
3791 warnedAboutMissingGetChildContext = {};
3792 }
3793
3794 var emptyContextObject = {};
3795
3796 {
3797 Object.freeze(emptyContextObject);
3798 }
3799
3800 function getMaskedContext(type, unmaskedContext) {
3801 {
3802 var contextTypes = type.contextTypes;
3803
3804 if (!contextTypes) {
3805 return emptyContextObject;
3806 }
3807
3808 var context = {};
3809
3810 for (var key in contextTypes) {
3811 context[key] = unmaskedContext[key];
3812 }
3813
3814 {
3815 var name = getComponentNameFromType(type) || 'Unknown';
3816 checkPropTypes(contextTypes, context, 'context', name);
3817 }
3818
3819 return context;
3820 }
3821 }
3822 function processChildContext(instance, type, parentContext, childContextTypes) {
3823 {
3824 // TODO (bvaughn) Replace this behavior with an invariant() in the future.
3825 // It has only been added in Fiber to match the (unintentional) behavior in Stack.
3826 if (typeof instance.getChildContext !== 'function') {
3827 {
3828 var componentName = getComponentNameFromType(type) || 'Unknown';
3829
3830 if (!warnedAboutMissingGetChildContext[componentName]) {
3831 warnedAboutMissingGetChildContext[componentName] = true;
3832
3833 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);
3834 }
3835 }
3836
3837 return parentContext;
3838 }
3839
3840 var childContext = instance.getChildContext();
3841
3842 for (var contextKey in childContext) {
3843 if (!(contextKey in childContextTypes)) {
3844 throw new Error((getComponentNameFromType(type) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes.");
3845 }
3846 }
3847
3848 {
3849 var name = getComponentNameFromType(type) || 'Unknown';
3850 checkPropTypes(childContextTypes, childContext, 'child context', name);
3851 }
3852
3853 return assign({}, parentContext, childContext);
3854 }
3855 }
3856
3857 var rendererSigil;
3858
3859 {
3860 // Use this to detect multiple renderers using the same context
3861 rendererSigil = {};
3862 } // Used to store the parent path of all context overrides in a shared linked list.
3863 // Forming a reverse tree.
3864
3865
3866 var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances.
3867 // This global (actually thread local) state represents what state all those "current",
3868 // fields are currently in.
3869
3870 var currentActiveSnapshot = null;
3871
3872 function popNode(prev) {
3873 {
3874 prev.context._currentValue2 = prev.parentValue;
3875 }
3876 }
3877
3878 function pushNode(next) {
3879 {
3880 next.context._currentValue2 = next.value;
3881 }
3882 }
3883
3884 function popToNearestCommonAncestor(prev, next) {
3885 if (prev === next) ; else {
3886 popNode(prev);
3887 var parentPrev = prev.parent;
3888 var parentNext = next.parent;
3889
3890 if (parentPrev === null) {
3891 if (parentNext !== null) {
3892 throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
3893 }
3894 } else {
3895 if (parentNext === null) {
3896 throw new Error('The stacks must reach the root at the same time. This is a bug in React.');
3897 }
3898
3899 popToNearestCommonAncestor(parentPrev, parentNext);
3900 } // On the way back, we push the new ones that weren't common.
3901
3902
3903 pushNode(next);
3904 }
3905 }
3906
3907 function popAllPrevious(prev) {
3908 popNode(prev);
3909 var parentPrev = prev.parent;
3910
3911 if (parentPrev !== null) {
3912 popAllPrevious(parentPrev);
3913 }
3914 }
3915
3916 function pushAllNext(next) {
3917 var parentNext = next.parent;
3918
3919 if (parentNext !== null) {
3920 pushAllNext(parentNext);
3921 }
3922
3923 pushNode(next);
3924 }
3925
3926 function popPreviousToCommonLevel(prev, next) {
3927 popNode(prev);
3928 var parentPrev = prev.parent;
3929
3930 if (parentPrev === null) {
3931 throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
3932 }
3933
3934 if (parentPrev.depth === next.depth) {
3935 // We found the same level. Now we just need to find a shared ancestor.
3936 popToNearestCommonAncestor(parentPrev, next);
3937 } else {
3938 // We must still be deeper.
3939 popPreviousToCommonLevel(parentPrev, next);
3940 }
3941 }
3942
3943 function popNextToCommonLevel(prev, next) {
3944 var parentNext = next.parent;
3945
3946 if (parentNext === null) {
3947 throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');
3948 }
3949
3950 if (prev.depth === parentNext.depth) {
3951 // We found the same level. Now we just need to find a shared ancestor.
3952 popToNearestCommonAncestor(prev, parentNext);
3953 } else {
3954 // We must still be deeper.
3955 popNextToCommonLevel(prev, parentNext);
3956 }
3957
3958 pushNode(next);
3959 } // Perform context switching to the new snapshot.
3960 // To make it cheap to read many contexts, while not suspending, we make the switch eagerly by
3961 // updating all the context's current values. That way reads, always just read the current value.
3962 // At the cost of updating contexts even if they're never read by this subtree.
3963
3964
3965 function switchContext(newSnapshot) {
3966 // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack.
3967 // We also need to update any new contexts that are now on the stack with the deepest value.
3968 // The easiest way to update new contexts is to just reapply them in reverse order from the
3969 // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack
3970 // for that. Therefore this algorithm is recursive.
3971 // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go.
3972 // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go.
3973 // 3) Then we reapply new contexts on the way back up the stack.
3974 var prev = currentActiveSnapshot;
3975 var next = newSnapshot;
3976
3977 if (prev !== next) {
3978 if (prev === null) {
3979 // $FlowFixMe: This has to be non-null since it's not equal to prev.
3980 pushAllNext(next);
3981 } else if (next === null) {
3982 popAllPrevious(prev);
3983 } else if (prev.depth === next.depth) {
3984 popToNearestCommonAncestor(prev, next);
3985 } else if (prev.depth > next.depth) {
3986 popPreviousToCommonLevel(prev, next);
3987 } else {
3988 popNextToCommonLevel(prev, next);
3989 }
3990
3991 currentActiveSnapshot = next;
3992 }
3993 }
3994 function pushProvider(context, nextValue) {
3995 var prevValue;
3996
3997 {
3998 prevValue = context._currentValue2;
3999 context._currentValue2 = nextValue;
4000
4001 {
4002 if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) {
4003 error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
4004 }
4005
4006 context._currentRenderer2 = rendererSigil;
4007 }
4008 }
4009
4010 var prevNode = currentActiveSnapshot;
4011 var newNode = {
4012 parent: prevNode,
4013 depth: prevNode === null ? 0 : prevNode.depth + 1,
4014 context: context,
4015 parentValue: prevValue,
4016 value: nextValue
4017 };
4018 currentActiveSnapshot = newNode;
4019 return newNode;
4020 }
4021 function popProvider(context) {
4022 var prevSnapshot = currentActiveSnapshot;
4023
4024 if (prevSnapshot === null) {
4025 throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.');
4026 }
4027
4028 {
4029 if (prevSnapshot.context !== context) {
4030 error('The parent context is not the expected context. This is probably a bug in React.');
4031 }
4032 }
4033
4034 {
4035 var _value = prevSnapshot.parentValue;
4036
4037 if (_value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) {
4038 prevSnapshot.context._currentValue2 = prevSnapshot.context._defaultValue;
4039 } else {
4040 prevSnapshot.context._currentValue2 = _value;
4041 }
4042
4043 {
4044 if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) {
4045 error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
4046 }
4047
4048 context._currentRenderer2 = rendererSigil;
4049 }
4050 }
4051
4052 return currentActiveSnapshot = prevSnapshot.parent;
4053 }
4054 function getActiveContext() {
4055 return currentActiveSnapshot;
4056 }
4057 function readContext(context) {
4058 var value = context._currentValue2;
4059 return value;
4060 }
4061
4062 /**
4063 * `ReactInstanceMap` maintains a mapping from a public facing stateful
4064 * instance (key) and the internal representation (value). This allows public
4065 * methods to accept the user facing instance as an argument and map them back
4066 * to internal methods.
4067 *
4068 * Note that this module is currently shared and assumed to be stateless.
4069 * If this becomes an actual Map, that will break.
4070 */
4071 function get(key) {
4072 return key._reactInternals;
4073 }
4074 function set(key, value) {
4075 key._reactInternals = value;
4076 }
4077
4078 var didWarnAboutNoopUpdateForComponent = {};
4079 var didWarnAboutDeprecatedWillMount = {};
4080 var didWarnAboutUninitializedState;
4081 var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
4082 var didWarnAboutLegacyLifecyclesAndDerivedState;
4083 var didWarnAboutUndefinedDerivedState;
4084 var warnOnUndefinedDerivedState;
4085 var warnOnInvalidCallback;
4086 var didWarnAboutDirectlyAssigningPropsToState;
4087 var didWarnAboutContextTypeAndContextTypes;
4088 var didWarnAboutInvalidateContextType;
4089
4090 {
4091 didWarnAboutUninitializedState = new Set();
4092 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
4093 didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
4094 didWarnAboutDirectlyAssigningPropsToState = new Set();
4095 didWarnAboutUndefinedDerivedState = new Set();
4096 didWarnAboutContextTypeAndContextTypes = new Set();
4097 didWarnAboutInvalidateContextType = new Set();
4098 var didWarnOnInvalidCallback = new Set();
4099
4100 warnOnInvalidCallback = function (callback, callerName) {
4101 if (callback === null || typeof callback === 'function') {
4102 return;
4103 }
4104
4105 var key = callerName + '_' + callback;
4106
4107 if (!didWarnOnInvalidCallback.has(key)) {
4108 didWarnOnInvalidCallback.add(key);
4109
4110 error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
4111 }
4112 };
4113
4114 warnOnUndefinedDerivedState = function (type, partialState) {
4115 if (partialState === undefined) {
4116 var componentName = getComponentNameFromType(type) || 'Component';
4117
4118 if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
4119 didWarnAboutUndefinedDerivedState.add(componentName);
4120
4121 error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
4122 }
4123 }
4124 };
4125 }
4126
4127 function warnNoop(publicInstance, callerName) {
4128 {
4129 var _constructor = publicInstance.constructor;
4130 var componentName = _constructor && getComponentNameFromType(_constructor) || 'ReactClass';
4131 var warningKey = componentName + '.' + callerName;
4132
4133 if (didWarnAboutNoopUpdateForComponent[warningKey]) {
4134 return;
4135 }
4136
4137 error('%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op.\n\nPlease check the code for the %s component.', callerName, callerName, componentName);
4138
4139 didWarnAboutNoopUpdateForComponent[warningKey] = true;
4140 }
4141 }
4142
4143 var classComponentUpdater = {
4144 isMounted: function (inst) {
4145 return false;
4146 },
4147 enqueueSetState: function (inst, payload, callback) {
4148 var internals = get(inst);
4149
4150 if (internals.queue === null) {
4151 warnNoop(inst, 'setState');
4152 } else {
4153 internals.queue.push(payload);
4154
4155 {
4156 if (callback !== undefined && callback !== null) {
4157 warnOnInvalidCallback(callback, 'setState');
4158 }
4159 }
4160 }
4161 },
4162 enqueueReplaceState: function (inst, payload, callback) {
4163 var internals = get(inst);
4164 internals.replace = true;
4165 internals.queue = [payload];
4166
4167 {
4168 if (callback !== undefined && callback !== null) {
4169 warnOnInvalidCallback(callback, 'setState');
4170 }
4171 }
4172 },
4173 enqueueForceUpdate: function (inst, callback) {
4174 var internals = get(inst);
4175
4176 if (internals.queue === null) {
4177 warnNoop(inst, 'forceUpdate');
4178 } else {
4179 {
4180 if (callback !== undefined && callback !== null) {
4181 warnOnInvalidCallback(callback, 'setState');
4182 }
4183 }
4184 }
4185 }
4186 };
4187
4188 function applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, prevState, nextProps) {
4189 var partialState = getDerivedStateFromProps(nextProps, prevState);
4190
4191 {
4192 warnOnUndefinedDerivedState(ctor, partialState);
4193 } // Merge the partial state and the previous state.
4194
4195
4196 var newState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState);
4197 return newState;
4198 }
4199
4200 function constructClassInstance(ctor, props, maskedLegacyContext) {
4201 var context = emptyContextObject;
4202 var contextType = ctor.contextType;
4203
4204 {
4205 if ('contextType' in ctor) {
4206 var isValid = // Allow null for conditional declaration
4207 contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>
4208
4209 if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
4210 didWarnAboutInvalidateContextType.add(ctor);
4211 var addendum = '';
4212
4213 if (contextType === undefined) {
4214 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.';
4215 } else if (typeof contextType !== 'object') {
4216 addendum = ' However, it is set to a ' + typeof contextType + '.';
4217 } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
4218 addendum = ' Did you accidentally pass the Context.Provider instead?';
4219 } else if (contextType._context !== undefined) {
4220 // <Context.Consumer>
4221 addendum = ' Did you accidentally pass the Context.Consumer instead?';
4222 } else {
4223 addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
4224 }
4225
4226 error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum);
4227 }
4228 }
4229 }
4230
4231 if (typeof contextType === 'object' && contextType !== null) {
4232 context = readContext(contextType);
4233 } else {
4234 context = maskedLegacyContext;
4235 }
4236
4237 var instance = new ctor(props, context);
4238
4239 {
4240 if (typeof ctor.getDerivedStateFromProps === 'function' && (instance.state === null || instance.state === undefined)) {
4241 var componentName = getComponentNameFromType(ctor) || 'Component';
4242
4243 if (!didWarnAboutUninitializedState.has(componentName)) {
4244 didWarnAboutUninitializedState.add(componentName);
4245
4246 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);
4247 }
4248 } // If new component APIs are defined, "unsafe" lifecycles won't be called.
4249 // Warn about these lifecycles if they are present.
4250 // Don't warn about react-lifecycles-compat polyfilled methods though.
4251
4252
4253 if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
4254 var foundWillMountName = null;
4255 var foundWillReceivePropsName = null;
4256 var foundWillUpdateName = null;
4257
4258 if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
4259 foundWillMountName = 'componentWillMount';
4260 } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
4261 foundWillMountName = 'UNSAFE_componentWillMount';
4262 }
4263
4264 if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
4265 foundWillReceivePropsName = 'componentWillReceiveProps';
4266 } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
4267 foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
4268 }
4269
4270 if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
4271 foundWillUpdateName = 'componentWillUpdate';
4272 } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
4273 foundWillUpdateName = 'UNSAFE_componentWillUpdate';
4274 }
4275
4276 if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
4277 var _componentName = getComponentNameFromType(ctor) || 'Component';
4278
4279 var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
4280
4281 if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
4282 didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
4283
4284 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 : '');
4285 }
4286 }
4287 }
4288 }
4289
4290 return instance;
4291 }
4292
4293 function checkClassInstance(instance, ctor, newProps) {
4294 {
4295 var name = getComponentNameFromType(ctor) || 'Component';
4296 var renderPresent = instance.render;
4297
4298 if (!renderPresent) {
4299 if (ctor.prototype && typeof ctor.prototype.render === 'function') {
4300 error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
4301 } else {
4302 error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
4303 }
4304 }
4305
4306 if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {
4307 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);
4308 }
4309
4310 if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {
4311 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);
4312 }
4313
4314 if (instance.propTypes) {
4315 error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);
4316 }
4317
4318 if (instance.contextType) {
4319 error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);
4320 }
4321
4322 {
4323 if (instance.contextTypes) {
4324 error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name);
4325 }
4326
4327 if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
4328 didWarnAboutContextTypeAndContextTypes.add(ctor);
4329
4330 error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
4331 }
4332 }
4333
4334 if (typeof instance.componentShouldUpdate === 'function') {
4335 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);
4336 }
4337
4338 if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
4339 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');
4340 }
4341
4342 if (typeof instance.componentDidUnmount === 'function') {
4343 error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);
4344 }
4345
4346 if (typeof instance.componentDidReceiveProps === 'function') {
4347 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);
4348 }
4349
4350 if (typeof instance.componentWillRecieveProps === 'function') {
4351 error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);
4352 }
4353
4354 if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {
4355 error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);
4356 }
4357
4358 var hasMutatedProps = instance.props !== newProps;
4359
4360 if (instance.props !== undefined && hasMutatedProps) {
4361 error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name);
4362 }
4363
4364 if (instance.defaultProps) {
4365 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);
4366 }
4367
4368 if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
4369 didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
4370
4371 error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor));
4372 }
4373
4374 if (typeof instance.getDerivedStateFromProps === 'function') {
4375 error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
4376 }
4377
4378 if (typeof instance.getDerivedStateFromError === 'function') {
4379 error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
4380 }
4381
4382 if (typeof ctor.getSnapshotBeforeUpdate === 'function') {
4383 error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);
4384 }
4385
4386 var _state = instance.state;
4387
4388 if (_state && (typeof _state !== 'object' || isArray(_state))) {
4389 error('%s.state: must be set to an object or null', name);
4390 }
4391
4392 if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {
4393 error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);
4394 }
4395 }
4396 }
4397
4398 function callComponentWillMount(type, instance) {
4399 var oldState = instance.state;
4400
4401 if (typeof instance.componentWillMount === 'function') {
4402 {
4403 if ( instance.componentWillMount.__suppressDeprecationWarning !== true) {
4404 var componentName = getComponentNameFromType(type) || 'Unknown';
4405
4406 if (!didWarnAboutDeprecatedWillMount[componentName]) {
4407 warn( // keep this warning in sync with ReactStrictModeWarning.js
4408 'componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code from componentWillMount to componentDidMount (preferred in most cases) ' + 'or the constructor.\n' + '\nPlease update the following components: %s', componentName);
4409
4410 didWarnAboutDeprecatedWillMount[componentName] = true;
4411 }
4412 }
4413 }
4414
4415 instance.componentWillMount();
4416 }
4417
4418 if (typeof instance.UNSAFE_componentWillMount === 'function') {
4419 instance.UNSAFE_componentWillMount();
4420 }
4421
4422 if (oldState !== instance.state) {
4423 {
4424 error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromType(type) || 'Component');
4425 }
4426
4427 classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
4428 }
4429 }
4430
4431 function processUpdateQueue(internalInstance, inst, props, maskedLegacyContext) {
4432 if (internalInstance.queue !== null && internalInstance.queue.length > 0) {
4433 var oldQueue = internalInstance.queue;
4434 var oldReplace = internalInstance.replace;
4435 internalInstance.queue = null;
4436 internalInstance.replace = false;
4437
4438 if (oldReplace && oldQueue.length === 1) {
4439 inst.state = oldQueue[0];
4440 } else {
4441 var nextState = oldReplace ? oldQueue[0] : inst.state;
4442 var dontMutate = true;
4443
4444 for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) {
4445 var partial = oldQueue[i];
4446 var partialState = typeof partial === 'function' ? partial.call(inst, nextState, props, maskedLegacyContext) : partial;
4447
4448 if (partialState != null) {
4449 if (dontMutate) {
4450 dontMutate = false;
4451 nextState = assign({}, nextState, partialState);
4452 } else {
4453 assign(nextState, partialState);
4454 }
4455 }
4456 }
4457
4458 inst.state = nextState;
4459 }
4460 } else {
4461 internalInstance.queue = null;
4462 }
4463 } // Invokes the mount life-cycles on a previously never rendered instance.
4464
4465
4466 function mountClassInstance(instance, ctor, newProps, maskedLegacyContext) {
4467 {
4468 checkClassInstance(instance, ctor, newProps);
4469 }
4470
4471 var initialState = instance.state !== undefined ? instance.state : null;
4472 instance.updater = classComponentUpdater;
4473 instance.props = newProps;
4474 instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway.
4475 // The internal instance will be used to manage updates that happen during this mount.
4476
4477 var internalInstance = {
4478 queue: [],
4479 replace: false
4480 };
4481 set(instance, internalInstance);
4482 var contextType = ctor.contextType;
4483
4484 if (typeof contextType === 'object' && contextType !== null) {
4485 instance.context = readContext(contextType);
4486 } else {
4487 instance.context = maskedLegacyContext;
4488 }
4489
4490 {
4491 if (instance.state === newProps) {
4492 var componentName = getComponentNameFromType(ctor) || 'Component';
4493
4494 if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
4495 didWarnAboutDirectlyAssigningPropsToState.add(componentName);
4496
4497 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);
4498 }
4499 }
4500 }
4501
4502 var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
4503
4504 if (typeof getDerivedStateFromProps === 'function') {
4505 instance.state = applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, initialState, newProps);
4506 } // In order to support react-lifecycles-compat polyfilled components,
4507 // Unsafe lifecycles should not be invoked for components using the new APIs.
4508
4509
4510 if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
4511 callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's
4512 // process them now.
4513
4514 processUpdateQueue(internalInstance, instance, newProps, maskedLegacyContext);
4515 }
4516 }
4517
4518 // Ids are base 32 strings whose binary representation corresponds to the
4519 // position of a node in a tree.
4520 // Every time the tree forks into multiple children, we add additional bits to
4521 // the left of the sequence that represent the position of the child within the
4522 // current level of children.
4523 //
4524 // 00101 00010001011010101
4525 // ╰─┬─╯ ╰───────┬───────╯
4526 // Fork 5 of 20 Parent id
4527 //
4528 // The leading 0s are important. In the above example, you only need 3 bits to
4529 // represent slot 5. However, you need 5 bits to represent all the forks at
4530 // the current level, so we must account for the empty bits at the end.
4531 //
4532 // For this same reason, slots are 1-indexed instead of 0-indexed. Otherwise,
4533 // the zeroth id at a level would be indistinguishable from its parent.
4534 //
4535 // If a node has only one child, and does not materialize an id (i.e. does not
4536 // contain a useId hook), then we don't need to allocate any space in the
4537 // sequence. It's treated as a transparent indirection. For example, these two
4538 // trees produce the same ids:
4539 //
4540 // <> <>
4541 // <Indirection> <A />
4542 // <A /> <B />
4543 // </Indirection> </>
4544 // <B />
4545 // </>
4546 //
4547 // However, we cannot skip any node that materializes an id. Otherwise, a parent
4548 // id that does not fork would be indistinguishable from its child id. For
4549 // example, this tree does not fork, but the parent and child must have
4550 // different ids.
4551 //
4552 // <Parent>
4553 // <Child />
4554 // </Parent>
4555 //
4556 // To handle this scenario, every time we materialize an id, we allocate a
4557 // new level with a single slot. You can think of this as a fork with only one
4558 // prong, or an array of children with length 1.
4559 //
4560 // It's possible for the size of the sequence to exceed 32 bits, the max
4561 // size for bitwise operations. When this happens, we make more room by
4562 // converting the right part of the id to a string and storing it in an overflow
4563 // variable. We use a base 32 string representation, because 32 is the largest
4564 // power of 2 that is supported by toString(). We want the base to be large so
4565 // that the resulting ids are compact, and we want the base to be a power of 2
4566 // because every log2(base) bits corresponds to a single character, i.e. every
4567 // log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without
4568 // affecting the final result.
4569 var emptyTreeContext = {
4570 id: 1,
4571 overflow: ''
4572 };
4573 function getTreeId(context) {
4574 var overflow = context.overflow;
4575 var idWithLeadingBit = context.id;
4576 var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit);
4577 return id.toString(32) + overflow;
4578 }
4579 function pushTreeContext(baseContext, totalChildren, index) {
4580 var baseIdWithLeadingBit = baseContext.id;
4581 var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part
4582 // of the id; we use it to account for leading 0s.
4583
4584 var baseLength = getBitLength(baseIdWithLeadingBit) - 1;
4585 var baseId = baseIdWithLeadingBit & ~(1 << baseLength);
4586 var slot = index + 1;
4587 var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into
4588 // consideration the leading 1 we use to mark the end of the sequence.
4589
4590 if (length > 30) {
4591 // We overflowed the bitwise-safe range. Fall back to slower algorithm.
4592 // This branch assumes the length of the base id is greater than 5; it won't
4593 // work for smaller ids, because you need 5 bits per character.
4594 //
4595 // We encode the id in multiple steps: first the base id, then the
4596 // remaining digits.
4597 //
4598 // Each 5 bit sequence corresponds to a single base 32 character. So for
4599 // example, if the current id is 23 bits long, we can convert 20 of those
4600 // bits into a string of 4 characters, with 3 bits left over.
4601 //
4602 // First calculate how many bits in the base id represent a complete
4603 // sequence of characters.
4604 var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits.
4605
4606 var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string.
4607
4608 var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id.
4609
4610 var restOfBaseId = baseId >> numberOfOverflowBits;
4611 var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because
4612 // we made more room, this time it won't overflow.
4613
4614 var restOfLength = getBitLength(totalChildren) + restOfBaseLength;
4615 var restOfNewBits = slot << restOfBaseLength;
4616 var id = restOfNewBits | restOfBaseId;
4617 var overflow = newOverflow + baseOverflow;
4618 return {
4619 id: 1 << restOfLength | id,
4620 overflow: overflow
4621 };
4622 } else {
4623 // Normal path
4624 var newBits = slot << baseLength;
4625
4626 var _id = newBits | baseId;
4627
4628 var _overflow = baseOverflow;
4629 return {
4630 id: 1 << length | _id,
4631 overflow: _overflow
4632 };
4633 }
4634 }
4635
4636 function getBitLength(number) {
4637 return 32 - clz32(number);
4638 }
4639
4640 function getLeadingBit(id) {
4641 return 1 << getBitLength(id) - 1;
4642 } // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback.
4643
4644
4645 var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros.
4646 // Based on:
4647 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32
4648
4649 var log = Math.log;
4650 var LN2 = Math.LN2;
4651
4652 function clz32Fallback(x) {
4653 var asUint = x >>> 0;
4654
4655 if (asUint === 0) {
4656 return 32;
4657 }
4658
4659 return 31 - (log(asUint) / LN2 | 0) | 0;
4660 }
4661
4662 /**
4663 * inlined Object.is polyfill to avoid requiring consumers ship their own
4664 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
4665 */
4666 function is(x, y) {
4667 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
4668 ;
4669 }
4670
4671 var objectIs = typeof Object.is === 'function' ? Object.is : is;
4672
4673 var currentlyRenderingComponent = null;
4674 var currentlyRenderingTask = null;
4675 var firstWorkInProgressHook = null;
4676 var workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook
4677
4678 var isReRender = false; // Whether an update was scheduled during the currently executing render pass.
4679
4680 var didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component
4681
4682 var localIdCounter = 0; // Lazily created map of render-phase updates
4683
4684 var renderPhaseUpdates = null; // Counter to prevent infinite loops.
4685
4686 var numberOfReRenders = 0;
4687 var RE_RENDER_LIMIT = 25;
4688 var isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook
4689
4690 var currentHookNameInDev;
4691
4692 function resolveCurrentlyRenderingComponent() {
4693 if (currentlyRenderingComponent === null) {
4694 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.');
4695 }
4696
4697 {
4698 if (isInHookUserCodeInDev) {
4699 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');
4700 }
4701 }
4702
4703 return currentlyRenderingComponent;
4704 }
4705
4706 function areHookInputsEqual(nextDeps, prevDeps) {
4707 if (prevDeps === null) {
4708 {
4709 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);
4710 }
4711
4712 return false;
4713 }
4714
4715 {
4716 // Don't bother comparing lengths in prod because these arrays should be
4717 // passed inline.
4718 if (nextDeps.length !== prevDeps.length) {
4719 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, "[" + nextDeps.join(', ') + "]", "[" + prevDeps.join(', ') + "]");
4720 }
4721 }
4722
4723 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
4724 if (objectIs(nextDeps[i], prevDeps[i])) {
4725 continue;
4726 }
4727
4728 return false;
4729 }
4730
4731 return true;
4732 }
4733
4734 function createHook() {
4735 if (numberOfReRenders > 0) {
4736 throw new Error('Rendered more hooks than during the previous render');
4737 }
4738
4739 return {
4740 memoizedState: null,
4741 queue: null,
4742 next: null
4743 };
4744 }
4745
4746 function createWorkInProgressHook() {
4747 if (workInProgressHook === null) {
4748 // This is the first hook in the list
4749 if (firstWorkInProgressHook === null) {
4750 isReRender = false;
4751 firstWorkInProgressHook = workInProgressHook = createHook();
4752 } else {
4753 // There's already a work-in-progress. Reuse it.
4754 isReRender = true;
4755 workInProgressHook = firstWorkInProgressHook;
4756 }
4757 } else {
4758 if (workInProgressHook.next === null) {
4759 isReRender = false; // Append to the end of the list
4760
4761 workInProgressHook = workInProgressHook.next = createHook();
4762 } else {
4763 // There's already a work-in-progress. Reuse it.
4764 isReRender = true;
4765 workInProgressHook = workInProgressHook.next;
4766 }
4767 }
4768
4769 return workInProgressHook;
4770 }
4771
4772 function prepareToUseHooks(task, componentIdentity) {
4773 currentlyRenderingComponent = componentIdentity;
4774 currentlyRenderingTask = task;
4775
4776 {
4777 isInHookUserCodeInDev = false;
4778 } // The following should have already been reset
4779 // didScheduleRenderPhaseUpdate = false;
4780 // localIdCounter = 0;
4781 // firstWorkInProgressHook = null;
4782 // numberOfReRenders = 0;
4783 // renderPhaseUpdates = null;
4784 // workInProgressHook = null;
4785
4786
4787 localIdCounter = 0;
4788 }
4789 function finishHooks(Component, props, children, refOrContext) {
4790 // This must be called after every function component to prevent hooks from
4791 // being used in classes.
4792 while (didScheduleRenderPhaseUpdate) {
4793 // Updates were scheduled during the render phase. They are stored in
4794 // the `renderPhaseUpdates` map. Call the component again, reusing the
4795 // work-in-progress hooks and applying the additional updates on top. Keep
4796 // restarting until no more updates are scheduled.
4797 didScheduleRenderPhaseUpdate = false;
4798 localIdCounter = 0;
4799 numberOfReRenders += 1; // Start over from the beginning of the list
4800
4801 workInProgressHook = null;
4802 children = Component(props, refOrContext);
4803 }
4804
4805 resetHooksState();
4806 return children;
4807 }
4808 function checkDidRenderIdHook() {
4809 // This should be called immediately after every finishHooks call.
4810 // Conceptually, it's part of the return value of finishHooks; it's only a
4811 // separate function to avoid using an array tuple.
4812 var didRenderIdHook = localIdCounter !== 0;
4813 return didRenderIdHook;
4814 } // Reset the internal hooks state if an error occurs while rendering a component
4815
4816 function resetHooksState() {
4817 {
4818 isInHookUserCodeInDev = false;
4819 }
4820
4821 currentlyRenderingComponent = null;
4822 currentlyRenderingTask = null;
4823 didScheduleRenderPhaseUpdate = false;
4824 firstWorkInProgressHook = null;
4825 numberOfReRenders = 0;
4826 renderPhaseUpdates = null;
4827 workInProgressHook = null;
4828 }
4829
4830 function readContext$1(context) {
4831 {
4832 if (isInHookUserCodeInDev) {
4833 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().');
4834 }
4835 }
4836
4837 return readContext(context);
4838 }
4839
4840 function useContext(context) {
4841 {
4842 currentHookNameInDev = 'useContext';
4843 }
4844
4845 resolveCurrentlyRenderingComponent();
4846 return readContext(context);
4847 }
4848
4849 function basicStateReducer(state, action) {
4850 // $FlowFixMe: Flow doesn't like mixed types
4851 return typeof action === 'function' ? action(state) : action;
4852 }
4853
4854 function useState(initialState) {
4855 {
4856 currentHookNameInDev = 'useState';
4857 }
4858
4859 return useReducer(basicStateReducer, // useReducer has a special case to support lazy useState initializers
4860 initialState);
4861 }
4862 function useReducer(reducer, initialArg, init) {
4863 {
4864 if (reducer !== basicStateReducer) {
4865 currentHookNameInDev = 'useReducer';
4866 }
4867 }
4868
4869 currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
4870 workInProgressHook = createWorkInProgressHook();
4871
4872 if (isReRender) {
4873 // This is a re-render. Apply the new render phase updates to the previous
4874 // current hook.
4875 var queue = workInProgressHook.queue;
4876 var dispatch = queue.dispatch;
4877
4878 if (renderPhaseUpdates !== null) {
4879 // Render phase updates are stored in a map of queue -> linked list
4880 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
4881
4882 if (firstRenderPhaseUpdate !== undefined) {
4883 renderPhaseUpdates.delete(queue);
4884 var newState = workInProgressHook.memoizedState;
4885 var update = firstRenderPhaseUpdate;
4886
4887 do {
4888 // Process this render phase update. We don't have to check the
4889 // priority because it will always be the same as the current
4890 // render's.
4891 var action = update.action;
4892
4893 {
4894 isInHookUserCodeInDev = true;
4895 }
4896
4897 newState = reducer(newState, action);
4898
4899 {
4900 isInHookUserCodeInDev = false;
4901 }
4902
4903 update = update.next;
4904 } while (update !== null);
4905
4906 workInProgressHook.memoizedState = newState;
4907 return [newState, dispatch];
4908 }
4909 }
4910
4911 return [workInProgressHook.memoizedState, dispatch];
4912 } else {
4913 {
4914 isInHookUserCodeInDev = true;
4915 }
4916
4917 var initialState;
4918
4919 if (reducer === basicStateReducer) {
4920 // Special case for `useState`.
4921 initialState = typeof initialArg === 'function' ? initialArg() : initialArg;
4922 } else {
4923 initialState = init !== undefined ? init(initialArg) : initialArg;
4924 }
4925
4926 {
4927 isInHookUserCodeInDev = false;
4928 }
4929
4930 workInProgressHook.memoizedState = initialState;
4931
4932 var _queue = workInProgressHook.queue = {
4933 last: null,
4934 dispatch: null
4935 };
4936
4937 var _dispatch = _queue.dispatch = dispatchAction.bind(null, currentlyRenderingComponent, _queue);
4938
4939 return [workInProgressHook.memoizedState, _dispatch];
4940 }
4941 }
4942
4943 function useMemo(nextCreate, deps) {
4944 currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
4945 workInProgressHook = createWorkInProgressHook();
4946 var nextDeps = deps === undefined ? null : deps;
4947
4948 if (workInProgressHook !== null) {
4949 var prevState = workInProgressHook.memoizedState;
4950
4951 if (prevState !== null) {
4952 if (nextDeps !== null) {
4953 var prevDeps = prevState[1];
4954
4955 if (areHookInputsEqual(nextDeps, prevDeps)) {
4956 return prevState[0];
4957 }
4958 }
4959 }
4960 }
4961
4962 {
4963 isInHookUserCodeInDev = true;
4964 }
4965
4966 var nextValue = nextCreate();
4967
4968 {
4969 isInHookUserCodeInDev = false;
4970 }
4971
4972 workInProgressHook.memoizedState = [nextValue, nextDeps];
4973 return nextValue;
4974 }
4975
4976 function useRef(initialValue) {
4977 currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
4978 workInProgressHook = createWorkInProgressHook();
4979 var previousRef = workInProgressHook.memoizedState;
4980
4981 if (previousRef === null) {
4982 var ref = {
4983 current: initialValue
4984 };
4985
4986 {
4987 Object.seal(ref);
4988 }
4989
4990 workInProgressHook.memoizedState = ref;
4991 return ref;
4992 } else {
4993 return previousRef;
4994 }
4995 }
4996
4997 function useLayoutEffect(create, inputs) {
4998 {
4999 currentHookNameInDev = 'useLayoutEffect';
5000
5001 error('useLayoutEffect does nothing on the server, because its effect cannot ' + "be encoded into the server renderer's output format. This will lead " + 'to a mismatch between the initial, non-hydrated UI and the intended ' + 'UI. To avoid this, useLayoutEffect should only be used in ' + 'components that render exclusively on the client. ' + 'See https://reactjs.org/link/uselayouteffect-ssr for common fixes.');
5002 }
5003 }
5004
5005 function dispatchAction(componentIdentity, queue, action) {
5006 if (numberOfReRenders >= RE_RENDER_LIMIT) {
5007 throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.');
5008 }
5009
5010 if (componentIdentity === currentlyRenderingComponent) {
5011 // This is a render phase update. Stash it in a lazily-created map of
5012 // queue -> linked list of updates. After this render pass, we'll restart
5013 // and apply the stashed updates on top of the work-in-progress hook.
5014 didScheduleRenderPhaseUpdate = true;
5015 var update = {
5016 action: action,
5017 next: null
5018 };
5019
5020 if (renderPhaseUpdates === null) {
5021 renderPhaseUpdates = new Map();
5022 }
5023
5024 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
5025
5026 if (firstRenderPhaseUpdate === undefined) {
5027 renderPhaseUpdates.set(queue, update);
5028 } else {
5029 // Append the update to the end of the list.
5030 var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
5031
5032 while (lastRenderPhaseUpdate.next !== null) {
5033 lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
5034 }
5035
5036 lastRenderPhaseUpdate.next = update;
5037 }
5038 }
5039 }
5040
5041 function useCallback(callback, deps) {
5042 return useMemo(function () {
5043 return callback;
5044 }, deps);
5045 } // TODO Decide on how to implement this hook for server rendering.
5046 // If a mutation occurs during render, consider triggering a Suspense boundary
5047 // and falling back to client rendering.
5048
5049 function useMutableSource(source, getSnapshot, subscribe) {
5050 resolveCurrentlyRenderingComponent();
5051 return getSnapshot(source._source);
5052 }
5053
5054 function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
5055 if (getServerSnapshot === undefined) {
5056 throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.');
5057 }
5058
5059 return getServerSnapshot();
5060 }
5061
5062 function useDeferredValue(value) {
5063 resolveCurrentlyRenderingComponent();
5064 return value;
5065 }
5066
5067 function unsupportedStartTransition() {
5068 throw new Error('startTransition cannot be called during server rendering.');
5069 }
5070
5071 function useTransition() {
5072 resolveCurrentlyRenderingComponent();
5073 return [false, unsupportedStartTransition];
5074 }
5075
5076 function useId() {
5077 var task = currentlyRenderingTask;
5078 var treeId = getTreeId(task.treeContext);
5079 var responseState = currentResponseState;
5080
5081 if (responseState === null) {
5082 throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component.');
5083 }
5084
5085 var localId = localIdCounter++;
5086 return makeId(responseState, treeId, localId);
5087 }
5088
5089 function noop() {}
5090
5091 var Dispatcher = {
5092 readContext: readContext$1,
5093 useContext: useContext,
5094 useMemo: useMemo,
5095 useReducer: useReducer,
5096 useRef: useRef,
5097 useState: useState,
5098 useInsertionEffect: noop,
5099 useLayoutEffect: useLayoutEffect,
5100 useCallback: useCallback,
5101 // useImperativeHandle is not run in the server environment
5102 useImperativeHandle: noop,
5103 // Effects are not run in the server environment.
5104 useEffect: noop,
5105 // Debugging effect
5106 useDebugValue: noop,
5107 useDeferredValue: useDeferredValue,
5108 useTransition: useTransition,
5109 useId: useId,
5110 // Subscriptions are not setup in a server environment.
5111 useMutableSource: useMutableSource,
5112 useSyncExternalStore: useSyncExternalStore
5113 };
5114
5115 var currentResponseState = null;
5116 function setCurrentResponseState(responseState) {
5117 currentResponseState = responseState;
5118 }
5119
5120 function getStackByComponentStackNode(componentStack) {
5121 try {
5122 var info = '';
5123 var node = componentStack;
5124
5125 do {
5126 switch (node.tag) {
5127 case 0:
5128 info += describeBuiltInComponentFrame(node.type, null, null);
5129 break;
5130
5131 case 1:
5132 info += describeFunctionComponentFrame(node.type, null, null);
5133 break;
5134
5135 case 2:
5136 info += describeClassComponentFrame(node.type, null, null);
5137 break;
5138 }
5139
5140 node = node.parent;
5141 } while (node);
5142
5143 return info;
5144 } catch (x) {
5145 return '\nError generating stack: ' + x.message + '\n' + x.stack;
5146 }
5147 }
5148
5149 var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
5150 var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
5151 var PENDING = 0;
5152 var COMPLETED = 1;
5153 var FLUSHED = 2;
5154 var ABORTED = 3;
5155 var ERRORED = 4;
5156 var OPEN = 0;
5157 var CLOSING = 1;
5158 var CLOSED = 2;
5159 // This is a default heuristic for how to split up the HTML content into progressive
5160 // loading. Our goal is to be able to display additional new content about every 500ms.
5161 // Faster than that is unnecessary and should be throttled on the client. It also
5162 // adds unnecessary overhead to do more splits. We don't know if it's a higher or lower
5163 // end device but higher end suffer less from the overhead than lower end does from
5164 // not getting small enough pieces. We error on the side of low end.
5165 // We base this on low end 3G speeds which is about 500kbits per second. We assume
5166 // that there can be a reasonable drop off from max bandwidth which leaves you with
5167 // as little as 80%. We can receive half of that each 500ms - at best. In practice,
5168 // a little bandwidth is lost to processing and contention - e.g. CSS and images that
5169 // are downloaded along with the main content. So we estimate about half of that to be
5170 // the lower end throughput. In other words, we expect that you can at least show
5171 // about 12.5kb of content per 500ms. Not counting starting latency for the first
5172 // paint.
5173 // 500 * 1024 / 8 * .8 * 0.5 / 2
5174 var DEFAULT_PROGRESSIVE_CHUNK_SIZE = 12800;
5175
5176 function defaultErrorHandler(error) {
5177 console['error'](error); // Don't transform to our wrapper
5178 }
5179
5180 function noop$1() {}
5181
5182 function createRequest(children, responseState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError) {
5183 var pingedTasks = [];
5184 var abortSet = new Set();
5185 var request = {
5186 destination: null,
5187 responseState: responseState,
5188 progressiveChunkSize: progressiveChunkSize === undefined ? DEFAULT_PROGRESSIVE_CHUNK_SIZE : progressiveChunkSize,
5189 status: OPEN,
5190 fatalError: null,
5191 nextSegmentId: 0,
5192 allPendingTasks: 0,
5193 pendingRootTasks: 0,
5194 completedRootSegment: null,
5195 abortableTasks: abortSet,
5196 pingedTasks: pingedTasks,
5197 clientRenderedBoundaries: [],
5198 completedBoundaries: [],
5199 partialBoundaries: [],
5200 onError: onError === undefined ? defaultErrorHandler : onError,
5201 onAllReady: onAllReady === undefined ? noop$1 : onAllReady,
5202 onShellReady: onShellReady === undefined ? noop$1 : onShellReady,
5203 onShellError: onShellError === undefined ? noop$1 : onShellError,
5204 onFatalError: onFatalError === undefined ? noop$1 : onFatalError
5205 }; // This segment represents the root fallback.
5206
5207 var rootSegment = createPendingSegment(request, 0, null, rootFormatContext); // There is no parent so conceptually, we're unblocked to flush this segment.
5208
5209 rootSegment.parentFlushed = true;
5210 var rootTask = createTask(request, children, null, rootSegment, abortSet, emptyContextObject, rootContextSnapshot, emptyTreeContext);
5211 pingedTasks.push(rootTask);
5212 return request;
5213 }
5214
5215 function pingTask(request, task) {
5216 var pingedTasks = request.pingedTasks;
5217 pingedTasks.push(task);
5218
5219 if (pingedTasks.length === 1) {
5220 scheduleWork(function () {
5221 return performWork(request);
5222 });
5223 }
5224 }
5225
5226 function createSuspenseBoundary(request, fallbackAbortableTasks) {
5227 return {
5228 id: UNINITIALIZED_SUSPENSE_BOUNDARY_ID,
5229 rootSegmentID: -1,
5230 parentFlushed: false,
5231 pendingTasks: 0,
5232 forceClientRender: false,
5233 completedSegments: [],
5234 byteSize: 0,
5235 fallbackAbortableTasks: fallbackAbortableTasks
5236 };
5237 }
5238
5239 function createTask(request, node, blockedBoundary, blockedSegment, abortSet, legacyContext, context, treeContext) {
5240 request.allPendingTasks++;
5241
5242 if (blockedBoundary === null) {
5243 request.pendingRootTasks++;
5244 } else {
5245 blockedBoundary.pendingTasks++;
5246 }
5247
5248 var task = {
5249 node: node,
5250 ping: function () {
5251 return pingTask(request, task);
5252 },
5253 blockedBoundary: blockedBoundary,
5254 blockedSegment: blockedSegment,
5255 abortSet: abortSet,
5256 legacyContext: legacyContext,
5257 context: context,
5258 treeContext: treeContext
5259 };
5260
5261 {
5262 task.componentStack = null;
5263 }
5264
5265 abortSet.add(task);
5266 return task;
5267 }
5268
5269 function createPendingSegment(request, index, boundary, formatContext) {
5270 return {
5271 status: PENDING,
5272 id: -1,
5273 // lazily assigned later
5274 index: index,
5275 parentFlushed: false,
5276 chunks: [],
5277 children: [],
5278 formatContext: formatContext,
5279 boundary: boundary
5280 };
5281 } // DEV-only global reference to the currently executing task
5282
5283
5284 var currentTaskInDEV = null;
5285
5286 function getCurrentStackInDEV() {
5287 {
5288 if (currentTaskInDEV === null || currentTaskInDEV.componentStack === null) {
5289 return '';
5290 }
5291
5292 return getStackByComponentStackNode(currentTaskInDEV.componentStack);
5293 }
5294 }
5295
5296 function pushBuiltInComponentStackInDEV(task, type) {
5297 {
5298 task.componentStack = {
5299 tag: 0,
5300 parent: task.componentStack,
5301 type: type
5302 };
5303 }
5304 }
5305
5306 function pushFunctionComponentStackInDEV(task, type) {
5307 {
5308 task.componentStack = {
5309 tag: 1,
5310 parent: task.componentStack,
5311 type: type
5312 };
5313 }
5314 }
5315
5316 function pushClassComponentStackInDEV(task, type) {
5317 {
5318 task.componentStack = {
5319 tag: 2,
5320 parent: task.componentStack,
5321 type: type
5322 };
5323 }
5324 }
5325
5326 function popComponentStackInDEV(task) {
5327 {
5328 if (task.componentStack === null) {
5329 error('Unexpectedly popped too many stack frames. This is a bug in React.');
5330 } else {
5331 task.componentStack = task.componentStack.parent;
5332 }
5333 }
5334 }
5335
5336 function logRecoverableError(request, error) {
5337 // If this callback errors, we intentionally let that error bubble up to become a fatal error
5338 // so that someone fixes the error reporting instead of hiding it.
5339 var onError = request.onError;
5340 onError(error);
5341 }
5342
5343 function fatalError(request, error) {
5344 // This is called outside error handling code such as if the root errors outside
5345 // a suspense boundary or if the root suspense boundary's fallback errors.
5346 // It's also called if React itself or its host configs errors.
5347 var onShellError = request.onShellError;
5348 onShellError(error);
5349 var onFatalError = request.onFatalError;
5350 onFatalError(error);
5351
5352 if (request.destination !== null) {
5353 request.status = CLOSED;
5354 closeWithError(request.destination, error);
5355 } else {
5356 request.status = CLOSING;
5357 request.fatalError = error;
5358 }
5359 }
5360
5361 function renderSuspenseBoundary(request, task, props) {
5362 pushBuiltInComponentStackInDEV(task, 'Suspense');
5363 var parentBoundary = task.blockedBoundary;
5364 var parentSegment = task.blockedSegment; // Each time we enter a suspense boundary, we split out into a new segment for
5365 // the fallback so that we can later replace that segment with the content.
5366 // This also lets us split out the main content even if it doesn't suspend,
5367 // in case it ends up generating a large subtree of content.
5368
5369 var fallback = props.fallback;
5370 var content = props.children;
5371 var fallbackAbortSet = new Set();
5372 var newBoundary = createSuspenseBoundary(request, fallbackAbortSet);
5373 var insertionIndex = parentSegment.chunks.length; // The children of the boundary segment is actually the fallback.
5374
5375 var boundarySegment = createPendingSegment(request, insertionIndex, newBoundary, parentSegment.formatContext);
5376 parentSegment.children.push(boundarySegment); // This segment is the actual child content. We can start rendering that immediately.
5377
5378 var contentRootSegment = createPendingSegment(request, 0, null, parentSegment.formatContext); // We mark the root segment as having its parent flushed. It's not really flushed but there is
5379 // no parent segment so there's nothing to wait on.
5380
5381 contentRootSegment.parentFlushed = true; // Currently this is running synchronously. We could instead schedule this to pingedTasks.
5382 // I suspect that there might be some efficiency benefits from not creating the suspended task
5383 // and instead just using the stack if possible.
5384 // TODO: Call this directly instead of messing with saving and restoring contexts.
5385 // We can reuse the current context and task to render the content immediately without
5386 // context switching. We just need to temporarily switch which boundary and which segment
5387 // we're writing to. If something suspends, it'll spawn new suspended task with that context.
5388
5389 task.blockedBoundary = newBoundary;
5390 task.blockedSegment = contentRootSegment;
5391
5392 try {
5393 // We use the safe form because we don't handle suspending here. Only error handling.
5394 renderNode(request, task, content);
5395 contentRootSegment.status = COMPLETED;
5396 queueCompletedSegment(newBoundary, contentRootSegment);
5397
5398 if (newBoundary.pendingTasks === 0) {
5399 // This must have been the last segment we were waiting on. This boundary is now complete.
5400 // Therefore we won't need the fallback. We early return so that we don't have to create
5401 // the fallback.
5402 popComponentStackInDEV(task);
5403 return;
5404 }
5405 } catch (error) {
5406 contentRootSegment.status = ERRORED;
5407 logRecoverableError(request, error);
5408 newBoundary.forceClientRender = true; // We don't need to decrement any task numbers because we didn't spawn any new task.
5409 // We don't need to schedule any task because we know the parent has written yet.
5410 // We do need to fallthrough to create the fallback though.
5411 } finally {
5412 task.blockedBoundary = parentBoundary;
5413 task.blockedSegment = parentSegment;
5414 } // We create suspended task for the fallback because we don't want to actually work
5415 // on it yet in case we finish the main content, so we queue for later.
5416
5417
5418 var suspendedFallbackTask = createTask(request, fallback, parentBoundary, boundarySegment, fallbackAbortSet, task.legacyContext, task.context, task.treeContext);
5419
5420 {
5421 suspendedFallbackTask.componentStack = task.componentStack;
5422 } // TODO: This should be queued at a separate lower priority queue so that we only work
5423 // on preparing fallbacks if we don't have any more main content to task on.
5424
5425
5426 request.pingedTasks.push(suspendedFallbackTask);
5427 popComponentStackInDEV(task);
5428 }
5429
5430 function renderHostElement(request, task, type, props) {
5431 pushBuiltInComponentStackInDEV(task, type);
5432 var segment = task.blockedSegment;
5433 var children = pushStartInstance(segment.chunks, type, props, request.responseState, segment.formatContext);
5434 var prevContext = segment.formatContext;
5435 segment.formatContext = getChildFormatContext(prevContext, type, props); // We use the non-destructive form because if something suspends, we still
5436 // need to pop back up and finish this subtree of HTML.
5437
5438 renderNode(request, task, children); // We expect that errors will fatal the whole task and that we don't need
5439 // the correct context. Therefore this is not in a finally.
5440
5441 segment.formatContext = prevContext;
5442 pushEndInstance(segment.chunks, type);
5443 popComponentStackInDEV(task);
5444 }
5445
5446 function shouldConstruct$1(Component) {
5447 return Component.prototype && Component.prototype.isReactComponent;
5448 }
5449
5450 function renderWithHooks(request, task, Component, props, secondArg) {
5451 var componentIdentity = {};
5452 prepareToUseHooks(task, componentIdentity);
5453 var result = Component(props, secondArg);
5454 return finishHooks(Component, props, result, secondArg);
5455 }
5456
5457 function finishClassComponent(request, task, instance, Component, props) {
5458 var nextChildren = instance.render();
5459
5460 {
5461 if (instance.props !== props) {
5462 if (!didWarnAboutReassigningProps) {
5463 error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromType(Component) || 'a component');
5464 }
5465
5466 didWarnAboutReassigningProps = true;
5467 }
5468 }
5469
5470 {
5471 var childContextTypes = Component.childContextTypes;
5472
5473 if (childContextTypes !== null && childContextTypes !== undefined) {
5474 var previousContext = task.legacyContext;
5475 var mergedContext = processChildContext(instance, Component, previousContext, childContextTypes);
5476 task.legacyContext = mergedContext;
5477 renderNodeDestructive(request, task, nextChildren);
5478 task.legacyContext = previousContext;
5479 return;
5480 }
5481 }
5482
5483 renderNodeDestructive(request, task, nextChildren);
5484 }
5485
5486 function renderClassComponent(request, task, Component, props) {
5487 pushClassComponentStackInDEV(task, Component);
5488 var maskedContext = getMaskedContext(Component, task.legacyContext) ;
5489 var instance = constructClassInstance(Component, props, maskedContext);
5490 mountClassInstance(instance, Component, props, maskedContext);
5491 finishClassComponent(request, task, instance, Component, props);
5492 popComponentStackInDEV(task);
5493 }
5494
5495 var didWarnAboutBadClass = {};
5496 var didWarnAboutModulePatternComponent = {};
5497 var didWarnAboutContextTypeOnFunctionComponent = {};
5498 var didWarnAboutGetDerivedStateOnFunctionComponent = {};
5499 var didWarnAboutReassigningProps = false;
5500 var didWarnAboutGenerators = false;
5501 var didWarnAboutMaps = false;
5502 var hasWarnedAboutUsingContextAsConsumer = false; // This would typically be a function component but we still support module pattern
5503 // components for some reason.
5504
5505 function renderIndeterminateComponent(request, task, Component, props) {
5506 var legacyContext;
5507
5508 {
5509 legacyContext = getMaskedContext(Component, task.legacyContext);
5510 }
5511
5512 pushFunctionComponentStackInDEV(task, Component);
5513
5514 {
5515 if (Component.prototype && typeof Component.prototype.render === 'function') {
5516 var componentName = getComponentNameFromType(Component) || 'Unknown';
5517
5518 if (!didWarnAboutBadClass[componentName]) {
5519 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);
5520
5521 didWarnAboutBadClass[componentName] = true;
5522 }
5523 }
5524 }
5525
5526 var value = renderWithHooks(request, task, Component, props, legacyContext);
5527 var hasId = checkDidRenderIdHook();
5528
5529 {
5530 // Support for module components is deprecated and is removed behind a flag.
5531 // Whether or not it would crash later, we want to show a good message in DEV first.
5532 if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
5533 var _componentName = getComponentNameFromType(Component) || 'Unknown';
5534
5535 if (!didWarnAboutModulePatternComponent[_componentName]) {
5536 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);
5537
5538 didWarnAboutModulePatternComponent[_componentName] = true;
5539 }
5540 }
5541 }
5542
5543 if ( // Run these checks in production only if the flag is off.
5544 // Eventually we'll delete this branch altogether.
5545 typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
5546 {
5547 var _componentName2 = getComponentNameFromType(Component) || 'Unknown';
5548
5549 if (!didWarnAboutModulePatternComponent[_componentName2]) {
5550 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);
5551
5552 didWarnAboutModulePatternComponent[_componentName2] = true;
5553 }
5554 }
5555
5556 mountClassInstance(value, Component, props, legacyContext);
5557 finishClassComponent(request, task, value, Component, props);
5558 } else {
5559
5560 {
5561 validateFunctionComponentInDev(Component);
5562 } // We're now successfully past this task, and we don't have to pop back to
5563 // the previous task every again, so we can use the destructive recursive form.
5564
5565
5566 if (hasId) {
5567 // This component materialized an id. We treat this as its own level, with
5568 // a single "child" slot.
5569 var prevTreeContext = task.treeContext;
5570 var totalChildren = 1;
5571 var index = 0;
5572 task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index);
5573
5574 try {
5575 renderNodeDestructive(request, task, value);
5576 } finally {
5577 task.treeContext = prevTreeContext;
5578 }
5579 } else {
5580 renderNodeDestructive(request, task, value);
5581 }
5582 }
5583
5584 popComponentStackInDEV(task);
5585 }
5586
5587 function validateFunctionComponentInDev(Component) {
5588 {
5589 if (Component) {
5590 if (Component.childContextTypes) {
5591 error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component');
5592 }
5593 }
5594
5595 if (typeof Component.getDerivedStateFromProps === 'function') {
5596 var _componentName3 = getComponentNameFromType(Component) || 'Unknown';
5597
5598 if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) {
5599 error('%s: Function components do not support getDerivedStateFromProps.', _componentName3);
5600
5601 didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true;
5602 }
5603 }
5604
5605 if (typeof Component.contextType === 'object' && Component.contextType !== null) {
5606 var _componentName4 = getComponentNameFromType(Component) || 'Unknown';
5607
5608 if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) {
5609 error('%s: Function components do not support contextType.', _componentName4);
5610
5611 didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true;
5612 }
5613 }
5614 }
5615 }
5616
5617 function resolveDefaultProps(Component, baseProps) {
5618 if (Component && Component.defaultProps) {
5619 // Resolve default props. Taken from ReactElement
5620 var props = assign({}, baseProps);
5621 var defaultProps = Component.defaultProps;
5622
5623 for (var propName in defaultProps) {
5624 if (props[propName] === undefined) {
5625 props[propName] = defaultProps[propName];
5626 }
5627 }
5628
5629 return props;
5630 }
5631
5632 return baseProps;
5633 }
5634
5635 function renderForwardRef(request, task, type, props, ref) {
5636 pushFunctionComponentStackInDEV(task, type.render);
5637 var children = renderWithHooks(request, task, type.render, props, ref);
5638 var hasId = checkDidRenderIdHook();
5639
5640 if (hasId) {
5641 // This component materialized an id. We treat this as its own level, with
5642 // a single "child" slot.
5643 var prevTreeContext = task.treeContext;
5644 var totalChildren = 1;
5645 var index = 0;
5646 task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index);
5647
5648 try {
5649 renderNodeDestructive(request, task, children);
5650 } finally {
5651 task.treeContext = prevTreeContext;
5652 }
5653 } else {
5654 renderNodeDestructive(request, task, children);
5655 }
5656
5657 popComponentStackInDEV(task);
5658 }
5659
5660 function renderMemo(request, task, type, props, ref) {
5661 var innerType = type.type;
5662 var resolvedProps = resolveDefaultProps(innerType, props);
5663 renderElement(request, task, innerType, resolvedProps, ref);
5664 }
5665
5666 function renderContextConsumer(request, task, context, props) {
5667 // The logic below for Context differs depending on PROD or DEV mode. In
5668 // DEV mode, we create a separate object for Context.Consumer that acts
5669 // like a proxy to Context. This proxy object adds unnecessary code in PROD
5670 // so we use the old behaviour (Context.Consumer references Context) to
5671 // reduce size and overhead. The separate object references context via
5672 // a property called "_context", which also gives us the ability to check
5673 // in DEV mode if this property exists or not and warn if it does not.
5674 {
5675 if (context._context === undefined) {
5676 // This may be because it's a Context (rather than a Consumer).
5677 // Or it may be because it's older React where they're the same thing.
5678 // We only want to warn if we're sure it's a new React.
5679 if (context !== context.Consumer) {
5680 if (!hasWarnedAboutUsingContextAsConsumer) {
5681 hasWarnedAboutUsingContextAsConsumer = true;
5682
5683 error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
5684 }
5685 }
5686 } else {
5687 context = context._context;
5688 }
5689 }
5690
5691 var render = props.children;
5692
5693 {
5694 if (typeof render !== 'function') {
5695 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.');
5696 }
5697 }
5698
5699 var newValue = readContext(context);
5700 var newChildren = render(newValue);
5701 renderNodeDestructive(request, task, newChildren);
5702 }
5703
5704 function renderContextProvider(request, task, type, props) {
5705 var context = type._context;
5706 var value = props.value;
5707 var children = props.children;
5708 var prevSnapshot;
5709
5710 {
5711 prevSnapshot = task.context;
5712 }
5713
5714 task.context = pushProvider(context, value);
5715 renderNodeDestructive(request, task, children);
5716 task.context = popProvider(context);
5717
5718 {
5719 if (prevSnapshot !== task.context) {
5720 error('Popping the context provider did not return back to the original snapshot. This is a bug in React.');
5721 }
5722 }
5723 }
5724
5725 function renderLazyComponent(request, task, lazyComponent, props, ref) {
5726 pushBuiltInComponentStackInDEV(task, 'Lazy');
5727 var payload = lazyComponent._payload;
5728 var init = lazyComponent._init;
5729 var Component = init(payload);
5730 var resolvedProps = resolveDefaultProps(Component, props);
5731 renderElement(request, task, Component, resolvedProps, ref);
5732 popComponentStackInDEV(task);
5733 }
5734
5735 function renderElement(request, task, type, props, ref) {
5736 if (typeof type === 'function') {
5737 if (shouldConstruct$1(type)) {
5738 renderClassComponent(request, task, type, props);
5739 return;
5740 } else {
5741 renderIndeterminateComponent(request, task, type, props);
5742 return;
5743 }
5744 }
5745
5746 if (typeof type === 'string') {
5747 renderHostElement(request, task, type, props);
5748 return;
5749 }
5750
5751 switch (type) {
5752 // TODO: LegacyHidden acts the same as a fragment. This only works
5753 // because we currently assume that every instance of LegacyHidden is
5754 // accompanied by a host component wrapper. In the hidden mode, the host
5755 // component is given a `hidden` attribute, which ensures that the
5756 // initial HTML is not visible. To support the use of LegacyHidden as a
5757 // true fragment, without an extra DOM node, we would have to hide the
5758 // initial HTML in some other way.
5759 // TODO: Add REACT_OFFSCREEN_TYPE here too with the same capability.
5760 case REACT_LEGACY_HIDDEN_TYPE:
5761 case REACT_DEBUG_TRACING_MODE_TYPE:
5762 case REACT_STRICT_MODE_TYPE:
5763 case REACT_PROFILER_TYPE:
5764 case REACT_FRAGMENT_TYPE:
5765 {
5766 renderNodeDestructive(request, task, props.children);
5767 return;
5768 }
5769
5770 case REACT_SUSPENSE_LIST_TYPE:
5771 {
5772 pushBuiltInComponentStackInDEV(task, 'SuspenseList'); // TODO: SuspenseList should control the boundaries.
5773
5774 renderNodeDestructive(request, task, props.children);
5775 popComponentStackInDEV(task);
5776 return;
5777 }
5778
5779 case REACT_SCOPE_TYPE:
5780 {
5781
5782 throw new Error('ReactDOMServer does not yet support scope components.');
5783 }
5784 // eslint-disable-next-line-no-fallthrough
5785
5786 case REACT_SUSPENSE_TYPE:
5787 {
5788 {
5789 renderSuspenseBoundary(request, task, props);
5790 }
5791
5792 return;
5793 }
5794 }
5795
5796 if (typeof type === 'object' && type !== null) {
5797 switch (type.$$typeof) {
5798 case REACT_FORWARD_REF_TYPE:
5799 {
5800 renderForwardRef(request, task, type, props, ref);
5801 return;
5802 }
5803
5804 case REACT_MEMO_TYPE:
5805 {
5806 renderMemo(request, task, type, props, ref);
5807 return;
5808 }
5809
5810 case REACT_PROVIDER_TYPE:
5811 {
5812 renderContextProvider(request, task, type, props);
5813 return;
5814 }
5815
5816 case REACT_CONTEXT_TYPE:
5817 {
5818 renderContextConsumer(request, task, type, props);
5819 return;
5820 }
5821
5822 case REACT_LAZY_TYPE:
5823 {
5824 renderLazyComponent(request, task, type, props);
5825 return;
5826 }
5827 }
5828 }
5829
5830 var info = '';
5831
5832 {
5833 if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
5834 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.';
5835 }
5836 }
5837
5838 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));
5839 }
5840
5841 function validateIterable(iterable, iteratorFn) {
5842 {
5843 // We don't support rendering Generators because it's a mutation.
5844 // See https://github.com/facebook/react/issues/12995
5845 if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag
5846 iterable[Symbol.toStringTag] === 'Generator') {
5847 if (!didWarnAboutGenerators) {
5848 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.');
5849 }
5850
5851 didWarnAboutGenerators = true;
5852 } // Warn about using Maps as children
5853
5854
5855 if (iterable.entries === iteratorFn) {
5856 if (!didWarnAboutMaps) {
5857 error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
5858 }
5859
5860 didWarnAboutMaps = true;
5861 }
5862 }
5863 } // This function by it self renders a node and consumes the task by mutating it
5864 // to update the current execution state.
5865
5866
5867 function renderNodeDestructive(request, task, node) {
5868 // Stash the node we're working on. We'll pick up from this task in case
5869 // something suspends.
5870 task.node = node; // Handle object types
5871
5872 if (typeof node === 'object' && node !== null) {
5873 switch (node.$$typeof) {
5874 case REACT_ELEMENT_TYPE:
5875 {
5876 var element = node;
5877 var type = element.type;
5878 var props = element.props;
5879 var ref = element.ref;
5880 renderElement(request, task, type, props, ref);
5881 return;
5882 }
5883
5884 case REACT_PORTAL_TYPE:
5885 throw new Error('Portals are not currently supported by the server renderer. ' + 'Render them conditionally so that they only appear on the client render.');
5886 // eslint-disable-next-line-no-fallthrough
5887
5888 case REACT_LAZY_TYPE:
5889 {
5890 {
5891 var lazyNode = node;
5892 var payload = lazyNode._payload;
5893 var init = lazyNode._init;
5894 var resolvedNode = init(payload);
5895 renderNodeDestructive(request, task, resolvedNode);
5896 return;
5897 }
5898 }
5899 }
5900
5901 if (isArray(node)) {
5902 renderChildrenArray(request, task, node);
5903 return;
5904 }
5905
5906 var iteratorFn = getIteratorFn(node);
5907
5908 if (iteratorFn) {
5909 {
5910 validateIterable(node, iteratorFn);
5911 }
5912
5913 var iterator = iteratorFn.call(node);
5914
5915 if (iterator) {
5916 // We need to know how many total children are in this set, so that we
5917 // can allocate enough id slots to acommodate them. So we must exhaust
5918 // the iterator before we start recursively rendering the children.
5919 // TODO: This is not great but I think it's inherent to the id
5920 // generation algorithm.
5921 var step = iterator.next(); // If there are not entries, we need to push an empty so we start by checking that.
5922
5923 if (!step.done) {
5924 var children = [];
5925
5926 do {
5927 children.push(step.value);
5928 step = iterator.next();
5929 } while (!step.done);
5930
5931 renderChildrenArray(request, task, children);
5932 return;
5933 }
5934
5935 return;
5936 }
5937 }
5938
5939 var childString = Object.prototype.toString.call(node);
5940 throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(node).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.');
5941 }
5942
5943 if (typeof node === 'string') {
5944 pushTextInstance$1(task.blockedSegment.chunks, node, request.responseState);
5945 return;
5946 }
5947
5948 if (typeof node === 'number') {
5949 pushTextInstance$1(task.blockedSegment.chunks, '' + node, request.responseState);
5950 return;
5951 }
5952
5953 {
5954 if (typeof node === 'function') {
5955 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.');
5956 }
5957 }
5958 }
5959
5960 function renderChildrenArray(request, task, children) {
5961 var totalChildren = children.length;
5962
5963 for (var i = 0; i < totalChildren; i++) {
5964 var prevTreeContext = task.treeContext;
5965 task.treeContext = pushTreeContext(prevTreeContext, totalChildren, i);
5966
5967 try {
5968 // We need to use the non-destructive form so that we can safely pop back
5969 // up and render the sibling if something suspends.
5970 renderNode(request, task, children[i]);
5971 } finally {
5972 task.treeContext = prevTreeContext;
5973 }
5974 }
5975 }
5976
5977 function spawnNewSuspendedTask(request, task, x) {
5978 // Something suspended, we'll need to create a new segment and resolve it later.
5979 var segment = task.blockedSegment;
5980 var insertionIndex = segment.chunks.length;
5981 var newSegment = createPendingSegment(request, insertionIndex, null, segment.formatContext);
5982 segment.children.push(newSegment);
5983 var newTask = createTask(request, task.node, task.blockedBoundary, newSegment, task.abortSet, task.legacyContext, task.context, task.treeContext);
5984
5985 {
5986 if (task.componentStack !== null) {
5987 // We pop one task off the stack because the node that suspended will be tried again,
5988 // which will add it back onto the stack.
5989 newTask.componentStack = task.componentStack.parent;
5990 }
5991 }
5992
5993 var ping = newTask.ping;
5994 x.then(ping, ping);
5995 } // This is a non-destructive form of rendering a node. If it suspends it spawns
5996 // a new task and restores the context of this task to what it was before.
5997
5998
5999 function renderNode(request, task, node) {
6000 // TODO: Store segment.children.length here and reset it in case something
6001 // suspended partially through writing something.
6002 // Snapshot the current context in case something throws to interrupt the
6003 // process.
6004 var previousFormatContext = task.blockedSegment.formatContext;
6005 var previousLegacyContext = task.legacyContext;
6006 var previousContext = task.context;
6007 var previousComponentStack = null;
6008
6009 {
6010 previousComponentStack = task.componentStack;
6011 }
6012
6013 try {
6014 return renderNodeDestructive(request, task, node);
6015 } catch (x) {
6016 resetHooksState();
6017
6018 if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
6019 spawnNewSuspendedTask(request, task, x); // Restore the context. We assume that this will be restored by the inner
6020 // functions in case nothing throws so we don't use "finally" here.
6021
6022 task.blockedSegment.formatContext = previousFormatContext;
6023 task.legacyContext = previousLegacyContext;
6024 task.context = previousContext; // Restore all active ReactContexts to what they were before.
6025
6026 switchContext(previousContext);
6027
6028 {
6029 task.componentStack = previousComponentStack;
6030 }
6031
6032 return;
6033 } else {
6034 // Restore the context. We assume that this will be restored by the inner
6035 // functions in case nothing throws so we don't use "finally" here.
6036 task.blockedSegment.formatContext = previousFormatContext;
6037 task.legacyContext = previousLegacyContext;
6038 task.context = previousContext; // Restore all active ReactContexts to what they were before.
6039
6040 switchContext(previousContext);
6041
6042 {
6043 task.componentStack = previousComponentStack;
6044 } // We assume that we don't need the correct context.
6045 // Let's terminate the rest of the tree and don't render any siblings.
6046
6047
6048 throw x;
6049 }
6050 }
6051 }
6052
6053 function erroredTask(request, boundary, segment, error) {
6054 // Report the error to a global handler.
6055 logRecoverableError(request, error);
6056
6057 if (boundary === null) {
6058 fatalError(request, error);
6059 } else {
6060 boundary.pendingTasks--;
6061
6062 if (!boundary.forceClientRender) {
6063 boundary.forceClientRender = true; // Regardless of what happens next, this boundary won't be displayed,
6064 // so we can flush it, if the parent already flushed.
6065
6066 if (boundary.parentFlushed) {
6067 // We don't have a preference where in the queue this goes since it's likely
6068 // to error on the client anyway. However, intentionally client-rendered
6069 // boundaries should be flushed earlier so that they can start on the client.
6070 // We reuse the same queue for errors.
6071 request.clientRenderedBoundaries.push(boundary);
6072 }
6073 }
6074 }
6075
6076 request.allPendingTasks--;
6077
6078 if (request.allPendingTasks === 0) {
6079 var onAllReady = request.onAllReady;
6080 onAllReady();
6081 }
6082 }
6083
6084 function abortTaskSoft(task) {
6085 // This aborts task without aborting the parent boundary that it blocks.
6086 // It's used for when we didn't need this task to complete the tree.
6087 // If task was needed, then it should use abortTask instead.
6088 var request = this;
6089 var boundary = task.blockedBoundary;
6090 var segment = task.blockedSegment;
6091 segment.status = ABORTED;
6092 finishedTask(request, boundary, segment);
6093 }
6094
6095 function abortTask(task) {
6096 // This aborts the task and aborts the parent that it blocks, putting it into
6097 // client rendered mode.
6098 var request = this;
6099 var boundary = task.blockedBoundary;
6100 var segment = task.blockedSegment;
6101 segment.status = ABORTED;
6102
6103 if (boundary === null) {
6104 request.allPendingTasks--; // We didn't complete the root so we have nothing to show. We can close
6105 // the request;
6106
6107 if (request.status !== CLOSED) {
6108 request.status = CLOSED;
6109
6110 if (request.destination !== null) {
6111 close(request.destination);
6112 }
6113 }
6114 } else {
6115 boundary.pendingTasks--;
6116
6117 if (!boundary.forceClientRender) {
6118 boundary.forceClientRender = true;
6119
6120 if (boundary.parentFlushed) {
6121 request.clientRenderedBoundaries.push(boundary);
6122 }
6123 } // If this boundary was still pending then we haven't already cancelled its fallbacks.
6124 // We'll need to abort the fallbacks, which will also error that parent boundary.
6125
6126
6127 boundary.fallbackAbortableTasks.forEach(abortTask, request);
6128 boundary.fallbackAbortableTasks.clear();
6129 request.allPendingTasks--;
6130
6131 if (request.allPendingTasks === 0) {
6132 var onAllReady = request.onAllReady;
6133 onAllReady();
6134 }
6135 }
6136 }
6137
6138 function queueCompletedSegment(boundary, segment) {
6139 if (segment.chunks.length === 0 && segment.children.length === 1 && segment.children[0].boundary === null) {
6140 // This is an empty segment. There's nothing to write, so we can instead transfer the ID
6141 // to the child. That way any existing references point to the child.
6142 var childSegment = segment.children[0];
6143 childSegment.id = segment.id;
6144 childSegment.parentFlushed = true;
6145
6146 if (childSegment.status === COMPLETED) {
6147 queueCompletedSegment(boundary, childSegment);
6148 }
6149 } else {
6150 var completedSegments = boundary.completedSegments;
6151 completedSegments.push(segment);
6152 }
6153 }
6154
6155 function finishedTask(request, boundary, segment) {
6156 if (boundary === null) {
6157 if (segment.parentFlushed) {
6158 if (request.completedRootSegment !== null) {
6159 throw new Error('There can only be one root segment. This is a bug in React.');
6160 }
6161
6162 request.completedRootSegment = segment;
6163 }
6164
6165 request.pendingRootTasks--;
6166
6167 if (request.pendingRootTasks === 0) {
6168 // We have completed the shell so the shell can't error anymore.
6169 request.onShellError = noop$1;
6170 var onShellReady = request.onShellReady;
6171 onShellReady();
6172 }
6173 } else {
6174 boundary.pendingTasks--;
6175
6176 if (boundary.forceClientRender) ; else if (boundary.pendingTasks === 0) {
6177 // This must have been the last segment we were waiting on. This boundary is now complete.
6178 if (segment.parentFlushed) {
6179 // Our parent segment already flushed, so we need to schedule this segment to be emitted.
6180 // If it is a segment that was aborted, we'll write other content instead so we don't need
6181 // to emit it.
6182 if (segment.status === COMPLETED) {
6183 queueCompletedSegment(boundary, segment);
6184 }
6185 }
6186
6187 if (boundary.parentFlushed) {
6188 // The segment might be part of a segment that didn't flush yet, but if the boundary's
6189 // parent flushed, we need to schedule the boundary to be emitted.
6190 request.completedBoundaries.push(boundary);
6191 } // We can now cancel any pending task on the fallback since we won't need to show it anymore.
6192 // This needs to happen after we read the parentFlushed flags because aborting can finish
6193 // work which can trigger user code, which can start flushing, which can change those flags.
6194
6195
6196 boundary.fallbackAbortableTasks.forEach(abortTaskSoft, request);
6197 boundary.fallbackAbortableTasks.clear();
6198 } else {
6199 if (segment.parentFlushed) {
6200 // Our parent already flushed, so we need to schedule this segment to be emitted.
6201 // If it is a segment that was aborted, we'll write other content instead so we don't need
6202 // to emit it.
6203 if (segment.status === COMPLETED) {
6204 queueCompletedSegment(boundary, segment);
6205 var completedSegments = boundary.completedSegments;
6206
6207 if (completedSegments.length === 1) {
6208 // This is the first time since we last flushed that we completed anything.
6209 // We can schedule this boundary to emit its partially completed segments early
6210 // in case the parent has already been flushed.
6211 if (boundary.parentFlushed) {
6212 request.partialBoundaries.push(boundary);
6213 }
6214 }
6215 }
6216 }
6217 }
6218 }
6219
6220 request.allPendingTasks--;
6221
6222 if (request.allPendingTasks === 0) {
6223 // This needs to be called at the very end so that we can synchronously write the result
6224 // in the callback if needed.
6225 var onAllReady = request.onAllReady;
6226 onAllReady();
6227 }
6228 }
6229
6230 function retryTask(request, task) {
6231 var segment = task.blockedSegment;
6232
6233 if (segment.status !== PENDING) {
6234 // We completed this by other means before we had a chance to retry it.
6235 return;
6236 } // We restore the context to what it was when we suspended.
6237 // We don't restore it after we leave because it's likely that we'll end up
6238 // needing a very similar context soon again.
6239
6240
6241 switchContext(task.context);
6242 var prevTaskInDEV = null;
6243
6244 {
6245 prevTaskInDEV = currentTaskInDEV;
6246 currentTaskInDEV = task;
6247 }
6248
6249 try {
6250 // We call the destructive form that mutates this task. That way if something
6251 // suspends again, we can reuse the same task instead of spawning a new one.
6252 renderNodeDestructive(request, task, task.node);
6253 task.abortSet.delete(task);
6254 segment.status = COMPLETED;
6255 finishedTask(request, task.blockedBoundary, segment);
6256 } catch (x) {
6257 resetHooksState();
6258
6259 if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
6260 // Something suspended again, let's pick it back up later.
6261 var ping = task.ping;
6262 x.then(ping, ping);
6263 } else {
6264 task.abortSet.delete(task);
6265 segment.status = ERRORED;
6266 erroredTask(request, task.blockedBoundary, segment, x);
6267 }
6268 } finally {
6269 {
6270 currentTaskInDEV = prevTaskInDEV;
6271 }
6272 }
6273 }
6274
6275 function performWork(request) {
6276 if (request.status === CLOSED) {
6277 return;
6278 }
6279
6280 var prevContext = getActiveContext();
6281 var prevDispatcher = ReactCurrentDispatcher$1.current;
6282 ReactCurrentDispatcher$1.current = Dispatcher;
6283 var prevGetCurrentStackImpl;
6284
6285 {
6286 prevGetCurrentStackImpl = ReactDebugCurrentFrame$1.getCurrentStack;
6287 ReactDebugCurrentFrame$1.getCurrentStack = getCurrentStackInDEV;
6288 }
6289
6290 var prevResponseState = currentResponseState;
6291 setCurrentResponseState(request.responseState);
6292
6293 try {
6294 var pingedTasks = request.pingedTasks;
6295 var i;
6296
6297 for (i = 0; i < pingedTasks.length; i++) {
6298 var task = pingedTasks[i];
6299 retryTask(request, task);
6300 }
6301
6302 pingedTasks.splice(0, i);
6303
6304 if (request.destination !== null) {
6305 flushCompletedQueues(request, request.destination);
6306 }
6307 } catch (error) {
6308 logRecoverableError(request, error);
6309 fatalError(request, error);
6310 } finally {
6311 setCurrentResponseState(prevResponseState);
6312 ReactCurrentDispatcher$1.current = prevDispatcher;
6313
6314 {
6315 ReactDebugCurrentFrame$1.getCurrentStack = prevGetCurrentStackImpl;
6316 }
6317
6318 if (prevDispatcher === Dispatcher) {
6319 // This means that we were in a reentrant work loop. This could happen
6320 // in a renderer that supports synchronous work like renderToString,
6321 // when it's called from within another renderer.
6322 // Normally we don't bother switching the contexts to their root/default
6323 // values when leaving because we'll likely need the same or similar
6324 // context again. However, when we're inside a synchronous loop like this
6325 // we'll to restore the context to what it was before returning.
6326 switchContext(prevContext);
6327 }
6328 }
6329 }
6330
6331 function flushSubtree(request, destination, segment) {
6332 segment.parentFlushed = true;
6333
6334 switch (segment.status) {
6335 case PENDING:
6336 {
6337 // We're emitting a placeholder for this segment to be filled in later.
6338 // Therefore we'll need to assign it an ID - to refer to it by.
6339 var segmentID = segment.id = request.nextSegmentId++;
6340 return writePlaceholder(destination, request.responseState, segmentID);
6341 }
6342
6343 case COMPLETED:
6344 {
6345 segment.status = FLUSHED;
6346 var r = true;
6347 var chunks = segment.chunks;
6348 var chunkIdx = 0;
6349 var children = segment.children;
6350
6351 for (var childIdx = 0; childIdx < children.length; childIdx++) {
6352 var nextChild = children[childIdx]; // Write all the chunks up until the next child.
6353
6354 for (; chunkIdx < nextChild.index; chunkIdx++) {
6355 writeChunk(destination, chunks[chunkIdx]);
6356 }
6357
6358 r = flushSegment(request, destination, nextChild);
6359 } // Finally just write all the remaining chunks
6360
6361
6362 for (; chunkIdx < chunks.length - 1; chunkIdx++) {
6363 writeChunk(destination, chunks[chunkIdx]);
6364 }
6365
6366 if (chunkIdx < chunks.length) {
6367 r = writeChunkAndReturn(destination, chunks[chunkIdx]);
6368 }
6369
6370 return r;
6371 }
6372
6373 default:
6374 {
6375 throw new Error('Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React.');
6376 }
6377 }
6378 }
6379
6380 function flushSegment(request, destination, segment) {
6381 var boundary = segment.boundary;
6382
6383 if (boundary === null) {
6384 // Not a suspense boundary.
6385 return flushSubtree(request, destination, segment);
6386 }
6387
6388 boundary.parentFlushed = true; // This segment is a Suspense boundary. We need to decide whether to
6389 // emit the content or the fallback now.
6390
6391 if (boundary.forceClientRender) {
6392 // Emit a client rendered suspense boundary wrapper.
6393 // We never queue the inner boundary so we'll never emit its content or partial segments.
6394 writeStartClientRenderedSuspenseBoundary$1(destination, request.responseState); // Flush the fallback.
6395
6396 flushSubtree(request, destination, segment);
6397 return writeEndClientRenderedSuspenseBoundary$1(destination, request.responseState);
6398 } else if (boundary.pendingTasks > 0) {
6399 // This boundary is still loading. Emit a pending suspense boundary wrapper.
6400 // Assign an ID to refer to the future content by.
6401 boundary.rootSegmentID = request.nextSegmentId++;
6402
6403 if (boundary.completedSegments.length > 0) {
6404 // If this is at least partially complete, we can queue it to be partially emitted early.
6405 request.partialBoundaries.push(boundary);
6406 } /// This is the first time we should have referenced this ID.
6407
6408
6409 var id = boundary.id = assignSuspenseBoundaryID(request.responseState);
6410 writeStartPendingSuspenseBoundary(destination, request.responseState, id); // Flush the fallback.
6411
6412 flushSubtree(request, destination, segment);
6413 return writeEndPendingSuspenseBoundary(destination, request.responseState);
6414 } else if (boundary.byteSize > request.progressiveChunkSize) {
6415 // This boundary is large and will be emitted separately so that we can progressively show
6416 // other content. We add it to the queue during the flush because we have to ensure that
6417 // the parent flushes first so that there's something to inject it into.
6418 // We also have to make sure that it's emitted into the queue in a deterministic slot.
6419 // I.e. we can't insert it here when it completes.
6420 // Assign an ID to refer to the future content by.
6421 boundary.rootSegmentID = request.nextSegmentId++;
6422 request.completedBoundaries.push(boundary); // Emit a pending rendered suspense boundary wrapper.
6423
6424 writeStartPendingSuspenseBoundary(destination, request.responseState, boundary.id); // Flush the fallback.
6425
6426 flushSubtree(request, destination, segment);
6427 return writeEndPendingSuspenseBoundary(destination, request.responseState);
6428 } else {
6429 // We can inline this boundary's content as a complete boundary.
6430 writeStartCompletedSuspenseBoundary$1(destination, request.responseState);
6431 var completedSegments = boundary.completedSegments;
6432
6433 if (completedSegments.length !== 1) {
6434 throw new Error('A previously unvisited boundary must have exactly one root segment. This is a bug in React.');
6435 }
6436
6437 var contentSegment = completedSegments[0];
6438 flushSegment(request, destination, contentSegment);
6439 return writeEndCompletedSuspenseBoundary$1(destination, request.responseState);
6440 }
6441 }
6442
6443 function flushClientRenderedBoundary(request, destination, boundary) {
6444 return writeClientRenderBoundaryInstruction(destination, request.responseState, boundary.id);
6445 }
6446
6447 function flushSegmentContainer(request, destination, segment) {
6448 writeStartSegment(destination, request.responseState, segment.formatContext, segment.id);
6449 flushSegment(request, destination, segment);
6450 return writeEndSegment(destination, segment.formatContext);
6451 }
6452
6453 function flushCompletedBoundary(request, destination, boundary) {
6454 var completedSegments = boundary.completedSegments;
6455 var i = 0;
6456
6457 for (; i < completedSegments.length; i++) {
6458 var segment = completedSegments[i];
6459 flushPartiallyCompletedSegment(request, destination, boundary, segment);
6460 }
6461
6462 completedSegments.length = 0;
6463 return writeCompletedBoundaryInstruction(destination, request.responseState, boundary.id, boundary.rootSegmentID);
6464 }
6465
6466 function flushPartialBoundary(request, destination, boundary) {
6467 var completedSegments = boundary.completedSegments;
6468 var i = 0;
6469
6470 for (; i < completedSegments.length; i++) {
6471 var segment = completedSegments[i];
6472
6473 if (!flushPartiallyCompletedSegment(request, destination, boundary, segment)) {
6474 i++;
6475 completedSegments.splice(0, i); // Only write as much as the buffer wants. Something higher priority
6476 // might want to write later.
6477
6478 return false;
6479 }
6480 }
6481
6482 completedSegments.splice(0, i);
6483 return true;
6484 }
6485
6486 function flushPartiallyCompletedSegment(request, destination, boundary, segment) {
6487 if (segment.status === FLUSHED) {
6488 // We've already flushed this inline.
6489 return true;
6490 }
6491
6492 var segmentID = segment.id;
6493
6494 if (segmentID === -1) {
6495 // This segment wasn't previously referred to. This happens at the root of
6496 // a boundary. We make kind of a leap here and assume this is the root.
6497 var rootSegmentID = segment.id = boundary.rootSegmentID;
6498
6499 if (rootSegmentID === -1) {
6500 throw new Error('A root segment ID must have been assigned by now. This is a bug in React.');
6501 }
6502
6503 return flushSegmentContainer(request, destination, segment);
6504 } else {
6505 flushSegmentContainer(request, destination, segment);
6506 return writeCompletedSegmentInstruction(destination, request.responseState, segmentID);
6507 }
6508 }
6509
6510 function flushCompletedQueues(request, destination) {
6511
6512 try {
6513 // The structure of this is to go through each queue one by one and write
6514 // until the sink tells us to stop. When we should stop, we still finish writing
6515 // that item fully and then yield. At that point we remove the already completed
6516 // items up until the point we completed them.
6517 // TODO: Emit preloading.
6518 // TODO: It's kind of unfortunate to keep checking this array after we've already
6519 // emitted the root.
6520 var completedRootSegment = request.completedRootSegment;
6521
6522 if (completedRootSegment !== null && request.pendingRootTasks === 0) {
6523 flushSegment(request, destination, completedRootSegment);
6524 request.completedRootSegment = null;
6525 writeCompletedRoot(destination, request.responseState);
6526 } // We emit client rendering instructions for already emitted boundaries first.
6527 // This is so that we can signal to the client to start client rendering them as
6528 // soon as possible.
6529
6530
6531 var clientRenderedBoundaries = request.clientRenderedBoundaries;
6532 var i;
6533
6534 for (i = 0; i < clientRenderedBoundaries.length; i++) {
6535 var boundary = clientRenderedBoundaries[i];
6536
6537 if (!flushClientRenderedBoundary(request, destination, boundary)) {
6538 request.destination = null;
6539 i++;
6540 clientRenderedBoundaries.splice(0, i);
6541 return;
6542 }
6543 }
6544
6545 clientRenderedBoundaries.splice(0, i); // Next we emit any complete boundaries. It's better to favor boundaries
6546 // that are completely done since we can actually show them, than it is to emit
6547 // any individual segments from a partially complete boundary.
6548
6549 var completedBoundaries = request.completedBoundaries;
6550
6551 for (i = 0; i < completedBoundaries.length; i++) {
6552 var _boundary = completedBoundaries[i];
6553
6554 if (!flushCompletedBoundary(request, destination, _boundary)) {
6555 request.destination = null;
6556 i++;
6557 completedBoundaries.splice(0, i);
6558 return;
6559 }
6560 }
6561
6562 completedBoundaries.splice(0, i); // Allow anything written so far to flush to the underlying sink before
6563 // we continue with lower priorities.
6564
6565 completeWriting(destination);
6566 beginWriting(destination); // TODO: Here we'll emit data used by hydration.
6567 // Next we emit any segments of any boundaries that are partially complete
6568 // but not deeply complete.
6569
6570 var partialBoundaries = request.partialBoundaries;
6571
6572 for (i = 0; i < partialBoundaries.length; i++) {
6573 var _boundary2 = partialBoundaries[i];
6574
6575 if (!flushPartialBoundary(request, destination, _boundary2)) {
6576 request.destination = null;
6577 i++;
6578 partialBoundaries.splice(0, i);
6579 return;
6580 }
6581 }
6582
6583 partialBoundaries.splice(0, i); // Next we check the completed boundaries again. This may have had
6584 // boundaries added to it in case they were too larged to be inlined.
6585 // New ones might be added in this loop.
6586
6587 var largeBoundaries = request.completedBoundaries;
6588
6589 for (i = 0; i < largeBoundaries.length; i++) {
6590 var _boundary3 = largeBoundaries[i];
6591
6592 if (!flushCompletedBoundary(request, destination, _boundary3)) {
6593 request.destination = null;
6594 i++;
6595 largeBoundaries.splice(0, i);
6596 return;
6597 }
6598 }
6599
6600 largeBoundaries.splice(0, i);
6601 } finally {
6602
6603 if (request.allPendingTasks === 0 && request.pingedTasks.length === 0 && request.clientRenderedBoundaries.length === 0 && request.completedBoundaries.length === 0 // We don't need to check any partially completed segments because
6604 // either they have pending task or they're complete.
6605 ) {
6606 {
6607 if (request.abortableTasks.size !== 0) {
6608 error('There was still abortable task at the root when we closed. This is a bug in React.');
6609 }
6610 } // We're done.
6611
6612
6613 close(destination);
6614 }
6615 }
6616 }
6617
6618 function startWork(request) {
6619 scheduleWork(function () {
6620 return performWork(request);
6621 });
6622 }
6623 function startFlowing(request, destination) {
6624 if (request.status === CLOSING) {
6625 request.status = CLOSED;
6626 closeWithError(destination, request.fatalError);
6627 return;
6628 }
6629
6630 if (request.status === CLOSED) {
6631 return;
6632 }
6633
6634 if (request.destination !== null) {
6635 // We're already flowing.
6636 return;
6637 }
6638
6639 request.destination = destination;
6640
6641 try {
6642 flushCompletedQueues(request, destination);
6643 } catch (error) {
6644 logRecoverableError(request, error);
6645 fatalError(request, error);
6646 }
6647 } // This is called to early terminate a request. It puts all pending boundaries in client rendered state.
6648
6649 function abort(request) {
6650 try {
6651 var abortableTasks = request.abortableTasks;
6652 abortableTasks.forEach(abortTask, request);
6653 abortableTasks.clear();
6654
6655 if (request.destination !== null) {
6656 flushCompletedQueues(request, request.destination);
6657 }
6658 } catch (error) {
6659 logRecoverableError(request, error);
6660 fatalError(request, error);
6661 }
6662 }
6663
6664 function onError() {// Non-fatal errors are ignored.
6665 }
6666
6667 function renderToStringImpl(children, options, generateStaticMarkup) {
6668 var didFatal = false;
6669 var fatalError = null;
6670 var result = '';
6671 var destination = {
6672 push: function (chunk) {
6673 if (chunk !== null) {
6674 result += chunk;
6675 }
6676
6677 return true;
6678 },
6679 destroy: function (error) {
6680 didFatal = true;
6681 fatalError = error;
6682 }
6683 };
6684 var readyToStream = false;
6685
6686 function onShellReady() {
6687 readyToStream = true;
6688 }
6689
6690 var request = createRequest(children, createResponseState$1(generateStaticMarkup, options ? options.identifierPrefix : undefined), createRootFormatContext(), Infinity, onError, undefined, onShellReady, undefined, undefined);
6691 startWork(request); // If anything suspended and is still pending, we'll abort it before writing.
6692 // That way we write only client-rendered boundaries from the start.
6693
6694 abort(request);
6695 startFlowing(request, destination);
6696
6697 if (didFatal) {
6698 throw fatalError;
6699 }
6700
6701 if (!readyToStream) {
6702 // Note: This error message is the one we use on the client. It doesn't
6703 // really make sense here. But this is the legacy server renderer, anyway.
6704 // We're going to delete it soon.
6705 throw 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.');
6706 }
6707
6708 return result;
6709 }
6710
6711 function renderToString(children, options) {
6712 return renderToStringImpl(children, options, false);
6713 }
6714
6715 function renderToStaticMarkup(children, options) {
6716 return renderToStringImpl(children, options, true);
6717 }
6718
6719 function renderToNodeStream() {
6720 throw new Error('ReactDOMServer.renderToNodeStream(): The streaming API is not available ' + 'in the browser. Use ReactDOMServer.renderToString() instead.');
6721 }
6722
6723 function renderToStaticNodeStream() {
6724 throw new Error('ReactDOMServer.renderToStaticNodeStream(): The streaming API is not available ' + 'in the browser. Use ReactDOMServer.renderToStaticMarkup() instead.');
6725 }
6726
6727 exports.renderToNodeStream = renderToNodeStream;
6728 exports.renderToStaticMarkup = renderToStaticMarkup;
6729 exports.renderToStaticNodeStream = renderToStaticNodeStream;
6730 exports.renderToString = renderToString;
6731 exports.version = ReactVersion;
6732
6733})));