@samitouri / QOS-React / commits / 21d0c11523

Convert the Source to ES Modules (#11389)

* Update transforms to handle ES modules * Update Jest to handle ES modules * Convert react package to ES modules * Convert react-art package to ES Modules * Convert react-call-return package to ES Modules * Convert react-test-renderer package to ES Modules * Convert react-cs-renderer package to ES Modules * Convert react-rt-renderer package to ES Modules * Convert react-noop-renderer package to ES Modules * Convert react-dom/server to ES modules * Convert react-dom/{client,events,test-utils} to ES modules * Convert react-dom/shared to ES modules * Convert react-native-renderer to ES modules * Convert react-reconciler to ES modules * Convert events to ES modules * Convert shared to ES modules * Remove CommonJS support from transforms * Move ReactDOMFB entry point code into react-dom/src This is clearer because we can use ES imports in it. * Fix Rollup shim configuration to work with ESM * Fix incorrect comment * Exclude external imports without side effects * Fix ReactDOM FB build * Remove TODOs I don’t intend to fix yet

Dan Abramov committed Nov 2, 2017 at 19:50 UTC 21d0c115238b4f38837020cf83e0c657d8c01c9f
234 files changed +3236 -3439
packages/events/EventPluginHub.js
+7 -7
@@ -7,13 +7,13 @@
7
8 'use strict';
9
10 -var ReactErrorUtils = require('shared/ReactErrorUtils');
11 -var invariant = require('fbjs/lib/invariant');
10 +import ReactErrorUtils from 'shared/ReactErrorUtils';
11 +import invariant from 'fbjs/lib/invariant';
12
13 -var EventPluginRegistry = require('./EventPluginRegistry');
14 -var EventPluginUtils = require('./EventPluginUtils');
15 -var accumulateInto = require('./accumulateInto');
16 -var forEachAccumulated = require('./forEachAccumulated');
13 +import EventPluginRegistry from './EventPluginRegistry';
14 +import EventPluginUtils from './EventPluginUtils';
15 +import accumulateInto from './accumulateInto';
16 +import forEachAccumulated from './forEachAccumulated';
17
18 /**
19 * Internal queue of events that have accumulated their dispatches and are
@@ -220,4 +220,4 @@ var EventPluginHub = {
220 },
221 };
222
223 -module.exports = EventPluginHub;
223 +export default EventPluginHub;
packages/events/EventPluginRegistry.js
+2 -2
@@ -16,7 +16,7 @@ import type {
16 PluginModule,
17 } from './PluginModuleType';
18
19 -var invariant = require('fbjs/lib/invariant');
19 +import invariant from 'fbjs/lib/invariant';
20
21 type NamesToPlugins = {[key: PluginName]: PluginModule<AnyNativeEvent>};
22 type EventPluginOrder = null | Array<PluginName>;
@@ -251,4 +251,4 @@ var EventPluginRegistry = {
251 },
252 };
253
254 -module.exports = EventPluginRegistry;
254 +export default EventPluginRegistry;
packages/events/EventPluginUtils.js
+4 -7
@@ -7,12 +7,9 @@
7
8 'use strict';
9
10 -var ReactErrorUtils = require('shared/ReactErrorUtils');
11 -var invariant = require('fbjs/lib/invariant');
12 -
13 -if (__DEV__) {
14 - var warning = require('fbjs/lib/warning');
15 -}
10 +import ReactErrorUtils from 'shared/ReactErrorUtils';
11 +import invariant from 'fbjs/lib/invariant';
12 +import warning from 'fbjs/lib/warning';
13
14 /**
15 * Injected dependencies:
@@ -228,4 +225,4 @@ var EventPluginUtils = {
225 injection: injection,
226 };
227
231 -module.exports = EventPluginUtils;
228 +export default EventPluginUtils;
packages/events/EventPropagators.js
+14 -29
@@ -7,20 +7,21 @@
7
8 'use strict';
9
10 -var ReactTreeTraversal = require('shared/ReactTreeTraversal');
10 +import {
11 + getParentInstance,
12 + traverseTwoPhase,
13 + traverseEnterLeave,
14 +} from 'shared/ReactTreeTraversal';
15 +import warning from 'fbjs/lib/warning';
16
12 -var EventPluginHub = require('./EventPluginHub');
13 -var accumulateInto = require('./accumulateInto');
14 -var forEachAccumulated = require('./forEachAccumulated');
17 +import EventPluginHub from './EventPluginHub';
18 +import accumulateInto from './accumulateInto';
19 +import forEachAccumulated from './forEachAccumulated';
20
21 type PropagationPhases = 'bubbled' | 'captured';
22
23 var getListener = EventPluginHub.getListener;
24
20 -if (__DEV__) {
21 - var warning = require('fbjs/lib/warning');
22 -}
23 -
25 /**
26 * Some event types have a notion of different registration names for different
27 * "phases" of propagation. This finds listeners by a given phase.
@@ -60,11 +61,7 @@ function accumulateDirectionalDispatches(inst, phase, event) {
61 */
62 function accumulateTwoPhaseDispatchesSingle(event) {
63 if (event && event.dispatchConfig.phasedRegistrationNames) {
63 - ReactTreeTraversal.traverseTwoPhase(
64 - event._targetInst,
65 - accumulateDirectionalDispatches,
66 - event,
67 - );
64 + traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
65 }
66 }
67
@@ -74,14 +71,8 @@ function accumulateTwoPhaseDispatchesSingle(event) {
71 function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
72 if (event && event.dispatchConfig.phasedRegistrationNames) {
73 var targetInst = event._targetInst;
77 - var parentInst = targetInst
78 - ? ReactTreeTraversal.getParentInstance(targetInst)
79 - : null;
80 - ReactTreeTraversal.traverseTwoPhase(
81 - parentInst,
82 - accumulateDirectionalDispatches,
83 - event,
84 - );
74 + var parentInst = targetInst ? getParentInstance(targetInst) : null;
75 + traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event);
76 }
77 }
78
@@ -124,13 +115,7 @@ function accumulateTwoPhaseDispatchesSkipTarget(events) {
115 }
116
117 function accumulateEnterLeaveDispatches(leave, enter, from, to) {
127 - ReactTreeTraversal.traverseEnterLeave(
128 - from,
129 - to,
130 - accumulateDispatches,
131 - leave,
132 - enter,
133 - );
118 + traverseEnterLeave(from, to, accumulateDispatches, leave, enter);
119 }
120
121 function accumulateDirectDispatches(events) {
@@ -155,4 +140,4 @@ var EventPropagators = {
140 accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches,
141 };
142
158 -module.exports = EventPropagators;
143 +export default EventPropagators;
packages/events/ReactControlledComponent.js
+3 -3
@@ -7,9 +7,9 @@
7
8 'use strict';
9
10 -var invariant = require('fbjs/lib/invariant');
10 +import invariant from 'fbjs/lib/invariant';
11
12 -var EventPluginUtils = require('./EventPluginUtils');
12 +import EventPluginUtils from './EventPluginUtils';
13
14 // Use to restore controlled state after a change event has fired.
15
@@ -83,4 +83,4 @@ var ReactControlledComponent = {
83 },
84 };
85
86 -module.exports = ReactControlledComponent;
86 +export default ReactControlledComponent;
packages/events/ReactEventEmitterMixin.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var EventPluginHub = require('./EventPluginHub');
10 +import EventPluginHub from './EventPluginHub';
11
12 function runEventQueueInBatch(events) {
13 EventPluginHub.enqueueEvents(events);
@@ -35,4 +35,4 @@ var ReactEventEmitterMixin = {
35 },
36 };
37
38 -module.exports = ReactEventEmitterMixin;
38 +export default ReactEventEmitterMixin;
packages/events/ReactGenericBatching.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var ReactControlledComponent = require('./ReactControlledComponent');
10 +import ReactControlledComponent from './ReactControlledComponent';
11
12 // Used as a way to call batchedUpdates when we don't have a reference to
13 // the renderer. Such as when we're dispatching events or if third party
@@ -58,4 +58,4 @@ var ReactGenericBatching = {
58 injection: ReactGenericBatchingInjection,
59 };
60
61 -module.exports = ReactGenericBatching;
61 +export default ReactGenericBatching;
packages/events/ResponderEventPlugin.js
+9 -9
@@ -7,13 +7,13 @@
7
8 'use strict';
9
10 -var ReactTreeTraversal = require('shared/ReactTreeTraversal');
10 +import {getLowestCommonAncestor, isAncestor} from 'shared/ReactTreeTraversal';
11
12 -var EventPluginUtils = require('./EventPluginUtils');
13 -var EventPropagators = require('./EventPropagators');
14 -var ResponderSyntheticEvent = require('./ResponderSyntheticEvent');
15 -var ResponderTouchHistoryStore = require('./ResponderTouchHistoryStore');
16 -var accumulate = require('./accumulate');
12 +import EventPluginUtils from './EventPluginUtils';
13 +import EventPropagators from './EventPropagators';
14 +import ResponderSyntheticEvent from './ResponderSyntheticEvent';
15 +import ResponderTouchHistoryStore from './ResponderTouchHistoryStore';
16 +import accumulate from './accumulate';
17
18 var isStartish = EventPluginUtils.isStartish;
19 var isMoveish = EventPluginUtils.isMoveish;
@@ -327,7 +327,7 @@ function setResponderAndExtractTransfer(
327 // TODO: stop one short of the current responder.
328 var bubbleShouldSetFrom = !responderInst
329 ? targetInst
330 - : ReactTreeTraversal.getLowestCommonAncestor(responderInst, targetInst);
330 + : getLowestCommonAncestor(responderInst, targetInst);
331
332 // When capturing/bubbling the "shouldSet" event, we want to skip the target
333 // (deepest ID) if it happens to be the current responder. The reasoning:
@@ -450,7 +450,7 @@ function noResponderTouches(nativeEvent) {
450 if (target !== null && target !== undefined && target !== 0) {
451 // Is the original touch location inside of the current responder?
452 var targetInst = EventPluginUtils.getInstanceFromNode(target);
453 - if (ReactTreeTraversal.isAncestor(responderInst, targetInst)) {
453 + if (isAncestor(responderInst, targetInst)) {
454 return false;
455 }
456 }
@@ -592,4 +592,4 @@ var ResponderEventPlugin = {
592 },
593 };
594
595 -module.exports = ResponderEventPlugin;
595 +export default ResponderEventPlugin;
packages/events/ResponderSyntheticEvent.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var SyntheticEvent = require('./SyntheticEvent');
10 +import SyntheticEvent from './SyntheticEvent';
11
12 /**
13 * `touchHistory` isn't actually on the native event, but putting it in the
@@ -43,4 +43,4 @@ function ResponderSyntheticEvent(
43
44 SyntheticEvent.augmentClass(ResponderSyntheticEvent, ResponderEventInterface);
45
46 -module.exports = ResponderSyntheticEvent;
46 +export default ResponderSyntheticEvent;
packages/events/ResponderTouchHistoryStore.js
+5 -7
@@ -9,14 +9,12 @@
9
10 'use strict';
11
12 -const invariant = require('fbjs/lib/invariant');
12 +import invariant from 'fbjs/lib/invariant';
13 +import warning from 'fbjs/lib/warning';
14
14 -const EventPluginUtils = require('./EventPluginUtils');
15 -const {isEndish, isMoveish, isStartish} = EventPluginUtils;
15 +import EventPluginUtils from './EventPluginUtils';
16
17 -if (__DEV__) {
18 - var warning = require('fbjs/lib/warning');
19 -}
17 +const {isEndish, isMoveish, isStartish} = EventPluginUtils;
18
19 /**
20 * Tracks the position and time of each active touch by `touch.identifier`. We
@@ -218,4 +216,4 @@ const ResponderTouchHistoryStore = {
216 touchHistory,
217 };
218
221 -module.exports = ResponderTouchHistoryStore;
219 +export default ResponderTouchHistoryStore;
packages/events/SyntheticEvent.js
+5 -8
@@ -9,17 +9,14 @@
9
10 'use strict';
11
12 -var emptyFunction = require('fbjs/lib/emptyFunction');
13 -var invariant = require('fbjs/lib/invariant');
12 +import emptyFunction from 'fbjs/lib/emptyFunction';
13 +import invariant from 'fbjs/lib/invariant';
14 +import warning from 'fbjs/lib/warning';
15
16 var didWarnForAddedNewProperty = false;
17 var isProxySupported = typeof Proxy === 'function';
18 var EVENT_POOL_SIZE = 10;
19
19 -if (__DEV__) {
20 - var warning = require('fbjs/lib/warning');
21 -}
22 -
20 var shouldBeReleasedProperties = [
21 'dispatchConfig',
22 '_targetInst',
@@ -271,8 +268,6 @@ if (__DEV__) {
268
269 addEventPoolingTo(SyntheticEvent);
270
274 -module.exports = SyntheticEvent;
275 -
271 /**
272 * Helper to nullify syntheticEvent instance properties when destructing
273 *
@@ -356,3 +351,5 @@ function addEventPoolingTo(EventConstructor) {
351 EventConstructor.getPooled = getPooledEvent;
352 EventConstructor.release = releasePooledEvent;
353 }
354 +
355 +export default SyntheticEvent;
packages/events/TouchHistoryMath.js
+1 -1
@@ -148,4 +148,4 @@ var TouchHistoryMath = {
148 noCentroid: -1,
149 };
150
151 -module.exports = TouchHistoryMath;
151 +export default TouchHistoryMath;
packages/events/__tests__/EventPluginRegistry-test.js
+1 -1
@@ -16,7 +16,7 @@ describe('EventPluginRegistry', () => {
16 beforeEach(() => {
17 jest.resetModuleRegistry();
18 // TODO: can we express this test with only public API?
19 - EventPluginRegistry = require('events/EventPluginRegistry');
19 + EventPluginRegistry = require('events/EventPluginRegistry').default;
20
21 createPlugin = function(properties) {
22 return Object.assign({extractEvents: function() {}}, properties);
packages/events/__tests__/accumulateInto-test.js
+1 -1
@@ -13,7 +13,7 @@ var accumulateInto;
13
14 describe('accumulateInto', () => {
15 beforeEach(() => {
16 - accumulateInto = require('events/accumulateInto');
16 + accumulateInto = require('events/accumulateInto').default;
17 });
18
19 it('throws if the second item is null', () => {
packages/events/accumulate.js
+2 -2
@@ -9,7 +9,7 @@
9
10 'use strict';
11
12 -var invariant = require('fbjs/lib/invariant');
12 +import invariant from 'fbjs/lib/invariant';
13
14 /**
15 * Accumulates items that must not be null or undefined.
@@ -44,4 +44,4 @@ function accumulate<T>(
44 return [current, next];
45 }
46
47 -module.exports = accumulate;
47 +export default accumulate;
packages/events/accumulateInto.js
+2 -2
@@ -9,7 +9,7 @@
9
10 'use strict';
11
12 -var invariant = require('fbjs/lib/invariant');
12 +import invariant from 'fbjs/lib/invariant';
13
14 /**
15 * Accumulates items that must not be null or undefined into the first one. This
@@ -56,4 +56,4 @@ function accumulateInto<T>(
56 return [current, next];
57 }
58
59 -module.exports = accumulateInto;
59 +export default accumulateInto;
packages/events/forEachAccumulated.js
+1 -1
@@ -30,4 +30,4 @@ function forEachAccumulated<T>(
30 }
31 }
32
33 -module.exports = forEachAccumulated;
33 +export default forEachAccumulated;
packages/react-art/index.js
+3 -1
@@ -9,4 +9,6 @@
9
10 'use strict';
11
12 -module.exports = require('./src/ReactART');
12 +var ReactART = require('./src/ReactART');
13 +
14 +module.exports = ReactART;
packages/react-art/src/ReactART.js
+17 -24
@@ -7,20 +7,20 @@
7
8 'use strict';
9
10 -require('art/modes/current').setCurrent(
10 +import React from 'react';
11 +import ReactFiberReconciler from 'react-reconciler';
12 +import * as ReactDOMFrameScheduling from 'shared/ReactDOMFrameScheduling';
13 +import Mode from 'art/modes/current';
14 +import FastNoSideEffects from 'art/modes/fast-noSideEffects';
15 +import Transform from 'art/core/transform';
16 +import invariant from 'fbjs/lib/invariant';
17 +import emptyObject from 'fbjs/lib/emptyObject';
18 +
19 +Mode.setCurrent(
20 // Change to 'art/modes/dom' for easier debugging via SVG
12 - require('art/modes/fast-noSideEffects'),
21 + FastNoSideEffects,
22 );
23
15 -const React = require('react');
16 -const ReactFiberReconciler = require('react-reconciler');
17 -const ReactDOMFrameScheduling = require('shared/ReactDOMFrameScheduling');
18 -const Mode = require('art/modes/current');
19 -const Transform = require('art/core/transform');
20 -const invariant = require('fbjs/lib/invariant');
21 -const emptyObject = require('fbjs/lib/emptyObject');
22 -const {Component} = React;
23 -
24 const pooledTransform = new Transform();
25
26 const EVENT_TYPES = {
@@ -306,7 +306,7 @@ class Pattern {
306
307 /** React Components */
308
309 -class Surface extends Component {
309 +class Surface extends React.Component {
310 componentDidMount() {
311 const {height, width} = this.props;
312
@@ -539,15 +539,8 @@ const ARTRenderer = ReactFiberReconciler({
539
540 /** API */
541
542 -module.exports = {
543 - ClippingRectangle: TYPES.CLIPPING_RECTANGLE,
544 - Group: TYPES.GROUP,
545 - LinearGradient,
546 - Path: Mode.Path,
547 - Pattern,
548 - RadialGradient,
549 - Shape: TYPES.SHAPE,
550 - Surface,
551 - Text: Text,
552 - Transform,
553 -};
542 +export const ClippingRectangle = TYPES.CLIPPING_RECTANGLE;
543 +export const Group = TYPES.GROUP;
544 +export const Shape = TYPES.SHAPE;
545 +export const Path = Mode.Path;
546 +export {LinearGradient, Pattern, RadialGradient, Surface, Text, Transform};
packages/react-call-return/src/ReactCallReturn.js
+10 -10
@@ -25,7 +25,7 @@ if (typeof Symbol === 'function' && Symbol.for) {
25
26 type CallHandler<T> = (props: T, returns: Array<mixed>) => ReactNodeList;
27
28 -exports.unstable_createCall = function<T>(
28 +export function unstable_createCall<T>(
29 children: mixed,
30 handler: CallHandler<T>,
31 props: T,
@@ -49,9 +49,9 @@ exports.unstable_createCall = function<T>(
49 }
50
51 return call;
52 -};
52 +}
53
54 -exports.unstable_createReturn = function(value: mixed): ReactReturn {
54 +export function unstable_createReturn(value: mixed): ReactReturn {
55 var returnNode = {
56 // This tag allow us to uniquely identify this as a React Return
57 $$typeof: REACT_RETURN_TYPE,
@@ -66,29 +66,29 @@ exports.unstable_createReturn = function(value: mixed): ReactReturn {
66 }
67
68 return returnNode;
69 -};
69 +}
70
71 /**
72 * Verifies the object is a call object.
73 */
74 -exports.unstable_isCall = function(object: mixed): boolean {
74 +export function unstable_isCall(object: mixed): boolean {
75 return (
76 typeof object === 'object' &&
77 object !== null &&
78 object.$$typeof === REACT_CALL_TYPE
79 );
80 -};
80 +}
81
82 /**
83 * Verifies the object is a return object.
84 */
85 -exports.unstable_isReturn = function(object: mixed): boolean {
85 +export function unstable_isReturn(object: mixed): boolean {
86 return (
87 typeof object === 'object' &&
88 object !== null &&
89 object.$$typeof === REACT_RETURN_TYPE
90 );
91 -};
91 +}
92
93 -exports.unstable_REACT_RETURN_TYPE = REACT_RETURN_TYPE;
94 -exports.unstable_REACT_CALL_TYPE = REACT_CALL_TYPE;
93 +export const unstable_REACT_RETURN_TYPE = REACT_RETURN_TYPE;
94 +export const unstable_REACT_CALL_TYPE = REACT_CALL_TYPE;
packages/react-cs-renderer/index.js
+5 -1
@@ -9,4 +9,8 @@
9
10 'use strict';
11
12 -module.exports = require('./src/ReactNativeCS');
12 +var ReactNativeCS = require('./src/ReactNativeCS');
13 +
14 +// TODO: decide on the top-level export form.
15 +// This is hacky but makes it work with both Rollup and Jest.
16 +module.exports = ReactNativeCS.default ? ReactNativeCS.default : ReactNativeCS;
packages/react-cs-renderer/src/ReactNativeCS.js
+8 -9
@@ -9,17 +9,16 @@
9
10 'use strict';
11
12 -const {CSStatefulComponent} = require('CSStatefulComponent');
13 -const ReactFiberReconciler = require('react-reconciler');
14 -const ReactVersion = require('shared/ReactVersion');
15 -
16 -const {
17 - injectInternals,
18 -} = require('react-reconciler/src/ReactFiberDevToolsHook');
19 -
12 import type {ReactNodeList} from 'shared/ReactTypes';
13 import type {ReactNativeCSType} from './ReactNativeCSTypes';
14
15 +// Provided by CS:
16 +import {CSStatefulComponent} from 'CSStatefulComponent';
17 +
18 +import ReactFiberReconciler from 'react-reconciler';
19 +import {injectInternals} from 'react-reconciler/src/ReactFiberDevToolsHook';
20 +import ReactVersion from 'shared/ReactVersion';
21 +
22 const emptyObject = {};
23
24 type Container = {
@@ -300,4 +299,4 @@ const ReactCS = CSStatefulComponent({
299 // TODO: Unmount hook. E.g. finalizer.
300 });
301
303 -module.exports = (ReactCS: ReactNativeCSType);
302 +export default (ReactCS: ReactNativeCSType);
packages/react-cs-renderer/src/ReactNativeCSFeatureFlags.js
+1 -1
@@ -21,4 +21,4 @@ var ReactNativeCSFeatureFlags: FeatureFlags = {
21 enablePersistentReconciler: true,
22 };
23
24 -module.exports = ReactNativeCSFeatureFlags;
24 +export default ReactNativeCSFeatureFlags;
packages/react-cs-renderer/src/__mocks__/CSStatefulComponent.js
+1 -1
@@ -9,6 +9,6 @@
9
10 // Mock of the CS Hooks
11
12 -exports.CSStatefulComponent = function(spec) {
12 +export const CSStatefulComponent = function(spec) {
13 return spec;
14 };
packages/react-dom/index.fb.js
+4 -15
@@ -7,19 +7,8 @@
7
8 'use strict';
9
10 -var ReactDOM = require('./src/client/ReactDOM');
10 +var ReactDOMFB = require('./src/client/ReactDOMFB');
11
12 -Object.assign(ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, {
13 - // These are real internal dependencies that are trickier to remove:
14 - ReactBrowserEventEmitter: require('./src/events/ReactBrowserEventEmitter'),
15 - ReactErrorUtils: require('shared/ReactErrorUtils'),
16 - // TODO: direct imports like some-package/src/* are bad. Fix me.
17 - ReactFiberErrorLogger: require('react-reconciler/src/ReactFiberErrorLogger'),
18 - ReactFiberTreeReflection: require('shared/ReactFiberTreeReflection'),
19 - ReactDOMComponentTree: require('./src/client/ReactDOMComponentTree'),
20 - ReactInstanceMap: require('shared/ReactInstanceMap'),
21 - // Used by www msite:
22 - TapEventPlugin: require('./src/events/TapEventPlugin'),
23 -});
24 -
25 -module.exports = ReactDOM;
12 +// TODO: decide on the top-level export form.
13 +// This is hacky but makes it work with both Rollup and Jest.
14 +module.exports = ReactDOMFB.default ? ReactDOMFB.default : ReactDOMFB;
packages/react-dom/index.js
+5 -1
@@ -9,4 +9,8 @@
9
10 'use strict';
11
12 -module.exports = require('./src/client/ReactDOM');
12 +var ReactDOM = require('./src/client/ReactDOM');
13 +
14 +// TODO: decide on the top-level export form.
15 +// This is hacky but makes it work with both Rollup and Jest.
16 +module.exports = ReactDOM.default ? ReactDOM.default : ReactDOM;
packages/react-dom/src/__tests__/ReactBrowserEventEmitter-test.js
+6 -5
@@ -58,14 +58,15 @@ describe('ReactBrowserEventEmitter', () => {
58 LISTENER.mockClear();
59
60 // TODO: can we express this test with only public API?
61 - EventPluginHub = require('events/EventPluginHub');
62 - EventPluginRegistry = require('events/EventPluginRegistry');
61 + EventPluginHub = require('events/EventPluginHub').default;
62 + EventPluginRegistry = require('events/EventPluginRegistry').default;
63 React = require('react');
64 ReactDOM = require('react-dom');
65 - ReactDOMComponentTree = require('../client/ReactDOMComponentTree');
66 - ReactBrowserEventEmitter = require('../events/ReactBrowserEventEmitter');
65 + ReactDOMComponentTree = require('../client/ReactDOMComponentTree').default;
66 + ReactBrowserEventEmitter = require('../events/ReactBrowserEventEmitter')
67 + .default;
68 ReactTestUtils = require('react-dom/test-utils');
68 - TapEventPlugin = require('../events/TapEventPlugin');
69 + TapEventPlugin = require('../events/TapEventPlugin').default;
70
71 var container = document.createElement('div');
72
packages/react-dom/src/__tests__/ReactDOMComponentTree-test.js
+1 -1
@@ -34,7 +34,7 @@ describe('ReactDOMComponentTree', () => {
34 React = require('react');
35 ReactDOM = require('react-dom');
36 // TODO: can we express this test with only public API?
37 - ReactDOMComponentTree = require('../client/ReactDOMComponentTree');
37 + ReactDOMComponentTree = require('../client/ReactDOMComponentTree').default;
38 ReactDOMServer = require('react-dom/server');
39 });
40
packages/react-dom/src/__tests__/ReactDOMEventListener-test.js
+2 -2
@@ -24,8 +24,8 @@ describe('ReactDOMEventListener', () => {
24 React = require('react');
25 ReactDOM = require('react-dom');
26 // TODO: can we express this test with only public API?
27 - ReactDOMComponentTree = require('../client/ReactDOMComponentTree');
28 - ReactDOMEventListener = require('../events/ReactDOMEventListener');
27 + ReactDOMComponentTree = require('../client/ReactDOMComponentTree').default;
28 + ReactDOMEventListener = require('../events/ReactDOMEventListener').default;
29 ReactTestUtils = require('react-dom/test-utils');
30
31 handleTopLevel = jest.fn();
packages/react-dom/src/__tests__/ReactServerRendering-test.js
+1 -1
@@ -35,7 +35,7 @@ describe('ReactDOMServer', () => {
35 ReactDOMServer = require('react-dom/server');
36
37 // TODO: can we express this test with only public API?
38 - var DOMProperty = require('../shared/DOMProperty');
38 + var DOMProperty = require('../shared/DOMProperty').default;
39 ROOT_ATTRIBUTE_NAME = DOMProperty.ROOT_ATTRIBUTE_NAME;
40 });
41
packages/react-dom/src/__tests__/ReactTreeTraversal-test.js
+1 -1
@@ -11,7 +11,7 @@
11
12 var React = require('react');
13 // TODO: can we express this test with only public API?
14 -var ReactDOMComponentTree = require('../client/ReactDOMComponentTree');
14 +var ReactDOMComponentTree = require('../client/ReactDOMComponentTree').default;
15 var ReactTestUtils = require('react-dom/test-utils');
16
17 /**
packages/react-dom/src/__tests__/escapeTextContentForBrowser-test.js
+2 -1
@@ -11,7 +11,8 @@
11
12 describe('escapeTextContentForBrowser', () => {
13 // TODO: can we express this test with only public API?
14 - var escapeTextContentForBrowser = require('../shared/escapeTextContentForBrowser');
14 + var escapeTextContentForBrowser = require('../shared/escapeTextContentForBrowser')
15 + .default;
16
17 it('should escape boolean to string', () => {
18 expect(escapeTextContentForBrowser(true)).toBe('true');
packages/react-dom/src/__tests__/quoteAttributeValueForBrowser-test.js
+2 -1
@@ -11,7 +11,8 @@
11
12 describe('quoteAttributeValueForBrowser', () => {
13 // TODO: can we express this test with only public API?
14 - var quoteAttributeValueForBrowser = require('../shared/quoteAttributeValueForBrowser');
14 + var quoteAttributeValueForBrowser = require('../shared/quoteAttributeValueForBrowser')
15 + .default;
16
17 it('should escape boolean to string', () => {
18 expect(quoteAttributeValueForBrowser(true)).toBe('"true"');
packages/react-dom/src/__tests__/validateDOMNesting-test.js
+1 -1
@@ -136,7 +136,7 @@ describe('ReactContextValidator', () => {
136 jest.resetModules();
137
138 // TODO: can we express this test with only public API?
139 - validateDOMNesting = require('../client/validateDOMNesting');
139 + validateDOMNesting = require('../client/validateDOMNesting').default;
140 });
141
142 it('allows any tag with no context', () => {
packages/react-dom/src/client/DOMPropertyOperations.js
+164 -170
@@ -7,11 +7,8 @@
7
8 'use strict';
9
10 -var DOMProperty = require('../shared/DOMProperty');
11 -
12 -if (__DEV__) {
13 - var warning = require('fbjs/lib/warning');
14 -}
10 +import DOMProperty from '../shared/DOMProperty';
11 +import warning from 'fbjs/lib/warning';
12
13 // isAttributeNameSafe() is currently duplicated in DOMMarkupOperations.
14 // TODO: Find a better place for this.
@@ -57,201 +54,198 @@ function shouldIgnoreValue(propertyInfo, value) {
54 /**
55 * Operations for dealing with DOM properties.
56 */
60 -var DOMPropertyOperations = {
61 - setAttributeForID: function(node, id) {
62 - node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id);
63 - },
57
65 - setAttributeForRoot: function(node) {
66 - node.setAttribute(DOMProperty.ROOT_ATTRIBUTE_NAME, '');
67 - },
58 +export function setAttributeForID(node, id) {
59 + node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id);
60 +}
61
69 - /**
70 - * Get the value for a property on a node. Only used in DEV for SSR validation.
71 - * The "expected" argument is used as a hint of what the expected value is.
72 - * Some properties have multiple equivalent values.
73 - */
74 - getValueForProperty: function(node, name, expected) {
75 - if (__DEV__) {
76 - var propertyInfo = DOMProperty.getPropertyInfo(name);
77 - if (propertyInfo) {
78 - var mutationMethod = propertyInfo.mutationMethod;
79 - if (mutationMethod || propertyInfo.mustUseProperty) {
80 - return node[propertyInfo.propertyName];
81 - } else {
82 - var attributeName = propertyInfo.attributeName;
62 +export function setAttributeForRoot(node) {
63 + node.setAttribute(DOMProperty.ROOT_ATTRIBUTE_NAME, '');
64 +}
65 +
66 +/**
67 + * Get the value for a property on a node. Only used in DEV for SSR validation.
68 + * The "expected" argument is used as a hint of what the expected value is.
69 + * Some properties have multiple equivalent values.
70 + */
71 +export function getValueForProperty(node, name, expected) {
72 + if (__DEV__) {
73 + var propertyInfo = DOMProperty.getPropertyInfo(name);
74 + if (propertyInfo) {
75 + var mutationMethod = propertyInfo.mutationMethod;
76 + if (mutationMethod || propertyInfo.mustUseProperty) {
77 + return node[propertyInfo.propertyName];
78 + } else {
79 + var attributeName = propertyInfo.attributeName;
80
84 - var stringValue = null;
81 + var stringValue = null;
82
86 - if (propertyInfo.hasOverloadedBooleanValue) {
87 - if (node.hasAttribute(attributeName)) {
88 - var value = node.getAttribute(attributeName);
89 - if (value === '') {
90 - return true;
91 - }
92 - if (shouldIgnoreValue(propertyInfo, expected)) {
93 - return value;
94 - }
95 - if (value === '' + expected) {
96 - return expected;
97 - }
98 - return value;
83 + if (propertyInfo.hasOverloadedBooleanValue) {
84 + if (node.hasAttribute(attributeName)) {
85 + var value = node.getAttribute(attributeName);
86 + if (value === '') {
87 + return true;
88 }
100 - } else if (node.hasAttribute(attributeName)) {
89 if (shouldIgnoreValue(propertyInfo, expected)) {
102 - // We had an attribute but shouldn't have had one, so read it
103 - // for the error message.
104 - return node.getAttribute(attributeName);
90 + return value;
91 }
106 - if (propertyInfo.hasBooleanValue) {
107 - // If this was a boolean, it doesn't matter what the value is
108 - // the fact that we have it is the same as the expected.
92 + if (value === '' + expected) {
93 return expected;
94 }
111 - // Even if this property uses a namespace we use getAttribute
112 - // because we assume its namespaced name is the same as our config.
113 - // To use getAttributeNS we need the local name which we don't have
114 - // in our config atm.
115 - stringValue = node.getAttribute(attributeName);
95 + return value;
96 }
117 -
97 + } else if (node.hasAttribute(attributeName)) {
98 if (shouldIgnoreValue(propertyInfo, expected)) {
119 - return stringValue === null ? expected : stringValue;
120 - } else if (stringValue === '' + expected) {
99 + // We had an attribute but shouldn't have had one, so read it
100 + // for the error message.
101 + return node.getAttribute(attributeName);
102 + }
103 + if (propertyInfo.hasBooleanValue) {
104 + // If this was a boolean, it doesn't matter what the value is
105 + // the fact that we have it is the same as the expected.
106 return expected;
122 - } else {
123 - return stringValue;
107 }
108 + // Even if this property uses a namespace we use getAttribute
109 + // because we assume its namespaced name is the same as our config.
110 + // To use getAttributeNS we need the local name which we don't have
111 + // in our config atm.
112 + stringValue = node.getAttribute(attributeName);
113 }
126 - }
127 - }
128 - },
114
130 - /**
131 - * Get the value for a attribute on a node. Only used in DEV for SSR validation.
132 - * The third argument is used as a hint of what the expected value is. Some
133 - * attributes have multiple equivalent values.
134 - */
135 - getValueForAttribute: function(node, name, expected) {
136 - if (__DEV__) {
137 - if (!isAttributeNameSafe(name)) {
138 - return;
139 - }
140 - if (!node.hasAttribute(name)) {
141 - return expected === undefined ? undefined : null;
142 - }
143 - var value = node.getAttribute(name);
144 - if (value === '' + expected) {
145 - return expected;
146 - }
147 - return value;
148 - }
149 - },
150 -
151 - /**
152 - * Sets the value for a property on a node.
153 - *
154 - * @param {DOMElement} node
155 - * @param {string} name
156 - * @param {*} value
157 - */
158 - setValueForProperty: function(node, name, value) {
159 - var propertyInfo = DOMProperty.getPropertyInfo(name);
160 -
161 - if (propertyInfo && DOMProperty.shouldSetAttribute(name, value)) {
162 - var mutationMethod = propertyInfo.mutationMethod;
163 - if (mutationMethod) {
164 - mutationMethod(node, value);
165 - } else if (shouldIgnoreValue(propertyInfo, value)) {
166 - DOMPropertyOperations.deleteValueForProperty(node, name);
167 - return;
168 - } else if (propertyInfo.mustUseProperty) {
169 - // Contrary to `setAttribute`, object properties are properly
170 - // `toString`ed by IE8/9.
171 - node[propertyInfo.propertyName] = value;
172 - } else {
173 - var attributeName = propertyInfo.attributeName;
174 - var namespace = propertyInfo.attributeNamespace;
175 - // `setAttribute` with objects becomes only `[object]` in IE8/9,
176 - // ('' + value) makes it output the correct toString()-value.
177 - if (namespace) {
178 - node.setAttributeNS(namespace, attributeName, '' + value);
179 - } else if (
180 - propertyInfo.hasBooleanValue ||
181 - (propertyInfo.hasOverloadedBooleanValue && value === true)
182 - ) {
183 - node.setAttribute(attributeName, '');
115 + if (shouldIgnoreValue(propertyInfo, expected)) {
116 + return stringValue === null ? expected : stringValue;
117 + } else if (stringValue === '' + expected) {
118 + return expected;
119 } else {
185 - node.setAttribute(attributeName, '' + value);
120 + return stringValue;
121 }
122 }
188 - } else {
189 - DOMPropertyOperations.setValueForAttribute(
190 - node,
191 - name,
192 - DOMProperty.shouldSetAttribute(name, value) ? value : null,
193 - );
194 - return;
123 }
124 + }
125 +}
126
197 - if (__DEV__) {
198 - var payload = {};
199 - payload[name] = value;
200 - }
201 - },
202 -
203 - setValueForAttribute: function(node, name, value) {
127 +/**
128 + * Get the value for a attribute on a node. Only used in DEV for SSR validation.
129 + * The third argument is used as a hint of what the expected value is. Some
130 + * attributes have multiple equivalent values.
131 + */
132 +export function getValueForAttribute(node, name, expected) {
133 + if (__DEV__) {
134 if (!isAttributeNameSafe(name)) {
135 return;
136 }
207 - if (value == null) {
208 - node.removeAttribute(name);
209 - } else {
210 - node.setAttribute(name, '' + value);
137 + if (!node.hasAttribute(name)) {
138 + return expected === undefined ? undefined : null;
139 + }
140 + var value = node.getAttribute(name);
141 + if (value === '' + expected) {
142 + return expected;
143 }
144 + return value;
145 + }
146 +}
147
213 - if (__DEV__) {
214 - var payload = {};
215 - payload[name] = value;
148 +/**
149 + * Sets the value for a property on a node.
150 + *
151 + * @param {DOMElement} node
152 + * @param {string} name
153 + * @param {*} value
154 + */
155 +export function setValueForProperty(node, name, value) {
156 + var propertyInfo = DOMProperty.getPropertyInfo(name);
157 +
158 + if (propertyInfo && DOMProperty.shouldSetAttribute(name, value)) {
159 + var mutationMethod = propertyInfo.mutationMethod;
160 + if (mutationMethod) {
161 + mutationMethod(node, value);
162 + } else if (shouldIgnoreValue(propertyInfo, value)) {
163 + deleteValueForProperty(node, name);
164 + return;
165 + } else if (propertyInfo.mustUseProperty) {
166 + // Contrary to `setAttribute`, object properties are properly
167 + // `toString`ed by IE8/9.
168 + node[propertyInfo.propertyName] = value;
169 + } else {
170 + var attributeName = propertyInfo.attributeName;
171 + var namespace = propertyInfo.attributeNamespace;
172 + // `setAttribute` with objects becomes only `[object]` in IE8/9,
173 + // ('' + value) makes it output the correct toString()-value.
174 + if (namespace) {
175 + node.setAttributeNS(namespace, attributeName, '' + value);
176 + } else if (
177 + propertyInfo.hasBooleanValue ||
178 + (propertyInfo.hasOverloadedBooleanValue && value === true)
179 + ) {
180 + node.setAttribute(attributeName, '');
181 + } else {
182 + node.setAttribute(attributeName, '' + value);
183 + }
184 }
217 - },
185 + } else {
186 + setValueForAttribute(
187 + node,
188 + name,
189 + DOMProperty.shouldSetAttribute(name, value) ? value : null,
190 + );
191 + return;
192 + }
193 +
194 + if (__DEV__) {
195 + var payload = {};
196 + payload[name] = value;
197 + }
198 +}
199
219 - /**
220 - * Deletes an attributes from a node.
221 - *
222 - * @param {DOMElement} node
223 - * @param {string} name
224 - */
225 - deleteValueForAttribute: function(node, name) {
200 +export function setValueForAttribute(node, name, value) {
201 + if (!isAttributeNameSafe(name)) {
202 + return;
203 + }
204 + if (value == null) {
205 node.removeAttribute(name);
227 - },
206 + } else {
207 + node.setAttribute(name, '' + value);
208 + }
209
229 - /**
230 - * Deletes the value for a property on a node.
231 - *
232 - * @param {DOMElement} node
233 - * @param {string} name
234 - */
235 - deleteValueForProperty: function(node, name) {
236 - var propertyInfo = DOMProperty.getPropertyInfo(name);
237 - if (propertyInfo) {
238 - var mutationMethod = propertyInfo.mutationMethod;
239 - if (mutationMethod) {
240 - mutationMethod(node, undefined);
241 - } else if (propertyInfo.mustUseProperty) {
242 - var propName = propertyInfo.propertyName;
243 - if (propertyInfo.hasBooleanValue) {
244 - node[propName] = false;
245 - } else {
246 - node[propName] = '';
247 - }
210 + if (__DEV__) {
211 + var payload = {};
212 + payload[name] = value;
213 + }
214 +}
215 +
216 +/**
217 + * Deletes an attributes from a node.
218 + *
219 + * @param {DOMElement} node
220 + * @param {string} name
221 + */
222 +export function deleteValueForAttribute(node, name) {
223 + node.removeAttribute(name);
224 +}
225 +
226 +/**
227 + * Deletes the value for a property on a node.
228 + *
229 + * @param {DOMElement} node
230 + * @param {string} name
231 + */
232 +export function deleteValueForProperty(node, name) {
233 + var propertyInfo = DOMProperty.getPropertyInfo(name);
234 + if (propertyInfo) {
235 + var mutationMethod = propertyInfo.mutationMethod;
236 + if (mutationMethod) {
237 + mutationMethod(node, undefined);
238 + } else if (propertyInfo.mustUseProperty) {
239 + var propName = propertyInfo.propertyName;
240 + if (propertyInfo.hasBooleanValue) {
241 + node[propName] = false;
242 } else {
249 - node.removeAttribute(propertyInfo.attributeName);
243 + node[propName] = '';
244 }
245 } else {
252 - node.removeAttribute(name);
246 + node.removeAttribute(propertyInfo.attributeName);
247 }
254 - },
255 -};
256 -
257 -module.exports = DOMPropertyOperations;
248 + } else {
249 + node.removeAttribute(name);
250 + }
251 +}
packages/react-dom/src/client/ReactDOM.js
+40 -37
@@ -11,38 +11,48 @@
11
12 import type {ReactNodeList} from 'shared/ReactTypes';
13
14 -require('../shared/checkReact');
14 +import '../shared/checkReact';
15 +import '../shared/ReactDOMInjection';
16 +import './ReactDOMClientInjection';
17
16 -var ReactFiberReconciler = require('react-reconciler');
18 +import ReactFiberReconciler from 'react-reconciler';
19 // TODO: direct imports like some-package/src/* are bad. Fix me.
18 -var ReactPortal = require('react-reconciler/src/ReactPortal');
20 +import * as ReactPortal from 'react-reconciler/src/ReactPortal';
21 // TODO: direct imports like some-package/src/* are bad. Fix me.
20 -var {injectInternals} = require('react-reconciler/src/ReactFiberDevToolsHook');
21 -var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
22 -var ReactGenericBatching = require('events/ReactGenericBatching');
23 -var ReactControlledComponent = require('events/ReactControlledComponent');
24 -var ReactInstanceMap = require('shared/ReactInstanceMap');
25 -var ReactFeatureFlags = require('shared/ReactFeatureFlags');
26 -var ReactVersion = require('shared/ReactVersion');
27 -var ReactDOMFrameScheduling = require('shared/ReactDOMFrameScheduling');
28 -var {ReactCurrentOwner} = require('shared/ReactGlobalSharedState');
29 -var getComponentName = require('shared/getComponentName');
30 -var invariant = require('fbjs/lib/invariant');
31 -
32 -var ReactDOMComponentTree = require('./ReactDOMComponentTree');
33 -var ReactDOMFiberComponent = require('./ReactDOMFiberComponent');
34 -var ReactInputSelection = require('./ReactInputSelection');
35 -var ReactBrowserEventEmitter = require('../events/ReactBrowserEventEmitter');
36 -var DOMNamespaces = require('../shared/DOMNamespaces');
37 -var {
22 +import {injectInternals} from 'react-reconciler/src/ReactFiberDevToolsHook';
23 +import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment';
24 +import ReactGenericBatching from 'events/ReactGenericBatching';
25 +import ReactControlledComponent from 'events/ReactControlledComponent';
26 +import EventPluginHub from 'events/EventPluginHub';
27 +import EventPluginRegistry from 'events/EventPluginRegistry';
28 +import EventPropagators from 'events/EventPropagators';
29 +import * as ReactInstanceMap from 'shared/ReactInstanceMap';
30 +import ReactFeatureFlags from 'shared/ReactFeatureFlags';
31 +import ReactVersion from 'shared/ReactVersion';
32 +import * as ReactDOMFrameScheduling from 'shared/ReactDOMFrameScheduling';
33 +import {ReactCurrentOwner} from 'shared/ReactGlobalSharedState';
34 +import getComponentName from 'shared/getComponentName';
35 +import invariant from 'fbjs/lib/invariant';
36 +import lowPriorityWarning from 'shared/lowPriorityWarning';
37 +import warning from 'fbjs/lib/warning';
38 +
39 +import ReactDOMComponentTree from './ReactDOMComponentTree';
40 +import * as ReactDOMFiberComponent from './ReactDOMFiberComponent';
41 +import * as ReactInputSelection from './ReactInputSelection';
42 +import validateDOMNesting from './validateDOMNesting';
43 +import ReactBrowserEventEmitter from '../events/ReactBrowserEventEmitter';
44 +import ReactDOMEventListener from '../events/ReactDOMEventListener';
45 +import {getChildNamespace} from '../shared/DOMNamespaces';
46 +import {
47 ELEMENT_NODE,
48 TEXT_NODE,
49 COMMENT_NODE,
50 DOCUMENT_NODE,
51 DOCUMENT_FRAGMENT_NODE,
43 -} = require('../shared/HTMLNodeType');
44 -var {ROOT_ATTRIBUTE_NAME} = require('../shared/DOMProperty');
45 -var {getChildNamespace} = DOMNamespaces;
52 +} from '../shared/HTMLNodeType';
53 +import DOMProperty from '../shared/DOMProperty';
54 +
55 +var {ROOT_ATTRIBUTE_NAME} = DOMProperty;
56 var {
57 createElement,
58 createTextNode,
@@ -57,15 +67,10 @@ var {
67 warnForInsertedHydratedElement,
68 warnForInsertedHydratedText,
69 } = ReactDOMFiberComponent;
70 +var {updatedAncestorInfo} = validateDOMNesting;
71 var {precacheFiberNode, updateFiberProps} = ReactDOMComponentTree;
72
73 if (__DEV__) {
63 - var lowPriorityWarning = require('shared/lowPriorityWarning');
64 - var warning = require('fbjs/lib/warning');
65 -
66 - var validateDOMNesting = require('./validateDOMNesting');
67 - var {updatedAncestorInfo} = validateDOMNesting;
68 -
74 var SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning';
75 if (
76 typeof Map !== 'function' ||
@@ -84,8 +89,6 @@ if (__DEV__) {
89 }
90 }
91
87 -require('./ReactDOMClientInjection');
88 -require('../shared/ReactDOMInjection');
92 ReactControlledComponent.injection.injectFiberControlledHostComponent(
93 ReactDOMFiberComponent,
94 );
@@ -941,13 +944,13 @@ var ReactDOM = {
944
945 __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
946 // For TapEventPlugin which is popular in open source
944 - EventPluginHub: require('events/EventPluginHub'),
947 + EventPluginHub,
948 // Used by test-utils
946 - EventPluginRegistry: require('events/EventPluginRegistry'),
947 - EventPropagators: require('events/EventPropagators'),
949 + EventPluginRegistry,
950 + EventPropagators,
951 ReactControlledComponent,
952 ReactDOMComponentTree,
950 - ReactDOMEventListener: require('../events/ReactDOMEventListener'),
953 + ReactDOMEventListener,
954 },
955 };
956
@@ -990,4 +993,4 @@ if (__DEV__) {
993 }
994 }
995
993 -module.exports = ReactDOM;
996 +export default ReactDOM;
packages/react-dom/src/client/ReactDOMClientInjection.js
+11 -11
@@ -7,18 +7,18 @@
7
8 'use strict';
9
10 -var EventPluginHub = require('events/EventPluginHub');
11 -var EventPluginUtils = require('events/EventPluginUtils');
10 +import EventPluginHub from 'events/EventPluginHub';
11 +import EventPluginUtils from 'events/EventPluginUtils';
12
13 -var ReactDOMComponentTree = require('./ReactDOMComponentTree');
14 -var BeforeInputEventPlugin = require('../events/BeforeInputEventPlugin');
15 -var ChangeEventPlugin = require('../events/ChangeEventPlugin');
16 -var DOMEventPluginOrder = require('../events/DOMEventPluginOrder');
17 -var EnterLeaveEventPlugin = require('../events/EnterLeaveEventPlugin');
18 -var ReactBrowserEventEmitter = require('../events/ReactBrowserEventEmitter');
19 -var ReactDOMEventListener = require('../events/ReactDOMEventListener');
20 -var SelectEventPlugin = require('../events/SelectEventPlugin');
21 -var SimpleEventPlugin = require('../events/SimpleEventPlugin');
13 +import ReactDOMComponentTree from './ReactDOMComponentTree';
14 +import BeforeInputEventPlugin from '../events/BeforeInputEventPlugin';
15 +import ChangeEventPlugin from '../events/ChangeEventPlugin';
16 +import DOMEventPluginOrder from '../events/DOMEventPluginOrder';
17 +import EnterLeaveEventPlugin from '../events/EnterLeaveEventPlugin';
18 +import ReactBrowserEventEmitter from '../events/ReactBrowserEventEmitter';
19 +import ReactDOMEventListener from '../events/ReactDOMEventListener';
20 +import SelectEventPlugin from '../events/SelectEventPlugin';
21 +import SimpleEventPlugin from '../events/SimpleEventPlugin';
22
23 ReactDOMEventListener.setHandleTopLevel(
24 ReactBrowserEventEmitter.handleTopLevel,
packages/react-dom/src/client/ReactDOMComponentTree.js
+3 -3
@@ -7,8 +7,8 @@
7
8 'use strict';
9
10 -var {HostComponent, HostText} = require('shared/ReactTypeOfWork');
11 -var invariant = require('fbjs/lib/invariant');
10 +import {HostComponent, HostText} from 'shared/ReactTypeOfWork';
11 +import invariant from 'fbjs/lib/invariant';
12
13 var randomKey = Math.random().toString(36).slice(2);
14 var internalInstanceKey = '__reactInternalInstance$' + randomKey;
@@ -102,4 +102,4 @@ var ReactDOMComponentTree = {
102 updateFiberProps,
103 };
104
105 -module.exports = ReactDOMComponentTree;
105 +export default ReactDOMComponentTree;
packages/react-dom/src/client/ReactDOMFB.js new
+39
@@ -0,0 +1,39 @@
1 +/**
2 + * Copyright (c) 2013-present, Facebook, Inc.
3 + *
4 + * This source code is licensed under the MIT license found in the
5 + * LICENSE file in the root directory of this source tree.
6 + *
7 + * @flow
8 + */
9 +
10 +'use strict';
11 +
12 +import * as ReactFiberTreeReflection from 'shared/ReactFiberTreeReflection';
13 +import * as ReactInstanceMap from 'shared/ReactInstanceMap';
14 +// TODO: direct imports like some-package/src/* are bad. Fix me.
15 +import * as ReactFiberErrorLogger
16 + from 'react-reconciler/src/ReactFiberErrorLogger';
17 +import ReactErrorUtils from 'shared/ReactErrorUtils';
18 +
19 +import ReactDOM from './ReactDOM';
20 +import ReactBrowserEventEmitter from '../events/ReactBrowserEventEmitter';
21 +import ReactDOMComponentTree from './ReactDOMComponentTree';
22 +import TapEventPlugin from '../events/TapEventPlugin';
23 +
24 +Object.assign(
25 + (ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: any),
26 + {
27 + // These are real internal dependencies that are trickier to remove:
28 + ReactBrowserEventEmitter,
29 + ReactErrorUtils,
30 + ReactFiberErrorLogger,
31 + ReactFiberTreeReflection,
32 + ReactDOMComponentTree,
33 + ReactInstanceMap,
34 + // Used by www msite:
35 + TapEventPlugin,
36 + },
37 +);
38 +
39 +export default ReactDOM;
packages/react-dom/src/client/ReactDOMFiberComponent.js
+838 -864
@@ -10,47 +10,41 @@
10 'use strict';
11
12 // TODO: direct imports like some-package/src/* are bad. Fix me.
13 -var {
14 - getCurrentFiberOwnerName,
15 -} = require('react-reconciler/src/ReactDebugCurrentFiber');
16 -var EventPluginRegistry = require('events/EventPluginRegistry');
17 -var emptyFunction = require('fbjs/lib/emptyFunction');
13 +import ReactDebugCurrentFiber
14 + from 'react-reconciler/src/ReactDebugCurrentFiber';
15 +import EventPluginRegistry from 'events/EventPluginRegistry';
16 +import emptyFunction from 'fbjs/lib/emptyFunction';
17 +import warning from 'fbjs/lib/warning';
18
19 -var DOMPropertyOperations = require('./DOMPropertyOperations');
20 -var ReactDOMFiberInput = require('./ReactDOMFiberInput');
21 -var ReactDOMFiberOption = require('./ReactDOMFiberOption');
22 -var ReactDOMFiberSelect = require('./ReactDOMFiberSelect');
23 -var ReactDOMFiberTextarea = require('./ReactDOMFiberTextarea');
24 -var inputValueTracking = require('./inputValueTracking');
25 -var setInnerHTML = require('./setInnerHTML');
26 -var setTextContent = require('./setTextContent');
27 -var ReactBrowserEventEmitter = require('../events/ReactBrowserEventEmitter');
28 -var CSSPropertyOperations = require('../shared/CSSPropertyOperations');
29 -var DOMNamespaces = require('../shared/DOMNamespaces');
30 -var DOMProperty = require('../shared/DOMProperty');
31 -var assertValidProps = require('../shared/assertValidProps');
32 -var {DOCUMENT_NODE, DOCUMENT_FRAGMENT_NODE} = require('../shared/HTMLNodeType');
33 -var isCustomComponent = require('../shared/isCustomComponent');
34 -
35 -if (__DEV__) {
36 - // TODO: direct imports like some-package/src/* are bad. Fix me.
37 - var {
38 - getCurrentFiberStackAddendum,
39 - } = require('react-reconciler/src/ReactDebugCurrentFiber');
40 - var warning = require('fbjs/lib/warning');
41 -
42 - var ReactDOMInvalidARIAHook = require('../shared/ReactDOMInvalidARIAHook');
43 - var ReactDOMNullInputValuePropHook = require('../shared/ReactDOMNullInputValuePropHook');
44 - var ReactDOMUnknownPropertyHook = require('../shared/ReactDOMUnknownPropertyHook');
45 - var {validateProperties: validateARIAProperties} = ReactDOMInvalidARIAHook;
46 - var {
47 - validateProperties: validateInputProperties,
48 - } = ReactDOMNullInputValuePropHook;
49 - var {
50 - validateProperties: validateUnknownProperties,
51 - } = ReactDOMUnknownPropertyHook;
52 -}
19 +import * as DOMPropertyOperations from './DOMPropertyOperations';
20 +import * as ReactDOMFiberInput from './ReactDOMFiberInput';
21 +import * as ReactDOMFiberOption from './ReactDOMFiberOption';
22 +import * as ReactDOMFiberSelect from './ReactDOMFiberSelect';
23 +import * as ReactDOMFiberTextarea from './ReactDOMFiberTextarea';
24 +import * as inputValueTracking from './inputValueTracking';
25 +import setInnerHTML from './setInnerHTML';
26 +import setTextContent from './setTextContent';
27 +import ReactBrowserEventEmitter from '../events/ReactBrowserEventEmitter';
28 +import * as CSSPropertyOperations from '../shared/CSSPropertyOperations';
29 +import {Namespaces, getIntrinsicNamespace} from '../shared/DOMNamespaces';
30 +import DOMProperty from '../shared/DOMProperty';
31 +import assertValidProps from '../shared/assertValidProps';
32 +import {DOCUMENT_NODE, DOCUMENT_FRAGMENT_NODE} from '../shared/HTMLNodeType';
33 +import isCustomComponent from '../shared/isCustomComponent';
34 +import {
35 + validateProperties as validateARIAProperties,
36 +} from '../shared/ReactDOMInvalidARIAHook';
37 +import {
38 + validateProperties as validateInputProperties,
39 +} from '../shared/ReactDOMNullInputValuePropHook';
40 +import {
41 + validateProperties as validateUnknownProperties,
42 +} from '../shared/ReactDOMUnknownPropertyHook';
43
44 +var {
45 + getCurrentFiberOwnerName,
46 + getCurrentFiberStackAddendum,
47 +} = ReactDebugCurrentFiber;
48 var didWarnInvalidHydration = false;
49 var didWarnShadyDOM = false;
50
@@ -65,7 +59,7 @@ var CHILDREN = 'children';
59 var STYLE = 'style';
60 var HTML = '__html';
61
68 -var {Namespaces: {html: HTML_NAMESPACE}, getIntrinsicNamespace} = DOMNamespaces;
62 +var {html: HTML_NAMESPACE} = Namespaces;
63
64 var getStack = emptyFunction.thatReturns('');
65
@@ -368,915 +362,895 @@ function updateDOMProperties(
362 }
363 }
364
371 -var ReactDOMFiberComponent = {
372 - createElement(
373 - type: *,
374 - props: Object,
375 - rootContainerElement: Element | Document,
376 - parentNamespace: string,
377 - ): Element {
378 - // We create tags in the namespace of their parent container, except HTML
379 - // tags get no namespace.
380 - var ownerDocument: Document = getOwnerDocumentFromRootContainer(
381 - rootContainerElement,
382 - );
383 - var domElement: Element;
384 - var namespaceURI = parentNamespace;
385 - if (namespaceURI === HTML_NAMESPACE) {
386 - namespaceURI = getIntrinsicNamespace(type);
365 +export function createElement(
366 + type: *,
367 + props: Object,
368 + rootContainerElement: Element | Document,
369 + parentNamespace: string,
370 +): Element {
371 + // We create tags in the namespace of their parent container, except HTML
372 + // tags get no namespace.
373 + var ownerDocument: Document = getOwnerDocumentFromRootContainer(
374 + rootContainerElement,
375 + );
376 + var domElement: Element;
377 + var namespaceURI = parentNamespace;
378 + if (namespaceURI === HTML_NAMESPACE) {
379 + namespaceURI = getIntrinsicNamespace(type);
380 + }
381 + if (namespaceURI === HTML_NAMESPACE) {
382 + if (__DEV__) {
383 + var isCustomComponentTag = isCustomComponent(type, props);
384 + // Should this check be gated by parent namespace? Not sure we want to
385 + // allow <SVG> or <mATH>.
386 + warning(
387 + isCustomComponentTag || type === type.toLowerCase(),
388 + '<%s /> is using uppercase HTML. Always use lowercase HTML tags ' +
389 + 'in React.',
390 + type,
391 + );
392 + }
393 +
394 + if (type === 'script') {
395 + // Create the script via .innerHTML so its "parser-inserted" flag is
396 + // set to true and it does not execute
397 + var div = ownerDocument.createElement('div');
398 + div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
399 + // This is guaranteed to yield a script element.
400 + var firstChild = ((div.firstChild: any): HTMLScriptElement);
401 + domElement = div.removeChild(firstChild);
402 + } else if (typeof props.is === 'string') {
403 + // $FlowIssue `createElement` should be updated for Web Components
404 + domElement = ownerDocument.createElement(type, {is: props.is});
405 + } else {
406 + // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
407 + // See discussion in https://github.com/facebook/react/pull/6896
408 + // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
409 + domElement = ownerDocument.createElement(type);
410 }
411 + } else {
412 + domElement = ownerDocument.createElementNS(namespaceURI, type);
413 + }
414 +
415 + if (__DEV__) {
416 if (namespaceURI === HTML_NAMESPACE) {
389 - if (__DEV__) {
390 - var isCustomComponentTag = isCustomComponent(type, props);
391 - // Should this check be gated by parent namespace? Not sure we want to
392 - // allow <SVG> or <mATH>.
417 + if (
418 + !isCustomComponentTag &&
419 + Object.prototype.toString.call(domElement) ===
420 + '[object HTMLUnknownElement]' &&
421 + !Object.prototype.hasOwnProperty.call(warnedUnknownTags, type)
422 + ) {
423 + warnedUnknownTags[type] = true;
424 warning(
394 - isCustomComponentTag || type === type.toLowerCase(),
395 - '<%s /> is using uppercase HTML. Always use lowercase HTML tags ' +
396 - 'in React.',
425 + false,
426 + 'The tag <%s> is unrecognized in this browser. ' +
427 + 'If you meant to render a React component, start its name with ' +
428 + 'an uppercase letter.',
429 type,
430 );
431 }
432 + }
433 + }
434
401 - if (type === 'script') {
402 - // Create the script via .innerHTML so its "parser-inserted" flag is
403 - // set to true and it does not execute
404 - var div = ownerDocument.createElement('div');
405 - div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
406 - // This is guaranteed to yield a script element.
407 - var firstChild = ((div.firstChild: any): HTMLScriptElement);
408 - domElement = div.removeChild(firstChild);
409 - } else if (typeof props.is === 'string') {
410 - // $FlowIssue `createElement` should be updated for Web Components
411 - domElement = ownerDocument.createElement(type, {is: props.is});
412 - } else {
413 - // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
414 - // See discussion in https://github.com/facebook/react/pull/6896
415 - // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
416 - domElement = ownerDocument.createElement(type);
417 - }
418 - } else {
419 - domElement = ownerDocument.createElementNS(namespaceURI, type);
435 + return domElement;
436 +}
437 +
438 +export function createTextNode(
439 + text: string,
440 + rootContainerElement: Element | Document,
441 +): Text {
442 + return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(
443 + text,
444 + );
445 +}
446 +
447 +export function setInitialProperties(
448 + domElement: Element,
449 + tag: string,
450 + rawProps: Object,
451 + rootContainerElement: Element | Document,
452 +): void {
453 + var isCustomComponentTag = isCustomComponent(tag, rawProps);
454 + if (__DEV__) {
455 + validatePropertiesInDevelopment(tag, rawProps);
456 + if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
457 + warning(
458 + false,
459 + '%s is using shady DOM. Using shady DOM with React can ' +
460 + 'cause things to break subtly.',
461 + getCurrentFiberOwnerName() || 'A component',
462 + );
463 + didWarnShadyDOM = true;
464 }
465 + }
466
422 - if (__DEV__) {
423 - if (namespaceURI === HTML_NAMESPACE) {
424 - if (
425 - !isCustomComponentTag &&
426 - Object.prototype.toString.call(domElement) ===
427 - '[object HTMLUnknownElement]' &&
428 - !Object.prototype.hasOwnProperty.call(warnedUnknownTags, type)
429 - ) {
430 - warnedUnknownTags[type] = true;
431 - warning(
432 - false,
433 - 'The tag <%s> is unrecognized in this browser. ' +
434 - 'If you meant to render a React component, start its name with ' +
435 - 'an uppercase letter.',
436 - type,
467 + // TODO: Make sure that we check isMounted before firing any of these events.
468 + var props: Object;
469 + switch (tag) {
470 + case 'iframe':
471 + case 'object':
472 + ReactBrowserEventEmitter.trapBubbledEvent('topLoad', 'load', domElement);
473 + props = rawProps;
474 + break;
475 + case 'video':
476 + case 'audio':
477 + // Create listener for each media event
478 + for (var event in mediaEvents) {
479 + if (mediaEvents.hasOwnProperty(event)) {
480 + ReactBrowserEventEmitter.trapBubbledEvent(
481 + event,
482 + mediaEvents[event],
483 + domElement,
484 );
485 }
486 }
440 - }
487 + props = rawProps;
488 + break;
489 + case 'source':
490 + ReactBrowserEventEmitter.trapBubbledEvent(
491 + 'topError',
492 + 'error',
493 + domElement,
494 + );
495 + props = rawProps;
496 + break;
497 + case 'img':
498 + case 'image':
499 + ReactBrowserEventEmitter.trapBubbledEvent(
500 + 'topError',
501 + 'error',
502 + domElement,
503 + );
504 + ReactBrowserEventEmitter.trapBubbledEvent('topLoad', 'load', domElement);
505 + props = rawProps;
506 + break;
507 + case 'form':
508 + ReactBrowserEventEmitter.trapBubbledEvent(
509 + 'topReset',
510 + 'reset',
511 + domElement,
512 + );
513 + ReactBrowserEventEmitter.trapBubbledEvent(
514 + 'topSubmit',
515 + 'submit',
516 + domElement,
517 + );
518 + props = rawProps;
519 + break;
520 + case 'details':
521 + ReactBrowserEventEmitter.trapBubbledEvent(
522 + 'topToggle',
523 + 'toggle',
524 + domElement,
525 + );
526 + props = rawProps;
527 + break;
528 + case 'input':
529 + ReactDOMFiberInput.initWrapperState(domElement, rawProps);
530 + props = ReactDOMFiberInput.getHostProps(domElement, rawProps);
531 + ReactBrowserEventEmitter.trapBubbledEvent(
532 + 'topInvalid',
533 + 'invalid',
534 + domElement,
535 + );
536 + // For controlled components we always need to ensure we're listening
537 + // to onChange. Even if there is no listener.
538 + ensureListeningTo(rootContainerElement, 'onChange');
539 + break;
540 + case 'option':
541 + ReactDOMFiberOption.validateProps(domElement, rawProps);
542 + props = ReactDOMFiberOption.getHostProps(domElement, rawProps);
543 + break;
544 + case 'select':
545 + ReactDOMFiberSelect.initWrapperState(domElement, rawProps);
546 + props = ReactDOMFiberSelect.getHostProps(domElement, rawProps);
547 + ReactBrowserEventEmitter.trapBubbledEvent(
548 + 'topInvalid',
549 + 'invalid',
550 + domElement,
551 + );
552 + // For controlled components we always need to ensure we're listening
553 + // to onChange. Even if there is no listener.
554 + ensureListeningTo(rootContainerElement, 'onChange');
555 + break;
556 + case 'textarea':
557 + ReactDOMFiberTextarea.initWrapperState(domElement, rawProps);
558 + props = ReactDOMFiberTextarea.getHostProps(domElement, rawProps);
559 + ReactBrowserEventEmitter.trapBubbledEvent(
560 + 'topInvalid',
561 + 'invalid',
562 + domElement,
563 + );
564 + // For controlled components we always need to ensure we're listening
565 + // to onChange. Even if there is no listener.
566 + ensureListeningTo(rootContainerElement, 'onChange');
567 + break;
568 + default:
569 + props = rawProps;
570 + }
571
442 - return domElement;
443 - },
572 + assertValidProps(tag, props, getStack);
573
445 - createTextNode(text: string, rootContainerElement: Element | Document): Text {
446 - return getOwnerDocumentFromRootContainer(
447 - rootContainerElement,
448 - ).createTextNode(text);
449 - },
574 + setInitialDOMProperties(
575 + tag,
576 + domElement,
577 + rootContainerElement,
578 + props,
579 + isCustomComponentTag,
580 + );
581
451 - setInitialProperties(
452 - domElement: Element,
453 - tag: string,
454 - rawProps: Object,
455 - rootContainerElement: Element | Document,
456 - ): void {
457 - var isCustomComponentTag = isCustomComponent(tag, rawProps);
458 - if (__DEV__) {
459 - validatePropertiesInDevelopment(tag, rawProps);
460 - if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
461 - warning(
462 - false,
463 - '%s is using shady DOM. Using shady DOM with React can ' +
464 - 'cause things to break subtly.',
465 - getCurrentFiberOwnerName() || 'A component',
466 - );
467 - didWarnShadyDOM = true;
582 + switch (tag) {
583 + case 'input':
584 + // TODO: Make sure we check if this is still unmounted or do any clean
585 + // up necessary since we never stop tracking anymore.
586 + inputValueTracking.track((domElement: any));
587 + ReactDOMFiberInput.postMountWrapper(domElement, rawProps);
588 + break;
589 + case 'textarea':
590 + // TODO: Make sure we check if this is still unmounted or do any clean
591 + // up necessary since we never stop tracking anymore.
592 + inputValueTracking.track((domElement: any));
593 + ReactDOMFiberTextarea.postMountWrapper(domElement, rawProps);
594 + break;
595 + case 'option':
596 + ReactDOMFiberOption.postMountWrapper(domElement, rawProps);
597 + break;
598 + case 'select':
599 + ReactDOMFiberSelect.postMountWrapper(domElement, rawProps);
600 + break;
601 + default:
602 + if (typeof props.onClick === 'function') {
603 + // TODO: This cast may not be sound for SVG, MathML or custom elements.
604 + trapClickOnNonInteractiveElement(((domElement: any): HTMLElement));
605 }
469 - }
606 + break;
607 + }
608 +}
609
471 - // TODO: Make sure that we check isMounted before firing any of these events.
472 - var props: Object;
473 - switch (tag) {
474 - case 'iframe':
475 - case 'object':
476 - ReactBrowserEventEmitter.trapBubbledEvent(
477 - 'topLoad',
478 - 'load',
479 - domElement,
480 - );
481 - props = rawProps;
482 - break;
483 - case 'video':
484 - case 'audio':
485 - // Create listener for each media event
486 - for (var event in mediaEvents) {
487 - if (mediaEvents.hasOwnProperty(event)) {
488 - ReactBrowserEventEmitter.trapBubbledEvent(
489 - event,
490 - mediaEvents[event],
491 - domElement,
492 - );
493 - }
494 - }
495 - props = rawProps;
496 - break;
497 - case 'source':
498 - ReactBrowserEventEmitter.trapBubbledEvent(
499 - 'topError',
500 - 'error',
501 - domElement,
502 - );
503 - props = rawProps;
504 - break;
505 - case 'img':
506 - case 'image':
507 - ReactBrowserEventEmitter.trapBubbledEvent(
508 - 'topError',
509 - 'error',
510 - domElement,
511 - );
512 - ReactBrowserEventEmitter.trapBubbledEvent(
513 - 'topLoad',
514 - 'load',
515 - domElement,
516 - );
517 - props = rawProps;
518 - break;
519 - case 'form':
520 - ReactBrowserEventEmitter.trapBubbledEvent(
521 - 'topReset',
522 - 'reset',
523 - domElement,
524 - );
525 - ReactBrowserEventEmitter.trapBubbledEvent(
526 - 'topSubmit',
527 - 'submit',
528 - domElement,
529 - );
530 - props = rawProps;
531 - break;
532 - case 'details':
533 - ReactBrowserEventEmitter.trapBubbledEvent(
534 - 'topToggle',
535 - 'toggle',
536 - domElement,
537 - );
538 - props = rawProps;
539 - break;
540 - case 'input':
541 - ReactDOMFiberInput.initWrapperState(domElement, rawProps);
542 - props = ReactDOMFiberInput.getHostProps(domElement, rawProps);
543 - ReactBrowserEventEmitter.trapBubbledEvent(
544 - 'topInvalid',
545 - 'invalid',
546 - domElement,
547 - );
548 - // For controlled components we always need to ensure we're listening
549 - // to onChange. Even if there is no listener.
550 - ensureListeningTo(rootContainerElement, 'onChange');
551 - break;
552 - case 'option':
553 - ReactDOMFiberOption.validateProps(domElement, rawProps);
554 - props = ReactDOMFiberOption.getHostProps(domElement, rawProps);
555 - break;
556 - case 'select':
557 - ReactDOMFiberSelect.initWrapperState(domElement, rawProps);
558 - props = ReactDOMFiberSelect.getHostProps(domElement, rawProps);
559 - ReactBrowserEventEmitter.trapBubbledEvent(
560 - 'topInvalid',
561 - 'invalid',
562 - domElement,
563 - );
564 - // For controlled components we always need to ensure we're listening
565 - // to onChange. Even if there is no listener.
566 - ensureListeningTo(rootContainerElement, 'onChange');
567 - break;
568 - case 'textarea':
569 - ReactDOMFiberTextarea.initWrapperState(domElement, rawProps);
570 - props = ReactDOMFiberTextarea.getHostProps(domElement, rawProps);
571 - ReactBrowserEventEmitter.trapBubbledEvent(
572 - 'topInvalid',
573 - 'invalid',
574 - domElement,
575 - );
576 - // For controlled components we always need to ensure we're listening
577 - // to onChange. Even if there is no listener.
578 - ensureListeningTo(rootContainerElement, 'onChange');
579 - break;
580 - default:
581 - props = rawProps;
582 - }
610 +// Calculate the diff between the two objects.
611 +export function diffProperties(
612 + domElement: Element,
613 + tag: string,
614 + lastRawProps: Object,
615 + nextRawProps: Object,
616 + rootContainerElement: Element | Document,
617 +): null | Array<mixed> {
618 + if (__DEV__) {
619 + validatePropertiesInDevelopment(tag, nextRawProps);
620 + }
621
584 - assertValidProps(tag, props, getStack);
622 + var updatePayload: null | Array<any> = null;
623
586 - setInitialDOMProperties(
587 - tag,
588 - domElement,
589 - rootContainerElement,
590 - props,
591 - isCustomComponentTag,
592 - );
624 + var lastProps: Object;
625 + var nextProps: Object;
626 + switch (tag) {
627 + case 'input':
628 + lastProps = ReactDOMFiberInput.getHostProps(domElement, lastRawProps);
629 + nextProps = ReactDOMFiberInput.getHostProps(domElement, nextRawProps);
630 + updatePayload = [];
631 + break;
632 + case 'option':
633 + lastProps = ReactDOMFiberOption.getHostProps(domElement, lastRawProps);
634 + nextProps = ReactDOMFiberOption.getHostProps(domElement, nextRawProps);
635 + updatePayload = [];
636 + break;
637 + case 'select':
638 + lastProps = ReactDOMFiberSelect.getHostProps(domElement, lastRawProps);
639 + nextProps = ReactDOMFiberSelect.getHostProps(domElement, nextRawProps);
640 + updatePayload = [];
641 + break;
642 + case 'textarea':
643 + lastProps = ReactDOMFiberTextarea.getHostProps(domElement, lastRawProps);
644 + nextProps = ReactDOMFiberTextarea.getHostProps(domElement, nextRawProps);
645 + updatePayload = [];
646 + break;
647 + default:
648 + lastProps = lastRawProps;
649 + nextProps = nextRawProps;
650 + if (
651 + typeof lastProps.onClick !== 'function' &&
652 + typeof nextProps.onClick === 'function'
653 + ) {
654 + // TODO: This cast may not be sound for SVG, MathML or custom elements.
655 + trapClickOnNonInteractiveElement(((domElement: any): HTMLElement));
656 + }
657 + break;
658 + }
659
594 - switch (tag) {
595 - case 'input':
596 - // TODO: Make sure we check if this is still unmounted or do any clean
597 - // up necessary since we never stop tracking anymore.
598 - inputValueTracking.track((domElement: any));
599 - ReactDOMFiberInput.postMountWrapper(domElement, rawProps);
600 - break;
601 - case 'textarea':
602 - // TODO: Make sure we check if this is still unmounted or do any clean
603 - // up necessary since we never stop tracking anymore.
604 - inputValueTracking.track((domElement: any));
605 - ReactDOMFiberTextarea.postMountWrapper(domElement, rawProps);
606 - break;
607 - case 'option':
608 - ReactDOMFiberOption.postMountWrapper(domElement, rawProps);
609 - break;
610 - case 'select':
611 - ReactDOMFiberSelect.postMountWrapper(domElement, rawProps);
612 - break;
613 - default:
614 - if (typeof props.onClick === 'function') {
615 - // TODO: This cast may not be sound for SVG, MathML or custom elements.
616 - trapClickOnNonInteractiveElement(((domElement: any): HTMLElement));
617 - }
618 - break;
619 - }
620 - },
660 + assertValidProps(tag, nextProps, getStack);
661
622 - // Calculate the diff between the two objects.
623 - diffProperties(
624 - domElement: Element,
625 - tag: string,
626 - lastRawProps: Object,
627 - nextRawProps: Object,
628 - rootContainerElement: Element | Document,
629 - ): null | Array<mixed> {
630 - if (__DEV__) {
631 - validatePropertiesInDevelopment(tag, nextRawProps);
662 + var propKey;
663 + var styleName;
664 + var styleUpdates = null;
665 + for (propKey in lastProps) {
666 + if (
667 + nextProps.hasOwnProperty(propKey) ||
668 + !lastProps.hasOwnProperty(propKey) ||
669 + lastProps[propKey] == null
670 + ) {
671 + continue;
672 }
633 -
634 - var updatePayload: null | Array<any> = null;
635 -
636 - var lastProps: Object;
637 - var nextProps: Object;
638 - switch (tag) {
639 - case 'input':
640 - lastProps = ReactDOMFiberInput.getHostProps(domElement, lastRawProps);
641 - nextProps = ReactDOMFiberInput.getHostProps(domElement, nextRawProps);
642 - updatePayload = [];
643 - break;
644 - case 'option':
645 - lastProps = ReactDOMFiberOption.getHostProps(domElement, lastRawProps);
646 - nextProps = ReactDOMFiberOption.getHostProps(domElement, nextRawProps);
647 - updatePayload = [];
648 - break;
649 - case 'select':
650 - lastProps = ReactDOMFiberSelect.getHostProps(domElement, lastRawProps);
651 - nextProps = ReactDOMFiberSelect.getHostProps(domElement, nextRawProps);
652 - updatePayload = [];
653 - break;
654 - case 'textarea':
655 - lastProps = ReactDOMFiberTextarea.getHostProps(
656 - domElement,
657 - lastRawProps,
658 - );
659 - nextProps = ReactDOMFiberTextarea.getHostProps(
660 - domElement,
661 - nextRawProps,
662 - );
663 - updatePayload = [];
664 - break;
665 - default:
666 - lastProps = lastRawProps;
667 - nextProps = nextRawProps;
668 - if (
669 - typeof lastProps.onClick !== 'function' &&
670 - typeof nextProps.onClick === 'function'
671 - ) {
672 - // TODO: This cast may not be sound for SVG, MathML or custom elements.
673 - trapClickOnNonInteractiveElement(((domElement: any): HTMLElement));
673 + if (propKey === STYLE) {
674 + var lastStyle = lastProps[propKey];
675 + for (styleName in lastStyle) {
676 + if (lastStyle.hasOwnProperty(styleName)) {
677 + if (!styleUpdates) {
678 + styleUpdates = {};
679 + }
680 + styleUpdates[styleName] = '';
681 }
675 - break;
682 + }
683 + } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) {
684 + // Noop. This is handled by the clear text mechanism.
685 + } else if (
686 + propKey === SUPPRESS_CONTENT_EDITABLE_WARNING ||
687 + propKey === SUPPRESS_HYDRATION_WARNING
688 + ) {
689 + // Noop
690 + } else if (propKey === AUTOFOCUS) {
691 + // Noop. It doesn't work on updates anyway.
692 + } else if (registrationNameModules.hasOwnProperty(propKey)) {
693 + // This is a special case. If any listener updates we need to ensure
694 + // that the "current" fiber pointer gets updated so we need a commit
695 + // to update this element.
696 + if (!updatePayload) {
697 + updatePayload = [];
698 + }
699 + } else {
700 + // For all other deleted properties we add it to the queue. We use
701 + // the whitelist in the commit phase instead.
702 + (updatePayload = updatePayload || []).push(propKey, null);
703 }
677 -
678 - assertValidProps(tag, nextProps, getStack);
679 -
680 - var propKey;
681 - var styleName;
682 - var styleUpdates = null;
683 - for (propKey in lastProps) {
684 - if (
685 - nextProps.hasOwnProperty(propKey) ||
686 - !lastProps.hasOwnProperty(propKey) ||
687 - lastProps[propKey] == null
688 - ) {
689 - continue;
704 + }
705 + for (propKey in nextProps) {
706 + var nextProp = nextProps[propKey];
707 + var lastProp = lastProps != null ? lastProps[propKey] : undefined;
708 + if (
709 + !nextProps.hasOwnProperty(propKey) ||
710 + nextProp === lastProp ||
711 + (nextProp == null && lastProp == null)
712 + ) {
713 + continue;
714 + }
715 + if (propKey === STYLE) {
716 + if (__DEV__) {
717 + if (nextProp) {
718 + // Freeze the next style object so that we can assume it won't be
719 + // mutated. We have already warned for this in the past.
720 + Object.freeze(nextProp);
721 + }
722 }
691 - if (propKey === STYLE) {
692 - var lastStyle = lastProps[propKey];
693 - for (styleName in lastStyle) {
694 - if (lastStyle.hasOwnProperty(styleName)) {
723 + if (lastProp) {
724 + // Unset styles on `lastProp` but not on `nextProp`.
725 + for (styleName in lastProp) {
726 + if (
727 + lastProp.hasOwnProperty(styleName) &&
728 + (!nextProp || !nextProp.hasOwnProperty(styleName))
729 + ) {
730 if (!styleUpdates) {
731 styleUpdates = {};
732 }
733 styleUpdates[styleName] = '';
734 }
735 }
701 - } else if (
702 - propKey === DANGEROUSLY_SET_INNER_HTML ||
703 - propKey === CHILDREN
704 - ) {
705 - // Noop. This is handled by the clear text mechanism.
706 - } else if (
707 - propKey === SUPPRESS_CONTENT_EDITABLE_WARNING ||
708 - propKey === SUPPRESS_HYDRATION_WARNING
709 - ) {
710 - // Noop
711 - } else if (propKey === AUTOFOCUS) {
712 - // Noop. It doesn't work on updates anyway.
713 - } else if (registrationNameModules.hasOwnProperty(propKey)) {
714 - // This is a special case. If any listener updates we need to ensure
715 - // that the "current" fiber pointer gets updated so we need a commit
716 - // to update this element.
717 - if (!updatePayload) {
718 - updatePayload = [];
719 - }
720 - } else {
721 - // For all other deleted properties we add it to the queue. We use
722 - // the whitelist in the commit phase instead.
723 - (updatePayload = updatePayload || []).push(propKey, null);
724 - }
725 - }
726 - for (propKey in nextProps) {
727 - var nextProp = nextProps[propKey];
728 - var lastProp = lastProps != null ? lastProps[propKey] : undefined;
729 - if (
730 - !nextProps.hasOwnProperty(propKey) ||
731 - nextProp === lastProp ||
732 - (nextProp == null && lastProp == null)
733 - ) {
734 - continue;
735 - }
736 - if (propKey === STYLE) {
737 - if (__DEV__) {
738 - if (nextProp) {
739 - // Freeze the next style object so that we can assume it won't be
740 - // mutated. We have already warned for this in the past.
741 - Object.freeze(nextProp);
742 - }
743 - }
744 - if (lastProp) {
745 - // Unset styles on `lastProp` but not on `nextProp`.
746 - for (styleName in lastProp) {
747 - if (
748 - lastProp.hasOwnProperty(styleName) &&
749 - (!nextProp || !nextProp.hasOwnProperty(styleName))
750 - ) {
751 - if (!styleUpdates) {
752 - styleUpdates = {};
753 - }
754 - styleUpdates[styleName] = '';
755 - }
756 - }
757 - // Update styles that changed since `lastProp`.
758 - for (styleName in nextProp) {
759 - if (
760 - nextProp.hasOwnProperty(styleName) &&
761 - lastProp[styleName] !== nextProp[styleName]
762 - ) {
763 - if (!styleUpdates) {
764 - styleUpdates = {};
765 - }
766 - styleUpdates[styleName] = nextProp[styleName];
767 - }
768 - }
769 - } else {
770 - // Relies on `updateStylesByID` not mutating `styleUpdates`.
771 - if (!styleUpdates) {
772 - if (!updatePayload) {
773 - updatePayload = [];
736 + // Update styles that changed since `lastProp`.
737 + for (styleName in nextProp) {
738 + if (
739 + nextProp.hasOwnProperty(styleName) &&
740 + lastProp[styleName] !== nextProp[styleName]
741 + ) {
742 + if (!styleUpdates) {
743 + styleUpdates = {};
744 }
775 - updatePayload.push(propKey, styleUpdates);
745 + styleUpdates[styleName] = nextProp[styleName];
746 }
777 - styleUpdates = nextProp;
747 }
779 - } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
780 - var nextHtml = nextProp ? nextProp[HTML] : undefined;
781 - var lastHtml = lastProp ? lastProp[HTML] : undefined;
782 - if (nextHtml != null) {
783 - if (lastHtml !== nextHtml) {
784 - (updatePayload = updatePayload || []).push(propKey, '' + nextHtml);
748 + } else {
749 + // Relies on `updateStylesByID` not mutating `styleUpdates`.
750 + if (!styleUpdates) {
751 + if (!updatePayload) {
752 + updatePayload = [];
753 }
786 - } else {
787 - // TODO: It might be too late to clear this if we have children
788 - // inserted already.
754 + updatePayload.push(propKey, styleUpdates);
755 }
790 - } else if (propKey === CHILDREN) {
791 - if (
792 - lastProp !== nextProp &&
793 - (typeof nextProp === 'string' || typeof nextProp === 'number')
794 - ) {
795 - (updatePayload = updatePayload || []).push(propKey, '' + nextProp);
756 + styleUpdates = nextProp;
757 + }
758 + } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
759 + var nextHtml = nextProp ? nextProp[HTML] : undefined;
760 + var lastHtml = lastProp ? lastProp[HTML] : undefined;
761 + if (nextHtml != null) {
762 + if (lastHtml !== nextHtml) {
763 + (updatePayload = updatePayload || []).push(propKey, '' + nextHtml);
764 }
797 - } else if (
798 - propKey === SUPPRESS_CONTENT_EDITABLE_WARNING ||
799 - propKey === SUPPRESS_HYDRATION_WARNING
765 + } else {
766 + // TODO: It might be too late to clear this if we have children
767 + // inserted already.
768 + }
769 + } else if (propKey === CHILDREN) {
770 + if (
771 + lastProp !== nextProp &&
772 + (typeof nextProp === 'string' || typeof nextProp === 'number')
773 ) {
801 - // Noop
802 - } else if (registrationNameModules.hasOwnProperty(propKey)) {
803 - if (nextProp != null) {
804 - // We eagerly listen to this even though we haven't committed yet.
805 - if (__DEV__ && typeof nextProp !== 'function') {
806 - warnForInvalidEventListener(propKey, nextProp);
807 - }
808 - ensureListeningTo(rootContainerElement, propKey);
809 - }
810 - if (!updatePayload && lastProp !== nextProp) {
811 - // This is a special case. If any listener updates we need to ensure
812 - // that the "current" props pointer gets updated so we need a commit
813 - // to update this element.
814 - updatePayload = [];
774 + (updatePayload = updatePayload || []).push(propKey, '' + nextProp);
775 + }
776 + } else if (
777 + propKey === SUPPRESS_CONTENT_EDITABLE_WARNING ||
778 + propKey === SUPPRESS_HYDRATION_WARNING
779 + ) {
780 + // Noop
781 + } else if (registrationNameModules.hasOwnProperty(propKey)) {
782 + if (nextProp != null) {
783 + // We eagerly listen to this even though we haven't committed yet.
784 + if (__DEV__ && typeof nextProp !== 'function') {
785 + warnForInvalidEventListener(propKey, nextProp);
786 }
816 - } else {
817 - // For any other property we always add it to the queue and then we
818 - // filter it out using the whitelist during the commit.
819 - (updatePayload = updatePayload || []).push(propKey, nextProp);
787 + ensureListeningTo(rootContainerElement, propKey);
788 }
789 + if (!updatePayload && lastProp !== nextProp) {
790 + // This is a special case. If any listener updates we need to ensure
791 + // that the "current" props pointer gets updated so we need a commit
792 + // to update this element.
793 + updatePayload = [];
794 + }
795 + } else {
796 + // For any other property we always add it to the queue and then we
797 + // filter it out using the whitelist during the commit.
798 + (updatePayload = updatePayload || []).push(propKey, nextProp);
799 }
822 - if (styleUpdates) {
823 - (updatePayload = updatePayload || []).push(STYLE, styleUpdates);
824 - }
825 - return updatePayload;
826 - },
800 + }
801 + if (styleUpdates) {
802 + (updatePayload = updatePayload || []).push(STYLE, styleUpdates);
803 + }
804 + return updatePayload;
805 +}
806
807 +// Apply the diff.
808 +export function updateProperties(
809 + domElement: Element,
810 + updatePayload: Array<any>,
811 + tag: string,
812 + lastRawProps: Object,
813 + nextRawProps: Object,
814 +): void {
815 + var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
816 + var isCustomComponentTag = isCustomComponent(tag, nextRawProps);
817 // Apply the diff.
829 - updateProperties(
830 - domElement: Element,
831 - updatePayload: Array<any>,
832 - tag: string,
833 - lastRawProps: Object,
834 - nextRawProps: Object,
835 - ): void {
836 - var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
837 - var isCustomComponentTag = isCustomComponent(tag, nextRawProps);
838 - // Apply the diff.
839 - updateDOMProperties(
840 - domElement,
841 - updatePayload,
842 - wasCustomComponentTag,
843 - isCustomComponentTag,
844 - );
818 + updateDOMProperties(
819 + domElement,
820 + updatePayload,
821 + wasCustomComponentTag,
822 + isCustomComponentTag,
823 + );
824
846 - // TODO: Ensure that an update gets scheduled if any of the special props
847 - // changed.
848 - switch (tag) {
849 - case 'input':
850 - // Update the wrapper around inputs *after* updating props. This has to
851 - // happen after `updateDOMProperties`. Otherwise HTML5 input validations
852 - // raise warnings and prevent the new value from being assigned.
853 - ReactDOMFiberInput.updateWrapper(domElement, nextRawProps);
825 + // TODO: Ensure that an update gets scheduled if any of the special props
826 + // changed.
827 + switch (tag) {
828 + case 'input':
829 + // Update the wrapper around inputs *after* updating props. This has to
830 + // happen after `updateDOMProperties`. Otherwise HTML5 input validations
831 + // raise warnings and prevent the new value from being assigned.
832 + ReactDOMFiberInput.updateWrapper(domElement, nextRawProps);
833
855 - // We also check that we haven't missed a value update, such as a
856 - // Radio group shifting the checked value to another named radio input.
857 - inputValueTracking.updateValueIfChanged((domElement: any));
858 - break;
859 - case 'textarea':
860 - ReactDOMFiberTextarea.updateWrapper(domElement, nextRawProps);
861 - break;
862 - case 'select':
863 - // <select> value update needs to occur after <option> children
864 - // reconciliation
865 - ReactDOMFiberSelect.postUpdateWrapper(domElement, nextRawProps);
866 - break;
867 - }
868 - },
834 + // We also check that we haven't missed a value update, such as a
835 + // Radio group shifting the checked value to another named radio input.
836 + inputValueTracking.updateValueIfChanged((domElement: any));
837 + break;
838 + case 'textarea':
839 + ReactDOMFiberTextarea.updateWrapper(domElement, nextRawProps);
840 + break;
841 + case 'select':
842 + // <select> value update needs to occur after <option> children
843 + // reconciliation
844 + ReactDOMFiberSelect.postUpdateWrapper(domElement, nextRawProps);
845 + break;
846 + }
847 +}
848
870 - diffHydratedProperties(
871 - domElement: Element,
872 - tag: string,
873 - rawProps: Object,
874 - parentNamespace: string,
875 - rootContainerElement: Element | Document,
876 - ): null | Array<mixed> {
877 - if (__DEV__) {
878 - var suppressHydrationWarning =
879 - rawProps[SUPPRESS_HYDRATION_WARNING] === true;
880 - var isCustomComponentTag = isCustomComponent(tag, rawProps);
881 - validatePropertiesInDevelopment(tag, rawProps);
882 - if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
883 - warning(
884 - false,
885 - '%s is using shady DOM. Using shady DOM with React can ' +
886 - 'cause things to break subtly.',
887 - getCurrentFiberOwnerName() || 'A component',
888 - );
889 - didWarnShadyDOM = true;
890 - }
849 +export function diffHydratedProperties(
850 + domElement: Element,
851 + tag: string,
852 + rawProps: Object,
853 + parentNamespace: string,
854 + rootContainerElement: Element | Document,
855 +): null | Array<mixed> {
856 + if (__DEV__) {
857 + var suppressHydrationWarning =
858 + rawProps[SUPPRESS_HYDRATION_WARNING] === true;
859 + var isCustomComponentTag = isCustomComponent(tag, rawProps);
860 + validatePropertiesInDevelopment(tag, rawProps);
861 + if (isCustomComponentTag && !didWarnShadyDOM && domElement.shadyRoot) {
862 + warning(
863 + false,
864 + '%s is using shady DOM. Using shady DOM with React can ' +
865 + 'cause things to break subtly.',
866 + getCurrentFiberOwnerName() || 'A component',
867 + );
868 + didWarnShadyDOM = true;
869 }
870 + }
871
893 - // TODO: Make sure that we check isMounted before firing any of these events.
894 - switch (tag) {
895 - case 'iframe':
896 - case 'object':
897 - ReactBrowserEventEmitter.trapBubbledEvent(
898 - 'topLoad',
899 - 'load',
900 - domElement,
901 - );
902 - break;
903 - case 'video':
904 - case 'audio':
905 - // Create listener for each media event
906 - for (var event in mediaEvents) {
907 - if (mediaEvents.hasOwnProperty(event)) {
908 - ReactBrowserEventEmitter.trapBubbledEvent(
909 - event,
910 - mediaEvents[event],
911 - domElement,
912 - );
913 - }
872 + // TODO: Make sure that we check isMounted before firing any of these events.
873 + switch (tag) {
874 + case 'iframe':
875 + case 'object':
876 + ReactBrowserEventEmitter.trapBubbledEvent('topLoad', 'load', domElement);
877 + break;
878 + case 'video':
879 + case 'audio':
880 + // Create listener for each media event
881 + for (var event in mediaEvents) {
882 + if (mediaEvents.hasOwnProperty(event)) {
883 + ReactBrowserEventEmitter.trapBubbledEvent(
884 + event,
885 + mediaEvents[event],
886 + domElement,
887 + );
888 }
915 - break;
916 - case 'source':
917 - ReactBrowserEventEmitter.trapBubbledEvent(
918 - 'topError',
919 - 'error',
920 - domElement,
921 - );
922 - break;
923 - case 'img':
924 - case 'image':
925 - ReactBrowserEventEmitter.trapBubbledEvent(
926 - 'topError',
927 - 'error',
928 - domElement,
929 - );
930 - ReactBrowserEventEmitter.trapBubbledEvent(
931 - 'topLoad',
932 - 'load',
933 - domElement,
934 - );
935 - break;
936 - case 'form':
937 - ReactBrowserEventEmitter.trapBubbledEvent(
938 - 'topReset',
939 - 'reset',
940 - domElement,
941 - );
942 - ReactBrowserEventEmitter.trapBubbledEvent(
943 - 'topSubmit',
944 - 'submit',
945 - domElement,
946 - );
947 - break;
948 - case 'details':
949 - ReactBrowserEventEmitter.trapBubbledEvent(
950 - 'topToggle',
951 - 'toggle',
952 - domElement,
953 - );
954 - break;
955 - case 'input':
956 - ReactDOMFiberInput.initWrapperState(domElement, rawProps);
957 - ReactBrowserEventEmitter.trapBubbledEvent(
958 - 'topInvalid',
959 - 'invalid',
960 - domElement,
961 - );
962 - // For controlled components we always need to ensure we're listening
963 - // to onChange. Even if there is no listener.
964 - ensureListeningTo(rootContainerElement, 'onChange');
965 - break;
966 - case 'option':
967 - ReactDOMFiberOption.validateProps(domElement, rawProps);
968 - break;
969 - case 'select':
970 - ReactDOMFiberSelect.initWrapperState(domElement, rawProps);
971 - ReactBrowserEventEmitter.trapBubbledEvent(
972 - 'topInvalid',
973 - 'invalid',
974 - domElement,
975 - );
976 - // For controlled components we always need to ensure we're listening
977 - // to onChange. Even if there is no listener.
978 - ensureListeningTo(rootContainerElement, 'onChange');
979 - break;
980 - case 'textarea':
981 - ReactDOMFiberTextarea.initWrapperState(domElement, rawProps);
982 - ReactBrowserEventEmitter.trapBubbledEvent(
983 - 'topInvalid',
984 - 'invalid',
985 - domElement,
986 - );
987 - // For controlled components we always need to ensure we're listening
988 - // to onChange. Even if there is no listener.
989 - ensureListeningTo(rootContainerElement, 'onChange');
990 - break;
991 - }
889 + }
890 + break;
891 + case 'source':
892 + ReactBrowserEventEmitter.trapBubbledEvent(
893 + 'topError',
894 + 'error',
895 + domElement,
896 + );
897 + break;
898 + case 'img':
899 + case 'image':
900 + ReactBrowserEventEmitter.trapBubbledEvent(
901 + 'topError',
902 + 'error',
903 + domElement,
904 + );
905 + ReactBrowserEventEmitter.trapBubbledEvent('topLoad', 'load', domElement);
906 + break;
907 + case 'form':
908 + ReactBrowserEventEmitter.trapBubbledEvent(
909 + 'topReset',
910 + 'reset',
911 + domElement,
912 + );
913 + ReactBrowserEventEmitter.trapBubbledEvent(
914 + 'topSubmit',
915 + 'submit',
916 + domElement,
917 + );
918 + break;
919 + case 'details':
920 + ReactBrowserEventEmitter.trapBubbledEvent(
921 + 'topToggle',
922 + 'toggle',
923 + domElement,
924 + );
925 + break;
926 + case 'input':
927 + ReactDOMFiberInput.initWrapperState(domElement, rawProps);
928 + ReactBrowserEventEmitter.trapBubbledEvent(
929 + 'topInvalid',
930 + 'invalid',
931 + domElement,
932 + );
933 + // For controlled components we always need to ensure we're listening
934 + // to onChange. Even if there is no listener.
935 + ensureListeningTo(rootContainerElement, 'onChange');
936 + break;
937 + case 'option':
938 + ReactDOMFiberOption.validateProps(domElement, rawProps);
939 + break;
940 + case 'select':
941 + ReactDOMFiberSelect.initWrapperState(domElement, rawProps);
942 + ReactBrowserEventEmitter.trapBubbledEvent(
943 + 'topInvalid',
944 + 'invalid',
945 + domElement,
946 + );
947 + // For controlled components we always need to ensure we're listening
948 + // to onChange. Even if there is no listener.
949 + ensureListeningTo(rootContainerElement, 'onChange');
950 + break;
951 + case 'textarea':
952 + ReactDOMFiberTextarea.initWrapperState(domElement, rawProps);
953 + ReactBrowserEventEmitter.trapBubbledEvent(
954 + 'topInvalid',
955 + 'invalid',
956 + domElement,
957 + );
958 + // For controlled components we always need to ensure we're listening
959 + // to onChange. Even if there is no listener.
960 + ensureListeningTo(rootContainerElement, 'onChange');
961 + break;
962 + }
963
993 - assertValidProps(tag, rawProps, getStack);
964 + assertValidProps(tag, rawProps, getStack);
965
995 - if (__DEV__) {
996 - var extraAttributeNames: Set<string> = new Set();
997 - var attributes = domElement.attributes;
998 - for (var i = 0; i < attributes.length; i++) {
999 - var name = attributes[i].name.toLowerCase();
1000 - switch (name) {
1001 - // Built-in SSR attribute is whitelisted
1002 - case 'data-reactroot':
1003 - break;
1004 - // Controlled attributes are not validated
1005 - // TODO: Only ignore them on controlled tags.
1006 - case 'value':
1007 - break;
1008 - case 'checked':
1009 - break;
1010 - case 'selected':
1011 - break;
1012 - default:
1013 - // Intentionally use the original name.
1014 - // See discussion in https://github.com/facebook/react/pull/10676.
1015 - extraAttributeNames.add(attributes[i].name);
1016 - }
966 + if (__DEV__) {
967 + var extraAttributeNames: Set<string> = new Set();
968 + var attributes = domElement.attributes;
969 + for (var i = 0; i < attributes.length; i++) {
970 + var name = attributes[i].name.toLowerCase();
971 + switch (name) {
972 + // Built-in SSR attribute is whitelisted
973 + case 'data-reactroot':
974 + break;
975 + // Controlled attributes are not validated
976 + // TODO: Only ignore them on controlled tags.
977 + case 'value':
978 + break;
979 + case 'checked':
980 + break;
981 + case 'selected':
982 + break;
983 + default:
984 + // Intentionally use the original name.
985 + // See discussion in https://github.com/facebook/react/pull/10676.
986 + extraAttributeNames.add(attributes[i].name);
987 }
988 }
989 + }
990
1020 - var updatePayload = null;
1021 - for (var propKey in rawProps) {
1022 - if (!rawProps.hasOwnProperty(propKey)) {
1023 - continue;
1024 - }
1025 - var nextProp = rawProps[propKey];
1026 - if (propKey === CHILDREN) {
1027 - // For text content children we compare against textContent. This
1028 - // might match additional HTML that is hidden when we read it using
1029 - // textContent. E.g. "foo" will match "f<span>oo</span>" but that still
1030 - // satisfies our requirement. Our requirement is not to produce perfect
1031 - // HTML and attributes. Ideally we should preserve structure but it's
1032 - // ok not to if the visible content is still enough to indicate what
1033 - // even listeners these nodes might be wired up to.
1034 - // TODO: Warn if there is more than a single textNode as a child.
1035 - // TODO: Should we use domElement.firstChild.nodeValue to compare?
1036 - if (typeof nextProp === 'string') {
1037 - if (domElement.textContent !== nextProp) {
1038 - if (__DEV__ && !suppressHydrationWarning) {
1039 - warnForTextDifference(domElement.textContent, nextProp);
1040 - }
1041 - updatePayload = [CHILDREN, nextProp];
1042 - }
1043 - } else if (typeof nextProp === 'number') {
1044 - if (domElement.textContent !== '' + nextProp) {
1045 - if (__DEV__ && !suppressHydrationWarning) {
1046 - warnForTextDifference(domElement.textContent, nextProp);
1047 - }
1048 - updatePayload = [CHILDREN, '' + nextProp];
991 + var updatePayload = null;
992 + for (var propKey in rawProps) {
993 + if (!rawProps.hasOwnProperty(propKey)) {
994 + continue;
995 + }
996 + var nextProp = rawProps[propKey];
997 + if (propKey === CHILDREN) {
998 + // For text content children we compare against textContent. This
999 + // might match additional HTML that is hidden when we read it using
1000 + // textContent. E.g. "foo" will match "f<span>oo</span>" but that still
1001 + // satisfies our requirement. Our requirement is not to produce perfect
1002 + // HTML and attributes. Ideally we should preserve structure but it's
1003 + // ok not to if the visible content is still enough to indicate what
1004 + // even listeners these nodes might be wired up to.
1005 + // TODO: Warn if there is more than a single textNode as a child.
1006 + // TODO: Should we use domElement.firstChild.nodeValue to compare?
1007 + if (typeof nextProp === 'string') {
1008 + if (domElement.textContent !== nextProp) {
1009 + if (__DEV__ && !suppressHydrationWarning) {
1010 + warnForTextDifference(domElement.textContent, nextProp);
1011 }
1012 + updatePayload = [CHILDREN, nextProp];
1013 }
1051 - } else if (registrationNameModules.hasOwnProperty(propKey)) {
1052 - if (nextProp != null) {
1053 - if (__DEV__ && typeof nextProp !== 'function') {
1054 - warnForInvalidEventListener(propKey, nextProp);
1014 + } else if (typeof nextProp === 'number') {
1015 + if (domElement.textContent !== '' + nextProp) {
1016 + if (__DEV__ && !suppressHydrationWarning) {
1017 + warnForTextDifference(domElement.textContent, nextProp);
1018 }
1056 - ensureListeningTo(rootContainerElement, propKey);
1019 + updatePayload = [CHILDREN, '' + nextProp];
1020 }
1058 - } else if (__DEV__) {
1059 - // Validate that the properties correspond to their expected values.
1060 - var serverValue;
1061 - var propertyInfo;
1062 - if (suppressHydrationWarning) {
1063 - // Don't bother comparing. We're ignoring all these warnings.
1064 - } else if (
1065 - propKey === SUPPRESS_CONTENT_EDITABLE_WARNING ||
1066 - propKey === SUPPRESS_HYDRATION_WARNING ||
1067 - // Controlled attributes are not validated
1068 - // TODO: Only ignore them on controlled tags.
1069 - propKey === 'value' ||
1070 - propKey === 'checked' ||
1071 - propKey === 'selected'
1072 - ) {
1073 - // Noop
1074 - } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
1075 - const rawHtml = nextProp ? nextProp[HTML] || '' : '';
1076 - const serverHTML = domElement.innerHTML;
1077 - const expectedHTML = normalizeHTML(domElement, rawHtml);
1078 - if (expectedHTML !== serverHTML) {
1079 - warnForPropDifference(propKey, serverHTML, expectedHTML);
1080 - }
1081 - } else if (propKey === STYLE) {
1082 - // $FlowFixMe - Should be inferred as not undefined.
1083 - extraAttributeNames.delete(propKey);
1084 - const expectedStyle = CSSPropertyOperations.createDangerousStringForStyles(
1085 - nextProp,
1086 - );
1087 - serverValue = domElement.getAttribute('style');
1088 - if (expectedStyle !== serverValue) {
1089 - warnForPropDifference(propKey, serverValue, expectedStyle);
1090 - }
1091 - } else if (isCustomComponentTag) {
1021 + }
1022 + } else if (registrationNameModules.hasOwnProperty(propKey)) {
1023 + if (nextProp != null) {
1024 + if (__DEV__ && typeof nextProp !== 'function') {
1025 + warnForInvalidEventListener(propKey, nextProp);
1026 + }
1027 + ensureListeningTo(rootContainerElement, propKey);
1028 + }
1029 + } else if (__DEV__) {
1030 + // Validate that the properties correspond to their expected values.
1031 + var serverValue;
1032 + var propertyInfo;
1033 + if (suppressHydrationWarning) {
1034 + // Don't bother comparing. We're ignoring all these warnings.
1035 + } else if (
1036 + propKey === SUPPRESS_CONTENT_EDITABLE_WARNING ||
1037 + propKey === SUPPRESS_HYDRATION_WARNING ||
1038 + // Controlled attributes are not validated
1039 + // TODO: Only ignore them on controlled tags.
1040 + propKey === 'value' ||
1041 + propKey === 'checked' ||
1042 + propKey === 'selected'
1043 + ) {
1044 + // Noop
1045 + } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
1046 + const rawHtml = nextProp ? nextProp[HTML] || '' : '';
1047 + const serverHTML = domElement.innerHTML;
1048 + const expectedHTML = normalizeHTML(domElement, rawHtml);
1049 + if (expectedHTML !== serverHTML) {
1050 + warnForPropDifference(propKey, serverHTML, expectedHTML);
1051 + }
1052 + } else if (propKey === STYLE) {
1053 + // $FlowFixMe - Should be inferred as not undefined.
1054 + extraAttributeNames.delete(propKey);
1055 + const expectedStyle = CSSPropertyOperations.createDangerousStringForStyles(
1056 + nextProp,
1057 + );
1058 + serverValue = domElement.getAttribute('style');
1059 + if (expectedStyle !== serverValue) {
1060 + warnForPropDifference(propKey, serverValue, expectedStyle);
1061 + }
1062 + } else if (isCustomComponentTag) {
1063 + // $FlowFixMe - Should be inferred as not undefined.
1064 + extraAttributeNames.delete(propKey.toLowerCase());
1065 + serverValue = DOMPropertyOperations.getValueForAttribute(
1066 + domElement,
1067 + propKey,
1068 + nextProp,
1069 + );
1070 +
1071 + if (nextProp !== serverValue) {
1072 + warnForPropDifference(propKey, serverValue, nextProp);
1073 + }
1074 + } else if (DOMProperty.shouldSetAttribute(propKey, nextProp)) {
1075 + if ((propertyInfo = DOMProperty.getPropertyInfo(propKey))) {
1076 // $FlowFixMe - Should be inferred as not undefined.
1093 - extraAttributeNames.delete(propKey.toLowerCase());
1094 - serverValue = DOMPropertyOperations.getValueForAttribute(
1077 + extraAttributeNames.delete(propertyInfo.attributeName);
1078 + serverValue = DOMPropertyOperations.getValueForProperty(
1079 domElement,
1080 propKey,
1081 nextProp,
1082 );
1099 -
1100 - if (nextProp !== serverValue) {
1101 - warnForPropDifference(propKey, serverValue, nextProp);
1083 + } else {
1084 + let ownNamespace = parentNamespace;
1085 + if (ownNamespace === HTML_NAMESPACE) {
1086 + ownNamespace = getIntrinsicNamespace(tag);
1087 }
1103 - } else if (DOMProperty.shouldSetAttribute(propKey, nextProp)) {
1104 - if ((propertyInfo = DOMProperty.getPropertyInfo(propKey))) {
1088 + if (ownNamespace === HTML_NAMESPACE) {
1089 // $FlowFixMe - Should be inferred as not undefined.
1106 - extraAttributeNames.delete(propertyInfo.attributeName);
1107 - serverValue = DOMPropertyOperations.getValueForProperty(
1108 - domElement,
1109 - propKey,
1110 - nextProp,
1111 - );
1090 + extraAttributeNames.delete(propKey.toLowerCase());
1091 } else {
1113 - let ownNamespace = parentNamespace;
1114 - if (ownNamespace === HTML_NAMESPACE) {
1115 - ownNamespace = getIntrinsicNamespace(tag);
1116 - }
1117 - if (ownNamespace === HTML_NAMESPACE) {
1118 - // $FlowFixMe - Should be inferred as not undefined.
1119 - extraAttributeNames.delete(propKey.toLowerCase());
1120 - } else {
1121 - // $FlowFixMe - Should be inferred as not undefined.
1122 - extraAttributeNames.delete(propKey);
1123 - }
1124 - serverValue = DOMPropertyOperations.getValueForAttribute(
1125 - domElement,
1126 - propKey,
1127 - nextProp,
1128 - );
1092 + // $FlowFixMe - Should be inferred as not undefined.
1093 + extraAttributeNames.delete(propKey);
1094 }
1095 + serverValue = DOMPropertyOperations.getValueForAttribute(
1096 + domElement,
1097 + propKey,
1098 + nextProp,
1099 + );
1100 + }
1101
1131 - if (nextProp !== serverValue) {
1132 - warnForPropDifference(propKey, serverValue, nextProp);
1133 - }
1102 + if (nextProp !== serverValue) {
1103 + warnForPropDifference(propKey, serverValue, nextProp);
1104 }
1105 }
1106 }
1107 + }
1108
1138 - if (__DEV__) {
1109 + if (__DEV__) {
1110 + // $FlowFixMe - Should be inferred as not undefined.
1111 + if (extraAttributeNames.size > 0 && !suppressHydrationWarning) {
1112 // $FlowFixMe - Should be inferred as not undefined.
1140 - if (extraAttributeNames.size > 0 && !suppressHydrationWarning) {
1141 - // $FlowFixMe - Should be inferred as not undefined.
1142 - warnForExtraAttributes(extraAttributeNames);
1143 - }
1113 + warnForExtraAttributes(extraAttributeNames);
1114 }
1115 + }
1116
1146 - switch (tag) {
1147 - case 'input':
1148 - // TODO: Make sure we check if this is still unmounted or do any clean
1149 - // up necessary since we never stop tracking anymore.
1150 - inputValueTracking.track((domElement: any));
1151 - ReactDOMFiberInput.postMountWrapper(domElement, rawProps);
1152 - break;
1153 - case 'textarea':
1154 - // TODO: Make sure we check if this is still unmounted or do any clean
1155 - // up necessary since we never stop tracking anymore.
1156 - inputValueTracking.track((domElement: any));
1157 - ReactDOMFiberTextarea.postMountWrapper(domElement, rawProps);
1158 - break;
1159 - case 'select':
1160 - case 'option':
1161 - // For input and textarea we current always set the value property at
1162 - // post mount to force it to diverge from attributes. However, for
1163 - // option and select we don't quite do the same thing and select
1164 - // is not resilient to the DOM state changing so we don't do that here.
1165 - // TODO: Consider not doing this for input and textarea.
1166 - break;
1167 - default:
1168 - if (typeof rawProps.onClick === 'function') {
1169 - // TODO: This cast may not be sound for SVG, MathML or custom elements.
1170 - trapClickOnNonInteractiveElement(((domElement: any): HTMLElement));
1171 - }
1172 - break;
1173 - }
1117 + switch (tag) {
1118 + case 'input':
1119 + // TODO: Make sure we check if this is still unmounted or do any clean
1120 + // up necessary since we never stop tracking anymore.
1121 + inputValueTracking.track((domElement: any));
1122 + ReactDOMFiberInput.postMountWrapper(domElement, rawProps);
1123 + break;
1124 + case 'textarea':
1125 + // TODO: Make sure we check if this is still unmounted or do any clean
1126 + // up necessary since we never stop tracking anymore.
1127 + inputValueTracking.track((domElement: any));
1128 + ReactDOMFiberTextarea.postMountWrapper(domElement, rawProps);
1129 + break;
1130 + case 'select':
1131 + case 'option':
1132 + // For input and textarea we current always set the value property at
1133 + // post mount to force it to diverge from attributes. However, for
1134 + // option and select we don't quite do the same thing and select
1135 + // is not resilient to the DOM state changing so we don't do that here.
1136 + // TODO: Consider not doing this for input and textarea.
1137 + break;
1138 + default:
1139 + if (typeof rawProps.onClick === 'function') {
1140 + // TODO: This cast may not be sound for SVG, MathML or custom elements.
1141 + trapClickOnNonInteractiveElement(((domElement: any): HTMLElement));
1142 + }
1143 + break;
1144 + }
1145
1175 - return updatePayload;
1176 - },
1146 + return updatePayload;
1147 +}
1148
1178 - diffHydratedText(textNode: Text, text: string): boolean {
1179 - const isDifferent = textNode.nodeValue !== text;
1180 - return isDifferent;
1181 - },
1149 +export function diffHydratedText(textNode: Text, text: string): boolean {
1150 + const isDifferent = textNode.nodeValue !== text;
1151 + return isDifferent;
1152 +}
1153
1183 - warnForUnmatchedText(textNode: Text, text: string) {
1184 - if (__DEV__) {
1185 - warnForTextDifference(textNode.nodeValue, text);
1186 - }
1187 - },
1154 +export function warnForUnmatchedText(textNode: Text, text: string) {
1155 + if (__DEV__) {
1156 + warnForTextDifference(textNode.nodeValue, text);
1157 + }
1158 +}
1159
1189 - warnForDeletedHydratableElement(
1190 - parentNode: Element | Document,
1191 - child: Element,
1192 - ) {
1193 - if (__DEV__) {
1194 - if (didWarnInvalidHydration) {
1195 - return;
1196 - }
1197 - didWarnInvalidHydration = true;
1198 - warning(
1199 - false,
1200 - 'Did not expect server HTML to contain a <%s> in <%s>.',
1201 - child.nodeName.toLowerCase(),
1202 - parentNode.nodeName.toLowerCase(),
1203 - );
1160 +export function warnForDeletedHydratableElement(
1161 + parentNode: Element | Document,
1162 + child: Element,
1163 +) {
1164 + if (__DEV__) {
1165 + if (didWarnInvalidHydration) {
1166 + return;
1167 }
1205 - },
1168 + didWarnInvalidHydration = true;
1169 + warning(
1170 + false,
1171 + 'Did not expect server HTML to contain a <%s> in <%s>.',
1172 + child.nodeName.toLowerCase(),
1173 + parentNode.nodeName.toLowerCase(),
1174 + );
1175 + }
1176 +}
1177
1207 - warnForDeletedHydratableText(parentNode: Element | Document, child: Text) {
1208 - if (__DEV__) {
1209 - if (didWarnInvalidHydration) {
1210 - return;
1211 - }
1212 - didWarnInvalidHydration = true;
1213 - warning(
1214 - false,
1215 - 'Did not expect server HTML to contain the text node "%s" in <%s>.',
1216 - child.nodeValue,
1217 - parentNode.nodeName.toLowerCase(),
1218 - );
1178 +export function warnForDeletedHydratableText(
1179 + parentNode: Element | Document,
1180 + child: Text,
1181 +) {
1182 + if (__DEV__) {
1183 + if (didWarnInvalidHydration) {
1184 + return;
1185 }
1220 - },
1186 + didWarnInvalidHydration = true;
1187 + warning(
1188 + false,
1189 + 'Did not expect server HTML to contain the text node "%s" in <%s>.',
1190 + child.nodeValue,
1191 + parentNode.nodeName.toLowerCase(),
1192 + );
1193 + }
1194 +}
1195
1222 - warnForInsertedHydratedElement(
1223 - parentNode: Element | Document,
1224 - tag: string,
1225 - props: Object,
1226 - ) {
1227 - if (__DEV__) {
1228 - if (didWarnInvalidHydration) {
1229 - return;
1230 - }
1231 - didWarnInvalidHydration = true;
1232 - warning(
1233 - false,
1234 - 'Expected server HTML to contain a matching <%s> in <%s>.',
1235 - tag,
1236 - parentNode.nodeName.toLowerCase(),
1237 - );
1196 +export function warnForInsertedHydratedElement(
1197 + parentNode: Element | Document,
1198 + tag: string,
1199 + props: Object,
1200 +) {
1201 + if (__DEV__) {
1202 + if (didWarnInvalidHydration) {
1203 + return;
1204 }
1239 - },
1205 + didWarnInvalidHydration = true;
1206 + warning(
1207 + false,
1208 + 'Expected server HTML to contain a matching <%s> in <%s>.',
1209 + tag,
1210 + parentNode.nodeName.toLowerCase(),
1211 + );
1212 + }
1213 +}
1214
1241 - warnForInsertedHydratedText(parentNode: Element | Document, text: string) {
1242 - if (__DEV__) {
1243 - if (text === '') {
1244 - // We expect to insert empty text nodes since they're not represented in
1245 - // the HTML.
1246 - // TODO: Remove this special case if we can just avoid inserting empty
1247 - // text nodes.
1248 - return;
1249 - }
1250 - if (didWarnInvalidHydration) {
1251 - return;
1252 - }
1253 - didWarnInvalidHydration = true;
1254 - warning(
1255 - false,
1256 - 'Expected server HTML to contain a matching text node for "%s" in <%s>.',
1257 - text,
1258 - parentNode.nodeName.toLowerCase(),
1259 - );
1215 +export function warnForInsertedHydratedText(
1216 + parentNode: Element | Document,
1217 + text: string,
1218 +) {
1219 + if (__DEV__) {
1220 + if (text === '') {
1221 + // We expect to insert empty text nodes since they're not represented in
1222 + // the HTML.
1223 + // TODO: Remove this special case if we can just avoid inserting empty
1224 + // text nodes.
1225 + return;
1226 }
1261 - },
1262 -
1263 - restoreControlledState(
1264 - domElement: Element,
1265 - tag: string,
1266 - props: Object,
1267 - ): void {
1268 - switch (tag) {
1269 - case 'input':
1270 - ReactDOMFiberInput.restoreControlledState(domElement, props);
1271 - return;
1272 - case 'textarea':
1273 - ReactDOMFiberTextarea.restoreControlledState(domElement, props);
1274 - return;
1275 - case 'select':
1276 - ReactDOMFiberSelect.restoreControlledState(domElement, props);
1277 - return;
1227 + if (didWarnInvalidHydration) {
1228 + return;
1229 }
1279 - },
1280 -};
1230 + didWarnInvalidHydration = true;
1231 + warning(
1232 + false,
1233 + 'Expected server HTML to contain a matching text node for "%s" in <%s>.',
1234 + text,
1235 + parentNode.nodeName.toLowerCase(),
1236 + );
1237 + }
1238 +}
1239
1282 -module.exports = ReactDOMFiberComponent;
1240 +export function restoreControlledState(
1241 + domElement: Element,
1242 + tag: string,
1243 + props: Object,
1244 +): void {
1245 + switch (tag) {
1246 + case 'input':
1247 + ReactDOMFiberInput.restoreControlledState(domElement, props);
1248 + return;
1249 + case 'textarea':
1250 + ReactDOMFiberTextarea.restoreControlledState(domElement, props);
1251 + return;
1252 + case 'select':
1253 + ReactDOMFiberSelect.restoreControlledState(domElement, props);
1254 + return;
1255 + }
1256 +}
packages/react-dom/src/client/ReactDOMFiberInput.js
+219 -225
@@ -10,22 +10,15 @@
10 'use strict';
11
12 // TODO: direct imports like some-package/src/* are bad. Fix me.
13 -var {
14 - getCurrentFiberOwnerName,
15 -} = require('react-reconciler/src/ReactDebugCurrentFiber');
16 -var invariant = require('fbjs/lib/invariant');
13 +import ReactDebugCurrentFiber
14 + from 'react-reconciler/src/ReactDebugCurrentFiber';
15 +import invariant from 'fbjs/lib/invariant';
16 +import warning from 'fbjs/lib/warning';
17
18 -var DOMPropertyOperations = require('./DOMPropertyOperations');
19 -var ReactDOMComponentTree = require('./ReactDOMComponentTree');
20 -var ReactControlledValuePropTypes = require('../shared/ReactControlledValuePropTypes');
21 -
22 -if (__DEV__) {
23 - // TODO: direct imports like some-package/src/* are bad. Fix me.
24 - var {
25 - getCurrentFiberStackAddendum,
26 - } = require('react-reconciler/src/ReactDebugCurrentFiber');
27 - var warning = require('fbjs/lib/warning');
28 -}
18 +import * as DOMPropertyOperations from './DOMPropertyOperations';
19 +import ReactDOMComponentTree from './ReactDOMComponentTree';
20 +import ReactControlledValuePropTypes
21 + from '../shared/ReactControlledValuePropTypes';
22
23 type InputWithWrapperState = HTMLInputElement & {
24 _wrapperState: {
@@ -35,6 +28,10 @@ type InputWithWrapperState = HTMLInputElement & {
28 },
29 };
30
31 +var {
32 + getCurrentFiberOwnerName,
33 + getCurrentFiberStackAddendum,
34 +} = ReactDebugCurrentFiber;
35 var didWarnValueDefaultValue = false;
36 var didWarnCheckedDefaultChecked = false;
37 var didWarnControlledToUncontrolled = false;
@@ -61,238 +58,237 @@ function isControlled(props) {
58 *
59 * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
60 */
64 -var ReactDOMInput = {
65 - getHostProps: function(element: Element, props: Object) {
66 - var node = ((element: any): InputWithWrapperState);
67 - var value = props.value;
68 - var checked = props.checked;
61
70 - var hostProps = Object.assign(
71 - {
72 - // Make sure we set .type before any other properties (setting .value
73 - // before .type means .value is lost in IE11 and below)
74 - type: undefined,
75 - // Make sure we set .step before .value (setting .value before .step
76 - // means .value is rounded on mount, based upon step precision)
77 - step: undefined,
78 - // Make sure we set .min & .max before .value (to ensure proper order
79 - // in corner cases such as min or max deriving from value, e.g. Issue #7170)
80 - min: undefined,
81 - max: undefined,
82 - },
62 +export function getHostProps(element: Element, props: Object) {
63 + var node = ((element: any): InputWithWrapperState);
64 + var value = props.value;
65 + var checked = props.checked;
66 +
67 + var hostProps = Object.assign(
68 + {
69 + // Make sure we set .type before any other properties (setting .value
70 + // before .type means .value is lost in IE11 and below)
71 + type: undefined,
72 + // Make sure we set .step before .value (setting .value before .step
73 + // means .value is rounded on mount, based upon step precision)
74 + step: undefined,
75 + // Make sure we set .min & .max before .value (to ensure proper order
76 + // in corner cases such as min or max deriving from value, e.g. Issue #7170)
77 + min: undefined,
78 + max: undefined,
79 + },
80 + props,
81 + {
82 + defaultChecked: undefined,
83 + defaultValue: undefined,
84 + value: value != null ? value : node._wrapperState.initialValue,
85 + checked: checked != null ? checked : node._wrapperState.initialChecked,
86 + },
87 + );
88 +
89 + return hostProps;
90 +}
91 +
92 +export function initWrapperState(element: Element, props: Object) {
93 + if (__DEV__) {
94 + ReactControlledValuePropTypes.checkPropTypes(
95 + 'input',
96 props,
84 - {
85 - defaultChecked: undefined,
86 - defaultValue: undefined,
87 - value: value != null ? value : node._wrapperState.initialValue,
88 - checked: checked != null ? checked : node._wrapperState.initialChecked,
89 - },
97 + getCurrentFiberStackAddendum,
98 );
99
92 - return hostProps;
93 - },
94 -
95 - initWrapperState: function(element: Element, props: Object) {
96 - if (__DEV__) {
97 - ReactControlledValuePropTypes.checkPropTypes(
98 - 'input',
99 - props,
100 - getCurrentFiberStackAddendum,
100 + if (
101 + props.checked !== undefined &&
102 + props.defaultChecked !== undefined &&
103 + !didWarnCheckedDefaultChecked
104 + ) {
105 + warning(
106 + false,
107 + '%s contains an input of type %s with both checked and defaultChecked props. ' +
108 + 'Input elements must be either controlled or uncontrolled ' +
109 + '(specify either the checked prop, or the defaultChecked prop, but not ' +
110 + 'both). Decide between using a controlled or uncontrolled input ' +
111 + 'element and remove one of these props. More info: ' +
112 + 'https://fb.me/react-controlled-components',
113 + getCurrentFiberOwnerName() || 'A component',
114 + props.type,
115 );
102 -
103 - if (
104 - props.checked !== undefined &&
105 - props.defaultChecked !== undefined &&
106 - !didWarnCheckedDefaultChecked
107 - ) {
108 - warning(
109 - false,
110 - '%s contains an input of type %s with both checked and defaultChecked props. ' +
111 - 'Input elements must be either controlled or uncontrolled ' +
112 - '(specify either the checked prop, or the defaultChecked prop, but not ' +
113 - 'both). Decide between using a controlled or uncontrolled input ' +
114 - 'element and remove one of these props. More info: ' +
115 - 'https://fb.me/react-controlled-components',
116 - getCurrentFiberOwnerName() || 'A component',
117 - props.type,
118 - );
119 - didWarnCheckedDefaultChecked = true;
120 - }
121 - if (
122 - props.value !== undefined &&
123 - props.defaultValue !== undefined &&
124 - !didWarnValueDefaultValue
125 - ) {
126 - warning(
127 - false,
128 - '%s contains an input of type %s with both value and defaultValue props. ' +
129 - 'Input elements must be either controlled or uncontrolled ' +
130 - '(specify either the value prop, or the defaultValue prop, but not ' +
131 - 'both). Decide between using a controlled or uncontrolled input ' +
132 - 'element and remove one of these props. More info: ' +
133 - 'https://fb.me/react-controlled-components',
134 - getCurrentFiberOwnerName() || 'A component',
135 - props.type,
136 - );
137 - didWarnValueDefaultValue = true;
138 - }
116 + didWarnCheckedDefaultChecked = true;
117 + }
118 + if (
119 + props.value !== undefined &&
120 + props.defaultValue !== undefined &&
121 + !didWarnValueDefaultValue
122 + ) {
123 + warning(
124 + false,
125 + '%s contains an input of type %s with both value and defaultValue props. ' +
126 + 'Input elements must be either controlled or uncontrolled ' +
127 + '(specify either the value prop, or the defaultValue prop, but not ' +
128 + 'both). Decide between using a controlled or uncontrolled input ' +
129 + 'element and remove one of these props. More info: ' +
130 + 'https://fb.me/react-controlled-components',
131 + getCurrentFiberOwnerName() || 'A component',
132 + props.type,
133 + );
134 + didWarnValueDefaultValue = true;
135 }
136 + }
137
141 - var defaultValue = props.defaultValue;
142 - var node = ((element: any): InputWithWrapperState);
143 - node._wrapperState = {
144 - initialChecked: props.checked != null
145 - ? props.checked
146 - : props.defaultChecked,
147 - initialValue: props.value != null ? props.value : defaultValue,
148 - controlled: isControlled(props),
149 - };
150 - },
138 + var defaultValue = props.defaultValue;
139 + var node = ((element: any): InputWithWrapperState);
140 + node._wrapperState = {
141 + initialChecked: props.checked != null
142 + ? props.checked
143 + : props.defaultChecked,
144 + initialValue: props.value != null ? props.value : defaultValue,
145 + controlled: isControlled(props),
146 + };
147 +}
148
152 - updateWrapper: function(element: Element, props: Object) {
153 - var node = ((element: any): InputWithWrapperState);
154 - if (__DEV__) {
155 - var controlled = isControlled(props);
149 +export function updateWrapper(element: Element, props: Object) {
150 + var node = ((element: any): InputWithWrapperState);
151 + if (__DEV__) {
152 + var controlled = isControlled(props);
153
157 - if (
158 - !node._wrapperState.controlled &&
159 - controlled &&
160 - !didWarnUncontrolledToControlled
161 - ) {
162 - warning(
163 - false,
164 - 'A component is changing an uncontrolled input of type %s to be controlled. ' +
165 - 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
166 - 'Decide between using a controlled or uncontrolled input ' +
167 - 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components%s',
168 - props.type,
169 - getCurrentFiberStackAddendum(),
170 - );
171 - didWarnUncontrolledToControlled = true;
172 - }
173 - if (
174 - node._wrapperState.controlled &&
175 - !controlled &&
176 - !didWarnControlledToUncontrolled
177 - ) {
178 - warning(
179 - false,
180 - 'A component is changing a controlled input of type %s to be uncontrolled. ' +
181 - 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
182 - 'Decide between using a controlled or uncontrolled input ' +
183 - 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components%s',
184 - props.type,
185 - getCurrentFiberStackAddendum(),
186 - );
187 - didWarnControlledToUncontrolled = true;
188 - }
154 + if (
155 + !node._wrapperState.controlled &&
156 + controlled &&
157 + !didWarnUncontrolledToControlled
158 + ) {
159 + warning(
160 + false,
161 + 'A component is changing an uncontrolled input of type %s to be controlled. ' +
162 + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' +
163 + 'Decide between using a controlled or uncontrolled input ' +
164 + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components%s',
165 + props.type,
166 + getCurrentFiberStackAddendum(),
167 + );
168 + didWarnUncontrolledToControlled = true;
169 }
190 -
191 - var checked = props.checked;
192 - if (checked != null) {
193 - DOMPropertyOperations.setValueForProperty(
194 - node,
195 - 'checked',
196 - checked || false,
170 + if (
171 + node._wrapperState.controlled &&
172 + !controlled &&
173 + !didWarnControlledToUncontrolled
174 + ) {
175 + warning(
176 + false,
177 + 'A component is changing a controlled input of type %s to be uncontrolled. ' +
178 + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' +
179 + 'Decide between using a controlled or uncontrolled input ' +
180 + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components%s',
181 + props.type,
182 + getCurrentFiberStackAddendum(),
183 );
184 + didWarnControlledToUncontrolled = true;
185 }
186 + }
187 +
188 + var checked = props.checked;
189 + if (checked != null) {
190 + DOMPropertyOperations.setValueForProperty(
191 + node,
192 + 'checked',
193 + checked || false,
194 + );
195 + }
196
200 - var value = props.value;
201 - if (value != null) {
202 - if (value === 0 && node.value === '') {
203 - node.value = '0';
204 - // Note: IE9 reports a number inputs as 'text', so check props instead.
205 - } else if (props.type === 'number') {
206 - // Simulate `input.valueAsNumber`. IE9 does not support it
207 - var valueAsNumber = parseFloat(node.value) || 0;
197 + var value = props.value;
198 + if (value != null) {
199 + if (value === 0 && node.value === '') {
200 + node.value = '0';
201 + // Note: IE9 reports a number inputs as 'text', so check props instead.
202 + } else if (props.type === 'number') {
203 + // Simulate `input.valueAsNumber`. IE9 does not support it
204 + var valueAsNumber = parseFloat(node.value) || 0;
205
209 - if (
210 - // eslint-disable-next-line
211 - value != valueAsNumber ||
212 - // eslint-disable-next-line
213 - (value == valueAsNumber && node.value != value)
214 - ) {
215 - // Cast `value` to a string to ensure the value is set correctly. While
216 - // browsers typically do this as necessary, jsdom doesn't.
217 - node.value = '' + value;
218 - }
219 - } else if (node.value !== '' + value) {
206 + if (
207 + // eslint-disable-next-line
208 + value != valueAsNumber ||
209 + // eslint-disable-next-line
210 + (value == valueAsNumber && node.value != value)
211 + ) {
212 // Cast `value` to a string to ensure the value is set correctly. While
213 // browsers typically do this as necessary, jsdom doesn't.
214 node.value = '' + value;
215 }
224 - } else {
225 - if (props.value == null && props.defaultValue != null) {
226 - // In Chrome, assigning defaultValue to certain input types triggers input validation.
227 - // For number inputs, the display value loses trailing decimal points. For email inputs,
228 - // Chrome raises "The specified value <x> is not a valid email address".
229 - //
230 - // Here we check to see if the defaultValue has actually changed, avoiding these problems
231 - // when the user is inputting text
232 - //
233 - // https://github.com/facebook/react/issues/7253
234 - if (node.defaultValue !== '' + props.defaultValue) {
235 - node.defaultValue = '' + props.defaultValue;
236 - }
237 - }
238 - if (props.checked == null && props.defaultChecked != null) {
239 - node.defaultChecked = !!props.defaultChecked;
216 + } else if (node.value !== '' + value) {
217 + // Cast `value` to a string to ensure the value is set correctly. While
218 + // browsers typically do this as necessary, jsdom doesn't.
219 + node.value = '' + value;
220 + }
221 + } else {
222 + if (props.value == null && props.defaultValue != null) {
223 + // In Chrome, assigning defaultValue to certain input types triggers input validation.
224 + // For number inputs, the display value loses trailing decimal points. For email inputs,
225 + // Chrome raises "The specified value <x> is not a valid email address".
226 + //
227 + // Here we check to see if the defaultValue has actually changed, avoiding these problems
228 + // when the user is inputting text
229 + //
230 + // https://github.com/facebook/react/issues/7253
231 + if (node.defaultValue !== '' + props.defaultValue) {
232 + node.defaultValue = '' + props.defaultValue;
233 }
234 }
242 - },
235 + if (props.checked == null && props.defaultChecked != null) {
236 + node.defaultChecked = !!props.defaultChecked;
237 + }
238 + }
239 +}
240
244 - postMountWrapper: function(element: Element, props: Object) {
245 - var node = ((element: any): InputWithWrapperState);
241 +export function postMountWrapper(element: Element, props: Object) {
242 + var node = ((element: any): InputWithWrapperState);
243
247 - // Detach value from defaultValue. We won't do anything if we're working on
248 - // submit or reset inputs as those values & defaultValues are linked. They
249 - // are not resetable nodes so this operation doesn't matter and actually
250 - // removes browser-default values (eg "Submit Query") when no value is
251 - // provided.
244 + // Detach value from defaultValue. We won't do anything if we're working on
245 + // submit or reset inputs as those values & defaultValues are linked. They
246 + // are not resetable nodes so this operation doesn't matter and actually
247 + // removes browser-default values (eg "Submit Query") when no value is
248 + // provided.
249
253 - switch (props.type) {
254 - case 'submit':
255 - case 'reset':
256 - break;
257 - case 'color':
258 - case 'date':
259 - case 'datetime':
260 - case 'datetime-local':
261 - case 'month':
262 - case 'time':
263 - case 'week':
264 - // This fixes the no-show issue on iOS Safari and Android Chrome:
265 - // https://github.com/facebook/react/issues/7233
266 - node.value = '';
267 - node.value = node.defaultValue;
268 - break;
269 - default:
270 - node.value = node.value;
271 - break;
272 - }
250 + switch (props.type) {
251 + case 'submit':
252 + case 'reset':
253 + break;
254 + case 'color':
255 + case 'date':
256 + case 'datetime':
257 + case 'datetime-local':
258 + case 'month':
259 + case 'time':
260 + case 'week':
261 + // This fixes the no-show issue on iOS Safari and Android Chrome:
262 + // https://github.com/facebook/react/issues/7233
263 + node.value = '';
264 + node.value = node.defaultValue;
265 + break;
266 + default:
267 + node.value = node.value;
268 + break;
269 + }
270
274 - // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
275 - // this is needed to work around a chrome bug where setting defaultChecked
276 - // will sometimes influence the value of checked (even after detachment).
277 - // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
278 - // We need to temporarily unset name to avoid disrupting radio button groups.
279 - var name = node.name;
280 - if (name !== '') {
281 - node.name = '';
282 - }
283 - node.defaultChecked = !node.defaultChecked;
284 - node.defaultChecked = !node.defaultChecked;
285 - if (name !== '') {
286 - node.name = name;
287 - }
288 - },
271 + // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
272 + // this is needed to work around a chrome bug where setting defaultChecked
273 + // will sometimes influence the value of checked (even after detachment).
274 + // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
275 + // We need to temporarily unset name to avoid disrupting radio button groups.
276 + var name = node.name;
277 + if (name !== '') {
278 + node.name = '';
279 + }
280 + node.defaultChecked = !node.defaultChecked;
281 + node.defaultChecked = !node.defaultChecked;
282 + if (name !== '') {
283 + node.name = name;
284 + }
285 +}
286
290 - restoreControlledState: function(element: Element, props: Object) {
291 - var node = ((element: any): InputWithWrapperState);
292 - ReactDOMInput.updateWrapper(node, props);
293 - updateNamedCousins(node, props);
294 - },
295 -};
287 +export function restoreControlledState(element: Element, props: Object) {
288 + var node = ((element: any): InputWithWrapperState);
289 + updateWrapper(node, props);
290 + updateNamedCousins(node, props);
291 +}
292
293 function updateNamedCousins(rootNode, props) {
294 var name = props.name;
@@ -334,9 +330,7 @@ function updateNamedCousins(rootNode, props) {
330 // If this is a controlled radio button group, forcing the input that
331 // was previously checked to update will cause it to be come re-checked
332 // as appropriate.
337 - ReactDOMInput.updateWrapper(otherNode, otherProps);
333 + updateWrapper(otherNode, otherProps);
334 }
335 }
336 }
341 -
342 -module.exports = ReactDOMInput;
packages/react-dom/src/client/ReactDOMFiberOption.js
+26 -32
@@ -9,11 +9,8 @@
9
10 'use strict';
11
12 -var React = require('react');
13 -
14 -if (__DEV__) {
15 - var warning = require('fbjs/lib/warning');
16 -}
12 +import React from 'react';
13 +import warning from 'fbjs/lib/warning';
14
15 function flattenChildren(children) {
16 var content = '';
@@ -37,36 +34,33 @@ function flattenChildren(children) {
34 /**
35 * Implements an <option> host component that warns when `selected` is set.
36 */
40 -var ReactDOMOption = {
41 - validateProps: function(element: Element, props: Object) {
42 - // TODO (yungsters): Remove support for `selected` in <option>.
43 - if (__DEV__) {
44 - warning(
45 - props.selected == null,
46 - 'Use the `defaultValue` or `value` props on <select> instead of ' +
47 - 'setting `selected` on <option>.',
48 - );
49 - }
50 - },
37
52 - postMountWrapper: function(element: Element, props: Object) {
53 - // value="" should make a value attribute (#6219)
54 - if (props.value != null) {
55 - element.setAttribute('value', props.value);
56 - }
57 - },
38 +export function validateProps(element: Element, props: Object) {
39 + // TODO (yungsters): Remove support for `selected` in <option>.
40 + if (__DEV__) {
41 + warning(
42 + props.selected == null,
43 + 'Use the `defaultValue` or `value` props on <select> instead of ' +
44 + 'setting `selected` on <option>.',
45 + );
46 + }
47 +}
48
59 - getHostProps: function(element: Element, props: Object) {
60 - var hostProps = Object.assign({children: undefined}, props);
49 +export function postMountWrapper(element: Element, props: Object) {
50 + // value="" should make a value attribute (#6219)
51 + if (props.value != null) {
52 + element.setAttribute('value', props.value);
53 + }
54 +}
55
62 - var content = flattenChildren(props.children);
56 +export function getHostProps(element: Element, props: Object) {
57 + var hostProps = Object.assign({children: undefined}, props);
58
64 - if (content) {
65 - hostProps.children = content;
66 - }
59 + var content = flattenChildren(props.children);
60
68 - return hostProps;
69 - },
70 -};
61 + if (content) {
62 + hostProps.children = content;
63 + }
64
72 -module.exports = ReactDOMOption;
65 + return hostProps;
66 +}
packages/react-dom/src/client/ReactDOMFiberSelect.js
+81 -83
@@ -9,19 +9,20 @@
9
10 'use strict';
11
12 +// TODO: direct imports like some-package/src/* are bad. Fix me.
13 +import ReactDebugCurrentFiber
14 + from 'react-reconciler/src/ReactDebugCurrentFiber';
15 +import warning from 'fbjs/lib/warning';
16 +
17 +import ReactControlledValuePropTypes
18 + from '../shared/ReactControlledValuePropTypes';
19 +
20 var {
21 getCurrentFiberOwnerName,
14 -} = require('react-reconciler/src/ReactDebugCurrentFiber');
15 -
16 -var ReactControlledValuePropTypes = require('../shared/ReactControlledValuePropTypes');
22 + getCurrentFiberStackAddendum,
23 +} = ReactDebugCurrentFiber;
24
25 if (__DEV__) {
19 - // TODO: direct imports like some-package/src/* are bad. Fix me.
20 - var {
21 - getCurrentFiberStackAddendum,
22 - } = require('react-reconciler/src/ReactDebugCurrentFiber');
23 - var warning = require('fbjs/lib/warning');
24 -
26 var didWarnValueDefaultValue = false;
27 }
28
@@ -143,86 +144,83 @@ function updateOptions(
144 * If `defaultValue` is provided, any options with the supplied values will be
145 * selected.
146 */
146 -var ReactDOMSelect = {
147 - getHostProps: function(element: Element, props: Object) {
148 - return Object.assign({}, props, {
149 - value: undefined,
150 - });
151 - },
147
153 - initWrapperState: function(element: Element, props: Object) {
154 - var node = ((element: any): SelectWithWrapperState);
155 - if (__DEV__) {
156 - checkSelectPropTypes(props);
157 - }
148 +export function getHostProps(element: Element, props: Object) {
149 + return Object.assign({}, props, {
150 + value: undefined,
151 + });
152 +}
153
159 - var value = props.value;
160 - node._wrapperState = {
161 - initialValue: value != null ? value : props.defaultValue,
162 - wasMultiple: !!props.multiple,
163 - };
164 -
165 - if (__DEV__) {
166 - if (
167 - props.value !== undefined &&
168 - props.defaultValue !== undefined &&
169 - !didWarnValueDefaultValue
170 - ) {
171 - warning(
172 - false,
173 - 'Select elements must be either controlled or uncontrolled ' +
174 - '(specify either the value prop, or the defaultValue prop, but not ' +
175 - 'both). Decide between using a controlled or uncontrolled select ' +
176 - 'element and remove one of these props. More info: ' +
177 - 'https://fb.me/react-controlled-components',
178 - );
179 - didWarnValueDefaultValue = true;
180 - }
181 - }
182 - },
154 +export function initWrapperState(element: Element, props: Object) {
155 + var node = ((element: any): SelectWithWrapperState);
156 + if (__DEV__) {
157 + checkSelectPropTypes(props);
158 + }
159
184 - postMountWrapper: function(element: Element, props: Object) {
185 - var node = ((element: any): SelectWithWrapperState);
186 - node.multiple = !!props.multiple;
187 - var value = props.value;
188 - if (value != null) {
189 - updateOptions(node, !!props.multiple, value, false);
190 - } else if (props.defaultValue != null) {
191 - updateOptions(node, !!props.multiple, props.defaultValue, true);
192 - }
193 - },
160 + var value = props.value;
161 + node._wrapperState = {
162 + initialValue: value != null ? value : props.defaultValue,
163 + wasMultiple: !!props.multiple,
164 + };
165
195 - postUpdateWrapper: function(element: Element, props: Object) {
196 - var node = ((element: any): SelectWithWrapperState);
197 - // After the initial mount, we control selected-ness manually so don't pass
198 - // this value down
199 - node._wrapperState.initialValue = undefined;
200 -
201 - var wasMultiple = node._wrapperState.wasMultiple;
202 - node._wrapperState.wasMultiple = !!props.multiple;
203 -
204 - var value = props.value;
205 - if (value != null) {
206 - updateOptions(node, !!props.multiple, value, false);
207 - } else if (wasMultiple !== !!props.multiple) {
208 - // For simplicity, reapply `defaultValue` if `multiple` is toggled.
209 - if (props.defaultValue != null) {
210 - updateOptions(node, !!props.multiple, props.defaultValue, true);
211 - } else {
212 - // Revert the select back to its default unselected state.
213 - updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);
214 - }
166 + if (__DEV__) {
167 + if (
168 + props.value !== undefined &&
169 + props.defaultValue !== undefined &&
170 + !didWarnValueDefaultValue
171 + ) {
172 + warning(
173 + false,
174 + 'Select elements must be either controlled or uncontrolled ' +
175 + '(specify either the value prop, or the defaultValue prop, but not ' +
176 + 'both). Decide between using a controlled or uncontrolled select ' +
177 + 'element and remove one of these props. More info: ' +
178 + 'https://fb.me/react-controlled-components',
179 + );
180 + didWarnValueDefaultValue = true;
181 }
216 - },
182 + }
183 +}
184
218 - restoreControlledState: function(element: Element, props: Object) {
219 - var node = ((element: any): SelectWithWrapperState);
220 - var value = props.value;
185 +export function postMountWrapper(element: Element, props: Object) {
186 + var node = ((element: any): SelectWithWrapperState);
187 + node.multiple = !!props.multiple;
188 + var value = props.value;
189 + if (value != null) {
190 + updateOptions(node, !!props.multiple, value, false);
191 + } else if (props.defaultValue != null) {
192 + updateOptions(node, !!props.multiple, props.defaultValue, true);
193 + }
194 +}
195
222 - if (value != null) {
223 - updateOptions(node, !!props.multiple, value, false);
196 +export function postUpdateWrapper(element: Element, props: Object) {
197 + var node = ((element: any): SelectWithWrapperState);
198 + // After the initial mount, we control selected-ness manually so don't pass
199 + // this value down
200 + node._wrapperState.initialValue = undefined;
201 +
202 + var wasMultiple = node._wrapperState.wasMultiple;
203 + node._wrapperState.wasMultiple = !!props.multiple;
204 +
205 + var value = props.value;
206 + if (value != null) {
207 + updateOptions(node, !!props.multiple, value, false);
208 + } else if (wasMultiple !== !!props.multiple) {
209 + // For simplicity, reapply `defaultValue` if `multiple` is toggled.
210 + if (props.defaultValue != null) {
211 + updateOptions(node, !!props.multiple, props.defaultValue, true);
212 + } else {
213 + // Revert the select back to its default unselected state.
214 + updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);
215 }
225 - },
226 -};
216 + }
217 +}
218 +
219 +export function restoreControlledState(element: Element, props: Object) {
220 + var node = ((element: any): SelectWithWrapperState);
221 + var value = props.value;
222
228 -module.exports = ReactDOMSelect;
223 + if (value != null) {
224 + updateOptions(node, !!props.multiple, value, false);
225 + }
226 +}
packages/react-dom/src/client/ReactDOMFiberTextarea.js
+121 -126
@@ -9,17 +9,17 @@
9
10 'use strict';
11
12 -var invariant = require('fbjs/lib/invariant');
12 +import invariant from 'fbjs/lib/invariant';
13 +import warning from 'fbjs/lib/warning';
14 +// TODO: direct imports like some-package/src/* are bad. Fix me.
15 +import ReactDebugCurrentFiber
16 + from 'react-reconciler/src/ReactDebugCurrentFiber';
17
14 -var ReactControlledValuePropTypes = require('../shared/ReactControlledValuePropTypes');
18 +import ReactControlledValuePropTypes
19 + from '../shared/ReactControlledValuePropTypes';
20
16 -if (__DEV__) {
17 - // TODO: direct imports like some-package/src/* are bad. Fix me.
18 - var {
19 - getCurrentFiberStackAddendum,
20 - } = require('react-reconciler/src/ReactDebugCurrentFiber');
21 - var warning = require('fbjs/lib/warning');
22 -}
21 +var {getCurrentFiberStackAddendum} = ReactDebugCurrentFiber;
22 +var didWarnValDefaultVal = false;
23
24 type TextAreaWithWrapperState = HTMLTextAreaElement & {
25 _wrapperState: {
@@ -27,8 +27,6 @@ type TextAreaWithWrapperState = HTMLTextAreaElement & {
27 },
28 };
29
30 -var didWarnValDefaultVal = false;
31 -
30 /**
31 * Implements a <textarea> host component that allows setting `value`, and
32 * `defaultValue`. This differs from the traditional DOM API because value is
@@ -44,135 +42,132 @@ var didWarnValDefaultVal = false;
42 * The rendered element will be initialized with an empty value, the prop
43 * `defaultValue` if specified, or the children content (deprecated).
44 */
47 -var ReactDOMTextarea = {
48 - getHostProps: function(element: Element, props: Object) {
49 - var node = ((element: any): TextAreaWithWrapperState);
50 - invariant(
51 - props.dangerouslySetInnerHTML == null,
52 - '`dangerouslySetInnerHTML` does not make sense on <textarea>.',
53 - );
45
55 - // Always set children to the same thing. In IE9, the selection range will
56 - // get reset if `textContent` is mutated. We could add a check in setTextContent
57 - // to only set the value if/when the value differs from the node value (which would
58 - // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
59 - // solution. The value can be a boolean or object so that's why it's forced
60 - // to be a string.
61 - var hostProps = Object.assign({}, props, {
62 - value: undefined,
63 - defaultValue: undefined,
64 - children: '' + node._wrapperState.initialValue,
65 - });
66 -
67 - return hostProps;
68 - },
46 +export function getHostProps(element: Element, props: Object) {
47 + var node = ((element: any): TextAreaWithWrapperState);
48 + invariant(
49 + props.dangerouslySetInnerHTML == null,
50 + '`dangerouslySetInnerHTML` does not make sense on <textarea>.',
51 + );
52 +
53 + // Always set children to the same thing. In IE9, the selection range will
54 + // get reset if `textContent` is mutated. We could add a check in setTextContent
55 + // to only set the value if/when the value differs from the node value (which would
56 + // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
57 + // solution. The value can be a boolean or object so that's why it's forced
58 + // to be a string.
59 + var hostProps = Object.assign({}, props, {
60 + value: undefined,
61 + defaultValue: undefined,
62 + children: '' + node._wrapperState.initialValue,
63 + });
64 +
65 + return hostProps;
66 +}
67
70 - initWrapperState: function(element: Element, props: Object) {
71 - var node = ((element: any): TextAreaWithWrapperState);
72 - if (__DEV__) {
73 - ReactControlledValuePropTypes.checkPropTypes(
74 - 'textarea',
75 - props,
76 - getCurrentFiberStackAddendum,
68 +export function initWrapperState(element: Element, props: Object) {
69 + var node = ((element: any): TextAreaWithWrapperState);
70 + if (__DEV__) {
71 + ReactControlledValuePropTypes.checkPropTypes(
72 + 'textarea',
73 + props,
74 + getCurrentFiberStackAddendum,
75 + );
76 + if (
77 + props.value !== undefined &&
78 + props.defaultValue !== undefined &&
79 + !didWarnValDefaultVal
80 + ) {
81 + warning(
82 + false,
83 + 'Textarea elements must be either controlled or uncontrolled ' +
84 + '(specify either the value prop, or the defaultValue prop, but not ' +
85 + 'both). Decide between using a controlled or uncontrolled textarea ' +
86 + 'and remove one of these props. More info: ' +
87 + 'https://fb.me/react-controlled-components',
88 );
78 - if (
79 - props.value !== undefined &&
80 - props.defaultValue !== undefined &&
81 - !didWarnValDefaultVal
82 - ) {
89 + didWarnValDefaultVal = true;
90 + }
91 + }
92 +
93 + var value = props.value;
94 + var initialValue = value;
95 +
96 + // Only bother fetching default value if we're going to use it
97 + if (value == null) {
98 + var defaultValue = props.defaultValue;
99 + // TODO (yungsters): Remove support for children content in <textarea>.
100 + var children = props.children;
101 + if (children != null) {
102 + if (__DEV__) {
103 warning(
104 false,
85 - 'Textarea elements must be either controlled or uncontrolled ' +
86 - '(specify either the value prop, or the defaultValue prop, but not ' +
87 - 'both). Decide between using a controlled or uncontrolled textarea ' +
88 - 'and remove one of these props. More info: ' +
89 - 'https://fb.me/react-controlled-components',
105 + 'Use the `defaultValue` or `value` props instead of setting ' +
106 + 'children on <textarea>.',
107 );
91 - didWarnValDefaultVal = true;
108 }
93 - }
94 -
95 - var value = props.value;
96 - var initialValue = value;
97 -
98 - // Only bother fetching default value if we're going to use it
99 - if (value == null) {
100 - var defaultValue = props.defaultValue;
101 - // TODO (yungsters): Remove support for children content in <textarea>.
102 - var children = props.children;
103 - if (children != null) {
104 - if (__DEV__) {
105 - warning(
106 - false,
107 - 'Use the `defaultValue` or `value` props instead of setting ' +
108 - 'children on <textarea>.',
109 - );
110 - }
109 + invariant(
110 + defaultValue == null,
111 + 'If you supply `defaultValue` on a <textarea>, do not pass children.',
112 + );
113 + if (Array.isArray(children)) {
114 invariant(
112 - defaultValue == null,
113 - 'If you supply `defaultValue` on a <textarea>, do not pass children.',
115 + children.length <= 1,
116 + '<textarea> can only have at most one child.',
117 );
115 - if (Array.isArray(children)) {
116 - invariant(
117 - children.length <= 1,
118 - '<textarea> can only have at most one child.',
119 - );
120 - children = children[0];
121 - }
122 -
123 - defaultValue = '' + children;
124 - }
125 - if (defaultValue == null) {
126 - defaultValue = '';
118 + children = children[0];
119 }
128 - initialValue = defaultValue;
129 - }
120
131 - node._wrapperState = {
132 - initialValue: '' + initialValue,
133 - };
134 - },
135 -
136 - updateWrapper: function(element: Element, props: Object) {
137 - var node = ((element: any): TextAreaWithWrapperState);
138 - var value = props.value;
139 - if (value != null) {
140 - // Cast `value` to a string to ensure the value is set correctly. While
141 - // browsers typically do this as necessary, jsdom doesn't.
142 - var newValue = '' + value;
143 -
144 - // To avoid side effects (such as losing text selection), only set value if changed
145 - if (newValue !== node.value) {
146 - node.value = newValue;
147 - }
148 - if (props.defaultValue == null) {
149 - node.defaultValue = newValue;
150 - }
121 + defaultValue = '' + children;
122 }
152 - if (props.defaultValue != null) {
153 - node.defaultValue = props.defaultValue;
123 + if (defaultValue == null) {
124 + defaultValue = '';
125 }
155 - },
126 + initialValue = defaultValue;
127 + }
128 +
129 + node._wrapperState = {
130 + initialValue: '' + initialValue,
131 + };
132 +}
133
157 - postMountWrapper: function(element: Element, props: Object) {
158 - var node = ((element: any): TextAreaWithWrapperState);
159 - // This is in postMount because we need access to the DOM node, which is not
160 - // available until after the component has mounted.
161 - var textContent = node.textContent;
162 -
163 - // Only set node.value if textContent is equal to the expected
164 - // initial value. In IE10/IE11 there is a bug where the placeholder attribute
165 - // will populate textContent as well.
166 - // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/
167 - if (textContent === node._wrapperState.initialValue) {
168 - node.value = textContent;
134 +export function updateWrapper(element: Element, props: Object) {
135 + var node = ((element: any): TextAreaWithWrapperState);
136 + var value = props.value;
137 + if (value != null) {
138 + // Cast `value` to a string to ensure the value is set correctly. While
139 + // browsers typically do this as necessary, jsdom doesn't.
140 + var newValue = '' + value;
141 +
142 + // To avoid side effects (such as losing text selection), only set value if changed
143 + if (newValue !== node.value) {
144 + node.value = newValue;
145 }
170 - },
146 + if (props.defaultValue == null) {
147 + node.defaultValue = newValue;
148 + }
149 + }
150 + if (props.defaultValue != null) {
151 + node.defaultValue = props.defaultValue;
152 + }
153 +}
154
172 - restoreControlledState: function(element: Element, props: Object) {
173 - // DOM component is still mounted; update
174 - ReactDOMTextarea.updateWrapper(element, props);
175 - },
176 -};
155 +export function postMountWrapper(element: Element, props: Object) {
156 + var node = ((element: any): TextAreaWithWrapperState);
157 + // This is in postMount because we need access to the DOM node, which is not
158 + // available until after the component has mounted.
159 + var textContent = node.textContent;
160 +
161 + // Only set node.value if textContent is equal to the expected
162 + // initial value. In IE10/IE11 there is a bug where the placeholder attribute
163 + // will populate textContent as well.
164 + // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/
165 + if (textContent === node._wrapperState.initialValue) {
166 + node.value = textContent;
167 + }
168 +}
169
178 -module.exports = ReactDOMTextarea;
170 +export function restoreControlledState(element: Element, props: Object) {
171 + // DOM component is still mounted; update
172 + updateWrapper(element, props);
173 +}
packages/react-dom/src/client/ReactDOMSelection.js
+8 -24
@@ -7,15 +7,15 @@
7
8 'use strict';
9
10 -var getNodeForCharacterOffset = require('./getNodeForCharacterOffset');
11 -var getTextContentAccessor = require('./getTextContentAccessor');
12 -var {TEXT_NODE} = require('../shared/HTMLNodeType');
10 +import getNodeForCharacterOffset from './getNodeForCharacterOffset';
11 +import getTextContentAccessor from './getTextContentAccessor';
12 +import {TEXT_NODE} from '../shared/HTMLNodeType';
13
14 /**
15 * @param {DOMElement} outerNode
16 * @return {?object}
17 */
18 -function getModernOffsets(outerNode) {
18 +export function getOffsets(outerNode) {
19 var selection = window.getSelection && window.getSelection();
20
21 if (!selection || selection.rangeCount === 0) {
@@ -58,8 +58,10 @@ function getModernOffsets(outerNode) {
58 * `end` is the index of (focusNode, focusOffset).
59 *
60 * Returns null if you pass in garbage input but we should probably just crash.
61 + *
62 + * Exported only for testing.
63 */
62 -function getModernOffsetsFromPoints(
64 +export function getModernOffsetsFromPoints(
65 outerNode,
66 anchorNode,
67 anchorOffset,
@@ -152,7 +154,7 @@ function getModernOffsetsFromPoints(
154 * @param {DOMElement|DOMTextNode} node
155 * @param {object} offsets
156 */
155 -function setModernOffsets(node, offsets) {
157 +export function setOffsets(node, offsets) {
158 if (!window.getSelection) {
159 return;
160 }
@@ -196,21 +198,3 @@ function setModernOffsets(node, offsets) {
198 }
199 }
200 }
199 -
200 -var ReactDOMSelection = {
201 - /**
202 - * @param {DOMElement} node
203 - */
204 - getOffsets: getModernOffsets,
205 -
206 - // For tests.
207 - getModernOffsetsFromPoints: getModernOffsetsFromPoints,
208 -
209 - /**
210 - * @param {DOMElement|DOMTextNode} node
211 - * @param {object} offsets
212 - */
213 - setOffsets: setModernOffsets,
214 -};
215 -
216 -module.exports = ReactDOMSelection;
packages/react-dom/src/client/ReactInputSelection.js
+97 -100
@@ -7,12 +7,12 @@
7
8 'use strict';
9
10 -var containsNode = require('fbjs/lib/containsNode');
11 -var focusNode = require('fbjs/lib/focusNode');
12 -var getActiveElement = require('fbjs/lib/getActiveElement');
10 +import containsNode from 'fbjs/lib/containsNode';
11 +import focusNode from 'fbjs/lib/focusNode';
12 +import getActiveElement from 'fbjs/lib/getActiveElement';
13
14 -var ReactDOMSelection = require('./ReactDOMSelection');
15 -var {ELEMENT_NODE} = require('../shared/HTMLNodeType');
14 +import * as ReactDOMSelection from './ReactDOMSelection';
15 +import {ELEMENT_NODE} from '../shared/HTMLNodeType';
16
17 function isInDocument(node) {
18 return containsNode(document.documentElement, node);
@@ -24,107 +24,104 @@ function isInDocument(node) {
24 * assume buttons have range selections allowed).
25 * Input selection module for React.
26 */
27 -var ReactInputSelection = {
28 - hasSelectionCapabilities: function(elem) {
29 - var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
30 - return (
31 - nodeName &&
32 - ((nodeName === 'input' && elem.type === 'text') ||
33 - nodeName === 'textarea' ||
34 - elem.contentEditable === 'true')
35 - );
36 - },
37 -
38 - getSelectionInformation: function() {
39 - var focusedElem = getActiveElement();
40 - return {
41 - focusedElem: focusedElem,
42 - selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem)
43 - ? ReactInputSelection.getSelection(focusedElem)
44 - : null,
45 - };
46 - },
47 -
48 - /**
49 - * @restoreSelection: If any selection information was potentially lost,
50 - * restore it. This is useful when performing operations that could remove dom
51 - * nodes and place them back in, resulting in focus being lost.
52 - */
53 - restoreSelection: function(priorSelectionInformation) {
54 - var curFocusedElem = getActiveElement();
55 - var priorFocusedElem = priorSelectionInformation.focusedElem;
56 - var priorSelectionRange = priorSelectionInformation.selectionRange;
57 - if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
58 - if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) {
59 - ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange);
60 - }
27
62 - // Focusing a node can change the scroll position, which is undesirable
63 - const ancestors = [];
64 - let ancestor = priorFocusedElem;
65 - while ((ancestor = ancestor.parentNode)) {
66 - if (ancestor.nodeType === ELEMENT_NODE) {
67 - ancestors.push({
68 - element: ancestor,
69 - left: ancestor.scrollLeft,
70 - top: ancestor.scrollTop,
71 - });
72 - }
73 - }
28 +export function hasSelectionCapabilities(elem) {
29 + var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
30 + return (
31 + nodeName &&
32 + ((nodeName === 'input' && elem.type === 'text') ||
33 + nodeName === 'textarea' ||
34 + elem.contentEditable === 'true')
35 + );
36 +}
37
75 - focusNode(priorFocusedElem);
38 +export function getSelectionInformation() {
39 + var focusedElem = getActiveElement();
40 + return {
41 + focusedElem: focusedElem,
42 + selectionRange: hasSelectionCapabilities(focusedElem)
43 + ? getSelection(focusedElem)
44 + : null,
45 + };
46 +}
47
77 - for (let i = 0; i < ancestors.length; i++) {
78 - const info = ancestors[i];
79 - info.element.scrollLeft = info.left;
80 - info.element.scrollTop = info.top;
81 - }
82 - }
83 - },
84 -
85 - /**
86 - * @getSelection: Gets the selection bounds of a focused textarea, input or
87 - * contentEditable node.
88 - * -@input: Look up selection bounds of this input
89 - * -@return {start: selectionStart, end: selectionEnd}
90 - */
91 - getSelection: function(input) {
92 - var selection;
93 -
94 - if ('selectionStart' in input) {
95 - // Modern browser with input or textarea.
96 - selection = {
97 - start: input.selectionStart,
98 - end: input.selectionEnd,
99 - };
100 - } else {
101 - // Content editable or old IE textarea.
102 - selection = ReactDOMSelection.getOffsets(input);
48 +/**
49 + * @restoreSelection: If any selection information was potentially lost,
50 + * restore it. This is useful when performing operations that could remove dom
51 + * nodes and place them back in, resulting in focus being lost.
52 + */
53 +export function restoreSelection(priorSelectionInformation) {
54 + var curFocusedElem = getActiveElement();
55 + var priorFocusedElem = priorSelectionInformation.focusedElem;
56 + var priorSelectionRange = priorSelectionInformation.selectionRange;
57 + if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
58 + if (hasSelectionCapabilities(priorFocusedElem)) {
59 + setSelection(priorFocusedElem, priorSelectionRange);
60 }
61
105 - return selection || {start: 0, end: 0};
106 - },
107 -
108 - /**
109 - * @setSelection: Sets the selection bounds of a textarea or input and focuses
110 - * the input.
111 - * -@input Set selection bounds of this input or textarea
112 - * -@offsets Object of same form that is returned from get*
113 - */
114 - setSelection: function(input, offsets) {
115 - var start = offsets.start;
116 - var end = offsets.end;
117 - if (end === undefined) {
118 - end = start;
62 + // Focusing a node can change the scroll position, which is undesirable
63 + const ancestors = [];
64 + let ancestor = priorFocusedElem;
65 + while ((ancestor = ancestor.parentNode)) {
66 + if (ancestor.nodeType === ELEMENT_NODE) {
67 + ancestors.push({
68 + element: ancestor,
69 + left: ancestor.scrollLeft,
70 + top: ancestor.scrollTop,
71 + });
72 + }
73 }
74
121 - if ('selectionStart' in input) {
122 - input.selectionStart = start;
123 - input.selectionEnd = Math.min(end, input.value.length);
124 - } else {
125 - ReactDOMSelection.setOffsets(input, offsets);
75 + focusNode(priorFocusedElem);
76 +
77 + for (let i = 0; i < ancestors.length; i++) {
78 + const info = ancestors[i];
79 + info.element.scrollLeft = info.left;
80 + info.element.scrollTop = info.top;
81 }
127 - },
128 -};
82 + }
83 +}
84 +
85 +/**
86 + * @getSelection: Gets the selection bounds of a focused textarea, input or
87 + * contentEditable node.
88 + * -@input: Look up selection bounds of this input
89 + * -@return {start: selectionStart, end: selectionEnd}
90 + */
91 +export function getSelection(input) {
92 + var selection;
93 +
94 + if ('selectionStart' in input) {
95 + // Modern browser with input or textarea.
96 + selection = {
97 + start: input.selectionStart,
98 + end: input.selectionEnd,
99 + };
100 + } else {
101 + // Content editable or old IE textarea.
102 + selection = ReactDOMSelection.getOffsets(input);
103 + }
104
130 -module.exports = ReactInputSelection;
105 + return selection || {start: 0, end: 0};
106 +}
107 +
108 +/**
109 + * @setSelection: Sets the selection bounds of a textarea or input and focuses
110 + * the input.
111 + * -@input Set selection bounds of this input or textarea
112 + * -@offsets Object of same form that is returned from get*
113 + */
114 +export function setSelection(input, offsets) {
115 + var start = offsets.start;
116 + var end = offsets.end;
117 + if (end === undefined) {
118 + end = start;
119 + }
120 +
121 + if ('selectionStart' in input) {
122 + input.selectionStart = start;
123 + input.selectionEnd = Math.min(end, input.value.length);
124 + } else {
125 + ReactDOMSelection.setOffsets(input, offsets);
126 + }
127 +}
packages/react-dom/src/client/__tests__/getNodeForCharacterOffset-test.js
+1 -1
@@ -10,7 +10,7 @@
10 'use strict';
11
12 // TODO: can we express this test with only public API?
13 -var getNodeForCharacterOffset = require('../getNodeForCharacterOffset');
13 +var getNodeForCharacterOffset = require('../getNodeForCharacterOffset').default;
14
15 // Create node from HTML string
16 function createNode(html) {
packages/react-dom/src/client/__tests__/setInnerHTML-test.js
+1 -1
@@ -10,7 +10,7 @@
10 'use strict';
11
12 // TODO: can we express this test with only public API?
13 -var setInnerHTML = require('../setInnerHTML');
13 +var setInnerHTML = require('../setInnerHTML').default;
14 var Namespaces = require('../../shared/DOMNamespaces').Namespaces;
15
16 describe('setInnerHTML', () => {
packages/react-dom/src/client/getNodeForCharacterOffset.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var {TEXT_NODE} = require('../shared/HTMLNodeType');
10 +import {TEXT_NODE} from '../shared/HTMLNodeType';
11
12 /**
13 * Given any node return the first leaf node without children.
@@ -68,4 +68,4 @@ function getNodeForCharacterOffset(root, offset) {
68 }
69 }
70
71 -module.exports = getNodeForCharacterOffset;
71 +export default getNodeForCharacterOffset;
packages/react-dom/src/client/getTextContentAccessor.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
10 +import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment';
11
12 var contentKey = null;
13
@@ -28,4 +28,4 @@ function getTextContentAccessor() {
28 return contentKey;
29 }
30
31 -module.exports = getTextContentAccessor;
31 +export default getTextContentAccessor;
packages/react-dom/src/client/inputValueTracking.js
+38 -40
@@ -98,46 +98,44 @@ function trackValueOnNode(node: any): ?ValueTracker {
98 return tracker;
99 }
100
101 -var inputValueTracking = {
101 +export {
102 // exposed for testing
103 - _getTrackerFromNode: getTracker,
104 -
105 - track(node: ElementWithValueTracker) {
106 - if (getTracker(node)) {
107 - return;
108 - }
109 -
110 - // TODO: Once it's just Fiber we can move this to node._wrapperState
111 - node._valueTracker = trackValueOnNode(node);
112 - },
113 -
114 - updateValueIfChanged(node: ElementWithValueTracker) {
115 - if (!node) {
116 - return false;
117 - }
118 -
119 - var tracker = getTracker(node);
120 - // if there is no tracker at this point it's unlikely
121 - // that trying again will succeed
122 - if (!tracker) {
123 - return true;
124 - }
125 -
126 - var lastValue = tracker.getValue();
127 - var nextValue = getValueFromNode(node);
128 - if (nextValue !== lastValue) {
129 - tracker.setValue(nextValue);
130 - return true;
131 - }
132 - return false;
133 - },
134 -
135 - stopTracking(node: ElementWithValueTracker) {
136 - var tracker = getTracker(node);
137 - if (tracker) {
138 - tracker.stopTracking();
139 - }
140 - },
103 + getTracker as _getTrackerFromNode,
104 };
105
143 -module.exports = inputValueTracking;
106 +export function track(node: ElementWithValueTracker) {
107 + if (getTracker(node)) {
108 + return;
109 + }
110 +
111 + // TODO: Once it's just Fiber we can move this to node._wrapperState
112 + node._valueTracker = trackValueOnNode(node);
113 +}
114 +
115 +export function updateValueIfChanged(node: ElementWithValueTracker) {
116 + if (!node) {
117 + return false;
118 + }
119 +
120 + var tracker = getTracker(node);
121 + // if there is no tracker at this point it's unlikely
122 + // that trying again will succeed
123 + if (!tracker) {
124 + return true;
125 + }
126 +
127 + var lastValue = tracker.getValue();
128 + var nextValue = getValueFromNode(node);
129 + if (nextValue !== lastValue) {
130 + tracker.setValue(nextValue);
131 + return true;
132 + }
133 + return false;
134 +}
135 +
136 +export function stopTracking(node: ElementWithValueTracker) {
137 + var tracker = getTracker(node);
138 + if (tracker) {
139 + tracker.stopTracking();
140 + }
141 +}
packages/react-dom/src/client/setInnerHTML.js
+4 -3
@@ -7,8 +7,9 @@
7
8 'use strict';
9
10 -var Namespaces = require('../shared/DOMNamespaces').Namespaces;
11 -var createMicrosoftUnsafeLocalFunction = require('../shared/createMicrosoftUnsafeLocalFunction');
10 +import {Namespaces} from '../shared/DOMNamespaces';
11 +import createMicrosoftUnsafeLocalFunction
12 + from '../shared/createMicrosoftUnsafeLocalFunction';
13
14 // SVG temp container for IE lacking innerHTML
15 var reusableSVGContainer;
@@ -40,4 +41,4 @@ var setInnerHTML = createMicrosoftUnsafeLocalFunction(function(node, html) {
41 }
42 });
43
43 -module.exports = setInnerHTML;
44 +export default setInnerHTML;
packages/react-dom/src/client/setTextContent.js
+5 -5
@@ -7,11 +7,11 @@
7
8 'use strict';
9
10 -var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
10 +import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment';
11
12 -var setInnerHTML = require('./setInnerHTML');
13 -var escapeTextContentForBrowser = require('../shared/escapeTextContentForBrowser');
14 -var {TEXT_NODE} = require('../shared/HTMLNodeType');
12 +import setInnerHTML from './setInnerHTML';
13 +import escapeTextContentForBrowser from '../shared/escapeTextContentForBrowser';
14 +import {TEXT_NODE} from '../shared/HTMLNodeType';
15
16 /**
17 * Set the textContent property of a node, ensuring that whitespace is preserved
@@ -51,4 +51,4 @@ if (ExecutionEnvironment.canUseDOM) {
51 }
52 }
53
54 -module.exports = setTextContent;
54 +export default setTextContent;
packages/react-dom/src/client/validateDOMNesting.js
+8 -8
@@ -7,17 +7,16 @@
7
8 'use strict';
9
10 -var emptyFunction = require('fbjs/lib/emptyFunction');
10 +import emptyFunction from 'fbjs/lib/emptyFunction';
11 +import warning from 'fbjs/lib/warning';
12 +// TODO: direct imports like some-package/src/* are bad. Fix me.
13 +import ReactDebugCurrentFiber
14 + from 'react-reconciler/src/ReactDebugCurrentFiber';
15
16 +var {getCurrentFiberStackAddendum} = ReactDebugCurrentFiber;
17 var validateDOMNesting = emptyFunction;
18
19 if (__DEV__) {
15 - // TODO: direct imports like some-package/src/* are bad. Fix me.
16 - var {
17 - getCurrentFiberStackAddendum,
18 - } = require('react-reconciler/src/ReactDebugCurrentFiber');
19 - var warning = require('fbjs/lib/warning');
20 -
20 // This validation code was written based on the HTML5 parsing spec:
21 // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
22 //
@@ -484,6 +483,7 @@ if (__DEV__) {
483 }
484 };
485
486 + // TODO: turn this into a named export
487 validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo;
488
489 // For testing
@@ -498,4 +498,4 @@ if (__DEV__) {
498 };
499 }
500
501 -module.exports = validateDOMNesting;
501 +export default validateDOMNesting;
packages/react-dom/src/events/BeforeInputEventPlugin.js
+6 -6
@@ -9,12 +9,12 @@
9
10 import type {TopLevelTypes} from './BrowserEventConstants';
11
12 -var EventPropagators = require('events/EventPropagators');
13 -var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
12 +import EventPropagators from 'events/EventPropagators';
13 +import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment';
14
15 -var FallbackCompositionState = require('./FallbackCompositionState');
16 -var SyntheticCompositionEvent = require('./SyntheticCompositionEvent');
17 -var SyntheticInputEvent = require('./SyntheticInputEvent');
15 +import FallbackCompositionState from './FallbackCompositionState';
16 +import SyntheticCompositionEvent from './SyntheticCompositionEvent';
17 +import SyntheticInputEvent from './SyntheticInputEvent';
18
19 var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
20 var START_KEYCODE = 229;
@@ -472,4 +472,4 @@ var BeforeInputEventPlugin = {
472 },
473 };
474
475 -module.exports = BeforeInputEventPlugin;
475 +export default BeforeInputEventPlugin;
packages/react-dom/src/events/BrowserEventConstants.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var getVendorPrefixedEventName = require('./getVendorPrefixedEventName');
10 +import getVendorPrefixedEventName from './getVendorPrefixedEventName';
11
12 /**
13 * Types of raw signals from the browser caught at the top level.
@@ -96,4 +96,4 @@ var BrowserEventConstants = {
96 topLevelTypes,
97 };
98
99 -module.exports = BrowserEventConstants;
99 +export default BrowserEventConstants;
packages/react-dom/src/events/ChangeEventPlugin.js
+13 -13
@@ -7,18 +7,18 @@
7
8 'use strict';
9
10 -var EventPluginHub = require('events/EventPluginHub');
11 -var EventPropagators = require('events/EventPropagators');
12 -var ReactControlledComponent = require('events/ReactControlledComponent');
13 -var ReactGenericBatching = require('events/ReactGenericBatching');
14 -var SyntheticEvent = require('events/SyntheticEvent');
15 -var isTextInputElement = require('shared/isTextInputElement');
16 -var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
17 -
18 -var getEventTarget = require('./getEventTarget');
19 -var isEventSupported = require('./isEventSupported');
20 -var ReactDOMComponentTree = require('../client/ReactDOMComponentTree');
21 -var inputValueTracking = require('../client/inputValueTracking');
10 +import EventPluginHub from 'events/EventPluginHub';
11 +import EventPropagators from 'events/EventPropagators';
12 +import ReactControlledComponent from 'events/ReactControlledComponent';
13 +import ReactGenericBatching from 'events/ReactGenericBatching';
14 +import SyntheticEvent from 'events/SyntheticEvent';
15 +import isTextInputElement from 'shared/isTextInputElement';
16 +import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment';
17 +
18 +import getEventTarget from './getEventTarget';
19 +import isEventSupported from './isEventSupported';
20 +import ReactDOMComponentTree from '../client/ReactDOMComponentTree';
21 +import * as inputValueTracking from '../client/inputValueTracking';
22
23 var eventTypes = {
24 change: {
@@ -305,4 +305,4 @@ var ChangeEventPlugin = {
305 },
306 };
307
308 -module.exports = ChangeEventPlugin;
308 +export default ChangeEventPlugin;
packages/react-dom/src/events/DOMEventPluginOrder.js
+1 -1
@@ -26,4 +26,4 @@ var DOMEventPluginOrder = [
26 'BeforeInputEventPlugin',
27 ];
28
29 -module.exports = DOMEventPluginOrder;
29 +export default DOMEventPluginOrder;
packages/react-dom/src/events/EnterLeaveEventPlugin.js
+4 -4
@@ -7,10 +7,10 @@
7
8 'use strict';
9
10 -var EventPropagators = require('events/EventPropagators');
10 +import EventPropagators from 'events/EventPropagators';
11
12 -var SyntheticMouseEvent = require('./SyntheticMouseEvent');
13 -var ReactDOMComponentTree = require('../client/ReactDOMComponentTree');
12 +import SyntheticMouseEvent from './SyntheticMouseEvent';
13 +import ReactDOMComponentTree from '../client/ReactDOMComponentTree';
14
15 var eventTypes = {
16 mouseEnter: {
@@ -116,4 +116,4 @@ var EnterLeaveEventPlugin = {
116 },
117 };
118
119 -module.exports = EnterLeaveEventPlugin;
119 +export default EnterLeaveEventPlugin;
packages/react-dom/src/events/FallbackCompositionState.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var getTextContentAccessor = require('../client/getTextContentAccessor');
10 +import getTextContentAccessor from '../client/getTextContentAccessor';
11
12 /**
13 * This helper object stores information about text content of a target node,
@@ -74,4 +74,4 @@ var FallbackCompositionState = {
74 },
75 };
76
77 -module.exports = FallbackCompositionState;
77 +export default FallbackCompositionState;
packages/react-dom/src/events/ReactBrowserEventEmitter.js
+8 -6
@@ -7,12 +7,14 @@
7
8 'use strict';
9
10 -var EventPluginRegistry = require('events/EventPluginRegistry');
11 -var ReactEventEmitterMixin = require('events/ReactEventEmitterMixin');
10 +import EventPluginRegistry from 'events/EventPluginRegistry';
11 +import ReactEventEmitterMixin from 'events/ReactEventEmitterMixin';
12
13 -var ReactDOMEventListener = require('./ReactDOMEventListener');
14 -var isEventSupported = require('./isEventSupported');
15 -var {topLevelTypes} = require('./BrowserEventConstants');
13 +import ReactDOMEventListener from './ReactDOMEventListener';
14 +import isEventSupported from './isEventSupported';
15 +import BrowserEventConstants from './BrowserEventConstants';
16 +
17 +var {topLevelTypes} = BrowserEventConstants;
18
19 /**
20 * Summary of `ReactBrowserEventEmitter` event handling:
@@ -237,4 +239,4 @@ var ReactBrowserEventEmitter = Object.assign({}, ReactEventEmitterMixin, {
239 },
240 });
241
240 -module.exports = ReactBrowserEventEmitter;
242 +export default ReactBrowserEventEmitter;
packages/react-dom/src/events/ReactDOMEventListener.js
+8 -9
@@ -7,14 +7,13 @@
7
8 'use strict';
9
10 -var ReactGenericBatching = require('events/ReactGenericBatching');
11 -var ReactFiberTreeReflection = require('shared/ReactFiberTreeReflection');
12 -var ReactTypeOfWork = require('shared/ReactTypeOfWork');
13 -var EventListener = require('fbjs/lib/EventListener');
14 -var {HostRoot} = ReactTypeOfWork;
10 +import ReactGenericBatching from 'events/ReactGenericBatching';
11 +import {isFiberMounted} from 'shared/ReactFiberTreeReflection';
12 +import {HostRoot} from 'shared/ReactTypeOfWork';
13 +import EventListener from 'fbjs/lib/EventListener';
14
16 -var getEventTarget = require('./getEventTarget');
17 -var ReactDOMComponentTree = require('../client/ReactDOMComponentTree');
15 +import getEventTarget from './getEventTarget';
16 +import ReactDOMComponentTree from '../client/ReactDOMComponentTree';
17
18 var CALLBACK_BOOKKEEPING_POOL_SIZE = 10;
19 var callbackBookkeepingPool = [];
@@ -167,7 +166,7 @@ var ReactDOMEventListener = {
166 if (
167 targetInst !== null &&
168 typeof targetInst.tag === 'number' &&
170 - !ReactFiberTreeReflection.isFiberMounted(targetInst)
169 + !isFiberMounted(targetInst)
170 ) {
171 // If we get an event (ex: img onload) before committing that
172 // component's mount, ignore it for now (that is, treat it as if it was an
@@ -192,4 +191,4 @@ var ReactDOMEventListener = {
191 },
192 };
193
195 -module.exports = ReactDOMEventListener;
194 +export default ReactDOMEventListener;
packages/react-dom/src/events/SelectEventPlugin.js
+12 -12
@@ -7,17 +7,17 @@
7
8 'use strict';
9
10 -var EventPropagators = require('events/EventPropagators');
11 -var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
12 -var SyntheticEvent = require('events/SyntheticEvent');
13 -var isTextInputElement = require('shared/isTextInputElement');
14 -var getActiveElement = require('fbjs/lib/getActiveElement');
15 -var shallowEqual = require('fbjs/lib/shallowEqual');
16 -
17 -var ReactBrowserEventEmitter = require('./ReactBrowserEventEmitter');
18 -var ReactDOMComponentTree = require('../client/ReactDOMComponentTree');
19 -var ReactInputSelection = require('../client/ReactInputSelection');
20 -var {DOCUMENT_NODE} = require('../shared/HTMLNodeType');
10 +import EventPropagators from 'events/EventPropagators';
11 +import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment';
12 +import SyntheticEvent from 'events/SyntheticEvent';
13 +import isTextInputElement from 'shared/isTextInputElement';
14 +import getActiveElement from 'fbjs/lib/getActiveElement';
15 +import shallowEqual from 'fbjs/lib/shallowEqual';
16 +
17 +import ReactBrowserEventEmitter from './ReactBrowserEventEmitter';
18 +import ReactDOMComponentTree from '../client/ReactDOMComponentTree';
19 +import * as ReactInputSelection from '../client/ReactInputSelection';
20 +import {DOCUMENT_NODE} from '../shared/HTMLNodeType';
21
22 var skipSelectionChangeEvent =
23 ExecutionEnvironment.canUseDOM &&
@@ -209,4 +209,4 @@ var SelectEventPlugin = {
209 },
210 };
211
212 -module.exports = SelectEventPlugin;
212 +export default SelectEventPlugin;
packages/react-dom/src/events/SimpleEventPlugin.js
+15 -18
@@ -17,24 +17,21 @@ import type {
17 import type {Fiber} from 'react-reconciler/src/ReactFiber';
18 import type {EventTypes, PluginModule} from 'events/PluginModuleType';
19
20 -var EventPropagators = require('events/EventPropagators');
21 -var SyntheticEvent = require('events/SyntheticEvent');
20 +import EventPropagators from 'events/EventPropagators';
21 +import SyntheticEvent from 'events/SyntheticEvent';
22 +import warning from 'fbjs/lib/warning';
23
23 -var SyntheticAnimationEvent = require('./SyntheticAnimationEvent');
24 -var SyntheticClipboardEvent = require('./SyntheticClipboardEvent');
25 -var SyntheticFocusEvent = require('./SyntheticFocusEvent');
26 -var SyntheticKeyboardEvent = require('./SyntheticKeyboardEvent');
27 -var SyntheticMouseEvent = require('./SyntheticMouseEvent');
28 -var SyntheticDragEvent = require('./SyntheticDragEvent');
29 -var SyntheticTouchEvent = require('./SyntheticTouchEvent');
30 -var SyntheticTransitionEvent = require('./SyntheticTransitionEvent');
31 -var SyntheticUIEvent = require('./SyntheticUIEvent');
32 -var SyntheticWheelEvent = require('./SyntheticWheelEvent');
33 -var getEventCharCode = require('./getEventCharCode');
34 -
35 -if (__DEV__) {
36 - var warning = require('fbjs/lib/warning');
37 -}
24 +import SyntheticAnimationEvent from './SyntheticAnimationEvent';
25 +import SyntheticClipboardEvent from './SyntheticClipboardEvent';
26 +import SyntheticFocusEvent from './SyntheticFocusEvent';
27 +import SyntheticKeyboardEvent from './SyntheticKeyboardEvent';
28 +import SyntheticMouseEvent from './SyntheticMouseEvent';
29 +import SyntheticDragEvent from './SyntheticDragEvent';
30 +import SyntheticTouchEvent from './SyntheticTouchEvent';
31 +import SyntheticTransitionEvent from './SyntheticTransitionEvent';
32 +import SyntheticUIEvent from './SyntheticUIEvent';
33 +import SyntheticWheelEvent from './SyntheticWheelEvent';
34 +import getEventCharCode from './getEventCharCode';
35
36 /**
37 * Turns
@@ -284,4 +281,4 @@ var SimpleEventPlugin: PluginModule<MouseEvent> = {
281 },
282 };
283
287 -module.exports = SimpleEventPlugin;
284 +export default SimpleEventPlugin;
packages/react-dom/src/events/SyntheticAnimationEvent.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var SyntheticEvent = require('events/SyntheticEvent');
10 +import SyntheticEvent from 'events/SyntheticEvent';
11
12 /**
13 * @interface Event
@@ -43,4 +43,4 @@ function SyntheticAnimationEvent(
43
44 SyntheticEvent.augmentClass(SyntheticAnimationEvent, AnimationEventInterface);
45
46 -module.exports = SyntheticAnimationEvent;
46 +export default SyntheticAnimationEvent;
packages/react-dom/src/events/SyntheticClipboardEvent.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var SyntheticEvent = require('events/SyntheticEvent');
10 +import SyntheticEvent from 'events/SyntheticEvent';
11
12 /**
13 * @interface Event
@@ -44,4 +44,4 @@ function SyntheticClipboardEvent(
44
45 SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface);
46
47 -module.exports = SyntheticClipboardEvent;
47 +export default SyntheticClipboardEvent;
packages/react-dom/src/events/SyntheticCompositionEvent.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var SyntheticEvent = require('events/SyntheticEvent');
10 +import SyntheticEvent from 'events/SyntheticEvent';
11
12 /**
13 * @interface Event
@@ -43,4 +43,4 @@ SyntheticEvent.augmentClass(
43 CompositionEventInterface,
44 );
45
46 -module.exports = SyntheticCompositionEvent;
46 +export default SyntheticCompositionEvent;
packages/react-dom/src/events/SyntheticDragEvent.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var SyntheticMouseEvent = require('./SyntheticMouseEvent');
10 +import SyntheticMouseEvent from './SyntheticMouseEvent';
11
12 /**
13 * @interface DragEvent
@@ -40,4 +40,4 @@ function SyntheticDragEvent(
40
41 SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface);
42
43 -module.exports = SyntheticDragEvent;
43 +export default SyntheticDragEvent;
packages/react-dom/src/events/SyntheticFocusEvent.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var SyntheticUIEvent = require('./SyntheticUIEvent');
10 +import SyntheticUIEvent from './SyntheticUIEvent';
11
12 /**
13 * @interface FocusEvent
@@ -40,4 +40,4 @@ function SyntheticFocusEvent(
40
41 SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface);
42
43 -module.exports = SyntheticFocusEvent;
43 +export default SyntheticFocusEvent;
packages/react-dom/src/events/SyntheticInputEvent.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var SyntheticEvent = require('events/SyntheticEvent');
10 +import SyntheticEvent from 'events/SyntheticEvent';
11
12 /**
13 * @interface Event
@@ -41,4 +41,4 @@ function SyntheticInputEvent(
41
42 SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface);
43
44 -module.exports = SyntheticInputEvent;
44 +export default SyntheticInputEvent;
packages/react-dom/src/events/SyntheticKeyboardEvent.js
+5 -5
@@ -7,10 +7,10 @@
7
8 'use strict';
9
10 -var SyntheticUIEvent = require('./SyntheticUIEvent');
11 -var getEventCharCode = require('./getEventCharCode');
12 -var getEventKey = require('./getEventKey');
13 -var getEventModifierState = require('./getEventModifierState');
10 +import SyntheticUIEvent from './SyntheticUIEvent';
11 +import getEventCharCode from './getEventCharCode';
12 +import getEventKey from './getEventKey';
13 +import getEventModifierState from './getEventModifierState';
14
15 /**
16 * @interface KeyboardEvent
@@ -87,4 +87,4 @@ function SyntheticKeyboardEvent(
87
88 SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface);
89
90 -module.exports = SyntheticKeyboardEvent;
90 +export default SyntheticKeyboardEvent;
packages/react-dom/src/events/SyntheticMouseEvent.js
+3 -3
@@ -7,8 +7,8 @@
7
8 'use strict';
9
10 -var SyntheticUIEvent = require('./SyntheticUIEvent');
11 -var getEventModifierState = require('./getEventModifierState');
10 +import SyntheticUIEvent from './SyntheticUIEvent';
11 +import getEventModifierState from './getEventModifierState';
12
13 /**
14 * @interface MouseEvent
@@ -61,4 +61,4 @@ function SyntheticMouseEvent(
61
62 SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface);
63
64 -module.exports = SyntheticMouseEvent;
64 +export default SyntheticMouseEvent;
packages/react-dom/src/events/SyntheticTouchEvent.js
+3 -3
@@ -7,8 +7,8 @@
7
8 'use strict';
9
10 -var SyntheticUIEvent = require('./SyntheticUIEvent');
11 -var getEventModifierState = require('./getEventModifierState');
10 +import SyntheticUIEvent from './SyntheticUIEvent';
11 +import getEventModifierState from './getEventModifierState';
12
13 /**
14 * @interface TouchEvent
@@ -48,4 +48,4 @@ function SyntheticTouchEvent(
48
49 SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface);
50
51 -module.exports = SyntheticTouchEvent;
51 +export default SyntheticTouchEvent;
packages/react-dom/src/events/SyntheticTransitionEvent.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var SyntheticEvent = require('events/SyntheticEvent');
10 +import SyntheticEvent from 'events/SyntheticEvent';
11
12 /**
13 * @interface Event
@@ -43,4 +43,4 @@ function SyntheticTransitionEvent(
43
44 SyntheticEvent.augmentClass(SyntheticTransitionEvent, TransitionEventInterface);
45
46 -module.exports = SyntheticTransitionEvent;
46 +export default SyntheticTransitionEvent;
packages/react-dom/src/events/SyntheticUIEvent.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var SyntheticEvent = require('events/SyntheticEvent');
10 +import SyntheticEvent from 'events/SyntheticEvent';
11
12 /**
13 * @interface UIEvent
@@ -41,4 +41,4 @@ function SyntheticUIEvent(
41
42 SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface);
43
44 -module.exports = SyntheticUIEvent;
44 +export default SyntheticUIEvent;
packages/react-dom/src/events/SyntheticWheelEvent.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var SyntheticMouseEvent = require('./SyntheticMouseEvent');
10 +import SyntheticMouseEvent from './SyntheticMouseEvent';
11
12 /**
13 * @interface WheelEvent
@@ -61,4 +61,4 @@ function SyntheticWheelEvent(
61
62 SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface);
63
64 -module.exports = SyntheticWheelEvent;
64 +export default SyntheticWheelEvent;
packages/react-dom/src/events/TapEventPlugin.js
+7 -6
@@ -9,14 +9,15 @@
9
10 'use strict';
11
12 -var EventPluginUtils = require('events/EventPluginUtils');
13 -var EventPropagators = require('events/EventPropagators');
14 -var TouchEventUtils = require('fbjs/lib/TouchEventUtils');
12 +import EventPluginUtils from 'events/EventPluginUtils';
13 +import EventPropagators from 'events/EventPropagators';
14 +import TouchEventUtils from 'fbjs/lib/TouchEventUtils';
15 +
16 +import SyntheticUIEvent from './SyntheticUIEvent';
17 +
18 var isStartish = EventPluginUtils.isStartish;
19 var isEndish = EventPluginUtils.isEndish;
20
18 -var SyntheticUIEvent = require('./SyntheticUIEvent');
19 -
21 /**
22 * We are extending the Flow 'Touch' declaration to enable using bracket
23 * notation to access properties.
@@ -150,4 +151,4 @@ var TapEventPlugin = {
151 },
152 };
153
153 -module.exports = TapEventPlugin;
154 +export default TapEventPlugin;
packages/react-dom/src/events/__tests__/BeforeInputEventPlugin-test.js
+4 -4
@@ -49,10 +49,10 @@ describe('BeforeInputEventPlugin', function() {
49 this.ReactDOM = require('react-dom');
50
51 // TODO: can we express this test with only public API?
52 - this.ReactDOMComponentTree = require('../../client//ReactDOMComponentTree');
53 - this.SyntheticCompositionEvent = require('../SyntheticCompositionEvent');
54 - this.SyntheticInputEvent = require('../SyntheticInputEvent');
55 - this.BeforeInputEventPlugin = require('../BeforeInputEventPlugin');
52 + this.ReactDOMComponentTree = require('../../client/ReactDOMComponentTree').default;
53 + this.SyntheticCompositionEvent = require('../SyntheticCompositionEvent').default;
54 + this.SyntheticInputEvent = require('../SyntheticInputEvent').default;
55 + this.BeforeInputEventPlugin = require('../BeforeInputEventPlugin').default;
56 }
57
58 function extract(node, eventType, optionalData) {
packages/react-dom/src/events/__tests__/ChangeEventPlugin-test.js
+1 -1
@@ -13,7 +13,7 @@ var React = require('react');
13 var ReactDOM = require('react-dom');
14 var ReactTestUtils = require('react-dom/test-utils');
15 // TODO: can we express this test with only public API?
16 -var ChangeEventPlugin = require('../ChangeEventPlugin');
16 +var ChangeEventPlugin = require('../ChangeEventPlugin').default;
17 var inputValueTracking = require('../../client/inputValueTracking');
18
19 function getTrackedValue(elem) {
packages/react-dom/src/events/__tests__/EnterLeaveEventPlugin-test.js
+3 -2
@@ -23,8 +23,9 @@ describe('EnterLeaveEventPlugin', () => {
23 ReactDOM = require('react-dom');
24 ReactTestUtils = require('react-dom/test-utils');
25 // TODO: can we express this test with only public API?
26 - ReactDOMComponentTree = require('../../client/ReactDOMComponentTree');
27 - EnterLeaveEventPlugin = require('../EnterLeaveEventPlugin');
26 + ReactDOMComponentTree = require('../../client/ReactDOMComponentTree')
27 + .default;
28 + EnterLeaveEventPlugin = require('../EnterLeaveEventPlugin').default;
29 });
30
31 it('should set relatedTarget properly in iframe', () => {
packages/react-dom/src/events/__tests__/FallbackCompositionState-test.js
+1 -1
@@ -16,7 +16,7 @@ describe('FallbackCompositionState', () => {
16
17 beforeEach(() => {
18 // TODO: can we express this test with only public API?
19 - FallbackCompositionState = require('../FallbackCompositionState');
19 + FallbackCompositionState = require('../FallbackCompositionState').default;
20 });
21
22 function getInput() {
packages/react-dom/src/events/__tests__/SelectEventPlugin-test.js
+3 -2
@@ -30,8 +30,9 @@ describe('SelectEventPlugin', () => {
30 ReactDOM = require('react-dom');
31 ReactTestUtils = require('react-dom/test-utils');
32 // TODO: can we express this test with only public API?
33 - ReactDOMComponentTree = require('../../client/ReactDOMComponentTree');
34 - SelectEventPlugin = require('../SelectEventPlugin');
33 + ReactDOMComponentTree = require('../../client/ReactDOMComponentTree')
34 + .default;
35 + SelectEventPlugin = require('../SelectEventPlugin').default;
36 });
37
38 it('should skip extraction if no listeners are present', () => {
packages/react-dom/src/events/__tests__/SyntheticClipboardEvent-test.js
+2 -2
@@ -16,9 +16,9 @@ describe('SyntheticClipboardEvent', () => {
16
17 beforeEach(() => {
18 // TODO: can we express this test with only public API?
19 - SyntheticClipboardEvent = require('../SyntheticClipboardEvent');
19 + SyntheticClipboardEvent = require('../SyntheticClipboardEvent').default;
20 createEvent = function(nativeEvent) {
21 - var target = require('../getEventTarget')(nativeEvent);
21 + var target = require('../getEventTarget').default(nativeEvent);
22 return SyntheticClipboardEvent.getPooled({}, '', nativeEvent, target);
23 };
24 });
packages/react-dom/src/events/__tests__/SyntheticEvent-test.js
+2 -2
@@ -19,13 +19,13 @@ describe('SyntheticEvent', () => {
19
20 beforeEach(() => {
21 // TODO: can we express this test with only public API?
22 - SyntheticEvent = require('events/SyntheticEvent');
22 + SyntheticEvent = require('events/SyntheticEvent').default;
23 React = require('react');
24 ReactDOM = require('react-dom');
25 ReactTestUtils = require('react-dom/test-utils');
26
27 createEvent = function(nativeEvent) {
28 - var target = require('../getEventTarget')(nativeEvent);
28 + var target = require('../getEventTarget').default(nativeEvent);
29 return SyntheticEvent.getPooled({}, '', nativeEvent, target);
30 };
31 });
packages/react-dom/src/events/__tests__/SyntheticKeyboardEvent-test.js
+3 -3
@@ -18,12 +18,12 @@ describe('SyntheticKeyboardEvent', () => {
18 beforeEach(() => {
19 // Mock getEventCharCode for proper unit testing
20 jest.mock('../getEventCharCode');
21 - getEventCharCode = require('../getEventCharCode');
21 + getEventCharCode = require('../getEventCharCode').default;
22
23 // TODO: can we express this test with only public API?
24 - SyntheticKeyboardEvent = require('../SyntheticKeyboardEvent');
24 + SyntheticKeyboardEvent = require('../SyntheticKeyboardEvent').default;
25 createEvent = function(nativeEvent) {
26 - var target = require('../getEventTarget')(nativeEvent);
26 + var target = require('../getEventTarget').default(nativeEvent);
27 return SyntheticKeyboardEvent.getPooled({}, '', nativeEvent, target);
28 };
29 });
packages/react-dom/src/events/__tests__/SyntheticWheelEvent-test.js
+2 -2
@@ -16,10 +16,10 @@ describe('SyntheticWheelEvent', () => {
16
17 beforeEach(() => {
18 // TODO: can we express this test with only public API?
19 - SyntheticWheelEvent = require('../SyntheticWheelEvent');
19 + SyntheticWheelEvent = require('../SyntheticWheelEvent').default;
20
21 createEvent = function(nativeEvent) {
22 - var target = require('../getEventTarget')(nativeEvent);
22 + var target = require('../getEventTarget').default(nativeEvent);
23 return SyntheticWheelEvent.getPooled({}, '', nativeEvent, target);
24 };
25 });
packages/react-dom/src/events/__tests__/getEventCharCode-test.js
+1 -1
@@ -10,7 +10,7 @@
10 'use strict';
11
12 // TODO: can we express this test with only public API?
13 -var getEventCharCode = require('../getEventCharCode');
13 +var getEventCharCode = require('../getEventCharCode').default;
14
15 describe('getEventCharCode', () => {
16 describe('when charCode is present in nativeEvent', () => {
packages/react-dom/src/events/__tests__/getEventKey-test.js
+1 -1
@@ -10,7 +10,7 @@
10 'use strict';
11
12 // TODO: can we express this test with only public API?
13 -var getEventKey = require('../getEventKey');
13 +var getEventKey = require('../getEventKey').default;
14
15 describe('getEventKey', () => {
16 describe('when key is implemented in a browser', () => {
packages/react-dom/src/events/getEventCharCode.js
+1 -1
@@ -42,4 +42,4 @@ function getEventCharCode(nativeEvent) {
42 return 0;
43 }
44
45 -module.exports = getEventCharCode;
45 +export default getEventCharCode;
packages/react-dom/src/events/getEventKey.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var getEventCharCode = require('./getEventCharCode');
10 +import getEventCharCode from './getEventCharCode';
11
12 /**
13 * Normalization of deprecated HTML5 `key` values
@@ -105,4 +105,4 @@ function getEventKey(nativeEvent) {
105 return '';
106 }
107
108 -module.exports = getEventKey;
108 +export default getEventKey;
packages/react-dom/src/events/getEventModifierState.js
+1 -1
@@ -36,4 +36,4 @@ function getEventModifierState(nativeEvent) {
36 return modifierStateGetter;
37 }
38
39 -module.exports = getEventModifierState;
39 +export default getEventModifierState;
packages/react-dom/src/events/getEventTarget.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var {TEXT_NODE} = require('../shared/HTMLNodeType');
10 +import {TEXT_NODE} from '../shared/HTMLNodeType';
11
12 /**
13 * Gets the target node from a native browser event by accounting for
@@ -29,4 +29,4 @@ function getEventTarget(nativeEvent) {
29 return target.nodeType === TEXT_NODE ? target.parentNode : target;
30 }
31
32 -module.exports = getEventTarget;
32 +export default getEventTarget;
packages/react-dom/src/events/getVendorPrefixedEventName.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
10 +import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment';
11
12 /**
13 * Generate a mapping of standard vendor prefixes using the defined style property and event name.
@@ -94,4 +94,4 @@ function getVendorPrefixedEventName(eventName) {
94 return '';
95 }
96
97 -module.exports = getVendorPrefixedEventName;
97 +export default getVendorPrefixedEventName;
packages/react-dom/src/events/isEventSupported.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
10 +import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment';
11
12 var useHasFeature;
13 if (ExecutionEnvironment.canUseDOM) {
@@ -58,4 +58,4 @@ function isEventSupported(eventNameSuffix, capture) {
58 return isSupported;
59 }
60
61 -module.exports = isEventSupported;
61 +export default isEventSupported;
packages/react-dom/src/server/DOMMarkupOperations.js
+5 -7
@@ -7,12 +7,10 @@
7
8 'use strict';
9
10 -var DOMProperty = require('../shared/DOMProperty');
11 -var quoteAttributeValueForBrowser = require('../shared/quoteAttributeValueForBrowser');
12 -
13 -if (__DEV__) {
14 - var warning = require('fbjs/lib/warning');
15 -}
10 +import DOMProperty from '../shared/DOMProperty';
11 +import quoteAttributeValueForBrowser
12 + from '../shared/quoteAttributeValueForBrowser';
13 +import warning from 'fbjs/lib/warning';
14
15 // isAttributeNameSafe() is currently duplicated in DOMPropertyOperations.
16 // TODO: Find a better place for this.
@@ -124,4 +122,4 @@ var DOMMarkupOperations = {
122 },
123 };
124
127 -module.exports = DOMMarkupOperations;
125 +export default DOMMarkupOperations;
packages/react-dom/src/server/ReactDOMNodeStreamRenderer.js
+4 -9
@@ -7,9 +7,9 @@
7
8 'use strict';
9
10 -var Readable = require('stream').Readable;
10 +import {Readable} from 'stream';
11
12 -var ReactPartialRenderer = require('./ReactPartialRenderer');
12 +import ReactPartialRenderer from './ReactPartialRenderer';
13
14 // This is a Readable Node.js stream which wraps the ReactDOMPartialRenderer.
15 class ReactMarkupReadableStream extends Readable {
@@ -33,7 +33,7 @@ class ReactMarkupReadableStream extends Readable {
33 * server.
34 * See https://reactjs.org/docs/react-dom-stream.html#rendertonodestream
35 */
36 -function renderToNodeStream(element) {
36 +export function renderToNodeStream(element) {
37 return new ReactMarkupReadableStream(element, false);
38 }
39
@@ -42,11 +42,6 @@ function renderToNodeStream(element) {
42 * such as data-react-id that React uses internally.
43 * See https://reactjs.org/docs/react-dom-stream.html#rendertostaticnodestream
44 */
45 -function renderToStaticNodeStream(element) {
45 +export function renderToStaticNodeStream(element) {
46 return new ReactMarkupReadableStream(element, true);
47 }
48 -
49 -module.exports = {
50 - renderToNodeStream: renderToNodeStream,
51 - renderToStaticNodeStream: renderToStaticNodeStream,
52 -};
packages/react-dom/src/server/ReactDOMServerBrowser.js
+26 -22
@@ -7,29 +7,33 @@
7
8 'use strict';
9
10 -require('../shared/ReactDOMInjection');
10 +import '../shared/ReactDOMInjection';
11 +import ReactVersion from 'shared/ReactVersion';
12 +import invariant from 'fbjs/lib/invariant';
13
12 -var ReactVersion = require('shared/ReactVersion');
13 -var invariant = require('fbjs/lib/invariant');
14 +import {renderToString, renderToStaticMarkup} from './ReactDOMStringRenderer';
15
15 -var ReactDOMStringRenderer = require('./ReactDOMStringRenderer');
16 +function renderToNodeStream() {
17 + invariant(
18 + false,
19 + 'ReactDOMServer.renderToNodeStream(): The streaming API is not available ' +
20 + 'in the browser. Use ReactDOMServer.renderToString() instead.',
21 + );
22 +}
23
17 -module.exports = {
18 - renderToString: ReactDOMStringRenderer.renderToString,
19 - renderToStaticMarkup: ReactDOMStringRenderer.renderToStaticMarkup,
20 - renderToNodeStream() {
21 - invariant(
22 - false,
23 - 'ReactDOMServer.renderToNodeStream(): The streaming API is not available ' +
24 - 'in the browser. Use ReactDOMServer.renderToString() instead.',
25 - );
26 - },
27 - renderToStaticNodeStream() {
28 - invariant(
29 - false,
30 - 'ReactDOMServer.renderToStaticNodeStream(): The streaming API is not available ' +
31 - 'in the browser. Use ReactDOMServer.renderToStaticMarkup() instead.',
32 - );
33 - },
34 - version: ReactVersion,
24 +function renderToStaticNodeStream() {
25 + invariant(
26 + false,
27 + 'ReactDOMServer.renderToStaticNodeStream(): The streaming API is not available ' +
28 + 'in the browser. Use ReactDOMServer.renderToStaticMarkup() instead.',
29 + );
30 +}
31 +
32 +export {
33 + renderToString,
34 + renderToStaticMarkup,
35 + renderToNodeStream,
36 + renderToStaticNodeStream,
37 };
38 +
39 +export const version = ReactVersion;
packages/react-dom/src/server/ReactDOMServerNode.js
+14 -11
@@ -7,17 +7,20 @@
7
8 'use strict';
9
10 -require('../shared/ReactDOMInjection');
10 +import '../shared/ReactDOMInjection';
11 +import ReactVersion from 'shared/ReactVersion';
12
12 -var ReactVersion = require('shared/ReactVersion');
13 +import {renderToString, renderToStaticMarkup} from './ReactDOMStringRenderer';
14 +import {
15 + renderToNodeStream,
16 + renderToStaticNodeStream,
17 +} from './ReactDOMNodeStreamRenderer';
18
14 -var ReactDOMStringRenderer = require('./ReactDOMStringRenderer');
15 -var ReactDOMNodeStreamRenderer = require('./ReactDOMNodeStreamRenderer');
16 -
17 -module.exports = {
18 - renderToString: ReactDOMStringRenderer.renderToString,
19 - renderToStaticMarkup: ReactDOMStringRenderer.renderToStaticMarkup,
20 - renderToNodeStream: ReactDOMNodeStreamRenderer.renderToNodeStream,
21 - renderToStaticNodeStream: ReactDOMNodeStreamRenderer.renderToStaticNodeStream,
22 - version: ReactVersion,
19 +export {
20 + renderToString,
21 + renderToStaticMarkup,
22 + renderToNodeStream,
23 + renderToStaticNodeStream,
24 };
25 +
26 +export const version = ReactVersion;
packages/react-dom/src/server/ReactDOMStringRenderer.js
+3 -8
@@ -7,14 +7,14 @@
7
8 'use strict';
9
10 -var ReactPartialRenderer = require('./ReactPartialRenderer');
10 +import ReactPartialRenderer from './ReactPartialRenderer';
11
12 /**
13 * Render a ReactElement to its initial HTML. This should only be used on the
14 * server.
15 * See https://reactjs.org/docs/react-dom-server.html#rendertostring
16 */
17 -function renderToString(element) {
17 +export function renderToString(element) {
18 var renderer = new ReactPartialRenderer(element, false);
19 var markup = renderer.read(Infinity);
20 return markup;
@@ -25,13 +25,8 @@ function renderToString(element) {
25 * such as data-react-id that React uses internally.
26 * See https://reactjs.org/docs/react-dom-server.html#rendertostaticmarkup
27 */
28 -function renderToStaticMarkup(element) {
28 +export function renderToStaticMarkup(element) {
29 var renderer = new ReactPartialRenderer(element, true);
30 var markup = renderer.read(Infinity);
31 return markup;
32 }
33 -
34 -module.exports = {
35 - renderToString: renderToString,
36 - renderToStaticMarkup: renderToStaticMarkup,
37 -};
packages/react-dom/src/server/ReactPartialRenderer.js
+32 -33
@@ -11,25 +11,40 @@
11
12 import type {ReactElement} from 'shared/ReactElementType';
13
14 -var React = require('react');
15 -var emptyFunction = require('fbjs/lib/emptyFunction');
16 -var emptyObject = require('fbjs/lib/emptyObject');
17 -var hyphenateStyleName = require('fbjs/lib/hyphenateStyleName');
18 -var invariant = require('fbjs/lib/invariant');
19 -var memoizeStringOnly = require('fbjs/lib/memoizeStringOnly');
20 -
21 -var DOMMarkupOperations = require('./DOMMarkupOperations');
22 -var {
14 +import React from 'react';
15 +import emptyFunction from 'fbjs/lib/emptyFunction';
16 +import emptyObject from 'fbjs/lib/emptyObject';
17 +import hyphenateStyleName from 'fbjs/lib/hyphenateStyleName';
18 +import invariant from 'fbjs/lib/invariant';
19 +import memoizeStringOnly from 'fbjs/lib/memoizeStringOnly';
20 +import warning from 'fbjs/lib/warning';
21 +import checkPropTypes from 'prop-types/checkPropTypes';
22 +import describeComponentFrame from 'shared/describeComponentFrame';
23 +import {ReactDebugCurrentFrame} from 'shared/ReactGlobalSharedState';
24 +
25 +import DOMMarkupOperations from './DOMMarkupOperations';
26 +import {
27 Namespaces,
28 getIntrinsicNamespace,
29 getChildNamespace,
26 -} = require('../shared/DOMNamespaces');
27 -var ReactControlledValuePropTypes = require('../shared/ReactControlledValuePropTypes');
28 -var assertValidProps = require('../shared/assertValidProps');
29 -var dangerousStyleValue = require('../shared/dangerousStyleValue');
30 -var escapeTextContentForBrowser = require('../shared/escapeTextContentForBrowser');
31 -var isCustomComponent = require('../shared/isCustomComponent');
32 -var omittedCloseTags = require('../shared/omittedCloseTags');
30 +} from '../shared/DOMNamespaces';
31 +import ReactControlledValuePropTypes
32 + from '../shared/ReactControlledValuePropTypes';
33 +import assertValidProps from '../shared/assertValidProps';
34 +import dangerousStyleValue from '../shared/dangerousStyleValue';
35 +import escapeTextContentForBrowser from '../shared/escapeTextContentForBrowser';
36 +import isCustomComponent from '../shared/isCustomComponent';
37 +import omittedCloseTags from '../shared/omittedCloseTags';
38 +import warnValidStyle from '../shared/warnValidStyle';
39 +import {
40 + validateProperties as validateARIAProperties,
41 +} from '../shared/ReactDOMInvalidARIAHook';
42 +import {
43 + validateProperties as validateInputProperties,
44 +} from '../shared/ReactDOMNullInputValuePropHook';
45 +import {
46 + validateProperties as validateUnknownProperties,
47 +} from '../shared/ReactDOMUnknownPropertyHook';
48
49 var REACT_FRAGMENT_TYPE =
50 (typeof Symbol === 'function' &&
@@ -46,27 +61,12 @@ var toArray = ((React.Children.toArray: any): toArrayType);
61 var getStackAddendum = emptyFunction.thatReturns('');
62
63 if (__DEV__) {
49 - var warning = require('fbjs/lib/warning');
50 - var checkPropTypes = require('prop-types/checkPropTypes');
51 -
52 - var warnValidStyle = require('../shared/warnValidStyle');
53 - var {
54 - validateProperties: validateARIAProperties,
55 - } = require('../shared/ReactDOMInvalidARIAHook');
56 - var {
57 - validateProperties: validateInputProperties,
58 - } = require('../shared/ReactDOMNullInputValuePropHook');
59 - var {
60 - validateProperties: validateUnknownProperties,
61 - } = require('../shared/ReactDOMUnknownPropertyHook');
62 -
64 var validatePropertiesInDevelopment = function(type, props) {
65 validateARIAProperties(type, props);
66 validateInputProperties(type, props);
67 validateUnknownProperties(type, props);
68 };
69
69 - var describeComponentFrame = require('shared/describeComponentFrame');
70 var describeStackFrame = function(element): string {
71 var source = element._source;
72 var type = element.type;
@@ -75,7 +75,6 @@ if (__DEV__) {
75 return describeComponentFrame(name, source, ownerName);
76 };
77
78 - var {ReactDebugCurrentFrame} = require('shared/ReactGlobalSharedState');
78 var currentDebugStack = null;
79 var currentDebugElementStack = null;
80 var setCurrentDebugStack = function(stack: Array<Frame>) {
@@ -933,4 +932,4 @@ class ReactDOMServerRenderer {
932 }
933 }
934
936 -module.exports = ReactDOMServerRenderer;
935 +export default ReactDOMServerRenderer;
packages/react-dom/src/shared/CSSProperty.js
+1 -7
@@ -10,7 +10,7 @@
10 /**
11 * CSS properties which accept numbers but are not in units of "px".
12 */
13 -var isUnitlessNumber = {
13 +export const isUnitlessNumber = {
14 animationIterationCount: true,
15 borderImageOutset: true,
16 borderImageSlice: true,
@@ -79,9 +79,3 @@ Object.keys(isUnitlessNumber).forEach(function(prop) {
79 isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
80 });
81 });
82 -
83 -var CSSProperty = {
84 - isUnitlessNumber: isUnitlessNumber,
85 -};
86 -
87 -module.exports = CSSProperty;
packages/react-dom/src/shared/CSSPropertyOperations.js
+52 -59
@@ -7,83 +7,76 @@
7
8 'use strict';
9
10 -var dangerousStyleValue = require('./dangerousStyleValue');
11 -
12 -if (__DEV__) {
13 - var hyphenateStyleName = require('fbjs/lib/hyphenateStyleName');
14 -
15 - var warnValidStyle = require('./warnValidStyle');
16 -}
10 +import dangerousStyleValue from './dangerousStyleValue';
11 +import hyphenateStyleName from 'fbjs/lib/hyphenateStyleName';
12 +import warnValidStyle from './warnValidStyle';
13
14 /**
15 * Operations for dealing with CSS properties.
16 */
21 -var CSSPropertyOperations = {
22 - /**
17 +
18 +/**
19 * This creates a string that is expected to be equivalent to the style
20 * attribute generated by server-side rendering. It by-passes warnings and
21 * security checks so it's not safe to use this value for anything other than
22 * comparison. It is only used in DEV for SSR validation.
23 */
28 - createDangerousStringForStyles: function(styles) {
29 - if (__DEV__) {
30 - var serialized = '';
31 - var delimiter = '';
32 - for (var styleName in styles) {
33 - if (!styles.hasOwnProperty(styleName)) {
34 - continue;
35 - }
36 - var styleValue = styles[styleName];
37 - if (styleValue != null) {
38 - var isCustomProperty = styleName.indexOf('--') === 0;
39 - serialized += delimiter + hyphenateStyleName(styleName) + ':';
40 - serialized += dangerousStyleValue(
41 - styleName,
42 - styleValue,
43 - isCustomProperty,
44 - );
24 +export function createDangerousStringForStyles(styles) {
25 + if (__DEV__) {
26 + var serialized = '';
27 + var delimiter = '';
28 + for (var styleName in styles) {
29 + if (!styles.hasOwnProperty(styleName)) {
30 + continue;
31 + }
32 + var styleValue = styles[styleName];
33 + if (styleValue != null) {
34 + var isCustomProperty = styleName.indexOf('--') === 0;
35 + serialized += delimiter + hyphenateStyleName(styleName) + ':';
36 + serialized += dangerousStyleValue(
37 + styleName,
38 + styleValue,
39 + isCustomProperty,
40 + );
41
46 - delimiter = ';';
47 - }
42 + delimiter = ';';
43 }
49 - return serialized || null;
44 }
51 - },
45 + return serialized || null;
46 + }
47 +}
48
53 - /**
49 +/**
50 * Sets the value for multiple styles on a node. If a value is specified as
51 * '' (empty string), the corresponding style property will be unset.
52 *
53 * @param {DOMElement} node
54 * @param {object} styles
55 */
60 - setValueForStyles: function(node, styles, getStack) {
61 - var style = node.style;
62 - for (var styleName in styles) {
63 - if (!styles.hasOwnProperty(styleName)) {
64 - continue;
65 - }
66 - var isCustomProperty = styleName.indexOf('--') === 0;
67 - if (__DEV__) {
68 - if (!isCustomProperty) {
69 - warnValidStyle(styleName, styles[styleName], getStack);
70 - }
71 - }
72 - var styleValue = dangerousStyleValue(
73 - styleName,
74 - styles[styleName],
75 - isCustomProperty,
76 - );
77 - if (styleName === 'float') {
78 - styleName = 'cssFloat';
79 - }
80 - if (isCustomProperty) {
81 - style.setProperty(styleName, styleValue);
82 - } else {
83 - style[styleName] = styleValue;
56 +export function setValueForStyles(node, styles, getStack) {
57 + var style = node.style;
58 + for (var styleName in styles) {
59 + if (!styles.hasOwnProperty(styleName)) {
60 + continue;
61 + }
62 + var isCustomProperty = styleName.indexOf('--') === 0;
63 + if (__DEV__) {
64 + if (!isCustomProperty) {
65 + warnValidStyle(styleName, styles[styleName], getStack);
66 }
67 }
86 - },
87 -};
88 -
89 -module.exports = CSSPropertyOperations;
68 + var styleValue = dangerousStyleValue(
69 + styleName,
70 + styles[styleName],
71 + isCustomProperty,
72 + );
73 + if (styleName === 'float') {
74 + styleName = 'cssFloat';
75 + }
76 + if (isCustomProperty) {
77 + style.setProperty(styleName, styleValue);
78 + } else {
79 + style[styleName] = styleValue;
80 + }
81 + }
82 +}
packages/react-dom/src/shared/DOMNamespaces.js
+3 -7
@@ -11,14 +11,14 @@ const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
11 const MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
12 const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
13
14 -const Namespaces = {
14 +export const Namespaces = {
15 html: HTML_NAMESPACE,
16 mathml: MATH_NAMESPACE,
17 svg: SVG_NAMESPACE,
18 };
19
20 // Assumes there is no parent namespace.
21 -function getIntrinsicNamespace(type: string): string {
21 +export function getIntrinsicNamespace(type: string): string {
22 switch (type) {
23 case 'svg':
24 return SVG_NAMESPACE;
@@ -29,7 +29,7 @@ function getIntrinsicNamespace(type: string): string {
29 }
30 }
31
32 -function getChildNamespace(
32 +export function getChildNamespace(
33 parentNamespace: string | null,
34 type: string,
35 ): string {
@@ -44,7 +44,3 @@ function getChildNamespace(
44 // By default, pass namespace below.
45 return parentNamespace;
46 }
47 -
48 -exports.Namespaces = Namespaces;
49 -exports.getIntrinsicNamespace = getIntrinsicNamespace;
50 -exports.getChildNamespace = getChildNamespace;
packages/react-dom/src/shared/DOMProperty.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var invariant = require('fbjs/lib/invariant');
10 +import invariant from 'fbjs/lib/invariant';
11
12 // These attributes should be all lowercase to allow for
13 // case insensitive checks
@@ -262,4 +262,4 @@ var DOMProperty = {
262 injection: DOMPropertyInjection,
263 };
264
265 -module.exports = DOMProperty;
265 +export default DOMProperty;
packages/react-dom/src/shared/HTMLDOMPropertyConfig.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var DOMProperty = require('./DOMProperty');
10 +import DOMProperty from './DOMProperty';
11
12 var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
13 var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
@@ -117,4 +117,4 @@ var HTMLDOMPropertyConfig = {
117 },
118 };
119
120 -module.exports = HTMLDOMPropertyConfig;
120 +export default HTMLDOMPropertyConfig;
packages/react-dom/src/shared/HTMLNodeType.js
+5 -9
@@ -11,12 +11,8 @@
11 * HTML nodeType values that represent the type of the node
12 */
13
14 -var HTMLNodeType = {
15 - ELEMENT_NODE: 1,
16 - TEXT_NODE: 3,
17 - COMMENT_NODE: 8,
18 - DOCUMENT_NODE: 9,
19 - DOCUMENT_FRAGMENT_NODE: 11,
20 -};
21 -
22 -module.exports = HTMLNodeType;
14 +export const ELEMENT_NODE = 1;
15 +export const TEXT_NODE = 3;
16 +export const COMMENT_NODE = 8;
17 +export const DOCUMENT_NODE = 9;
18 +export const DOCUMENT_FRAGMENT_NODE = 11;
packages/react-dom/src/shared/ReactControlledValuePropTypes.js
+3 -3
@@ -7,13 +7,13 @@
7
8 'use strict';
9
10 +import checkPropTypes from 'prop-types/checkPropTypes';
11 +
12 var ReactControlledValuePropTypes = {
13 checkPropTypes: null,
14 };
15
16 if (__DEV__) {
15 - var checkPropTypes = require('prop-types/checkPropTypes');
16 -
17 var hasReadOnlyValue = {
18 button: true,
19 checkbox: true,
@@ -73,4 +73,4 @@ if (__DEV__) {
73 };
74 }
75
76 -module.exports = ReactControlledValuePropTypes;
76 +export default ReactControlledValuePropTypes;
packages/react-dom/src/shared/ReactDOMInjection.js
+3 -3
@@ -7,9 +7,9 @@
7
8 'use strict';
9
10 -var DOMProperty = require('./DOMProperty');
11 -var HTMLDOMPropertyConfig = require('./HTMLDOMPropertyConfig');
12 -var SVGDOMPropertyConfig = require('./SVGDOMPropertyConfig');
10 +import DOMProperty from './DOMProperty';
11 +import HTMLDOMPropertyConfig from './HTMLDOMPropertyConfig';
12 +import SVGDOMPropertyConfig from './SVGDOMPropertyConfig';
13
14 DOMProperty.injection.injectDOMPropertyConfig(HTMLDOMPropertyConfig);
15 DOMProperty.injection.injectDOMPropertyConfig(SVGDOMPropertyConfig);
packages/react-dom/src/shared/ReactDOMInvalidARIAHook.js
+7 -16
@@ -7,8 +7,12 @@
7
8 'use strict';
9
10 -var DOMProperty = require('./DOMProperty');
11 -var isCustomComponent = require('./isCustomComponent');
10 +import warning from 'fbjs/lib/warning';
11 +import {ReactDebugCurrentFrame} from 'shared/ReactGlobalSharedState';
12 +
13 +import DOMProperty from './DOMProperty';
14 +import isCustomComponent from './isCustomComponent';
15 +import validAriaProperties from './validAriaProperties';
16
17 var warnedProperties = {};
18 var rARIA = new RegExp('^(aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$');
@@ -18,13 +22,6 @@ var rARIACamel = new RegExp(
22
23 var hasOwnProperty = Object.prototype.hasOwnProperty;
24
21 -if (__DEV__) {
22 - var warning = require('fbjs/lib/warning');
23 - var {ReactDebugCurrentFrame} = require('shared/ReactGlobalSharedState');
24 -
25 - var validAriaProperties = require('./validAriaProperties');
26 -}
27 -
25 function getStackAddendum() {
26 var stack = ReactDebugCurrentFrame.getStackAddendum();
27 return stack != null ? stack : '';
@@ -131,15 +128,9 @@ function warnInvalidARIAProps(type, props) {
128 }
129 }
130
134 -function validateProperties(type, props) {
131 +export function validateProperties(type, props) {
132 if (isCustomComponent(type, props)) {
133 return;
134 }
135 warnInvalidARIAProps(type, props);
136 }
140 -
141 -var ReactDOMInvalidARIAHook = {
142 - validateProperties,
143 -};
144 -
145 -module.exports = ReactDOMInvalidARIAHook;
packages/react-dom/src/shared/ReactDOMNullInputValuePropHook.js
+3 -11
@@ -7,10 +7,8 @@
7
8 'use strict';
9
10 -if (__DEV__) {
11 - var {ReactDebugCurrentFrame} = require('shared/ReactGlobalSharedState');
12 - var warning = require('fbjs/lib/warning');
13 -}
10 +import {ReactDebugCurrentFrame} from 'shared/ReactGlobalSharedState';
11 +import warning from 'fbjs/lib/warning';
12
13 var didWarnValueNull = false;
14
@@ -19,7 +17,7 @@ function getStackAddendum() {
17 return stack != null ? stack : '';
18 }
19
22 -function validateProperties(type, props) {
20 +export function validateProperties(type, props) {
21 if (type !== 'input' && type !== 'textarea' && type !== 'select') {
22 return;
23 }
@@ -47,9 +45,3 @@ function validateProperties(type, props) {
45 }
46 }
47 }
50 -
51 -var ReactDOMNullInputValuePropHook = {
52 - validateProperties,
53 -};
54 -
55 -module.exports = ReactDOMNullInputValuePropHook;
packages/react-dom/src/shared/ReactDOMUnknownPropertyHook.js
+7 -16
@@ -7,15 +7,13 @@
7
8 'use strict';
9
10 -var EventPluginRegistry = require('events/EventPluginRegistry');
10 +import EventPluginRegistry from 'events/EventPluginRegistry';
11 +import {ReactDebugCurrentFrame} from 'shared/ReactGlobalSharedState';
12 +import warning from 'fbjs/lib/warning';
13
12 -var DOMProperty = require('./DOMProperty');
13 -var isCustomComponent = require('./isCustomComponent');
14 -
15 -if (__DEV__) {
16 - var {ReactDebugCurrentFrame} = require('shared/ReactGlobalSharedState');
17 - var warning = require('fbjs/lib/warning');
18 -}
14 +import DOMProperty from './DOMProperty';
15 +import isCustomComponent from './isCustomComponent';
16 +import possibleStandardNames from './possibleStandardNames';
17
18 function getStackAddendum() {
19 var stack = ReactDebugCurrentFrame.getStackAddendum();
@@ -30,7 +28,6 @@ if (__DEV__) {
28 var rARIACamel = new RegExp(
29 '^(aria)[A-Z][' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$',
30 );
33 - var possibleStandardNames = require('./possibleStandardNames');
31
32 var validateProperty = function(tagName, name, value) {
33 if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) {
@@ -267,15 +264,9 @@ var warnUnknownProperties = function(type, props) {
264 }
265 };
266
270 -function validateProperties(type, props) {
267 +export function validateProperties(type, props) {
268 if (isCustomComponent(type, props)) {
269 return;
270 }
271 warnUnknownProperties(type, props);
272 }
276 -
277 -var ReactDOMUnknownPropertyHook = {
278 - validateProperties,
279 -};
280 -
281 -module.exports = ReactDOMUnknownPropertyHook;
packages/react-dom/src/shared/SVGDOMPropertyConfig.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var DOMProperty = require('./DOMProperty');
10 +import DOMProperty from './DOMProperty';
11
12 var {HAS_STRING_BOOLEAN_VALUE} = DOMProperty.injection;
13
@@ -150,4 +150,4 @@ ATTRS.forEach(original => {
150 SVGDOMPropertyConfig.DOMAttributeNames[reactName] = original;
151 });
152
153 -module.exports = SVGDOMPropertyConfig;
153 +export default SVGDOMPropertyConfig;
packages/react-dom/src/shared/assertValidProps.js
+4 -7
@@ -7,13 +7,10 @@
7
8 'use strict';
9
10 -var invariant = require('fbjs/lib/invariant');
10 +import invariant from 'fbjs/lib/invariant';
11 +import warning from 'fbjs/lib/warning';
12
12 -var voidElementTags = require('./voidElementTags');
13 -
14 -if (__DEV__) {
15 - var warning = require('fbjs/lib/warning');
16 -}
13 +import voidElementTags from './voidElementTags';
14
15 var HTML = '__html';
16
@@ -65,4 +62,4 @@ function assertValidProps(tag: string, props: ?Object, getStack: () => string) {
62 );
63 }
64
68 -module.exports = assertValidProps;
65 +export default assertValidProps;
packages/react-dom/src/shared/checkReact.js
+2 -2
@@ -7,8 +7,8 @@
7 * @flow
8 */
9
10 -var React = require('react');
11 -var invariant = require('fbjs/lib/invariant');
10 +import React from 'react';
11 +import invariant from 'fbjs/lib/invariant';
12
13 invariant(
14 React,
packages/react-dom/src/shared/createMicrosoftUnsafeLocalFunction.js
+1 -1
@@ -24,4 +24,4 @@ var createMicrosoftUnsafeLocalFunction = function(func) {
24 }
25 };
26
27 -module.exports = createMicrosoftUnsafeLocalFunction;
27 +export default createMicrosoftUnsafeLocalFunction;
packages/react-dom/src/shared/dangerousStyleValue.js
+2 -4
@@ -7,9 +7,7 @@
7
8 'use strict';
9
10 -var CSSProperty = require('./CSSProperty');
11 -
12 -var isUnitlessNumber = CSSProperty.isUnitlessNumber;
10 +import {isUnitlessNumber} from './CSSProperty';
11
12 /**
13 * Convert a value into the proper css writable value. The style name `name`
@@ -48,4 +46,4 @@ function dangerousStyleValue(name, value, isCustomProperty) {
46 return ('' + value).trim();
47 }
48
51 -module.exports = dangerousStyleValue;
49 +export default dangerousStyleValue;
packages/react-dom/src/shared/escapeTextContentForBrowser.js
+1 -1
@@ -110,4 +110,4 @@ function escapeTextContentForBrowser(text) {
110 return escapeHtml(text);
111 }
112
113 -module.exports = escapeTextContentForBrowser;
113 +export default escapeTextContentForBrowser;
packages/react-dom/src/shared/isCustomComponent.js
+1 -1
@@ -32,4 +32,4 @@ function isCustomComponent(tagName: string, props: Object) {
32 }
33 }
34
35 -module.exports = isCustomComponent;
35 +export default isCustomComponent;
packages/react-dom/src/shared/omittedCloseTags.js
+1 -1
@@ -29,4 +29,4 @@ var omittedCloseTags = {
29 // NOTE: menuitem's close tag should be omitted, but that causes problems.
30 };
31
32 -module.exports = omittedCloseTags;
32 +export default omittedCloseTags;
packages/react-dom/src/shared/possibleStandardNames.js
+1 -1
@@ -493,4 +493,4 @@ var possibleStandardNames = {
493 zoomandpan: 'zoomAndPan',
494 };
495
496 -module.exports = possibleStandardNames;
496 +export default possibleStandardNames;
packages/react-dom/src/shared/quoteAttributeValueForBrowser.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var escapeTextContentForBrowser = require('./escapeTextContentForBrowser');
10 +import escapeTextContentForBrowser from './escapeTextContentForBrowser';
11
12 /**
13 * Escapes attribute value to prevent scripting attacks.
@@ -19,4 +19,4 @@ function quoteAttributeValueForBrowser(value) {
19 return '"' + escapeTextContentForBrowser(value) + '"';
20 }
21
22 -module.exports = quoteAttributeValueForBrowser;
22 +export default quoteAttributeValueForBrowser;
packages/react-dom/src/shared/validAriaProperties.js
+1 -1
@@ -62,4 +62,4 @@ var ariaProperties = {
62 'aria-setsize': 0,
63 };
64
65 -module.exports = ariaProperties;
65 +export default ariaProperties;
packages/react-dom/src/shared/voidElementTags.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var omittedCloseTags = require('./omittedCloseTags');
10 +import omittedCloseTags from './omittedCloseTags';
11
12 // For HTML, certain tags cannot have children. This has the same purpose as
13 // `omittedCloseTags` except that `menuitem` should still have its closing tag.
@@ -17,4 +17,4 @@ var voidElementTags = {
17 ...omittedCloseTags,
18 };
19
20 -module.exports = voidElementTags;
20 +export default voidElementTags;
packages/react-dom/src/shared/warnValidStyle.js
+4 -5
@@ -7,14 +7,13 @@
7
8 'use strict';
9
10 -var emptyFunction = require('fbjs/lib/emptyFunction');
10 +import emptyFunction from 'fbjs/lib/emptyFunction';
11 +import camelizeStyleName from 'fbjs/lib/camelizeStyleName';
12 +import warning from 'fbjs/lib/warning';
13
14 var warnValidStyle = emptyFunction;
15
16 if (__DEV__) {
15 - var camelizeStyleName = require('fbjs/lib/camelizeStyleName');
16 - var warning = require('fbjs/lib/warning');
17 -
17 // 'msTransform' is correct, but the other prefixes should be capitalized
18 var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
19
@@ -119,4 +118,4 @@ if (__DEV__) {
118 };
119 }
120
122 -module.exports = warnValidStyle;
121 +export default warnValidStyle;
packages/react-dom/src/test-utils/ReactTestUtils.js
+15 -18
@@ -7,15 +7,20 @@
7
8 'use strict';
9
10 -var React = require('react');
11 -var ReactDOM = require('react-dom');
12 -var ReactFiberTreeReflection = require('shared/ReactFiberTreeReflection');
13 -var ReactInstanceMap = require('shared/ReactInstanceMap');
14 -var ReactTypeOfWork = require('shared/ReactTypeOfWork');
15 -var SyntheticEvent = require('events/SyntheticEvent');
16 -var invariant = require('fbjs/lib/invariant');
10 +import React from 'react';
11 +import ReactDOM from 'react-dom';
12 +import {findCurrentFiberUsingSlowPath} from 'shared/ReactFiberTreeReflection';
13 +import * as ReactInstanceMap from 'shared/ReactInstanceMap';
14 +import {
15 + ClassComponent,
16 + FunctionalComponent,
17 + HostComponent,
18 + HostText,
19 +} from 'shared/ReactTypeOfWork';
20 +import SyntheticEvent from 'events/SyntheticEvent';
21 +import invariant from 'fbjs/lib/invariant';
22
18 -var BrowserEventConstants = require('../events/BrowserEventConstants');
23 +import BrowserEventConstants from '../events/BrowserEventConstants';
24
25 var {findDOMNode} = ReactDOM;
26 var {
@@ -28,12 +33,6 @@ var {
33 } = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
34
35 var topLevelTypes = BrowserEventConstants.topLevelTypes;
31 -var {
32 - ClassComponent,
33 - FunctionalComponent,
34 - HostComponent,
35 - HostText,
36 -} = ReactTypeOfWork;
36
37 function Event(suffix) {}
38
@@ -45,9 +44,7 @@ function findAllInRenderedFiberTreeInternal(fiber, test) {
44 if (!fiber) {
45 return [];
46 }
48 - var currentParent = ReactFiberTreeReflection.findCurrentFiberUsingSlowPath(
49 - fiber,
50 - );
47 + var currentParent = findCurrentFiberUsingSlowPath(fiber);
48 if (!currentParent) {
49 return [];
50 }
@@ -478,4 +475,4 @@ Object.keys(topLevelTypes).forEach(function(eventType) {
475 );
476 });
477
481 -module.exports = ReactTestUtils;
478 +export default ReactTestUtils;
packages/react-dom/src/unstable-native-dependencies/ReactDOMUnstableNativeDependencies.js
+8 -12
@@ -5,22 +5,18 @@
5 * LICENSE file in the root directory of this source tree.
6 */
7
8 -const EventPluginUtils = require('events/EventPluginUtils');
9 -const ResponderEventPlugin = require('events/ResponderEventPlugin');
10 -const ResponderTouchHistoryStore = require('events/ResponderTouchHistoryStore');
8 +import ReactDOM from 'react-dom';
9 +import EventPluginUtils from 'events/EventPluginUtils';
10 +import ResponderEventPlugin from 'events/ResponderEventPlugin';
11 +import ResponderTouchHistoryStore from 'events/ResponderTouchHistoryStore';
12
13 // This is used by react-native-web.
13 -const ReactDOMUnstableNativeDependencies = {
14 - injectComponentTree: EventPluginUtils.injection.injectComponentTree,
15 - ResponderEventPlugin,
16 - ResponderTouchHistoryStore,
17 -};
14 +export const injectComponentTree =
15 + EventPluginUtils.injection.injectComponentTree;
16 +export {ResponderEventPlugin, ResponderTouchHistoryStore};
17
18 // Inject react-dom's ComponentTree into this module.
20 -const ReactDOM = require('react-dom');
19 const {
20 ReactDOMComponentTree,
21 } = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
24 -ReactDOMUnstableNativeDependencies.injectComponentTree(ReactDOMComponentTree);
25 -
26 -module.exports = ReactDOMUnstableNativeDependencies;
22 +injectComponentTree(ReactDOMComponentTree);
packages/react-dom/test-utils.js
+7 -1
@@ -9,4 +9,10 @@
9
10 'use strict';
11
12 -module.exports = require('./src/test-utils/ReactTestUtils');
12 +var ReactTestUtils = require('./src/test-utils/ReactTestUtils');
13 +
14 +// TODO: decide on the top-level export form.
15 +// This is hacky but makes it work with both Rollup and Jest.
16 +module.exports = ReactTestUtils.default
17 + ? ReactTestUtils.default
18 + : ReactTestUtils;
packages/react-native-renderer/index.js
+7 -1
@@ -9,4 +9,10 @@
9
10 'use strict';
11
12 -module.exports = require('./src/ReactNativeRenderer');
12 +var ReactNativeRenderer = require('./src/ReactNativeRenderer');
13 +
14 +// TODO: decide on the top-level export form.
15 +// This is hacky but makes it work with both Rollup and Jest.
16 +module.exports = ReactNativeRenderer.default
17 + ? ReactNativeRenderer.default
18 + : ReactNativeRenderer;
packages/react-native-renderer/src/NativeMethodsMixin.js
+9 -9
@@ -16,19 +16,19 @@ import type {
16 ReactNativeBaseComponentViewConfig,
17 } from './ReactNativeTypes';
18
19 -const invariant = require('fbjs/lib/invariant');
19 +import invariant from 'fbjs/lib/invariant';
20 // Modules provided by RN:
21 -const TextInputState = require('TextInputState');
22 -const UIManager = require('UIManager');
21 +import TextInputState from 'TextInputState';
22 +import UIManager from 'UIManager';
23
24 -const ReactNativeAttributePayload = require('./ReactNativeAttributePayload');
25 -const {
24 +import * as ReactNativeAttributePayload from './ReactNativeAttributePayload';
25 +import {
26 mountSafeCallback,
27 throwOnStylesProp,
28 warnForStyleProps,
29 -} = require('./NativeMethodsMixinUtils');
30 -const findNodeHandle = require('./findNodeHandle');
31 -const findNumericNodeHandle = require('./findNumericNodeHandle');
29 +} from './NativeMethodsMixinUtils';
30 +import findNodeHandle from './findNodeHandle';
31 +import findNumericNodeHandle from './findNumericNodeHandle';
32
33 /**
34 * `NativeMethodsMixin` provides methods to access the underlying native
@@ -199,4 +199,4 @@ if (__DEV__) {
199 };
200 }
201
202 -module.exports = NativeMethodsMixin;
202 +export default NativeMethodsMixin;
packages/react-native-renderer/src/NativeMethodsMixinUtils.js
+3 -9
@@ -12,7 +12,7 @@
12 * In the future, we should cleanup callbacks by cancelling them instead of
13 * using this.
14 */
15 -function mountSafeCallback(context: any, callback: ?Function): any {
15 +export function mountSafeCallback(context: any, callback: ?Function): any {
16 return function() {
17 if (!callback) {
18 return undefined;
@@ -36,7 +36,7 @@ function mountSafeCallback(context: any, callback: ?Function): any {
36 };
37 }
38
39 -function throwOnStylesProp(component: any, props: any) {
39 +export function throwOnStylesProp(component: any, props: any) {
40 if (props.styles !== undefined) {
41 var owner = component._owner || null;
42 var name = component.constructor.displayName;
@@ -56,7 +56,7 @@ function throwOnStylesProp(component: any, props: any) {
56 }
57 }
58
59 -function warnForStyleProps(props: any, validAttributes: any) {
59 +export function warnForStyleProps(props: any, validAttributes: any) {
60 for (var key in validAttributes.style) {
61 if (!(validAttributes[key] || props[key] === undefined)) {
62 console.error(
@@ -71,9 +71,3 @@ function warnForStyleProps(props: any, validAttributes: any) {
71 }
72 }
73 }
74 -
75 -module.exports = {
76 - mountSafeCallback,
77 - throwOnStylesProp,
78 - warnForStyleProps,
79 -};
packages/react-native-renderer/src/ReactNativeAttributePayload.js
+25 -29
@@ -9,10 +9,10 @@
9 'use strict';
10
11 // Modules provided by RN:
12 -var deepDiffer = require('deepDiffer');
13 -var flattenStyle = require('flattenStyle');
12 +import deepDiffer from 'deepDiffer';
13 +import flattenStyle from 'flattenStyle';
14
15 -var ReactNativePropRegistry = require('./ReactNativePropRegistry');
15 +import ReactNativePropRegistry from './ReactNativePropRegistry';
16
17 var emptyObject = {};
18
@@ -485,30 +485,26 @@ function clearProperties(
485 return diffProperties(updatePayload, prevProps, emptyObject, validAttributes);
486 }
487
488 -var ReactNativeAttributePayload = {
489 - create: function(
490 - props: Object,
491 - validAttributes: AttributeConfiguration,
492 - ): ?Object {
493 - return addProperties(
494 - null, // updatePayload
495 - props,
496 - validAttributes,
497 - );
498 - },
499 -
500 - diff: function(
501 - prevProps: Object,
502 - nextProps: Object,
503 - validAttributes: AttributeConfiguration,
504 - ): ?Object {
505 - return diffProperties(
506 - null, // updatePayload
507 - prevProps,
508 - nextProps,
509 - validAttributes,
510 - );
511 - },
512 -};
488 +export function create(
489 + props: Object,
490 + validAttributes: AttributeConfiguration,
491 +): ?Object {
492 + return addProperties(
493 + null, // updatePayload
494 + props,
495 + validAttributes,
496 + );
497 +}
498
514 -module.exports = ReactNativeAttributePayload;
499 +export function diff(
500 + prevProps: Object,
501 + nextProps: Object,
502 + validAttributes: AttributeConfiguration,
503 +): ?Object {
504 + return diffProperties(
505 + null, // updatePayload
506 + prevProps,
507 + nextProps,
508 + validAttributes,
509 + );
510 +}
packages/react-native-renderer/src/ReactNativeBridgeEventPlugin.js
+4 -4
@@ -10,9 +10,9 @@
10
11 import type {ReactNativeBaseComponentViewConfig} from './ReactNativeTypes';
12
13 -const EventPropagators = require('events/EventPropagators');
14 -const SyntheticEvent = require('events/SyntheticEvent');
15 -const invariant = require('fbjs/lib/invariant');
13 +import EventPropagators from 'events/EventPropagators';
14 +import SyntheticEvent from 'events/SyntheticEvent';
15 +import invariant from 'fbjs/lib/invariant';
16
17 const customBubblingEventTypes = {};
18 const customDirectEventTypes = {};
@@ -93,4 +93,4 @@ const ReactNativeBridgeEventPlugin = {
93 },
94 };
95
96 -module.exports = ReactNativeBridgeEventPlugin;
96 +export default ReactNativeBridgeEventPlugin;
packages/react-native-renderer/src/ReactNativeComponent.js
+8 -8
@@ -18,15 +18,15 @@ import type {
18 ReactNativeBaseComponentViewConfig,
19 } from './ReactNativeTypes';
20
21 -const React = require('react');
21 +import React from 'react';
22 // Modules provided by RN:
23 -const TextInputState = require('TextInputState');
24 -const UIManager = require('UIManager');
23 +import TextInputState from 'TextInputState';
24 +import UIManager from 'UIManager';
25
26 -const ReactNativeAttributePayload = require('./ReactNativeAttributePayload');
27 -const {mountSafeCallback} = require('./NativeMethodsMixinUtils');
28 -const findNodeHandle = require('./findNodeHandle');
29 -const findNumericNodeHandle = require('./findNumericNodeHandle');
26 +import * as ReactNativeAttributePayload from './ReactNativeAttributePayload';
27 +import {mountSafeCallback} from './NativeMethodsMixinUtils';
28 +import findNodeHandle from './findNodeHandle';
29 +import findNumericNodeHandle from './findNumericNodeHandle';
30
31 /**
32 * Superclass that provides methods to access the underlying native component.
@@ -172,4 +172,4 @@ class ReactNativeComponent<DefaultProps, Props, State>
172 // eslint-disable-next-line no-unused-expressions
173 (ReactNativeComponent.prototype: NativeMethodsMixinType);
174
175 -module.exports = ReactNativeComponent;
175 +export default ReactNativeComponent;
packages/react-native-renderer/src/ReactNativeComponentTree.js
+2 -2
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var invariant = require('fbjs/lib/invariant');
10 +import invariant from 'fbjs/lib/invariant';
11
12 var instanceCache = {};
13 var instanceProps = {};
@@ -49,4 +49,4 @@ var ReactNativeComponentTree = {
49 updateFiberProps,
50 };
51
52 -module.exports = ReactNativeComponentTree;
52 +export default ReactNativeComponentTree;
packages/react-native-renderer/src/ReactNativeEventEmitter.js
+8 -11
@@ -8,17 +8,14 @@
8 */
9 'use strict';
10
11 -var EventPluginHub = require('events/EventPluginHub');
12 -var EventPluginRegistry = require('events/EventPluginRegistry');
13 -var ReactEventEmitterMixin = require('events/ReactEventEmitterMixin');
14 -var ReactGenericBatching = require('events/ReactGenericBatching');
11 +import EventPluginHub from 'events/EventPluginHub';
12 +import EventPluginRegistry from 'events/EventPluginRegistry';
13 +import ReactEventEmitterMixin from 'events/ReactEventEmitterMixin';
14 +import ReactGenericBatching from 'events/ReactGenericBatching';
15 +import warning from 'fbjs/lib/warning';
16
16 -var ReactNativeComponentTree = require('./ReactNativeComponentTree');
17 -var ReactNativeTagHandles = require('./ReactNativeTagHandles');
18 -
19 -if (__DEV__) {
20 - var warning = require('fbjs/lib/warning');
21 -}
17 +import ReactNativeComponentTree from './ReactNativeComponentTree';
18 +import ReactNativeTagHandles from './ReactNativeTagHandles';
19
20 /**
21 * Version of `ReactBrowserEventEmitter` that works on the receiving side of a
@@ -197,4 +194,4 @@ var ReactNativeEventEmitter = {
194 },
195 };
196
200 -module.exports = ReactNativeEventEmitter;
197 +export default ReactNativeEventEmitter;
packages/react-native-renderer/src/ReactNativeEventPluginOrder.js
+1 -1
@@ -13,4 +13,4 @@ var ReactNativeEventPluginOrder = [
13 'ReactNativeBridgeEventPlugin',
14 ];
15
16 -module.exports = ReactNativeEventPluginOrder;
16 +export default ReactNativeEventPluginOrder;
packages/react-native-renderer/src/ReactNativeFiberErrorDialog.js
+2 -4
@@ -12,13 +12,13 @@
12 import type {CapturedError} from 'react-reconciler/src/ReactFiberScheduler';
13
14 // Module provided by RN:
15 -const ExceptionsManager = require('ExceptionsManager');
15 +import ExceptionsManager from 'ExceptionsManager';
16
17 /**
18 * Intercept lifecycle errors and ensure they are shown with the correct stack
19 * trace within the native redbox component.
20 */
21 -function ReactNativeFiberErrorDialog(capturedError: CapturedError): boolean {
21 +export function showDialog(capturedError: CapturedError): boolean {
22 const {componentStack, error} = capturedError;
23
24 let errorToHandle: Error;
@@ -50,5 +50,3 @@ function ReactNativeFiberErrorDialog(capturedError: CapturedError): boolean {
50 // done above by calling ExceptionsManager.
51 return false;
52 }
53 -
54 -module.exports.showDialog = ReactNativeFiberErrorDialog;
packages/react-native-renderer/src/ReactNativeFiberHostComponent.js
+5 -8
@@ -19,14 +19,11 @@ import type {
19 import type {Instance} from './ReactNativeFiberRenderer';
20
21 // Modules provided by RN:
22 -var TextInputState = require('TextInputState');
23 -var UIManager = require('UIManager');
22 +import TextInputState from 'TextInputState';
23 +import UIManager from 'UIManager';
24
25 -var ReactNativeAttributePayload = require('./ReactNativeAttributePayload');
26 -var {
27 - mountSafeCallback,
28 - warnForStyleProps,
29 -} = require('./NativeMethodsMixinUtils');
25 +import * as ReactNativeAttributePayload from './ReactNativeAttributePayload';
26 +import {mountSafeCallback, warnForStyleProps} from './NativeMethodsMixinUtils';
27
28 /**
29 * This component defines the same methods as NativeMethodsMixin but without the
@@ -104,4 +101,4 @@ class ReactNativeFiberHostComponent {
101 // eslint-disable-next-line no-unused-expressions
102 (ReactNativeFiberHostComponent.prototype: NativeMethodsMixinType);
103
107 -module.exports = ReactNativeFiberHostComponent;
104 +export default ReactNativeFiberHostComponent;
packages/react-native-renderer/src/ReactNativeFiberInspector.js
+13 -14
@@ -10,19 +10,20 @@
10
11 import type {Fiber} from 'react-reconciler/src/ReactFiber';
12
13 -const ReactFiberTreeReflection = require('shared/ReactFiberTreeReflection');
14 -const getComponentName = require('shared/getComponentName');
15 -const ReactTypeOfWork = require('shared/ReactTypeOfWork');
16 -const emptyObject = require('fbjs/lib/emptyObject');
17 -const invariant = require('fbjs/lib/invariant');
18 -const {findCurrentFiberUsingSlowPath} = ReactFiberTreeReflection;
19 -const {HostComponent} = ReactTypeOfWork;
13 +import {
14 + findCurrentHostFiber,
15 + findCurrentFiberUsingSlowPath,
16 +} from 'shared/ReactFiberTreeReflection';
17 +import getComponentName from 'shared/getComponentName';
18 +import {HostComponent} from 'shared/ReactTypeOfWork';
19 +import emptyObject from 'fbjs/lib/emptyObject';
20 +import invariant from 'fbjs/lib/invariant';
21 // Module provided by RN:
21 -const UIManager = require('UIManager');
22 +import UIManager from 'UIManager';
23
23 -const ReactNativeComponentTree = require('./ReactNativeComponentTree');
24 -const {getClosestInstanceFromNode} = ReactNativeComponentTree;
24 +import ReactNativeComponentTree from './ReactNativeComponentTree';
25
26 +const {getClosestInstanceFromNode} = ReactNativeComponentTree;
27 let getInspectorDataForViewTag;
28
29 if (__DEV__) {
@@ -51,7 +52,7 @@ if (__DEV__) {
52 };
53
54 var getHostProps = function(fiber) {
54 - const host = ReactFiberTreeReflection.findCurrentHostFiber(fiber);
55 + const host = findCurrentHostFiber(fiber);
56 if (host) {
57 return host.memoizedProps || emptyObject;
58 }
@@ -123,6 +124,4 @@ if (__DEV__) {
124 };
125 }
126
126 -module.exports = {
127 - getInspectorDataForViewTag,
128 -};
127 +export {getInspectorDataForViewTag};
packages/react-native-renderer/src/ReactNativeFiberRenderer.js
+16 -13
@@ -11,19 +11,22 @@
11
12 import type {ReactNativeBaseComponentViewConfig} from './ReactNativeTypes';
13
14 -const ReactFiberReconciler = require('react-reconciler');
15 -const emptyObject = require('fbjs/lib/emptyObject');
16 -const invariant = require('fbjs/lib/invariant');
14 +import ReactFiberReconciler from 'react-reconciler';
15 +import emptyObject from 'fbjs/lib/emptyObject';
16 +import invariant from 'fbjs/lib/invariant';
17 // Modules provided by RN:
18 -const UIManager = require('UIManager');
19 -const deepFreezeAndThrowOnMutationInDev = require('deepFreezeAndThrowOnMutationInDev');
20 -
21 -const ReactNativeAttributePayload = require('./ReactNativeAttributePayload');
22 -const ReactNativeComponentTree = require('./ReactNativeComponentTree');
23 -const ReactNativeFiberHostComponent = require('./ReactNativeFiberHostComponent');
24 -const ReactNativeFrameScheduling = require('./ReactNativeFrameScheduling');
25 -const ReactNativeTagHandles = require('./ReactNativeTagHandles');
26 -const ReactNativeViewConfigRegistry = require('./ReactNativeViewConfigRegistry');
18 +import UIManager from 'UIManager';
19 +import deepFreezeAndThrowOnMutationInDev
20 + from 'deepFreezeAndThrowOnMutationInDev';
21 +
22 +import * as ReactNativeViewConfigRegistry
23 + from './ReactNativeViewConfigRegistry';
24 +import * as ReactNativeAttributePayload from './ReactNativeAttributePayload';
25 +import ReactNativeComponentTree from './ReactNativeComponentTree';
26 +import ReactNativeFiberHostComponent from './ReactNativeFiberHostComponent';
27 +import * as ReactNativeFrameScheduling from './ReactNativeFrameScheduling';
28 +import ReactNativeTagHandles from './ReactNativeTagHandles';
29 +
30 const {
31 precacheFiberNode,
32 uncacheFiberNode,
@@ -389,4 +392,4 @@ const NativeRenderer = ReactFiberReconciler({
392 },
393 });
394
392 -module.exports = NativeRenderer;
395 +export default NativeRenderer;
packages/react-native-renderer/src/ReactNativeFrameScheduling.js
+1 -4
@@ -59,7 +59,4 @@ function scheduleDeferredCallback(callback: Callback): number {
59 return 0;
60 }
61
62 -module.exports = {
63 - now,
64 - scheduleDeferredCallback,
65 -};
62 +export {now, scheduleDeferredCallback};
packages/react-native-renderer/src/ReactNativeGlobalResponderHandler.js
+2 -2
@@ -7,7 +7,7 @@
7 'use strict';
8
9 // Module provided by RN:
10 -var UIManager = require('UIManager');
10 +import UIManager from 'UIManager';
11
12 var ReactNativeGlobalResponderHandler = {
13 onChange: function(from, to, blockNativeResponder) {
@@ -20,4 +20,4 @@ var ReactNativeGlobalResponderHandler = {
20 },
21 };
22
23 -module.exports = ReactNativeGlobalResponderHandler;
23 +export default ReactNativeGlobalResponderHandler;
packages/react-native-renderer/src/ReactNativeInjection.js
+11 -10
@@ -15,19 +15,20 @@
15 * TODO: require this in packager, not in React #10932517
16 */
17 // Module provided by RN:
18 -require('InitializeCore');
18 +import 'InitializeCore';
19
20 -var EventPluginHub = require('events/EventPluginHub');
21 -var EventPluginUtils = require('events/EventPluginUtils');
22 -var ResponderEventPlugin = require('events/ResponderEventPlugin');
20 +import EventPluginHub from 'events/EventPluginHub';
21 +import EventPluginUtils from 'events/EventPluginUtils';
22 +import ResponderEventPlugin from 'events/ResponderEventPlugin';
23 // Module provided by RN:
24 -var RCTEventEmitter = require('RCTEventEmitter');
24 +import RCTEventEmitter from 'RCTEventEmitter';
25
26 -var ReactNativeBridgeEventPlugin = require('./ReactNativeBridgeEventPlugin');
27 -var ReactNativeComponentTree = require('./ReactNativeComponentTree');
28 -var ReactNativeEventEmitter = require('./ReactNativeEventEmitter');
29 -var ReactNativeEventPluginOrder = require('./ReactNativeEventPluginOrder');
30 -var ReactNativeGlobalResponderHandler = require('./ReactNativeGlobalResponderHandler');
26 +import ReactNativeBridgeEventPlugin from './ReactNativeBridgeEventPlugin';
27 +import ReactNativeComponentTree from './ReactNativeComponentTree';
28 +import ReactNativeEventEmitter from './ReactNativeEventEmitter';
29 +import ReactNativeEventPluginOrder from './ReactNativeEventPluginOrder';
30 +import ReactNativeGlobalResponderHandler
31 + from './ReactNativeGlobalResponderHandler';
32
33 /**
34 * Register the event emitter with the native bridge
packages/react-native-renderer/src/ReactNativePropRegistry.js
+1 -1
@@ -38,4 +38,4 @@ class ReactNativePropRegistry {
38 }
39 }
40
41 -module.exports = ReactNativePropRegistry;
41 +export default ReactNativePropRegistry;
packages/react-native-renderer/src/ReactNativeRenderer.js
+34 -30
@@ -12,24 +12,31 @@
12 import type {ReactNativeType} from './ReactNativeTypes';
13 import type {ReactNodeList} from 'shared/ReactTypes';
14
15 -require('./ReactNativeInjection');
15 +import './ReactNativeInjection';
16
17 // TODO: direct imports like some-package/src/* are bad. Fix me.
18 -const ReactFiberErrorLogger = require('react-reconciler/src/ReactFiberErrorLogger');
19 -const ReactPortal = require('react-reconciler/src/ReactPortal');
20 -const {
21 - injectInternals,
22 -} = require('react-reconciler/src/ReactFiberDevToolsHook');
23 -const ReactGenericBatching = require('events/ReactGenericBatching');
24 -const ReactVersion = require('shared/ReactVersion');
18 +import * as ReactFiberErrorLogger
19 + from 'react-reconciler/src/ReactFiberErrorLogger';
20 +import * as ReactPortal from 'react-reconciler/src/ReactPortal';
21 +import {injectInternals} from 'react-reconciler/src/ReactFiberDevToolsHook';
22 +import ReactGenericBatching from 'events/ReactGenericBatching';
23 +import TouchHistoryMath from 'events/TouchHistoryMath';
24 +import * as ReactGlobalSharedState from 'shared/ReactGlobalSharedState';
25 +import ReactVersion from 'shared/ReactVersion';
26 // Module provided by RN:
26 -const UIManager = require('UIManager');
27 -
28 -const ReactNativeFiberErrorDialog = require('./ReactNativeFiberErrorDialog');
29 -const ReactNativeComponentTree = require('./ReactNativeComponentTree');
30 -const ReactNativeFiberRenderer = require('./ReactNativeFiberRenderer');
31 -const ReactNativeFiberInspector = require('./ReactNativeFiberInspector');
32 -const findNumericNodeHandle = require('./findNumericNodeHandle');
27 +import UIManager from 'UIManager';
28 +
29 +import {showDialog} from './ReactNativeFiberErrorDialog';
30 +import NativeMethodsMixin from './NativeMethodsMixin';
31 +import ReactNativeBridgeEventPlugin from './ReactNativeBridgeEventPlugin';
32 +import ReactNativeComponent from './ReactNativeComponent';
33 +import ReactNativeComponentTree from './ReactNativeComponentTree';
34 +import ReactNativeFiberRenderer from './ReactNativeFiberRenderer';
35 +import ReactNativePropRegistry from './ReactNativePropRegistry';
36 +import {getInspectorDataForViewTag} from './ReactNativeFiberInspector';
37 +import createReactNativeComponentClass from './createReactNativeComponentClass';
38 +import findNumericNodeHandle from './findNumericNodeHandle';
39 +import takeSnapshot from './takeSnapshot';
40
41 ReactGenericBatching.injection.injectFiberBatchedUpdates(
42 ReactNativeFiberRenderer.batchedUpdates,
@@ -39,12 +46,10 @@ const roots = new Map();
46
47 // Intercept lifecycle errors and ensure they are shown with the correct stack
48 // trace within the native redbox component.
42 -ReactFiberErrorLogger.injection.injectDialog(
43 - ReactNativeFiberErrorDialog.showDialog,
44 -);
49 +ReactFiberErrorLogger.injection.injectDialog(showDialog);
50
51 const ReactNativeRenderer: ReactNativeType = {
47 - NativeComponent: require('./ReactNativeComponent'),
52 + NativeComponent: ReactNativeComponent,
53
54 findNodeHandle: findNumericNodeHandle,
55
@@ -93,16 +98,15 @@ const ReactNativeRenderer: ReactNativeType = {
98
99 __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
100 // Used as a mixin in many createClass-based components
96 - NativeMethodsMixin: require('./NativeMethodsMixin'),
97 -
101 + NativeMethodsMixin,
102 // Used by react-native-github/Libraries/ components
99 - ReactNativeBridgeEventPlugin: require('./ReactNativeBridgeEventPlugin'), // requireNativeComponent
100 - ReactGlobalSharedState: require('shared/ReactGlobalSharedState'), // Systrace
101 - ReactNativeComponentTree: require('./ReactNativeComponentTree'), // InspectorUtils, ScrollResponder
102 - ReactNativePropRegistry: require('./ReactNativePropRegistry'), // flattenStyle, Stylesheet
103 - TouchHistoryMath: require('events/TouchHistoryMath'), // PanResponder
104 - createReactNativeComponentClass: require('./createReactNativeComponentClass'), // RCTText, RCTView, ReactNativeART
105 - takeSnapshot: require('./takeSnapshot'), // react-native-implementation
103 + ReactNativeBridgeEventPlugin, // requireNativeComponent
104 + ReactGlobalSharedState, // Systrace
105 + ReactNativeComponentTree, // InspectorUtils, ScrollResponder
106 + ReactNativePropRegistry, // flattenStyle, Stylesheet
107 + TouchHistoryMath, // PanResponder
108 + createReactNativeComponentClass, // RCTText, RCTView, ReactNativeART
109 + takeSnapshot, // react-native-implementation
110 },
111 };
112
@@ -131,11 +135,11 @@ if (__DEV__) {
135 injectInternals({
136 findFiberByHostInstance: ReactNativeComponentTree.getClosestInstanceFromNode,
137 findHostInstanceByFiber: ReactNativeFiberRenderer.findHostInstance,
134 - getInspectorDataForViewTag: ReactNativeFiberInspector.getInspectorDataForViewTag,
138 + getInspectorDataForViewTag: getInspectorDataForViewTag,
139 // This is an enum because we may add more (e.g. profiler build)
140 bundleType: __DEV__ ? 1 : 0,
141 version: ReactVersion,
142 rendererPackageName: 'react-native-renderer',
143 });
144
141 -module.exports = ReactNativeRenderer;
145 +export default ReactNativeRenderer;
packages/react-native-renderer/src/ReactNativeTagHandles.js
+2 -2
@@ -8,7 +8,7 @@
8 */
9 'use strict';
10
11 -var invariant = require('fbjs/lib/invariant');
11 +import invariant from 'fbjs/lib/invariant';
12
13 /**
14 * Keeps track of allocating and associating native "tags" which are numeric,
@@ -52,4 +52,4 @@ var ReactNativeTagHandles = {
52 },
53 };
54
55 -module.exports = ReactNativeTagHandles;
55 +export default ReactNativeTagHandles;
packages/react-native-renderer/src/ReactNativeViewConfigRegistry.js
+30 -34
@@ -14,51 +14,47 @@ import type {
14 ViewConfigGetter,
15 } from './ReactNativeTypes';
16
17 -const invariant = require('fbjs/lib/invariant');
17 +import invariant from 'fbjs/lib/invariant';
18
19 const viewConfigCallbacks = new Map();
20 const viewConfigs = new Map();
21
22 -const ReactNativeViewConfigRegistry = {
23 - /**
22 +/**
23 * Registers a native view/component by name.
24 * A callback is provided to load the view config from UIManager.
25 * The callback is deferred until the view is actually rendered.
26 * This is done to avoid causing Prepack deopts.
27 */
29 - register(name: string, callback: ViewConfigGetter): string {
30 - invariant(
31 - !viewConfigCallbacks.has(name),
32 - 'Tried to register two views with the same name %s',
33 - name,
34 - );
35 - viewConfigCallbacks.set(name, callback);
36 - return name;
37 - },
28 +export function register(name: string, callback: ViewConfigGetter): string {
29 + invariant(
30 + !viewConfigCallbacks.has(name),
31 + 'Tried to register two views with the same name %s',
32 + name,
33 + );
34 + viewConfigCallbacks.set(name, callback);
35 + return name;
36 +}
37
39 - /**
38 +/**
39 * Retrieves a config for the specified view.
40 * If this is the first time the view has been used,
41 * This configuration will be lazy-loaded from UIManager.
42 */
44 - get(name: string): ReactNativeBaseComponentViewConfig {
45 - let viewConfig;
46 - if (!viewConfigs.has(name)) {
47 - const callback = viewConfigCallbacks.get(name);
48 - invariant(
49 - typeof callback === 'function',
50 - 'View config not found for name %s',
51 - name,
52 - );
53 - viewConfigCallbacks.set(name, null);
54 - viewConfig = callback();
55 - viewConfigs.set(name, viewConfig);
56 - } else {
57 - viewConfig = viewConfigs.get(name);
58 - }
59 - invariant(viewConfig, 'View config not found for name %s', name);
60 - return viewConfig;
61 - },
62 -};
63 -
64 -module.exports = ReactNativeViewConfigRegistry;
43 +export function get(name: string): ReactNativeBaseComponentViewConfig {
44 + let viewConfig;
45 + if (!viewConfigs.has(name)) {
46 + const callback = viewConfigCallbacks.get(name);
47 + invariant(
48 + typeof callback === 'function',
49 + 'View config not found for name %s',
50 + name,
51 + );
52 + viewConfigCallbacks.set(name, null);
53 + viewConfig = callback();
54 + viewConfigs.set(name, viewConfig);
55 + } else {
56 + viewConfig = viewConfigs.get(name);
57 + }
58 + invariant(viewConfig, 'View config not found for name %s', name);
59 + return viewConfig;
60 +}
packages/react-native-renderer/src/__mocks__/UIManager.js
+1 -1
@@ -9,7 +9,7 @@
9
10 // Mock of the Native Hooks
11
12 -const ReactNativeTagHandles = require('../ReactNativeTagHandles');
12 +const ReactNativeTagHandles = require('../ReactNativeTagHandles').default;
13 const invariant = require('fbjs/lib/invariant');
14
15 // Map of viewTag -> {children: [childTag], parent: ?parentTag}
packages/react-native-renderer/src/__mocks__/View.js
+2 -1
@@ -7,7 +7,8 @@
7
8 'use strict';
9
10 -var createReactNativeComponentClass = require('../createReactNativeComponentClass');
10 +var createReactNativeComponentClass = require('../createReactNativeComponentClass')
11 + .default;
12
13 var View = createReactNativeComponentClass({
14 validAttributes: {},
packages/react-native-renderer/src/__tests__/ReactNativeAttributePayload-test.js
+1 -1
@@ -8,7 +8,7 @@
8 'use strict';
9
10 var ReactNativeAttributePayload = require('../ReactNativeAttributePayload');
11 -var ReactNativePropRegistry = require('../ReactNativePropRegistry');
11 +var ReactNativePropRegistry = require('../ReactNativePropRegistry').default;
12
13 var diff = ReactNativeAttributePayload.diff;
14
packages/react-native-renderer/src/__tests__/ReactNativeEvents-test.js
+5 -3
@@ -69,10 +69,12 @@ beforeEach(() => {
69 RCTEventEmitter = require('RCTEventEmitter');
70 React = require('react');
71 ReactNative = require('react-native-renderer');
72 - ReactNativeBridgeEventPlugin = require('../ReactNativeBridgeEventPlugin');
73 - ResponderEventPlugin = require('events/ResponderEventPlugin');
72 + ReactNativeBridgeEventPlugin = require('../ReactNativeBridgeEventPlugin')
73 + .default;
74 + ResponderEventPlugin = require('events/ResponderEventPlugin').default;
75 UIManager = require('UIManager');
75 - createReactNativeComponentClass = require('../createReactNativeComponentClass');
76 + createReactNativeComponentClass = require('../createReactNativeComponentClass')
77 + .default;
78 });
79
80 it('fails if unknown/unsupported event types are dispatched', () => {
packages/react-native-renderer/src/__tests__/ReactNativeMount-test.js
+2 -1
@@ -21,7 +21,8 @@ describe('ReactNative', () => {
21 React = require('react');
22 ReactNative = require('react-native-renderer');
23 UIManager = require('UIManager');
24 - createReactNativeComponentClass = require('../createReactNativeComponentClass');
24 + createReactNativeComponentClass = require('../createReactNativeComponentClass')
25 + .default;
26 });
27
28 it('should be able to create and render a native component', () => {
packages/react-native-renderer/src/__tests__/createReactNativeComponentClass-test.js
+2 -1
@@ -17,7 +17,8 @@ describe('createReactNativeComponentClass', () => {
17 beforeEach(() => {
18 jest.resetModules();
19
20 - createReactNativeComponentClass = require('../createReactNativeComponentClass');
20 + createReactNativeComponentClass = require('../createReactNativeComponentClass')
21 + .default;
22 React = require('react');
23 ReactNative = require('react-native-renderer');
24 });
packages/react-native-renderer/src/createReactNativeComponentClass.js
+3 -3
@@ -11,7 +11,7 @@
11
12 import type {ViewConfigGetter} from './ReactNativeTypes';
13
14 -const ReactNativeViewConfigRegistry = require('./ReactNativeViewConfigRegistry');
14 +import {register} from './ReactNativeViewConfigRegistry';
15
16 /**
17 * Creates a renderable ReactNative host component.
@@ -25,7 +25,7 @@ const createReactNativeComponentClass = function(
25 name: string,
26 callback: ViewConfigGetter,
27 ): string {
28 - return ReactNativeViewConfigRegistry.register(name, callback);
28 + return register(name, callback);
29 };
30
31 -module.exports = createReactNativeComponentClass;
31 +export default createReactNativeComponentClass;
packages/react-native-renderer/src/findNodeHandle.js
+7 -10
@@ -11,16 +11,13 @@
11
12 import type {Fiber} from 'react-reconciler/src/ReactFiber';
13
14 -var ReactInstanceMap = require('shared/ReactInstanceMap');
15 -var {ReactCurrentOwner} = require('shared/ReactGlobalSharedState');
16 -var getComponentName = require('shared/getComponentName');
17 -var invariant = require('fbjs/lib/invariant');
14 +import * as ReactInstanceMap from 'shared/ReactInstanceMap';
15 +import {ReactCurrentOwner} from 'shared/ReactGlobalSharedState';
16 +import getComponentName from 'shared/getComponentName';
17 +import invariant from 'fbjs/lib/invariant';
18 +import warning from 'fbjs/lib/warning';
19
19 -var ReactNativeFiberRenderer = require('./ReactNativeFiberRenderer');
20 -
21 -if (__DEV__) {
22 - var warning = require('fbjs/lib/warning');
23 -}
20 +import ReactNativeFiberRenderer from './ReactNativeFiberRenderer';
21
22 /**
23 * ReactNative vs ReactWeb
@@ -110,4 +107,4 @@ function findNodeHandle(componentOrHandle: any): any {
107 }
108 }
109
113 -module.exports = findNodeHandle;
110 +export default findNodeHandle;
packages/react-native-renderer/src/findNumericNodeHandle.js
+3 -3
@@ -8,14 +8,14 @@
8 */
9 'use strict';
10
11 -var findNodeHandle = require('./findNodeHandle');
11 +import findNodeHandle from './findNodeHandle';
12
13 /**
14 * External users of findNodeHandle() expect the host tag number return type.
15 * The injected findNodeHandle() strategy returns the instance wrapper though.
16 * See NativeMethodsMixin#setNativeProps for more info on why this is done.
17 */
18 -module.exports = function findNumericNodeHandleFiber(
18 +export default function findNumericNodeHandleFiber(
19 componentOrHandle: any,
20 ): ?number {
21 const instance: any = findNodeHandle(componentOrHandle);
@@ -23,4 +23,4 @@ module.exports = function findNumericNodeHandleFiber(
23 return instance;
24 }
25 return instance._nativeTag;
26 -};
26 +}
packages/react-native-renderer/src/takeSnapshot.js
+3 -5
@@ -9,9 +9,9 @@
9 'use strict';
10
11 // Module provided by RN:
12 -const UIManager = require('UIManager');
12 +import UIManager from 'UIManager';
13
14 -const findNumericNodeHandle = require('./findNumericNodeHandle');
14 +import findNumericNodeHandle from './findNumericNodeHandle';
15
16 /**
17 * Capture an image of the screen, window or an individual view. The image
@@ -30,7 +30,7 @@ const findNumericNodeHandle = require('./findNumericNodeHandle');
30 * Returns a Promise.
31 * @platform ios
32 */
33 -function takeSnapshot(
33 +export default function takeSnapshot(
34 view?: 'window' | React$Element<any> | number,
35 options?: {
36 width?: number,
@@ -47,5 +47,3 @@ function takeSnapshot(
47 // prevent accidental backwards-incompatible usage.
48 return UIManager.__takeSnapshot(view, options);
49 }
50 -
51 -module.exports = takeSnapshot;
packages/react-noop-renderer/index.js
+5 -1
@@ -9,4 +9,8 @@
9
10 'use strict';
11
12 -module.exports = require('./src/ReactNoop');
12 +var ReactNoop = require('./src/ReactNoop');
13 +
14 +// TODO: decide on the top-level export form.
15 +// This is hacky but makes it work with both Rollup and Jest.
16 +module.exports = ReactNoop.default ? ReactNoop.default : ReactNoop;
packages/react-noop-renderer/src/ReactNoop.js
+8 -8
@@ -20,12 +20,13 @@ import type {Fiber} from 'react-reconciler/src/ReactFiber';
20 import type {UpdateQueue} from 'react-reconciler/src/ReactFiberUpdateQueue';
21
22 // TODO: direct imports like some-package/src/* are bad. Fix me.
23 -var ReactFiberInstrumentation = require('react-reconciler/src/ReactFiberInstrumentation');
24 -var ReactFiberReconciler = require('react-reconciler');
25 -var ReactFeatureFlags = require('shared/ReactFeatureFlags');
26 -var ReactInstanceMap = require('shared/ReactInstanceMap');
27 -var emptyObject = require('fbjs/lib/emptyObject');
28 -var expect = require('expect');
23 +import ReactFiberInstrumentation
24 + from 'react-reconciler/src/ReactFiberInstrumentation';
25 +import ReactFiberReconciler from 'react-reconciler';
26 +import ReactFeatureFlags from 'shared/ReactFeatureFlags';
27 +import * as ReactInstanceMap from 'shared/ReactInstanceMap';
28 +import emptyObject from 'fbjs/lib/emptyObject';
29 +import expect from 'expect';
30
31 const UPDATE_SIGNAL = {};
32
@@ -558,9 +559,8 @@ var ReactNoop = {
559
560 __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
561 // Private. Used only by fixtures/fiber-debugger.
561 - // (To be fair, it's the only place where `react-noop-renderer` package is used at all.)
562 ReactFiberInstrumentation,
563 },
564 };
565
566 -module.exports = ReactNoop;
566 +export default ReactNoop;
packages/react-reconciler/index.js
+7 -1
@@ -16,4 +16,10 @@ export type {
16 Reconciler,
17 } from './src/ReactFiberReconciler';
18
19 -module.exports = require('./src/ReactFiberReconciler');
19 +var ReactFiberReconciler = require('./src/ReactFiberReconciler');
20 +
21 +// TODO: decide on the top-level export form.
22 +// This is hacky but makes it work with both Rollup and Jest.
23 +module.exports = ReactFiberReconciler.default
24 + ? ReactFiberReconciler.default
25 + : ReactFiberReconciler;
packages/react-reconciler/src/ReactChildFiber.js
+32 -37
@@ -16,19 +16,36 @@ import type {
16 ExpirationTime,
17 } from 'react-reconciler/src/ReactFiberExpirationTime';
18
19 -var ReactTypeOfSideEffect = require('shared/ReactTypeOfSideEffect');
20 -var ReactTypeOfWork = require('shared/ReactTypeOfWork');
21 -var ReactFeatureFlags = require('shared/ReactFeatureFlags');
22 -var emptyObject = require('fbjs/lib/emptyObject');
23 -var invariant = require('fbjs/lib/invariant');
24 -var {REACT_PORTAL_TYPE} = require('./ReactPortal');
25 -var ReactFiber = require('./ReactFiber');
19 +import ReactFeatureFlags from 'shared/ReactFeatureFlags';
20 +import {NoEffect, Placement, Deletion} from 'shared/ReactTypeOfSideEffect';
21 +import {
22 + FunctionalComponent,
23 + ClassComponent,
24 + HostText,
25 + HostPortal,
26 + CallComponent,
27 + ReturnComponent,
28 + Fragment,
29 +} from 'shared/ReactTypeOfWork';
30 +import emptyObject from 'fbjs/lib/emptyObject';
31 +import invariant from 'fbjs/lib/invariant';
32 +import warning from 'fbjs/lib/warning';
33
27 -if (__DEV__) {
28 - var warning = require('fbjs/lib/warning');
34 +import {REACT_PORTAL_TYPE} from './ReactPortal';
35 +import {
36 + createWorkInProgress,
37 + createFiberFromElement,
38 + createFiberFromFragment,
39 + createFiberFromText,
40 + createFiberFromCall,
41 + createFiberFromReturn,
42 + createFiberFromPortal,
43 +} from './ReactFiber';
44 +import ReactDebugCurrentFiber from './ReactDebugCurrentFiber';
45
30 - var {getCurrentFiberStackAddendum} = require('./ReactDebugCurrentFiber');
46 +const {getCurrentFiberStackAddendum} = ReactDebugCurrentFiber;
47
48 +if (__DEV__) {
49 var didWarnAboutMaps = false;
50 /**
51 * Warn if there's no key explicitly set on dynamic arrays of children or
@@ -72,30 +89,8 @@ if (__DEV__) {
89 };
90 }
91
75 -const {
76 - createWorkInProgress,
77 - createFiberFromElement,
78 - createFiberFromFragment,
79 - createFiberFromText,
80 - createFiberFromCall,
81 - createFiberFromReturn,
82 - createFiberFromPortal,
83 -} = ReactFiber;
84 -
92 const isArray = Array.isArray;
93
87 -const {
88 - FunctionalComponent,
89 - ClassComponent,
90 - HostText,
91 - HostPortal,
92 - CallComponent,
93 - ReturnComponent,
94 - Fragment,
95 -} = ReactTypeOfWork;
96 -
97 -const {NoEffect, Placement, Deletion} = ReactTypeOfSideEffect;
98 -
94 const ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
95 const FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
96
@@ -1562,13 +1557,13 @@ function ChildReconciler(shouldClone, shouldTrackSideEffects) {
1557 return reconcileChildFibers;
1558 }
1559
1565 -exports.reconcileChildFibers = ChildReconciler(true, true);
1560 +export const reconcileChildFibers = ChildReconciler(true, true);
1561
1567 -exports.reconcileChildFibersInPlace = ChildReconciler(false, true);
1562 +export const reconcileChildFibersInPlace = ChildReconciler(false, true);
1563
1569 -exports.mountChildFibersInPlace = ChildReconciler(false, false);
1564 +export const mountChildFibersInPlace = ChildReconciler(false, false);
1565
1571 -exports.cloneChildFibers = function(
1566 +export function cloneChildFibers(
1567 current: Fiber | null,
1568 workInProgress: Fiber,
1569 ): void {
@@ -1600,4 +1595,4 @@ exports.cloneChildFibers = function(
1595 newChild.return = workInProgress;
1596 }
1597 newChild.sibling = null;
1603 -};
1598 +}
packages/react-reconciler/src/ReactDebugCurrentFiber.js
+6 -9
@@ -9,14 +9,11 @@
9
10 'use strict';
11
12 -var {ReactDebugCurrentFrame} = require('shared/ReactGlobalSharedState');
13 -
14 -if (__DEV__) {
15 - var getComponentName = require('shared/getComponentName');
16 - var {
17 - getStackAddendumByWorkInProgressFiber,
18 - } = require('shared/ReactFiberComponentTreeHook');
19 -}
12 +import {ReactDebugCurrentFrame} from 'shared/ReactGlobalSharedState';
13 +import {
14 + getStackAddendumByWorkInProgressFiber,
15 +} from 'shared/ReactFiberComponentTreeHook';
16 +import getComponentName from 'shared/getComponentName';
17
18 import type {Fiber} from './ReactFiber';
19
@@ -75,4 +72,4 @@ var ReactDebugCurrentFiber = {
72 getCurrentFiberStackAddendum,
73 };
74
78 -module.exports = ReactDebugCurrentFiber;
75 +export default ReactDebugCurrentFiber;
packages/react-reconciler/src/ReactDebugFiberPerf.js
+14 -12
@@ -9,8 +9,18 @@
9
10 import type {Fiber} from './ReactFiber';
11
12 +import getComponentName from 'shared/getComponentName';
13 +import {
14 + HostRoot,
15 + HostComponent,
16 + HostText,
17 + HostPortal,
18 + ReturnComponent,
19 + Fragment,
20 +} from 'shared/ReactTypeOfWork';
21 +
22 // Trust the developer to only use this with a __DEV__ check
13 -let ReactDebugFiberPerf = ((null: any): typeof ReactDebugFiberPerf);
23 +let ReactDebugFiberPerf = (({}: any): typeof ReactDebugFiberPerf);
24
25 type MeasurementPhase =
26 | 'componentWillMount'
@@ -23,16 +33,6 @@ type MeasurementPhase =
33 | 'getChildContext';
34
35 if (__DEV__) {
26 - const getComponentName = require('shared/getComponentName');
27 - const {
28 - HostRoot,
29 - HostComponent,
30 - HostText,
31 - HostPortal,
32 - ReturnComponent,
33 - Fragment,
34 - } = require('shared/ReactTypeOfWork');
35 -
36 // Prefix measurements so that it's possible to filter them.
37 // Longer prefixes are hard to read in DevTools.
38 const reactEmoji = '\u269B';
@@ -408,4 +408,6 @@ if (__DEV__) {
408 };
409 }
410
411 -module.exports = ReactDebugFiberPerf;
411 +// TODO: convert to named exports
412 +// if this doesn't inflate the bundle.
413 +export default ReactDebugFiberPerf;
packages/react-reconciler/src/ReactFiber.js
+24 -27
@@ -21,9 +21,9 @@ import type {TypeOfSideEffect} from 'shared/ReactTypeOfSideEffect';
21 import type {ExpirationTime} from './ReactFiberExpirationTime';
22 import type {UpdateQueue} from './ReactFiberUpdateQueue';
23
24 -var invariant = require('fbjs/lib/invariant');
25 -var {NoEffect} = require('shared/ReactTypeOfSideEffect');
26 -var {
24 +import invariant from 'fbjs/lib/invariant';
25 +import {NoEffect} from 'shared/ReactTypeOfSideEffect';
26 +import {
27 IndeterminateComponent,
28 ClassComponent,
29 HostRoot,
@@ -33,14 +33,13 @@ var {
33 CallComponent,
34 ReturnComponent,
35 Fragment,
36 -} = require('shared/ReactTypeOfWork');
36 +} from 'shared/ReactTypeOfWork';
37 +import getComponentName from 'shared/getComponentName';
38
38 -var {NoWork} = require('./ReactFiberExpirationTime');
39 -var {NoContext} = require('./ReactTypeOfInternalContext');
39 +import {NoWork} from './ReactFiberExpirationTime';
40 +import {NoContext} from './ReactTypeOfInternalContext';
41
42 if (__DEV__) {
42 - var getComponentName = require('shared/getComponentName');
43 -
43 var hasBadMapPolyfill = false;
44 try {
45 const nonExtensibleObject = Object.preventExtensions({});
@@ -228,7 +227,7 @@ function shouldConstruct(Component) {
227 }
228
229 // This is used to create an alternate fiber to do work on.
231 -exports.createWorkInProgress = function(
230 +export function createWorkInProgress(
231 current: Fiber,
232 pendingProps: any,
233 expirationTime: ExpirationTime,
@@ -282,14 +281,14 @@ exports.createWorkInProgress = function(
281 workInProgress.ref = current.ref;
282
283 return workInProgress;
285 -};
284 +}
285
287 -exports.createHostRootFiber = function(): Fiber {
286 +export function createHostRootFiber(): Fiber {
287 const fiber = createFiber(HostRoot, null, NoContext);
288 return fiber;
290 -};
289 +}
290
292 -exports.createFiberFromElement = function(
291 +export function createFiberFromElement(
292 element: ReactElement,
293 internalContextTag: TypeOfInternalContext,
294 expirationTime: ExpirationTime,
@@ -359,9 +358,9 @@ exports.createFiberFromElement = function(
358 fiber.expirationTime = expirationTime;
359
360 return fiber;
362 -};
361 +}
362
364 -function createFiberFromFragment(
363 +export function createFiberFromFragment(
364 elements: ReactFragment,
365 internalContextTag: TypeOfInternalContext,
366 expirationTime: ExpirationTime,
@@ -373,9 +372,7 @@ function createFiberFromFragment(
372 return fiber;
373 }
374
376 -exports.createFiberFromFragment = createFiberFromFragment;
377 -
378 -exports.createFiberFromText = function(
375 +export function createFiberFromText(
376 content: string,
377 internalContextTag: TypeOfInternalContext,
378 expirationTime: ExpirationTime,
@@ -384,15 +381,15 @@ exports.createFiberFromText = function(
381 fiber.pendingProps = content;
382 fiber.expirationTime = expirationTime;
383 return fiber;
387 -};
384 +}
385
389 -exports.createFiberFromHostInstanceForDeletion = function(): Fiber {
386 +export function createFiberFromHostInstanceForDeletion(): Fiber {
387 const fiber = createFiber(HostComponent, null, NoContext);
388 fiber.type = 'DELETED';
389 return fiber;
393 -};
390 +}
391
395 -exports.createFiberFromCall = function(
392 +export function createFiberFromCall(
393 call: ReactCall,
394 internalContextTag: TypeOfInternalContext,
395 expirationTime: ExpirationTime,
@@ -402,9 +399,9 @@ exports.createFiberFromCall = function(
399 fiber.pendingProps = call;
400 fiber.expirationTime = expirationTime;
401 return fiber;
405 -};
402 +}
403
407 -exports.createFiberFromReturn = function(
404 +export function createFiberFromReturn(
405 returnNode: ReactReturn,
406 internalContextTag: TypeOfInternalContext,
407 expirationTime: ExpirationTime,
@@ -412,9 +409,9 @@ exports.createFiberFromReturn = function(
409 const fiber = createFiber(ReturnComponent, null, internalContextTag);
410 fiber.expirationTime = expirationTime;
411 return fiber;
415 -};
412 +}
413
417 -exports.createFiberFromPortal = function(
414 +export function createFiberFromPortal(
415 portal: ReactPortal,
416 internalContextTag: TypeOfInternalContext,
417 expirationTime: ExpirationTime,
@@ -428,4 +425,4 @@ exports.createFiberFromPortal = function(
425 implementation: portal.implementation,
426 };
427 return fiber;
431 -};
428 +}
packages/react-reconciler/src/ReactFiberBeginWork.js
+21 -22
@@ -17,7 +17,7 @@ import type {HydrationContext} from './ReactFiberHydrationContext';
17 import type {FiberRoot} from './ReactFiberRoot';
18 import type {ExpirationTime} from './ReactFiberExpirationTime';
19
20 -var {
20 +import {
21 IndeterminateComponent,
22 FunctionalComponent,
23 ClassComponent,
@@ -29,46 +29,45 @@ var {
29 CallHandlerPhase,
30 ReturnComponent,
31 Fragment,
32 -} = require('shared/ReactTypeOfWork');
33 -var {
32 +} from 'shared/ReactTypeOfWork';
33 +import {
34 PerformedWork,
35 Placement,
36 ContentReset,
37 Err,
38 Ref,
39 -} = require('shared/ReactTypeOfSideEffect');
40 -var {ReactCurrentOwner} = require('shared/ReactGlobalSharedState');
41 -var invariant = require('fbjs/lib/invariant');
42 -var getComponentName = require('shared/getComponentName');
43 -
44 -var ReactFiberClassComponent = require('./ReactFiberClassComponent');
45 -var {
39 +} from 'shared/ReactTypeOfSideEffect';
40 +import {ReactCurrentOwner} from 'shared/ReactGlobalSharedState';
41 +import invariant from 'fbjs/lib/invariant';
42 +import getComponentName from 'shared/getComponentName';
43 +import warning from 'fbjs/lib/warning';
44 +import ReactDebugCurrentFiber from './ReactDebugCurrentFiber';
45 +import ReactDebugFiberPerf from './ReactDebugFiberPerf';
46 +
47 +import ReactFiberClassComponent from './ReactFiberClassComponent';
48 +import {
49 mountChildFibersInPlace,
50 reconcileChildFibers,
51 reconcileChildFibersInPlace,
52 cloneChildFibers,
50 -} = require('./ReactChildFiber');
51 -var {processUpdateQueue} = require('./ReactFiberUpdateQueue');
52 -var {
53 +} from './ReactChildFiber';
54 +import {processUpdateQueue} from './ReactFiberUpdateQueue';
55 +import {
56 getMaskedContext,
57 getUnmaskedContext,
58 hasContextChanged,
59 pushContextProvider,
60 pushTopLevelContextObject,
61 invalidateContextProvider,
59 -} = require('./ReactFiberContext');
60 -var {NoWork, Never} = require('./ReactFiberExpirationTime');
62 +} from './ReactFiberContext';
63 +import {NoWork, Never} from './ReactFiberExpirationTime';
64
65 +var {cancelWorkTimer} = ReactDebugFiberPerf;
66 if (__DEV__) {
63 - var warning = require('fbjs/lib/warning');
64 -
65 - var ReactDebugCurrentFiber = require('./ReactDebugCurrentFiber');
66 - var {cancelWorkTimer} = require('./ReactDebugFiberPerf');
67 -
67 var warnedAboutStatelessRefs = {};
68 }
69
71 -module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>(
70 +export default function<T, P, I, TI, PI, C, CC, CX, PL>(
71 config: HostConfig<T, P, I, TI, PI, C, CC, CX, PL>,
72 hostContext: HostContext<C, CX>,
73 hydrationContext: HydrationContext<C, CX>,
@@ -865,4 +864,4 @@ module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>(
864 beginWork,
865 beginFailedWork,
866 };
868 -};
867 +}
packages/react-reconciler/src/ReactFiberClassComponent.js
+20 -20
@@ -12,35 +12,35 @@
12 import type {Fiber} from './ReactFiber';
13 import type {ExpirationTime} from './ReactFiberExpirationTime';
14
15 -var {Update} = require('shared/ReactTypeOfSideEffect');
16 -var ReactFeatureFlags = require('shared/ReactFeatureFlags');
17 -var {isMounted} = require('shared/ReactFiberTreeReflection');
18 -var ReactInstanceMap = require('shared/ReactInstanceMap');
19 -var emptyObject = require('fbjs/lib/emptyObject');
20 -var getComponentName = require('shared/getComponentName');
21 -var shallowEqual = require('fbjs/lib/shallowEqual');
22 -var invariant = require('fbjs/lib/invariant');
23 -
24 -var {AsyncUpdates} = require('./ReactTypeOfInternalContext');
25 -var {
15 +import {Update} from 'shared/ReactTypeOfSideEffect';
16 +import ReactFeatureFlags from 'shared/ReactFeatureFlags';
17 +import {isMounted} from 'shared/ReactFiberTreeReflection';
18 +import * as ReactInstanceMap from 'shared/ReactInstanceMap';
19 +import emptyObject from 'fbjs/lib/emptyObject';
20 +import getComponentName from 'shared/getComponentName';
21 +import shallowEqual from 'fbjs/lib/shallowEqual';
22 +import invariant from 'fbjs/lib/invariant';
23 +import warning from 'fbjs/lib/warning';
24 +
25 +import ReactDebugFiberPerf from './ReactDebugFiberPerf';
26 +import {AsyncUpdates} from './ReactTypeOfInternalContext';
27 +import {
28 cacheContext,
29 getMaskedContext,
30 getUnmaskedContext,
31 isContextConsumer,
30 -} = require('./ReactFiberContext');
31 -var {
32 +} from './ReactFiberContext';
33 +import {
34 insertUpdateIntoFiber,
35 processUpdateQueue,
34 -} = require('./ReactFiberUpdateQueue');
35 -var {hasContextChanged} = require('./ReactFiberContext');
36 +} from './ReactFiberUpdateQueue';
37 +import {hasContextChanged} from './ReactFiberContext';
38
39 +var {startPhaseTimer, stopPhaseTimer} = ReactDebugFiberPerf;
40 const fakeInternalInstance = {};
41 const isArray = Array.isArray;
42
43 if (__DEV__) {
41 - var warning = require('fbjs/lib/warning');
42 -
43 - var {startPhaseTimer, stopPhaseTimer} = require('./ReactDebugFiberPerf');
44 var didWarnAboutStateAssignmentForComponent = {};
45
46 var warnOnInvalidCallback = function(callback: mixed, callerName: string) {
@@ -75,7 +75,7 @@ if (__DEV__) {
75 Object.freeze(fakeInternalInstance);
76 }
77
78 -module.exports = function(
78 +export default function(
79 scheduleWork: (fiber: Fiber, expirationTime: ExpirationTime) => void,
80 computeExpirationForFiber: (fiber: Fiber) => ExpirationTime,
81 memoizeProps: (workInProgress: Fiber, props: any) => void,
@@ -720,4 +720,4 @@ module.exports = function(
720 // resumeMountClassInstance,
721 updateClassInstance,
722 };
723 -};
723 +}
packages/react-reconciler/src/ReactFiberCommitWork.js
+15 -20
@@ -12,32 +12,27 @@
12 import type {HostConfig} from 'react-reconciler';
13 import type {Fiber} from './ReactFiber';
14
15 -var ReactFeatureFlags = require('shared/ReactFeatureFlags');
16 -var ReactTypeOfWork = require('shared/ReactTypeOfWork');
17 -var {
15 +import ReactFeatureFlags from 'shared/ReactFeatureFlags';
16 +import {
17 ClassComponent,
18 HostRoot,
19 HostComponent,
20 HostText,
21 HostPortal,
22 CallComponent,
24 -} = ReactTypeOfWork;
25 -var {
26 - invokeGuardedCallback,
27 - hasCaughtError,
28 - clearCaughtError,
29 -} = require('shared/ReactErrorUtils');
30 -var {Placement, Update, ContentReset} = require('shared/ReactTypeOfSideEffect');
31 -var invariant = require('fbjs/lib/invariant');
32 -
33 -var {commitCallbacks} = require('./ReactFiberUpdateQueue');
34 -var {onCommitUnmount} = require('./ReactFiberDevToolsHook');
35 -
36 -if (__DEV__) {
37 - var {startPhaseTimer, stopPhaseTimer} = require('./ReactDebugFiberPerf');
38 -}
23 +} from 'shared/ReactTypeOfWork';
24 +import ReactErrorUtils from 'shared/ReactErrorUtils';
25 +import {Placement, Update, ContentReset} from 'shared/ReactTypeOfSideEffect';
26 +import invariant from 'fbjs/lib/invariant';
27 +
28 +import {commitCallbacks} from './ReactFiberUpdateQueue';
29 +import {onCommitUnmount} from './ReactFiberDevToolsHook';
30 +import ReactDebugFiberPerf from './ReactDebugFiberPerf';
31
40 -module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>(
32 +var {invokeGuardedCallback, hasCaughtError, clearCaughtError} = ReactErrorUtils;
33 +var {startPhaseTimer, stopPhaseTimer} = ReactDebugFiberPerf;
34 +
35 +export default function<T, P, I, TI, PI, C, CC, CX, PL>(
36 config: HostConfig<T, P, I, TI, PI, C, CC, CX, PL>,
37 captureError: (failedFiber: Fiber, error: mixed) => Fiber | null,
38 ) {
@@ -680,4 +675,4 @@ module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>(
675 } else {
676 invariant(false, 'Mutating reconciler is disabled.');
677 }
683 -};
678 +}
packages/react-reconciler/src/ReactFiberCompleteWork.js
+11 -11
@@ -17,8 +17,8 @@ import type {HostContext} from './ReactFiberHostContext';
17 import type {HydrationContext} from './ReactFiberHydrationContext';
18 import type {FiberRoot} from './ReactFiberRoot';
19
20 -var ReactFeatureFlags = require('shared/ReactFeatureFlags');
21 -var {
20 +import ReactFeatureFlags from 'shared/ReactFeatureFlags';
21 +import {
22 IndeterminateComponent,
23 FunctionalComponent,
24 ClassComponent,
@@ -30,18 +30,18 @@ var {
30 CallHandlerPhase,
31 ReturnComponent,
32 Fragment,
33 -} = require('shared/ReactTypeOfWork');
34 -var {Placement, Ref, Update} = require('shared/ReactTypeOfSideEffect');
35 -var invariant = require('fbjs/lib/invariant');
33 +} from 'shared/ReactTypeOfWork';
34 +import {Placement, Ref, Update} from 'shared/ReactTypeOfSideEffect';
35 +import invariant from 'fbjs/lib/invariant';
36
37 -var {reconcileChildFibers} = require('./ReactChildFiber');
38 -var {
37 +import {reconcileChildFibers} from './ReactChildFiber';
38 +import {
39 popContextProvider,
40 popTopLevelContextObject,
41 -} = require('./ReactFiberContext');
42 -var {Never} = require('./ReactFiberExpirationTime');
41 +} from './ReactFiberContext';
42 +import {Never} from './ReactFiberExpirationTime';
43
44 -module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>(
44 +export default function<T, P, I, TI, PI, C, CC, CX, PL>(
45 config: HostConfig<T, P, I, TI, PI, C, CC, CX, PL>,
46 hostContext: HostContext<C, CX>,
47 hydrationContext: HydrationContext<C, CX>,
@@ -606,4 +606,4 @@ module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>(
606 return {
607 completeWork,
608 };
609 -};
609 +}
packages/react-reconciler/src/ReactFiberContext.js
+37 -40
@@ -12,21 +12,21 @@
12 import type {Fiber} from './ReactFiber';
13 import type {StackCursor} from './ReactFiberStack';
14
15 -var {isFiberMounted} = require('shared/ReactFiberTreeReflection');
16 -var {ClassComponent, HostRoot} = require('shared/ReactTypeOfWork');
17 -var getComponentName = require('shared/getComponentName');
18 -var emptyObject = require('fbjs/lib/emptyObject');
19 -var invariant = require('fbjs/lib/invariant');
15 +import {isFiberMounted} from 'shared/ReactFiberTreeReflection';
16 +import {ClassComponent, HostRoot} from 'shared/ReactTypeOfWork';
17 +import getComponentName from 'shared/getComponentName';
18 +import emptyObject from 'fbjs/lib/emptyObject';
19 +import invariant from 'fbjs/lib/invariant';
20 +import warning from 'fbjs/lib/warning';
21 +import checkPropTypes from 'prop-types/checkPropTypes';
22
21 -const {createCursor, pop, push} = require('./ReactFiberStack');
23 +import {createCursor, pop, push} from './ReactFiberStack';
24 +import ReactDebugCurrentFiber from './ReactDebugCurrentFiber';
25 +import ReactDebugFiberPerf from './ReactDebugFiberPerf';
26
23 -if (__DEV__) {
24 - var warning = require('fbjs/lib/warning');
25 - var checkPropTypes = require('prop-types/checkPropTypes');
26 -
27 - var ReactDebugCurrentFiber = require('./ReactDebugCurrentFiber');
28 - var {startPhaseTimer, stopPhaseTimer} = require('./ReactDebugFiberPerf');
27 +const {startPhaseTimer, stopPhaseTimer} = ReactDebugFiberPerf;
28
29 +if (__DEV__) {
30 var warnedAboutMissingGetChildContext = {};
31 }
32
@@ -39,7 +39,7 @@ let didPerformWorkStackCursor: StackCursor<boolean> = createCursor(false);
39 // pushed the next context provider, and now need to merge their contexts.
40 let previousContext: Object = emptyObject;
41
42 -function getUnmaskedContext(workInProgress: Fiber): Object {
42 +export function getUnmaskedContext(workInProgress: Fiber): Object {
43 const hasOwnContext = isContextProvider(workInProgress);
44 if (hasOwnContext) {
45 // If the fiber is a context provider itself, when we read its context
@@ -50,9 +50,8 @@ function getUnmaskedContext(workInProgress: Fiber): Object {
50 }
51 return contextStackCursor.current;
52 }
53 -exports.getUnmaskedContext = getUnmaskedContext;
53
55 -function cacheContext(
54 +export function cacheContext(
55 workInProgress: Fiber,
56 unmaskedContext: Object,
57 maskedContext: Object,
@@ -61,9 +60,8 @@ function cacheContext(
60 instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
61 instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
62 }
64 -exports.cacheContext = cacheContext;
63
66 -exports.getMaskedContext = function(
64 +export function getMaskedContext(
65 workInProgress: Fiber,
66 unmaskedContext: Object,
67 ) {
@@ -107,23 +105,21 @@ exports.getMaskedContext = function(
105 }
106
107 return context;
110 -};
108 +}
109
112 -exports.hasContextChanged = function(): boolean {
110 +export function hasContextChanged(): boolean {
111 return didPerformWorkStackCursor.current;
114 -};
112 +}
113
116 -function isContextConsumer(fiber: Fiber): boolean {
114 +export function isContextConsumer(fiber: Fiber): boolean {
115 return fiber.tag === ClassComponent && fiber.type.contextTypes != null;
116 }
119 -exports.isContextConsumer = isContextConsumer;
117
121 -function isContextProvider(fiber: Fiber): boolean {
118 +export function isContextProvider(fiber: Fiber): boolean {
119 return fiber.tag === ClassComponent && fiber.type.childContextTypes != null;
120 }
124 -exports.isContextProvider = isContextProvider;
121
126 -function popContextProvider(fiber: Fiber): void {
122 +export function popContextProvider(fiber: Fiber): void {
123 if (!isContextProvider(fiber)) {
124 return;
125 }
@@ -131,14 +127,13 @@ function popContextProvider(fiber: Fiber): void {
127 pop(didPerformWorkStackCursor, fiber);
128 pop(contextStackCursor, fiber);
129 }
134 -exports.popContextProvider = popContextProvider;
130
136 -exports.popTopLevelContextObject = function(fiber: Fiber) {
131 +export function popTopLevelContextObject(fiber: Fiber) {
132 pop(didPerformWorkStackCursor, fiber);
133 pop(contextStackCursor, fiber);
139 -};
134 +}
135
141 -exports.pushTopLevelContextObject = function(
136 +export function pushTopLevelContextObject(
137 fiber: Fiber,
138 context: Object,
139 didChange: boolean,
@@ -151,9 +146,12 @@ exports.pushTopLevelContextObject = function(
146
147 push(contextStackCursor, context, fiber);
148 push(didPerformWorkStackCursor, didChange, fiber);
154 -};
149 +}
150
156 -function processChildContext(fiber: Fiber, parentContext: Object): Object {
151 +export function processChildContext(
152 + fiber: Fiber,
153 + parentContext: Object,
154 +): Object {
155 const instance = fiber.stateNode;
156 const childContextTypes = fiber.type.childContextTypes;
157
@@ -214,9 +212,8 @@ function processChildContext(fiber: Fiber, parentContext: Object): Object {
212
213 return {...parentContext, ...childContext};
214 }
217 -exports.processChildContext = processChildContext;
215
219 -exports.pushContextProvider = function(workInProgress: Fiber): boolean {
216 +export function pushContextProvider(workInProgress: Fiber): boolean {
217 if (!isContextProvider(workInProgress)) {
218 return false;
219 }
@@ -240,9 +237,9 @@ exports.pushContextProvider = function(workInProgress: Fiber): boolean {
237 );
238
239 return true;
243 -};
240 +}
241
245 -exports.invalidateContextProvider = function(
242 +export function invalidateContextProvider(
243 workInProgress: Fiber,
244 didChange: boolean,
245 ): void {
@@ -271,15 +268,15 @@ exports.invalidateContextProvider = function(
268 pop(didPerformWorkStackCursor, workInProgress);
269 push(didPerformWorkStackCursor, didChange, workInProgress);
270 }
274 -};
271 +}
272
276 -exports.resetContext = function(): void {
273 +export function resetContext(): void {
274 previousContext = emptyObject;
275 contextStackCursor.current = emptyObject;
276 didPerformWorkStackCursor.current = false;
280 -};
277 +}
278
282 -exports.findCurrentUnmaskedContext = function(fiber: Fiber): Object {
279 +export function findCurrentUnmaskedContext(fiber: Fiber): Object {
280 // Currently this is only used with renderSubtreeIntoContainer; not sure if it
281 // makes sense elsewhere
282 invariant(
@@ -302,4 +299,4 @@ exports.findCurrentUnmaskedContext = function(fiber: Fiber): Object {
299 node = parent;
300 }
301 return node.stateNode.context;
305 -};
302 +}
packages/react-reconciler/src/ReactFiberDevToolsHook.js
+5 -11
@@ -12,11 +12,9 @@
12 import type {Fiber} from './ReactFiber';
13 import type {FiberRoot} from './ReactFiberRoot';
14
15 -declare var __REACT_DEVTOOLS_GLOBAL_HOOK__: Object | void;
15 +import warning from 'fbjs/lib/warning';
16
17 -if (__DEV__) {
18 - var warning = require('fbjs/lib/warning');
19 -}
17 +declare var __REACT_DEVTOOLS_GLOBAL_HOOK__: Object | void;
18
19 let onCommitFiberRoot = null;
20 let onCommitFiberUnmount = null;
@@ -35,7 +33,7 @@ function catchErrors(fn) {
33 };
34 }
35
38 -function injectInternals(internals: Object): boolean {
36 +export function injectInternals(internals: Object): boolean {
37 if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
38 // No DevTools
39 return false;
@@ -72,18 +70,14 @@ function injectInternals(internals: Object): boolean {
70 return true;
71 }
72
75 -function onCommitRoot(root: FiberRoot) {
73 +export function onCommitRoot(root: FiberRoot) {
74 if (typeof onCommitFiberRoot === 'function') {
75 onCommitFiberRoot(root);
76 }
77 }
78
81 -function onCommitUnmount(fiber: Fiber) {
79 +export function onCommitUnmount(fiber: Fiber) {
80 if (typeof onCommitFiberUnmount === 'function') {
81 onCommitFiberUnmount(fiber);
82 }
83 }
86 -
87 -exports.injectInternals = injectInternals;
88 -exports.onCommitRoot = onCommitRoot;
89 -exports.onCommitUnmount = onCommitUnmount;
packages/react-reconciler/src/ReactFiberErrorLogger.js
+3 -5
@@ -11,13 +11,13 @@
11
12 import type {CapturedError} from './ReactFiberScheduler';
13
14 -const invariant = require('fbjs/lib/invariant');
14 +import invariant from 'fbjs/lib/invariant';
15
16 const defaultShowDialog = (capturedError: CapturedError) => true;
17
18 let showDialog = defaultShowDialog;
19
20 -function logCapturedError(capturedError: CapturedError): void {
20 +export function logCapturedError(capturedError: CapturedError): void {
21 const logError = showDialog(capturedError);
22
23 // Allow injected showDialog() to prevent default console.error logging.
@@ -74,7 +74,7 @@ function logCapturedError(capturedError: CapturedError): void {
74 }
75 }
76
77 -exports.injection = {
77 +export const injection = {
78 /**
79 * Display custom dialog for lifecycle errors.
80 * Return false to prevent default behavior of logging to console.error.
@@ -91,5 +91,3 @@ exports.injection = {
91 showDialog = fn;
92 },
93 };
94 -
95 -exports.logCapturedError = logCapturedError;
packages/react-reconciler/src/ReactFiberExpirationTime.js
+5 -11
@@ -12,29 +12,24 @@
12 // TODO: Use an opaque type once ESLint et al support the syntax
13 export type ExpirationTime = number;
14
15 -const NoWork = 0;
16 -const Sync = 1;
17 -const Never = 2147483647; // Max int32: Math.pow(2, 31) - 1
15 +export const NoWork = 0;
16 +export const Sync = 1;
17 +export const Never = 2147483647; // Max int32: Math.pow(2, 31) - 1
18
19 const UNIT_SIZE = 10;
20 const MAGIC_NUMBER_OFFSET = 2;
21
22 -exports.Sync = Sync;
23 -exports.NoWork = NoWork;
24 -exports.Never = Never;
25 -
22 // 1 unit of expiration time represents 10ms.
27 -function msToExpirationTime(ms: number): ExpirationTime {
23 +export function msToExpirationTime(ms: number): ExpirationTime {
24 // Always add an offset so that we don't clash with the magic number for NoWork.
25 return ((ms / UNIT_SIZE) | 0) + MAGIC_NUMBER_OFFSET;
26 }
31 -exports.msToExpirationTime = msToExpirationTime;
27
28 function ceiling(num: number, precision: number): number {
29 return (((num / precision) | 0) + 1) * precision;
30 }
31
37 -function computeExpirationBucket(
32 +export function computeExpirationBucket(
33 currentTime: ExpirationTime,
34 expirationInMs: number,
35 bucketSizeMs: number,
@@ -44,4 +39,3 @@ function computeExpirationBucket(
39 bucketSizeMs / UNIT_SIZE,
40 );
41 }
47 -exports.computeExpirationBucket = computeExpirationBucket;
packages/react-reconciler/src/ReactFiberHostContext.js
+4 -4
@@ -13,9 +13,9 @@ import type {HostConfig} from 'react-reconciler';
13 import type {Fiber} from './ReactFiber';
14 import type {StackCursor} from './ReactFiberStack';
15
16 -const invariant = require('fbjs/lib/invariant');
16 +import invariant from 'fbjs/lib/invariant';
17
18 -const {createCursor, pop, push} = require('./ReactFiberStack');
18 +import {createCursor, pop, push} from './ReactFiberStack';
19
20 declare class NoContextT {}
21 const NO_CONTEXT: NoContextT = ({}: any);
@@ -30,7 +30,7 @@ export type HostContext<C, CX> = {
30 resetHostContainer(): void,
31 };
32
33 -module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>(
33 +export default function<T, P, I, TI, PI, C, CC, CX, PL>(
34 config: HostConfig<T, P, I, TI, PI, C, CC, CX, PL>,
35 ): HostContext<C, CX> {
36 const {getChildHostContext, getRootHostContext} = config;
@@ -124,4 +124,4 @@ module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>(
124 pushHostContext,
125 resetHostContainer,
126 };
127 -};
127 +}
packages/react-reconciler/src/ReactFiberHydrationContext.js
+6 -6
@@ -12,11 +12,11 @@
12 import type {HostConfig} from 'react-reconciler';
13 import type {Fiber} from './ReactFiber';
14
15 -const {HostComponent, HostText, HostRoot} = require('shared/ReactTypeOfWork');
16 -const {Deletion, Placement} = require('shared/ReactTypeOfSideEffect');
17 -var invariant = require('fbjs/lib/invariant');
15 +import {HostComponent, HostText, HostRoot} from 'shared/ReactTypeOfWork';
16 +import {Deletion, Placement} from 'shared/ReactTypeOfSideEffect';
17 +import invariant from 'fbjs/lib/invariant';
18
19 -const {createFiberFromHostInstanceForDeletion} = require('./ReactFiber');
19 +import {createFiberFromHostInstanceForDeletion} from './ReactFiber';
20
21 export type HydrationContext<C, CX> = {
22 enterHydrationState(fiber: Fiber): boolean,
@@ -31,7 +31,7 @@ export type HydrationContext<C, CX> = {
31 popHydrationState(fiber: Fiber): boolean,
32 };
33
34 -module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>(
34 +export default function<T, P, I, TI, PI, C, CC, CX, PL>(
35 config: HostConfig<T, P, I, TI, PI, C, CC, CX, PL>,
36 ): HydrationContext<C, CX> {
37 const {shouldSetTextContent, hydration} = config;
@@ -376,4 +376,4 @@ module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>(
376 prepareToHydrateHostTextInstance,
377 popHydrationState,
378 };
379 -};
379 +}
packages/react-reconciler/src/ReactFiberReconciler.js
+20 -23
@@ -13,35 +13,32 @@ import type {Fiber} from './ReactFiber';
13 import type {FiberRoot} from './ReactFiberRoot';
14 import type {ReactNodeList} from 'shared/ReactTypes';
15
16 -var ReactFeatureFlags = require('shared/ReactFeatureFlags');
17 -var ReactInstanceMap = require('shared/ReactInstanceMap');
18 -var {HostComponent} = require('shared/ReactTypeOfWork');
19 -var emptyObject = require('fbjs/lib/emptyObject');
20 -
21 -var {
16 +import ReactFeatureFlags from 'shared/ReactFeatureFlags';
17 +import {
18 + findCurrentHostFiber,
19 + findCurrentHostFiberWithNoPortals,
20 +} from 'shared/ReactFiberTreeReflection';
21 +import * as ReactInstanceMap from 'shared/ReactInstanceMap';
22 +import {HostComponent} from 'shared/ReactTypeOfWork';
23 +import emptyObject from 'fbjs/lib/emptyObject';
24 +import getComponentName from 'shared/getComponentName';
25 +import warning from 'fbjs/lib/warning';
26 +
27 +import {
28 findCurrentUnmaskedContext,
29 isContextProvider,
30 processChildContext,
25 -} = require('./ReactFiberContext');
26 -var {createFiberRoot} = require('./ReactFiberRoot');
27 -var ReactFiberScheduler = require('./ReactFiberScheduler');
28 -var {insertUpdateIntoFiber} = require('./ReactFiberUpdateQueue');
31 +} from './ReactFiberContext';
32 +import {createFiberRoot} from './ReactFiberRoot';
33 +import ReactFiberScheduler from './ReactFiberScheduler';
34 +import {insertUpdateIntoFiber} from './ReactFiberUpdateQueue';
35 +import ReactFiberInstrumentation from './ReactFiberInstrumentation';
36 +import ReactDebugCurrentFiber from './ReactDebugCurrentFiber';
37
38 if (__DEV__) {
31 - var getComponentName = require('shared/getComponentName');
32 - var warning = require('fbjs/lib/warning');
33 -
34 - var ReactFiberInstrumentation = require('./ReactFiberInstrumentation');
35 - var ReactDebugCurrentFiber = require('./ReactDebugCurrentFiber');
36 -
39 var didWarnAboutNestedUpdates = false;
40 }
41
40 -var {
41 - findCurrentHostFiber,
42 - findCurrentHostFiberWithNoPortals,
43 -} = require('shared/ReactFiberTreeReflection');
44 -
42 export type Deadline = {
43 timeRemaining: () => number,
44 };
@@ -255,7 +252,7 @@ function getContextForSubtree(
252 : parentContext;
253 }
254
258 -module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>(
255 +export default function<T, P, I, TI, PI, C, CC, CX, PL>(
256 config: HostConfig<T, P, I, TI, PI, C, CC, CX, PL>,
257 ): Reconciler<C, I, TI> {
258 var {getPublicInstance} = config;
@@ -407,4 +404,4 @@ module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>(
404 return hostFiber.stateNode;
405 },
406 };
410 -};
407 +}
packages/react-reconciler/src/ReactFiberRoot.js
+4 -4
@@ -12,8 +12,8 @@
12 import type {Fiber} from './ReactFiber';
13 import type {ExpirationTime} from './ReactFiberExpirationTime';
14
15 -const {createHostRootFiber} = require('./ReactFiber');
16 -const {NoWork} = require('./ReactFiberExpirationTime');
15 +import {createHostRootFiber} from './ReactFiber';
16 +import {NoWork} from './ReactFiberExpirationTime';
17
18 export type FiberRoot = {
19 // Any additional information from the host associated with this root.
@@ -40,7 +40,7 @@ export type FiberRoot = {
40 nextScheduledRoot: FiberRoot | null,
41 };
42
43 -exports.createFiberRoot = function(
43 +export function createFiberRoot(
44 containerInfo: any,
45 hydrate: boolean,
46 ): FiberRoot {
@@ -61,4 +61,4 @@ exports.createFiberRoot = function(
61 };
62 uninitializedFiber.stateNode = root;
63 return root;
64 -};
64 +}
packages/react-reconciler/src/ReactFiberScheduler.js
+49 -52
@@ -15,17 +15,12 @@ import type {FiberRoot} from './ReactFiberRoot';
15 import type {HydrationContext} from './ReactFiberHydrationContext';
16 import type {ExpirationTime} from './ReactFiberExpirationTime';
17
18 -var {
18 +import {
19 getStackAddendumByWorkInProgressFiber,
20 -} = require('shared/ReactFiberComponentTreeHook');
21 -var {
22 - invokeGuardedCallback,
23 - hasCaughtError,
24 - clearCaughtError,
25 -} = require('shared/ReactErrorUtils');
26 -var {ReactCurrentOwner} = require('shared/ReactGlobalSharedState');
27 -var getComponentName = require('shared/getComponentName');
28 -var {
20 +} from 'shared/ReactFiberComponentTreeHook';
21 +import ReactErrorUtils from 'shared/ReactErrorUtils';
22 +import {ReactCurrentOwner} from 'shared/ReactGlobalSharedState';
23 +import {
24 PerformedWork,
25 Placement,
26 Update,
@@ -35,35 +30,57 @@ var {
30 Callback,
31 Err,
32 Ref,
38 -} = require('shared/ReactTypeOfSideEffect');
39 -var {
33 +} from 'shared/ReactTypeOfSideEffect';
34 +import {
35 HostRoot,
36 HostComponent,
37 HostPortal,
38 ClassComponent,
44 -} = require('shared/ReactTypeOfWork');
45 -var invariant = require('fbjs/lib/invariant');
46 -
47 -var ReactFiberBeginWork = require('./ReactFiberBeginWork');
48 -var ReactFiberCompleteWork = require('./ReactFiberCompleteWork');
49 -var ReactFiberCommitWork = require('./ReactFiberCommitWork');
50 -var ReactFiberHostContext = require('./ReactFiberHostContext');
51 -var ReactFiberHydrationContext = require('./ReactFiberHydrationContext');
52 -var {popContextProvider} = require('./ReactFiberContext');
53 -const {reset} = require('./ReactFiberStack');
54 -var {logCapturedError} = require('./ReactFiberErrorLogger');
55 -var {createWorkInProgress} = require('./ReactFiber');
56 -var {onCommitRoot} = require('./ReactFiberDevToolsHook');
57 -var {
39 +} from 'shared/ReactTypeOfWork';
40 +import getComponentName from 'shared/getComponentName';
41 +import invariant from 'fbjs/lib/invariant';
42 +import warning from 'fbjs/lib/warning';
43 +
44 +import ReactFiberBeginWork from './ReactFiberBeginWork';
45 +import ReactFiberCompleteWork from './ReactFiberCompleteWork';
46 +import ReactFiberCommitWork from './ReactFiberCommitWork';
47 +import ReactFiberHostContext from './ReactFiberHostContext';
48 +import ReactFiberHydrationContext from './ReactFiberHydrationContext';
49 +import ReactFiberInstrumentation from './ReactFiberInstrumentation';
50 +import ReactDebugCurrentFiber from './ReactDebugCurrentFiber';
51 +import ReactDebugFiberPerf from './ReactDebugFiberPerf';
52 +import {popContextProvider} from './ReactFiberContext';
53 +import {reset} from './ReactFiberStack';
54 +import {logCapturedError} from './ReactFiberErrorLogger';
55 +import {createWorkInProgress} from './ReactFiber';
56 +import {onCommitRoot} from './ReactFiberDevToolsHook';
57 +import {
58 NoWork,
59 Sync,
60 Never,
61 msToExpirationTime,
62 computeExpirationBucket,
63 -} = require('./ReactFiberExpirationTime');
64 -var {AsyncUpdates} = require('./ReactTypeOfInternalContext');
65 -var {getUpdateExpirationTime} = require('./ReactFiberUpdateQueue');
66 -var {resetContext} = require('./ReactFiberContext');
63 +} from './ReactFiberExpirationTime';
64 +import {AsyncUpdates} from './ReactTypeOfInternalContext';
65 +import {getUpdateExpirationTime} from './ReactFiberUpdateQueue';
66 +import {resetContext} from './ReactFiberContext';
67 +
68 +var {invokeGuardedCallback, hasCaughtError, clearCaughtError} = ReactErrorUtils;
69 +var {
70 + recordEffect,
71 + recordScheduleUpdate,
72 + startWorkTimer,
73 + stopWorkTimer,
74 + stopFailedWorkTimer,
75 + startWorkLoopTimer,
76 + stopWorkLoopTimer,
77 + startCommitTimer,
78 + stopCommitTimer,
79 + startCommitHostEffectsTimer,
80 + stopCommitHostEffectsTimer,
81 + startCommitLifeCyclesTimer,
82 + stopCommitLifeCyclesTimer,
83 +} = ReactDebugFiberPerf;
84
85 export type CapturedError = {
86 componentName: ?string,
@@ -80,26 +97,6 @@ export type HandleErrorInfo = {
97 };
98
99 if (__DEV__) {
83 - var warning = require('fbjs/lib/warning');
84 -
85 - var ReactFiberInstrumentation = require('./ReactFiberInstrumentation');
86 - var ReactDebugCurrentFiber = require('./ReactDebugCurrentFiber');
87 - var {
88 - recordEffect,
89 - recordScheduleUpdate,
90 - startWorkTimer,
91 - stopWorkTimer,
92 - stopFailedWorkTimer,
93 - startWorkLoopTimer,
94 - stopWorkLoopTimer,
95 - startCommitTimer,
96 - stopCommitTimer,
97 - startCommitHostEffectsTimer,
98 - stopCommitHostEffectsTimer,
99 - startCommitLifeCyclesTimer,
100 - stopCommitLifeCyclesTimer,
101 - } = require('./ReactDebugFiberPerf');
102 -
100 var didWarnAboutStateTransition = false;
101 var didWarnSetStateChildContext = false;
102 var didWarnStateUpdateForUnmountedComponent = {};
@@ -149,7 +146,7 @@ if (__DEV__) {
146 };
147 }
148
152 -module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>(
149 +export default function<T, P, I, TI, PI, C, CC, CX, PL>(
150 config: HostConfig<T, P, I, TI, PI, C, CC, CX, PL>,
151 ) {
152 const hostContext = ReactFiberHostContext(config);
@@ -1634,4 +1631,4 @@ module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>(
1631 flushSync,
1632 deferredUpdates,
1633 };
1637 -};
1634 +}
packages/react-reconciler/src/ReactFiberStack.js
+12 -18
@@ -11,14 +11,12 @@
11
12 import type {Fiber} from './ReactFiber';
13
14 +import warning from 'fbjs/lib/warning';
15 +
16 export type StackCursor<T> = {
17 current: T,
18 };
19
18 -if (__DEV__) {
19 - var warning = require('fbjs/lib/warning');
20 -}
21 -
20 const valueStack: Array<any> = [];
21
22 if (__DEV__) {
@@ -27,17 +25,17 @@ if (__DEV__) {
25
26 let index = -1;
27
30 -exports.createCursor = function<T>(defaultValue: T): StackCursor<T> {
28 +export function createCursor<T>(defaultValue: T): StackCursor<T> {
29 return {
30 current: defaultValue,
31 };
34 -};
32 +}
33
36 -exports.isEmpty = function(): boolean {
34 +export function isEmpty(): boolean {
35 return index === -1;
38 -};
36 +}
37
40 -exports.pop = function<T>(cursor: StackCursor<T>, fiber: Fiber): void {
38 +export function pop<T>(cursor: StackCursor<T>, fiber: Fiber): void {
39 if (index < 0) {
40 if (__DEV__) {
41 warning(false, 'Unexpected pop.');
@@ -60,13 +58,9 @@ exports.pop = function<T>(cursor: StackCursor<T>, fiber: Fiber): void {
58 }
59
60 index--;
63 -};
61 +}
62
65 -exports.push = function<T>(
66 - cursor: StackCursor<T>,
67 - value: T,
68 - fiber: Fiber,
69 -): void {
63 +export function push<T>(cursor: StackCursor<T>, value: T, fiber: Fiber): void {
64 index++;
65
66 valueStack[index] = cursor.current;
@@ -76,9 +70,9 @@ exports.push = function<T>(
70 }
71
72 cursor.current = value;
79 -};
73 +}
74
81 -exports.reset = function(): void {
75 +export function reset(): void {
76 while (index > -1) {
77 valueStack[index] = null;
78
@@ -88,4 +82,4 @@ exports.reset = function(): void {
82
83 index--;
84 }
91 -};
85 +}
packages/react-reconciler/src/ReactFiberUpdateQueue.js
+13 -15
@@ -12,14 +12,14 @@
12 import type {Fiber} from './ReactFiber';
13 import type {ExpirationTime} from './ReactFiberExpirationTime';
14
15 -const {Callback: CallbackEffect} = require('shared/ReactTypeOfSideEffect');
16 -const {ClassComponent, HostRoot} = require('shared/ReactTypeOfWork');
17 -const invariant = require('fbjs/lib/invariant');
15 +import {Callback as CallbackEffect} from 'shared/ReactTypeOfSideEffect';
16 +import {ClassComponent, HostRoot} from 'shared/ReactTypeOfWork';
17 +import invariant from 'fbjs/lib/invariant';
18 +import warning from 'fbjs/lib/warning';
19
19 -const {NoWork} = require('./ReactFiberExpirationTime');
20 +import {NoWork} from './ReactFiberExpirationTime';
21
22 if (__DEV__) {
22 - var warning = require('fbjs/lib/warning');
23 var didWarnUpdateInsideUpdate = false;
24 }
25
@@ -84,7 +84,7 @@ function createUpdateQueue<State>(baseState: State): UpdateQueue<State> {
84 return queue;
85 }
86
87 -function insertUpdateIntoQueue<State>(
87 +export function insertUpdateIntoQueue<State>(
88 queue: UpdateQueue<State>,
89 update: Update<State>,
90 ): void {
@@ -103,9 +103,8 @@ function insertUpdateIntoQueue<State>(
103 queue.expirationTime = update.expirationTime;
104 }
105 }
106 -exports.insertUpdateIntoQueue = insertUpdateIntoQueue;
106
108 -function insertUpdateIntoFiber<State>(
107 +export function insertUpdateIntoFiber<State>(
108 fiber: Fiber,
109 update: Update<State>,
110 ): void {
@@ -168,9 +167,8 @@ function insertUpdateIntoFiber<State>(
167 // But we still need to update the `last` pointer of queue2.
168 queue2.last = update;
169 }
171 -exports.insertUpdateIntoFiber = insertUpdateIntoFiber;
170
173 -function getUpdateExpirationTime(fiber: Fiber): ExpirationTime {
171 +export function getUpdateExpirationTime(fiber: Fiber): ExpirationTime {
172 if (fiber.tag !== ClassComponent && fiber.tag !== HostRoot) {
173 return NoWork;
174 }
@@ -180,7 +178,6 @@ function getUpdateExpirationTime(fiber: Fiber): ExpirationTime {
178 }
179 return updateQueue.expirationTime;
180 }
183 -exports.getUpdateExpirationTime = getUpdateExpirationTime;
181
182 function getStateFromUpdate(update, instance, prevState, props) {
183 const partialState = update.partialState;
@@ -192,7 +189,7 @@ function getStateFromUpdate(update, instance, prevState, props) {
189 }
190 }
191
195 -function processUpdateQueue<State>(
192 +export function processUpdateQueue<State>(
193 current: Fiber | null,
194 workInProgress: Fiber,
195 queue: UpdateQueue<State>,
@@ -322,9 +319,11 @@ function processUpdateQueue<State>(
319
320 return state;
321 }
325 -exports.processUpdateQueue = processUpdateQueue;
322
327 -function commitCallbacks<State>(queue: UpdateQueue<State>, context: any) {
323 +export function commitCallbacks<State>(
324 + queue: UpdateQueue<State>,
325 + context: any,
326 +) {
327 const callbackList = queue.callbackList;
328 if (callbackList === null) {
329 return;
@@ -346,4 +345,3 @@ function commitCallbacks<State>(queue: UpdateQueue<State>, context: any) {
345 callback.call(context);
346 }
347 }
349 -exports.commitCallbacks = commitCallbacks;
packages/react-reconciler/src/ReactPortal.js
+3 -5
@@ -13,11 +13,11 @@ import type {ReactNodeList, ReactPortal} from 'shared/ReactTypes';
13
14 // The Symbol used to tag the special React types. If there is no native Symbol
15 // nor polyfill, then a plain number is used for performance.
16 -var REACT_PORTAL_TYPE =
16 +export const REACT_PORTAL_TYPE =
17 (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.portal')) ||
18 0xeaca;
19
20 -exports.createPortal = function(
20 +export function createPortal(
21 children: ReactNodeList,
22 containerInfo: any,
23 // TODO: figure out the API for cross-renderer implementation.
@@ -32,6 +32,4 @@ exports.createPortal = function(
32 containerInfo,
33 implementation,
34 };
35 -};
36 -
37 -exports.REACT_PORTAL_TYPE = REACT_PORTAL_TYPE;
35 +}
packages/react-reconciler/src/ReactTypeOfInternalContext.js
+2 -4
@@ -11,7 +11,5 @@
11
12 export type TypeOfInternalContext = number;
13
14 -module.exports = {
15 - NoContext: 0,
16 - AsyncUpdates: 1,
17 -};
14 +export const NoContext = 0;
15 +export const AsyncUpdates = 1;
packages/react-rt-renderer/index.js
+5 -1
@@ -9,4 +9,8 @@
9
10 'use strict';
11
12 -module.exports = require('./src/ReactNativeRT');
12 +var ReactNativeRT = require('./src/ReactNativeRT');
13 +
14 +// TODO: decide on the top-level export form.
15 +// This is hacky but makes it work with both Rollup and Jest.
16 +module.exports = ReactNativeRT.default ? ReactNativeRT.default : ReactNativeRT;
packages/react-rt-renderer/src/ReactNativeRT.js
+15 -16
@@ -13,18 +13,19 @@ import type {ReactNativeRTType} from './ReactNativeRTTypes';
13 import type {ReactNodeList} from 'shared/ReactTypes';
14
15 // TODO: direct imports like some-package/src/* are bad. Fix me.
16 -const ReactFiberErrorLogger = require('react-reconciler/src/ReactFiberErrorLogger');
17 -const ReactNativeFiberErrorDialog = require('react-native-renderer/src/ReactNativeFiberErrorDialog');
18 -const ReactPortal = require('react-reconciler/src/ReactPortal');
19 -const {
20 - injectInternals,
21 -} = require('react-reconciler/src/ReactFiberDevToolsHook');
22 -const ReactGenericBatching = require('events/ReactGenericBatching');
23 -const ReactVersion = require('shared/ReactVersion');
24 -
25 -const ReactNativeRTComponentTree = require('./ReactNativeRTComponentTree');
26 -const ReactNativeRTFiberRenderer = require('./ReactNativeRTFiberRenderer');
27 -const ReactNativeRTFiberInspector = require('./ReactNativeRTFiberInspector');
16 +import * as ReactFiberErrorLogger
17 + from 'react-reconciler/src/ReactFiberErrorLogger';
18 +import {
19 + showDialog,
20 +} from 'react-native-renderer/src/ReactNativeFiberErrorDialog';
21 +import * as ReactPortal from 'react-reconciler/src/ReactPortal';
22 +import {injectInternals} from 'react-reconciler/src/ReactFiberDevToolsHook';
23 +import ReactGenericBatching from 'events/ReactGenericBatching';
24 +import ReactVersion from 'shared/ReactVersion';
25 +
26 +import ReactNativeRTComponentTree from './ReactNativeRTComponentTree';
27 +import ReactNativeRTFiberRenderer from './ReactNativeRTFiberRenderer';
28 +import ReactNativeRTFiberInspector from './ReactNativeRTFiberInspector';
29
30 /**
31 * Make sure essential globals are available and are patched correctly. Please don't remove this
@@ -44,9 +45,7 @@ const roots = new Map();
45
46 // Intercept lifecycle errors and ensure they are shown with the correct stack
47 // trace within the native redbox component.
47 -ReactFiberErrorLogger.injection.injectDialog(
48 - ReactNativeFiberErrorDialog.showDialog,
49 -);
48 +ReactFiberErrorLogger.injection.injectDialog(showDialog);
49
50 const ReactNativeRTFiber: ReactNativeRTType = {
51 render(element: React$Element<any>, containerTag: any, callback: ?Function) {
@@ -96,4 +95,4 @@ injectInternals({
95 rendererPackageName: 'react-rt-renderer',
96 });
97
99 -module.exports = ReactNativeRTFiber;
98 +export default ReactNativeRTFiber;
packages/react-rt-renderer/src/ReactNativeRTComponentTree.js
+1 -1
@@ -43,4 +43,4 @@ var ReactNativeRTComponentTree = {
43 updateFiberProps,
44 };
45
46 -module.exports = ReactNativeRTComponentTree;
46 +export default ReactNativeRTComponentTree;
packages/react-rt-renderer/src/ReactNativeRTEventEmitter.js
+3 -3
@@ -8,11 +8,11 @@
8 */
9 'use strict';
10
11 -var ReactGenericBatching = require('events/ReactGenericBatching');
11 +import ReactGenericBatching from 'events/ReactGenericBatching';
12 // Module provided by RN:
13 -var BatchedBridge = require('BatchedBridge');
13 +import BatchedBridge from 'BatchedBridge';
14
15 -var ReactNativeRTComponentTree = require('./ReactNativeRTComponentTree');
15 +import ReactNativeRTComponentTree from './ReactNativeRTComponentTree';
16
17 var ReactNativeRTEventEmitter = {
18 /**
packages/react-rt-renderer/src/ReactNativeRTFiberInspector.js
+12 -11
@@ -8,17 +8,18 @@
8 */
9 'use strict';
10
11 -const ReactFiberTreeReflection = require('shared/ReactFiberTreeReflection');
12 -const getComponentName = require('shared/getComponentName');
13 -const ReactTypeOfWork = require('shared/ReactTypeOfWork');
14 -const emptyObject = require('fbjs/lib/emptyObject');
15 -const invariant = require('fbjs/lib/invariant');
16 -const {findCurrentFiberUsingSlowPath} = ReactFiberTreeReflection;
17 -const {HostComponent} = ReactTypeOfWork;
11 +import {
12 + findCurrentFiberUsingSlowPath,
13 + findCurrentHostFiber,
14 +} from 'shared/ReactFiberTreeReflection';
15 +import getComponentName from 'shared/getComponentName';
16 +import {HostComponent} from 'shared/ReactTypeOfWork';
17 +import emptyObject from 'fbjs/lib/emptyObject';
18 +import invariant from 'fbjs/lib/invariant';
19
19 -const ReactNativeRTComponentTree = require('./ReactNativeRTComponentTree');
20 -const {getFiberFromTag} = ReactNativeRTComponentTree;
20 +import ReactNativeRTComponentTree from './ReactNativeRTComponentTree';
21
22 +const {getFiberFromTag} = ReactNativeRTComponentTree;
23 let getInspectorDataForViewTag;
24
25 if (__DEV__) {
@@ -47,7 +48,7 @@ if (__DEV__) {
48 };
49
50 var getHostProps = function(fiber) {
50 - const host = ReactFiberTreeReflection.findCurrentHostFiber(fiber);
51 + const host = findCurrentHostFiber(fiber);
52 if (host) {
53 return host.memoizedProps || emptyObject;
54 }
@@ -102,6 +103,6 @@ if (__DEV__) {
103 };
104 }
105
105 -module.exports = {
106 +export default {
107 getInspectorDataForViewTag,
108 };
packages/react-rt-renderer/src/ReactNativeRTFiberRenderer.js
+7 -7
@@ -9,14 +9,14 @@
9
10 'use strict';
11
12 -const ReactFiberReconciler = require('react-reconciler');
13 -const emptyObject = require('fbjs/lib/emptyObject');
14 -const invariant = require('fbjs/lib/invariant');
12 +import ReactFiberReconciler from 'react-reconciler';
13 +import emptyObject from 'fbjs/lib/emptyObject';
14 +import invariant from 'fbjs/lib/invariant';
15 // Module provided by RN:
16 -const RTManager = require('RTManager');
16 +import RTManager from 'RTManager';
17
18 -const ReactNativeRTComponentTree = require('./ReactNativeRTComponentTree');
19 -const ReactNativeRTTagHandles = require('./ReactNativeRTTagHandles');
18 +import ReactNativeRTComponentTree from './ReactNativeRTComponentTree';
19 +import ReactNativeRTTagHandles from './ReactNativeRTTagHandles';
20
21 export type Container = number;
22 export type Instance = number;
@@ -242,4 +242,4 @@ const NativeRTRenderer = ReactFiberReconciler({
242 },
243 });
244
245 -module.exports = NativeRTRenderer;
245 +export default NativeRTRenderer;
packages/react-rt-renderer/src/ReactNativeRTTagHandles.js
+2 -2
@@ -8,7 +8,7 @@
8 */
9 'use strict';
10
11 -var invariant = require('fbjs/lib/invariant');
11 +import invariant from 'fbjs/lib/invariant';
12
13 /**
14 * Keeps track of allocating and associating native "tags" which are numeric,
@@ -49,4 +49,4 @@ var ReactNativeRTTagHandles = {
49 },
50 };
51
52 -module.exports = ReactNativeRTTagHandles;
52 +export default ReactNativeRTTagHandles;
packages/react-test-renderer/index.js
+7 -1
@@ -9,4 +9,10 @@
9
10 'use strict';
11
12 -module.exports = require('./src/ReactTestRenderer');
12 +var ReactTestRenderer = require('./src/ReactTestRenderer');
13 +
14 +// TODO: decide on the top-level export form.
15 +// This is hacky but makes it work with both Rollup and Jest.
16 +module.exports = ReactTestRenderer.default
17 + ? ReactTestRenderer.default
18 + : ReactTestRenderer;
packages/react-test-renderer/shallow.js
+7 -1
@@ -9,4 +9,10 @@
9
10 'use strict';
11
12 -module.exports = require('./src/ReactShallowRenderer');
12 +var ReactShallowRenderer = require('./src/ReactShallowRenderer');
13 +
14 +// TODO: decide on the top-level export form.
15 +// This is hacky but makes it work with both Rollup and Jest.
16 +module.exports = ReactShallowRenderer.default
17 + ? ReactShallowRenderer.default
18 + : ReactShallowRenderer;
packages/react-test-renderer/src/ReactShallowRenderer.js
+7 -7
@@ -8,12 +8,12 @@
8
9 'use strict';
10
11 -const React = require('react');
12 -const describeComponentFrame = require('shared/describeComponentFrame');
13 -const getComponentName = require('shared/getComponentName');
14 -const emptyObject = require('fbjs/lib/emptyObject');
15 -const invariant = require('fbjs/lib/invariant');
16 -const checkPropTypes = require('prop-types/checkPropTypes');
11 +import React from 'react';
12 +import describeComponentFrame from 'shared/describeComponentFrame';
13 +import getComponentName from 'shared/getComponentName';
14 +import emptyObject from 'fbjs/lib/emptyObject';
15 +import invariant from 'fbjs/lib/invariant';
16 +import checkPropTypes from 'prop-types/checkPropTypes';
17
18 class ReactShallowRenderer {
19 static createRenderer = function() {
@@ -267,4 +267,4 @@ function shouldConstruct(Component) {
267 return !!(Component.prototype && Component.prototype.isReactComponent);
268 }
269
270 -module.exports = ReactShallowRenderer;
270 +export default ReactShallowRenderer;
packages/react-test-renderer/src/ReactTestRenderer.js
+9 -12
@@ -12,20 +12,19 @@
12 import type {Fiber} from 'react-reconciler/src/ReactFiber';
13 import type {FiberRoot} from 'react-reconciler/src/ReactFiberRoot';
14
15 -var ReactFiberReconciler = require('react-reconciler');
16 -var ReactGenericBatching = require('events/ReactGenericBatching');
17 -var ReactFiberTreeReflection = require('shared/ReactFiberTreeReflection');
18 -var emptyObject = require('fbjs/lib/emptyObject');
19 -var ReactTypeOfWork = require('shared/ReactTypeOfWork');
20 -var invariant = require('fbjs/lib/invariant');
21 -var {
15 +import ReactFiberReconciler from 'react-reconciler';
16 +import ReactGenericBatching from 'events/ReactGenericBatching';
17 +import {findCurrentFiberUsingSlowPath} from 'shared/ReactFiberTreeReflection';
18 +import emptyObject from 'fbjs/lib/emptyObject';
19 +import {
20 Fragment,
21 FunctionalComponent,
22 ClassComponent,
23 HostComponent,
24 HostText,
25 HostRoot,
28 -} = ReactTypeOfWork;
26 +} from 'shared/ReactTypeOfWork';
27 +import invariant from 'fbjs/lib/invariant';
28
29 type TestRendererOptions = {
30 createNodeMock: (element: React$Element<any>) => any,
@@ -372,9 +371,7 @@ class ReactTestInstance {
371
372 _currentFiber(): Fiber {
373 // Throws if this component has been unmounted.
375 - const fiber = ReactFiberTreeReflection.findCurrentFiberUsingSlowPath(
376 - this._fiber,
377 - );
374 + const fiber = findCurrentFiberUsingSlowPath(this._fiber);
375 invariant(
376 fiber !== null,
377 "Can't read from currently-mounting component. This error is likely " +
@@ -642,4 +639,4 @@ var ReactTestRendererFiber = {
639 /* eslint-enable camelcase */
640 };
641
645 -module.exports = ReactTestRendererFiber;
642 +export default ReactTestRendererFiber;
packages/react/index.js
+5 -1
@@ -9,4 +9,8 @@
9
10 'use strict';
11
12 -module.exports = require('./src/React');
12 +var React = require('./src/React');
13 +
14 +// TODO: decide on the top-level export form.
15 +// This is hacky but makes it work with both Rollup and Jest.
16 +module.exports = React.default ? React.default : React;
packages/react/src/React.js
+34 -34
@@ -7,24 +7,25 @@
7
8 'use strict';
9
10 -var ReactVersion = require('shared/ReactVersion');
11 -var ReactFeatureFlags = require('shared/ReactFeatureFlags');
10 +import assign from 'object-assign';
11 +import ReactVersion from 'shared/ReactVersion';
12 +import ReactFeatureFlags from 'shared/ReactFeatureFlags';
13
13 -var ReactBaseClasses = require('./ReactBaseClasses');
14 -var ReactChildren = require('./ReactChildren');
15 -var ReactElement = require('./ReactElement');
16 -var onlyChild = require('./onlyChild');
17 -
18 -var createElement = ReactElement.createElement;
19 -var createFactory = ReactElement.createFactory;
20 -var cloneElement = ReactElement.cloneElement;
21 -
22 -if (__DEV__) {
23 - var ReactElementValidator = require('./ReactElementValidator');
24 - createElement = ReactElementValidator.createElement;
25 - createFactory = ReactElementValidator.createFactory;
26 - cloneElement = ReactElementValidator.cloneElement;
27 -}
14 +import {Component, PureComponent, AsyncComponent} from './ReactBaseClasses';
15 +import {forEach, map, count, toArray, only} from './ReactChildren';
16 +import ReactCurrentOwner from './ReactCurrentOwner';
17 +import {
18 + createElement,
19 + createFactory,
20 + cloneElement,
21 + isValidElement,
22 +} from './ReactElement';
23 +import {
24 + createElementWithValidation,
25 + createFactoryWithValidation,
26 + cloneElementWithValidation,
27 +} from './ReactElementValidator';
28 +import ReactDebugCurrentFrame from './ReactDebugCurrentFrame';
29
30 const REACT_FRAGMENT_TYPE =
31 (typeof Symbol === 'function' &&
@@ -34,29 +35,28 @@ const REACT_FRAGMENT_TYPE =
35
36 var React = {
37 Children: {
37 - map: ReactChildren.map,
38 - forEach: ReactChildren.forEach,
39 - count: ReactChildren.count,
40 - toArray: ReactChildren.toArray,
41 - only: onlyChild,
38 + map,
39 + forEach,
40 + count,
41 + toArray,
42 + only,
43 },
44
44 - Component: ReactBaseClasses.Component,
45 - PureComponent: ReactBaseClasses.PureComponent,
46 - unstable_AsyncComponent: ReactBaseClasses.AsyncComponent,
47 -
48 - createElement: createElement,
49 - cloneElement: cloneElement,
50 - isValidElement: ReactElement.isValidElement,
45 + Component,
46 + PureComponent,
47 + unstable_AsyncComponent: AsyncComponent,
48
52 - createFactory: createFactory,
49 + createElement: __DEV__ ? createElementWithValidation : createElement,
50 + cloneElement: __DEV__ ? cloneElementWithValidation : cloneElement,
51 + createFactory: __DEV__ ? createFactoryWithValidation : createFactory,
52 + isValidElement: isValidElement,
53
54 version: ReactVersion,
55
56 __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
57 - ReactCurrentOwner: require('./ReactCurrentOwner'),
57 + ReactCurrentOwner,
58 // Used by renderers to avoid bundling object-assign twice in UMD bundles:
59 - assign: require('object-assign'),
59 + assign,
60 },
61 };
62
@@ -67,11 +67,11 @@ if (ReactFeatureFlags.enableReactFragment) {
67 if (__DEV__) {
68 Object.assign(React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, {
69 // These should not be included in production.
70 - ReactDebugCurrentFrame: require('./ReactDebugCurrentFrame'),
70 + ReactDebugCurrentFrame,
71 // Shim for React DOM 16.0.0 which still destructured (but not used) this.
72 // TODO: remove in React 17.0.
73 ReactComponentTreeHook: {},
74 });
75 }
76
77 -module.exports = React;
77 +export default React;
packages/react/src/ReactBaseClasses.js
+21 -25
@@ -7,16 +7,16 @@
7
8 'use strict';
9
10 -var emptyObject = require('fbjs/lib/emptyObject');
11 -var invariant = require('fbjs/lib/invariant');
12 -var lowPriorityWarning = require('shared/lowPriorityWarning');
10 +import emptyObject from 'fbjs/lib/emptyObject';
11 +import invariant from 'fbjs/lib/invariant';
12 +import lowPriorityWarning from 'shared/lowPriorityWarning';
13
14 -var ReactNoopUpdateQueue = require('./ReactNoopUpdateQueue');
14 +import ReactNoopUpdateQueue from './ReactNoopUpdateQueue';
15
16 /**
17 * Base class helpers for the updating state of a component.
18 */
19 -function ReactComponent(props, context, updater) {
19 +function Component(props, context, updater) {
20 this.props = props;
21 this.context = context;
22 this.refs = emptyObject;
@@ -25,7 +25,7 @@ function ReactComponent(props, context, updater) {
25 this.updater = updater || ReactNoopUpdateQueue;
26 }
27
28 -ReactComponent.prototype.isReactComponent = {};
28 +Component.prototype.isReactComponent = {};
29
30 /**
31 * Sets a subset of the state. Always use this to mutate
@@ -52,7 +52,7 @@ ReactComponent.prototype.isReactComponent = {};
52 * @final
53 * @protected
54 */
55 -ReactComponent.prototype.setState = function(partialState, callback) {
55 +Component.prototype.setState = function(partialState, callback) {
56 invariant(
57 typeof partialState === 'object' ||
58 typeof partialState === 'function' ||
@@ -77,7 +77,7 @@ ReactComponent.prototype.setState = function(partialState, callback) {
77 * @final
78 * @protected
79 */
80 -ReactComponent.prototype.forceUpdate = function(callback) {
80 +Component.prototype.forceUpdate = function(callback) {
81 this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
82 };
83
@@ -100,7 +100,7 @@ if (__DEV__) {
100 ],
101 };
102 var defineDeprecationWarning = function(methodName, info) {
103 - Object.defineProperty(ReactComponent.prototype, methodName, {
103 + Object.defineProperty(Component.prototype, methodName, {
104 get: function() {
105 lowPriorityWarning(
106 false,
@@ -122,8 +122,8 @@ if (__DEV__) {
122 /**
123 * Base class helpers for the updating state of a component.
124 */
125 -function ReactPureComponent(props, context, updater) {
126 - // Duplicated from ReactComponent.
125 +function PureComponent(props, context, updater) {
126 + // Duplicated from Component.
127 this.props = props;
128 this.context = context;
129 this.refs = emptyObject;
@@ -133,15 +133,15 @@ function ReactPureComponent(props, context, updater) {
133 }
134
135 function ComponentDummy() {}
136 -ComponentDummy.prototype = ReactComponent.prototype;
137 -var pureComponentPrototype = (ReactPureComponent.prototype = new ComponentDummy());
138 -pureComponentPrototype.constructor = ReactPureComponent;
136 +ComponentDummy.prototype = Component.prototype;
137 +var pureComponentPrototype = (PureComponent.prototype = new ComponentDummy());
138 +pureComponentPrototype.constructor = PureComponent;
139 // Avoid an extra prototype jump for these methods.
140 -Object.assign(pureComponentPrototype, ReactComponent.prototype);
140 +Object.assign(pureComponentPrototype, Component.prototype);
141 pureComponentPrototype.isPureReactComponent = true;
142
143 -function ReactAsyncComponent(props, context, updater) {
144 - // Duplicated from ReactComponent.
143 +function AsyncComponent(props, context, updater) {
144 + // Duplicated from Component.
145 this.props = props;
146 this.context = context;
147 this.refs = emptyObject;
@@ -150,17 +150,13 @@ function ReactAsyncComponent(props, context, updater) {
150 this.updater = updater || ReactNoopUpdateQueue;
151 }
152
153 -var asyncComponentPrototype = (ReactAsyncComponent.prototype = new ComponentDummy());
154 -asyncComponentPrototype.constructor = ReactAsyncComponent;
153 +var asyncComponentPrototype = (AsyncComponent.prototype = new ComponentDummy());
154 +asyncComponentPrototype.constructor = AsyncComponent;
155 // Avoid an extra prototype jump for these methods.
156 -Object.assign(asyncComponentPrototype, ReactComponent.prototype);
156 +Object.assign(asyncComponentPrototype, Component.prototype);
157 asyncComponentPrototype.unstable_isAsyncReactComponent = true;
158 asyncComponentPrototype.render = function() {
159 return this.props.children;
160 };
161
162 -module.exports = {
163 - Component: ReactComponent,
164 - PureComponent: ReactPureComponent,
165 - AsyncComponent: ReactAsyncComponent,
166 -};
162 +export {Component, PureComponent, AsyncComponent};
packages/react/src/ReactChildren.js
+37 -20
@@ -7,16 +7,12 @@
7
8 'use strict';
9
10 -var emptyFunction = require('fbjs/lib/emptyFunction');
11 -var invariant = require('fbjs/lib/invariant');
10 +import emptyFunction from 'fbjs/lib/emptyFunction';
11 +import invariant from 'fbjs/lib/invariant';
12 +import warning from 'fbjs/lib/warning';
13
13 -var ReactElement = require('./ReactElement');
14 -
15 -if (__DEV__) {
16 - var warning = require('fbjs/lib/warning');
17 -
18 - var {getStackAddendum} = require('./ReactDebugCurrentFrame');
19 -}
14 +import {isValidElement, cloneAndReplaceKey} from './ReactElement';
15 +import ReactDebugCurrentFrame from './ReactDebugCurrentFrame';
16
17 var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
18 var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
@@ -169,7 +165,7 @@ function traverseAllChildrenImpl(
165 'Using Maps as children is unsupported and will likely yield ' +
166 'unexpected results. Convert it to a sequence/iterable of keyed ' +
167 'ReactElements instead.%s',
172 - getStackAddendum(),
168 + ReactDebugCurrentFrame.getStackAddendum(),
169 );
170 didWarnAboutMaps = true;
171 }
@@ -194,7 +190,7 @@ function traverseAllChildrenImpl(
190 addendum =
191 ' If you meant to render a collection of children, use an array ' +
192 'instead.' +
197 - getStackAddendum();
193 + ReactDebugCurrentFrame.getStackAddendum();
194 }
195 var childrenString = '' + children;
196 invariant(
@@ -300,8 +296,8 @@ function mapSingleChildIntoContext(bookKeeping, child, childKey) {
296 emptyFunction.thatReturnsArgument,
297 );
298 } else if (mappedChild != null) {
303 - if (ReactElement.isValidElement(mappedChild)) {
304 - mappedChild = ReactElement.cloneAndReplaceKey(
299 + if (isValidElement(mappedChild)) {
300 + mappedChild = cloneAndReplaceKey(
301 mappedChild,
302 // Keep both the (mapped) and old keys if they differ, just as
303 // traverseAllChildren used to do for objects as children
@@ -383,11 +379,32 @@ function toArray(children) {
379 return result;
380 }
381
386 -var ReactChildren = {
387 - forEach: forEachChildren,
388 - map: mapChildren,
389 - count: countChildren,
390 - toArray: toArray,
391 -};
382 +/**
383 + * Returns the first child in a collection of children and verifies that there
384 + * is only one child in the collection.
385 + *
386 + * See https://reactjs.org/docs/react-api.html#react.children.only
387 + *
388 + * The current implementation of this function assumes that a single child gets
389 + * passed without a wrapper, but the purpose of this helper function is to
390 + * abstract away the particular structure of children.
391 + *
392 + * @param {?object} children Child collection structure.
393 + * @return {ReactElement} The first and only `ReactElement` contained in the
394 + * structure.
395 + */
396 +function onlyChild(children) {
397 + invariant(
398 + isValidElement(children),
399 + 'React.Children.only expected to receive a single React element child.',
400 + );
401 + return children;
402 +}
403
393 -module.exports = ReactChildren;
404 +export {
405 + forEachChildren as forEach,
406 + mapChildren as map,
407 + countChildren as count,
408 + onlyChild as only,
409 + toArray,
410 +};
packages/react/src/ReactCurrentOwner.js
+1 -3
@@ -7,8 +7,6 @@
7 * @flow
8 */
9
10 -'use strict';
11 -
10 import type {Fiber} from 'react-reconciler/src/ReactFiber';
11
12 /**
@@ -25,4 +23,4 @@ var ReactCurrentOwner = {
23 current: (null: null | Fiber),
24 };
25
28 -module.exports = ReactCurrentOwner;
26 +export default ReactCurrentOwner;
packages/react/src/ReactDebugCurrentFrame.js
+1 -1
@@ -24,4 +24,4 @@ if (__DEV__) {
24 };
25 }
26
27 -module.exports = ReactDebugCurrentFrame;
27 +export default ReactDebugCurrentFrame;
packages/react/src/ReactElement.js
+14 -17
@@ -7,12 +7,11 @@
7
8 'use strict';
9
10 -var ReactCurrentOwner = require('./ReactCurrentOwner');
11 -var hasOwnProperty = Object.prototype.hasOwnProperty;
10 +import warning from 'fbjs/lib/warning';
11
13 -if (__DEV__) {
14 - var warning = require('fbjs/lib/warning');
15 -}
12 +import ReactCurrentOwner from './ReactCurrentOwner';
13 +
14 +var hasOwnProperty = Object.prototype.hasOwnProperty;
15
16 // The Symbol used to tag the ReactElement type. If there is no native Symbol
17 // nor polyfill, then a plain number is used for performance.
@@ -175,7 +174,7 @@ var ReactElement = function(type, key, ref, self, source, owner, props) {
174 * Create and return a new ReactElement of the given type.
175 * See https://reactjs.org/docs/react-api.html#createelement
176 */
178 -ReactElement.createElement = function(type, config, children) {
177 +export function createElement(type, config, children) {
178 var propName;
179
180 // Reserved names are extracted
@@ -261,13 +260,13 @@ ReactElement.createElement = function(type, config, children) {
260 ReactCurrentOwner.current,
261 props,
262 );
264 -};
263 +}
264
265 /**
266 * Return a function that produces ReactElements of a given type.
267 * See https://reactjs.org/docs/react-api.html#createfactory
268 */
270 -ReactElement.createFactory = function(type) {
269 +export function createFactory(type) {
270 var factory = ReactElement.createElement.bind(null, type);
271 // Expose the type on the factory and the prototype so that it can be
272 // easily accessed on elements. E.g. `<Foo />.type === Foo`.
@@ -276,9 +275,9 @@ ReactElement.createFactory = function(type) {
275 // Legacy hook TODO: Warn if this is accessed
276 factory.type = type;
277 return factory;
279 -};
278 +}
279
281 -ReactElement.cloneAndReplaceKey = function(oldElement, newKey) {
280 +export function cloneAndReplaceKey(oldElement, newKey) {
281 var newElement = ReactElement(
282 oldElement.type,
283 newKey,
@@ -290,13 +289,13 @@ ReactElement.cloneAndReplaceKey = function(oldElement, newKey) {
289 );
290
291 return newElement;
293 -};
292 +}
293
294 /**
295 * Clone and return a new ReactElement using element as the starting point.
296 * See https://reactjs.org/docs/react-api.html#cloneelement
297 */
299 -ReactElement.cloneElement = function(element, config, children) {
298 +export function cloneElement(element, config, children) {
299 var propName;
300
301 // Original props are copied
@@ -359,7 +358,7 @@ ReactElement.cloneElement = function(element, config, children) {
358 }
359
360 return ReactElement(element.type, key, ref, self, source, owner, props);
362 -};
361 +}
362
363 /**
364 * Verifies the object is a ReactElement.
@@ -368,12 +367,10 @@ ReactElement.cloneElement = function(element, config, children) {
367 * @return {boolean} True if `object` is a valid component.
368 * @final
369 */
371 -ReactElement.isValidElement = function(object) {
370 +export function isValidElement(object) {
371 return (
372 typeof object === 'object' &&
373 object !== null &&
374 object.$$typeof === REACT_ELEMENT_TYPE
375 );
377 -};
378 -
379 -module.exports = ReactElement;
376 +}
packages/react/src/ReactElementValidator.js
+102 -107
@@ -14,21 +14,20 @@
14
15 'use strict';
16
17 -var ReactCurrentOwner = require('./ReactCurrentOwner');
18 -var ReactElement = require('./ReactElement');
17 +import lowPriorityWarning from 'shared/lowPriorityWarning';
18 +import describeComponentFrame from 'shared/describeComponentFrame';
19 +import getComponentName from 'shared/getComponentName';
20 +import checkPropTypes from 'prop-types/checkPropTypes';
21 +import warning from 'fbjs/lib/warning';
22
20 -if (__DEV__) {
21 - var lowPriorityWarning = require('shared/lowPriorityWarning');
22 - var describeComponentFrame = require('shared/describeComponentFrame');
23 - var getComponentName = require('shared/getComponentName');
24 - var checkPropTypes = require('prop-types/checkPropTypes');
25 - var warning = require('fbjs/lib/warning');
26 -
27 - var ReactDebugCurrentFrame = require('./ReactDebugCurrentFrame');
23 +import ReactCurrentOwner from './ReactCurrentOwner';
24 +import {isValidElement, createElement, cloneElement} from './ReactElement';
25 +import ReactDebugCurrentFrame from './ReactDebugCurrentFrame';
26
27 +if (__DEV__) {
28 var currentlyValidatingElement = null;
29
31 - var getDisplayName = function(element: ?ReactElement): string {
30 + var getDisplayName = function(element): string {
31 if (element == null) {
32 return '#empty';
33 } else if (typeof element === 'string' || typeof element === 'number') {
@@ -180,11 +179,11 @@ function validateChildKeys(node, parentType) {
179 if (Array.isArray(node)) {
180 for (var i = 0; i < node.length; i++) {
181 var child = node[i];
183 - if (ReactElement.isValidElement(child)) {
182 + if (isValidElement(child)) {
183 validateExplicitKey(child, parentType);
184 }
185 }
187 - } else if (ReactElement.isValidElement(node)) {
186 + } else if (isValidElement(node)) {
187 // This element was passed in a valid location.
188 if (node._store) {
189 node._store.validated = true;
@@ -199,7 +198,7 @@ function validateChildKeys(node, parentType) {
198 var iterator = iteratorFn.call(node);
199 var step;
200 while (!(step = iterator.next()).done) {
202 - if (ReactElement.isValidElement(step.value)) {
201 + if (isValidElement(step.value)) {
202 validateExplicitKey(step.value, parentType);
203 }
204 }
@@ -267,108 +266,104 @@ function validateFragmentProps(fragment) {
266 currentlyValidatingElement = null;
267 }
268
270 -var ReactElementValidator = {
271 - createElement: function(type, props, children) {
272 - var validType =
273 - typeof type === 'string' ||
274 - typeof type === 'function' ||
275 - typeof type === 'symbol' ||
276 - typeof type === 'number';
277 - // We warn in this case but don't throw. We expect the element creation to
278 - // succeed and there will likely be errors in render.
279 - if (!validType) {
280 - var info = '';
281 - if (
282 - type === undefined ||
283 - (typeof type === 'object' &&
284 - type !== null &&
285 - Object.keys(type).length === 0)
286 - ) {
287 - info +=
288 - ' You likely forgot to export your component from the file ' +
289 - "it's defined in.";
290 - }
269 +export function createElementWithValidation(type, props, children) {
270 + var validType =
271 + typeof type === 'string' ||
272 + typeof type === 'function' ||
273 + typeof type === 'symbol' ||
274 + typeof type === 'number';
275 + // We warn in this case but don't throw. We expect the element creation to
276 + // succeed and there will likely be errors in render.
277 + if (!validType) {
278 + var info = '';
279 + if (
280 + type === undefined ||
281 + (typeof type === 'object' &&
282 + type !== null &&
283 + Object.keys(type).length === 0)
284 + ) {
285 + info +=
286 + ' You likely forgot to export your component from the file ' +
287 + "it's defined in.";
288 + }
289
292 - var sourceInfo = getSourceInfoErrorAddendum(props);
293 - if (sourceInfo) {
294 - info += sourceInfo;
295 - } else {
296 - info += getDeclarationErrorAddendum();
297 - }
290 + var sourceInfo = getSourceInfoErrorAddendum(props);
291 + if (sourceInfo) {
292 + info += sourceInfo;
293 + } else {
294 + info += getDeclarationErrorAddendum();
295 + }
296
299 - info += ReactDebugCurrentFrame.getStackAddendum() || '';
297 + info += getStackAddendum() || '';
298
301 - warning(
302 - false,
303 - 'React.createElement: type is invalid -- expected a string (for ' +
304 - 'built-in components) or a class/function (for composite ' +
305 - 'components) but got: %s.%s',
306 - type == null ? type : typeof type,
307 - info,
308 - );
309 - }
299 + warning(
300 + false,
301 + 'React.createElement: type is invalid -- expected a string (for ' +
302 + 'built-in components) or a class/function (for composite ' +
303 + 'components) but got: %s.%s',
304 + type == null ? type : typeof type,
305 + info,
306 + );
307 + }
308
311 - var element = ReactElement.createElement.apply(this, arguments);
309 + var element = createElement.apply(this, arguments);
310
313 - // The result can be nullish if a mock or a custom function is used.
314 - // TODO: Drop this when these are no longer allowed as the type argument.
315 - if (element == null) {
316 - return element;
317 - }
311 + // The result can be nullish if a mock or a custom function is used.
312 + // TODO: Drop this when these are no longer allowed as the type argument.
313 + if (element == null) {
314 + return element;
315 + }
316
319 - // Skip key warning if the type isn't valid since our key validation logic
320 - // doesn't expect a non-string/function type and can throw confusing errors.
321 - // We don't want exception behavior to differ between dev and prod.
322 - // (Rendering will throw with a helpful message and as soon as the type is
323 - // fixed, the key warnings will appear.)
324 - if (validType) {
325 - for (var i = 2; i < arguments.length; i++) {
326 - validateChildKeys(arguments[i], type);
327 - }
317 + // Skip key warning if the type isn't valid since our key validation logic
318 + // doesn't expect a non-string/function type and can throw confusing errors.
319 + // We don't want exception behavior to differ between dev and prod.
320 + // (Rendering will throw with a helpful message and as soon as the type is
321 + // fixed, the key warnings will appear.)
322 + if (validType) {
323 + for (var i = 2; i < arguments.length; i++) {
324 + validateChildKeys(arguments[i], type);
325 }
326 + }
327
330 - if (typeof type === 'symbol' && type === REACT_FRAGMENT_TYPE) {
331 - validateFragmentProps(element);
332 - } else {
333 - validatePropTypes(element);
334 - }
328 + if (typeof type === 'symbol' && type === REACT_FRAGMENT_TYPE) {
329 + validateFragmentProps(element);
330 + } else {
331 + validatePropTypes(element);
332 + }
333
336 - return element;
337 - },
338 -
339 - createFactory: function(type) {
340 - var validatedFactory = ReactElementValidator.createElement.bind(null, type);
341 - // Legacy hook TODO: Warn if this is accessed
342 - validatedFactory.type = type;
343 -
344 - if (__DEV__) {
345 - Object.defineProperty(validatedFactory, 'type', {
346 - enumerable: false,
347 - get: function() {
348 - lowPriorityWarning(
349 - false,
350 - 'Factory.type is deprecated. Access the class directly ' +
351 - 'before passing it to createFactory.',
352 - );
353 - Object.defineProperty(this, 'type', {
354 - value: type,
355 - });
356 - return type;
357 - },
358 - });
359 - }
334 + return element;
335 +}
336
361 - return validatedFactory;
362 - },
337 +export function createFactoryWithValidation(type) {
338 + var validatedFactory = createElementWithValidation.bind(null, type);
339 + // Legacy hook TODO: Warn if this is accessed
340 + validatedFactory.type = type;
341
364 - cloneElement: function(element, props, children) {
365 - var newElement = ReactElement.cloneElement.apply(this, arguments);
366 - for (var i = 2; i < arguments.length; i++) {
367 - validateChildKeys(arguments[i], newElement.type);
368 - }
369 - validatePropTypes(newElement);
370 - return newElement;
371 - },
372 -};
342 + if (__DEV__) {
343 + Object.defineProperty(validatedFactory, 'type', {
344 + enumerable: false,
345 + get: function() {
346 + lowPriorityWarning(
347 + false,
348 + 'Factory.type is deprecated. Access the class directly ' +
349 + 'before passing it to createFactory.',
350 + );
351 + Object.defineProperty(this, 'type', {
352 + value: type,
353 + });
354 + return type;
355 + },
356 + });
357 + }
358
374 -module.exports = ReactElementValidator;
359 + return validatedFactory;
360 +}
361 +
362 +export function cloneElementWithValidation(element, props, children) {
363 + var newElement = cloneElement.apply(this, arguments);
364 + for (var i = 2; i < arguments.length; i++) {
365 + validateChildKeys(arguments[i], newElement.type);
366 + }
367 + validatePropTypes(newElement);
368 + return newElement;
369 +}
packages/react/src/ReactNoopUpdateQueue.js
+4 -5
@@ -7,10 +7,9 @@
7
8 'use strict';
9
10 -if (__DEV__) {
11 - var warning = require('fbjs/lib/warning');
12 - var didWarnStateUpdateForUnmountedComponent = {};
13 -}
10 +import warning from 'fbjs/lib/warning';
11 +
12 +var didWarnStateUpdateForUnmountedComponent = {};
13
14 function warnNoop(publicInstance, callerName) {
15 if (__DEV__) {
@@ -113,4 +112,4 @@ var ReactNoopUpdateQueue = {
112 },
113 };
114
116 -module.exports = ReactNoopUpdateQueue;
115 +export default ReactNoopUpdateQueue;
packages/react/src/onlyChild.js deleted
-35
@@ -1,35 +0,0 @@
1 -/**
2 - * Copyright (c) 2013-present, Facebook, Inc.
3 - *
4 - * This source code is licensed under the MIT license found in the
5 - * LICENSE file in the root directory of this source tree.
6 - */
7 -'use strict';
8 -
9 -var invariant = require('fbjs/lib/invariant');
10 -
11 -var ReactElement = require('./ReactElement');
12 -
13 -/**
14 - * Returns the first child in a collection of children and verifies that there
15 - * is only one child in the collection.
16 - *
17 - * See https://reactjs.org/docs/react-api.html#react.children.only
18 - *
19 - * The current implementation of this function assumes that a single child gets
20 - * passed without a wrapper, but the purpose of this helper function is to
21 - * abstract away the particular structure of children.
22 - *
23 - * @param {?object} children Child collection structure.
24 - * @return {ReactElement} The first and only `ReactElement` contained in the
25 - * structure.
26 - */
27 -function onlyChild(children) {
28 - invariant(
29 - ReactElement.isValidElement(children),
30 - 'React.Children.only expected to receive a single React element child.',
31 - );
32 - return children;
33 -}
34 -
35 -module.exports = onlyChild;
packages/shared/ReactDOMFrameScheduling.js
+3 -5
@@ -19,11 +19,10 @@
19
20 import type {Deadline} from 'react-reconciler';
21
22 -var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment');
22 +import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment';
23 +import warning from 'fbjs/lib/warning';
24
25 if (__DEV__) {
25 - var warning = require('fbjs/lib/warning');
26 -
26 if (
27 ExecutionEnvironment.canUseDOM &&
28 typeof requestAnimationFrame !== 'function'
@@ -164,5 +163,4 @@ if (!ExecutionEnvironment.canUseDOM) {
163 rIC = requestIdleCallback;
164 }
165
167 -exports.now = now;
168 -exports.rIC = rIC;
166 +export {now, rIC};
packages/shared/ReactErrorUtils.js
+2 -2
@@ -9,7 +9,7 @@
9
10 'use strict';
11
12 -const invariant = require('fbjs/lib/invariant');
12 +import invariant from 'fbjs/lib/invariant';
13
14 const ReactErrorUtils = {
15 // Used by Fiber to simulate a try-catch.
@@ -272,4 +272,4 @@ let rethrowCaughtError = function() {
272 }
273 };
274
275 -module.exports = ReactErrorUtils;
275 +export default ReactErrorUtils;
packages/shared/ReactFeatureFlags.js
+1 -1
@@ -37,4 +37,4 @@ if (__DEV__) {
37 }
38 }
39
40 -module.exports = ReactFeatureFlags;
40 +export default ReactFeatureFlags;
packages/shared/ReactFiberComponentTreeHook.js
+7 -10
@@ -11,15 +11,14 @@
11
12 import type {Fiber} from 'react-reconciler/src/ReactFiber';
13
14 -var ReactTypeOfWork = require('./ReactTypeOfWork');
15 -var {
14 +import {
15 IndeterminateComponent,
16 FunctionalComponent,
17 ClassComponent,
18 HostComponent,
20 -} = ReactTypeOfWork;
21 -var describeComponentFrame = require('./describeComponentFrame');
22 -var getComponentName = require('./getComponentName');
19 +} from './ReactTypeOfWork';
20 +import describeComponentFrame from './describeComponentFrame';
21 +import getComponentName from './getComponentName';
22
23 function describeFiber(fiber: Fiber): string {
24 switch (fiber.tag) {
@@ -43,7 +42,9 @@ function describeFiber(fiber: Fiber): string {
42 // This function can only be called with a work-in-progress fiber and
43 // only during begin or complete phase. Do not call it under any other
44 // circumstances.
46 -function getStackAddendumByWorkInProgressFiber(workInProgress: Fiber): string {
45 +export function getStackAddendumByWorkInProgressFiber(
46 + workInProgress: Fiber,
47 +): string {
48 var info = '';
49 var node = workInProgress;
50 do {
@@ -53,7 +54,3 @@ function getStackAddendumByWorkInProgressFiber(workInProgress: Fiber): string {
54 } while (node);
55 return info;
56 }
56 -
57 -module.exports = {
58 - getStackAddendumByWorkInProgressFiber,
59 -};
packages/shared/ReactFiberTreeReflection.js
+18 -23
@@ -11,23 +11,20 @@
11
12 import type {Fiber} from 'react-reconciler/src/ReactFiber';
13
14 -var invariant = require('fbjs/lib/invariant');
14 +import invariant from 'fbjs/lib/invariant';
15 +import warning from 'fbjs/lib/warning';
16
16 -var ReactInstanceMap = require('./ReactInstanceMap');
17 -var {ReactCurrentOwner} = require('./ReactGlobalSharedState');
18 -var getComponentName = require('./getComponentName');
19 -var {
17 +import * as ReactInstanceMap from './ReactInstanceMap';
18 +import {ReactCurrentOwner} from './ReactGlobalSharedState';
19 +import getComponentName from './getComponentName';
20 +import {
21 ClassComponent,
22 HostComponent,
23 HostRoot,
24 HostPortal,
25 HostText,
25 -} = require('./ReactTypeOfWork');
26 -var {NoEffect, Placement} = require('./ReactTypeOfSideEffect');
27 -
28 -if (__DEV__) {
29 - var warning = require('fbjs/lib/warning');
30 -}
26 +} from './ReactTypeOfWork';
27 +import {NoEffect, Placement} from './ReactTypeOfSideEffect';
28
29 var MOUNTING = 1;
30 var MOUNTED = 2;
@@ -61,11 +58,12 @@ function isFiberMountedImpl(fiber: Fiber): number {
58 // that has been unmounted.
59 return UNMOUNTED;
60 }
64 -exports.isFiberMounted = function(fiber: Fiber): boolean {
61 +
62 +export function isFiberMounted(fiber: Fiber): boolean {
63 return isFiberMountedImpl(fiber) === MOUNTED;
66 -};
64 +}
65
68 -exports.isMounted = function(component: React$Component<any, any>): boolean {
66 +export function isMounted(component: React$Component<any, any>): boolean {
67 if (__DEV__) {
68 const owner = (ReactCurrentOwner.current: any);
69 if (owner !== null && owner.tag === ClassComponent) {
@@ -89,7 +87,7 @@ exports.isMounted = function(component: React$Component<any, any>): boolean {
87 return false;
88 }
89 return isFiberMountedImpl(fiber) === MOUNTED;
92 -};
90 +}
91
92 function assertIsMounted(fiber) {
93 invariant(
@@ -98,7 +96,7 @@ function assertIsMounted(fiber) {
96 );
97 }
98
101 -function findCurrentFiberUsingSlowPath(fiber: Fiber): Fiber | null {
99 +export function findCurrentFiberUsingSlowPath(fiber: Fiber): Fiber | null {
100 let alternate = fiber.alternate;
101 if (!alternate) {
102 // If there is no alternate, then we only need to check if it is mounted.
@@ -223,9 +221,8 @@ function findCurrentFiberUsingSlowPath(fiber: Fiber): Fiber | null {
221 // Otherwise B has to be current branch.
222 return alternate;
223 }
226 -exports.findCurrentFiberUsingSlowPath = findCurrentFiberUsingSlowPath;
224
228 -exports.findCurrentHostFiber = function(parent: Fiber): Fiber | null {
225 +export function findCurrentHostFiber(parent: Fiber): Fiber | null {
226 const currentParent = findCurrentFiberUsingSlowPath(parent);
227 if (!currentParent) {
228 return null;
@@ -256,11 +253,9 @@ exports.findCurrentHostFiber = function(parent: Fiber): Fiber | null {
253 // Flow needs the return null here, but ESLint complains about it.
254 // eslint-disable-next-line no-unreachable
255 return null;
259 -};
256 +}
257
261 -exports.findCurrentHostFiberWithNoPortals = function(
262 - parent: Fiber,
263 -): Fiber | null {
258 +export function findCurrentHostFiberWithNoPortals(parent: Fiber): Fiber | null {
259 const currentParent = findCurrentFiberUsingSlowPath(parent);
260 if (!currentParent) {
261 return null;
@@ -291,4 +286,4 @@ exports.findCurrentHostFiberWithNoPortals = function(
286 // Flow needs the return null here, but ESLint complains about it.
287 // eslint-disable-next-line no-unreachable
288 return null;
294 -};
289 +}
packages/shared/ReactGlobalSharedState.js
+6 -12
@@ -7,17 +7,11 @@
7
8 'use strict';
9
10 -var ReactInternals = require('react')
11 - .__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
10 +import React from 'react';
11
13 -var ReactGlobalSharedState = {
14 - ReactCurrentOwner: ReactInternals.ReactCurrentOwner,
15 -};
12 +var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
13
17 -if (__DEV__) {
18 - Object.assign(ReactGlobalSharedState, {
19 - ReactDebugCurrentFrame: ReactInternals.ReactDebugCurrentFrame,
20 - });
21 -}
22 -
23 -module.exports = ReactGlobalSharedState;
14 +export const ReactCurrentOwner = ReactInternals.ReactCurrentOwner;
15 +export const ReactDebugCurrentFrame = __DEV__
16 + ? ReactInternals.ReactDebugCurrentFrame
17 + : null;
packages/shared/ReactInstanceMap.js
+13 -17
@@ -17,27 +17,23 @@
17 * If this becomes an actual Map, that will break.
18 */
19
20 -var ReactInstanceMap = {
21 - /**
20 +/**
21 * This API should be called `delete` but we'd have to make sure to always
22 * transform these to strings for IE support. When this transform is fully
23 * supported we can rename it.
24 */
26 - remove: function(key) {
27 - key._reactInternalFiber = undefined;
28 - },
29 -
30 - get: function(key) {
31 - return key._reactInternalFiber;
32 - },
25 +export function remove(key) {
26 + key._reactInternalFiber = undefined;
27 +}
28
34 - has: function(key) {
35 - return key._reactInternalFiber !== undefined;
36 - },
29 +export function get(key) {
30 + return key._reactInternalFiber;
31 +}
32
38 - set: function(key, value) {
39 - key._reactInternalFiber = value;
40 - },
41 -};
33 +export function has(key) {
34 + return key._reactInternalFiber !== undefined;
35 +}
36
43 -module.exports = ReactInstanceMap;
37 +export function set(key, value) {
38 + key._reactInternalFiber = value;
39 +}
packages/shared/ReactTreeTraversal.js
+6 -14
@@ -7,7 +7,7 @@
7
8 'use strict';
9
10 -var {HostComponent} = require('./ReactTypeOfWork');
10 +import {HostComponent} from './ReactTypeOfWork';
11
12 function getParent(inst) {
13 do {
@@ -28,7 +28,7 @@ function getParent(inst) {
28 * Return the lowest common ancestor of A and B, or null if they are in
29 * different trees.
30 */
31 -function getLowestCommonAncestor(instA, instB) {
31 +export function getLowestCommonAncestor(instA, instB) {
32 var depthA = 0;
33 for (var tempA = instA; tempA; tempA = getParent(tempA)) {
34 depthA++;
@@ -65,7 +65,7 @@ function getLowestCommonAncestor(instA, instB) {
65 /**
66 * Return if A is an ancestor of B.
67 */
68 -function isAncestor(instA, instB) {
68 +export function isAncestor(instA, instB) {
69 while (instB) {
70 if (instA === instB || instA === instB.alternate) {
71 return true;
@@ -78,14 +78,14 @@ function isAncestor(instA, instB) {
78 /**
79 * Return the parent instance of the passed-in instance.
80 */
81 -function getParentInstance(inst) {
81 +export function getParentInstance(inst) {
82 return getParent(inst);
83 }
84
85 /**
86 * Simulates the traversal of a two-phase, capture/bubble event dispatch.
87 */
88 -function traverseTwoPhase(inst, fn, arg) {
88 +export function traverseTwoPhase(inst, fn, arg) {
89 var path = [];
90 while (inst) {
91 path.push(inst);
@@ -107,7 +107,7 @@ function traverseTwoPhase(inst, fn, arg) {
107 * Does not invoke the callback on the nearest common ancestor because nothing
108 * "entered" or "left" that element.
109 */
110 -function traverseEnterLeave(from, to, fn, argFrom, argTo) {
110 +export function traverseEnterLeave(from, to, fn, argFrom, argTo) {
111 const common = from && to ? getLowestCommonAncestor(from, to) : null;
112 const pathFrom = [];
113 while (true) {
@@ -146,11 +146,3 @@ function traverseEnterLeave(from, to, fn, argFrom, argTo) {
146 fn(pathTo[i], 'captured', argTo);
147 }
148 }
149 -
150 -module.exports = {
151 - isAncestor: isAncestor,
152 - getLowestCommonAncestor: getLowestCommonAncestor,
153 - getParentInstance: getParentInstance,
154 - traverseTwoPhase: traverseTwoPhase,
155 - traverseEnterLeave: traverseEnterLeave,
156 -};
packages/shared/ReactTypeOfSideEffect.js
+13 -14
@@ -11,17 +11,16 @@
11
12 export type TypeOfSideEffect = number;
13
14 -module.exports = {
15 - // Don't change these two values:
16 - NoEffect: 0, // 0b00000000
17 - PerformedWork: 1, // 0b00000001
18 - // You can change the rest (and add more).
19 - Placement: 2, // 0b00000010
20 - Update: 4, // 0b00000100
21 - PlacementAndUpdate: 6, // 0b00000110
22 - Deletion: 8, // 0b00001000
23 - ContentReset: 16, // 0b00010000
24 - Callback: 32, // 0b00100000
25 - Err: 64, // 0b01000000
26 - Ref: 128, // 0b10000000
27 -};
14 +// Don't change these two values:
15 +export const NoEffect = 0; // 0b00000000
16 +export const PerformedWork = 1; // 0b00000001
17 +
18 +// You can change the rest (and add more).
19 +export const Placement = 2; // 0b00000010
20 +export const Update = 4; // 0b00000100
21 +export const PlacementAndUpdate = 6; // 0b00000110
22 +export const Deletion = 8; // 0b00001000
23 +export const ContentReset = 16; // 0b00010000
24 +export const Callback = 32; // 0b00100000
25 +export const Err = 64; // 0b01000000
26 +export const Ref = 128; // 0b10000000
packages/shared/ReactTypeOfWork.js
+11 -13
@@ -11,16 +11,14 @@
11
12 export type TypeOfWork = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;
13
14 -module.exports = {
15 - IndeterminateComponent: 0, // Before we know whether it is functional or class
16 - FunctionalComponent: 1,
17 - ClassComponent: 2,
18 - HostRoot: 3, // Root of a host tree. Could be nested inside another node.
19 - HostPortal: 4, // A subtree. Could be an entry point to a different renderer.
20 - HostComponent: 5,
21 - HostText: 6,
22 - CallComponent: 7,
23 - CallHandlerPhase: 8,
24 - ReturnComponent: 9,
25 - Fragment: 10,
26 -};
14 +export const IndeterminateComponent = 0; // Before we know whether it is functional or class
15 +export const FunctionalComponent = 1;
16 +export const ClassComponent = 2;
17 +export const HostRoot = 3; // Root of a host tree. Could be nested inside another node.
18 +export const HostPortal = 4; // A subtree. Could be an entry point to a different renderer.
19 +export const HostComponent = 5;
20 +export const HostText = 6;
21 +export const CallComponent = 7;
22 +export const CallHandlerPhase = 8;
23 +export const ReturnComponent = 9;
24 +export const Fragment = 10;
packages/shared/ReactVersion.js
+1
@@ -7,4 +7,5 @@
7
8 'use strict';
9
10 +// TODO: this is special because it gets imported during build.
11 module.exports = '16.0.0';
packages/shared/__tests__/ReactErrorUtils-test.js
+4 -4
@@ -14,7 +14,7 @@ var ReactErrorUtils;
14 describe('ReactErrorUtils', () => {
15 beforeEach(() => {
16 // TODO: can we express this test with only public API?
17 - ReactErrorUtils = require('shared/ReactErrorUtils');
17 + ReactErrorUtils = require('shared/ReactErrorUtils').default;
18 });
19
20 // Run tests in both DEV and production
@@ -36,7 +36,7 @@ describe('ReactErrorUtils', () => {
36 };
37
38 jest.resetModules();
39 - ReactErrorUtils = require('shared/ReactErrorUtils');
39 + ReactErrorUtils = require('shared/ReactErrorUtils').default;
40 });
41
42 afterEach(() => {
@@ -161,9 +161,9 @@ describe('ReactErrorUtils', () => {
161 });
162
163 it('handles nested errors in separate renderers', () => {
164 - const ReactErrorUtils1 = require('shared/ReactErrorUtils');
164 + const ReactErrorUtils1 = require('shared/ReactErrorUtils').default;
165 jest.resetModules();
166 - const ReactErrorUtils2 = require('shared/ReactErrorUtils');
166 + const ReactErrorUtils2 = require('shared/ReactErrorUtils').default;
167 expect(ReactErrorUtils1).not.toEqual(ReactErrorUtils2);
168
169 let ops = [];
packages/shared/__tests__/reactProdInvariant-test.js
+1 -1
@@ -13,7 +13,7 @@ var reactProdInvariant;
13 describe('reactProdInvariant', () => {
14 beforeEach(() => {
15 jest.resetModules();
16 - reactProdInvariant = require('shared/reactProdInvariant');
16 + reactProdInvariant = require('shared/reactProdInvariant').default;
17 });
18
19 it('should throw with the correct number of `%s`s in the URL', () => {
packages/shared/describeComponentFrame.js
+2 -2
@@ -9,7 +9,7 @@
9
10 'use strict';
11
12 -module.exports = function(
12 +export default function(
13 name: null | string,
14 source: any,
15 ownerName: null | string,
@@ -25,4 +25,4 @@ module.exports = function(
25 ')'
26 : ownerName ? ' (created by ' + ownerName + ')' : '')
27 );
28 -};
28 +}
packages/shared/getComponentName.js
+1 -1
@@ -22,4 +22,4 @@ function getComponentName(fiber: Fiber): string | null {
22 return null;
23 }
24
25 -module.exports = getComponentName;
25 +export default getComponentName;
packages/shared/isTextInputElement.js
+1 -1
@@ -44,4 +44,4 @@ function isTextInputElement(elem: ?HTMLElement): boolean {
44 return false;
45 }
46
47 -module.exports = isTextInputElement;
47 +export default isTextInputElement;
packages/shared/lowPriorityWarning.js
+1 -1
@@ -51,4 +51,4 @@ if (__DEV__) {
51 };
52 }
53
54 -module.exports = lowPriorityWarning;
54 +export default lowPriorityWarning;
packages/shared/reactProdInvariant.js
+1 -1
@@ -39,4 +39,4 @@ function reactProdInvariant(code: string): void {
39 throw error;
40 }
41
42 -module.exports = reactProdInvariant;
42 +export default reactProdInvariant;
packages/shared/validateCallback.js
+1 -1
@@ -20,4 +20,4 @@ function validateCallback(callback: ?Function) {
20 );
21 }
22
23 -module.exports = validateCallback;
23 +export default validateCallback;
scripts/babel/transform-object-assign-require.js
+3 -10
@@ -8,18 +8,11 @@
8 'use strict';
9
10 module.exports = function autoImporter(babel) {
11 - const t = babel.types;
12 -
11 function getAssignIdent(path, file, state) {
14 - if (!state.id) {
15 - state.id = path.scope.generateUidIdentifier('assign');
16 - path.scope.getProgramParent().push({
17 - id: state.id,
18 - init: t.callExpression(t.identifier('require'), [
19 - t.stringLiteral('object-assign'),
20 - ]),
21 - });
12 + if (state.id) {
13 + return state.id;
14 }
15 + state.id = file.addImport('object-assign', 'default', 'assign');
16 return state.id;
17 }
18
scripts/error-codes/__tests__/replace-invariant-error-codes-test.js
+21 -24
@@ -23,7 +23,7 @@ function compare(input, output) {
23
24 var oldEnv;
25
26 -describe('dev-expression', () => {
26 +describe('error codes transform', () => {
27 beforeEach(() => {
28 oldEnv = process.env.NODE_ENV;
29 process.env.NODE_ENV = '';
@@ -33,19 +33,12 @@ describe('dev-expression', () => {
33 process.env.NODE_ENV = oldEnv;
34 });
35
36 - it("should add `reactProdInvariant` when it finds `require('invariant')`", () => {
37 - compare(
38 - "var invariant = require('invariant');",
39 - `var _prodInvariant = require('shared/reactProdInvariant');
40 -
41 -var invariant = require('invariant');`
42 - );
43 - });
44 -
36 it('should replace simple invariant calls', () => {
37 compare(
47 - "invariant(condition, 'Do not override existing functions.');",
48 - "var _prodInvariant = require('shared/reactProdInvariant');\n\n" +
38 + "import invariant from 'shared/reactProdInvariant';\n" +
39 + "invariant(condition, 'Do not override existing functions.');",
40 + "import _prodInvariant from 'shared/reactProdInvariant';\n" +
41 + "import invariant from 'shared/reactProdInvariant';\n" +
42 '!condition ? ' +
43 '__DEV__ ? ' +
44 "invariant(false, 'Do not override existing functions.') : " +
@@ -61,12 +54,11 @@ var invariant = require('invariant');`
54 `_prodInvariant('16') : void 0;`;
55
56 compare(
64 - `var invariant = require('invariant');
57 + `import invariant from 'invariant';
58 invariant(condition, 'Do not override existing functions.');
59 invariant(condition, 'Do not override existing functions.');`,
67 - `var _prodInvariant = require('shared/reactProdInvariant');
68 -
69 -var invariant = require('invariant');
60 + `import _prodInvariant from 'shared/reactProdInvariant';
61 +import invariant from 'invariant';
62 ${expectedInvariantTransformResult}
63 ${expectedInvariantTransformResult}`
64 );
@@ -74,8 +66,10 @@ ${expectedInvariantTransformResult}`
66
67 it('should support invariant calls with args', () => {
68 compare(
77 - "invariant(condition, 'Expected %s target to be an array; got %s', 'foo', 'bar');",
78 - "var _prodInvariant = require('shared/reactProdInvariant');\n\n" +
69 + "import invariant from 'shared/reactProdInvariant';\n" +
70 + "invariant(condition, 'Expected %s target to be an array; got %s', 'foo', 'bar');",
71 + "import _prodInvariant from 'shared/reactProdInvariant';\n" +
72 + "import invariant from 'shared/reactProdInvariant';\n" +
73 '!condition ? ' +
74 '__DEV__ ? ' +
75 "invariant(false, 'Expected %s target to be an array; got %s', 'foo', 'bar') : " +
@@ -85,8 +79,10 @@ ${expectedInvariantTransformResult}`
79
80 it('should support invariant calls with a concatenated template string and args', () => {
81 compare(
88 - "invariant(condition, 'Expected a component class, ' + 'got %s.' + '%s', 'Foo', 'Bar');",
89 - "var _prodInvariant = require('shared/reactProdInvariant');\n\n" +
82 + "import invariant from 'shared/reactProdInvariant';\n" +
83 + "invariant(condition, 'Expected a component class, ' + 'got %s.' + '%s', 'Foo', 'Bar');",
84 + "import _prodInvariant from 'shared/reactProdInvariant';\n" +
85 + "import invariant from 'shared/reactProdInvariant';\n" +
86 '!condition ? ' +
87 '__DEV__ ? ' +
88 "invariant(false, 'Expected a component class, got %s.%s', 'Foo', 'Bar') : " +
@@ -96,10 +92,11 @@ ${expectedInvariantTransformResult}`
92
93 it('should correctly transform invariants that are not in the error codes map', () => {
94 compare(
99 - "invariant(condition, 'This is not a real error message.');",
100 - `var _prodInvariant = require('shared/reactProdInvariant');
101 -
102 -!condition ? invariant(false, 'This is not a real error message.') : void 0;`
95 + "import invariant from 'shared/reactProdInvariant';\n" +
96 + "invariant(condition, 'This is not a real error message.');",
97 + "import _prodInvariant from 'shared/reactProdInvariant';\n" +
98 + "import invariant from 'shared/reactProdInvariant';\n" +
99 + "!condition ? invariant(false, 'This is not a real error message.') : void 0;"
100 );
101 });
102 });
scripts/error-codes/replace-invariant-error-codes.js
+9 -21
@@ -16,17 +16,13 @@ module.exports = function(babel) {
16 var SEEN_SYMBOL = Symbol('replace-invariant-error-codes.seen');
17
18 // Generate a hygienic identifier
19 - function getProdInvariantIdentifier(path, localState) {
19 + function getProdInvariantIdentifier(path, file, localState) {
20 if (!localState.prodInvariantIdentifier) {
21 - localState.prodInvariantIdentifier = path.scope.generateUidIdentifier(
21 + localState.prodInvariantIdentifier = file.addImport(
22 + 'shared/reactProdInvariant',
23 + 'default',
24 'prodInvariant'
25 );
24 - path.scope.getProgramParent().push({
25 - id: localState.prodInvariantIdentifier,
26 - init: t.callExpression(t.identifier('require'), [
27 - t.stringLiteral('shared/reactProdInvariant'),
28 - ]),
29 - });
26 }
27 return localState.prodInvariantIdentifier;
28 }
@@ -40,23 +36,15 @@ module.exports = function(babel) {
36
37 visitor: {
38 CallExpression: {
43 - exit: function(path) {
39 + exit: function(path, file) {
40 var node = path.node;
41 // Ignore if it's already been processed
42 if (node[SEEN_SYMBOL]) {
43 return;
44 }
49 - // Insert `var PROD_INVARIANT = require('reactProdInvariant');`
50 - // before all `require('invariant')`s.
51 - // NOTE it doesn't support ES6 imports yet.
52 - if (
53 - path.get('callee').isIdentifier({name: 'require'}) &&
54 - path.get('arguments')[0] &&
55 - path.get('arguments')[0].isStringLiteral({value: 'invariant'})
56 - ) {
57 - node[SEEN_SYMBOL] = true;
58 - getProdInvariantIdentifier(path, this);
59 - } else if (path.get('callee').isIdentifier({name: 'invariant'})) {
45 + // Insert `import PROD_INVARIANT from 'reactProdInvariant';`
46 + // before all `invariant()` calls.
47 + if (path.get('callee').isIdentifier({name: 'invariant'})) {
48 // Turns this code:
49 //
50 // invariant(condition, argument, 'foo', 'bar');
@@ -105,7 +93,7 @@ module.exports = function(babel) {
93 );
94 var errorMap = invertObject(existingErrorMap);
95
108 - var localInvariantId = getProdInvariantIdentifier(path, this);
96 + var localInvariantId = getProdInvariantIdentifier(path, file, this);
97 var prodErrorId = errorMap[errorMsgLiteral];
98 var body = null;
99
scripts/flow/react-native-host-hooks.js
+1 -1
@@ -117,5 +117,5 @@ declare module 'CSComponent' {
117 }
118
119 declare module 'CSStatefulComponent' {
120 - declare function exports(spec: any): any;
120 + declare function CSStatefulComponent(spec: any): any;
121 }
scripts/jest/preprocessor.js
+3
@@ -34,6 +34,9 @@ var pathToErrorCodes = require.resolve('../error-codes/codes.json');
34 // TODO: make sure this stays in sync with gulpfile
35 var babelOptions = {
36 plugins: [
37 + // For Node environment only. For builds, Rollup takes care of ESM.
38 + require.resolve('babel-plugin-transform-es2015-modules-commonjs'),
39 +
40 pathToBabelPluginDevWithCode,
41 // Keep stacks detailed in tests.
42 // Don't put this in .babelrc so that we don't embed filenames
scripts/jest/setup.js
+1 -1
@@ -3,7 +3,7 @@
3 // We want to globally mock this but jest doesn't let us do that by default
4 // for a file that already exists. So we have to explicitly mock it.
5 jest.mock('shared/ReactFeatureFlags', () => {
6 - const flags = require.requireActual('shared/ReactFeatureFlags');
6 + const flags = require.requireActual('shared/ReactFeatureFlags').default;
7 return Object.assign({}, flags, {
8 disableNewFiberFeatures: true,
9 });
scripts/rollup/build.js
+32 -18
@@ -221,6 +221,27 @@ function handleRollupWarnings(warning) {
221 console.error(warning.message);
222 process.exit(1);
223 }
224 + if (warning.code === 'UNUSED_EXTERNAL_IMPORT') {
225 + const match = warning.message.match(/external module '([^']+)'/);
226 + if (!match || typeof match[1] !== 'string') {
227 + throw new Error(
228 + 'Could not parse a Rollup warning. ' + 'Fix this method.'
229 + );
230 + }
231 + const importSideEffects = Modules.getImportSideEffects();
232 + const path = match[1];
233 + if (typeof importSideEffects[path] !== 'boolean') {
234 + throw new Error(
235 + 'An external module "' +
236 + path +
237 + '" is used in a DEV-only code path ' +
238 + 'but we do not know if it is safe to omit an unused require() to it in production. ' +
239 + 'Please add it to the `importSideEffects` list in `scripts/rollup/modules.js`.'
240 + );
241 + }
242 + // Don't warn. We will remove side effectless require() in a later pass.
243 + return;
244 + }
245 console.warn(warning.message || warning);
246 }
247
@@ -345,23 +366,6 @@ function getUglifyConfig(configs) {
366 };
367 }
368
348 -// We use this for various shims, such as www forks of the code,
349 -// renderer-specific feature flag overrides, and UMD optimizations.
350 -function shimModules(shims) {
351 - // For some reason, even if we use the alias plugin,
352 - // Rollup still attempts to bundle unused original code
353 - // if it exists. We have to explicitly stub it out.
354 - const nullStub = {
355 - transform(source, id) {
356 - if (shims[id]) {
357 - return 'module.exports = null;';
358 - }
359 - return source;
360 - },
361 - };
362 - return [nullStub, alias(shims)];
363 -}
364 -
369 // FB uses require('React') instead of require('react').
370 // We can't set up a forwarding module due to case sensitivity issues.
371 function rewriteFBReactImport() {
@@ -408,11 +412,15 @@ function getPlugins(
412 ) {
413 const shims = Modules.getShims(bundleType, entry, featureFlags);
414 const plugins = [
415 + // Extract error codes from invariant() messages into a file.
416 shouldExtractErrors && writeErrorCodes(),
412 - ...shimModules(shims),
417 + // Shim some modules for www custom behavior and optimizations.
418 + alias(shims),
419 + // Use Node resolution mechanism.
420 resolvePlugin({
421 skip: externals,
422 }),
423 + // Compile to ES5.
424 babel(getBabelConfig(updateBabelOptions, bundleType)),
425 stripUseStrict(),
426 ].filter(Boolean);
@@ -545,9 +553,15 @@ function createBundle(bundle, bundleType) {
553 externals = externals.concat(deps);
554 }
555
556 + const importSideEffects = Modules.getImportSideEffects();
557 + const pureExternalModules = Object.keys(importSideEffects).filter(
558 + module => !importSideEffects[module]
559 + );
560 +
561 console.log(`${chalk.bgYellow.black(' BUILDING ')} ${logKey}`);
562 return rollup({
563 input: resolvedEntry,
564 + pureExternalModules,
565 external(id) {
566 const containsThisModule = pkg => id === pkg || id.startsWith(pkg + '/');
567 const isProvidedByDependency = externals.some(containsThisModule);
scripts/rollup/modules.js
+22 -6
@@ -27,6 +27,20 @@ const forkedFBModules = Object.freeze([
27 'react/src/ReactCurrentOwner',
28 ]);
29
30 +// For any external that is used in a DEV-only condition, explicitly
31 +// specify whether it has side effects during import or not. This lets
32 +// us know whether we can safely omit them when they are unused.
33 +const HAS_NO_SIDE_EFFECTS_ON_IMPORT = false;
34 +// const HAS_SIDE_EFFECTS_ON_IMPORT = true;
35 +const importSideEffects = Object.freeze({
36 + 'fbjs/lib/invariant': HAS_NO_SIDE_EFFECTS_ON_IMPORT,
37 + 'fbjs/lib/warning': HAS_NO_SIDE_EFFECTS_ON_IMPORT,
38 + 'prop-types/checkPropTypes': HAS_NO_SIDE_EFFECTS_ON_IMPORT,
39 + 'fbjs/lib/camelizeStyleName': HAS_NO_SIDE_EFFECTS_ON_IMPORT,
40 + 'fbjs/lib/hyphenateStyleName': HAS_NO_SIDE_EFFECTS_ON_IMPORT,
41 + deepFreezeAndThrowOnMutationInDev: HAS_NO_SIDE_EFFECTS_ON_IMPORT,
42 +});
43 +
44 // Given ['react'] in bundle externals, returns { 'react': 'React' }.
45 function getPeerGlobals(externals, moduleType) {
46 const peerGlobals = {};
@@ -61,6 +75,10 @@ function getDependencies(bundleType, entry) {
75 return deps;
76 }
77
78 +function getImportSideEffects() {
79 + return importSideEffects;
80 +}
81 +
82 // Hijacks some modules for optimization and integration reasons.
83 function getShims(bundleType, entry, featureFlags) {
84 const shims = {};
@@ -84,24 +102,22 @@ function getShims(bundleType, entry, featureFlags) {
102 // so we resort to using a shim that re-exports the www module, and then
103 // treating shim's target destinations as external (see getDependencies).
104 forkedFBModules.forEach(srcPath => {
87 - const resolvedSrcPath = require.resolve(srcPath);
88 - const wwwName = path.parse(resolvedSrcPath).name;
105 + const wwwName = path.parse(srcPath).name;
106 const shimPath = path.resolve(
107 __dirname + `/shims/rollup/${wwwName}-www.js`
108 );
92 - shims[resolvedSrcPath] = shimPath;
109 + shims[srcPath] = shimPath;
110 });
111 break;
112 }
113 if (featureFlags) {
97 - shims[require.resolve('shared/ReactFeatureFlags')] = require.resolve(
98 - featureFlags
99 - );
114 + shims['shared/ReactFeatureFlags'] = require.resolve(featureFlags);
115 }
116 return shims;
117 }
118
119 module.exports = {
120 + getImportSideEffects,
121 getPeerGlobals,
122 getDependencies,
123 getShims,
scripts/rollup/results.json
+4 -4
@@ -41,12 +41,12 @@
41 "gzip": 33239
42 },
43 "ReactDOM-dev.js (FB_DEV)": {
44 - "size": 609049,
45 - "gzip": 136235
44 + "size": 580159,
45 + "gzip": 130593
46 },
47 "ReactDOM-prod.js (FB_PROD)": {
48 - "size": 422543,
49 - "gzip": 93634
48 + "size": 412862,
49 + "gzip": 91252
50 },
51 "react-dom-test-utils.development.js (NODE_DEV)": {
52 "size": 42927,
scripts/rollup/shims/rollup/ReactCurrentOwner-www.js
+1 -1
@@ -1 +1 @@
1 -module.exports = require('ReactCurrentOwner');
1 +export default require('ReactCurrentOwner');
scripts/rollup/shims/rollup/ReactFeatureFlags-www.js
+1 -1
@@ -1 +1 @@
1 -module.exports = require('ReactFeatureFlags');
1 +export default require('ReactFeatureFlags');
scripts/rollup/shims/rollup/assign-umd.js
+4 -3
@@ -1,4 +1,5 @@
1 -var ReactInternals = require('react')
2 - .__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
1 +import React from 'react';
2
4 -module.exports = ReactInternals.assign;
3 +const ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
4 +
5 +export default ReactInternals.assign;
scripts/rollup/shims/rollup/lowPriorityWarning-www.js
+1 -1
@@ -1 +1 @@
1 -module.exports = require('lowPriorityWarning');
1 +export default require('lowPriorityWarning');