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