diff --git a/.gitignore b/.gitignore index d8e5a85..15491a4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,8 @@ PLACE-REACT-SOURCE-CODE-HERE/* !PLACE-REACT-SOURCE-CODE-HERE/PLACEHOLDER_FOR_GITIGNORE.md -build +!example/*/node_modules +/node_modules # Logs logs @@ -43,7 +44,7 @@ bower_components build/Release # Dependency directories -node_modules/ +# node_modules/ jspm_packages/ # TypeScript v1 declaration files diff --git a/.vscode/launch.json b/.vscode/launch.json index 124dfd3..8eb789d 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -4,17 +4,12 @@ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ - { - "type": "node", + "type": "chrome", "request": "launch", - "name": "Launch Program", - "skipFiles": [ - "/**" - ], - "program": "${workspaceFolder}/index.js", - // "program": "${workspaceFolder}/test/test.js", - "cwd": "${workspaceFolder}/PLACE-REACT-SOURCE-CODE-HERE" + "name": "Launch Chrome against localhost", + "url": "http://localhost:6001", + "webRoot": "${workspaceFolder}/react-16.6.0" } ] } \ No newline at end of file diff --git a/README.md b/README.md deleted file mode 100644 index 8829373..0000000 --- a/README.md +++ /dev/null @@ -1 +0,0 @@ -# debug-react-source-code \ No newline at end of file diff --git a/index.js b/index.js deleted file mode 100644 index 5a65466..0000000 --- a/index.js +++ /dev/null @@ -1,246 +0,0 @@ -const fs = require('fs') -const path = require(`path`) -const trash = require(`trash`) -const { spawn, exec } = require('child_process') -const {IDENTITY_START_STR, IDENTITY_END_STR, ANNOTATION_PREFIX} = require('./shared.js') - -const PATH_PLUGIN = path.resolve(__dirname, 'rollup-plugin-add-path-info-annoation-for-each-file.js').replace(/\\/g, '/') -const PATH_DEPENDENCIES = path.resolve(__dirname, 'dependencies').replace(/\\/g, '/') -const PATH_BUILD = path.resolve(__dirname, 'build').replace(/\\/g, '/') - - -const PATH_REACT_CONTAINER = path.resolve(__dirname, 'PLACE-REACT-SOURCE-CODE-HERE').replace(/\\/g, '/') -const dirs = fs.readdirSync(PATH_REACT_CONTAINER).filter(v => fs.lstatSync( path.resolve(PATH_REACT_CONTAINER, v).replace(/\\/g, '/') ).isDirectory()) -if (dirs.length === 0) { throw new Error('No React Source Code Directory Found!') } -const PATH_REACT = path.resolve(PATH_REACT_CONTAINER, dirs[0]).replace(/\\/g, '/') -const PATH_BUILD_REACT = path.resolve(PATH_BUILD, path.basename(PATH_REACT).replace(/\.js/, '')).replace(/\\/g, '/') - - -const PATH_REACT_NODE_MODULES = path.resolve(PATH_REACT, 'node_modules').replace(/\\/g, '/') -const PATH_REACT_ROLLUP_BUILD_JS = path.resolve(PATH_REACT, 'scripts/rollup/build.js').replace(/\\/g, '/') -const PATH_NEW_REACT_ROLLUP_BUILD_JS = path.resolve(PATH_REACT, 'scripts/rollup/build.for-debug-react-code.js').replace(/\\/g, '/') -const TMP = 'scripts/rollup/build.for-debug-react-code.js' -const RELATIVE_PATH_NEW_REACT_ROLLUP_BUILD_JS_TO_PLUGIN = path.relative(path.resolve(PATH_REACT, 'scripts/rollup' ), PATH_PLUGIN).replace(/\\/g, '/') -const RELATIVE_PATH_REACT_TO__NEW_REACT_ROLLUP_BUILD_JS = path.relative(PATH_REACT, PATH_NEW_REACT_ROLLUP_BUILD_JS).replace(/\\/g, '/') -const RELATIVE_PATH_ROLLUP_BUILD_JS_TO_REACT = path.relative(PATH_REACT_ROLLUP_BUILD_JS, PATH_REACT).replace(/\\/g, '/') - -const NAME_PLUGIN = `$$addPathInfoAnnotationForEachFilePlugin` - -const NAME_DEPENDENCY_REACT = 'dependency-react.html' -const NAME_DEPENDENCY_REACT_DOM = 'dependency-react-dom.html' -const NAME_DEPENDENCY_DEFAULT_JS = `index.js` - -const PATH_DEPENDENCY_SOURCE_BABEL = path.resolve(PATH_DEPENDENCIES, 'source-babel.js').replace(/\\/g, '/') -const PATH_DEPENDENCY_SOURCE_DEPENDENCY_MAIN = path.resolve(PATH_DEPENDENCIES, 'source-dependency-main.html').replace(/\\/g, '/') -const PATH_DEPENDENCY_SOURCE_DEFAULT_JS = path.resolve(PATH_DEPENDENCIES, 'source-index.js').replace(/\\/g, '/') -const PATH_DEPENDENCY_SOURCE_DEFAULT = path.resolve(PATH_DEPENDENCIES, 'source-index.html').replace(/\\/g, '/') - -// # generate a new build js -function generateNewBuildJS() { - const buildJsStr = fs.readFileSync(PATH_REACT_ROLLUP_BUILD_JS, {encoding: 'utf8'}) - const lines = buildJsStr.split('\n') - const newFistLine = `const ${NAME_PLUGIN} = require('${RELATIVE_PATH_NEW_REACT_ROLLUP_BUILD_JS_TO_PLUGIN}');\n` - newBuildJsStr = newFistLine + lines.map(line => { - if (line.match(/rollup\(/)) { - return `rollupConfig.plugins.push(${NAME_PLUGIN}('${PATH_REACT}')); - ${line}` - } - return line - }).join('\n') - fs.writeFileSync(PATH_NEW_REACT_ROLLUP_BUILD_JS, newBuildJsStr, {encoding: 'utf-8'}) - console.log(`$$ DEBUG REACT SOURCE CODE: generated a new build js!`) -} - -function installDependencies(cb) { - const ls = spawn(`yarn.cmd`, [`install`], {cwd: PATH_REACT}) - ls.stdout.on('data', data => console.log(data.toString())) - ls.stdout.on('close', cb) -} - -function build(cb) { - const ls = spawn('node', [TMP, `react/index,react-dom/index`, `--type`, `UMD_DEV`], {cwd: PATH_REACT}) - // const ls = spawn('node', [TMP], {cwd: PATH_REACT}) - ls.stdout.on('data', data => console.log(data.toString())) - ls.stderr.on('data', data => console.log(data.toString())) - ls.on('close', () => { - console.log(`$$ DEBUG REACT SOURCE CODE: generated react.development.js and react-dom.development.js!`) - cb && cb() - }) -} - -function getReactOrReactDOMNamespace(reactOrReactDOMDevelopmentFile) { - const isReactFile = path.parse(reactOrReactDOMDevelopmentFile).name.replace(/\..*/, '') === 'react' - return isReactFile ? 'React' : 'ReactDOM' -} - -/** - * - * @param {*} reactOrReactDOMDevelopmentFile - * @return {{outputFile, text}[]} - */ -function getReactOrReactDOMSplitFilesData(reactOrReactDOMDevelopmentFile) { - const getFileOnEndLine = (line) => { - const isSpecialFormat = /commonjs-proxy-/.test( line ) - - if ( isSpecialFormat ) { - let tmpPath = line.replace( /.*commonjs-proxy-/, '' ) - tmpPath = path.relative( PATH_REACT, tmpPath ).replace(/\\/g,'/') - - return `commonjs-proxy-/${ tmpPath }` - // return path - } - return line.replace( new RegExp(`.*${ANNOTATION_PREFIX.replace('/', '\\/')}${IDENTITY_END_STR.replace(/\$/g, '\\$')} `), '' ) - } - const isStartLine = line => new RegExp( `${IDENTITY_START_STR.replace(/\$/g, '\\$')}` ).test( line ) - const isEndLine = line => new RegExp( `${IDENTITY_END_STR.replace(/\$/g, '\\$')}` ).test( line ) - - const namespace = getReactOrReactDOMNamespace(reactOrReactDOMDevelopmentFile) - - const sourceText = fs.readFileSync(reactOrReactDOMDevelopmentFile, {encoding: 'utf8'}) - const lines = sourceText.split( '\n' ) - /** @type {{outputFile, text}[]} */ - const data = [] - let hasStarted = false - // resolve the content between **end** and **start** - let isBetweenEndAndStart = false - /** @type {string[]} */ - let curry = [] - let lineIndex = -1 - for (let line of lines) { - lineIndex++ - - if (isStartLine(line)) { - hasStarted = true - } - if (hasStarted) { - if (isStartLine(line) || lineIndex === lines.length - 2) { - if (isBetweenEndAndStart && curry.length > 0 && !(curry.every(line => line.trim() === ''))) { - const outputFile = `$$umd/line-number-${lineIndex}.js` - let text = curry.join('\n') - text = text.replace(/exports/g, namespace) - data.push({outputFile, text}) - } - isBetweenEndAndStart = false - curry = [] - } - if (!isStartLine(line) && !isEndLine(line)) {curry.push(line)} - if (isEndLine(line)) { - let text = curry.join('\n') - text = text.replace(/exports/g, namespace) - const outputFile = getFileOnEndLine(line) - data.push({outputFile, text}) - curry = [] - isBetweenEndAndStart = true - } - } - } - return data -} - -/** - * - * @param {{outputFile, text}[]} filesData - * @param {string} reactOrReactDOMDevelopmentFile - */ -function generateReactOrReactDOMSplitFiles(filesData, reactOrReactDOMDevelopmentFile) { - for (let {outputFile, text} of filesData) { - const folderName = path.parse(reactOrReactDOMDevelopmentFile).name - const targetPath = path.resolve(PATH_BUILD_REACT, `${folderName}/${outputFile}`) - const folerPath = path.dirname(targetPath) - !fs.existsSync(folerPath) && fs.mkdirSync(folerPath, {recursive: true}) - fs.writeFileSync(targetPath, text, {encoding: 'utf-8'}) - } -} - -function copyDependencies() { - const dependencyPaths = [ - PATH_DEPENDENCY_SOURCE_BABEL, - PATH_DEPENDENCY_SOURCE_DEPENDENCY_MAIN, - PATH_DEPENDENCY_SOURCE_DEFAULT_JS, - PATH_DEPENDENCY_SOURCE_DEFAULT, - ] - for (let file of dependencyPaths) { - const filename = path.parse(file).base.replace(/^source-/, '') - const targetPath = path.resolve(PATH_BUILD_REACT, filename) - fs.copyFileSync(file, targetPath) - } -} - - -function generateDependencyReactDOMHTML(reactDOMFilesData, reactDOMFile) { - const namespace = getReactOrReactDOMNamespace(reactDOMFile) - const dependencyFolerName = path.parse(reactDOMFile).name - const mainText = reactDOMFilesData.map(v => ``).join('\n') - const text = ` - - - - - Dependency ${namespace} - - - ${mainText} - - - - ` - const targetPath = path.resolve(PATH_BUILD_REACT, NAME_DEPENDENCY_REACT_DOM) - fs.writeFileSync(targetPath, text, {encoding: 'utf-8'}) -} - -function generateDependencyReactHTML(reactFilesData, reactFile) { - const namespace = getReactOrReactDOMNamespace(reactFile) - const dependencyFolerName = path.parse(reactFile).name - const mainText = reactFilesData.map(v => ``).join('\n') - const text = ` - - - - - Dependency ${namespace} - - ${mainText} - - - - - - ` - const targetPath = path.resolve(PATH_BUILD_REACT, NAME_DEPENDENCY_REACT) - fs.writeFileSync(targetPath, text, {encoding: 'utf-8'}) -} - -async function takeOnReactReactDOMFiles() { - await trash(PATH_BUILD_REACT) - const PATH_REACT_DEVELOPMENT = path.resolve(PATH_REACT, `build/node_modules/react/umd/react.development.js`) - const PATH_REACT_DOM_DEVELOPMENT = path.resolve(PATH_REACT, `build/node_modules/react-dom/umd/react-dom.development.js`) - - const reactFilesData = getReactOrReactDOMSplitFilesData(PATH_REACT_DEVELOPMENT) - generateReactOrReactDOMSplitFiles(reactFilesData, PATH_REACT_DEVELOPMENT) - generateDependencyReactHTML(reactFilesData, PATH_REACT_DEVELOPMENT) - - const reactDOMFilesData = getReactOrReactDOMSplitFilesData(PATH_REACT_DOM_DEVELOPMENT) - generateReactOrReactDOMSplitFiles(reactDOMFilesData, PATH_REACT_DOM_DEVELOPMENT) - generateDependencyReactDOMHTML(reactDOMFilesData, PATH_REACT_DOM_DEVELOPMENT) - - copyDependencies() - console.log(`$$ DEBUG REACT SOURCE CODE: built ${path.parse(PATH_BUILD_REACT).name} to ${PATH_BUILD_REACT}!`) -} - - -generateNewBuildJS();installDependencies( () => build( takeOnReactReactDOMFiles )) -// build() -// takeOnReactReactDOMFiles() - - -module.exports.getReactOrReactDOMSplitFilesData = getReactOrReactDOMSplitFilesData -module.exports.generateReactOrReactDOMSplitFiles = generateReactOrReactDOMSplitFiles -module.exports.copyDependencies = copyDependencies -module.exports.generateDependencyReactDOMHTML = generateDependencyReactDOMHTML -module.exports.generateDependencyReactHTML = generateDependencyReactHTML -module.exports.PATH_REACT = PATH_REACT diff --git a/package.json b/package.json index bab0bf3..676b4c7 100644 --- a/package.json +++ b/package.json @@ -4,9 +4,7 @@ "description": "", "main": "index.js", "scripts": { - "start": "node index.js", - "serve": "serve build", - "test": "node test/test.js" + "start": "cd ./react-16.6.0 && http-server -p 6001" }, "repository": { "type": "git", @@ -20,7 +18,6 @@ }, "homepage": "https://github.com/Terry-Su/debug-react-source-code#readme", "devDependencies": { - "serve": "^11.3.2", - "trash": "^6.1.1" + "http-server": "^0.12.3" } } diff --git a/dependencies/source-babel.js b/react-16.6.0/babel.js similarity index 100% rename from dependencies/source-babel.js rename to react-16.6.0/babel.js diff --git a/dependencies/source-dependency-main.html b/react-16.6.0/dependency-main.html similarity index 100% rename from dependencies/source-dependency-main.html rename to react-16.6.0/dependency-main.html diff --git a/react-16.6.0/dependency-react-dom.html b/react-16.6.0/dependency-react-dom.html new file mode 100644 index 0000000..ebc5eab --- /dev/null +++ b/react-16.6.0/dependency-react-dom.html @@ -0,0 +1,158 @@ + + + + + + Dependency ReactDOM + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/react-16.6.0/dependency-react.html b/react-16.6.0/dependency-react.html new file mode 100644 index 0000000..24d028d --- /dev/null +++ b/react-16.6.0/dependency-react.html @@ -0,0 +1,55 @@ + + + + + + Dependency React + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dependencies/source-index.html b/react-16.6.0/index.html similarity index 100% rename from dependencies/source-index.html rename to react-16.6.0/index.html diff --git a/dependencies/source-index.js b/react-16.6.0/index.js similarity index 100% rename from dependencies/source-index.js rename to react-16.6.0/index.js diff --git a/react-16.6.0/react-dom.development/$$umd/line-number-19486.js b/react-16.6.0/react-dom.development/$$umd/line-number-19486.js new file mode 100644 index 0000000..b015117 --- /dev/null +++ b/react-16.6.0/react-dom.development/$$umd/line-number-19486.js @@ -0,0 +1,6 @@ + +var ReactDOM$2 = Object.freeze({ + default: ReactDOM +}); + +var ReactDOM$3 = ( ReactDOM$2 && ReactDOM ) || ReactDOM$2; diff --git a/react-16.6.0/react-dom.development/$$umd/line-number-19500.js b/react-16.6.0/react-dom.development/$$umd/line-number-19500.js new file mode 100644 index 0000000..d0420aa --- /dev/null +++ b/react-16.6.0/react-dom.development/$$umd/line-number-19500.js @@ -0,0 +1,2 @@ + +// return reactDom; diff --git a/react-16.6.0/react-dom.development/node_modules/prop-types/checkPropTypes.js b/react-16.6.0/react-dom.development/node_modules/prop-types/checkPropTypes.js new file mode 100644 index 0000000..01bfdec --- /dev/null +++ b/react-16.6.0/react-dom.development/node_modules/prop-types/checkPropTypes.js @@ -0,0 +1,92 @@ +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + +var printWarning = function() {}; + +{ + var ReactPropTypesSecret = ReactPropTypesSecret_1; + var loggedTypeFailures = {}; + + printWarning = function(text) { + var message = 'Warning: ' + text; + if (typeof console !== 'undefined') { + console.error(message); + } + 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. + throw new Error(message); + } catch (x) {} + }; +} + +/** + * Assert that the values match with the type specs. + * Error messages are memorized and will only be shown once. + * + * @param {object} typeSpecs Map of name to a ReactPropType + * @param {object} values Runtime values that need to be type-checked + * @param {string} location e.g. "prop", "context", "child context" + * @param {string} componentName Name of the component for error messages. + * @param {?Function} getStack Returns the component stack. + * @private + */ +function checkPropTypes(typeSpecs, values, location, componentName, getStack) { + { + for (var typeSpecName in typeSpecs) { + if (typeSpecs.hasOwnProperty(typeSpecName)) { + var error; + // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + 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] + '`.' + ); + err.name = 'Invariant Violation'; + throw err; + } + error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); + } catch (ex) { + error = ex; + } + if (error && !(error instanceof Error)) { + printWarning( + (componentName || 'React class') + ': type specification of ' + + location + ' `' + typeSpecName + '` is invalid; the type checker ' + + 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' + + 'You may have forgotten to pass an argument to the type checker ' + + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + + 'shape all require an argument).' + ); + + } + if (error instanceof Error && !(error.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error.message] = true; + + var stack = getStack ? getStack() : ''; + + printWarning( + 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '') + ); + } + } + } + } +} + +var checkPropTypes_1 = checkPropTypes; + diff --git a/react-16.6.0/react-dom.development/node_modules/prop-types/lib/ReactPropTypesSecret.js b/react-16.6.0/react-dom.development/node_modules/prop-types/lib/ReactPropTypesSecret.js new file mode 100644 index 0000000..d567221 --- /dev/null +++ b/react-16.6.0/react-dom.development/node_modules/prop-types/lib/ReactPropTypesSecret.js @@ -0,0 +1,13 @@ +/** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + +var ReactPropTypesSecret$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; + +var ReactPropTypesSecret_1 = ReactPropTypesSecret$1; + diff --git a/react-16.6.0/react-dom.development/packages/events/EventPluginHub.js b/react-16.6.0/react-dom.development/packages/events/EventPluginHub.js new file mode 100644 index 0000000..020966d --- /dev/null +++ b/react-16.6.0/react-dom.development/packages/events/EventPluginHub.js @@ -0,0 +1,168 @@ +/** + * 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. + * + * @param {?object} event Synthetic event to be dispatched. + * @param {boolean} simulated If the event is simulated (changes exn behavior) + * @private + */ +var executeDispatchesAndRelease = function (event, simulated) { + if (event) { + executeDispatchesInOrder(event, simulated); + + if (!event.isPersistent()) { + event.constructor.release(event); + } + } +}; +var executeDispatchesAndReleaseSimulated = function (e) { + return executeDispatchesAndRelease(e, true); +}; +var executeDispatchesAndReleaseTopLevel = function (e) { + return executeDispatchesAndRelease(e, false); +}; + +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; + } +} + +/** + * 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 + */ + +/** + * Methods for injecting dependencies. + */ +var injection = { + /** + * @param {array} InjectedEventPluginOrder + * @public + */ + injectEventPluginOrder: injectEventPluginOrder, + + /** + * @param {object} injectedNamesToPlugins Map from names to plugin modules. + */ + injectEventPluginsByName: injectEventPluginsByName +}; + +/** + * @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. + */ +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; + } + !(!listener || typeof listener === 'function') ? invariant(false, 'Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener) : void 0; + return listener; +} + +/** + * Allows registered plugins an opportunity to extract events from top-level + * native browser events. + * + * @return {*} An accumulation of synthetic events. + * @internal + */ +function extractEvents(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 runEventsInBatch(events, simulated) { + if (events !== null) { + eventQueue = accumulateInto(eventQueue, events); + } + + // 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 (!processingEventQueue) { + return; + } + + if (simulated) { + forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated); + } else { + forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); + } + !!eventQueue ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.') : void 0; + // This would be a good time to rethrow if any of the event handlers threw. + rethrowCaughtError(); +} + +function runExtractedEventsInBatch(topLevelType, targetInst, nativeEvent, nativeEventTarget) { + var events = extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); + runEventsInBatch(events, false); +} \ No newline at end of file diff --git a/react-16.6.0/react-dom.development/packages/events/EventPluginRegistry.js b/react-16.6.0/react-dom.development/packages/events/EventPluginRegistry.js new file mode 100644 index 0000000..3615ced --- /dev/null +++ b/react-16.6.0/react-dom.development/packages/events/EventPluginRegistry.js @@ -0,0 +1,164 @@ +/** + * 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); + !(pluginIndex > -1) ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.', pluginName) : void 0; + if (plugins[pluginIndex]) { + continue; + } + !pluginModule.extractEvents ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.', pluginName) : void 0; + plugins[pluginIndex] = pluginModule; + var publishedEvents = pluginModule.eventTypes; + for (var eventName in publishedEvents) { + !publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName) ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : void 0; + } + } +} + +/** + * 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) { + !!eventNameDispatchConfigs.hasOwnProperty(eventName) ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.', eventName) : void 0; + 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; + } + 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) { + !!registrationNameModules[registrationName] ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.', registrationName) : void 0; + registrationNameModules[registrationName] = pluginModule; + registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; + + { + 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} + */ + +/** + * Ordered list of injected plugins. + */ +var plugins = []; + +/** + * Mapping from event name to dispatch config + */ +var eventNameDispatchConfigs = {}; + +/** + * Mapping from registration name to plugin module + */ +var registrationNameModules = {}; + +/** + * 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. + * + * @param {array} InjectedEventPluginOrder + * @internal + * @see {EventPluginHub.injection.injectEventPluginOrder} + */ +function injectEventPluginOrder(injectedEventPluginOrder) { + !!eventPluginOrder ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.') : void 0; + // Clone the ordering so it cannot be dynamically mutated. + eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); + recomputePluginOrdering(); +} + +/** + * 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) { + !!namesToPlugins[pluginName] ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.', pluginName) : void 0; + namesToPlugins[pluginName] = pluginModule; + isOrderingDirty = true; + } + } + if (isOrderingDirty) { + recomputePluginOrdering(); + } +} \ No newline at end of file diff --git a/react-16.6.0/react-dom.development/packages/events/EventPluginUtils.js b/react-16.6.0/react-dom.development/packages/events/EventPluginUtils.js new file mode 100644 index 0000000..b5d015e --- /dev/null +++ b/react-16.6.0/react-dom.development/packages/events/EventPluginUtils.js @@ -0,0 +1,87 @@ +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; + } +} + +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; + }; +} + +/** + * Dispatch the event to the listener. + * @param {SyntheticEvent} event SyntheticEvent to handle + * @param {boolean} simulated If the event is simulated (changes exn behavior) + * @param {function} listener Application-level callback + * @param {*} inst Internal component instance + */ +function executeDispatch(event, simulated, 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, simulated) { + 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. + executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); + } + } else if (dispatchListeners) { + executeDispatch(event, simulated, dispatchListeners, dispatchInstances); + } + event._dispatchListeners = null; + event._dispatchInstances = null; +} + +/** + * @see executeDispatchesInOrderStopAtTrueImpl + */ + + +/** + * 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. + */ + + +/** + * @param {SyntheticEvent} event + * @return {boolean} True iff number of dispatches accumulated is greater than 0. + */ diff --git a/react-16.6.0/react-dom.development/packages/events/EventPropagators.js b/react-16.6.0/react-dom.development/packages/events/EventPropagators.js new file mode 100644 index 0000000..34d0336 --- /dev/null +++ b/react-16.6.0/react-dom.development/packages/events/EventPropagators.js @@ -0,0 +1,89 @@ +/** + * 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); +} + +/** + * 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. + */ + +/** + * 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); + } +} + +/** + * 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); + } +} + +/** + * 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); + } + } +} + +/** + * 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 accumulateTwoPhaseDispatches(events) { + forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); +} + + + +function accumulateEnterLeaveDispatches(leave, enter, from, to) { + traverseEnterLeave(from, to, accumulateDispatches, leave, enter); +} + +function accumulateDirectDispatches(events) { + forEachAccumulated(events, accumulateDirectDispatchesSingle); +} \ No newline at end of file diff --git a/react-16.6.0/react-dom.development/packages/events/ReactControlledComponent.js b/react-16.6.0/react-dom.development/packages/events/ReactControlledComponent.js new file mode 100644 index 0000000..5e046fa --- /dev/null +++ b/react-16.6.0/react-dom.development/packages/events/ReactControlledComponent.js @@ -0,0 +1,55 @@ +// 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; + } + !(typeof restoreImpl === 'function') ? invariant(false, '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.') : void 0; + var props = getFiberCurrentPropsFromNode(internalInstance.stateNode); + restoreImpl(internalInstance.stateNode, internalInstance.type, props); +} + +function setRestoreImplementation(impl) { + restoreImpl = impl; +} + +function enqueueStateRestore(target) { + if (restoreTarget) { + if (restoreQueue) { + restoreQueue.push(target); + } else { + restoreQueue = [target]; + } + } else { + restoreTarget = target; + } +} + +function needsStateRestore() { + return restoreTarget !== null || restoreQueue !== null; +} + +function restoreStateIfNeeded() { + if (!restoreTarget) { + return; + } + 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]); + } + } +} \ No newline at end of file diff --git a/react-16.6.0/react-dom.development/packages/events/ReactGenericBatching.js b/react-16.6.0/react-dom.development/packages/events/ReactGenericBatching.js new file mode 100644 index 0000000..565d3d3 --- /dev/null +++ b/react-16.6.0/react-dom.development/packages/events/ReactGenericBatching.js @@ -0,0 +1,53 @@ +// 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. + +// Defaults +var _batchedUpdatesImpl = function (fn, bookkeeping) { + return fn(bookkeeping); +}; +var _interactiveUpdatesImpl = function (fn, a, b) { + return fn(a, b); +}; +var _flushInteractiveUpdatesImpl = function () {}; + +var isBatching = false; +function batchedUpdates(fn, bookkeeping) { + if (isBatching) { + // If we are currently inside another batch, we need to wait until it + // fully completes before restoring state. + return fn(bookkeeping); + } + isBatching = true; + try { + return _batchedUpdatesImpl(fn, bookkeeping); + } finally { + // 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. + isBatching = false; + 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. + _flushInteractiveUpdatesImpl(); + restoreStateIfNeeded(); + } + } +} + +function interactiveUpdates(fn, a, b) { + return _interactiveUpdatesImpl(fn, a, b); +} + + + +function setBatchingImplementation(batchedUpdatesImpl, interactiveUpdatesImpl, flushInteractiveUpdatesImpl) { + _batchedUpdatesImpl = batchedUpdatesImpl; + _interactiveUpdatesImpl = interactiveUpdatesImpl; + _flushInteractiveUpdatesImpl = flushInteractiveUpdatesImpl; +} \ No newline at end of file diff --git a/react-16.6.0/react-dom.development/packages/events/SyntheticEvent.js b/react-16.6.0/react-dom.development/packages/events/SyntheticEvent.js new file mode 100644 index 0000000..836016d --- /dev/null +++ b/react-16.6.0/react-dom.development/packages/events/SyntheticEvent.js @@ -0,0 +1,261 @@ +/* eslint valid-typeof: 0 */ + +var EVENT_POOL_SIZE = 10; + +/** + * @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 +}; + +function functionThatReturnsTrue() { + return true; +} + +function functionThatReturnsFalse() { + return false; +} + +/** + * 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; + } + + 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 defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; + if (defaultPrevented) { + this.isDefaultPrevented = functionThatReturnsTrue; + } else { + this.isDefaultPrevented = functionThatReturnsFalse; + } + this.isPropagationStopped = functionThatReturnsFalse; + return this; +} + +_assign(SyntheticEvent.prototype, { + preventDefault: function () { + this.defaultPrevented = true; + var event = this.nativeEvent; + if (!event) { + return; + } + + if (event.preventDefault) { + event.preventDefault(); + } else if (typeof event.returnValue !== 'unknown') { + event.returnValue = false; + } + this.isDefaultPrevented = functionThatReturnsTrue; + }, + + stopPropagation: function () { + var event = this.nativeEvent; + if (!event) { + return; + } + + 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; + } + + this.isPropagationStopped = functionThatReturnsTrue; + }, + + /** + * 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; + }, + + /** + * Checks if this event should be released back into the pool. + * + * @return {boolean} True if this should not be released, false otherwise. + */ + isPersistent: functionThatReturnsFalse, + + /** + * `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 () {})); + } + } +}); + +SyntheticEvent.Interface = EventInterface; + +/** + * 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(); + + function Class() { + return Super.apply(this, arguments); + } + _assign(prototype, Class.prototype); + Class.prototype = prototype; + Class.prototype.constructor = Class; + + Class.Interface = _assign({}, Super.Interface, Interface); + Class.extend = Super.extend; + addEventPoolingTo(Class); + + return Class; +}; + +addEventPoolingTo(SyntheticEvent); + +/** + * 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 + }; + + function set(val) { + var action = isFunction ? 'setting the method' : 'setting the property'; + warn(action, 'This is effectively a no-op'); + return val; + } + + 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; + } + + 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); +} + +function releasePooledEvent(event) { + var EventConstructor = this; + !(event instanceof EventConstructor) ? invariant(false, 'Trying to release an event instance into a pool of a different type.') : void 0; + event.destructor(); + if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) { + EventConstructor.eventPool.push(event); + } +} + +function addEventPoolingTo(EventConstructor) { + EventConstructor.eventPool = []; + EventConstructor.getPooled = getPooledEvent; + EventConstructor.release = releasePooledEvent; +} + diff --git a/react-16.6.0/react-dom.development/packages/events/TopLevelEventTypes.js b/react-16.6.0/react-dom.development/packages/events/TopLevelEventTypes.js new file mode 100644 index 0000000..c80a5e2 --- /dev/null +++ b/react-16.6.0/react-dom.development/packages/events/TopLevelEventTypes.js @@ -0,0 +1,13 @@ + + +// Do not uses 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.) + +function unsafeCastStringToDOMTopLevelType(topLevelType) { + return topLevelType; +} + +function unsafeCastDOMTopLevelTypeToString(topLevelType) { + return topLevelType; +} \ No newline at end of file diff --git a/react-16.6.0/react-dom.development/packages/events/accumulateInto.js b/react-16.6.0/react-dom.development/packages/events/accumulateInto.js new file mode 100644 index 0000000..6027b6e --- /dev/null +++ b/react-16.6.0/react-dom.development/packages/events/accumulateInto.js @@ -0,0 +1,39 @@ +/** + * 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. + * + * @return {*|array<*>} An accumulation of items. + */ + +function accumulateInto(current, next) { + !(next != null) ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : void 0; + + 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; + } + current.push(next); + return current; + } + + if (Array.isArray(next)) { + // A bit too dangerous to mutate `next`. + return [current].concat(next); + } + + return [current, next]; +} + diff --git a/react-16.6.0/react-dom.development/packages/events/forEachAccumulated.js b/react-16.6.0/react-dom.development/packages/events/forEachAccumulated.js new file mode 100644 index 0000000..950aa82 --- /dev/null +++ b/react-16.6.0/react-dom.development/packages/events/forEachAccumulated.js @@ -0,0 +1,17 @@ +/** + * @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); + } +} + diff --git a/react-16.6.0/react-dom.development/packages/react-dom/index.js b/react-16.6.0/react-dom.development/packages/react-dom/index.js new file mode 100644 index 0000000..29e66b5 --- /dev/null +++ b/react-16.6.0/react-dom.development/packages/react-dom/index.js @@ -0,0 +1,8 @@ + + + + +// TODO: decide on the top-level export form. +// This is hacky but makes it work with both Rollup and Jest. +var reactDom = ReactDOM$3.default || ReactDOM$3; + diff --git a/react-16.6.0/react-dom.development/packages/react-dom/src/client/DOMPropertyOperations.js b/react-16.6.0/react-dom.development/packages/react-dom/src/client/DOMPropertyOperations.js new file mode 100644 index 0000000..e4693cf --- /dev/null +++ b/react-16.6.0/react-dom.development/packages/react-dom/src/client/DOMPropertyOperations.js @@ -0,0 +1,147 @@ +/** + * 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. + */ +function getValueForProperty(node, name, expected, propertyInfo) { + { + if (propertyInfo.mustUseProperty) { + var propertyName = propertyInfo.propertyName; + + return node[propertyName]; + } else { + var attributeName = propertyInfo.attributeName; + + var stringValue = null; + + if (propertyInfo.type === OVERLOADED_BOOLEAN) { + if (node.hasAttribute(attributeName)) { + var value = node.getAttribute(attributeName); + if (value === '') { + return true; + } + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + return value; + } + if (value === '' + expected) { + return expected; + } + 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); + } + 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. + stringValue = node.getAttribute(attributeName); + } + + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + return stringValue === null ? expected : stringValue; + } else if (stringValue === '' + expected) { + return expected; + } else { + return stringValue; + } + } + } +} + +/** + * 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 getValueForAttribute(node, name, expected) { + { + if (!isAttributeNameSafe(name)) { + return; + } + if (!node.hasAttribute(name)) { + return expected === undefined ? undefined : null; + } + var value = node.getAttribute(name); + if (value === '' + expected) { + return expected; + } + return value; + } +} + +/** + * Sets the value for a property on a node. + * + * @param {DOMElement} node + * @param {string} name + * @param {*} value + */ +function setValueForProperty(node, name, value, isCustomComponentTag) { + var propertyInfo = getPropertyInfo(name); + if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) { + return; + } + if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) { + value = null; + } + // If the prop isn't in the special list, treat it as a simple attribute. + if (isCustomComponentTag || propertyInfo === null) { + if (isAttributeNameSafe(name)) { + var _attributeName = name; + if (value === null) { + node.removeAttribute(_attributeName); + } else { + node.setAttribute(_attributeName, '' + value); + } + } + return; + } + var mustUseProperty = propertyInfo.mustUseProperty; + + 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; + } + return; + } + // The rest are treated as attributes with special cases. + var attributeName = propertyInfo.attributeName, + attributeNamespace = propertyInfo.attributeNamespace; + + if (value === null) { + node.removeAttribute(attributeName); + } else { + var _type = propertyInfo.type; + + var attributeValue = void 0; + if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) { + attributeValue = ''; + } else { + // `setAttribute` with objects becomes only `[object]` in IE8/9, + // ('' + value) makes it output the correct toString()-value. + attributeValue = '' + value; + } + if (attributeNamespace) { + node.setAttributeNS(attributeNamespace, attributeName, attributeValue); + } else { + node.setAttribute(attributeName, attributeValue); + } + } +} \ No newline at end of file diff --git a/react-16.6.0/react-dom.development/packages/react-dom/src/client/ReactDOM.js b/react-16.6.0/react-dom.development/packages/react-dom/src/client/ReactDOM.js new file mode 100644 index 0000000..dc9c88c --- /dev/null +++ b/react-16.6.0/react-dom.development/packages/react-dom/src/client/ReactDOM.js @@ -0,0 +1,485 @@ +// TODO: This type is shared between the reconciler and ReactDOM, but will +// eventually be lifted out to the renderer. +var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; + +var topLevelUpdateWarnings = void 0; +var warnOnInvalidCallback = void 0; +var didWarnAboutUnstableCreatePortal = false; + +{ + if (typeof Map !== 'function' || + // $FlowIssue Flow incorrectly thinks Map has no prototype + Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' || + // $FlowIssue Flow incorrectly thinks Set has no prototype + Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') { + warningWithoutStack$1(false, 'React depends on Map and Set built-in types. Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills'); + } + + topLevelUpdateWarnings = function (container) { + if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) { + var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current); + if (hostInstance) { + !(hostInstance.parentNode === container) ? warningWithoutStack$1(false, 'render(...): It looks like the React-rendered content of this ' + 'container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + 'ReactDOM.unmountComponentAtNode to empty a container.') : void 0; + } + } + + var isRootRenderedBySomeReact = !!container._reactRootContainer; + var rootEl = getReactRootElementInContainer(container); + var hasNonRootReactChild = !!(rootEl && getInstanceFromNode$1(rootEl)); + + !(!hasNonRootReactChild || isRootRenderedBySomeReact) ? warningWithoutStack$1(false, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : void 0; + + !(container.nodeType !== ELEMENT_NODE || !container.tagName || container.tagName.toUpperCase() !== 'BODY') ? warningWithoutStack$1(false, 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : void 0; + }; + + warnOnInvalidCallback = function (callback, callerName) { + !(callback === null || typeof callback === 'function') ? warningWithoutStack$1(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback) : void 0; + }; +} + +setRestoreImplementation(restoreControlledState$1); + +function ReactBatch(root) { + var expirationTime = computeUniqueAsyncExpiration(); + this._expirationTime = expirationTime; + this._root = root; + this._next = null; + this._callbacks = null; + this._didComplete = false; + this._hasChildren = false; + this._children = null; + this._defer = true; +} +ReactBatch.prototype.render = function (children) { + !this._defer ? invariant(false, 'batch.render: Cannot render a batch that already committed.') : void 0; + this._hasChildren = true; + this._children = children; + var internalRoot = this._root._internalRoot; + var expirationTime = this._expirationTime; + var work = new ReactWork(); + updateContainerAtExpirationTime(children, internalRoot, null, expirationTime, work._onCommit); + return work; +}; +ReactBatch.prototype.then = function (onComplete) { + if (this._didComplete) { + onComplete(); + return; + } + var callbacks = this._callbacks; + if (callbacks === null) { + callbacks = this._callbacks = []; + } + callbacks.push(onComplete); +}; +ReactBatch.prototype.commit = function () { + var internalRoot = this._root._internalRoot; + var firstBatch = internalRoot.firstBatch; + !(this._defer && firstBatch !== null) ? invariant(false, 'batch.commit: Cannot commit a batch multiple times.') : void 0; + + if (!this._hasChildren) { + // This batch is empty. Return. + this._next = null; + this._defer = false; + return; + } + + var expirationTime = this._expirationTime; + + // Ensure this is the first batch in the list. + if (firstBatch !== this) { + // This batch is not the earliest batch. We need to move it to the front. + // Update its expiration time to be the expiration time of the earliest + // batch, so that we can flush it without flushing the other batches. + if (this._hasChildren) { + expirationTime = this._expirationTime = firstBatch._expirationTime; + // Rendering this batch again ensures its children will be the final state + // when we flush (updates are processed in insertion order: last + // update wins). + // TODO: This forces a restart. Should we print a warning? + this.render(this._children); + } + + // Remove the batch from the list. + var previous = null; + var batch = firstBatch; + while (batch !== this) { + previous = batch; + batch = batch._next; + } + !(previous !== null) ? invariant(false, 'batch.commit: Cannot commit a batch multiple times.') : void 0; + previous._next = batch._next; + + // Add it to the front. + this._next = firstBatch; + firstBatch = internalRoot.firstBatch = this; + } + + // Synchronously flush all the work up to this batch's expiration time. + this._defer = false; + flushRoot(internalRoot, expirationTime); + + // Pop the batch from the list. + var next = this._next; + this._next = null; + firstBatch = internalRoot.firstBatch = next; + + // Append the next earliest batch's children to the update queue. + if (firstBatch !== null && firstBatch._hasChildren) { + firstBatch.render(firstBatch._children); + } +}; +ReactBatch.prototype._onComplete = function () { + if (this._didComplete) { + return; + } + this._didComplete = true; + var callbacks = this._callbacks; + if (callbacks === null) { + return; + } + // TODO: Error handling. + for (var i = 0; i < callbacks.length; i++) { + var _callback = callbacks[i]; + _callback(); + } +}; + +function ReactWork() { + this._callbacks = null; + this._didCommit = false; + // TODO: Avoid need to bind by replacing callbacks in the update queue with + // list of Work objects. + this._onCommit = this._onCommit.bind(this); +} +ReactWork.prototype.then = function (onCommit) { + if (this._didCommit) { + onCommit(); + return; + } + var callbacks = this._callbacks; + if (callbacks === null) { + callbacks = this._callbacks = []; + } + callbacks.push(onCommit); +}; +ReactWork.prototype._onCommit = function () { + if (this._didCommit) { + return; + } + this._didCommit = true; + var callbacks = this._callbacks; + if (callbacks === null) { + return; + } + // TODO: Error handling. + for (var i = 0; i < callbacks.length; i++) { + var _callback2 = callbacks[i]; + !(typeof _callback2 === 'function') ? invariant(false, 'Invalid argument passed as callback. Expected a function. Instead received: %s', _callback2) : void 0; + _callback2(); + } +}; + +function ReactRoot(container, isConcurrent, hydrate) { + var root = createContainer(container, isConcurrent, hydrate); + this._internalRoot = root; +} +ReactRoot.prototype.render = function (children, callback) { + var root = this._internalRoot; + var work = new ReactWork(); + callback = callback === undefined ? null : callback; + { + warnOnInvalidCallback(callback, 'render'); + } + if (callback !== null) { + work.then(callback); + } + updateContainer(children, root, null, work._onCommit); + return work; +}; +ReactRoot.prototype.unmount = function (callback) { + var root = this._internalRoot; + var work = new ReactWork(); + callback = callback === undefined ? null : callback; + { + warnOnInvalidCallback(callback, 'render'); + } + if (callback !== null) { + work.then(callback); + } + updateContainer(null, root, null, work._onCommit); + return work; +}; +ReactRoot.prototype.legacy_renderSubtreeIntoContainer = function (parentComponent, children, callback) { + var root = this._internalRoot; + var work = new ReactWork(); + callback = callback === undefined ? null : callback; + { + warnOnInvalidCallback(callback, 'render'); + } + if (callback !== null) { + work.then(callback); + } + updateContainer(children, root, parentComponent, work._onCommit); + return work; +}; +ReactRoot.prototype.createBatch = function () { + var batch = new ReactBatch(this); + var expirationTime = batch._expirationTime; + + var internalRoot = this._internalRoot; + var firstBatch = internalRoot.firstBatch; + if (firstBatch === null) { + internalRoot.firstBatch = batch; + batch._next = null; + } else { + // Insert sorted by expiration time then insertion order + var insertAfter = null; + var insertBefore = firstBatch; + while (insertBefore !== null && insertBefore._expirationTime <= expirationTime) { + insertAfter = insertBefore; + insertBefore = insertBefore._next; + } + batch._next = insertBefore; + if (insertAfter !== null) { + insertAfter._next = batch; + } + } + + return batch; +}; + +/** + * True if the supplied DOM node is a valid node element. + * + * @param {?DOMElement} node The candidate DOM node. + * @return {boolean} True if the DOM is a valid DOM node. + * @internal + */ +function isValidContainer(node) { + return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-mount-point-unstable ')); +} + +function getReactRootElementInContainer(container) { + if (!container) { + return null; + } + + if (container.nodeType === DOCUMENT_NODE) { + return container.documentElement; + } else { + return container.firstChild; + } +} + +function shouldHydrateDueToLegacyHeuristic(container) { + var rootElement = getReactRootElementInContainer(container); + return !!(rootElement && rootElement.nodeType === ELEMENT_NODE && rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME)); +} + +setBatchingImplementation(batchedUpdates$1, interactiveUpdates$1, flushInteractiveUpdates$1); + +var warnedAboutHydrateAPI = false; + +function legacyCreateRootFromDOMContainer(container, forceHydrate) { + var shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container); + // First clear any existing content. + if (!shouldHydrate) { + var warned = false; + var rootSibling = void 0; + while (rootSibling = container.lastChild) { + { + if (!warned && rootSibling.nodeType === ELEMENT_NODE && rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)) { + warned = true; + warningWithoutStack$1(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.'); + } + } + container.removeChild(rootSibling); + } + } + { + if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) { + warnedAboutHydrateAPI = true; + lowPriorityWarning$1(false, 'render(): Calling ReactDOM.render() to hydrate server-rendered markup ' + 'will stop working in React v17. Replace the ReactDOM.render() call ' + 'with ReactDOM.hydrate() if you want React to attach to the server HTML.'); + } + } + // Legacy roots are not async by default. + var isConcurrent = false; + return new ReactRoot(container, isConcurrent, shouldHydrate); +} + +function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) { + // TODO: Ensure all entry points contain this check + !isValidContainer(container) ? invariant(false, 'Target container is not a DOM element.') : void 0; + + { + topLevelUpdateWarnings(container); + } + + // TODO: Without `any` type, Flow says "Property cannot be accessed on any + // member of intersection type." Whyyyyyy. + var root = container._reactRootContainer; + if (!root) { + // Initial mount + root = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate); + if (typeof callback === 'function') { + var originalCallback = callback; + callback = function () { + var instance = getPublicRootInstance(root._internalRoot); + originalCallback.call(instance); + }; + } + // Initial mount should not be batched. + unbatchedUpdates(function () { + if (parentComponent != null) { + root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback); + } else { + root.render(children, callback); + } + }); + } else { + if (typeof callback === 'function') { + var _originalCallback = callback; + callback = function () { + var instance = getPublicRootInstance(root._internalRoot); + _originalCallback.call(instance); + }; + } + // Update + if (parentComponent != null) { + root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback); + } else { + root.render(children, callback); + } + } + return getPublicRootInstance(root._internalRoot); +} + +function createPortal(children, container) { + var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + !isValidContainer(container) ? invariant(false, 'Target container is not a DOM element.') : void 0; + // TODO: pass ReactDOM portal implementation as third argument + return createPortal$1(children, container, null, key); +} + +var ReactDOM = { + createPortal: createPortal, + + findDOMNode: function (componentOrElement) { + { + var owner = ReactCurrentOwner.current; + if (owner !== null && owner.stateNode !== null) { + var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender; + !warnedAboutRefsInRender ? warningWithoutStack$1(false, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(owner.type) || 'A component') : void 0; + owner.stateNode._warnedAboutRefsInRender = true; + } + } + if (componentOrElement == null) { + return null; + } + if (componentOrElement.nodeType === ELEMENT_NODE) { + return componentOrElement; + } + { + return findHostInstanceWithWarning(componentOrElement, 'findDOMNode'); + } + return findHostInstance(componentOrElement); + }, + hydrate: function (element, container, callback) { + // TODO: throw or warn if we couldn't hydrate? + return legacyRenderSubtreeIntoContainer(null, element, container, true, callback); + }, + render: function (element, container, callback) { + return legacyRenderSubtreeIntoContainer(null, element, container, false, callback); + }, + unstable_renderSubtreeIntoContainer: function (parentComponent, element, containerNode, callback) { + !(parentComponent != null && has(parentComponent)) ? invariant(false, 'parentComponent must be a valid React Component') : void 0; + return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback); + }, + unmountComponentAtNode: function (container) { + !isValidContainer(container) ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : void 0; + + if (container._reactRootContainer) { + { + var rootEl = getReactRootElementInContainer(container); + var renderedByDifferentReact = rootEl && !getInstanceFromNode$1(rootEl); + !!renderedByDifferentReact ? warningWithoutStack$1(false, "unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.') : void 0; + } + + // Unmount should not be batched. + unbatchedUpdates(function () { + legacyRenderSubtreeIntoContainer(null, null, container, false, function () { + container._reactRootContainer = null; + }); + }); + // If you call unmountComponentAtNode twice in quick succession, you'll + // get `true` twice. That's probably fine? + return true; + } else { + { + var _rootEl = getReactRootElementInContainer(container); + var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode$1(_rootEl)); + + // Check if the container itself is a React root node. + var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainer(container.parentNode) && !!container.parentNode._reactRootContainer; + + !!hasNonRootReactChild ? warningWithoutStack$1(false, "unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : void 0; + } + + return false; + } + }, + + + // Temporary alias since we already shipped React 16 RC with it. + // TODO: remove in React 17. + unstable_createPortal: function () { + if (!didWarnAboutUnstableCreatePortal) { + didWarnAboutUnstableCreatePortal = true; + lowPriorityWarning$1(false, 'The ReactDOM.unstable_createPortal() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactDOM.createPortal() instead. It has the exact same API, ' + 'but without the "unstable_" prefix.'); + } + return createPortal.apply(undefined, arguments); + }, + + + unstable_batchedUpdates: batchedUpdates$1, + + unstable_interactiveUpdates: interactiveUpdates$1, + + flushSync: flushSync, + + unstable_flushControlled: flushControlled, + + __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: { + // Keep in sync with ReactDOMUnstableNativeDependencies.js + // and ReactTestUtils.js. This is an array for better minification. + Events: [getInstanceFromNode$1, getNodeFromInstance$1, getFiberCurrentPropsFromNode$1, injection.injectEventPluginsByName, eventNameDispatchConfigs, accumulateTwoPhaseDispatches, accumulateDirectDispatches, enqueueStateRestore, restoreStateIfNeeded, dispatchEvent, runEventsInBatch] + } +}; + +ReactDOM.unstable_createRoot = function createRoot(container, options) { + !isValidContainer(container) ? invariant(false, 'unstable_createRoot(...): Target container is not a DOM element.') : void 0; + var hydrate = options != null && options.hydrate === true; + return new ReactRoot(container, true, hydrate); +}; + +var foundDevTools = injectIntoDevTools({ + findFiberByHostInstance: getClosestInstanceFromNode, + bundleType: 1, + version: ReactVersion, + rendererPackageName: 'react-dom' +}); + +{ + if (!foundDevTools && canUseDOM && window.top === window.self) { + // If we're in Chrome or Firefox, provide a download link if not installed. + if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) { + var protocol = window.location.protocol; + // Don't warn in exotic cases like chrome-extension://. + if (/^(https?|file):$/.test(protocol)) { + console.info('%cDownload the React DevTools ' + 'for a better development experience: ' + 'https://fb.me/react-devtools' + (protocol === 'file:' ? '\nYou might need to use a local HTTP server (instead of file://): ' + 'https://fb.me/react-devtools-faq' : ''), 'font-weight:bold'); + } + } + } +} + diff --git a/react-16.6.0/react-dom.development/packages/react-dom/src/client/ReactDOMClientInjection.js b/react-16.6.0/react-dom.development/packages/react-dom/src/client/ReactDOMClientInjection.js new file mode 100644 index 0000000..9949703 --- /dev/null +++ b/react-16.6.0/react-dom.development/packages/react-dom/src/client/ReactDOMClientInjection.js @@ -0,0 +1,17 @@ +/** + * Inject modules for resolving DOM hierarchy and plugin ordering. + */ +injection.injectEventPluginOrder(DOMEventPluginOrder); +setComponentTree(getFiberCurrentPropsFromNode$1, getInstanceFromNode$1, getNodeFromInstance$1); + +/** + * Some important event plugins included by default (without having to require + * them). + */ +injection.injectEventPluginsByName({ + SimpleEventPlugin: SimpleEventPlugin, + EnterLeaveEventPlugin: EnterLeaveEventPlugin, + ChangeEventPlugin: ChangeEventPlugin, + SelectEventPlugin: SelectEventPlugin, + BeforeInputEventPlugin: BeforeInputEventPlugin +}); \ No newline at end of file diff --git a/react-16.6.0/react-dom.development/packages/react-dom/src/client/ReactDOMComponent.js b/react-16.6.0/react-dom.development/packages/react-dom/src/client/ReactDOMComponent.js new file mode 100644 index 0000000..b329e9c --- /dev/null +++ b/react-16.6.0/react-dom.development/packages/react-dom/src/client/ReactDOMComponent.js @@ -0,0 +1,937 @@ +// TODO: direct imports like some-package/src/* are bad. Fix me. +var didWarnInvalidHydration = false; +var didWarnShadyDOM = false; + +var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML'; +var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning'; +var SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning'; +var AUTOFOCUS = 'autoFocus'; +var CHILDREN = 'children'; +var STYLE$1 = 'style'; +var HTML = '__html'; + +var HTML_NAMESPACE = Namespaces.html; + + +var warnedUnknownTags = void 0; +var suppressHydrationWarning = void 0; + +var validatePropertiesInDevelopment = void 0; +var warnForTextDifference = void 0; +var warnForPropDifference = void 0; +var warnForExtraAttributes = void 0; +var warnForInvalidEventListener = void 0; +var canDiffStyleForHydrationWarning = void 0; + +var normalizeMarkupForTextOrAttribute = void 0; +var normalizeHTML = void 0; + +{ + warnedUnknownTags = { + // Chrome is the only major browser not shipping