UNPKG

37.7 kBJavaScriptView Raw
1/** @license React v16.8.0
2 * react-test-renderer-shallow.development.js
3 *
4 * Copyright (c) Facebook, Inc. and its affiliates.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE file in the root directory of this source tree.
8 */
9
10'use strict';
11
12(function (global, factory) {
13 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react')) :
14 typeof define === 'function' && define.amd ? define(['react'], factory) :
15 (global.ReactShallowRenderer = factory(global.React));
16}(this, (function (React) { 'use strict';
17
18/**
19 * Use invariant() to assert state which your program assumes to be true.
20 *
21 * Provide sprintf-style format (only %s is supported) and arguments
22 * to provide information about what broke and what you were
23 * expecting.
24 *
25 * The invariant message will be stripped in production, but the invariant
26 * will remain to ensure logic does not differ in production.
27 */
28
29var validateFormat = function () {};
30
31{
32 validateFormat = function (format) {
33 if (format === undefined) {
34 throw new Error('invariant requires an error message argument');
35 }
36 };
37}
38
39function invariant(condition, format, a, b, c, d, e, f) {
40 validateFormat(format);
41
42 if (!condition) {
43 var error = void 0;
44 if (format === undefined) {
45 error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
46 } else {
47 var args = [a, b, c, d, e, f];
48 var argIndex = 0;
49 error = new Error(format.replace(/%s/g, function () {
50 return args[argIndex++];
51 }));
52 error.name = 'Invariant Violation';
53 }
54
55 error.framesToPop = 1; // we don't care about invariant's own frame
56 throw error;
57 }
58}
59
60// Relying on the `invariant()` implementation lets us
61// preserve the format and params in the www builds.
62
63var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
64
65var _assign = ReactInternals.assign;
66
67// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
68// nor polyfill, then a plain number is used for performance.
69var hasSymbol = typeof Symbol === 'function' && Symbol.for;
70
71var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
72var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
73var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
74var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
75var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
76var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
77var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
78var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
79var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
80var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
81var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
82var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
83var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
84
85/**
86 * Forked from fbjs/warning:
87 * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
88 *
89 * Only change is we use console.warn instead of console.error,
90 * and do nothing when 'console' is not supported.
91 * This really simplifies the code.
92 * ---
93 * Similar to invariant but only logs a warning if the condition is not met.
94 * This can be used to log issues in development environments in critical
95 * paths. Removing the logging code for production environments will keep the
96 * same logic and follow the same code paths.
97 */
98
99{
100
101}
102
103function typeOf(object) {
104 if (typeof object === 'object' && object !== null) {
105 var $$typeof = object.$$typeof;
106 switch ($$typeof) {
107 case REACT_ELEMENT_TYPE:
108 var type = object.type;
109
110 switch (type) {
111 case REACT_ASYNC_MODE_TYPE:
112 case REACT_CONCURRENT_MODE_TYPE:
113 case REACT_FRAGMENT_TYPE:
114 case REACT_PROFILER_TYPE:
115 case REACT_STRICT_MODE_TYPE:
116 case REACT_SUSPENSE_TYPE:
117 return type;
118 default:
119 var $$typeofType = type && type.$$typeof;
120
121 switch ($$typeofType) {
122 case REACT_CONTEXT_TYPE:
123 case REACT_FORWARD_REF_TYPE:
124 case REACT_PROVIDER_TYPE:
125 return $$typeofType;
126 default:
127 return $$typeof;
128 }
129 }
130 case REACT_LAZY_TYPE:
131 case REACT_MEMO_TYPE:
132 case REACT_PORTAL_TYPE:
133 return $$typeof;
134 }
135 }
136
137 return undefined;
138}
139
140// AsyncMode is deprecated along with isAsyncMode
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155// AsyncMode should be deprecated
156
157
158
159
160
161function isForwardRef(object) {
162 return typeOf(object) === REACT_FORWARD_REF_TYPE;
163}
164
165var BEFORE_SLASH_RE = /^(.*)[\\\/]/;
166
167var describeComponentFrame = function (name, source, ownerName) {
168 var sourceInfo = '';
169 if (source) {
170 var path = source.fileName;
171 var fileName = path.replace(BEFORE_SLASH_RE, '');
172 {
173 // In DEV, include code for a common special case:
174 // prefer "folder/index.js" instead of just "index.js".
175 if (/^index\./.test(fileName)) {
176 var match = path.match(BEFORE_SLASH_RE);
177 if (match) {
178 var pathBeforeSlash = match[1];
179 if (pathBeforeSlash) {
180 var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
181 fileName = folderName + '/' + fileName;
182 }
183 }
184 }
185 }
186 sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
187 } else if (ownerName) {
188 sourceInfo = ' (created by ' + ownerName + ')';
189 }
190 return '\n in ' + (name || 'Unknown') + sourceInfo;
191};
192
193/**
194 * Similar to invariant but only logs a warning if the condition is not met.
195 * This can be used to log issues in development environments in critical
196 * paths. Removing the logging code for production environments will keep the
197 * same logic and follow the same code paths.
198 */
199
200var warningWithoutStack = function () {};
201
202{
203 warningWithoutStack = function (condition, format) {
204 for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
205 args[_key - 2] = arguments[_key];
206 }
207
208 if (format === undefined) {
209 throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
210 }
211 if (args.length > 8) {
212 // Check before the condition to catch violations early.
213 throw new Error('warningWithoutStack() currently supports at most 8 arguments.');
214 }
215 if (condition) {
216 return;
217 }
218 if (typeof console !== 'undefined') {
219 var argsWithFormat = args.map(function (item) {
220 return '' + item;
221 });
222 argsWithFormat.unshift('Warning: ' + format);
223
224 // We intentionally don't use spread (or .apply) directly because it
225 // breaks IE9: https://github.com/facebook/react/issues/13610
226 Function.prototype.apply.call(console.error, console, argsWithFormat);
227 }
228 try {
229 // --- Welcome to debugging React ---
230 // This error was thrown as a convenience so that you can use this stack
231 // to find the callsite that caused this warning to fire.
232 var argIndex = 0;
233 var message = 'Warning: ' + format.replace(/%s/g, function () {
234 return args[argIndex++];
235 });
236 throw new Error(message);
237 } catch (x) {}
238 };
239}
240
241var warningWithoutStack$1 = warningWithoutStack;
242
243var Resolved = 1;
244
245
246function refineResolvedLazyComponent(lazyComponent) {
247 return lazyComponent._status === Resolved ? lazyComponent._result : null;
248}
249
250function getWrappedName(outerType, innerType, wrapperName) {
251 var functionName = innerType.displayName || innerType.name || '';
252 return outerType.displayName || (functionName !== '' ? wrapperName + '(' + functionName + ')' : wrapperName);
253}
254
255function getComponentName(type) {
256 if (type == null) {
257 // Host root, text node or just invalid type.
258 return null;
259 }
260 {
261 if (typeof type.tag === 'number') {
262 warningWithoutStack$1(false, 'Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
263 }
264 }
265 if (typeof type === 'function') {
266 return type.displayName || type.name || null;
267 }
268 if (typeof type === 'string') {
269 return type;
270 }
271 switch (type) {
272 case REACT_CONCURRENT_MODE_TYPE:
273 return 'ConcurrentMode';
274 case REACT_FRAGMENT_TYPE:
275 return 'Fragment';
276 case REACT_PORTAL_TYPE:
277 return 'Portal';
278 case REACT_PROFILER_TYPE:
279 return 'Profiler';
280 case REACT_STRICT_MODE_TYPE:
281 return 'StrictMode';
282 case REACT_SUSPENSE_TYPE:
283 return 'Suspense';
284 }
285 if (typeof type === 'object') {
286 switch (type.$$typeof) {
287 case REACT_CONTEXT_TYPE:
288 return 'Context.Consumer';
289 case REACT_PROVIDER_TYPE:
290 return 'Context.Provider';
291 case REACT_FORWARD_REF_TYPE:
292 return getWrappedName(type, type.render, 'ForwardRef');
293 case REACT_MEMO_TYPE:
294 return getComponentName(type.type);
295 case REACT_LAZY_TYPE:
296 {
297 var thenable = type;
298 var resolvedThenable = refineResolvedLazyComponent(thenable);
299 if (resolvedThenable) {
300 return getComponentName(resolvedThenable);
301 }
302 }
303 }
304 }
305 return null;
306}
307
308/**
309 * inlined Object.is polyfill to avoid requiring consumers ship their own
310 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
311 */
312function is(x, y) {
313 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
314 ;
315}
316
317var hasOwnProperty = Object.prototype.hasOwnProperty;
318
319/**
320 * Performs equality by iterating through keys on an object and returning false
321 * when any key has values which are not strictly equal between the arguments.
322 * Returns true when the values of all keys are strictly equal.
323 */
324function shallowEqual(objA, objB) {
325 if (is(objA, objB)) {
326 return true;
327 }
328
329 if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
330 return false;
331 }
332
333 var keysA = Object.keys(objA);
334 var keysB = Object.keys(objB);
335
336 if (keysA.length !== keysB.length) {
337 return false;
338 }
339
340 // Test for A's keys different from B.
341 for (var i = 0; i < keysA.length; i++) {
342 if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
343 return false;
344 }
345 }
346
347 return true;
348}
349
350/**
351 * Copyright (c) 2013-present, Facebook, Inc.
352 *
353 * This source code is licensed under the MIT license found in the
354 * LICENSE file in the root directory of this source tree.
355 */
356
357
358
359var ReactPropTypesSecret$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
360
361var ReactPropTypesSecret_1 = ReactPropTypesSecret$1;
362
363/**
364 * Copyright (c) 2013-present, Facebook, Inc.
365 *
366 * This source code is licensed under the MIT license found in the
367 * LICENSE file in the root directory of this source tree.
368 */
369
370
371
372var printWarning$1 = function() {};
373
374{
375 var ReactPropTypesSecret = ReactPropTypesSecret_1;
376 var loggedTypeFailures = {};
377
378 printWarning$1 = function(text) {
379 var message = 'Warning: ' + text;
380 if (typeof console !== 'undefined') {
381 console.error(message);
382 }
383 try {
384 // --- Welcome to debugging React ---
385 // This error was thrown as a convenience so that you can use this stack
386 // to find the callsite that caused this warning to fire.
387 throw new Error(message);
388 } catch (x) {}
389 };
390}
391
392/**
393 * Assert that the values match with the type specs.
394 * Error messages are memorized and will only be shown once.
395 *
396 * @param {object} typeSpecs Map of name to a ReactPropType
397 * @param {object} values Runtime values that need to be type-checked
398 * @param {string} location e.g. "prop", "context", "child context"
399 * @param {string} componentName Name of the component for error messages.
400 * @param {?Function} getStack Returns the component stack.
401 * @private
402 */
403function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
404 {
405 for (var typeSpecName in typeSpecs) {
406 if (typeSpecs.hasOwnProperty(typeSpecName)) {
407 var error;
408 // Prop type validation may throw. In case they do, we don't want to
409 // fail the render phase where it didn't fail before. So we log it.
410 // After these have been cleaned up, we'll let them throw.
411 try {
412 // This is intentionally an invariant that gets caught. It's the same
413 // behavior as without this statement except with a better message.
414 if (typeof typeSpecs[typeSpecName] !== 'function') {
415 var err = Error(
416 (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
417 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
418 );
419 err.name = 'Invariant Violation';
420 throw err;
421 }
422 error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
423 } catch (ex) {
424 error = ex;
425 }
426 if (error && !(error instanceof Error)) {
427 printWarning$1(
428 (componentName || 'React class') + ': type specification of ' +
429 location + ' `' + typeSpecName + '` is invalid; the type checker ' +
430 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
431 'You may have forgotten to pass an argument to the type checker ' +
432 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
433 'shape all require an argument).'
434 );
435
436 }
437 if (error instanceof Error && !(error.message in loggedTypeFailures)) {
438 // Only monitor this failure once because there tends to be a lot of the
439 // same error.
440 loggedTypeFailures[error.message] = true;
441
442 var stack = getStack ? getStack() : '';
443
444 printWarning$1(
445 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
446 );
447 }
448 }
449 }
450 }
451}
452
453var checkPropTypes_1 = checkPropTypes;
454
455var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
456
457/**
458 * Similar to invariant but only logs a warning if the condition is not met.
459 * This can be used to log issues in development environments in critical
460 * paths. Removing the logging code for production environments will keep the
461 * same logic and follow the same code paths.
462 */
463
464var warning = warningWithoutStack$1;
465
466{
467 warning = function (condition, format) {
468 if (condition) {
469 return;
470 }
471 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
472 var stack = ReactDebugCurrentFrame.getStackAddendum();
473 // eslint-disable-next-line react-internal/warning-and-invariant-args
474
475 for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
476 args[_key - 2] = arguments[_key];
477 }
478
479 warningWithoutStack$1.apply(undefined, [false, format + '%s'].concat(args, [stack]));
480 };
481}
482
483var warning$1 = warning;
484
485function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
486
487var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
488
489
490var RE_RENDER_LIMIT = 25;
491
492var emptyObject = {};
493{
494 Object.freeze(emptyObject);
495}
496
497// In DEV, this is the name of the currently executing primitive hook
498var currentHookNameInDev = void 0;
499
500function areHookInputsEqual(nextDeps, prevDeps) {
501 if (prevDeps === null) {
502 warning$1(false, '%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);
503 return false;
504 }
505
506 // Don't bother comparing lengths in prod because these arrays should be
507 // passed inline.
508 if (nextDeps.length !== prevDeps.length) {
509 warning$1(false, 'The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, '[' + nextDeps.join(', ') + ']', '[' + prevDeps.join(', ') + ']');
510 }
511 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
512 if (is(nextDeps[i], prevDeps[i])) {
513 continue;
514 }
515 return false;
516 }
517 return true;
518}
519
520var Updater = function () {
521 function Updater(renderer) {
522 _classCallCheck(this, Updater);
523
524 this._renderer = renderer;
525 this._callbacks = [];
526 }
527
528 Updater.prototype._enqueueCallback = function _enqueueCallback(callback, publicInstance) {
529 if (typeof callback === 'function' && publicInstance) {
530 this._callbacks.push({
531 callback: callback,
532 publicInstance: publicInstance
533 });
534 }
535 };
536
537 Updater.prototype._invokeCallbacks = function _invokeCallbacks() {
538 var callbacks = this._callbacks;
539 this._callbacks = [];
540
541 callbacks.forEach(function (_ref) {
542 var callback = _ref.callback,
543 publicInstance = _ref.publicInstance;
544
545 callback.call(publicInstance);
546 });
547 };
548
549 Updater.prototype.isMounted = function isMounted(publicInstance) {
550 return !!this._renderer._element;
551 };
552
553 Updater.prototype.enqueueForceUpdate = function enqueueForceUpdate(publicInstance, callback, callerName) {
554 this._enqueueCallback(callback, publicInstance);
555 this._renderer._forcedUpdate = true;
556 this._renderer.render(this._renderer._element, this._renderer._context);
557 };
558
559 Updater.prototype.enqueueReplaceState = function enqueueReplaceState(publicInstance, completeState, callback, callerName) {
560 this._enqueueCallback(callback, publicInstance);
561 this._renderer._newState = completeState;
562 this._renderer.render(this._renderer._element, this._renderer._context);
563 };
564
565 Updater.prototype.enqueueSetState = function enqueueSetState(publicInstance, partialState, callback, callerName) {
566 this._enqueueCallback(callback, publicInstance);
567 var currentState = this._renderer._newState || publicInstance.state;
568
569 if (typeof partialState === 'function') {
570 partialState = partialState.call(publicInstance, currentState, publicInstance.props);
571 }
572
573 // Null and undefined are treated as no-ops.
574 if (partialState === null || partialState === undefined) {
575 return;
576 }
577
578 this._renderer._newState = _assign({}, currentState, partialState);
579
580 this._renderer.render(this._renderer._element, this._renderer._context);
581 };
582
583 return Updater;
584}();
585
586function createHook() {
587 return {
588 memoizedState: null,
589 queue: null,
590 next: null
591 };
592}
593
594function basicStateReducer(state, action) {
595 return typeof action === 'function' ? action(state) : action;
596}
597
598var ReactShallowRenderer = function () {
599 function ReactShallowRenderer() {
600 _classCallCheck(this, ReactShallowRenderer);
601
602 this._context = null;
603 this._element = null;
604 this._instance = null;
605 this._newState = null;
606 this._rendered = null;
607 this._rendering = false;
608 this._forcedUpdate = false;
609 this._updater = new Updater(this);
610 this._dispatcher = this._createDispatcher();
611 this._workInProgressHook = null;
612 this._firstWorkInProgressHook = null;
613 this._isReRender = false;
614 this._didScheduleRenderPhaseUpdate = false;
615 this._renderPhaseUpdates = null;
616 this._currentlyRenderingComponent = null;
617 this._numberOfReRenders = 0;
618 this._previousComponentIdentity = null;
619 }
620
621 ReactShallowRenderer.prototype._validateCurrentlyRenderingComponent = function _validateCurrentlyRenderingComponent() {
622 !(this._currentlyRenderingComponent !== null) ? invariant(false, 'Hooks can only be called inside the body of a function component. (https://fb.me/react-invalid-hook-call)') : void 0;
623 };
624
625 ReactShallowRenderer.prototype._createDispatcher = function _createDispatcher() {
626 var _this = this;
627
628 var useReducer = function (reducer, initialArg, init) {
629 _this._validateCurrentlyRenderingComponent();
630 _this._createWorkInProgressHook();
631 var workInProgressHook = _this._workInProgressHook;
632 if (_this._isReRender) {
633 // This is a re-render. Apply the new render phase updates to the previous
634 var _queue = workInProgressHook.queue;
635 var _dispatch = _queue.dispatch;
636 if (_this._renderPhaseUpdates !== null) {
637 // Render phase updates are stored in a map of queue -> linked list
638 var firstRenderPhaseUpdate = _this._renderPhaseUpdates.get(_queue);
639 if (firstRenderPhaseUpdate !== undefined) {
640 _this._renderPhaseUpdates.delete(_queue);
641 var newState = workInProgressHook.memoizedState;
642 var update = firstRenderPhaseUpdate;
643 do {
644 // Process this render phase update. We don't have to check the
645 // priority because it will always be the same as the current
646 // render's.
647 var _action = update.action;
648 newState = reducer(newState, _action);
649 update = update.next;
650 } while (update !== null);
651
652 workInProgressHook.memoizedState = newState;
653
654 return [newState, _dispatch];
655 }
656 }
657 return [workInProgressHook.memoizedState, _dispatch];
658 } else {
659 var initialState = void 0;
660 if (reducer === basicStateReducer) {
661 // Special case for `useState`.
662 initialState = typeof initialArg === 'function' ? initialArg() : initialArg;
663 } else {
664 initialState = init !== undefined ? init(initialArg) : initialArg;
665 }
666 workInProgressHook.memoizedState = initialState;
667 var _queue2 = workInProgressHook.queue = {
668 last: null,
669 dispatch: null
670 };
671 var _dispatch2 = _queue2.dispatch = _this._dispatchAction.bind(_this, _this._currentlyRenderingComponent, _queue2);
672 return [workInProgressHook.memoizedState, _dispatch2];
673 }
674 };
675
676 var useState = function (initialState) {
677 return useReducer(basicStateReducer,
678 // useReducer has a special case to support lazy useState initializers
679 initialState);
680 };
681
682 var useMemo = function (nextCreate, deps) {
683 _this._validateCurrentlyRenderingComponent();
684 _this._createWorkInProgressHook();
685
686 var nextDeps = deps !== undefined ? deps : null;
687
688 if (_this._workInProgressHook !== null && _this._workInProgressHook.memoizedState !== null) {
689 var prevState = _this._workInProgressHook.memoizedState;
690 var prevDeps = prevState[1];
691 if (nextDeps !== null) {
692 if (areHookInputsEqual(nextDeps, prevDeps)) {
693 return prevState[0];
694 }
695 }
696 }
697
698 var nextValue = nextCreate();
699 _this._workInProgressHook.memoizedState = [nextValue, nextDeps];
700 return nextValue;
701 };
702
703 var useRef = function (initialValue) {
704 _this._validateCurrentlyRenderingComponent();
705 _this._createWorkInProgressHook();
706 var previousRef = _this._workInProgressHook.memoizedState;
707 if (previousRef === null) {
708 var ref = { current: initialValue };
709 {
710 Object.seal(ref);
711 }
712 _this._workInProgressHook.memoizedState = ref;
713 return ref;
714 } else {
715 return previousRef;
716 }
717 };
718
719 var readContext = function (context, observedBits) {
720 return context._currentValue;
721 };
722
723 var noOp = function () {
724 _this._validateCurrentlyRenderingComponent();
725 };
726
727 var identity = function (fn) {
728 return fn;
729 };
730
731 return {
732 readContext: readContext,
733 useCallback: identity,
734 useContext: function (context) {
735 _this._validateCurrentlyRenderingComponent();
736 return readContext(context);
737 },
738 useDebugValue: noOp,
739 useEffect: noOp,
740 useImperativeHandle: noOp,
741 useLayoutEffect: noOp,
742 useMemo: useMemo,
743 useReducer: useReducer,
744 useRef: useRef,
745 useState: useState
746 };
747 };
748
749 ReactShallowRenderer.prototype._dispatchAction = function _dispatchAction(componentIdentity, queue, action) {
750 !(this._numberOfReRenders < RE_RENDER_LIMIT) ? invariant(false, 'Too many re-renders. React limits the number of renders to prevent an infinite loop.') : void 0;
751
752 if (componentIdentity === this._currentlyRenderingComponent) {
753 // This is a render phase update. Stash it in a lazily-created map of
754 // queue -> linked list of updates. After this render pass, we'll restart
755 // and apply the stashed updates on top of the work-in-progress hook.
756 this._didScheduleRenderPhaseUpdate = true;
757 var update = {
758 action: action,
759 next: null
760 };
761 var renderPhaseUpdates = this._renderPhaseUpdates;
762 if (renderPhaseUpdates === null) {
763 this._renderPhaseUpdates = renderPhaseUpdates = new Map();
764 }
765 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
766 if (firstRenderPhaseUpdate === undefined) {
767 renderPhaseUpdates.set(queue, update);
768 } else {
769 // Append the update to the end of the list.
770 var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
771 while (lastRenderPhaseUpdate.next !== null) {
772 lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
773 }
774 lastRenderPhaseUpdate.next = update;
775 }
776 } else {
777 // This means an update has happened after the function component has
778 // returned. On the server this is a no-op. In React Fiber, the update
779 // would be scheduled for a future render.
780 }
781 };
782
783 ReactShallowRenderer.prototype._createWorkInProgressHook = function _createWorkInProgressHook() {
784 if (this._workInProgressHook === null) {
785 // This is the first hook in the list
786 if (this._firstWorkInProgressHook === null) {
787 this._isReRender = false;
788 this._firstWorkInProgressHook = this._workInProgressHook = createHook();
789 } else {
790 // There's already a work-in-progress. Reuse it.
791 this._isReRender = true;
792 this._workInProgressHook = this._firstWorkInProgressHook;
793 }
794 } else {
795 if (this._workInProgressHook.next === null) {
796 this._isReRender = false;
797 // Append to the end of the list
798 this._workInProgressHook = this._workInProgressHook.next = createHook();
799 } else {
800 // There's already a work-in-progress. Reuse it.
801 this._isReRender = true;
802 this._workInProgressHook = this._workInProgressHook.next;
803 }
804 }
805 return this._workInProgressHook;
806 };
807
808 ReactShallowRenderer.prototype._prepareToUseHooks = function _prepareToUseHooks(componentIdentity) {
809 if (this._previousComponentIdentity !== null && this._previousComponentIdentity !== componentIdentity) {
810 this._firstWorkInProgressHook = null;
811 }
812 this._currentlyRenderingComponent = componentIdentity;
813 this._previousComponentIdentity = componentIdentity;
814 };
815
816 ReactShallowRenderer.prototype._finishHooks = function _finishHooks(element, context) {
817 if (this._didScheduleRenderPhaseUpdate) {
818 // Updates were scheduled during the render phase. They are stored in
819 // the `renderPhaseUpdates` map. Call the component again, reusing the
820 // work-in-progress hooks and applying the additional updates on top. Keep
821 // restarting until no more updates are scheduled.
822 this._didScheduleRenderPhaseUpdate = false;
823 this._numberOfReRenders += 1;
824
825 // Start over from the beginning of the list
826 this._workInProgressHook = null;
827 this._rendering = false;
828 this.render(element, context);
829 } else {
830 this._currentlyRenderingComponent = null;
831 this._workInProgressHook = null;
832 this._renderPhaseUpdates = null;
833 this._numberOfReRenders = 0;
834 }
835 };
836
837 ReactShallowRenderer.prototype.getMountedInstance = function getMountedInstance() {
838 return this._instance;
839 };
840
841 ReactShallowRenderer.prototype.getRenderOutput = function getRenderOutput() {
842 return this._rendered;
843 };
844
845 ReactShallowRenderer.prototype.render = function render(element) {
846 var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : emptyObject;
847
848 !React.isValidElement(element) ? invariant(false, 'ReactShallowRenderer render(): Invalid component element.%s', typeof element === 'function' ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' : '') : void 0;
849 element = element;
850 // Show a special message for host elements since it's a common case.
851 !(typeof element.type !== 'string') ? invariant(false, 'ReactShallowRenderer render(): Shallow rendering works only with custom components, not primitives (%s). Instead of calling `.render(el)` and inspecting the rendered output, look at `el.props` directly instead.', element.type) : void 0;
852 !(isForwardRef(element) || typeof element.type === 'function') ? invariant(false, 'ReactShallowRenderer render(): Shallow rendering works only with custom components, but the provided element type was `%s`.', Array.isArray(element.type) ? 'array' : element.type === null ? 'null' : typeof element.type) : void 0;
853
854 if (this._rendering) {
855 return;
856 }
857
858 this._rendering = true;
859 this._element = element;
860 this._context = getMaskedContext(element.type.contextTypes, context);
861
862 if (this._instance) {
863 this._updateClassComponent(element, this._context);
864 } else {
865 if (isForwardRef(element)) {
866 this._rendered = element.type.render(element.props, element.ref);
867 } else if (shouldConstruct(element.type)) {
868 this._instance = new element.type(element.props, this._context, this._updater);
869
870 if (typeof element.type.getDerivedStateFromProps === 'function') {
871 var partialState = element.type.getDerivedStateFromProps.call(null, element.props, this._instance.state);
872 if (partialState != null) {
873 this._instance.state = _assign({}, this._instance.state, partialState);
874 }
875 }
876
877 if (element.type.hasOwnProperty('contextTypes')) {
878 currentlyValidatingElement = element;
879
880 checkPropTypes_1(element.type.contextTypes, this._context, 'context', getName(element.type, this._instance), getStackAddendum);
881
882 currentlyValidatingElement = null;
883 }
884
885 this._mountClassComponent(element, this._context);
886 } else {
887 var prevDispatcher = ReactCurrentDispatcher.current;
888 ReactCurrentDispatcher.current = this._dispatcher;
889 this._prepareToUseHooks(element.type);
890 try {
891 this._rendered = element.type.call(undefined, element.props, this._context);
892 } finally {
893 ReactCurrentDispatcher.current = prevDispatcher;
894 }
895 this._finishHooks(element, context);
896 }
897 }
898
899 this._rendering = false;
900 this._updater._invokeCallbacks();
901
902 return this.getRenderOutput();
903 };
904
905 ReactShallowRenderer.prototype.unmount = function unmount() {
906 if (this._instance) {
907 if (typeof this._instance.componentWillUnmount === 'function') {
908 this._instance.componentWillUnmount();
909 }
910 }
911
912 this._firstWorkInProgressHook = null;
913 this._previousComponentIdentity = null;
914 this._context = null;
915 this._element = null;
916 this._newState = null;
917 this._rendered = null;
918 this._instance = null;
919 };
920
921 ReactShallowRenderer.prototype._mountClassComponent = function _mountClassComponent(element, context) {
922 this._instance.context = context;
923 this._instance.props = element.props;
924 this._instance.state = this._instance.state || null;
925 this._instance.updater = this._updater;
926
927 if (typeof this._instance.UNSAFE_componentWillMount === 'function' || typeof this._instance.componentWillMount === 'function') {
928 var beforeState = this._newState;
929
930 // In order to support react-lifecycles-compat polyfilled components,
931 // Unsafe lifecycles should not be invoked for components using the new APIs.
932 if (typeof element.type.getDerivedStateFromProps !== 'function' && typeof this._instance.getSnapshotBeforeUpdate !== 'function') {
933 if (typeof this._instance.componentWillMount === 'function') {
934 this._instance.componentWillMount();
935 }
936 if (typeof this._instance.UNSAFE_componentWillMount === 'function') {
937 this._instance.UNSAFE_componentWillMount();
938 }
939 }
940
941 // setState may have been called during cWM
942 if (beforeState !== this._newState) {
943 this._instance.state = this._newState || emptyObject;
944 }
945 }
946
947 this._rendered = this._instance.render();
948 // Intentionally do not call componentDidMount()
949 // because DOM refs are not available.
950 };
951
952 ReactShallowRenderer.prototype._updateClassComponent = function _updateClassComponent(element, context) {
953 var props = element.props,
954 type = element.type;
955
956
957 var oldState = this._instance.state || emptyObject;
958 var oldProps = this._instance.props;
959
960 if (oldProps !== props) {
961 // In order to support react-lifecycles-compat polyfilled components,
962 // Unsafe lifecycles should not be invoked for components using the new APIs.
963 if (typeof element.type.getDerivedStateFromProps !== 'function' && typeof this._instance.getSnapshotBeforeUpdate !== 'function') {
964 if (typeof this._instance.componentWillReceiveProps === 'function') {
965 this._instance.componentWillReceiveProps(props, context);
966 }
967 if (typeof this._instance.UNSAFE_componentWillReceiveProps === 'function') {
968 this._instance.UNSAFE_componentWillReceiveProps(props, context);
969 }
970 }
971 }
972
973 // Read state after cWRP in case it calls setState
974 var state = this._newState || oldState;
975 if (typeof type.getDerivedStateFromProps === 'function') {
976 var partialState = type.getDerivedStateFromProps.call(null, props, state);
977 if (partialState != null) {
978 state = _assign({}, state, partialState);
979 }
980 }
981
982 var shouldUpdate = true;
983 if (this._forcedUpdate) {
984 shouldUpdate = true;
985 this._forcedUpdate = false;
986 } else if (typeof this._instance.shouldComponentUpdate === 'function') {
987 shouldUpdate = !!this._instance.shouldComponentUpdate(props, state, context);
988 } else if (type.prototype && type.prototype.isPureReactComponent) {
989 shouldUpdate = !shallowEqual(oldProps, props) || !shallowEqual(oldState, state);
990 }
991
992 if (shouldUpdate) {
993 // In order to support react-lifecycles-compat polyfilled components,
994 // Unsafe lifecycles should not be invoked for components using the new APIs.
995 if (typeof element.type.getDerivedStateFromProps !== 'function' && typeof this._instance.getSnapshotBeforeUpdate !== 'function') {
996 if (typeof this._instance.componentWillUpdate === 'function') {
997 this._instance.componentWillUpdate(props, state, context);
998 }
999 if (typeof this._instance.UNSAFE_componentWillUpdate === 'function') {
1000 this._instance.UNSAFE_componentWillUpdate(props, state, context);
1001 }
1002 }
1003 }
1004
1005 this._instance.context = context;
1006 this._instance.props = props;
1007 this._instance.state = state;
1008 this._newState = null;
1009
1010 if (shouldUpdate) {
1011 this._rendered = this._instance.render();
1012 }
1013 // Intentionally do not call componentDidUpdate()
1014 // because DOM refs are not available.
1015 };
1016
1017 return ReactShallowRenderer;
1018}();
1019
1020ReactShallowRenderer.createRenderer = function () {
1021 return new ReactShallowRenderer();
1022};
1023
1024var currentlyValidatingElement = null;
1025
1026function getDisplayName(element) {
1027 if (element == null) {
1028 return '#empty';
1029 } else if (typeof element === 'string' || typeof element === 'number') {
1030 return '#text';
1031 } else if (typeof element.type === 'string') {
1032 return element.type;
1033 } else {
1034 return element.type.displayName || element.type.name || 'Unknown';
1035 }
1036}
1037
1038function getStackAddendum() {
1039 var stack = '';
1040 if (currentlyValidatingElement) {
1041 var name = getDisplayName(currentlyValidatingElement);
1042 var owner = currentlyValidatingElement._owner;
1043 stack += describeComponentFrame(name, currentlyValidatingElement._source, owner && getComponentName(owner.type));
1044 }
1045 return stack;
1046}
1047
1048function getName(type, instance) {
1049 var constructor = instance && instance.constructor;
1050 return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null;
1051}
1052
1053function shouldConstruct(Component) {
1054 return !!(Component.prototype && Component.prototype.isReactComponent);
1055}
1056
1057function getMaskedContext(contextTypes, unmaskedContext) {
1058 if (!contextTypes || !unmaskedContext) {
1059 return emptyObject;
1060 }
1061 var context = {};
1062 for (var key in contextTypes) {
1063 context[key] = unmaskedContext[key];
1064 }
1065 return context;
1066}
1067
1068
1069
1070var ReactShallowRenderer$2 = Object.freeze({
1071 default: ReactShallowRenderer
1072});
1073
1074var ReactShallowRenderer$3 = ( ReactShallowRenderer$2 && ReactShallowRenderer ) || ReactShallowRenderer$2;
1075
1076// TODO: decide on the top-level export form.
1077// This is hacky but makes it work with both Rollup and Jest.
1078var shallow = ReactShallowRenderer$3.default || ReactShallowRenderer$3;
1079
1080return shallow;
1081
1082})));