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

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