react-test-renderer-shallow.development.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. /** @license React v16.8.3
  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. 'use strict';
  10. if (process.env.NODE_ENV !== "production") {
  11. (function() {
  12. 'use strict';
  13. var _assign = require('object-assign');
  14. var React = require('react');
  15. var reactIs = require('react-is');
  16. var checkPropTypes = require('prop-types/checkPropTypes');
  17. /**
  18. * Use invariant() to assert state which your program assumes to be true.
  19. *
  20. * Provide sprintf-style format (only %s is supported) and arguments
  21. * to provide information about what broke and what you were
  22. * expecting.
  23. *
  24. * The invariant message will be stripped in production, but the invariant
  25. * will remain to ensure logic does not differ in production.
  26. */
  27. var validateFormat = function () {};
  28. {
  29. validateFormat = function (format) {
  30. if (format === undefined) {
  31. throw new Error('invariant requires an error message argument');
  32. }
  33. };
  34. }
  35. function invariant(condition, format, a, b, c, d, e, f) {
  36. validateFormat(format);
  37. if (!condition) {
  38. var error = void 0;
  39. if (format === undefined) {
  40. error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
  41. } else {
  42. var args = [a, b, c, d, e, f];
  43. var argIndex = 0;
  44. error = new Error(format.replace(/%s/g, function () {
  45. return args[argIndex++];
  46. }));
  47. error.name = 'Invariant Violation';
  48. }
  49. error.framesToPop = 1; // we don't care about invariant's own frame
  50. throw error;
  51. }
  52. }
  53. // Relying on the `invariant()` implementation lets us
  54. // preserve the format and params in the www builds.
  55. var BEFORE_SLASH_RE = /^(.*)[\\\/]/;
  56. var describeComponentFrame = function (name, source, ownerName) {
  57. var sourceInfo = '';
  58. if (source) {
  59. var path = source.fileName;
  60. var fileName = path.replace(BEFORE_SLASH_RE, '');
  61. {
  62. // In DEV, include code for a common special case:
  63. // prefer "folder/index.js" instead of just "index.js".
  64. if (/^index\./.test(fileName)) {
  65. var match = path.match(BEFORE_SLASH_RE);
  66. if (match) {
  67. var pathBeforeSlash = match[1];
  68. if (pathBeforeSlash) {
  69. var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
  70. fileName = folderName + '/' + fileName;
  71. }
  72. }
  73. }
  74. }
  75. sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
  76. } else if (ownerName) {
  77. sourceInfo = ' (created by ' + ownerName + ')';
  78. }
  79. return '\n in ' + (name || 'Unknown') + sourceInfo;
  80. };
  81. /**
  82. * Similar to invariant but only logs a warning if the condition is not met.
  83. * This can be used to log issues in development environments in critical
  84. * paths. Removing the logging code for production environments will keep the
  85. * same logic and follow the same code paths.
  86. */
  87. var warningWithoutStack = function () {};
  88. {
  89. warningWithoutStack = function (condition, format) {
  90. for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  91. args[_key - 2] = arguments[_key];
  92. }
  93. if (format === undefined) {
  94. throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
  95. }
  96. if (args.length > 8) {
  97. // Check before the condition to catch violations early.
  98. throw new Error('warningWithoutStack() currently supports at most 8 arguments.');
  99. }
  100. if (condition) {
  101. return;
  102. }
  103. if (typeof console !== 'undefined') {
  104. var argsWithFormat = args.map(function (item) {
  105. return '' + item;
  106. });
  107. argsWithFormat.unshift('Warning: ' + format);
  108. // We intentionally don't use spread (or .apply) directly because it
  109. // breaks IE9: https://github.com/facebook/react/issues/13610
  110. Function.prototype.apply.call(console.error, console, argsWithFormat);
  111. }
  112. try {
  113. // --- Welcome to debugging React ---
  114. // This error was thrown as a convenience so that you can use this stack
  115. // to find the callsite that caused this warning to fire.
  116. var argIndex = 0;
  117. var message = 'Warning: ' + format.replace(/%s/g, function () {
  118. return args[argIndex++];
  119. });
  120. throw new Error(message);
  121. } catch (x) {}
  122. };
  123. }
  124. var warningWithoutStack$1 = warningWithoutStack;
  125. // The Symbol used to tag the ReactElement-like types. If there is no native Symbol
  126. // nor polyfill, then a plain number is used for performance.
  127. var hasSymbol = typeof Symbol === 'function' && Symbol.for;
  128. var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
  129. var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
  130. var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
  131. var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
  132. var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
  133. var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
  134. var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
  135. var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
  136. var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
  137. var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
  138. var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
  139. var Resolved = 1;
  140. function refineResolvedLazyComponent(lazyComponent) {
  141. return lazyComponent._status === Resolved ? lazyComponent._result : null;
  142. }
  143. function getWrappedName(outerType, innerType, wrapperName) {
  144. var functionName = innerType.displayName || innerType.name || '';
  145. return outerType.displayName || (functionName !== '' ? wrapperName + '(' + functionName + ')' : wrapperName);
  146. }
  147. function getComponentName(type) {
  148. if (type == null) {
  149. // Host root, text node or just invalid type.
  150. return null;
  151. }
  152. {
  153. if (typeof type.tag === 'number') {
  154. warningWithoutStack$1(false, 'Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
  155. }
  156. }
  157. if (typeof type === 'function') {
  158. return type.displayName || type.name || null;
  159. }
  160. if (typeof type === 'string') {
  161. return type;
  162. }
  163. switch (type) {
  164. case REACT_CONCURRENT_MODE_TYPE:
  165. return 'ConcurrentMode';
  166. case REACT_FRAGMENT_TYPE:
  167. return 'Fragment';
  168. case REACT_PORTAL_TYPE:
  169. return 'Portal';
  170. case REACT_PROFILER_TYPE:
  171. return 'Profiler';
  172. case REACT_STRICT_MODE_TYPE:
  173. return 'StrictMode';
  174. case REACT_SUSPENSE_TYPE:
  175. return 'Suspense';
  176. }
  177. if (typeof type === 'object') {
  178. switch (type.$$typeof) {
  179. case REACT_CONTEXT_TYPE:
  180. return 'Context.Consumer';
  181. case REACT_PROVIDER_TYPE:
  182. return 'Context.Provider';
  183. case REACT_FORWARD_REF_TYPE:
  184. return getWrappedName(type, type.render, 'ForwardRef');
  185. case REACT_MEMO_TYPE:
  186. return getComponentName(type.type);
  187. case REACT_LAZY_TYPE:
  188. {
  189. var thenable = type;
  190. var resolvedThenable = refineResolvedLazyComponent(thenable);
  191. if (resolvedThenable) {
  192. return getComponentName(resolvedThenable);
  193. }
  194. }
  195. }
  196. }
  197. return null;
  198. }
  199. /**
  200. * inlined Object.is polyfill to avoid requiring consumers ship their own
  201. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
  202. */
  203. function is(x, y) {
  204. return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
  205. ;
  206. }
  207. var hasOwnProperty = Object.prototype.hasOwnProperty;
  208. /**
  209. * Performs equality by iterating through keys on an object and returning false
  210. * when any key has values which are not strictly equal between the arguments.
  211. * Returns true when the values of all keys are strictly equal.
  212. */
  213. function shallowEqual(objA, objB) {
  214. if (is(objA, objB)) {
  215. return true;
  216. }
  217. if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
  218. return false;
  219. }
  220. var keysA = Object.keys(objA);
  221. var keysB = Object.keys(objB);
  222. if (keysA.length !== keysB.length) {
  223. return false;
  224. }
  225. // Test for A's keys different from B.
  226. for (var i = 0; i < keysA.length; i++) {
  227. if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
  228. return false;
  229. }
  230. }
  231. return true;
  232. }
  233. var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  234. // Prevent newer renderers from RTE when used with older react package versions.
  235. // Current owner and dispatcher used to share the same ref,
  236. // but PR #14548 split them out to better support the react-debug-tools package.
  237. if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {
  238. ReactSharedInternals.ReactCurrentDispatcher = {
  239. current: null
  240. };
  241. }
  242. /**
  243. * Similar to invariant but only logs a warning if the condition is not met.
  244. * This can be used to log issues in development environments in critical
  245. * paths. Removing the logging code for production environments will keep the
  246. * same logic and follow the same code paths.
  247. */
  248. var warning = warningWithoutStack$1;
  249. {
  250. warning = function (condition, format) {
  251. if (condition) {
  252. return;
  253. }
  254. var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
  255. var stack = ReactDebugCurrentFrame.getStackAddendum();
  256. // eslint-disable-next-line react-internal/warning-and-invariant-args
  257. for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  258. args[_key - 2] = arguments[_key];
  259. }
  260. warningWithoutStack$1.apply(undefined, [false, format + '%s'].concat(args, [stack]));
  261. };
  262. }
  263. var warning$1 = warning;
  264. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  265. var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
  266. var RE_RENDER_LIMIT = 25;
  267. var emptyObject = {};
  268. {
  269. Object.freeze(emptyObject);
  270. }
  271. // In DEV, this is the name of the currently executing primitive hook
  272. var currentHookNameInDev = void 0;
  273. function areHookInputsEqual(nextDeps, prevDeps) {
  274. if (prevDeps === null) {
  275. 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);
  276. return false;
  277. }
  278. // Don't bother comparing lengths in prod because these arrays should be
  279. // passed inline.
  280. if (nextDeps.length !== prevDeps.length) {
  281. 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(', ') + ']');
  282. }
  283. for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
  284. if (is(nextDeps[i], prevDeps[i])) {
  285. continue;
  286. }
  287. return false;
  288. }
  289. return true;
  290. }
  291. var Updater = function () {
  292. function Updater(renderer) {
  293. _classCallCheck(this, Updater);
  294. this._renderer = renderer;
  295. this._callbacks = [];
  296. }
  297. Updater.prototype._enqueueCallback = function _enqueueCallback(callback, publicInstance) {
  298. if (typeof callback === 'function' && publicInstance) {
  299. this._callbacks.push({
  300. callback: callback,
  301. publicInstance: publicInstance
  302. });
  303. }
  304. };
  305. Updater.prototype._invokeCallbacks = function _invokeCallbacks() {
  306. var callbacks = this._callbacks;
  307. this._callbacks = [];
  308. callbacks.forEach(function (_ref) {
  309. var callback = _ref.callback,
  310. publicInstance = _ref.publicInstance;
  311. callback.call(publicInstance);
  312. });
  313. };
  314. Updater.prototype.isMounted = function isMounted(publicInstance) {
  315. return !!this._renderer._element;
  316. };
  317. Updater.prototype.enqueueForceUpdate = function enqueueForceUpdate(publicInstance, callback, callerName) {
  318. this._enqueueCallback(callback, publicInstance);
  319. this._renderer._forcedUpdate = true;
  320. this._renderer.render(this._renderer._element, this._renderer._context);
  321. };
  322. Updater.prototype.enqueueReplaceState = function enqueueReplaceState(publicInstance, completeState, callback, callerName) {
  323. this._enqueueCallback(callback, publicInstance);
  324. this._renderer._newState = completeState;
  325. this._renderer.render(this._renderer._element, this._renderer._context);
  326. };
  327. Updater.prototype.enqueueSetState = function enqueueSetState(publicInstance, partialState, callback, callerName) {
  328. this._enqueueCallback(callback, publicInstance);
  329. var currentState = this._renderer._newState || publicInstance.state;
  330. if (typeof partialState === 'function') {
  331. partialState = partialState.call(publicInstance, currentState, publicInstance.props);
  332. }
  333. // Null and undefined are treated as no-ops.
  334. if (partialState === null || partialState === undefined) {
  335. return;
  336. }
  337. this._renderer._newState = _assign({}, currentState, partialState);
  338. this._renderer.render(this._renderer._element, this._renderer._context);
  339. };
  340. return Updater;
  341. }();
  342. function createHook() {
  343. return {
  344. memoizedState: null,
  345. queue: null,
  346. next: null
  347. };
  348. }
  349. function basicStateReducer(state, action) {
  350. return typeof action === 'function' ? action(state) : action;
  351. }
  352. var ReactShallowRenderer = function () {
  353. function ReactShallowRenderer() {
  354. _classCallCheck(this, ReactShallowRenderer);
  355. this._context = null;
  356. this._element = null;
  357. this._instance = null;
  358. this._newState = null;
  359. this._rendered = null;
  360. this._rendering = false;
  361. this._forcedUpdate = false;
  362. this._updater = new Updater(this);
  363. this._dispatcher = this._createDispatcher();
  364. this._workInProgressHook = null;
  365. this._firstWorkInProgressHook = null;
  366. this._isReRender = false;
  367. this._didScheduleRenderPhaseUpdate = false;
  368. this._renderPhaseUpdates = null;
  369. this._currentlyRenderingComponent = null;
  370. this._numberOfReRenders = 0;
  371. this._previousComponentIdentity = null;
  372. }
  373. ReactShallowRenderer.prototype._validateCurrentlyRenderingComponent = function _validateCurrentlyRenderingComponent() {
  374. !(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;
  375. };
  376. ReactShallowRenderer.prototype._createDispatcher = function _createDispatcher() {
  377. var _this = this;
  378. var useReducer = function (reducer, initialArg, init) {
  379. _this._validateCurrentlyRenderingComponent();
  380. _this._createWorkInProgressHook();
  381. var workInProgressHook = _this._workInProgressHook;
  382. if (_this._isReRender) {
  383. // This is a re-render. Apply the new render phase updates to the previous
  384. var _queue = workInProgressHook.queue;
  385. var _dispatch = _queue.dispatch;
  386. if (_this._renderPhaseUpdates !== null) {
  387. // Render phase updates are stored in a map of queue -> linked list
  388. var firstRenderPhaseUpdate = _this._renderPhaseUpdates.get(_queue);
  389. if (firstRenderPhaseUpdate !== undefined) {
  390. _this._renderPhaseUpdates.delete(_queue);
  391. var newState = workInProgressHook.memoizedState;
  392. var update = firstRenderPhaseUpdate;
  393. do {
  394. // Process this render phase update. We don't have to check the
  395. // priority because it will always be the same as the current
  396. // render's.
  397. var _action = update.action;
  398. newState = reducer(newState, _action);
  399. update = update.next;
  400. } while (update !== null);
  401. workInProgressHook.memoizedState = newState;
  402. return [newState, _dispatch];
  403. }
  404. }
  405. return [workInProgressHook.memoizedState, _dispatch];
  406. } else {
  407. var initialState = void 0;
  408. if (reducer === basicStateReducer) {
  409. // Special case for `useState`.
  410. initialState = typeof initialArg === 'function' ? initialArg() : initialArg;
  411. } else {
  412. initialState = init !== undefined ? init(initialArg) : initialArg;
  413. }
  414. workInProgressHook.memoizedState = initialState;
  415. var _queue2 = workInProgressHook.queue = {
  416. last: null,
  417. dispatch: null
  418. };
  419. var _dispatch2 = _queue2.dispatch = _this._dispatchAction.bind(_this, _this._currentlyRenderingComponent, _queue2);
  420. return [workInProgressHook.memoizedState, _dispatch2];
  421. }
  422. };
  423. var useState = function (initialState) {
  424. return useReducer(basicStateReducer,
  425. // useReducer has a special case to support lazy useState initializers
  426. initialState);
  427. };
  428. var useMemo = function (nextCreate, deps) {
  429. _this._validateCurrentlyRenderingComponent();
  430. _this._createWorkInProgressHook();
  431. var nextDeps = deps !== undefined ? deps : null;
  432. if (_this._workInProgressHook !== null && _this._workInProgressHook.memoizedState !== null) {
  433. var prevState = _this._workInProgressHook.memoizedState;
  434. var prevDeps = prevState[1];
  435. if (nextDeps !== null) {
  436. if (areHookInputsEqual(nextDeps, prevDeps)) {
  437. return prevState[0];
  438. }
  439. }
  440. }
  441. var nextValue = nextCreate();
  442. _this._workInProgressHook.memoizedState = [nextValue, nextDeps];
  443. return nextValue;
  444. };
  445. var useRef = function (initialValue) {
  446. _this._validateCurrentlyRenderingComponent();
  447. _this._createWorkInProgressHook();
  448. var previousRef = _this._workInProgressHook.memoizedState;
  449. if (previousRef === null) {
  450. var ref = { current: initialValue };
  451. {
  452. Object.seal(ref);
  453. }
  454. _this._workInProgressHook.memoizedState = ref;
  455. return ref;
  456. } else {
  457. return previousRef;
  458. }
  459. };
  460. var readContext = function (context, observedBits) {
  461. return context._currentValue;
  462. };
  463. var noOp = function () {
  464. _this._validateCurrentlyRenderingComponent();
  465. };
  466. var identity = function (fn) {
  467. return fn;
  468. };
  469. return {
  470. readContext: readContext,
  471. useCallback: identity,
  472. useContext: function (context) {
  473. _this._validateCurrentlyRenderingComponent();
  474. return readContext(context);
  475. },
  476. useDebugValue: noOp,
  477. useEffect: noOp,
  478. useImperativeHandle: noOp,
  479. useLayoutEffect: noOp,
  480. useMemo: useMemo,
  481. useReducer: useReducer,
  482. useRef: useRef,
  483. useState: useState
  484. };
  485. };
  486. ReactShallowRenderer.prototype._dispatchAction = function _dispatchAction(componentIdentity, queue, action) {
  487. !(this._numberOfReRenders < RE_RENDER_LIMIT) ? invariant(false, 'Too many re-renders. React limits the number of renders to prevent an infinite loop.') : void 0;
  488. if (componentIdentity === this._currentlyRenderingComponent) {
  489. // This is a render phase update. Stash it in a lazily-created map of
  490. // queue -> linked list of updates. After this render pass, we'll restart
  491. // and apply the stashed updates on top of the work-in-progress hook.
  492. this._didScheduleRenderPhaseUpdate = true;
  493. var update = {
  494. action: action,
  495. next: null
  496. };
  497. var renderPhaseUpdates = this._renderPhaseUpdates;
  498. if (renderPhaseUpdates === null) {
  499. this._renderPhaseUpdates = renderPhaseUpdates = new Map();
  500. }
  501. var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
  502. if (firstRenderPhaseUpdate === undefined) {
  503. renderPhaseUpdates.set(queue, update);
  504. } else {
  505. // Append the update to the end of the list.
  506. var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
  507. while (lastRenderPhaseUpdate.next !== null) {
  508. lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
  509. }
  510. lastRenderPhaseUpdate.next = update;
  511. }
  512. } else {
  513. // This means an update has happened after the function component has
  514. // returned. On the server this is a no-op. In React Fiber, the update
  515. // would be scheduled for a future render.
  516. }
  517. };
  518. ReactShallowRenderer.prototype._createWorkInProgressHook = function _createWorkInProgressHook() {
  519. if (this._workInProgressHook === null) {
  520. // This is the first hook in the list
  521. if (this._firstWorkInProgressHook === null) {
  522. this._isReRender = false;
  523. this._firstWorkInProgressHook = this._workInProgressHook = createHook();
  524. } else {
  525. // There's already a work-in-progress. Reuse it.
  526. this._isReRender = true;
  527. this._workInProgressHook = this._firstWorkInProgressHook;
  528. }
  529. } else {
  530. if (this._workInProgressHook.next === null) {
  531. this._isReRender = false;
  532. // Append to the end of the list
  533. this._workInProgressHook = this._workInProgressHook.next = createHook();
  534. } else {
  535. // There's already a work-in-progress. Reuse it.
  536. this._isReRender = true;
  537. this._workInProgressHook = this._workInProgressHook.next;
  538. }
  539. }
  540. return this._workInProgressHook;
  541. };
  542. ReactShallowRenderer.prototype._prepareToUseHooks = function _prepareToUseHooks(componentIdentity) {
  543. if (this._previousComponentIdentity !== null && this._previousComponentIdentity !== componentIdentity) {
  544. this._firstWorkInProgressHook = null;
  545. }
  546. this._currentlyRenderingComponent = componentIdentity;
  547. this._previousComponentIdentity = componentIdentity;
  548. };
  549. ReactShallowRenderer.prototype._finishHooks = function _finishHooks(element, context) {
  550. if (this._didScheduleRenderPhaseUpdate) {
  551. // Updates were scheduled during the render phase. They are stored in
  552. // the `renderPhaseUpdates` map. Call the component again, reusing the
  553. // work-in-progress hooks and applying the additional updates on top. Keep
  554. // restarting until no more updates are scheduled.
  555. this._didScheduleRenderPhaseUpdate = false;
  556. this._numberOfReRenders += 1;
  557. // Start over from the beginning of the list
  558. this._workInProgressHook = null;
  559. this._rendering = false;
  560. this.render(element, context);
  561. } else {
  562. this._currentlyRenderingComponent = null;
  563. this._workInProgressHook = null;
  564. this._renderPhaseUpdates = null;
  565. this._numberOfReRenders = 0;
  566. }
  567. };
  568. ReactShallowRenderer.prototype.getMountedInstance = function getMountedInstance() {
  569. return this._instance;
  570. };
  571. ReactShallowRenderer.prototype.getRenderOutput = function getRenderOutput() {
  572. return this._rendered;
  573. };
  574. ReactShallowRenderer.prototype.render = function render(element) {
  575. var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : emptyObject;
  576. !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;
  577. element = element;
  578. // Show a special message for host elements since it's a common case.
  579. !(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;
  580. !(reactIs.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;
  581. if (this._rendering) {
  582. return;
  583. }
  584. this._rendering = true;
  585. this._element = element;
  586. this._context = getMaskedContext(element.type.contextTypes, context);
  587. if (this._instance) {
  588. this._updateClassComponent(element, this._context);
  589. } else {
  590. if (reactIs.isForwardRef(element)) {
  591. this._rendered = element.type.render(element.props, element.ref);
  592. } else if (shouldConstruct(element.type)) {
  593. this._instance = new element.type(element.props, this._context, this._updater);
  594. if (typeof element.type.getDerivedStateFromProps === 'function') {
  595. var partialState = element.type.getDerivedStateFromProps.call(null, element.props, this._instance.state);
  596. if (partialState != null) {
  597. this._instance.state = _assign({}, this._instance.state, partialState);
  598. }
  599. }
  600. if (element.type.hasOwnProperty('contextTypes')) {
  601. currentlyValidatingElement = element;
  602. checkPropTypes(element.type.contextTypes, this._context, 'context', getName(element.type, this._instance), getStackAddendum);
  603. currentlyValidatingElement = null;
  604. }
  605. this._mountClassComponent(element, this._context);
  606. } else {
  607. var prevDispatcher = ReactCurrentDispatcher.current;
  608. ReactCurrentDispatcher.current = this._dispatcher;
  609. this._prepareToUseHooks(element.type);
  610. try {
  611. this._rendered = element.type.call(undefined, element.props, this._context);
  612. } finally {
  613. ReactCurrentDispatcher.current = prevDispatcher;
  614. }
  615. this._finishHooks(element, context);
  616. }
  617. }
  618. this._rendering = false;
  619. this._updater._invokeCallbacks();
  620. return this.getRenderOutput();
  621. };
  622. ReactShallowRenderer.prototype.unmount = function unmount() {
  623. if (this._instance) {
  624. if (typeof this._instance.componentWillUnmount === 'function') {
  625. this._instance.componentWillUnmount();
  626. }
  627. }
  628. this._firstWorkInProgressHook = null;
  629. this._previousComponentIdentity = null;
  630. this._context = null;
  631. this._element = null;
  632. this._newState = null;
  633. this._rendered = null;
  634. this._instance = null;
  635. };
  636. ReactShallowRenderer.prototype._mountClassComponent = function _mountClassComponent(element, context) {
  637. this._instance.context = context;
  638. this._instance.props = element.props;
  639. this._instance.state = this._instance.state || null;
  640. this._instance.updater = this._updater;
  641. if (typeof this._instance.UNSAFE_componentWillMount === 'function' || typeof this._instance.componentWillMount === 'function') {
  642. var beforeState = this._newState;
  643. // In order to support react-lifecycles-compat polyfilled components,
  644. // Unsafe lifecycles should not be invoked for components using the new APIs.
  645. if (typeof element.type.getDerivedStateFromProps !== 'function' && typeof this._instance.getSnapshotBeforeUpdate !== 'function') {
  646. if (typeof this._instance.componentWillMount === 'function') {
  647. this._instance.componentWillMount();
  648. }
  649. if (typeof this._instance.UNSAFE_componentWillMount === 'function') {
  650. this._instance.UNSAFE_componentWillMount();
  651. }
  652. }
  653. // setState may have been called during cWM
  654. if (beforeState !== this._newState) {
  655. this._instance.state = this._newState || emptyObject;
  656. }
  657. }
  658. this._rendered = this._instance.render();
  659. // Intentionally do not call componentDidMount()
  660. // because DOM refs are not available.
  661. };
  662. ReactShallowRenderer.prototype._updateClassComponent = function _updateClassComponent(element, context) {
  663. var props = element.props,
  664. type = element.type;
  665. var oldState = this._instance.state || emptyObject;
  666. var oldProps = this._instance.props;
  667. if (oldProps !== props) {
  668. // In order to support react-lifecycles-compat polyfilled components,
  669. // Unsafe lifecycles should not be invoked for components using the new APIs.
  670. if (typeof element.type.getDerivedStateFromProps !== 'function' && typeof this._instance.getSnapshotBeforeUpdate !== 'function') {
  671. if (typeof this._instance.componentWillReceiveProps === 'function') {
  672. this._instance.componentWillReceiveProps(props, context);
  673. }
  674. if (typeof this._instance.UNSAFE_componentWillReceiveProps === 'function') {
  675. this._instance.UNSAFE_componentWillReceiveProps(props, context);
  676. }
  677. }
  678. }
  679. // Read state after cWRP in case it calls setState
  680. var state = this._newState || oldState;
  681. if (typeof type.getDerivedStateFromProps === 'function') {
  682. var partialState = type.getDerivedStateFromProps.call(null, props, state);
  683. if (partialState != null) {
  684. state = _assign({}, state, partialState);
  685. }
  686. }
  687. var shouldUpdate = true;
  688. if (this._forcedUpdate) {
  689. shouldUpdate = true;
  690. this._forcedUpdate = false;
  691. } else if (typeof this._instance.shouldComponentUpdate === 'function') {
  692. shouldUpdate = !!this._instance.shouldComponentUpdate(props, state, context);
  693. } else if (type.prototype && type.prototype.isPureReactComponent) {
  694. shouldUpdate = !shallowEqual(oldProps, props) || !shallowEqual(oldState, state);
  695. }
  696. if (shouldUpdate) {
  697. // In order to support react-lifecycles-compat polyfilled components,
  698. // Unsafe lifecycles should not be invoked for components using the new APIs.
  699. if (typeof element.type.getDerivedStateFromProps !== 'function' && typeof this._instance.getSnapshotBeforeUpdate !== 'function') {
  700. if (typeof this._instance.componentWillUpdate === 'function') {
  701. this._instance.componentWillUpdate(props, state, context);
  702. }
  703. if (typeof this._instance.UNSAFE_componentWillUpdate === 'function') {
  704. this._instance.UNSAFE_componentWillUpdate(props, state, context);
  705. }
  706. }
  707. }
  708. this._instance.context = context;
  709. this._instance.props = props;
  710. this._instance.state = state;
  711. this._newState = null;
  712. if (shouldUpdate) {
  713. this._rendered = this._instance.render();
  714. }
  715. // Intentionally do not call componentDidUpdate()
  716. // because DOM refs are not available.
  717. };
  718. return ReactShallowRenderer;
  719. }();
  720. ReactShallowRenderer.createRenderer = function () {
  721. return new ReactShallowRenderer();
  722. };
  723. var currentlyValidatingElement = null;
  724. function getDisplayName(element) {
  725. if (element == null) {
  726. return '#empty';
  727. } else if (typeof element === 'string' || typeof element === 'number') {
  728. return '#text';
  729. } else if (typeof element.type === 'string') {
  730. return element.type;
  731. } else {
  732. return element.type.displayName || element.type.name || 'Unknown';
  733. }
  734. }
  735. function getStackAddendum() {
  736. var stack = '';
  737. if (currentlyValidatingElement) {
  738. var name = getDisplayName(currentlyValidatingElement);
  739. var owner = currentlyValidatingElement._owner;
  740. stack += describeComponentFrame(name, currentlyValidatingElement._source, owner && getComponentName(owner.type));
  741. }
  742. return stack;
  743. }
  744. function getName(type, instance) {
  745. var constructor = instance && instance.constructor;
  746. return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null;
  747. }
  748. function shouldConstruct(Component) {
  749. return !!(Component.prototype && Component.prototype.isReactComponent);
  750. }
  751. function getMaskedContext(contextTypes, unmaskedContext) {
  752. if (!contextTypes || !unmaskedContext) {
  753. return emptyObject;
  754. }
  755. var context = {};
  756. for (var key in contextTypes) {
  757. context[key] = unmaskedContext[key];
  758. }
  759. return context;
  760. }
  761. var ReactShallowRenderer$2 = Object.freeze({
  762. default: ReactShallowRenderer
  763. });
  764. var ReactShallowRenderer$3 = ( ReactShallowRenderer$2 && ReactShallowRenderer ) || ReactShallowRenderer$2;
  765. // TODO: decide on the top-level export form.
  766. // This is hacky but makes it work with both Rollup and Jest.
  767. var shallow = ReactShallowRenderer$3.default || ReactShallowRenderer$3;
  768. module.exports = shallow;
  769. })();
  770. }