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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759
  1. /**
  2. * @license React
  3. * react-dom-test-utils.development.js
  4. *
  5. * Copyright (c) Facebook, Inc. and its affiliates.
  6. *
  7. * This source code is licensed under the MIT license found in the
  8. * LICENSE file in the root directory of this source tree.
  9. */
  10. (function (global, factory) {
  11. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('react-dom')) :
  12. typeof define === 'function' && define.amd ? define(['exports', 'react', 'react-dom'], factory) :
  13. (global = global || self, factory(global.ReactTestUtils = {}, global.React, global.ReactDOM));
  14. }(this, (function (exports, React, ReactDOM) { 'use strict';
  15. var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  16. // by calls to these methods by a Babel plugin.
  17. //
  18. // In PROD (or in packages without access to React internals),
  19. // they are left as they are instead.
  20. function warn(format) {
  21. {
  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. }
  30. function error(format) {
  31. {
  32. {
  33. for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  34. args[_key2 - 1] = arguments[_key2];
  35. }
  36. printWarning('error', format, args);
  37. }
  38. }
  39. }
  40. function printWarning(level, format, args) {
  41. // When changing this logic, you might want to also
  42. // update consoleWithStackDev.www.js as well.
  43. {
  44. var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
  45. var stack = ReactDebugCurrentFrame.getStackAddendum();
  46. if (stack !== '') {
  47. format += '%s';
  48. args = args.concat([stack]);
  49. } // eslint-disable-next-line react-internal/safe-string-coercion
  50. var argsWithFormat = args.map(function (item) {
  51. return String(item);
  52. }); // Careful: RN currently depends on this prefix
  53. argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
  54. // breaks IE9: https://github.com/facebook/react/issues/13610
  55. // eslint-disable-next-line react-internal/no-production-logging
  56. Function.prototype.apply.call(console[level], console, argsWithFormat);
  57. }
  58. }
  59. /**
  60. * `ReactInstanceMap` maintains a mapping from a public facing stateful
  61. * instance (key) and the internal representation (value). This allows public
  62. * methods to accept the user facing instance as an argument and map them back
  63. * to internal methods.
  64. *
  65. * Note that this module is currently shared and assumed to be stateless.
  66. * If this becomes an actual Map, that will break.
  67. */
  68. function get(key) {
  69. return key._reactInternals;
  70. }
  71. var FunctionComponent = 0;
  72. var ClassComponent = 1;
  73. var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
  74. var HostComponent = 5;
  75. var HostText = 6;
  76. // Don't change these two values. They're used by React Dev Tools.
  77. var NoFlags =
  78. /* */
  79. 0;
  80. var Placement =
  81. /* */
  82. 2;
  83. var Hydrating =
  84. /* */
  85. 4096;
  86. var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
  87. function getNearestMountedFiber(fiber) {
  88. var node = fiber;
  89. var nearestMounted = fiber;
  90. if (!fiber.alternate) {
  91. // If there is no alternate, this might be a new tree that isn't inserted
  92. // yet. If it is, then it will have a pending insertion effect on it.
  93. var nextNode = node;
  94. do {
  95. node = nextNode;
  96. if ((node.flags & (Placement | Hydrating)) !== NoFlags) {
  97. // This is an insertion or in-progress hydration. The nearest possible
  98. // mounted fiber is the parent but we need to continue to figure out
  99. // if that one is still mounted.
  100. nearestMounted = node.return;
  101. }
  102. nextNode = node.return;
  103. } while (nextNode);
  104. } else {
  105. while (node.return) {
  106. node = node.return;
  107. }
  108. }
  109. if (node.tag === HostRoot) {
  110. // TODO: Check if this was a nested HostRoot when used with
  111. // renderContainerIntoSubtree.
  112. return nearestMounted;
  113. } // If we didn't hit the root, that means that we're in an disconnected tree
  114. // that has been unmounted.
  115. return null;
  116. }
  117. function assertIsMounted(fiber) {
  118. if (getNearestMountedFiber(fiber) !== fiber) {
  119. throw new Error('Unable to find node on an unmounted component.');
  120. }
  121. }
  122. function findCurrentFiberUsingSlowPath(fiber) {
  123. var alternate = fiber.alternate;
  124. if (!alternate) {
  125. // If there is no alternate, then we only need to check if it is mounted.
  126. var nearestMounted = getNearestMountedFiber(fiber);
  127. if (nearestMounted === null) {
  128. throw new Error('Unable to find node on an unmounted component.');
  129. }
  130. if (nearestMounted !== fiber) {
  131. return null;
  132. }
  133. return fiber;
  134. } // If we have two possible branches, we'll walk backwards up to the root
  135. // to see what path the root points to. On the way we may hit one of the
  136. // special cases and we'll deal with them.
  137. var a = fiber;
  138. var b = alternate;
  139. while (true) {
  140. var parentA = a.return;
  141. if (parentA === null) {
  142. // We're at the root.
  143. break;
  144. }
  145. var parentB = parentA.alternate;
  146. if (parentB === null) {
  147. // There is no alternate. This is an unusual case. Currently, it only
  148. // happens when a Suspense component is hidden. An extra fragment fiber
  149. // is inserted in between the Suspense fiber and its children. Skip
  150. // over this extra fragment fiber and proceed to the next parent.
  151. var nextParent = parentA.return;
  152. if (nextParent !== null) {
  153. a = b = nextParent;
  154. continue;
  155. } // If there's no parent, we're at the root.
  156. break;
  157. } // If both copies of the parent fiber point to the same child, we can
  158. // assume that the child is current. This happens when we bailout on low
  159. // priority: the bailed out fiber's child reuses the current child.
  160. if (parentA.child === parentB.child) {
  161. var child = parentA.child;
  162. while (child) {
  163. if (child === a) {
  164. // We've determined that A is the current branch.
  165. assertIsMounted(parentA);
  166. return fiber;
  167. }
  168. if (child === b) {
  169. // We've determined that B is the current branch.
  170. assertIsMounted(parentA);
  171. return alternate;
  172. }
  173. child = child.sibling;
  174. } // We should never have an alternate for any mounting node. So the only
  175. // way this could possibly happen is if this was unmounted, if at all.
  176. throw new Error('Unable to find node on an unmounted component.');
  177. }
  178. if (a.return !== b.return) {
  179. // The return pointer of A and the return pointer of B point to different
  180. // fibers. We assume that return pointers never criss-cross, so A must
  181. // belong to the child set of A.return, and B must belong to the child
  182. // set of B.return.
  183. a = parentA;
  184. b = parentB;
  185. } else {
  186. // The return pointers point to the same fiber. We'll have to use the
  187. // default, slow path: scan the child sets of each parent alternate to see
  188. // which child belongs to which set.
  189. //
  190. // Search parent A's child set
  191. var didFindChild = false;
  192. var _child = parentA.child;
  193. while (_child) {
  194. if (_child === a) {
  195. didFindChild = true;
  196. a = parentA;
  197. b = parentB;
  198. break;
  199. }
  200. if (_child === b) {
  201. didFindChild = true;
  202. b = parentA;
  203. a = parentB;
  204. break;
  205. }
  206. _child = _child.sibling;
  207. }
  208. if (!didFindChild) {
  209. // Search parent B's child set
  210. _child = parentB.child;
  211. while (_child) {
  212. if (_child === a) {
  213. didFindChild = true;
  214. a = parentB;
  215. b = parentA;
  216. break;
  217. }
  218. if (_child === b) {
  219. didFindChild = true;
  220. b = parentB;
  221. a = parentA;
  222. break;
  223. }
  224. _child = _child.sibling;
  225. }
  226. if (!didFindChild) {
  227. throw new Error('Child was not found in either parent set. This indicates a bug ' + 'in React related to the return pointer. Please file an issue.');
  228. }
  229. }
  230. }
  231. if (a.alternate !== b) {
  232. throw new Error("Return fibers should always be each others' alternates. " + 'This error is likely caused by a bug in React. Please file an issue.');
  233. }
  234. } // If the root is not a host container, we're in a disconnected tree. I.e.
  235. // unmounted.
  236. if (a.tag !== HostRoot) {
  237. throw new Error('Unable to find node on an unmounted component.');
  238. }
  239. if (a.stateNode.current === a) {
  240. // We've determined that A is the current branch.
  241. return fiber;
  242. } // Otherwise B has to be current branch.
  243. return alternate;
  244. }
  245. var assign = Object.assign;
  246. /**
  247. * `charCode` represents the actual "character code" and is safe to use with
  248. * `String.fromCharCode`. As such, only keys that correspond to printable
  249. * characters produce a valid `charCode`, the only exception to this is Enter.
  250. * The Tab-key is considered non-printable and does not have a `charCode`,
  251. * presumably because it does not produce a tab-character in browsers.
  252. *
  253. * @param {object} nativeEvent Native browser event.
  254. * @return {number} Normalized `charCode` property.
  255. */
  256. function getEventCharCode(nativeEvent) {
  257. var charCode;
  258. var keyCode = nativeEvent.keyCode;
  259. if ('charCode' in nativeEvent) {
  260. charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`.
  261. if (charCode === 0 && keyCode === 13) {
  262. charCode = 13;
  263. }
  264. } else {
  265. // IE8 does not implement `charCode`, but `keyCode` has the correct value.
  266. charCode = keyCode;
  267. } // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
  268. // report Enter as charCode 10 when ctrl is pressed.
  269. if (charCode === 10) {
  270. charCode = 13;
  271. } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
  272. // Must not discard the (non-)printable Enter-key.
  273. if (charCode >= 32 || charCode === 13) {
  274. return charCode;
  275. }
  276. return 0;
  277. }
  278. function functionThatReturnsTrue() {
  279. return true;
  280. }
  281. function functionThatReturnsFalse() {
  282. return false;
  283. } // This is intentionally a factory so that we have different returned constructors.
  284. // If we had a single constructor, it would be megamorphic and engines would deopt.
  285. function createSyntheticEvent(Interface) {
  286. /**
  287. * Synthetic events are dispatched by event plugins, typically in response to a
  288. * top-level event delegation handler.
  289. *
  290. * These systems should generally use pooling to reduce the frequency of garbage
  291. * collection. The system should check `isPersistent` to determine whether the
  292. * event should be released into the pool after being dispatched. Users that
  293. * need a persisted event should invoke `persist`.
  294. *
  295. * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
  296. * normalizing browser quirks. Subclasses do not necessarily have to implement a
  297. * DOM interface; custom application-specific events can also subclass this.
  298. */
  299. function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) {
  300. this._reactName = reactName;
  301. this._targetInst = targetInst;
  302. this.type = reactEventType;
  303. this.nativeEvent = nativeEvent;
  304. this.target = nativeEventTarget;
  305. this.currentTarget = null;
  306. for (var _propName in Interface) {
  307. if (!Interface.hasOwnProperty(_propName)) {
  308. continue;
  309. }
  310. var normalize = Interface[_propName];
  311. if (normalize) {
  312. this[_propName] = normalize(nativeEvent);
  313. } else {
  314. this[_propName] = nativeEvent[_propName];
  315. }
  316. }
  317. var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
  318. if (defaultPrevented) {
  319. this.isDefaultPrevented = functionThatReturnsTrue;
  320. } else {
  321. this.isDefaultPrevented = functionThatReturnsFalse;
  322. }
  323. this.isPropagationStopped = functionThatReturnsFalse;
  324. return this;
  325. }
  326. assign(SyntheticBaseEvent.prototype, {
  327. preventDefault: function () {
  328. this.defaultPrevented = true;
  329. var event = this.nativeEvent;
  330. if (!event) {
  331. return;
  332. }
  333. if (event.preventDefault) {
  334. event.preventDefault(); // $FlowFixMe - flow is not aware of `unknown` in IE
  335. } else if (typeof event.returnValue !== 'unknown') {
  336. event.returnValue = false;
  337. }
  338. this.isDefaultPrevented = functionThatReturnsTrue;
  339. },
  340. stopPropagation: function () {
  341. var event = this.nativeEvent;
  342. if (!event) {
  343. return;
  344. }
  345. if (event.stopPropagation) {
  346. event.stopPropagation(); // $FlowFixMe - flow is not aware of `unknown` in IE
  347. } else if (typeof event.cancelBubble !== 'unknown') {
  348. // The ChangeEventPlugin registers a "propertychange" event for
  349. // IE. This event does not support bubbling or cancelling, and
  350. // any references to cancelBubble throw "Member not found". A
  351. // typeof check of "unknown" circumvents this issue (and is also
  352. // IE specific).
  353. event.cancelBubble = true;
  354. }
  355. this.isPropagationStopped = functionThatReturnsTrue;
  356. },
  357. /**
  358. * We release all dispatched `SyntheticEvent`s after each event loop, adding
  359. * them back into the pool. This allows a way to hold onto a reference that
  360. * won't be added back into the pool.
  361. */
  362. persist: function () {// Modern event system doesn't use pooling.
  363. },
  364. /**
  365. * Checks if this event should be released back into the pool.
  366. *
  367. * @return {boolean} True if this should not be released, false otherwise.
  368. */
  369. isPersistent: functionThatReturnsTrue
  370. });
  371. return SyntheticBaseEvent;
  372. }
  373. /**
  374. * @interface Event
  375. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  376. */
  377. var EventInterface = {
  378. eventPhase: 0,
  379. bubbles: 0,
  380. cancelable: 0,
  381. timeStamp: function (event) {
  382. return event.timeStamp || Date.now();
  383. },
  384. defaultPrevented: 0,
  385. isTrusted: 0
  386. };
  387. var SyntheticEvent = createSyntheticEvent(EventInterface);
  388. var UIEventInterface = assign({}, EventInterface, {
  389. view: 0,
  390. detail: 0
  391. });
  392. var SyntheticUIEvent = createSyntheticEvent(UIEventInterface);
  393. var lastMovementX;
  394. var lastMovementY;
  395. var lastMouseEvent;
  396. function updateMouseMovementPolyfillState(event) {
  397. if (event !== lastMouseEvent) {
  398. if (lastMouseEvent && event.type === 'mousemove') {
  399. lastMovementX = event.screenX - lastMouseEvent.screenX;
  400. lastMovementY = event.screenY - lastMouseEvent.screenY;
  401. } else {
  402. lastMovementX = 0;
  403. lastMovementY = 0;
  404. }
  405. lastMouseEvent = event;
  406. }
  407. }
  408. /**
  409. * @interface MouseEvent
  410. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  411. */
  412. var MouseEventInterface = assign({}, UIEventInterface, {
  413. screenX: 0,
  414. screenY: 0,
  415. clientX: 0,
  416. clientY: 0,
  417. pageX: 0,
  418. pageY: 0,
  419. ctrlKey: 0,
  420. shiftKey: 0,
  421. altKey: 0,
  422. metaKey: 0,
  423. getModifierState: getEventModifierState,
  424. button: 0,
  425. buttons: 0,
  426. relatedTarget: function (event) {
  427. if (event.relatedTarget === undefined) return event.fromElement === event.srcElement ? event.toElement : event.fromElement;
  428. return event.relatedTarget;
  429. },
  430. movementX: function (event) {
  431. if ('movementX' in event) {
  432. return event.movementX;
  433. }
  434. updateMouseMovementPolyfillState(event);
  435. return lastMovementX;
  436. },
  437. movementY: function (event) {
  438. if ('movementY' in event) {
  439. return event.movementY;
  440. } // Don't need to call updateMouseMovementPolyfillState() here
  441. // because it's guaranteed to have already run when movementX
  442. // was copied.
  443. return lastMovementY;
  444. }
  445. });
  446. var SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface);
  447. /**
  448. * @interface DragEvent
  449. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  450. */
  451. var DragEventInterface = assign({}, MouseEventInterface, {
  452. dataTransfer: 0
  453. });
  454. var SyntheticDragEvent = createSyntheticEvent(DragEventInterface);
  455. /**
  456. * @interface FocusEvent
  457. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  458. */
  459. var FocusEventInterface = assign({}, UIEventInterface, {
  460. relatedTarget: 0
  461. });
  462. var SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface);
  463. /**
  464. * @interface Event
  465. * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
  466. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
  467. */
  468. var AnimationEventInterface = assign({}, EventInterface, {
  469. animationName: 0,
  470. elapsedTime: 0,
  471. pseudoElement: 0
  472. });
  473. var SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface);
  474. /**
  475. * @interface Event
  476. * @see http://www.w3.org/TR/clipboard-apis/
  477. */
  478. var ClipboardEventInterface = assign({}, EventInterface, {
  479. clipboardData: function (event) {
  480. return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
  481. }
  482. });
  483. var SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface);
  484. /**
  485. * @interface Event
  486. * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
  487. */
  488. var CompositionEventInterface = assign({}, EventInterface, {
  489. data: 0
  490. });
  491. var SyntheticCompositionEvent = createSyntheticEvent(CompositionEventInterface);
  492. /**
  493. * Normalization of deprecated HTML5 `key` values
  494. * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
  495. */
  496. var normalizeKey = {
  497. Esc: 'Escape',
  498. Spacebar: ' ',
  499. Left: 'ArrowLeft',
  500. Up: 'ArrowUp',
  501. Right: 'ArrowRight',
  502. Down: 'ArrowDown',
  503. Del: 'Delete',
  504. Win: 'OS',
  505. Menu: 'ContextMenu',
  506. Apps: 'ContextMenu',
  507. Scroll: 'ScrollLock',
  508. MozPrintableKey: 'Unidentified'
  509. };
  510. /**
  511. * Translation from legacy `keyCode` to HTML5 `key`
  512. * Only special keys supported, all others depend on keyboard layout or browser
  513. * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
  514. */
  515. var translateToKey = {
  516. '8': 'Backspace',
  517. '9': 'Tab',
  518. '12': 'Clear',
  519. '13': 'Enter',
  520. '16': 'Shift',
  521. '17': 'Control',
  522. '18': 'Alt',
  523. '19': 'Pause',
  524. '20': 'CapsLock',
  525. '27': 'Escape',
  526. '32': ' ',
  527. '33': 'PageUp',
  528. '34': 'PageDown',
  529. '35': 'End',
  530. '36': 'Home',
  531. '37': 'ArrowLeft',
  532. '38': 'ArrowUp',
  533. '39': 'ArrowRight',
  534. '40': 'ArrowDown',
  535. '45': 'Insert',
  536. '46': 'Delete',
  537. '112': 'F1',
  538. '113': 'F2',
  539. '114': 'F3',
  540. '115': 'F4',
  541. '116': 'F5',
  542. '117': 'F6',
  543. '118': 'F7',
  544. '119': 'F8',
  545. '120': 'F9',
  546. '121': 'F10',
  547. '122': 'F11',
  548. '123': 'F12',
  549. '144': 'NumLock',
  550. '145': 'ScrollLock',
  551. '224': 'Meta'
  552. };
  553. /**
  554. * @param {object} nativeEvent Native browser event.
  555. * @return {string} Normalized `key` property.
  556. */
  557. function getEventKey(nativeEvent) {
  558. if (nativeEvent.key) {
  559. // Normalize inconsistent values reported by browsers due to
  560. // implementations of a working draft specification.
  561. // FireFox implements `key` but returns `MozPrintableKey` for all
  562. // printable characters (normalized to `Unidentified`), ignore it.
  563. var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
  564. if (key !== 'Unidentified') {
  565. return key;
  566. }
  567. } // Browser does not implement `key`, polyfill as much of it as we can.
  568. if (nativeEvent.type === 'keypress') {
  569. var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can
  570. // thus be captured by `keypress`, no other non-printable key should.
  571. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
  572. }
  573. if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
  574. // While user keyboard layout determines the actual meaning of each
  575. // `keyCode` value, almost all function keys have a universal value.
  576. return translateToKey[nativeEvent.keyCode] || 'Unidentified';
  577. }
  578. return '';
  579. }
  580. /**
  581. * Translation from modifier key to the associated property in the event.
  582. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
  583. */
  584. var modifierKeyToProp = {
  585. Alt: 'altKey',
  586. Control: 'ctrlKey',
  587. Meta: 'metaKey',
  588. Shift: 'shiftKey'
  589. }; // Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
  590. // getModifierState. If getModifierState is not supported, we map it to a set of
  591. // modifier keys exposed by the event. In this case, Lock-keys are not supported.
  592. function modifierStateGetter(keyArg) {
  593. var syntheticEvent = this;
  594. var nativeEvent = syntheticEvent.nativeEvent;
  595. if (nativeEvent.getModifierState) {
  596. return nativeEvent.getModifierState(keyArg);
  597. }
  598. var keyProp = modifierKeyToProp[keyArg];
  599. return keyProp ? !!nativeEvent[keyProp] : false;
  600. }
  601. function getEventModifierState(nativeEvent) {
  602. return modifierStateGetter;
  603. }
  604. /**
  605. * @interface KeyboardEvent
  606. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  607. */
  608. var KeyboardEventInterface = assign({}, UIEventInterface, {
  609. key: getEventKey,
  610. code: 0,
  611. location: 0,
  612. ctrlKey: 0,
  613. shiftKey: 0,
  614. altKey: 0,
  615. metaKey: 0,
  616. repeat: 0,
  617. locale: 0,
  618. getModifierState: getEventModifierState,
  619. // Legacy Interface
  620. charCode: function (event) {
  621. // `charCode` is the result of a KeyPress event and represents the value of
  622. // the actual printable character.
  623. // KeyPress is deprecated, but its replacement is not yet final and not
  624. // implemented in any major browser. Only KeyPress has charCode.
  625. if (event.type === 'keypress') {
  626. return getEventCharCode(event);
  627. }
  628. return 0;
  629. },
  630. keyCode: function (event) {
  631. // `keyCode` is the result of a KeyDown/Up event and represents the value of
  632. // physical keyboard key.
  633. // The actual meaning of the value depends on the users' keyboard layout
  634. // which cannot be detected. Assuming that it is a US keyboard layout
  635. // provides a surprisingly accurate mapping for US and European users.
  636. // Due to this, it is left to the user to implement at this time.
  637. if (event.type === 'keydown' || event.type === 'keyup') {
  638. return event.keyCode;
  639. }
  640. return 0;
  641. },
  642. which: function (event) {
  643. // `which` is an alias for either `keyCode` or `charCode` depending on the
  644. // type of the event.
  645. if (event.type === 'keypress') {
  646. return getEventCharCode(event);
  647. }
  648. if (event.type === 'keydown' || event.type === 'keyup') {
  649. return event.keyCode;
  650. }
  651. return 0;
  652. }
  653. });
  654. var SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface);
  655. /**
  656. * @interface PointerEvent
  657. * @see http://www.w3.org/TR/pointerevents/
  658. */
  659. var PointerEventInterface = assign({}, MouseEventInterface, {
  660. pointerId: 0,
  661. width: 0,
  662. height: 0,
  663. pressure: 0,
  664. tangentialPressure: 0,
  665. tiltX: 0,
  666. tiltY: 0,
  667. twist: 0,
  668. pointerType: 0,
  669. isPrimary: 0
  670. });
  671. var SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface);
  672. /**
  673. * @interface TouchEvent
  674. * @see http://www.w3.org/TR/touch-events/
  675. */
  676. var TouchEventInterface = assign({}, UIEventInterface, {
  677. touches: 0,
  678. targetTouches: 0,
  679. changedTouches: 0,
  680. altKey: 0,
  681. metaKey: 0,
  682. ctrlKey: 0,
  683. shiftKey: 0,
  684. getModifierState: getEventModifierState
  685. });
  686. var SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface);
  687. /**
  688. * @interface Event
  689. * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
  690. * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
  691. */
  692. var TransitionEventInterface = assign({}, EventInterface, {
  693. propertyName: 0,
  694. elapsedTime: 0,
  695. pseudoElement: 0
  696. });
  697. var SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface);
  698. /**
  699. * @interface WheelEvent
  700. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  701. */
  702. var WheelEventInterface = assign({}, MouseEventInterface, {
  703. deltaX: function (event) {
  704. return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
  705. 'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
  706. },
  707. deltaY: function (event) {
  708. return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
  709. 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
  710. 'wheelDelta' in event ? -event.wheelDelta : 0;
  711. },
  712. deltaZ: 0,
  713. // Browsers without "deltaMode" is reporting in raw wheel delta where one
  714. // notch on the scroll is always +/- 120, roughly equivalent to pixels.
  715. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
  716. // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
  717. deltaMode: 0
  718. });
  719. var SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface);
  720. /**
  721. * HTML nodeType values that represent the type of the node
  722. */
  723. var ELEMENT_NODE = 1;
  724. function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) {
  725. var funcArgs = Array.prototype.slice.call(arguments, 3);
  726. try {
  727. func.apply(context, funcArgs);
  728. } catch (error) {
  729. this.onError(error);
  730. }
  731. }
  732. var invokeGuardedCallbackImpl = invokeGuardedCallbackProd;
  733. {
  734. // In DEV mode, we swap out invokeGuardedCallback for a special version
  735. // that plays more nicely with the browser's DevTools. The idea is to preserve
  736. // "Pause on exceptions" behavior. Because React wraps all user-provided
  737. // functions in invokeGuardedCallback, and the production version of
  738. // invokeGuardedCallback uses a try-catch, all user exceptions are treated
  739. // like caught exceptions, and the DevTools won't pause unless the developer
  740. // takes the extra step of enabling pause on caught exceptions. This is
  741. // unintuitive, though, because even though React has caught the error, from
  742. // the developer's perspective, the error is uncaught.
  743. //
  744. // To preserve the expected "Pause on exceptions" behavior, we don't use a
  745. // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
  746. // DOM node, and call the user-provided callback from inside an event handler
  747. // for that fake event. If the callback throws, the error is "captured" using
  748. // a global event handler. But because the error happens in a different
  749. // event loop context, it does not interrupt the normal program flow.
  750. // Effectively, this gives us try-catch behavior without actually using
  751. // try-catch. Neat!
  752. // Check that the browser supports the APIs we need to implement our special
  753. // DEV version of invokeGuardedCallback
  754. if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
  755. var fakeNode = document.createElement('react');
  756. invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) {
  757. // If document doesn't exist we know for sure we will crash in this method
  758. // when we call document.createEvent(). However this can cause confusing
  759. // errors: https://github.com/facebook/create-react-app/issues/3482
  760. // So we preemptively throw with a better message instead.
  761. if (typeof document === 'undefined' || document === null) {
  762. throw new 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.');
  763. }
  764. var evt = document.createEvent('Event');
  765. var didCall = false; // Keeps track of whether the user-provided callback threw an error. We
  766. // set this to true at the beginning, then set it to false right after
  767. // calling the function. If the function errors, `didError` will never be
  768. // set to false. This strategy works even if the browser is flaky and
  769. // fails to call our global error handler, because it doesn't rely on
  770. // the error event at all.
  771. var didError = true; // Keeps track of the value of window.event so that we can reset it
  772. // during the callback to let user code access window.event in the
  773. // browsers that support it.
  774. var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event
  775. // dispatching: https://github.com/facebook/react/issues/13688
  776. var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event');
  777. function restoreAfterDispatch() {
  778. // We immediately remove the callback from event listeners so that
  779. // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
  780. // nested call would trigger the fake event handlers of any call higher
  781. // in the stack.
  782. fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the
  783. // window.event assignment in both IE <= 10 as they throw an error
  784. // "Member not found" in strict mode, and in Firefox which does not
  785. // support window.event.
  786. if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
  787. window.event = windowEvent;
  788. }
  789. } // Create an event handler for our fake event. We will synchronously
  790. // dispatch our fake event using `dispatchEvent`. Inside the handler, we
  791. // call the user-provided callback.
  792. var funcArgs = Array.prototype.slice.call(arguments, 3);
  793. function callCallback() {
  794. didCall = true;
  795. restoreAfterDispatch();
  796. func.apply(context, funcArgs);
  797. didError = false;
  798. } // Create a global error event handler. We use this to capture the value
  799. // that was thrown. It's possible that this error handler will fire more
  800. // than once; for example, if non-React code also calls `dispatchEvent`
  801. // and a handler for that event throws. We should be resilient to most of
  802. // those cases. Even if our error event handler fires more than once, the
  803. // last error event is always used. If the callback actually does error,
  804. // we know that the last error event is the correct one, because it's not
  805. // possible for anything else to have happened in between our callback
  806. // erroring and the code that follows the `dispatchEvent` call below. If
  807. // the callback doesn't error, but the error event was fired, we know to
  808. // ignore it because `didError` will be false, as described above.
  809. var error; // Use this to track whether the error event is ever called.
  810. var didSetError = false;
  811. var isCrossOriginError = false;
  812. function handleWindowError(event) {
  813. error = event.error;
  814. didSetError = true;
  815. if (error === null && event.colno === 0 && event.lineno === 0) {
  816. isCrossOriginError = true;
  817. }
  818. if (event.defaultPrevented) {
  819. // Some other error handler has prevented default.
  820. // Browsers silence the error report if this happens.
  821. // We'll remember this to later decide whether to log it or not.
  822. if (error != null && typeof error === 'object') {
  823. try {
  824. error._suppressLogging = true;
  825. } catch (inner) {// Ignore.
  826. }
  827. }
  828. }
  829. } // Create a fake event type.
  830. var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers
  831. window.addEventListener('error', handleWindowError);
  832. fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function
  833. // errors, it will trigger our global error handler.
  834. evt.initEvent(evtType, false, false);
  835. fakeNode.dispatchEvent(evt);
  836. if (windowEventDescriptor) {
  837. Object.defineProperty(window, 'event', windowEventDescriptor);
  838. }
  839. if (didCall && didError) {
  840. if (!didSetError) {
  841. // The callback errored, but the error event never fired.
  842. // eslint-disable-next-line react-internal/prod-error-codes
  843. 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.');
  844. } else if (isCrossOriginError) {
  845. // eslint-disable-next-line react-internal/prod-error-codes
  846. 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.');
  847. }
  848. this.onError(error);
  849. } // Remove our event listeners
  850. window.removeEventListener('error', handleWindowError);
  851. if (!didCall) {
  852. // Something went really wrong, and our event was not dispatched.
  853. // https://github.com/facebook/react/issues/16734
  854. // https://github.com/facebook/react/issues/16585
  855. // Fall back to the production implementation.
  856. restoreAfterDispatch();
  857. return invokeGuardedCallbackProd.apply(this, arguments);
  858. }
  859. };
  860. }
  861. }
  862. var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
  863. var hasError = false;
  864. var caughtError = null; // Used by event system to capture/rethrow the first error.
  865. var hasRethrowError = false;
  866. var rethrowError = null;
  867. var reporter = {
  868. onError: function (error) {
  869. hasError = true;
  870. caughtError = error;
  871. }
  872. };
  873. /**
  874. * Call a function while guarding against errors that happens within it.
  875. * Returns an error if it throws, otherwise null.
  876. *
  877. * In production, this is implemented using a try-catch. The reason we don't
  878. * use a try-catch directly is so that we can swap out a different
  879. * implementation in DEV mode.
  880. *
  881. * @param {String} name of the guard to use for logging or debugging
  882. * @param {Function} func The function to invoke
  883. * @param {*} context The context to use when calling the function
  884. * @param {...*} args Arguments for function
  885. */
  886. function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
  887. hasError = false;
  888. caughtError = null;
  889. invokeGuardedCallbackImpl$1.apply(reporter, arguments);
  890. }
  891. /**
  892. * Same as invokeGuardedCallback, but instead of returning an error, it stores
  893. * it in a global so it can be rethrown by `rethrowCaughtError` later.
  894. * TODO: See if caughtError and rethrowError can be unified.
  895. *
  896. * @param {String} name of the guard to use for logging or debugging
  897. * @param {Function} func The function to invoke
  898. * @param {*} context The context to use when calling the function
  899. * @param {...*} args Arguments for function
  900. */
  901. function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
  902. invokeGuardedCallback.apply(this, arguments);
  903. if (hasError) {
  904. var error = clearCaughtError();
  905. if (!hasRethrowError) {
  906. hasRethrowError = true;
  907. rethrowError = error;
  908. }
  909. }
  910. }
  911. /**
  912. * During execution of guarded functions we will capture the first error which
  913. * we will rethrow to be handled by the top level error handler.
  914. */
  915. function rethrowCaughtError() {
  916. if (hasRethrowError) {
  917. var error = rethrowError;
  918. hasRethrowError = false;
  919. rethrowError = null;
  920. throw error;
  921. }
  922. }
  923. function clearCaughtError() {
  924. if (hasError) {
  925. var error = caughtError;
  926. hasError = false;
  927. caughtError = null;
  928. return error;
  929. } else {
  930. throw new Error('clearCaughtError was called but no error was captured. This error ' + 'is likely caused by a bug in React. Please file an issue.');
  931. }
  932. }
  933. var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
  934. function isArray(a) {
  935. return isArrayImpl(a);
  936. }
  937. var SecretInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  938. var EventInternals = SecretInternals.Events;
  939. var getInstanceFromNode = EventInternals[0];
  940. var getNodeFromInstance = EventInternals[1];
  941. var getFiberCurrentPropsFromNode = EventInternals[2];
  942. var enqueueStateRestore = EventInternals[3];
  943. var restoreStateIfNeeded = EventInternals[4];
  944. var reactAct = React.unstable_act;
  945. function Event(suffix) {}
  946. var hasWarnedAboutDeprecatedMockComponent = false;
  947. /**
  948. * @class ReactTestUtils
  949. */
  950. function findAllInRenderedFiberTreeInternal(fiber, test) {
  951. if (!fiber) {
  952. return [];
  953. }
  954. var currentParent = findCurrentFiberUsingSlowPath(fiber);
  955. if (!currentParent) {
  956. return [];
  957. }
  958. var node = currentParent;
  959. var ret = [];
  960. while (true) {
  961. if (node.tag === HostComponent || node.tag === HostText || node.tag === ClassComponent || node.tag === FunctionComponent) {
  962. var publicInst = node.stateNode;
  963. if (test(publicInst)) {
  964. ret.push(publicInst);
  965. }
  966. }
  967. if (node.child) {
  968. node.child.return = node;
  969. node = node.child;
  970. continue;
  971. }
  972. if (node === currentParent) {
  973. return ret;
  974. }
  975. while (!node.sibling) {
  976. if (!node.return || node.return === currentParent) {
  977. return ret;
  978. }
  979. node = node.return;
  980. }
  981. node.sibling.return = node.return;
  982. node = node.sibling;
  983. }
  984. }
  985. function validateClassInstance(inst, methodName) {
  986. if (!inst) {
  987. // This is probably too relaxed but it's existing behavior.
  988. return;
  989. }
  990. if (get(inst)) {
  991. // This is a public instance indeed.
  992. return;
  993. }
  994. var received;
  995. var stringified = String(inst);
  996. if (isArray(inst)) {
  997. received = 'an array';
  998. } else if (inst && inst.nodeType === ELEMENT_NODE && inst.tagName) {
  999. received = 'a DOM node';
  1000. } else if (stringified === '[object Object]') {
  1001. received = 'object with keys {' + Object.keys(inst).join(', ') + '}';
  1002. } else {
  1003. received = stringified;
  1004. }
  1005. throw new Error(methodName + "(...): the first argument must be a React class instance. " + ("Instead received: " + received + "."));
  1006. }
  1007. /**
  1008. * Utilities for making it easy to test React components.
  1009. *
  1010. * See https://reactjs.org/docs/test-utils.html
  1011. *
  1012. * Todo: Support the entire DOM.scry query syntax. For now, these simple
  1013. * utilities will suffice for testing purposes.
  1014. * @lends ReactTestUtils
  1015. */
  1016. var didWarnAboutReactTestUtilsDeprecation = false;
  1017. function renderIntoDocument(element) {
  1018. {
  1019. if (!didWarnAboutReactTestUtilsDeprecation) {
  1020. didWarnAboutReactTestUtilsDeprecation = true;
  1021. error('ReactDOMTestUtils is deprecated and will be removed in a future ' + 'major release, because it exposes internal implementation details ' + 'that are highly likely to change between releases. Upgrade to a ' + 'modern testing library, such as @testing-library/react. See ' + 'https://react.dev/warnings/react-dom-test-utils for more info.');
  1022. }
  1023. }
  1024. var div = document.createElement('div'); // None of our tests actually require attaching the container to the
  1025. // DOM, and doing so creates a mess that we rely on test isolation to
  1026. // clean up, so we're going to stop honoring the name of this method
  1027. // (and probably rename it eventually) if no problems arise.
  1028. // document.documentElement.appendChild(div);
  1029. return ReactDOM.render(element, div);
  1030. }
  1031. function isElement(element) {
  1032. return React.isValidElement(element);
  1033. }
  1034. function isElementOfType(inst, convenienceConstructor) {
  1035. return React.isValidElement(inst) && inst.type === convenienceConstructor;
  1036. }
  1037. function isDOMComponent(inst) {
  1038. return !!(inst && inst.nodeType === ELEMENT_NODE && inst.tagName);
  1039. }
  1040. function isDOMComponentElement(inst) {
  1041. return !!(inst && React.isValidElement(inst) && !!inst.tagName);
  1042. }
  1043. function isCompositeComponent(inst) {
  1044. if (isDOMComponent(inst)) {
  1045. // Accessing inst.setState warns; just return false as that'll be what
  1046. // this returns when we have DOM nodes as refs directly
  1047. return false;
  1048. }
  1049. return inst != null && typeof inst.render === 'function' && typeof inst.setState === 'function';
  1050. }
  1051. function isCompositeComponentWithType(inst, type) {
  1052. if (!isCompositeComponent(inst)) {
  1053. return false;
  1054. }
  1055. var internalInstance = get(inst);
  1056. var constructor = internalInstance.type;
  1057. return constructor === type;
  1058. }
  1059. function findAllInRenderedTree(inst, test) {
  1060. validateClassInstance(inst, 'findAllInRenderedTree');
  1061. if (!inst) {
  1062. return [];
  1063. }
  1064. var internalInstance = get(inst);
  1065. return findAllInRenderedFiberTreeInternal(internalInstance, test);
  1066. }
  1067. /**
  1068. * Finds all instances of components in the rendered tree that are DOM
  1069. * components with the class name matching `className`.
  1070. * @return {array} an array of all the matches.
  1071. */
  1072. function scryRenderedDOMComponentsWithClass(root, classNames) {
  1073. validateClassInstance(root, 'scryRenderedDOMComponentsWithClass');
  1074. return findAllInRenderedTree(root, function (inst) {
  1075. if (isDOMComponent(inst)) {
  1076. var className = inst.className;
  1077. if (typeof className !== 'string') {
  1078. // SVG, probably.
  1079. className = inst.getAttribute('class') || '';
  1080. }
  1081. var classList = className.split(/\s+/);
  1082. if (!isArray(classNames)) {
  1083. if (classNames === undefined) {
  1084. throw new Error('TestUtils.scryRenderedDOMComponentsWithClass expects a ' + 'className as a second argument.');
  1085. }
  1086. classNames = classNames.split(/\s+/);
  1087. }
  1088. return classNames.every(function (name) {
  1089. return classList.indexOf(name) !== -1;
  1090. });
  1091. }
  1092. return false;
  1093. });
  1094. }
  1095. /**
  1096. * Like scryRenderedDOMComponentsWithClass but expects there to be one result,
  1097. * and returns that one result, or throws exception if there is any other
  1098. * number of matches besides one.
  1099. * @return {!ReactDOMComponent} The one match.
  1100. */
  1101. function findRenderedDOMComponentWithClass(root, className) {
  1102. validateClassInstance(root, 'findRenderedDOMComponentWithClass');
  1103. var all = scryRenderedDOMComponentsWithClass(root, className);
  1104. if (all.length !== 1) {
  1105. throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for class:' + className);
  1106. }
  1107. return all[0];
  1108. }
  1109. /**
  1110. * Finds all instances of components in the rendered tree that are DOM
  1111. * components with the tag name matching `tagName`.
  1112. * @return {array} an array of all the matches.
  1113. */
  1114. function scryRenderedDOMComponentsWithTag(root, tagName) {
  1115. validateClassInstance(root, 'scryRenderedDOMComponentsWithTag');
  1116. return findAllInRenderedTree(root, function (inst) {
  1117. return isDOMComponent(inst) && inst.tagName.toUpperCase() === tagName.toUpperCase();
  1118. });
  1119. }
  1120. /**
  1121. * Like scryRenderedDOMComponentsWithTag but expects there to be one result,
  1122. * and returns that one result, or throws exception if there is any other
  1123. * number of matches besides one.
  1124. * @return {!ReactDOMComponent} The one match.
  1125. */
  1126. function findRenderedDOMComponentWithTag(root, tagName) {
  1127. validateClassInstance(root, 'findRenderedDOMComponentWithTag');
  1128. var all = scryRenderedDOMComponentsWithTag(root, tagName);
  1129. if (all.length !== 1) {
  1130. throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for tag:' + tagName);
  1131. }
  1132. return all[0];
  1133. }
  1134. /**
  1135. * Finds all instances of components with type equal to `componentType`.
  1136. * @return {array} an array of all the matches.
  1137. */
  1138. function scryRenderedComponentsWithType(root, componentType) {
  1139. validateClassInstance(root, 'scryRenderedComponentsWithType');
  1140. return findAllInRenderedTree(root, function (inst) {
  1141. return isCompositeComponentWithType(inst, componentType);
  1142. });
  1143. }
  1144. /**
  1145. * Same as `scryRenderedComponentsWithType` but expects there to be one result
  1146. * and returns that one result, or throws exception if there is any other
  1147. * number of matches besides one.
  1148. * @return {!ReactComponent} The one match.
  1149. */
  1150. function findRenderedComponentWithType(root, componentType) {
  1151. validateClassInstance(root, 'findRenderedComponentWithType');
  1152. var all = scryRenderedComponentsWithType(root, componentType);
  1153. if (all.length !== 1) {
  1154. throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for componentType:' + componentType);
  1155. }
  1156. return all[0];
  1157. }
  1158. /**
  1159. * Pass a mocked component module to this method to augment it with
  1160. * useful methods that allow it to be used as a dummy React component.
  1161. * Instead of rendering as usual, the component will become a simple
  1162. * <div> containing any provided children.
  1163. *
  1164. * @param {object} module the mock function object exported from a
  1165. * module that defines the component to be mocked
  1166. * @param {?string} mockTagName optional dummy root tag name to return
  1167. * from render method (overrides
  1168. * module.mockTagName if provided)
  1169. * @return {object} the ReactTestUtils object (for chaining)
  1170. */
  1171. function mockComponent(module, mockTagName) {
  1172. {
  1173. if (!hasWarnedAboutDeprecatedMockComponent) {
  1174. hasWarnedAboutDeprecatedMockComponent = true;
  1175. 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.');
  1176. }
  1177. }
  1178. mockTagName = mockTagName || module.mockTagName || 'div';
  1179. module.prototype.render.mockImplementation(function () {
  1180. return React.createElement(mockTagName, null, this.props.children);
  1181. });
  1182. return this;
  1183. }
  1184. function nativeTouchData(x, y) {
  1185. return {
  1186. touches: [{
  1187. pageX: x,
  1188. pageY: y
  1189. }]
  1190. };
  1191. } // Start of inline: the below functions were inlined from
  1192. // EventPropagator.js, as they deviated from ReactDOM's newer
  1193. // implementations.
  1194. /**
  1195. * Dispatch the event to the listener.
  1196. * @param {SyntheticEvent} event SyntheticEvent to handle
  1197. * @param {function} listener Application-level callback
  1198. * @param {*} inst Internal component instance
  1199. */
  1200. function executeDispatch(event, listener, inst) {
  1201. var type = event.type || 'unknown-event';
  1202. event.currentTarget = getNodeFromInstance(inst);
  1203. invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
  1204. event.currentTarget = null;
  1205. }
  1206. /**
  1207. * Standard/simple iteration through an event's collected dispatches.
  1208. */
  1209. function executeDispatchesInOrder(event) {
  1210. var dispatchListeners = event._dispatchListeners;
  1211. var dispatchInstances = event._dispatchInstances;
  1212. if (isArray(dispatchListeners)) {
  1213. for (var i = 0; i < dispatchListeners.length; i++) {
  1214. if (event.isPropagationStopped()) {
  1215. break;
  1216. } // Listeners and Instances are two parallel arrays that are always in sync.
  1217. executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
  1218. }
  1219. } else if (dispatchListeners) {
  1220. executeDispatch(event, dispatchListeners, dispatchInstances);
  1221. }
  1222. event._dispatchListeners = null;
  1223. event._dispatchInstances = null;
  1224. }
  1225. /**
  1226. * Dispatches an event and releases it back into the pool, unless persistent.
  1227. *
  1228. * @param {?object} event Synthetic event to be dispatched.
  1229. * @private
  1230. */
  1231. var executeDispatchesAndRelease = function (event) {
  1232. if (event) {
  1233. executeDispatchesInOrder(event);
  1234. if (!event.isPersistent()) {
  1235. event.constructor.release(event);
  1236. }
  1237. }
  1238. };
  1239. function isInteractive(tag) {
  1240. return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
  1241. }
  1242. function getParent(inst) {
  1243. do {
  1244. inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.
  1245. // That is depending on if we want nested subtrees (layers) to bubble
  1246. // events to their parent. We could also go through parentNode on the
  1247. // host node but that wouldn't work for React Native and doesn't let us
  1248. // do the portal feature.
  1249. } while (inst && inst.tag !== HostComponent);
  1250. if (inst) {
  1251. return inst;
  1252. }
  1253. return null;
  1254. }
  1255. /**
  1256. * Simulates the traversal of a two-phase, capture/bubble event dispatch.
  1257. */
  1258. function traverseTwoPhase(inst, fn, arg) {
  1259. var path = [];
  1260. while (inst) {
  1261. path.push(inst);
  1262. inst = getParent(inst);
  1263. }
  1264. var i;
  1265. for (i = path.length; i-- > 0;) {
  1266. fn(path[i], 'captured', arg);
  1267. }
  1268. for (i = 0; i < path.length; i++) {
  1269. fn(path[i], 'bubbled', arg);
  1270. }
  1271. }
  1272. function shouldPreventMouseEvent(name, type, props) {
  1273. switch (name) {
  1274. case 'onClick':
  1275. case 'onClickCapture':
  1276. case 'onDoubleClick':
  1277. case 'onDoubleClickCapture':
  1278. case 'onMouseDown':
  1279. case 'onMouseDownCapture':
  1280. case 'onMouseMove':
  1281. case 'onMouseMoveCapture':
  1282. case 'onMouseUp':
  1283. case 'onMouseUpCapture':
  1284. case 'onMouseEnter':
  1285. return !!(props.disabled && isInteractive(type));
  1286. default:
  1287. return false;
  1288. }
  1289. }
  1290. /**
  1291. * @param {object} inst The instance, which is the source of events.
  1292. * @param {string} registrationName Name of listener (e.g. `onClick`).
  1293. * @return {?function} The stored callback.
  1294. */
  1295. function getListener(inst, registrationName) {
  1296. // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
  1297. // live here; needs to be moved to a better place soon
  1298. var stateNode = inst.stateNode;
  1299. if (!stateNode) {
  1300. // Work in progress (ex: onload events in incremental mode).
  1301. return null;
  1302. }
  1303. var props = getFiberCurrentPropsFromNode(stateNode);
  1304. if (!props) {
  1305. // Work in progress.
  1306. return null;
  1307. }
  1308. var listener = props[registrationName];
  1309. if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
  1310. return null;
  1311. }
  1312. if (listener && typeof listener !== 'function') {
  1313. throw new Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type.");
  1314. }
  1315. return listener;
  1316. }
  1317. function listenerAtPhase(inst, event, propagationPhase) {
  1318. var registrationName = event._reactName;
  1319. if (propagationPhase === 'captured') {
  1320. registrationName += 'Capture';
  1321. }
  1322. return getListener(inst, registrationName);
  1323. }
  1324. function accumulateDispatches(inst, ignoredDirection, event) {
  1325. if (inst && event && event._reactName) {
  1326. var registrationName = event._reactName;
  1327. var listener = getListener(inst, registrationName);
  1328. if (listener) {
  1329. if (event._dispatchListeners == null) {
  1330. event._dispatchListeners = [];
  1331. }
  1332. if (event._dispatchInstances == null) {
  1333. event._dispatchInstances = [];
  1334. }
  1335. event._dispatchListeners.push(listener);
  1336. event._dispatchInstances.push(inst);
  1337. }
  1338. }
  1339. }
  1340. function accumulateDirectionalDispatches(inst, phase, event) {
  1341. {
  1342. if (!inst) {
  1343. error('Dispatching inst must not be null');
  1344. }
  1345. }
  1346. var listener = listenerAtPhase(inst, event, phase);
  1347. if (listener) {
  1348. if (event._dispatchListeners == null) {
  1349. event._dispatchListeners = [];
  1350. }
  1351. if (event._dispatchInstances == null) {
  1352. event._dispatchInstances = [];
  1353. }
  1354. event._dispatchListeners.push(listener);
  1355. event._dispatchInstances.push(inst);
  1356. }
  1357. }
  1358. function accumulateDirectDispatchesSingle(event) {
  1359. if (event && event._reactName) {
  1360. accumulateDispatches(event._targetInst, null, event);
  1361. }
  1362. }
  1363. function accumulateTwoPhaseDispatchesSingle(event) {
  1364. if (event && event._reactName) {
  1365. traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
  1366. }
  1367. } // End of inline
  1368. var Simulate = {};
  1369. var directDispatchEventTypes = new Set(['mouseEnter', 'mouseLeave', 'pointerEnter', 'pointerLeave']);
  1370. /**
  1371. * Exports:
  1372. *
  1373. * - `Simulate.click(Element)`
  1374. * - `Simulate.mouseMove(Element)`
  1375. * - `Simulate.change(Element)`
  1376. * - ... (All keys from event plugin `eventTypes` objects)
  1377. */
  1378. function makeSimulator(eventType) {
  1379. return function (domNode, eventData) {
  1380. if (React.isValidElement(domNode)) {
  1381. throw new 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.');
  1382. }
  1383. if (isCompositeComponent(domNode)) {
  1384. throw new 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.');
  1385. }
  1386. var reactName = 'on' + eventType[0].toUpperCase() + eventType.slice(1);
  1387. var fakeNativeEvent = new Event();
  1388. fakeNativeEvent.target = domNode;
  1389. fakeNativeEvent.type = eventType.toLowerCase();
  1390. var targetInst = getInstanceFromNode(domNode);
  1391. var event = new SyntheticEvent(reactName, fakeNativeEvent.type, targetInst, fakeNativeEvent, domNode); // Since we aren't using pooling, always persist the event. This will make
  1392. // sure it's marked and won't warn when setting additional properties.
  1393. event.persist();
  1394. assign(event, eventData);
  1395. if (directDispatchEventTypes.has(eventType)) {
  1396. accumulateDirectDispatchesSingle(event);
  1397. } else {
  1398. accumulateTwoPhaseDispatchesSingle(event);
  1399. }
  1400. ReactDOM.unstable_batchedUpdates(function () {
  1401. // Normally extractEvent enqueues a state restore, but we'll just always
  1402. // do that since we're by-passing it here.
  1403. enqueueStateRestore(domNode);
  1404. executeDispatchesAndRelease(event);
  1405. rethrowCaughtError();
  1406. });
  1407. restoreStateIfNeeded();
  1408. };
  1409. } // A one-time snapshot with no plans to update. We'll probably want to deprecate Simulate API.
  1410. 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', 'resize', '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'];
  1411. function buildSimulators() {
  1412. simulatedEventTypes.forEach(function (eventType) {
  1413. Simulate[eventType] = makeSimulator(eventType);
  1414. });
  1415. }
  1416. buildSimulators();
  1417. var didWarnAboutUsingAct = false;
  1418. var act = function actWithWarning(callback) {
  1419. {
  1420. if (!didWarnAboutUsingAct) {
  1421. didWarnAboutUsingAct = true;
  1422. error('`ReactDOMTestUtils.act` is deprecated in favor of `React.act`. ' + 'Import `act` from `react` instead of `react-dom/test-utils`. ' + 'See https://react.dev/warnings/react-dom-test-utils for more info.');
  1423. }
  1424. }
  1425. return reactAct(callback);
  1426. } ;
  1427. exports.Simulate = Simulate;
  1428. exports.act = act;
  1429. exports.findAllInRenderedTree = findAllInRenderedTree;
  1430. exports.findRenderedComponentWithType = findRenderedComponentWithType;
  1431. exports.findRenderedDOMComponentWithClass = findRenderedDOMComponentWithClass;
  1432. exports.findRenderedDOMComponentWithTag = findRenderedDOMComponentWithTag;
  1433. exports.isCompositeComponent = isCompositeComponent;
  1434. exports.isCompositeComponentWithType = isCompositeComponentWithType;
  1435. exports.isDOMComponent = isDOMComponent;
  1436. exports.isDOMComponentElement = isDOMComponentElement;
  1437. exports.isElement = isElement;
  1438. exports.isElementOfType = isElementOfType;
  1439. exports.mockComponent = mockComponent;
  1440. exports.nativeTouchData = nativeTouchData;
  1441. exports.renderIntoDocument = renderIntoDocument;
  1442. exports.scryRenderedComponentsWithType = scryRenderedComponentsWithType;
  1443. exports.scryRenderedDOMComponentsWithClass = scryRenderedDOMComponentsWithClass;
  1444. exports.scryRenderedDOMComponentsWithTag = scryRenderedDOMComponentsWithTag;
  1445. exports.traverseTwoPhase = traverseTwoPhase;
  1446. })));