diff --git a/.flowconfig b/.flowconfig index b7aa19446d88dc..6c51ae9173407e 100644 --- a/.flowconfig +++ b/.flowconfig @@ -51,5 +51,7 @@ suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(\\)? *\\(site=[a-z,_]* suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError +experimental.const_params=true + [version] ^0.66.0 diff --git a/IntegrationTests/AsyncStorageTest.js b/IntegrationTests/AsyncStorageTest.js index 3ce0265dd8ceb0..065e073f1329ec 100644 --- a/IntegrationTests/AsyncStorageTest.js +++ b/IntegrationTests/AsyncStorageTest.js @@ -56,10 +56,11 @@ function expectEqual(lhs, rhs, testname : string) { } function expectAsyncNoError(place, err) { - if (err instanceof Error) { - err = err.message; + let error = err; + if (error instanceof Error) { + error = error.message; } - expectTrue(err === null, 'Unexpected error in ' + place + ': ' + JSON.stringify(err)); + expectTrue(error === null, 'Unexpected error in ' + place + ': ' + JSON.stringify(err)); } function testSetAndGet() { diff --git a/Libraries/Animated/src/AnimatedImplementation.js b/Libraries/Animated/src/AnimatedImplementation.js index b23a44db0e4fc7..dc3e44a363ee41 100644 --- a/Libraries/Animated/src/AnimatedImplementation.js +++ b/Libraries/Animated/src/AnimatedImplementation.js @@ -127,7 +127,7 @@ const spring = function( configuration: SpringAnimationConfig, callback?: ?EndCallback, ): void { - callback = _combineCallbacks(callback, configuration); + let mergedCallbacks = _combineCallbacks(callback, configuration); const singleValue: any = animatedValue; const singleConfig: any = configuration; singleValue.stopTracking(); @@ -138,11 +138,11 @@ const spring = function( configuration.toValue, SpringAnimation, singleConfig, - callback, + mergedCallbacks, ), ); } else { - singleValue.animate(new SpringAnimation(singleConfig), callback); + singleValue.animate(new SpringAnimation(singleConfig), mergedCallbacks); } }; return ( @@ -180,7 +180,7 @@ const timing = function( configuration: TimingAnimationConfig, callback?: ?EndCallback, ): void { - callback = _combineCallbacks(callback, configuration); + let callbacks = _combineCallbacks(callback, configuration); const singleValue: any = animatedValue; const singleConfig: any = configuration; singleValue.stopTracking(); @@ -191,11 +191,11 @@ const timing = function( configuration.toValue, TimingAnimation, singleConfig, - callback, + callbacks, ), ); } else { - singleValue.animate(new TimingAnimation(singleConfig), callback); + singleValue.animate(new TimingAnimation(singleConfig), callbacks); } }; @@ -234,11 +234,11 @@ const decay = function( configuration: DecayAnimationConfig, callback?: ?EndCallback, ): void { - callback = _combineCallbacks(callback, configuration); + let mergedCallbacks = _combineCallbacks(callback, configuration); const singleValue: any = animatedValue; const singleConfig: any = configuration; singleValue.stopTracking(); - singleValue.animate(new DecayAnimation(singleConfig), callback); + singleValue.animate(new DecayAnimation(singleConfig), mergedCallbacks); }; return ( diff --git a/Libraries/Animated/src/Easing.js b/Libraries/Animated/src/Easing.js index f5c00fd813f7dc..f8d1ab5a4ad7f1 100644 --- a/Libraries/Animated/src/Easing.js +++ b/Libraries/Animated/src/Easing.js @@ -175,10 +175,11 @@ class Easing { * - http://tiny.cc/back_default (s = 1.70158, default) */ static back(s: number): (t: number) => number { - if (s === undefined) { - s = 1.70158; + let ss = s; + if (ss === undefined) { + ss = 1.70158; } - return (t) => t * t * ((s + 1) * t - s); + return (t) => t * t * ((ss + 1) * t - ss); } /** @@ -187,22 +188,23 @@ class Easing { * http://easings.net/#easeInBounce */ static bounce(t: number): number { - if (t < 1 / 2.75) { - return 7.5625 * t * t; + let tt = t; + if (tt < 1 / 2.75) { + return 7.5625 * tt * tt; } - if (t < 2 / 2.75) { - t -= 1.5 / 2.75; - return 7.5625 * t * t + 0.75; + if (tt < 2 / 2.75) { + tt -= 1.5 / 2.75; + return 7.5625 * tt * tt + 0.75; } - if (t < 2.5 / 2.75) { - t -= 2.25 / 2.75; - return 7.5625 * t * t + 0.9375; + if (tt < 2.5 / 2.75) { + tt -= 2.25 / 2.75; + return 7.5625 * tt * tt + 0.9375; } - t -= 2.625 / 2.75; - return 7.5625 * t * t + 0.984375; + tt -= 2.625 / 2.75; + return 7.5625 * tt * tt + 0.984375; } /** diff --git a/Libraries/Animated/src/nodes/AnimatedProps.js b/Libraries/Animated/src/nodes/AnimatedProps.js index 78cd11189edfa7..b10cd03c183898 100644 --- a/Libraries/Animated/src/nodes/AnimatedProps.js +++ b/Libraries/Animated/src/nodes/AnimatedProps.js @@ -25,13 +25,14 @@ class AnimatedProps extends AnimatedNode { constructor(props: Object, callback: () => void) { super(); - if (props.style) { - props = { - ...props, - style: new AnimatedStyle(props.style), + let propsTmp = props; + if (propsTmp.style) { + propsTmp = { + ...propsTmp, + style: new AnimatedStyle(propsTmp.style), }; } - this._props = props; + this._props = propsTmp; this._callback = callback; this.__attach(); } diff --git a/Libraries/Animated/src/nodes/AnimatedStyle.js b/Libraries/Animated/src/nodes/AnimatedStyle.js index c7bb24e3b42b14..e2fad696363b9e 100644 --- a/Libraries/Animated/src/nodes/AnimatedStyle.js +++ b/Libraries/Animated/src/nodes/AnimatedStyle.js @@ -22,14 +22,14 @@ class AnimatedStyle extends AnimatedWithChildren { constructor(style: any) { super(); - style = flattenStyle(style) || {}; - if (style.transform) { - style = { - ...style, - transform: new AnimatedTransform(style.transform), + let styleTmp = flattenStyle(style) || {}; + if (styleTmp.transform) { + styleTmp = { + ...styleTmp, + transform: new AnimatedTransform(styleTmp.transform), }; } - this._style = style; + this._style = styleTmp; } // Recursively get values for nested styles (like iOS's shadowOffset) diff --git a/Libraries/BatchedBridge/NativeModules.js b/Libraries/BatchedBridge/NativeModules.js index 324c4f6e995bdd..ff5bda3476a823 100644 --- a/Libraries/BatchedBridge/NativeModules.js +++ b/Libraries/BatchedBridge/NativeModules.js @@ -101,8 +101,8 @@ function genMethod(moduleID: number, methodID: number, type: MethodType) { const onSuccess = hasSuccessCallback ? lastArg : null; const onFail = hasErrorCallback ? secondLastArg : null; const callbackCount = hasSuccessCallback + hasErrorCallback; - args = args.slice(0, args.length - callbackCount); - BatchedBridge.enqueueNativeCall(moduleID, methodID, args, onFail, onSuccess); + let argsArray = args.slice(0, args.length - callbackCount); + BatchedBridge.enqueueNativeCall(moduleID, methodID, argsArray, onFail, onSuccess); }; } fn.type = type; diff --git a/Libraries/Blob/Blob.js b/Libraries/Blob/Blob.js index eca13a6a309e8f..35b5814f2616d1 100644 --- a/Libraries/Blob/Blob.js +++ b/Libraries/Blob/Blob.js @@ -83,19 +83,21 @@ class Blob { slice(start?: number, end?: number): Blob { const BlobManager = require('BlobManager'); let {offset, size} = this.data; + let startVal = start; + let endVal = end; - if (typeof start === 'number') { - if (start > size) { - start = size; + if (typeof startVal === 'number') { + if (startVal > size) { + startVal = size; } - offset += start; - size -= start; + offset += startVal; + size -= startVal; - if (typeof end === 'number') { - if (end < 0) { - end = this.size + end; + if (typeof endVal === 'number') { + if (endVal < 0) { + endVal = this.size + endVal; } - size = end - start; + size = endVal - startVal; } } return BlobManager.createFromOptions({ diff --git a/Libraries/CameraRoll/ImagePickerIOS.js b/Libraries/CameraRoll/ImagePickerIOS.js index 24d1309d2e1b91..285615b7fddff3 100644 --- a/Libraries/CameraRoll/ImagePickerIOS.js +++ b/Libraries/CameraRoll/ImagePickerIOS.js @@ -19,19 +19,19 @@ var ImagePickerIOS = { return RCTImagePicker.canUseCamera(callback); }, openCameraDialog: function(config: Object, successCallback: Function, cancelCallback: Function) { - config = { + let configTmp = { videoMode: false, ...config, }; - return RCTImagePicker.openCameraDialog(config, successCallback, cancelCallback); + return RCTImagePicker.openCameraDialog(configTmp, successCallback, cancelCallback); }, openSelectDialog: function(config: Object, successCallback: Function, cancelCallback: Function) { - config = { + let configTmp = { showImages: true, showVideos: false, ...config, }; - return RCTImagePicker.openSelectDialog(config, successCallback, cancelCallback); + return RCTImagePicker.openSelectDialog(configTmp, successCallback, cancelCallback); }, }; diff --git a/Libraries/Components/Navigation/NavigatorIOS.ios.js b/Libraries/Components/Navigation/NavigatorIOS.ios.js index 66aa906f61a4fd..0f0b1bc8fca2da 100644 --- a/Libraries/Components/Navigation/NavigatorIOS.ios.js +++ b/Libraries/Components/Navigation/NavigatorIOS.ios.js @@ -732,11 +732,12 @@ var NavigatorIOS = createReactClass({ */ replaceAtIndex: function(route: Route, index: number) { invariant(!!route, 'Must supply route to replace'); - if (index < 0) { - index += this.state.routeStack.length; + let idx = index; + if (idx < 0) { + idx += this.state.routeStack.length; } - if (this.state.routeStack.length <= index) { + if (this.state.routeStack.length <= idx) { return; } diff --git a/Libraries/Components/ScrollResponder.js b/Libraries/Components/ScrollResponder.js index 9d60c462ef1dc7..2d35acca95e3b4 100644 --- a/Libraries/Components/ScrollResponder.js +++ b/Libraries/Components/ScrollResponder.js @@ -414,15 +414,21 @@ const ScrollResponderMixin = { y?: number, animated?: boolean ) { + let params = {}; if (typeof x === 'number') { console.warn('`scrollResponderScrollTo(x, y, animated)` is deprecated. Use `scrollResponderScrollTo({x: 5, y: 5, animated: true})` instead.'); - } else { - ({x, y, animated} = x || {}); + params.x = x || 0; + params.y = y || 0; + params.animated = animated !== false; + } else if(typeof x === 'object') { + params.x = x.x || 0; + params.y = x.y || 0; + params.animated = x.animated !== false; } UIManager.dispatchViewManagerCommand( nullthrows(this.scrollResponderGetScrollableNode()), UIManager.RCTScrollView.Commands.scrollTo, - [x || 0, y || 0, animated !== false], + [params.x, params.y, params.animated], ); }, @@ -465,13 +471,14 @@ const ScrollResponderMixin = { animated?: boolean // deprecated, put this inside the rect argument instead ) { invariant(ScrollViewManager && ScrollViewManager.zoomToRect, 'zoomToRect is not implemented'); + let isAnimated = animated; if ('animated' in rect) { - animated = rect.animated; + isAnimated = rect.animated; delete rect.animated; - } else if (typeof animated !== 'undefined') { + } else if (typeof isAnimated !== 'undefined') { console.warn('`scrollResponderZoomTo` `animated` argument is deprecated. Use `options.animated` instead'); } - ScrollViewManager.zoomToRect(this.scrollResponderGetScrollableNode(), rect, animated !== false); + ScrollViewManager.zoomToRect(this.scrollResponderGetScrollableNode(), rect, isAnimated !== false); }, /** diff --git a/Libraries/Components/ScrollView/ScrollView.js b/Libraries/Components/ScrollView/ScrollView.js index 354fd952b8191e..be2071f2e0dabf 100644 --- a/Libraries/Components/ScrollView/ScrollView.js +++ b/Libraries/Components/ScrollView/ScrollView.js @@ -567,15 +567,21 @@ const ScrollView = createReactClass({ x?: number, animated?: boolean ) { + let params = {}; + // animation is enabled by default if (typeof y === 'number') { console.warn('`scrollTo(y, x, animated)` is deprecated. Use `scrollTo({x: 5, y: 5, ' + 'animated: true})` instead.'); - } else { - ({x, y, animated} = y || {}); + params.x = x || 0; + params.y = y || 0; + params.animated = animated !== false; } - this.getScrollResponder().scrollResponderScrollTo( - {x: x || 0, y: y || 0, animated: animated !== false} - ); + else if(typeof y === 'object') { + params.x = y.x || 0; + params.y = y.y || 0; + params.animated = y.animated !== false; + } + this.getScrollResponder().scrollResponderScrollTo(params); }, /** diff --git a/Libraries/Components/StatusBar/StatusBar.js b/Libraries/Components/StatusBar/StatusBar.js index 0562a315493853..7152d4183f67a1 100644 --- a/Libraries/Components/StatusBar/StatusBar.js +++ b/Libraries/Components/StatusBar/StatusBar.js @@ -193,10 +193,10 @@ class StatusBar extends React.Component<{ * changing the status bar hidden property. */ static setHidden(hidden: boolean, animation?: StatusBarAnimation) { - animation = animation || 'none'; + let isAnimation = animation || 'none'; StatusBar._defaultProps.hidden.value = hidden; if (Platform.OS === 'ios') { - StatusBarManager.setHidden(hidden, animation); + StatusBarManager.setHidden(hidden, isAnimation); } else if (Platform.OS === 'android') { StatusBarManager.setHidden(hidden); } @@ -208,10 +208,10 @@ class StatusBar extends React.Component<{ * @param animated Animate the style change. */ static setBarStyle(style: StatusBarStyle, animated?: boolean) { - animated = animated || false; + let isAnimated = animated || false; StatusBar._defaultProps.barStyle.value = style; if (Platform.OS === 'ios') { - StatusBarManager.setStyle(style, animated); + StatusBarManager.setStyle(style, isAnimated); } else if (Platform.OS === 'android') { StatusBarManager.setStyle(style); } @@ -242,9 +242,9 @@ class StatusBar extends React.Component<{ console.warn('`setBackgroundColor` is only available on Android'); return; } - animated = animated || false; + let isAnimated = animated || false; StatusBar._defaultProps.backgroundColor.value = color; - StatusBarManager.setColor(processColor(color), animated); + StatusBarManager.setColor(processColor(color), isAnimated); } /** diff --git a/Libraries/Core/ExceptionsManager.js b/Libraries/Core/ExceptionsManager.js index 8a63ec3bff4bcc..81c2275a329bba 100644 --- a/Libraries/Core/ExceptionsManager.js +++ b/Libraries/Core/ExceptionsManager.js @@ -56,15 +56,16 @@ function handleException(e: Error, isFatal: boolean) { // Unfortunately there is no way to figure out the stacktrace in this // case, so if you ended up here trying to trace an error, look for // `throw ''` somewhere in your codebase. - if (!e.message) { - e = new Error(e); + let error = e; + if (!error.message) { + error = new Error(error); } if (console._errorOriginal) { - console._errorOriginal(e.message); + console._errorOriginal(error.message); } else { - console.error(e.message); + console.error(error.message); } - reportException(e, isFatal); + reportException(error, isFatal); } function reactConsoleErrorHandler() { diff --git a/Libraries/Experimental/SwipeableRow/SwipeableRow.js b/Libraries/Experimental/SwipeableRow/SwipeableRow.js index 80e627376e8482..2f09285b73194f 100644 --- a/Libraries/Experimental/SwipeableRow/SwipeableRow.js +++ b/Libraries/Experimental/SwipeableRow/SwipeableRow.js @@ -290,7 +290,7 @@ const SwipeableRow = createReactClass({ * Ensure the speed is at least the set speed threshold to prevent a slow * swiping animation */ - speed = ( + let speedVal = ( speed > HORIZONTAL_FULL_SWIPE_SPEED_THRESHOLD ? speed : HORIZONTAL_FULL_SWIPE_SPEED_THRESHOLD @@ -299,7 +299,7 @@ const SwipeableRow = createReactClass({ * Calculate the duration the row should take to swipe the remaining distance * at the same speed the user swiped (or the speed threshold) */ - const duration = Math.abs((this.props.maxSwipeDistance - Math.abs(distMoved)) / speed); + const duration = Math.abs((this.props.maxSwipeDistance - Math.abs(distMoved)) / speedVal); const maxSwipeDistance = IS_RTL ? -this.props.maxSwipeDistance : this.props.maxSwipeDistance; this._animateTo(-maxSwipeDistance, duration); }, diff --git a/Libraries/Image/resolveAssetSource.js b/Libraries/Image/resolveAssetSource.js index a5b6229d35d738..3c97e801817f5b 100644 --- a/Libraries/Image/resolveAssetSource.js +++ b/Libraries/Image/resolveAssetSource.js @@ -34,19 +34,20 @@ function getDevServerURL(): ?string { } function _coerceLocalScriptURL(scriptURL: ?string): ?string { + let scriptURLTmp = scriptURL; if (scriptURL) { if (scriptURL.startsWith('assets://')) { // android: running from within assets, no offline path to use return null; } - scriptURL = scriptURL.substring(0, scriptURL.lastIndexOf('/') + 1); - if (!scriptURL.includes('://')) { + scriptURLTmp = scriptURL.substring(0, scriptURL.lastIndexOf('/') + 1); + if (!scriptURLTmp.includes('://')) { // Add file protocol in case we have an absolute file path and not a URL. // This shouldn't really be necessary. scriptURL should be a URL. - scriptURL = 'file://' + scriptURL; + scriptURLTmp = 'file://' + scriptURLTmp; } } - return scriptURL; + return scriptURLTmp; } function getScriptURL(): ?string { diff --git a/Libraries/Inspector/Inspector.js b/Libraries/Inspector/Inspector.js index 90e30b346a9461..af615ad9a13cad 100644 --- a/Libraries/Inspector/Inspector.js +++ b/Libraries/Inspector/Inspector.js @@ -97,17 +97,18 @@ class Inspector extends React.Component<{ attachToDevtools = (agent: Object) => { let _hideWait = null; const hlSub = agent.sub('highlight', ({node, name, props}) => { + let nodeTmp = node; /* $FlowFixMe(>=0.63.0 site=react_native_fb) This comment suppresses an * error found when Flow v0.63 was deployed. To see the error delete this * comment and run Flow. */ clearTimeout(_hideWait); - if (typeof node !== 'number') { + if (typeof nodeTmp !== 'number') { // Fiber - node = ReactNative.findNodeHandle(node); + nodeTmp = ReactNative.findNodeHandle(nodeTmp); } - UIManager.measure(node, (x, y, width, height, left, top) => { + UIManager.measure(nodeTmp, (x, y, width, height, left, top) => { this.setState({ hierarchy: [], inspected: { diff --git a/Libraries/Lists/ViewabilityHelper.js b/Libraries/Lists/ViewabilityHelper.js index 0c0a8356019075..2ae8c50b7ffa01 100644 --- a/Libraries/Lists/ViewabilityHelper.js +++ b/Libraries/Lists/ViewabilityHelper.js @@ -235,12 +235,12 @@ class ViewabilityHelper { createViewToken, ) { // Filter out indices that have gone out of view since this call was scheduled. - viewableIndicesToCheck = viewableIndicesToCheck.filter(ii => + let toCheck = viewableIndicesToCheck.filter(ii => this._viewableIndices.includes(ii), ); const prevItems = this._viewableItems; const nextItems = new Map( - viewableIndicesToCheck.map(ii => { + toCheck.map(ii => { const viewable = createViewToken(ii, true); return [viewable.key, viewable]; }), diff --git a/Libraries/Lists/VirtualizedList.js b/Libraries/Lists/VirtualizedList.js index f40b44e404c4f6..e859dda603e6db 100644 --- a/Libraries/Lists/VirtualizedList.js +++ b/Libraries/Lists/VirtualizedList.js @@ -656,8 +656,8 @@ class VirtualizedList extends React.PureComponent { const stickyOffset = this.props.ListHeaderComponent ? 1 : 0; const end = getItemCount(data) - 1; let prevCellKey; - last = Math.min(end, last); - for (let ii = first; ii <= last; ii++) { + let lastIndex = Math.min(end, last); + for (let ii = first; ii <= lastIndex; ii++) { const item = getItem(data, ii); const key = keyExtractor(item, ii); this._indicesToKeys.set(ii, key); diff --git a/Libraries/Lists/VirtualizedSectionList.js b/Libraries/Lists/VirtualizedSectionList.js index 2bb196814abf13..cb71aee56b532e 100644 --- a/Libraries/Lists/VirtualizedSectionList.js +++ b/Libraries/Lists/VirtualizedSectionList.js @@ -309,15 +309,16 @@ class VirtualizedSectionList extends React.PureComponent< index: number, info?: ?Object, ): ?React.ComponentType<*> { - info = info || this._subExtractor(index); - if (!info) { + let infoTmp = info; + infoTmp = infoTmp || this._subExtractor(index); + if (!infoTmp) { return null; } const ItemSeparatorComponent = - info.section.ItemSeparatorComponent || this.props.ItemSeparatorComponent; + infoTmp.section.ItemSeparatorComponent || this.props.ItemSeparatorComponent; const {SectionSeparatorComponent} = this.props; const isLastItemInList = index === this.state.childProps.getItemCount() - 1; - const isLastItemInSection = info.index === info.section.data.length - 1; + const isLastItemInSection = infoTmp.index === infoTmp.section.data.length - 1; if (SectionSeparatorComponent && isLastItemInSection) { return SectionSeparatorComponent; } diff --git a/Libraries/Performance/Systrace.js b/Libraries/Performance/Systrace.js index 1abedee7c1734b..0c6cf72ea3df5d 100644 --- a/Libraries/Performance/Systrace.js +++ b/Libraries/Performance/Systrace.js @@ -134,9 +134,9 @@ const Systrace = { **/ beginEvent(profileName?: any, args?: any) { if (_enabled) { - profileName = typeof profileName === 'function' ? + let name = typeof profileName === 'function' ? profileName() : profileName; - global.nativeTraceBeginSection(TRACE_TAG_REACT_APPS, profileName, args); + global.nativeTraceBeginSection(TRACE_TAG_REACT_APPS, name, args); } }, @@ -155,18 +155,18 @@ const Systrace = { const cookie = _asyncCookie; if (_enabled) { _asyncCookie++; - profileName = typeof profileName === 'function' ? + let name = typeof profileName === 'function' ? profileName() : profileName; - global.nativeTraceBeginAsyncSection(TRACE_TAG_REACT_APPS, profileName, cookie); + global.nativeTraceBeginAsyncSection(TRACE_TAG_REACT_APPS, name, cookie); } return cookie; }, endAsyncEvent(profileName?: any, cookie?: any) { if (_enabled) { - profileName = typeof profileName === 'function' ? + let name = typeof profileName === 'function' ? profileName() : profileName; - global.nativeTraceEndAsyncSection(TRACE_TAG_REACT_APPS, profileName, cookie); + global.nativeTraceEndAsyncSection(TRACE_TAG_REACT_APPS, name, cookie); } }, @@ -175,10 +175,10 @@ const Systrace = { **/ counterEvent(profileName?: any, value?: any) { if (_enabled) { - profileName = typeof profileName === 'function' ? + let name = typeof profileName === 'function' ? profileName() : profileName; global.nativeTraceCounter && - global.nativeTraceCounter(TRACE_TAG_REACT_APPS, profileName, value); + global.nativeTraceCounter(TRACE_TAG_REACT_APPS, name, value); } }, @@ -188,12 +188,13 @@ const Systrace = { **/ attachToRelayProfiler(relayProfiler: RelayProfiler) { relayProfiler.attachProfileHandler('*', (name, state?) => { + let nameTmp = name; if (state != null && state.queryName !== undefined) { - name += '_' + state.queryName; + nameTmp += '_' + state.queryName } - const cookie = Systrace.beginAsyncEvent(name); + const cookie = Systrace.beginAsyncEvent(nameTmp); return () => { - Systrace.endAsyncEvent(name, cookie); + Systrace.endAsyncEvent(nameTmp, cookie); }; }); diff --git a/Libraries/ReactNative/requireNativeComponent.js b/Libraries/ReactNative/requireNativeComponent.js index 2a6c7c8ca71e8d..907f36f0db8123 100644 --- a/Libraries/ReactNative/requireNativeComponent.js +++ b/Libraries/ReactNative/requireNativeComponent.js @@ -56,6 +56,7 @@ function requireNativeComponent( // as lazy view managers discovery is Android-specific. if (UIManager.ViewManagerNames) { // Lazy view managers enabled. + // $FlowFixMe because parameter mutation here seems intentional viewConfig = merge(viewConfig, UIManager.getDefaultEventTypes()); } else { viewConfig.bubblingEventTypes = merge( diff --git a/Libraries/Settings/Settings.ios.js b/Libraries/Settings/Settings.ios.js index 08f1be6a1c8ae1..11717d1d64b38a 100644 --- a/Libraries/Settings/Settings.ios.js +++ b/Libraries/Settings/Settings.ios.js @@ -29,17 +29,18 @@ var Settings = { }, watchKeys(keys: string | Array, callback: Function): number { - if (typeof keys === 'string') { - keys = [keys]; + let keysTmp = keys; + if (typeof keysTmp === 'string') { + keysTmp = [keysTmp]; } invariant( - Array.isArray(keys), + Array.isArray(keysTmp), 'keys should be a string or array of strings' ); var sid = subscriptions.length; - subscriptions.push({keys: keys, callback: callback}); + subscriptions.push({keys: keysTmp, callback: callback}); return sid; }, diff --git a/Libraries/StyleSheet/normalizeColor.js b/Libraries/StyleSheet/normalizeColor.js index 09c2e1525d5473..589107bc90f268 100755 --- a/Libraries/StyleSheet/normalizeColor.js +++ b/Libraries/StyleSheet/normalizeColor.js @@ -96,20 +96,21 @@ function normalizeColor(color: string | number): ?number { } function hue2rgb(p: number, q: number, t: number): number { - if (t < 0) { - t += 1; + let tt = t; + if (tt < 0) { + tt += 1; } - if (t > 1) { - t -= 1; + if (tt > 1) { + tt -= 1; } - if (t < 1 / 6) { - return p + (q - p) * 6 * t; + if (tt < 1 / 6) { + return p + (q - p) * 6 * tt; } - if (t < 1 / 2) { + if (tt < 1 / 2) { return q; } - if (t < 2 / 3) { - return p + (q - p) * (2 / 3 - t) * 6; + if (tt < 2 / 3) { + return p + (q - p) * (2 / 3 - tt) * 6; } return p; } diff --git a/Libraries/StyleSheet/setNormalizedColorAlpha.js b/Libraries/StyleSheet/setNormalizedColorAlpha.js index 309d86cea12e80..b3d33670caee66 100644 --- a/Libraries/StyleSheet/setNormalizedColorAlpha.js +++ b/Libraries/StyleSheet/setNormalizedColorAlpha.js @@ -15,15 +15,16 @@ * alpha should be number between 0 and 1 */ function setNormalizedColorAlpha(input: number, alpha: number): number { - if (alpha < 0) { - alpha = 0; - } else if (alpha > 1) { - alpha = 1; + let alphaTemp = alpha; + if (alphaTemp < 0) { + alphaTemp = 0; + } else if (alphaTemp > 1) { + alphaTemp = 1; } - alpha = Math.round(alpha * 255); + alphaTemp = Math.round(alphaTemp * 255); // magic bitshift guarantees we return an unsigned int - return ((input & 0xffffff00) | alpha) >>> 0; + return ((input & 0xffffff00) | alphaTemp) >>> 0; } module.exports = setNormalizedColorAlpha; diff --git a/Libraries/Utilities/Dimensions.js b/Libraries/Utilities/Dimensions.js index d13b14f1bd18ea..d4754a2001b28a 100644 --- a/Libraries/Utilities/Dimensions.js +++ b/Libraries/Utilities/Dimensions.js @@ -29,12 +29,13 @@ class Dimensions { // We calculate the window dimensions in JS so that we don't encounter loss of // precision in transferring the dimensions (which could be non-integers) over // the bridge. - if (dims && dims.windowPhysicalPixels) { + let tempDims = dims; + if (tempDims && tempDims.windowPhysicalPixels) { // parse/stringify => Clone hack - dims = JSON.parse(JSON.stringify(dims)); + tempDims = JSON.parse(JSON.stringify(tempDims)); - const windowPhysicalPixels = dims.windowPhysicalPixels; - dims.window = { + const windowPhysicalPixels = tempDims.windowPhysicalPixels; + tempDims.window = { width: windowPhysicalPixels.width / windowPhysicalPixels.scale, height: windowPhysicalPixels.height / windowPhysicalPixels.scale, scale: windowPhysicalPixels.scale, @@ -42,8 +43,8 @@ class Dimensions { }; if (Platform.OS === 'android') { // Screen and window dimensions are different on android - const screenPhysicalPixels = dims.screenPhysicalPixels; - dims.screen = { + const screenPhysicalPixels = tempDims.screenPhysicalPixels; + tempDims.screen = { width: screenPhysicalPixels.width / screenPhysicalPixels.scale, height: screenPhysicalPixels.height / screenPhysicalPixels.scale, scale: screenPhysicalPixels.scale, @@ -51,15 +52,15 @@ class Dimensions { }; // delete so no callers rely on this existing - delete dims.screenPhysicalPixels; + delete tempDims.screenPhysicalPixels; } else { - dims.screen = dims.window; + tempDims.screen = tempDims.window; } // delete so no callers rely on this existing - delete dims.windowPhysicalPixels; + delete tempDims.windowPhysicalPixels; } - Object.assign(dimensions, dims); + Object.assign(dimensions, tempDims); if (dimensionsInitialized) { // Don't fire 'change' the first time the dimensions are set. eventEmitter.emit('change', { diff --git a/Libraries/Utilities/HMRClient.js b/Libraries/Utilities/HMRClient.js index ff897afda8bf99..1a96a754af2d00 100644 --- a/Libraries/Utilities/HMRClient.js +++ b/Libraries/Utilities/HMRClient.js @@ -30,13 +30,13 @@ const HMRClient = { const wsHostPort = port !== null && port !== '' ? `${host}:${port}` : host; - bundleEntry = bundleEntry.replace(/\.(bundle|delta)/, '.js'); + const bundleEntryParam = bundleEntry.replace(/\.(bundle|delta)/, '.js'); // Build the websocket url const wsUrl = `ws://${wsHostPort}/hot?` + `platform=${platform}&` + - `bundleEntry=${bundleEntry}`; + `bundleEntry=${bundleEntryParam}`; const hmrClient = new MetroHMRClient(wsUrl); diff --git a/Libraries/Utilities/binaryToBase64.js b/Libraries/Utilities/binaryToBase64.js index d17c4d403c8705..1f93c732883e31 100644 --- a/Libraries/Utilities/binaryToBase64.js +++ b/Libraries/Utilities/binaryToBase64.js @@ -15,16 +15,17 @@ const base64 = require('base64-js'); function binaryToBase64(data: ArrayBuffer | $ArrayBufferView) { - if (data instanceof ArrayBuffer) { - data = new Uint8Array(data); + let dataBuffer = data; + if (dataBuffer instanceof ArrayBuffer) { + dataBuffer = new Uint8Array(dataBuffer); } - if (data instanceof Uint8Array) { - return base64.fromByteArray(data); + if (dataBuffer instanceof Uint8Array) { + return base64.fromByteArray(dataBuffer); } - if (!ArrayBuffer.isView(data)) { + if (!ArrayBuffer.isView(dataBuffer)) { throw new Error('data must be ArrayBuffer or typed array'); } - const {buffer, byteOffset, byteLength} = data; + const {buffer, byteOffset, byteLength} = dataBuffer; return base64.fromByteArray(new Uint8Array(buffer, byteOffset, byteLength)); } diff --git a/Libraries/Utilities/differ/insetsDiffer.js b/Libraries/Utilities/differ/insetsDiffer.js index 1d497c0948e53a..c27b3149a82cef 100644 --- a/Libraries/Utilities/differ/insetsDiffer.js +++ b/Libraries/Utilities/differ/insetsDiffer.js @@ -27,13 +27,13 @@ var insetsDiffer = function( one: ?Inset, two: ?Inset ): bool { - one = one || dummyInsets; - two = two || dummyInsets; - return one !== two && ( - one.top !== two.top || - one.left !== two.left || - one.right !== two.right || - one.bottom !== two.bottom + var insetOne = one || dummyInsets; + var insetTwo = two || dummyInsets; + return insetOne !== insetTwo && ( + insetOne.top !== insetTwo.top || + insetOne.left !== insetTwo.left || + insetOne.right !== insetTwo.right || + insetOne.bottom !== insetTwo.bottom ); }; diff --git a/Libraries/Utilities/differ/pointsDiffer.js b/Libraries/Utilities/differ/pointsDiffer.js index cb41cec85494a4..4694c8a16e8114 100644 --- a/Libraries/Utilities/differ/pointsDiffer.js +++ b/Libraries/Utilities/differ/pointsDiffer.js @@ -17,11 +17,11 @@ type Point = { var dummyPoint = {x: undefined, y: undefined}; var pointsDiffer = function(one: ?Point, two: ?Point): bool { - one = one || dummyPoint; - two = two || dummyPoint; - return one !== two && ( - one.x !== two.x || - one.y !== two.y + var ptOne = one || dummyPoint; + var ptTwo = two || dummyPoint; + return ptOne !== ptTwo && ( + ptOne.x !== ptTwo.x || + ptOne.y !== ptTwo.y ); }; diff --git a/Libraries/Utilities/truncate.js b/Libraries/Utilities/truncate.js index 6a1204f9c4c2fb..8e78d082f40244 100644 --- a/Libraries/Utilities/truncate.js +++ b/Libraries/Utilities/truncate.js @@ -27,17 +27,18 @@ const truncate = function( maxChars: number, options: truncateOptions ): ?string { - options = Object.assign({}, defaultOptions, options); - if (str && str.length && - str.length - options.minDelta + options.elipsis.length >= maxChars) { - str = str.slice(0, maxChars - options.elipsis.length + 1); - if (options.breakOnWords) { - var ii = Math.max(str.lastIndexOf(' '), str.lastIndexOf('\n')); - str = str.slice(0, ii); + let opts = Object.assign({}, defaultOptions, options); + let strArg = str; + if (strArg && strArg.length && + strArg.length - opts.minDelta + opts.elipsis.length >= maxChars) { + strArg = strArg.slice(0, maxChars - opts.elipsis.length + 1); + if (opts.breakOnWords) { + var ii = Math.max(strArg.lastIndexOf(' '), strArg.lastIndexOf('\n')); + strArg = strArg.slice(0, ii); } - str = str.trim() + options.elipsis; + strArg = strArg.trim() + opts.elipsis; } - return str; + return strArg; }; module.exports = truncate; diff --git a/Libraries/Vibration/Vibration.js b/Libraries/Vibration/Vibration.js index e01da3d4022663..bf5cc1f96fa896 100644 --- a/Libraries/Vibration/Vibration.js +++ b/Libraries/Vibration/Vibration.js @@ -15,7 +15,7 @@ var Platform = require('Platform'); /** * Vibration API - * + * * See https://facebook.github.io/react-native/docs/vibration.html */ @@ -27,15 +27,16 @@ function vibrateByPattern(pattern: Array, repeat: boolean = false) { return; } _vibrating = true; - if (pattern[0] === 0) { + var vibrationPattern = pattern; + if (vibrationPattern[0] === 0) { RCTVibration.vibrate(); - pattern = pattern.slice(1); + vibrationPattern = vibrationPattern.slice(1); } - if (pattern.length === 0) { + if (vibrationPattern.length === 0) { _vibrating = false; return; } - setTimeout(() => vibrateScheduler(++_id, pattern, repeat, 1), pattern[0]); + setTimeout(() => vibrateScheduler(++_id, vibrationPattern, repeat, 1), vibrationPattern[0]); } function vibrateScheduler(id, pattern: Array, repeat: boolean, nextIndex: number) { @@ -43,21 +44,22 @@ function vibrateScheduler(id, pattern: Array, repeat: boolean, nextIndex return; } RCTVibration.vibrate(); - if (nextIndex >= pattern.length) { + var indexNext = nextIndex; + if (indexNext >= pattern.length) { if (repeat) { - nextIndex = 0; + indexNext = 0; } else { _vibrating = false; return; } } - setTimeout(() => vibrateScheduler(id, pattern, repeat, nextIndex + 1), pattern[nextIndex]); + setTimeout(() => vibrateScheduler(id, pattern, repeat, indexNext + 1), pattern[indexNext]); } var Vibration = { /** * Trigger a vibration with specified `pattern`. - * + * * See https://facebook.github.io/react-native/docs/vibration.html#vibrate */ vibrate: function(pattern: number | Array = 400, repeat: boolean = false) { @@ -84,7 +86,7 @@ var Vibration = { }, /** * Stop vibration - * + * * See https://facebook.github.io/react-native/docs/vibration.html#cancel */ cancel: function() { diff --git a/Libraries/WebSocket/WebSocket.js b/Libraries/WebSocket/WebSocket.js index 13e614557d78b4..ebb2688eb149a5 100644 --- a/Libraries/WebSocket/WebSocket.js +++ b/Libraries/WebSocket/WebSocket.js @@ -97,8 +97,9 @@ class WebSocket extends EventTarget(...WEBSOCKET_EVENTS) { constructor(url: string, protocols: ?string | ?Array, options: ?{headers?: {origin?: string}}) { super(); - if (typeof protocols === 'string') { - protocols = [protocols]; + let protocolList = protocols; + if (typeof protocolList === 'string') { + protocolList = [protocolList]; } const {headers = {}, ...unrecognized} = options || {}; @@ -122,8 +123,8 @@ class WebSocket extends EventTarget(...WEBSOCKET_EVENTS) { + 'Did you mean to put these under `headers`?'); } - if (!Array.isArray(protocols)) { - protocols = null; + if (!Array.isArray(protocolList)) { + protocolList = null; } if (!WebSocket.isAvailable) { @@ -134,7 +135,7 @@ class WebSocket extends EventTarget(...WEBSOCKET_EVENTS) { this._eventEmitter = new NativeEventEmitter(WebSocketModule); this._socketId = nextWebSocketId++; this._registerEvents(); - WebSocketModule.connect(url, protocols, { headers }, this._socketId); + WebSocketModule.connect(url, protocolList, { headers }, this._socketId); } get binaryType(): ?BinaryType { diff --git a/RNTester/js/AnimatedGratuitousApp/AnExApp.js b/RNTester/js/AnimatedGratuitousApp/AnExApp.js index 1116a84ee98254..d9f2d51e64782e 100644 --- a/RNTester/js/AnimatedGratuitousApp/AnExApp.js +++ b/RNTester/js/AnimatedGratuitousApp/AnExApp.js @@ -254,15 +254,16 @@ function moveToClosest({activeKey, keys, restLayouts}, position) { var minDist = Infinity; var newKeys = []; keys.forEach((key, idx) => { - var dist = distance(position, restLayouts[idx]); + var currentIdx = idx; + var dist = distance(position, restLayouts[currentIdx]); if (key === activeKey) { - idx = activeIdx; + currentIdx = activeIdx; } else { newKeys.push(key); } if (dist < minDist) { minDist = dist; - closestIdx = idx; + closestIdx = currentIdx; } }); if (closestIdx === activeIdx) { diff --git a/RNTester/js/TextInputExample.ios.js b/RNTester/js/TextInputExample.ios.js index a55206355046da..5199d8386b8ecc 100644 --- a/RNTester/js/TextInputExample.ios.js +++ b/RNTester/js/TextInputExample.ios.js @@ -106,8 +106,8 @@ class RewriteExample extends React.Component<$FlowFixMeProps, any> { multiline={false} maxLength={limit} onChangeText={(text) => { - text = text.replace(/ /g, '_'); - this.setState({text}); + let textReplace = text.replace(/ /g, '_'); + this.setState({textReplace}); }} style={styles.default} value={this.state.text} diff --git a/RNTester/js/websocket_test_server.js b/RNTester/js/websocket_test_server.js index 83a48ed213f062..ebfbec2bbd951c 100755 --- a/RNTester/js/websocket_test_server.js +++ b/RNTester/js/websocket_test_server.js @@ -32,16 +32,17 @@ const respondWithBinary = process.argv.indexOf('--binary') !== -1; const server = new WebSocket.Server({port: 5555}); server.on('connection', (ws) => { ws.on('message', (message) => { - console.log('Received message:', message); + let messageBuffer = message; + console.log('Received message:', messageBuffer); console.log('Cookie:', ws.upgradeReq.headers.cookie); if (respondWithBinary) { - message = new Buffer(message); + messageBuffer = new Buffer(messageBuffer); } - if (message === 'getImage') { - message = fs.readFileSync(path.resolve(__dirname, 'flux@3x.png')); + if (messageBuffer === 'getImage') { + messageBuffer = fs.readFileSync(path.resolve(__dirname, 'flux@3x.png')); } - console.log('Replying with:', message); - ws.send(message); + console.log('Replying with:', messageBuffer); + ws.send(messageBuffer); }); console.log('Incoming connection!');