UNPKG

38.1 kBJavaScriptView Raw
1/** @license React v16.8.1
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// Prevent newer renderers from RTE when used with older react package versions.
458// Current owner and dispatcher used to share the same ref,
459// but PR #14548 split them out to better support the react-debug-tools package.
460if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {
461 ReactSharedInternals.ReactCurrentDispatcher = {
462 current: null
463 };
464}
465
466/**
467 * Similar to invariant but only logs a warning if the condition is not met.
468 * This can be used to log issues in development environments in critical
469 * paths. Removing the logging code for production environments will keep the
470 * same logic and follow the same code paths.
471 */
472
473var warning = warningWithoutStack$1;
474
475{
476 warning = function (condition, format) {
477 if (condition) {
478 return;
479 }
480 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
481 var stack = ReactDebugCurrentFrame.getStackAddendum();
482 // eslint-disable-next-line react-internal/warning-and-invariant-args
483
484 for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
485 args[_key - 2] = arguments[_key];
486 }
487
488 warningWithoutStack$1.apply(undefined, [false, format + '%s'].concat(args, [stack]));
489 };
490}
491
492var warning$1 = warning;
493
494function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
495
496var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
497
498
499var RE_RENDER_LIMIT = 25;
500
501var emptyObject = {};
502{
503 Object.freeze(emptyObject);
504}
505
506// In DEV, this is the name of the currently executing primitive hook
507var currentHookNameInDev = void 0;
508
509function areHookInputsEqual(nextDeps, prevDeps) {
510 if (prevDeps === null) {
511 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);
512 return false;
513 }
514
515 // Don't bother comparing lengths in prod because these arrays should be
516 // passed inline.
517 if (nextDeps.length !== prevDeps.length) {
518 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(', ') + ']');
519 }
520 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
521 if (is(nextDeps[i], prevDeps[i])) {
522 continue;
523 }
524 return false;
525 }
526 return true;
527}
528
529var Updater = function () {
530 function Updater(renderer) {
531 _classCallCheck(this, Updater);
532
533 this._renderer = renderer;
534 this._callbacks = [];
535 }
536
537 Updater.prototype._enqueueCallback = function _enqueueCallback(callback, publicInstance) {
538 if (typeof callback === 'function' && publicInstance) {
539 this._callbacks.push({
540 callback: callback,
541 publicInstance: publicInstance
542 });
543 }
544 };
545
546 Updater.prototype._invokeCallbacks = function _invokeCallbacks() {
547 var callbacks = this._callbacks;
548 this._callbacks = [];
549
550 callbacks.forEach(function (_ref) {
551 var callback = _ref.callback,
552 publicInstance = _ref.publicInstance;
553
554 callback.call(publicInstance);
555 });
556 };
557
558 Updater.prototype.isMounted = function isMounted(publicInstance) {
559 return !!this._renderer._element;
560 };
561
562 Updater.prototype.enqueueForceUpdate = function enqueueForceUpdate(publicInstance, callback, callerName) {
563 this._enqueueCallback(callback, publicInstance);
564 this._renderer._forcedUpdate = true;
565 this._renderer.render(this._renderer._element, this._renderer._context);
566 };
567
568 Updater.prototype.enqueueReplaceState = function enqueueReplaceState(publicInstance, completeState, callback, callerName) {
569 this._enqueueCallback(callback, publicInstance);
570 this._renderer._newState = completeState;
571 this._renderer.render(this._renderer._element, this._renderer._context);
572 };
573
574 Updater.prototype.enqueueSetState = function enqueueSetState(publicInstance, partialState, callback, callerName) {
575 this._enqueueCallback(callback, publicInstance);
576 var currentState = this._renderer._newState || publicInstance.state;
577
578 if (typeof partialState === 'function') {
579 partialState = partialState.call(publicInstance, currentState, publicInstance.props);
580 }
581
582 // Null and undefined are treated as no-ops.
583 if (partialState === null || partialState === undefined) {
584 return;
585 }
586
587 this._renderer._newState = _assign({}, currentState, partialState);
588
589 this._renderer.render(this._renderer._element, this._renderer._context);
590 };
591
592 return Updater;
593}();
594
595function createHook() {
596 return {
597 memoizedState: null,
598 queue: null,
599 next: null
600 };
601}
602
603function basicStateReducer(state, action) {
604 return typeof action === 'function' ? action(state) : action;
605}
606
607var ReactShallowRenderer = function () {
608 function ReactShallowRenderer() {
609 _classCallCheck(this, ReactShallowRenderer);
610
611 this._context = null;
612 this._element = null;
613 this._instance = null;
614 this._newState = null;
615 this._rendered = null;
616 this._rendering = false;
617 this._forcedUpdate = false;
618 this._updater = new Updater(this);
619 this._dispatcher = this._createDispatcher();
620 this._workInProgressHook = null;
621 this._firstWorkInProgressHook = null;
622 this._isReRender = false;
623 this._didScheduleRenderPhaseUpdate = false;
624 this._renderPhaseUpdates = null;
625 this._currentlyRenderingComponent = null;
626 this._numberOfReRenders = 0;
627 this._previousComponentIdentity = null;
628 }
629
630 ReactShallowRenderer.prototype._validateCurrentlyRenderingComponent = function _validateCurrentlyRenderingComponent() {
631 !(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;
632 };
633
634 ReactShallowRenderer.prototype._createDispatcher = function _createDispatcher() {
635 var _this = this;
636
637 var useReducer = function (reducer, initialArg, init) {
638 _this._validateCurrentlyRenderingComponent();
639 _this._createWorkInProgressHook();
640 var workInProgressHook = _this._workInProgressHook;
641 if (_this._isReRender) {
642 // This is a re-render. Apply the new render phase updates to the previous
643 var _queue = workInProgressHook.queue;
644 var _dispatch = _queue.dispatch;
645 if (_this._renderPhaseUpdates !== null) {
646 // Render phase updates are stored in a map of queue -> linked list
647 var firstRenderPhaseUpdate = _this._renderPhaseUpdates.get(_queue);
648 if (firstRenderPhaseUpdate !== undefined) {
649 _this._renderPhaseUpdates.delete(_queue);
650 var newState = workInProgressHook.memoizedState;
651 var update = firstRenderPhaseUpdate;
652 do {
653 // Process this render phase update. We don't have to check the
654 // priority because it will always be the same as the current
655 // render's.
656 var _action = update.action;
657 newState = reducer(newState, _action);
658 update = update.next;
659 } while (update !== null);
660
661 workInProgressHook.memoizedState = newState;
662
663 return [newState, _dispatch];
664 }
665 }
666 return [workInProgressHook.memoizedState, _dispatch];
667 } else {
668 var initialState = void 0;
669 if (reducer === basicStateReducer) {
670 // Special case for `useState`.
671 initialState = typeof initialArg === 'function' ? initialArg() : initialArg;
672 } else {
673 initialState = init !== undefined ? init(initialArg) : initialArg;
674 }
675 workInProgressHook.memoizedState = initialState;
676 var _queue2 = workInProgressHook.queue = {
677 last: null,
678 dispatch: null
679 };
680 var _dispatch2 = _queue2.dispatch = _this._dispatchAction.bind(_this, _this._currentlyRenderingComponent, _queue2);
681 return [workInProgressHook.memoizedState, _dispatch2];
682 }
683 };
684
685 var useState = function (initialState) {
686 return useReducer(basicStateReducer,
687 // useReducer has a special case to support lazy useState initializers
688 initialState);
689 };
690
691 var useMemo = function (nextCreate, deps) {
692 _this._validateCurrentlyRenderingComponent();
693 _this._createWorkInProgressHook();
694
695 var nextDeps = deps !== undefined ? deps : null;
696
697 if (_this._workInProgressHook !== null && _this._workInProgressHook.memoizedState !== null) {
698 var prevState = _this._workInProgressHook.memoizedState;
699 var prevDeps = prevState[1];
700 if (nextDeps !== null) {
701 if (areHookInputsEqual(nextDeps, prevDeps)) {
702 return prevState[0];
703 }
704 }
705 }
706
707 var nextValue = nextCreate();
708 _this._workInProgressHook.memoizedState = [nextValue, nextDeps];
709 return nextValue;
710 };
711
712 var useRef = function (initialValue) {
713 _this._validateCurrentlyRenderingComponent();
714 _this._createWorkInProgressHook();
715 var previousRef = _this._workInProgressHook.memoizedState;
716 if (previousRef === null) {
717 var ref = { current: initialValue };
718 {
719 Object.seal(ref);
720 }
721 _this._workInProgressHook.memoizedState = ref;
722 return ref;
723 } else {
724 return previousRef;
725 }
726 };
727
728 var readContext = function (context, observedBits) {
729 return context._currentValue;
730 };
731
732 var noOp = function () {
733 _this._validateCurrentlyRenderingComponent();
734 };
735
736 var identity = function (fn) {
737 return fn;
738 };
739
740 return {
741 readContext: readContext,
742 useCallback: identity,
743 useContext: function (context) {
744 _this._validateCurrentlyRenderingComponent();
745 return readContext(context);
746 },
747 useDebugValue: noOp,
748 useEffect: noOp,
749 useImperativeHandle: noOp,
750 useLayoutEffect: noOp,
751 useMemo: useMemo,
752 useReducer: useReducer,
753 useRef: useRef,
754 useState: useState
755 };
756 };
757
758 ReactShallowRenderer.prototype._dispatchAction = function _dispatchAction(componentIdentity, queue, action) {
759 !(this._numberOfReRenders < RE_RENDER_LIMIT) ? invariant(false, 'Too many re-renders. React limits the number of renders to prevent an infinite loop.') : void 0;
760
761 if (componentIdentity === this._currentlyRenderingComponent) {
762 // This is a render phase update. Stash it in a lazily-created map of
763 // queue -> linked list of updates. After this render pass, we'll restart
764 // and apply the stashed updates on top of the work-in-progress hook.
765 this._didScheduleRenderPhaseUpdate = true;
766 var update = {
767 action: action,
768 next: null
769 };
770 var renderPhaseUpdates = this._renderPhaseUpdates;
771 if (renderPhaseUpdates === null) {
772 this._renderPhaseUpdates = renderPhaseUpdates = new Map();
773 }
774 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
775 if (firstRenderPhaseUpdate === undefined) {
776 renderPhaseUpdates.set(queue, update);
777 } else {
778 // Append the update to the end of the list.
779 var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
780 while (lastRenderPhaseUpdate.next !== null) {
781 lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
782 }
783 lastRenderPhaseUpdate.next = update;
784 }
785 } else {
786 // This means an update has happened after the function component has
787 // returned. On the server this is a no-op. In React Fiber, the update
788 // would be scheduled for a future render.
789 }
790 };
791
792 ReactShallowRenderer.prototype._createWorkInProgressHook = function _createWorkInProgressHook() {
793 if (this._workInProgressHook === null) {
794 // This is the first hook in the list
795 if (this._firstWorkInProgressHook === null) {
796 this._isReRender = false;
797 this._firstWorkInProgressHook = this._workInProgressHook = createHook();
798 } else {
799 // There's already a work-in-progress. Reuse it.
800 this._isReRender = true;
801 this._workInProgressHook = this._firstWorkInProgressHook;
802 }
803 } else {
804 if (this._workInProgressHook.next === null) {
805 this._isReRender = false;
806 // Append to the end of the list
807 this._workInProgressHook = this._workInProgressHook.next = createHook();
808 } else {
809 // There's already a work-in-progress. Reuse it.
810 this._isReRender = true;
811 this._workInProgressHook = this._workInProgressHook.next;
812 }
813 }
814 return this._workInProgressHook;
815 };
816
817 ReactShallowRenderer.prototype._prepareToUseHooks = function _prepareToUseHooks(componentIdentity) {
818 if (this._previousComponentIdentity !== null && this._previousComponentIdentity !== componentIdentity) {
819 this._firstWorkInProgressHook = null;
820 }
821 this._currentlyRenderingComponent = componentIdentity;
822 this._previousComponentIdentity = componentIdentity;
823 };
824
825 ReactShallowRenderer.prototype._finishHooks = function _finishHooks(element, context) {
826 if (this._didScheduleRenderPhaseUpdate) {
827 // Updates were scheduled during the render phase. They are stored in
828 // the `renderPhaseUpdates` map. Call the component again, reusing the
829 // work-in-progress hooks and applying the additional updates on top. Keep
830 // restarting until no more updates are scheduled.
831 this._didScheduleRenderPhaseUpdate = false;
832 this._numberOfReRenders += 1;
833
834 // Start over from the beginning of the list
835 this._workInProgressHook = null;
836 this._rendering = false;
837 this.render(element, context);
838 } else {
839 this._currentlyRenderingComponent = null;
840 this._workInProgressHook = null;
841 this._renderPhaseUpdates = null;
842 this._numberOfReRenders = 0;
843 }
844 };
845
846 ReactShallowRenderer.prototype.getMountedInstance = function getMountedInstance() {
847 return this._instance;
848 };
849
850 ReactShallowRenderer.prototype.getRenderOutput = function getRenderOutput() {
851 return this._rendered;
852 };
853
854 ReactShallowRenderer.prototype.render = function render(element) {
855 var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : emptyObject;
856
857 !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;
858 element = element;
859 // Show a special message for host elements since it's a common case.
860 !(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;
861 !(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;
862
863 if (this._rendering) {
864 return;
865 }
866
867 this._rendering = true;
868 this._element = element;
869 this._context = getMaskedContext(element.type.contextTypes, context);
870
871 if (this._instance) {
872 this._updateClassComponent(element, this._context);
873 } else {
874 if (isForwardRef(element)) {
875 this._rendered = element.type.render(element.props, element.ref);
876 } else if (shouldConstruct(element.type)) {
877 this._instance = new element.type(element.props, this._context, this._updater);
878
879 if (typeof element.type.getDerivedStateFromProps === 'function') {
880 var partialState = element.type.getDerivedStateFromProps.call(null, element.props, this._instance.state);
881 if (partialState != null) {
882 this._instance.state = _assign({}, this._instance.state, partialState);
883 }
884 }
885
886 if (element.type.hasOwnProperty('contextTypes')) {
887 currentlyValidatingElement = element;
888
889 checkPropTypes_1(element.type.contextTypes, this._context, 'context', getName(element.type, this._instance), getStackAddendum);
890
891 currentlyValidatingElement = null;
892 }
893
894 this._mountClassComponent(element, this._context);
895 } else {
896 var prevDispatcher = ReactCurrentDispatcher.current;
897 ReactCurrentDispatcher.current = this._dispatcher;
898 this._prepareToUseHooks(element.type);
899 try {
900 this._rendered = element.type.call(undefined, element.props, this._context);
901 } finally {
902 ReactCurrentDispatcher.current = prevDispatcher;
903 }
904 this._finishHooks(element, context);
905 }
906 }
907
908 this._rendering = false;
909 this._updater._invokeCallbacks();
910
911 return this.getRenderOutput();
912 };
913
914 ReactShallowRenderer.prototype.unmount = function unmount() {
915 if (this._instance) {
916 if (typeof this._instance.componentWillUnmount === 'function') {
917 this._instance.componentWillUnmount();
918 }
919 }
920
921 this._firstWorkInProgressHook = null;
922 this._previousComponentIdentity = null;
923 this._context = null;
924 this._element = null;
925 this._newState = null;
926 this._rendered = null;
927 this._instance = null;
928 };
929
930 ReactShallowRenderer.prototype._mountClassComponent = function _mountClassComponent(element, context) {
931 this._instance.context = context;
932 this._instance.props = element.props;
933 this._instance.state = this._instance.state || null;
934 this._instance.updater = this._updater;
935
936 if (typeof this._instance.UNSAFE_componentWillMount === 'function' || typeof this._instance.componentWillMount === 'function') {
937 var beforeState = this._newState;
938
939 // In order to support react-lifecycles-compat polyfilled components,
940 // Unsafe lifecycles should not be invoked for components using the new APIs.
941 if (typeof element.type.getDerivedStateFromProps !== 'function' && typeof this._instance.getSnapshotBeforeUpdate !== 'function') {
942 if (typeof this._instance.componentWillMount === 'function') {
943 this._instance.componentWillMount();
944 }
945 if (typeof this._instance.UNSAFE_componentWillMount === 'function') {
946 this._instance.UNSAFE_componentWillMount();
947 }
948 }
949
950 // setState may have been called during cWM
951 if (beforeState !== this._newState) {
952 this._instance.state = this._newState || emptyObject;
953 }
954 }
955
956 this._rendered = this._instance.render();
957 // Intentionally do not call componentDidMount()
958 // because DOM refs are not available.
959 };
960
961 ReactShallowRenderer.prototype._updateClassComponent = function _updateClassComponent(element, context) {
962 var props = element.props,
963 type = element.type;
964
965
966 var oldState = this._instance.state || emptyObject;
967 var oldProps = this._instance.props;
968
969 if (oldProps !== props) {
970 // In order to support react-lifecycles-compat polyfilled components,
971 // Unsafe lifecycles should not be invoked for components using the new APIs.
972 if (typeof element.type.getDerivedStateFromProps !== 'function' && typeof this._instance.getSnapshotBeforeUpdate !== 'function') {
973 if (typeof this._instance.componentWillReceiveProps === 'function') {
974 this._instance.componentWillReceiveProps(props, context);
975 }
976 if (typeof this._instance.UNSAFE_componentWillReceiveProps === 'function') {
977 this._instance.UNSAFE_componentWillReceiveProps(props, context);
978 }
979 }
980 }
981
982 // Read state after cWRP in case it calls setState
983 var state = this._newState || oldState;
984 if (typeof type.getDerivedStateFromProps === 'function') {
985 var partialState = type.getDerivedStateFromProps.call(null, props, state);
986 if (partialState != null) {
987 state = _assign({}, state, partialState);
988 }
989 }
990
991 var shouldUpdate = true;
992 if (this._forcedUpdate) {
993 shouldUpdate = true;
994 this._forcedUpdate = false;
995 } else if (typeof this._instance.shouldComponentUpdate === 'function') {
996 shouldUpdate = !!this._instance.shouldComponentUpdate(props, state, context);
997 } else if (type.prototype && type.prototype.isPureReactComponent) {
998 shouldUpdate = !shallowEqual(oldProps, props) || !shallowEqual(oldState, state);
999 }
1000
1001 if (shouldUpdate) {
1002 // In order to support react-lifecycles-compat polyfilled components,
1003 // Unsafe lifecycles should not be invoked for components using the new APIs.
1004 if (typeof element.type.getDerivedStateFromProps !== 'function' && typeof this._instance.getSnapshotBeforeUpdate !== 'function') {
1005 if (typeof this._instance.componentWillUpdate === 'function') {
1006 this._instance.componentWillUpdate(props, state, context);
1007 }
1008 if (typeof this._instance.UNSAFE_componentWillUpdate === 'function') {
1009 this._instance.UNSAFE_componentWillUpdate(props, state, context);
1010 }
1011 }
1012 }
1013
1014 this._instance.context = context;
1015 this._instance.props = props;
1016 this._instance.state = state;
1017 this._newState = null;
1018
1019 if (shouldUpdate) {
1020 this._rendered = this._instance.render();
1021 }
1022 // Intentionally do not call componentDidUpdate()
1023 // because DOM refs are not available.
1024 };
1025
1026 return ReactShallowRenderer;
1027}();
1028
1029ReactShallowRenderer.createRenderer = function () {
1030 return new ReactShallowRenderer();
1031};
1032
1033var currentlyValidatingElement = null;
1034
1035function getDisplayName(element) {
1036 if (element == null) {
1037 return '#empty';
1038 } else if (typeof element === 'string' || typeof element === 'number') {
1039 return '#text';
1040 } else if (typeof element.type === 'string') {
1041 return element.type;
1042 } else {
1043 return element.type.displayName || element.type.name || 'Unknown';
1044 }
1045}
1046
1047function getStackAddendum() {
1048 var stack = '';
1049 if (currentlyValidatingElement) {
1050 var name = getDisplayName(currentlyValidatingElement);
1051 var owner = currentlyValidatingElement._owner;
1052 stack += describeComponentFrame(name, currentlyValidatingElement._source, owner && getComponentName(owner.type));
1053 }
1054 return stack;
1055}
1056
1057function getName(type, instance) {
1058 var constructor = instance && instance.constructor;
1059 return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null;
1060}
1061
1062function shouldConstruct(Component) {
1063 return !!(Component.prototype && Component.prototype.isReactComponent);
1064}
1065
1066function getMaskedContext(contextTypes, unmaskedContext) {
1067 if (!contextTypes || !unmaskedContext) {
1068 return emptyObject;
1069 }
1070 var context = {};
1071 for (var key in contextTypes) {
1072 context[key] = unmaskedContext[key];
1073 }
1074 return context;
1075}
1076
1077
1078
1079var ReactShallowRenderer$2 = Object.freeze({
1080 default: ReactShallowRenderer
1081});
1082
1083var ReactShallowRenderer$3 = ( ReactShallowRenderer$2 && ReactShallowRenderer ) || ReactShallowRenderer$2;
1084
1085// TODO: decide on the top-level export form.
1086// This is hacky but makes it work with both Rollup and Jest.
1087var shallow = ReactShallowRenderer$3.default || ReactShallowRenderer$3;
1088
1089return shallow;
1090
1091})));