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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136
  1. /** @license React v17.0.2
  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. (function (global, factory) {
  10. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('react-dom')) :
  11. typeof define === 'function' && define.amd ? define(['exports', 'react', 'react-dom'], factory) :
  12. (global = global || self, factory(global.ReactTestUtils = {}, global.React, global.ReactDOM));
  13. }(this, (function (exports, React, ReactDOM) { 'use strict';
  14. var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  15. var _assign = ReactInternals.assign;
  16. var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  17. // by calls to these methods by a Babel plugin.
  18. //
  19. // In PROD (or in packages without access to React internals),
  20. // they are left as they are instead.
  21. function warn(format) {
  22. {
  23. for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  24. args[_key - 1] = arguments[_key];
  25. }
  26. printWarning('warn', format, args);
  27. }
  28. }
  29. function error(format) {
  30. {
  31. for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  32. args[_key2 - 1] = arguments[_key2];
  33. }
  34. printWarning('error', format, args);
  35. }
  36. }
  37. function printWarning(level, format, args) {
  38. // When changing this logic, you might want to also
  39. // update consoleWithStackDev.www.js as well.
  40. {
  41. var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
  42. var stack = ReactDebugCurrentFrame.getStackAddendum();
  43. if (stack !== '') {
  44. format += '%s';
  45. args = args.concat([stack]);
  46. }
  47. var argsWithFormat = args.map(function (item) {
  48. return '' + item;
  49. }); // Careful: RN currently depends on this prefix
  50. argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
  51. // breaks IE9: https://github.com/facebook/react/issues/13610
  52. // eslint-disable-next-line react-internal/no-production-logging
  53. Function.prototype.apply.call(console[level], console, argsWithFormat);
  54. }
  55. }
  56. /**
  57. * `ReactInstanceMap` maintains a mapping from a public facing stateful
  58. * instance (key) and the internal representation (value). This allows public
  59. * methods to accept the user facing instance as an argument and map them back
  60. * to internal methods.
  61. *
  62. * Note that this module is currently shared and assumed to be stateless.
  63. * If this becomes an actual Map, that will break.
  64. */
  65. function get(key) {
  66. return key._reactInternals;
  67. }
  68. // ATTENTION
  69. // When adding new symbols to this file,
  70. // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
  71. // The Symbol used to tag the ReactElement-like types. If there is no native Symbol
  72. // nor polyfill, then a plain number is used for performance.
  73. var REACT_ELEMENT_TYPE = 0xeac7;
  74. var REACT_PORTAL_TYPE = 0xeaca;
  75. var REACT_FRAGMENT_TYPE = 0xeacb;
  76. var REACT_STRICT_MODE_TYPE = 0xeacc;
  77. var REACT_PROFILER_TYPE = 0xead2;
  78. var REACT_PROVIDER_TYPE = 0xeacd;
  79. var REACT_CONTEXT_TYPE = 0xeace;
  80. var REACT_FORWARD_REF_TYPE = 0xead0;
  81. var REACT_SUSPENSE_TYPE = 0xead1;
  82. var REACT_SUSPENSE_LIST_TYPE = 0xead8;
  83. var REACT_MEMO_TYPE = 0xead3;
  84. var REACT_LAZY_TYPE = 0xead4;
  85. var REACT_BLOCK_TYPE = 0xead9;
  86. var REACT_SERVER_BLOCK_TYPE = 0xeada;
  87. var REACT_FUNDAMENTAL_TYPE = 0xead5;
  88. var REACT_SCOPE_TYPE = 0xead7;
  89. var REACT_OPAQUE_ID_TYPE = 0xeae0;
  90. var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1;
  91. var REACT_OFFSCREEN_TYPE = 0xeae2;
  92. var REACT_LEGACY_HIDDEN_TYPE = 0xeae3;
  93. if (typeof Symbol === 'function' && Symbol.for) {
  94. var symbolFor = Symbol.for;
  95. REACT_ELEMENT_TYPE = symbolFor('react.element');
  96. REACT_PORTAL_TYPE = symbolFor('react.portal');
  97. REACT_FRAGMENT_TYPE = symbolFor('react.fragment');
  98. REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode');
  99. REACT_PROFILER_TYPE = symbolFor('react.profiler');
  100. REACT_PROVIDER_TYPE = symbolFor('react.provider');
  101. REACT_CONTEXT_TYPE = symbolFor('react.context');
  102. REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref');
  103. REACT_SUSPENSE_TYPE = symbolFor('react.suspense');
  104. REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list');
  105. REACT_MEMO_TYPE = symbolFor('react.memo');
  106. REACT_LAZY_TYPE = symbolFor('react.lazy');
  107. REACT_BLOCK_TYPE = symbolFor('react.block');
  108. REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block');
  109. REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental');
  110. REACT_SCOPE_TYPE = symbolFor('react.scope');
  111. REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id');
  112. REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode');
  113. REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen');
  114. REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden');
  115. }
  116. var FunctionComponent = 0;
  117. var ClassComponent = 1;
  118. var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
  119. var HostComponent = 5;
  120. var HostText = 6;
  121. // Don't change these two values. They're used by React Dev Tools.
  122. var NoFlags =
  123. /* */
  124. 0;
  125. var Placement =
  126. /* */
  127. 2;
  128. var Hydrating =
  129. /* */
  130. 1024;
  131. var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
  132. function getNearestMountedFiber(fiber) {
  133. var node = fiber;
  134. var nearestMounted = fiber;
  135. if (!fiber.alternate) {
  136. // If there is no alternate, this might be a new tree that isn't inserted
  137. // yet. If it is, then it will have a pending insertion effect on it.
  138. var nextNode = node;
  139. do {
  140. node = nextNode;
  141. if ((node.flags & (Placement | Hydrating)) !== NoFlags) {
  142. // This is an insertion or in-progress hydration. The nearest possible
  143. // mounted fiber is the parent but we need to continue to figure out
  144. // if that one is still mounted.
  145. nearestMounted = node.return;
  146. }
  147. nextNode = node.return;
  148. } while (nextNode);
  149. } else {
  150. while (node.return) {
  151. node = node.return;
  152. }
  153. }
  154. if (node.tag === HostRoot) {
  155. // TODO: Check if this was a nested HostRoot when used with
  156. // renderContainerIntoSubtree.
  157. return nearestMounted;
  158. } // If we didn't hit the root, that means that we're in an disconnected tree
  159. // that has been unmounted.
  160. return null;
  161. }
  162. function assertIsMounted(fiber) {
  163. if (!(getNearestMountedFiber(fiber) === fiber)) {
  164. {
  165. throw Error( "Unable to find node on an unmounted component." );
  166. }
  167. }
  168. }
  169. function findCurrentFiberUsingSlowPath(fiber) {
  170. var alternate = fiber.alternate;
  171. if (!alternate) {
  172. // If there is no alternate, then we only need to check if it is mounted.
  173. var nearestMounted = getNearestMountedFiber(fiber);
  174. if (!(nearestMounted !== null)) {
  175. {
  176. throw Error( "Unable to find node on an unmounted component." );
  177. }
  178. }
  179. if (nearestMounted !== fiber) {
  180. return null;
  181. }
  182. return fiber;
  183. } // If we have two possible branches, we'll walk backwards up to the root
  184. // to see what path the root points to. On the way we may hit one of the
  185. // special cases and we'll deal with them.
  186. var a = fiber;
  187. var b = alternate;
  188. while (true) {
  189. var parentA = a.return;
  190. if (parentA === null) {
  191. // We're at the root.
  192. break;
  193. }
  194. var parentB = parentA.alternate;
  195. if (parentB === null) {
  196. // There is no alternate. This is an unusual case. Currently, it only
  197. // happens when a Suspense component is hidden. An extra fragment fiber
  198. // is inserted in between the Suspense fiber and its children. Skip
  199. // over this extra fragment fiber and proceed to the next parent.
  200. var nextParent = parentA.return;
  201. if (nextParent !== null) {
  202. a = b = nextParent;
  203. continue;
  204. } // If there's no parent, we're at the root.
  205. break;
  206. } // If both copies of the parent fiber point to the same child, we can
  207. // assume that the child is current. This happens when we bailout on low
  208. // priority: the bailed out fiber's child reuses the current child.
  209. if (parentA.child === parentB.child) {
  210. var child = parentA.child;
  211. while (child) {
  212. if (child === a) {
  213. // We've determined that A is the current branch.
  214. assertIsMounted(parentA);
  215. return fiber;
  216. }
  217. if (child === b) {
  218. // We've determined that B is the current branch.
  219. assertIsMounted(parentA);
  220. return alternate;
  221. }
  222. child = child.sibling;
  223. } // We should never have an alternate for any mounting node. So the only
  224. // way this could possibly happen is if this was unmounted, if at all.
  225. {
  226. {
  227. throw Error( "Unable to find node on an unmounted component." );
  228. }
  229. }
  230. }
  231. if (a.return !== b.return) {
  232. // The return pointer of A and the return pointer of B point to different
  233. // fibers. We assume that return pointers never criss-cross, so A must
  234. // belong to the child set of A.return, and B must belong to the child
  235. // set of B.return.
  236. a = parentA;
  237. b = parentB;
  238. } else {
  239. // The return pointers point to the same fiber. We'll have to use the
  240. // default, slow path: scan the child sets of each parent alternate to see
  241. // which child belongs to which set.
  242. //
  243. // Search parent A's child set
  244. var didFindChild = false;
  245. var _child = parentA.child;
  246. while (_child) {
  247. if (_child === a) {
  248. didFindChild = true;
  249. a = parentA;
  250. b = parentB;
  251. break;
  252. }
  253. if (_child === b) {
  254. didFindChild = true;
  255. b = parentA;
  256. a = parentB;
  257. break;
  258. }
  259. _child = _child.sibling;
  260. }
  261. if (!didFindChild) {
  262. // Search parent B's child set
  263. _child = parentB.child;
  264. while (_child) {
  265. if (_child === a) {
  266. didFindChild = true;
  267. a = parentB;
  268. b = parentA;
  269. break;
  270. }
  271. if (_child === b) {
  272. didFindChild = true;
  273. b = parentB;
  274. a = parentA;
  275. break;
  276. }
  277. _child = _child.sibling;
  278. }
  279. if (!didFindChild) {
  280. {
  281. 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." );
  282. }
  283. }
  284. }
  285. }
  286. if (!(a.alternate === b)) {
  287. {
  288. throw Error( "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." );
  289. }
  290. }
  291. } // If the root is not a host container, we're in a disconnected tree. I.e.
  292. // unmounted.
  293. if (!(a.tag === HostRoot)) {
  294. {
  295. throw Error( "Unable to find node on an unmounted component." );
  296. }
  297. }
  298. if (a.stateNode.current === a) {
  299. // We've determined that A is the current branch.
  300. return fiber;
  301. } // Otherwise B has to be current branch.
  302. return alternate;
  303. }
  304. /**
  305. * `charCode` represents the actual "character code" and is safe to use with
  306. * `String.fromCharCode`. As such, only keys that correspond to printable
  307. * characters produce a valid `charCode`, the only exception to this is Enter.
  308. * The Tab-key is considered non-printable and does not have a `charCode`,
  309. * presumably because it does not produce a tab-character in browsers.
  310. *
  311. * @param {object} nativeEvent Native browser event.
  312. * @return {number} Normalized `charCode` property.
  313. */
  314. function getEventCharCode(nativeEvent) {
  315. var charCode;
  316. var keyCode = nativeEvent.keyCode;
  317. if ('charCode' in nativeEvent) {
  318. charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`.
  319. if (charCode === 0 && keyCode === 13) {
  320. charCode = 13;
  321. }
  322. } else {
  323. // IE8 does not implement `charCode`, but `keyCode` has the correct value.
  324. charCode = keyCode;
  325. } // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
  326. // report Enter as charCode 10 when ctrl is pressed.
  327. if (charCode === 10) {
  328. charCode = 13;
  329. } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
  330. // Must not discard the (non-)printable Enter-key.
  331. if (charCode >= 32 || charCode === 13) {
  332. return charCode;
  333. }
  334. return 0;
  335. }
  336. function functionThatReturnsTrue() {
  337. return true;
  338. }
  339. function functionThatReturnsFalse() {
  340. return false;
  341. } // This is intentionally a factory so that we have different returned constructors.
  342. // If we had a single constructor, it would be megamorphic and engines would deopt.
  343. function createSyntheticEvent(Interface) {
  344. /**
  345. * Synthetic events are dispatched by event plugins, typically in response to a
  346. * top-level event delegation handler.
  347. *
  348. * These systems should generally use pooling to reduce the frequency of garbage
  349. * collection. The system should check `isPersistent` to determine whether the
  350. * event should be released into the pool after being dispatched. Users that
  351. * need a persisted event should invoke `persist`.
  352. *
  353. * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
  354. * normalizing browser quirks. Subclasses do not necessarily have to implement a
  355. * DOM interface; custom application-specific events can also subclass this.
  356. */
  357. function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) {
  358. this._reactName = reactName;
  359. this._targetInst = targetInst;
  360. this.type = reactEventType;
  361. this.nativeEvent = nativeEvent;
  362. this.target = nativeEventTarget;
  363. this.currentTarget = null;
  364. for (var _propName in Interface) {
  365. if (!Interface.hasOwnProperty(_propName)) {
  366. continue;
  367. }
  368. var normalize = Interface[_propName];
  369. if (normalize) {
  370. this[_propName] = normalize(nativeEvent);
  371. } else {
  372. this[_propName] = nativeEvent[_propName];
  373. }
  374. }
  375. var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
  376. if (defaultPrevented) {
  377. this.isDefaultPrevented = functionThatReturnsTrue;
  378. } else {
  379. this.isDefaultPrevented = functionThatReturnsFalse;
  380. }
  381. this.isPropagationStopped = functionThatReturnsFalse;
  382. return this;
  383. }
  384. _assign(SyntheticBaseEvent.prototype, {
  385. preventDefault: function () {
  386. this.defaultPrevented = true;
  387. var event = this.nativeEvent;
  388. if (!event) {
  389. return;
  390. }
  391. if (event.preventDefault) {
  392. event.preventDefault(); // $FlowFixMe - flow is not aware of `unknown` in IE
  393. } else if (typeof event.returnValue !== 'unknown') {
  394. event.returnValue = false;
  395. }
  396. this.isDefaultPrevented = functionThatReturnsTrue;
  397. },
  398. stopPropagation: function () {
  399. var event = this.nativeEvent;
  400. if (!event) {
  401. return;
  402. }
  403. if (event.stopPropagation) {
  404. event.stopPropagation(); // $FlowFixMe - flow is not aware of `unknown` in IE
  405. } else if (typeof event.cancelBubble !== 'unknown') {
  406. // The ChangeEventPlugin registers a "propertychange" event for
  407. // IE. This event does not support bubbling or cancelling, and
  408. // any references to cancelBubble throw "Member not found". A
  409. // typeof check of "unknown" circumvents this issue (and is also
  410. // IE specific).
  411. event.cancelBubble = true;
  412. }
  413. this.isPropagationStopped = functionThatReturnsTrue;
  414. },
  415. /**
  416. * We release all dispatched `SyntheticEvent`s after each event loop, adding
  417. * them back into the pool. This allows a way to hold onto a reference that
  418. * won't be added back into the pool.
  419. */
  420. persist: function () {// Modern event system doesn't use pooling.
  421. },
  422. /**
  423. * Checks if this event should be released back into the pool.
  424. *
  425. * @return {boolean} True if this should not be released, false otherwise.
  426. */
  427. isPersistent: functionThatReturnsTrue
  428. });
  429. return SyntheticBaseEvent;
  430. }
  431. /**
  432. * @interface Event
  433. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  434. */
  435. var EventInterface = {
  436. eventPhase: 0,
  437. bubbles: 0,
  438. cancelable: 0,
  439. timeStamp: function (event) {
  440. return event.timeStamp || Date.now();
  441. },
  442. defaultPrevented: 0,
  443. isTrusted: 0
  444. };
  445. var SyntheticEvent = createSyntheticEvent(EventInterface);
  446. var UIEventInterface = _assign({}, EventInterface, {
  447. view: 0,
  448. detail: 0
  449. });
  450. var SyntheticUIEvent = createSyntheticEvent(UIEventInterface);
  451. var lastMovementX;
  452. var lastMovementY;
  453. var lastMouseEvent;
  454. function updateMouseMovementPolyfillState(event) {
  455. if (event !== lastMouseEvent) {
  456. if (lastMouseEvent && event.type === 'mousemove') {
  457. lastMovementX = event.screenX - lastMouseEvent.screenX;
  458. lastMovementY = event.screenY - lastMouseEvent.screenY;
  459. } else {
  460. lastMovementX = 0;
  461. lastMovementY = 0;
  462. }
  463. lastMouseEvent = event;
  464. }
  465. }
  466. /**
  467. * @interface MouseEvent
  468. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  469. */
  470. var MouseEventInterface = _assign({}, UIEventInterface, {
  471. screenX: 0,
  472. screenY: 0,
  473. clientX: 0,
  474. clientY: 0,
  475. pageX: 0,
  476. pageY: 0,
  477. ctrlKey: 0,
  478. shiftKey: 0,
  479. altKey: 0,
  480. metaKey: 0,
  481. getModifierState: getEventModifierState,
  482. button: 0,
  483. buttons: 0,
  484. relatedTarget: function (event) {
  485. if (event.relatedTarget === undefined) return event.fromElement === event.srcElement ? event.toElement : event.fromElement;
  486. return event.relatedTarget;
  487. },
  488. movementX: function (event) {
  489. if ('movementX' in event) {
  490. return event.movementX;
  491. }
  492. updateMouseMovementPolyfillState(event);
  493. return lastMovementX;
  494. },
  495. movementY: function (event) {
  496. if ('movementY' in event) {
  497. return event.movementY;
  498. } // Don't need to call updateMouseMovementPolyfillState() here
  499. // because it's guaranteed to have already run when movementX
  500. // was copied.
  501. return lastMovementY;
  502. }
  503. });
  504. var SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface);
  505. /**
  506. * @interface DragEvent
  507. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  508. */
  509. var DragEventInterface = _assign({}, MouseEventInterface, {
  510. dataTransfer: 0
  511. });
  512. var SyntheticDragEvent = createSyntheticEvent(DragEventInterface);
  513. /**
  514. * @interface FocusEvent
  515. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  516. */
  517. var FocusEventInterface = _assign({}, UIEventInterface, {
  518. relatedTarget: 0
  519. });
  520. var SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface);
  521. /**
  522. * @interface Event
  523. * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
  524. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
  525. */
  526. var AnimationEventInterface = _assign({}, EventInterface, {
  527. animationName: 0,
  528. elapsedTime: 0,
  529. pseudoElement: 0
  530. });
  531. var SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface);
  532. /**
  533. * @interface Event
  534. * @see http://www.w3.org/TR/clipboard-apis/
  535. */
  536. var ClipboardEventInterface = _assign({}, EventInterface, {
  537. clipboardData: function (event) {
  538. return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
  539. }
  540. });
  541. var SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface);
  542. /**
  543. * @interface Event
  544. * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
  545. */
  546. var CompositionEventInterface = _assign({}, EventInterface, {
  547. data: 0
  548. });
  549. var SyntheticCompositionEvent = createSyntheticEvent(CompositionEventInterface);
  550. /**
  551. * Normalization of deprecated HTML5 `key` values
  552. * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
  553. */
  554. var normalizeKey = {
  555. Esc: 'Escape',
  556. Spacebar: ' ',
  557. Left: 'ArrowLeft',
  558. Up: 'ArrowUp',
  559. Right: 'ArrowRight',
  560. Down: 'ArrowDown',
  561. Del: 'Delete',
  562. Win: 'OS',
  563. Menu: 'ContextMenu',
  564. Apps: 'ContextMenu',
  565. Scroll: 'ScrollLock',
  566. MozPrintableKey: 'Unidentified'
  567. };
  568. /**
  569. * Translation from legacy `keyCode` to HTML5 `key`
  570. * Only special keys supported, all others depend on keyboard layout or browser
  571. * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
  572. */
  573. var translateToKey = {
  574. '8': 'Backspace',
  575. '9': 'Tab',
  576. '12': 'Clear',
  577. '13': 'Enter',
  578. '16': 'Shift',
  579. '17': 'Control',
  580. '18': 'Alt',
  581. '19': 'Pause',
  582. '20': 'CapsLock',
  583. '27': 'Escape',
  584. '32': ' ',
  585. '33': 'PageUp',
  586. '34': 'PageDown',
  587. '35': 'End',
  588. '36': 'Home',
  589. '37': 'ArrowLeft',
  590. '38': 'ArrowUp',
  591. '39': 'ArrowRight',
  592. '40': 'ArrowDown',
  593. '45': 'Insert',
  594. '46': 'Delete',
  595. '112': 'F1',
  596. '113': 'F2',
  597. '114': 'F3',
  598. '115': 'F4',
  599. '116': 'F5',
  600. '117': 'F6',
  601. '118': 'F7',
  602. '119': 'F8',
  603. '120': 'F9',
  604. '121': 'F10',
  605. '122': 'F11',
  606. '123': 'F12',
  607. '144': 'NumLock',
  608. '145': 'ScrollLock',
  609. '224': 'Meta'
  610. };
  611. /**
  612. * @param {object} nativeEvent Native browser event.
  613. * @return {string} Normalized `key` property.
  614. */
  615. function getEventKey(nativeEvent) {
  616. if (nativeEvent.key) {
  617. // Normalize inconsistent values reported by browsers due to
  618. // implementations of a working draft specification.
  619. // FireFox implements `key` but returns `MozPrintableKey` for all
  620. // printable characters (normalized to `Unidentified`), ignore it.
  621. var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
  622. if (key !== 'Unidentified') {
  623. return key;
  624. }
  625. } // Browser does not implement `key`, polyfill as much of it as we can.
  626. if (nativeEvent.type === 'keypress') {
  627. var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can
  628. // thus be captured by `keypress`, no other non-printable key should.
  629. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
  630. }
  631. if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
  632. // While user keyboard layout determines the actual meaning of each
  633. // `keyCode` value, almost all function keys have a universal value.
  634. return translateToKey[nativeEvent.keyCode] || 'Unidentified';
  635. }
  636. return '';
  637. }
  638. /**
  639. * Translation from modifier key to the associated property in the event.
  640. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
  641. */
  642. var modifierKeyToProp = {
  643. Alt: 'altKey',
  644. Control: 'ctrlKey',
  645. Meta: 'metaKey',
  646. Shift: 'shiftKey'
  647. }; // Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
  648. // getModifierState. If getModifierState is not supported, we map it to a set of
  649. // modifier keys exposed by the event. In this case, Lock-keys are not supported.
  650. function modifierStateGetter(keyArg) {
  651. var syntheticEvent = this;
  652. var nativeEvent = syntheticEvent.nativeEvent;
  653. if (nativeEvent.getModifierState) {
  654. return nativeEvent.getModifierState(keyArg);
  655. }
  656. var keyProp = modifierKeyToProp[keyArg];
  657. return keyProp ? !!nativeEvent[keyProp] : false;
  658. }
  659. function getEventModifierState(nativeEvent) {
  660. return modifierStateGetter;
  661. }
  662. /**
  663. * @interface KeyboardEvent
  664. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  665. */
  666. var KeyboardEventInterface = _assign({}, UIEventInterface, {
  667. key: getEventKey,
  668. code: 0,
  669. location: 0,
  670. ctrlKey: 0,
  671. shiftKey: 0,
  672. altKey: 0,
  673. metaKey: 0,
  674. repeat: 0,
  675. locale: 0,
  676. getModifierState: getEventModifierState,
  677. // Legacy Interface
  678. charCode: function (event) {
  679. // `charCode` is the result of a KeyPress event and represents the value of
  680. // the actual printable character.
  681. // KeyPress is deprecated, but its replacement is not yet final and not
  682. // implemented in any major browser. Only KeyPress has charCode.
  683. if (event.type === 'keypress') {
  684. return getEventCharCode(event);
  685. }
  686. return 0;
  687. },
  688. keyCode: function (event) {
  689. // `keyCode` is the result of a KeyDown/Up event and represents the value of
  690. // physical keyboard key.
  691. // The actual meaning of the value depends on the users' keyboard layout
  692. // which cannot be detected. Assuming that it is a US keyboard layout
  693. // provides a surprisingly accurate mapping for US and European users.
  694. // Due to this, it is left to the user to implement at this time.
  695. if (event.type === 'keydown' || event.type === 'keyup') {
  696. return event.keyCode;
  697. }
  698. return 0;
  699. },
  700. which: function (event) {
  701. // `which` is an alias for either `keyCode` or `charCode` depending on the
  702. // type of the event.
  703. if (event.type === 'keypress') {
  704. return getEventCharCode(event);
  705. }
  706. if (event.type === 'keydown' || event.type === 'keyup') {
  707. return event.keyCode;
  708. }
  709. return 0;
  710. }
  711. });
  712. var SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface);
  713. /**
  714. * @interface PointerEvent
  715. * @see http://www.w3.org/TR/pointerevents/
  716. */
  717. var PointerEventInterface = _assign({}, MouseEventInterface, {
  718. pointerId: 0,
  719. width: 0,
  720. height: 0,
  721. pressure: 0,
  722. tangentialPressure: 0,
  723. tiltX: 0,
  724. tiltY: 0,
  725. twist: 0,
  726. pointerType: 0,
  727. isPrimary: 0
  728. });
  729. var SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface);
  730. /**
  731. * @interface TouchEvent
  732. * @see http://www.w3.org/TR/touch-events/
  733. */
  734. var TouchEventInterface = _assign({}, UIEventInterface, {
  735. touches: 0,
  736. targetTouches: 0,
  737. changedTouches: 0,
  738. altKey: 0,
  739. metaKey: 0,
  740. ctrlKey: 0,
  741. shiftKey: 0,
  742. getModifierState: getEventModifierState
  743. });
  744. var SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface);
  745. /**
  746. * @interface Event
  747. * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
  748. * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
  749. */
  750. var TransitionEventInterface = _assign({}, EventInterface, {
  751. propertyName: 0,
  752. elapsedTime: 0,
  753. pseudoElement: 0
  754. });
  755. var SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface);
  756. /**
  757. * @interface WheelEvent
  758. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  759. */
  760. var WheelEventInterface = _assign({}, MouseEventInterface, {
  761. deltaX: function (event) {
  762. return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
  763. 'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
  764. },
  765. deltaY: function (event) {
  766. return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
  767. 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
  768. 'wheelDelta' in event ? -event.wheelDelta : 0;
  769. },
  770. deltaZ: 0,
  771. // Browsers without "deltaMode" is reporting in raw wheel delta where one
  772. // notch on the scroll is always +/- 120, roughly equivalent to pixels.
  773. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
  774. // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
  775. deltaMode: 0
  776. });
  777. var SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface);
  778. /**
  779. * HTML nodeType values that represent the type of the node
  780. */
  781. var ELEMENT_NODE = 1;
  782. var didWarnAboutMessageChannel = false;
  783. var enqueueTaskImpl = null;
  784. function enqueueTask(task) {
  785. if (enqueueTaskImpl === null) {
  786. try {
  787. // read require off the module object to get around the bundlers.
  788. // we don't want them to detect a require and bundle a Node polyfill.
  789. var requireString = ('require' + Math.random()).slice(0, 7);
  790. var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's
  791. // version of setImmediate, bypassing fake timers if any.
  792. enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate;
  793. } catch (_err) {
  794. // we're in a browser
  795. // we can't use regular timers because they may still be faked
  796. // so we try MessageChannel+postMessage instead
  797. enqueueTaskImpl = function (callback) {
  798. {
  799. if (didWarnAboutMessageChannel === false) {
  800. didWarnAboutMessageChannel = true;
  801. if (typeof MessageChannel === 'undefined') {
  802. error('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.');
  803. }
  804. }
  805. }
  806. var channel = new MessageChannel();
  807. channel.port1.onmessage = callback;
  808. channel.port2.postMessage(undefined);
  809. };
  810. }
  811. }
  812. return enqueueTaskImpl(task);
  813. }
  814. var ReactInternals$1 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  815. var _ReactInternals$Sched = ReactInternals$1.Scheduler,
  816. unstable_cancelCallback = _ReactInternals$Sched.unstable_cancelCallback,
  817. unstable_now = _ReactInternals$Sched.unstable_now,
  818. unstable_scheduleCallback = _ReactInternals$Sched.unstable_scheduleCallback,
  819. unstable_shouldYield = _ReactInternals$Sched.unstable_shouldYield,
  820. unstable_requestPaint = _ReactInternals$Sched.unstable_requestPaint,
  821. unstable_getFirstCallbackNode = _ReactInternals$Sched.unstable_getFirstCallbackNode,
  822. unstable_runWithPriority = _ReactInternals$Sched.unstable_runWithPriority,
  823. unstable_next = _ReactInternals$Sched.unstable_next,
  824. unstable_continueExecution = _ReactInternals$Sched.unstable_continueExecution,
  825. unstable_pauseExecution = _ReactInternals$Sched.unstable_pauseExecution,
  826. unstable_getCurrentPriorityLevel = _ReactInternals$Sched.unstable_getCurrentPriorityLevel,
  827. unstable_ImmediatePriority = _ReactInternals$Sched.unstable_ImmediatePriority,
  828. unstable_UserBlockingPriority = _ReactInternals$Sched.unstable_UserBlockingPriority,
  829. unstable_NormalPriority = _ReactInternals$Sched.unstable_NormalPriority,
  830. unstable_LowPriority = _ReactInternals$Sched.unstable_LowPriority,
  831. unstable_IdlePriority = _ReactInternals$Sched.unstable_IdlePriority,
  832. unstable_forceFrameRate = _ReactInternals$Sched.unstable_forceFrameRate,
  833. unstable_flushAllWithoutAsserting = _ReactInternals$Sched.unstable_flushAllWithoutAsserting;
  834. var EventInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Events; // const getInstanceFromNode = EventInternals[0];
  835. // const getNodeFromInstance = EventInternals[1];
  836. // const getFiberCurrentPropsFromNode = EventInternals[2];
  837. // const enqueueStateRestore = EventInternals[3];
  838. // const restoreStateIfNeeded = EventInternals[4];
  839. var flushPassiveEffects = EventInternals[5];
  840. var IsThisRendererActing = EventInternals[6];
  841. var batchedUpdates = ReactDOM.unstable_batchedUpdates;
  842. var IsSomeRendererActing = ReactSharedInternals.IsSomeRendererActing; // This is the public version of `ReactTestUtils.act`. It is implemented in
  843. // "userspace" (i.e. not the reconciler), so that it doesn't add to the
  844. // production bundle size.
  845. // TODO: Remove this implementation of `act` in favor of the one exported by
  846. // the reconciler. To do this, we must first drop support for `act` in
  847. // production mode.
  848. // TODO: Remove support for the mock scheduler build, which was only added for
  849. // the purposes of internal testing. Internal tests should use
  850. // `unstable_concurrentAct` instead.
  851. var isSchedulerMocked = typeof unstable_flushAllWithoutAsserting === 'function';
  852. var flushWork = unstable_flushAllWithoutAsserting || function () {
  853. var didFlushWork = false;
  854. while (flushPassiveEffects()) {
  855. didFlushWork = true;
  856. }
  857. return didFlushWork;
  858. };
  859. function flushWorkAndMicroTasks(onDone) {
  860. try {
  861. flushWork();
  862. enqueueTask(function () {
  863. if (flushWork()) {
  864. flushWorkAndMicroTasks(onDone);
  865. } else {
  866. onDone();
  867. }
  868. });
  869. } catch (err) {
  870. onDone(err);
  871. }
  872. } // we track the 'depth' of the act() calls with this counter,
  873. // so we can tell if any async act() calls try to run in parallel.
  874. var actingUpdatesScopeDepth = 0;
  875. function act(callback) {
  876. var previousActingUpdatesScopeDepth = actingUpdatesScopeDepth;
  877. actingUpdatesScopeDepth++;
  878. var previousIsSomeRendererActing = IsSomeRendererActing.current;
  879. var previousIsThisRendererActing = IsThisRendererActing.current;
  880. IsSomeRendererActing.current = true;
  881. IsThisRendererActing.current = true;
  882. function onDone() {
  883. actingUpdatesScopeDepth--;
  884. IsSomeRendererActing.current = previousIsSomeRendererActing;
  885. IsThisRendererActing.current = previousIsThisRendererActing;
  886. {
  887. if (actingUpdatesScopeDepth > previousActingUpdatesScopeDepth) {
  888. // if it's _less than_ previousActingUpdatesScopeDepth, then we can assume the 'other' one has warned
  889. error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. ');
  890. }
  891. }
  892. }
  893. var result;
  894. try {
  895. result = batchedUpdates(callback);
  896. } catch (error) {
  897. // on sync errors, we still want to 'cleanup' and decrement actingUpdatesScopeDepth
  898. onDone();
  899. throw error;
  900. }
  901. if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
  902. // setup a boolean that gets set to true only
  903. // once this act() call is await-ed
  904. var called = false;
  905. {
  906. if (typeof Promise !== 'undefined') {
  907. //eslint-disable-next-line no-undef
  908. Promise.resolve().then(function () {}).then(function () {
  909. if (called === false) {
  910. error('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 () => ...);');
  911. }
  912. });
  913. }
  914. } // in the async case, the returned thenable runs the callback, flushes
  915. // effects and microtasks in a loop until flushPassiveEffects() === false,
  916. // and cleans up
  917. return {
  918. then: function (resolve, reject) {
  919. called = true;
  920. result.then(function () {
  921. if (actingUpdatesScopeDepth > 1 || isSchedulerMocked === true && previousIsSomeRendererActing === true) {
  922. onDone();
  923. resolve();
  924. return;
  925. } // we're about to exit the act() scope,
  926. // now's the time to flush tasks/effects
  927. flushWorkAndMicroTasks(function (err) {
  928. onDone();
  929. if (err) {
  930. reject(err);
  931. } else {
  932. resolve();
  933. }
  934. });
  935. }, function (err) {
  936. onDone();
  937. reject(err);
  938. });
  939. }
  940. };
  941. } else {
  942. {
  943. if (result !== undefined) {
  944. error('The callback passed to act(...) function ' + 'must return undefined, or a Promise. You returned %s', result);
  945. }
  946. } // flush effects until none remain, and cleanup
  947. try {
  948. if (actingUpdatesScopeDepth === 1 && (isSchedulerMocked === false || previousIsSomeRendererActing === false)) {
  949. // we're about to exit the act() scope,
  950. // now's the time to flush effects
  951. flushWork();
  952. }
  953. onDone();
  954. } catch (err) {
  955. onDone();
  956. throw err;
  957. } // in the sync case, the returned thenable only warns *if* await-ed
  958. return {
  959. then: function (resolve) {
  960. {
  961. error('Do not await the result of calling act(...) with sync logic, it is not a Promise.');
  962. }
  963. resolve();
  964. }
  965. };
  966. }
  967. }
  968. var EventInternals$1 = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Events; // const getInstanceFromNode = EventInternals[0];
  969. // const getNodeFromInstance = EventInternals[1];
  970. // const getFiberCurrentPropsFromNode = EventInternals[2];
  971. // const enqueueStateRestore = EventInternals[3];
  972. // const restoreStateIfNeeded = EventInternals[4];
  973. // const flushPassiveEffects = EventInternals[5];
  974. var IsThisRendererActing$1 = EventInternals$1[6];
  975. var batchedUpdates$1 = ReactDOM.unstable_batchedUpdates;
  976. var IsSomeRendererActing$1 = ReactSharedInternals.IsSomeRendererActing; // This version of `act` is only used by our tests. Unlike the public version
  977. // of `act`, it's designed to work identically in both production and
  978. // development. It may have slightly different behavior from the public
  979. // version, too, since our constraints in our test suite are not the same as
  980. // those of developers using React — we're testing React itself, as opposed to
  981. // building an app with React.
  982. var actingUpdatesScopeDepth$1 = 0;
  983. function unstable_concurrentAct(scope) {
  984. if (unstable_flushAllWithoutAsserting === undefined) {
  985. throw Error('This version of `act` requires a special mock build of Scheduler.');
  986. }
  987. if (setTimeout._isMockFunction !== true) {
  988. throw Error("This version of `act` requires Jest's timer mocks " + '(i.e. jest.useFakeTimers).');
  989. }
  990. var previousActingUpdatesScopeDepth = actingUpdatesScopeDepth$1;
  991. var previousIsSomeRendererActing = IsSomeRendererActing$1.current;
  992. var previousIsThisRendererActing = IsThisRendererActing$1.current;
  993. IsSomeRendererActing$1.current = true;
  994. IsThisRendererActing$1.current = true;
  995. actingUpdatesScopeDepth$1++;
  996. var unwind = function () {
  997. actingUpdatesScopeDepth$1--;
  998. IsSomeRendererActing$1.current = previousIsSomeRendererActing;
  999. IsThisRendererActing$1.current = previousIsThisRendererActing;
  1000. {
  1001. if (actingUpdatesScopeDepth$1 > previousActingUpdatesScopeDepth) {
  1002. // if it's _less than_ previousActingUpdatesScopeDepth, then we can
  1003. // assume the 'other' one has warned
  1004. error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. ');
  1005. }
  1006. }
  1007. }; // TODO: This would be way simpler if 1) we required a promise to be
  1008. // returned and 2) we could use async/await. Since it's only our used in
  1009. // our test suite, we should be able to.
  1010. try {
  1011. var thenable = batchedUpdates$1(scope);
  1012. if (typeof thenable === 'object' && thenable !== null && typeof thenable.then === 'function') {
  1013. return {
  1014. then: function (resolve, reject) {
  1015. thenable.then(function () {
  1016. flushActWork(function () {
  1017. unwind();
  1018. resolve();
  1019. }, function (error) {
  1020. unwind();
  1021. reject(error);
  1022. });
  1023. }, function (error) {
  1024. unwind();
  1025. reject(error);
  1026. });
  1027. }
  1028. };
  1029. } else {
  1030. try {
  1031. // TODO: Let's not support non-async scopes at all in our tests. Need to
  1032. // migrate existing tests.
  1033. var didFlushWork;
  1034. do {
  1035. didFlushWork = unstable_flushAllWithoutAsserting();
  1036. } while (didFlushWork);
  1037. } finally {
  1038. unwind();
  1039. }
  1040. }
  1041. } catch (error) {
  1042. unwind();
  1043. throw error;
  1044. }
  1045. }
  1046. function flushActWork(resolve, reject) {
  1047. // Flush suspended fallbacks
  1048. // $FlowFixMe: Flow doesn't know about global Jest object
  1049. jest.runOnlyPendingTimers();
  1050. enqueueTask(function () {
  1051. try {
  1052. var didFlushWork = unstable_flushAllWithoutAsserting();
  1053. if (didFlushWork) {
  1054. flushActWork(resolve, reject);
  1055. } else {
  1056. resolve();
  1057. }
  1058. } catch (error) {
  1059. reject(error);
  1060. }
  1061. });
  1062. }
  1063. function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) {
  1064. var funcArgs = Array.prototype.slice.call(arguments, 3);
  1065. try {
  1066. func.apply(context, funcArgs);
  1067. } catch (error) {
  1068. this.onError(error);
  1069. }
  1070. }
  1071. var invokeGuardedCallbackImpl = invokeGuardedCallbackProd;
  1072. {
  1073. // In DEV mode, we swap out invokeGuardedCallback for a special version
  1074. // that plays more nicely with the browser's DevTools. The idea is to preserve
  1075. // "Pause on exceptions" behavior. Because React wraps all user-provided
  1076. // functions in invokeGuardedCallback, and the production version of
  1077. // invokeGuardedCallback uses a try-catch, all user exceptions are treated
  1078. // like caught exceptions, and the DevTools won't pause unless the developer
  1079. // takes the extra step of enabling pause on caught exceptions. This is
  1080. // unintuitive, though, because even though React has caught the error, from
  1081. // the developer's perspective, the error is uncaught.
  1082. //
  1083. // To preserve the expected "Pause on exceptions" behavior, we don't use a
  1084. // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
  1085. // DOM node, and call the user-provided callback from inside an event handler
  1086. // for that fake event. If the callback throws, the error is "captured" using
  1087. // a global event handler. But because the error happens in a different
  1088. // event loop context, it does not interrupt the normal program flow.
  1089. // Effectively, this gives us try-catch behavior without actually using
  1090. // try-catch. Neat!
  1091. // Check that the browser supports the APIs we need to implement our special
  1092. // DEV version of invokeGuardedCallback
  1093. if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
  1094. var fakeNode = document.createElement('react');
  1095. invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) {
  1096. // If document doesn't exist we know for sure we will crash in this method
  1097. // when we call document.createEvent(). However this can cause confusing
  1098. // errors: https://github.com/facebookincubator/create-react-app/issues/3482
  1099. // So we preemptively throw with a better message instead.
  1100. if (!(typeof document !== 'undefined')) {
  1101. {
  1102. throw Error( "The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous." );
  1103. }
  1104. }
  1105. var evt = document.createEvent('Event');
  1106. var didCall = false; // Keeps track of whether the user-provided callback threw an error. We
  1107. // set this to true at the beginning, then set it to false right after
  1108. // calling the function. If the function errors, `didError` will never be
  1109. // set to false. This strategy works even if the browser is flaky and
  1110. // fails to call our global error handler, because it doesn't rely on
  1111. // the error event at all.
  1112. var didError = true; // Keeps track of the value of window.event so that we can reset it
  1113. // during the callback to let user code access window.event in the
  1114. // browsers that support it.
  1115. var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event
  1116. // dispatching: https://github.com/facebook/react/issues/13688
  1117. var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event');
  1118. function restoreAfterDispatch() {
  1119. // We immediately remove the callback from event listeners so that
  1120. // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
  1121. // nested call would trigger the fake event handlers of any call higher
  1122. // in the stack.
  1123. fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the
  1124. // window.event assignment in both IE <= 10 as they throw an error
  1125. // "Member not found" in strict mode, and in Firefox which does not
  1126. // support window.event.
  1127. if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
  1128. window.event = windowEvent;
  1129. }
  1130. } // Create an event handler for our fake event. We will synchronously
  1131. // dispatch our fake event using `dispatchEvent`. Inside the handler, we
  1132. // call the user-provided callback.
  1133. var funcArgs = Array.prototype.slice.call(arguments, 3);
  1134. function callCallback() {
  1135. didCall = true;
  1136. restoreAfterDispatch();
  1137. func.apply(context, funcArgs);
  1138. didError = false;
  1139. } // Create a global error event handler. We use this to capture the value
  1140. // that was thrown. It's possible that this error handler will fire more
  1141. // than once; for example, if non-React code also calls `dispatchEvent`
  1142. // and a handler for that event throws. We should be resilient to most of
  1143. // those cases. Even if our error event handler fires more than once, the
  1144. // last error event is always used. If the callback actually does error,
  1145. // we know that the last error event is the correct one, because it's not
  1146. // possible for anything else to have happened in between our callback
  1147. // erroring and the code that follows the `dispatchEvent` call below. If
  1148. // the callback doesn't error, but the error event was fired, we know to
  1149. // ignore it because `didError` will be false, as described above.
  1150. var error; // Use this to track whether the error event is ever called.
  1151. var didSetError = false;
  1152. var isCrossOriginError = false;
  1153. function handleWindowError(event) {
  1154. error = event.error;
  1155. didSetError = true;
  1156. if (error === null && event.colno === 0 && event.lineno === 0) {
  1157. isCrossOriginError = true;
  1158. }
  1159. if (event.defaultPrevented) {
  1160. // Some other error handler has prevented default.
  1161. // Browsers silence the error report if this happens.
  1162. // We'll remember this to later decide whether to log it or not.
  1163. if (error != null && typeof error === 'object') {
  1164. try {
  1165. error._suppressLogging = true;
  1166. } catch (inner) {// Ignore.
  1167. }
  1168. }
  1169. }
  1170. } // Create a fake event type.
  1171. var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers
  1172. window.addEventListener('error', handleWindowError);
  1173. fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function
  1174. // errors, it will trigger our global error handler.
  1175. evt.initEvent(evtType, false, false);
  1176. fakeNode.dispatchEvent(evt);
  1177. if (windowEventDescriptor) {
  1178. Object.defineProperty(window, 'event', windowEventDescriptor);
  1179. }
  1180. if (didCall && didError) {
  1181. if (!didSetError) {
  1182. // The callback errored, but the error event never fired.
  1183. error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.');
  1184. } else if (isCrossOriginError) {
  1185. error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://reactjs.org/link/crossorigin-error for more information.');
  1186. }
  1187. this.onError(error);
  1188. } // Remove our event listeners
  1189. window.removeEventListener('error', handleWindowError);
  1190. if (!didCall) {
  1191. // Something went really wrong, and our event was not dispatched.
  1192. // https://github.com/facebook/react/issues/16734
  1193. // https://github.com/facebook/react/issues/16585
  1194. // Fall back to the production implementation.
  1195. restoreAfterDispatch();
  1196. return invokeGuardedCallbackProd.apply(this, arguments);
  1197. }
  1198. };
  1199. }
  1200. }
  1201. var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
  1202. var hasError = false;
  1203. var caughtError = null; // Used by event system to capture/rethrow the first error.
  1204. var hasRethrowError = false;
  1205. var rethrowError = null;
  1206. var reporter = {
  1207. onError: function (error) {
  1208. hasError = true;
  1209. caughtError = error;
  1210. }
  1211. };
  1212. /**
  1213. * Call a function while guarding against errors that happens within it.
  1214. * Returns an error if it throws, otherwise null.
  1215. *
  1216. * In production, this is implemented using a try-catch. The reason we don't
  1217. * use a try-catch directly is so that we can swap out a different
  1218. * implementation in DEV mode.
  1219. *
  1220. * @param {String} name of the guard to use for logging or debugging
  1221. * @param {Function} func The function to invoke
  1222. * @param {*} context The context to use when calling the function
  1223. * @param {...*} args Arguments for function
  1224. */
  1225. function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
  1226. hasError = false;
  1227. caughtError = null;
  1228. invokeGuardedCallbackImpl$1.apply(reporter, arguments);
  1229. }
  1230. /**
  1231. * Same as invokeGuardedCallback, but instead of returning an error, it stores
  1232. * it in a global so it can be rethrown by `rethrowCaughtError` later.
  1233. * TODO: See if caughtError and rethrowError can be unified.
  1234. *
  1235. * @param {String} name of the guard to use for logging or debugging
  1236. * @param {Function} func The function to invoke
  1237. * @param {*} context The context to use when calling the function
  1238. * @param {...*} args Arguments for function
  1239. */
  1240. function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
  1241. invokeGuardedCallback.apply(this, arguments);
  1242. if (hasError) {
  1243. var error = clearCaughtError();
  1244. if (!hasRethrowError) {
  1245. hasRethrowError = true;
  1246. rethrowError = error;
  1247. }
  1248. }
  1249. }
  1250. /**
  1251. * During execution of guarded functions we will capture the first error which
  1252. * we will rethrow to be handled by the top level error handler.
  1253. */
  1254. function rethrowCaughtError() {
  1255. if (hasRethrowError) {
  1256. var error = rethrowError;
  1257. hasRethrowError = false;
  1258. rethrowError = null;
  1259. throw error;
  1260. }
  1261. }
  1262. function clearCaughtError() {
  1263. if (hasError) {
  1264. var error = caughtError;
  1265. hasError = false;
  1266. caughtError = null;
  1267. return error;
  1268. } else {
  1269. {
  1270. {
  1271. throw Error( "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." );
  1272. }
  1273. }
  1274. }
  1275. }
  1276. var EventInternals$2 = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Events;
  1277. var getInstanceFromNode = EventInternals$2[0];
  1278. var getNodeFromInstance = EventInternals$2[1];
  1279. var getFiberCurrentPropsFromNode = EventInternals$2[2];
  1280. var enqueueStateRestore = EventInternals$2[3];
  1281. var restoreStateIfNeeded = EventInternals$2[4]; // const flushPassiveEffects = EventInternals[5];
  1282. // TODO: This is related to `act`, not events. Move to separate key?
  1283. // const IsThisRendererActing = EventInternals[6];
  1284. function Event(suffix) {}
  1285. var hasWarnedAboutDeprecatedMockComponent = false;
  1286. /**
  1287. * @class ReactTestUtils
  1288. */
  1289. function findAllInRenderedFiberTreeInternal(fiber, test) {
  1290. if (!fiber) {
  1291. return [];
  1292. }
  1293. var currentParent = findCurrentFiberUsingSlowPath(fiber);
  1294. if (!currentParent) {
  1295. return [];
  1296. }
  1297. var node = currentParent;
  1298. var ret = [];
  1299. while (true) {
  1300. if (node.tag === HostComponent || node.tag === HostText || node.tag === ClassComponent || node.tag === FunctionComponent) {
  1301. var publicInst = node.stateNode;
  1302. if (test(publicInst)) {
  1303. ret.push(publicInst);
  1304. }
  1305. }
  1306. if (node.child) {
  1307. node.child.return = node;
  1308. node = node.child;
  1309. continue;
  1310. }
  1311. if (node === currentParent) {
  1312. return ret;
  1313. }
  1314. while (!node.sibling) {
  1315. if (!node.return || node.return === currentParent) {
  1316. return ret;
  1317. }
  1318. node = node.return;
  1319. }
  1320. node.sibling.return = node.return;
  1321. node = node.sibling;
  1322. }
  1323. }
  1324. function validateClassInstance(inst, methodName) {
  1325. if (!inst) {
  1326. // This is probably too relaxed but it's existing behavior.
  1327. return;
  1328. }
  1329. if (get(inst)) {
  1330. // This is a public instance indeed.
  1331. return;
  1332. }
  1333. var received;
  1334. var stringified = '' + inst;
  1335. if (Array.isArray(inst)) {
  1336. received = 'an array';
  1337. } else if (inst && inst.nodeType === ELEMENT_NODE && inst.tagName) {
  1338. received = 'a DOM node';
  1339. } else if (stringified === '[object Object]') {
  1340. received = 'object with keys {' + Object.keys(inst).join(', ') + '}';
  1341. } else {
  1342. received = stringified;
  1343. }
  1344. {
  1345. {
  1346. throw Error( methodName + "(...): the first argument must be a React class instance. Instead received: " + received + "." );
  1347. }
  1348. }
  1349. }
  1350. /**
  1351. * Utilities for making it easy to test React components.
  1352. *
  1353. * See https://reactjs.org/docs/test-utils.html
  1354. *
  1355. * Todo: Support the entire DOM.scry query syntax. For now, these simple
  1356. * utilities will suffice for testing purposes.
  1357. * @lends ReactTestUtils
  1358. */
  1359. function renderIntoDocument(element) {
  1360. var div = document.createElement('div'); // None of our tests actually require attaching the container to the
  1361. // DOM, and doing so creates a mess that we rely on test isolation to
  1362. // clean up, so we're going to stop honoring the name of this method
  1363. // (and probably rename it eventually) if no problems arise.
  1364. // document.documentElement.appendChild(div);
  1365. return ReactDOM.render(element, div);
  1366. }
  1367. function isElement(element) {
  1368. return React.isValidElement(element);
  1369. }
  1370. function isElementOfType(inst, convenienceConstructor) {
  1371. return React.isValidElement(inst) && inst.type === convenienceConstructor;
  1372. }
  1373. function isDOMComponent(inst) {
  1374. return !!(inst && inst.nodeType === ELEMENT_NODE && inst.tagName);
  1375. }
  1376. function isDOMComponentElement(inst) {
  1377. return !!(inst && React.isValidElement(inst) && !!inst.tagName);
  1378. }
  1379. function isCompositeComponent(inst) {
  1380. if (isDOMComponent(inst)) {
  1381. // Accessing inst.setState warns; just return false as that'll be what
  1382. // this returns when we have DOM nodes as refs directly
  1383. return false;
  1384. }
  1385. return inst != null && typeof inst.render === 'function' && typeof inst.setState === 'function';
  1386. }
  1387. function isCompositeComponentWithType(inst, type) {
  1388. if (!isCompositeComponent(inst)) {
  1389. return false;
  1390. }
  1391. var internalInstance = get(inst);
  1392. var constructor = internalInstance.type;
  1393. return constructor === type;
  1394. }
  1395. function findAllInRenderedTree(inst, test) {
  1396. validateClassInstance(inst, 'findAllInRenderedTree');
  1397. if (!inst) {
  1398. return [];
  1399. }
  1400. var internalInstance = get(inst);
  1401. return findAllInRenderedFiberTreeInternal(internalInstance, test);
  1402. }
  1403. /**
  1404. * Finds all instance of components in the rendered tree that are DOM
  1405. * components with the class name matching `className`.
  1406. * @return {array} an array of all the matches.
  1407. */
  1408. function scryRenderedDOMComponentsWithClass(root, classNames) {
  1409. validateClassInstance(root, 'scryRenderedDOMComponentsWithClass');
  1410. return findAllInRenderedTree(root, function (inst) {
  1411. if (isDOMComponent(inst)) {
  1412. var className = inst.className;
  1413. if (typeof className !== 'string') {
  1414. // SVG, probably.
  1415. className = inst.getAttribute('class') || '';
  1416. }
  1417. var classList = className.split(/\s+/);
  1418. if (!Array.isArray(classNames)) {
  1419. if (!(classNames !== undefined)) {
  1420. {
  1421. throw Error( "TestUtils.scryRenderedDOMComponentsWithClass expects a className as a second argument." );
  1422. }
  1423. }
  1424. classNames = classNames.split(/\s+/);
  1425. }
  1426. return classNames.every(function (name) {
  1427. return classList.indexOf(name) !== -1;
  1428. });
  1429. }
  1430. return false;
  1431. });
  1432. }
  1433. /**
  1434. * Like scryRenderedDOMComponentsWithClass but expects there to be one result,
  1435. * and returns that one result, or throws exception if there is any other
  1436. * number of matches besides one.
  1437. * @return {!ReactDOMComponent} The one match.
  1438. */
  1439. function findRenderedDOMComponentWithClass(root, className) {
  1440. validateClassInstance(root, 'findRenderedDOMComponentWithClass');
  1441. var all = scryRenderedDOMComponentsWithClass(root, className);
  1442. if (all.length !== 1) {
  1443. throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for class:' + className);
  1444. }
  1445. return all[0];
  1446. }
  1447. /**
  1448. * Finds all instance of components in the rendered tree that are DOM
  1449. * components with the tag name matching `tagName`.
  1450. * @return {array} an array of all the matches.
  1451. */
  1452. function scryRenderedDOMComponentsWithTag(root, tagName) {
  1453. validateClassInstance(root, 'scryRenderedDOMComponentsWithTag');
  1454. return findAllInRenderedTree(root, function (inst) {
  1455. return isDOMComponent(inst) && inst.tagName.toUpperCase() === tagName.toUpperCase();
  1456. });
  1457. }
  1458. /**
  1459. * Like scryRenderedDOMComponentsWithTag but expects there to be one result,
  1460. * and returns that one result, or throws exception if there is any other
  1461. * number of matches besides one.
  1462. * @return {!ReactDOMComponent} The one match.
  1463. */
  1464. function findRenderedDOMComponentWithTag(root, tagName) {
  1465. validateClassInstance(root, 'findRenderedDOMComponentWithTag');
  1466. var all = scryRenderedDOMComponentsWithTag(root, tagName);
  1467. if (all.length !== 1) {
  1468. throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for tag:' + tagName);
  1469. }
  1470. return all[0];
  1471. }
  1472. /**
  1473. * Finds all instances of components with type equal to `componentType`.
  1474. * @return {array} an array of all the matches.
  1475. */
  1476. function scryRenderedComponentsWithType(root, componentType) {
  1477. validateClassInstance(root, 'scryRenderedComponentsWithType');
  1478. return findAllInRenderedTree(root, function (inst) {
  1479. return isCompositeComponentWithType(inst, componentType);
  1480. });
  1481. }
  1482. /**
  1483. * Same as `scryRenderedComponentsWithType` but expects there to be one result
  1484. * and returns that one result, or throws exception if there is any other
  1485. * number of matches besides one.
  1486. * @return {!ReactComponent} The one match.
  1487. */
  1488. function findRenderedComponentWithType(root, componentType) {
  1489. validateClassInstance(root, 'findRenderedComponentWithType');
  1490. var all = scryRenderedComponentsWithType(root, componentType);
  1491. if (all.length !== 1) {
  1492. throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for componentType:' + componentType);
  1493. }
  1494. return all[0];
  1495. }
  1496. /**
  1497. * Pass a mocked component module to this method to augment it with
  1498. * useful methods that allow it to be used as a dummy React component.
  1499. * Instead of rendering as usual, the component will become a simple
  1500. * <div> containing any provided children.
  1501. *
  1502. * @param {object} module the mock function object exported from a
  1503. * module that defines the component to be mocked
  1504. * @param {?string} mockTagName optional dummy root tag name to return
  1505. * from render method (overrides
  1506. * module.mockTagName if provided)
  1507. * @return {object} the ReactTestUtils object (for chaining)
  1508. */
  1509. function mockComponent(module, mockTagName) {
  1510. {
  1511. if (!hasWarnedAboutDeprecatedMockComponent) {
  1512. hasWarnedAboutDeprecatedMockComponent = true;
  1513. warn('ReactTestUtils.mockComponent() is deprecated. ' + 'Use shallow rendering or jest.mock() instead.\n\n' + 'See https://reactjs.org/link/test-utils-mock-component for more information.');
  1514. }
  1515. }
  1516. mockTagName = mockTagName || module.mockTagName || 'div';
  1517. module.prototype.render.mockImplementation(function () {
  1518. return React.createElement(mockTagName, null, this.props.children);
  1519. });
  1520. return this;
  1521. }
  1522. function nativeTouchData(x, y) {
  1523. return {
  1524. touches: [{
  1525. pageX: x,
  1526. pageY: y
  1527. }]
  1528. };
  1529. } // Start of inline: the below functions were inlined from
  1530. // EventPropagator.js, as they deviated from ReactDOM's newer
  1531. // implementations.
  1532. /**
  1533. * Dispatch the event to the listener.
  1534. * @param {SyntheticEvent} event SyntheticEvent to handle
  1535. * @param {function} listener Application-level callback
  1536. * @param {*} inst Internal component instance
  1537. */
  1538. function executeDispatch(event, listener, inst) {
  1539. var type = event.type || 'unknown-event';
  1540. event.currentTarget = getNodeFromInstance(inst);
  1541. invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
  1542. event.currentTarget = null;
  1543. }
  1544. /**
  1545. * Standard/simple iteration through an event's collected dispatches.
  1546. */
  1547. function executeDispatchesInOrder(event) {
  1548. var dispatchListeners = event._dispatchListeners;
  1549. var dispatchInstances = event._dispatchInstances;
  1550. if (Array.isArray(dispatchListeners)) {
  1551. for (var i = 0; i < dispatchListeners.length; i++) {
  1552. if (event.isPropagationStopped()) {
  1553. break;
  1554. } // Listeners and Instances are two parallel arrays that are always in sync.
  1555. executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
  1556. }
  1557. } else if (dispatchListeners) {
  1558. executeDispatch(event, dispatchListeners, dispatchInstances);
  1559. }
  1560. event._dispatchListeners = null;
  1561. event._dispatchInstances = null;
  1562. }
  1563. /**
  1564. * Dispatches an event and releases it back into the pool, unless persistent.
  1565. *
  1566. * @param {?object} event Synthetic event to be dispatched.
  1567. * @private
  1568. */
  1569. var executeDispatchesAndRelease = function (event) {
  1570. if (event) {
  1571. executeDispatchesInOrder(event);
  1572. if (!event.isPersistent()) {
  1573. event.constructor.release(event);
  1574. }
  1575. }
  1576. };
  1577. function isInteractive(tag) {
  1578. return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
  1579. }
  1580. function getParent(inst) {
  1581. do {
  1582. inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.
  1583. // That is depending on if we want nested subtrees (layers) to bubble
  1584. // events to their parent. We could also go through parentNode on the
  1585. // host node but that wouldn't work for React Native and doesn't let us
  1586. // do the portal feature.
  1587. } while (inst && inst.tag !== HostComponent);
  1588. if (inst) {
  1589. return inst;
  1590. }
  1591. return null;
  1592. }
  1593. /**
  1594. * Simulates the traversal of a two-phase, capture/bubble event dispatch.
  1595. */
  1596. function traverseTwoPhase(inst, fn, arg) {
  1597. var path = [];
  1598. while (inst) {
  1599. path.push(inst);
  1600. inst = getParent(inst);
  1601. }
  1602. var i;
  1603. for (i = path.length; i-- > 0;) {
  1604. fn(path[i], 'captured', arg);
  1605. }
  1606. for (i = 0; i < path.length; i++) {
  1607. fn(path[i], 'bubbled', arg);
  1608. }
  1609. }
  1610. function shouldPreventMouseEvent(name, type, props) {
  1611. switch (name) {
  1612. case 'onClick':
  1613. case 'onClickCapture':
  1614. case 'onDoubleClick':
  1615. case 'onDoubleClickCapture':
  1616. case 'onMouseDown':
  1617. case 'onMouseDownCapture':
  1618. case 'onMouseMove':
  1619. case 'onMouseMoveCapture':
  1620. case 'onMouseUp':
  1621. case 'onMouseUpCapture':
  1622. case 'onMouseEnter':
  1623. return !!(props.disabled && isInteractive(type));
  1624. default:
  1625. return false;
  1626. }
  1627. }
  1628. /**
  1629. * @param {object} inst The instance, which is the source of events.
  1630. * @param {string} registrationName Name of listener (e.g. `onClick`).
  1631. * @return {?function} The stored callback.
  1632. */
  1633. function getListener(inst, registrationName) {
  1634. // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
  1635. // live here; needs to be moved to a better place soon
  1636. var stateNode = inst.stateNode;
  1637. if (!stateNode) {
  1638. // Work in progress (ex: onload events in incremental mode).
  1639. return null;
  1640. }
  1641. var props = getFiberCurrentPropsFromNode(stateNode);
  1642. if (!props) {
  1643. // Work in progress.
  1644. return null;
  1645. }
  1646. var listener = props[registrationName];
  1647. if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
  1648. return null;
  1649. }
  1650. if (!(!listener || typeof listener === 'function')) {
  1651. {
  1652. throw Error( "Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type." );
  1653. }
  1654. }
  1655. return listener;
  1656. }
  1657. function listenerAtPhase(inst, event, propagationPhase) {
  1658. var registrationName = event._reactName;
  1659. if (propagationPhase === 'captured') {
  1660. registrationName += 'Capture';
  1661. }
  1662. return getListener(inst, registrationName);
  1663. }
  1664. function accumulateDispatches(inst, ignoredDirection, event) {
  1665. if (inst && event && event._reactName) {
  1666. var registrationName = event._reactName;
  1667. var listener = getListener(inst, registrationName);
  1668. if (listener) {
  1669. if (event._dispatchListeners == null) {
  1670. event._dispatchListeners = [];
  1671. }
  1672. if (event._dispatchInstances == null) {
  1673. event._dispatchInstances = [];
  1674. }
  1675. event._dispatchListeners.push(listener);
  1676. event._dispatchInstances.push(inst);
  1677. }
  1678. }
  1679. }
  1680. function accumulateDirectionalDispatches(inst, phase, event) {
  1681. {
  1682. if (!inst) {
  1683. error('Dispatching inst must not be null');
  1684. }
  1685. }
  1686. var listener = listenerAtPhase(inst, event, phase);
  1687. if (listener) {
  1688. if (event._dispatchListeners == null) {
  1689. event._dispatchListeners = [];
  1690. }
  1691. if (event._dispatchInstances == null) {
  1692. event._dispatchInstances = [];
  1693. }
  1694. event._dispatchListeners.push(listener);
  1695. event._dispatchInstances.push(inst);
  1696. }
  1697. }
  1698. function accumulateDirectDispatchesSingle(event) {
  1699. if (event && event._reactName) {
  1700. accumulateDispatches(event._targetInst, null, event);
  1701. }
  1702. }
  1703. function accumulateTwoPhaseDispatchesSingle(event) {
  1704. if (event && event._reactName) {
  1705. traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
  1706. }
  1707. } // End of inline
  1708. var Simulate = {};
  1709. var directDispatchEventTypes = new Set(['mouseEnter', 'mouseLeave', 'pointerEnter', 'pointerLeave']);
  1710. /**
  1711. * Exports:
  1712. *
  1713. * - `Simulate.click(Element)`
  1714. * - `Simulate.mouseMove(Element)`
  1715. * - `Simulate.change(Element)`
  1716. * - ... (All keys from event plugin `eventTypes` objects)
  1717. */
  1718. function makeSimulator(eventType) {
  1719. return function (domNode, eventData) {
  1720. if (!!React.isValidElement(domNode)) {
  1721. {
  1722. 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." );
  1723. }
  1724. }
  1725. if (!!isCompositeComponent(domNode)) {
  1726. {
  1727. 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." );
  1728. }
  1729. }
  1730. var reactName = 'on' + eventType[0].toUpperCase() + eventType.slice(1);
  1731. var fakeNativeEvent = new Event();
  1732. fakeNativeEvent.target = domNode;
  1733. fakeNativeEvent.type = eventType.toLowerCase();
  1734. var targetInst = getInstanceFromNode(domNode);
  1735. var event = new SyntheticEvent(reactName, fakeNativeEvent.type, targetInst, fakeNativeEvent, domNode); // Since we aren't using pooling, always persist the event. This will make
  1736. // sure it's marked and won't warn when setting additional properties.
  1737. event.persist();
  1738. _assign(event, eventData);
  1739. if (directDispatchEventTypes.has(eventType)) {
  1740. accumulateDirectDispatchesSingle(event);
  1741. } else {
  1742. accumulateTwoPhaseDispatchesSingle(event);
  1743. }
  1744. ReactDOM.unstable_batchedUpdates(function () {
  1745. // Normally extractEvent enqueues a state restore, but we'll just always
  1746. // do that since we're by-passing it here.
  1747. enqueueStateRestore(domNode);
  1748. executeDispatchesAndRelease(event);
  1749. rethrowCaughtError();
  1750. });
  1751. restoreStateIfNeeded();
  1752. };
  1753. } // A one-time snapshot with no plans to update. We'll probably want to deprecate Simulate API.
  1754. var simulatedEventTypes = ['blur', 'cancel', 'click', 'close', 'contextMenu', 'copy', 'cut', 'auxClick', 'doubleClick', 'dragEnd', 'dragStart', 'drop', 'focus', 'input', 'invalid', 'keyDown', 'keyPress', 'keyUp', 'mouseDown', 'mouseUp', 'paste', 'pause', 'play', 'pointerCancel', 'pointerDown', 'pointerUp', 'rateChange', 'reset', 'seeked', 'submit', 'touchCancel', 'touchEnd', 'touchStart', 'volumeChange', 'drag', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'mouseMove', 'mouseOut', 'mouseOver', 'pointerMove', 'pointerOut', 'pointerOver', 'scroll', 'toggle', 'touchMove', 'wheel', 'abort', 'animationEnd', 'animationIteration', 'animationStart', 'canPlay', 'canPlayThrough', 'durationChange', 'emptied', 'encrypted', 'ended', 'error', 'gotPointerCapture', 'load', 'loadedData', 'loadedMetadata', 'loadStart', 'lostPointerCapture', 'playing', 'progress', 'seeking', 'stalled', 'suspend', 'timeUpdate', 'transitionEnd', 'waiting', 'mouseEnter', 'mouseLeave', 'pointerEnter', 'pointerLeave', 'change', 'select', 'beforeInput', 'compositionEnd', 'compositionStart', 'compositionUpdate'];
  1755. function buildSimulators() {
  1756. simulatedEventTypes.forEach(function (eventType) {
  1757. Simulate[eventType] = makeSimulator(eventType);
  1758. });
  1759. }
  1760. buildSimulators();
  1761. exports.Simulate = Simulate;
  1762. exports.act = act;
  1763. exports.findAllInRenderedTree = findAllInRenderedTree;
  1764. exports.findRenderedComponentWithType = findRenderedComponentWithType;
  1765. exports.findRenderedDOMComponentWithClass = findRenderedDOMComponentWithClass;
  1766. exports.findRenderedDOMComponentWithTag = findRenderedDOMComponentWithTag;
  1767. exports.isCompositeComponent = isCompositeComponent;
  1768. exports.isCompositeComponentWithType = isCompositeComponentWithType;
  1769. exports.isDOMComponent = isDOMComponent;
  1770. exports.isDOMComponentElement = isDOMComponentElement;
  1771. exports.isElement = isElement;
  1772. exports.isElementOfType = isElementOfType;
  1773. exports.mockComponent = mockComponent;
  1774. exports.nativeTouchData = nativeTouchData;
  1775. exports.renderIntoDocument = renderIntoDocument;
  1776. exports.scryRenderedComponentsWithType = scryRenderedComponentsWithType;
  1777. exports.scryRenderedDOMComponentsWithClass = scryRenderedDOMComponentsWithClass;
  1778. exports.scryRenderedDOMComponentsWithTag = scryRenderedDOMComponentsWithTag;
  1779. exports.traverseTwoPhase = traverseTwoPhase;
  1780. exports.unstable_concurrentAct = unstable_concurrentAct;
  1781. })));