Dashboard sipadu mbip
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

react-dom-test-utils.development.js 56KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656
  1. /** @license React v16.12.0
  2. * react-dom-test-utils.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. (function (global, factory) {
  11. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react'), require('react-dom')) :
  12. typeof define === 'function' && define.amd ? define(['react', 'react-dom'], factory) :
  13. (global.ReactTestUtils = factory(global.React,global.ReactDOM));
  14. }(this, (function (React,ReactDOM) { 'use strict';
  15. var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  16. var _assign = ReactInternals.assign;
  17. // Do not require this module directly! Use normal `invariant` calls with
  18. // template literal strings. The messages will be replaced with error codes
  19. // during build.
  20. /**
  21. * Use invariant() to assert state which your program assumes to be true.
  22. *
  23. * Provide sprintf-style format (only %s is supported) and arguments
  24. * to provide information about what broke and what you were
  25. * expecting.
  26. *
  27. * The invariant message will be stripped in production, but the invariant
  28. * will remain to ensure logic does not differ in production.
  29. */
  30. /**
  31. * Similar to invariant but only logs a warning if the condition is not met.
  32. * This can be used to log issues in development environments in critical
  33. * paths. Removing the logging code for production environments will keep the
  34. * same logic and follow the same code paths.
  35. */
  36. var warningWithoutStack = function () {};
  37. {
  38. warningWithoutStack = function (condition, format) {
  39. for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  40. args[_key - 2] = arguments[_key];
  41. }
  42. if (format === undefined) {
  43. throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
  44. }
  45. if (args.length > 8) {
  46. // Check before the condition to catch violations early.
  47. throw new Error('warningWithoutStack() currently supports at most 8 arguments.');
  48. }
  49. if (condition) {
  50. return;
  51. }
  52. if (typeof console !== 'undefined') {
  53. var argsWithFormat = args.map(function (item) {
  54. return '' + item;
  55. });
  56. argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
  57. // breaks IE9: https://github.com/facebook/react/issues/13610
  58. Function.prototype.apply.call(console.error, console, argsWithFormat);
  59. }
  60. try {
  61. // --- Welcome to debugging React ---
  62. // This error was thrown as a convenience so that you can use this stack
  63. // to find the callsite that caused this warning to fire.
  64. var argIndex = 0;
  65. var message = 'Warning: ' + format.replace(/%s/g, function () {
  66. return args[argIndex++];
  67. });
  68. throw new Error(message);
  69. } catch (x) {}
  70. };
  71. }
  72. var warningWithoutStack$1 = warningWithoutStack;
  73. /**
  74. * `ReactInstanceMap` maintains a mapping from a public facing stateful
  75. * instance (key) and the internal representation (value). This allows public
  76. * methods to accept the user facing instance as an argument and map them back
  77. * to internal methods.
  78. *
  79. * Note that this module is currently shared and assumed to be stateless.
  80. * If this becomes an actual Map, that will break.
  81. */
  82. /**
  83. * This API should be called `delete` but we'd have to make sure to always
  84. * transform these to strings for IE support. When this transform is fully
  85. * supported we can rename it.
  86. */
  87. function get(key) {
  88. return key._reactInternalFiber;
  89. }
  90. var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions.
  91. // Current owner and dispatcher used to share the same ref,
  92. // but PR #14548 split them out to better support the react-debug-tools package.
  93. if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {
  94. ReactSharedInternals.ReactCurrentDispatcher = {
  95. current: null
  96. };
  97. }
  98. if (!ReactSharedInternals.hasOwnProperty('ReactCurrentBatchConfig')) {
  99. ReactSharedInternals.ReactCurrentBatchConfig = {
  100. suspense: null
  101. };
  102. }
  103. // The Symbol used to tag the ReactElement-like types. If there is no native Symbol
  104. // nor polyfill, then a plain number is used for performance.
  105. // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary
  106. // (unstable) APIs that have been removed. Can we remove the symbols?
  107. {
  108. }
  109. var FunctionComponent = 0;
  110. var ClassComponent = 1;
  111. // Before we know whether it is function or class
  112. var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
  113. // A subtree. Could be an entry point to a different renderer.
  114. var HostComponent = 5;
  115. var HostText = 6;
  116. // Don't change these two values. They're used by React Dev Tools.
  117. var NoEffect =
  118. /* */
  119. 0;
  120. // You can change the rest (and add more).
  121. var Placement =
  122. /* */
  123. 2;
  124. var Hydrating =
  125. /* */
  126. 1024;
  127. // Passive & Update & Callback & Ref & Snapshot
  128. // Union of all host effects
  129. // Helps identify side effects in render-phase lifecycle hooks and setState
  130. // reducers by double invoking them in Strict Mode.
  131. // To preserve the "Pause on caught exceptions" behavior of the debugger, we
  132. // replay the begin phase of a failed component inside invokeGuardedCallback.
  133. // Warn about deprecated, async-unsafe lifecycles; relates to RFC #6:
  134. // Gather advanced timing metrics for Profiler subtrees.
  135. // Trace which interactions trigger each commit.
  136. // SSR experiments
  137. // Only used in www builds.
  138. // Only used in www builds.
  139. // Disable javascript: URL strings in href for XSS protection.
  140. // React Fire: prevent the value and checked attributes from syncing
  141. // with their related DOM properties
  142. // These APIs will no longer be "unstable" in the upcoming 16.7 release,
  143. // Control this behavior with a flag to support 16.6 minor releases in the meanwhile.
  144. // Experimental React Flare event system and event components support.
  145. // Experimental Host Component support.
  146. // Experimental Scope support.
  147. // New API for JSX transforms to target - https://github.com/reactjs/rfcs/pull/107
  148. // We will enforce mocking scheduler with scheduler/unstable_mock at some point. (v17?)
  149. // Till then, we warn about the missing mock, but still fallback to a legacy mode compatible version
  150. // For tests, we flush suspense fallbacks in an act scope;
  151. // *except* in some of our own tests, where we test incremental loading states.
  152. // Add a callback property to suspense to notify which promises are currently
  153. // in the update queue. This allows reporting and tracing of what is causing
  154. // the user to see a loading state.
  155. // Also allows hydration callbacks to fire when a dehydrated boundary gets
  156. // hydrated or deleted.
  157. // Part of the simplification of React.createElement so we can eventually move
  158. // from React.createElement to React.jsx
  159. // https://github.com/reactjs/rfcs/blob/createlement-rfc/text/0000-create-element-changes.md
  160. // Flag to turn event.target and event.currentTarget in ReactNative from a reactTag to a component instance
  161. var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
  162. function getNearestMountedFiber(fiber) {
  163. var node = fiber;
  164. var nearestMounted = fiber;
  165. if (!fiber.alternate) {
  166. // If there is no alternate, this might be a new tree that isn't inserted
  167. // yet. If it is, then it will have a pending insertion effect on it.
  168. var nextNode = node;
  169. do {
  170. node = nextNode;
  171. if ((node.effectTag & (Placement | Hydrating)) !== NoEffect) {
  172. // This is an insertion or in-progress hydration. The nearest possible
  173. // mounted fiber is the parent but we need to continue to figure out
  174. // if that one is still mounted.
  175. nearestMounted = node.return;
  176. }
  177. nextNode = node.return;
  178. } while (nextNode);
  179. } else {
  180. while (node.return) {
  181. node = node.return;
  182. }
  183. }
  184. if (node.tag === HostRoot) {
  185. // TODO: Check if this was a nested HostRoot when used with
  186. // renderContainerIntoSubtree.
  187. return nearestMounted;
  188. } // If we didn't hit the root, that means that we're in an disconnected tree
  189. // that has been unmounted.
  190. return null;
  191. }
  192. function assertIsMounted(fiber) {
  193. if (!(getNearestMountedFiber(fiber) === fiber)) {
  194. {
  195. throw Error("Unable to find node on an unmounted component.");
  196. }
  197. }
  198. }
  199. function findCurrentFiberUsingSlowPath(fiber) {
  200. var alternate = fiber.alternate;
  201. if (!alternate) {
  202. // If there is no alternate, then we only need to check if it is mounted.
  203. var nearestMounted = getNearestMountedFiber(fiber);
  204. if (!(nearestMounted !== null)) {
  205. {
  206. throw Error("Unable to find node on an unmounted component.");
  207. }
  208. }
  209. if (nearestMounted !== fiber) {
  210. return null;
  211. }
  212. return fiber;
  213. } // If we have two possible branches, we'll walk backwards up to the root
  214. // to see what path the root points to. On the way we may hit one of the
  215. // special cases and we'll deal with them.
  216. var a = fiber;
  217. var b = alternate;
  218. while (true) {
  219. var parentA = a.return;
  220. if (parentA === null) {
  221. // We're at the root.
  222. break;
  223. }
  224. var parentB = parentA.alternate;
  225. if (parentB === null) {
  226. // There is no alternate. This is an unusual case. Currently, it only
  227. // happens when a Suspense component is hidden. An extra fragment fiber
  228. // is inserted in between the Suspense fiber and its children. Skip
  229. // over this extra fragment fiber and proceed to the next parent.
  230. var nextParent = parentA.return;
  231. if (nextParent !== null) {
  232. a = b = nextParent;
  233. continue;
  234. } // If there's no parent, we're at the root.
  235. break;
  236. } // If both copies of the parent fiber point to the same child, we can
  237. // assume that the child is current. This happens when we bailout on low
  238. // priority: the bailed out fiber's child reuses the current child.
  239. if (parentA.child === parentB.child) {
  240. var child = parentA.child;
  241. while (child) {
  242. if (child === a) {
  243. // We've determined that A is the current branch.
  244. assertIsMounted(parentA);
  245. return fiber;
  246. }
  247. if (child === b) {
  248. // We've determined that B is the current branch.
  249. assertIsMounted(parentA);
  250. return alternate;
  251. }
  252. child = child.sibling;
  253. } // We should never have an alternate for any mounting node. So the only
  254. // way this could possibly happen is if this was unmounted, if at all.
  255. {
  256. {
  257. throw Error("Unable to find node on an unmounted component.");
  258. }
  259. }
  260. }
  261. if (a.return !== b.return) {
  262. // The return pointer of A and the return pointer of B point to different
  263. // fibers. We assume that return pointers never criss-cross, so A must
  264. // belong to the child set of A.return, and B must belong to the child
  265. // set of B.return.
  266. a = parentA;
  267. b = parentB;
  268. } else {
  269. // The return pointers point to the same fiber. We'll have to use the
  270. // default, slow path: scan the child sets of each parent alternate to see
  271. // which child belongs to which set.
  272. //
  273. // Search parent A's child set
  274. var didFindChild = false;
  275. var _child = parentA.child;
  276. while (_child) {
  277. if (_child === a) {
  278. didFindChild = true;
  279. a = parentA;
  280. b = parentB;
  281. break;
  282. }
  283. if (_child === b) {
  284. didFindChild = true;
  285. b = parentA;
  286. a = parentB;
  287. break;
  288. }
  289. _child = _child.sibling;
  290. }
  291. if (!didFindChild) {
  292. // Search parent B's child set
  293. _child = parentB.child;
  294. while (_child) {
  295. if (_child === a) {
  296. didFindChild = true;
  297. a = parentB;
  298. b = parentA;
  299. break;
  300. }
  301. if (_child === b) {
  302. didFindChild = true;
  303. b = parentB;
  304. a = parentA;
  305. break;
  306. }
  307. _child = _child.sibling;
  308. }
  309. if (!didFindChild) {
  310. {
  311. throw Error("Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.");
  312. }
  313. }
  314. }
  315. }
  316. if (!(a.alternate === b)) {
  317. {
  318. throw Error("Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue.");
  319. }
  320. }
  321. } // If the root is not a host container, we're in a disconnected tree. I.e.
  322. // unmounted.
  323. if (!(a.tag === HostRoot)) {
  324. {
  325. throw Error("Unable to find node on an unmounted component.");
  326. }
  327. }
  328. if (a.stateNode.current === a) {
  329. // We've determined that A is the current branch.
  330. return fiber;
  331. } // Otherwise B has to be current branch.
  332. return alternate;
  333. }
  334. /* eslint valid-typeof: 0 */
  335. var EVENT_POOL_SIZE = 10;
  336. /**
  337. * @interface Event
  338. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  339. */
  340. var EventInterface = {
  341. type: null,
  342. target: null,
  343. // currentTarget is set when dispatching; no use in copying it here
  344. currentTarget: function () {
  345. return null;
  346. },
  347. eventPhase: null,
  348. bubbles: null,
  349. cancelable: null,
  350. timeStamp: function (event) {
  351. return event.timeStamp || Date.now();
  352. },
  353. defaultPrevented: null,
  354. isTrusted: null
  355. };
  356. function functionThatReturnsTrue() {
  357. return true;
  358. }
  359. function functionThatReturnsFalse() {
  360. return false;
  361. }
  362. /**
  363. * Synthetic events are dispatched by event plugins, typically in response to a
  364. * top-level event delegation handler.
  365. *
  366. * These systems should generally use pooling to reduce the frequency of garbage
  367. * collection. The system should check `isPersistent` to determine whether the
  368. * event should be released into the pool after being dispatched. Users that
  369. * need a persisted event should invoke `persist`.
  370. *
  371. * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
  372. * normalizing browser quirks. Subclasses do not necessarily have to implement a
  373. * DOM interface; custom application-specific events can also subclass this.
  374. *
  375. * @param {object} dispatchConfig Configuration used to dispatch this event.
  376. * @param {*} targetInst Marker identifying the event target.
  377. * @param {object} nativeEvent Native browser event.
  378. * @param {DOMEventTarget} nativeEventTarget Target node.
  379. */
  380. function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
  381. {
  382. // these have a getter/setter for warnings
  383. delete this.nativeEvent;
  384. delete this.preventDefault;
  385. delete this.stopPropagation;
  386. delete this.isDefaultPrevented;
  387. delete this.isPropagationStopped;
  388. }
  389. this.dispatchConfig = dispatchConfig;
  390. this._targetInst = targetInst;
  391. this.nativeEvent = nativeEvent;
  392. var Interface = this.constructor.Interface;
  393. for (var propName in Interface) {
  394. if (!Interface.hasOwnProperty(propName)) {
  395. continue;
  396. }
  397. {
  398. delete this[propName]; // this has a getter/setter for warnings
  399. }
  400. var normalize = Interface[propName];
  401. if (normalize) {
  402. this[propName] = normalize(nativeEvent);
  403. } else {
  404. if (propName === 'target') {
  405. this.target = nativeEventTarget;
  406. } else {
  407. this[propName] = nativeEvent[propName];
  408. }
  409. }
  410. }
  411. var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
  412. if (defaultPrevented) {
  413. this.isDefaultPrevented = functionThatReturnsTrue;
  414. } else {
  415. this.isDefaultPrevented = functionThatReturnsFalse;
  416. }
  417. this.isPropagationStopped = functionThatReturnsFalse;
  418. return this;
  419. }
  420. _assign(SyntheticEvent.prototype, {
  421. preventDefault: function () {
  422. this.defaultPrevented = true;
  423. var event = this.nativeEvent;
  424. if (!event) {
  425. return;
  426. }
  427. if (event.preventDefault) {
  428. event.preventDefault();
  429. } else if (typeof event.returnValue !== 'unknown') {
  430. event.returnValue = false;
  431. }
  432. this.isDefaultPrevented = functionThatReturnsTrue;
  433. },
  434. stopPropagation: function () {
  435. var event = this.nativeEvent;
  436. if (!event) {
  437. return;
  438. }
  439. if (event.stopPropagation) {
  440. event.stopPropagation();
  441. } else if (typeof event.cancelBubble !== 'unknown') {
  442. // The ChangeEventPlugin registers a "propertychange" event for
  443. // IE. This event does not support bubbling or cancelling, and
  444. // any references to cancelBubble throw "Member not found". A
  445. // typeof check of "unknown" circumvents this issue (and is also
  446. // IE specific).
  447. event.cancelBubble = true;
  448. }
  449. this.isPropagationStopped = functionThatReturnsTrue;
  450. },
  451. /**
  452. * We release all dispatched `SyntheticEvent`s after each event loop, adding
  453. * them back into the pool. This allows a way to hold onto a reference that
  454. * won't be added back into the pool.
  455. */
  456. persist: function () {
  457. this.isPersistent = functionThatReturnsTrue;
  458. },
  459. /**
  460. * Checks if this event should be released back into the pool.
  461. *
  462. * @return {boolean} True if this should not be released, false otherwise.
  463. */
  464. isPersistent: functionThatReturnsFalse,
  465. /**
  466. * `PooledClass` looks for `destructor` on each instance it releases.
  467. */
  468. destructor: function () {
  469. var Interface = this.constructor.Interface;
  470. for (var propName in Interface) {
  471. {
  472. Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
  473. }
  474. }
  475. this.dispatchConfig = null;
  476. this._targetInst = null;
  477. this.nativeEvent = null;
  478. this.isDefaultPrevented = functionThatReturnsFalse;
  479. this.isPropagationStopped = functionThatReturnsFalse;
  480. this._dispatchListeners = null;
  481. this._dispatchInstances = null;
  482. {
  483. Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
  484. Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse));
  485. Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse));
  486. Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {}));
  487. Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {}));
  488. }
  489. }
  490. });
  491. SyntheticEvent.Interface = EventInterface;
  492. /**
  493. * Helper to reduce boilerplate when creating subclasses.
  494. */
  495. SyntheticEvent.extend = function (Interface) {
  496. var Super = this;
  497. var E = function () {};
  498. E.prototype = Super.prototype;
  499. var prototype = new E();
  500. function Class() {
  501. return Super.apply(this, arguments);
  502. }
  503. _assign(prototype, Class.prototype);
  504. Class.prototype = prototype;
  505. Class.prototype.constructor = Class;
  506. Class.Interface = _assign({}, Super.Interface, Interface);
  507. Class.extend = Super.extend;
  508. addEventPoolingTo(Class);
  509. return Class;
  510. };
  511. addEventPoolingTo(SyntheticEvent);
  512. /**
  513. * Helper to nullify syntheticEvent instance properties when destructing
  514. *
  515. * @param {String} propName
  516. * @param {?object} getVal
  517. * @return {object} defineProperty object
  518. */
  519. function getPooledWarningPropertyDefinition(propName, getVal) {
  520. var isFunction = typeof getVal === 'function';
  521. return {
  522. configurable: true,
  523. set: set,
  524. get: get
  525. };
  526. function set(val) {
  527. var action = isFunction ? 'setting the method' : 'setting the property';
  528. warn(action, 'This is effectively a no-op');
  529. return val;
  530. }
  531. function get() {
  532. var action = isFunction ? 'accessing the method' : 'accessing the property';
  533. var result = isFunction ? 'This is a no-op function' : 'This is set to null';
  534. warn(action, result);
  535. return getVal;
  536. }
  537. function warn(action, result) {
  538. var warningCondition = false;
  539. !warningCondition ? warningWithoutStack$1(false, "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0;
  540. }
  541. }
  542. function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) {
  543. var EventConstructor = this;
  544. if (EventConstructor.eventPool.length) {
  545. var instance = EventConstructor.eventPool.pop();
  546. EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst);
  547. return instance;
  548. }
  549. return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst);
  550. }
  551. function releasePooledEvent(event) {
  552. var EventConstructor = this;
  553. if (!(event instanceof EventConstructor)) {
  554. {
  555. throw Error("Trying to release an event instance into a pool of a different type.");
  556. }
  557. }
  558. event.destructor();
  559. if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) {
  560. EventConstructor.eventPool.push(event);
  561. }
  562. }
  563. function addEventPoolingTo(EventConstructor) {
  564. EventConstructor.eventPool = [];
  565. EventConstructor.getPooled = getPooledEvent;
  566. EventConstructor.release = releasePooledEvent;
  567. }
  568. /**
  569. * Forked from fbjs/warning:
  570. * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
  571. *
  572. * Only change is we use console.warn instead of console.error,
  573. * and do nothing when 'console' is not supported.
  574. * This really simplifies the code.
  575. * ---
  576. * Similar to invariant but only logs a warning if the condition is not met.
  577. * This can be used to log issues in development environments in critical
  578. * paths. Removing the logging code for production environments will keep the
  579. * same logic and follow the same code paths.
  580. */
  581. var lowPriorityWarningWithoutStack = function () {};
  582. {
  583. var printWarning = function (format) {
  584. for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  585. args[_key - 1] = arguments[_key];
  586. }
  587. var argIndex = 0;
  588. var message = 'Warning: ' + format.replace(/%s/g, function () {
  589. return args[argIndex++];
  590. });
  591. if (typeof console !== 'undefined') {
  592. console.warn(message);
  593. }
  594. try {
  595. // --- Welcome to debugging React ---
  596. // This error was thrown as a convenience so that you can use this stack
  597. // to find the callsite that caused this warning to fire.
  598. throw new Error(message);
  599. } catch (x) {}
  600. };
  601. lowPriorityWarningWithoutStack = function (condition, format) {
  602. if (format === undefined) {
  603. throw new Error('`lowPriorityWarningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
  604. }
  605. if (!condition) {
  606. for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
  607. args[_key2 - 2] = arguments[_key2];
  608. }
  609. printWarning.apply(void 0, [format].concat(args));
  610. }
  611. };
  612. }
  613. var lowPriorityWarningWithoutStack$1 = lowPriorityWarningWithoutStack;
  614. /**
  615. * HTML nodeType values that represent the type of the node
  616. */
  617. var ELEMENT_NODE = 1;
  618. // Do not use the below two methods directly!
  619. // Instead use constants exported from DOMTopLevelEventTypes in ReactDOM.
  620. // (It is the only module that is allowed to access these methods.)
  621. function unsafeCastStringToDOMTopLevelType(topLevelType) {
  622. return topLevelType;
  623. }
  624. var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
  625. /**
  626. * Generate a mapping of standard vendor prefixes using the defined style property and event name.
  627. *
  628. * @param {string} styleProp
  629. * @param {string} eventName
  630. * @returns {object}
  631. */
  632. function makePrefixMap(styleProp, eventName) {
  633. var prefixes = {};
  634. prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
  635. prefixes['Webkit' + styleProp] = 'webkit' + eventName;
  636. prefixes['Moz' + styleProp] = 'moz' + eventName;
  637. return prefixes;
  638. }
  639. /**
  640. * A list of event names to a configurable list of vendor prefixes.
  641. */
  642. var vendorPrefixes = {
  643. animationend: makePrefixMap('Animation', 'AnimationEnd'),
  644. animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
  645. animationstart: makePrefixMap('Animation', 'AnimationStart'),
  646. transitionend: makePrefixMap('Transition', 'TransitionEnd')
  647. };
  648. /**
  649. * Event names that have already been detected and prefixed (if applicable).
  650. */
  651. var prefixedEventNames = {};
  652. /**
  653. * Element to check for prefixes on.
  654. */
  655. var style = {};
  656. /**
  657. * Bootstrap if a DOM exists.
  658. */
  659. if (canUseDOM) {
  660. style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x,
  661. // the un-prefixed "animation" and "transition" properties are defined on the
  662. // style object but the events that fire will still be prefixed, so we need
  663. // to check if the un-prefixed events are usable, and if not remove them from the map.
  664. if (!('AnimationEvent' in window)) {
  665. delete vendorPrefixes.animationend.animation;
  666. delete vendorPrefixes.animationiteration.animation;
  667. delete vendorPrefixes.animationstart.animation;
  668. } // Same as above
  669. if (!('TransitionEvent' in window)) {
  670. delete vendorPrefixes.transitionend.transition;
  671. }
  672. }
  673. /**
  674. * Attempts to determine the correct vendor prefixed event name.
  675. *
  676. * @param {string} eventName
  677. * @returns {string}
  678. */
  679. function getVendorPrefixedEventName(eventName) {
  680. if (prefixedEventNames[eventName]) {
  681. return prefixedEventNames[eventName];
  682. } else if (!vendorPrefixes[eventName]) {
  683. return eventName;
  684. }
  685. var prefixMap = vendorPrefixes[eventName];
  686. for (var styleProp in prefixMap) {
  687. if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
  688. return prefixedEventNames[eventName] = prefixMap[styleProp];
  689. }
  690. }
  691. return eventName;
  692. }
  693. /**
  694. * To identify top level events in ReactDOM, we use constants defined by this
  695. * module. This is the only module that uses the unsafe* methods to express
  696. * that the constants actually correspond to the browser event names. This lets
  697. * us save some bundle size by avoiding a top level type -> event name map.
  698. * The rest of ReactDOM code should import top level types from this file.
  699. */
  700. var TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort');
  701. var TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend'));
  702. var TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration'));
  703. var TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart'));
  704. var TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur');
  705. var TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay');
  706. var TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough');
  707. var TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel');
  708. var TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change');
  709. var TOP_CLICK = unsafeCastStringToDOMTopLevelType('click');
  710. var TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close');
  711. var TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend');
  712. var TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType('compositionstart');
  713. var TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType('compositionupdate');
  714. var TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu');
  715. var TOP_COPY = unsafeCastStringToDOMTopLevelType('copy');
  716. var TOP_CUT = unsafeCastStringToDOMTopLevelType('cut');
  717. var TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick');
  718. var TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag');
  719. var TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend');
  720. var TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter');
  721. var TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit');
  722. var TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave');
  723. var TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover');
  724. var TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart');
  725. var TOP_DROP = unsafeCastStringToDOMTopLevelType('drop');
  726. var TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange');
  727. var TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied');
  728. var TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted');
  729. var TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended');
  730. var TOP_ERROR = unsafeCastStringToDOMTopLevelType('error');
  731. var TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus');
  732. var TOP_INPUT = unsafeCastStringToDOMTopLevelType('input');
  733. var TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown');
  734. var TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress');
  735. var TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup');
  736. var TOP_LOAD = unsafeCastStringToDOMTopLevelType('load');
  737. var TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart');
  738. var TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata');
  739. var TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata');
  740. var TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown');
  741. var TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove');
  742. var TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout');
  743. var TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover');
  744. var TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup');
  745. var TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste');
  746. var TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause');
  747. var TOP_PLAY = unsafeCastStringToDOMTopLevelType('play');
  748. var TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing');
  749. var TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress');
  750. var TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange');
  751. var TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll');
  752. var TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked');
  753. var TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking');
  754. var TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange');
  755. var TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled');
  756. var TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend');
  757. var TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput');
  758. var TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate');
  759. var TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle');
  760. var TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel');
  761. var TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend');
  762. var TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove');
  763. var TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart');
  764. var TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend'));
  765. var TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange');
  766. var TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting');
  767. var TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel'); // List of events that need to be individually attached to media elements.
  768. // Note that events in this list will *not* be listened to at the top level
  769. // unless they're explicitly whitelisted in `ReactBrowserEventEmitter.listenTo`.
  770. var PLUGIN_EVENT_SYSTEM = 1;
  771. var didWarnAboutMessageChannel = false;
  772. var enqueueTask;
  773. try {
  774. // read require off the module object to get around the bundlers.
  775. // we don't want them to detect a require and bundle a Node polyfill.
  776. var requireString = ('require' + Math.random()).slice(0, 7);
  777. var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's
  778. // version of setImmediate, bypassing fake timers if any.
  779. enqueueTask = nodeRequire('timers').setImmediate;
  780. } catch (_err) {
  781. // we're in a browser
  782. // we can't use regular timers because they may still be faked
  783. // so we try MessageChannel+postMessage instead
  784. enqueueTask = function (callback) {
  785. {
  786. if (didWarnAboutMessageChannel === false) {
  787. didWarnAboutMessageChannel = true;
  788. !(typeof MessageChannel !== 'undefined') ? warningWithoutStack$1(false, 'This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.') : void 0;
  789. }
  790. }
  791. var channel = new MessageChannel();
  792. channel.port1.onmessage = callback;
  793. channel.port2.postMessage(undefined);
  794. };
  795. }
  796. var enqueueTask$1 = enqueueTask;
  797. var ReactInternals$1 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  798. var _ReactInternals$Sched = ReactInternals$1.Scheduler;
  799. var unstable_cancelCallback = _ReactInternals$Sched.unstable_cancelCallback;
  800. var unstable_now = _ReactInternals$Sched.unstable_now;
  801. var unstable_scheduleCallback = _ReactInternals$Sched.unstable_scheduleCallback;
  802. var unstable_shouldYield = _ReactInternals$Sched.unstable_shouldYield;
  803. var unstable_requestPaint = _ReactInternals$Sched.unstable_requestPaint;
  804. var unstable_getFirstCallbackNode = _ReactInternals$Sched.unstable_getFirstCallbackNode;
  805. var unstable_runWithPriority = _ReactInternals$Sched.unstable_runWithPriority;
  806. var unstable_next = _ReactInternals$Sched.unstable_next;
  807. var unstable_continueExecution = _ReactInternals$Sched.unstable_continueExecution;
  808. var unstable_pauseExecution = _ReactInternals$Sched.unstable_pauseExecution;
  809. var unstable_getCurrentPriorityLevel = _ReactInternals$Sched.unstable_getCurrentPriorityLevel;
  810. var unstable_ImmediatePriority = _ReactInternals$Sched.unstable_ImmediatePriority;
  811. var unstable_UserBlockingPriority = _ReactInternals$Sched.unstable_UserBlockingPriority;
  812. var unstable_NormalPriority = _ReactInternals$Sched.unstable_NormalPriority;
  813. var unstable_LowPriority = _ReactInternals$Sched.unstable_LowPriority;
  814. var unstable_IdlePriority = _ReactInternals$Sched.unstable_IdlePriority;
  815. var unstable_forceFrameRate = _ReactInternals$Sched.unstable_forceFrameRate;
  816. var unstable_flushAllWithoutAsserting = _ReactInternals$Sched.unstable_flushAllWithoutAsserting;
  817. // ReactDOM.js, and ReactTestUtils.js:
  818. var _ReactDOM$__SECRET_IN$1 = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Events;
  819. var getInstanceFromNode$1 = _ReactDOM$__SECRET_IN$1[0];
  820. var getNodeFromInstance$1 = _ReactDOM$__SECRET_IN$1[1];
  821. var getFiberCurrentPropsFromNode$1 = _ReactDOM$__SECRET_IN$1[2];
  822. var injectEventPluginsByName$1 = _ReactDOM$__SECRET_IN$1[3];
  823. var eventNameDispatchConfigs$1 = _ReactDOM$__SECRET_IN$1[4];
  824. var accumulateTwoPhaseDispatches$1 = _ReactDOM$__SECRET_IN$1[5];
  825. var accumulateDirectDispatches$1 = _ReactDOM$__SECRET_IN$1[6];
  826. var enqueueStateRestore$1 = _ReactDOM$__SECRET_IN$1[7];
  827. var restoreStateIfNeeded$1 = _ReactDOM$__SECRET_IN$1[8];
  828. var dispatchEvent$1 = _ReactDOM$__SECRET_IN$1[9];
  829. var runEventsInBatch$1 = _ReactDOM$__SECRET_IN$1[10];
  830. var flushPassiveEffects$1 = _ReactDOM$__SECRET_IN$1[11];
  831. var IsThisRendererActing$1 = _ReactDOM$__SECRET_IN$1[12];
  832. var batchedUpdates = ReactDOM.unstable_batchedUpdates;
  833. var IsSomeRendererActing = ReactSharedInternals.IsSomeRendererActing; // this implementation should be exactly the same in
  834. // ReactTestUtilsAct.js, ReactTestRendererAct.js, createReactNoop.js
  835. var isSchedulerMocked = typeof unstable_flushAllWithoutAsserting === 'function';
  836. var flushWork = unstable_flushAllWithoutAsserting || function () {
  837. var didFlushWork = false;
  838. while (flushPassiveEffects$1()) {
  839. didFlushWork = true;
  840. }
  841. return didFlushWork;
  842. };
  843. function flushWorkAndMicroTasks(onDone) {
  844. try {
  845. flushWork();
  846. enqueueTask$1(function () {
  847. if (flushWork()) {
  848. flushWorkAndMicroTasks(onDone);
  849. } else {
  850. onDone();
  851. }
  852. });
  853. } catch (err) {
  854. onDone(err);
  855. }
  856. } // we track the 'depth' of the act() calls with this counter,
  857. // so we can tell if any async act() calls try to run in parallel.
  858. var actingUpdatesScopeDepth = 0;
  859. function act(callback) {
  860. var previousActingUpdatesScopeDepth = actingUpdatesScopeDepth;
  861. var previousIsSomeRendererActing;
  862. var previousIsThisRendererActing;
  863. actingUpdatesScopeDepth++;
  864. previousIsSomeRendererActing = IsSomeRendererActing.current;
  865. previousIsThisRendererActing = IsThisRendererActing$1.current;
  866. IsSomeRendererActing.current = true;
  867. IsThisRendererActing$1.current = true;
  868. function onDone() {
  869. actingUpdatesScopeDepth--;
  870. IsSomeRendererActing.current = previousIsSomeRendererActing;
  871. IsThisRendererActing$1.current = previousIsThisRendererActing;
  872. {
  873. if (actingUpdatesScopeDepth > previousActingUpdatesScopeDepth) {
  874. // if it's _less than_ previousActingUpdatesScopeDepth, then we can assume the 'other' one has warned
  875. warningWithoutStack$1(false, 'You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. ');
  876. }
  877. }
  878. }
  879. var result;
  880. try {
  881. result = batchedUpdates(callback);
  882. } catch (error) {
  883. // on sync errors, we still want to 'cleanup' and decrement actingUpdatesScopeDepth
  884. onDone();
  885. throw error;
  886. }
  887. if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
  888. // setup a boolean that gets set to true only
  889. // once this act() call is await-ed
  890. var called = false;
  891. {
  892. if (typeof Promise !== 'undefined') {
  893. //eslint-disable-next-line no-undef
  894. Promise.resolve().then(function () {}).then(function () {
  895. if (called === false) {
  896. warningWithoutStack$1(false, 'You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, interleaving multiple act ' + 'calls and mixing their scopes. You should - await act(async () => ...);');
  897. }
  898. });
  899. }
  900. } // in the async case, the returned thenable runs the callback, flushes
  901. // effects and microtasks in a loop until flushPassiveEffects() === false,
  902. // and cleans up
  903. return {
  904. then: function (resolve, reject) {
  905. called = true;
  906. result.then(function () {
  907. if (actingUpdatesScopeDepth > 1 || isSchedulerMocked === true && previousIsSomeRendererActing === true) {
  908. onDone();
  909. resolve();
  910. return;
  911. } // we're about to exit the act() scope,
  912. // now's the time to flush tasks/effects
  913. flushWorkAndMicroTasks(function (err) {
  914. onDone();
  915. if (err) {
  916. reject(err);
  917. } else {
  918. resolve();
  919. }
  920. });
  921. }, function (err) {
  922. onDone();
  923. reject(err);
  924. });
  925. }
  926. };
  927. } else {
  928. {
  929. !(result === undefined) ? warningWithoutStack$1(false, 'The callback passed to act(...) function ' + 'must return undefined, or a Promise. You returned %s', result) : void 0;
  930. } // flush effects until none remain, and cleanup
  931. try {
  932. if (actingUpdatesScopeDepth === 1 && (isSchedulerMocked === false || previousIsSomeRendererActing === false)) {
  933. // we're about to exit the act() scope,
  934. // now's the time to flush effects
  935. flushWork();
  936. }
  937. onDone();
  938. } catch (err) {
  939. onDone();
  940. throw err;
  941. } // in the sync case, the returned thenable only warns *if* await-ed
  942. return {
  943. then: function (resolve) {
  944. {
  945. warningWithoutStack$1(false, 'Do not await the result of calling act(...) with sync logic, it is not a Promise.');
  946. }
  947. resolve();
  948. }
  949. };
  950. }
  951. }
  952. var findDOMNode = ReactDOM.findDOMNode; // Keep in sync with ReactDOMUnstableNativeDependencies.js
  953. // ReactDOM.js, and ReactTestUtilsAct.js:
  954. var _ReactDOM$__SECRET_IN = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Events;
  955. var getInstanceFromNode = _ReactDOM$__SECRET_IN[0];
  956. var getNodeFromInstance = _ReactDOM$__SECRET_IN[1];
  957. var getFiberCurrentPropsFromNode = _ReactDOM$__SECRET_IN[2];
  958. var injectEventPluginsByName = _ReactDOM$__SECRET_IN[3];
  959. var eventNameDispatchConfigs = _ReactDOM$__SECRET_IN[4];
  960. var accumulateTwoPhaseDispatches = _ReactDOM$__SECRET_IN[5];
  961. var accumulateDirectDispatches = _ReactDOM$__SECRET_IN[6];
  962. var enqueueStateRestore = _ReactDOM$__SECRET_IN[7];
  963. var restoreStateIfNeeded = _ReactDOM$__SECRET_IN[8];
  964. var dispatchEvent = _ReactDOM$__SECRET_IN[9];
  965. var runEventsInBatch = _ReactDOM$__SECRET_IN[10];
  966. var flushPassiveEffects = _ReactDOM$__SECRET_IN[11];
  967. var IsThisRendererActing = _ReactDOM$__SECRET_IN[12];
  968. function Event(suffix) {}
  969. var hasWarnedAboutDeprecatedMockComponent = false;
  970. /**
  971. * @class ReactTestUtils
  972. */
  973. /**
  974. * Simulates a top level event being dispatched from a raw event that occurred
  975. * on an `Element` node.
  976. * @param {number} topLevelType A number from `TopLevelEventTypes`
  977. * @param {!Element} node The dom to simulate an event occurring on.
  978. * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent.
  979. */
  980. function simulateNativeEventOnNode(topLevelType, node, fakeNativeEvent) {
  981. fakeNativeEvent.target = node;
  982. dispatchEvent(topLevelType, PLUGIN_EVENT_SYSTEM, fakeNativeEvent);
  983. }
  984. /**
  985. * Simulates a top level event being dispatched from a raw event that occurred
  986. * on the `ReactDOMComponent` `comp`.
  987. * @param {Object} topLevelType A type from `BrowserEventConstants.topLevelTypes`.
  988. * @param {!ReactDOMComponent} comp
  989. * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent.
  990. */
  991. function simulateNativeEventOnDOMComponent(topLevelType, comp, fakeNativeEvent) {
  992. simulateNativeEventOnNode(topLevelType, findDOMNode(comp), fakeNativeEvent);
  993. }
  994. function findAllInRenderedFiberTreeInternal(fiber, test) {
  995. if (!fiber) {
  996. return [];
  997. }
  998. var currentParent = findCurrentFiberUsingSlowPath(fiber);
  999. if (!currentParent) {
  1000. return [];
  1001. }
  1002. var node = currentParent;
  1003. var ret = [];
  1004. while (true) {
  1005. if (node.tag === HostComponent || node.tag === HostText || node.tag === ClassComponent || node.tag === FunctionComponent) {
  1006. var publicInst = node.stateNode;
  1007. if (test(publicInst)) {
  1008. ret.push(publicInst);
  1009. }
  1010. }
  1011. if (node.child) {
  1012. node.child.return = node;
  1013. node = node.child;
  1014. continue;
  1015. }
  1016. if (node === currentParent) {
  1017. return ret;
  1018. }
  1019. while (!node.sibling) {
  1020. if (!node.return || node.return === currentParent) {
  1021. return ret;
  1022. }
  1023. node = node.return;
  1024. }
  1025. node.sibling.return = node.return;
  1026. node = node.sibling;
  1027. }
  1028. }
  1029. function validateClassInstance(inst, methodName) {
  1030. if (!inst) {
  1031. // This is probably too relaxed but it's existing behavior.
  1032. return;
  1033. }
  1034. if (get(inst)) {
  1035. // This is a public instance indeed.
  1036. return;
  1037. }
  1038. var received;
  1039. var stringified = '' + inst;
  1040. if (Array.isArray(inst)) {
  1041. received = 'an array';
  1042. } else if (inst && inst.nodeType === ELEMENT_NODE && inst.tagName) {
  1043. received = 'a DOM node';
  1044. } else if (stringified === '[object Object]') {
  1045. received = 'object with keys {' + Object.keys(inst).join(', ') + '}';
  1046. } else {
  1047. received = stringified;
  1048. }
  1049. {
  1050. {
  1051. throw Error(methodName + "(...): the first argument must be a React class instance. Instead received: " + received + ".");
  1052. }
  1053. }
  1054. }
  1055. /**
  1056. * Utilities for making it easy to test React components.
  1057. *
  1058. * See https://reactjs.org/docs/test-utils.html
  1059. *
  1060. * Todo: Support the entire DOM.scry query syntax. For now, these simple
  1061. * utilities will suffice for testing purposes.
  1062. * @lends ReactTestUtils
  1063. */
  1064. var ReactTestUtils = {
  1065. renderIntoDocument: function (element) {
  1066. var div = document.createElement('div'); // None of our tests actually require attaching the container to the
  1067. // DOM, and doing so creates a mess that we rely on test isolation to
  1068. // clean up, so we're going to stop honoring the name of this method
  1069. // (and probably rename it eventually) if no problems arise.
  1070. // document.documentElement.appendChild(div);
  1071. return ReactDOM.render(element, div);
  1072. },
  1073. isElement: function (element) {
  1074. return React.isValidElement(element);
  1075. },
  1076. isElementOfType: function (inst, convenienceConstructor) {
  1077. return React.isValidElement(inst) && inst.type === convenienceConstructor;
  1078. },
  1079. isDOMComponent: function (inst) {
  1080. return !!(inst && inst.nodeType === ELEMENT_NODE && inst.tagName);
  1081. },
  1082. isDOMComponentElement: function (inst) {
  1083. return !!(inst && React.isValidElement(inst) && !!inst.tagName);
  1084. },
  1085. isCompositeComponent: function (inst) {
  1086. if (ReactTestUtils.isDOMComponent(inst)) {
  1087. // Accessing inst.setState warns; just return false as that'll be what
  1088. // this returns when we have DOM nodes as refs directly
  1089. return false;
  1090. }
  1091. return inst != null && typeof inst.render === 'function' && typeof inst.setState === 'function';
  1092. },
  1093. isCompositeComponentWithType: function (inst, type) {
  1094. if (!ReactTestUtils.isCompositeComponent(inst)) {
  1095. return false;
  1096. }
  1097. var internalInstance = get(inst);
  1098. var constructor = internalInstance.type;
  1099. return constructor === type;
  1100. },
  1101. findAllInRenderedTree: function (inst, test) {
  1102. validateClassInstance(inst, 'findAllInRenderedTree');
  1103. if (!inst) {
  1104. return [];
  1105. }
  1106. var internalInstance = get(inst);
  1107. return findAllInRenderedFiberTreeInternal(internalInstance, test);
  1108. },
  1109. /**
  1110. * Finds all instance of components in the rendered tree that are DOM
  1111. * components with the class name matching `className`.
  1112. * @return {array} an array of all the matches.
  1113. */
  1114. scryRenderedDOMComponentsWithClass: function (root, classNames) {
  1115. validateClassInstance(root, 'scryRenderedDOMComponentsWithClass');
  1116. return ReactTestUtils.findAllInRenderedTree(root, function (inst) {
  1117. if (ReactTestUtils.isDOMComponent(inst)) {
  1118. var className = inst.className;
  1119. if (typeof className !== 'string') {
  1120. // SVG, probably.
  1121. className = inst.getAttribute('class') || '';
  1122. }
  1123. var classList = className.split(/\s+/);
  1124. if (!Array.isArray(classNames)) {
  1125. if (!(classNames !== undefined)) {
  1126. {
  1127. throw Error("TestUtils.scryRenderedDOMComponentsWithClass expects a className as a second argument.");
  1128. }
  1129. }
  1130. classNames = classNames.split(/\s+/);
  1131. }
  1132. return classNames.every(function (name) {
  1133. return classList.indexOf(name) !== -1;
  1134. });
  1135. }
  1136. return false;
  1137. });
  1138. },
  1139. /**
  1140. * Like scryRenderedDOMComponentsWithClass but expects there to be one result,
  1141. * and returns that one result, or throws exception if there is any other
  1142. * number of matches besides one.
  1143. * @return {!ReactDOMComponent} The one match.
  1144. */
  1145. findRenderedDOMComponentWithClass: function (root, className) {
  1146. validateClassInstance(root, 'findRenderedDOMComponentWithClass');
  1147. var all = ReactTestUtils.scryRenderedDOMComponentsWithClass(root, className);
  1148. if (all.length !== 1) {
  1149. throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for class:' + className);
  1150. }
  1151. return all[0];
  1152. },
  1153. /**
  1154. * Finds all instance of components in the rendered tree that are DOM
  1155. * components with the tag name matching `tagName`.
  1156. * @return {array} an array of all the matches.
  1157. */
  1158. scryRenderedDOMComponentsWithTag: function (root, tagName) {
  1159. validateClassInstance(root, 'scryRenderedDOMComponentsWithTag');
  1160. return ReactTestUtils.findAllInRenderedTree(root, function (inst) {
  1161. return ReactTestUtils.isDOMComponent(inst) && inst.tagName.toUpperCase() === tagName.toUpperCase();
  1162. });
  1163. },
  1164. /**
  1165. * Like scryRenderedDOMComponentsWithTag but expects there to be one result,
  1166. * and returns that one result, or throws exception if there is any other
  1167. * number of matches besides one.
  1168. * @return {!ReactDOMComponent} The one match.
  1169. */
  1170. findRenderedDOMComponentWithTag: function (root, tagName) {
  1171. validateClassInstance(root, 'findRenderedDOMComponentWithTag');
  1172. var all = ReactTestUtils.scryRenderedDOMComponentsWithTag(root, tagName);
  1173. if (all.length !== 1) {
  1174. throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for tag:' + tagName);
  1175. }
  1176. return all[0];
  1177. },
  1178. /**
  1179. * Finds all instances of components with type equal to `componentType`.
  1180. * @return {array} an array of all the matches.
  1181. */
  1182. scryRenderedComponentsWithType: function (root, componentType) {
  1183. validateClassInstance(root, 'scryRenderedComponentsWithType');
  1184. return ReactTestUtils.findAllInRenderedTree(root, function (inst) {
  1185. return ReactTestUtils.isCompositeComponentWithType(inst, componentType);
  1186. });
  1187. },
  1188. /**
  1189. * Same as `scryRenderedComponentsWithType` but expects there to be one result
  1190. * and returns that one result, or throws exception if there is any other
  1191. * number of matches besides one.
  1192. * @return {!ReactComponent} The one match.
  1193. */
  1194. findRenderedComponentWithType: function (root, componentType) {
  1195. validateClassInstance(root, 'findRenderedComponentWithType');
  1196. var all = ReactTestUtils.scryRenderedComponentsWithType(root, componentType);
  1197. if (all.length !== 1) {
  1198. throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for componentType:' + componentType);
  1199. }
  1200. return all[0];
  1201. },
  1202. /**
  1203. * Pass a mocked component module to this method to augment it with
  1204. * useful methods that allow it to be used as a dummy React component.
  1205. * Instead of rendering as usual, the component will become a simple
  1206. * <div> containing any provided children.
  1207. *
  1208. * @param {object} module the mock function object exported from a
  1209. * module that defines the component to be mocked
  1210. * @param {?string} mockTagName optional dummy root tag name to return
  1211. * from render method (overrides
  1212. * module.mockTagName if provided)
  1213. * @return {object} the ReactTestUtils object (for chaining)
  1214. */
  1215. mockComponent: function (module, mockTagName) {
  1216. if (!hasWarnedAboutDeprecatedMockComponent) {
  1217. hasWarnedAboutDeprecatedMockComponent = true;
  1218. lowPriorityWarningWithoutStack$1(false, 'ReactTestUtils.mockComponent() is deprecated. ' + 'Use shallow rendering or jest.mock() instead.\n\n' + 'See https://fb.me/test-utils-mock-component for more information.');
  1219. }
  1220. mockTagName = mockTagName || module.mockTagName || 'div';
  1221. module.prototype.render.mockImplementation(function () {
  1222. return React.createElement(mockTagName, null, this.props.children);
  1223. });
  1224. return this;
  1225. },
  1226. nativeTouchData: function (x, y) {
  1227. return {
  1228. touches: [{
  1229. pageX: x,
  1230. pageY: y
  1231. }]
  1232. };
  1233. },
  1234. Simulate: null,
  1235. SimulateNative: {},
  1236. act: act
  1237. };
  1238. /**
  1239. * Exports:
  1240. *
  1241. * - `ReactTestUtils.Simulate.click(Element)`
  1242. * - `ReactTestUtils.Simulate.mouseMove(Element)`
  1243. * - `ReactTestUtils.Simulate.change(Element)`
  1244. * - ... (All keys from event plugin `eventTypes` objects)
  1245. */
  1246. function makeSimulator(eventType) {
  1247. return function (domNode, eventData) {
  1248. if (!!React.isValidElement(domNode)) {
  1249. {
  1250. throw Error("TestUtils.Simulate expected a DOM node as the first argument but received a React element. Pass the DOM node you wish to simulate the event on instead. Note that TestUtils.Simulate will not work if you are using shallow rendering.");
  1251. }
  1252. }
  1253. if (!!ReactTestUtils.isCompositeComponent(domNode)) {
  1254. {
  1255. throw Error("TestUtils.Simulate expected a DOM node as the first argument but received a component instance. Pass the DOM node you wish to simulate the event on instead.");
  1256. }
  1257. }
  1258. var dispatchConfig = eventNameDispatchConfigs[eventType];
  1259. var fakeNativeEvent = new Event();
  1260. fakeNativeEvent.target = domNode;
  1261. fakeNativeEvent.type = eventType.toLowerCase(); // We don't use SyntheticEvent.getPooled in order to not have to worry about
  1262. // properly destroying any properties assigned from `eventData` upon release
  1263. var targetInst = getInstanceFromNode(domNode);
  1264. var event = new SyntheticEvent(dispatchConfig, targetInst, fakeNativeEvent, domNode); // Since we aren't using pooling, always persist the event. This will make
  1265. // sure it's marked and won't warn when setting additional properties.
  1266. event.persist();
  1267. _assign(event, eventData);
  1268. if (dispatchConfig.phasedRegistrationNames) {
  1269. accumulateTwoPhaseDispatches(event);
  1270. } else {
  1271. accumulateDirectDispatches(event);
  1272. }
  1273. ReactDOM.unstable_batchedUpdates(function () {
  1274. // Normally extractEvent enqueues a state restore, but we'll just always
  1275. // do that since we're by-passing it here.
  1276. enqueueStateRestore(domNode);
  1277. runEventsInBatch(event);
  1278. });
  1279. restoreStateIfNeeded();
  1280. };
  1281. }
  1282. function buildSimulators() {
  1283. ReactTestUtils.Simulate = {};
  1284. var eventType;
  1285. for (eventType in eventNameDispatchConfigs) {
  1286. /**
  1287. * @param {!Element|ReactDOMComponent} domComponentOrNode
  1288. * @param {?object} eventData Fake event data to use in SyntheticEvent.
  1289. */
  1290. ReactTestUtils.Simulate[eventType] = makeSimulator(eventType);
  1291. }
  1292. }
  1293. buildSimulators();
  1294. /**
  1295. * Exports:
  1296. *
  1297. * - `ReactTestUtils.SimulateNative.click(Element/ReactDOMComponent)`
  1298. * - `ReactTestUtils.SimulateNative.mouseMove(Element/ReactDOMComponent)`
  1299. * - `ReactTestUtils.SimulateNative.mouseIn/ReactDOMComponent)`
  1300. * - `ReactTestUtils.SimulateNative.mouseOut(Element/ReactDOMComponent)`
  1301. * - ... (All keys from `BrowserEventConstants.topLevelTypes`)
  1302. *
  1303. * Note: Top level event types are a subset of the entire set of handler types
  1304. * (which include a broader set of "synthetic" events). For example, onDragDone
  1305. * is a synthetic event. Except when testing an event plugin or React's event
  1306. * handling code specifically, you probably want to use ReactTestUtils.Simulate
  1307. * to dispatch synthetic events.
  1308. */
  1309. function makeNativeSimulator(eventType, topLevelType) {
  1310. return function (domComponentOrNode, nativeEventData) {
  1311. var fakeNativeEvent = new Event(eventType);
  1312. _assign(fakeNativeEvent, nativeEventData);
  1313. if (ReactTestUtils.isDOMComponent(domComponentOrNode)) {
  1314. simulateNativeEventOnDOMComponent(topLevelType, domComponentOrNode, fakeNativeEvent);
  1315. } else if (domComponentOrNode.tagName) {
  1316. // Will allow on actual dom nodes.
  1317. simulateNativeEventOnNode(topLevelType, domComponentOrNode, fakeNativeEvent);
  1318. }
  1319. };
  1320. }
  1321. [[TOP_ABORT, 'abort'], [TOP_ANIMATION_END, 'animationEnd'], [TOP_ANIMATION_ITERATION, 'animationIteration'], [TOP_ANIMATION_START, 'animationStart'], [TOP_BLUR, 'blur'], [TOP_CAN_PLAY_THROUGH, 'canPlayThrough'], [TOP_CAN_PLAY, 'canPlay'], [TOP_CANCEL, 'cancel'], [TOP_CHANGE, 'change'], [TOP_CLICK, 'click'], [TOP_CLOSE, 'close'], [TOP_COMPOSITION_END, 'compositionEnd'], [TOP_COMPOSITION_START, 'compositionStart'], [TOP_COMPOSITION_UPDATE, 'compositionUpdate'], [TOP_CONTEXT_MENU, 'contextMenu'], [TOP_COPY, 'copy'], [TOP_CUT, 'cut'], [TOP_DOUBLE_CLICK, 'doubleClick'], [TOP_DRAG_END, 'dragEnd'], [TOP_DRAG_ENTER, 'dragEnter'], [TOP_DRAG_EXIT, 'dragExit'], [TOP_DRAG_LEAVE, 'dragLeave'], [TOP_DRAG_OVER, 'dragOver'], [TOP_DRAG_START, 'dragStart'], [TOP_DRAG, 'drag'], [TOP_DROP, 'drop'], [TOP_DURATION_CHANGE, 'durationChange'], [TOP_EMPTIED, 'emptied'], [TOP_ENCRYPTED, 'encrypted'], [TOP_ENDED, 'ended'], [TOP_ERROR, 'error'], [TOP_FOCUS, 'focus'], [TOP_INPUT, 'input'], [TOP_KEY_DOWN, 'keyDown'], [TOP_KEY_PRESS, 'keyPress'], [TOP_KEY_UP, 'keyUp'], [TOP_LOAD_START, 'loadStart'], [TOP_LOAD_START, 'loadStart'], [TOP_LOAD, 'load'], [TOP_LOADED_DATA, 'loadedData'], [TOP_LOADED_METADATA, 'loadedMetadata'], [TOP_MOUSE_DOWN, 'mouseDown'], [TOP_MOUSE_MOVE, 'mouseMove'], [TOP_MOUSE_OUT, 'mouseOut'], [TOP_MOUSE_OVER, 'mouseOver'], [TOP_MOUSE_UP, 'mouseUp'], [TOP_PASTE, 'paste'], [TOP_PAUSE, 'pause'], [TOP_PLAY, 'play'], [TOP_PLAYING, 'playing'], [TOP_PROGRESS, 'progress'], [TOP_RATE_CHANGE, 'rateChange'], [TOP_SCROLL, 'scroll'], [TOP_SEEKED, 'seeked'], [TOP_SEEKING, 'seeking'], [TOP_SELECTION_CHANGE, 'selectionChange'], [TOP_STALLED, 'stalled'], [TOP_SUSPEND, 'suspend'], [TOP_TEXT_INPUT, 'textInput'], [TOP_TIME_UPDATE, 'timeUpdate'], [TOP_TOGGLE, 'toggle'], [TOP_TOUCH_CANCEL, 'touchCancel'], [TOP_TOUCH_END, 'touchEnd'], [TOP_TOUCH_MOVE, 'touchMove'], [TOP_TOUCH_START, 'touchStart'], [TOP_TRANSITION_END, 'transitionEnd'], [TOP_VOLUME_CHANGE, 'volumeChange'], [TOP_WAITING, 'waiting'], [TOP_WHEEL, 'wheel']].forEach(function (_ref) {
  1322. var topLevelType = _ref[0],
  1323. eventType = _ref[1];
  1324. /**
  1325. * @param {!Element|ReactDOMComponent} domComponentOrNode
  1326. * @param {?Event} nativeEventData Fake native event to use in SyntheticEvent.
  1327. */
  1328. ReactTestUtils.SimulateNative[eventType] = makeNativeSimulator(eventType, topLevelType);
  1329. });
  1330. var ReactTestUtils$2 = Object.freeze({
  1331. default: ReactTestUtils
  1332. });
  1333. var ReactTestUtils$3 = ( ReactTestUtils$2 && ReactTestUtils ) || ReactTestUtils$2;
  1334. // TODO: decide on the top-level export form.
  1335. // This is hacky but makes it work with both Rollup and Jest.
  1336. var testUtils = ReactTestUtils$3.default || ReactTestUtils$3;
  1337. return testUtils;
  1338. })));