diff --git a/src/web/toManual/js/scrollbar.jsx b/src/web/toManual/js/scrollbar.jsx index 2354b1a84..4b59db99d 100644 --- a/src/web/toManual/js/scrollbar.jsx +++ b/src/web/toManual/js/scrollbar.jsx @@ -2,7 +2,7 @@ // // SPDX-License-Identifier: GPL-3.0-or-later -import React from 'react'; +import React, { useRef, useEffect } from 'react'; import { Scrollbars } from 'react-custom-scrollbars'; function renderScrollBarTrackHorizontal(props) { @@ -27,14 +27,66 @@ function renderView(props) { } export default function(props) { + const scrollbarsRef = useRef(null); + const timeoutRef = useRef(null); + + useEffect(() => { + const scrollbars = scrollbarsRef.current; + if (!scrollbars) return; + + const showScrollbar = () => { + const container = scrollbars.container; + if (container) { + container.style.setProperty('--scrollbar-opacity', '1'); + } + if (timeoutRef.current) { + clearTimeout(timeoutRef.current); + } + timeoutRef.current = setTimeout(hideScrollbar, 800); + }; + + const hideScrollbar = () => { + if (timeoutRef.current) { + clearTimeout(timeoutRef.current); + timeoutRef.current = null; + } + const container = scrollbars.container; + if (container) { + container.style.setProperty('--scrollbar-opacity', '0'); + } + }; + + const view = scrollbars.view; + const container = scrollbars.container; + if (view) { + view.addEventListener('scroll', showScrollbar); + } + if (container) { + container.addEventListener('mousemove', showScrollbar); + container.addEventListener('mouseleave', hideScrollbar); + } + + return () => { + if (view) { + view.removeEventListener('scroll', showScrollbar); + } + if (container) { + container.removeEventListener('mousemove', showScrollbar); + container.removeEventListener('mouseleave', hideScrollbar); + } + if (timeoutRef.current) { + clearTimeout(timeoutRef.current); + } + }; + }, []); + return ( {props.children} diff --git a/src/web/toManual/sass/app.scss b/src/web/toManual/sass/app.scss index 8c6974363..77c4b348f 100644 --- a/src/web/toManual/sass/app.scss +++ b/src/web/toManual/sass/app.scss @@ -22,29 +22,39 @@ body { } } -.scrollbar>div:last-child { - width: 6px !important; - border-radius: 3px !important; +// 使用 CSS 变量实现滚动条自动隐藏,避免 JavaScript autoHide 导致的光标闪烁 +// CSS变量的改变只会触发重绘(repaint),不会触发回流(reflow),因此不会导致光标闪烁 +.scrollbar { + // 滚动条轨道(垂直) + > div:last-child { + width: 6px !important; + border-radius: 3px !important; + opacity: var(--scrollbar-opacity, 0); // 使用CSS变量,默认值为0 + transition: opacity 0.3s ease-in-out; + + // 滚动条滑块 + div { + background-color: var(--scrollbar-div-background-color) !important; + cursor: default !important; - div { - background-color: var(--scrollbar-div-background-color) !important; - cursor: default !important; + &:hover { + background-color: var(--scrollbar-div-hover-background-color) !important; + } + } &:hover { - background-color: var(--scrollbar-div-hover-background-color) !important; + width: 8px !important; + border-radius: 4px !important; } } - - &:hover { - width: 8px !important; - border-radius: 4px !important; - } } +// 文本选择模式下滚动条保持显示 body[style*='user-select: none'] { - .scrollbar>div:last-child { + .scrollbar > div:last-child { width: 8px !important; border-radius: 4px !important; + opacity: 1; div { background-color: var(--scrollbar-div-select-background-color) !important; diff --git a/src/web_dist/toManual/index.css b/src/web_dist/toManual/index.css index ca4451e76..2daa622ce 100644 --- a/src/web_dist/toManual/index.css +++ b/src/web_dist/toManual/index.css @@ -14,7 +14,9 @@ body { .scrollbar > div:last-child { width: 6px !important; - border-radius: 3px !important; } + border-radius: 3px !important; + opacity: var(--scrollbar-opacity, 0); + transition: opacity 0.3s ease-in-out; } .scrollbar > div:last-child div { background-color: var(--scrollbar-div-background-color) !important; cursor: default !important; } @@ -26,7 +28,8 @@ body { body[style*='user-select: none'] .scrollbar > div:last-child { width: 8px !important; - border-radius: 4px !important; } + border-radius: 4px !important; + opacity: 1; } body[style*='user-select: none'] .scrollbar > div:last-child div { background-color: var(--scrollbar-div-select-background-color) !important; } diff --git a/src/web_dist/toManual/index.js b/src/web_dist/toManual/index.js index 4e87a3b0c..82a8828f6 100644 --- a/src/web_dist/toManual/index.js +++ b/src/web_dist/toManual/index.js @@ -1,5 +1,5 @@ (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i scrollingEdgeEnd || elementEdgeStart > scrollingEdgeStart && elementEdgeEnd < scrollingEdgeEnd) { - return 0; - } - - if (elementEdgeStart <= scrollingEdgeStart && elementSize <= scrollingSize || elementEdgeEnd >= scrollingEdgeEnd && elementSize >= scrollingSize) { - return elementEdgeStart - scrollingEdgeStart - scrollingBorderStart; - } - - if (elementEdgeEnd > scrollingEdgeEnd && elementSize < scrollingSize || elementEdgeStart < scrollingEdgeStart && elementSize > scrollingSize) { - return elementEdgeEnd - scrollingEdgeEnd + scrollingBorderEnd; - } - - return 0; -} - -var _default = function _default(target, options) { - var scrollMode = options.scrollMode, - block = options.block, - inline = options.inline, - boundary = options.boundary, - skipOverflowHiddenElements = options.skipOverflowHiddenElements; - var checkBoundary = typeof boundary === 'function' ? boundary : function (node) { - return node !== boundary; - }; - - if (!isElement(target)) { - throw new TypeError('Invalid target'); - } - - var scrollingElement = document.scrollingElement || document.documentElement; - var frames = []; - var cursor = target; - - while (isElement(cursor) && checkBoundary(cursor)) { - cursor = cursor.parentNode; - - if (cursor === scrollingElement) { - frames.push(cursor); - break; - } - - if (cursor === document.body && isScrollable(cursor) && !isScrollable(document.documentElement)) { - continue; - } - - if (isScrollable(cursor, skipOverflowHiddenElements)) { - frames.push(cursor); - } - } - - var viewportWidth = window.visualViewport ? visualViewport.width : innerWidth; - var viewportHeight = window.visualViewport ? visualViewport.height : innerHeight; - var viewportX = window.scrollX || pageXOffset; - var viewportY = window.scrollY || pageYOffset; - - var _target$getBoundingCl = target.getBoundingClientRect(), - targetHeight = _target$getBoundingCl.height, - targetWidth = _target$getBoundingCl.width, - targetTop = _target$getBoundingCl.top, - targetRight = _target$getBoundingCl.right, - targetBottom = _target$getBoundingCl.bottom, - targetLeft = _target$getBoundingCl.left; - - var targetBlock = block === 'start' || block === 'nearest' ? targetTop : block === 'end' ? targetBottom : targetTop + targetHeight / 2; - var targetInline = inline === 'center' ? targetLeft + targetWidth / 2 : inline === 'end' ? targetRight : targetLeft; - var computations = []; - - for (var index = 0; index < frames.length; index++) { - var frame = frames[index]; - - var _frame$getBoundingCli = frame.getBoundingClientRect(), - _height = _frame$getBoundingCli.height, - _width = _frame$getBoundingCli.width, - _top = _frame$getBoundingCli.top, - right = _frame$getBoundingCli.right, - bottom = _frame$getBoundingCli.bottom, - _left = _frame$getBoundingCli.left; - - if (scrollMode === 'if-needed' && targetTop >= 0 && targetLeft >= 0 && targetBottom <= viewportHeight && targetRight <= viewportWidth && targetTop >= _top && targetBottom <= bottom && targetLeft >= _left && targetRight <= right) { - return computations; - } - - var frameStyle = getComputedStyle(frame); - var borderLeft = parseInt(frameStyle.borderLeftWidth, 10); - var borderTop = parseInt(frameStyle.borderTopWidth, 10); - var borderRight = parseInt(frameStyle.borderRightWidth, 10); - var borderBottom = parseInt(frameStyle.borderBottomWidth, 10); - var blockScroll = 0; - var inlineScroll = 0; - var scrollbarWidth = 'offsetWidth' in frame ? frame.offsetWidth - frame.clientWidth - borderLeft - borderRight : 0; - var scrollbarHeight = 'offsetHeight' in frame ? frame.offsetHeight - frame.clientHeight - borderTop - borderBottom : 0; - - if (scrollingElement === frame) { - if (block === 'start') { - blockScroll = targetBlock; - } else if (block === 'end') { - blockScroll = targetBlock - viewportHeight; - } else if (block === 'nearest') { - blockScroll = alignNearest(viewportY, viewportY + viewportHeight, viewportHeight, borderTop, borderBottom, viewportY + targetBlock, viewportY + targetBlock + targetHeight, targetHeight); - } else { - blockScroll = targetBlock - viewportHeight / 2; - } - - if (inline === 'start') { - inlineScroll = targetInline; - } else if (inline === 'center') { - inlineScroll = targetInline - viewportWidth / 2; - } else if (inline === 'end') { - inlineScroll = targetInline - viewportWidth; - } else { - inlineScroll = alignNearest(viewportX, viewportX + viewportWidth, viewportWidth, borderLeft, borderRight, viewportX + targetInline, viewportX + targetInline + targetWidth, targetWidth); - } - - blockScroll = Math.max(0, blockScroll + viewportY); - inlineScroll = Math.max(0, inlineScroll + viewportX); - } else { - if (block === 'start') { - blockScroll = targetBlock - _top - borderTop; - } else if (block === 'end') { - blockScroll = targetBlock - bottom + borderBottom + scrollbarHeight; - } else if (block === 'nearest') { - blockScroll = alignNearest(_top, bottom, _height, borderTop, borderBottom + scrollbarHeight, targetBlock, targetBlock + targetHeight, targetHeight); - } else { - blockScroll = targetBlock - (_top + _height / 2) + scrollbarHeight / 2; - } - - if (inline === 'start') { - inlineScroll = targetInline - _left - borderLeft; - } else if (inline === 'center') { - inlineScroll = targetInline - (_left + _width / 2) + scrollbarWidth / 2; - } else if (inline === 'end') { - inlineScroll = targetInline - right + borderRight + scrollbarWidth; - } else { - inlineScroll = alignNearest(_left, right, _width, borderLeft, borderRight + scrollbarWidth, targetInline, targetInline + targetWidth, targetWidth); - } +function t(t){return"object"==typeof t&&null!=t&&1===t.nodeType}function e(t,e){return(!e||"hidden"!==t)&&"visible"!==t&&"clip"!==t}function n(t,n){if(t.clientHeighte||o>t&&l=e&&d>=n?o-t-i:l>e&&dn?l-e+r:0}module.exports=function(e,r){var o=window,l=r.scrollMode,d=r.block,f=r.inline,h=r.boundary,u=r.skipOverflowHiddenElements,s="function"==typeof h?h:function(t){return t!==h};if(!t(e))throw new TypeError("Invalid target");for(var c,a,g=document.scrollingElement||document.documentElement,m=[],p=e;t(p)&&s(p);){if((p=null==(a=(c=p).parentElement)?c.getRootNode().host||null:a)===g){m.push(p);break}null!=p&&p===document.body&&n(p)&&!n(document.documentElement)||null!=p&&n(p,u)&&m.push(p)}for(var w=o.visualViewport?o.visualViewport.width:innerWidth,v=o.visualViewport?o.visualViewport.height:innerHeight,W=window.scrollX||pageXOffset,H=window.scrollY||pageYOffset,b=e.getBoundingClientRect(),y=b.height,E=b.width,M=b.top,V=b.right,x=b.bottom,I=b.left,C="start"===d||"nearest"===d?M:"end"===d?x:M+y/2,R="center"===f?I+E/2:"end"===f?V:I,T=[],k=0;k=0&&I>=0&&x<=v&&V<=w&&M>=Y&&x<=S&&I>=j&&V<=L)return T;var N=getComputedStyle(B),q=parseInt(N.borderLeftWidth,10),z=parseInt(N.borderTopWidth,10),A=parseInt(N.borderRightWidth,10),F=parseInt(N.borderBottomWidth,10),G=0,J=0,K="offsetWidth"in B?B.offsetWidth-B.clientWidth-q-A:0,P="offsetHeight"in B?B.offsetHeight-B.clientHeight-z-F:0,Q="offsetWidth"in B?0===B.offsetWidth?0:X/B.offsetWidth:0,U="offsetHeight"in B?0===B.offsetHeight?0:O/B.offsetHeight:0;if(g===B)G="start"===d?C:"end"===d?C-v:"nearest"===d?i(H,H+v,v,z,F,H+C,H+C+y,y):C-v/2,J="start"===f?R:"center"===f?R-w/2:"end"===f?R-w:i(W,W+w,w,q,A,W+R,W+R+E,E),G=Math.max(0,G+H),J=Math.max(0,J+W);else{G="start"===d?C-Y-z:"end"===d?C-S+F+P:"nearest"===d?i(Y,S,O,z,F+P,C,C+y,y):C-(Y+O/2)+P/2,J="start"===f?R-j-q:"center"===f?R-(j+X/2)+K/2:"end"===f?R-L+A+K:i(j,L,X,q,A+K,R,R+E,E);var Z=B.scrollLeft,$=B.scrollTop;C+=$-(G=Math.max(0,Math.min($+G/U,B.scrollHeight-O/U+P))),R+=Z-(J=Math.max(0,Math.min(Z+J/Q,B.scrollWidth-X/Q+K)))}T.push({el:B,top:G,left:J})}return T}; - var scrollLeft = frame.scrollLeft, - scrollTop = frame.scrollTop; - blockScroll = Math.max(0, Math.min(scrollTop + blockScroll, frame.scrollHeight - _height + scrollbarHeight)); - inlineScroll = Math.max(0, Math.min(scrollLeft + inlineScroll, frame.scrollWidth - _width + scrollbarWidth)); - targetBlock += scrollTop - blockScroll; - targetInline += scrollLeft - inlineScroll; - } - computations.push({ - el: frame, - top: blockScroll, - left: inlineScroll - }); - } - - return computations; -}; - -exports.default = _default; -module.exports = exports.default; },{}],11:[function(require,module,exports){ var prefix = require('prefix-style') var toCamelCase = require('to-camel-case') @@ -3251,7 +3134,7 @@ module.exports.get = function (element, properties) { } } -},{"add-px-to-style":9,"prefix-style":24,"to-camel-case":86}],12:[function(require,module,exports){ +},{"add-px-to-style":9,"prefix-style":23,"to-camel-case":91}],12:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); @@ -3288,7 +3171,7 @@ function stripLeadingSlash(path) { return path.charAt(0) === '/' ? path.substr(1) : path; } function hasBasename(path, prefix) { - return new RegExp('^' + prefix + '(\\/|\\?|#|$)', 'i').test(path); + return path.toLowerCase().indexOf(prefix.toLowerCase()) === 0 && '/?#'.indexOf(path.charAt(prefix.length)) !== -1; } function stripBasename(path, prefix) { return hasBasename(path, prefix) ? path.substr(prefix.length) : path; @@ -3498,7 +3381,7 @@ function supportsGoWithoutReloadUsingHash() { */ function isExtraneousPopstateEvent(event) { - event.state === undefined && navigator.userAgent.indexOf('CriOS') === -1; + return event.state === undefined && navigator.userAgent.indexOf('CriOS') === -1; } var PopStateEvent = 'popstate'; @@ -3640,7 +3523,7 @@ function createBrowserHistory(props) { window.location.href = href; } else { var prevIndex = allKeys.indexOf(history.location.key); - var nextKeys = allKeys.slice(0, prevIndex === -1 ? 0 : prevIndex + 1); + var nextKeys = allKeys.slice(0, prevIndex + 1); nextKeys.push(location.key); allKeys = nextKeys; setState({ @@ -3783,6 +3666,11 @@ var HashPathCoders = { } }; +function stripHash(url) { + var hashIndex = url.indexOf('#'); + return hashIndex === -1 ? url : url.slice(0, hashIndex); +} + function getHashPath() { // We can't use window.location.hash here because it's not // consistent across browsers - Firefox will pre-decode it! @@ -3796,8 +3684,7 @@ function pushHashPath(path) { } function replaceHashPath(path) { - var hashIndex = window.location.href.indexOf('#'); - window.location.replace(window.location.href.slice(0, hashIndex >= 0 ? hashIndex : 0) + '#' + path); + window.location.replace(stripHash(window.location.href) + '#' + path); } function createHashHistory(props) { @@ -3837,6 +3724,10 @@ function createHashHistory(props) { var forceNextPop = false; var ignorePath = null; + function locationsAreEqual$$1(a, b) { + return a.pathname === b.pathname && a.search === b.search && a.hash === b.hash; + } + function handleHashChange() { var path = getHashPath(); var encodedPath = encodePath(path); @@ -3847,7 +3738,7 @@ function createHashHistory(props) { } else { var location = getDOMLocation(); var prevLocation = history.location; - if (!forceNextPop && locationsAreEqual(prevLocation, location)) return; // A hashchange doesn't always == location change. + if (!forceNextPop && locationsAreEqual$$1(prevLocation, location)) return; // A hashchange doesn't always == location change. if (ignorePath === createPath(location)) return; // Ignore this change; we already setState in push/replace. @@ -3900,7 +3791,14 @@ function createHashHistory(props) { var allPaths = [createPath(initialLocation)]; // Public interface function createHref(location) { - return '#' + encodePath(basename + createPath(location)); + var baseTag = document.querySelector('base'); + var href = ''; + + if (baseTag && baseTag.getAttribute('href')) { + href = stripHash(window.location.href); + } + + return href + '#' + encodePath(basename + createPath(location)); } function push(path, state) { @@ -3920,7 +3818,7 @@ function createHashHistory(props) { ignorePath = path; pushHashPath(encodedPath); var prevIndex = allPaths.lastIndexOf(createPath(history.location)); - var nextPaths = allPaths.slice(0, prevIndex === -1 ? 0 : prevIndex + 1); + var nextPaths = allPaths.slice(0, prevIndex + 1); nextPaths.push(path); allPaths = nextPaths; setState({ @@ -4186,11 +4084,11 @@ exports.locationsAreEqual = locationsAreEqual; exports.parsePath = parsePath; exports.createPath = createPath; -},{"resolve-pathname":75,"tiny-invariant":84,"tiny-warning":85,"value-equal":89}],13:[function(require,module,exports){ -"use strict";function _interopDefault(n){return n&&"object"==typeof n&&"default"in n?n.default:n}Object.defineProperty(exports,"__esModule",{value:!0});var resolvePathname=_interopDefault(require("resolve-pathname")),valueEqual=_interopDefault(require("value-equal"));require("tiny-warning");var invariant=_interopDefault(require("tiny-invariant"));function _extends(){return(_extends=Object.assign||function(n){for(var t=1;tt?e.splice(t,e.length-t,a):e.push(a),u({action:"PUSH",location:a,index:t,entries:e})}})},replace:function(n,t){var e="REPLACE",a=createLocation(n,t,f(),g.location);h.confirmTransitionTo(a,e,o,function(n){n&&(g.entries[g.index]=a,u({action:e,location:a}))})},go:p,goBack:function(){p(-1)},goForward:function(){p(1)},canGo:function(n){var t=g.index+n;return 0<=t&&tn?e.splice(n,e.length-n,a):e.push(a),u({action:"PUSH",location:a,index:n,entries:e})}})},replace:function(t,n){var e="REPLACE",a=createLocation(t,n,f(),g.location);h.confirmTransitionTo(a,e,r,function(t){t&&(g.entries[g.index]=a,u({action:e,location:a}))})},go:p,goBack:function(){p(-1)},goForward:function(){p(1)},canGo:function(t){var n=g.index+t;return 0<=n&&n -1) { + return '[^' + escapeString(delimiter) + ']+?' + } + + return escapeString(prevText) + '|(?:(?!' + escapeString(prevText) + ')[^' + escapeString(delimiter) + '])+?' +} + /** * Compile a string to a template function for the path. * @@ -16687,7 +16502,7 @@ function parse (str, options) { * @return {!function(Object=, Object=)} */ function compile (str, options) { - return tokensToFunction(parse(str, options)) + return tokensToFunction(parse(str, options), options) } /** @@ -16717,14 +16532,14 @@ function encodeAsterisk (str) { /** * Expose a method for transforming tokens into the path function. */ -function tokensToFunction (tokens) { +function tokensToFunction (tokens, options) { // Compile all the tokens into regexps. var matches = new Array(tokens.length) // Compile all the patterns before compilation. for (var i = 0; i < tokens.length; i++) { if (typeof tokens[i] === 'object') { - matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$') + matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$', flags(options)) } } @@ -16837,7 +16652,7 @@ function attachKeys (re, keys) { * @return {string} */ function flags (options) { - return options.sensitive ? '' : 'i' + return options && options.sensitive ? '' : 'i' } /** @@ -17004,13 +16819,13 @@ function pathToRegexp (path, keys, options) { return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options) } -},{"isarray":22}],22:[function(require,module,exports){ +},{"isarray":21}],21:[function(require,module,exports){ module.exports = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]'; }; -},{}],23:[function(require,module,exports){ -(function (process){ +},{}],22:[function(require,module,exports){ +(function (process){(function (){ // Generated by CoffeeScript 1.12.2 (function() { var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime; @@ -17048,8 +16863,8 @@ module.exports = Array.isArray || function (arr) { -}).call(this,require('_process')) -},{"_process":25}],24:[function(require,module,exports){ +}).call(this)}).call(this,require('_process')) +},{"_process":24}],23:[function(require,module,exports){ var div = null var prefixes = [ 'Webkit', 'Moz', 'O', 'ms' ] @@ -17081,7 +16896,7 @@ module.exports = function prefixStyle (prop) { return false } -},{}],25:[function(require,module,exports){ +},{}],24:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; @@ -17267,8 +17082,8 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],26:[function(require,module,exports){ -(function (process){ +},{}],25:[function(require,module,exports){ +(function (process){(function (){ /** * Copyright (c) 2013-present, Facebook, Inc. * @@ -17283,7 +17098,7 @@ var printWarning = function() {}; if (process.env.NODE_ENV !== 'production') { var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret'); var loggedTypeFailures = {}; - var has = Function.call.bind(Object.prototype.hasOwnProperty); + var has = require('./lib/has'); printWarning = function(text) { var message = 'Warning: ' + text; @@ -17295,7 +17110,7 @@ if (process.env.NODE_ENV !== 'production') { // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); - } catch (x) {} + } catch (x) { /**/ } }; } @@ -17324,7 +17139,8 @@ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { if (typeof typeSpecs[typeSpecName] !== 'function') { var err = Error( (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + - 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.' ); err.name = 'Invariant Violation'; throw err; @@ -17372,8 +17188,8 @@ checkPropTypes.resetWarningCache = function() { module.exports = checkPropTypes; -}).call(this,require('_process')) -},{"./lib/ReactPropTypesSecret":30,"_process":25}],27:[function(require,module,exports){ +}).call(this)}).call(this,require('_process')) +},{"./lib/ReactPropTypesSecret":29,"./lib/has":30,"_process":24}],26:[function(require,module,exports){ /** * Copyright (c) 2013-present, Facebook, Inc. * @@ -17411,6 +17227,7 @@ module.exports = function() { // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. var ReactPropTypes = { array: shim, + bigint: shim, bool: shim, func: shim, number: shim, @@ -17439,8 +17256,8 @@ module.exports = function() { return ReactPropTypes; }; -},{"./lib/ReactPropTypesSecret":30}],28:[function(require,module,exports){ -(function (process){ +},{"./lib/ReactPropTypesSecret":29}],27:[function(require,module,exports){ +(function (process){(function (){ /** * Copyright (c) 2013-present, Facebook, Inc. * @@ -17454,9 +17271,9 @@ var ReactIs = require('react-is'); var assign = require('object-assign'); var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret'); +var has = require('./lib/has'); var checkPropTypes = require('./checkPropTypes'); -var has = Function.call.bind(Object.prototype.hasOwnProperty); var printWarning = function() {}; if (process.env.NODE_ENV !== 'production') { @@ -17557,6 +17374,7 @@ module.exports = function(isValidElement, throwOnDirectAccess) { // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), + bigint: createPrimitiveTypeChecker('bigint'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), @@ -17602,8 +17420,9 @@ module.exports = function(isValidElement, throwOnDirectAccess) { * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ - function PropTypeError(message) { + function PropTypeError(message, data) { this.message = message; + this.data = data && typeof data === 'object' ? data: {}; this.stack = ''; } // Make `instanceof Error` still work for returned errors. @@ -17638,7 +17457,7 @@ module.exports = function(isValidElement, throwOnDirectAccess) { ) { printWarning( 'You are manually calling a React.PropTypes validation ' + - 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' + + 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.' @@ -17677,7 +17496,10 @@ module.exports = function(isValidElement, throwOnDirectAccess) { // 'of type `object`'. var preciseType = getPreciseType(propValue); - return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); + return new PropTypeError( + 'Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'), + {expectedType: expectedType} + ); } return null; } @@ -17821,14 +17643,19 @@ module.exports = function(isValidElement, throwOnDirectAccess) { } function validate(props, propName, componentName, location, propFullName) { + var expectedTypes = []; for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; - if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { + var checkerResult = checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret); + if (checkerResult == null) { return null; } + if (checkerResult.data && has(checkerResult.data, 'expectedType')) { + expectedTypes.push(checkerResult.data.expectedType); + } } - - return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); + var expectedTypesMessage = (expectedTypes.length > 0) ? ', expected one of type [' + expectedTypes.join(', ') + ']': ''; + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`' + expectedTypesMessage + '.')); } return createChainableTypeChecker(validate); } @@ -17843,6 +17670,13 @@ module.exports = function(isValidElement, throwOnDirectAccess) { return createChainableTypeChecker(validate); } + function invalidValidatorError(componentName, location, propFullName, key, type) { + return new PropTypeError( + (componentName || 'React class') + ': ' + location + ' type `' + propFullName + '.' + key + '` is invalid; ' + + 'it must be a function, usually from the `prop-types` package, but received `' + type + '`.' + ); + } + function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; @@ -17852,8 +17686,8 @@ module.exports = function(isValidElement, throwOnDirectAccess) { } for (var key in shapeTypes) { var checker = shapeTypes[key]; - if (!checker) { - continue; + if (typeof checker !== 'function') { + return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker)); } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { @@ -17872,16 +17706,18 @@ module.exports = function(isValidElement, throwOnDirectAccess) { if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } - // We need to check all keys in case some are required but missing from - // props. + // We need to check all keys in case some are required but missing from props. var allKeys = assign({}, props[propName], shapeTypes); for (var key in allKeys) { var checker = shapeTypes[key]; + if (has(shapeTypes, key) && typeof checker !== 'function') { + return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker)); + } if (!checker) { return new PropTypeError( 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' + '\nBad object: ' + JSON.stringify(props[propName], null, ' ') + - '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ') + '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ') ); } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); @@ -18033,9 +17869,9 @@ module.exports = function(isValidElement, throwOnDirectAccess) { return ReactPropTypes; }; -}).call(this,require('_process')) -},{"./checkPropTypes":26,"./lib/ReactPropTypesSecret":30,"_process":25,"object-assign":19,"react-is":46}],29:[function(require,module,exports){ -(function (process){ +}).call(this)}).call(this,require('_process')) +},{"./checkPropTypes":25,"./lib/ReactPropTypesSecret":29,"./lib/has":30,"_process":24,"object-assign":31,"react-is":48}],28:[function(require,module,exports){ +(function (process){(function (){ /** * Copyright (c) 2013-present, Facebook, Inc. * @@ -18056,8 +17892,8 @@ if (process.env.NODE_ENV !== 'production') { module.exports = require('./factoryWithThrowingShims')(); } -}).call(this,require('_process')) -},{"./factoryWithThrowingShims":27,"./factoryWithTypeCheckers":28,"_process":25,"react-is":46}],30:[function(require,module,exports){ +}).call(this)}).call(this,require('_process')) +},{"./factoryWithThrowingShims":26,"./factoryWithTypeCheckers":27,"_process":24,"react-is":48}],29:[function(require,module,exports){ /** * Copyright (c) 2013-present, Facebook, Inc. * @@ -18071,8 +17907,103 @@ var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; +},{}],30:[function(require,module,exports){ +module.exports = Function.call.bind(Object.prototype.hasOwnProperty); + },{}],31:[function(require,module,exports){ -(function (global){ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],32:[function(require,module,exports){ +(function (global){(function (){ var now = require('performance-now') , root = typeof window === 'undefined' ? global : window , vendors = ['moz', 'webkit'] @@ -18149,8 +18080,8 @@ module.exports.polyfill = function(object) { object.cancelAnimationFrame = caf } -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"performance-now":23}],32:[function(require,module,exports){ +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"performance-now":22}],33:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -18228,7 +18159,7 @@ function renderThumbVerticalDefault(_ref4) { }); return _react2["default"].createElement('div', _extends({ style: finalStyle }, props)); } -},{"react":74}],33:[function(require,module,exports){ +},{"react":76}],34:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -19022,7 +18953,7 @@ Scrollbars.defaultProps = { autoHeightMax: 200, universal: false }; -},{"../utils/getInnerHeight":36,"../utils/getInnerWidth":37,"../utils/getScrollbarWidth":38,"../utils/isString":39,"../utils/returnFalse":40,"./defaultRenderElements":32,"./styles":34,"dom-css":11,"prop-types":29,"raf":31,"react":74}],34:[function(require,module,exports){ +},{"../utils/getInnerHeight":37,"../utils/getInnerWidth":38,"../utils/getScrollbarWidth":39,"../utils/isString":40,"../utils/returnFalse":41,"./defaultRenderElements":33,"./styles":35,"dom-css":11,"prop-types":28,"raf":32,"react":76}],35:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -19094,7 +19025,7 @@ var disableSelectStyle = exports.disableSelectStyle = { var disableSelectStyleReset = exports.disableSelectStyleReset = { userSelect: '' }; -},{}],35:[function(require,module,exports){ +},{}],36:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -19110,7 +19041,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "d exports["default"] = _Scrollbars2["default"]; exports.Scrollbars = _Scrollbars2["default"]; -},{"./Scrollbars":33}],36:[function(require,module,exports){ +},{"./Scrollbars":34}],37:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -19126,7 +19057,7 @@ function getInnerHeight(el) { return clientHeight - parseFloat(paddingTop) - parseFloat(paddingBottom); } -},{}],37:[function(require,module,exports){ +},{}],38:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -19142,7 +19073,7 @@ function getInnerWidth(el) { return clientWidth - parseFloat(paddingLeft) - parseFloat(paddingRight); } -},{}],38:[function(require,module,exports){ +},{}],39:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -19179,7 +19110,7 @@ function getScrollbarWidth() { } return scrollbarWidth || 0; } -},{"dom-css":11}],39:[function(require,module,exports){ +},{"dom-css":11}],40:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { @@ -19189,7 +19120,7 @@ exports["default"] = isString; function isString(maybe) { return typeof maybe === 'string'; } -},{}],40:[function(require,module,exports){ +},{}],41:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { @@ -19199,9 +19130,9 @@ exports["default"] = returnFalse; function returnFalse() { return false; } -},{}],41:[function(require,module,exports){ -(function (process){ -/** @license React v16.9.0 +},{}],42:[function(require,module,exports){ +(function (process){(function (){ +/** @license React v16.14.0 * react-dom.development.js * * Copyright (c) Facebook, Inc. and its affiliates. @@ -19220,251 +19151,98 @@ if (process.env.NODE_ENV !== "production") { var React = require('react'); var _assign = require('object-assign'); -var checkPropTypes = require('prop-types/checkPropTypes'); var Scheduler = require('scheduler'); +var checkPropTypes = require('prop-types/checkPropTypes'); var tracing = require('scheduler/tracing'); -// Do not require this module directly! Use normal `invariant` calls with -// template literal strings. The messages will be converted to ReactError during -// build, and in production they will be minified. +var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions. +// Current owner and dispatcher used to share the same ref, +// but PR #14548 split them out to better support the react-debug-tools package. -// Do not require this module directly! Use normal `invariant` calls with -// template literal strings. The messages will be converted to ReactError during -// build, and in production they will be minified. +if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) { + ReactSharedInternals.ReactCurrentDispatcher = { + current: null + }; +} -function ReactError(error) { - error.name = 'Invariant Violation'; - return error; +if (!ReactSharedInternals.hasOwnProperty('ReactCurrentBatchConfig')) { + ReactSharedInternals.ReactCurrentBatchConfig = { + suspense: null + }; } -/** - * Use invariant() to assert state which your program assumes to be true. - * - * Provide sprintf-style format (only %s is supported) and arguments - * to provide information about what broke and what you were - * expecting. - * - * The invariant message will be stripped in production, but the invariant - * will remain to ensure logic does not differ in production. - */ +// by calls to these methods by a Babel plugin. +// +// In PROD (or in packages without access to React internals), +// they are left as they are instead. -(function () { - if (!React) { - { - throw ReactError(Error('ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM.')); +function warn(format) { + { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; } - } -})(); - -/** - * Injectable ordering of event plugins. - */ -var eventPluginOrder = null; - -/** - * Injectable mapping from names to event plugin modules. - */ -var namesToPlugins = {}; -/** - * Recomputes the plugin list using the injected plugins and plugin ordering. - * - * @private - */ -function recomputePluginOrdering() { - if (!eventPluginOrder) { - // Wait until an `eventPluginOrder` is injected. - return; - } - for (var pluginName in namesToPlugins) { - var pluginModule = namesToPlugins[pluginName]; - var pluginIndex = eventPluginOrder.indexOf(pluginName); - (function () { - if (!(pluginIndex > -1)) { - { - throw ReactError(Error('EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `' + pluginName + '`.')); - } - } - })(); - if (plugins[pluginIndex]) { - continue; - } - (function () { - if (!pluginModule.extractEvents) { - { - throw ReactError(Error('EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `' + pluginName + '` does not.')); - } - } - })(); - plugins[pluginIndex] = pluginModule; - var publishedEvents = pluginModule.eventTypes; - for (var eventName in publishedEvents) { - (function () { - if (!publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName)) { - { - throw ReactError(Error('EventPluginRegistry: Failed to publish event `' + eventName + '` for plugin `' + pluginName + '`.')); - } - } - })(); - } + printWarning('warn', format, args); } } - -/** - * Publishes an event so that it can be dispatched by the supplied plugin. - * - * @param {object} dispatchConfig Dispatch configuration for the event. - * @param {object} PluginModule Plugin publishing the event. - * @return {boolean} True if the event was successfully published. - * @private - */ -function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { - (function () { - if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) { - { - throw ReactError(Error('EventPluginHub: More than one plugin attempted to publish the same event name, `' + eventName + '`.')); - } +function error(format) { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; } - })(); - eventNameDispatchConfigs[eventName] = dispatchConfig; - var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; - if (phasedRegistrationNames) { - for (var phaseName in phasedRegistrationNames) { - if (phasedRegistrationNames.hasOwnProperty(phaseName)) { - var phasedRegistrationName = phasedRegistrationNames[phaseName]; - publishRegistrationName(phasedRegistrationName, pluginModule, eventName); - } - } - return true; - } else if (dispatchConfig.registrationName) { - publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName); - return true; + printWarning('error', format, args); } - return false; } -/** - * Publishes a registration name that is used to identify dispatched events. - * - * @param {string} registrationName Registration name to add. - * @param {object} PluginModule Plugin publishing the event. - * @private - */ -function publishRegistrationName(registrationName, pluginModule, eventName) { - (function () { - if (!!registrationNameModules[registrationName]) { - { - throw ReactError(Error('EventPluginHub: More than one plugin attempted to publish the same registration name, `' + registrationName + '`.')); - } - } - })(); - registrationNameModules[registrationName] = pluginModule; - registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; - +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. { - var lowerCasedName = registrationName.toLowerCase(); - possibleRegistrationNames[lowerCasedName] = registrationName; - - if (registrationName === 'onDoubleClick') { - possibleRegistrationNames.ondblclick = registrationName; - } - } -} - -/** - * Registers plugins so that they can extract and dispatch events. - * - * @see {EventPluginHub} - */ + var hasExistingStack = args.length > 0 && typeof args[args.length - 1] === 'string' && args[args.length - 1].indexOf('\n in') === 0; -/** - * Ordered list of injected plugins. - */ -var plugins = []; + if (!hasExistingStack) { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); -/** - * Mapping from event name to dispatch config - */ -var eventNameDispatchConfigs = {}; + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } + } -/** - * Mapping from registration name to plugin module - */ -var registrationNameModules = {}; + var argsWithFormat = args.map(function (item) { + return '' + item; + }); // Careful: RN currently depends on this prefix -/** - * Mapping from registration name to event name - */ -var registrationNameDependencies = {}; + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging -/** - * Mapping from lowercase registration names to the properly cased version, - * used to warn in the case of missing event handlers. Available - * only in true. - * @type {Object} - */ -var possibleRegistrationNames = {}; -// Trust the developer to only use possibleRegistrationNames in true + Function.prototype.apply.call(console[level], console, argsWithFormat); -/** - * Injects an ordering of plugins (by plugin name). This allows the ordering - * to be decoupled from injection of the actual plugins so that ordering is - * always deterministic regardless of packaging, on-the-fly injection, etc. - * - * @param {array} InjectedEventPluginOrder - * @internal - * @see {EventPluginHub.injection.injectEventPluginOrder} - */ -function injectEventPluginOrder(injectedEventPluginOrder) { - (function () { - if (!!eventPluginOrder) { - { - throw ReactError(Error('EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.')); - } - } - })(); - // Clone the ordering so it cannot be dynamically mutated. - eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); - recomputePluginOrdering(); + try { + // --- Welcome to debugging React --- + // This error was thrown as a convenience so that you can use this stack + // to find the callsite that caused this warning to fire. + var argIndex = 0; + var message = 'Warning: ' + format.replace(/%s/g, function () { + return args[argIndex++]; + }); + throw new Error(message); + } catch (x) {} + } } -/** - * Injects plugins to be used by `EventPluginHub`. The plugin names must be - * in the ordering injected by `injectEventPluginOrder`. - * - * Plugins can be injected as part of page initialization or on-the-fly. - * - * @param {object} injectedNamesToPlugins Map from names to plugin modules. - * @internal - * @see {EventPluginHub.injection.injectEventPluginsByName} - */ -function injectEventPluginsByName(injectedNamesToPlugins) { - var isOrderingDirty = false; - for (var pluginName in injectedNamesToPlugins) { - if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { - continue; - } - var pluginModule = injectedNamesToPlugins[pluginName]; - if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) { - (function () { - if (!!namesToPlugins[pluginName]) { - { - throw ReactError(Error('EventPluginRegistry: Cannot inject two different event plugins using the same name, `' + pluginName + '`.')); - } - } - })(); - namesToPlugins[pluginName] = pluginModule; - isOrderingDirty = true; - } - } - if (isOrderingDirty) { - recomputePluginOrdering(); +if (!React) { + { + throw Error( "ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM." ); } } var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) { var funcArgs = Array.prototype.slice.call(arguments, 3); + try { func.apply(context, funcArgs); } catch (error) { @@ -19491,7 +19269,6 @@ var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) // event loop context, it does not interrupt the normal program flow. // Effectively, this gives us try-catch behavior without actually using // try-catch. Neat! - // Check that the browser supports the APIs we need to implement our special // DEV version of invokeGuardedCallback if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { @@ -19502,56 +19279,49 @@ var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) // when we call document.createEvent(). However this can cause confusing // errors: https://github.com/facebookincubator/create-react-app/issues/3482 // So we preemptively throw with a better message instead. - (function () { - if (!(typeof document !== 'undefined')) { - { - throw ReactError(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.')); - } + if (!(typeof document !== 'undefined')) { + { + throw Error( "The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous." ); } - })(); - var evt = document.createEvent('Event'); + } - // Keeps track of whether the user-provided callback threw an error. We + var evt = document.createEvent('Event'); // Keeps track of whether the user-provided callback threw an error. We // set this to true at the beginning, then set it to false right after // calling the function. If the function errors, `didError` will never be // set to false. This strategy works even if the browser is flaky and // fails to call our global error handler, because it doesn't rely on // the error event at all. - var didError = true; - // Keeps track of the value of window.event so that we can reset it + var didError = true; // Keeps track of the value of window.event so that we can reset it // during the callback to let user code access window.event in the // browsers that support it. - var windowEvent = window.event; - // Keeps track of the descriptor of window.event to restore it after event + var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event // dispatching: https://github.com/facebook/react/issues/13688 - var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event'); - // Create an event handler for our fake event. We will synchronously + var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event'); // Create an event handler for our fake event. We will synchronously // dispatch our fake event using `dispatchEvent`. Inside the handler, we // call the user-provided callback. + var funcArgs = Array.prototype.slice.call(arguments, 3); + function callCallback() { // We immediately remove the callback from event listeners so that // nested `invokeGuardedCallback` calls do not clash. Otherwise, a // nested call would trigger the fake event handlers of any call higher // in the stack. - fakeNode.removeEventListener(evtType, callCallback, false); - - // We check for window.hasOwnProperty('event') to prevent the + fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the // window.event assignment in both IE <= 10 as they throw an error // "Member not found" in strict mode, and in Firefox which does not // support window.event. + if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) { window.event = windowEvent; } func.apply(context, funcArgs); didError = false; - } - - // Create a global error event handler. We use this to capture the value + } // Create a global error event handler. We use this to capture the value // that was thrown. It's possible that this error handler will fire more // than once; for example, if non-React code also calls `dispatchEvent` // and a handler for that event throws. We should be resilient to most of @@ -19562,17 +19332,21 @@ var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) // erroring and the code that follows the `dispatchEvent` call below. If // the callback doesn't error, but the error event was fired, we know to // ignore it because `didError` will be false, as described above. - var error = void 0; - // Use this to track whether the error event is ever called. + + + var error; // Use this to track whether the error event is ever called. + var didSetError = false; var isCrossOriginError = false; function handleWindowError(event) { error = event.error; didSetError = true; + if (error === null && event.colno === 0 && event.lineno === 0) { isCrossOriginError = true; } + if (event.defaultPrevented) { // Some other error handler has prevented default. // Browsers silence the error report if this happens. @@ -19580,22 +19354,19 @@ var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) if (error != null && typeof error === 'object') { try { error._suppressLogging = true; - } catch (inner) { - // Ignore. + } catch (inner) {// Ignore. } } } - } + } // Create a fake event type. - // Create a fake event type. - var evtType = 'react-' + (name ? name : 'invokeguardedcallback'); - // Attach our event handlers - window.addEventListener('error', handleWindowError); - fakeNode.addEventListener(evtType, callCallback, false); + var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers - // Synchronously dispatch our fake event. If the user-provided function + window.addEventListener('error', handleWindowError); + fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function // errors, it will trigger our global error handler. + evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); @@ -19610,10 +19381,11 @@ var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) } else if (isCrossOriginError) { error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://fb.me/react-crossorigin-error for more information.'); } + this.onError(error); - } + } // Remove our event listeners + - // Remove our event listeners window.removeEventListener('error', handleWindowError); }; @@ -19623,21 +19395,17 @@ var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl; -// Used by Fiber to simulate a try-catch. var hasError = false; -var caughtError = null; +var caughtError = null; // Used by event system to capture/rethrow the first error. -// Used by event system to capture/rethrow the first error. var hasRethrowError = false; var rethrowError = null; - var reporter = { onError: function (error) { hasError = true; caughtError = error; } }; - /** * Call a function while guarding against errors that happens within it. * Returns an error if it throws, otherwise null. @@ -19651,12 +19419,12 @@ var reporter = { * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ + function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { hasError = false; caughtError = null; invokeGuardedCallbackImpl$1.apply(reporter, arguments); } - /** * Same as invokeGuardedCallback, but instead of returning an error, it stores * it in a global so it can be rethrown by `rethrowCaughtError` later. @@ -19667,21 +19435,24 @@ function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ + function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) { invokeGuardedCallback.apply(this, arguments); + if (hasError) { var error = clearCaughtError(); + if (!hasRethrowError) { hasRethrowError = true; rethrowError = error; } } } - /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ + function rethrowCaughtError() { if (hasRethrowError) { var error = rethrowError; @@ -19690,11 +19461,9 @@ function rethrowCaughtError() { throw error; } } - function hasCaughtError() { return hasError; } - function clearCaughtError() { if (hasError) { var error = caughtError; @@ -19702,1994 +19471,1347 @@ function clearCaughtError() { caughtError = null; return error; } else { - (function () { + { { - { - throw ReactError(Error('clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.')); - } + throw Error( "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." ); } - })(); - } -} - -/** - * Similar to invariant but only logs a warning if the condition is not met. - * This can be used to log issues in development environments in critical - * paths. Removing the logging code for production environments will keep the - * same logic and follow the same code paths. - */ - -var warningWithoutStack = function () {}; - -{ - warningWithoutStack = function (condition, format) { - for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { - args[_key - 2] = arguments[_key]; - } - - if (format === undefined) { - throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument'); - } - if (args.length > 8) { - // Check before the condition to catch violations early. - throw new Error('warningWithoutStack() currently supports at most 8 arguments.'); - } - if (condition) { - return; - } - if (typeof console !== 'undefined') { - var argsWithFormat = args.map(function (item) { - return '' + item; - }); - argsWithFormat.unshift('Warning: ' + format); - - // We intentionally don't use spread (or .apply) directly because it - // breaks IE9: https://github.com/facebook/react/issues/13610 - Function.prototype.apply.call(console.error, console, argsWithFormat); } - try { - // --- Welcome to debugging React --- - // This error was thrown as a convenience so that you can use this stack - // to find the callsite that caused this warning to fire. - var argIndex = 0; - var message = 'Warning: ' + format.replace(/%s/g, function () { - return args[argIndex++]; - }); - throw new Error(message); - } catch (x) {} - }; + } } -var warningWithoutStack$1 = warningWithoutStack; - var getFiberCurrentPropsFromNode = null; var getInstanceFromNode = null; var getNodeFromInstance = null; - function setComponentTree(getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, getNodeFromInstanceImpl) { getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl; getInstanceFromNode = getInstanceFromNodeImpl; getNodeFromInstance = getNodeFromInstanceImpl; + { - !(getNodeFromInstance && getInstanceFromNode) ? warningWithoutStack$1(false, 'EventPluginUtils.setComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0; + if (!getNodeFromInstance || !getInstanceFromNode) { + error('EventPluginUtils.setComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.'); + } } } +var validateEventDispatches; -var validateEventDispatches = void 0; { validateEventDispatches = function (event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; - var listenersIsArr = Array.isArray(dispatchListeners); var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; - var instancesIsArr = Array.isArray(dispatchInstances); var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; - !(instancesIsArr === listenersIsArr && instancesLen === listenersLen) ? warningWithoutStack$1(false, 'EventPluginUtils: Invalid `event`.') : void 0; + if (instancesIsArr !== listenersIsArr || instancesLen !== listenersLen) { + error('EventPluginUtils: Invalid `event`.'); + } }; } - /** * Dispatch the event to the listener. * @param {SyntheticEvent} event SyntheticEvent to handle * @param {function} listener Application-level callback * @param {*} inst Internal component instance */ + + function executeDispatch(event, listener, inst) { var type = event.type || 'unknown-event'; event.currentTarget = getNodeFromInstance(inst); invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event); event.currentTarget = null; } - /** * Standard/simple iteration through an event's collected dispatches. */ + function executeDispatchesInOrder(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; + { validateEventDispatches(event); } + if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; - } - // Listeners and Instances are two parallel arrays that are always in sync. + } // Listeners and Instances are two parallel arrays that are always in sync. + + executeDispatch(event, dispatchListeners[i], dispatchInstances[i]); } } else if (dispatchListeners) { executeDispatch(event, dispatchListeners, dispatchInstances); } + event._dispatchListeners = null; event._dispatchInstances = null; } -/** - * @see executeDispatchesInOrderStopAtTrueImpl - */ +var FunctionComponent = 0; +var ClassComponent = 1; +var IndeterminateComponent = 2; // Before we know whether it is function or class +var HostRoot = 3; // Root of a host tree. Could be nested inside another node. -/** - * Execution of a "direct" dispatch - there must be at most one dispatch - * accumulated on the event or it is considered an error. It doesn't really make - * sense for an event with multiple dispatches (bubbled) to keep track of the - * return values at each dispatch execution, but it does tend to make sense when - * dealing with "direct" dispatches. - * - * @return {*} The return value of executing the single dispatch. - */ +var HostPortal = 4; // A subtree. Could be an entry point to a different renderer. +var HostComponent = 5; +var HostText = 6; +var Fragment = 7; +var Mode = 8; +var ContextConsumer = 9; +var ContextProvider = 10; +var ForwardRef = 11; +var Profiler = 12; +var SuspenseComponent = 13; +var MemoComponent = 14; +var SimpleMemoComponent = 15; +var LazyComponent = 16; +var IncompleteClassComponent = 17; +var DehydratedFragment = 18; +var SuspenseListComponent = 19; +var FundamentalComponent = 20; +var ScopeComponent = 21; +var Block = 22; /** - * @param {SyntheticEvent} event - * @return {boolean} True iff number of dispatches accumulated is greater than 0. + * Injectable ordering of event plugins. + */ +var eventPluginOrder = null; +/** + * Injectable mapping from names to event plugin modules. */ +var namesToPlugins = {}; /** - * Accumulates items that must not be null or undefined into the first one. This - * is used to conserve memory by avoiding array allocations, and thus sacrifices - * API cleanness. Since `current` can be null before being passed in and not - * null after this function, make sure to assign it back to `current`: - * - * `a = accumulateInto(a, b);` - * - * This API should be sparingly used. Try `accumulate` for something cleaner. + * Recomputes the plugin list using the injected plugins and plugin ordering. * - * @return {*|array<*>} An accumulation of items. + * @private */ -function accumulateInto(current, next) { - (function () { - if (!(next != null)) { +function recomputePluginOrdering() { + if (!eventPluginOrder) { + // Wait until an `eventPluginOrder` is injected. + return; + } + + for (var pluginName in namesToPlugins) { + var pluginModule = namesToPlugins[pluginName]; + var pluginIndex = eventPluginOrder.indexOf(pluginName); + + if (!(pluginIndex > -1)) { { - throw ReactError(Error('accumulateInto(...): Accumulated items must not be null or undefined.')); + throw Error( "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + pluginName + "`." ); } } - })(); - - if (current == null) { - return next; - } - // Both are not empty. Warning: Never call x.concat(y) when you are not - // certain that x is an Array (x could be a string with concat method). - if (Array.isArray(current)) { - if (Array.isArray(next)) { - current.push.apply(current, next); - return current; + if (plugins[pluginIndex]) { + continue; } - current.push(next); - return current; - } - if (Array.isArray(next)) { - // A bit too dangerous to mutate `next`. - return [current].concat(next); - } + if (!pluginModule.extractEvents) { + { + throw Error( "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + pluginName + "` does not." ); + } + } - return [current, next]; -} + plugins[pluginIndex] = pluginModule; + var publishedEvents = pluginModule.eventTypes; -/** - * @param {array} arr an "accumulation" of items which is either an Array or - * a single item. Useful when paired with the `accumulate` module. This is a - * simple utility that allows us to reason about a collection of items, but - * handling the case when there is exactly one item (and we do not need to - * allocate an array). - * @param {function} cb Callback invoked with each element or a collection. - * @param {?} [scope] Scope used as `this` in a callback. - */ -function forEachAccumulated(arr, cb, scope) { - if (Array.isArray(arr)) { - arr.forEach(cb, scope); - } else if (arr) { - cb.call(scope, arr); + for (var eventName in publishedEvents) { + if (!publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName)) { + { + throw Error( "EventPluginRegistry: Failed to publish event `" + eventName + "` for plugin `" + pluginName + "`." ); + } + } + } } } - -/** - * Internal queue of events that have accumulated their dispatches and are - * waiting to have their dispatches executed. - */ -var eventQueue = null; - /** - * Dispatches an event and releases it back into the pool, unless persistent. + * Publishes an event so that it can be dispatched by the supplied plugin. * - * @param {?object} event Synthetic event to be dispatched. + * @param {object} dispatchConfig Dispatch configuration for the event. + * @param {object} PluginModule Plugin publishing the event. + * @return {boolean} True if the event was successfully published. * @private */ -var executeDispatchesAndRelease = function (event) { - if (event) { - executeDispatchesInOrder(event); - if (!event.isPersistent()) { - event.constructor.release(event); + +function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { + if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) { + { + throw Error( "EventPluginRegistry: More than one plugin attempted to publish the same event name, `" + eventName + "`." ); } } -}; -var executeDispatchesAndReleaseTopLevel = function (e) { - return executeDispatchesAndRelease(e); -}; -function runEventsInBatch(events) { - if (events !== null) { - eventQueue = accumulateInto(eventQueue, events); - } + eventNameDispatchConfigs[eventName] = dispatchConfig; + var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; - // Set `eventQueue` to null before processing it so that we can tell if more - // events get enqueued while processing. - var processingEventQueue = eventQueue; - eventQueue = null; + if (phasedRegistrationNames) { + for (var phaseName in phasedRegistrationNames) { + if (phasedRegistrationNames.hasOwnProperty(phaseName)) { + var phasedRegistrationName = phasedRegistrationNames[phaseName]; + publishRegistrationName(phasedRegistrationName, pluginModule, eventName); + } + } - if (!processingEventQueue) { - return; + return true; + } else if (dispatchConfig.registrationName) { + publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName); + return true; } - forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); - (function () { - if (!!eventQueue) { - { - throw ReactError(Error('processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.')); - } - } - })(); - // This would be a good time to rethrow if any of the event handlers threw. - rethrowCaughtError(); + return false; } +/** + * Publishes a registration name that is used to identify dispatched events. + * + * @param {string} registrationName Registration name to add. + * @param {object} PluginModule Plugin publishing the event. + * @private + */ -function isInteractive(tag) { - return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea'; -} -function shouldPreventMouseEvent(name, type, props) { - switch (name) { - case 'onClick': - case 'onClickCapture': - case 'onDoubleClick': - case 'onDoubleClickCapture': - case 'onMouseDown': - case 'onMouseDownCapture': - case 'onMouseMove': - case 'onMouseMoveCapture': - case 'onMouseUp': - case 'onMouseUpCapture': - return !!(props.disabled && isInteractive(type)); - default: - return false; +function publishRegistrationName(registrationName, pluginModule, eventName) { + if (!!registrationNameModules[registrationName]) { + { + throw Error( "EventPluginRegistry: More than one plugin attempted to publish the same registration name, `" + registrationName + "`." ); + } } -} + registrationNameModules[registrationName] = pluginModule; + registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; + + { + var lowerCasedName = registrationName.toLowerCase(); + possibleRegistrationNames[lowerCasedName] = registrationName; + + if (registrationName === 'onDoubleClick') { + possibleRegistrationNames.ondblclick = registrationName; + } + } +} /** - * This is a unified interface for event plugins to be installed and configured. - * - * Event plugins can implement the following properties: - * - * `extractEvents` {function(string, DOMEventTarget, string, object): *} - * Required. When a top-level event is fired, this method is expected to - * extract synthetic events that will in turn be queued and dispatched. - * - * `eventTypes` {object} - * Optional, plugins that fire events must publish a mapping of registration - * names that are used to register listeners. Values of this mapping must - * be objects that contain `registrationName` or `phasedRegistrationNames`. - * - * `executeDispatch` {function(object, function, string)} - * Optional, allows plugins to override how an event gets dispatched. By - * default, the listener is simply invoked. - * - * Each plugin that is injected into `EventsPluginHub` is immediately operable. - * - * @public + * Registers plugins so that they can extract and dispatch events. */ /** - * Methods for injecting dependencies. + * Ordered list of injected plugins. */ -var injection = { - /** - * @param {array} InjectedEventPluginOrder - * @public - */ - injectEventPluginOrder: injectEventPluginOrder, - /** - * @param {object} injectedNamesToPlugins Map from names to plugin modules. - */ - injectEventPluginsByName: injectEventPluginsByName -}; +var plugins = []; /** - * @param {object} inst The instance, which is the source of events. - * @param {string} registrationName Name of listener (e.g. `onClick`). - * @return {?function} The stored callback. + * Mapping from event name to dispatch config */ -function getListener(inst, registrationName) { - var listener = void 0; - // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not - // live here; needs to be moved to a better place soon - var stateNode = inst.stateNode; - if (!stateNode) { - // Work in progress (ex: onload events in incremental mode). - return null; - } - var props = getFiberCurrentPropsFromNode(stateNode); - if (!props) { - // Work in progress. - return null; - } - listener = props[registrationName]; - if (shouldPreventMouseEvent(registrationName, inst.type, props)) { - return null; - } - (function () { - if (!(!listener || typeof listener === 'function')) { - { - throw ReactError(Error('Expected `' + registrationName + '` listener to be a function, instead got a value of `' + typeof listener + '` type.')); - } - } - })(); - return listener; -} +var eventNameDispatchConfigs = {}; +/** + * Mapping from registration name to plugin module + */ +var registrationNameModules = {}; /** - * Allows registered plugins an opportunity to extract events from top-level - * native browser events. + * Mapping from registration name to event name + */ + +var registrationNameDependencies = {}; +/** + * Mapping from lowercase registration names to the properly cased version, + * used to warn in the case of missing event handlers. Available + * only in true. + * @type {Object} + */ + +var possibleRegistrationNames = {} ; // Trust the developer to only use possibleRegistrationNames in true + +/** + * Injects an ordering of plugins (by plugin name). This allows the ordering + * to be decoupled from injection of the actual plugins so that ordering is + * always deterministic regardless of packaging, on-the-fly injection, etc. * - * @return {*} An accumulation of synthetic events. + * @param {array} InjectedEventPluginOrder * @internal */ -function extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget) { - var events = null; - for (var i = 0; i < plugins.length; i++) { - // Not every plugin in the ordering may be loaded at runtime. - var possiblePlugin = plugins[i]; - if (possiblePlugin) { - var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); - if (extractedEvents) { - events = accumulateInto(events, extractedEvents); - } - } - } - return events; -} - -function runExtractedPluginEventsInBatch(topLevelType, targetInst, nativeEvent, nativeEventTarget) { - var events = extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); - runEventsInBatch(events); -} -var FunctionComponent = 0; -var ClassComponent = 1; -var IndeterminateComponent = 2; // Before we know whether it is function or class -var HostRoot = 3; // Root of a host tree. Could be nested inside another node. -var HostPortal = 4; // A subtree. Could be an entry point to a different renderer. -var HostComponent = 5; -var HostText = 6; -var Fragment = 7; -var Mode = 8; -var ContextConsumer = 9; -var ContextProvider = 10; -var ForwardRef = 11; -var Profiler = 12; -var SuspenseComponent = 13; -var MemoComponent = 14; -var SimpleMemoComponent = 15; -var LazyComponent = 16; -var IncompleteClassComponent = 17; -var DehydratedSuspenseComponent = 18; -var SuspenseListComponent = 19; -var FundamentalComponent = 20; +function injectEventPluginOrder(injectedEventPluginOrder) { + if (!!eventPluginOrder) { + { + throw Error( "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." ); + } + } // Clone the ordering so it cannot be dynamically mutated. -var randomKey = Math.random().toString(36).slice(2); -var internalInstanceKey = '__reactInternalInstance$' + randomKey; -var internalEventHandlersKey = '__reactEventHandlers$' + randomKey; -function precacheFiberNode(hostInst, node) { - node[internalInstanceKey] = hostInst; + eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); + recomputePluginOrdering(); } - /** - * Given a DOM node, return the closest ReactDOMComponent or - * ReactDOMTextComponent instance ancestor. + * Injects plugins to be used by plugin event system. The plugin names must be + * in the ordering injected by `injectEventPluginOrder`. + * + * Plugins can be injected as part of page initialization or on-the-fly. + * + * @param {object} injectedNamesToPlugins Map from names to plugin modules. + * @internal */ -function getClosestInstanceFromNode(node) { - if (node[internalInstanceKey]) { - return node[internalInstanceKey]; - } - while (!node[internalInstanceKey]) { - if (node.parentNode) { - node = node.parentNode; - } else { - // Top of the tree. This node must not be part of a React tree (or is - // unmounted, potentially). - return null; +function injectEventPluginsByName(injectedNamesToPlugins) { + var isOrderingDirty = false; + + for (var pluginName in injectedNamesToPlugins) { + if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { + continue; } - } - var inst = node[internalInstanceKey]; - if (inst.tag === HostComponent || inst.tag === HostText) { - // In Fiber, this will always be the deepest root. - return inst; - } + var pluginModule = injectedNamesToPlugins[pluginName]; - return null; -} + if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) { + if (!!namesToPlugins[pluginName]) { + { + throw Error( "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + pluginName + "`." ); + } + } -/** - * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent - * instance, or null if the node was not rendered by this React. - */ -function getInstanceFromNode$1(node) { - var inst = node[internalInstanceKey]; - if (inst) { - if (inst.tag === HostComponent || inst.tag === HostText) { - return inst; - } else { - return null; + namesToPlugins[pluginName] = pluginModule; + isOrderingDirty = true; } } - return null; + + if (isOrderingDirty) { + recomputePluginOrdering(); + } } -/** - * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding - * DOM node. - */ -function getNodeFromInstance$1(inst) { - if (inst.tag === HostComponent || inst.tag === HostText) { - // In Fiber this, is just the state node right now. We assume it will be - // a host component or host text. - return inst.stateNode; +var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined'); + +var PLUGIN_EVENT_SYSTEM = 1; +var IS_REPLAYED = 1 << 5; +var IS_FIRST_ANCESTOR = 1 << 6; + +var restoreImpl = null; +var restoreTarget = null; +var restoreQueue = null; + +function restoreStateOfTarget(target) { + // We perform this translation at the end of the event loop so that we + // always receive the correct fiber here + var internalInstance = getInstanceFromNode(target); + + if (!internalInstance) { + // Unmounted + return; } - // Without this first invariant, passing a non-DOM-component triggers the next - // invariant for a missing parent, which is super confusing. - (function () { + if (!(typeof restoreImpl === 'function')) { { - { - throw ReactError(Error('getNodeFromInstance: Invalid argument.')); - } + throw Error( "setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue." ); } - })(); -} + } -function getFiberCurrentPropsFromNode$1(node) { - return node[internalEventHandlersKey] || null; -} + var stateNode = internalInstance.stateNode; // Guard against Fiber being unmounted. -function updateFiberProps(node, props) { - node[internalEventHandlersKey] = props; -} + if (stateNode) { + var _props = getFiberCurrentPropsFromNode(stateNode); -function getParent(inst) { - do { - inst = inst.return; - // TODO: If this is a HostRoot we might want to bail out. - // That is depending on if we want nested subtrees (layers) to bubble - // events to their parent. We could also go through parentNode on the - // host node but that wouldn't work for React Native and doesn't let us - // do the portal feature. - } while (inst && inst.tag !== HostComponent); - if (inst) { - return inst; + restoreImpl(internalInstance.stateNode, internalInstance.type, _props); } - return null; } -/** - * Return the lowest common ancestor of A and B, or null if they are in - * different trees. - */ -function getLowestCommonAncestor(instA, instB) { - var depthA = 0; - for (var tempA = instA; tempA; tempA = getParent(tempA)) { - depthA++; - } - var depthB = 0; - for (var tempB = instB; tempB; tempB = getParent(tempB)) { - depthB++; +function setRestoreImplementation(impl) { + restoreImpl = impl; +} +function enqueueStateRestore(target) { + if (restoreTarget) { + if (restoreQueue) { + restoreQueue.push(target); + } else { + restoreQueue = [target]; + } + } else { + restoreTarget = target; } - - // If A is deeper, crawl up. - while (depthA - depthB > 0) { - instA = getParent(instA); - depthA--; +} +function needsStateRestore() { + return restoreTarget !== null || restoreQueue !== null; +} +function restoreStateIfNeeded() { + if (!restoreTarget) { + return; } - // If B is deeper, crawl up. - while (depthB - depthA > 0) { - instB = getParent(instB); - depthB--; - } + var target = restoreTarget; + var queuedTargets = restoreQueue; + restoreTarget = null; + restoreQueue = null; + restoreStateOfTarget(target); - // Walk in lockstep until we find a match. - var depth = depthA; - while (depth--) { - if (instA === instB || instA === instB.alternate) { - return instA; + if (queuedTargets) { + for (var i = 0; i < queuedTargets.length; i++) { + restoreStateOfTarget(queuedTargets[i]); } - instA = getParent(instA); - instB = getParent(instB); } - return null; } -/** - * Return if A is an ancestor of B. - */ +var enableProfilerTimer = true; // Trace which interactions trigger each commit. +var enableDeprecatedFlareAPI = false; // Experimental Host Component support. -/** - * Return the parent instance of the passed-in instance. - */ +var enableFundamentalAPI = false; // Experimental Scope support. +var warnAboutStringRefs = false; +// the renderer. Such as when we're dispatching events or if third party +// libraries need to call batchedUpdates. Eventually, this API will go away when +// everything is batched by default. We'll then have a similar API to opt-out of +// scheduled work and instead do synchronous work. +// Defaults -/** - * Simulates the traversal of a two-phase, capture/bubble event dispatch. - */ -function traverseTwoPhase(inst, fn, arg) { - var path = []; - while (inst) { - path.push(inst); - inst = getParent(inst); - } - var i = void 0; - for (i = path.length; i-- > 0;) { - fn(path[i], 'captured', arg); - } - for (i = 0; i < path.length; i++) { - fn(path[i], 'bubbled', arg); - } -} +var batchedUpdatesImpl = function (fn, bookkeeping) { + return fn(bookkeeping); +}; -/** - * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that - * should would receive a `mouseEnter` or `mouseLeave` event. - * - * Does not invoke the callback on the nearest common ancestor because nothing - * "entered" or "left" that element. - */ -function traverseEnterLeave(from, to, fn, argFrom, argTo) { - var common = from && to ? getLowestCommonAncestor(from, to) : null; - var pathFrom = []; - while (true) { - if (!from) { - break; - } - if (from === common) { - break; - } - var alternate = from.alternate; - if (alternate !== null && alternate === common) { - break; - } - pathFrom.push(from); - from = getParent(from); - } - var pathTo = []; - while (true) { - if (!to) { - break; - } - if (to === common) { - break; - } - var _alternate = to.alternate; - if (_alternate !== null && _alternate === common) { - break; - } - pathTo.push(to); - to = getParent(to); - } - for (var i = 0; i < pathFrom.length; i++) { - fn(pathFrom[i], 'bubbled', argFrom); - } - for (var _i = pathTo.length; _i-- > 0;) { - fn(pathTo[_i], 'captured', argTo); +var discreteUpdatesImpl = function (fn, a, b, c, d) { + return fn(a, b, c, d); +}; + +var flushDiscreteUpdatesImpl = function () {}; + +var batchedEventUpdatesImpl = batchedUpdatesImpl; +var isInsideEventHandler = false; +var isBatchingEventUpdates = false; + +function finishEventHandler() { + // Here we wait until all updates have propagated, which is important + // when using controlled components within layers: + // https://github.com/facebook/react/issues/1698 + // Then we restore state of any controlled component. + var controlledComponentsHavePendingUpdates = needsStateRestore(); + + if (controlledComponentsHavePendingUpdates) { + // If a controlled event was fired, we may need to restore the state of + // the DOM node back to the controlled value. This is necessary when React + // bails out of the update without touching the DOM. + flushDiscreteUpdatesImpl(); + restoreStateIfNeeded(); } } -/** - * Some event types have a notion of different registration names for different - * "phases" of propagation. This finds listeners by a given phase. - */ -function listenerAtPhase(inst, event, propagationPhase) { - var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; - return getListener(inst, registrationName); -} +function batchedUpdates(fn, bookkeeping) { + if (isInsideEventHandler) { + // If we are currently inside another batch, we need to wait until it + // fully completes before restoring state. + return fn(bookkeeping); + } -/** - * A small set of propagation patterns, each of which will accept a small amount - * of information, and generate a set of "dispatch ready event objects" - which - * are sets of events that have already been annotated with a set of dispatched - * listener functions/ids. The API is designed this way to discourage these - * propagation strategies from actually executing the dispatches, since we - * always want to collect the entire set of dispatches before executing even a - * single one. - */ + isInsideEventHandler = true; -/** - * Tags a `SyntheticEvent` with dispatched listeners. Creating this function - * here, allows us to not have to bind or create functions for each event. - * Mutating the event's members allows us to not have to create a wrapping - * "dispatch" object that pairs the event with the listener. - */ -function accumulateDirectionalDispatches(inst, phase, event) { - { - !inst ? warningWithoutStack$1(false, 'Dispatching inst must not be null') : void 0; - } - var listener = listenerAtPhase(inst, event, phase); - if (listener) { - event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); - event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); + try { + return batchedUpdatesImpl(fn, bookkeeping); + } finally { + isInsideEventHandler = false; + finishEventHandler(); } } +function batchedEventUpdates(fn, a, b) { + if (isBatchingEventUpdates) { + // If we are currently inside another batch, we need to wait until it + // fully completes before restoring state. + return fn(a, b); + } -/** - * Collect dispatches (must be entirely collected before dispatching - see unit - * tests). Lazily allocate the array to conserve memory. We must loop through - * each event and perform the traversal for each one. We cannot perform a - * single traversal for the entire collection of events because each event may - * have a different target. - */ -function accumulateTwoPhaseDispatchesSingle(event) { - if (event && event.dispatchConfig.phasedRegistrationNames) { - traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); + isBatchingEventUpdates = true; + + try { + return batchedEventUpdatesImpl(fn, a, b); + } finally { + isBatchingEventUpdates = false; + finishEventHandler(); } -} +} // This is for the React Flare event system +function discreteUpdates(fn, a, b, c, d) { + var prevIsInsideEventHandler = isInsideEventHandler; + isInsideEventHandler = true; -/** - * Accumulates without regard to direction, does not look for phased - * registration names. Same as `accumulateDirectDispatchesSingle` but without - * requiring that the `dispatchMarker` be the same as the dispatched ID. - */ -function accumulateDispatches(inst, ignoredDirection, event) { - if (inst && event && event.dispatchConfig.registrationName) { - var registrationName = event.dispatchConfig.registrationName; - var listener = getListener(inst, registrationName); - if (listener) { - event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); - event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); + try { + return discreteUpdatesImpl(fn, a, b, c, d); + } finally { + isInsideEventHandler = prevIsInsideEventHandler; + + if (!isInsideEventHandler) { + finishEventHandler(); } } } - -/** - * Accumulates dispatches on an `SyntheticEvent`, but only for the - * `dispatchMarker`. - * @param {SyntheticEvent} event - */ -function accumulateDirectDispatchesSingle(event) { - if (event && event.dispatchConfig.registrationName) { - accumulateDispatches(event._targetInst, null, event); +function flushDiscreteUpdatesIfNeeded(timeStamp) { + // event.timeStamp isn't overly reliable due to inconsistencies in + // how different browsers have historically provided the time stamp. + // Some browsers provide high-resolution time stamps for all events, + // some provide low-resolution time stamps for all events. FF < 52 + // even mixes both time stamps together. Some browsers even report + // negative time stamps or time stamps that are 0 (iOS9) in some cases. + // Given we are only comparing two time stamps with equality (!==), + // we are safe from the resolution differences. If the time stamp is 0 + // we bail-out of preventing the flush, which can affect semantics, + // such as if an earlier flush removes or adds event listeners that + // are fired in the subsequent flush. However, this is the same + // behaviour as we had before this change, so the risks are low. + if (!isInsideEventHandler && (!enableDeprecatedFlareAPI )) { + flushDiscreteUpdatesImpl(); } } - -function accumulateTwoPhaseDispatches(events) { - forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); +function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushDiscreteUpdatesImpl, _batchedEventUpdatesImpl) { + batchedUpdatesImpl = _batchedUpdatesImpl; + discreteUpdatesImpl = _discreteUpdatesImpl; + flushDiscreteUpdatesImpl = _flushDiscreteUpdatesImpl; + batchedEventUpdatesImpl = _batchedEventUpdatesImpl; } +var DiscreteEvent = 0; +var UserBlockingEvent = 1; +var ContinuousEvent = 2; +// A reserved attribute. +// It is handled by React separately and shouldn't be written to the DOM. +var RESERVED = 0; // A simple string attribute. +// Attributes that aren't in the whitelist are presumed to have this type. -function accumulateEnterLeaveDispatches(leave, enter, from, to) { - traverseEnterLeave(from, to, accumulateDispatches, leave, enter); -} +var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called +// "enumerated" attributes with "true" and "false" as possible values. +// When true, it should be set to a "true" string. +// When false, it should be set to a "false" string. -function accumulateDirectDispatches(events) { - forEachAccumulated(events, accumulateDirectDispatchesSingle); -} +var BOOLEANISH_STRING = 2; // A real boolean attribute. +// When true, it should be present (set either to an empty string or its name). +// When false, it should be omitted. -var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined'); +var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value. +// When true, it should be present (set either to an empty string or its name). +// When false, it should be omitted. +// For any other value, should be present with that value. -// Do not use the below two methods directly! -// Instead use constants exported from DOMTopLevelEventTypes in ReactDOM. -// (It is the only module that is allowed to access these methods.) +var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric. +// When falsy, it should be removed. -function unsafeCastStringToDOMTopLevelType(topLevelType) { - return topLevelType; -} +var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric. +// When falsy, it should be removed. -function unsafeCastDOMTopLevelTypeToString(topLevelType) { - return topLevelType; -} +var POSITIVE_NUMERIC = 6; -/** - * Generate a mapping of standard vendor prefixes using the defined style property and event name. - * - * @param {string} styleProp - * @param {string} eventName - * @returns {object} - */ -function makePrefixMap(styleProp, eventName) { - var prefixes = {}; +/* eslint-disable max-len */ +var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; +/* eslint-enable max-len */ - prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); - prefixes['Webkit' + styleProp] = 'webkit' + eventName; - prefixes['Moz' + styleProp] = 'moz' + eventName; +var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; +var ROOT_ATTRIBUTE_NAME = 'data-reactroot'; +var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$'); +var hasOwnProperty = Object.prototype.hasOwnProperty; +var illegalAttributeNameCache = {}; +var validatedAttributeNameCache = {}; +function isAttributeNameSafe(attributeName) { + if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) { + return true; + } - return prefixes; -} + if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) { + return false; + } -/** - * A list of event names to a configurable list of vendor prefixes. - */ -var vendorPrefixes = { - animationend: makePrefixMap('Animation', 'AnimationEnd'), - animationiteration: makePrefixMap('Animation', 'AnimationIteration'), - animationstart: makePrefixMap('Animation', 'AnimationStart'), - transitionend: makePrefixMap('Transition', 'TransitionEnd') -}; + if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { + validatedAttributeNameCache[attributeName] = true; + return true; + } -/** - * Event names that have already been detected and prefixed (if applicable). - */ -var prefixedEventNames = {}; - -/** - * Element to check for prefixes on. - */ -var style = {}; - -/** - * Bootstrap if a DOM exists. - */ -if (canUseDOM) { - style = document.createElement('div').style; + illegalAttributeNameCache[attributeName] = true; - // On some platforms, in particular some releases of Android 4.x, - // the un-prefixed "animation" and "transition" properties are defined on the - // style object but the events that fire will still be prefixed, so we need - // to check if the un-prefixed events are usable, and if not remove them from the map. - if (!('AnimationEvent' in window)) { - delete vendorPrefixes.animationend.animation; - delete vendorPrefixes.animationiteration.animation; - delete vendorPrefixes.animationstart.animation; + { + error('Invalid attribute name: `%s`', attributeName); } - // Same as above - if (!('TransitionEvent' in window)) { - delete vendorPrefixes.transitionend.transition; - } + return false; } - -/** - * Attempts to determine the correct vendor prefixed event name. - * - * @param {string} eventName - * @returns {string} - */ -function getVendorPrefixedEventName(eventName) { - if (prefixedEventNames[eventName]) { - return prefixedEventNames[eventName]; - } else if (!vendorPrefixes[eventName]) { - return eventName; +function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) { + if (propertyInfo !== null) { + return propertyInfo.type === RESERVED; } - var prefixMap = vendorPrefixes[eventName]; - - for (var styleProp in prefixMap) { - if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { - return prefixedEventNames[eventName] = prefixMap[styleProp]; - } + if (isCustomComponentTag) { + return false; } - return eventName; -} - -/** - * To identify top level events in ReactDOM, we use constants defined by this - * module. This is the only module that uses the unsafe* methods to express - * that the constants actually correspond to the browser event names. This lets - * us save some bundle size by avoiding a top level type -> event name map. - * The rest of ReactDOM code should import top level types from this file. - */ -var TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort'); -var TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend')); -var TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration')); -var TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart')); -var TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur'); -var TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay'); -var TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough'); -var TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel'); -var TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change'); -var TOP_CLICK = unsafeCastStringToDOMTopLevelType('click'); -var TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close'); -var TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend'); -var TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType('compositionstart'); -var TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType('compositionupdate'); -var TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu'); -var TOP_COPY = unsafeCastStringToDOMTopLevelType('copy'); -var TOP_CUT = unsafeCastStringToDOMTopLevelType('cut'); -var TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick'); -var TOP_AUX_CLICK = unsafeCastStringToDOMTopLevelType('auxclick'); -var TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag'); -var TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend'); -var TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter'); -var TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit'); -var TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave'); -var TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover'); -var TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart'); -var TOP_DROP = unsafeCastStringToDOMTopLevelType('drop'); -var TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange'); -var TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied'); -var TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted'); -var TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended'); -var TOP_ERROR = unsafeCastStringToDOMTopLevelType('error'); -var TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus'); -var TOP_GOT_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('gotpointercapture'); -var TOP_INPUT = unsafeCastStringToDOMTopLevelType('input'); -var TOP_INVALID = unsafeCastStringToDOMTopLevelType('invalid'); -var TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown'); -var TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress'); -var TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup'); -var TOP_LOAD = unsafeCastStringToDOMTopLevelType('load'); -var TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart'); -var TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata'); -var TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata'); -var TOP_LOST_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('lostpointercapture'); -var TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown'); -var TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove'); -var TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout'); -var TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover'); -var TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup'); -var TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste'); -var TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause'); -var TOP_PLAY = unsafeCastStringToDOMTopLevelType('play'); -var TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing'); -var TOP_POINTER_CANCEL = unsafeCastStringToDOMTopLevelType('pointercancel'); -var TOP_POINTER_DOWN = unsafeCastStringToDOMTopLevelType('pointerdown'); - - -var TOP_POINTER_MOVE = unsafeCastStringToDOMTopLevelType('pointermove'); -var TOP_POINTER_OUT = unsafeCastStringToDOMTopLevelType('pointerout'); -var TOP_POINTER_OVER = unsafeCastStringToDOMTopLevelType('pointerover'); -var TOP_POINTER_UP = unsafeCastStringToDOMTopLevelType('pointerup'); -var TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress'); -var TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange'); -var TOP_RESET = unsafeCastStringToDOMTopLevelType('reset'); -var TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll'); -var TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked'); -var TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking'); -var TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange'); -var TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled'); -var TOP_SUBMIT = unsafeCastStringToDOMTopLevelType('submit'); -var TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend'); -var TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput'); -var TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate'); -var TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle'); -var TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel'); -var TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend'); -var TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove'); -var TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart'); -var TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend')); -var TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange'); -var TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting'); -var TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel'); - -// List of events that need to be individually attached to media elements. -// Note that events in this list will *not* be listened to at the top level -// unless they're explicitly whitelisted in `ReactBrowserEventEmitter.listenTo`. -var mediaEventTypes = [TOP_ABORT, TOP_CAN_PLAY, TOP_CAN_PLAY_THROUGH, TOP_DURATION_CHANGE, TOP_EMPTIED, TOP_ENCRYPTED, TOP_ENDED, TOP_ERROR, TOP_LOADED_DATA, TOP_LOADED_METADATA, TOP_LOAD_START, TOP_PAUSE, TOP_PLAY, TOP_PLAYING, TOP_PROGRESS, TOP_RATE_CHANGE, TOP_SEEKED, TOP_SEEKING, TOP_STALLED, TOP_SUSPEND, TOP_TIME_UPDATE, TOP_VOLUME_CHANGE, TOP_WAITING]; + if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) { + return true; + } -function getRawEventName(topLevelType) { - return unsafeCastDOMTopLevelTypeToString(topLevelType); + return false; } +function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { + if (propertyInfo !== null && propertyInfo.type === RESERVED) { + return false; + } -/** - * These variables store information about text content of a target node, - * allowing comparison of content before and after a given event. - * - * Identify the node where selection currently begins, then observe - * both its text content and its current position in the DOM. Since the - * browser may natively replace the target node during composition, we can - * use its position to find its replacement. - * - * - */ + switch (typeof value) { + case 'function': // $FlowIssue symbol is perfectly valid here -var root = null; -var startText = null; -var fallbackText = null; + case 'symbol': + // eslint-disable-line + return true; -function initialize(nativeEventTarget) { - root = nativeEventTarget; - startText = getText(); - return true; -} + case 'boolean': + { + if (isCustomComponentTag) { + return false; + } -function reset() { - root = null; - startText = null; - fallbackText = null; -} + if (propertyInfo !== null) { + return !propertyInfo.acceptsBooleans; + } else { + var prefix = name.toLowerCase().slice(0, 5); + return prefix !== 'data-' && prefix !== 'aria-'; + } + } -function getData() { - if (fallbackText) { - return fallbackText; + default: + return false; } - - var start = void 0; - var startValue = startText; - var startLength = startValue.length; - var end = void 0; - var endValue = getText(); - var endLength = endValue.length; - - for (start = 0; start < startLength; start++) { - if (startValue[start] !== endValue[start]) { - break; - } +} +function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) { + if (value === null || typeof value === 'undefined') { + return true; } - var minEnd = startLength - start; - for (end = 1; end <= minEnd; end++) { - if (startValue[startLength - end] !== endValue[endLength - end]) { - break; - } + if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) { + return true; } - var sliceTail = end > 1 ? 1 - end : undefined; - fallbackText = endValue.slice(start, sliceTail); - return fallbackText; -} - -function getText() { - if ('value' in root) { - return root.value; + if (isCustomComponentTag) { + return false; } - return root.textContent; -} -/* eslint valid-typeof: 0 */ + if (propertyInfo !== null) { + switch (propertyInfo.type) { + case BOOLEAN: + return !value; -var EVENT_POOL_SIZE = 10; + case OVERLOADED_BOOLEAN: + return value === false; -/** - * @interface Event - * @see http://www.w3.org/TR/DOM-Level-3-Events/ - */ -var EventInterface = { - type: null, - target: null, - // currentTarget is set when dispatching; no use in copying it here - currentTarget: function () { - return null; - }, - eventPhase: null, - bubbles: null, - cancelable: null, - timeStamp: function (event) { - return event.timeStamp || Date.now(); - }, - defaultPrevented: null, - isTrusted: null -}; + case NUMERIC: + return isNaN(value); -function functionThatReturnsTrue() { - return true; -} + case POSITIVE_NUMERIC: + return isNaN(value) || value < 1; + } + } -function functionThatReturnsFalse() { return false; } +function getPropertyInfo(name) { + return properties.hasOwnProperty(name) ? properties[name] : null; +} -/** - * Synthetic events are dispatched by event plugins, typically in response to a - * top-level event delegation handler. - * - * These systems should generally use pooling to reduce the frequency of garbage - * collection. The system should check `isPersistent` to determine whether the - * event should be released into the pool after being dispatched. Users that - * need a persisted event should invoke `persist`. - * - * Synthetic events (and subclasses) implement the DOM Level 3 Events API by - * normalizing browser quirks. Subclasses do not necessarily have to implement a - * DOM interface; custom application-specific events can also subclass this. - * - * @param {object} dispatchConfig Configuration used to dispatch this event. - * @param {*} targetInst Marker identifying the event target. - * @param {object} nativeEvent Native browser event. - * @param {DOMEventTarget} nativeEventTarget Target node. - */ -function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { - { - // these have a getter/setter for warnings - delete this.nativeEvent; - delete this.preventDefault; - delete this.stopPropagation; - delete this.isDefaultPrevented; - delete this.isPropagationStopped; - } +function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL) { + this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; + this.attributeName = attributeName; + this.attributeNamespace = attributeNamespace; + this.mustUseProperty = mustUseProperty; + this.propertyName = name; + this.type = type; + this.sanitizeURL = sanitizeURL; +} // When adding attributes to this list, be sure to also add them to +// the `possibleStandardNames` module to ensure casing and incorrect +// name warnings. - this.dispatchConfig = dispatchConfig; - this._targetInst = targetInst; - this.nativeEvent = nativeEvent; - var Interface = this.constructor.Interface; - for (var propName in Interface) { - if (!Interface.hasOwnProperty(propName)) { - continue; - } - { - delete this[propName]; // this has a getter/setter for warnings - } - var normalize = Interface[propName]; - if (normalize) { - this[propName] = normalize(nativeEvent); - } else { - if (propName === 'target') { - this.target = nativeEventTarget; - } else { - this[propName] = nativeEvent[propName]; - } - } - } +var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM. - var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; - if (defaultPrevented) { - this.isDefaultPrevented = functionThatReturnsTrue; - } else { - this.isDefaultPrevented = functionThatReturnsFalse; - } - this.isPropagationStopped = functionThatReturnsFalse; - return this; -} +var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular +// elements (not just inputs). Now that ReactDOMInput assigns to the +// defaultValue property -- do we need this? +'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style']; -_assign(SyntheticEvent.prototype, { - preventDefault: function () { - this.defaultPrevented = true; - var event = this.nativeEvent; - if (!event) { - return; - } +reservedProps.forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false); +}); // A few React string attributes have a different name. +// This is a mapping from React prop names to the attribute names. - if (event.preventDefault) { - event.preventDefault(); - } else if (typeof event.returnValue !== 'unknown') { - event.returnValue = false; - } - this.isDefaultPrevented = functionThatReturnsTrue; - }, +[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) { + var name = _ref[0], + attributeName = _ref[1]; + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, // attributeName + null, // attributeNamespace + false); +}); // These are "enumerated" HTML attributes that accept "true" and "false". +// In React, we let users pass `true` and `false` even though technically +// these aren't boolean attributes (they are coerced to strings). - stopPropagation: function () { - var event = this.nativeEvent; - if (!event) { - return; - } +['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty + name.toLowerCase(), // attributeName + null, // attributeNamespace + false); +}); // These are "enumerated" SVG attributes that accept "true" and "false". +// In React, we let users pass `true` and `false` even though technically +// these aren't boolean attributes (they are coerced to strings). +// Since these are SVG attributes, their attribute names are case-sensitive. - if (event.stopPropagation) { - event.stopPropagation(); - } else if (typeof event.cancelBubble !== 'unknown') { - // The ChangeEventPlugin registers a "propertychange" event for - // IE. This event does not support bubbling or cancelling, and - // any references to cancelBubble throw "Member not found". A - // typeof check of "unknown" circumvents this issue (and is also - // IE specific). - event.cancelBubble = true; - } +['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false); +}); // These are HTML boolean attributes. - this.isPropagationStopped = functionThatReturnsTrue; - }, +['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM +// on the client side because the browsers are inconsistent. Instead we call focus(). +'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata +'itemScope'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty + name.toLowerCase(), // attributeName + null, // attributeNamespace + false); +}); // These are the few React props that we set as DOM properties +// rather than attributes. These are all booleans. - /** - * We release all dispatched `SyntheticEvent`s after each event loop, adding - * them back into the pool. This allows a way to hold onto a reference that - * won't be added back into the pool. - */ - persist: function () { - this.isPersistent = functionThatReturnsTrue; - }, +['checked', // Note: `option.selected` is not updated if `select.multiple` is +// disabled with `removeAttribute`. We have special logic for handling this. +'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false); +}); // These are HTML attributes that are "overloaded booleans": they behave like +// booleans, but can also accept a string value. - /** - * Checks if this event should be released back into the pool. - * - * @return {boolean} True if this should not be released, false otherwise. - */ - isPersistent: functionThatReturnsFalse, +['capture', 'download' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false); +}); // These are HTML attributes that must be positive numbers. - /** - * `PooledClass` looks for `destructor` on each instance it releases. - */ - destructor: function () { - var Interface = this.constructor.Interface; - for (var propName in Interface) { - { - Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])); - } - } - this.dispatchConfig = null; - this._targetInst = null; - this.nativeEvent = null; - this.isDefaultPrevented = functionThatReturnsFalse; - this.isPropagationStopped = functionThatReturnsFalse; - this._dispatchListeners = null; - this._dispatchInstances = null; - { - Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null)); - Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse)); - Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse)); - Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {})); - Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {})); - } - } +['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false); +}); // These are HTML attributes that must be numbers. + +['rowSpan', 'start'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty + name.toLowerCase(), // attributeName + null, // attributeNamespace + false); }); +var CAMELIZE = /[\-\:]([a-z])/g; -SyntheticEvent.Interface = EventInterface; +var capitalize = function (token) { + return token[1].toUpperCase(); +}; // This is a list of all SVG attributes that need special casing, namespacing, +// or boolean value assignment. Regular attributes that just accept strings +// and have the same names are omitted, just like in the HTML whitelist. +// Some of these attributes can be hard to find. This list was created by +// scraping the MDN documentation. -/** - * Helper to reduce boilerplate when creating subclasses. - */ -SyntheticEvent.extend = function (Interface) { - var Super = this; - var E = function () {}; - E.prototype = Super.prototype; - var prototype = new E(); +['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, null, // attributeNamespace + false); +}); // String SVG attributes with the xlink namespace. - function Class() { - return Super.apply(this, arguments); - } - _assign(prototype, Class.prototype); - Class.prototype = prototype; - Class.prototype.constructor = Class; +['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, 'http://www.w3.org/1999/xlink', false); +}); // String SVG attributes with the xml namespace. - Class.Interface = _assign({}, Super.Interface, Interface); - Class.extend = Super.extend; - addEventPoolingTo(Class); +['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, 'http://www.w3.org/XML/1998/namespace', false); +}); // These attribute exists both in HTML and SVG. +// The attribute name is case-sensitive in SVG so we can't just use +// the React name like we do for attributes that exist only in HTML. - return Class; -}; +['tabIndex', 'crossOrigin'].forEach(function (attributeName) { + properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty + attributeName.toLowerCase(), // attributeName + null, // attributeNamespace + false); +}); // These attributes accept URLs. These must not allow javascript: URLS. +// These will also need to accept Trusted Types object in the future. -addEventPoolingTo(SyntheticEvent); +var xlinkHref = 'xlinkHref'; +properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty +'xlink:href', 'http://www.w3.org/1999/xlink', true); +['src', 'href', 'action', 'formAction'].forEach(function (attributeName) { + properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty + attributeName.toLowerCase(), // attributeName + null, // attributeNamespace + true); +}); -/** - * Helper to nullify syntheticEvent instance properties when destructing - * - * @param {String} propName - * @param {?object} getVal - * @return {object} defineProperty object - */ -function getPooledWarningPropertyDefinition(propName, getVal) { - var isFunction = typeof getVal === 'function'; - return { - configurable: true, - set: set, - get: get - }; +var ReactDebugCurrentFrame = null; - function set(val) { - var action = isFunction ? 'setting the method' : 'setting the property'; - warn(action, 'This is effectively a no-op'); - return val; - } +{ + ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; +} // A javascript: URL can contain leading C0 control or \u0020 SPACE, +// and any newline or tab are filtered out as if they're not part of the URL. +// https://url.spec.whatwg.org/#url-parsing +// Tab or newline are defined as \r\n\t: +// https://infra.spec.whatwg.org/#ascii-tab-or-newline +// A C0 control is a code point in the range \u0000 NULL to \u001F +// INFORMATION SEPARATOR ONE, inclusive: +// https://infra.spec.whatwg.org/#c0-control-or-space - function get() { - var action = isFunction ? 'accessing the method' : 'accessing the property'; - var result = isFunction ? 'This is a no-op function' : 'This is set to null'; - warn(action, result); - return getVal; - } +/* eslint-disable max-len */ - function warn(action, result) { - var warningCondition = false; - !warningCondition ? warningWithoutStack$1(false, "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0; - } -} -function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { - var EventConstructor = this; - if (EventConstructor.eventPool.length) { - var instance = EventConstructor.eventPool.pop(); - EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst); - return instance; - } - return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst); -} +var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; +var didWarn = false; -function releasePooledEvent(event) { - var EventConstructor = this; - (function () { - if (!(event instanceof EventConstructor)) { - { - throw ReactError(Error('Trying to release an event instance into a pool of a different type.')); - } +function sanitizeURL(url) { + { + if (!didWarn && isJavaScriptProtocol.test(url)) { + didWarn = true; + + error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url)); } - })(); - event.destructor(); - if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) { - EventConstructor.eventPool.push(event); } } -function addEventPoolingTo(EventConstructor) { - EventConstructor.eventPool = []; - EventConstructor.getPooled = getPooledEvent; - EventConstructor.release = releasePooledEvent; -} - -/** - * @interface Event - * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents - */ -var SyntheticCompositionEvent = SyntheticEvent.extend({ - data: null -}); - /** - * @interface Event - * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 - * /#events-inputevents + * Get the value for a property on a node. Only used in DEV for SSR validation. + * The "expected" argument is used as a hint of what the expected value is. + * Some properties have multiple equivalent values. */ -var SyntheticInputEvent = SyntheticEvent.extend({ - data: null -}); +function getValueForProperty(node, name, expected, propertyInfo) { + { + if (propertyInfo.mustUseProperty) { + var propertyName = propertyInfo.propertyName; + return node[propertyName]; + } else { + if ( propertyInfo.sanitizeURL) { + // If we haven't fully disabled javascript: URLs, and if + // the hydration is successful of a javascript: URL, we + // still want to warn on the client. + sanitizeURL('' + expected); + } -var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space -var START_KEYCODE = 229; + var attributeName = propertyInfo.attributeName; + var stringValue = null; -var canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window; + if (propertyInfo.type === OVERLOADED_BOOLEAN) { + if (node.hasAttribute(attributeName)) { + var value = node.getAttribute(attributeName); -var documentMode = null; -if (canUseDOM && 'documentMode' in document) { - documentMode = document.documentMode; -} + if (value === '') { + return true; + } -// Webkit offers a very useful `textInput` event that can be used to -// directly represent `beforeInput`. The IE `textinput` event is not as -// useful, so we don't use it. -var canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode; + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + return value; + } -// In IE9+, we have access to composition events, but the data supplied -// by the native compositionend event may be incorrect. Japanese ideographic -// spaces, for instance (\u3000) are not recorded correctly. -var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11); + if (value === '' + expected) { + return expected; + } -var SPACEBAR_CODE = 32; -var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); + return value; + } + } else if (node.hasAttribute(attributeName)) { + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + // We had an attribute but shouldn't have had one, so read it + // for the error message. + return node.getAttribute(attributeName); + } -// Events and their corresponding property names. -var eventTypes = { - beforeInput: { - phasedRegistrationNames: { - bubbled: 'onBeforeInput', - captured: 'onBeforeInputCapture' - }, - dependencies: [TOP_COMPOSITION_END, TOP_KEY_PRESS, TOP_TEXT_INPUT, TOP_PASTE] - }, - compositionEnd: { - phasedRegistrationNames: { - bubbled: 'onCompositionEnd', - captured: 'onCompositionEndCapture' - }, - dependencies: [TOP_BLUR, TOP_COMPOSITION_END, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN] - }, - compositionStart: { - phasedRegistrationNames: { - bubbled: 'onCompositionStart', - captured: 'onCompositionStartCapture' - }, - dependencies: [TOP_BLUR, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN] - }, - compositionUpdate: { - phasedRegistrationNames: { - bubbled: 'onCompositionUpdate', - captured: 'onCompositionUpdateCapture' - }, - dependencies: [TOP_BLUR, TOP_COMPOSITION_UPDATE, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN] - } -}; + if (propertyInfo.type === BOOLEAN) { + // If this was a boolean, it doesn't matter what the value is + // the fact that we have it is the same as the expected. + return expected; + } // Even if this property uses a namespace we use getAttribute + // because we assume its namespaced name is the same as our config. + // To use getAttributeNS we need the local name which we don't have + // in our config atm. -// Track whether we've ever handled a keypress on the space key. -var hasSpaceKeypress = false; -/** - * Return whether a native keypress event is assumed to be a command. - * This is required because Firefox fires `keypress` events for key commands - * (cut, copy, select-all, etc.) even though no character is inserted. - */ -function isKeypressCommand(nativeEvent) { - return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && - // ctrlKey && altKey is equivalent to AltGr, and is not a command. - !(nativeEvent.ctrlKey && nativeEvent.altKey); -} + stringValue = node.getAttribute(attributeName); + } -/** - * Translate native top level events into event types. - * - * @param {string} topLevelType - * @return {object} - */ -function getCompositionEventType(topLevelType) { - switch (topLevelType) { - case TOP_COMPOSITION_START: - return eventTypes.compositionStart; - case TOP_COMPOSITION_END: - return eventTypes.compositionEnd; - case TOP_COMPOSITION_UPDATE: - return eventTypes.compositionUpdate; + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + return stringValue === null ? expected : stringValue; + } else if (stringValue === '' + expected) { + return expected; + } else { + return stringValue; + } + } } } - /** - * Does our fallback best-guess model think this event signifies that - * composition has begun? - * - * @param {string} topLevelType - * @param {object} nativeEvent - * @return {boolean} + * Get the value for a attribute on a node. Only used in DEV for SSR validation. + * The third argument is used as a hint of what the expected value is. Some + * attributes have multiple equivalent values. */ -function isFallbackCompositionStart(topLevelType, nativeEvent) { - return topLevelType === TOP_KEY_DOWN && nativeEvent.keyCode === START_KEYCODE; -} -/** - * Does our fallback mode think that this event is the end of composition? - * - * @param {string} topLevelType - * @param {object} nativeEvent - * @return {boolean} - */ -function isFallbackCompositionEnd(topLevelType, nativeEvent) { - switch (topLevelType) { - case TOP_KEY_UP: - // Command keys insert or clear IME input. - return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; - case TOP_KEY_DOWN: - // Expect IME keyCode on each keydown. If we get any other - // code we must have exited earlier. - return nativeEvent.keyCode !== START_KEYCODE; - case TOP_KEY_PRESS: - case TOP_MOUSE_DOWN: - case TOP_BLUR: - // Events are not possible without cancelling IME. - return true; - default: - return false; - } -} +function getValueForAttribute(node, name, expected) { + { + if (!isAttributeNameSafe(name)) { + return; + } -/** - * Google Input Tools provides composition data via a CustomEvent, - * with the `data` property populated in the `detail` object. If this - * is available on the event object, use it. If not, this is a plain - * composition event and we have nothing special to extract. - * - * @param {object} nativeEvent - * @return {?string} - */ -function getDataFromCustomEvent(nativeEvent) { - var detail = nativeEvent.detail; - if (typeof detail === 'object' && 'data' in detail) { - return detail.data; + if (!node.hasAttribute(name)) { + return expected === undefined ? undefined : null; + } + + var value = node.getAttribute(name); + + if (value === '' + expected) { + return expected; + } + + return value; } - return null; } - /** - * Check if a composition event was triggered by Korean IME. - * Our fallback mode does not work well with IE's Korean IME, - * so just use native composition events when Korean IME is used. - * Although CompositionEvent.locale property is deprecated, - * it is available in IE, where our fallback mode is enabled. + * Sets the value for a property on a node. * - * @param {object} nativeEvent - * @return {boolean} + * @param {DOMElement} node + * @param {string} name + * @param {*} value */ -function isUsingKoreanIME(nativeEvent) { - return nativeEvent.locale === 'ko'; -} - -// Track the current IME composition status, if any. -var isComposing = false; -/** - * @return {?object} A SyntheticCompositionEvent. - */ -function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { - var eventType = void 0; - var fallbackData = void 0; +function setValueForProperty(node, name, value, isCustomComponentTag) { + var propertyInfo = getPropertyInfo(name); - if (canUseCompositionEvent) { - eventType = getCompositionEventType(topLevelType); - } else if (!isComposing) { - if (isFallbackCompositionStart(topLevelType, nativeEvent)) { - eventType = eventTypes.compositionStart; - } - } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) { - eventType = eventTypes.compositionEnd; + if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) { + return; } - if (!eventType) { - return null; - } + if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) { + value = null; + } // If the prop isn't in the special list, treat it as a simple attribute. - if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) { - // The current composition is stored statically and must not be - // overwritten while composition continues. - if (!isComposing && eventType === eventTypes.compositionStart) { - isComposing = initialize(nativeEventTarget); - } else if (eventType === eventTypes.compositionEnd) { - if (isComposing) { - fallbackData = getData(); + + if (isCustomComponentTag || propertyInfo === null) { + if (isAttributeNameSafe(name)) { + var _attributeName = name; + + if (value === null) { + node.removeAttribute(_attributeName); + } else { + node.setAttribute(_attributeName, '' + value); } } + + return; } - var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget); + var mustUseProperty = propertyInfo.mustUseProperty; - if (fallbackData) { - // Inject data generated from fallback path into the synthetic event. - // This matches the property of native CompositionEventInterface. - event.data = fallbackData; - } else { - var customData = getDataFromCustomEvent(nativeEvent); - if (customData !== null) { - event.data = customData; + if (mustUseProperty) { + var propertyName = propertyInfo.propertyName; + + if (value === null) { + var type = propertyInfo.type; + node[propertyName] = type === BOOLEAN ? false : ''; + } else { + // Contrary to `setAttribute`, object properties are properly + // `toString`ed by IE8/9. + node[propertyName] = value; } - } - accumulateTwoPhaseDispatches(event); - return event; -} + return; + } // The rest are treated as attributes with special cases. -/** - * @param {TopLevelType} topLevelType Number from `TopLevelType`. - * @param {object} nativeEvent Native browser event. - * @return {?string} The string corresponding to this `beforeInput` event. - */ -function getNativeBeforeInputChars(topLevelType, nativeEvent) { - switch (topLevelType) { - case TOP_COMPOSITION_END: - return getDataFromCustomEvent(nativeEvent); - case TOP_KEY_PRESS: - /** - * If native `textInput` events are available, our goal is to make - * use of them. However, there is a special case: the spacebar key. - * In Webkit, preventing default on a spacebar `textInput` event - * cancels character insertion, but it *also* causes the browser - * to fall back to its default spacebar behavior of scrolling the - * page. - * - * Tracking at: - * https://code.google.com/p/chromium/issues/detail?id=355103 - * - * To avoid this issue, use the keypress event as if no `textInput` - * event is available. - */ - var which = nativeEvent.which; - if (which !== SPACEBAR_CODE) { - return null; - } - hasSpaceKeypress = true; - return SPACEBAR_CHAR; + var attributeName = propertyInfo.attributeName, + attributeNamespace = propertyInfo.attributeNamespace; - case TOP_TEXT_INPUT: - // Record the characters to be added to the DOM. - var chars = nativeEvent.data; + if (value === null) { + node.removeAttribute(attributeName); + } else { + var _type = propertyInfo.type; + var attributeValue; - // If it's a spacebar character, assume that we have already handled - // it at the keypress level and bail immediately. Android Chrome - // doesn't give us keycodes, so we need to ignore it. - if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { - return null; + if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) { + // If attribute type is boolean, we know for sure it won't be an execution sink + // and we won't require Trusted Type here. + attributeValue = ''; + } else { + // `setAttribute` with objects becomes only `[object]` in IE8/9, + // ('' + value) makes it output the correct toString()-value. + { + attributeValue = '' + value; } - return chars; + if (propertyInfo.sanitizeURL) { + sanitizeURL(attributeValue.toString()); + } + } - default: - // For other native event types, do nothing. - return null; + if (attributeNamespace) { + node.setAttributeNS(attributeNamespace, attributeName, attributeValue); + } else { + node.setAttribute(attributeName, attributeValue); + } } } -/** - * For browsers that do not provide the `textInput` event, extract the - * appropriate string to use for SyntheticInputEvent. - * - * @param {number} topLevelType Number from `TopLevelEventTypes`. - * @param {object} nativeEvent Native browser event. - * @return {?string} The fallback string for this `beforeInput` event. - */ -function getFallbackBeforeInputChars(topLevelType, nativeEvent) { - // If we are currently composing (IME) and using a fallback to do so, - // try to extract the composed characters from the fallback object. - // If composition event is available, we extract a string only at - // compositionevent, otherwise extract it at fallback events. - if (isComposing) { - if (topLevelType === TOP_COMPOSITION_END || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) { - var chars = getData(); - reset(); - isComposing = false; - return chars; - } - return null; - } +var BEFORE_SLASH_RE = /^(.*)[\\\/]/; +function describeComponentFrame (name, source, ownerName) { + var sourceInfo = ''; - switch (topLevelType) { - case TOP_PASTE: - // If a paste event occurs after a keypress, throw out the input - // chars. Paste events should not lead to BeforeInput events. - return null; - case TOP_KEY_PRESS: - /** - * As of v27, Firefox may fire keypress events even when no character - * will be inserted. A few possibilities: - * - * - `which` is `0`. Arrow keys, Esc key, etc. - * - * - `which` is the pressed key code, but no char is available. - * Ex: 'AltGr + d` in Polish. There is no modified character for - * this key combination and no character is inserted into the - * document, but FF fires the keypress for char code `100` anyway. - * No `input` event will occur. - * - * - `which` is the pressed key code, but a command combination is - * being used. Ex: `Cmd+C`. No character is inserted, and no - * `input` event will occur. - */ - if (!isKeypressCommand(nativeEvent)) { - // IE fires the `keypress` event when a user types an emoji via - // Touch keyboard of Windows. In such a case, the `char` property - // holds an emoji character like `\uD83D\uDE0A`. Because its length - // is 2, the property `which` does not represent an emoji correctly. - // In such a case, we directly return the `char` property instead of - // using `which`. - if (nativeEvent.char && nativeEvent.char.length > 1) { - return nativeEvent.char; - } else if (nativeEvent.which) { - return String.fromCharCode(nativeEvent.which); + if (source) { + var path = source.fileName; + var fileName = path.replace(BEFORE_SLASH_RE, ''); + + { + // In DEV, include code for a common special case: + // prefer "folder/index.js" instead of just "index.js". + if (/^index\./.test(fileName)) { + var match = path.match(BEFORE_SLASH_RE); + + if (match) { + var pathBeforeSlash = match[1]; + + if (pathBeforeSlash) { + var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, ''); + fileName = folderName + '/' + fileName; + } } } - return null; - case TOP_COMPOSITION_END: - return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data; - default: - return null; + } + + sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')'; + } else if (ownerName) { + sourceInfo = ' (created by ' + ownerName + ')'; } -} -/** - * Extract a SyntheticInputEvent for `beforeInput`, based on either native - * `textInput` or fallback behavior. - * - * @return {?object} A SyntheticInputEvent. - */ -function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { - var chars = void 0; + return '\n in ' + (name || 'Unknown') + sourceInfo; +} - if (canUseTextInputEvent) { - chars = getNativeBeforeInputChars(topLevelType, nativeEvent); - } else { - chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); - } - - // If no characters are being inserted, no BeforeInput event should - // be fired. - if (!chars) { +// The Symbol used to tag the ReactElement-like types. If there is no native Symbol +// nor polyfill, then a plain number is used for performance. +var hasSymbol = typeof Symbol === 'function' && Symbol.for; +var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7; +var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca; +var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb; +var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc; +var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2; +var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd; +var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary +var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf; +var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0; +var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1; +var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8; +var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3; +var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4; +var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9; +var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { return null; } - var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget); - - event.data = chars; - accumulateTwoPhaseDispatches(event); - return event; -} - -/** - * Create an `onBeforeInput` event to match - * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. - * - * This event plugin is based on the native `textInput` event - * available in Chrome, Safari, Opera, and IE. This event fires after - * `onKeyPress` and `onCompositionEnd`, but before `onInput`. - * - * `beforeInput` is spec'd but not implemented in any browsers, and - * the `input` event does not provide any useful information about what has - * actually been added, contrary to the spec. Thus, `textInput` is the best - * available event to identify the characters that have actually been inserted - * into the target node. - * - * This plugin is also responsible for emitting `composition` events, thus - * allowing us to share composition fallback code for both `beforeInput` and - * `composition` event types. - */ -var BeforeInputEventPlugin = { - eventTypes: eventTypes, - - extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { - var composition = extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget); - - var beforeInput = extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget); - - if (composition === null) { - return beforeInput; - } - - if (beforeInput === null) { - return composition; - } + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - return [composition, beforeInput]; + if (typeof maybeIterator === 'function') { + return maybeIterator; } -}; - -// Use to restore controlled state after a change event has fired. - -var restoreImpl = null; -var restoreTarget = null; -var restoreQueue = null; -function restoreStateOfTarget(target) { - // We perform this translation at the end of the event loop so that we - // always receive the correct fiber here - var internalInstance = getInstanceFromNode(target); - if (!internalInstance) { - // Unmounted - return; - } - (function () { - if (!(typeof restoreImpl === 'function')) { - { - throw ReactError(Error('setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue.')); - } - } - })(); - var props = getFiberCurrentPropsFromNode(internalInstance.stateNode); - restoreImpl(internalInstance.stateNode, internalInstance.type, props); + return null; } -function setRestoreImplementation(impl) { - restoreImpl = impl; +var Uninitialized = -1; +var Pending = 0; +var Resolved = 1; +var Rejected = 2; +function refineResolvedLazyComponent(lazyComponent) { + return lazyComponent._status === Resolved ? lazyComponent._result : null; } +function initializeLazyComponentType(lazyComponent) { + if (lazyComponent._status === Uninitialized) { + lazyComponent._status = Pending; + var ctor = lazyComponent._ctor; + var thenable = ctor(); + lazyComponent._result = thenable; + thenable.then(function (moduleObject) { + if (lazyComponent._status === Pending) { + var defaultExport = moduleObject.default; -function enqueueStateRestore(target) { - if (restoreTarget) { - if (restoreQueue) { - restoreQueue.push(target); - } else { - restoreQueue = [target]; - } - } else { - restoreTarget = target; + { + if (defaultExport === undefined) { + error('lazy: Expected the result of a dynamic import() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + "const MyComponent = lazy(() => import('./MyComponent'))", moduleObject); + } + } + + lazyComponent._status = Resolved; + lazyComponent._result = defaultExport; + } + }, function (error) { + if (lazyComponent._status === Pending) { + lazyComponent._status = Rejected; + lazyComponent._result = error; + } + }); } } -function needsStateRestore() { - return restoreTarget !== null || restoreQueue !== null; +function getWrappedName(outerType, innerType, wrapperName) { + var functionName = innerType.displayName || innerType.name || ''; + return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName); } -function restoreStateIfNeeded() { - if (!restoreTarget) { - return; +function getComponentName(type) { + if (type == null) { + // Host root, text node or just invalid type. + return null; } - var target = restoreTarget; - var queuedTargets = restoreQueue; - restoreTarget = null; - restoreQueue = null; - restoreStateOfTarget(target); - if (queuedTargets) { - for (var i = 0; i < queuedTargets.length; i++) { - restoreStateOfTarget(queuedTargets[i]); + { + if (typeof type.tag === 'number') { + error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.'); } } -} - -var enableUserTimingAPI = true; - -// Helps identify side effects in begin-phase lifecycle hooks and setState reducers: -var debugRenderPhaseSideEffects = false; - -// In some cases, StrictMode should also double-render lifecycles. -// This can be confusing for tests though, -// And it can be bad for performance in production. -// This feature flag can be used to control the behavior: -var debugRenderPhaseSideEffectsForStrictMode = true; - -// To preserve the "Pause on caught exceptions" behavior of the debugger, we -// replay the begin phase of a failed component inside invokeGuardedCallback. -var replayFailedUnitOfWorkWithInvokeGuardedCallback = true; -// Warn about deprecated, async-unsafe lifecycles; relates to RFC #6: -var warnAboutDeprecatedLifecycles = true; - -// Gather advanced timing metrics for Profiler subtrees. -var enableProfilerTimer = true; - -// Trace which interactions trigger each commit. -var enableSchedulerTracing = true; + if (typeof type === 'function') { + return type.displayName || type.name || null; + } -// Only used in www builds. -var enableSuspenseServerRenderer = false; // TODO: true? Here it might just be false. + if (typeof type === 'string') { + return type; + } -// Only used in www builds. + switch (type) { + case REACT_FRAGMENT_TYPE: + return 'Fragment'; + case REACT_PORTAL_TYPE: + return 'Portal'; -// Only used in www builds. + case REACT_PROFILER_TYPE: + return "Profiler"; + case REACT_STRICT_MODE_TYPE: + return 'StrictMode'; -// Disable javascript: URL strings in href for XSS protection. -var disableJavaScriptURLs = false; + case REACT_SUSPENSE_TYPE: + return 'Suspense'; -// React Fire: prevent the value and checked attributes from syncing -// with their related DOM properties -var disableInputAttributeSyncing = false; + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } -// These APIs will no longer be "unstable" in the upcoming 16.7 release, -// Control this behavior with a flag to support 16.6 minor releases in the meanwhile. -var enableStableConcurrentModeAPIs = false; + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + return 'Context.Consumer'; -var warnAboutShorthandPropertyCollision = false; + case REACT_PROVIDER_TYPE: + return 'Context.Provider'; -// See https://github.com/react-native-community/discussions-and-proposals/issues/72 for more information -// This is a flag so we can fix warnings in RN core before turning it on + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, 'ForwardRef'); + case REACT_MEMO_TYPE: + return getComponentName(type.type); -// Experimental React Flare event system and event components support. -var enableFlareAPI = false; + case REACT_BLOCK_TYPE: + return getComponentName(type.render); -// Experimental Host Component support. -var enableFundamentalAPI = false; + case REACT_LAZY_TYPE: + { + var thenable = type; + var resolvedThenable = refineResolvedLazyComponent(thenable); -// New API for JSX transforms to target - https://github.com/reactjs/rfcs/pull/107 + if (resolvedThenable) { + return getComponentName(resolvedThenable); + } + break; + } + } + } -// We will enforce mocking scheduler with scheduler/unstable_mock at some point. (v17?) -// Till then, we warn about the missing mock, but still fallback to a sync mode compatible version -var warnAboutUnmockedScheduler = false; -// Temporary flag to revert the fix in #15650 -var revertPassiveEffectsChange = false; + return null; +} -// For tests, we flush suspense fallbacks in an act scope; -// *except* in some of our own tests, where we test incremental loading states. -var flushSuspenseFallbacksInTests = true; +var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; -// Changes priority of some events like mousemove to user-blocking priority, -// but without making them discrete. The flag exists in case it causes -// starvation problems. -var enableUserBlockingEvents = false; +function describeFiber(fiber) { + switch (fiber.tag) { + case HostRoot: + case HostPortal: + case HostText: + case Fragment: + case ContextProvider: + case ContextConsumer: + return ''; -// Add a callback property to suspense to notify which promises are currently -// in the update queue. This allows reporting and tracing of what is causing -// the user to see a loading state. -var enableSuspenseCallback = false; + default: + var owner = fiber._debugOwner; + var source = fiber._debugSource; + var name = getComponentName(fiber.type); + var ownerName = null; -// Part of the simplification of React.createElement so we can eventually move -// from React.createElement to React.jsx -// https://github.com/reactjs/rfcs/blob/createlement-rfc/text/0000-create-element-changes.md -var warnAboutDefaultPropsOnFunctionComponents = false; + if (owner) { + ownerName = getComponentName(owner.type); + } -var disableLegacyContext = false; + return describeComponentFrame(name, source, ownerName); + } +} -var disableSchedulerTimeoutBasedOnReactExpirationTime = false; +function getStackByFiberInDevAndProd(workInProgress) { + var info = ''; + var node = workInProgress; -// Used as a way to call batchedUpdates when we don't have a reference to -// the renderer. Such as when we're dispatching events or if third party -// libraries need to call batchedUpdates. Eventually, this API will go away when -// everything is batched by default. We'll then have a similar API to opt-out of -// scheduled work and instead do synchronous work. + do { + info += describeFiber(node); + node = node.return; + } while (node); -// Defaults -var batchedUpdatesImpl = function (fn, bookkeeping) { - return fn(bookkeeping); -}; -var discreteUpdatesImpl = function (fn, a, b, c) { - return fn(a, b, c); -}; -var flushDiscreteUpdatesImpl = function () {}; -var batchedEventUpdatesImpl = batchedUpdatesImpl; + return info; +} +var current = null; +var isRendering = false; +function getCurrentFiberOwnerNameInDevOrNull() { + { + if (current === null) { + return null; + } -var isInsideEventHandler = false; + var owner = current._debugOwner; -function finishEventHandler() { - // Here we wait until all updates have propagated, which is important - // when using controlled components within layers: - // https://github.com/facebook/react/issues/1698 - // Then we restore state of any controlled component. - var controlledComponentsHavePendingUpdates = needsStateRestore(); - if (controlledComponentsHavePendingUpdates) { - // If a controlled event was fired, we may need to restore the state of - // the DOM node back to the controlled value. This is necessary when React - // bails out of the update without touching the DOM. - flushDiscreteUpdatesImpl(); - restoreStateIfNeeded(); + if (owner !== null && typeof owner !== 'undefined') { + return getComponentName(owner.type); + } } -} -function batchedUpdates(fn, bookkeeping) { - if (isInsideEventHandler) { - // If we are currently inside another batch, we need to wait until it - // fully completes before restoring state. - return fn(bookkeeping); - } - isInsideEventHandler = true; - try { - return batchedUpdatesImpl(fn, bookkeeping); - } finally { - isInsideEventHandler = false; - finishEventHandler(); - } + return null; } +function getCurrentFiberStackInDev() { + { + if (current === null) { + return ''; + } // Safe because if current fiber exists, we are reconciling, + // and it is guaranteed to be the work-in-progress version. -function batchedEventUpdates(fn, a, b) { - if (isInsideEventHandler) { - // If we are currently inside another batch, we need to wait until it - // fully completes before restoring state. - return fn(a, b); + + return getStackByFiberInDevAndProd(current); } - isInsideEventHandler = true; - try { - return batchedEventUpdatesImpl(fn, a, b); - } finally { - isInsideEventHandler = false; - finishEventHandler(); +} +function resetCurrentFiber() { + { + ReactDebugCurrentFrame$1.getCurrentStack = null; + current = null; + isRendering = false; } } - -function discreteUpdates(fn, a, b, c) { - var prevIsInsideEventHandler = isInsideEventHandler; - isInsideEventHandler = true; - try { - return discreteUpdatesImpl(fn, a, b, c); - } finally { - isInsideEventHandler = prevIsInsideEventHandler; - if (!isInsideEventHandler) { - finishEventHandler(); - } +function setCurrentFiber(fiber) { + { + ReactDebugCurrentFrame$1.getCurrentStack = getCurrentFiberStackInDev; + current = fiber; + isRendering = false; } } - -var lastFlushedEventTimeStamp = 0; -function flushDiscreteUpdatesIfNeeded(timeStamp) { - // event.timeStamp isn't overly reliable due to inconsistencies in - // how different browsers have historically provided the time stamp. - // Some browsers provide high-resolution time stamps for all events, - // some provide low-resolution time stamps for all events. FF < 52 - // even mixes both time stamps together. Some browsers even report - // negative time stamps or time stamps that are 0 (iOS9) in some cases. - // Given we are only comparing two time stamps with equality (!==), - // we are safe from the resolution differences. If the time stamp is 0 - // we bail-out of preventing the flush, which can affect semantics, - // such as if an earlier flush removes or adds event listeners that - // are fired in the subsequent flush. However, this is the same - // behaviour as we had before this change, so the risks are low. - if (!isInsideEventHandler && (!enableFlareAPI || timeStamp === 0 || lastFlushedEventTimeStamp !== timeStamp)) { - lastFlushedEventTimeStamp = timeStamp; - flushDiscreteUpdatesImpl(); +function setIsRendering(rendering) { + { + isRendering = rendering; } } -function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushDiscreteUpdatesImpl, _batchedEventUpdatesImpl) { - batchedUpdatesImpl = _batchedUpdatesImpl; - discreteUpdatesImpl = _discreteUpdatesImpl; - flushDiscreteUpdatesImpl = _flushDiscreteUpdatesImpl; - batchedEventUpdatesImpl = _batchedEventUpdatesImpl; +// Flow does not allow string concatenation of most non-string types. To work +// around this limitation, we use an opaque type that can only be obtained by +// passing the value through getToStringValue first. +function toString(value) { + return '' + value; } +function getToStringValue(value) { + switch (typeof value) { + case 'boolean': + case 'number': + case 'object': + case 'string': + case 'undefined': + return value; -/** - * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary - */ -var supportedInputTypes = { - color: true, - date: true, - datetime: true, - 'datetime-local': true, - email: true, - month: true, - number: true, - password: true, - range: true, - search: true, - tel: true, - text: true, - time: true, - url: true, - week: true -}; - -function isTextInputElement(elem) { - var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); - - if (nodeName === 'input') { - return !!supportedInputTypes[elem.type]; - } - - if (nodeName === 'textarea') { - return true; + default: + // function, symbol are assigned as empty strings + return ''; } - - return false; } -/** - * HTML nodeType values that represent the type of the node - */ - -var ELEMENT_NODE = 1; -var TEXT_NODE = 3; -var COMMENT_NODE = 8; -var DOCUMENT_NODE = 9; -var DOCUMENT_FRAGMENT_NODE = 11; - -/** - * Gets the target node from a native browser event by accounting for - * inconsistencies in browser DOM APIs. - * - * @param {object} nativeEvent Native browser event. - * @return {DOMEventTarget} Target node. - */ -function getEventTarget(nativeEvent) { - // Fallback to nativeEvent.srcElement for IE9 - // https://github.com/facebook/react/issues/12506 - var target = nativeEvent.target || nativeEvent.srcElement || window; - - // Normalize SVG element events #4963 - if (target.correspondingUseElement) { - target = target.correspondingUseElement; - } - - // Safari may fire events on text nodes (Node.TEXT_NODE is 3). - // @see http://www.quirksmode.org/js/events_properties.html - return target.nodeType === TEXT_NODE ? target.parentNode : target; -} +var ReactDebugCurrentFrame$2 = null; +var ReactControlledValuePropTypes = { + checkPropTypes: null +}; -/** - * Checks if an event is supported in the current execution environment. - * - * NOTE: This will not work correctly for non-generic events such as `change`, - * `reset`, `load`, `error`, and `select`. - * - * Borrows from Modernizr. - * - * @param {string} eventNameSuffix Event name, e.g. "click". - * @return {boolean} True if the event is supported. - * @internal - * @license Modernizr 3.0.0pre (Custom Build) | MIT - */ -function isEventSupported(eventNameSuffix) { - if (!canUseDOM) { - return false; - } +{ + ReactDebugCurrentFrame$2 = ReactSharedInternals.ReactDebugCurrentFrame; + var hasReadOnlyValue = { + button: true, + checkbox: true, + image: true, + hidden: true, + radio: true, + reset: true, + submit: true + }; + var propTypes = { + value: function (props, propName, componentName) { + if (hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled || props[propName] == null || enableDeprecatedFlareAPI ) { + return null; + } - var eventName = 'on' + eventNameSuffix; - var isSupported = eventName in document; + return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); + }, + checked: function (props, propName, componentName) { + if (props.onChange || props.readOnly || props.disabled || props[propName] == null || enableDeprecatedFlareAPI ) { + return null; + } - if (!isSupported) { - var element = document.createElement('div'); - element.setAttribute(eventName, 'return;'); - isSupported = typeof element[eventName] === 'function'; - } + return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); + } + }; + /** + * Provide a linked `value` attribute for controlled forms. You should not use + * this outside of the ReactDOM controlled form components. + */ - return isSupported; + ReactControlledValuePropTypes.checkPropTypes = function (tagName, props) { + checkPropTypes(propTypes, props, 'prop', tagName, ReactDebugCurrentFrame$2.getStackAddendum); + }; } function isCheckable(elem) { @@ -21708,6 +20830,7 @@ function detachTracker(node) { function getValueFromNode(node) { var value = ''; + if (!node) { return value; } @@ -21724,19 +20847,17 @@ function getValueFromNode(node) { function trackValueOnNode(node) { var valueField = isCheckable(node) ? 'checked' : 'value'; var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField); - - var currentValue = '' + node[valueField]; - - // if someone has already defined a value or Safari, then bail + var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail // and don't track value will cause over reporting of changes, // but it's better then a hard failure // (needed for certain tests that spyOn input values and Safari) + if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') { return; } + var get = descriptor.get, set = descriptor.set; - Object.defineProperty(node, valueField, { configurable: true, get: function () { @@ -21746,15 +20867,14 @@ function trackValueOnNode(node) { currentValue = '' + value; set.call(this, value); } - }); - // We could've passed this the first time + }); // We could've passed this the first time // but it triggers a bug in IE11 and Edge 14/15. // Calling defineProperty() again should be equivalent. // https://github.com/facebook/react/issues/11768 + Object.defineProperty(node, valueField, { enumerable: descriptor.enumerable }); - var tracker = { getValue: function () { return currentValue; @@ -21773,7899 +20893,8479 @@ function trackValueOnNode(node) { function track(node) { if (getTracker(node)) { return; - } + } // TODO: Once it's just Fiber we can move this to node._wrapperState + - // TODO: Once it's just Fiber we can move this to node._wrapperState node._valueTracker = trackValueOnNode(node); } - function updateValueIfChanged(node) { if (!node) { return false; } - var tracker = getTracker(node); - // if there is no tracker at this point it's unlikely + var tracker = getTracker(node); // if there is no tracker at this point it's unlikely // that trying again will succeed + if (!tracker) { return true; } var lastValue = tracker.getValue(); var nextValue = getValueFromNode(node); + if (nextValue !== lastValue) { tracker.setValue(nextValue); return true; } + return false; } -var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; +var didWarnValueDefaultValue = false; +var didWarnCheckedDefaultChecked = false; +var didWarnControlledToUncontrolled = false; +var didWarnUncontrolledToControlled = false; -// Prevent newer renderers from RTE when used with older react package versions. -// Current owner and dispatcher used to share the same ref, -// but PR #14548 split them out to better support the react-debug-tools package. -if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) { - ReactSharedInternals.ReactCurrentDispatcher = { - current: null - }; -} -if (!ReactSharedInternals.hasOwnProperty('ReactCurrentBatchConfig')) { - ReactSharedInternals.ReactCurrentBatchConfig = { - suspense: null - }; +function isControlled(props) { + var usesChecked = props.type === 'checkbox' || props.type === 'radio'; + return usesChecked ? props.checked != null : props.value != null; } +/** + * Implements an host component that allows setting these optional + * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. + * + * If `checked` or `value` are not supplied (or null/undefined), user actions + * that affect the checked state or value will trigger updates to the element. + * + * If they are supplied (and not null/undefined), the rendered element will not + * trigger updates to the element. Instead, the props must change in order for + * the rendered element to be updated. + * + * The rendered element will be initialized as unchecked (or `defaultChecked`) + * with an empty value (or `defaultValue`). + * + * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html + */ -var BEFORE_SLASH_RE = /^(.*)[\\\/]/; -var describeComponentFrame = function (name, source, ownerName) { - var sourceInfo = ''; - if (source) { - var path = source.fileName; - var fileName = path.replace(BEFORE_SLASH_RE, ''); - { - // In DEV, include code for a common special case: - // prefer "folder/index.js" instead of just "index.js". - if (/^index\./.test(fileName)) { - var match = path.match(BEFORE_SLASH_RE); - if (match) { - var pathBeforeSlash = match[1]; - if (pathBeforeSlash) { - var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, ''); - fileName = folderName + '/' + fileName; - } - } - } - } - sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')'; - } else if (ownerName) { - sourceInfo = ' (created by ' + ownerName + ')'; - } - return '\n in ' + (name || 'Unknown') + sourceInfo; -}; +function getHostProps(element, props) { + var node = element; + var checked = props.checked; -// The Symbol used to tag the ReactElement-like types. If there is no native Symbol -// nor polyfill, then a plain number is used for performance. -var hasSymbol = typeof Symbol === 'function' && Symbol.for; + var hostProps = _assign({}, props, { + defaultChecked: undefined, + defaultValue: undefined, + value: undefined, + checked: checked != null ? checked : node._wrapperState.initialChecked + }); -var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7; -var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca; -var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb; -var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc; -var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2; -var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd; -var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; -// TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary -// (unstable) APIs that have been removed. Can we remove the symbols? + return hostProps; +} +function initWrapperState(element, props) { + { + ReactControlledValuePropTypes.checkPropTypes('input', props); -var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf; -var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0; -var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1; -var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8; -var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3; -var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4; -var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5; -var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6; + if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) { + error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type); -var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; -var FAUX_ITERATOR_SYMBOL = '@@iterator'; + didWarnCheckedDefaultChecked = true; + } -function getIteratorFn(maybeIterable) { - if (maybeIterable === null || typeof maybeIterable !== 'object') { - return null; - } - var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - if (typeof maybeIterator === 'function') { - return maybeIterator; - } - return null; -} + if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { + error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type); -var Pending = 0; -var Resolved = 1; -var Rejected = 2; + didWarnValueDefaultValue = true; + } + } -function refineResolvedLazyComponent(lazyComponent) { - return lazyComponent._status === Resolved ? lazyComponent._result : null; + var node = element; + var defaultValue = props.defaultValue == null ? '' : props.defaultValue; + node._wrapperState = { + initialChecked: props.checked != null ? props.checked : props.defaultChecked, + initialValue: getToStringValue(props.value != null ? props.value : defaultValue), + controlled: isControlled(props) + }; } +function updateChecked(element, props) { + var node = element; + var checked = props.checked; -function getWrappedName(outerType, innerType, wrapperName) { - var functionName = innerType.displayName || innerType.name || ''; - return outerType.displayName || (functionName !== '' ? wrapperName + '(' + functionName + ')' : wrapperName); + if (checked != null) { + setValueForProperty(node, 'checked', checked, false); + } } +function updateWrapper(element, props) { + var node = element; -function getComponentName(type) { - if (type == null) { - // Host root, text node or just invalid type. - return null; - } { - if (typeof type.tag === 'number') { - warningWithoutStack$1(false, 'Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.'); + var controlled = isControlled(props); + + if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { + error('A component is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', props.type); + + didWarnUncontrolledToControlled = true; } - } - if (typeof type === 'function') { - return type.displayName || type.name || null; - } - if (typeof type === 'string') { - return type; - } - switch (type) { - case REACT_FRAGMENT_TYPE: - return 'Fragment'; - case REACT_PORTAL_TYPE: - return 'Portal'; - case REACT_PROFILER_TYPE: - return 'Profiler'; - case REACT_STRICT_MODE_TYPE: - return 'StrictMode'; - case REACT_SUSPENSE_TYPE: - return 'Suspense'; - case REACT_SUSPENSE_LIST_TYPE: - return 'SuspenseList'; - } - if (typeof type === 'object') { - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - return 'Context.Consumer'; - case REACT_PROVIDER_TYPE: - return 'Context.Provider'; - case REACT_FORWARD_REF_TYPE: - return getWrappedName(type, type.render, 'ForwardRef'); - case REACT_MEMO_TYPE: - return getComponentName(type.type); - case REACT_LAZY_TYPE: - { - var thenable = type; - var resolvedThenable = refineResolvedLazyComponent(thenable); - if (resolvedThenable) { - return getComponentName(resolvedThenable); - } - break; - } + + if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { + error('A component is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', props.type); + + didWarnControlledToUncontrolled = true; } } - return null; -} -var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + updateChecked(element, props); + var value = getToStringValue(props.value); + var type = props.type; -function describeFiber(fiber) { - switch (fiber.tag) { - case HostRoot: - case HostPortal: - case HostText: - case Fragment: - case ContextProvider: - case ContextConsumer: - return ''; - default: - var owner = fiber._debugOwner; - var source = fiber._debugSource; - var name = getComponentName(fiber.type); - var ownerName = null; - if (owner) { - ownerName = getComponentName(owner.type); + if (value != null) { + if (type === 'number') { + if (value === 0 && node.value === '' || // We explicitly want to coerce to number here if possible. + // eslint-disable-next-line + node.value != value) { + node.value = toString(value); } - return describeComponentFrame(name, source, ownerName); + } else if (node.value !== toString(value)) { + node.value = toString(value); + } + } else if (type === 'submit' || type === 'reset') { + // Submit/reset inputs need the attribute removed completely to avoid + // blank-text buttons. + node.removeAttribute('value'); + return; } -} - -function getStackByFiberInDevAndProd(workInProgress) { - var info = ''; - var node = workInProgress; - do { - info += describeFiber(node); - node = node.return; - } while (node); - return info; -} -var current = null; -var phase = null; - -function getCurrentFiberOwnerNameInDevOrNull() { { - if (current === null) { - return null; - } - var owner = current._debugOwner; - if (owner !== null && typeof owner !== 'undefined') { - return getComponentName(owner.type); + // When syncing the value attribute, the value comes from a cascade of + // properties: + // 1. The value React property + // 2. The defaultValue React property + // 3. Otherwise there should be no change + if (props.hasOwnProperty('value')) { + setDefaultValue(node, props.type, value); + } else if (props.hasOwnProperty('defaultValue')) { + setDefaultValue(node, props.type, getToStringValue(props.defaultValue)); } } - return null; -} -function getCurrentFiberStackInDev() { { - if (current === null) { - return ''; + // When syncing the checked attribute, it only changes when it needs + // to be removed, such as transitioning from a checkbox into a text input + if (props.checked == null && props.defaultChecked != null) { + node.defaultChecked = !!props.defaultChecked; } - // Safe because if current fiber exists, we are reconciling, - // and it is guaranteed to be the work-in-progress version. - return getStackByFiberInDevAndProd(current); } - return ''; } +function postMountWrapper(element, props, isHydrating) { + var node = element; // Do not assign value if it is already set. This prevents user text input + // from being lost during SSR hydration. -function resetCurrentFiber() { - { - ReactDebugCurrentFrame.getCurrentStack = null; - current = null; - phase = null; + if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) { + var type = props.type; + var isButton = type === 'submit' || type === 'reset'; // Avoid setting value attribute on submit/reset inputs as it overrides the + // default value provided by the browser. See: #12872 + + if (isButton && (props.value === undefined || props.value === null)) { + return; + } + + var initialValue = toString(node._wrapperState.initialValue); // Do not assign value if it is already set. This prevents user text input + // from being lost during SSR hydration. + + if (!isHydrating) { + { + // When syncing the value attribute, the value property should use + // the wrapperState._initialValue property. This uses: + // + // 1. The value React property when present + // 2. The defaultValue React property when present + // 3. An empty string + if (initialValue !== node.value) { + node.value = initialValue; + } + } + } + + { + // Otherwise, the value attribute is synchronized to the property, + // so we assign defaultValue to the same thing as the value property + // assignment step above. + node.defaultValue = initialValue; + } + } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug + // this is needed to work around a chrome bug where setting defaultChecked + // will sometimes influence the value of checked (even after detachment). + // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416 + // We need to temporarily unset name to avoid disrupting radio button groups. + + + var name = node.name; + + if (name !== '') { + node.name = ''; } -} -function setCurrentFiber(fiber) { { - ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev; - current = fiber; - phase = null; + // When syncing the checked attribute, both the checked property and + // attribute are assigned at the same time using defaultChecked. This uses: + // + // 1. The checked React property when present + // 2. The defaultChecked React property when present + // 3. Otherwise, false + node.defaultChecked = !node.defaultChecked; + node.defaultChecked = !!node._wrapperState.initialChecked; } -} -function setCurrentPhase(lifeCyclePhase) { - { - phase = lifeCyclePhase; + if (name !== '') { + node.name = name; } } +function restoreControlledState(element, props) { + var node = element; + updateWrapper(node, props); + updateNamedCousins(node, props); +} -/** - * Similar to invariant but only logs a warning if the condition is not met. - * This can be used to log issues in development environments in critical - * paths. Removing the logging code for production environments will keep the - * same logic and follow the same code paths. - */ +function updateNamedCousins(rootNode, props) { + var name = props.name; -var warning = warningWithoutStack$1; + if (props.type === 'radio' && name != null) { + var queryRoot = rootNode; -{ - warning = function (condition, format) { - if (condition) { - return; - } - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame.getStackAddendum(); - // eslint-disable-next-line react-internal/warning-and-invariant-args + while (queryRoot.parentNode) { + queryRoot = queryRoot.parentNode; + } // If `rootNode.form` was non-null, then we could try `form.elements`, + // but that sometimes behaves strangely in IE8. We could also try using + // `form.getElementsByName`, but that will only return direct children + // and won't include inputs that use the HTML5 `form=` attribute. Since + // the input might not even be in a form. It might not even be in the + // document. Let's just use the local `querySelectorAll` to ensure we don't + // miss anything. + + + var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); + + for (var i = 0; i < group.length; i++) { + var otherNode = group[i]; + + if (otherNode === rootNode || otherNode.form !== rootNode.form) { + continue; + } // This will throw if radio buttons rendered by different copies of React + // and the same name are rendered into the same form (same as #1939). + // That's probably okay; we don't support it just as we don't support + // mixing React radio buttons with non-React ones. + + + var otherProps = getFiberCurrentPropsFromNode$1(otherNode); + + if (!otherProps) { + { + throw Error( "ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported." ); + } + } // We need update the tracked value on the named cousin since the value + // was changed but the input saw no event or value set + + + updateValueIfChanged(otherNode); // If this is a controlled radio button group, forcing the input that + // was previously checked to update will cause it to be come re-checked + // as appropriate. - for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { - args[_key - 2] = arguments[_key]; + updateWrapper(otherNode, otherProps); } + } +} // In Chrome, assigning defaultValue to certain input types triggers input validation. +// For number inputs, the display value loses trailing decimal points. For email inputs, +// Chrome raises "The specified value is not a valid email address". +// +// Here we check to see if the defaultValue has actually changed, avoiding these problems +// when the user is inputting text +// +// https://github.com/facebook/react/issues/7253 - warningWithoutStack$1.apply(undefined, [false, format + '%s'].concat(args, [stack])); - }; + +function setDefaultValue(node, type, value) { + if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js + type !== 'number' || node.ownerDocument.activeElement !== node) { + if (value == null) { + node.defaultValue = toString(node._wrapperState.initialValue); + } else if (node.defaultValue !== toString(value)) { + node.defaultValue = toString(value); + } + } } -var warning$1 = warning; +var didWarnSelectedSetOnOption = false; +var didWarnInvalidChild = false; -// A reserved attribute. -// It is handled by React separately and shouldn't be written to the DOM. -var RESERVED = 0; +function flattenChildren(children) { + var content = ''; // Flatten children. We'll warn if they are invalid + // during validateProps() which runs for hydration too. + // Note that this would throw on non-element objects. + // Elements are stringified (which is normally irrelevant + // but matters for ). -// A simple string attribute. -// Attributes that aren't in the whitelist are presumed to have this type. -var STRING = 1; + React.Children.forEach(children, function (child) { + if (child == null) { + return; + } -// A string attribute that accepts booleans in React. In HTML, these are called -// "enumerated" attributes with "true" and "false" as possible values. -// When true, it should be set to a "true" string. -// When false, it should be set to a "false" string. -var BOOLEANISH_STRING = 2; + content += child; // Note: we don't warn about invalid children here. + // Instead, this is done separately below so that + // it happens during the hydration codepath too. + }); + return content; +} +/** + * Implements an