From a2f25a46c495ca53a75e728cfb14dbdf67cdb342 Mon Sep 17 00:00:00 2001 From: Nicolas Gallagher Date: Mon, 27 Feb 2017 22:52:41 -0800 Subject: [PATCH] Reformat 'performance' and 'src' code --- .../components/Touchable/TouchableExample.js | 1 - package.json | 2 +- .../implementations/css-modules/Box/index.js | 13 +- .../implementations/css-modules/View/index.js | 2 +- .../implementations/glamor/View/index.js | 2 +- .../react-native-web/View/lite.js | 2 +- .../styled-components/Box/index.js | 12 +- performance/index.js | 4 +- performance/modules/NestedTree.js | 37 ++-- performance/modules/benchmark.js | 24 ++- performance/tests/renderDeepTree.js | 10 +- performance/tests/renderWideTree.js | 10 +- performance/webpack.config.js | 4 +- src/apis/AppRegistry/index.js | 22 +- src/apis/AppRegistry/renderApplication.js | 19 +- src/apis/AppState/__tests__/index-test.js | 4 +- src/apis/AppState/index.js | 25 ++- src/apis/AsyncStorage/__tests__/index-test.js | 51 ++--- src/apis/AsyncStorage/index.js | 32 ++- src/apis/I18nManager/index.js | 2 +- src/apis/InteractionManager/index.js | 10 +- src/apis/Linking/index.js | 2 +- src/apis/NetInfo/__tests__/index-test.js | 4 +- src/apis/NetInfo/index.js | 42 ++-- src/apis/PanResponder/index.js | 64 +++--- src/apis/StyleSheet/StyleManager.js | 40 ++-- src/apis/StyleSheet/StyleRegistry.js | 10 +- src/apis/StyleSheet/StyleSheetValidation.js | 40 ++-- .../StyleSheet/__tests__/StyleManager-test.js | 5 +- .../__tests__/StyleRegistry-test.js | 20 +- .../StyleSheet/__tests__/expandStyle-test.js | 36 +++- .../StyleSheet/__tests__/flattenStyle-test.js | 19 +- src/apis/StyleSheet/__tests__/index-test.js | 8 +- .../__tests__/prefixInlineStyles-test.js | 2 +- .../__tests__/resolveTransform-test.js | 9 +- src/apis/StyleSheet/createReactDOMStyle.js | 3 +- src/apis/StyleSheet/expandStyle.js | 59 +++--- src/apis/StyleSheet/generateCss.js | 5 +- src/apis/StyleSheet/hash.js | 36 ++-- src/apis/StyleSheet/hyphenate.js | 2 +- src/apis/StyleSheet/i18nStyle.js | 42 ++-- src/apis/StyleSheet/index.js | 10 +- src/apis/StyleSheet/prefixInlineStyles.js | 4 +- src/apis/StyleSheet/resolveTransform.js | 6 +- src/apis/StyleSheet/staticCss.js | 18 +- src/apis/UIManager/__tests__/index-test.js | 6 +- src/apis/UIManager/index.js | 10 +- src/apis/Vibration/index.js | 2 +- .../ActivityIndicator/__tests__/index-test.js | 4 +- src/components/ActivityIndicator/index.js | 39 ++-- src/components/Button/index.js | 8 +- src/components/Image/ImageStylePropTypes.js | 2 +- src/components/Image/__tests__/index-test.js | 24 ++- src/components/Image/index.js | 37 ++-- src/components/ListView/ListViewDataSource.js | 84 +++----- src/components/ListView/index.js | 189 ++++++++++-------- src/components/ProgressBar/index.js | 27 +-- src/components/ScrollView/ScrollViewBase.js | 26 ++- src/components/ScrollView/index.js | 49 +++-- src/components/StaticContainer/index.js | 2 +- src/components/Switch/index.js | 25 +-- src/components/Text/TextStylePropTypes.js | 21 +- src/components/Text/__tests__/index-test.js | 2 +- src/components/Text/index.js | 4 +- src/components/TextInput/TextInputState.js | 2 +- .../TextInput/TextInputStylePropTypes.js | 2 +- .../TextInput/__tests__/index-test.js | 61 +++--- src/components/TextInput/index.js | 85 +++++--- .../Touchable/BoundingDimensions.js | 5 +- src/components/Touchable/Touchable.js | 167 ++++++++-------- .../Touchable/TouchableHighlight.js | 74 ++++--- src/components/Touchable/TouchableOpacity.js | 36 ++-- .../Touchable/TouchableWithoutFeedback.js | 23 +-- .../Touchable/ensureComponentIsNative.js | 3 +- .../Touchable/ensurePositiveDelayProps.js | 3 +- src/components/View/ViewPropTypes.js | 2 +- src/components/View/ViewStylePropTypes.js | 10 +- src/components/View/__tests__/index-test.js | 6 +- src/components/View/index.js | 16 +- src/modules/NativeMethodsMixin/index.js | 2 +- src/modules/ReactNativePropRegistry/index.js | 2 +- src/modules/ScrollResponder/index.js | 69 ++++--- src/modules/applyLayout/index.js | 12 +- src/modules/applyNativeMethods/index.js | 4 +- .../createDOMElement/__tests__/index-test.js | 7 +- src/modules/createDOMElement/index.js | 20 +- src/modules/injectResponderEventPlugin.js | 14 +- src/modules/modality/index.js | 60 ++++-- src/modules/multiplyStyleLengthValue/index.js | 4 +- src/modules/normalizeNativeEvent.js | 59 +++--- src/modules/requestIdleCallback/index.js | 25 ++- src/propTypes/AnimationPropTypes.js | 8 +- src/propTypes/BaseComponentPropTypes.js | 4 +- src/propTypes/BorderPropTypes.js | 4 +- src/propTypes/ColorPropType.js | 33 ++- src/propTypes/EdgeInsetsPropType.js | 2 +- src/propTypes/LayoutPropTypes.js | 23 ++- src/propTypes/PointPropType.js | 2 +- src/propTypes/ShadowPropTypes.js | 2 +- src/propTypes/StyleSheetPropType.js | 2 +- src/propTypes/TransformPropTypes.js | 2 +- src/propTypes/createStrictShapeTypeChecker.js | 25 ++- 102 files changed, 1177 insertions(+), 1038 deletions(-) diff --git a/examples/components/Touchable/TouchableExample.js b/examples/components/Touchable/TouchableExample.js index 6dc79a55..01a757e0 100644 --- a/examples/components/Touchable/TouchableExample.js +++ b/examples/components/Touchable/TouchableExample.js @@ -57,7 +57,6 @@ const examples = [ console.log('custom THW text - highlight')}> diff --git a/package.json b/package.json index 7673e2ef..02cead49 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ "build:umd": "webpack --config webpack.config.js --sort-assets-by --progress", "deploy:examples": "git checkout gh-pages && rm -rf ./storybook && mv dist-examples storybook && git add -A && git commit -m \"Storybook deploy\" && git push origin gh-pages && git checkout -", "examples": "start-storybook -p 9001 -c ./examples/.storybook --dont-track", - "fmt": "prettier --singleQuote=true --write performnce/**/*.js src/**/*.js, + "fmt": "find performance src -name '*.js' | grep -v -E '(node_modules|dist)' | xargs prettier --print-width=100 --single-quote --write", "lint": "eslint performance src --ignore-path .gitignore", "prepublish": "npm run build && npm run build:umd", "test": "npm run lint && npm run test:jest", diff --git a/performance/implementations/css-modules/Box/index.js b/performance/implementations/css-modules/Box/index.js index d3f5001d..c0acfa05 100644 --- a/performance/implementations/css-modules/Box/index.js +++ b/performance/implementations/css-modules/Box/index.js @@ -7,14 +7,11 @@ import styles from './styles.css'; const Box = ({ color, fixed = false, layout = 'column', outer = false, ...other }) => ( ); diff --git a/performance/implementations/css-modules/View/index.js b/performance/implementations/css-modules/View/index.js index 2763c5a7..0ce4cb7d 100644 --- a/performance/implementations/css-modules/View/index.js +++ b/performance/implementations/css-modules/View/index.js @@ -3,6 +3,6 @@ import classnames from 'classnames'; import React from 'react'; import styles from './styles.css'; -const View = (props) =>
; +const View = props =>
; module.exports = View; diff --git a/performance/implementations/glamor/View/index.js b/performance/implementations/glamor/View/index.js index a8de5305..abbfee5a 100644 --- a/performance/implementations/glamor/View/index.js +++ b/performance/implementations/glamor/View/index.js @@ -2,7 +2,7 @@ import { css } from 'glamor'; import React from 'react'; -const View = (props) =>
; +const View = props =>
; const viewStyle = { alignItems: 'stretch', diff --git a/performance/implementations/react-native-web/View/lite.js b/performance/implementations/react-native-web/View/lite.js index 6269fb63..013ee36a 100644 --- a/performance/implementations/react-native-web/View/lite.js +++ b/performance/implementations/react-native-web/View/lite.js @@ -1,7 +1,7 @@ import createDOMElement from 'react-native/modules/createDOMElement'; import StyleSheet from 'react-native/apis/StyleSheet'; -const View = (props) => createDOMElement('div', { ...props, style: [ styles.initial, props.style ] }); +const View = props => createDOMElement('div', { ...props, style: [styles.initial, props.style] }); const styles = StyleSheet.create({ initial: { diff --git a/performance/implementations/styled-components/Box/index.js b/performance/implementations/styled-components/Box/index.js index 35738979..5eb6d533 100644 --- a/performance/implementations/styled-components/Box/index.js +++ b/performance/implementations/styled-components/Box/index.js @@ -1,7 +1,7 @@ import styled from 'styled-components'; import View from '../View'; -const getColor = (color) => { +const getColor = color => { switch (color) { case 0: return '#222'; @@ -21,11 +21,11 @@ const getColor = (color) => { }; const Box = styled(View)` - flex-direction: ${(props) => props.layout === 'column' ? 'column' : 'row'}; - padding: ${(props) => props.outer ? '4px' : '0'}; - height: ${(props) => props.fixed ? '20px' : 'auto'}; - width: ${(props) => props.fixed ? '20px' : 'auto'}; - background-color: ${(props) => getColor(props.color)}; + flex-direction: ${props => props.layout === 'column' ? 'column' : 'row'}; + padding: ${props => props.outer ? '4px' : '0'}; + height: ${props => props.fixed ? '20px' : 'auto'}; + width: ${props => props.fixed ? '20px' : 'auto'}; + background-color: ${props => getColor(props.color)}; `; module.exports = Box; diff --git a/performance/index.js b/performance/index.js index d9593197..1704a55e 100644 --- a/performance/index.js +++ b/performance/index.js @@ -23,6 +23,4 @@ const tests = [ ]; // run benchmarks -tests.reduce((promise, test) => { - return promise.then(test()); -}, Promise.resolve()); +tests.reduce((promise, test) => promise.then(test()), Promise.resolve()); diff --git a/performance/modules/NestedTree.js b/performance/modules/NestedTree.js index d076d0e1..87cacba2 100644 --- a/performance/modules/NestedTree.js +++ b/performance/modules/NestedTree.js @@ -14,29 +14,20 @@ class DeepTree extends Component { const { Box } = components; let result = ( - - {depth === 0 && ( - - )} - {depth !== 0 && Array.from({ length: breadth }).map((el, i) => ( - - ))} + + {depth === 0 && } + {depth !== 0 && + Array.from({ length: breadth }) + .map((el, i) => ( + + ))} ); for (let i = 0; i < wrap; i++) { diff --git a/performance/modules/benchmark.js b/performance/modules/benchmark.js index 6b05a3f7..2ab3f603 100644 --- a/performance/modules/benchmark.js +++ b/performance/modules/benchmark.js @@ -1,6 +1,6 @@ import * as marky from 'marky'; -const fmt = (time) => `${Math.round(time * 100) / 100}ms`; +const fmt = time => `${Math.round(time * 100) / 100}ms`; const measure = (name, fn) => { marky.mark(name); @@ -9,23 +9,27 @@ const measure = (name, fn) => { return performanceMeasure.duration; }; -const mean = (values) => { +const mean = values => { const sum = values.reduce((sum, value) => sum + value, 0); return sum / values.length; }; -const median = (values) => { - if (!Array.isArray(values)) { return 0; } - if (values.length === 1) { return values[0]; } +const median = values => { + if (!Array.isArray(values)) { + return 0; + } + if (values.length === 1) { + return values[0]; + } - const numbers = [ ...values ].sort((a, b) => a - b); - return (numbers[(numbers.length - 1) >> 1] + numbers[numbers.length >> 1]) / 2; + const numbers = [...values].sort((a, b) => a - b); + return (numbers[numbers.length - 1 >> 1] + numbers[numbers.length >> 1]) / 2; }; -const standardDeviation = (values) => { +const standardDeviation = values => { const avg = mean(values); - const squareDiffs = values.map((value) => { + const squareDiffs = values.map(value => { const diff = value - avg; return diff * diff; }); @@ -35,7 +39,7 @@ const standardDeviation = (values) => { }; const benchmark = ({ name, description, setup, teardown, task, runs }) => { - return new Promise((resolve) => { + return new Promise(resolve => { const durations = []; let i = 0; diff --git a/performance/tests/renderDeepTree.js b/performance/tests/renderDeepTree.js index 0af3d95e..6deecfe5 100644 --- a/performance/tests/renderDeepTree.js +++ b/performance/tests/renderDeepTree.js @@ -6,15 +6,7 @@ const renderDeepTree = (label, components) => createRenderBenchmark({ name: `Deep tree [${label}]`, runs: 20, getElement() { - return ( - - ); + return ; } }); diff --git a/performance/tests/renderWideTree.js b/performance/tests/renderWideTree.js index 922b1352..731256a7 100644 --- a/performance/tests/renderWideTree.js +++ b/performance/tests/renderWideTree.js @@ -6,15 +6,7 @@ const renderWideTree = (label, components) => createRenderBenchmark({ name: `Wide tree [${label}]`, runs: 20, getElement() { - return ( - - ); + return ; } }); diff --git a/performance/webpack.config.js b/performance/webpack.config.js index 0a07089a..3d6bd3de 100644 --- a/performance/webpack.config.js +++ b/performance/webpack.config.js @@ -28,7 +28,9 @@ module.exports = { analyzerMode: 'static', openAnalyzer: false }), - new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }), + new webpack.DefinePlugin({ + 'process.env.NODE_ENV': JSON.stringify('production') + }), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ diff --git a/src/apis/AppRegistry/index.js b/src/apis/AppRegistry/index.js index fe79ee28..712aaa83 100644 --- a/src/apis/AppRegistry/index.js +++ b/src/apis/AppRegistry/index.js @@ -14,12 +14,12 @@ import renderApplication, { getApplication } from './renderApplication'; const emptyObject = {}; const runnables = {}; -type ComponentProvider = () => Component +type ComponentProvider = () => Component; type AppConfig = { - appKey: string; - component?: ComponentProvider; - run?: Function; + appKey: string, + component?: ComponentProvider, + run?: Function }; /** @@ -34,7 +34,7 @@ class AppRegistry { invariant( runnables[appKey] && runnables[appKey].getApplication, `Application ${appKey} has not been registered. ` + - 'This is either due to an import error during initialization or failure to call AppRegistry.registerComponent.' + 'This is either due to an import error during initialization or failure to call AppRegistry.registerComponent.' ); return runnables[appKey].getApplication(appParameters); @@ -42,8 +42,10 @@ class AppRegistry { static registerComponent(appKey: string, getComponentFunc: ComponentProvider): string { runnables[appKey] = { - getApplication: ({ initialProps } = emptyObject) => getApplication(getComponentFunc(), initialProps), - run: ({ initialProps = emptyObject, rootTag }) => renderApplication(getComponentFunc(), initialProps, rootTag) + getApplication: ({ initialProps } = emptyObject) => + getApplication(getComponentFunc(), initialProps), + run: ({ initialProps = emptyObject, rootTag }) => + renderApplication(getComponentFunc(), initialProps, rootTag) }; return appKey; } @@ -72,14 +74,14 @@ class AppRegistry { console.log( `Running application "${appKey}" with appParams: ${JSON.stringify(params)}. ` + - `development-level warnings are ${isDevelopment ? 'ON' : 'OFF'}, ` + - `performance optimizations are ${isDevelopment ? 'OFF' : 'ON'}` + `development-level warnings are ${isDevelopment ? 'ON' : 'OFF'}, ` + + `performance optimizations are ${isDevelopment ? 'OFF' : 'ON'}` ); invariant( runnables[appKey] && runnables[appKey].run, `Application "${appKey}" has not been registered. ` + - 'This is either due to an import error during initialization or failure to call AppRegistry.registerComponent.' + 'This is either due to an import error during initialization or failure to call AppRegistry.registerComponent.' ); runnables[appKey].run(appParameters); diff --git a/src/apis/AppRegistry/renderApplication.js b/src/apis/AppRegistry/renderApplication.js index 47e9361c..5db0b3c5 100644 --- a/src/apis/AppRegistry/renderApplication.js +++ b/src/apis/AppRegistry/renderApplication.js @@ -12,26 +12,21 @@ import ReactNativeApp from './ReactNativeApp'; import StyleSheet from '../../apis/StyleSheet'; import React, { Component } from 'react'; -export default function renderApplication(RootComponent: Component, initialProps: Object, rootTag: any) { +export default function renderApplication( + RootComponent: Component, + initialProps: Object, + rootTag: any +) { invariant(rootTag, 'Expect to have a valid rootTag, instead got ', rootTag); const component = ( - + ); render(component, rootTag); } export function getApplication(RootComponent: Component, initialProps: Object): Object { - const element = ( - - ); + const element = ; const stylesheet = StyleSheet.renderToString(); return { element, stylesheet }; } diff --git a/src/apis/AppState/__tests__/index-test.js b/src/apis/AppState/__tests__/index-test.js index a8559628..a05860ff 100644 --- a/src/apis/AppState/__tests__/index-test.js +++ b/src/apis/AppState/__tests__/index-test.js @@ -6,7 +6,9 @@ describe('apis/AppState', () => { const handler = () => {}; afterEach(() => { - try { AppState.removeEventListener('change', handler); } catch (e) {} + try { + AppState.removeEventListener('change', handler); + } catch (e) {} }); describe('addEventListener', () => { diff --git a/src/apis/AppState/index.js b/src/apis/AppState/index.js index e69bedd0..af361d07 100644 --- a/src/apis/AppState/index.js +++ b/src/apis/AppState/index.js @@ -2,7 +2,7 @@ import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment'; import findIndex from 'array-find-index'; import invariant from 'fbjs/lib/invariant'; -const EVENT_TYPES = [ 'change' ]; +const EVENT_TYPES = ['change']; const VISIBILITY_CHANGE_EVENT = 'visibilitychange'; const AppStates = { @@ -13,7 +13,7 @@ const AppStates = { const listeners = []; class AppState { - static isSupported = ExecutionEnvironment.canUseDOM && document.visibilityState + static isSupported = ExecutionEnvironment.canUseDOM && document.visibilityState; static get currentState() { if (!AppState.isSupported) { @@ -32,18 +32,29 @@ class AppState { static addEventListener(type: string, handler: Function) { if (AppState.isSupported) { - invariant(EVENT_TYPES.indexOf(type) !== -1, 'Trying to subscribe to unknown event: "%s"', type); + invariant( + EVENT_TYPES.indexOf(type) !== -1, + 'Trying to subscribe to unknown event: "%s"', + type + ); const callback = () => handler(AppState.currentState); - listeners.push([ handler, callback ]); + listeners.push([handler, callback]); document.addEventListener(VISIBILITY_CHANGE_EVENT, callback, false); } } static removeEventListener(type: string, handler: Function) { if (AppState.isSupported) { - invariant(EVENT_TYPES.indexOf(type) !== -1, 'Trying to remove listener for unknown event: "%s"', type); - const listenerIndex = findIndex(listeners, (pair) => pair[0] === handler); - invariant(listenerIndex !== -1, 'Trying to remove AppState listener for unregistered handler'); + invariant( + EVENT_TYPES.indexOf(type) !== -1, + 'Trying to remove listener for unknown event: "%s"', + type + ); + const listenerIndex = findIndex(listeners, pair => pair[0] === handler); + invariant( + listenerIndex !== -1, + 'Trying to remove AppState listener for unregistered handler' + ); const callback = listeners[listenerIndex][1]; document.removeEventListener(VISIBILITY_CHANGE_EVENT, callback, false); listeners.splice(listenerIndex, 1); diff --git a/src/apis/AsyncStorage/__tests__/index-test.js b/src/apis/AsyncStorage/__tests__/index-test.js index db6e2ab2..9a2dfef9 100644 --- a/src/apis/AsyncStorage/__tests__/index-test.js +++ b/src/apis/AsyncStorage/__tests__/index-test.js @@ -32,7 +32,7 @@ const originalLocalStorage = window.localStorage; describe('apis/AsyncStorage', () => { describe('mergeLocalStorageItem', () => { - test('should have same behavior as react-native', (done) => { + test('should have same behavior as react-native', done => { window.localStorage = mockLocalStorage; // https://facebook.github.io/react-native/docs/asyncstorage.html const UID123_object = { @@ -45,30 +45,33 @@ describe('apis/AsyncStorage', () => { traits: { eyes: 'blue', shoe_size: 10 } }; - waterfall([ - (cb) => { - AsyncStorage.setItem('UID123', JSON.stringify(UID123_object)) - .then(() => cb(null)) - .catch(cb); - }, - (cb) => { - AsyncStorage.mergeItem('UID123', JSON.stringify(UID123_delta)) - .then(() => cb(null)) - .catch(cb); - }, - (cb) => { - AsyncStorage.getItem('UID123') - .then((result) => { - cb(null, JSON.parse(result)); - }) - .catch(cb); + waterfall( + [ + cb => { + AsyncStorage.setItem('UID123', JSON.stringify(UID123_object)) + .then(() => cb(null)) + .catch(cb); + }, + cb => { + AsyncStorage.mergeItem('UID123', JSON.stringify(UID123_delta)) + .then(() => cb(null)) + .catch(cb); + }, + cb => { + AsyncStorage.getItem('UID123') + .then(result => { + cb(null, JSON.parse(result)); + }) + .catch(cb); + } + ], + (err, result) => { + expect(err).toEqual(null); + expect(result).toMatchSnapshot(); + window.localStorage = originalLocalStorage; + done(); } - ], (err, result) => { - expect(err).toEqual(null); - expect(result).toMatchSnapshot(); - window.localStorage = originalLocalStorage; - done(); - }); + ); }); }); }); diff --git a/src/apis/AsyncStorage/index.js b/src/apis/AsyncStorage/index.js index 059aa3f7..fe78538b 100644 --- a/src/apis/AsyncStorage/index.js +++ b/src/apis/AsyncStorage/index.js @@ -82,12 +82,13 @@ class AsyncStorage { * multiGet(['k1', 'k2']) -> [['k1', 'val1'], ['k2', 'val2']] */ static multiGet(keys: Array) { - const promises = keys.map((key) => AsyncStorage.getItem(key)); + const promises = keys.map(key => AsyncStorage.getItem(key)); - return Promise.all(promises).then( - (result) => Promise.resolve(result.map((value, i) => [ keys[i], value ])), - (error) => Promise.reject(error) - ); + return Promise.all(promises) + .then( + result => Promise.resolve(result.map((value, i) => [keys[i], value])), + error => Promise.reject(error) + ); } /** @@ -97,24 +98,18 @@ class AsyncStorage { * multiMerge([['k1', 'val1'], ['k2', 'val2']]) */ static multiMerge(keyValuePairs: Array>) { - const promises = keyValuePairs.map((item) => AsyncStorage.mergeItem(item[0], item[1])); + const promises = keyValuePairs.map(item => AsyncStorage.mergeItem(item[0], item[1])); - return Promise.all(promises).then( - () => Promise.resolve(null), - (error) => Promise.reject(error) - ); + return Promise.all(promises).then(() => Promise.resolve(null), error => Promise.reject(error)); } /** * Delete all the keys in the `keys` array. */ static multiRemove(keys: Array) { - const promises = keys.map((key) => AsyncStorage.removeItem(key)); + const promises = keys.map(key => AsyncStorage.removeItem(key)); - return Promise.all(promises).then( - () => Promise.resolve(null), - (error) => Promise.reject(error) - ); + return Promise.all(promises).then(() => Promise.resolve(null), error => Promise.reject(error)); } /** @@ -122,12 +117,9 @@ class AsyncStorage { * multiSet([['k1', 'val1'], ['k2', 'val2']]) */ static multiSet(keyValuePairs: Array>) { - const promises = keyValuePairs.map((item) => AsyncStorage.setItem(item[0], item[1])); + const promises = keyValuePairs.map(item => AsyncStorage.setItem(item[0], item[1])); - return Promise.all(promises).then( - () => Promise.resolve(null), - (error) => Promise.reject(error) - ); + return Promise.all(promises).then(() => Promise.resolve(null), error => Promise.reject(error)); } /** diff --git a/src/apis/I18nManager/index.js b/src/apis/I18nManager/index.js index 0a860edf..ccae8fd7 100644 --- a/src/apis/I18nManager/index.js +++ b/src/apis/I18nManager/index.js @@ -5,7 +5,7 @@ type I18nManagerStatus = { forceRTL: (forceRTL: boolean) => {}, setRTL: (setRTL: boolean) => {}, isRTL: boolean -} +}; let isPreferredLanguageRTL = false; let isRTLAllowed = true; diff --git a/src/apis/InteractionManager/index.js b/src/apis/InteractionManager/index.js index b3d8b271..de006d3f 100644 --- a/src/apis/InteractionManager/index.js +++ b/src/apis/InteractionManager/index.js @@ -17,10 +17,7 @@ const InteractionManager = { * Schedule a function to run after all interactions have completed. */ runAfterInteractions(callback: Function) { - invariant( - typeof callback === 'function', - 'Must specify a function to schedule.' - ); + invariant(typeof callback === 'function', 'Must specify a function to schedule.'); callback(); }, @@ -35,10 +32,7 @@ const InteractionManager = { * Notify manager that an interaction has completed. */ clearInteractionHandle(handle) { - invariant( - !!handle, - 'Must provide a handle to clear.' - ); + invariant(!!handle, 'Must provide a handle to clear.'); }, addListener: () => {} diff --git a/src/apis/Linking/index.js b/src/apis/Linking/index.js index 79b97d24..c2e9ecfd 100644 --- a/src/apis/Linking/index.js +++ b/src/apis/Linking/index.js @@ -27,7 +27,7 @@ const Linking = { * * https://mathiasbynens.github.io/rel-noopener/ */ -const iframeOpen = (url) => { +const iframeOpen = url => { const iframe = document.createElement('iframe'); iframe.style.display = 'none'; document.body.appendChild(iframe); diff --git a/src/apis/NetInfo/__tests__/index-test.js b/src/apis/NetInfo/__tests__/index-test.js index 0c5b53fc..c25c02b7 100644 --- a/src/apis/NetInfo/__tests__/index-test.js +++ b/src/apis/NetInfo/__tests__/index-test.js @@ -7,7 +7,9 @@ describe('apis/NetInfo', () => { const handler = () => {}; afterEach(() => { - try { NetInfo.isConnected.removeEventListener('change', handler); } catch (e) {} + try { + NetInfo.isConnected.removeEventListener('change', handler); + } catch (e) {} }); describe('addEventListener', () => { diff --git a/src/apis/NetInfo/index.js b/src/apis/NetInfo/index.js index 287ee119..5d35f210 100644 --- a/src/apis/NetInfo/index.js +++ b/src/apis/NetInfo/index.js @@ -10,13 +10,12 @@ import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment'; import findIndex from 'array-find-index'; import invariant from 'fbjs/lib/invariant'; -const connection = ExecutionEnvironment.canUseDOM && ( - window.navigator.connection || - window.navigator.mozConnection || - window.navigator.webkitConnection -); +const connection = ExecutionEnvironment.canUseDOM && + (window.navigator.connection || + window.navigator.mozConnection || + window.navigator.webkitConnection); -const eventTypes = [ 'change' ]; +const eventTypes = ['change']; const connectionListeners = []; @@ -28,7 +27,9 @@ const NetInfo = { addEventListener(type: string, handler: Function): { remove: () => void } { invariant(eventTypes.indexOf(type) !== -1, 'Trying to subscribe to unknown event: "%s"', type); if (!connection) { - console.error('Network Connection API is not supported. Not listening for connection type changes.'); + console.error( + 'Network Connection API is not supported. Not listening for connection type changes.' + ); return { remove: () => {} }; @@ -42,7 +43,9 @@ const NetInfo = { removeEventListener(type: string, handler: Function): void { invariant(eventTypes.indexOf(type) !== -1, 'Trying to subscribe to unknown event: "%s"', type); - if (!connection) { return; } + if (!connection) { + return; + } connection.removeEventListener(type, handler); }, @@ -58,10 +61,14 @@ const NetInfo = { isConnected: { addEventListener(type: string, handler: Function): { remove: () => void } { - invariant(eventTypes.indexOf(type) !== -1, 'Trying to subscribe to unknown event: "%s"', type); + invariant( + eventTypes.indexOf(type) !== -1, + 'Trying to subscribe to unknown event: "%s"', + type + ); const onlineCallback = () => handler(true); const offlineCallback = () => handler(false); - connectionListeners.push([ handler, onlineCallback, offlineCallback ]); + connectionListeners.push([handler, onlineCallback, offlineCallback]); window.addEventListener('online', onlineCallback, false); window.addEventListener('offline', offlineCallback, false); @@ -72,11 +79,18 @@ const NetInfo = { }, removeEventListener(type: string, handler: Function): void { - invariant(eventTypes.indexOf(type) !== -1, 'Trying to subscribe to unknown event: "%s"', type); + invariant( + eventTypes.indexOf(type) !== -1, + 'Trying to subscribe to unknown event: "%s"', + type + ); - const listenerIndex = findIndex(connectionListeners, (pair) => pair[0] === handler); - invariant(listenerIndex !== -1, 'Trying to remove NetInfo connection listener for unregistered handler'); - const [ , onlineCallback, offlineCallback ] = connectionListeners[listenerIndex]; + const listenerIndex = findIndex(connectionListeners, pair => pair[0] === handler); + invariant( + listenerIndex !== -1, + 'Trying to remove NetInfo connection listener for unregistered handler' + ); + const [, onlineCallback, offlineCallback] = connectionListeners[listenerIndex]; window.removeEventListener('online', onlineCallback, false); window.removeEventListener('offline', offlineCallback, false); diff --git a/src/apis/PanResponder/index.js b/src/apis/PanResponder/index.js index 58267ee0..73c8af92 100644 --- a/src/apis/PanResponder/index.js +++ b/src/apis/PanResponder/index.js @@ -4,18 +4,14 @@ * All rights reserved. */ -"use strict"; +'use strict'; var TouchHistoryMath = require('react-dom/lib/TouchHistoryMath'); -var currentCentroidXOfTouchesChangedAfter = - TouchHistoryMath.currentCentroidXOfTouchesChangedAfter; -var currentCentroidYOfTouchesChangedAfter = - TouchHistoryMath.currentCentroidYOfTouchesChangedAfter; -var previousCentroidXOfTouchesChangedAfter = - TouchHistoryMath.previousCentroidXOfTouchesChangedAfter; -var previousCentroidYOfTouchesChangedAfter = - TouchHistoryMath.previousCentroidYOfTouchesChangedAfter; +var currentCentroidXOfTouchesChangedAfter = TouchHistoryMath.currentCentroidXOfTouchesChangedAfter; +var currentCentroidYOfTouchesChangedAfter = TouchHistoryMath.currentCentroidYOfTouchesChangedAfter; +var previousCentroidXOfTouchesChangedAfter = TouchHistoryMath.previousCentroidXOfTouchesChangedAfter; +var previousCentroidYOfTouchesChangedAfter = TouchHistoryMath.previousCentroidYOfTouchesChangedAfter; var currentCentroidX = TouchHistoryMath.currentCentroidX; var currentCentroidY = TouchHistoryMath.currentCentroidY; @@ -115,7 +111,6 @@ var currentCentroidY = TouchHistoryMath.currentCentroidY; */ var PanResponder = { - /** * * A graphical explanation of the touch data flow: @@ -236,8 +231,7 @@ var PanResponder = { var nextDY = gestureState.dy + (y - prevY); // TODO: This must be filtered intelligently. - var dt = - (touchHistory.mostRecentTimeStamp - gestureState._accountsForMovesUpTo); + var dt = touchHistory.mostRecentTimeStamp - gestureState._accountsForMovesUpTo; gestureState.vx = (nextDX - gestureState.dx) / dt; gestureState.vy = (nextDY - gestureState.dy) / dt; @@ -281,17 +275,19 @@ var PanResponder = { create: function(config) { var gestureState = { // Useful for debugging - stateID: Math.random(), + stateID: Math.random() }; PanResponder._initializeGestureState(gestureState); var panHandlers = { onStartShouldSetResponder: function(e) { - return config.onStartShouldSetPanResponder === undefined ? false : - config.onStartShouldSetPanResponder(e, gestureState); + return config.onStartShouldSetPanResponder === undefined + ? false + : config.onStartShouldSetPanResponder(e, gestureState); }, onMoveShouldSetResponder: function(e) { - return config.onMoveShouldSetPanResponder === undefined ? false : - config.onMoveShouldSetPanResponder(e, gestureState); + return config.onMoveShouldSetPanResponder === undefined + ? false + : config.onMoveShouldSetPanResponder(e, gestureState); }, onStartShouldSetResponderCapture: function(e) { // TODO: Actually, we should reinitialize the state any time @@ -300,13 +296,15 @@ var PanResponder = { if (e.nativeEvent.touches.length === 1) { PanResponder._initializeGestureState(gestureState); } - } - else if (e.nativeEvent.originalEvent && e.nativeEvent.originalEvent.type === 'mousedown') { + } else if ( + e.nativeEvent.originalEvent && e.nativeEvent.originalEvent.type === 'mousedown' + ) { PanResponder._initializeGestureState(gestureState); } gestureState.numberActiveTouches = e.touchHistory.numberActiveTouches; - return config.onStartShouldSetPanResponderCapture !== undefined ? - config.onStartShouldSetPanResponderCapture(e, gestureState) : false; + return config.onStartShouldSetPanResponderCapture !== undefined + ? config.onStartShouldSetPanResponderCapture(e, gestureState) + : false; }, onMoveShouldSetResponderCapture: function(e) { @@ -318,8 +316,9 @@ var PanResponder = { return false; } PanResponder._updateGestureStateOnMove(gestureState, touchHistory); - return config.onMoveShouldSetPanResponderCapture ? - config.onMoveShouldSetPanResponderCapture(e, gestureState) : false; + return config.onMoveShouldSetPanResponderCapture + ? config.onMoveShouldSetPanResponderCapture(e, gestureState) + : false; }, onResponderGrant: function(e) { @@ -329,8 +328,9 @@ var PanResponder = { gestureState.dy = 0; config.onPanResponderGrant && config.onPanResponderGrant(e, gestureState); // TODO: t7467124 investigate if this can be removed - return config.onShouldBlockNativeResponder === undefined ? true : - config.onShouldBlockNativeResponder(); + return config.onShouldBlockNativeResponder === undefined + ? true + : config.onShouldBlockNativeResponder(); }, onResponderReject: function(e) { @@ -368,18 +368,18 @@ var PanResponder = { }, onResponderTerminate: function(e) { - config.onPanResponderTerminate && - config.onPanResponderTerminate(e, gestureState); + config.onPanResponderTerminate && config.onPanResponderTerminate(e, gestureState); PanResponder._initializeGestureState(gestureState); }, onResponderTerminationRequest: function(e) { - return config.onPanResponderTerminationRequest === undefined ? true : - config.onPanResponderTerminationRequest(e, gestureState); - }, + return config.onPanResponderTerminationRequest === undefined + ? true + : config.onPanResponderTerminationRequest(e, gestureState); + } }; - return {panHandlers: panHandlers}; - }, + return { panHandlers: panHandlers }; + } }; module.exports = PanResponder; diff --git a/src/apis/StyleSheet/StyleManager.js b/src/apis/StyleSheet/StyleManager.js index ed0a8ebe..08d194de 100644 --- a/src/apis/StyleSheet/StyleManager.js +++ b/src/apis/StyleSheet/StyleManager.js @@ -25,8 +25,7 @@ const pointerEvents = { none: createClassName('pointerEvents', 'none') }; -const pointerEventsCss = - `.${pointerEvents.auto}{pointer-events:auto;}\n` + +const pointerEventsCss = `.${pointerEvents.auto}{pointer-events:auto;}\n` + `.${pointerEvents.boxNone}{pointer-events:none;}\n` + `.${pointerEvents.boxNone} *{pointer-events:auto;}\n` + `.${pointerEvents.boxOnly}{pointer-events:auto;}\n` + @@ -41,16 +40,22 @@ class StyleManager { this.cache = { byClassName: { [pointerEvents.auto]: { prop: pointerEventsPropName, value: 'auto' }, - [pointerEvents.boxNone]: { prop: pointerEventsPropName, value: 'box-none' }, - [pointerEvents.boxOnly]: { prop: pointerEventsPropName, value: 'box-only' }, + [pointerEvents.boxNone]: { + prop: pointerEventsPropName, + value: 'box-none' + }, + [pointerEvents.boxOnly]: { + prop: pointerEventsPropName, + value: 'box-only' + }, [pointerEvents.none]: { prop: pointerEventsPropName, value: 'none' } }, byProp: { pointerEvents: { - 'auto': pointerEvents.auto, + auto: pointerEvents.auto, 'box-none': pointerEvents.boxNone, 'box-only': pointerEvents.boxOnly, - 'none': pointerEvents.none + none: pointerEvents.none } } }; @@ -80,15 +85,20 @@ class StyleManager { getStyleSheetHtml() { const cache = this.cache.byProp; - const mainSheetTextContext = Object.keys(cache).reduce((rules, prop) => { - if (prop !== 'pointerEvents') { - Object.keys(cache[prop]).forEach((value) => { - const className = this.getClassName(prop, value); - rules.push(createCssRule(className, prop, value)); - }); - } - return rules; - }, []).join('\n'); + const mainSheetTextContext = Object.keys(cache) + .reduce( + (rules, prop) => { + if (prop !== 'pointerEvents') { + Object.keys(cache[prop]).forEach(value => { + const className = this.getClassName(prop, value); + rules.push(createCssRule(className, prop, value)); + }); + } + return rules; + }, + [] + ) + .join('\n'); const staticSheet = ``; const mainSheet = ``; diff --git a/src/apis/StyleSheet/StyleRegistry.js b/src/apis/StyleSheet/StyleRegistry.js index 57507cb9..23226383 100644 --- a/src/apis/StyleSheet/StyleRegistry.js +++ b/src/apis/StyleSheet/StyleRegistry.js @@ -11,12 +11,12 @@ import prefixInlineStyles from './prefixInlineStyles'; import ReactNativePropRegistry from '../../modules/ReactNativePropRegistry'; import StyleManager from './StyleManager'; -const createCacheKey = (id) => { +const createCacheKey = id => { const prefix = I18nManager.isRTL ? 'rtl' : 'ltr'; return `${prefix}-${id}`; }; -const classListToString = (list) => list.join(' ').trim(); +const classListToString = list => list.join(' ').trim(); class StyleRegistry { constructor() { @@ -89,7 +89,7 @@ class StyleRegistry { // Convert the existing classList to a React Native style and preserve any // unrecognized classNames. - domClassList.forEach((className) => { + domClassList.forEach(className => { const { prop, value } = this.styleManager.getDeclaration(className); if (prop) { previousReactNativeStyle[prop] = value; @@ -99,11 +99,11 @@ class StyleRegistry { }); // Resolve the two React Native styles. - const { classList, style = {} } = this.resolve([ previousReactNativeStyle, reactNativeStyle ]); + const { classList, style = {} } = this.resolve([previousReactNativeStyle, reactNativeStyle]); // Because this is used in stateful operations we need to remove any // existing inline styles that would override the classNames. - classList.forEach((className) => { + classList.forEach(className => { const { prop } = this.styleManager.getDeclaration(className); style[prop] = null; }); diff --git a/src/apis/StyleSheet/StyleSheetValidation.js b/src/apis/StyleSheet/StyleSheetValidation.js index 2f153af6..5970c24e 100644 --- a/src/apis/StyleSheet/StyleSheetValidation.js +++ b/src/apis/StyleSheet/StyleSheetValidation.js @@ -7,14 +7,14 @@ * @flow */ -import { PropTypes } from 'react' -import ImageStylePropTypes from '../../components/Image/ImageStylePropTypes' -import ReactPropTypeLocations from 'react-dom/lib/ReactPropTypeLocations' -import ReactPropTypesSecret from 'react-dom/lib/ReactPropTypesSecret' -import TextInputStylePropTypes from '../../components/TextInput/TextInputStylePropTypes' -import TextStylePropTypes from '../../components/Text/TextStylePropTypes' -import ViewStylePropTypes from '../../components/View/ViewStylePropTypes' -import warning from 'fbjs/lib/warning' +import { PropTypes } from 'react'; +import ImageStylePropTypes from '../../components/Image/ImageStylePropTypes'; +import ReactPropTypeLocations from 'react-dom/lib/ReactPropTypeLocations'; +import ReactPropTypesSecret from 'react-dom/lib/ReactPropTypesSecret'; +import TextInputStylePropTypes from '../../components/TextInput/TextInputStylePropTypes'; +import TextStylePropTypes from '../../components/Text/TextStylePropTypes'; +import ViewStylePropTypes from '../../components/View/ViewStylePropTypes'; +import warning from 'fbjs/lib/warning'; class StyleSheetValidation { static validateStyleProp(prop, style, caller) { @@ -58,25 +58,29 @@ class StyleSheetValidation { var styleError = function(message1, style, caller?, message2?) { warning( false, - message1 + '\n' + (caller || '<>') + ': ' + - JSON.stringify(style, null, ' ') + (message2 || '') + message1 + + '\n' + + (caller || '<>') + + ': ' + + JSON.stringify(style, null, ' ') + + (message2 || '') ); }; var allStylePropTypes = {}; -StyleSheetValidation.addValidStylePropTypes(ImageStylePropTypes) -StyleSheetValidation.addValidStylePropTypes(TextStylePropTypes) -StyleSheetValidation.addValidStylePropTypes(TextInputStylePropTypes) -StyleSheetValidation.addValidStylePropTypes(ViewStylePropTypes) +StyleSheetValidation.addValidStylePropTypes(ImageStylePropTypes); +StyleSheetValidation.addValidStylePropTypes(TextStylePropTypes); +StyleSheetValidation.addValidStylePropTypes(TextInputStylePropTypes); +StyleSheetValidation.addValidStylePropTypes(ViewStylePropTypes); StyleSheetValidation.addValidStylePropTypes({ appearance: PropTypes.string, clear: PropTypes.string, cursor: PropTypes.string, - float: PropTypes.oneOf([ 'left', 'none', 'right' ]), - font: PropTypes.string, /* @private */ + float: PropTypes.oneOf(['left', 'none', 'right']), + font: PropTypes.string /* @private */, listStyle: PropTypes.string, pointerEvents: PropTypes.string -}) +}); -module.exports = StyleSheetValidation +module.exports = StyleSheetValidation; diff --git a/src/apis/StyleSheet/__tests__/StyleManager-test.js b/src/apis/StyleSheet/__tests__/StyleManager-test.js index fc07d905..ae7f2df4 100644 --- a/src/apis/StyleSheet/__tests__/StyleManager-test.js +++ b/src/apis/StyleSheet/__tests__/StyleManager-test.js @@ -17,7 +17,10 @@ describe('apis/StyleSheet/StyleManager', () => { test('getDeclaration', () => { const className = styleManager.setDeclaration('width', '100px'); - expect(styleManager.getDeclaration(className)).toEqual({ prop: 'width', value: '100px' }); + expect(styleManager.getDeclaration(className)).toEqual({ + prop: 'width', + value: '100px' + }); }); test('getStyleSheetHtml', () => { diff --git a/src/apis/StyleSheet/__tests__/StyleRegistry-test.js b/src/apis/StyleSheet/__tests__/StyleRegistry-test.js index 41bf0543..bddb4f0b 100644 --- a/src/apis/StyleSheet/__tests__/StyleRegistry-test.js +++ b/src/apis/StyleSheet/__tests__/StyleRegistry-test.js @@ -17,20 +17,24 @@ describe('apis/StyleSheet/StyleRegistry', () => { describe('resolve', () => { const styleA = { borderWidth: 0, borderColor: 'red', width: 100 }; - const styleB = { position: 'absolute', left: 50, pointerEvents: 'box-only' }; + const styleB = { + position: 'absolute', + left: 50, + pointerEvents: 'box-only' + }; const styleC = { width: 200 }; const testResolve = (a, b, c) => { // no common properties, different resolving order, same result - const resolve1 = styleRegistry.resolve([ a, b ]); + const resolve1 = styleRegistry.resolve([a, b]); expect(resolve1).toMatchSnapshot(); - const resolve2 = styleRegistry.resolve([ b, a ]); + const resolve2 = styleRegistry.resolve([b, a]); expect(resolve1).toEqual(resolve2); // common properties, different resolving order, different result - const resolve3 = styleRegistry.resolve([ a, b, c ]); + const resolve3 = styleRegistry.resolve([a, b, c]); expect(resolve3).toMatchSnapshot(); - const resolve4 = styleRegistry.resolve([ c, a, b ]); + const resolve4 = styleRegistry.resolve([c, a, b]); expect(resolve4).toMatchSnapshot(); expect(resolve3).not.toEqual(resolve4); }; @@ -56,7 +60,11 @@ describe('apis/StyleSheet/StyleRegistry', () => { test('resolveStateful', () => { // generate a classList to act as pre-existing DOM state - const mockStyle = styleRegistry.register({ borderWidth: 0, borderColor: 'red', width: 100 }); + const mockStyle = styleRegistry.register({ + borderWidth: 0, + borderColor: 'red', + width: 100 + }); const { classList: domClassList } = styleRegistry.resolve(mockStyle); domClassList.unshift('external-className'); expect(domClassList).toMatchSnapshot(); diff --git a/src/apis/StyleSheet/__tests__/expandStyle-test.js b/src/apis/StyleSheet/__tests__/expandStyle-test.js index 159784ab..47921bca 100644 --- a/src/apis/StyleSheet/__tests__/expandStyle-test.js +++ b/src/apis/StyleSheet/__tests__/expandStyle-test.js @@ -47,19 +47,35 @@ describe('apis/StyleSheet/expandStyle', () => { }); test('flex', () => { - expect(expandStyle({ display: 'flex' })) - .toEqual({ display: 'flex', flexShrink: 0 }); + expect(expandStyle({ display: 'flex' })).toEqual({ + display: 'flex', + flexShrink: 0 + }); - expect(expandStyle({ display: 'flex', flex: 1 })) - .toEqual({ display: 'flex', flexGrow: 1, flexShrink: 1, flexBasis: 'auto' }); + expect(expandStyle({ display: 'flex', flex: 1 })).toEqual({ + display: 'flex', + flexGrow: 1, + flexShrink: 1, + flexBasis: 'auto' + }); - expect(expandStyle({ display: 'flex', flex: 10 })) - .toEqual({ display: 'flex', flexGrow: 10, flexShrink: 1, flexBasis: 'auto' }); + expect(expandStyle({ display: 'flex', flex: 10 })).toEqual({ + display: 'flex', + flexGrow: 10, + flexShrink: 1, + flexBasis: 'auto' + }); - expect(expandStyle({ display: 'flex', flexShrink: 1 })) - .toEqual({ display: 'flex', flexShrink: 1 }); + expect(expandStyle({ display: 'flex', flexShrink: 1 })).toEqual({ + display: 'flex', + flexShrink: 1 + }); - expect(expandStyle({ display: 'flex', flex: 1, flexShrink: 2 })) - .toEqual({ display: 'flex', flexGrow: 1, flexShrink: 2, flexBasis: 'auto' }); + expect(expandStyle({ display: 'flex', flex: 1, flexShrink: 2 })).toEqual({ + display: 'flex', + flexGrow: 1, + flexShrink: 2, + flexBasis: 'auto' + }); }); }); diff --git a/src/apis/StyleSheet/__tests__/flattenStyle-test.js b/src/apis/StyleSheet/__tests__/flattenStyle-test.js index eb36a651..fa937d40 100644 --- a/src/apis/StyleSheet/__tests__/flattenStyle-test.js +++ b/src/apis/StyleSheet/__tests__/flattenStyle-test.js @@ -13,10 +13,7 @@ import flattenStyle from '../flattenStyle'; describe('apis/StyleSheet/flattenStyle', () => { test('should merge style objects', () => { - const style = flattenStyle([ - { opacity: 1 }, - { order: 2 } - ]); + const style = flattenStyle([{ opacity: 1 }, { order: 2 }]); expect(style).toMatchSnapshot(); }); @@ -29,24 +26,16 @@ describe('apis/StyleSheet/flattenStyle', () => { }); test('should overwrite properties with `undefined`', () => { - const style = flattenStyle([ - { backgroundColor: '#000' }, - { backgroundColor: undefined } - ]); + const style = flattenStyle([{ backgroundColor: '#000' }, { backgroundColor: undefined }]); expect(style).toMatchSnapshot(); }); test('should not fail on falsy values', () => { - expect(() => flattenStyle([ null, false, undefined ])).not.toThrow(); + expect(() => flattenStyle([null, false, undefined])).not.toThrow(); }); test('should recursively flatten arrays', () => { - const style = flattenStyle([ - null, - [], - [ { order: 2 }, { opacity: 1 } ], - { order: 3 } - ]); + const style = flattenStyle([null, [], [{ order: 2 }, { opacity: 1 }], { order: 3 }]); expect(style).toMatchSnapshot(); }); }); diff --git a/src/apis/StyleSheet/__tests__/index-test.js b/src/apis/StyleSheet/__tests__/index-test.js index 52ca1f89..c9f3a7af 100644 --- a/src/apis/StyleSheet/__tests__/index-test.js +++ b/src/apis/StyleSheet/__tests__/index-test.js @@ -2,14 +2,12 @@ import StyleSheet from '..'; -const isPlainObject = (x) => { +const isPlainObject = x => { const toString = Object.prototype.toString; let proto; /* eslint-disable */ - return ( - toString.call(x) === '[object Object]' && - (proto = Object.getPrototypeOf(x), proto === null || proto === Object.getPrototypeOf({})) - ); + return toString.call(x) === '[object Object]' && + (proto = Object.getPrototypeOf(x), proto === null || proto === Object.getPrototypeOf({})); /* eslint-enable */ }; diff --git a/src/apis/StyleSheet/__tests__/prefixInlineStyles-test.js b/src/apis/StyleSheet/__tests__/prefixInlineStyles-test.js index 48a1e31e..aef3f4b7 100644 --- a/src/apis/StyleSheet/__tests__/prefixInlineStyles-test.js +++ b/src/apis/StyleSheet/__tests__/prefixInlineStyles-test.js @@ -5,7 +5,7 @@ import prefixInlineStyles from '../prefixInlineStyles'; describe('apis/StyleSheet/prefixInlineStyles', () => { test('handles array values', () => { const style = { - display: [ '-webkit-flex', 'flex' ] + display: ['-webkit-flex', 'flex'] }; expect(prefixInlineStyles(style)).toEqual({ display: 'flex' }); diff --git a/src/apis/StyleSheet/__tests__/resolveTransform-test.js b/src/apis/StyleSheet/__tests__/resolveTransform-test.js index f7e3ec95..18ee341a 100644 --- a/src/apis/StyleSheet/__tests__/resolveTransform-test.js +++ b/src/apis/StyleSheet/__tests__/resolveTransform-test.js @@ -6,12 +6,7 @@ describe('apis/StyleSheet/resolveTransform', () => { test('transform', () => { const resolvedStyle = {}; const style = { - transform: [ - { perspective: 50 }, - { scaleX: 20 }, - { translateX: 20 }, - { rotate: '20deg' } - ] + transform: [{ perspective: 50 }, { scaleX: 20 }, { translateX: 20 }, { rotate: '20deg' }] }; resolveTransform(resolvedStyle, style); @@ -22,7 +17,7 @@ describe('apis/StyleSheet/resolveTransform', () => { test('transformMatrix', () => { const resolvedStyle = {}; - const style = { transformMatrix: [ 1, 2, 3, 4, 5, 6 ] }; + const style = { transformMatrix: [1, 2, 3, 4, 5, 6] }; resolveTransform(resolvedStyle, style); expect(resolvedStyle).toEqual({ diff --git a/src/apis/StyleSheet/createReactDOMStyle.js b/src/apis/StyleSheet/createReactDOMStyle.js index e173e675..d9551404 100644 --- a/src/apis/StyleSheet/createReactDOMStyle.js +++ b/src/apis/StyleSheet/createReactDOMStyle.js @@ -1,6 +1,7 @@ import expandStyle from './expandStyle'; import i18nStyle from './i18nStyle'; -const createReactDOMStyle = (flattenedReactNativeStyle) => expandStyle(i18nStyle(flattenedReactNativeStyle)); +const createReactDOMStyle = flattenedReactNativeStyle => + expandStyle(i18nStyle(flattenedReactNativeStyle)); module.exports = createReactDOMStyle; diff --git a/src/apis/StyleSheet/expandStyle.js b/src/apis/StyleSheet/expandStyle.js index f6a05340..234b6ee9 100644 --- a/src/apis/StyleSheet/expandStyle.js +++ b/src/apis/StyleSheet/expandStyle.js @@ -16,24 +16,33 @@ import resolveTransform from './resolveTransform'; const emptyObject = {}; const styleShortFormProperties = { - borderColor: [ 'borderTopColor', 'borderRightColor', 'borderBottomColor', 'borderLeftColor' ], - borderRadius: [ 'borderTopLeftRadius', 'borderTopRightRadius', 'borderBottomRightRadius', 'borderBottomLeftRadius' ], - borderStyle: [ 'borderTopStyle', 'borderRightStyle', 'borderBottomStyle', 'borderLeftStyle' ], - borderWidth: [ 'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth' ], - margin: [ 'marginTop', 'marginRight', 'marginBottom', 'marginLeft' ], - marginHorizontal: [ 'marginRight', 'marginLeft' ], - marginVertical: [ 'marginTop', 'marginBottom' ], - overflow: [ 'overflowX', 'overflowY' ], - padding: [ 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft' ], - paddingHorizontal: [ 'paddingRight', 'paddingLeft' ], - paddingVertical: [ 'paddingTop', 'paddingBottom' ], - textDecorationLine: [ 'textDecoration' ], - writingDirection: [ 'direction' ] + borderColor: ['borderTopColor', 'borderRightColor', 'borderBottomColor', 'borderLeftColor'], + borderRadius: [ + 'borderTopLeftRadius', + 'borderTopRightRadius', + 'borderBottomRightRadius', + 'borderBottomLeftRadius' + ], + borderStyle: ['borderTopStyle', 'borderRightStyle', 'borderBottomStyle', 'borderLeftStyle'], + borderWidth: ['borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth'], + margin: ['marginTop', 'marginRight', 'marginBottom', 'marginLeft'], + marginHorizontal: ['marginRight', 'marginLeft'], + marginVertical: ['marginTop', 'marginBottom'], + overflow: ['overflowX', 'overflowY'], + padding: ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft'], + paddingHorizontal: ['paddingRight', 'paddingLeft'], + paddingVertical: ['paddingTop', 'paddingBottom'], + textDecorationLine: ['textDecoration'], + writingDirection: ['direction'] }; -const alphaSortProps = (propsArray) => propsArray.sort((a, b) => { - if (a < b) { return -1; } - if (a > b) { return 1; } +const alphaSortProps = propsArray => propsArray.sort((a, b) => { + if (a < b) { + return -1; + } + if (a > b) { + return 1; + } return 0; }); @@ -43,17 +52,15 @@ const createReducer = (style, styleProps) => { return (resolvedStyle, prop) => { const value = normalizeValue(prop, style[prop]); - if (value == null) { return resolvedStyle; } + if (value == null) { + return resolvedStyle; + } switch (prop) { case 'display': { resolvedStyle.display = value; // default of 'flexShrink:0' has lowest precedence - if ( - style.display === 'flex' && - style.flex == null && - style.flexShrink == null - ) { + if (style.display === 'flex' && style.flex == null && style.flexShrink == null) { resolvedStyle.flexShrink = 0; } break; @@ -82,7 +89,7 @@ const createReducer = (style, styleProps) => { break; } case 'textAlignVertical': { - resolvedStyle.verticalAlign = (value === 'center' ? 'middle' : value); + resolvedStyle.verticalAlign = value === 'center' ? 'middle' : value; break; } case 'textShadowColor': @@ -118,8 +125,10 @@ const createReducer = (style, styleProps) => { }; }; -const expandStyle = (style) => { - if (!style) { return emptyObject; } +const expandStyle = style => { + if (!style) { + return emptyObject; + } const styleProps = Object.keys(style); const sortedStyleProps = alphaSortProps(styleProps); const reducer = createReducer(style, styleProps); diff --git a/src/apis/StyleSheet/generateCss.js b/src/apis/StyleSheet/generateCss.js index 9de74d61..934a9b34 100644 --- a/src/apis/StyleSheet/generateCss.js +++ b/src/apis/StyleSheet/generateCss.js @@ -7,7 +7,7 @@ const createDeclarationString = (prop, val) => { const name = hyphenate(prop); const value = normalizeValue(prop, val); if (Array.isArray(val)) { - return val.map((v) => `${name}:${v}`).join(';'); + return val.map(v => `${name}:${v}`).join(';'); } return `${name}:${value}`; }; @@ -18,6 +18,7 @@ const createDeclarationString = (prop, val) => { * generateCss({ width: 20, color: 'blue' }); * // => 'color:blue;width:20px' */ -const generateCss = (style) => mapKeyValue(prefixAll(style), createDeclarationString).sort().join(';'); +const generateCss = style => + mapKeyValue(prefixAll(style), createDeclarationString).sort().join(';'); module.exports = generateCss; diff --git a/src/apis/StyleSheet/hash.js b/src/apis/StyleSheet/hash.js index b1f8167d..39f46b22 100644 --- a/src/apis/StyleSheet/hash.js +++ b/src/apis/StyleSheet/hash.js @@ -13,41 +13,39 @@ */ function murmurhash2_32_gc(str, seed) { - var - l = str.length, - h = seed ^ l, - i = 0, - k; + var l = str.length, h = seed ^ l, i = 0, k; while (l >= 4) { - k = - ((str.charCodeAt(i) & 0xff)) | - ((str.charCodeAt(++i) & 0xff) << 8) | - ((str.charCodeAt(++i) & 0xff) << 16) | - ((str.charCodeAt(++i) & 0xff) << 24); + k = str.charCodeAt(i) & 0xff | + (str.charCodeAt((++i)) & 0xff) << 8 | + (str.charCodeAt((++i)) & 0xff) << 16 | + (str.charCodeAt((++i)) & 0xff) << 24; - k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16); k ^= k >>> 24; - k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16); - h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k; + h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16) ^ k; l -= 4; ++i; } switch (l) { - case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; - case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; - case 1: h ^= (str.charCodeAt(i) & 0xff); - h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + case 3: + h ^= (str.charCodeAt(i + 2) & 0xff) << 16; + case 2: + h ^= (str.charCodeAt(i + 1) & 0xff) << 8; + case 1: + h ^= str.charCodeAt(i) & 0xff; + h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16); } h ^= h >>> 13; - h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); + h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16); h ^= h >>> 15; return h >>> 0; } -module.exports = (str) => murmurhash2_32_gc(str, 1).toString(36); +module.exports = str => murmurhash2_32_gc(str, 1).toString(36); diff --git a/src/apis/StyleSheet/hyphenate.js b/src/apis/StyleSheet/hyphenate.js index a42222d2..492deb0c 100644 --- a/src/apis/StyleSheet/hyphenate.js +++ b/src/apis/StyleSheet/hyphenate.js @@ -2,7 +2,7 @@ const cache = {}; const MS_REGEXP = /^ms-/; const UPPERCASE_REGEXP = /([A-Z])/g; -const hyphenateStyleProp = (prop) => { +const hyphenateStyleProp = prop => { if (!cache.hasOwnProperty(prop)) { cache[prop] = prop.replace(UPPERCASE_REGEXP, '-$&').toLowerCase().replace(MS_REGEXP, '-ms-'); } diff --git a/src/apis/StyleSheet/i18nStyle.js b/src/apis/StyleSheet/i18nStyle.js index dc8cb679..af1b2d1a 100644 --- a/src/apis/StyleSheet/i18nStyle.js +++ b/src/apis/StyleSheet/i18nStyle.js @@ -7,28 +7,28 @@ const emptyObject = {}; * Map of property names to their BiDi equivalent. */ const PROPERTIES_TO_SWAP = { - 'borderTopLeftRadius': 'borderTopRightRadius', - 'borderTopRightRadius': 'borderTopLeftRadius', - 'borderBottomLeftRadius': 'borderBottomRightRadius', - 'borderBottomRightRadius': 'borderBottomLeftRadius', - 'borderLeftColor': 'borderRightColor', - 'borderLeftStyle': 'borderRightStyle', - 'borderLeftWidth': 'borderRightWidth', - 'borderRightColor': 'borderLeftColor', - 'borderRightWidth': 'borderLeftWidth', - 'borderRightStyle': 'borderLeftStyle', - 'left': 'right', - 'marginLeft': 'marginRight', - 'marginRight': 'marginLeft', - 'paddingLeft': 'paddingRight', - 'paddingRight': 'paddingLeft', - 'right': 'left' + borderTopLeftRadius: 'borderTopRightRadius', + borderTopRightRadius: 'borderTopLeftRadius', + borderBottomLeftRadius: 'borderBottomRightRadius', + borderBottomRightRadius: 'borderBottomLeftRadius', + borderLeftColor: 'borderRightColor', + borderLeftStyle: 'borderRightStyle', + borderLeftWidth: 'borderRightWidth', + borderRightColor: 'borderLeftColor', + borderRightWidth: 'borderLeftWidth', + borderRightStyle: 'borderLeftStyle', + left: 'right', + marginLeft: 'marginRight', + marginRight: 'marginLeft', + paddingLeft: 'paddingRight', + paddingRight: 'paddingLeft', + right: 'left' }; const PROPERTIES_SWAP_LEFT_RIGHT = { - 'clear': true, - 'float': true, - 'textAlign': true + clear: true, + float: true, + textAlign: true }; /** @@ -54,11 +54,11 @@ const flipTransform = (transform: Object): Object => { return transform; }; -const swapLeftRight = (value:String): String => { +const swapLeftRight = (value: String): String => { return value === 'left' ? 'right' : value === 'right' ? 'left' : value; }; -const i18nStyle = (originalStyle) => { +const i18nStyle = originalStyle => { if (!I18nManager.isRTL) { return originalStyle; } diff --git a/src/apis/StyleSheet/index.js b/src/apis/StyleSheet/index.js index 842e482b..83774dae 100644 --- a/src/apis/StyleSheet/index.js +++ b/src/apis/StyleSheet/index.js @@ -1,7 +1,13 @@ import flattenStyle from './flattenStyle'; import StyleRegistry from './registry'; -const absoluteFillObject = { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0 }; +const absoluteFillObject = { + position: 'absolute', + left: 0, + right: 0, + top: 0, + bottom: 0 +}; const absoluteFill = StyleRegistry.register(absoluteFillObject); module.exports = { @@ -9,7 +15,7 @@ module.exports = { absoluteFillObject, create(styles) { const result = {}; - Object.keys(styles).forEach((key) => { + Object.keys(styles).forEach(key => { if (process.env.NODE_ENV !== 'production') { require('./StyleSheetValidation').validateStyle(key, styles); } diff --git a/src/apis/StyleSheet/prefixInlineStyles.js b/src/apis/StyleSheet/prefixInlineStyles.js index 5f24b9c2..78ff51ec 100644 --- a/src/apis/StyleSheet/prefixInlineStyles.js +++ b/src/apis/StyleSheet/prefixInlineStyles.js @@ -1,11 +1,11 @@ import prefixAll from 'inline-style-prefixer/static'; -const prefixInlineStyles = (style) => { +const prefixInlineStyles = style => { const prefixedStyles = prefixAll(style); // React@15 removed undocumented support for fallback values in // inline-styles. Revert array values to the standard CSS value - Object.keys(prefixedStyles).forEach((prop) => { + Object.keys(prefixedStyles).forEach(prop => { const value = prefixedStyles[prop]; if (Array.isArray(value)) { prefixedStyles[prop] = value[value.length - 1]; diff --git a/src/apis/StyleSheet/resolveTransform.js b/src/apis/StyleSheet/resolveTransform.js index dc95ed0b..2bd77020 100644 --- a/src/apis/StyleSheet/resolveTransform.js +++ b/src/apis/StyleSheet/resolveTransform.js @@ -1,15 +1,15 @@ import normalizeValue from './normalizeValue'; // { scale: 2 } => 'scale(2)' - // { translateX: 20 } => 'translateX(20px)' -const mapTransform = (transform) => { +// { translateX: 20 } => 'translateX(20px)' +const mapTransform = transform => { const type = Object.keys(transform)[0]; const value = normalizeValue(type, transform[type]); return `${type}(${value})`; }; // [1,2,3,4,5,6] => 'matrix3d(1,2,3,4,5,6)' -const convertTransformMatrix = (transformMatrix) => { +const convertTransformMatrix = transformMatrix => { const matrix = transformMatrix.join(','); return `matrix3d(${matrix})`; }; diff --git a/src/apis/StyleSheet/staticCss.js b/src/apis/StyleSheet/staticCss.js index b0f9e8b5..ecc7b8dc 100644 --- a/src/apis/StyleSheet/staticCss.js +++ b/src/apis/StyleSheet/staticCss.js @@ -1,21 +1,17 @@ -module.exports = - // css reset - 'html{' + - 'font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;' + - '-webkit-tap-highlight-color:rgba(0,0,0,0);' + +module.exports = 'html{' + // css reset + 'font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;' + + '-webkit-tap-highlight-color:rgba(0,0,0,0);' + '}\n' + 'body{margin:0;}\n' + 'button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0;}\n' + 'input::-webkit-inner-spin-button,input::-webkit-outer-spin-button,' + 'input::-webkit-search-cancel-button,input::-webkit-search-decoration,' + 'input::-webkit-search-results-button,input::-webkit-search-results-decoration{display:none;}\n' + - '@keyframes rn-ActivityIndicator-animation{' + - '0%{-webkit-transform:rotate(0deg);transform:rotate(0deg);}' + - '100%{-webkit-transform:rotate(360deg);transform:rotate(360deg);}' + + '0%{-webkit-transform:rotate(0deg);transform:rotate(0deg);}' + + '100%{-webkit-transform:rotate(360deg);transform:rotate(360deg);}' + '}\n' + - '@keyframes rn-ProgressBar-animation{' + - '0%{-webkit-transform:translateX(-100%);transform:translateX(-100%)};' + - '100%{-webkit-transform:translateX(400%);transform:translateX(400%)};' + + '0%{-webkit-transform:translateX(-100%);transform:translateX(-100%)};' + + '100%{-webkit-transform:translateX(400%);transform:translateX(400%)};' + '}'; diff --git a/src/apis/UIManager/__tests__/index-test.js b/src/apis/UIManager/__tests__/index-test.js index 5e8103a8..ce77ffbb 100644 --- a/src/apis/UIManager/__tests__/index-test.js +++ b/src/apis/UIManager/__tests__/index-test.js @@ -4,7 +4,7 @@ import UIManager from '..'; const createNode = (style = {}) => { const root = document.createElement('div'); - Object.keys(style).forEach((prop) => { + Object.keys(style).forEach(prop => { root.style[prop] = style[prop]; }); return root; @@ -30,7 +30,9 @@ describe('apis/UIManager', () => { const node = createNode({ color: 'red' }); const props = { style: { marginTop: 0, marginBottom: 0, opacity: 0 } }; UIManager.updateView(node, props, componentStub); - expect(node.getAttribute('style')).toEqual('color: red; margin-top: 0px; margin-bottom: 0px; opacity: 0;'); + expect(node.getAttribute('style')).toEqual( + 'color: red; margin-top: 0px; margin-bottom: 0px; opacity: 0;' + ); }); test('replaces input and textarea text', () => { diff --git a/src/apis/UIManager/index.js b/src/apis/UIManager/index.js index 2a397d89..34b0ed20 100644 --- a/src/apis/UIManager/index.js +++ b/src/apis/UIManager/index.js @@ -1,7 +1,7 @@ import asap from 'asap'; import CSSPropertyOperations from 'react-dom/lib/CSSPropertyOperations'; -const getRect = (node) => { +const getRect = node => { const height = node.offsetHeight; const width = node.offsetWidth; let left = 0; @@ -27,11 +27,15 @@ const measureLayout = (node, relativeToNativeNode, callback) => { const UIManager = { blur(node) { - try { node.blur(); } catch (err) {} + try { + node.blur(); + } catch (err) {} }, focus(node) { - try { node.focus(); } catch (err) {} + try { + node.focus(); + } catch (err) {} }, measure(node, callback) { diff --git a/src/apis/Vibration/index.js b/src/apis/Vibration/index.js index 032b9229..ce83900a 100644 --- a/src/apis/Vibration/index.js +++ b/src/apis/Vibration/index.js @@ -1,4 +1,4 @@ -const vibrate = (pattern) => { +const vibrate = pattern => { if ('vibrate' in window.navigator) { if (typeof pattern === 'number' || Array.isArray(pattern)) { window.navigator.vibrate(pattern); diff --git a/src/components/ActivityIndicator/__tests__/index-test.js b/src/components/ActivityIndicator/__tests__/index-test.js index 614997c1..d50b41b1 100644 --- a/src/components/ActivityIndicator/__tests__/index-test.js +++ b/src/components/ActivityIndicator/__tests__/index-test.js @@ -11,7 +11,9 @@ describe('components/ActivityIndicator', () => { }); test('other render', () => { - const component = renderer.create(); + const component = renderer.create( + + ); expect(component.toJSON()).toMatchSnapshot(); }); }); diff --git a/src/components/ActivityIndicator/index.js b/src/components/ActivityIndicator/index.js index 1f0abec5..c7f2e88c 100644 --- a/src/components/ActivityIndicator/index.js +++ b/src/components/ActivityIndicator/index.js @@ -12,7 +12,7 @@ class ActivityIndicator extends Component { animating: PropTypes.bool, color: PropTypes.string, hidesWhenStopped: PropTypes.bool, - size: PropTypes.oneOfType([ PropTypes.oneOf([ 'small', 'large' ]), PropTypes.number ]) + size: PropTypes.oneOfType([PropTypes.oneOf(['small', 'large']), PropTypes.number]) }; static defaultProps = { @@ -33,24 +33,24 @@ class ActivityIndicator extends Component { } = this.props; const svg = ( - + - + ]} + > + {title} diff --git a/src/components/Image/ImageStylePropTypes.js b/src/components/Image/ImageStylePropTypes.js index 61219b0b..f4b07c08 100644 --- a/src/components/Image/ImageStylePropTypes.js +++ b/src/components/Image/ImageStylePropTypes.js @@ -7,7 +7,7 @@ import ShadowPropTypes from '../../propTypes/ShadowPropTypes'; import TransformPropTypes from '../../propTypes/TransformPropTypes'; const { number, oneOf, string } = PropTypes; -const hiddenOrVisible = oneOf([ 'hidden', 'visible' ]); +const hiddenOrVisible = oneOf(['hidden', 'visible']); module.exports = { ...BorderPropTypes, diff --git a/src/components/Image/__tests__/index-test.js b/src/components/Image/__tests__/index-test.js index d62b57e0..65cec6e4 100644 --- a/src/components/Image/__tests__/index-test.js +++ b/src/components/Image/__tests__/index-test.js @@ -23,7 +23,7 @@ describe('components/Image', () => { }); test('prop "accessibilityLabel"', () => { - const component = renderer.create(); + const component = renderer.create(); expect(component.toJSON()).toMatchSnapshot(); }); @@ -33,7 +33,7 @@ describe('components/Image', () => { }); test('prop "children"', () => { - const children =
; + const children =
; const component = renderer.create(); expect(component.toJSON()).toMatchSnapshot(); }); @@ -53,14 +53,24 @@ describe('components/Image', () => { }); test('sets "height" and "width" styles if missing', () => { - const defaultSource = { uri: 'https://google.com/favicon.ico', height: 10, width: 20 }; + const defaultSource = { + uri: 'https://google.com/favicon.ico', + height: 10, + width: 20 + }; const component = renderer.create(); expect(component.toJSON()).toMatchSnapshot(); }); test('does not override "height" and "width" styles', () => { - const defaultSource = { uri: 'https://google.com/favicon.ico', height: 10, width: 20 }; - const component = renderer.create(); + const defaultSource = { + uri: 'https://google.com/favicon.ico', + height: 10, + width: 20 + }; + const component = renderer.create( + + ); expect(component.toJSON()).toMatchSnapshot(); }); }); @@ -72,7 +82,7 @@ describe('components/Image', () => { Image.resizeMode.none, Image.resizeMode.stretch, undefined - ].forEach((resizeMode) => { + ].forEach(resizeMode => { test(`value "${resizeMode}"`, () => { const component = renderer.create(); expect(component.toJSON()).toMatchSnapshot(); @@ -88,7 +98,7 @@ describe('components/Image', () => { }); test('prop "testID"', () => { - const component = renderer.create(); + const component = renderer.create(); expect(component.toJSON()).toMatchSnapshot(); }); diff --git a/src/components/Image/index.js b/src/components/Image/index.js index a35e92e3..45577bcd 100644 --- a/src/components/Image/index.js +++ b/src/components/Image/index.js @@ -28,15 +28,15 @@ const ImageSourcePropType = PropTypes.oneOfType([ PropTypes.string ]); -const resolveAssetDimensions = (source) => { +const resolveAssetDimensions = source => { if (typeof source === 'object') { const { height, width } = source; return { height, width }; } }; -const resolveAssetSource = (source) => { - return ((typeof source === 'object') ? source.uri : source) || null; +const resolveAssetSource = source => { + return (typeof source === 'object' ? source.uri : source) || null; }; class Image extends Component { @@ -140,10 +140,12 @@ class Image extends Component { delete style.resizeMode; // Allows users to trigger the browser's image context menu - const hiddenImage = displayImage ? createDOMElement('img', { - src: displayImage, - style: [ StyleSheet.absoluteFill, styles.img ] - }) : null; + const hiddenImage = displayImage + ? createDOMElement('img', { + src: displayImage, + style: [StyleSheet.absoluteFill, styles.img] + }) + : null; return ( { + _onLoad = e => { const { onLoad } = this.props; const event = { nativeEvent: e }; this._updateImageState(STATUS_LOADED); - if (onLoad) { onLoad(event); } + if (onLoad) { + onLoad(event); + } this._onLoadEnd(); - } + }; _onLoadEnd() { const { onLoadEnd } = this.props; - if (onLoadEnd) { onLoadEnd(); } + if (onLoadEnd) { + onLoadEnd(); + } } _onLoadStart() { const { onLoadStart } = this.props; this._updateImageState(STATUS_LOADING); - if (onLoadStart) { onLoadStart(); } + if (onLoadStart) { + onLoadStart(); + } } _updateImageState(status) { this._imageState = status; - const shouldDisplaySource = this._imageState === STATUS_LOADED || this._imageState === STATUS_LOADING; + const shouldDisplaySource = this._imageState === STATUS_LOADED || + this._imageState === STATUS_LOADING; // only triggers a re-render when the image is loading (to support PJEG), loaded, or failed if (shouldDisplaySource !== this.state.shouldDisplaySource) { if (this._isMounted) { diff --git a/src/components/ListView/ListViewDataSource.js b/src/components/ListView/ListViewDataSource.js index 8ec091a1..5e34eeb9 100644 --- a/src/components/ListView/ListViewDataSource.js +++ b/src/components/ListView/ListViewDataSource.js @@ -33,29 +33,22 @@ var invariant = require('fbjs/lib/invariant'); var isEmpty = require('fbjs/lib/isEmpty'); var warning = require('fbjs/lib/warning'); -function defaultGetRowData( - dataBlob: any, - sectionID: number | string, - rowID: number | string -): any { +function defaultGetRowData(dataBlob: any, sectionID: number | string, rowID: number | string): any { return dataBlob[sectionID][rowID]; } -function defaultGetSectionHeaderData( - dataBlob: any, - sectionID: number | string -): any { +function defaultGetSectionHeaderData(dataBlob: any, sectionID: number | string): any { return dataBlob[sectionID]; } -type differType = (data1: any, data2: any) => bool; +type differType = (data1: any, data2: any) => boolean; type ParamType = { - rowHasChanged: differType; - getRowData: ?typeof defaultGetRowData; - sectionHeaderHasChanged: ?differType; - getSectionHeaderData: ?typeof defaultGetSectionHeaderData; -} + rowHasChanged: differType, + getRowData: ?typeof defaultGetRowData, + sectionHeaderHasChanged: ?differType, + getSectionHeaderData: ?typeof defaultGetSectionHeaderData +}; /** * Provides efficient data processing and access to the @@ -92,7 +85,6 @@ type ParamType = { */ class ListViewDataSource { - /** * You can provide custom extraction and `hasChanged` functions for section * headers and rows. If absent, data will be extracted with the @@ -126,8 +118,7 @@ class ListViewDataSource { this._rowHasChanged = params.rowHasChanged; this._getRowData = params.getRowData || defaultGetRowData; this._sectionHeaderHasChanged = params.sectionHeaderHasChanged; - this._getSectionHeaderData = - params.getSectionHeaderData || defaultGetSectionHeaderData; + this._getSectionHeaderData = params.getSectionHeaderData || defaultGetSectionHeaderData; this._dataBlob = null; this._dirtyRows = []; @@ -156,15 +147,15 @@ class ListViewDataSource { * handle merging of old and new data separately and then pass that into * this function as the `dataBlob`. */ - cloneWithRows( - dataBlob: Array | {[key: string]: any}, - rowIdentities: ?Array - ): ListViewDataSource { + cloneWithRows( + dataBlob: Array | { [key: string]: any }, + rowIdentities: ?Array + ): ListViewDataSource { var rowIds = rowIdentities ? [rowIdentities] : null; if (!this._sectionHeaderHasChanged) { this._sectionHeaderHasChanged = () => false; } - return this.cloneWithRowsAndSections({s1: dataBlob}, ['s1'], rowIds); + return this.cloneWithRowsAndSections({ s1: dataBlob }, ['s1'], rowIds); } /** @@ -179,9 +170,9 @@ class ListViewDataSource { * Note: this returns a new object! */ cloneWithRowsAndSections( - dataBlob: any, - sectionIdentities: ?Array, - rowIdentities: ?Array> + dataBlob: any, + sectionIdentities: ?Array, + rowIdentities: ?Array> ): ListViewDataSource { invariant( typeof this._sectionHeaderHasChanged === 'function', @@ -191,7 +182,7 @@ class ListViewDataSource { getRowData: this._getRowData, getSectionHeaderData: this._getSectionHeaderData, rowHasChanged: this._rowHasChanged, - sectionHeaderHasChanged: this._sectionHeaderHasChanged, + sectionHeaderHasChanged: this._sectionHeaderHasChanged }); newSource._dataBlob = dataBlob; if (sectionIdentities) { @@ -203,17 +194,13 @@ class ListViewDataSource { newSource.rowIdentities = rowIdentities; } else { newSource.rowIdentities = []; - newSource.sectionIdentities.forEach((sectionID) => { + newSource.sectionIdentities.forEach(sectionID => { newSource.rowIdentities.push(Object.keys(dataBlob[sectionID])); }); } newSource._cachedRowCount = countRows(newSource.rowIdentities); - newSource._calculateDirtyArrays( - this._dataBlob, - this.sectionIdentities, - this.rowIdentities - ); + newSource._calculateDirtyArrays(this._dataBlob, this.sectionIdentities, this.rowIdentities); return newSource; } @@ -223,16 +210,18 @@ class ListViewDataSource { } getRowAndSectionCount(): number { - return (this._cachedRowCount + this.sectionIdentities.length); + return this._cachedRowCount + this.sectionIdentities.length; } /** * Returns if the row is dirtied and needs to be rerendered */ - rowShouldUpdate(sectionIndex: number, rowIndex: number): bool { + rowShouldUpdate(sectionIndex: number, rowIndex: number): boolean { var needsUpdate = this._dirtyRows[sectionIndex][rowIndex]; - warning(needsUpdate !== undefined, - 'missing dirtyBit for section, row: ' + sectionIndex + ', ' + rowIndex); + warning( + needsUpdate !== undefined, + 'missing dirtyBit for section, row: ' + sectionIndex + ', ' + rowIndex + ); return needsUpdate; } @@ -295,10 +284,9 @@ class ListViewDataSource { /** * Returns if the section header is dirtied and needs to be rerendered */ - sectionHeaderShouldUpdate(sectionIndex: number): bool { + sectionHeaderShouldUpdate(sectionIndex: number): boolean { var needsUpdate = this._dirtySections[sectionIndex]; - warning(needsUpdate !== undefined, - 'missing dirtyBit for section: ' + sectionIndex); + warning(needsUpdate !== undefined, 'missing dirtyBit for section: ' + sectionIndex); return needsUpdate; } @@ -310,8 +298,7 @@ class ListViewDataSource { return null; } var sectionID = this.sectionIdentities[sectionIndex]; - warning(sectionID !== undefined, - 'renderSection called on invalid section: ' + sectionIndex); + warning(sectionID !== undefined, 'renderSection called on invalid section: ' + sectionIndex); return this._getSectionHeaderData(this._dataBlob, sectionID); } @@ -325,8 +312,8 @@ class ListViewDataSource { _sectionHeaderHasChanged: ?differType; _dataBlob: any; - _dirtyRows: Array>; - _dirtySections: Array; + _dirtyRows: Array>; + _dirtySections: Array; _cachedRowCount: number; // These two 'protected' variables are accessed by ListView to iterate over @@ -344,10 +331,7 @@ class ListViewDataSource { var prevRowsHash = {}; for (var ii = 0; ii < prevRowIDs.length; ii++) { var sectionID = prevSectionIDs[ii]; - warning( - !prevRowsHash[sectionID], - 'SectionID appears more than once: ' + sectionID - ); + warning(!prevRowsHash[sectionID], 'SectionID appears more than once: ' + sectionID); prevRowsHash[sectionID] = keyedDictionaryFromArray(prevRowIDs[ii]); } @@ -373,8 +357,7 @@ class ListViewDataSource { for (var rIndex = 0; rIndex < this.rowIdentities[sIndex].length; rIndex++) { var rowID = this.rowIdentities[sIndex][rIndex]; // dirty if the section is new, row is new or _rowHasChanged is true - dirty = - !prevSectionsHash[sectionID] || + dirty = !prevSectionsHash[sectionID] || !prevRowsHash[sectionID][rowID] || this._rowHasChanged( this._getRowData(prevDataBlob, sectionID, rowID), @@ -408,5 +391,4 @@ function keyedDictionaryFromArray(arr) { return result; } - module.exports = ListViewDataSource; diff --git a/src/components/ListView/index.js b/src/components/ListView/index.js index 9ba494ee..7a6678da 100644 --- a/src/components/ListView/index.js +++ b/src/components/ListView/index.js @@ -19,7 +19,7 @@ class ListView extends Component { static defaultProps = { initialListSize: DEFAULT_INITIAL_ROWS, pageSize: DEFAULT_PAGE_SIZE, - renderScrollComponent: (props) => , + renderScrollComponent: props => , scrollRenderAheadDistance: DEFAULT_SCROLL_RENDER_AHEAD, onEndReachedThreshold: DEFAULT_END_REACHED_THRESHOLD, scrollEventThrottle: DEFAULT_SCROLL_CALLBACK_THROTTLE, @@ -61,16 +61,24 @@ class ListView extends Component { } componentWillReceiveProps(nextProps: Object) { - if (this.props.dataSource !== nextProps.dataSource || this.props.initialListSize !== nextProps.initialListSize) { - this.setState((state, props) => { - this._prevRenderedRowsCount = 0; - return { - curRenderedRowsCount: Math.min( - Math.max(state.curRenderedRowsCount, props.initialListSize), - props.enableEmptySections ? props.dataSource.getRowAndSectionCount() : props.dataSource.getRowCount() - ) - }; - }, () => this._renderMoreRowsIfNeeded()); + if ( + this.props.dataSource !== nextProps.dataSource || + this.props.initialListSize !== nextProps.initialListSize + ) { + this.setState( + (state, props) => { + this._prevRenderedRowsCount = 0; + return { + curRenderedRowsCount: Math.min( + Math.max(state.curRenderedRowsCount, props.initialListSize), + props.enableEmptySections + ? props.dataSource.getRowAndSectionCount() + : props.dataSource.getRowCount() + ) + }; + }, + () => this._renderMoreRowsIfNeeded() + ); } } @@ -94,15 +102,15 @@ class ListView extends Component { _onRowHighlighted = (sectionId, rowId) => { this.setState({ highlightedRow: { sectionId, rowId } }); - } + }; renderSectionHeaderFn = (data, sectionID) => { return () => this.props.renderSectionHeader(data, sectionID); - } + }; renderRowFn = (data, sectionID, rowID) => { return () => this.props.renderRow(data, sectionID, rowID, this._onRowHighlighted); - } + }; render() { const children = []; @@ -144,18 +152,22 @@ class ListView extends Component { if (rowIDs.length === 0) { if (enableEmptySections === undefined) { const warning = require('fbjs/lib/warning'); - warning(false, 'In next release empty section headers will be rendered.' + - ' In this release you can use \'enableEmptySections\' flag to render empty section headers.'); + warning( + false, + 'In next release empty section headers will be rendered.' + + " In this release you can use 'enableEmptySections' flag to render empty section headers." + ); continue; } else { const invariant = require('fbjs/lib/invariant'); invariant( enableEmptySections, - 'In next release \'enableEmptySections\' flag will be deprecated,' + - ' empty section headers will always be rendered. If empty section headers' + - ' are not desirable their indices should be excluded from sectionIDs object.' + - ' In this release \'enableEmptySections\' may only have value \'true\'' + - ' to allow empty section headers rendering.'); + "In next release 'enableEmptySections' flag will be deprecated," + + ' empty section headers will always be rendered. If empty section headers' + + ' are not desirable their indices should be excluded from sectionIDs object.' + + " In this release 'enableEmptySections' may only have value 'true'" + + ' to allow empty section headers rendering.' + ); } } @@ -172,7 +184,7 @@ class ListView extends Component { shouldUpdate={!!shouldUpdateHeader} /> ); - sectionHeaderIndices.push(totalIndex++); + sectionHeaderIndices.push((totalIndex++)); } for (let rowIdx = 0; rowIdx < rowIDs.length; rowIdx++) { @@ -180,31 +192,23 @@ class ListView extends Component { const comboID = `${sectionID}_${rowID}`; const shouldUpdateRow = rowCount >= this._prevRenderedRowsCount && dataSource.rowShouldUpdate(sectionIdx, rowIdx); - const row = + const row = ( ; + /> + ); children.push(row); totalIndex++; - if (renderSeparator && - (rowIdx !== rowIDs.length - 1 || sectionIdx === allRowIDs.length - 1)) { - const adjacentRowHighlighted = - this.state.highlightedRow.sectionID === sectionID && ( - this.state.highlightedRow.rowID === rowID || - this.state.highlightedRow.rowID === rowIDs[rowIdx + 1] - ); - const separator = renderSeparator( - sectionID, - rowID, - adjacentRowHighlighted - ); + if ( + renderSeparator && (rowIdx !== rowIDs.length - 1 || sectionIdx === allRowIDs.length - 1) + ) { + const adjacentRowHighlighted = this.state.highlightedRow.sectionID === sectionID && + (this.state.highlightedRow.rowID === rowID || + this.state.highlightedRow.rowID === rowIDs[rowIdx + 1]); + const separator = renderSeparator(sectionID, rowID, adjacentRowHighlighted); if (separator) { children.push(separator); totalIndex++; @@ -220,11 +224,17 @@ class ListView extends Component { } scrollProps.onScroll = this._onScroll; - return React.cloneElement(renderScrollComponent(scrollProps), { - ref: this._setScrollViewRef, - onContentSizeChange: this._onContentSizeChange, - onLayout: this._onLayout - }, header, children, footer); + return React.cloneElement( + renderScrollComponent(scrollProps), + { + ref: this._setScrollViewRef, + onContentSizeChange: this._onContentSizeChange, + onLayout: this._onLayout + }, + header, + children, + footer + ); } _measureAndUpdateScrollProps() { @@ -245,14 +255,14 @@ class ListView extends Component { this._renderMoreRowsIfNeeded(); } this.props.onLayout && this.props.onLayout(event); - } + }; _updateVisibleRows(updatedFrames?: Array) { if (!this.props.onChangeVisibleRows) { return; // No need to compute visible rows if there is no callback } if (updatedFrames) { - updatedFrames.forEach((newFrame) => { + updatedFrames.forEach(newFrame => { this._childFrames[newFrame.index] = Object.assign({}, newFrame); }); } @@ -283,8 +293,10 @@ class ListView extends Component { const rowID = rowIDs[rowIdx]; const frame = this._childFrames[totalIndex]; totalIndex++; - if (this.props.renderSeparator && - (rowIdx !== rowIDs.length - 1 || sectionIdx === allRowIDs.length - 1)) { + if ( + this.props.renderSeparator && + (rowIdx !== rowIDs.length - 1 || sectionIdx === allRowIDs.length - 1) + ) { totalIndex++; } if (!frame) { @@ -293,7 +305,7 @@ class ListView extends Component { const rowVisible = visibleSection[rowID]; const min = isVertical ? frame.y : frame.x; const max = min + (isVertical ? frame.height : frame.width); - if ((!min && !max) || (min === max)) { + if ((!min && !max) || min === max) { break; } if (min > visibleMax || max < visibleMin) { @@ -331,18 +343,24 @@ class ListView extends Component { this._renderMoreRowsIfNeeded(); } this.props.onContentSizeChange && this.props.onContentSizeChange(width, height); - } + }; _getDistanceFromEnd(scrollProperties: Object) { - return scrollProperties.contentLength - scrollProperties.visibleLength - scrollProperties.offset; + return scrollProperties.contentLength - + scrollProperties.visibleLength - + scrollProperties.offset; } _maybeCallOnEndReached(event?: Object) { - if (this.props.onEndReached && - this.scrollProperties.contentLength !== this._sentEndForContentLength && - this._getDistanceFromEnd(this.scrollProperties) < this.props.onEndReachedThreshold && - this.state.curRenderedRowsCount === (this.props.enableEmptySections ? - this.props.dataSource.getRowAndSectionCount() : this.props.dataSource.getRowCount())) { + if ( + this.props.onEndReached && + this.scrollProperties.contentLength !== this._sentEndForContentLength && + this._getDistanceFromEnd(this.scrollProperties) < this.props.onEndReachedThreshold && + this.state.curRenderedRowsCount === + (this.props.enableEmptySections + ? this.props.dataSource.getRowAndSectionCount() + : this.props.dataSource.getRowCount()) + ) { this._sentEndForContentLength = this.scrollProperties.contentLength; this.props.onEndReached(event); return true; @@ -351,10 +369,14 @@ class ListView extends Component { } _renderMoreRowsIfNeeded() { - if (this.scrollProperties.contentLength === null || + if ( + this.scrollProperties.contentLength === null || this.scrollProperties.visibleLength === null || - this.state.curRenderedRowsCount === (this.props.enableEmptySections ? - this.props.dataSource.getRowAndSectionCount() : this.props.dataSource.getRowCount())) { + this.state.curRenderedRowsCount === + (this.props.enableEmptySections + ? this.props.dataSource.getRowAndSectionCount() + : this.props.dataSource.getRowCount()) + ) { this._maybeCallOnEndReached(); return; } @@ -366,19 +388,24 @@ class ListView extends Component { } _pageInNewRows() { - this.setState((state, props) => { - const rowsToRender = Math.min( - state.curRenderedRowsCount + props.pageSize, - (props.enableEmptySections ? props.dataSource.getRowAndSectionCount() : props.dataSource.getRowCount()) - ); - this._prevRenderedRowsCount = state.curRenderedRowsCount; - return { - curRenderedRowsCount: rowsToRender - }; - }, () => { - this._measureAndUpdateScrollProps(); - this._prevRenderedRowsCount = this.state.curRenderedRowsCount; - }); + this.setState( + (state, props) => { + const rowsToRender = Math.min( + state.curRenderedRowsCount + props.pageSize, + props.enableEmptySections + ? props.dataSource.getRowAndSectionCount() + : props.dataSource.getRowCount() + ); + this._prevRenderedRowsCount = state.curRenderedRowsCount; + return { + curRenderedRowsCount: rowsToRender + }; + }, + () => { + this._measureAndUpdateScrollProps(); + this._prevRenderedRowsCount = this.state.curRenderedRowsCount; + } + ); } _onScroll = (e: Object) => { @@ -389,16 +416,16 @@ class ListView extends Component { this.scrollProperties.contentLength = e.nativeEvent.contentSize[ isVertical ? 'height' : 'width' ]; - this.scrollProperties.offset = e.nativeEvent.contentOffset[ - isVertical ? 'y' : 'x' - ]; + this.scrollProperties.offset = e.nativeEvent.contentOffset[isVertical ? 'y' : 'x']; this._updateVisibleRows(e.nativeEvent.updatedChildFrames); if (!this._maybeCallOnEndReached(e)) { this._renderMoreRowsIfNeeded(); } - if (this.props.onEndReached && - this._getDistanceFromEnd(this.scrollProperties) > this.props.onEndReachedThreshold) { + if ( + this.props.onEndReached && + this._getDistanceFromEnd(this.scrollProperties) > this.props.onEndReachedThreshold + ) { // Scrolled out of the end zone, so it should be able to trigger again. this._sentEndForContentLength = null; } @@ -406,9 +433,9 @@ class ListView extends Component { this.props.onScroll && this.props.onScroll(e); }; - _setScrollViewRef = (component) => { + _setScrollViewRef = component => { this._scrollViewRef = component; - } + }; } module.exports = applyNativeMethods(ListView); diff --git a/src/components/ProgressBar/index.js b/src/components/ProgressBar/index.js index eaf8443e..94a0c672 100644 --- a/src/components/ProgressBar/index.js +++ b/src/components/ProgressBar/index.js @@ -44,32 +44,25 @@ class ProgressBar extends Component { const percentageProgress = progress * 100; return ( - ); } - _setProgressRef = (component) => { + _setProgressRef = component => { this._progressRef = component; - } + }; _updateProgressWidth = () => { const { indeterminate, progress } = this.props; @@ -78,7 +71,7 @@ class ProgressBar extends Component { this._progressRef.setNativeProps({ style: { width } }); - } + }; } const styles = StyleSheet.create({ diff --git a/src/components/ScrollView/ScrollViewBase.js b/src/components/ScrollView/ScrollViewBase.js index a469b7cf..31f5cf6f 100644 --- a/src/components/ScrollView/ScrollViewBase.js +++ b/src/components/ScrollView/ScrollViewBase.js @@ -11,7 +11,7 @@ import View from '../View'; import ViewPropTypes from '../View/ViewPropTypes'; import React, { Component, PropTypes } from 'react'; -const normalizeScrollEvent = (e) => ({ +const normalizeScrollEvent = e => ({ nativeEvent: { contentOffset: { get x() { @@ -72,17 +72,19 @@ export default class ScrollViewBase extends Component { this._state = { isScrolling: false }; } - _handlePreventableScrollEvent = (handler) => { - return (e) => { + _handlePreventableScrollEvent = handler => { + return e => { if (!this.props.scrollEnabled) { e.preventDefault(); } else { - if (handler) { handler(e); } + if (handler) { + handler(e); + } } }; - } + }; - _handleScroll = (e) => { + _handleScroll = e => { e.persist(); const { scrollEventThrottle } = this.props; // A scroll happened, so the scroll bumps the debounce. @@ -96,7 +98,7 @@ export default class ScrollViewBase extends Component { // Weren't scrolling, so we must have just started this._handleScrollStart(e); } - } + }; _handleScrollStart(e) { this._state.isScrolling = true; @@ -106,18 +108,22 @@ export default class ScrollViewBase extends Component { _handleScrollTick(e) { const { onScroll } = this.props; this._state.scrollLastTick = Date.now(); - if (onScroll) { onScroll(normalizeScrollEvent(e)); } + if (onScroll) { + onScroll(normalizeScrollEvent(e)); + } } _handleScrollEnd(e) { const { onScroll } = this.props; this._state.isScrolling = false; - if (onScroll) { onScroll(normalizeScrollEvent(e)); } + if (onScroll) { + onScroll(normalizeScrollEvent(e)); + } } _shouldEmitScrollEvent(lastTick, eventThrottle) { const timeSinceLastTick = Date.now() - lastTick; - return (eventThrottle > 0 && timeSinceLastTick >= eventThrottle); + return eventThrottle > 0 && timeSinceLastTick >= eventThrottle; } render() { diff --git a/src/components/ScrollView/index.js b/src/components/ScrollView/index.js index c61ec6c3..aa0de5df 100644 --- a/src/components/ScrollView/index.js +++ b/src/components/ScrollView/index.js @@ -26,7 +26,7 @@ const ScrollView = React.createClass({ ...ViewPropTypes, contentContainerStyle: StyleSheetPropType(ViewStylePropTypes), horizontal: PropTypes.bool, - keyboardDismissMode: PropTypes.oneOf([ 'none', 'interactive', 'on-drag' ]), + keyboardDismissMode: PropTypes.oneOf(['none', 'interactive', 'on-drag']), onContentSizeChange: PropTypes.func, onScroll: PropTypes.func, pagingEnabled: PropTypes.bool, @@ -36,7 +36,7 @@ const ScrollView = React.createClass({ style: StyleSheetPropType(ViewStylePropTypes) }, - mixins: [ ScrollResponder.Mixin ], + mixins: [ScrollResponder.Mixin], getInitialState() { return this.scrollResponderMixinGetInitialState(); @@ -80,12 +80,18 @@ const ScrollView = React.createClass({ animated?: boolean ) { if (typeof y === 'number') { - console.warn('`scrollTo(y, x, animated)` is deprecated. Use `scrollTo({x: 5, y: 5, animated: true})` instead.'); + console.warn( + '`scrollTo(y, x, animated)` is deprecated. Use `scrollTo({x: 5, y: 5, animated: true})` instead.' + ); } else { ({ x, y, animated } = y || emptyObject); } - this.getScrollResponder().scrollResponderScrollTo({ x: x || 0, y: y || 0, animated: animated !== false }); + this.getScrollResponder().scrollResponderScrollTo({ + x: x || 0, + y: y || 0, + animated: animated !== false + }); }, /** @@ -112,11 +118,13 @@ const ScrollView = React.createClass({ if (process.env.NODE_ENV !== 'production' && this.props.style) { const style = StyleSheet.flatten(this.props.style); - const childLayoutProps = [ 'alignItems', 'justifyContent' ].filter((prop) => style && style[prop] !== undefined); + const childLayoutProps = ['alignItems', 'justifyContent'].filter( + prop => style && style[prop] !== undefined + ); invariant( childLayoutProps.length === 0, `ScrollView child layout (${JSON.stringify(childLayoutProps)}) ` + - 'must be applied through the contentContainerStyle prop.' + 'must be applied through the contentContainerStyle prop.' ); } @@ -143,11 +151,7 @@ const ScrollView = React.createClass({ const props = { ...other, - style: [ - styles.base, - horizontal && styles.baseHorizontal, - this.props.style - ], + style: [styles.base, horizontal && styles.baseHorizontal, this.props.style], onTouchStart: this.scrollResponderHandleTouchStart, onTouchMove: this.scrollResponderHandleTouchMove, onTouchEnd: this.scrollResponderHandleTouchEnd, @@ -168,20 +172,15 @@ const ScrollView = React.createClass({ const ScrollViewClass = ScrollViewBase; - invariant( - ScrollViewClass !== undefined, - 'ScrollViewClass must not be undefined' - ); + invariant(ScrollViewClass !== undefined, 'ScrollViewClass must not be undefined'); if (refreshControl) { return React.cloneElement( refreshControl, { style: props.style }, - ( - - {contentContainer} - - ) + + {contentContainer} + ); } @@ -202,10 +201,10 @@ const ScrollView = React.createClass({ if (this.props.onScroll && !this.props.scrollEventThrottle) { console.log( 'You specified `onScroll` on a but not ' + - '`scrollEventThrottle`. You will only receive one event. ' + - 'Using `16` you get all the events but be aware that it may ' + - 'cause frame drops, use a bigger number if you don\'t need as ' + - 'much precision.' + '`scrollEventThrottle`. You will only receive one event. ' + + 'Using `16` you get all the events but be aware that it may ' + + "cause frame drops, use a bigger number if you don't need as " + + 'much precision.' ); } } @@ -239,7 +238,7 @@ const styles = StyleSheet.create({ overflowY: 'hidden' }, contentContainer: { - transform: [ { translateZ: 0 } ] + transform: [{ translateZ: 0 }] }, contentContainerHorizontal: { flexDirection: 'row' diff --git a/src/components/StaticContainer/index.js b/src/components/StaticContainer/index.js index b208a015..5752495b 100644 --- a/src/components/StaticContainer/index.js +++ b/src/components/StaticContainer/index.js @@ -35,7 +35,7 @@ class StaticContainer extends Component { render() { const child = this.props.children; - return (child === null || child === false) ? null : React.Children.only(child); + return child === null || child === false ? null : React.Children.only(child); } } diff --git a/src/components/Switch/index.js b/src/components/Switch/index.js index 0f55296f..859a36e0 100644 --- a/src/components/Switch/index.js +++ b/src/components/Switch/index.js @@ -71,12 +71,7 @@ class Switch extends Component { const thumbHeight = height; const thumbWidth = thumbHeight; - const rootStyle = [ - styles.root, - style, - { height, width }, - disabled && styles.cursorDefault - ]; + const rootStyle = [styles.root, style, { height, width }, disabled && styles.cursorDefault]; const trackStyle = [ styles.track, @@ -104,7 +99,7 @@ class Switch extends Component { onChange: this._handleChange, onFocus: this._handleFocusState, ref: this._setCheckboxRef, - style: [ styles.nativeControl, styles.cursorInherit ], + style: [styles.nativeControl, styles.cursorInherit], type: 'checkbox' }); @@ -129,21 +124,21 @@ class Switch extends Component { _handleChange = (event: Object) => { const { onValueChange } = this.props; onValueChange && onValueChange(event.nativeEvent.target.checked); - } + }; _handleFocusState = (event: Object) => { const isFocused = event.nativeEvent.type === 'focus'; const boxShadow = isFocused ? thumbFocusedBoxShadow : thumbDefaultBoxShadow; this._thumb.setNativeProps({ style: { boxShadow } }); - } + }; - _setCheckboxRef = (component) => { + _setCheckboxRef = component => { this._checkbox = component; - } + }; - _setThumbRef = (component) => { + _setThumbRef = component => { this._thumb = component; - } + }; } const styles = StyleSheet.create({ @@ -172,9 +167,7 @@ const styles = StyleSheet.create({ borderRadius: '100%', boxShadow: thumbDefaultBoxShadow, left: '0%', - transform: [ - { translateZ: 0 } - ], + transform: [{ translateZ: 0 }], transitionDuration: '0.1s' }, thumbOn: { diff --git a/src/components/Text/TextStylePropTypes.js b/src/components/Text/TextStylePropTypes.js index dae20e27..1ab6a290 100644 --- a/src/components/Text/TextStylePropTypes.js +++ b/src/components/Text/TextStylePropTypes.js @@ -3,11 +3,11 @@ import { PropTypes } from 'react'; import ViewStylePropTypes from '../View/ViewStylePropTypes'; const { number, oneOf, oneOfType, shape, string } = PropTypes; -const numberOrString = oneOfType([ number, string ]); +const numberOrString = oneOfType([number, string]); const ShadowOffsetPropType = shape({ width: number, height: number }); -const TextAlignPropType = oneOf([ 'center', 'inherit', 'justify', 'justify-all', 'left', 'right' ]); -const WritingDirectionPropType = oneOf([ 'auto', 'ltr', 'rtl' ]); +const TextAlignPropType = oneOf(['center', 'inherit', 'justify', 'justify-all', 'left', 'right']); +const WritingDirectionPropType = oneOf(['auto', 'ltr', 'rtl']); const TextOnlyStylePropTypes = { color: ColorPropType, @@ -19,7 +19,7 @@ const TextOnlyStylePropTypes = { letterSpacing: numberOrString, lineHeight: numberOrString, textAlign: TextAlignPropType, - textAlignVertical: oneOf([ 'auto', 'bottom', 'center', 'top' ]), + textAlignVertical: oneOf(['auto', 'bottom', 'center', 'top']), textDecorationLine: string, textShadowColor: ColorPropType, textShadowOffset: ShadowOffsetPropType, @@ -27,9 +27,16 @@ const TextOnlyStylePropTypes = { writingDirection: WritingDirectionPropType, /* @platform web */ textOverflow: string, - textRendering: oneOf([ 'auto', 'geometricPrecision', 'optimizeLegibility', 'optimizeSpeed' ]), - textTransform: oneOf([ 'capitalize', 'lowercase', 'none', 'uppercase' ]), - unicodeBidi: oneOf([ 'normal', 'bidi-override', 'embed', 'isolate', 'isolate-override', 'plaintext' ]), + textRendering: oneOf(['auto', 'geometricPrecision', 'optimizeLegibility', 'optimizeSpeed']), + textTransform: oneOf(['capitalize', 'lowercase', 'none', 'uppercase']), + unicodeBidi: oneOf([ + 'normal', + 'bidi-override', + 'embed', + 'isolate', + 'isolate-override', + 'plaintext' + ]), whiteSpace: string, wordWrap: string, MozOsxFontSmoothing: string, diff --git a/src/components/Text/__tests__/index-test.js b/src/components/Text/__tests__/index-test.js index f8b13c4a..2018b621 100644 --- a/src/components/Text/__tests__/index-test.js +++ b/src/components/Text/__tests__/index-test.js @@ -15,7 +15,7 @@ describe('components/Text', () => { test('prop "numberOfLines"'); test('prop "onPress"', () => { - const onPress = (e) => {}; + const onPress = e => {}; const component = renderer.create(); expect(component.toJSON()).toMatchSnapshot(); }); diff --git a/src/components/Text/index.js b/src/components/Text/index.js index ed1462c7..9e2e55ef 100644 --- a/src/components/Text/index.js +++ b/src/components/Text/index.js @@ -12,7 +12,7 @@ class Text extends Component { static propTypes = { ...BaseComponentPropTypes, - accessibilityRole: PropTypes.oneOf([ 'button', 'heading', 'link', 'listitem' ]), + accessibilityRole: PropTypes.oneOf(['button', 'heading', 'link', 'listitem']), children: PropTypes.any, numberOfLines: PropTypes.number, onLayout: PropTypes.func, @@ -63,7 +63,7 @@ class Text extends Component { } _createEnterHandler(fn) { - return (e) => { + return e => { if (e.keyCode === 13) { fn && fn(e); } diff --git a/src/components/TextInput/TextInputState.js b/src/components/TextInput/TextInputState.js index 27daab51..32ccaac4 100644 --- a/src/components/TextInput/TextInputState.js +++ b/src/components/TextInput/TextInputState.js @@ -14,7 +14,7 @@ import UIManager from '../../apis/UIManager'; * should be funneled through here */ const TextInputState = { - /** + /** * Internal state */ _currentlyFocusedNode: (null: ?Object), diff --git a/src/components/TextInput/TextInputStylePropTypes.js b/src/components/TextInput/TextInputStylePropTypes.js index 04fe0339..bafb5c9a 100644 --- a/src/components/TextInput/TextInputStylePropTypes.js +++ b/src/components/TextInput/TextInputStylePropTypes.js @@ -5,7 +5,7 @@ const { oneOf } = PropTypes; const TextInputOnlyStylePropTypes = { /* @platform web */ - resize: oneOf([ 'none', 'vertical', 'horizontal', 'both' ]) + resize: oneOf(['none', 'vertical', 'horizontal', 'both']) }; module.exports = { diff --git a/src/components/TextInput/__tests__/index-test.js b/src/components/TextInput/__tests__/index-test.js index 3e02acf5..90c2ac98 100644 --- a/src/components/TextInput/__tests__/index-test.js +++ b/src/components/TextInput/__tests__/index-test.js @@ -5,8 +5,8 @@ import TextareaAutosize from 'react-textarea-autosize'; import TextInput from '..'; import { mount, shallow } from 'enzyme'; -const findNativeInput = (wrapper) => wrapper.find('input'); -const findNativeTextarea = (wrapper) => wrapper.find(TextareaAutosize); +const findNativeInput = wrapper => wrapper.find('input'); +const findNativeTextarea = wrapper => wrapper.find(TextareaAutosize); const testIfDocumentIsFocused = (message, fn) => { if (document.hasFocus && document.hasFocus()) { @@ -22,7 +22,7 @@ describe('components/TextInput', () => { let input = findNativeInput(shallow()); expect(input.prop('autoComplete')).toEqual('on'); // off - input = findNativeInput(shallow()); + input = findNativeInput(shallow()); expect(input.prop('autoComplete')).toEqual('off'); }); @@ -66,19 +66,19 @@ describe('components/TextInput', () => { // default let input = findNativeInput(shallow()); expect(input.prop('type')).toEqual('text'); - input = findNativeInput(shallow()); + input = findNativeInput(shallow()); expect(input.prop('type')).toEqual('text'); // email-address - input = findNativeInput(shallow()); + input = findNativeInput(shallow()); expect(input.prop('type')).toEqual('email'); // numeric - input = findNativeInput(shallow()); + input = findNativeInput(shallow()); expect(input.prop('type')).toEqual('number'); // phone-pad - input = findNativeInput(shallow()); + input = findNativeInput(shallow()); expect(input.prop('type')).toEqual('tel'); // url - input = findNativeInput(shallow()); + input = findNativeInput(shallow()); expect(input.prop('type')).toEqual('url'); }); @@ -92,17 +92,15 @@ describe('components/TextInput', () => { test('prop "maxNumberOfLines"', () => { const generateValue = () => { let str = ''; - while (str.length < 100) { str += 'x'; } + while (str.length < 100) { + str += 'x'; + } return str; }; - const input = findNativeTextarea(shallow( - - )); + const input = findNativeTextarea( + shallow() + ); expect(input.prop('maxRows')).toEqual(3); }); @@ -123,16 +121,11 @@ describe('components/TextInput', () => { input = findNativeTextarea(shallow()); expect(input.length).toEqual(1); - input = findNativeTextarea(shallow( - - )); + input = findNativeTextarea(shallow()); expect(input.prop('minRows')).toEqual(3); }); - test('prop "onBlur"', (done) => { + test('prop "onBlur"', done => { const input = findNativeInput(mount()); input.simulate('blur'); function onBlur(e) { @@ -141,7 +134,7 @@ describe('components/TextInput', () => { } }); - test('prop "onChange"', (done) => { + test('prop "onChange"', done => { const input = findNativeInput(mount()); input.simulate('change'); function onChange(e) { @@ -150,7 +143,7 @@ describe('components/TextInput', () => { } }); - test('prop "onChangeText"', (done) => { + test('prop "onChangeText"', done => { const newText = 'newText'; const input = findNativeInput(mount()); input.simulate('change', { target: { value: newText } }); @@ -160,7 +153,7 @@ describe('components/TextInput', () => { } }); - test('prop "onFocus"', (done) => { + test('prop "onFocus"', done => { const input = findNativeInput(mount()); input.simulate('focus'); function onFocus(e) { @@ -169,9 +162,13 @@ describe('components/TextInput', () => { } }); - test('prop "onSelectionChange"', (done) => { - const input = findNativeInput(mount()); - input.simulate('select', { target: { selectionStart: 0, selectionEnd: 3 } }); + test('prop "onSelectionChange"', done => { + const input = findNativeInput( + mount() + ); + input.simulate('select', { + target: { selectionStart: 0, selectionEnd: 3 } + }); function onSelectionChange(e) { expect(e.nativeEvent.selection.end).toEqual(3); expect(e.nativeEvent.selection.start).toEqual(0); @@ -180,8 +177,10 @@ describe('components/TextInput', () => { }); describe('prop "onSubmitEditing"', () => { - test('single-line input', (done) => { - const input = findNativeInput(mount()); + test('single-line input', done => { + const input = findNativeInput( + mount() + ); input.simulate('keyPress', { which: 13 }); function onSubmitEditing(e) { done(); diff --git a/src/components/TextInput/index.js b/src/components/TextInput/index.js index a06641d2..d4495fad 100644 --- a/src/components/TextInput/index.js +++ b/src/components/TextInput/index.js @@ -16,7 +16,7 @@ const emptyObject = {}; /** * React Native events differ from W3C events. */ -const normalizeEventHandler = (handler) => (e) => { +const normalizeEventHandler = handler => e => { if (handler) { e.nativeEvent.text = e.target.value; return handler(e); @@ -54,7 +54,7 @@ class TextInput extends Component { static propTypes = { ...ViewPropTypes, - autoCapitalize: PropTypes.oneOf([ 'characters', 'none', 'sentences', 'words' ]), + autoCapitalize: PropTypes.oneOf(['characters', 'none', 'sentences', 'words']), autoComplete: PropTypes.string, autoCorrect: PropTypes.bool, autoFocus: PropTypes.bool, @@ -63,7 +63,14 @@ class TextInput extends Component { defaultValue: PropTypes.string, editable: PropTypes.bool, keyboardType: PropTypes.oneOf([ - 'default', 'email-address', 'number-pad', 'numeric', 'phone-pad', 'search', 'url', 'web-search' + 'default', + 'email-address', + 'number-pad', + 'numeric', + 'phone-pad', + 'search', + 'url', + 'web-search' ]), maxLength: PropTypes.number, maxNumberOfLines: PropTypes.number, @@ -201,10 +208,7 @@ class TextInput extends Component { onSelect: normalizeEventHandler(this._handleSelectionChange), readOnly: !editable, ref: this._setNode, - style: [ - styles.initial, - style - ] + style: [styles.initial, style] }); if (multiline) { @@ -217,54 +221,75 @@ class TextInput extends Component { return createDOMElement(component, otherProps); } - _handleBlur = (e) => { + _handleBlur = e => { const { onBlur } = this.props; - if (onBlur) { onBlur(e); } - } + if (onBlur) { + onBlur(e); + } + }; - _handleChange = (e) => { + _handleChange = e => { const { onChange, onChangeText } = this.props; const { text } = e.nativeEvent; - if (onChange) { onChange(e); } - if (onChangeText) { onChangeText(text); } - } + if (onChange) { + onChange(e); + } + if (onChangeText) { + onChangeText(text); + } + }; - _handleFocus = (e) => { + _handleFocus = e => { const { clearTextOnFocus, onFocus, selectTextOnFocus } = this.props; const node = this._node; - if (onFocus) { onFocus(e); } - if (clearTextOnFocus) { this.clear(); } - if (selectTextOnFocus) { node && node.select(); } - } + if (onFocus) { + onFocus(e); + } + if (clearTextOnFocus) { + this.clear(); + } + if (selectTextOnFocus) { + node && node.select(); + } + }; - _handleKeyPress = (e) => { + _handleKeyPress = e => { const { blurOnSubmit, multiline, onKeyPress, onSubmitEditing } = this.props; const blurOnSubmitDefault = !multiline; const shouldBlurOnSubmit = blurOnSubmit == null ? blurOnSubmitDefault : blurOnSubmit; - if (onKeyPress) { onKeyPress(e); } - if (!e.isDefaultPrevented() && e.which === 13) { - if (onSubmitEditing) { onSubmitEditing(e); } - if (shouldBlurOnSubmit) { this.blur(); } + if (onKeyPress) { + onKeyPress(e); } - } + if (!e.isDefaultPrevented() && e.which === 13) { + if (onSubmitEditing) { + onSubmitEditing(e); + } + if (shouldBlurOnSubmit) { + this.blur(); + } + } + }; - _handleSelectionChange = (e) => { + _handleSelectionChange = e => { const { onSelectionChange, selection = emptyObject } = this.props; if (onSelectionChange) { try { const node = e.target; if (isSelectionStale(node, selection)) { const { selectionStart, selectionEnd } = node; - e.nativeEvent.selection = { start: selectionStart, end: selectionEnd }; + e.nativeEvent.selection = { + start: selectionStart, + end: selectionEnd + }; onSelectionChange(e); } } catch (e) {} } - } + }; - _setNode = (component) => { + _setNode = component => { this._node = findNodeHandle(component); - } + }; } const styles = StyleSheet.create({ diff --git a/src/components/Touchable/BoundingDimensions.js b/src/components/Touchable/BoundingDimensions.js index 0e2f7143..24d1b8af 100644 --- a/src/components/Touchable/BoundingDimensions.js +++ b/src/components/Touchable/BoundingDimensions.js @@ -32,10 +32,7 @@ BoundingDimensions.prototype.destructor = function() { * @return {BoundingDimensions} Bounding dimensions of `element`. */ BoundingDimensions.getPooledFromElement = function(element) { - return BoundingDimensions.getPooled( - element.offsetWidth, - element.offsetHeight - ); + return BoundingDimensions.getPooled(element.offsetWidth, element.offsetHeight); }; PooledClass.addPoolingTo(BoundingDimensions, twoArgumentPooler); diff --git a/src/components/Touchable/Touchable.js b/src/components/Touchable/Touchable.js index deddede0..b93b993f 100644 --- a/src/components/Touchable/Touchable.js +++ b/src/components/Touchable/Touchable.js @@ -110,12 +110,12 @@ const View = require('../../components/View'); * Touchable states. */ var States = { - NOT_RESPONDER: 'NOT_RESPONDER', // Not the responder - RESPONDER_INACTIVE_PRESS_IN: 'RESPONDER_INACTIVE_PRESS_IN', // Responder, inactive, in the `PressRect` - RESPONDER_INACTIVE_PRESS_OUT: 'RESPONDER_INACTIVE_PRESS_OUT', // Responder, inactive, out of `PressRect` - RESPONDER_ACTIVE_PRESS_IN: 'RESPONDER_ACTIVE_PRESS_IN', // Responder, active, in the `PressRect` - RESPONDER_ACTIVE_PRESS_OUT: 'RESPONDER_ACTIVE_PRESS_OUT', // Responder, active, out of `PressRect` - RESPONDER_ACTIVE_LONG_PRESS_IN: 'RESPONDER_ACTIVE_LONG_PRESS_IN', // Responder, active, in the `PressRect`, after long press threshold + NOT_RESPONDER: 'NOT_RESPONDER', // Not the responder + RESPONDER_INACTIVE_PRESS_IN: 'RESPONDER_INACTIVE_PRESS_IN', // Responder, inactive, in the `PressRect` + RESPONDER_INACTIVE_PRESS_OUT: 'RESPONDER_INACTIVE_PRESS_OUT', // Responder, inactive, out of `PressRect` + RESPONDER_ACTIVE_PRESS_IN: 'RESPONDER_ACTIVE_PRESS_IN', // Responder, active, in the `PressRect` + RESPONDER_ACTIVE_PRESS_OUT: 'RESPONDER_ACTIVE_PRESS_OUT', // Responder, active, out of `PressRect` + RESPONDER_ACTIVE_LONG_PRESS_IN: 'RESPONDER_ACTIVE_LONG_PRESS_IN', // Responder, active, in the `PressRect`, after long press threshold RESPONDER_ACTIVE_LONG_PRESS_OUT: 'RESPONDER_ACTIVE_LONG_PRESS_OUT', // Responder, active, out of `PressRect`, after long press threshold ERROR: 'ERROR' }; @@ -135,11 +135,11 @@ var IsActive = { var IsPressingIn = { RESPONDER_INACTIVE_PRESS_IN: true, RESPONDER_ACTIVE_PRESS_IN: true, - RESPONDER_ACTIVE_LONG_PRESS_IN: true, + RESPONDER_ACTIVE_LONG_PRESS_IN: true }; var IsLongPressingIn = { - RESPONDER_ACTIVE_LONG_PRESS_IN: true, + RESPONDER_ACTIVE_LONG_PRESS_IN: true }; /** @@ -152,7 +152,7 @@ var Signals = { RESPONDER_TERMINATED: 'RESPONDER_TERMINATED', ENTER_PRESS_RECT: 'ENTER_PRESS_RECT', LEAVE_PRESS_RECT: 'LEAVE_PRESS_RECT', - LONG_PRESS_DETECTED: 'LONG_PRESS_DETECTED', + LONG_PRESS_DETECTED: 'LONG_PRESS_DETECTED' }; /** @@ -166,7 +166,7 @@ var Transitions = { RESPONDER_TERMINATED: States.ERROR, ENTER_PRESS_RECT: States.ERROR, LEAVE_PRESS_RECT: States.ERROR, - LONG_PRESS_DETECTED: States.ERROR, + LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_INACTIVE_PRESS_IN: { DELAY: States.RESPONDER_ACTIVE_PRESS_IN, @@ -175,7 +175,7 @@ var Transitions = { RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT, - LONG_PRESS_DETECTED: States.ERROR, + LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_INACTIVE_PRESS_OUT: { DELAY: States.RESPONDER_ACTIVE_PRESS_OUT, @@ -184,7 +184,7 @@ var Transitions = { RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT, - LONG_PRESS_DETECTED: States.ERROR, + LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_ACTIVE_PRESS_IN: { DELAY: States.ERROR, @@ -193,7 +193,7 @@ var Transitions = { RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT, - LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN, + LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN }, RESPONDER_ACTIVE_PRESS_OUT: { DELAY: States.ERROR, @@ -202,7 +202,7 @@ var Transitions = { RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT, - LONG_PRESS_DETECTED: States.ERROR, + LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_ACTIVE_LONG_PRESS_IN: { DELAY: States.ERROR, @@ -211,7 +211,7 @@ var Transitions = { RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT, - LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN, + LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN }, RESPONDER_ACTIVE_LONG_PRESS_OUT: { DELAY: States.ERROR, @@ -220,7 +220,7 @@ var Transitions = { RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT, - LONG_PRESS_DETECTED: States.ERROR, + LONG_PRESS_DETECTED: States.ERROR }, error: { DELAY: States.NOT_RESPONDER, @@ -229,7 +229,7 @@ var Transitions = { RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.NOT_RESPONDER, LEAVE_PRESS_RECT: States.NOT_RESPONDER, - LONG_PRESS_DETECTED: States.NOT_RESPONDER, + LONG_PRESS_DETECTED: States.NOT_RESPONDER } }; @@ -331,7 +331,7 @@ var TouchableMixin = { */ touchableGetInitialState: function() { return { - touchable: {touchState: undefined, responderID: null} + touchable: { touchState: undefined, responderID: null } }; }, @@ -353,7 +353,7 @@ var TouchableMixin = { /** * Return true to cancel press on long press. */ - touchableLongPressCancelsPress: function () { + touchableLongPressCancelsPress: function() { return true; }, @@ -375,22 +375,19 @@ var TouchableMixin = { this.state.touchable.touchState = States.NOT_RESPONDER; this.state.touchable.responderID = dispatchID; this._receiveSignal(Signals.RESPONDER_GRANT, e); - var delayMS = - this.touchableGetHighlightDelayMS !== undefined ? - Math.max(this.touchableGetHighlightDelayMS(), 0) : HIGHLIGHT_DELAY_MS; + var delayMS = this.touchableGetHighlightDelayMS !== undefined + ? Math.max(this.touchableGetHighlightDelayMS(), 0) + : HIGHLIGHT_DELAY_MS; delayMS = isNaN(delayMS) ? HIGHLIGHT_DELAY_MS : delayMS; if (delayMS !== 0) { - this.touchableDelayTimeout = setTimeout( - this._handleDelay.bind(this, e), - delayMS - ); + this.touchableDelayTimeout = setTimeout(this._handleDelay.bind(this, e), delayMS); } else { this._handleDelay(e); } - var longDelayMS = - this.touchableGetLongPressDelayMS !== undefined ? - Math.max(this.touchableGetLongPressDelayMS(), 10) : LONG_PRESS_DELAY_MS; + var longDelayMS = this.touchableGetLongPressDelayMS !== undefined + ? Math.max(this.touchableGetLongPressDelayMS(), 10) + : LONG_PRESS_DELAY_MS; longDelayMS = isNaN(longDelayMS) ? LONG_PRESS_DELAY_MS : longDelayMS; this.longPressDelayTimeout = setTimeout( this._handleLongDelay.bind(this, e), @@ -436,21 +433,21 @@ var TouchableMixin = { var positionOnActivate = this.state.touchable.positionOnActivate; var dimensionsOnActivate = this.state.touchable.dimensionsOnActivate; - var pressRectOffset = this.touchableGetPressRectOffset ? - this.touchableGetPressRectOffset() : { - left: PRESS_EXPAND_PX, - right: PRESS_EXPAND_PX, - top: PRESS_EXPAND_PX, - bottom: PRESS_EXPAND_PX - }; + var pressRectOffset = this.touchableGetPressRectOffset + ? this.touchableGetPressRectOffset() + : { + left: PRESS_EXPAND_PX, + right: PRESS_EXPAND_PX, + top: PRESS_EXPAND_PX, + bottom: PRESS_EXPAND_PX + }; var pressExpandLeft = pressRectOffset.left; var pressExpandTop = pressRectOffset.top; var pressExpandRight = pressRectOffset.right; var pressExpandBottom = pressRectOffset.bottom; - var hitSlop = this.touchableGetHitSlop ? - this.touchableGetHitSlop() : null; + var hitSlop = this.touchableGetHitSlop ? this.touchableGetHitSlop() : null; if (hitSlop) { pressExpandLeft += hitSlop.left; @@ -464,23 +461,21 @@ var TouchableMixin = { var pageY = touch && touch.pageY; if (this.pressInLocation) { - var movedDistance = this._getDistanceBetweenPoints(pageX, pageY, this.pressInLocation.pageX, this.pressInLocation.pageY); + var movedDistance = this._getDistanceBetweenPoints( + pageX, + pageY, + this.pressInLocation.pageX, + this.pressInLocation.pageY + ); if (movedDistance > LONG_PRESS_ALLOWED_MOVEMENT) { this._cancelLongPressDelayTimeout(); } } - var isTouchWithinActive = - pageX > positionOnActivate.left - pressExpandLeft && - pageY > positionOnActivate.top - pressExpandTop && - pageX < - positionOnActivate.left + - dimensionsOnActivate.width + - pressExpandRight && - pageY < - positionOnActivate.top + - dimensionsOnActivate.height + - pressExpandBottom; + var isTouchWithinActive = pageX > positionOnActivate.left - pressExpandLeft && + pageY > positionOnActivate.top - pressExpandTop && + pageX < positionOnActivate.left + dimensionsOnActivate.width + pressExpandRight && + pageY < positionOnActivate.top + dimensionsOnActivate.height + pressExpandBottom; if (isTouchWithinActive) { this._receiveSignal(Signals.ENTER_PRESS_RECT, e); var curState = this.state.touchable.touchState; @@ -556,8 +551,6 @@ var TouchableMixin = { * touchableGetPressRectOffset: function */ - - // ==== Internal Logic ==== /** @@ -598,11 +591,18 @@ var TouchableMixin = { _handleLongDelay: function(e) { this.longPressDelayTimeout = null; var curState = this.state.touchable.touchState; - if (curState !== States.RESPONDER_ACTIVE_PRESS_IN && - curState !== States.RESPONDER_ACTIVE_LONG_PRESS_IN) { - console.error('Attempted to transition from state `' + curState + '` to `' + - States.RESPONDER_ACTIVE_LONG_PRESS_IN + '`, which is not supported. This is ' + - 'most likely due to `Touchable.longPressDelayTimeout` not being cancelled.'); + if ( + curState !== States.RESPONDER_ACTIVE_PRESS_IN && + curState !== States.RESPONDER_ACTIVE_LONG_PRESS_IN + ) { + console.error( + 'Attempted to transition from state `' + + curState + + '` to `' + + States.RESPONDER_ACTIVE_LONG_PRESS_IN + + '`, which is not supported. This is ' + + 'most likely due to `Touchable.longPressDelayTimeout` not being cancelled.' + ); } else { this._receiveSignal(Signals.LONG_PRESS_DETECTED, e); } @@ -625,14 +625,24 @@ var TouchableMixin = { } if (!nextState) { throw new Error( - 'Unrecognized signal `' + signal + '` or state `' + curState + - '` for Touchable responder `' + responderID + '`' + 'Unrecognized signal `' + + signal + + '` or state `' + + curState + + '` for Touchable responder `' + + responderID + + '`' ); } if (nextState === States.ERROR) { throw new Error( - 'Touchable cannot transition from `' + curState + '` to `' + signal + - '` for responder `' + responderID + '`' + 'Touchable cannot transition from `' + + curState + + '` to `' + + signal + + '` for responder `' + + responderID + + '`' ); } if (curState !== nextState) { @@ -641,14 +651,14 @@ var TouchableMixin = { } }, - _cancelLongPressDelayTimeout: function () { + _cancelLongPressDelayTimeout: function() { this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout); this.longPressDelayTimeout = null; }, - _isHighlight: function (state) { + _isHighlight: function(state) { return state === States.RESPONDER_ACTIVE_PRESS_IN || - state === States.RESPONDER_ACTIVE_LONG_PRESS_IN; + state === States.RESPONDER_ACTIVE_LONG_PRESS_IN; }, _savePressInLocation: function(e) { @@ -657,10 +667,10 @@ var TouchableMixin = { var pageY = touch && touch.pageY; var locationX = touch && touch.locationX; var locationY = touch && touch.locationY; - this.pressInLocation = {pageX, pageY, locationX, locationY}; + this.pressInLocation = { pageX, pageY, locationX, locationY }; }, - _getDistanceBetweenPoints: function (aX, aY, bX, bY) { + _getDistanceBetweenPoints: function(aX, aY, bX, bY) { var deltaX = aX - bX; var deltaY = aY - bY; return Math.sqrt(deltaX * deltaX + deltaY * deltaY); @@ -681,8 +691,7 @@ var TouchableMixin = { var curIsHighlight = this._isHighlight(curState); var newIsHighlight = this._isHighlight(nextState); - var isFinalSignal = - signal === Signals.RESPONDER_TERMINATED || + var isFinalSignal = signal === Signals.RESPONDER_TERMINATED || signal === Signals.RESPONDER_RELEASE; if (isFinalSignal) { @@ -705,13 +714,11 @@ var TouchableMixin = { if (IsPressingIn[curState] && signal === Signals.RESPONDER_RELEASE) { var hasLongPressHandler = !!this.props.onLongPress; - var pressIsLongButStillCallOnPress = - IsLongPressingIn[curState] && ( // We *are* long pressing.. - !hasLongPressHandler || // But either has no long handler - !this.touchableLongPressCancelsPress() // or we're told to ignore it. - ); + var pressIsLongButStillCallOnPress = IsLongPressingIn[curState] && // We *are* long pressing.. + (!hasLongPressHandler || // But either has no long handler + !this.touchableLongPressCancelsPress()); // or we're told to ignore it. - var shouldInvokePress = !IsLongPressingIn[curState] || pressIsLongButStillCallOnPress; + var shouldInvokePress = !IsLongPressingIn[curState] || pressIsLongButStillCallOnPress; if (shouldInvokePress && this.touchableHandlePress) { if (!newIsHighlight && !curIsHighlight) { // we never highlighted because of delay, but we should highlight now @@ -734,15 +741,17 @@ var TouchableMixin = { _endHighlight: function(e) { if (this.touchableHandleActivePressOut) { if (this.touchableGetPressOutDelayMS && this.touchableGetPressOutDelayMS()) { - this.pressOutDelayTimeout = setTimeout(() => { - this.touchableHandleActivePressOut(e); - }, this.touchableGetPressOutDelayMS()); + this.pressOutDelayTimeout = setTimeout( + () => { + this.touchableHandleActivePressOut(e); + }, + this.touchableGetPressOutDelayMS() + ); } else { this.touchableHandleActivePressOut(e); } } - }, - + } }; var Touchable = { diff --git a/src/components/Touchable/TouchableHighlight.js b/src/components/Touchable/TouchableHighlight.js index 9bfb8ffb..1f063a50 100644 --- a/src/components/Touchable/TouchableHighlight.js +++ b/src/components/Touchable/TouchableHighlight.js @@ -36,7 +36,7 @@ var DEFAULT_PROPS = { underlayColor: 'black' }; -var PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30}; +var PRESS_RETENTION_OFFSET = { top: 20, left: 20, right: 20, bottom: 30 }; /** * A wrapper for making views respond properly to touches. @@ -86,7 +86,7 @@ var TouchableHighlight = React.createClass({ /** * Called immediately after the underlay is hidden */ - onHideUnderlay: React.PropTypes.func, + onHideUnderlay: React.PropTypes.func }, mixins: [NativeMethodsMixin, TimerMixin, Touchable.Mixin], @@ -94,28 +94,28 @@ var TouchableHighlight = React.createClass({ getDefaultProps: () => DEFAULT_PROPS, // Performance optimization to avoid constantly re-generating these objects. - computeSyntheticState: (props) => { + computeSyntheticState: props => { const { activeOpacity, style, underlayColor } = props; return { activeProps: { style: { - opacity: activeOpacity, + opacity: activeOpacity } }, activeUnderlayProps: { style: { - backgroundColor: underlayColor, + backgroundColor: underlayColor } }, - underlayStyle: [ - INACTIVE_UNDERLAY_PROPS.style, - props.style, - ] + underlayStyle: [INACTIVE_UNDERLAY_PROPS.style, props.style] }; }, getInitialState: function() { - return { ...this.touchableGetInitialState(), ...this.computeSyntheticState(this.props) } + return { + ...this.touchableGetInitialState(), + ...this.computeSyntheticState(this.props) + }; }, componentDidMount: function() { @@ -129,9 +129,11 @@ var TouchableHighlight = React.createClass({ componentWillReceiveProps: function(nextProps) { ensurePositiveDelayProps(nextProps); - if (nextProps.activeOpacity !== this.props.activeOpacity || - nextProps.underlayColor !== this.props.underlayColor || - nextProps.style !== this.props.style) { + if ( + nextProps.activeOpacity !== this.props.activeOpacity || + nextProps.underlayColor !== this.props.underlayColor || + nextProps.style !== this.props.style + ) { this.setState(this.computeSyntheticState(nextProps)); } }, @@ -162,8 +164,7 @@ var TouchableHighlight = React.createClass({ touchableHandlePress: function(e: Event) { this.clearTimeout(this._hideTimeout); this._showUnderlay(); - this._hideTimeout = this.setTimeout(this._hideUnderlay, - this.props.delayPressOut || 100); + this._hideTimeout = this.setTimeout(this._hideUnderlay, this.props.delayPressOut || 100); this.props.onPress && this.props.onPress(e); }, @@ -208,25 +209,23 @@ var TouchableHighlight = React.createClass({ this.refs[CHILD_REF].setNativeProps(INACTIVE_CHILD_PROPS); this.refs[UNDERLAY_REF].setNativeProps({ ...INACTIVE_UNDERLAY_PROPS, - style: this.state.underlayStyle, + style: this.state.underlayStyle }); this.props.onHideUnderlay && this.props.onHideUnderlay(); } }, _hasPressHandler: function() { - return !!( - this.props.onPress || + return !!(this.props.onPress || this.props.onPressIn || this.props.onPressOut || - this.props.onLongPress - ); + this.props.onLongPress); }, _onKeyEnter(e, callback) { - var ENTER = 13 + var ENTER = 13; if ((e.type === 'keypress' ? e.charCode : e.keyCode) === ENTER) { - callback && callback(e) + callback && callback(e); } }, @@ -252,9 +251,15 @@ var TouchableHighlight = React.createClass({ return ( { this._onKeyEnter(e, this.touchableHandleActivePressIn) }} - onKeyPress={(e) => { this._onKeyEnter(e, this.touchableHandlePress) }} - onKeyUp={(e) => { this._onKeyEnter(e, this.touchableHandleActivePressOut) }} + onKeyDown={e => { + this._onKeyEnter(e, this.touchableHandleActivePressIn); + }} + onKeyPress={e => { + this._onKeyEnter(e, this.touchableHandlePress); + }} + onKeyUp={e => { + this._onKeyEnter(e, this.touchableHandleActivePressOut); + }} onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder} onResponderTerminationRequest={this.touchableHandleResponderTerminationRequest} onResponderGrant={this.touchableHandleResponderGrant} @@ -262,19 +267,12 @@ var TouchableHighlight = React.createClass({ onResponderRelease={this.touchableHandleResponderRelease} onResponderTerminate={this.touchableHandleResponderTerminate} ref={UNDERLAY_REF} - style={[ - styles.root, - this.props.disabled && styles.disabled, - this.state.underlayStyle - ]} + style={[styles.root, this.props.disabled && styles.disabled, this.state.underlayStyle]} tabIndex={this.props.disabled ? null : '0'} > - {React.cloneElement( - React.Children.only(this.props.children), - { - ref: CHILD_REF, - } - )} + {React.cloneElement(React.Children.only(this.props.children), { + ref: CHILD_REF + })} ); } @@ -284,10 +282,10 @@ var CHILD_REF = 'childRef'; var UNDERLAY_REF = 'underlayRef'; var INACTIVE_CHILD_PROPS = { - style: StyleSheet.create({x: {opacity: 1.0}}).x, + style: StyleSheet.create({ x: { opacity: 1.0 } }).x }; var INACTIVE_UNDERLAY_PROPS = { - style: StyleSheet.create({x: {backgroundColor: 'transparent'}}).x, + style: StyleSheet.create({ x: { backgroundColor: 'transparent' } }).x }; var styles = StyleSheet.create({ diff --git a/src/components/Touchable/TouchableOpacity.js b/src/components/Touchable/TouchableOpacity.js index 635d3536..82fa4953 100644 --- a/src/components/Touchable/TouchableOpacity.js +++ b/src/components/Touchable/TouchableOpacity.js @@ -23,11 +23,11 @@ var TouchableWithoutFeedback = require('./TouchableWithoutFeedback'); var View = require('../View'); var ensurePositiveDelayProps = require('./ensurePositiveDelayProps'); -var flattenStyle = StyleSheet.flatten +var flattenStyle = StyleSheet.flatten; type Event = Object; -var PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30}; +var PRESS_RETENTION_OFFSET = { top: 20, left: 20, right: 20, bottom: 30 }; /** * A wrapper for making views respond properly to touches. @@ -131,8 +131,7 @@ var TouchableOpacity = React.createClass({ }, touchableGetLongPressDelayMS: function() { - return this.props.delayLongPress === 0 ? 0 : - this.props.delayLongPress || 500; + return this.props.delayLongPress === 0 ? 0 : this.props.delayLongPress || 500; }, touchableGetPressOutDelayMS: function() { @@ -145,10 +144,7 @@ var TouchableOpacity = React.createClass({ _opacityInactive: function(duration: number) { var childStyle = flattenStyle(this.props.style) || {}; - this.setOpacityTo( - childStyle.opacity === undefined ? 1 : childStyle.opacity, - duration - ); + this.setOpacityTo(childStyle.opacity === undefined ? 1 : childStyle.opacity, duration); }, _opacityFocused: function() { @@ -156,9 +152,9 @@ var TouchableOpacity = React.createClass({ }, _onKeyEnter(e, callback) { - var ENTER = 13 + var ENTER = 13; if ((e.type === 'keypress' ? e.charCode : e.keyCode) === ENTER) { - callback && callback(e) + callback && callback(e); } }, @@ -182,14 +178,16 @@ var TouchableOpacity = React.createClass({ return ( { this._onKeyEnter(e, this.touchableHandleActivePressIn) }} - onKeyPress={(e) => { this._onKeyEnter(e, this.touchableHandlePress) }} - onKeyUp={(e) => { this._onKeyEnter(e, this.touchableHandleActivePressOut) }} + style={[styles.root, this.props.disabled && styles.disabled, this.props.style]} + onKeyDown={e => { + this._onKeyEnter(e, this.touchableHandleActivePressIn); + }} + onKeyPress={e => { + this._onKeyEnter(e, this.touchableHandlePress); + }} + onKeyUp={e => { + this._onKeyEnter(e, this.touchableHandleActivePressOut); + }} onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder} onResponderTerminationRequest={this.touchableHandleResponderTerminationRequest} onResponderGrant={this.touchableHandleResponderGrant} @@ -199,7 +197,7 @@ var TouchableOpacity = React.createClass({ tabIndex={this.props.disabled ? null : '0'} /> ); - }, + } }); var styles = StyleSheet.create({ diff --git a/src/components/Touchable/TouchableWithoutFeedback.js b/src/components/Touchable/TouchableWithoutFeedback.js index 74982eb1..59509e93 100644 --- a/src/components/Touchable/TouchableWithoutFeedback.js +++ b/src/components/Touchable/TouchableWithoutFeedback.js @@ -22,7 +22,7 @@ var StyleSheet = require('../../apis/StyleSheet'); type Event = Object; -const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30}; +const PRESS_RETENTION_OFFSET = { top: 20, left: 20, right: 20, bottom: 30 }; /** * Do not use unless you have a very good reason. All the elements that @@ -88,7 +88,7 @@ const TouchableWithoutFeedback = React.createClass({ * of sibling views always takes precedence if a touch hits two overlapping * views. */ - hitSlop: EdgeInsetsPropType, + hitSlop: EdgeInsetsPropType }, getInitialState: function() { @@ -136,8 +136,7 @@ const TouchableWithoutFeedback = React.createClass({ }, touchableGetLongPressDelayMS: function(): number { - return this.props.delayLongPress === 0 ? 0 : - this.props.delayLongPress || 500; + return this.props.delayLongPress === 0 ? 0 : this.props.delayLongPress || 500; }, touchableGetPressOutDelayMS: function(): number { @@ -159,7 +158,6 @@ const TouchableWithoutFeedback = React.createClass({ ...other } = this.props; - // Note(avik): remove dynamic typecast once Flow has been upgraded const child = React.Children.only(this.props.children); let children = child.props.children; @@ -168,18 +166,9 @@ const TouchableWithoutFeedback = React.createClass({ 'TouchableWithoutFeedback does not work well with Text children. Wrap children in a View instead. See ' + ((child._owner && child._owner.getName && child._owner.getName()) || '') ); - const style = (Touchable.TOUCH_TARGET_DEBUG && child.type && child.type.displayName === 'Text') ? - [ - styles.root, - this.props.disabled && styles.disabled, - child.props.style, - {color: 'red'} - ] : - [ - styles.root, - this.props.disabled && styles.disabled, - child.props.style - ]; + const style = Touchable.TOUCH_TARGET_DEBUG && child.type && child.type.displayName === 'Text' + ? [styles.root, this.props.disabled && styles.disabled, child.props.style, { color: 'red' }] + : [styles.root, this.props.disabled && styles.disabled, child.props.style]; return (React: any).cloneElement(child, { ...other, onStartShouldSetResponder: this.touchableHandleStartShouldSetResponder, diff --git a/src/components/Touchable/ensureComponentIsNative.js b/src/components/Touchable/ensureComponentIsNative.js index f8eee4b4..c49b2d1b 100644 --- a/src/components/Touchable/ensureComponentIsNative.js +++ b/src/components/Touchable/ensureComponentIsNative.js @@ -17,8 +17,7 @@ var invariant = require('fbjs/lib/invariant'); var ensureComponentIsNative = function(component: any) { invariant( component && typeof component.setNativeProps === 'function', - 'Touchable child must either be native or forward setNativeProps to a ' + - 'native component' + 'Touchable child must either be native or forward setNativeProps to a ' + 'native component' ); }; diff --git a/src/components/Touchable/ensurePositiveDelayProps.js b/src/components/Touchable/ensurePositiveDelayProps.js index 2be15328..688d6db2 100644 --- a/src/components/Touchable/ensurePositiveDelayProps.js +++ b/src/components/Touchable/ensurePositiveDelayProps.js @@ -16,8 +16,7 @@ var invariant = require('fbjs/lib/invariant'); var ensurePositiveDelayProps = function(props: any) { invariant( - !(props.delayPressIn < 0 || props.delayPressOut < 0 || - props.delayLongPress < 0), + !(props.delayPressIn < 0 || props.delayPressOut < 0 || props.delayLongPress < 0), 'Touchable components cannot have negative delay properties' ); }; diff --git a/src/components/View/ViewPropTypes.js b/src/components/View/ViewPropTypes.js index def4227f..1ea686d3 100644 --- a/src/components/View/ViewPropTypes.js +++ b/src/components/View/ViewPropTypes.js @@ -30,7 +30,7 @@ const ViewPropTypes = { onTouchMoveCapture: PropTypes.func, onTouchStart: PropTypes.func, onTouchStartCapture: PropTypes.func, - pointerEvents: PropTypes.oneOf([ 'auto', 'box-none', 'box-only', 'none' ]), + pointerEvents: PropTypes.oneOf(['auto', 'box-none', 'box-only', 'none']), style: StyleSheetPropType(ViewStylePropTypes) }; diff --git a/src/components/View/ViewStylePropTypes.js b/src/components/View/ViewStylePropTypes.js index bc537eaf..a06d9f3d 100644 --- a/src/components/View/ViewStylePropTypes.js +++ b/src/components/View/ViewStylePropTypes.js @@ -7,8 +7,8 @@ import ShadowPropTypes from '../../propTypes/ShadowPropTypes'; import TransformPropTypes from '../../propTypes/TransformPropTypes'; const { number, oneOf, string } = PropTypes; -const autoOrHiddenOrVisible = oneOf([ 'auto', 'hidden', 'visible' ]); -const hiddenOrVisible = oneOf([ 'hidden', 'visible' ]); +const autoOrHiddenOrVisible = oneOf(['auto', 'hidden', 'visible']); +const hiddenOrVisible = oneOf(['hidden', 'visible']); module.exports = { ...AnimationPropTypes, @@ -31,7 +31,7 @@ module.exports = { backgroundAttachment: string, backgroundClip: string, backgroundImage: string, - backgroundOrigin: oneOf([ 'border-box', 'content-box', 'padding-box' ]), + backgroundOrigin: oneOf(['border-box', 'content-box', 'padding-box']), backgroundPosition: string, backgroundRepeat: string, backgroundSize: string, @@ -40,7 +40,7 @@ module.exports = { outline: string, overflowX: autoOrHiddenOrVisible, overflowY: autoOrHiddenOrVisible, - perspective: PropTypes.oneOfType([ number, string ]), + perspective: PropTypes.oneOfType([number, string]), perspectiveOrigin: string, transitionDelay: string, transitionDuration: string, @@ -49,5 +49,5 @@ module.exports = { userSelect: string, visibility: hiddenOrVisible, willChange: string, - WebkitOverflowScrolling: oneOf([ 'auto', 'touch' ]) + WebkitOverflowScrolling: oneOf(['auto', 'touch']) }; diff --git a/src/components/View/__tests__/index-test.js b/src/components/View/__tests__/index-test.js index 6fcfe97c..0eb71559 100644 --- a/src/components/View/__tests__/index-test.js +++ b/src/components/View/__tests__/index-test.js @@ -14,19 +14,19 @@ describe('components/View', () => { }); test('is a "span" when inside ', () => { - const component = renderer.create(); + const component = renderer.create(); expect(component.toJSON()).toMatchSnapshot(); }); }); test('prop "children"', () => { - const children = ; + const children = ; const component = renderer.create({children}); expect(component.toJSON()).toMatchSnapshot(); }); test('prop "pointerEvents"', () => { - const component = renderer.create(); + const component = renderer.create(); expect(component.toJSON()).toMatchSnapshot(); }); }); diff --git a/src/components/View/index.js b/src/components/View/index.js index e5028ab9..0a9c1932 100644 --- a/src/components/View/index.js +++ b/src/components/View/index.js @@ -31,13 +31,13 @@ const eventHandlerNames = [ 'onTouchStartCapture' ]; -const _normalizeEventForHandler = (handler) => (e) => { +const _normalizeEventForHandler = handler => e => { e.nativeEvent = normalizeNativeEvent(e.nativeEvent); return handler(e); }; -const normalizeEventHandlers = (props) => { - eventHandlerNames.forEach((handlerName) => { +const normalizeEventHandlers = props => { + eventHandlerNames.forEach(handlerName => { const handler = props[handlerName]; if (typeof handler === 'function') { props[handlerName] = _normalizeEventForHandler(handler); @@ -90,11 +90,7 @@ class View extends Component { // DOM events need to be normalized to expect RN format normalizeEventHandlers(otherProps); - otherProps.style = [ - styles.initial, - style, - pointerEvents && pointerEventStyles[pointerEvents] - ]; + otherProps.style = [styles.initial, style, pointerEvents && pointerEventStyles[pointerEvents]]; return createDOMElement(component, otherProps); } @@ -128,7 +124,7 @@ const styles = StyleSheet.create({ }); const pointerEventStyles = StyleSheet.create({ - 'auto': { + auto: { pointerEvents: 'auto' }, 'box-none': { @@ -137,7 +133,7 @@ const pointerEventStyles = StyleSheet.create({ 'box-only': { pointerEvents: 'box-only' }, - 'none': { + none: { pointerEvents: 'none' } }); diff --git a/src/modules/NativeMethodsMixin/index.js b/src/modules/NativeMethodsMixin/index.js index 4a6abda2..152bcd7b 100644 --- a/src/modules/NativeMethodsMixin/index.js +++ b/src/modules/NativeMethodsMixin/index.js @@ -68,7 +68,7 @@ const NativeMethodsMixin = { setNativeProps(nativeProps: Object) { // DOM state const node = findNodeHandle(this); - const classList = [ ...node.classList ]; + const classList = [...node.classList]; const { className, style } = StyleRegistry.resolveStateful(nativeProps.style, classList); const props = { ...nativeProps, className, style }; diff --git a/src/modules/ReactNativePropRegistry/index.js b/src/modules/ReactNativePropRegistry/index.js index 9dca6690..8a294ca4 100644 --- a/src/modules/ReactNativePropRegistry/index.js +++ b/src/modules/ReactNativePropRegistry/index.js @@ -17,7 +17,7 @@ const objects = {}; const prefix = 'r'; let uniqueID = 1; -const createKey = (id) => `${prefix}-${id}`; +const createKey = id => `${prefix}-${id}`; class ReactNativePropRegistry { static register(object: Object): number { diff --git a/src/modules/ScrollResponder/index.js b/src/modules/ScrollResponder/index.js index 8ff42b39..1997f072 100644 --- a/src/modules/ScrollResponder/index.js +++ b/src/modules/ScrollResponder/index.js @@ -110,11 +110,11 @@ const emptyObject = {}; var IS_ANIMATING_TOUCH_START_THRESHOLD_MS = 16; type State = { - isTouching: boolean; - lastMomentumScrollBeginTime: number; - lastMomentumScrollEndTime: number; - observedScrollSinceBecomingResponder: boolean; - becameResponderWhileAnimating: boolean; + isTouching: boolean, + lastMomentumScrollBeginTime: number, + lastMomentumScrollEndTime: number, + observedScrollSinceBecomingResponder: boolean, + becameResponderWhileAnimating: boolean }; type Event = Object; @@ -132,7 +132,7 @@ var ScrollResponderMixin = { // - Determine if releasing should dismiss the keyboard when we are in // tap-to-dismiss mode (!this.props.keyboardShouldPersistTaps). observedScrollSinceBecomingResponder: false, - becameResponderWhileAnimating: false, + becameResponderWhileAnimating: false }; }, @@ -247,11 +247,13 @@ var ScrollResponderMixin = { // By default scroll views will unfocus a textField // if another touch occurs outside of it var currentlyFocusedTextInput = TextInputState.currentlyFocusedField(); - if (!this.props.keyboardShouldPersistTaps && + if ( + !this.props.keyboardShouldPersistTaps && currentlyFocusedTextInput != null && - e.target !== currentlyFocusedTextInput && + e.target !== currentlyFocusedTextInput && !this.state.observedScrollSinceBecomingResponder && - !this.state.becameResponderWhileAnimating) { + !this.state.becameResponderWhileAnimating + ) { this.props.onScrollResponderKeyboardDismissed && this.props.onScrollResponderKeyboardDismissed(e); TextInputState.blurTextInput(currentlyFocusedTextInput); @@ -356,9 +358,7 @@ var ScrollResponderMixin = { * function otherwise `this` is used. */ scrollResponderGetScrollableNode: function(): any { - return this.getScrollableNode ? - this.getScrollableNode() : - findNodeHandle(this); + return this.getScrollableNode ? this.getScrollableNode() : findNodeHandle(this); }, /** @@ -373,26 +373,30 @@ var ScrollResponderMixin = { * This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED. */ scrollResponderScrollTo: function( - x?: number | { x?: number; y?: number; animated?: boolean }, + x?: number | { x?: number, y?: number, animated?: boolean }, y?: number, animated?: boolean ) { if (typeof x === 'number') { - console.warn('`scrollResponderScrollTo(x, y, animated)` is deprecated. Use `scrollResponderScrollTo({x: 5, y: 5, animated: true})` instead.'); + console.warn( + '`scrollResponderScrollTo(x, y, animated)` is deprecated. Use `scrollResponderScrollTo({x: 5, y: 5, animated: true})` instead.' + ); } else { - ({x, y, animated} = x || emptyObject); + ({ x, y, animated } = x || emptyObject); } - const node = this.scrollResponderGetScrollableNode() - node.scrollLeft = x || 0 - node.scrollTop = y || 0 + const node = this.scrollResponderGetScrollableNode(); + node.scrollLeft = x || 0; + node.scrollTop = y || 0; }, /** * Deprecated, do not use. */ scrollResponderScrollWithoutAnimationTo: function(offsetX: number, offsetY: number) { - console.warn('`scrollResponderScrollWithoutAnimationTo` is deprecated. Use `scrollResponderScrollTo` instead'); - this.scrollResponderScrollTo({x: offsetX, y: offsetY, animated: false}); + console.warn( + '`scrollResponderScrollWithoutAnimationTo` is deprecated. Use `scrollResponderScrollTo` instead' + ); + this.scrollResponderScrollTo({ x: offsetX, y: offsetY, animated: false }); }, /** @@ -402,7 +406,13 @@ var ScrollResponderMixin = { * @platform ios */ scrollResponderZoomTo: function( - rect: { x: number; y: number; width: number; height: number; animated?: boolean }, + rect: { + x: number, + y: number, + width: number, + height: number, + animated?: boolean + }, animated?: boolean // deprecated, put this inside the rect argument instead ) { if (Platform.OS !== 'ios') { @@ -420,7 +430,11 @@ var ScrollResponderMixin = { * @param {bool} preventNegativeScrolling Whether to allow pulling the content * down to make it meet the keyboard's top. Default is false. */ - scrollResponderScrollNativeHandleToKeyboard: function(nodeHandle: any, additionalOffset?: number, preventNegativeScrollOffset?: bool) { + scrollResponderScrollNativeHandleToKeyboard: function( + nodeHandle: any, + additionalOffset?: number, + preventNegativeScrollOffset?: boolean + ) { this.additionalScrollOffset = additionalOffset || 0; this.preventNegativeScrollOffset = !!preventNegativeScrollOffset; UIManager.measureLayout( @@ -441,7 +455,12 @@ var ScrollResponderMixin = { * @param {number} width Width of the text input. * @param {number} height Height of the text input. */ - scrollResponderInputMeasureAndScrollToKeyboard: function(left: number, top: number, width: number, height: number) { + scrollResponderInputMeasureAndScrollToKeyboard: function( + left: number, + top: number, + width: number, + height: number + ) { var keyboardScreenY = Dimensions.get('window').height; if (this.keyboardWillOpenTo) { keyboardScreenY = this.keyboardWillOpenTo.endCoordinates.screenY; @@ -455,7 +474,7 @@ var ScrollResponderMixin = { if (this.preventNegativeScrollOffset) { scrollOffsetY = Math.max(0, scrollOffsetY); } - this.scrollResponderScrollTo({x: 0, y: scrollOffsetY, animated: true}); + this.scrollResponderScrollTo({ x: 0, y: scrollOffsetY, animated: true }); this.additionalOffset = 0; this.preventNegativeScrollOffset = false; @@ -534,7 +553,7 @@ var ScrollResponderMixin = { }; var ScrollResponder = { - Mixin: ScrollResponderMixin, + Mixin: ScrollResponderMixin }; module.exports = ScrollResponder; diff --git a/src/modules/applyLayout/index.js b/src/modules/applyLayout/index.js index 79ecd0c7..92e2b51f 100644 --- a/src/modules/applyLayout/index.js +++ b/src/modules/applyLayout/index.js @@ -9,28 +9,30 @@ import emptyFunction from 'fbjs/lib/emptyFunction'; const emptyObject = {}; -const applyLayout = (Component) => { +const applyLayout = Component => { const componentDidMount = Component.prototype.componentDidMount || emptyFunction; const componentDidUpdate = Component.prototype.componentDidUpdate || emptyFunction; - Component.prototype.componentDidMount = function () { + Component.prototype.componentDidMount = function() { componentDidMount.call(this); this._layoutState = emptyObject; this._handleLayout(); }; - Component.prototype.componentDidUpdate = function () { + Component.prototype.componentDidUpdate = function() { componentDidUpdate.call(this); this._handleLayout(); }; - Component.prototype._handleLayout = function () { + Component.prototype._handleLayout = function() { const layout = this._layoutState; const { onLayout } = this.props; if (onLayout) { this.measure((x, y, width, height) => { - if (layout.x !== x || layout.y !== y || layout.width !== width || layout.height !== height) { + if ( + layout.x !== x || layout.y !== y || layout.width !== width || layout.height !== height + ) { const nextLayout = { x, y, width, height }; const nativeEvent = { layout: nextLayout }; onLayout({ nativeEvent, timeStamp: Date.now() }); diff --git a/src/modules/applyNativeMethods/index.js b/src/modules/applyNativeMethods/index.js index 1d001130..6d13de63 100644 --- a/src/modules/applyNativeMethods/index.js +++ b/src/modules/applyNativeMethods/index.js @@ -7,8 +7,8 @@ import NativeMethodsMixin from '../NativeMethodsMixin'; -const applyNativeMethods = (Component) => { - Object.keys(NativeMethodsMixin).forEach((method) => { +const applyNativeMethods = Component => { + Object.keys(NativeMethodsMixin).forEach(method => { if (!Component.prototype[method]) { Component.prototype[method] = NativeMethodsMixin[method]; } diff --git a/src/modules/createDOMElement/__tests__/index-test.js b/src/modules/createDOMElement/__tests__/index-test.js index 1e58b2bb..594298d3 100644 --- a/src/modules/createDOMElement/__tests__/index-test.js +++ b/src/modules/createDOMElement/__tests__/index-test.js @@ -35,7 +35,12 @@ describe('modules/createDOMElement', () => { }); test('link and target="_blank"', () => { - const component = renderer.create(createDOMElement('span', { accessibilityRole: 'link', target: '_blank' })); + const component = renderer.create( + createDOMElement('span', { + accessibilityRole: 'link', + target: '_blank' + }) + ); expect(component.toJSON()).toMatchSnapshot(); }); }); diff --git a/src/modules/createDOMElement/index.js b/src/modules/createDOMElement/index.js index e8567ebf..17661418 100644 --- a/src/modules/createDOMElement/index.js +++ b/src/modules/createDOMElement/index.js @@ -36,10 +36,18 @@ const createDOMElement = (component, rnProps) => { const { className, style } = StyleRegistry.resolve(rnStyle) || emptyObject; - if (!accessible) { domProps['aria-hidden'] = true; } - if (accessibilityLabel) { domProps['aria-label'] = accessibilityLabel; } - if (accessibilityLiveRegion) { domProps['aria-live'] = accessibilityLiveRegion; } - if (testID) { domProps['data-testid'] = testID; } + if (!accessible) { + domProps['aria-hidden'] = true; + } + if (accessibilityLabel) { + domProps['aria-label'] = accessibilityLabel; + } + if (accessibilityLiveRegion) { + domProps['aria-live'] = accessibilityLiveRegion; + } + if (testID) { + domProps['data-testid'] = testID; + } if (accessibilityRole) { domProps.role = accessibilityRole; if (accessibilityRole === 'button') { @@ -58,9 +66,7 @@ const createDOMElement = (component, rnProps) => { domProps.type = type; } - return ( - - ); + return ; }; module.exports = createDOMElement; diff --git a/src/modules/injectResponderEventPlugin.js b/src/modules/injectResponderEventPlugin.js index 4d9739b7..3a80e9ea 100644 --- a/src/modules/injectResponderEventPlugin.js +++ b/src/modules/injectResponderEventPlugin.js @@ -15,9 +15,9 @@ const topTouchEnd = 'topTouchEnd'; const topTouchMove = 'topTouchMove'; const topTouchStart = 'topTouchStart'; -const endDependencies = [ topTouchCancel, topTouchEnd, topMouseUp ]; -const moveDependencies = [ topTouchMove, topMouseMove ]; -const startDependencies = [ topTouchStart, topMouseDown ]; +const endDependencies = [topTouchCancel, topTouchEnd, topMouseUp]; +const moveDependencies = [topTouchMove, topMouseMove]; +const startDependencies = [topTouchStart, topMouseDown]; /** * Setup ResponderEventPlugin dependencies @@ -31,15 +31,17 @@ ResponderEventPlugin.eventTypes.responderGrant.dependencies = []; ResponderEventPlugin.eventTypes.responderReject.dependencies = []; ResponderEventPlugin.eventTypes.responderTerminate.dependencies = []; ResponderEventPlugin.eventTypes.moveShouldSetResponder.dependencies = moveDependencies; -ResponderEventPlugin.eventTypes.selectionChangeShouldSetResponder.dependencies = [ topSelectionChange ]; -ResponderEventPlugin.eventTypes.scrollShouldSetResponder.dependencies = [ topScroll ]; +ResponderEventPlugin.eventTypes.selectionChangeShouldSetResponder.dependencies = [ + topSelectionChange +]; +ResponderEventPlugin.eventTypes.scrollShouldSetResponder.dependencies = [topScroll]; ResponderEventPlugin.eventTypes.startShouldSetResponder.dependencies = startDependencies; const originalRecordTouchTrack = ResponderTouchHistoryStore.recordTouchTrack; ResponderTouchHistoryStore.recordTouchTrack = (topLevelType, nativeEvent) => { // Filter out mouse-move events when the mouse button is not down - if ((topLevelType === topMouseMove) && !ResponderTouchHistoryStore.touchHistory.touchBank.length) { + if (topLevelType === topMouseMove && !ResponderTouchHistoryStore.touchHistory.touchBank.length) { return; } diff --git a/src/modules/modality/index.js b/src/modules/modality/index.js index bc906b55..e7f9a10d 100644 --- a/src/modules/modality/index.js +++ b/src/modules/modality/index.js @@ -20,7 +20,10 @@ const modality = () => { * Determine whether the keyboard is required when an element is focused */ const proto = window.Element.prototype; - const matcher = proto.matches || proto.mozMatchesSelector || proto.msMatchesSelector || proto.webkitMatchesSelector; + const matcher = proto.matches || + proto.mozMatchesSelector || + proto.msMatchesSelector || + proto.webkitMatchesSelector; const keyboardModalityWhitelist = [ 'input:not([type])', 'input[type=text]', @@ -34,7 +37,7 @@ const modality = () => { '[supports-modality=keyboard]' ].join(','); - const focusTriggersKeyboardModality = (el) => { + const focusTriggersKeyboardModality = el => { if (matcher) { return matcher.call(el, keyboardModalityWhitelist) && matcher.call(el, ':not([readonly])'); } else { @@ -72,29 +75,44 @@ const modality = () => { let hadKeyboardEvent = false; // track when the keyboard is in use - document.body.addEventListener('keydown', () => { - hadKeyboardEvent = true; - if (keyboardTimer) { - clearTimeout(keyboardTimer); - } - keyboardTimer = setTimeout(() => { - hadKeyboardEvent = false; - }, 100); - }, true); + document.body.addEventListener( + 'keydown', + () => { + hadKeyboardEvent = true; + if (keyboardTimer) { + clearTimeout(keyboardTimer); + } + keyboardTimer = setTimeout( + () => { + hadKeyboardEvent = false; + }, + 100 + ); + }, + true + ); // disable focus style reset when the keyboard is in use - document.body.addEventListener('focus', (e) => { - if (hadKeyboardEvent || focusTriggersKeyboardModality(e.target)) { - enableFocus(); - } - }, true); + document.body.addEventListener( + 'focus', + e => { + if (hadKeyboardEvent || focusTriggersKeyboardModality(e.target)) { + enableFocus(); + } + }, + true + ); // enable focus style reset when keyboard is no longer in use - document.body.addEventListener('blur', () => { - if (!hadKeyboardEvent) { - disableFocus(); - } - }, true); + document.body.addEventListener( + 'blur', + () => { + if (!hadKeyboardEvent) { + disableFocus(); + } + }, + true + ); }; export default modality; diff --git a/src/modules/multiplyStyleLengthValue/index.js b/src/modules/multiplyStyleLengthValue/index.js index f44c068a..b5a3d46b 100644 --- a/src/modules/multiplyStyleLengthValue/index.js +++ b/src/modules/multiplyStyleLengthValue/index.js @@ -1,8 +1,8 @@ const CSS_UNIT_RE = /^[+-]?\d*(?:\.\d+)?(?:[Ee][+-]?\d+)?(%|\w*)/; -const getUnit = (str) => str.match(CSS_UNIT_RE)[1]; +const getUnit = str => str.match(CSS_UNIT_RE)[1]; -const isNumeric = (n) => { +const isNumeric = n => { return !isNaN(parseFloat(n)) && isFinite(n); }; diff --git a/src/modules/normalizeNativeEvent.js b/src/modules/normalizeNativeEvent.js index d70490b1..daa10c3c 100644 --- a/src/modules/normalizeNativeEvent.js +++ b/src/modules/normalizeNativeEvent.js @@ -1,34 +1,35 @@ const emptyArray = []; // Mobile Safari re-uses touch objects, so we copy the properties we want and normalize the identifier -const normalizeTouches = (touches = emptyArray) => Array.prototype.slice.call(touches).map((touch) => { - const identifier = touch.identifier > 20 ? (touch.identifier % 20) : touch.identifier; +const normalizeTouches = (touches = emptyArray) => + Array.prototype.slice.call(touches).map(touch => { + const identifier = touch.identifier > 20 ? touch.identifier % 20 : touch.identifier; - const rect = touch.target && touch.target.getBoundingClientRect(); - const locationX = touch.pageX - rect.left; - const locationY = touch.pageY - rect.top; + const rect = touch.target && touch.target.getBoundingClientRect(); + const locationX = touch.pageX - rect.left; + const locationY = touch.pageY - rect.top; - return { - _normalized: true, - clientX: touch.clientX, - clientY: touch.clientY, - force: touch.force, - locationX: locationX, - locationY: locationY, - identifier: identifier, - pageX: touch.pageX, - pageY: touch.pageY, - radiusX: touch.radiusX, - radiusY: touch.radiusY, - rotationAngle: touch.rotationAngle, - screenX: touch.screenX, - screenY: touch.screenY, - target: touch.target, - // normalize the timestamp - // https://stackoverflow.com/questions/26177087/ios-8-mobile-safari-wrong-timestamp-on-touch-events - timestamp: Date.now() - }; -}); + return { + _normalized: true, + clientX: touch.clientX, + clientY: touch.clientY, + force: touch.force, + locationX: locationX, + locationY: locationY, + identifier: identifier, + pageX: touch.pageX, + pageY: touch.pageY, + radiusX: touch.radiusX, + radiusY: touch.radiusY, + rotationAngle: touch.rotationAngle, + screenX: touch.screenX, + screenY: touch.screenY, + target: touch.target, + // normalize the timestamp + // https://stackoverflow.com/questions/26177087/ios-8-mobile-safari-wrong-timestamp-on-touch-events + timestamp: Date.now() + }; + }); function normalizeTouchEvent(nativeEvent) { const changedTouches = normalizeTouches(nativeEvent.changedTouches); @@ -91,12 +92,14 @@ function normalizeMouseEvent(nativeEvent) { stopPropagation: nativeEvent.stopPropagation.bind(nativeEvent), target: nativeEvent.target, timestamp: touches[0].timestamp, - touches: (nativeEvent.type === 'mouseup') ? emptyArray : touches + touches: nativeEvent.type === 'mouseup' ? emptyArray : touches }; } function normalizeNativeEvent(nativeEvent) { - if (nativeEvent._normalized) { return nativeEvent; } + if (nativeEvent._normalized) { + return nativeEvent; + } const eventType = nativeEvent.type || ''; const mouse = eventType.indexOf('mouse') >= 0; return mouse ? normalizeMouseEvent(nativeEvent) : normalizeTouchEvent(nativeEvent); diff --git a/src/modules/requestIdleCallback/index.js b/src/modules/requestIdleCallback/index.js index 03f0c64b..4bb7a79a 100644 --- a/src/modules/requestIdleCallback/index.js +++ b/src/modules/requestIdleCallback/index.js @@ -1,19 +1,22 @@ /* global window */ import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; -const _requestIdleCallback = function (cb) { - return setTimeout(() => { - const start = Date.now(); - cb({ - didTimeout: false, - timeRemaining() { - return Math.max(0, 50 - (Date.now() - start)); - } - }); - }, 1); +const _requestIdleCallback = function(cb) { + return setTimeout( + () => { + const start = Date.now(); + cb({ + didTimeout: false, + timeRemaining() { + return Math.max(0, 50 - (Date.now() - start)); + } + }); + }, + 1 + ); }; -const _cancelIdleCallback = function (id) { +const _cancelIdleCallback = function(id) { clearTimeout(id); }; diff --git a/src/propTypes/AnimationPropTypes.js b/src/propTypes/AnimationPropTypes.js index d9dc30ab..3818d069 100644 --- a/src/propTypes/AnimationPropTypes.js +++ b/src/propTypes/AnimationPropTypes.js @@ -4,12 +4,12 @@ const { number, oneOf, oneOfType, string } = PropTypes; const AnimationPropTypes = { animationDelay: string, - animationDirection: oneOf([ 'alternate', 'alternate-reverse', 'normal', 'reverse' ]), + animationDirection: oneOf(['alternate', 'alternate-reverse', 'normal', 'reverse']), animationDuration: string, - animationFillMode: oneOf([ 'none', 'forwards', 'backwards', 'both' ]), - animationIterationCount: oneOfType([ number, oneOf([ 'infinite' ]) ]), + animationFillMode: oneOf(['none', 'forwards', 'backwards', 'both']), + animationIterationCount: oneOfType([number, oneOf(['infinite'])]), animationName: string, - animationPlayState: oneOf([ 'paused', 'running' ]), + animationPlayState: oneOf(['paused', 'running']), animationTimingFunction: string }; diff --git a/src/propTypes/BaseComponentPropTypes.js b/src/propTypes/BaseComponentPropTypes.js index 48e83033..24035628 100644 --- a/src/propTypes/BaseComponentPropTypes.js +++ b/src/propTypes/BaseComponentPropTypes.js @@ -3,10 +3,10 @@ const { array, bool, number, object, oneOf, oneOfType, string } = PropTypes; const BaseComponentPropTypes = { accessibilityLabel: string, - accessibilityLiveRegion: oneOf([ 'assertive', 'off', 'polite' ]), + accessibilityLiveRegion: oneOf(['assertive', 'off', 'polite']), accessibilityRole: string, accessible: bool, - style: oneOfType([ array, number, object ]), + style: oneOfType([array, number, object]), testID: string }; diff --git a/src/propTypes/BorderPropTypes.js b/src/propTypes/BorderPropTypes.js index 997dff9e..cc18be5f 100644 --- a/src/propTypes/BorderPropTypes.js +++ b/src/propTypes/BorderPropTypes.js @@ -1,8 +1,8 @@ import ColorPropType from './ColorPropType'; import { PropTypes } from 'react'; -const numberOrString = PropTypes.oneOfType([ PropTypes.number, PropTypes.string ]); -const BorderStylePropType = PropTypes.oneOf([ 'solid', 'dotted', 'dashed' ]); +const numberOrString = PropTypes.oneOfType([PropTypes.number, PropTypes.string]); +const BorderStylePropType = PropTypes.oneOf(['solid', 'dotted', 'dashed']); const BorderPropTypes = { borderColor: ColorPropType, diff --git a/src/propTypes/ColorPropType.js b/src/propTypes/ColorPropType.js index ccacacb5..49bc2ced 100644 --- a/src/propTypes/ColorPropType.js +++ b/src/propTypes/ColorPropType.js @@ -1,5 +1,5 @@ /* eslint-disable */ - /** +/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * @@ -10,7 +10,7 @@ * @providesModule ColorPropType */ -import { PropTypes } from 'react' +import { PropTypes } from 'react'; var colorPropType = function(isRequired, props, propName, componentName, location, propFullName) { var normalizeColor = require('normalize-css-color'); @@ -20,8 +20,13 @@ var colorPropType = function(isRequired, props, propName, componentName, locatio if (isRequired) { var locationName = ReactPropTypeLocationNames[location]; return new Error( - 'Required ' + locationName + ' `' + (propFullName || propName) + - '` was not specified in `' + componentName + '`.' + 'Required ' + + locationName + + ' `' + + (propFullName || propName) + + '` was not specified in `' + + componentName + + '`.' ); } return; @@ -41,9 +46,16 @@ var colorPropType = function(isRequired, props, propName, componentName, locatio if (normalizeColor(color) === null) { var locationName = ReactPropTypeLocationNames[location]; return new Error( - 'Invalid ' + locationName + ' `' + (propFullName || propName) + - '` supplied to `' + componentName + '`: ' + color + '\n' + -`Valid color formats are + 'Invalid ' + + locationName + + ' `' + + (propFullName || propName) + + '` supplied to `' + + componentName + + '`: ' + + color + + '\n' + + `Valid color formats are - '#f0f' (#rgb) - '#f0fc' (#rgba) - '#ff00ff' (#rrggbb) @@ -55,7 +67,8 @@ var colorPropType = function(isRequired, props, propName, componentName, locatio - 'transparent' - 'red' - 0xff00ff00 (0xrrggbbaa) -`); +` + ); } }; @@ -63,7 +76,7 @@ if (process.env.NODE_ENV !== 'production') { var ColorPropType = colorPropType.bind(null, false /* isRequired */); ColorPropType.isRequired = colorPropType.bind(null, true /* isRequired */); } else { - var ColorPropType = function () {} + var ColorPropType = function() {}; } -module.exports = ColorPropType +module.exports = ColorPropType; diff --git a/src/propTypes/EdgeInsetsPropType.js b/src/propTypes/EdgeInsetsPropType.js index 8c016637..e84905ed 100644 --- a/src/propTypes/EdgeInsetsPropType.js +++ b/src/propTypes/EdgeInsetsPropType.js @@ -18,7 +18,7 @@ var EdgeInsetsPropType = require('./createStrictShapeTypeChecker')({ top: PropTypes.number, left: PropTypes.number, bottom: PropTypes.number, - right: PropTypes.number, + right: PropTypes.number }); module.exports = EdgeInsetsPropType; diff --git a/src/propTypes/LayoutPropTypes.js b/src/propTypes/LayoutPropTypes.js index 16ff00b2..6c965d4e 100644 --- a/src/propTypes/LayoutPropTypes.js +++ b/src/propTypes/LayoutPropTypes.js @@ -1,7 +1,7 @@ import { PropTypes } from 'react'; const { number, oneOf, oneOfType, string } = PropTypes; -const numberOrString = oneOfType([ number, string ]); +const numberOrString = oneOfType([number, string]); const LayoutPropTypes = { // box model @@ -33,21 +33,28 @@ const LayoutPropTypes = { paddingVertical: numberOrString, width: numberOrString, // flexbox - alignContent: oneOf([ 'center', 'flex-end', 'flex-start', 'space-around', 'space-between', 'stretch' ]), - alignItems: oneOf([ 'baseline', 'center', 'flex-end', 'flex-start', 'stretch' ]), - alignSelf: oneOf([ 'auto', 'baseline', 'center', 'flex-end', 'flex-start', 'stretch' ]), + alignContent: oneOf([ + 'center', + 'flex-end', + 'flex-start', + 'space-around', + 'space-between', + 'stretch' + ]), + alignItems: oneOf(['baseline', 'center', 'flex-end', 'flex-start', 'stretch']), + alignSelf: oneOf(['auto', 'baseline', 'center', 'flex-end', 'flex-start', 'stretch']), flex: number, flexBasis: numberOrString, - flexDirection: oneOf([ 'column', 'column-reverse', 'row', 'row-reverse' ]), + flexDirection: oneOf(['column', 'column-reverse', 'row', 'row-reverse']), flexGrow: number, flexShrink: number, - flexWrap: oneOf([ 'nowrap', 'wrap', 'wrap-reverse' ]), - justifyContent: oneOf([ 'center', 'flex-end', 'flex-start', 'space-around', 'space-between' ]), + flexWrap: oneOf(['nowrap', 'wrap', 'wrap-reverse']), + justifyContent: oneOf(['center', 'flex-end', 'flex-start', 'space-around', 'space-between']), order: number, // position bottom: numberOrString, left: numberOrString, - position: oneOf([ 'absolute', 'fixed', 'relative', 'static' ]), + position: oneOf(['absolute', 'fixed', 'relative', 'static']), right: numberOrString, top: numberOrString }; diff --git a/src/propTypes/PointPropType.js b/src/propTypes/PointPropType.js index f7b2ef8c..56f939a5 100644 --- a/src/propTypes/PointPropType.js +++ b/src/propTypes/PointPropType.js @@ -16,7 +16,7 @@ var PropTypes = require('react').PropTypes; var PointPropType = require('./createStrictShapeTypeChecker')({ x: PropTypes.number, - y: PropTypes.number, + y: PropTypes.number }); module.exports = PointPropType; diff --git a/src/propTypes/ShadowPropTypes.js b/src/propTypes/ShadowPropTypes.js index 80b4dd1e..4b2c9237 100644 --- a/src/propTypes/ShadowPropTypes.js +++ b/src/propTypes/ShadowPropTypes.js @@ -2,7 +2,7 @@ import ColorPropType from './ColorPropType'; import { PropTypes } from 'react'; const { number, oneOfType, shape, string } = PropTypes; -const numberOrString = oneOfType([ number, string ]); +const numberOrString = oneOfType([number, string]); const ShadowPropTypes = { shadowColor: ColorPropType, diff --git a/src/propTypes/StyleSheetPropType.js b/src/propTypes/StyleSheetPropType.js index ad6f11f1..1d4e8eba 100644 --- a/src/propTypes/StyleSheetPropType.js +++ b/src/propTypes/StyleSheetPropType.js @@ -10,7 +10,7 @@ module.exports = function StyleSheetPropType(shape) { const StyleSheet = require('../apis/StyleSheet'); const shapePropType = createStrictShapeTypeChecker(shape); - return function (props, propName, componentName, location?) { + return function(props, propName, componentName, location?) { let newProps = props; if (props[propName]) { // Just make a dummy prop object with only the flattened style diff --git a/src/propTypes/TransformPropTypes.js b/src/propTypes/TransformPropTypes.js index c7a325f2..8ec93c57 100644 --- a/src/propTypes/TransformPropTypes.js +++ b/src/propTypes/TransformPropTypes.js @@ -8,7 +8,7 @@ import { PropTypes } from 'react'; const { arrayOf, number, oneOfType, shape, string } = PropTypes; -const numberOrString = oneOfType([ number, string ]); +const numberOrString = oneOfType([number, string]); const TransformPropTypes = { transform: arrayOf( diff --git a/src/propTypes/createStrictShapeTypeChecker.js b/src/propTypes/createStrictShapeTypeChecker.js index 8b878c3c..1c9ee81e 100644 --- a/src/propTypes/createStrictShapeTypeChecker.js +++ b/src/propTypes/createStrictShapeTypeChecker.js @@ -11,28 +11,26 @@ * @flow */ -import invariant from 'fbjs/lib/invariant' -import ReactPropTypeLocationNames from 'react-dom/lib/ReactPropTypeLocationNames' -import ReactPropTypesSecret from 'react-dom/lib/ReactPropTypesSecret' +import invariant from 'fbjs/lib/invariant'; +import ReactPropTypeLocationNames from 'react-dom/lib/ReactPropTypeLocationNames'; +import ReactPropTypesSecret from 'react-dom/lib/ReactPropTypesSecret'; function createStrictShapeTypeChecker( - shapeTypes: {[key: string]: ReactPropsCheckType} + shapeTypes: { [key: string]: ReactPropsCheckType } ): ReactPropsChainableTypeChecker { function checkType(isRequired, props, propName, componentName, location?) { if (!props[propName]) { if (isRequired) { invariant( false, - `Required object \`${propName}\` was not specified in ` + - `\`${componentName}\`.` + `Required object \`${propName}\` was not specified in ` + `\`${componentName}\`.` ); } return; } var propValue = props[propName]; var propType = typeof propValue; - var locationName = - location && ReactPropTypeLocationNames[location] || '(unknown)'; + var locationName = (location && ReactPropTypeLocationNames[location]) || '(unknown)'; if (propType !== 'object') { invariant( false, @@ -49,22 +47,23 @@ function createStrictShapeTypeChecker( invariant( false, `Invalid props.${propName} key \`${key}\` supplied to \`${componentName}\`.` + - `\nBad object: ` + JSON.stringify(props[propName], null, ' ') + - `\nValid keys: ` + JSON.stringify(Object.keys(shapeTypes), null, ' ') + `\nBad object: ` + + JSON.stringify(props[propName], null, ' ') + + `\nValid keys: ` + + JSON.stringify(Object.keys(shapeTypes), null, ' ') ); } var error = checker(propValue, key, componentName, location, null, ReactPropTypesSecret); if (error) { invariant( false, - error.message + - `\nBad object: ` + JSON.stringify(props[propName], null, ' ') + error.message + `\nBad object: ` + JSON.stringify(props[propName], null, ' ') ); } } } function chainedCheckType( - props: {[key: string]: any}, + props: { [key: string]: any }, propName: string, componentName: string, location?: string