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