initial commit taken from gitlab.lrz.de

This commit is contained in:
privatereese
2018-08-24 18:09:42 +02:00
parent ae54ed4c48
commit fc05486403
28494 changed files with 2159823 additions and 0 deletions

View File

@@ -0,0 +1,74 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule AccessibilityInfo
* @flow
*/
'use strict';
const NativeModules = require('NativeModules');
const RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
const RCTAccessibilityInfo = NativeModules.AccessibilityInfo;
const TOUCH_EXPLORATION_EVENT = 'touchExplorationDidChange';
type ChangeEventName = $Enum<{
change: string,
}>;
const _subscriptions = new Map();
/**
* Sometimes it's useful to know whether or not the device has a screen reader
* that is currently active. The `AccessibilityInfo` API is designed for this
* purpose. You can use it to query the current state of the screen reader as
* well as to register to be notified when the state of the screen reader
* changes.
*
* See http://facebook.github.io/react-native/docs/accessibilityinfo.html
*/
const AccessibilityInfo = {
fetch: function(): Promise {
return new Promise((resolve, reject) => {
RCTAccessibilityInfo.isTouchExplorationEnabled(
function(resp) {
resolve(resp);
}
);
});
},
addEventListener: function (
eventName: ChangeEventName,
handler: Function
): void {
const listener = RCTDeviceEventEmitter.addListener(
TOUCH_EXPLORATION_EVENT,
(enabled) => {
handler(enabled);
}
);
_subscriptions.set(handler, listener);
},
removeEventListener: function(
eventName: ChangeEventName,
handler: Function
): void {
const listener = _subscriptions.get(handler);
if (!listener) {
return;
}
listener.remove();
_subscriptions.delete(handler);
},
};
module.exports = AccessibilityInfo;

View File

@@ -0,0 +1,140 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule AccessibilityInfo
* @flow
*/
'use strict';
const NativeModules = require('NativeModules');
const Promise = require('Promise');
const RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
const AccessibilityManager = NativeModules.AccessibilityManager;
const VOICE_OVER_EVENT = 'voiceOverDidChange';
const ANNOUNCEMENT_DID_FINISH_EVENT = 'announcementDidFinish';
type ChangeEventName = $Enum<{
change: string,
announcementFinished: string
}>;
const _subscriptions = new Map();
/**
* Sometimes it's useful to know whether or not the device has a screen reader
* that is currently active. The `AccessibilityInfo` API is designed for this
* purpose. You can use it to query the current state of the screen reader as
* well as to register to be notified when the state of the screen reader
* changes.
*
* See http://facebook.github.io/react-native/docs/accessibilityinfo.html
*/
const AccessibilityInfo = {
/**
* Query whether a screen reader is currently enabled.
*
* Returns a promise which resolves to a boolean.
* The result is `true` when a screen reader is enabledand `false` otherwise.
*
* See http://facebook.github.io/react-native/docs/accessibilityinfo.html#fetch
*/
fetch: function(): Promise {
return new Promise((resolve, reject) => {
AccessibilityManager.getCurrentVoiceOverState(
resolve,
reject
);
});
},
/**
* Add an event handler. Supported events:
*
* - `change`: Fires when the state of the screen reader changes. The argument
* to the event handler is a boolean. The boolean is `true` when a screen
* reader is enabled and `false` otherwise.
* - `announcementFinished`: iOS-only event. Fires when the screen reader has
* finished making an announcement. The argument to the event handler is a
* dictionary with these keys:
* - `announcement`: The string announced by the screen reader.
* - `success`: A boolean indicating whether the announcement was
* successfully made.
*
* See http://facebook.github.io/react-native/docs/accessibilityinfo.html#addeventlistener
*/
addEventListener: function (
eventName: ChangeEventName,
handler: Function
): Object {
let listener;
if (eventName === 'change') {
listener = RCTDeviceEventEmitter.addListener(
VOICE_OVER_EVENT,
handler
);
} else if (eventName === 'announcementFinished') {
listener = RCTDeviceEventEmitter.addListener(
ANNOUNCEMENT_DID_FINISH_EVENT,
handler
);
}
_subscriptions.set(handler, listener);
return {
remove: AccessibilityInfo.removeEventListener.bind(null, eventName, handler),
};
},
/**
* Set accessibility focus to a react component.
*
* @platform ios
*
* See http://facebook.github.io/react-native/docs/accessibilityinfo.html#setaccessibilityfocus
*/
setAccessibilityFocus: function(
reactTag: number
): void {
AccessibilityManager.setAccessibilityFocus(reactTag);
},
/**
* Post a string to be announced by the screen reader.
*
* @platform ios
*
* See http://facebook.github.io/react-native/docs/accessibilityinfo.html#announceforaccessibility
*/
announceForAccessibility: function(
announcement: string
): void {
AccessibilityManager.announceForAccessibility(announcement);
},
/**
* Remove an event handler.
*
* See http://facebook.github.io/react-native/docs/accessibilityinfo.html#removeeventlistener
*/
removeEventListener: function(
eventName: ChangeEventName,
handler: Function
): void {
const listener = _subscriptions.get(handler);
if (!listener) {
return;
}
listener.remove();
_subscriptions.delete(handler);
},
};
module.exports = AccessibilityInfo;

View File

@@ -0,0 +1,147 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ActivityIndicator
* @flow
*/
'use strict';
const ColorPropType = require('ColorPropType');
const NativeMethodsMixin = require('NativeMethodsMixin');
const Platform = require('Platform');
const ProgressBarAndroid = require('ProgressBarAndroid');
const PropTypes = require('prop-types');
const React = require('React');
const StyleSheet = require('StyleSheet');
const View = require('View');
const ViewPropTypes = require('ViewPropTypes');
const createReactClass = require('create-react-class');
const requireNativeComponent = require('requireNativeComponent');
let RCTActivityIndicator;
const GRAY = '#999999';
type IndicatorSize = number | 'small' | 'large';
type DefaultProps = {
animating: boolean,
color: any,
hidesWhenStopped: boolean,
size: IndicatorSize,
}
/**
* Displays a circular loading indicator.
*
* See http://facebook.github.io/react-native/docs/activityindicator.html
*/
const ActivityIndicator = createReactClass({
displayName: 'ActivityIndicator',
mixins: [NativeMethodsMixin],
propTypes: {
...ViewPropTypes,
/**
* Whether to show the indicator (true, the default) or hide it (false).
*
* See http://facebook.github.io/react-native/docs/activityindicator.html#animating
*/
animating: PropTypes.bool,
/**
* The foreground color of the spinner (default is gray).
*
* See http://facebook.github.io/react-native/docs/activityindicator.html#color
*/
color: ColorPropType,
/**
* Size of the indicator (default is 'small').
* Passing a number to the size prop is only supported on Android.
*
* See http://facebook.github.io/react-native/docs/activityindicator.html#size
*/
size: PropTypes.oneOfType([
PropTypes.oneOf([ 'small', 'large' ]),
PropTypes.number,
]),
/**
* Whether the indicator should hide when not animating (true by default).
*
* @platform ios
*
* See http://facebook.github.io/react-native/docs/activityindicator.html#hideswhenstopped
*/
hidesWhenStopped: PropTypes.bool,
},
getDefaultProps(): DefaultProps {
return {
animating: true,
color: Platform.OS === 'ios' ? GRAY : undefined,
hidesWhenStopped: true,
size: 'small',
};
},
render() {
const {onLayout, style, ...props} = this.props;
let sizeStyle;
switch (props.size) {
case 'small':
sizeStyle = styles.sizeSmall;
break;
case 'large':
sizeStyle = styles.sizeLarge;
break;
default:
sizeStyle = {height: props.size, width: props.size};
break;
}
const nativeProps = {
...props,
style: sizeStyle,
styleAttr: 'Normal',
indeterminate: true,
};
return (
<View onLayout={onLayout} style={[styles.container, style]}>
{Platform.OS === 'ios' ? (
<RCTActivityIndicator {...nativeProps} />
) : (
<ProgressBarAndroid {...nativeProps} />
)}
</View>
);
}
});
if (Platform.OS === 'ios') {
RCTActivityIndicator = requireNativeComponent(
'RCTActivityIndicatorView',
ActivityIndicator,
{ nativeOnly: { activityIndicatorViewStyle: true } }
);
}
const styles = StyleSheet.create({
container: {
alignItems: 'center',
justifyContent: 'center',
},
sizeSmall: {
width: 20,
height: 20,
},
sizeLarge: {
width: 36,
height: 36,
},
});
module.exports = ActivityIndicator;

View File

@@ -0,0 +1,47 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule TVEventHandler
* @flow
*/
'use strict';
const Platform = require('Platform');
const TVNavigationEventEmitter = require('NativeModules').TVNavigationEventEmitter;
const NativeEventEmitter = require('NativeEventEmitter');
function TVEventHandler() {
this.__nativeTVNavigationEventListener = null;
this.__nativeTVNavigationEventEmitter = null;
}
TVEventHandler.prototype.enable = function(component: ?any, callback: Function) {
if (Platform.OS === 'ios' && !TVNavigationEventEmitter) {
return;
}
this.__nativeTVNavigationEventEmitter = new NativeEventEmitter(TVNavigationEventEmitter);
this.__nativeTVNavigationEventListener = this.__nativeTVNavigationEventEmitter.addListener(
'onHWKeyEvent',
(data) => {
if (callback) {
callback(component, data);
}
}
);
};
TVEventHandler.prototype.disable = function() {
if (this.__nativeTVNavigationEventListener) {
this.__nativeTVNavigationEventListener.remove();
delete this.__nativeTVNavigationEventListener;
}
if (this.__nativeTVNavigationEventEmitter) {
delete this.__nativeTVNavigationEventEmitter;
}
};
module.exports = TVEventHandler;

View File

@@ -0,0 +1,84 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule TVViewPropTypes
* @flow
*/
'use strict';
const PropTypes = require('prop-types');
/**
* Additional View properties for Apple TV
*/
const TVViewPropTypes = {
/**
* When set to true, this view will be focusable
* and navigable using the TV remote.
*/
isTVSelectable: PropTypes.bool,
/**
* May be set to true to force the TV focus engine to move focus to this view.
*/
hasTVPreferredFocus: PropTypes.bool,
/**
* *(Apple TV only)* Object with properties to control Apple TV parallax effects.
*
* enabled: If true, parallax effects are enabled. Defaults to true.
* shiftDistanceX: Defaults to 2.0.
* shiftDistanceY: Defaults to 2.0.
* tiltAngle: Defaults to 0.05.
* magnification: Defaults to 1.0.
* pressMagnification: Defaults to 1.0.
* pressDuration: Defaults to 0.3.
* pressDelay: Defaults to 0.0.
*
* @platform ios
*/
tvParallaxProperties: PropTypes.object,
/**
* *(Apple TV only)* May be used to change the appearance of the Apple TV parallax effect when this view goes in or out of focus. Defaults to 2.0.
*
* @platform ios
*/
tvParallaxShiftDistanceX: PropTypes.number,
/**
* *(Apple TV only)* May be used to change the appearance of the Apple TV parallax effect when this view goes in or out of focus. Defaults to 2.0.
*
* @platform ios
*/
tvParallaxShiftDistanceY: PropTypes.number,
/**
* *(Apple TV only)* May be used to change the appearance of the Apple TV parallax effect when this view goes in or out of focus. Defaults to 0.05.
*
* @platform ios
*/
tvParallaxTiltAngle: PropTypes.number,
/**
* *(Apple TV only)* May be used to change the appearance of the Apple TV parallax effect when this view goes in or out of focus. Defaults to 1.0.
*
* @platform ios
*/
tvParallaxMagnification: PropTypes.number,
};
export type TVViewProps = {
isTVSelectable?: bool,
hasTVPreferredFocus?: bool,
tvParallaxProperties?: Object,
tvParallaxShiftDistanceX?: number,
tvParallaxShiftDistanceY?: number,
tvParallaxTiltAngle?: number,
tvParallaxMagnification?: number,
};
module.exports = TVViewPropTypes;

View File

@@ -0,0 +1,183 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule Button
* @flow
*/
'use strict';
const ColorPropType = require('ColorPropType');
const Platform = require('Platform');
const React = require('React');
const PropTypes = require('prop-types');
const StyleSheet = require('StyleSheet');
const Text = require('Text');
const TouchableNativeFeedback = require('TouchableNativeFeedback');
const TouchableOpacity = require('TouchableOpacity');
const View = require('View');
const invariant = require('fbjs/lib/invariant');
/**
* A basic button component that should render nicely on any platform. Supports
* a minimal level of customization.
*
* <center><img src="img/buttonExample.png"></img></center>
*
* If this button doesn't look right for your app, you can build your own
* button using [TouchableOpacity](docs/touchableopacity.html)
* or [TouchableNativeFeedback](docs/touchablenativefeedback.html).
* For inspiration, look at the [source code for this button component](https://github.com/facebook/react-native/blob/master/Libraries/Components/Button.js).
* Or, take a look at the [wide variety of button components built by the community](https://js.coach/react-native?search=button).
*
* Example usage:
*
* ```
* import { Button } from 'react-native';
* ...
*
* <Button
* onPress={onPressLearnMore}
* title="Learn More"
* color="#841584"
* accessibilityLabel="Learn more about this purple button"
* />
* ```
*
*/
class Button extends React.Component<{
title: string,
onPress: () => any,
color?: ?string,
hasTVPreferredFocus?: ?boolean,
accessibilityLabel?: ?string,
disabled?: ?boolean,
testID?: ?string,
hasTVPreferredFocus?: ?boolean,
}> {
static propTypes = {
/**
* Text to display inside the button
*/
title: PropTypes.string.isRequired,
/**
* Text to display for blindness accessibility features
*/
accessibilityLabel: PropTypes.string,
/**
* Color of the text (iOS), or background color of the button (Android)
*/
color: ColorPropType,
/**
* If true, disable all interactions for this component.
*/
disabled: PropTypes.bool,
/**
* TV preferred focus (see documentation for the View component).
*/
hasTVPreferredFocus: PropTypes.bool,
/**
* Handler to be called when the user taps the button
*/
onPress: PropTypes.func.isRequired,
/**
* Used to locate this view in end-to-end tests.
*/
testID: PropTypes.string,
};
render() {
const {
accessibilityLabel,
color,
onPress,
title,
hasTVPreferredFocus,
disabled,
testID,
} = this.props;
const buttonStyles = [styles.button];
const textStyles = [styles.text];
if (color) {
if (Platform.OS === 'ios') {
textStyles.push({color: color});
} else {
buttonStyles.push({backgroundColor: color});
}
}
const accessibilityTraits = ['button'];
if (disabled) {
buttonStyles.push(styles.buttonDisabled);
textStyles.push(styles.textDisabled);
accessibilityTraits.push('disabled');
}
invariant(
typeof title === 'string',
'The title prop of a Button must be a string',
);
const formattedTitle = Platform.OS === 'android' ? title.toUpperCase() : title;
const Touchable = Platform.OS === 'android' ? TouchableNativeFeedback : TouchableOpacity;
return (
<Touchable
accessibilityComponentType="button"
accessibilityLabel={accessibilityLabel}
accessibilityTraits={accessibilityTraits}
hasTVPreferredFocus={hasTVPreferredFocus}
testID={testID}
disabled={disabled}
onPress={onPress}>
<View style={buttonStyles}>
<Text style={textStyles} disabled={disabled}>{formattedTitle}</Text>
</View>
</Touchable>
);
}
}
const styles = StyleSheet.create({
button: Platform.select({
ios: {},
android: {
elevation: 4,
// Material design blue from https://material.google.com/style/color.html#color-color-palette
backgroundColor: '#2196F3',
borderRadius: 2,
},
}),
text: Platform.select({
ios: {
// iOS blue from https://developer.apple.com/ios/human-interface-guidelines/visual-design/color/
color: '#007AFF',
textAlign: 'center',
padding: 8,
fontSize: 18,
},
android: {
color: 'white',
textAlign: 'center',
padding: 8,
fontWeight: '500',
},
}),
buttonDisabled: Platform.select({
ios: {},
android: {
elevation: 0,
backgroundColor: '#dfdfdf',
}
}),
textDisabled: Platform.select({
ios: {
color: '#cdcdcd',
},
android: {
color: '#a1a1a1',
}
}),
});
module.exports = Button;

View File

@@ -0,0 +1,167 @@
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule CheckBox
* @flow
* @format
*/
'use strict';
const NativeMethodsMixin = require('NativeMethodsMixin');
const PropTypes = require('prop-types');
const React = require('React');
const StyleSheet = require('StyleSheet');
const ViewPropTypes = require('ViewPropTypes');
const createReactClass = require('create-react-class');
const requireNativeComponent = require('requireNativeComponent');
type DefaultProps = {
value: boolean,
disabled: boolean,
};
/**
* Renders a boolean input (Android only).
*
* This is a controlled component that requires an `onValueChange` callback that
* updates the `value` prop in order for the component to reflect user actions.
* If the `value` prop is not updated, the component will continue to render
* the supplied `value` prop instead of the expected result of any user actions.
*
* ```
* import React from 'react';
* import { AppRegistry, StyleSheet, Text, View, CheckBox } from 'react-native';
*
* export default class App extends React.Component {
* constructor(props) {
* super(props);
* this.state = {
* checked: false
* }
* }
*
* toggle() {
* this.setState(({checked}) => {
* return {
* checked: !checked
* };
* });
* }
*
* render() {
* const {checked} = this.state;
* return (
* <View style={styles.container}>
* <Text>Checked</Text>
* <CheckBox value={checked} onChange={this.toggle.bind(this)} />
* </View>
* );
* }
* }
*
* const styles = StyleSheet.create({
* container: {
* flex: 1,
* flexDirection: 'row',
* alignItems: 'center',
* justifyContent: 'center',
* },
* });
*
* // skip this line if using Create React Native App
* AppRegistry.registerComponent('App', () => App);
* ```
*
* @keyword checkbox
* @keyword toggle
*/
let CheckBox = createReactClass({
displayName: 'CheckBox',
propTypes: {
...ViewPropTypes,
/**
* The value of the checkbox. If true the checkbox will be turned on.
* Default value is false.
*/
value: PropTypes.bool,
/**
* If true the user won't be able to toggle the checkbox.
* Default value is false.
*/
disabled: PropTypes.bool,
/**
* Used in case the props change removes the component.
*/
onChange: PropTypes.func,
/**
* Invoked with the new value when the value changes.
*/
onValueChange: PropTypes.func,
/**
* Used to locate this view in end-to-end tests.
*/
testID: PropTypes.string,
},
getDefaultProps: function(): DefaultProps {
return {
value: false,
disabled: false,
};
},
mixins: [NativeMethodsMixin],
_rctCheckBox: {},
_onChange: function(event: Object) {
this._rctCheckBox.setNativeProps({value: this.props.value});
// Change the props after the native props are set in case the props
// change removes the component
this.props.onChange && this.props.onChange(event);
this.props.onValueChange &&
this.props.onValueChange(event.nativeEvent.value);
},
render: function() {
let props = {...this.props};
props.onStartShouldSetResponder = () => true;
props.onResponderTerminationRequest = () => false;
props.enabled = !this.props.disabled;
props.on = this.props.value;
props.style = [styles.rctCheckBox, this.props.style];
return (
<RCTCheckBox
{...props}
ref={ref => {
/* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This
* comment suppresses an error when upgrading Flow's support for
* React. To see the error delete this comment and run Flow. */
this._rctCheckBox = ref;
}}
onChange={this._onChange}
/>
);
},
});
let styles = StyleSheet.create({
rctCheckBox: {
height: 32,
width: 32,
},
});
let RCTCheckBox = requireNativeComponent('AndroidCheckBox', CheckBox, {
nativeOnly: {
onChange: true,
on: true,
enabled: true,
},
});
module.exports = CheckBox;

View File

@@ -0,0 +1,13 @@
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule CheckBox
* @flow
* @format
*/
'use strict';
module.exports = require('UnimplementedView');

View File

@@ -0,0 +1,41 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule Clipboard
* @flow
*/
'use strict';
const Clipboard = require('NativeModules').Clipboard;
/**
* `Clipboard` gives you an interface for setting and getting content from Clipboard on both iOS and Android
*/
module.exports = {
/**
* Get content of string type, this method returns a `Promise`, so you can use following code to get clipboard content
* ```javascript
* async _getContent() {
* var content = await Clipboard.getString();
* }
* ```
*/
getString(): Promise<string> {
return Clipboard.getString();
},
/**
* Set content of string type. You can use following code to set clipboard content
* ```javascript
* _setContent() {
* Clipboard.setString('hello world');
* }
* ```
* @param the content to be stored in the clipboard.
*/
setString(content: string) {
Clipboard.setString(content);
}
};

View File

@@ -0,0 +1,44 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule DatePickerIOS
*/
'use strict';
const React = require('React');
const StyleSheet = require('StyleSheet');
const Text = require('Text');
const View = require('View');
class DummyDatePickerIOS extends React.Component {
render() {
return (
<View style={[styles.dummyDatePickerIOS, this.props.style]}>
<Text style={styles.datePickerText}>DatePickerIOS is not supported on this platform!</Text>
</View>
);
}
}
const styles = StyleSheet.create({
dummyDatePickerIOS: {
height: 100,
width: 300,
backgroundColor: '#ffbcbc',
borderWidth: 1,
borderColor: 'red',
alignItems: 'center',
justifyContent: 'center',
margin: 10,
},
datePickerText: {
color: '#333333',
margin: 20,
}
});
module.exports = DummyDatePickerIOS;

View File

@@ -0,0 +1,185 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule DatePickerIOS
* @flow
*
* This is a controlled component version of RCTDatePickerIOS
*/
'use strict';
const NativeMethodsMixin = require('NativeMethodsMixin');
const React = require('React');
const invariant = require('fbjs/lib/invariant');
const PropTypes = require('prop-types');
const StyleSheet = require('StyleSheet');
const View = require('View');
const ViewPropTypes = require('ViewPropTypes');
const createReactClass = require('create-react-class');
const requireNativeComponent = require('requireNativeComponent');
type DefaultProps = {
mode: 'date' | 'time' | 'datetime',
};
type Event = Object;
/**
* Use `DatePickerIOS` to render a date/time picker (selector) on iOS. This is
* a controlled component, so you must hook in to the `onDateChange` callback
* and update the `date` prop in order for the component to update, otherwise
* the user's change will be reverted immediately to reflect `props.date` as the
* source of truth.
*/
const DatePickerIOS = createReactClass({
displayName: 'DatePickerIOS',
// TOOD: Put a better type for _picker
_picker: (undefined: ?$FlowFixMe),
mixins: [NativeMethodsMixin],
propTypes: {
...ViewPropTypes,
/**
* The currently selected date.
*/
date: PropTypes.instanceOf(Date),
/**
* Provides an initial value that will change when the user starts selecting
* a date. It is useful for simple use-cases where you do not want to deal
* with listening to events and updating the date prop to keep the
* controlled state in sync. The controlled state has known bugs which
* causes it to go out of sync with native. The initialDate prop is intended
* to allow you to have native be source of truth.
*/
initialDate: PropTypes.instanceOf(Date),
/**
* Date change handler.
*
* This is called when the user changes the date or time in the UI.
* The first and only argument is a Date object representing the new
* date and time.
*/
onDateChange: PropTypes.func.isRequired,
/**
* Maximum date.
*
* Restricts the range of possible date/time values.
*/
maximumDate: PropTypes.instanceOf(Date),
/**
* Minimum date.
*
* Restricts the range of possible date/time values.
*/
minimumDate: PropTypes.instanceOf(Date),
/**
* The date picker mode.
*/
mode: PropTypes.oneOf(['date', 'time', 'datetime']),
/**
* The date picker locale.
*/
locale: PropTypes.string,
/**
* The interval at which minutes can be selected.
*/
minuteInterval: PropTypes.oneOf([1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30]),
/**
* Timezone offset in minutes.
*
* By default, the date picker will use the device's timezone. With this
* parameter, it is possible to force a certain timezone offset. For
* instance, to show times in Pacific Standard Time, pass -7 * 60.
*/
timeZoneOffsetInMinutes: PropTypes.number,
},
getDefaultProps: function(): DefaultProps {
return {
mode: 'datetime',
};
},
componentDidUpdate: function() {
if (this.props.date) {
const propsTimeStamp = this.props.date.getTime();
if (this._picker) {
this._picker.setNativeProps({
date: propsTimeStamp,
});
}
}
},
_onChange: function(event: Event) {
const nativeTimeStamp = event.nativeEvent.timestamp;
this.props.onDateChange && this.props.onDateChange(
new Date(nativeTimeStamp)
);
// $FlowFixMe(>=0.41.0)
this.props.onChange && this.props.onChange(event);
},
render: function() {
const props = this.props;
invariant(
props.date || props.initialDate,
'A selected date or initial date should be specified.',
);
return (
<View style={props.style}>
<RCTDatePickerIOS
ref={ picker => { this._picker = picker; } }
style={styles.datePickerIOS}
date={props.date ? props.date.getTime() : props.initialDate ? props.initialDate.getTime() : undefined}
locale={props.locale ? props.locale : undefined}
maximumDate={
props.maximumDate ? props.maximumDate.getTime() : undefined
}
minimumDate={
props.minimumDate ? props.minimumDate.getTime() : undefined
}
mode={props.mode}
minuteInterval={props.minuteInterval}
timeZoneOffsetInMinutes={props.timeZoneOffsetInMinutes}
onChange={this._onChange}
onStartShouldSetResponder={() => true}
onResponderTerminationRequest={() => false}
/>
</View>
);
}
});
const styles = StyleSheet.create({
datePickerIOS: {
height: 216,
},
});
const RCTDatePickerIOS = requireNativeComponent('RCTDatePicker', {
propTypes: {
...DatePickerIOS.propTypes,
date: PropTypes.number,
locale: PropTypes.string,
minimumDate: PropTypes.number,
maximumDate: PropTypes.number,
onDateChange: () => null,
onChange: PropTypes.func,
}
});
module.exports = DatePickerIOS;

View File

@@ -0,0 +1,87 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule DatePickerAndroid
* @flow
*/
'use strict';
const DatePickerModule = require('NativeModules').DatePickerAndroid;
/**
* Convert a Date to a timestamp.
*/
function _toMillis(options: Object, key: string) {
const dateVal = options[key];
// Is it a Date object?
if (typeof dateVal === 'object' && typeof dateVal.getMonth === 'function') {
options[key] = dateVal.getTime();
}
}
/**
* Opens the standard Android date picker dialog.
*
* ### Example
*
* ```
* try {
* const {action, year, month, day} = await DatePickerAndroid.open({
* // Use `new Date()` for current date.
* // May 25 2020. Month 0 is January.
* date: new Date(2020, 4, 25)
* });
* if (action !== DatePickerAndroid.dismissedAction) {
* // Selected year, month (0-11), day
* }
* } catch ({code, message}) {
* console.warn('Cannot open date picker', message);
* }
* ```
*/
class DatePickerAndroid {
/**
* Opens the standard Android date picker dialog.
*
* The available keys for the `options` object are:
*
* - `date` (`Date` object or timestamp in milliseconds) - date to show by default
* - `minDate` (`Date` or timestamp in milliseconds) - minimum date that can be selected
* - `maxDate` (`Date` object or timestamp in milliseconds) - maximum date that can be selected
* - `mode` (`enum('calendar', 'spinner', 'default')`) - To set the date-picker mode to calendar/spinner/default
* - 'calendar': Show a date picker in calendar mode.
* - 'spinner': Show a date picker in spinner mode.
* - 'default': Show a default native date picker(spinner/calendar) based on android versions.
*
* Returns a Promise which will be invoked an object containing `action`, `year`, `month` (0-11),
* `day` if the user picked a date. If the user dismissed the dialog, the Promise will
* still be resolved with action being `DatePickerAndroid.dismissedAction` and all the other keys
* being undefined. **Always** check whether the `action` before reading the values.
*
* Note the native date picker dialog has some UI glitches on Android 4 and lower
* when using the `minDate` and `maxDate` options.
*/
static async open(options: Object): Promise<Object> {
const optionsMs = options;
if (optionsMs) {
_toMillis(options, 'date');
_toMillis(options, 'minDate');
_toMillis(options, 'maxDate');
}
return DatePickerModule.open(options);
}
/**
* A date has been selected.
*/
static get dateSetAction() { return 'dateSetAction'; }
/**
* The dialog has been dismissed.
*/
static get dismissedAction() { return 'dismissedAction'; }
}
module.exports = DatePickerAndroid;

View File

@@ -0,0 +1,20 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule DatePickerAndroid
* @flow
*/
'use strict';
const DatePickerAndroid = {
async open(options: Object): Promise<Object> {
return Promise.reject({
message: 'DatePickerAndroid is not supported on this platform.'
});
},
};
module.exports = DatePickerAndroid;

View File

@@ -0,0 +1,318 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule DrawerLayoutAndroid
*/
'use strict';
const ColorPropType = require('ColorPropType');
const NativeMethodsMixin = require('NativeMethodsMixin');
const Platform = require('Platform');
const React = require('React');
const PropTypes = require('prop-types');
const ReactNative = require('ReactNative');
const StatusBar = require('StatusBar');
const StyleSheet = require('StyleSheet');
const UIManager = require('UIManager');
const View = require('View');
const ViewPropTypes = require('ViewPropTypes');
const DrawerConsts = UIManager.AndroidDrawerLayout.Constants;
const createReactClass = require('create-react-class');
const dismissKeyboard = require('dismissKeyboard');
const requireNativeComponent = require('requireNativeComponent');
const RK_DRAWER_REF = 'drawerlayout';
const INNERVIEW_REF = 'innerView';
const DRAWER_STATES = [
'Idle',
'Dragging',
'Settling',
];
/**
* React component that wraps the platform `DrawerLayout` (Android only). The
* Drawer (typically used for navigation) is rendered with `renderNavigationView`
* and direct children are the main view (where your content goes). The navigation
* view is initially not visible on the screen, but can be pulled in from the
* side of the window specified by the `drawerPosition` prop and its width can
* be set by the `drawerWidth` prop.
*
* Example:
*
* ```
* render: function() {
* var navigationView = (
* <View style={{flex: 1, backgroundColor: '#fff'}}>
* <Text style={{margin: 10, fontSize: 15, textAlign: 'left'}}>I'm in the Drawer!</Text>
* </View>
* );
* return (
* <DrawerLayoutAndroid
* drawerWidth={300}
* drawerPosition={DrawerLayoutAndroid.positions.Left}
* renderNavigationView={() => navigationView}>
* <View style={{flex: 1, alignItems: 'center'}}>
* <Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>Hello</Text>
* <Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>World!</Text>
* </View>
* </DrawerLayoutAndroid>
* );
* },
* ```
*/
const DrawerLayoutAndroid = createReactClass({
displayName: 'DrawerLayoutAndroid',
statics: {
positions: DrawerConsts.DrawerPosition,
},
propTypes: {
...ViewPropTypes,
/**
* Determines whether the keyboard gets dismissed in response to a drag.
* - 'none' (the default), drags do not dismiss the keyboard.
* - 'on-drag', the keyboard is dismissed when a drag begins.
*/
keyboardDismissMode: PropTypes.oneOf([
'none', // default
'on-drag',
]),
/**
* Specifies the background color of the drawer. The default value is white.
* If you want to set the opacity of the drawer, use rgba. Example:
*
* ```
* return (
* <DrawerLayoutAndroid drawerBackgroundColor="rgba(0,0,0,0.5)">
* </DrawerLayoutAndroid>
* );
* ```
*/
drawerBackgroundColor: ColorPropType,
/**
* Specifies the side of the screen from which the drawer will slide in.
*/
drawerPosition: PropTypes.oneOf([
DrawerConsts.DrawerPosition.Left,
DrawerConsts.DrawerPosition.Right
]),
/**
* Specifies the width of the drawer, more precisely the width of the view that be pulled in
* from the edge of the window.
*/
drawerWidth: PropTypes.number,
/**
* Specifies the lock mode of the drawer. The drawer can be locked in 3 states:
* - unlocked (default), meaning that the drawer will respond (open/close) to touch gestures.
* - locked-closed, meaning that the drawer will stay closed and not respond to gestures.
* - locked-open, meaning that the drawer will stay opened and not respond to gestures.
* The drawer may still be opened and closed programmatically (`openDrawer`/`closeDrawer`).
*/
drawerLockMode: PropTypes.oneOf([
'unlocked',
'locked-closed',
'locked-open'
]),
/**
* Function called whenever there is an interaction with the navigation view.
*/
onDrawerSlide: PropTypes.func,
/**
* Function called when the drawer state has changed. The drawer can be in 3 states:
* - idle, meaning there is no interaction with the navigation view happening at the time
* - dragging, meaning there is currently an interaction with the navigation view
* - settling, meaning that there was an interaction with the navigation view, and the
* navigation view is now finishing its closing or opening animation
*/
onDrawerStateChanged: PropTypes.func,
/**
* Function called whenever the navigation view has been opened.
*/
onDrawerOpen: PropTypes.func,
/**
* Function called whenever the navigation view has been closed.
*/
onDrawerClose: PropTypes.func,
/**
* The navigation view that will be rendered to the side of the screen and can be pulled in.
*/
renderNavigationView: PropTypes.func.isRequired,
/**
* Make the drawer take the entire screen and draw the background of the
* status bar to allow it to open over the status bar. It will only have an
* effect on API 21+.
*/
statusBarBackgroundColor: ColorPropType,
},
mixins: [NativeMethodsMixin],
getDefaultProps: function(): Object {
return {
drawerBackgroundColor: 'white',
};
},
getInitialState: function() {
return {statusBarBackgroundColor: undefined};
},
getInnerViewNode: function() {
return this.refs[INNERVIEW_REF].getInnerViewNode();
},
render: function() {
const drawStatusBar = Platform.Version >= 21 && this.props.statusBarBackgroundColor;
const drawerViewWrapper =
<View
style={[
styles.drawerSubview,
{width: this.props.drawerWidth, backgroundColor: this.props.drawerBackgroundColor}
]}
collapsable={false}>
{this.props.renderNavigationView()}
{drawStatusBar && <View style={styles.drawerStatusBar} />}
</View>;
const childrenWrapper =
<View ref={INNERVIEW_REF} style={styles.mainSubview} collapsable={false}>
{drawStatusBar &&
<StatusBar
translucent
backgroundColor={this.props.statusBarBackgroundColor}
/>}
{drawStatusBar &&
<View style={[
styles.statusBar,
{backgroundColor: this.props.statusBarBackgroundColor}
]} />}
{this.props.children}
</View>;
return (
<AndroidDrawerLayout
{...this.props}
ref={RK_DRAWER_REF}
drawerWidth={this.props.drawerWidth}
drawerPosition={this.props.drawerPosition}
drawerLockMode={this.props.drawerLockMode}
style={[styles.base, this.props.style]}
onDrawerSlide={this._onDrawerSlide}
onDrawerOpen={this._onDrawerOpen}
onDrawerClose={this._onDrawerClose}
onDrawerStateChanged={this._onDrawerStateChanged}>
{childrenWrapper}
{drawerViewWrapper}
</AndroidDrawerLayout>
);
},
_onDrawerSlide: function(event) {
if (this.props.onDrawerSlide) {
this.props.onDrawerSlide(event);
}
if (this.props.keyboardDismissMode === 'on-drag') {
dismissKeyboard();
}
},
_onDrawerOpen: function() {
if (this.props.onDrawerOpen) {
this.props.onDrawerOpen();
}
},
_onDrawerClose: function() {
if (this.props.onDrawerClose) {
this.props.onDrawerClose();
}
},
_onDrawerStateChanged: function(event) {
if (this.props.onDrawerStateChanged) {
this.props.onDrawerStateChanged(DRAWER_STATES[event.nativeEvent.drawerState]);
}
},
/**
* Opens the drawer.
*/
openDrawer: function() {
UIManager.dispatchViewManagerCommand(
this._getDrawerLayoutHandle(),
UIManager.AndroidDrawerLayout.Commands.openDrawer,
null
);
},
/**
* Closes the drawer.
*/
closeDrawer: function() {
UIManager.dispatchViewManagerCommand(
this._getDrawerLayoutHandle(),
UIManager.AndroidDrawerLayout.Commands.closeDrawer,
null
);
},
/**
* Closing and opening example
* Note: To access the drawer you have to give it a ref. Refs do not work on stateless components
* render () {
* this.openDrawer = () => {
* this.refs.DRAWER.openDrawer()
* }
* this.closeDrawer = () => {
* this.refs.DRAWER.closeDrawer()
* }
* return (
* <DrawerLayoutAndroid ref={'DRAWER'}>
* </DrawerLayoutAndroid>
* )
* }
*/
_getDrawerLayoutHandle: function() {
return ReactNative.findNodeHandle(this.refs[RK_DRAWER_REF]);
},
});
const styles = StyleSheet.create({
base: {
flex: 1,
elevation: 16,
},
mainSubview: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
},
drawerSubview: {
position: 'absolute',
top: 0,
bottom: 0,
},
statusBar: {
height: StatusBar.currentHeight,
},
drawerStatusBar: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
height: StatusBar.currentHeight,
backgroundColor: 'rgba(0, 0, 0, 0.251)',
},
});
// The View that contains both the actual drawer and the main view
const AndroidDrawerLayout = requireNativeComponent('AndroidDrawerLayout', DrawerLayoutAndroid);
module.exports = DrawerLayoutAndroid;

View File

@@ -0,0 +1,11 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule DrawerLayoutAndroid
*/
'use strict';
module.exports = require('UnimplementedView');

View File

@@ -0,0 +1,165 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule Keyboard
* @flow
*/
'use strict';
const LayoutAnimation = require('LayoutAnimation');
const invariant = require('fbjs/lib/invariant');
const NativeEventEmitter = require('NativeEventEmitter');
const KeyboardObserver = require('NativeModules').KeyboardObserver;
const dismissKeyboard = require('dismissKeyboard');
const KeyboardEventEmitter = new NativeEventEmitter(KeyboardObserver);
type KeyboardEventName =
| 'keyboardWillShow'
| 'keyboardDidShow'
| 'keyboardWillHide'
| 'keyboardDidHide'
| 'keyboardWillChangeFrame'
| 'keyboardDidChangeFrame';
export type KeyboardEvent = {|
+duration?: number,
+easing?: string,
+endCoordinates: {|
+width: number,
+height: number,
+screenX: number,
+screenY: number,
|},
|};
type KeyboardEventListener = (e: KeyboardEvent) => void;
// The following object exists for documentation purposes
// Actual work happens in
// https://github.com/facebook/react-native/blob/master/Libraries/EventEmitter/NativeEventEmitter.js
/**
* `Keyboard` module to control keyboard events.
*
* ### Usage
*
* The Keyboard module allows you to listen for native events and react to them, as
* well as make changes to the keyboard, like dismissing it.
*
*```
* import React, { Component } from 'react';
* import { Keyboard, TextInput } from 'react-native';
*
* class Example extends Component {
* componentWillMount () {
* this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
* this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
* }
*
* componentWillUnmount () {
* this.keyboardDidShowListener.remove();
* this.keyboardDidHideListener.remove();
* }
*
* _keyboardDidShow () {
* alert('Keyboard Shown');
* }
*
* _keyboardDidHide () {
* alert('Keyboard Hidden');
* }
*
* render() {
* return (
* <TextInput
* onSubmitEditing={Keyboard.dismiss}
* />
* );
* }
* }
*```
*/
let Keyboard = {
/**
* The `addListener` function connects a JavaScript function to an identified native
* keyboard notification event.
*
* This function then returns the reference to the listener.
*
* @param {string} eventName The `nativeEvent` is the string that identifies the event you're listening for. This
*can be any of the following:
*
* - `keyboardWillShow`
* - `keyboardDidShow`
* - `keyboardWillHide`
* - `keyboardDidHide`
* - `keyboardWillChangeFrame`
* - `keyboardDidChangeFrame`
*
* Note that if you set `android:windowSoftInputMode` to `adjustResize` or `adjustNothing`,
* only `keyboardDidShow` and `keyboardDidHide` events will be available on Android.
* `keyboardWillShow` as well as `keyboardWillHide` are generally not available on Android
* since there is no native corresponding event.
*
* @param {function} callback function to be called when the event fires.
*/
addListener(eventName: KeyboardEventName, callback: KeyboardEventListener) {
invariant(false, 'Dummy method used for documentation');
},
/**
* Removes a specific listener.
*
* @param {string} eventName The `nativeEvent` is the string that identifies the event you're listening for.
* @param {function} callback function to be called when the event fires.
*/
removeListener(eventName: KeyboardEventName, callback: Function) {
invariant(false, 'Dummy method used for documentation');
},
/**
* Removes all listeners for a specific event type.
*
* @param {string} eventType The native event string listeners are watching which will be removed.
*/
removeAllListeners(eventName: KeyboardEventName) {
invariant(false, 'Dummy method used for documentation');
},
/**
* Dismisses the active keyboard and removes focus.
*/
dismiss() {
invariant(false, 'Dummy method used for documentation');
},
/**
* Useful for syncing TextInput (or other keyboard accessory view) size of
* position changes with keyboard movements.
*/
scheduleLayoutAnimation(event: KeyboardEvent) {
invariant(false, 'Dummy method used for documentation');
},
};
// Throw away the dummy object and reassign it to original module
Keyboard = KeyboardEventEmitter;
Keyboard.dismiss = dismissKeyboard;
Keyboard.scheduleLayoutAnimation = function(event: KeyboardEvent) {
const {duration, easing} = event;
if (duration) {
LayoutAnimation.configureNext({
duration: duration,
update: {
duration: duration,
type: (easing && LayoutAnimation.Types[easing]) || 'keyboard',
},
});
}
};
module.exports = Keyboard;

View File

@@ -0,0 +1,211 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule KeyboardAvoidingView
* @flow
*/
'use strict';
const createReactClass = require('create-react-class');
const Keyboard = require('Keyboard');
const LayoutAnimation = require('LayoutAnimation');
const Platform = require('Platform');
const PropTypes = require('prop-types');
const React = require('React');
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */
const TimerMixin = require('react-timer-mixin');
const View = require('View');
const ViewPropTypes = require('ViewPropTypes');
import type EmitterSubscription from 'EmitterSubscription';
import type {ViewLayout, ViewLayoutEvent} from 'ViewPropTypes';
type ScreenRect = {
screenX: number,
screenY: number,
width: number,
height: number,
};
type KeyboardChangeEvent = {
startCoordinates?: ScreenRect,
endCoordinates: ScreenRect,
duration?: number,
easing?: string,
};
const viewRef = 'VIEW';
/**
* This is a component to solve the common problem of views that need to move out of the way of the virtual keyboard.
* It can automatically adjust either its height, position or bottom padding based on the position of the keyboard.
*/
const KeyboardAvoidingView = createReactClass({
displayName: 'KeyboardAvoidingView',
mixins: [TimerMixin],
propTypes: {
...ViewPropTypes,
/**
* Specify how the `KeyboardAvoidingView` will react to the presence of
* the keyboard. It can adjust the height, position or bottom padding of the view
*/
behavior: PropTypes.oneOf(['height', 'position', 'padding']),
/**
* The style of the content container(View) when behavior is 'position'.
*/
contentContainerStyle: ViewPropTypes.style,
/**
* This is the distance between the top of the user screen and the react native view,
* may be non-zero in some use cases. The default value is 0.
*/
keyboardVerticalOffset: PropTypes.number.isRequired,
/**
* This is to allow us to manually control which KAV shuld take effect when
* having more than one KAV at the same screen
*/
enabled: PropTypes.bool.isRequired,
},
getDefaultProps() {
return {
enabled: true,
keyboardVerticalOffset: 0,
};
},
getInitialState() {
return {
bottom: 0,
};
},
subscriptions: ([]: Array<EmitterSubscription>),
frame: (null: ?ViewLayout),
_relativeKeyboardHeight(keyboardFrame: ScreenRect): number {
const frame = this.frame;
if (!frame || !keyboardFrame) {
return 0;
}
const keyboardY = keyboardFrame.screenY - this.props.keyboardVerticalOffset;
// Calculate the displacement needed for the view such that it
// no longer overlaps with the keyboard
return Math.max(frame.y + frame.height - keyboardY, 0);
},
_onKeyboardChange(event: ?KeyboardChangeEvent) {
if (!event) {
this.setState({bottom: 0});
return;
}
const {duration, easing, endCoordinates} = event;
const height = this._relativeKeyboardHeight(endCoordinates);
if (this.state.bottom === height) {
return;
}
if (duration && easing) {
LayoutAnimation.configureNext({
duration: duration,
update: {
duration: duration,
type: LayoutAnimation.Types[easing] || 'keyboard',
},
});
}
this.setState({bottom: height});
},
_onLayout(event: ViewLayoutEvent) {
this.frame = event.nativeEvent.layout;
},
UNSAFE_componentWillUpdate(nextProps: Object, nextState: Object, nextContext?: Object): void {
if (nextState.bottom === this.state.bottom &&
this.props.behavior === 'height' &&
nextProps.behavior === 'height') {
// If the component rerenders without an internal state change, e.g.
// triggered by parent component re-rendering, no need for bottom to change.
nextState.bottom = 0;
}
},
UNSAFE_componentWillMount() {
if (Platform.OS === 'ios') {
this.subscriptions = [
Keyboard.addListener('keyboardWillChangeFrame', this._onKeyboardChange),
];
} else {
this.subscriptions = [
Keyboard.addListener('keyboardDidHide', this._onKeyboardChange),
Keyboard.addListener('keyboardDidShow', this._onKeyboardChange),
];
}
},
componentWillUnmount() {
this.subscriptions.forEach((sub) => sub.remove());
},
render(): React.Element<any> {
// $FlowFixMe(>=0.41.0)
const {behavior, children, style, ...props} = this.props;
const bottomHeight = this.props.enabled ? this.state.bottom : 0;
switch (behavior) {
case 'height':
let heightStyle;
if (this.frame) {
// Note that we only apply a height change when there is keyboard present,
// i.e. this.state.bottom is greater than 0. If we remove that condition,
// this.frame.height will never go back to its original value.
// When height changes, we need to disable flex.
heightStyle = {height: this.frame.height - bottomHeight, flex: 0};
}
return (
<View ref={viewRef} style={[style, heightStyle]} onLayout={this._onLayout} {...props}>
{children}
</View>
);
case 'position':
const positionStyle = {bottom: bottomHeight};
const { contentContainerStyle } = this.props;
return (
<View ref={viewRef} style={style} onLayout={this._onLayout} {...props}>
<View style={[contentContainerStyle, positionStyle]}>
{children}
</View>
</View>
);
case 'padding':
const paddingStyle = {paddingBottom: bottomHeight};
return (
<View ref={viewRef} style={[style, paddingStyle]} onLayout={this._onLayout} {...props}>
{children}
</View>
);
default:
return (
<View ref={viewRef} onLayout={this._onLayout} style={style} {...props}>
{children}
</View>
);
}
},
});
module.exports = KeyboardAvoidingView;

View File

@@ -0,0 +1,43 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule LazyRenderer
*/
'use strict';
const React = require('React');
const createReactClass = require('create-react-class');
const PropTypes = require('prop-types');
const TimerMixin = require('react-timer-mixin');
const LazyRenderer = createReactClass({
displayName: 'LazyRenderer',
mixin: [TimerMixin],
propTypes: {
render: PropTypes.func.isRequired,
},
UNSAFE_componentWillMount: function(): void {
this.setState({
_lazyRender : true,
});
},
componentDidMount: function(): void {
requestAnimationFrame(() => {
this.setState({
_lazyRender : false,
});
});
},
render: function(): ?React.Element {
return this.state._lazyRender ? null : this.props.render();
},
});
module.exports = LazyRenderer;

View File

@@ -0,0 +1,12 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule MaskedViewIOS
* @flow
*/
'use strict';
module.exports = require('UnimplementedView');

View File

@@ -0,0 +1,106 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule MaskedViewIOS
* @flow
*/
const PropTypes = require('prop-types');
const React = require('React');
const StyleSheet = require('StyleSheet');
const View = require('View');
const ViewPropTypes = require('ViewPropTypes');
const requireNativeComponent = require('requireNativeComponent');
import type { ViewProps } from 'ViewPropTypes';
type Props = ViewProps & {
children: any,
/**
* Should be a React element to be rendered and applied as the
* mask for the child element.
*/
maskElement: React.Element<any>,
};
/**
* Renders the child view with a mask specified in the `maskElement` prop.
*
* ```
* import React from 'react';
* import { MaskedViewIOS, Text, View } from 'react-native';
*
* class MyMaskedView extends React.Component {
* render() {
* return (
* <MaskedViewIOS
* style={{ flex: 1 }}
* maskElement={
* <View style={styles.maskContainerStyle}>
* <Text style={styles.maskTextStyle}>
* Basic Mask
* </Text>
* </View>
* }
* >
* <View style={{ flex: 1, backgroundColor: 'blue' }} />
* </MaskedViewIOS>
* );
* }
* }
* ```
*
* The above example will render a view with a blue background that fills its
* parent, and then mask that view with text that says "Basic Mask".
*
* The alpha channel of the view rendered by the `maskElement` prop determines how
* much of the view's content and background shows through. Fully or partially
* opaque pixels allow the underlying content to show through but fully
* transparent pixels block that content.
*
*/
class MaskedViewIOS extends React.Component<Props> {
static propTypes = {
...ViewPropTypes,
maskElement: PropTypes.element.isRequired,
};
_hasWarnedInvalidRenderMask = false;
render() {
const { maskElement, children, ...otherViewProps } = this.props;
if (!React.isValidElement(maskElement)) {
if (!this._hasWarnedInvalidRenderMask) {
console.warn(
'MaskedView: Invalid `maskElement` prop was passed to MaskedView. ' +
'Expected a React Element. No mask will render.'
);
this._hasWarnedInvalidRenderMask = true;
}
return <View {...otherViewProps}>{children}</View>;
}
return (
<RCTMaskedView {...otherViewProps}>
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
{maskElement}
</View>
{children}
</RCTMaskedView>
);
}
}
const RCTMaskedView = requireNativeComponent('RCTMaskedView', {
name: 'RCTMaskedView',
displayName: 'RCTMaskedView',
propTypes: {
...ViewPropTypes,
},
});
module.exports = MaskedViewIOS;

View File

@@ -0,0 +1,11 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule NavigatorIOS
*/
'use strict';
module.exports = require('UnimplementedView');

View File

@@ -0,0 +1,940 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule NavigatorIOS
* @flow
*/
'use strict';
const EventEmitter = require('EventEmitter');
const Image = require('Image');
const RCTNavigatorManager = require('NativeModules').NavigatorManager;
const React = require('React');
const PropTypes = require('prop-types');
const ReactNative = require('ReactNative');
const StaticContainer = require('StaticContainer.react');
const StyleSheet = require('StyleSheet');
const TVEventHandler = require('TVEventHandler');
const View = require('View');
const ViewPropTypes = require('ViewPropTypes');
const createReactClass = require('create-react-class');
const invariant = require('fbjs/lib/invariant');
const requireNativeComponent = require('requireNativeComponent');
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */
const keyMirror = require('fbjs/lib/keyMirror');
const TRANSITIONER_REF = 'transitionerRef';
let __uid = 0;
function getuid() {
return __uid++;
}
class NavigatorTransitionerIOS extends React.Component<$FlowFixMeProps> {
requestSchedulingNavigation(cb) {
RCTNavigatorManager.requestSchedulingJavaScriptNavigation(
ReactNative.findNodeHandle(this),
cb
);
}
render() {
return (
<RCTNavigator {...this.props}/>
);
}
}
const SystemIconLabels = {
done: true,
cancel: true,
edit: true,
save: true,
add: true,
compose: true,
reply: true,
action: true,
organize: true,
bookmarks: true,
search: true,
refresh: true,
stop: true,
camera: true,
trash: true,
play: true,
pause: true,
rewind: true,
'fast-forward': true,
undo: true,
redo: true,
'page-curl': true,
};
const SystemIcons = keyMirror(SystemIconLabels);
type SystemButtonType = $Enum<typeof SystemIconLabels>;
type Route = {
component: Function,
title: string,
titleImage?: Object,
passProps?: Object,
backButtonTitle?: string,
backButtonIcon?: Object,
leftButtonTitle?: string,
leftButtonIcon?: Object,
leftButtonSystemIcon?: SystemButtonType,
onLeftButtonPress?: Function,
rightButtonTitle?: string,
rightButtonIcon?: Object,
rightButtonSystemIcon?: SystemButtonType,
onRightButtonPress?: Function,
wrapperStyle?: any,
};
type State = {
idStack: Array<number>,
routeStack: Array<Route>,
requestedTopOfStack: number,
observedTopOfStack: number,
progress: number,
fromIndex: number,
toIndex: number,
makingNavigatorRequest: boolean,
updatingAllIndicesAtOrBeyond: ?number,
}
type Event = Object;
/**
* Think of `<NavigatorIOS>` as simply a component that renders an
* `RCTNavigator`, and moves the `RCTNavigator`'s `requestedTopOfStack` pointer
* forward and backward. The `RCTNavigator` interprets changes in
* `requestedTopOfStack` to be pushes and pops of children that are rendered.
* `<NavigatorIOS>` always ensures that whenever the `requestedTopOfStack`
* pointer is moved, that we've also rendered enough children so that the
* `RCTNavigator` can carry out the push/pop with those children.
* `<NavigatorIOS>` also removes children that will no longer be needed
* (after the pop of a child has been fully completed/animated out).
*/
/**
* `NavigatorIOS` is a wrapper around
* [`UINavigationController`](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UINavigationController_Class/),
* enabling you to implement a navigation stack. It works exactly the same as it
* would on a native app using `UINavigationController`, providing the same
* animations and behavior from UIKit.
*
* As the name implies, it is only available on iOS. Take a look at
* [`React Navigation`](https://reactnavigation.org/) for a cross-platform
* solution in JavaScript, or check out either of these components for native
* solutions: [native-navigation](http://airbnb.io/native-navigation/),
* [react-native-navigation](https://github.com/wix/react-native-navigation).
*
* To set up the navigator, provide the `initialRoute` prop with a route
* object. A route object is used to describe each scene that your app
* navigates to. `initialRoute` represents the first route in your navigator.
*
* ```
* import PropTypes from 'prop-types';
* import React, { Component } from 'react';
* import { NavigatorIOS, Text } from 'react-native';
*
* export default class NavigatorIOSApp extends Component {
* render() {
* return (
* <NavigatorIOS
* initialRoute={{
* component: MyScene,
* title: 'My Initial Scene',
* }}
* style={{flex: 1}}
* />
* );
* }
* }
*
* class MyScene extends Component {
* static propTypes = {
* title: PropTypes.string.isRequired,
* navigator: PropTypes.object.isRequired,
* }
*
* _onForward = () => {
* this.props.navigator.push({
* title: 'Scene ' + nextIndex,
* });
* }
*
* render() {
* return (
* <View>
* <Text>Current Scene: { this.props.title }</Text>
* <TouchableHighlight onPress={this._onForward}>
* <Text>Tap me to load the next scene</Text>
* </TouchableHighlight>
* </View>
* )
* }
* }
* ```
*
* In this code, the navigator renders the component specified in initialRoute,
* which in this case is `MyScene`. This component will receive a `route` prop
* and a `navigator` prop representing the navigator. The navigator's navigation
* bar will render the title for the current scene, "My Initial Scene".
*
* You can optionally pass in a `passProps` property to your `initialRoute`.
* `NavigatorIOS` passes this in as props to the rendered component:
*
* ```
* initialRoute={{
* component: MyScene,
* title: 'My Initial Scene',
* passProps: { myProp: 'foo' }
* }}
* ```
*
* You can then access the props passed in via `{this.props.myProp}`.
*
* #### Handling Navigation
*
* To trigger navigation functionality such as pushing or popping a view, you
* have access to a `navigator` object. The object is passed in as a prop to any
* component that is rendered by `NavigatorIOS`. You can then call the
* relevant methods to perform the navigation action you need:
*
* ```
* class MyView extends Component {
* _handleBackPress() {
* this.props.navigator.pop();
* }
*
* _handleNextPress(nextRoute) {
* this.props.navigator.push(nextRoute);
* }
*
* render() {
* const nextRoute = {
* component: MyView,
* title: 'Bar That',
* passProps: { myProp: 'bar' }
* };
* return(
* <TouchableHighlight onPress={() => this._handleNextPress(nextRoute)}>
* <Text style={{marginTop: 200, alignSelf: 'center'}}>
* See you on the other nav {this.props.myProp}!
* </Text>
* </TouchableHighlight>
* );
* }
* }
* ```
*
* You can also trigger navigator functionality from the `NavigatorIOS`
* component:
*
* ```
* class NavvyIOS extends Component {
* _handleNavigationRequest() {
* this.refs.nav.push({
* component: MyView,
* title: 'Genius',
* passProps: { myProp: 'genius' },
* });
* }
*
* render() {
* return (
* <NavigatorIOS
* ref='nav'
* initialRoute={{
* component: MyView,
* title: 'Foo This',
* passProps: { myProp: 'foo' },
* rightButtonTitle: 'Add',
* onRightButtonPress: () => this._handleNavigationRequest(),
* }}
* style={{flex: 1}}
* />
* );
* }
* }
* ```
*
* The code above adds a `_handleNavigationRequest` private method that is
* invoked from the `NavigatorIOS` component when the right navigation bar item
* is pressed. To get access to the navigator functionality, a reference to it
* is saved in the `ref` prop and later referenced to push a new scene into the
* navigation stack.
*
* #### Navigation Bar Configuration
*
* Props passed to `NavigatorIOS` will set the default configuration
* for the navigation bar. Props passed as properties to a route object will set
* the configuration for that route's navigation bar, overriding any props
* passed to the `NavigatorIOS` component.
*
* ```
* _handleNavigationRequest() {
* this.refs.nav.push({
* //...
* passProps: { myProp: 'genius' },
* barTintColor: '#996699',
* });
* }
*
* render() {
* return (
* <NavigatorIOS
* //...
* style={{flex: 1}}
* barTintColor='#ffffcc'
* />
* );
* }
* ```
*
* In the example above the navigation bar color is changed when the new route
* is pushed.
*
*/
const NavigatorIOS = createReactClass({
displayName: 'NavigatorIOS',
propTypes: {
/**
* NavigatorIOS uses `route` objects to identify child views, their props,
* and navigation bar configuration. Navigation operations such as push
* operations expect routes to look like this the `initialRoute`.
*/
initialRoute: PropTypes.shape({
/**
* The React Class to render for this route
*/
component: PropTypes.func.isRequired,
/**
* The title displayed in the navigation bar and the back button for this
* route.
*/
title: PropTypes.string.isRequired,
/**
* If set, a title image will appear instead of the text title.
*/
titleImage: Image.propTypes.source,
/**
* Use this to specify additional props to pass to the rendered
* component. `NavigatorIOS` will automatically pass in `route` and
* `navigator` props to the component.
*/
passProps: PropTypes.object,
/**
* If set, the left navigation button image will be displayed using this
* source. Note that this doesn't apply to the header of the current
* view, but to those views that are subsequently pushed.
*/
backButtonIcon: Image.propTypes.source,
/**
* If set, the left navigation button text will be set to this. Note that
* this doesn't apply to the left button of the current view, but to
* those views that are subsequently pushed
*/
backButtonTitle: PropTypes.string,
/**
* If set, the left navigation button image will be displayed using
* this source.
*/
leftButtonIcon: Image.propTypes.source,
/**
* If set, the left navigation button will display this text.
*/
leftButtonTitle: PropTypes.string,
/**
* If set, the left header button will appear with this system icon
*
* Supported icons are `done`, `cancel`, `edit`, `save`, `add`,
* `compose`, `reply`, `action`, `organize`, `bookmarks`, `search`,
* `refresh`, `stop`, `camera`, `trash`, `play`, `pause`, `rewind`,
* `fast-forward`, `undo`, `redo`, and `page-curl`
*/
leftButtonSystemIcon: PropTypes.oneOf(Object.keys(SystemIcons)),
/**
* This function will be invoked when the left navigation bar item is
* pressed.
*/
onLeftButtonPress: PropTypes.func,
/**
* If set, the right navigation button image will be displayed using
* this source.
*/
rightButtonIcon: Image.propTypes.source,
/**
* If set, the right navigation button will display this text.
*/
rightButtonTitle: PropTypes.string,
/**
* If set, the right header button will appear with this system icon
*
* See leftButtonSystemIcon for supported icons
*/
rightButtonSystemIcon: PropTypes.oneOf(Object.keys(SystemIcons)),
/**
* This function will be invoked when the right navigation bar item is
* pressed.
*/
onRightButtonPress: PropTypes.func,
/**
* Styles for the navigation item containing the component.
*/
wrapperStyle: ViewPropTypes.style,
/**
* Boolean value that indicates whether the navigation bar is hidden.
*/
navigationBarHidden: PropTypes.bool,
/**
* Boolean value that indicates whether to hide the 1px hairline
* shadow.
*/
shadowHidden: PropTypes.bool,
/**
* The color used for the buttons in the navigation bar.
*/
tintColor: PropTypes.string,
/**
* The background color of the navigation bar.
*/
barTintColor: PropTypes.string,
/**
* The style of the navigation bar. Supported values are 'default', 'black'.
* Use 'black' instead of setting `barTintColor` to black. This produces
* a navigation bar with the native iOS style with higher translucency.
*/
barStyle: PropTypes.oneOf(['default', 'black']),
/**
* The text color of the navigation bar title.
*/
titleTextColor: PropTypes.string,
/**
* Boolean value that indicates whether the navigation bar is
* translucent.
*/
translucent: PropTypes.bool,
}).isRequired,
/**
* Boolean value that indicates whether the navigation bar is hidden
* by default.
*/
navigationBarHidden: PropTypes.bool,
/**
* Boolean value that indicates whether to hide the 1px hairline shadow
* by default.
*/
shadowHidden: PropTypes.bool,
/**
* The default wrapper style for components in the navigator.
* A common use case is to set the `backgroundColor` for every scene.
*/
itemWrapperStyle: ViewPropTypes.style,
/**
* The default color used for the buttons in the navigation bar.
*/
tintColor: PropTypes.string,
/**
* The default background color of the navigation bar.
*/
barTintColor: PropTypes.string,
/**
* The style of the navigation bar. Supported values are 'default', 'black'.
* Use 'black' instead of setting `barTintColor` to black. This produces
* a navigation bar with the native iOS style with higher translucency.
*/
barStyle: PropTypes.oneOf(['default', 'black']),
/**
* The default text color of the navigation bar title.
*/
titleTextColor: PropTypes.string,
/**
* Boolean value that indicates whether the navigation bar is
* translucent by default
*/
translucent: PropTypes.bool,
/**
* Boolean value that indicates whether the interactive pop gesture is
* enabled. This is useful for enabling/disabling the back swipe navigation
* gesture.
*
* If this prop is not provided, the default behavior is for the back swipe
* gesture to be enabled when the navigation bar is shown and disabled when
* the navigation bar is hidden. Once you've provided the
* `interactivePopGestureEnabled` prop, you can never restore the default
* behavior.
*/
interactivePopGestureEnabled: PropTypes.bool,
},
navigator: (undefined: ?Object),
UNSAFE_componentWillMount: function() {
// Precompute a pack of callbacks that's frequently generated and passed to
// instances.
this.navigator = {
push: this.push,
pop: this.pop,
popN: this.popN,
replace: this.replace,
replaceAtIndex: this.replaceAtIndex,
replacePrevious: this.replacePrevious,
replacePreviousAndPop: this.replacePreviousAndPop,
resetTo: this.resetTo,
popToRoute: this.popToRoute,
popToTop: this.popToTop,
};
},
componentDidMount: function() {
this._enableTVEventHandler();
},
componentWillUnmount: function() {
this._disableTVEventHandler();
},
getDefaultProps: function(): Object {
return {
translucent: true,
};
},
getInitialState: function(): State {
return {
idStack: [getuid()],
routeStack: [this.props.initialRoute],
// The navigation index that we wish to push/pop to.
requestedTopOfStack: 0,
// The last index that native has sent confirmation of completed push/pop
// for. At this point, we can discard any views that are beyond the
// `requestedTopOfStack`. A value of `null` means we have not received
// any confirmation, ever. We may receive an `observedTopOfStack` without
// ever requesting it - native can instigate pops of its own with the
// backswipe gesture.
observedTopOfStack: 0,
progress: 1,
fromIndex: 0,
toIndex: 0,
// Whether or not we are making a navigator request to push/pop. (Used
// for performance optimization).
makingNavigatorRequest: false,
// Whether or not we are updating children of navigator and if so (not
// `null`) which index marks the beginning of all updates. Used for
// performance optimization.
updatingAllIndicesAtOrBeyond: 0,
};
},
_toFocusOnNavigationComplete: (undefined: any),
_handleFocusRequest: function(item: any) {
if (this.state.makingNavigatorRequest) {
this._toFocusOnNavigationComplete = item;
} else {
this._getFocusEmitter().emit('focus', item);
}
},
_focusEmitter: (undefined: ?EventEmitter),
_getFocusEmitter: function(): EventEmitter {
// Flow not yet tracking assignments to instance fields.
let focusEmitter = this._focusEmitter;
if (!focusEmitter) {
focusEmitter = new EventEmitter();
this._focusEmitter = focusEmitter;
}
return focusEmitter;
},
getChildContext: function(): {
onFocusRequested: Function,
focusEmitter: EventEmitter,
} {
return {
onFocusRequested: this._handleFocusRequest,
focusEmitter: this._getFocusEmitter(),
};
},
childContextTypes: {
onFocusRequested: PropTypes.func,
focusEmitter: PropTypes.instanceOf(EventEmitter),
},
_tryLockNavigator: function(cb: () => void) {
this.refs[TRANSITIONER_REF].requestSchedulingNavigation(
(acquiredLock) => acquiredLock && cb()
);
},
_handleNavigatorStackChanged: function(e: Event) {
const newObservedTopOfStack = e.nativeEvent.stackLength - 1;
invariant(
newObservedTopOfStack <= this.state.requestedTopOfStack,
'No navigator item should be pushed without JS knowing about it %s %s', newObservedTopOfStack, this.state.requestedTopOfStack
);
const wasWaitingForConfirmation =
this.state.requestedTopOfStack !== this.state.observedTopOfStack;
if (wasWaitingForConfirmation) {
invariant(
newObservedTopOfStack === this.state.requestedTopOfStack,
'If waiting for observedTopOfStack to reach requestedTopOfStack, ' +
'the only valid observedTopOfStack should be requestedTopOfStack.'
);
}
// Mark the most recent observation regardless of if we can lock the
// navigator. `observedTopOfStack` merely represents what we've observed
// and this first `setState` is only executed to update debugging
// overlays/navigation bar.
// Also reset progress, toIndex, and fromIndex as they might not end
// in the correct states for a two possible reasons:
// Progress isn't always 0 or 1 at the end, the system rounds
// If the Navigator is offscreen these values won't be updated
// TOOD: Revisit this decision when no longer relying on native navigator.
const nextState = {
observedTopOfStack: newObservedTopOfStack,
makingNavigatorRequest: false,
updatingAllIndicesAtOrBeyond: null,
progress: 1,
toIndex: newObservedTopOfStack,
fromIndex: newObservedTopOfStack,
};
this.setState(nextState, this._eliminateUnneededChildren);
},
_eliminateUnneededChildren: function() {
// Updating the indices that we're deleting and that's all. (Truth: Nothing
// even uses the indices in this case, but let's make this describe the
// truth anyways).
const updatingAllIndicesAtOrBeyond =
this.state.routeStack.length > this.state.observedTopOfStack + 1 ?
this.state.observedTopOfStack + 1 :
null;
this.setState({
idStack: this.state.idStack.slice(0, this.state.observedTopOfStack + 1),
routeStack: this.state.routeStack.slice(0, this.state.observedTopOfStack + 1),
// Now we rerequest the top of stack that we observed.
requestedTopOfStack: this.state.observedTopOfStack,
makingNavigatorRequest: true,
updatingAllIndicesAtOrBeyond: updatingAllIndicesAtOrBeyond,
});
},
/**
* Navigate forward to a new route.
* @param route The new route to navigate to.
*/
push: function(route: Route) {
invariant(!!route, 'Must supply route to push');
// Make sure all previous requests are caught up first. Otherwise reject.
if (this.state.requestedTopOfStack === this.state.observedTopOfStack) {
this._tryLockNavigator(() => {
const nextStack = this.state.routeStack.concat([route]);
const nextIDStack = this.state.idStack.concat([getuid()]);
this.setState({
// We have to make sure that we've also supplied enough views to
// satisfy our request to adjust the `requestedTopOfStack`.
idStack: nextIDStack,
routeStack: nextStack,
requestedTopOfStack: nextStack.length - 1,
makingNavigatorRequest: true,
updatingAllIndicesAtOrBeyond: nextStack.length - 1,
});
});
}
},
/**
* Go back N scenes at once. When N=1, behavior matches `pop()`.
* @param n The number of scenes to pop.
*/
popN: function(n: number) {
if (n === 0) {
return;
}
// Make sure all previous requests are caught up first. Otherwise reject.
if (this.state.requestedTopOfStack === this.state.observedTopOfStack) {
if (this.state.requestedTopOfStack > 0) {
this._tryLockNavigator(() => {
const newRequestedTopOfStack = this.state.requestedTopOfStack - n;
invariant(newRequestedTopOfStack >= 0, 'Cannot pop below 0');
this.setState({
requestedTopOfStack: newRequestedTopOfStack,
makingNavigatorRequest: true,
updatingAllIndicesAtOrBeyond: this.state.requestedTopOfStack - n,
});
});
}
}
},
/**
* Pop back to the previous scene.
*/
pop: function() {
this.popN(1);
},
/**
* Replace a route in the navigation stack.
*
* @param route The new route that will replace the specified one.
* @param index The route into the stack that should be replaced.
* If it is negative, it counts from the back of the stack.
*/
replaceAtIndex: function(route: Route, index: number) {
invariant(!!route, 'Must supply route to replace');
if (index < 0) {
index += this.state.routeStack.length;
}
if (this.state.routeStack.length <= index) {
return;
}
// I don't believe we need to lock for a replace since there's no
// navigation actually happening
const nextIDStack = this.state.idStack.slice();
const nextRouteStack = this.state.routeStack.slice();
nextIDStack[index] = getuid();
nextRouteStack[index] = route;
this.setState({
idStack: nextIDStack,
routeStack: nextRouteStack,
makingNavigatorRequest: false,
updatingAllIndicesAtOrBeyond: index,
});
},
/**
* Replace the route for the current scene and immediately
* load the view for the new route.
* @param route The new route to navigate to.
*/
replace: function(route: Route) {
this.replaceAtIndex(route, -1);
},
/**
* Replace the route/view for the previous scene.
* @param route The new route to will replace the previous scene.
*/
replacePrevious: function(route: Route) {
this.replaceAtIndex(route, -2);
},
/**
* Go back to the topmost item in the navigation stack.
*/
popToTop: function() {
this.popToRoute(this.state.routeStack[0]);
},
/**
* Go back to the item for a particular route object.
* @param route The new route to navigate to.
*/
popToRoute: function(route: Route) {
const indexOfRoute = this.state.routeStack.indexOf(route);
invariant(
indexOfRoute !== -1,
'Calling pop to route for a route that doesn\'t exist!'
);
const numToPop = this.state.routeStack.length - indexOfRoute - 1;
this.popN(numToPop);
},
/**
* Replaces the previous route/view and transitions back to it.
* @param route The new route that replaces the previous scene.
*/
replacePreviousAndPop: function(route: Route) {
// Make sure all previous requests are caught up first. Otherwise reject.
if (this.state.requestedTopOfStack !== this.state.observedTopOfStack) {
return;
}
if (this.state.routeStack.length < 2) {
return;
}
this._tryLockNavigator(() => {
this.replacePrevious(route);
this.setState({
requestedTopOfStack: this.state.requestedTopOfStack - 1,
makingNavigatorRequest: true,
});
});
},
/**
* Replaces the top item and pop to it.
* @param route The new route that will replace the topmost item.
*/
resetTo: function(route: Route) {
invariant(!!route, 'Must supply route to push');
// Make sure all previous requests are caught up first. Otherwise reject.
if (this.state.requestedTopOfStack !== this.state.observedTopOfStack) {
return;
}
this.replaceAtIndex(route, 0);
this.popToRoute(route);
},
_handleNavigationComplete: function(e: Event) {
// Don't propagate to other NavigatorIOS instances this is nested in:
e.stopPropagation();
if (this._toFocusOnNavigationComplete) {
this._getFocusEmitter().emit('focus', this._toFocusOnNavigationComplete);
this._toFocusOnNavigationComplete = null;
}
this._handleNavigatorStackChanged(e);
},
_routeToStackItem: function(routeArg: Route, i: number) {
const {component, wrapperStyle, passProps, ...route} = routeArg;
const {itemWrapperStyle, ...props} = this.props;
const shouldUpdateChild =
this.state.updatingAllIndicesAtOrBeyond != null &&
this.state.updatingAllIndicesAtOrBeyond >= i;
const Component = component;
return (
<StaticContainer key={'nav' + i} shouldUpdate={shouldUpdateChild}>
<RCTNavigatorItem
{...props}
{...route}
style={[
styles.stackItem,
itemWrapperStyle,
wrapperStyle
]}>
<Component
navigator={this.navigator}
route={route}
{...passProps}
/>
</RCTNavigatorItem>
</StaticContainer>
);
},
_renderNavigationStackItems: function() {
const shouldRecurseToNavigator =
this.state.makingNavigatorRequest ||
this.state.updatingAllIndicesAtOrBeyond !== null;
// If not recursing update to navigator at all, may as well avoid
// computation of navigator children.
const items = shouldRecurseToNavigator ?
this.state.routeStack.map(this._routeToStackItem) : null;
return (
<StaticContainer shouldUpdate={shouldRecurseToNavigator}>
<NavigatorTransitionerIOS
ref={TRANSITIONER_REF}
style={styles.transitioner}
// $FlowFixMe(>=0.41.0)
vertical={this.props.vertical}
requestedTopOfStack={this.state.requestedTopOfStack}
onNavigationComplete={this._handleNavigationComplete}
interactivePopGestureEnabled={this.props.interactivePopGestureEnabled}>
{items}
</NavigatorTransitionerIOS>
</StaticContainer>
);
},
_tvEventHandler: (undefined: ?TVEventHandler),
_enableTVEventHandler: function() {
this._tvEventHandler = new TVEventHandler();
this._tvEventHandler.enable(this, function(cmp, evt) {
if (evt && evt.eventType === 'menu') {
cmp.pop();
}
});
},
_disableTVEventHandler: function() {
if (this._tvEventHandler) {
this._tvEventHandler.disable();
delete this._tvEventHandler;
}
},
render: function() {
return (
// $FlowFixMe(>=0.41.0)
<View style={this.props.style}>
{this._renderNavigationStackItems()}
</View>
);
},
});
const styles = StyleSheet.create({
stackItem: {
backgroundColor: 'white',
overflow: 'hidden',
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
},
transitioner: {
flex: 1,
},
});
const RCTNavigator = requireNativeComponent('RCTNavigator');
const RCTNavigatorItem = requireNativeComponent('RCTNavItem');
module.exports = NavigatorIOS;

View File

@@ -0,0 +1,165 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule Picker
* @flow
*/
'use strict';
const ColorPropType = require('ColorPropType');
const PickerIOS = require('PickerIOS');
const PickerAndroid = require('PickerAndroid');
const Platform = require('Platform');
const React = require('React');
const PropTypes = require('prop-types');
const StyleSheetPropType = require('StyleSheetPropType');
const TextStylePropTypes = require('TextStylePropTypes');
const UnimplementedView = require('UnimplementedView');
const ViewPropTypes = require('ViewPropTypes');
const ViewStylePropTypes = require('ViewStylePropTypes');
const itemStylePropType = StyleSheetPropType(TextStylePropTypes);
const pickerStyleType = StyleSheetPropType({
...ViewStylePropTypes,
color: ColorPropType,
});
const MODE_DIALOG = 'dialog';
const MODE_DROPDOWN = 'dropdown';
/**
* Individual selectable item in a Picker.
*/
class PickerItem extends React.Component<{
label: string,
value?: any,
color?: ColorPropType,
testID?: string,
}> {
static propTypes = {
/**
* Text to display for this item.
*/
label: PropTypes.string.isRequired,
/**
* The value to be passed to picker's `onValueChange` callback when
* this item is selected. Can be a string or an integer.
*/
value: PropTypes.any,
/**
* Color of this item's text.
* @platform android
*/
color: ColorPropType,
/**
* Used to locate the item in end-to-end tests.
*/
testID: PropTypes.string,
};
render() {
// The items are not rendered directly
throw null;
}
}
/**
* Renders the native picker component on iOS and Android. Example:
*
* <Picker
* selectedValue={this.state.language}
* onValueChange={(itemValue, itemIndex) => this.setState({language: itemValue})}>
* <Picker.Item label="Java" value="java" />
* <Picker.Item label="JavaScript" value="js" />
* </Picker>
*/
class Picker extends React.Component<{
style?: $FlowFixMe,
selectedValue?: any,
onValueChange?: Function,
enabled?: boolean,
mode?: 'dialog' | 'dropdown',
itemStyle?: $FlowFixMe,
prompt?: string,
testID?: string,
}> {
/**
* On Android, display the options in a dialog.
*/
static MODE_DIALOG = MODE_DIALOG;
/**
* On Android, display the options in a dropdown (this is the default).
*/
static MODE_DROPDOWN = MODE_DROPDOWN;
static Item = PickerItem;
static defaultProps = {
mode: MODE_DIALOG,
};
// $FlowFixMe(>=0.41.0)
static propTypes = {
...ViewPropTypes,
style: pickerStyleType,
/**
* Value matching value of one of the items. Can be a string or an integer.
*/
selectedValue: PropTypes.any,
/**
* Callback for when an item is selected. This is called with the following parameters:
* - `itemValue`: the `value` prop of the item that was selected
* - `itemPosition`: the index of the selected item in this picker
*/
onValueChange: PropTypes.func,
/**
* If set to false, the picker will be disabled, i.e. the user will not be able to make a
* selection.
* @platform android
*/
enabled: PropTypes.bool,
/**
* On Android, specifies how to display the selection items when the user taps on the picker:
*
* - 'dialog': Show a modal dialog. This is the default.
* - 'dropdown': Shows a dropdown anchored to the picker view
*
* @platform android
*/
mode: PropTypes.oneOf(['dialog', 'dropdown']),
/**
* Style to apply to each of the item labels.
* @platform ios
*/
itemStyle: itemStylePropType,
/**
* Prompt string for this picker, used on Android in dialog mode as the title of the dialog.
* @platform android
*/
prompt: PropTypes.string,
/**
* Used to locate this view in end-to-end tests.
*/
testID: PropTypes.string,
};
render() {
if (Platform.OS === 'ios') {
// $FlowFixMe found when converting React.createClass to ES6
return <PickerIOS {...this.props}>{this.props.children}</PickerIOS>;
} else if (Platform.OS === 'android') {
// $FlowFixMe found when converting React.createClass to ES6
return <PickerAndroid {...this.props}>{this.props.children}</PickerAndroid>;
} else {
return <UnimplementedView />;
}
}
}
module.exports = Picker;

View File

@@ -0,0 +1,162 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule PickerAndroid
* @flow
*/
'use strict';
const ColorPropType = require('ColorPropType');
const React = require('React');
const ReactPropTypes = require('prop-types');
const StyleSheet = require('StyleSheet');
const StyleSheetPropType = require('StyleSheetPropType');
const ViewPropTypes = require('ViewPropTypes');
const ViewStylePropTypes = require('ViewStylePropTypes');
const processColor = require('processColor');
const requireNativeComponent = require('requireNativeComponent');
const REF_PICKER = 'picker';
const MODE_DROPDOWN = 'dropdown';
const pickerStyleType = StyleSheetPropType({
...ViewStylePropTypes,
color: ColorPropType,
});
type Event = Object;
/**
* Not exposed as a public API - use <Picker> instead.
*/
class PickerAndroid extends React.Component<{
style?: $FlowFixMe,
selectedValue?: any,
enabled?: boolean,
mode?: 'dialog' | 'dropdown',
onValueChange?: Function,
prompt?: string,
testID?: string,
}, *> {
static propTypes = {
...ViewPropTypes,
style: pickerStyleType,
selectedValue: ReactPropTypes.any,
enabled: ReactPropTypes.bool,
mode: ReactPropTypes.oneOf(['dialog', 'dropdown']),
onValueChange: ReactPropTypes.func,
prompt: ReactPropTypes.string,
testID: ReactPropTypes.string,
};
constructor(props, context) {
super(props, context);
const state = this._stateFromProps(props);
this.state = {
...state,
initialSelectedIndex: state.selectedIndex,
};
}
UNSAFE_componentWillReceiveProps(nextProps) {
this.setState(this._stateFromProps(nextProps));
}
// Translate prop and children into stuff that the native picker understands.
_stateFromProps = (props) => {
let selectedIndex = 0;
const items = React.Children.map(props.children, (child, index) => {
if (child.props.value === props.selectedValue) {
selectedIndex = index;
}
const childProps = {
value: child.props.value,
label: child.props.label,
};
if (child.props.color) {
childProps.color = processColor(child.props.color);
}
return childProps;
});
return {selectedIndex, items};
};
render() {
const Picker = this.props.mode === MODE_DROPDOWN ? DropdownPicker : DialogPicker;
const nativeProps = {
enabled: this.props.enabled,
items: this.state.items,
mode: this.props.mode,
onSelect: this._onChange,
prompt: this.props.prompt,
selected: this.state.initialSelectedIndex,
testID: this.props.testID,
style: [styles.pickerAndroid, this.props.style],
accessibilityLabel: this.props.accessibilityLabel,
};
return <Picker ref={REF_PICKER} {...nativeProps} />;
}
_onChange = (event: Event) => {
if (this.props.onValueChange) {
const position = event.nativeEvent.position;
if (position >= 0) {
const children = React.Children.toArray(this.props.children);
const value = children[position].props.value;
this.props.onValueChange(value, position);
} else {
this.props.onValueChange(null, position);
}
}
this._lastNativePosition = event.nativeEvent.position;
this.forceUpdate();
};
componentDidMount() {
this._lastNativePosition = this.state.initialSelectedIndex;
}
componentDidUpdate() {
// The picker is a controlled component. This means we expect the
// on*Change handlers to be in charge of updating our
// `selectedValue` prop. That way they can also
// disallow/undo/mutate the selection of certain values. In other
// words, the embedder of this component should be the source of
// truth, not the native component.
if (this.refs[REF_PICKER] && this.state.selectedIndex !== this._lastNativePosition) {
this.refs[REF_PICKER].setNativeProps({selected: this.state.selectedIndex});
this._lastNativePosition = this.state.selectedIndex;
}
}
}
const styles = StyleSheet.create({
pickerAndroid: {
// The picker will conform to whatever width is given, but we do
// have to set the component's height explicitly on the
// surrounding view to ensure it gets rendered.
// TODO would be better to export a native constant for this,
// like in iOS the RCTDatePickerManager.m
height: 50,
},
});
const cfg = {
nativeOnly: {
items: true,
selected: true,
}
};
const DropdownPicker = requireNativeComponent('AndroidDropdownPicker', PickerAndroid, cfg);
const DialogPicker = requireNativeComponent('AndroidDialogPicker', PickerAndroid, cfg);
module.exports = PickerAndroid;

View File

@@ -0,0 +1,11 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule PickerAndroid
*/
'use strict';
module.exports = require('UnimplementedView');

View File

@@ -0,0 +1,13 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule PickerIOS
*
* This is a controlled component version of RCTPickerIOS
*/
'use strict';
module.exports = require('UnimplementedView');

View File

@@ -0,0 +1,135 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule PickerIOS
*
* This is a controlled component version of RCTPickerIOS
*/
'use strict';
const NativeMethodsMixin = require('NativeMethodsMixin');
const React = require('React');
const PropTypes = require('prop-types');
const StyleSheet = require('StyleSheet');
const StyleSheetPropType = require('StyleSheetPropType');
const TextStylePropTypes = require('TextStylePropTypes');
const View = require('View');
const ViewPropTypes = require('ViewPropTypes');
const processColor = require('processColor');
const createReactClass = require('create-react-class');
const itemStylePropType = StyleSheetPropType(TextStylePropTypes);
const requireNativeComponent = require('requireNativeComponent');
const PickerIOS = createReactClass({
displayName: 'PickerIOS',
mixins: [NativeMethodsMixin],
propTypes: {
...ViewPropTypes,
itemStyle: itemStylePropType,
onValueChange: PropTypes.func,
selectedValue: PropTypes.any, // string or integer basically
},
getInitialState: function() {
return this._stateFromProps(this.props);
},
UNSAFE_componentWillReceiveProps: function(nextProps) {
this.setState(this._stateFromProps(nextProps));
},
// Translate PickerIOS prop and children into stuff that RCTPickerIOS understands.
_stateFromProps: function(props) {
let selectedIndex = 0;
const items = [];
React.Children.toArray(props.children).forEach(function (child, index) {
if (child.props.value === props.selectedValue) {
selectedIndex = index;
}
items.push({
value: child.props.value,
label: child.props.label,
textColor: processColor(child.props.color),
});
});
return {selectedIndex, items};
},
render: function() {
return (
<View style={this.props.style}>
<RCTPickerIOS
ref={picker => this._picker = picker}
style={[styles.pickerIOS, this.props.itemStyle]}
items={this.state.items}
selectedIndex={this.state.selectedIndex}
onChange={this._onChange}
onStartShouldSetResponder={() => true}
onResponderTerminationRequest={() => false}
/>
</View>
);
},
_onChange: function(event) {
if (this.props.onChange) {
this.props.onChange(event);
}
if (this.props.onValueChange) {
this.props.onValueChange(event.nativeEvent.newValue, event.nativeEvent.newIndex);
}
// The picker is a controlled component. This means we expect the
// on*Change handlers to be in charge of updating our
// `selectedValue` prop. That way they can also
// disallow/undo/mutate the selection of certain values. In other
// words, the embedder of this component should be the source of
// truth, not the native component.
if (this._picker && this.state.selectedIndex !== event.nativeEvent.newIndex) {
this._picker.setNativeProps({
selectedIndex: this.state.selectedIndex
});
}
},
});
PickerIOS.Item = class extends React.Component {
static propTypes = {
value: PropTypes.any, // string or integer basically
label: PropTypes.string,
color: PropTypes.string,
};
render() {
// These items don't get rendered directly.
return null;
}
};
const styles = StyleSheet.create({
pickerIOS: {
// The picker will conform to whatever width is given, but we do
// have to set the component's height explicitly on the
// surrounding view to ensure it gets rendered.
height: 216,
},
});
const RCTPickerIOS = requireNativeComponent('RCTPicker', {
propTypes: {
style: itemStylePropType,
},
}, {
nativeOnly: {
items: true,
onChange: true,
selectedIndex: true,
},
});
module.exports = PickerIOS;

View File

@@ -0,0 +1,124 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ProgressBarAndroid
*/
'use strict';
const ColorPropType = require('ColorPropType');
const PropTypes = require('prop-types');
const React = require('React');
const ReactNative = require('ReactNative');
const ViewPropTypes = require('ViewPropTypes');
const requireNativeComponent = require('requireNativeComponent');
const STYLE_ATTRIBUTES = [
'Horizontal',
'Normal',
'Small',
'Large',
'Inverse',
'SmallInverse',
'LargeInverse',
];
const indeterminateType = function(props, propName, componentName, ...rest) {
const checker = function() {
const indeterminate = props[propName];
const styleAttr = props.styleAttr;
if (!indeterminate && styleAttr !== 'Horizontal') {
return new Error('indeterminate=false is only valid for styleAttr=Horizontal');
}
};
return PropTypes.bool(props, propName, componentName, ...rest) || checker();
};
/**
* React component that wraps the Android-only `ProgressBar`. This component is used to indicate
* that the app is loading or there is some activity in the app.
*
* Example:
*
* ```
* render: function() {
* var progressBar =
* <View style={styles.container}>
* <ProgressBar styleAttr="Inverse" />
* </View>;
* return (
* <MyLoadingComponent
* componentView={componentView}
* loadingView={progressBar}
* style={styles.loadingComponent}
* />
* );
* },
* ```
*/
class ProgressBarAndroid extends ReactNative.NativeComponent {
static propTypes = {
...ViewPropTypes,
/**
* Style of the ProgressBar. One of:
*
* - Horizontal
* - Normal (default)
* - Small
* - Large
* - Inverse
* - SmallInverse
* - LargeInverse
*/
styleAttr: PropTypes.oneOf(STYLE_ATTRIBUTES),
/**
* Whether to show the ProgressBar (true, the default) or hide it (false).
*/
animating: PropTypes.bool,
/**
* If the progress bar will show indeterminate progress. Note that this
* can only be false if styleAttr is Horizontal.
*/
indeterminate: indeterminateType,
/**
* The progress value (between 0 and 1).
*/
progress: PropTypes.number,
/**
* Color of the progress bar.
*/
color: ColorPropType,
/**
* Used to locate this view in end-to-end tests.
*/
testID: PropTypes.string,
};
static defaultProps = {
styleAttr: 'Normal',
indeterminate: true,
animating: true,
};
render() {
return <AndroidProgressBar {...this.props} />;
}
}
const AndroidProgressBar = requireNativeComponent(
'AndroidProgressBar',
ProgressBarAndroid,
{
nativeOnly: {
animating: true,
},
}
);
module.exports = ProgressBarAndroid;

View File

@@ -0,0 +1,11 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ProgressBarAndroid
*/
'use strict';
module.exports = require('UnimplementedView');

View File

@@ -0,0 +1,47 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ProgressViewIOS
*/
'use strict';
const React = require('React');
const StyleSheet = require('StyleSheet');
const Text = require('Text');
const View = require('View');
class DummyProgressViewIOS extends React.Component {
render() {
return (
<View style={[styles.dummy, this.props.style]}>
<Text style={styles.text}>
ProgressViewIOS is not supported on this platform!
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
dummy: {
width: 120,
height: 20,
backgroundColor: '#ffbcbc',
borderWidth: 1,
borderColor: 'red',
alignItems: 'center',
justifyContent: 'center',
},
text: {
color: '#333333',
margin: 5,
fontSize: 10,
}
});
module.exports = DummyProgressViewIOS;

View File

@@ -0,0 +1,83 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ProgressViewIOS
* @flow
*/
'use strict';
const Image = require('Image');
const NativeMethodsMixin = require('NativeMethodsMixin');
const React = require('React');
const PropTypes = require('prop-types');
const StyleSheet = require('StyleSheet');
const ViewPropTypes = require('ViewPropTypes');
const createReactClass = require('create-react-class');
const requireNativeComponent = require('requireNativeComponent');
/**
* Use `ProgressViewIOS` to render a UIProgressView on iOS.
*/
const ProgressViewIOS = createReactClass({
displayName: 'ProgressViewIOS',
mixins: [NativeMethodsMixin],
propTypes: {
...ViewPropTypes,
/**
* The progress bar style.
*/
progressViewStyle: PropTypes.oneOf(['default', 'bar']),
/**
* The progress value (between 0 and 1).
*/
progress: PropTypes.number,
/**
* The tint color of the progress bar itself.
*/
progressTintColor: PropTypes.string,
/**
* The tint color of the progress bar track.
*/
trackTintColor: PropTypes.string,
/**
* A stretchable image to display as the progress bar.
*/
progressImage: Image.propTypes.source,
/**
* A stretchable image to display behind the progress bar.
*/
trackImage: Image.propTypes.source,
},
render: function() {
return (
<RCTProgressView
{...this.props}
style={[styles.progressView, this.props.style]}
/>
);
}
});
const styles = StyleSheet.create({
progressView: {
height: 2,
},
});
const RCTProgressView = requireNativeComponent(
'RCTProgressView',
ProgressViewIOS
);
module.exports = ProgressViewIOS;

View File

@@ -0,0 +1,189 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule RefreshControl
* @flow
*/
'use strict';
const ColorPropType = require('ColorPropType');
const NativeMethodsMixin = require('NativeMethodsMixin');
const Platform = require('Platform');
const React = require('React');
const PropTypes = require('prop-types');
const ViewPropTypes = require('ViewPropTypes');
const createReactClass = require('create-react-class');
const requireNativeComponent = require('requireNativeComponent');
if (Platform.OS === 'android') {
const AndroidSwipeRefreshLayout =
require('UIManager').AndroidSwipeRefreshLayout;
var RefreshLayoutConsts = AndroidSwipeRefreshLayout
? AndroidSwipeRefreshLayout.Constants
: {SIZE: {}};
} else {
var RefreshLayoutConsts = {SIZE: {}};
}
/**
* This component is used inside a ScrollView or ListView to add pull to refresh
* functionality. When the ScrollView is at `scrollY: 0`, swiping down
* triggers an `onRefresh` event.
*
* ### Usage example
*
* ``` js
* class RefreshableList extends Component {
* constructor(props) {
* super(props);
* this.state = {
* refreshing: false,
* };
* }
*
* _onRefresh() {
* this.setState({refreshing: true});
* fetchData().then(() => {
* this.setState({refreshing: false});
* });
* }
*
* render() {
* return (
* <ListView
* refreshControl={
* <RefreshControl
* refreshing={this.state.refreshing}
* onRefresh={this._onRefresh.bind(this)}
* />
* }
* ...
* >
* ...
* </ListView>
* );
* }
* ...
* }
* ```
*
* __Note:__ `refreshing` is a controlled prop, this is why it needs to be set to true
* in the `onRefresh` function otherwise the refresh indicator will stop immediately.
*/
const RefreshControl = createReactClass({
displayName: 'RefreshControl',
statics: {
SIZE: RefreshLayoutConsts.SIZE,
},
mixins: [NativeMethodsMixin],
propTypes: {
...ViewPropTypes,
/**
* Called when the view starts refreshing.
*/
onRefresh: PropTypes.func,
/**
* Whether the view should be indicating an active refresh.
*/
refreshing: PropTypes.bool.isRequired,
/**
* The color of the refresh indicator.
* @platform ios
*/
tintColor: ColorPropType,
/**
* Title color.
* @platform ios
*/
titleColor: ColorPropType,
/**
* The title displayed under the refresh indicator.
* @platform ios
*/
title: PropTypes.string,
/**
* Whether the pull to refresh functionality is enabled.
* @platform android
*/
enabled: PropTypes.bool,
/**
* The colors (at least one) that will be used to draw the refresh indicator.
* @platform android
*/
colors: PropTypes.arrayOf(ColorPropType),
/**
* The background color of the refresh indicator.
* @platform android
*/
progressBackgroundColor: ColorPropType,
/**
* Size of the refresh indicator, see RefreshControl.SIZE.
* @platform android
*/
size: PropTypes.oneOf([RefreshLayoutConsts.SIZE.DEFAULT, RefreshLayoutConsts.SIZE.LARGE]),
/**
* Progress view top offset
* @platform android
*/
progressViewOffset: PropTypes.number,
},
_nativeRef: (null: any),
_lastNativeRefreshing: false,
componentDidMount() {
this._lastNativeRefreshing = this.props.refreshing;
},
componentDidUpdate(prevProps: {refreshing: boolean}) {
// RefreshControl is a controlled component so if the native refreshing
// value doesn't match the current js refreshing prop update it to
// the js value.
if (this.props.refreshing !== prevProps.refreshing) {
this._lastNativeRefreshing = this.props.refreshing;
} else if (this.props.refreshing !== this._lastNativeRefreshing) {
this._nativeRef.setNativeProps({refreshing: this.props.refreshing});
this._lastNativeRefreshing = this.props.refreshing;
}
},
render() {
return (
<NativeRefreshControl
{...this.props}
ref={ref => {this._nativeRef = ref;}}
onRefresh={this._onRefresh}
/>
);
},
_onRefresh() {
this._lastNativeRefreshing = true;
this.props.onRefresh && this.props.onRefresh();
// The native component will start refreshing so force an update to
// make sure it stays in sync with the js component.
this.forceUpdate();
},
});
if (Platform.OS === 'ios') {
var NativeRefreshControl = requireNativeComponent(
'RCTRefreshControl',
RefreshControl
);
} else if (Platform.OS === 'android') {
var NativeRefreshControl = requireNativeComponent(
'AndroidSwipeRefreshLayout',
RefreshControl
);
}
module.exports = RefreshControl;

View File

@@ -0,0 +1,27 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
'use strict';
const React = require('React');
const requireNativeComponent = require('requireNativeComponent');
const RCTRefreshControl = requireNativeComponent('RCTRefreshControl');
class RefreshControlMock extends React.Component<{}> {
static latestRef: ?RefreshControlMock;
componentDidMount() {
RefreshControlMock.latestRef = this;
}
render() {
return <RCTRefreshControl />;
}
}
module.exports = RefreshControlMock;

View File

@@ -0,0 +1,12 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule SafeAreaView
* @flow
*/
'use strict';
module.exports = require('View');

View File

@@ -0,0 +1,46 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule SafeAreaView
* @flow
* @format
*/
const React = require('React');
const ViewPropTypes = require('ViewPropTypes');
const requireNativeComponent = require('requireNativeComponent');
import type {ViewProps} from 'ViewPropTypes';
type Props = ViewProps & {
children: any,
};
/**
* Renders nested content and automatically applies paddings reflect the portion of the view
* that is not covered by navigation bars, tab bars, toolbars, and other ancestor views.
* Moreover, and most importantly, Safe Area's paddings reflect physical limitation of the screen,
* such as rounded corners or camera notches (aka sensor housing area on iPhone X).
*/
class SafeAreaView extends React.Component<Props> {
static propTypes = {
...ViewPropTypes,
};
render() {
return <RCTSafeAreaView {...this.props} />;
}
}
const RCTSafeAreaView = requireNativeComponent('RCTSafeAreaView', {
name: 'RCTSafeAreaView',
displayName: 'RCTSafeAreaView',
propTypes: {
...ViewPropTypes,
},
});
module.exports = SafeAreaView;

View File

@@ -0,0 +1,623 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ScrollResponder
* @flow
*/
'use strict';
const Dimensions = require('Dimensions');
const FrameRateLogger = require('FrameRateLogger');
const Keyboard = require('Keyboard');
const ReactNative = require('ReactNative');
const Subscribable = require('Subscribable');
const TextInputState = require('TextInputState');
const UIManager = require('UIManager');
const invariant = require('fbjs/lib/invariant');
const nullthrows = require('fbjs/lib/nullthrows');
const performanceNow = require('fbjs/lib/performanceNow');
const warning = require('fbjs/lib/warning');
const { ScrollViewManager } = require('NativeModules');
const { getInstanceFromNode } = require('ReactNativeComponentTree');
/**
* Mixin that can be integrated in order to handle scrolling that plays well
* with `ResponderEventPlugin`. Integrate with your platform specific scroll
* views, or even your custom built (every-frame animating) scroll views so that
* all of these systems play well with the `ResponderEventPlugin`.
*
* iOS scroll event timing nuances:
* ===============================
*
*
* Scrolling without bouncing, if you touch down:
* -------------------------------
*
* 1. `onMomentumScrollBegin` (when animation begins after letting up)
* ... physical touch starts ...
* 2. `onTouchStartCapture` (when you press down to stop the scroll)
* 3. `onTouchStart` (same, but bubble phase)
* 4. `onResponderRelease` (when lifting up - you could pause forever before * lifting)
* 5. `onMomentumScrollEnd`
*
*
* Scrolling with bouncing, if you touch down:
* -------------------------------
*
* 1. `onMomentumScrollBegin` (when animation begins after letting up)
* ... bounce begins ...
* ... some time elapses ...
* ... physical touch during bounce ...
* 2. `onMomentumScrollEnd` (Makes no sense why this occurs first during bounce)
* 3. `onTouchStartCapture` (immediately after `onMomentumScrollEnd`)
* 4. `onTouchStart` (same, but bubble phase)
* 5. `onTouchEnd` (You could hold the touch start for a long time)
* 6. `onMomentumScrollBegin` (When releasing the view starts bouncing back)
*
* So when we receive an `onTouchStart`, how can we tell if we are touching
* *during* an animation (which then causes the animation to stop)? The only way
* to tell is if the `touchStart` occurred immediately after the
* `onMomentumScrollEnd`.
*
* This is abstracted out for you, so you can just call this.scrollResponderIsAnimating() if
* necessary
*
* `ScrollResponder` also includes logic for blurring a currently focused input
* if one is focused while scrolling. The `ScrollResponder` is a natural place
* to put this logic since it can support not dismissing the keyboard while
* scrolling, unless a recognized "tap"-like gesture has occurred.
*
* The public lifecycle API includes events for keyboard interaction, responder
* interaction, and scrolling (among others). The keyboard callbacks
* `onKeyboardWill/Did/*` are *global* events, but are invoked on scroll
* responder's props so that you can guarantee that the scroll responder's
* internal state has been updated accordingly (and deterministically) by
* the time the props callbacks are invoke. Otherwise, you would always wonder
* if the scroll responder is currently in a state where it recognizes new
* keyboard positions etc. If coordinating scrolling with keyboard movement,
* *always* use these hooks instead of listening to your own global keyboard
* events.
*
* Public keyboard lifecycle API: (props callbacks)
*
* Standard Keyboard Appearance Sequence:
*
* this.props.onKeyboardWillShow
* this.props.onKeyboardDidShow
*
* `onScrollResponderKeyboardDismissed` will be invoked if an appropriate
* tap inside the scroll responder's scrollable region was responsible
* for the dismissal of the keyboard. There are other reasons why the
* keyboard could be dismissed.
*
* this.props.onScrollResponderKeyboardDismissed
*
* Standard Keyboard Hide Sequence:
*
* this.props.onKeyboardWillHide
* this.props.onKeyboardDidHide
*/
const IS_ANIMATING_TOUCH_START_THRESHOLD_MS = 16;
type State = {
isTouching: boolean,
lastMomentumScrollBeginTime: number,
lastMomentumScrollEndTime: number,
observedScrollSinceBecomingResponder: boolean,
becameResponderWhileAnimating: boolean,
};
type Event = Object;
function isTagInstanceOfTextInput(tag) {
const instance = getInstanceFromNode(tag);
return instance && instance.viewConfig && (
instance.viewConfig.uiViewClassName === 'AndroidTextInput' ||
instance.viewConfig.uiViewClassName === 'RCTMultilineTextInputView' ||
instance.viewConfig.uiViewClassName === 'RCTSinglelineTextInputView'
);
}
const ScrollResponderMixin = {
mixins: [Subscribable.Mixin],
scrollResponderMixinGetInitialState: function(): State {
return {
isTouching: false,
lastMomentumScrollBeginTime: 0,
lastMomentumScrollEndTime: 0,
// Reset to false every time becomes responder. This is used to:
// - Determine if the scroll view has been scrolled and therefore should
// refuse to give up its responder lock.
// - Determine if releasing should dismiss the keyboard when we are in
// tap-to-dismiss mode (this.props.keyboardShouldPersistTaps !== 'always').
observedScrollSinceBecomingResponder: false,
becameResponderWhileAnimating: false,
};
},
/**
* Invoke this from an `onScroll` event.
*/
scrollResponderHandleScrollShouldSetResponder: function(): boolean {
return this.state.isTouching;
},
/**
* Merely touch starting is not sufficient for a scroll view to become the
* responder. Being the "responder" means that the very next touch move/end
* event will result in an action/movement.
*
* Invoke this from an `onStartShouldSetResponder` event.
*
* `onStartShouldSetResponder` is used when the next move/end will trigger
* some UI movement/action, but when you want to yield priority to views
* nested inside of the view.
*
* There may be some cases where scroll views actually should return `true`
* from `onStartShouldSetResponder`: Any time we are detecting a standard tap
* that gives priority to nested views.
*
* - If a single tap on the scroll view triggers an action such as
* recentering a map style view yet wants to give priority to interaction
* views inside (such as dropped pins or labels), then we would return true
* from this method when there is a single touch.
*
* - Similar to the previous case, if a two finger "tap" should trigger a
* zoom, we would check the `touches` count, and if `>= 2`, we would return
* true.
*
*/
scrollResponderHandleStartShouldSetResponder: function(e: Event): boolean {
const currentlyFocusedTextInput = TextInputState.currentlyFocusedField();
if (this.props.keyboardShouldPersistTaps === 'handled' &&
currentlyFocusedTextInput != null &&
e.target !== currentlyFocusedTextInput) {
return true;
}
return false;
},
/**
* There are times when the scroll view wants to become the responder
* (meaning respond to the next immediate `touchStart/touchEnd`), in a way
* that *doesn't* give priority to nested views (hence the capture phase):
*
* - Currently animating.
* - Tapping anywhere that is not a text input, while the keyboard is
* up (which should dismiss the keyboard).
*
* Invoke this from an `onStartShouldSetResponderCapture` event.
*/
scrollResponderHandleStartShouldSetResponderCapture: function(e: Event): boolean {
// First see if we want to eat taps while the keyboard is up
const currentlyFocusedTextInput = TextInputState.currentlyFocusedField();
const {keyboardShouldPersistTaps} = this.props;
const keyboardNeverPersistTaps = !keyboardShouldPersistTaps ||
keyboardShouldPersistTaps === 'never';
if (keyboardNeverPersistTaps &&
currentlyFocusedTextInput != null &&
!isTagInstanceOfTextInput(e.target)) {
return true;
}
return this.scrollResponderIsAnimating();
},
/**
* Invoke this from an `onResponderReject` event.
*
* Some other element is not yielding its role as responder. Normally, we'd
* just disable the `UIScrollView`, but a touch has already began on it, the
* `UIScrollView` will not accept being disabled after that. The easiest
* solution for now is to accept the limitation of disallowing this
* altogether. To improve this, find a way to disable the `UIScrollView` after
* a touch has already started.
*/
scrollResponderHandleResponderReject: function() {
},
/**
* We will allow the scroll view to give up its lock iff it acquired the lock
* during an animation. This is a very useful default that happens to satisfy
* many common user experiences.
*
* - Stop a scroll on the left edge, then turn that into an outer view's
* backswipe.
* - Stop a scroll mid-bounce at the top, continue pulling to have the outer
* view dismiss.
* - However, without catching the scroll view mid-bounce (while it is
* motionless), if you drag far enough for the scroll view to become
* responder (and therefore drag the scroll view a bit), any backswipe
* navigation of a swipe gesture higher in the view hierarchy, should be
* rejected.
*/
scrollResponderHandleTerminationRequest: function(): boolean {
return !this.state.observedScrollSinceBecomingResponder;
},
/**
* Invoke this from an `onTouchEnd` event.
*
* @param {SyntheticEvent} e Event.
*/
scrollResponderHandleTouchEnd: function(e: Event) {
const nativeEvent = e.nativeEvent;
this.state.isTouching = nativeEvent.touches.length !== 0;
this.props.onTouchEnd && this.props.onTouchEnd(e);
},
/**
* Invoke this from an `onTouchCancel` event.
*
* @param {SyntheticEvent} e Event.
*/
scrollResponderHandleTouchCancel: function(e: Event) {
this.state.isTouching = false;
this.props.onTouchCancel && this.props.onTouchCancel(e);
},
/**
* Invoke this from an `onResponderRelease` event.
*/
scrollResponderHandleResponderRelease: function(e: Event) {
this.props.onResponderRelease && this.props.onResponderRelease(e);
// By default scroll views will unfocus a textField
// if another touch occurs outside of it
const currentlyFocusedTextInput = TextInputState.currentlyFocusedField();
if (this.props.keyboardShouldPersistTaps !== true &&
this.props.keyboardShouldPersistTaps !== 'always' &&
currentlyFocusedTextInput != null &&
e.target !== currentlyFocusedTextInput &&
!this.state.observedScrollSinceBecomingResponder &&
!this.state.becameResponderWhileAnimating) {
this.props.onScrollResponderKeyboardDismissed &&
this.props.onScrollResponderKeyboardDismissed(e);
TextInputState.blurTextInput(currentlyFocusedTextInput);
}
},
scrollResponderHandleScroll: function(e: Event) {
this.state.observedScrollSinceBecomingResponder = true;
this.props.onScroll && this.props.onScroll(e);
},
/**
* Invoke this from an `onResponderGrant` event.
*/
scrollResponderHandleResponderGrant: function(e: Event) {
this.state.observedScrollSinceBecomingResponder = false;
this.props.onResponderGrant && this.props.onResponderGrant(e);
this.state.becameResponderWhileAnimating = this.scrollResponderIsAnimating();
},
/**
* Unfortunately, `onScrollBeginDrag` also fires when *stopping* the scroll
* animation, and there's not an easy way to distinguish a drag vs. stopping
* momentum.
*
* Invoke this from an `onScrollBeginDrag` event.
*/
scrollResponderHandleScrollBeginDrag: function(e: Event) {
FrameRateLogger.beginScroll(); // TODO: track all scrolls after implementing onScrollEndAnimation
this.props.onScrollBeginDrag && this.props.onScrollBeginDrag(e);
},
/**
* Invoke this from an `onScrollEndDrag` event.
*/
scrollResponderHandleScrollEndDrag: function(e: Event) {
const {velocity} = e.nativeEvent;
// - If we are animating, then this is a "drag" that is stopping the scrollview and momentum end
// will fire.
// - If velocity is non-zero, then the interaction will stop when momentum scroll ends or
// another drag starts and ends.
// - If we don't get velocity, better to stop the interaction twice than not stop it.
if (!this.scrollResponderIsAnimating() &&
(!velocity || velocity.x === 0 && velocity.y === 0)) {
FrameRateLogger.endScroll();
}
this.props.onScrollEndDrag && this.props.onScrollEndDrag(e);
},
/**
* Invoke this from an `onMomentumScrollBegin` event.
*/
scrollResponderHandleMomentumScrollBegin: function(e: Event) {
this.state.lastMomentumScrollBeginTime = performanceNow();
this.props.onMomentumScrollBegin && this.props.onMomentumScrollBegin(e);
},
/**
* Invoke this from an `onMomentumScrollEnd` event.
*/
scrollResponderHandleMomentumScrollEnd: function(e: Event) {
FrameRateLogger.endScroll();
this.state.lastMomentumScrollEndTime = performanceNow();
this.props.onMomentumScrollEnd && this.props.onMomentumScrollEnd(e);
},
/**
* Invoke this from an `onTouchStart` event.
*
* Since we know that the `SimpleEventPlugin` occurs later in the plugin
* order, after `ResponderEventPlugin`, we can detect that we were *not*
* permitted to be the responder (presumably because a contained view became
* responder). The `onResponderReject` won't fire in that case - it only
* fires when a *current* responder rejects our request.
*
* @param {SyntheticEvent} e Touch Start event.
*/
scrollResponderHandleTouchStart: function(e: Event) {
this.state.isTouching = true;
this.props.onTouchStart && this.props.onTouchStart(e);
},
/**
* Invoke this from an `onTouchMove` event.
*
* Since we know that the `SimpleEventPlugin` occurs later in the plugin
* order, after `ResponderEventPlugin`, we can detect that we were *not*
* permitted to be the responder (presumably because a contained view became
* responder). The `onResponderReject` won't fire in that case - it only
* fires when a *current* responder rejects our request.
*
* @param {SyntheticEvent} e Touch Start event.
*/
scrollResponderHandleTouchMove: function(e: Event) {
this.props.onTouchMove && this.props.onTouchMove(e);
},
/**
* A helper function for this class that lets us quickly determine if the
* view is currently animating. This is particularly useful to know when
* a touch has just started or ended.
*/
scrollResponderIsAnimating: function(): boolean {
const now = performanceNow();
const timeSinceLastMomentumScrollEnd = now - this.state.lastMomentumScrollEndTime;
const isAnimating = timeSinceLastMomentumScrollEnd < IS_ANIMATING_TOUCH_START_THRESHOLD_MS ||
this.state.lastMomentumScrollEndTime < this.state.lastMomentumScrollBeginTime;
return isAnimating;
},
/**
* Returns the node that represents native view that can be scrolled.
* Components can pass what node to use by defining a `getScrollableNode`
* function otherwise `this` is used.
*/
scrollResponderGetScrollableNode: function(): any {
return this.getScrollableNode ?
this.getScrollableNode() :
ReactNative.findNodeHandle(this);
},
/**
* A helper function to scroll to a specific point in the ScrollView.
* This is currently used to help focus child TextViews, but can also
* be used to quickly scroll to any element we want to focus. Syntax:
*
* `scrollResponderScrollTo(options: {x: number = 0; y: number = 0; animated: boolean = true})`
*
* Note: The weird argument signature is due to the fact that, for historical reasons,
* the function also accepts separate arguments as as alternative to the options object.
* This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED.
*/
scrollResponderScrollTo: function(
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.');
} else {
({x, y, animated} = x || {});
}
UIManager.dispatchViewManagerCommand(
nullthrows(this.scrollResponderGetScrollableNode()),
UIManager.RCTScrollView.Commands.scrollTo,
[x || 0, y || 0, animated !== false],
);
},
/**
* Scrolls to the end of the ScrollView, either immediately or with a smooth
* animation.
*
* Example:
*
* `scrollResponderScrollToEnd({animated: true})`
*/
scrollResponderScrollToEnd: function(
options?: { animated?: boolean },
) {
// Default to true
const animated = (options && options.animated) !== false;
UIManager.dispatchViewManagerCommand(
this.scrollResponderGetScrollableNode(),
UIManager.RCTScrollView.Commands.scrollToEnd,
[animated],
);
},
/**
* 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});
},
/**
* A helper function to zoom to a specific rect in the scrollview. The argument has the shape
* {x: number; y: number; width: number; height: number; animated: boolean = true}
*
* @platform ios
*/
scrollResponderZoomTo: function(
rect: {| x: number, y: number, width: number, height: number, animated?: boolean |},
animated?: boolean // deprecated, put this inside the rect argument instead
) {
invariant(ScrollViewManager && ScrollViewManager.zoomToRect, 'zoomToRect is not implemented');
if ('animated' in rect) {
animated = rect.animated;
delete rect.animated;
} else if (typeof animated !== 'undefined') {
console.warn('`scrollResponderZoomTo` `animated` argument is deprecated. Use `options.animated` instead');
}
ScrollViewManager.zoomToRect(this.scrollResponderGetScrollableNode(), rect, animated !== false);
},
/**
* Displays the scroll indicators momentarily.
*/
scrollResponderFlashScrollIndicators: function() {
UIManager.dispatchViewManagerCommand(
this.scrollResponderGetScrollableNode(),
UIManager.RCTScrollView.Commands.flashScrollIndicators,
[]
);
},
/**
* This method should be used as the callback to onFocus in a TextInputs'
* parent view. Note that any module using this mixin needs to return
* the parent view's ref in getScrollViewRef() in order to use this method.
* @param {any} nodeHandle The TextInput node handle
* @param {number} additionalOffset The scroll view's bottom "contentInset".
* Default is 0.
* @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) {
this.additionalScrollOffset = additionalOffset || 0;
this.preventNegativeScrollOffset = !!preventNegativeScrollOffset;
UIManager.measureLayout(
nodeHandle,
ReactNative.findNodeHandle(this.getInnerViewNode()),
this.scrollResponderTextInputFocusError,
this.scrollResponderInputMeasureAndScrollToKeyboard
);
},
/**
* The calculations performed here assume the scroll view takes up the entire
* screen - even if has some content inset. We then measure the offsets of the
* keyboard, and compensate both for the scroll view's "contentInset".
*
* @param {number} left Position of input w.r.t. table view.
* @param {number} top Position of input w.r.t. table view.
* @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) {
let keyboardScreenY = Dimensions.get('window').height;
if (this.keyboardWillOpenTo) {
keyboardScreenY = this.keyboardWillOpenTo.endCoordinates.screenY;
}
let scrollOffsetY = top - keyboardScreenY + height + this.additionalScrollOffset;
// By default, this can scroll with negative offset, pulling the content
// down so that the target component's bottom meets the keyboard's top.
// If requested otherwise, cap the offset at 0 minimum to avoid content
// shifting down.
if (this.preventNegativeScrollOffset) {
scrollOffsetY = Math.max(0, scrollOffsetY);
}
this.scrollResponderScrollTo({x: 0, y: scrollOffsetY, animated: true});
this.additionalOffset = 0;
this.preventNegativeScrollOffset = false;
},
scrollResponderTextInputFocusError: function(e: Event) {
console.error('Error measuring text field: ', e);
},
/**
* `componentWillMount` is the closest thing to a standard "constructor" for
* React components.
*
* The `keyboardWillShow` is called before input focus.
*/
UNSAFE_componentWillMount: function() {
const {keyboardShouldPersistTaps} = this.props;
warning(
typeof keyboardShouldPersistTaps !== 'boolean',
`'keyboardShouldPersistTaps={${keyboardShouldPersistTaps}}' is deprecated. `
+ `Use 'keyboardShouldPersistTaps="${keyboardShouldPersistTaps ? 'always' : 'never'}"' instead`
);
this.keyboardWillOpenTo = null;
this.additionalScrollOffset = 0;
this.addListenerOn(Keyboard, 'keyboardWillShow', this.scrollResponderKeyboardWillShow);
this.addListenerOn(Keyboard, 'keyboardWillHide', this.scrollResponderKeyboardWillHide);
this.addListenerOn(Keyboard, 'keyboardDidShow', this.scrollResponderKeyboardDidShow);
this.addListenerOn(Keyboard, 'keyboardDidHide', this.scrollResponderKeyboardDidHide);
},
/**
* Warning, this may be called several times for a single keyboard opening.
* It's best to store the information in this method and then take any action
* at a later point (either in `keyboardDidShow` or other).
*
* Here's the order that events occur in:
* - focus
* - willShow {startCoordinates, endCoordinates} several times
* - didShow several times
* - blur
* - willHide {startCoordinates, endCoordinates} several times
* - didHide several times
*
* The `ScrollResponder` providesModule callbacks for each of these events.
* Even though any user could have easily listened to keyboard events
* themselves, using these `props` callbacks ensures that ordering of events
* is consistent - and not dependent on the order that the keyboard events are
* subscribed to. This matters when telling the scroll view to scroll to where
* the keyboard is headed - the scroll responder better have been notified of
* the keyboard destination before being instructed to scroll to where the
* keyboard will be. Stick to the `ScrollResponder` callbacks, and everything
* will work.
*
* WARNING: These callbacks will fire even if a keyboard is displayed in a
* different navigation pane. Filter out the events to determine if they are
* relevant to you. (For example, only if you receive these callbacks after
* you had explicitly focused a node etc).
*/
scrollResponderKeyboardWillShow: function(e: Event) {
this.keyboardWillOpenTo = e;
this.props.onKeyboardWillShow && this.props.onKeyboardWillShow(e);
},
scrollResponderKeyboardWillHide: function(e: Event) {
this.keyboardWillOpenTo = null;
this.props.onKeyboardWillHide && this.props.onKeyboardWillHide(e);
},
scrollResponderKeyboardDidShow: function(e: Event) {
// TODO(7693961): The event for DidShow is not available on iOS yet.
// Use the one from WillShow and do not assign.
if (e) {
this.keyboardWillOpenTo = e;
}
this.props.onKeyboardDidShow && this.props.onKeyboardDidShow(e);
},
scrollResponderKeyboardDidHide: function(e: Event) {
this.keyboardWillOpenTo = null;
this.props.onKeyboardDidHide && this.props.onKeyboardDidHide(e);
}
};
const ScrollResponder = {
Mixin: ScrollResponderMixin,
};
module.exports = ScrollResponder;

View File

@@ -0,0 +1,965 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ScrollView
* @flow
*/
'use strict';
const AnimatedImplementation = require('AnimatedImplementation');
const ColorPropType = require('ColorPropType');
const EdgeInsetsPropType = require('EdgeInsetsPropType');
const Platform = require('Platform');
const PointPropType = require('PointPropType');
const PropTypes = require('prop-types');
const React = require('React');
const ReactNative = require('ReactNative');
const ScrollResponder = require('ScrollResponder');
const ScrollViewStickyHeader = require('ScrollViewStickyHeader');
const StyleSheet = require('StyleSheet');
const StyleSheetPropType = require('StyleSheetPropType');
const View = require('View');
const ViewPropTypes = require('ViewPropTypes');
const ViewStylePropTypes = require('ViewStylePropTypes');
const createReactClass = require('create-react-class');
const dismissKeyboard = require('dismissKeyboard');
const flattenStyle = require('flattenStyle');
const invariant = require('fbjs/lib/invariant');
const processDecelerationRate = require('processDecelerationRate');
const requireNativeComponent = require('requireNativeComponent');
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */
const warning = require('fbjs/lib/warning');
const resolveAssetSource = require('resolveAssetSource');
import type {NativeMethodsMixinType} from 'ReactNativeTypes';
/**
* Component that wraps platform ScrollView while providing
* integration with touch locking "responder" system.
*
* Keep in mind that ScrollViews must have a bounded height in order to work,
* since they contain unbounded-height children into a bounded container (via
* a scroll interaction). In order to bound the height of a ScrollView, either
* set the height of the view directly (discouraged) or make sure all parent
* views have bounded height. Forgetting to transfer `{flex: 1}` down the
* view stack can lead to errors here, which the element inspector makes
* easy to debug.
*
* Doesn't yet support other contained responders from blocking this scroll
* view from becoming the responder.
*
*
* `<ScrollView>` vs [`<FlatList>`](/react-native/docs/flatlist.html) - which one to use?
*
* `ScrollView` simply renders all its react child components at once. That
* makes it very easy to understand and use.
*
* On the other hand, this has a performance downside. Imagine you have a very
* long list of items you want to display, maybe several screens worth of
* content. Creating JS components and native views for everything all at once,
* much of which may not even be shown, will contribute to slow rendering and
* increased memory usage.
*
* This is where `FlatList` comes into play. `FlatList` renders items lazily,
* just when they are about to appear, and removes items that scroll way off
* screen to save memory and processing time.
*
* `FlatList` is also handy if you want to render separators between your items,
* multiple columns, infinite scroll loading, or any number of other features it
* supports out of the box.
*/
// $FlowFixMe(>=0.41.0)
const ScrollView = createReactClass({
displayName: 'ScrollView',
propTypes: {
...ViewPropTypes,
/**
* Controls whether iOS should automatically adjust the content inset
* for scroll views that are placed behind a navigation bar or
* tab bar/ toolbar. The default value is true.
* @platform ios
*/
automaticallyAdjustContentInsets: PropTypes.bool,
/**
* The amount by which the scroll view content is inset from the edges
* of the scroll view. Defaults to `{top: 0, left: 0, bottom: 0, right: 0}`.
* @platform ios
*/
contentInset: EdgeInsetsPropType,
/**
* Used to manually set the starting scroll offset.
* The default value is `{x: 0, y: 0}`.
* @platform ios
*/
contentOffset: PointPropType,
/**
* When true, the scroll view bounces when it reaches the end of the
* content if the content is larger then the scroll view along the axis of
* the scroll direction. When false, it disables all bouncing even if
* the `alwaysBounce*` props are true. The default value is true.
* @platform ios
*/
bounces: PropTypes.bool,
/**
* When true, gestures can drive zoom past min/max and the zoom will animate
* to the min/max value at gesture end, otherwise the zoom will not exceed
* the limits.
* @platform ios
*/
bouncesZoom: PropTypes.bool,
/**
* When true, the scroll view bounces horizontally when it reaches the end
* even if the content is smaller than the scroll view itself. The default
* value is true when `horizontal={true}` and false otherwise.
* @platform ios
*/
alwaysBounceHorizontal: PropTypes.bool,
/**
* When true, the scroll view bounces vertically when it reaches the end
* even if the content is smaller than the scroll view itself. The default
* value is false when `horizontal={true}` and true otherwise.
* @platform ios
*/
alwaysBounceVertical: PropTypes.bool,
/**
* When true, the scroll view automatically centers the content when the
* content is smaller than the scroll view bounds; when the content is
* larger than the scroll view, this property has no effect. The default
* value is false.
* @platform ios
*/
centerContent: PropTypes.bool,
/**
* These styles will be applied to the scroll view content container which
* wraps all of the child views. Example:
*
* ```
* return (
* <ScrollView contentContainerStyle={styles.contentContainer}>
* </ScrollView>
* );
* ...
* const styles = StyleSheet.create({
* contentContainer: {
* paddingVertical: 20
* }
* });
* ```
*/
contentContainerStyle: StyleSheetPropType(ViewStylePropTypes),
/**
* A floating-point number that determines how quickly the scroll view
* decelerates after the user lifts their finger. You may also use string
* shortcuts `"normal"` and `"fast"` which match the underlying iOS settings
* for `UIScrollViewDecelerationRateNormal` and
* `UIScrollViewDecelerationRateFast` respectively.
*
* - `'normal'`: 0.998 (the default)
* - `'fast'`: 0.99
*
* @platform ios
*/
decelerationRate: PropTypes.oneOfType([
PropTypes.oneOf(['fast', 'normal']),
PropTypes.number,
]),
/**
* When true, the scroll view's children are arranged horizontally in a row
* instead of vertically in a column. The default value is false.
*/
horizontal: PropTypes.bool,
/**
* The style of the scroll indicators.
*
* - `'default'` (the default), same as `black`.
* - `'black'`, scroll indicator is black. This style is good against a light background.
* - `'white'`, scroll indicator is white. This style is good against a dark background.
*
* @platform ios
*/
indicatorStyle: PropTypes.oneOf([
'default', // default
'black',
'white',
]),
/**
* If sticky headers should stick at the bottom instead of the top of the
* ScrollView. This is usually used with inverted ScrollViews.
*/
invertStickyHeaders: PropTypes.bool,
/**
* When true, the ScrollView will try to lock to only vertical or horizontal
* scrolling while dragging. The default value is false.
* @platform ios
*/
directionalLockEnabled: PropTypes.bool,
/**
* When false, once tracking starts, won't try to drag if the touch moves.
* The default value is true.
* @platform ios
*/
canCancelContentTouches: PropTypes.bool,
/**
* Determines whether the keyboard gets dismissed in response to a drag.
*
* *Cross platform*
*
* - `'none'` (the default), drags do not dismiss the keyboard.
* - `'on-drag'`, the keyboard is dismissed when a drag begins.
*
* *iOS Only*
*
* - `'interactive'`, the keyboard is dismissed interactively with the drag and moves in
* synchrony with the touch; dragging upwards cancels the dismissal.
* On android this is not supported and it will have the same behavior as 'none'.
*/
keyboardDismissMode: PropTypes.oneOf([
'none', // default
'on-drag', // Cross-platform
'interactive', // iOS-only
]),
/**
* Determines when the keyboard should stay visible after a tap.
*
* - `'never'` (the default), tapping outside of the focused text input when the keyboard
* is up dismisses the keyboard. When this happens, children won't receive the tap.
* - `'always'`, the keyboard will not dismiss automatically, and the scroll view will not
* catch taps, but children of the scroll view can catch taps.
* - `'handled'`, the keyboard will not dismiss automatically when the tap was handled by
* a children, (or captured by an ancestor).
* - `false`, deprecated, use 'never' instead
* - `true`, deprecated, use 'always' instead
*/
keyboardShouldPersistTaps: PropTypes.oneOf(['always', 'never', 'handled', false, true]),
/**
* When set, the scroll view will adjust the scroll position so that the first child that is
* currently visible and at or beyond `minIndexForVisible` will not change position. This is
* useful for lists that are loading content in both directions, e.g. a chat thread, where new
* messages coming in might otherwise cause the scroll position to jump. A value of 0 is common,
* but other values such as 1 can be used to skip loading spinners or other content that should
* not maintain position.
*
* The optional `autoscrollToTopThreshold` can be used to make the content automatically scroll
* to the top after making the adjustment if the user was within the threshold of the top before
* the adjustment was made. This is also useful for chat-like applications where you want to see
* new messages scroll into place, but not if the user has scrolled up a ways and it would be
* disruptive to scroll a bunch.
*
* Caveat 1: Reordering elements in the scrollview with this enabled will probably cause
* jumpiness and jank. It can be fixed, but there are currently no plans to do so. For now,
* don't re-order the content of any ScrollViews or Lists that use this feature.
*
* Caveat 2: This simply uses `contentOffset` and `frame.origin` in native code to compute
* visibility. Occlusion, transforms, and other complexity won't be taken into account as to
* whether content is "visible" or not.
*
* @platform ios
*/
maintainVisibleContentPosition: PropTypes.shape({
minIndexForVisible: PropTypes.number.isRequired,
autoscrollToTopThreshold: PropTypes.number,
}),
/**
* The maximum allowed zoom scale. The default value is 1.0.
* @platform ios
*/
maximumZoomScale: PropTypes.number,
/**
* The minimum allowed zoom scale. The default value is 1.0.
* @platform ios
*/
minimumZoomScale: PropTypes.number,
/**
* Called when the momentum scroll starts (scroll which occurs as the ScrollView glides to a stop).
*/
onMomentumScrollBegin: PropTypes.func,
/**
* Called when the momentum scroll ends (scroll which occurs as the ScrollView glides to a stop).
*/
onMomentumScrollEnd: PropTypes.func,
/**
* Fires at most once per frame during scrolling. The frequency of the
* events can be controlled using the `scrollEventThrottle` prop.
*/
onScroll: PropTypes.func,
/**
* Called when the user begins to drag the scroll view.
*/
onScrollBeginDrag: PropTypes.func,
/**
* Called when the user stops dragging the scroll view and it either stops
* or begins to glide.
*/
onScrollEndDrag: PropTypes.func,
/**
* Called when scrollable content view of the ScrollView changes.
*
* Handler function is passed the content width and content height as parameters:
* `(contentWidth, contentHeight)`
*
* It's implemented using onLayout handler attached to the content container
* which this ScrollView renders.
*/
onContentSizeChange: PropTypes.func,
/**
* When true, the scroll view stops on multiples of the scroll view's size
* when scrolling. This can be used for horizontal pagination. The default
* value is false.
*
* Note: Vertical pagination is not supported on Android.
*/
pagingEnabled: PropTypes.bool,
/**
* When true, ScrollView allows use of pinch gestures to zoom in and out.
* The default value is true.
* @platform ios
*/
pinchGestureEnabled: PropTypes.bool,
/**
* When false, the view cannot be scrolled via touch interaction.
* The default value is true.
*
* Note that the view can always be scrolled by calling `scrollTo`.
*/
scrollEnabled: PropTypes.bool,
/**
* This controls how often the scroll event will be fired while scrolling
* (as a time interval in ms). A lower number yields better accuracy for code
* that is tracking the scroll position, but can lead to scroll performance
* problems due to the volume of information being send over the bridge.
* You will not notice a difference between values set between 1-16 as the
* JS run loop is synced to the screen refresh rate. If you do not need precise
* scroll position tracking, set this value higher to limit the information
* being sent across the bridge. The default value is zero, which results in
* the scroll event being sent only once each time the view is scrolled.
* @platform ios
*/
scrollEventThrottle: PropTypes.number,
/**
* The amount by which the scroll view indicators are inset from the edges
* of the scroll view. This should normally be set to the same value as
* the `contentInset`. Defaults to `{0, 0, 0, 0}`.
* @platform ios
*/
scrollIndicatorInsets: EdgeInsetsPropType,
/**
* When true, the scroll view scrolls to top when the status bar is tapped.
* The default value is true.
* @platform ios
*/
scrollsToTop: PropTypes.bool,
/**
* When true, shows a horizontal scroll indicator.
* The default value is true.
*/
showsHorizontalScrollIndicator: PropTypes.bool,
/**
* When true, shows a vertical scroll indicator.
* The default value is true.
*/
showsVerticalScrollIndicator: PropTypes.bool,
/**
* An array of child indices determining which children get docked to the
* top of the screen when scrolling. For example, passing
* `stickyHeaderIndices={[0]}` will cause the first child to be fixed to the
* top of the scroll view. This property is not supported in conjunction
* with `horizontal={true}`.
*/
stickyHeaderIndices: PropTypes.arrayOf(PropTypes.number),
/**
* When set, causes the scroll view to stop at multiples of the value of
* `snapToInterval`. This can be used for paginating through children
* that have lengths smaller than the scroll view. Typically used in
* combination with `snapToAlignment` and `decelerationRate="fast"` on ios.
* Overrides less configurable `pagingEnabled` prop.
*
* Supported for horizontal scrollview on android.
*/
snapToInterval: PropTypes.number,
/**
* When `snapToInterval` is set, `snapToAlignment` will define the relationship
* of the snapping to the scroll view.
*
* - `'start'` (the default) will align the snap at the left (horizontal) or top (vertical)
* - `'center'` will align the snap in the center
* - `'end'` will align the snap at the right (horizontal) or bottom (vertical)
*
* @platform ios
*/
snapToAlignment: PropTypes.oneOf([
'start', // default
'center',
'end',
]),
/**
* Experimental: When true, offscreen child views (whose `overflow` value is
* `hidden`) are removed from their native backing superview when offscreen.
* This can improve scrolling performance on long lists. The default value is
* true.
*/
removeClippedSubviews: PropTypes.bool,
/**
* The current scale of the scroll view content. The default value is 1.0.
* @platform ios
*/
zoomScale: PropTypes.number,
/**
* This property specifies how the safe area insets are used to modify the
* content area of the scroll view. The default value of this property is
* "never". Available on iOS 11 and later.
* @platform ios
*/
contentInsetAdjustmentBehavior: PropTypes.oneOf([
'automatic',
'scrollableAxes',
'never', // default
'always',
]),
/**
* A RefreshControl component, used to provide pull-to-refresh
* functionality for the ScrollView. Only works for vertical ScrollViews
* (`horizontal` prop must be `false`).
*
* See [RefreshControl](docs/refreshcontrol.html).
*/
refreshControl: PropTypes.element,
/**
* Sometimes a scrollview takes up more space than its content fills. When this is
* the case, this prop will fill the rest of the scrollview with a color to avoid setting
* a background and creating unnecessary overdraw. This is an advanced optimization
* that is not needed in the general case.
* @platform android
*/
endFillColor: ColorPropType,
/**
* Tag used to log scroll performance on this scroll view. Will force
* momentum events to be turned on (see sendMomentumEvents). This doesn't do
* anything out of the box and you need to implement a custom native
* FpsListener for it to be useful.
* @platform android
*/
scrollPerfTag: PropTypes.string,
/**
* Used to override default value of overScroll mode.
*
* Possible values:
*
* - `'auto'` - Default value, allow a user to over-scroll
* this view only if the content is large enough to meaningfully scroll.
* - `'always'` - Always allow a user to over-scroll this view.
* - `'never'` - Never allow a user to over-scroll this view.
*
* @platform android
*/
overScrollMode: PropTypes.oneOf([
'auto',
'always',
'never',
]),
/**
* When true, ScrollView will emit updateChildFrames data in scroll events,
* otherwise will not compute or emit child frame data. This only exists
* to support legacy issues, `onLayout` should be used instead to retrieve
* frame data.
* The default value is false.
* @platform ios
*/
DEPRECATED_sendUpdatedChildFrames: PropTypes.bool,
/**
* Optionally an image can be used for the scroll bar thumb. This will
* override the color. While the image is loading or the image fails to
* load the color will be used instead. Use an alpha of 0 in the color
* to avoid seeing it while the image is loading.
*
* - `uri` - a string representing the resource identifier for the image, which
* should be either a local file path or the name of a static image resource
* - `number` - Opaque type returned by something like
* `import IMAGE from './image.jpg'`.
* @platform vr
*/
scrollBarThumbImage: PropTypes.oneOfType([
PropTypes.shape({
uri: PropTypes.string,
}),
// Opaque type returned by import IMAGE from './image.jpg'
PropTypes.number,
]),
},
mixins: [ScrollResponder.Mixin],
_scrollAnimatedValue: (new AnimatedImplementation.Value(0): AnimatedImplementation.Value),
_scrollAnimatedValueAttachment: (null: ?{detach: () => void}),
_stickyHeaderRefs: (new Map(): Map<number, ScrollViewStickyHeader>),
_headerLayoutYs: (new Map(): Map<string, number>),
getInitialState: function() {
return {
...this.scrollResponderMixinGetInitialState(),
layoutHeight: null,
};
},
UNSAFE_componentWillMount: function() {
this._scrollAnimatedValue = new AnimatedImplementation.Value(this.props.contentOffset ? this.props.contentOffset.y : 0);
this._scrollAnimatedValue.setOffset(this.props.contentInset ? this.props.contentInset.top : 0);
this._stickyHeaderRefs = new Map();
this._headerLayoutYs = new Map();
},
componentDidMount: function() {
this._updateAnimatedNodeAttachment();
},
componentDidUpdate: function() {
this._updateAnimatedNodeAttachment();
},
componentWillUnmount: function() {
if (this._scrollAnimatedValueAttachment) {
this._scrollAnimatedValueAttachment.detach();
}
},
setNativeProps: function(props: Object) {
this._scrollViewRef && this._scrollViewRef.setNativeProps(props);
},
/**
* Returns a reference to the underlying scroll responder, which supports
* operations like `scrollTo`. All ScrollView-like components should
* implement this method so that they can be composed while providing access
* to the underlying scroll responder's methods.
*/
getScrollResponder: function(): ScrollView {
return this;
},
getScrollableNode: function(): any {
return ReactNative.findNodeHandle(this._scrollViewRef);
},
getInnerViewNode: function(): any {
return ReactNative.findNodeHandle(this._innerViewRef);
},
/**
* Scrolls to a given x, y offset, either immediately or with a smooth animation.
*
* Example:
*
* `scrollTo({x: 0, y: 0, animated: true})`
*
* Note: The weird function signature is due to the fact that, for historical reasons,
* the function also accepts separate arguments as an alternative to the options object.
* This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED.
*/
scrollTo: function(
y?: number | { x?: number, y?: number, animated?: boolean },
x?: number,
animated?: boolean
) {
if (typeof y === 'number') {
console.warn('`scrollTo(y, x, animated)` is deprecated. Use `scrollTo({x: 5, y: 5, ' +
'animated: true})` instead.');
} else {
({x, y, animated} = y || {});
}
this.getScrollResponder().scrollResponderScrollTo(
{x: x || 0, y: y || 0, animated: animated !== false}
);
},
/**
* If this is a vertical ScrollView scrolls to the bottom.
* If this is a horizontal ScrollView scrolls to the right.
*
* Use `scrollToEnd({animated: true})` for smooth animated scrolling,
* `scrollToEnd({animated: false})` for immediate scrolling.
* If no options are passed, `animated` defaults to true.
*/
scrollToEnd: function(
options?: { animated?: boolean },
) {
// Default to true
const animated = (options && options.animated) !== false;
this.getScrollResponder().scrollResponderScrollToEnd({
animated: animated,
});
},
/**
* Deprecated, use `scrollTo` instead.
*/
scrollWithoutAnimationTo: function(y: number = 0, x: number = 0) {
console.warn('`scrollWithoutAnimationTo` is deprecated. Use `scrollTo` instead');
this.scrollTo({x, y, animated: false});
},
/**
* Displays the scroll indicators momentarily.
*
* @platform ios
*/
flashScrollIndicators: function() {
this.getScrollResponder().scrollResponderFlashScrollIndicators();
},
_getKeyForIndex: function(index, childArray) {
const child = childArray[index];
return child && child.key;
},
_updateAnimatedNodeAttachment: function() {
if (this._scrollAnimatedValueAttachment) {
this._scrollAnimatedValueAttachment.detach();
}
if (this.props.stickyHeaderIndices && this.props.stickyHeaderIndices.length > 0) {
this._scrollAnimatedValueAttachment = AnimatedImplementation.attachNativeEvent(
this._scrollViewRef,
'onScroll',
[{nativeEvent: {contentOffset: {y: this._scrollAnimatedValue}}}]
);
}
},
_setStickyHeaderRef: function(key, ref) {
if (ref) {
this._stickyHeaderRefs.set(key, ref);
} else {
this._stickyHeaderRefs.delete(key);
}
},
_onStickyHeaderLayout: function(index, event, key) {
if (!this.props.stickyHeaderIndices) {
return;
}
const childArray = React.Children.toArray(this.props.children);
if (key !== this._getKeyForIndex(index, childArray)) {
// ignore stale layout update
return;
}
const layoutY = event.nativeEvent.layout.y;
this._headerLayoutYs.set(key, layoutY);
const indexOfIndex = this.props.stickyHeaderIndices.indexOf(index);
const previousHeaderIndex = this.props.stickyHeaderIndices[indexOfIndex - 1];
if (previousHeaderIndex != null) {
const previousHeader = this._stickyHeaderRefs.get(
this._getKeyForIndex(previousHeaderIndex, childArray)
);
previousHeader && previousHeader.setNextHeaderY(layoutY);
}
},
_handleScroll: function(e: Object) {
if (__DEV__) {
if (this.props.onScroll && this.props.scrollEventThrottle == null && Platform.OS === 'ios') {
console.log(
'You specified `onScroll` on a <ScrollView> 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.'
);
}
}
if (Platform.OS === 'android') {
if (this.props.keyboardDismissMode === 'on-drag') {
dismissKeyboard();
}
}
this.scrollResponderHandleScroll(e);
},
_handleLayout: function(e: Object) {
if (this.props.invertStickyHeaders) {
this.setState({ layoutHeight: e.nativeEvent.layout.height });
}
if (this.props.onLayout) {
this.props.onLayout(e);
}
},
_handleContentOnLayout: function(e: Object) {
const {width, height} = e.nativeEvent.layout;
this.props.onContentSizeChange && this.props.onContentSizeChange(width, height);
},
_scrollViewRef: (null: ?ScrollView),
_setScrollViewRef: function(ref: ?ScrollView) {
this._scrollViewRef = ref;
},
_innerViewRef: (null: ?NativeMethodsMixinType),
_setInnerViewRef: function(ref: ?NativeMethodsMixinType) {
this._innerViewRef = ref;
},
render: function() {
let ScrollViewClass;
let ScrollContentContainerViewClass;
if (Platform.OS === 'android') {
if (this.props.horizontal) {
ScrollViewClass = AndroidHorizontalScrollView;
ScrollContentContainerViewClass = AndroidHorizontalScrollContentView;
} else {
ScrollViewClass = AndroidScrollView;
ScrollContentContainerViewClass = View;
}
} else {
ScrollViewClass = RCTScrollView;
ScrollContentContainerViewClass = RCTScrollContentView;
warning(
!this.props.snapToInterval || !this.props.pagingEnabled,
'snapToInterval is currently ignored when pagingEnabled is true.'
);
}
invariant(
ScrollViewClass !== undefined,
'ScrollViewClass must not be undefined'
);
invariant(
ScrollContentContainerViewClass !== undefined,
'ScrollContentContainerViewClass must not be undefined'
);
const contentContainerStyle = [
this.props.horizontal && styles.contentContainerHorizontal,
this.props.contentContainerStyle,
];
let style, childLayoutProps;
if (__DEV__ && this.props.style) {
style = flattenStyle(this.props.style);
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.'
);
}
let contentSizeChangeProps = {};
if (this.props.onContentSizeChange) {
contentSizeChangeProps = {
onLayout: this._handleContentOnLayout,
};
}
const {stickyHeaderIndices} = this.props;
const hasStickyHeaders = stickyHeaderIndices && stickyHeaderIndices.length > 0;
const childArray = hasStickyHeaders && React.Children.toArray(this.props.children);
const children = hasStickyHeaders ?
childArray.map((child, index) => {
const indexOfIndex = child ? stickyHeaderIndices.indexOf(index) : -1;
if (indexOfIndex > -1) {
const key = child.key;
const nextIndex = stickyHeaderIndices[indexOfIndex + 1];
return (
<ScrollViewStickyHeader
key={key}
ref={(ref) => this._setStickyHeaderRef(key, ref)}
nextHeaderLayoutY={
this._headerLayoutYs.get(this._getKeyForIndex(nextIndex, childArray))
}
onLayout={(event) => this._onStickyHeaderLayout(index, event, key)}
scrollAnimatedValue={this._scrollAnimatedValue}
inverted={this.props.invertStickyHeaders}
scrollViewHeight={this.state.layoutHeight}>
{child}
</ScrollViewStickyHeader>
);
} else {
return child;
}
}) :
this.props.children;
const contentContainer =
<ScrollContentContainerViewClass
{...contentSizeChangeProps}
ref={this._setInnerViewRef}
style={contentContainerStyle}
removeClippedSubviews={
// Subview clipping causes issues with sticky headers on Android and
// would be hard to fix properly in a performant way.
Platform.OS === 'android' && hasStickyHeaders ?
false :
this.props.removeClippedSubviews
}
collapsable={false}>
{children}
</ScrollContentContainerViewClass>;
const alwaysBounceHorizontal =
this.props.alwaysBounceHorizontal !== undefined ?
this.props.alwaysBounceHorizontal :
this.props.horizontal;
const alwaysBounceVertical =
this.props.alwaysBounceVertical !== undefined ?
this.props.alwaysBounceVertical :
!this.props.horizontal;
const DEPRECATED_sendUpdatedChildFrames =
!!this.props.DEPRECATED_sendUpdatedChildFrames;
const baseStyle = this.props.horizontal ? styles.baseHorizontal : styles.baseVertical;
const props = {
...this.props,
alwaysBounceHorizontal,
alwaysBounceVertical,
style: ([baseStyle, this.props.style]: ?Array<any>),
// Override the onContentSizeChange from props, since this event can
// bubble up from TextInputs
onContentSizeChange: null,
onLayout: this._handleLayout,
onMomentumScrollBegin: this.scrollResponderHandleMomentumScrollBegin,
onMomentumScrollEnd: this.scrollResponderHandleMomentumScrollEnd,
onResponderGrant: this.scrollResponderHandleResponderGrant,
onResponderReject: this.scrollResponderHandleResponderReject,
onResponderRelease: this.scrollResponderHandleResponderRelease,
onResponderTerminate: this.scrollResponderHandleTerminate,
onResponderTerminationRequest: this.scrollResponderHandleTerminationRequest,
onScroll: this._handleScroll,
onScrollBeginDrag: this.scrollResponderHandleScrollBeginDrag,
onScrollEndDrag: this.scrollResponderHandleScrollEndDrag,
onScrollShouldSetResponder: this.scrollResponderHandleScrollShouldSetResponder,
onStartShouldSetResponder: this.scrollResponderHandleStartShouldSetResponder,
onStartShouldSetResponderCapture: this.scrollResponderHandleStartShouldSetResponderCapture,
onTouchEnd: this.scrollResponderHandleTouchEnd,
onTouchMove: this.scrollResponderHandleTouchMove,
onTouchStart: this.scrollResponderHandleTouchStart,
onTouchCancel: this.scrollResponderHandleTouchCancel,
scrollBarThumbImage: resolveAssetSource(this.props.scrollBarThumbImage),
scrollEventThrottle: hasStickyHeaders ? 1 : this.props.scrollEventThrottle,
sendMomentumEvents: (this.props.onMomentumScrollBegin || this.props.onMomentumScrollEnd) ?
true : false,
DEPRECATED_sendUpdatedChildFrames,
};
const { decelerationRate } = this.props;
if (decelerationRate) {
props.decelerationRate = processDecelerationRate(decelerationRate);
}
const refreshControl = this.props.refreshControl;
if (refreshControl) {
if (Platform.OS === 'ios') {
// On iOS the RefreshControl is a child of the ScrollView.
// tvOS lacks native support for RefreshControl, so don't include it in that case
return (
<ScrollViewClass {...props} ref={this._setScrollViewRef}>
{Platform.isTVOS ? null : refreshControl}
{contentContainer}
</ScrollViewClass>
);
} else if (Platform.OS === 'android') {
// On Android wrap the ScrollView with a AndroidSwipeRefreshLayout.
// Since the ScrollView is wrapped add the style props to the
// AndroidSwipeRefreshLayout and use flex: 1 for the ScrollView.
// Note: we should only apply props.style on the wrapper
// however, the ScrollView still needs the baseStyle to be scrollable
return React.cloneElement(
refreshControl,
{style: props.style},
<ScrollViewClass {...props} style={baseStyle} ref={this._setScrollViewRef}>
{contentContainer}
</ScrollViewClass>
);
}
}
return (
<ScrollViewClass {...props} ref={this._setScrollViewRef}>
{contentContainer}
</ScrollViewClass>
);
}
});
const styles = StyleSheet.create({
baseVertical: {
flexGrow: 1,
flexShrink: 1,
flexDirection: 'column',
overflow: 'scroll',
},
baseHorizontal: {
flexGrow: 1,
flexShrink: 1,
flexDirection: 'row',
overflow: 'scroll',
},
contentContainerHorizontal: {
flexDirection: 'row',
},
});
let nativeOnlyProps,
AndroidScrollView,
AndroidHorizontalScrollContentView,
AndroidHorizontalScrollView,
RCTScrollView,
RCTScrollContentView;
if (Platform.OS === 'android') {
nativeOnlyProps = {
nativeOnly: {
sendMomentumEvents: true,
}
};
AndroidScrollView = requireNativeComponent(
'RCTScrollView',
(ScrollView: React.ComponentType<any>),
nativeOnlyProps
);
AndroidHorizontalScrollView = requireNativeComponent(
'AndroidHorizontalScrollView',
(ScrollView: React.ComponentType<any>),
nativeOnlyProps
);
AndroidHorizontalScrollContentView = requireNativeComponent(
'AndroidHorizontalScrollContentView'
);
} else if (Platform.OS === 'ios') {
nativeOnlyProps = {
nativeOnly: {
onMomentumScrollBegin: true,
onMomentumScrollEnd : true,
onScrollBeginDrag: true,
onScrollEndDrag: true,
}
};
RCTScrollView = requireNativeComponent(
'RCTScrollView',
(ScrollView: React.ComponentType<any>),
nativeOnlyProps,
);
RCTScrollContentView = requireNativeComponent('RCTScrollContentView', View);
} else {
nativeOnlyProps = {
nativeOnly: {
}
};
RCTScrollView = requireNativeComponent(
'RCTScrollView',
null,
nativeOnlyProps,
);
RCTScrollContentView = requireNativeComponent('RCTScrollContentView', View);
}
module.exports = ScrollView;

View File

@@ -0,0 +1,164 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ScrollViewStickyHeader
* @flow
* @format
*/
'use strict';
const AnimatedImplementation = require('AnimatedImplementation');
const React = require('React');
const StyleSheet = require('StyleSheet');
const View = require('View');
import type {LayoutEvent} from 'CoreEventTypes';
const AnimatedView = AnimatedImplementation.createAnimatedComponent(View);
type Props = {
children?: React.Element<any>,
nextHeaderLayoutY: ?number,
onLayout: (event: LayoutEvent) => void,
scrollAnimatedValue: AnimatedImplementation.Value,
// Will cause sticky headers to stick at the bottom of the ScrollView instead
// of the top.
inverted: ?boolean,
// The height of the parent ScrollView. Currently only set when inverted.
scrollViewHeight: ?number,
};
type State = {
measured: boolean,
layoutY: number,
layoutHeight: number,
nextHeaderLayoutY: ?number,
};
class ScrollViewStickyHeader extends React.Component<Props, State> {
state = {
measured: false,
layoutY: 0,
layoutHeight: 0,
nextHeaderLayoutY: this.props.nextHeaderLayoutY,
};
setNextHeaderY(y: number) {
this.setState({nextHeaderLayoutY: y});
}
_onLayout = event => {
this.setState({
measured: true,
layoutY: event.nativeEvent.layout.y,
layoutHeight: event.nativeEvent.layout.height,
});
this.props.onLayout(event);
const child = React.Children.only(this.props.children);
if (child.props.onLayout) {
child.props.onLayout(event);
}
};
render() {
const {inverted, scrollViewHeight} = this.props;
const {measured, layoutHeight, layoutY, nextHeaderLayoutY} = this.state;
const inputRange: Array<number> = [-1, 0];
const outputRange: Array<number> = [0, 0];
if (measured) {
if (inverted) {
// The interpolation looks like:
// - Negative scroll: no translation
// - `stickStartPoint` is the point at which the header will start sticking.
// It is calculated using the ScrollView viewport height so it is a the bottom.
// - Headers that are in the initial viewport will never stick, `stickStartPoint`
// will be negative.
// - From 0 to `stickStartPoint` no translation. This will cause the header
// to scroll normally until it reaches the top of the scroll view.
// - From `stickStartPoint` to when the next header y hits the bottom edge of the header: translate
// equally to scroll. This will cause the header to stay at the top of the scroll view.
// - Past the collision with the next header y: no more translation. This will cause the
// header to continue scrolling up and make room for the next sticky header.
// In the case that there is no next header just translate equally to
// scroll indefinitely.
if (scrollViewHeight != null) {
const stickStartPoint = layoutY + layoutHeight - scrollViewHeight;
if (stickStartPoint > 0) {
inputRange.push(stickStartPoint);
outputRange.push(0);
inputRange.push(stickStartPoint + 1);
outputRange.push(1);
// If the next sticky header has not loaded yet (probably windowing) or is the last
// we can just keep it sticked forever.
const collisionPoint =
(nextHeaderLayoutY || 0) - layoutHeight - scrollViewHeight;
if (collisionPoint > stickStartPoint) {
inputRange.push(collisionPoint, collisionPoint + 1);
outputRange.push(
collisionPoint - stickStartPoint,
collisionPoint - stickStartPoint,
);
}
}
}
} else {
// The interpolation looks like:
// - Negative scroll: no translation
// - From 0 to the y of the header: no translation. This will cause the header
// to scroll normally until it reaches the top of the scroll view.
// - From header y to when the next header y hits the bottom edge of the header: translate
// equally to scroll. This will cause the header to stay at the top of the scroll view.
// - Past the collision with the next header y: no more translation. This will cause the
// header to continue scrolling up and make room for the next sticky header.
// In the case that there is no next header just translate equally to
// scroll indefinitely.
inputRange.push(layoutY);
outputRange.push(0);
// If the next sticky header has not loaded yet (probably windowing) or is the last
// we can just keep it sticked forever.
const collisionPoint = (nextHeaderLayoutY || 0) - layoutHeight;
if (collisionPoint >= layoutY) {
inputRange.push(collisionPoint, collisionPoint + 1);
outputRange.push(collisionPoint - layoutY, collisionPoint - layoutY);
} else {
inputRange.push(layoutY + 1);
outputRange.push(1);
}
}
}
const translateY = this.props.scrollAnimatedValue.interpolate({
inputRange,
outputRange,
});
const child = React.Children.only(this.props.children);
return (
<AnimatedView
collapsable={false}
onLayout={this._onLayout}
style={[child.props.style, styles.header, {transform: [{translateY}]}]}>
{React.cloneElement(child, {
style: styles.fill, // We transfer the child style to the wrapper.
onLayout: undefined, // we call this manually through our this._onLayout
})}
</AnimatedView>
);
}
}
const styles = StyleSheet.create({
header: {
zIndex: 10,
},
fill: {
flex: 1,
},
});
module.exports = ScrollViewStickyHeader;

View File

@@ -0,0 +1,38 @@
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
/* eslint-env jest */
'use strict';
declare var jest: any;
const React = require('React');
const View = require('View');
const requireNativeComponent = require('requireNativeComponent');
const RCTScrollView = requireNativeComponent('RCTScrollView');
const ScrollViewComponent = jest.genMockFromModule('ScrollView');
class ScrollViewMock extends ScrollViewComponent {
render() {
return (
<RCTScrollView {...this.props}>
{this.props.refreshControl}
<View>
{this.props.children}
</View>
</RCTScrollView>
);
}
}
module.exports = ScrollViewMock;

View File

@@ -0,0 +1,20 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule processDecelerationRate
*/
'use strict';
function processDecelerationRate(decelerationRate) {
if (decelerationRate === 'normal') {
decelerationRate = 0.998;
} else if (decelerationRate === 'fast') {
decelerationRate = 0.99;
}
return decelerationRate;
}
module.exports = processDecelerationRate;

View File

@@ -0,0 +1,47 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule SegmentedControlIOS
*/
'use strict';
const React = require('React');
const StyleSheet = require('StyleSheet');
const Text = require('Text');
const View = require('View');
class DummySegmentedControlIOS extends React.Component {
render() {
return (
<View style={[styles.dummy, this.props.style]}>
<Text style={styles.text}>
SegmentedControlIOS is not supported on this platform!
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
dummy: {
width: 120,
height: 50,
backgroundColor: '#ffbcbc',
borderWidth: 1,
borderColor: 'red',
alignItems: 'center',
justifyContent: 'center',
},
text: {
color: '#333333',
margin: 5,
fontSize: 10,
}
});
module.exports = DummySegmentedControlIOS;

View File

@@ -0,0 +1,131 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule SegmentedControlIOS
* @flow
*/
'use strict';
const NativeMethodsMixin = require('NativeMethodsMixin');
const React = require('React');
const PropTypes = require('prop-types');
const StyleSheet = require('StyleSheet');
const ViewPropTypes = require('ViewPropTypes');
const createReactClass = require('create-react-class');
const requireNativeComponent = require('requireNativeComponent');
type DefaultProps = {
values: Array<string>,
enabled: boolean,
};
const SEGMENTED_CONTROL_REFERENCE = 'segmentedcontrol';
type Event = Object;
/**
* Use `SegmentedControlIOS` to render a UISegmentedControl iOS.
*
* #### Programmatically changing selected index
*
* The selected index can be changed on the fly by assigning the
* selectedIndex prop to a state variable, then changing that variable.
* Note that the state variable would need to be updated as the user
* selects a value and changes the index, as shown in the example below.
*
* ````
* <SegmentedControlIOS
* values={['One', 'Two']}
* selectedIndex={this.state.selectedIndex}
* onChange={(event) => {
* this.setState({selectedIndex: event.nativeEvent.selectedSegmentIndex});
* }}
* />
* ````
*/
const SegmentedControlIOS = createReactClass({
displayName: 'SegmentedControlIOS',
mixins: [NativeMethodsMixin],
propTypes: {
...ViewPropTypes,
/**
* The labels for the control's segment buttons, in order.
*/
values: PropTypes.arrayOf(PropTypes.string),
/**
* The index in `props.values` of the segment to be (pre)selected.
*/
selectedIndex: PropTypes.number,
/**
* Callback that is called when the user taps a segment;
* passes the segment's value as an argument
*/
onValueChange: PropTypes.func,
/**
* Callback that is called when the user taps a segment;
* passes the event as an argument
*/
onChange: PropTypes.func,
/**
* If false the user won't be able to interact with the control.
* Default value is true.
*/
enabled: PropTypes.bool,
/**
* Accent color of the control.
*/
tintColor: PropTypes.string,
/**
* If true, then selecting a segment won't persist visually.
* The `onValueChange` callback will still work as expected.
*/
momentary: PropTypes.bool
},
getDefaultProps: function(): DefaultProps {
return {
values: [],
enabled: true
};
},
_onChange: function(event: Event) {
this.props.onChange && this.props.onChange(event);
this.props.onValueChange && this.props.onValueChange(event.nativeEvent.value);
},
render: function() {
return (
<RCTSegmentedControl
{...this.props}
ref={SEGMENTED_CONTROL_REFERENCE}
style={[styles.segmentedControl, this.props.style]}
onChange={this._onChange}
/>
);
}
});
const styles = StyleSheet.create({
segmentedControl: {
height: 28,
},
});
const RCTSegmentedControl = requireNativeComponent(
'RCTSegmentedControl',
SegmentedControlIOS
);
module.exports = SegmentedControlIOS;

View File

@@ -0,0 +1,278 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule Slider
* @flow
*/
'use strict';
const Image = require('Image');
const ColorPropType = require('ColorPropType');
const NativeMethodsMixin = require('NativeMethodsMixin');
const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
const Platform = require('Platform');
const React = require('React');
const PropTypes = require('prop-types');
const StyleSheet = require('StyleSheet');
const ViewPropTypes = require('ViewPropTypes');
const createReactClass = require('create-react-class');
const requireNativeComponent = require('requireNativeComponent');
type Event = Object;
/**
* A component used to select a single value from a range of values.
*
* ### Usage
*
* The example below shows how to use `Slider` to change
* a value used by `Text`. The value is stored using
* the state of the root component (`App`). The same component
* subscribes to the `onValueChange` of `Slider` and changes
* the value using `setState`.
*
*```
* import React from 'react';
* import { StyleSheet, Text, View, Slider } from 'react-native';
*
* export default class App extends React.Component {
* constructor(props) {
* super(props);
* this.state = {
* value: 50
* }
* }
*
* change(value) {
* this.setState(() => {
* return {
* value: parseFloat(value)
* };
* });
* }
*
* render() {
* const {value} = this.state;
* return (
* <View style={styles.container}>
* <Text style={styles.text}>{String(value)}</Text>
* <Slider
* step={1}
* maximumValue={100}
* onValueChange={this.change.bind(this)}
* value={value} />
* </View>
* );
* }
* }
*
* const styles = StyleSheet.create({
* container: {
* flex: 1,
* flexDirection: 'column',
* justifyContent: 'center'
* },
* text: {
* fontSize: 50,
* textAlign: 'center'
* }
* });
*```
*
*/
const Slider = createReactClass({
displayName: 'Slider',
mixins: [NativeMethodsMixin],
propTypes: {
...ViewPropTypes,
/**
* Used to style and layout the `Slider`. See `StyleSheet.js` and
* `ViewStylePropTypes.js` for more info.
*/
style: ViewPropTypes.style,
/**
* Initial value of the slider. The value should be between minimumValue
* and maximumValue, which default to 0 and 1 respectively.
* Default value is 0.
*
* *This is not a controlled component*, you don't need to update the
* value during dragging.
*/
value: PropTypes.number,
/**
* Step value of the slider. The value should be
* between 0 and (maximumValue - minimumValue).
* Default value is 0.
*/
step: PropTypes.number,
/**
* Initial minimum value of the slider. Default value is 0.
*/
minimumValue: PropTypes.number,
/**
* Initial maximum value of the slider. Default value is 1.
*/
maximumValue: PropTypes.number,
/**
* The color used for the track to the left of the button.
* Overrides the default blue gradient image on iOS.
*/
minimumTrackTintColor: ColorPropType,
/**
* The color used for the track to the right of the button.
* Overrides the default blue gradient image on iOS.
*/
maximumTrackTintColor: ColorPropType,
/**
* If true the user won't be able to move the slider.
* Default value is false.
*/
disabled: PropTypes.bool,
/**
* Assigns a single image for the track. Only static images are supported.
* The center pixel of the image will be stretched to fill the track.
* @platform ios
*/
trackImage: Image.propTypes.source,
/**
* Assigns a minimum track image. Only static images are supported. The
* rightmost pixel of the image will be stretched to fill the track.
* @platform ios
*/
minimumTrackImage: Image.propTypes.source,
/**
* Assigns a maximum track image. Only static images are supported. The
* leftmost pixel of the image will be stretched to fill the track.
* @platform ios
*/
maximumTrackImage: Image.propTypes.source,
/**
* Sets an image for the thumb. Only static images are supported.
* @platform ios
*/
thumbImage: Image.propTypes.source,
/**
* Color of the foreground switch grip.
* @platform android
*/
thumbTintColor: ColorPropType,
/**
* Callback continuously called while the user is dragging the slider.
*/
onValueChange: PropTypes.func,
/**
* Callback that is called when the user releases the slider,
* regardless if the value has changed. The current value is passed
* as an argument to the callback handler.
*/
onSlidingComplete: PropTypes.func,
/**
* Used to locate this view in UI automation tests.
*/
testID: PropTypes.string,
},
getDefaultProps: function() : any {
return {
disabled: false,
value: 0,
minimumValue: 0,
maximumValue: 1,
step: 0
};
},
viewConfig: {
uiViewClassName: 'RCTSlider',
validAttributes: {
...ReactNativeViewAttributes.RCTView,
value: true
}
},
render: function() {
const {style, onValueChange, onSlidingComplete, ...props} = this.props;
/* $FlowFixMe(>=0.54.0 site=react_native_fb,react_native_oss) This comment
* suppresses an error found when Flow v0.54 was deployed. To see the error
* delete this comment and run Flow. */
props.style = [styles.slider, style];
/* $FlowFixMe(>=0.54.0 site=react_native_fb,react_native_oss) This comment
* suppresses an error found when Flow v0.54 was deployed. To see the error
* delete this comment and run Flow. */
props.onValueChange = onValueChange && ((event: Event) => {
let userEvent = true;
if (Platform.OS === 'android') {
// On Android there's a special flag telling us the user is
// dragging the slider.
userEvent = event.nativeEvent.fromUser;
}
onValueChange && userEvent && onValueChange(event.nativeEvent.value);
});
/* $FlowFixMe(>=0.54.0 site=react_native_fb,react_native_oss) This comment
* suppresses an error found when Flow v0.54 was deployed. To see the error
* delete this comment and run Flow. */
props.onChange = props.onValueChange;
/* $FlowFixMe(>=0.54.0 site=react_native_fb,react_native_oss) This comment
* suppresses an error found when Flow v0.54 was deployed. To see the error
* delete this comment and run Flow. */
props.onSlidingComplete = onSlidingComplete && ((event: Event) => {
onSlidingComplete && onSlidingComplete(event.nativeEvent.value);
});
return <RCTSlider
{...props}
enabled={!this.props.disabled}
onStartShouldSetResponder={() => true}
onResponderTerminationRequest={() => false}
/>;
}
});
let styles;
if (Platform.OS === 'ios') {
styles = StyleSheet.create({
slider: {
height: 40,
},
});
} else {
styles = StyleSheet.create({
slider: {},
});
}
let options = {};
if (Platform.OS === 'android') {
options = {
nativeOnly: {
enabled: true,
}
};
}
const RCTSlider = requireNativeComponent('RCTSlider', Slider, options);
module.exports = Slider;

View File

@@ -0,0 +1,44 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule StaticContainer.react
* @flow
*/
'use strict';
const React = require('React');
/**
* Renders static content efficiently by allowing React to short-circuit the
* reconciliation process. This component should be used when you know that a
* subtree of components will never need to be updated.
*
* const someValue = ...; // We know for certain this value will never change.
* return (
* <StaticContainer>
* <MyComponent value={someValue} />
* </StaticContainer>
* );
*
* Typically, you will not need to use this component and should opt for normal
* React reconciliation.
*/
class StaticContainer extends React.Component<Object> {
shouldComponentUpdate(nextProps: Object): boolean {
return !!nextProps.shouldUpdate;
}
render() {
const child = this.props.children;
return (child === null || child === false)
? null
: React.Children.only(child);
}
}
module.exports = StaticContainer;

View File

@@ -0,0 +1,34 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule StaticRenderer
* @flow
*/
'use strict';
const React = require('React');
const PropTypes = require('prop-types');
class StaticRenderer extends React.Component<{
shouldUpdate: boolean,
render: Function,
}> {
static propTypes = {
shouldUpdate: PropTypes.bool.isRequired,
render: PropTypes.func.isRequired,
};
shouldComponentUpdate(nextProps: { shouldUpdate: boolean }): boolean {
return nextProps.shouldUpdate;
}
render(): React.Node {
return this.props.render();
}
}
module.exports = StaticRenderer;

View File

@@ -0,0 +1,412 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule StatusBar
* @flow
*/
'use strict';
const React = require('React');
const PropTypes = require('prop-types');
const ColorPropType = require('ColorPropType');
const Platform = require('Platform');
const processColor = require('processColor');
const StatusBarManager = require('NativeModules').StatusBarManager;
/**
* Status bar style
*/
export type StatusBarStyle = $Enum<{
/**
* Default status bar style (dark for iOS, light for Android)
*/
'default': string,
/**
* Dark background, white texts and icons
*/
'light-content': string,
/**
* Light background, dark texts and icons
*/
'dark-content': string,
}>;
/**
* Status bar animation
*/
export type StatusBarAnimation = $Enum<{
/**
* No animation
*/
'none': string,
/**
* Fade animation
*/
'fade': string,
/**
* Slide animation
*/
'slide': string,
}>;
type DefaultProps = {
animated: boolean,
};
/**
* Merges the prop stack with the default values.
*/
function mergePropsStack(
propsStack: Array<Object>,
defaultValues: Object
): Object {
return propsStack.reduce((prev, cur) => {
for (const prop in cur) {
if (cur[prop] != null) {
prev[prop] = cur[prop];
}
}
return prev;
}, Object.assign({}, defaultValues));
}
/**
* Returns an object to insert in the props stack from the props
* and the transition/animation info.
*/
function createStackEntry(props: any): any {
return {
backgroundColor:
props.backgroundColor != null
? {
value: props.backgroundColor,
animated: props.animated,
}
: null,
barStyle:
props.barStyle != null
? {
value: props.barStyle,
animated: props.animated,
}
: null,
translucent: props.translucent,
hidden:
props.hidden != null
? {
value: props.hidden,
animated: props.animated,
transition: props.showHideTransition,
}
: null,
networkActivityIndicatorVisible: props.networkActivityIndicatorVisible,
};
}
/**
* Component to control the app status bar.
*
* ### Usage with Navigator
*
* It is possible to have multiple `StatusBar` components mounted at the same
* time. The props will be merged in the order the `StatusBar` components were
* mounted. One use case is to specify status bar styles per route using `Navigator`.
*
* ```
* <View>
* <StatusBar
* backgroundColor="blue"
* barStyle="light-content"
* />
* <Navigator
* initialRoute={{statusBarHidden: true}}
* renderScene={(route, navigator) =>
* <View>
* <StatusBar hidden={route.statusBarHidden} />
* ...
* </View>
* }
* />
* </View>
* ```
*
* ### Imperative API
*
* For cases where using a component is not ideal, there is also an imperative
* API exposed as static functions on the component. It is however not recommended
* to use the static API and the component for the same prop because any value
* set by the static API will get overriden by the one set by the component in
* the next render.
*
* ### Constants
*
* `currentHeight` (Android only) The height of the status bar.
*/
class StatusBar extends React.Component<{
hidden?: boolean,
animated?: boolean,
backgroundColor?: string,
translucent?: boolean,
barStyle?: 'default' | 'light-content' | 'dark-content',
networkActivityIndicatorVisible?: boolean,
showHideTransition?: 'fade' | 'slide',
}> {
static _propsStack = [];
static _defaultProps = createStackEntry({
animated: false,
showHideTransition: 'fade',
backgroundColor: 'black',
barStyle: 'default',
translucent: false,
hidden: false,
networkActivityIndicatorVisible: false,
});
// Timer for updating the native module values at the end of the frame.
static _updateImmediate = null;
// The current merged values from the props stack.
static _currentValues = null;
// TODO(janic): Provide a real API to deal with status bar height. See the
// discussion in #6195.
/**
* The current height of the status bar on the device.
*
* @platform android
*/
static currentHeight = StatusBarManager.HEIGHT;
// Provide an imperative API as static functions of the component.
// See the corresponding prop for more detail.
/**
* Show or hide the status bar
* @param hidden Hide the status bar.
* @param animation Optional animation when
* changing the status bar hidden property.
*/
static setHidden(hidden: boolean, animation?: StatusBarAnimation) {
animation = animation || 'none';
StatusBar._defaultProps.hidden.value = hidden;
if (Platform.OS === 'ios') {
StatusBarManager.setHidden(hidden, animation);
} else if (Platform.OS === 'android') {
StatusBarManager.setHidden(hidden);
}
}
/**
* Set the status bar style
* @param style Status bar style to set
* @param animated Animate the style change.
*/
static setBarStyle(style: StatusBarStyle, animated?: boolean) {
animated = animated || false;
StatusBar._defaultProps.barStyle.value = style;
if (Platform.OS === 'ios') {
StatusBarManager.setStyle(style, animated);
} else if (Platform.OS === 'android') {
StatusBarManager.setStyle(style);
}
}
/**
* Control the visibility of the network activity indicator
* @param visible Show the indicator.
*/
static setNetworkActivityIndicatorVisible(visible: boolean) {
if (Platform.OS !== 'ios') {
console.warn(
'`setNetworkActivityIndicatorVisible` is only available on iOS'
);
return;
}
StatusBar._defaultProps.networkActivityIndicatorVisible = visible;
StatusBarManager.setNetworkActivityIndicatorVisible(visible);
}
/**
* Set the background color for the status bar
* @param color Background color.
* @param animated Animate the style change.
*/
static setBackgroundColor(color: string, animated?: boolean) {
if (Platform.OS !== 'android') {
console.warn('`setBackgroundColor` is only available on Android');
return;
}
animated = animated || false;
StatusBar._defaultProps.backgroundColor.value = color;
StatusBarManager.setColor(processColor(color), animated);
}
/**
* Control the translucency of the status bar
* @param translucent Set as translucent.
*/
static setTranslucent(translucent: boolean) {
if (Platform.OS !== 'android') {
console.warn('`setTranslucent` is only available on Android');
return;
}
StatusBar._defaultProps.translucent = translucent;
StatusBarManager.setTranslucent(translucent);
}
static propTypes = {
/**
* If the status bar is hidden.
*/
hidden: PropTypes.bool,
/**
* If the transition between status bar property changes should be animated.
* Supported for backgroundColor, barStyle and hidden.
*/
animated: PropTypes.bool,
/**
* The background color of the status bar.
* @platform android
*/
backgroundColor: ColorPropType,
/**
* If the status bar is translucent.
* When translucent is set to true, the app will draw under the status bar.
* This is useful when using a semi transparent status bar color.
*
* @platform android
*/
translucent: PropTypes.bool,
/**
* Sets the color of the status bar text.
*/
barStyle: PropTypes.oneOf(['default', 'light-content', 'dark-content']),
/**
* If the network activity indicator should be visible.
*
* @platform ios
*/
networkActivityIndicatorVisible: PropTypes.bool,
/**
* The transition effect when showing and hiding the status bar using the `hidden`
* prop. Defaults to 'fade'.
*
* @platform ios
*/
showHideTransition: PropTypes.oneOf(['fade', 'slide']),
};
static defaultProps = {
animated: false,
showHideTransition: 'fade',
};
_stackEntry = null;
componentDidMount() {
// Every time a StatusBar component is mounted, we push it's prop to a stack
// and always update the native status bar with the props from the top of then
// stack. This allows having multiple StatusBar components and the one that is
// added last or is deeper in the view hierarchy will have priority.
this._stackEntry = createStackEntry(this.props);
StatusBar._propsStack.push(this._stackEntry);
this._updatePropsStack();
}
componentWillUnmount() {
// When a StatusBar is unmounted, remove itself from the stack and update
// the native bar with the next props.
const index = StatusBar._propsStack.indexOf(this._stackEntry);
StatusBar._propsStack.splice(index, 1);
this._updatePropsStack();
}
componentDidUpdate() {
const index = StatusBar._propsStack.indexOf(this._stackEntry);
this._stackEntry = createStackEntry(this.props);
StatusBar._propsStack[index] = this._stackEntry;
this._updatePropsStack();
}
/**
* Updates the native status bar with the props from the stack.
*/
_updatePropsStack = () => {
// Send the update to the native module only once at the end of the frame.
clearImmediate(StatusBar._updateImmediate);
StatusBar._updateImmediate = setImmediate(() => {
const oldProps = StatusBar._currentValues;
const mergedProps = mergePropsStack(
StatusBar._propsStack,
StatusBar._defaultProps
);
// Update the props that have changed using the merged values from the props stack.
if (Platform.OS === 'ios') {
if (
!oldProps ||
oldProps.barStyle.value !== mergedProps.barStyle.value
) {
StatusBarManager.setStyle(
mergedProps.barStyle.value,
mergedProps.barStyle.animated
);
}
if (!oldProps || oldProps.hidden.value !== mergedProps.hidden.value) {
StatusBarManager.setHidden(
mergedProps.hidden.value,
mergedProps.hidden.animated ? mergedProps.hidden.transition : 'none'
);
}
if (
!oldProps ||
oldProps.networkActivityIndicatorVisible !==
mergedProps.networkActivityIndicatorVisible
) {
StatusBarManager.setNetworkActivityIndicatorVisible(
mergedProps.networkActivityIndicatorVisible
);
}
} else if (Platform.OS === 'android') {
if (
!oldProps ||
oldProps.barStyle.value !== mergedProps.barStyle.value
) {
StatusBarManager.setStyle(mergedProps.barStyle.value);
}
if (
!oldProps ||
oldProps.backgroundColor.value !== mergedProps.backgroundColor.value
) {
StatusBarManager.setColor(
processColor(mergedProps.backgroundColor.value),
mergedProps.backgroundColor.animated
);
}
if (!oldProps || oldProps.hidden.value !== mergedProps.hidden.value) {
StatusBarManager.setHidden(mergedProps.hidden.value);
}
if (!oldProps || oldProps.translucent !== mergedProps.translucent) {
StatusBarManager.setTranslucent(mergedProps.translucent);
}
}
// Update the current prop values.
StatusBar._currentValues = mergedProps;
});
};
render(): React.Node {
return null;
}
}
module.exports = StatusBar;

View File

@@ -0,0 +1,14 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule StatusBarIOS
* @flow
*/
'use strict';
const NativeEventEmitter = require('NativeEventEmitter');
module.exports = new NativeEventEmitter('StatusBarManager');

View File

@@ -0,0 +1,20 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule StatusBarIOS
* @flow
*/
'use strict';
const NativeEventEmitter = require('NativeEventEmitter');
const { StatusBarManager } = require('NativeModules');
/**
* Use `StatusBar` for mutating the status bar.
*/
class StatusBarIOS extends NativeEventEmitter {}
module.exports = new StatusBarIOS(StatusBarManager);

View File

@@ -0,0 +1,64 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule Subscribable
* @flow
*/
'use strict';
import type EventEmitter from 'EventEmitter';
/**
* Subscribable provides a mixin for safely subscribing a component to an
* eventEmitter
*
* This will be replaced with the observe interface that will be coming soon to
* React Core
*/
const Subscribable = {};
Subscribable.Mixin = {
UNSAFE_componentWillMount: function() {
this._subscribableSubscriptions = [];
},
componentWillUnmount: function() {
// This null check is a fix for a broken version of uglify-es. Should be deleted eventually
// https://github.com/facebook/react-native/issues/17348
this._subscribableSubscriptions && this._subscribableSubscriptions.forEach(
(subscription) => subscription.remove()
);
this._subscribableSubscriptions = null;
},
/**
* Special form of calling `addListener` that *guarantees* that a
* subscription *must* be tied to a component instance, and therefore will
* be cleaned up when the component is unmounted. It is impossible to create
* the subscription and pass it in - this method must be the one to create
* the subscription and therefore can guarantee it is retained in a way that
* will be cleaned up.
*
* @param {EventEmitter} eventEmitter emitter to subscribe to.
* @param {string} eventType Type of event to listen to.
* @param {function} listener Function to invoke when event occurs.
* @param {object} context Object to use as listener context.
*/
addListenerOn: function(
eventEmitter: EventEmitter,
eventType: string,
listener: Function,
context: Object
) {
this._subscribableSubscriptions.push(
eventEmitter.addListener(eventType, listener, context)
);
}
};
module.exports = Subscribable;

View File

@@ -0,0 +1,149 @@
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule Switch
* @flow
*/
'use strict';
const ColorPropType = require('ColorPropType');
const NativeMethodsMixin = require('NativeMethodsMixin');
const Platform = require('Platform');
const React = require('React');
const PropTypes = require('prop-types');
const StyleSheet = require('StyleSheet');
const ViewPropTypes = require('ViewPropTypes');
const createReactClass = require('create-react-class');
const requireNativeComponent = require('requireNativeComponent');
type DefaultProps = {
value: boolean,
disabled: boolean,
};
/**
* Renders a boolean input.
*
* This is a controlled component that requires an `onValueChange` callback that
* updates the `value` prop in order for the component to reflect user actions.
* If the `value` prop is not updated, the component will continue to render
* the supplied `value` prop instead of the expected result of any user actions.
*
* @keyword checkbox
* @keyword toggle
*/
const Switch = createReactClass({
displayName: 'Switch',
propTypes: {
...ViewPropTypes,
/**
* The value of the switch. If true the switch will be turned on.
* Default value is false.
*/
value: PropTypes.bool,
/**
* If true the user won't be able to toggle the switch.
* Default value is false.
*/
disabled: PropTypes.bool,
/**
* Invoked with the new value when the value changes.
*/
onValueChange: PropTypes.func,
/**
* Used to locate this view in end-to-end tests.
*/
testID: PropTypes.string,
/**
* Border color on iOS and background color on Android when the switch is turned off.
*/
tintColor: ColorPropType,
/**
* Background color when the switch is turned on.
*/
onTintColor: ColorPropType,
/**
* Color of the foreground switch grip.
*/
thumbTintColor: ColorPropType,
},
getDefaultProps: function(): DefaultProps {
return {
value: false,
disabled: false,
};
},
mixins: [NativeMethodsMixin],
_rctSwitch: {},
_onChange: function(event: Object) {
if (Platform.OS === 'android') {
this._rctSwitch.setNativeProps({on: this.props.value});
} else {
this._rctSwitch.setNativeProps({value: this.props.value});
}
//Change the props after the native props are set in case the props change removes the component
/* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This comment
* suppresses an error when upgrading Flow's support for React. To see the
* error delete this comment and run Flow. */
this.props.onChange && this.props.onChange(event);
this.props.onValueChange && this.props.onValueChange(event.nativeEvent.value);
},
render: function() {
const props = {...this.props};
props.onStartShouldSetResponder = () => true;
props.onResponderTerminationRequest = () => false;
if (Platform.OS === 'android') {
props.enabled = !this.props.disabled;
props.on = this.props.value;
props.style = this.props.style;
props.trackTintColor = this.props.value ? this.props.onTintColor : this.props.tintColor;
} else if (Platform.OS === 'ios') {
props.style = [styles.rctSwitchIOS, this.props.style];
}
return (
<RCTSwitch
{...props}
/* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This
* comment suppresses an error when upgrading Flow's support for React.
* To see the error delete this comment and run Flow. */
ref={(ref) => { this._rctSwitch = ref; }}
onChange={this._onChange}
/>
);
},
});
const styles = StyleSheet.create({
rctSwitchIOS: {
height: 31,
width: 51,
}
});
if (Platform.OS === 'android') {
var RCTSwitch = requireNativeComponent('AndroidSwitch', Switch, {
nativeOnly: {
onChange: true,
on: true,
enabled: true,
trackTintColor: true,
}
});
} else {
var RCTSwitch = requireNativeComponent('RCTSwitch', Switch, {
nativeOnly: {
onChange: true
}
});
}
module.exports = Switch;

View File

@@ -0,0 +1,36 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule TabBarIOS
* @flow
*/
'use strict';
const React = require('React');
const StyleSheet = require('StyleSheet');
const TabBarItemIOS = require('TabBarItemIOS');
const View = require('View');
class DummyTabBarIOS extends React.Component<$FlowFixMeProps> {
static Item = TabBarItemIOS;
render() {
return (
<View style={[this.props.style, styles.tabGroup]}>
{this.props.children}
</View>
);
}
}
const styles = StyleSheet.create({
tabGroup: {
flex: 1,
}
});
module.exports = DummyTabBarIOS;

View File

@@ -0,0 +1,103 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule TabBarIOS
* @flow
*/
'use strict';
const ColorPropType = require('ColorPropType');
const React = require('React');
const PropTypes = require('prop-types');
const StyleSheet = require('StyleSheet');
const TabBarItemIOS = require('TabBarItemIOS');
const ViewPropTypes = require('ViewPropTypes');
const requireNativeComponent = require('requireNativeComponent');
import type {DangerouslyImpreciseStyleProp} from 'StyleSheet';
import type {ViewProps} from 'ViewPropTypes';
class TabBarIOS extends React.Component<ViewProps & {
style?: DangerouslyImpreciseStyleProp,
unselectedTintColor?: string,
tintColor?: string,
unselectedItemTintColor?: string,
barTintColor?: string,
barStyle?: 'default' | 'black',
translucent?: boolean,
itemPositioning?: 'fill' | 'center' | 'auto',
children: React.Node,
}> {
static Item = TabBarItemIOS;
static propTypes = {
...ViewPropTypes,
style: ViewPropTypes.style,
/**
* Color of text on unselected tabs
*/
unselectedTintColor: ColorPropType,
/**
* Color of the currently selected tab icon
*/
tintColor: ColorPropType,
/**
* Color of unselected tab icons. Available since iOS 10.
*/
unselectedItemTintColor: ColorPropType,
/**
* Background color of the tab bar
*/
barTintColor: ColorPropType,
/**
* The style of the tab bar. Supported values are 'default', 'black'.
* Use 'black' instead of setting `barTintColor` to black. This produces
* a tab bar with the native iOS style with higher translucency.
*/
barStyle: PropTypes.oneOf(['default', 'black']),
/**
* A Boolean value that indicates whether the tab bar is translucent
*/
translucent: PropTypes.bool,
/**
* Specifies tab bar item positioning. Available values are:
* - fill - distributes items across the entire width of the tab bar
* - center - centers item in the available tab bar space
* - auto (default) - distributes items dynamically according to the
* user interface idiom. In a horizontally compact environment (e.g. iPhone 5)
* this value defaults to `fill`, in a horizontally regular one (e.g. iPad)
* it defaults to center.
*/
itemPositioning: PropTypes.oneOf(['fill', 'center', 'auto']),
};
render() {
return (
<RCTTabBar
style={[styles.tabGroup, this.props.style]}
unselectedTintColor={this.props.unselectedTintColor}
unselectedItemTintColor={this.props.unselectedItemTintColor}
tintColor={this.props.tintColor}
barTintColor={this.props.barTintColor}
barStyle={this.props.barStyle}
itemPositioning={this.props.itemPositioning}
translucent={this.props.translucent !== false}>
{this.props.children}
</RCTTabBar>
);
}
}
const styles = StyleSheet.create({
tabGroup: {
flex: 1,
}
});
const RCTTabBar = requireNativeComponent('RCTTabBar', TabBarIOS);
module.exports = TabBarIOS;

View File

@@ -0,0 +1,42 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule TabBarItemIOS
*/
'use strict';
const React = require('React');
const View = require('View');
const StyleSheet = require('StyleSheet');
class DummyTab extends React.Component {
render() {
if (!this.props.selected) {
return <View />;
}
return (
<View style={[this.props.style, styles.tab]}>
{this.props.children}
</View>
);
}
}
const styles = StyleSheet.create({
tab: {
// TODO(5405356): Implement overflow: visible so position: absolute isn't useless
// position: 'absolute',
top: 0,
right: 0,
bottom: 0,
left: 0,
borderColor: 'red',
borderWidth: 1,
}
});
module.exports = DummyTab;

View File

@@ -0,0 +1,151 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule TabBarItemIOS
* @noflow
*/
'use strict';
const ColorPropType = require('ColorPropType');
const Image = require('Image');
const React = require('React');
const PropTypes = require('prop-types');
const StaticContainer = require('StaticContainer.react');
const StyleSheet = require('StyleSheet');
const View = require('View');
const ViewPropTypes = require('ViewPropTypes');
const requireNativeComponent = require('requireNativeComponent');
class TabBarItemIOS extends React.Component {
static propTypes = {
...ViewPropTypes,
/**
* Little red bubble that sits at the top right of the icon.
*/
badge: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
/**
* Background color for the badge. Available since iOS 10.
*/
badgeColor: ColorPropType,
/**
* Items comes with a few predefined system icons. Note that if you are
* using them, the title and selectedIcon will be overridden with the
* system ones.
*/
systemIcon: PropTypes.oneOf([
'bookmarks',
'contacts',
'downloads',
'favorites',
'featured',
'history',
'more',
'most-recent',
'most-viewed',
'recents',
'search',
'top-rated',
]),
/**
* A custom icon for the tab. It is ignored when a system icon is defined.
*/
icon: Image.propTypes.source,
/**
* A custom icon when the tab is selected. It is ignored when a system
* icon is defined. If left empty, the icon will be tinted in blue.
*/
selectedIcon: Image.propTypes.source,
/**
* Callback when this tab is being selected, you should change the state of your
* component to set selected={true}.
*/
onPress: PropTypes.func,
/**
* If set to true it renders the image as original,
* it defaults to being displayed as a template
*/
renderAsOriginal: PropTypes.bool,
/**
* It specifies whether the children are visible or not. If you see a
* blank content, you probably forgot to add a selected one.
*/
selected: PropTypes.bool,
/**
* React style object.
*/
style: ViewPropTypes.style,
/**
* Text that appears under the icon. It is ignored when a system icon
* is defined.
*/
title: PropTypes.string,
/**
*(Apple TV only)* When set to true, this view will be focusable
* and navigable using the Apple TV remote.
*
* @platform ios
*/
isTVSelectable: PropTypes.bool,
};
state = {
hasBeenSelected: false,
};
UNSAFE_componentWillMount() {
if (this.props.selected) {
this.setState({hasBeenSelected: true});
}
}
UNSAFE_componentWillReceiveProps(nextProps: { selected?: boolean }) {
if (this.state.hasBeenSelected || nextProps.selected) {
this.setState({hasBeenSelected: true});
}
}
render() {
const {style, children, ...props} = this.props;
// if the tab has already been shown once, always continue to show it so we
// preserve state between tab transitions
if (this.state.hasBeenSelected) {
var tabContents =
<StaticContainer shouldUpdate={this.props.selected}>
{children}
</StaticContainer>;
} else {
var tabContents = <View />;
}
return (
<RCTTabBarItem
{...props}
style={[styles.tab, style]}>
{tabContents}
</RCTTabBarItem>
);
}
}
const styles = StyleSheet.create({
tab: {
position: 'absolute',
top: 0,
right: 0,
bottom: 0,
left: 0,
}
});
const RCTTabBarItem = requireNativeComponent('RCTTabBarItem', TabBarItemIOS);
module.exports = TabBarItemIOS;

View File

@@ -0,0 +1,114 @@
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule InputAccessoryView
* @flow
* @format
*/
'use strict';
const ColorPropType = require('ColorPropType');
const React = require('React');
const StyleSheet = require('StyleSheet');
const ViewPropTypes = require('ViewPropTypes');
const requireNativeComponent = require('requireNativeComponent');
const RCTInputAccessoryView = requireNativeComponent('RCTInputAccessoryView');
/**
* Note: iOS only
*
* A component which enables customization of the keyboard input accessory view.
* The input accessory view is displayed above the keyboard whenever a TextInput
* has focus. This component can be used to create custom toolbars.
*
* To use this component wrap your custom toolbar with the
* InputAccessoryView component, and set a nativeID. Then, pass that nativeID
* as the inputAccessoryViewID of whatever TextInput you desire. A simple
* example:
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react';
* import { AppRegistry, TextInput, InputAccessoryView, Button } from 'react-native';
*
* export default class UselessTextInput extends Component {
* constructor(props) {
* super(props);
* this.state = {text: 'Placeholder Text'};
* }
*
* render() {
* const inputAccessoryViewID = "uniqueID";
* return (
* <View>
* <ScrollView keyboardDismissMode="interactive">
* <TextInput
* style={{
* padding: 10,
* paddingTop: 50,
* }}
* inputAccessoryViewID=inputAccessoryViewID
* onChangeText={text => this.setState({text})}
* value={this.state.text}
* />
* </ScrollView>
* <InputAccessoryView nativeID=inputAccessoryViewID>
* <Button
* onPress={() => this.setState({text: 'Placeholder Text'})}
* title="Reset Text"
* />
* </InputAccessoryView>
* </View>
* );
* }
* }
*
* // skip this line if using Create React Native App
* AppRegistry.registerComponent('AwesomeProject', () => UselessTextInput);
* ```
*
* This component can also be used to create sticky text inputs (text inputs
* which are anchored to the top of the keyboard). To do this, wrap a
* TextInput with the InputAccessoryView component, and don't set a nativeID.
* For an example, look at InputAccessoryViewExample.js in RNTester.
*/
type Props = {
+children: React.Node,
/**
* An ID which is used to associate this `InputAccessoryView` to
* specified TextInput(s).
*/
nativeID?: string,
style?: ViewPropTypes.style,
backgroundColor?: ColorPropType,
};
class InputAccessoryView extends React.Component<Props> {
render(): React.Node {
if (React.Children.count(this.props.children) === 0) {
return null;
}
return (
<RCTInputAccessoryView
style={[this.props.style, styles.container]}
nativeID={this.props.nativeID}
backgroundColor={this.props.backgroundColor}>
{this.props.children}
</RCTInputAccessoryView>
);
}
}
const styles = StyleSheet.create({
container: {
position: 'absolute',
},
});
module.exports = InputAccessoryView;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,74 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule TextInputState
* @flow
*
* This class is responsible for coordinating the "focused"
* state for TextInputs. All calls relating to the keyboard
* should be funneled through here
*/
'use strict';
const Platform = require('Platform');
const UIManager = require('UIManager');
const TextInputState = {
/**
* Internal state
*/
_currentlyFocusedID: (null: ?number),
/**
* Returns the ID of the currently focused text field, if one exists
* If no text field is focused it returns null
*/
currentlyFocusedField: function(): ?number {
return this._currentlyFocusedID;
},
/**
* @param {number} TextInputID id of the text field to focus
* Focuses the specified text field
* noop if the text field was already focused
*/
focusTextInput: function(textFieldID: ?number) {
if (this._currentlyFocusedID !== textFieldID && textFieldID !== null) {
this._currentlyFocusedID = textFieldID;
if (Platform.OS === 'ios') {
UIManager.focus(textFieldID);
} else if (Platform.OS === 'android') {
UIManager.dispatchViewManagerCommand(
textFieldID,
UIManager.AndroidTextInput.Commands.focusTextInput,
null
);
}
}
},
/**
* @param {number} textFieldID id of the text field to unfocus
* Unfocuses the specified text field
* noop if it wasn't focused
*/
blurTextInput: function(textFieldID: ?number) {
if (this._currentlyFocusedID === textFieldID && textFieldID !== null) {
this._currentlyFocusedID = null;
if (Platform.OS === 'ios') {
UIManager.blur(textFieldID);
} else if (Platform.OS === 'android') {
UIManager.dispatchViewManagerCommand(
textFieldID,
UIManager.AndroidTextInput.Commands.blurTextInput,
null
);
}
}
}
};
module.exports = TextInputState;

View File

@@ -0,0 +1,69 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule TimePickerAndroid
* @flow
*/
'use strict';
const TimePickerModule = require('NativeModules').TimePickerAndroid;
/**
* Opens the standard Android time picker dialog.
*
* ### Example
*
* ```
* try {
* const {action, hour, minute} = await TimePickerAndroid.open({
* hour: 14,
* minute: 0,
* is24Hour: false, // Will display '2 PM'
* });
* if (action !== TimePickerAndroid.dismissedAction) {
* // Selected hour (0-23), minute (0-59)
* }
* } catch ({code, message}) {
* console.warn('Cannot open time picker', message);
* }
* ```
*/
class TimePickerAndroid {
/**
* Opens the standard Android time picker dialog.
*
* The available keys for the `options` object are:
* * `hour` (0-23) - the hour to show, defaults to the current time
* * `minute` (0-59) - the minute to show, defaults to the current time
* * `is24Hour` (boolean) - If `true`, the picker uses the 24-hour format. If `false`,
* the picker shows an AM/PM chooser. If undefined, the default for the current locale
* is used.
* * `mode` (`enum('clock', 'spinner', 'default')`) - set the time picker mode
* - 'clock': Show a time picker in clock mode.
* - 'spinner': Show a time picker in spinner mode.
* - 'default': Show a default time picker based on Android versions.
*
* Returns a Promise which will be invoked an object containing `action`, `hour` (0-23),
* `minute` (0-59) if the user picked a time. If the user dismissed the dialog, the Promise will
* still be resolved with action being `TimePickerAndroid.dismissedAction` and all the other keys
* being undefined. **Always** check whether the `action` before reading the values.
*/
static async open(options: Object): Promise<Object> {
return TimePickerModule.open(options);
}
/**
* A time has been selected.
*/
static get timeSetAction() { return 'timeSetAction'; }
/**
* The dialog has been dismissed.
*/
static get dismissedAction() { return 'dismissedAction'; }
}
module.exports = TimePickerAndroid;

View File

@@ -0,0 +1,20 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule TimePickerAndroid
* @flow
*/
'use strict';
const TimePickerAndroid = {
async open(options: Object): Promise<Object> {
return Promise.reject({
message: 'TimePickerAndroid is not supported on this platform.'
});
},
};
module.exports = TimePickerAndroid;

View File

@@ -0,0 +1,73 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ToastAndroid
* @flow
*/
'use strict';
const RCTToastAndroid = require('NativeModules').ToastAndroid;
/**
* This exposes the native ToastAndroid module as a JS module. This has a function 'show'
* which takes the following parameters:
*
* 1. String message: A string with the text to toast
* 2. int duration: The duration of the toast. May be ToastAndroid.SHORT or ToastAndroid.LONG
*
* There is also a function `showWithGravity` to specify the layout gravity. May be
* ToastAndroid.TOP, ToastAndroid.BOTTOM, ToastAndroid.CENTER.
*
* The 'showWithGravityAndOffset' function adds on the ability to specify offset
* These offset values will translate to pixels.
*
* Basic usage:
* ```javascript
* ToastAndroid.show('A pikachu appeared nearby !', ToastAndroid.SHORT);
* ToastAndroid.showWithGravity('All Your Base Are Belong To Us', ToastAndroid.SHORT, ToastAndroid.CENTER);
* ToastAndroid.showWithGravityAndOffset('A wild toast appeared!', ToastAndroid.LONG, ToastAndroid.BOTTOM, 25, 50);
* ```
*/
const ToastAndroid = {
// Toast duration constants
SHORT: RCTToastAndroid.SHORT,
LONG: RCTToastAndroid.LONG,
// Toast gravity constants
TOP: RCTToastAndroid.TOP,
BOTTOM: RCTToastAndroid.BOTTOM,
CENTER: RCTToastAndroid.CENTER,
show: function (
message: string,
duration: number
): void {
RCTToastAndroid.show(message, duration);
},
showWithGravity: function (
message: string,
duration: number,
gravity: number,
): void {
RCTToastAndroid.showWithGravity(message, duration, gravity);
},
showWithGravityAndOffset: function (
message: string,
duration: number,
gravity: number,
xOffset: number,
yOffset: number,
): void {
RCTToastAndroid.showWithGravityAndOffset(message, duration, gravity, xOffset, yOffset);
},
};
module.exports = ToastAndroid;

View File

@@ -0,0 +1,25 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ToastAndroid
* @noflow
*/
'use strict';
const warning = require('fbjs/lib/warning');
const ToastAndroid = {
show: function (
message: string,
duration: number
): void {
warning(false, 'ToastAndroid is not supported on this platform.');
},
};
module.exports = ToastAndroid;

View File

@@ -0,0 +1,213 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ToolbarAndroid
*/
'use strict';
const Image = require('Image');
const NativeMethodsMixin = require('NativeMethodsMixin');
const React = require('React');
const PropTypes = require('prop-types');
const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
const UIManager = require('UIManager');
const ViewPropTypes = require('ViewPropTypes');
const ColorPropType = require('ColorPropType');
const createReactClass = require('create-react-class');
const requireNativeComponent = require('requireNativeComponent');
const resolveAssetSource = require('resolveAssetSource');
const optionalImageSource = PropTypes.oneOfType([
Image.propTypes.source,
// Image.propTypes.source is required but we want it to be optional, so we OR
// it with a nullable propType.
PropTypes.oneOf([]),
]);
/**
* React component that wraps the Android-only [`Toolbar` widget][0]. A Toolbar can display a logo,
* navigation icon (e.g. hamburger menu), a title & subtitle and a list of actions. The title and
* subtitle are expanded so the logo and navigation icons are displayed on the left, title and
* subtitle in the middle and the actions on the right.
*
* If the toolbar has an only child, it will be displayed between the title and actions.
*
* Although the Toolbar supports remote images for the logo, navigation and action icons, this
* should only be used in DEV mode where `require('./some_icon.png')` translates into a packager
* URL. In release mode you should always use a drawable resource for these icons. Using
* `require('./some_icon.png')` will do this automatically for you, so as long as you don't
* explicitly use e.g. `{uri: 'http://...'}`, you will be good.
*
* Example:
*
* ```
* render: function() {
* return (
* <ToolbarAndroid
* logo={require('./app_logo.png')}
* title="AwesomeApp"
* actions={[{title: 'Settings', icon: require('./icon_settings.png'), show: 'always'}]}
* onActionSelected={this.onActionSelected} />
* )
* },
* onActionSelected: function(position) {
* if (position === 0) { // index of 'Settings'
* showSettings();
* }
* }
* ```
*
* [0]: https://developer.android.com/reference/android/support/v7/widget/Toolbar.html
*/
const ToolbarAndroid = createReactClass({
displayName: 'ToolbarAndroid',
mixins: [NativeMethodsMixin],
propTypes: {
...ViewPropTypes,
/**
* Sets possible actions on the toolbar as part of the action menu. These are displayed as icons
* or text on the right side of the widget. If they don't fit they are placed in an 'overflow'
* menu.
*
* This property takes an array of objects, where each object has the following keys:
*
* * `title`: **required**, the title of this action
* * `icon`: the icon for this action, e.g. `require('./some_icon.png')`
* * `show`: when to show this action as an icon or hide it in the overflow menu: `always`,
* `ifRoom` or `never`
* * `showWithText`: boolean, whether to show text alongside the icon or not
*/
actions: PropTypes.arrayOf(PropTypes.shape({
title: PropTypes.string.isRequired,
icon: optionalImageSource,
show: PropTypes.oneOf(['always', 'ifRoom', 'never']),
showWithText: PropTypes.bool
})),
/**
* Sets the toolbar logo.
*/
logo: optionalImageSource,
/**
* Sets the navigation icon.
*/
navIcon: optionalImageSource,
/**
* Callback that is called when an action is selected. The only argument that is passed to the
* callback is the position of the action in the actions array.
*/
onActionSelected: PropTypes.func,
/**
* Callback called when the icon is selected.
*/
onIconClicked: PropTypes.func,
/**
* Sets the overflow icon.
*/
overflowIcon: optionalImageSource,
/**
* Sets the toolbar subtitle.
*/
subtitle: PropTypes.string,
/**
* Sets the toolbar subtitle color.
*/
subtitleColor: ColorPropType,
/**
* Sets the toolbar title.
*/
title: PropTypes.string,
/**
* Sets the toolbar title color.
*/
titleColor: ColorPropType,
/**
* Sets the content inset for the toolbar starting edge.
*
* The content inset affects the valid area for Toolbar content other than
* the navigation button and menu. Insets define the minimum margin for
* these components and can be used to effectively align Toolbar content
* along well-known gridlines.
*/
contentInsetStart: PropTypes.number,
/**
* Sets the content inset for the toolbar ending edge.
*
* The content inset affects the valid area for Toolbar content other than
* the navigation button and menu. Insets define the minimum margin for
* these components and can be used to effectively align Toolbar content
* along well-known gridlines.
*/
contentInsetEnd: PropTypes.number,
/**
* Used to set the toolbar direction to RTL.
* In addition to this property you need to add
*
* android:supportsRtl="true"
*
* to your application AndroidManifest.xml and then call
* `setLayoutDirection(LayoutDirection.RTL)` in your MainActivity
* `onCreate` method.
*/
rtl: PropTypes.bool,
/**
* Used to locate this view in end-to-end tests.
*/
testID: PropTypes.string,
},
render: function() {
const nativeProps = {
...this.props,
};
if (this.props.logo) {
nativeProps.logo = resolveAssetSource(this.props.logo);
}
if (this.props.navIcon) {
nativeProps.navIcon = resolveAssetSource(this.props.navIcon);
}
if (this.props.overflowIcon) {
nativeProps.overflowIcon = resolveAssetSource(this.props.overflowIcon);
}
if (this.props.actions) {
const nativeActions = [];
for (let i = 0; i < this.props.actions.length; i++) {
const action = {
...this.props.actions[i],
};
if (action.icon) {
action.icon = resolveAssetSource(action.icon);
}
if (action.show) {
action.show = UIManager.ToolbarAndroid.Constants.ShowAsAction[action.show];
}
nativeActions.push(action);
}
nativeProps.nativeActions = nativeActions;
}
return <NativeToolbar onSelect={this._onSelect} {...nativeProps} />;
},
_onSelect: function(event) {
const position = event.nativeEvent.position;
if (position === -1) {
this.props.onIconClicked && this.props.onIconClicked();
} else {
this.props.onActionSelected && this.props.onActionSelected(position);
}
},
});
const NativeToolbar = requireNativeComponent('ToolbarAndroid', ToolbarAndroid, {
nativeOnly: {
nativeActions: true,
}
});
module.exports = ToolbarAndroid;

View File

@@ -0,0 +1,11 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ToolbarAndroid
*/
'use strict';
module.exports = require('UnimplementedView');

View File

@@ -0,0 +1,46 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule BoundingDimensions
*/
'use strict';
const PooledClass = require('PooledClass');
const twoArgumentPooler = PooledClass.twoArgumentPooler;
/**
* PooledClass representing the bounding rectangle of a region.
*
* @param {number} width Width of bounding rectangle.
* @param {number} height Height of bounding rectangle.
* @constructor BoundingDimensions
*/
function BoundingDimensions(width, height) {
this.width = width;
this.height = height;
}
BoundingDimensions.prototype.destructor = function() {
this.width = null;
this.height = null;
};
/**
* @param {HTMLElement} element Element to return `BoundingDimensions` for.
* @return {BoundingDimensions} Bounding dimensions of `element`.
*/
BoundingDimensions.getPooledFromElement = function(element) {
return BoundingDimensions.getPooled(
element.offsetWidth,
element.offsetHeight
);
};
PooledClass.addPoolingTo(BoundingDimensions, twoArgumentPooler);
module.exports = BoundingDimensions;

View File

@@ -0,0 +1,121 @@
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule PooledClass
* @flow
*/
'use strict';
const invariant = require('fbjs/lib/invariant');
/**
* Static poolers. Several custom versions for each potential number of
* arguments. A completely generic pooler is easy to implement, but would
* require accessing the `arguments` object. In each of these, `this` refers to
* the Class itself, not an instance. If any others are needed, simply add them
* here, or in their own files.
*/
const oneArgumentPooler = function(copyFieldsFrom) {
const Klass = this;
if (Klass.instancePool.length) {
const instance = Klass.instancePool.pop();
Klass.call(instance, copyFieldsFrom);
return instance;
} else {
return new Klass(copyFieldsFrom);
}
};
const twoArgumentPooler = function(a1, a2) {
const Klass = this;
if (Klass.instancePool.length) {
const instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2);
return instance;
} else {
return new Klass(a1, a2);
}
};
const threeArgumentPooler = function(a1, a2, a3) {
const Klass = this;
if (Klass.instancePool.length) {
const instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3);
return instance;
} else {
return new Klass(a1, a2, a3);
}
};
const fourArgumentPooler = function(a1, a2, a3, a4) {
const Klass = this;
if (Klass.instancePool.length) {
const instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3, a4);
return instance;
} else {
return new Klass(a1, a2, a3, a4);
}
};
const standardReleaser = function(instance) {
const Klass = this;
invariant(
instance instanceof Klass,
'Trying to release an instance into a pool of a different type.',
);
instance.destructor();
if (Klass.instancePool.length < Klass.poolSize) {
Klass.instancePool.push(instance);
}
};
const DEFAULT_POOL_SIZE = 10;
const DEFAULT_POOLER = oneArgumentPooler;
type Pooler = any;
/**
* Augments `CopyConstructor` to be a poolable class, augmenting only the class
* itself (statically) not adding any prototypical fields. Any CopyConstructor
* you give this may have a `poolSize` property, and will look for a
* prototypical `destructor` on instances.
*
* @param {Function} CopyConstructor Constructor that can be used to reset.
* @param {Function} pooler Customizable pooler.
*/
const addPoolingTo = function<T>(
CopyConstructor: Class<T>,
pooler: Pooler,
): Class<T> & {
getPooled(
...args: $ReadOnlyArray<mixed>
): /* arguments of the constructor */ T,
release(instance: mixed): void,
} {
// Casting as any so that flow ignores the actual implementation and trusts
// it to match the type we declared
const NewKlass = (CopyConstructor: any);
NewKlass.instancePool = [];
NewKlass.getPooled = pooler || DEFAULT_POOLER;
if (!NewKlass.poolSize) {
NewKlass.poolSize = DEFAULT_POOL_SIZE;
}
NewKlass.release = standardReleaser;
return NewKlass;
};
const PooledClass = {
addPoolingTo: addPoolingTo,
oneArgumentPooler: (oneArgumentPooler: Pooler),
twoArgumentPooler: (twoArgumentPooler: Pooler),
threeArgumentPooler: (threeArgumentPooler: Pooler),
fourArgumentPooler: (fourArgumentPooler: Pooler),
};
module.exports = PooledClass;

View File

@@ -0,0 +1,36 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule Position
*/
'use strict';
const PooledClass = require('PooledClass');
const twoArgumentPooler = PooledClass.twoArgumentPooler;
/**
* Position does not expose methods for construction via an `HTMLDOMElement`,
* because it isn't meaningful to construct such a thing without first defining
* a frame of reference.
*
* @param {number} windowStartKey Key that window starts at.
* @param {number} windowEndKey Key that window ends at.
*/
function Position(left, top) {
this.left = left;
this.top = top;
}
Position.prototype.destructor = function() {
this.left = null;
this.top = null;
};
PooledClass.addPoolingTo(Position, twoArgumentPooler);
module.exports = Position;

View File

@@ -0,0 +1,806 @@
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule Touchable
*/
'use strict';
const BoundingDimensions = require('BoundingDimensions');
const Platform = require('Platform');
const Position = require('Position');
const React = require('React');
const ReactNative = require('ReactNative');
const TVEventHandler = require('TVEventHandler');
const TouchEventUtils = require('fbjs/lib/TouchEventUtils');
const UIManager = require('UIManager');
const View = require('View');
const keyMirror = require('fbjs/lib/keyMirror');
const normalizeColor = require('normalizeColor');
/**
* `Touchable`: Taps done right.
*
* You hook your `ResponderEventPlugin` events into `Touchable`. `Touchable`
* will measure time/geometry and tells you when to give feedback to the user.
*
* ====================== Touchable Tutorial ===============================
* The `Touchable` mixin helps you handle the "press" interaction. It analyzes
* the geometry of elements, and observes when another responder (scroll view
* etc) has stolen the touch lock. It notifies your component when it should
* give feedback to the user. (bouncing/highlighting/unhighlighting).
*
* - When a touch was activated (typically you highlight)
* - When a touch was deactivated (typically you unhighlight)
* - When a touch was "pressed" - a touch ended while still within the geometry
* of the element, and no other element (like scroller) has "stolen" touch
* lock ("responder") (Typically you bounce the element).
*
* A good tap interaction isn't as simple as you might think. There should be a
* slight delay before showing a highlight when starting a touch. If a
* subsequent touch move exceeds the boundary of the element, it should
* unhighlight, but if that same touch is brought back within the boundary, it
* should rehighlight again. A touch can move in and out of that boundary
* several times, each time toggling highlighting, but a "press" is only
* triggered if that touch ends while within the element's boundary and no
* scroller (or anything else) has stolen the lock on touches.
*
* To create a new type of component that handles interaction using the
* `Touchable` mixin, do the following:
*
* - Initialize the `Touchable` state.
*
* getInitialState: function() {
* return merge(this.touchableGetInitialState(), yourComponentState);
* }
*
* - Choose the rendered component who's touches should start the interactive
* sequence. On that rendered node, forward all `Touchable` responder
* handlers. You can choose any rendered node you like. Choose a node whose
* hit target you'd like to instigate the interaction sequence:
*
* // In render function:
* return (
* <View
* onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder}
* onResponderTerminationRequest={this.touchableHandleResponderTerminationRequest}
* onResponderGrant={this.touchableHandleResponderGrant}
* onResponderMove={this.touchableHandleResponderMove}
* onResponderRelease={this.touchableHandleResponderRelease}
* onResponderTerminate={this.touchableHandleResponderTerminate}>
* <View>
* Even though the hit detection/interactions are triggered by the
* wrapping (typically larger) node, we usually end up implementing
* custom logic that highlights this inner one.
* </View>
* </View>
* );
*
* - You may set up your own handlers for each of these events, so long as you
* also invoke the `touchable*` handlers inside of your custom handler.
*
* - Implement the handlers on your component class in order to provide
* feedback to the user. See documentation for each of these class methods
* that you should implement.
*
* touchableHandlePress: function() {
* this.performBounceAnimation(); // or whatever you want to do.
* },
* touchableHandleActivePressIn: function() {
* this.beginHighlighting(...); // Whatever you like to convey activation
* },
* touchableHandleActivePressOut: function() {
* this.endHighlighting(...); // Whatever you like to convey deactivation
* },
*
* - There are more advanced methods you can implement (see documentation below):
* touchableGetHighlightDelayMS: function() {
* return 20;
* }
* // In practice, *always* use a predeclared constant (conserve memory).
* touchableGetPressRectOffset: function() {
* return {top: 20, left: 20, right: 20, bottom: 100};
* }
*/
/**
* Touchable states.
*/
const States = keyMirror({
NOT_RESPONDER: null, // Not the responder
RESPONDER_INACTIVE_PRESS_IN: null, // Responder, inactive, in the `PressRect`
RESPONDER_INACTIVE_PRESS_OUT: null, // Responder, inactive, out of `PressRect`
RESPONDER_ACTIVE_PRESS_IN: null, // Responder, active, in the `PressRect`
RESPONDER_ACTIVE_PRESS_OUT: null, // Responder, active, out of `PressRect`
RESPONDER_ACTIVE_LONG_PRESS_IN: null, // Responder, active, in the `PressRect`, after long press threshold
RESPONDER_ACTIVE_LONG_PRESS_OUT: null, // Responder, active, out of `PressRect`, after long press threshold
ERROR: null
});
/**
* Quick lookup map for states that are considered to be "active"
*/
const IsActive = {
RESPONDER_ACTIVE_PRESS_OUT: true,
RESPONDER_ACTIVE_PRESS_IN: true
};
/**
* Quick lookup for states that are considered to be "pressing" and are
* therefore eligible to result in a "selection" if the press stops.
*/
const IsPressingIn = {
RESPONDER_INACTIVE_PRESS_IN: true,
RESPONDER_ACTIVE_PRESS_IN: true,
RESPONDER_ACTIVE_LONG_PRESS_IN: true,
};
const IsLongPressingIn = {
RESPONDER_ACTIVE_LONG_PRESS_IN: true,
};
/**
* Inputs to the state machine.
*/
const Signals = keyMirror({
DELAY: null,
RESPONDER_GRANT: null,
RESPONDER_RELEASE: null,
RESPONDER_TERMINATED: null,
ENTER_PRESS_RECT: null,
LEAVE_PRESS_RECT: null,
LONG_PRESS_DETECTED: null,
});
/**
* Mapping from States x Signals => States
*/
const Transitions = {
NOT_RESPONDER: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN,
RESPONDER_RELEASE: States.ERROR,
RESPONDER_TERMINATED: States.ERROR,
ENTER_PRESS_RECT: States.ERROR,
LEAVE_PRESS_RECT: States.ERROR,
LONG_PRESS_DETECTED: States.ERROR,
},
RESPONDER_INACTIVE_PRESS_IN: {
DELAY: States.RESPONDER_ACTIVE_PRESS_IN,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
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,
},
RESPONDER_INACTIVE_PRESS_OUT: {
DELAY: States.RESPONDER_ACTIVE_PRESS_OUT,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
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,
},
RESPONDER_ACTIVE_PRESS_IN: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
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,
},
RESPONDER_ACTIVE_PRESS_OUT: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
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,
},
RESPONDER_ACTIVE_LONG_PRESS_IN: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
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,
},
RESPONDER_ACTIVE_LONG_PRESS_OUT: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
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,
},
error: {
DELAY: States.NOT_RESPONDER,
RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.NOT_RESPONDER,
LEAVE_PRESS_RECT: States.NOT_RESPONDER,
LONG_PRESS_DETECTED: States.NOT_RESPONDER,
}
};
// ==== Typical Constants for integrating into UI components ====
// var HIT_EXPAND_PX = 20;
// var HIT_VERT_OFFSET_PX = 10;
const HIGHLIGHT_DELAY_MS = 130;
const PRESS_EXPAND_PX = 20;
const LONG_PRESS_THRESHOLD = 500;
const LONG_PRESS_DELAY_MS = LONG_PRESS_THRESHOLD - HIGHLIGHT_DELAY_MS;
const LONG_PRESS_ALLOWED_MOVEMENT = 10;
// Default amount "active" region protrudes beyond box
/**
* By convention, methods prefixed with underscores are meant to be @private,
* and not @protected. Mixers shouldn't access them - not even to provide them
* as callback handlers.
*
*
* ========== Geometry =========
* `Touchable` only assumes that there exists a `HitRect` node. The `PressRect`
* is an abstract box that is extended beyond the `HitRect`.
*
* +--------------------------+
* | | - "Start" events in `HitRect` cause `HitRect`
* | +--------------------+ | to become the responder.
* | | +--------------+ | | - `HitRect` is typically expanded around
* | | | | | | the `VisualRect`, but shifted downward.
* | | | VisualRect | | | - After pressing down, after some delay,
* | | | | | | and before letting up, the Visual React
* | | +--------------+ | | will become "active". This makes it eligible
* | | HitRect | | for being highlighted (so long as the
* | +--------------------+ | press remains in the `PressRect`).
* | PressRect o |
* +----------------------|---+
* Out Region |
* +-----+ This gap between the `HitRect` and
* `PressRect` allows a touch to move far away
* from the original hit rect, and remain
* highlighted, and eligible for a "Press".
* Customize this via
* `touchableGetPressRectOffset()`.
*
*
*
* ======= State Machine =======
*
* +-------------+ <---+ RESPONDER_RELEASE
* |NOT_RESPONDER|
* +-------------+ <---+ RESPONDER_TERMINATED
* +
* | RESPONDER_GRANT (HitRect)
* v
* +---------------------------+ DELAY +-------------------------+ T + DELAY +------------------------------+
* |RESPONDER_INACTIVE_PRESS_IN|+-------->|RESPONDER_ACTIVE_PRESS_IN| +------------> |RESPONDER_ACTIVE_LONG_PRESS_IN|
* +---------------------------+ +-------------------------+ +------------------------------+
* + ^ + ^ + ^
* |LEAVE_ |ENTER_ |LEAVE_ |ENTER_ |LEAVE_ |ENTER_
* |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT
* | | | | | |
* v + v + v +
* +----------------------------+ DELAY +--------------------------+ +-------------------------------+
* |RESPONDER_INACTIVE_PRESS_OUT|+------->|RESPONDER_ACTIVE_PRESS_OUT| |RESPONDER_ACTIVE_LONG_PRESS_OUT|
* +----------------------------+ +--------------------------+ +-------------------------------+
*
* T + DELAY => LONG_PRESS_DELAY_MS + DELAY
*
* Not drawn are the side effects of each transition. The most important side
* effect is the `touchableHandlePress` abstract method invocation that occurs
* when a responder is released while in either of the "Press" states.
*
* The other important side effects are the highlight abstract method
* invocations (internal callbacks) to be implemented by the mixer.
*
*
* @lends Touchable.prototype
*/
const TouchableMixin = {
componentDidMount: function() {
if (!Platform.isTV) {
return;
}
this._tvEventHandler = new TVEventHandler();
this._tvEventHandler.enable(this, function(cmp, evt) {
const myTag = ReactNative.findNodeHandle(cmp);
evt.dispatchConfig = {};
if (myTag === evt.tag) {
if (evt.eventType === 'focus') {
cmp.touchableHandleActivePressIn && cmp.touchableHandleActivePressIn(evt);
} else if (evt.eventType === 'blur') {
cmp.touchableHandleActivePressOut && cmp.touchableHandleActivePressOut(evt);
} else if (evt.eventType === 'select') {
cmp.touchableHandlePress && !cmp.props.disabled && cmp.touchableHandlePress(evt);
}
}
});
},
/**
* Clear all timeouts on unmount
*/
componentWillUnmount: function() {
if (this._tvEventHandler) {
this._tvEventHandler.disable();
delete this._tvEventHandler;
}
this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout);
this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout);
this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout);
},
/**
* It's prefer that mixins determine state in this way, having the class
* explicitly mix the state in the one and only `getInitialState` method.
*
* @return {object} State object to be placed inside of
* `this.state.touchable`.
*/
touchableGetInitialState: function() {
return {
touchable: {touchState: undefined, responderID: null}
};
},
// ==== Hooks to Gesture Responder system ====
/**
* Must return true if embedded in a native platform scroll view.
*/
touchableHandleResponderTerminationRequest: function() {
return !this.props.rejectResponderTermination;
},
/**
* Must return true to start the process of `Touchable`.
*/
touchableHandleStartShouldSetResponder: function() {
return !this.props.disabled;
},
/**
* Return true to cancel press on long press.
*/
touchableLongPressCancelsPress: function () {
return true;
},
/**
* Place as callback for a DOM element's `onResponderGrant` event.
* @param {SyntheticEvent} e Synthetic event from event system.
*
*/
touchableHandleResponderGrant: function(e) {
const dispatchID = e.currentTarget;
// Since e is used in a callback invoked on another event loop
// (as in setTimeout etc), we need to call e.persist() on the
// event to make sure it doesn't get reused in the event object pool.
e.persist();
this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout);
this.pressOutDelayTimeout = null;
this.state.touchable.touchState = States.NOT_RESPONDER;
this.state.touchable.responderID = dispatchID;
this._receiveSignal(Signals.RESPONDER_GRANT, e);
let 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
);
} else {
this._handleDelay(e);
}
let 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),
longDelayMS + delayMS
);
},
/**
* Place as callback for a DOM element's `onResponderRelease` event.
*/
touchableHandleResponderRelease: function(e) {
this._receiveSignal(Signals.RESPONDER_RELEASE, e);
},
/**
* Place as callback for a DOM element's `onResponderTerminate` event.
*/
touchableHandleResponderTerminate: function(e) {
this._receiveSignal(Signals.RESPONDER_TERMINATED, e);
},
/**
* Place as callback for a DOM element's `onResponderMove` event.
*/
touchableHandleResponderMove: function(e) {
// Not enough time elapsed yet, wait for highlight -
// this is just a perf optimization.
if (this.state.touchable.touchState === States.RESPONDER_INACTIVE_PRESS_IN) {
return;
}
// Measurement may not have returned yet.
if (!this.state.touchable.positionOnActivate) {
return;
}
const positionOnActivate = this.state.touchable.positionOnActivate;
const dimensionsOnActivate = this.state.touchable.dimensionsOnActivate;
const pressRectOffset = this.touchableGetPressRectOffset ?
this.touchableGetPressRectOffset() : {
left: PRESS_EXPAND_PX,
right: PRESS_EXPAND_PX,
top: PRESS_EXPAND_PX,
bottom: PRESS_EXPAND_PX
};
let pressExpandLeft = pressRectOffset.left;
let pressExpandTop = pressRectOffset.top;
let pressExpandRight = pressRectOffset.right;
let pressExpandBottom = pressRectOffset.bottom;
const hitSlop = this.touchableGetHitSlop ?
this.touchableGetHitSlop() : null;
if (hitSlop) {
pressExpandLeft += hitSlop.left;
pressExpandTop += hitSlop.top;
pressExpandRight += hitSlop.right;
pressExpandBottom += hitSlop.bottom;
}
const touch = TouchEventUtils.extractSingleTouch(e.nativeEvent);
const pageX = touch && touch.pageX;
const pageY = touch && touch.pageY;
if (this.pressInLocation) {
const movedDistance = this._getDistanceBetweenPoints(pageX, pageY, this.pressInLocation.pageX, this.pressInLocation.pageY);
if (movedDistance > LONG_PRESS_ALLOWED_MOVEMENT) {
this._cancelLongPressDelayTimeout();
}
}
const 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);
const curState = this.state.touchable.touchState;
if (curState === States.RESPONDER_INACTIVE_PRESS_IN) {
// fix for t7967420
this._cancelLongPressDelayTimeout();
}
} else {
this._cancelLongPressDelayTimeout();
this._receiveSignal(Signals.LEAVE_PRESS_RECT, e);
}
},
// ==== Abstract Application Callbacks ====
/**
* Invoked when the item should be highlighted. Mixers should implement this
* to visually distinguish the `VisualRect` so that the user knows that
* releasing a touch will result in a "selection" (analog to click).
*
* @abstract
* touchableHandleActivePressIn: function,
*/
/**
* Invoked when the item is "active" (in that it is still eligible to become
* a "select") but the touch has left the `PressRect`. Usually the mixer will
* want to unhighlight the `VisualRect`. If the user (while pressing) moves
* back into the `PressRect` `touchableHandleActivePressIn` will be invoked
* again and the mixer should probably highlight the `VisualRect` again. This
* event will not fire on an `touchEnd/mouseUp` event, only move events while
* the user is depressing the mouse/touch.
*
* @abstract
* touchableHandleActivePressOut: function
*/
/**
* Invoked when the item is "selected" - meaning the interaction ended by
* letting up while the item was either in the state
* `RESPONDER_ACTIVE_PRESS_IN` or `RESPONDER_INACTIVE_PRESS_IN`.
*
* @abstract
* touchableHandlePress: function
*/
/**
* Invoked when the item is long pressed - meaning the interaction ended by
* letting up while the item was in `RESPONDER_ACTIVE_LONG_PRESS_IN`. If
* `touchableHandleLongPress` is *not* provided, `touchableHandlePress` will
* be called as it normally is. If `touchableHandleLongPress` is provided, by
* default any `touchableHandlePress` callback will not be invoked. To
* override this default behavior, override `touchableLongPressCancelsPress`
* to return false. As a result, `touchableHandlePress` will be called when
* lifting up, even if `touchableHandleLongPress` has also been called.
*
* @abstract
* touchableHandleLongPress: function
*/
/**
* Returns the number of millis to wait before triggering a highlight.
*
* @abstract
* touchableGetHighlightDelayMS: function
*/
/**
* Returns the amount to extend the `HitRect` into the `PressRect`. Positive
* numbers mean the size expands outwards.
*
* @abstract
* touchableGetPressRectOffset: function
*/
// ==== Internal Logic ====
/**
* Measures the `HitRect` node on activation. The Bounding rectangle is with
* respect to viewport - not page, so adding the `pageXOffset/pageYOffset`
* should result in points that are in the same coordinate system as an
* event's `globalX/globalY` data values.
*
* - Consider caching this for the lifetime of the component, or possibly
* being able to share this cache between any `ScrollMap` view.
*
* @sideeffects
* @private
*/
_remeasureMetricsOnActivation: function() {
const tag = this.state.touchable.responderID;
if (tag == null) {
return;
}
UIManager.measure(tag, this._handleQueryLayout);
},
_handleQueryLayout: function(l, t, w, h, globalX, globalY) {
//don't do anything UIManager failed to measure node
if (!l && !t && !w && !h && !globalX && !globalY) {
return;
}
this.state.touchable.positionOnActivate &&
Position.release(this.state.touchable.positionOnActivate);
this.state.touchable.dimensionsOnActivate &&
BoundingDimensions.release(this.state.touchable.dimensionsOnActivate);
this.state.touchable.positionOnActivate = Position.getPooled(globalX, globalY);
this.state.touchable.dimensionsOnActivate = BoundingDimensions.getPooled(w, h);
},
_handleDelay: function(e) {
this.touchableDelayTimeout = null;
this._receiveSignal(Signals.DELAY, e);
},
_handleLongDelay: function(e) {
this.longPressDelayTimeout = null;
const 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.');
} else {
this._receiveSignal(Signals.LONG_PRESS_DETECTED, e);
}
},
/**
* Receives a state machine signal, performs side effects of the transition
* and stores the new state. Validates the transition as well.
*
* @param {Signals} signal State machine signal.
* @throws Error if invalid state transition or unrecognized signal.
* @sideeffects
*/
_receiveSignal: function(signal, e) {
const responderID = this.state.touchable.responderID;
const curState = this.state.touchable.touchState;
const nextState = Transitions[curState] && Transitions[curState][signal];
if (!responderID && signal === Signals.RESPONDER_RELEASE) {
return;
}
if (!nextState) {
throw new Error(
'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 + '`'
);
}
if (curState !== nextState) {
this._performSideEffectsForTransition(curState, nextState, signal, e);
this.state.touchable.touchState = nextState;
}
},
_cancelLongPressDelayTimeout: function () {
this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout);
this.longPressDelayTimeout = null;
},
_isHighlight: function (state) {
return state === States.RESPONDER_ACTIVE_PRESS_IN ||
state === States.RESPONDER_ACTIVE_LONG_PRESS_IN;
},
_savePressInLocation: function(e) {
const touch = TouchEventUtils.extractSingleTouch(e.nativeEvent);
const pageX = touch && touch.pageX;
const pageY = touch && touch.pageY;
const locationX = touch && touch.locationX;
const locationY = touch && touch.locationY;
this.pressInLocation = {pageX, pageY, locationX, locationY};
},
_getDistanceBetweenPoints: function (aX, aY, bX, bY) {
const deltaX = aX - bX;
const deltaY = aY - bY;
return Math.sqrt(deltaX * deltaX + deltaY * deltaY);
},
/**
* Will perform a transition between touchable states, and identify any
* highlighting or unhighlighting that must be performed for this particular
* transition.
*
* @param {States} curState Current Touchable state.
* @param {States} nextState Next Touchable state.
* @param {Signal} signal Signal that triggered the transition.
* @param {Event} e Native event.
* @sideeffects
*/
_performSideEffectsForTransition: function(curState, nextState, signal, e) {
const curIsHighlight = this._isHighlight(curState);
const newIsHighlight = this._isHighlight(nextState);
const isFinalSignal =
signal === Signals.RESPONDER_TERMINATED ||
signal === Signals.RESPONDER_RELEASE;
if (isFinalSignal) {
this._cancelLongPressDelayTimeout();
}
if (!IsActive[curState] && IsActive[nextState]) {
this._remeasureMetricsOnActivation();
}
if (IsPressingIn[curState] && signal === Signals.LONG_PRESS_DETECTED) {
this.touchableHandleLongPress && this.touchableHandleLongPress(e);
}
if (newIsHighlight && !curIsHighlight) {
this._startHighlight(e);
} else if (!newIsHighlight && curIsHighlight) {
this._endHighlight(e);
}
if (IsPressingIn[curState] && signal === Signals.RESPONDER_RELEASE) {
const hasLongPressHandler = !!this.props.onLongPress;
const pressIsLongButStillCallOnPress =
IsLongPressingIn[curState] && ( // We *are* long pressing..
(// But either has no long handler
!hasLongPressHandler || !this.touchableLongPressCancelsPress()) // or we're told to ignore it.
);
const shouldInvokePress = !IsLongPressingIn[curState] || pressIsLongButStillCallOnPress;
if (shouldInvokePress && this.touchableHandlePress) {
if (!newIsHighlight && !curIsHighlight) {
// we never highlighted because of delay, but we should highlight now
this._startHighlight(e);
this._endHighlight(e);
}
this.touchableHandlePress(e);
}
}
this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout);
this.touchableDelayTimeout = null;
},
_startHighlight: function(e) {
this._savePressInLocation(e);
this.touchableHandleActivePressIn && this.touchableHandleActivePressIn(e);
},
_endHighlight: function(e) {
if (this.touchableHandleActivePressOut) {
if (this.touchableGetPressOutDelayMS && this.touchableGetPressOutDelayMS()) {
this.pressOutDelayTimeout = setTimeout(() => {
this.touchableHandleActivePressOut(e);
}, this.touchableGetPressOutDelayMS());
} else {
this.touchableHandleActivePressOut(e);
}
}
},
};
const Touchable = {
Mixin: TouchableMixin,
TOUCH_TARGET_DEBUG: false, // Highlights all touchable targets. Toggle with Inspector.
/**
* Renders a debugging overlay to visualize touch target with hitSlop (might not work on Android).
*/
renderDebugView: ({color, hitSlop}) => {
if (!Touchable.TOUCH_TARGET_DEBUG) {
return null;
}
if (!__DEV__) {
throw Error('Touchable.TOUCH_TARGET_DEBUG should not be enabled in prod!');
}
const debugHitSlopStyle = {};
hitSlop = hitSlop || {top: 0, bottom: 0, left: 0, right: 0};
for (const key in hitSlop) {
debugHitSlopStyle[key] = -hitSlop[key];
}
const hexColor = '#' + ('00000000' + normalizeColor(color).toString(16)).substr(-8);
return (
<View
pointerEvents="none"
style={{
position: 'absolute',
borderColor: hexColor.slice(0, -2) + '55', // More opaque
borderWidth: 1,
borderStyle: 'dashed',
backgroundColor: hexColor.slice(0, -2) + '0F', // Less opaque
...debugHitSlopStyle
}}
/>
);
}
};
module.exports = Touchable;

View File

@@ -0,0 +1,203 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule TouchableBounce
* @flow
* @format
*/
'use strict';
const Animated = require('Animated');
const EdgeInsetsPropType = require('EdgeInsetsPropType');
const NativeMethodsMixin = require('NativeMethodsMixin');
const React = require('React');
const createReactClass = require('create-react-class');
const PropTypes = require('prop-types');
const Touchable = require('Touchable');
type Event = Object;
type State = {
animationID: ?number,
scale: Animated.Value,
};
const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};
/**
* Example of using the `TouchableMixin` to play well with other responder
* locking views including `ScrollView`. `TouchableMixin` provides touchable
* hooks (`this.touchableHandle*`) that we forward events to. In turn,
* `TouchableMixin` expects us to implement some abstract methods to handle
* interesting interactions such as `handleTouchablePress`.
*/
const TouchableBounce = createReactClass({
displayName: 'TouchableBounce',
mixins: [Touchable.Mixin, NativeMethodsMixin],
propTypes: {
/**
* When true, indicates that the view is an accessibility element. By default,
* all the touchable elements are accessible.
*/
accessible: PropTypes.bool,
onPress: PropTypes.func,
onPressIn: PropTypes.func,
onPressOut: PropTypes.func,
// The function passed takes a callback to start the animation which should
// be run after this onPress handler is done. You can use this (for example)
// to update UI before starting the animation.
onPressWithCompletion: PropTypes.func,
// the function passed is called after the animation is complete
onPressAnimationComplete: PropTypes.func,
/**
* When the scroll view is disabled, this defines how far your touch may
* move off of the button, before deactivating the button. Once deactivated,
* try moving it back and you'll see that the button is once again
* reactivated! Move it back and forth several times while the scroll view
* is disabled. Ensure you pass in a constant to reduce memory allocations.
*/
pressRetentionOffset: EdgeInsetsPropType,
/**
* This defines how far your touch can start away from the button. This is
* added to `pressRetentionOffset` when moving off of the button.
* ** NOTE **
* The touch area never extends past the parent view bounds and the Z-index
* of sibling views always takes precedence if a touch hits two overlapping
* views.
*/
hitSlop: EdgeInsetsPropType,
releaseVelocity: PropTypes.number.isRequired,
releaseBounciness: PropTypes.number.isRequired,
},
getDefaultProps: function() {
return {releaseBounciness: 10, releaseVelocity: 10};
},
getInitialState: function(): State {
return {
...this.touchableGetInitialState(),
scale: new Animated.Value(1),
};
},
bounceTo: function(
value: number,
velocity: number,
bounciness: number,
callback?: ?Function,
) {
Animated.spring(this.state.scale, {
toValue: value,
velocity,
bounciness,
useNativeDriver: true,
}).start(callback);
},
/**
* `Touchable.Mixin` self callbacks. The mixin will invoke these if they are
* defined on your component.
*/
touchableHandleActivePressIn: function(e: Event) {
this.bounceTo(0.93, 0.1, 0);
this.props.onPressIn && this.props.onPressIn(e);
},
touchableHandleActivePressOut: function(e: Event) {
this.bounceTo(1, 0.4, 0);
this.props.onPressOut && this.props.onPressOut(e);
},
touchableHandlePress: function(e: Event) {
const onPressWithCompletion = this.props.onPressWithCompletion;
if (onPressWithCompletion) {
onPressWithCompletion(() => {
this.state.scale.setValue(0.93);
this.bounceTo(
1,
this.props.releaseVelocity,
this.props.releaseBounciness,
this.props.onPressAnimationComplete,
);
});
return;
}
this.bounceTo(
1,
this.props.releaseVelocity,
this.props.releaseBounciness,
this.props.onPressAnimationComplete,
);
this.props.onPress && this.props.onPress(e);
},
touchableGetPressRectOffset: function(): typeof PRESS_RETENTION_OFFSET {
return this.props.pressRetentionOffset || PRESS_RETENTION_OFFSET;
},
touchableGetHitSlop: function(): ?Object {
return this.props.hitSlop;
},
touchableGetHighlightDelayMS: function(): number {
return 0;
},
render: function(): React.Element<any> {
return (
<Animated.View
/* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This
* comment suppresses an error when upgrading Flow's support for React.
* To see the error delete this comment and run Flow. */
style={[{transform: [{scale: this.state.scale}]}, this.props.style]}
accessible={this.props.accessible !== false}
/* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This
* comment suppresses an error when upgrading Flow's support for React.
* To see the error delete this comment and run Flow. */
accessibilityLabel={this.props.accessibilityLabel}
/* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This
* comment suppresses an error when upgrading Flow's support for React.
* To see the error delete this comment and run Flow. */
accessibilityComponentType={this.props.accessibilityComponentType}
/* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This
* comment suppresses an error when upgrading Flow's support for React.
* To see the error delete this comment and run Flow. */
accessibilityTraits={this.props.accessibilityTraits}
/* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This
* comment suppresses an error when upgrading Flow's support for React.
* To see the error delete this comment and run Flow. */
nativeID={this.props.nativeID}
/* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This
* comment suppresses an error when upgrading Flow's support for React.
* To see the error delete this comment and run Flow. */
testID={this.props.testID}
hitSlop={this.props.hitSlop}
onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder}
onResponderTerminationRequest={
this.touchableHandleResponderTerminationRequest
}
onResponderGrant={this.touchableHandleResponderGrant}
onResponderMove={this.touchableHandleResponderMove}
onResponderRelease={this.touchableHandleResponderRelease}
onResponderTerminate={this.touchableHandleResponderTerminate}>
{
// $FlowFixMe(>=0.41.0)
this.props.children
}
{Touchable.renderDebugView({
color: 'orange',
hitSlop: this.props.hitSlop,
})}
</Animated.View>
);
},
});
module.exports = TouchableBounce;

View File

@@ -0,0 +1,368 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule TouchableHighlight
* @flow
* @format
*/
'use strict';
const ColorPropType = require('ColorPropType');
const NativeMethodsMixin = require('NativeMethodsMixin');
const PropTypes = require('prop-types');
const Platform = require('Platform');
const React = require('React');
const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
const StyleSheet = require('StyleSheet');
const Touchable = require('Touchable');
const TouchableWithoutFeedback = require('TouchableWithoutFeedback');
const View = require('View');
const ViewPropTypes = require('ViewPropTypes');
const createReactClass = require('create-react-class');
const ensurePositiveDelayProps = require('ensurePositiveDelayProps');
import type {PressEvent} from 'CoreEventTypes';
const DEFAULT_PROPS = {
activeOpacity: 0.85,
delayPressOut: 100,
underlayColor: 'black',
};
const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};
/**
* A wrapper for making views respond properly to touches.
* On press down, the opacity of the wrapped view is decreased, which allows
* the underlay color to show through, darkening or tinting the view.
*
* The underlay comes from wrapping the child in a new View, which can affect
* layout, and sometimes cause unwanted visual artifacts if not used correctly,
* for example if the backgroundColor of the wrapped view isn't explicitly set
* to an opaque color.
*
* TouchableHighlight must have one child (not zero or more than one).
* If you wish to have several child components, wrap them in a View.
*
* Example:
*
* ```
* renderButton: function() {
* return (
* <TouchableHighlight onPress={this._onPressButton}>
* <Image
* style={styles.button}
* source={require('./myButton.png')}
* />
* </TouchableHighlight>
* );
* },
* ```
*
*
* ### Example
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react'
* import {
* AppRegistry,
* StyleSheet,
* TouchableHighlight,
* Text,
* View,
* } from 'react-native'
*
* class App extends Component {
* constructor(props) {
* super(props)
* this.state = { count: 0 }
* }
*
* onPress = () => {
* this.setState({
* count: this.state.count+1
* })
* }
*
* render() {
* return (
* <View style={styles.container}>
* <TouchableHighlight
* style={styles.button}
* onPress={this.onPress}
* >
* <Text> Touch Here </Text>
* </TouchableHighlight>
* <View style={[styles.countContainer]}>
* <Text style={[styles.countText]}>
* { this.state.count !== 0 ? this.state.count: null}
* </Text>
* </View>
* </View>
* )
* }
* }
*
* const styles = StyleSheet.create({
* container: {
* flex: 1,
* justifyContent: 'center',
* paddingHorizontal: 10
* },
* button: {
* alignItems: 'center',
* backgroundColor: '#DDDDDD',
* padding: 10
* },
* countContainer: {
* alignItems: 'center',
* padding: 10
* },
* countText: {
* color: '#FF00FF'
* }
* })
*
* AppRegistry.registerComponent('App', () => App)
* ```
*
*/
const TouchableHighlight = createReactClass({
displayName: 'TouchableHighlight',
propTypes: {
...TouchableWithoutFeedback.propTypes,
/**
* Determines what the opacity of the wrapped view should be when touch is
* active.
*/
activeOpacity: PropTypes.number,
/**
* The color of the underlay that will show through when the touch is
* active.
*/
underlayColor: ColorPropType,
/**
* Style to apply to the container/underlay. Most commonly used to make sure
* rounded corners match the wrapped component.
*/
style: ViewPropTypes.style,
/**
* Called immediately after the underlay is shown
*/
onShowUnderlay: PropTypes.func,
/**
* Called immediately after the underlay is hidden
*/
onHideUnderlay: PropTypes.func,
/**
* *(Apple TV only)* TV preferred focus (see documentation for the View component).
*
* @platform ios
*/
hasTVPreferredFocus: PropTypes.bool,
/**
* *(Apple TV only)* Object with properties to control Apple TV parallax effects.
*
* enabled: If true, parallax effects are enabled. Defaults to true.
* shiftDistanceX: Defaults to 2.0.
* shiftDistanceY: Defaults to 2.0.
* tiltAngle: Defaults to 0.05.
* magnification: Defaults to 1.0.
* pressMagnification: Defaults to 1.0.
* pressDuration: Defaults to 0.3.
* pressDelay: Defaults to 0.0.
*
* @platform ios
*/
tvParallaxProperties: PropTypes.object,
/**
* Handy for snapshot tests.
*/
testOnly_pressed: PropTypes.bool,
},
mixins: [NativeMethodsMixin, Touchable.Mixin],
getDefaultProps: () => DEFAULT_PROPS,
getInitialState: function() {
this._isMounted = false;
if (this.props.testOnly_pressed) {
return {
...this.touchableGetInitialState(),
extraChildStyle: {
opacity: this.props.activeOpacity,
},
extraUnderlayStyle: {
backgroundColor: this.props.underlayColor,
},
};
} else {
return {
...this.touchableGetInitialState(),
extraChildStyle: null,
extraUnderlayStyle: null,
};
}
},
componentDidMount: function() {
this._isMounted = true;
ensurePositiveDelayProps(this.props);
},
componentWillUnmount: function() {
this._isMounted = false;
clearTimeout(this._hideTimeout);
},
UNSAFE_componentWillReceiveProps: function(nextProps) {
ensurePositiveDelayProps(nextProps);
},
viewConfig: {
uiViewClassName: 'RCTView',
validAttributes: ReactNativeViewAttributes.RCTView,
},
/**
* `Touchable.Mixin` self callbacks. The mixin will invoke these if they are
* defined on your component.
*/
touchableHandleActivePressIn: function(e: PressEvent) {
clearTimeout(this._hideTimeout);
this._hideTimeout = null;
this._showUnderlay();
this.props.onPressIn && this.props.onPressIn(e);
},
touchableHandleActivePressOut: function(e: PressEvent) {
if (!this._hideTimeout) {
this._hideUnderlay();
}
this.props.onPressOut && this.props.onPressOut(e);
},
touchableHandlePress: function(e: PressEvent) {
clearTimeout(this._hideTimeout);
if (!Platform.isTVOS) {
this._showUnderlay();
this._hideTimeout = setTimeout(
this._hideUnderlay,
this.props.delayPressOut,
);
}
this.props.onPress && this.props.onPress(e);
},
touchableHandleLongPress: function(e: PressEvent) {
this.props.onLongPress && this.props.onLongPress(e);
},
touchableGetPressRectOffset: function() {
return this.props.pressRetentionOffset || PRESS_RETENTION_OFFSET;
},
touchableGetHitSlop: function() {
return this.props.hitSlop;
},
touchableGetHighlightDelayMS: function() {
return this.props.delayPressIn;
},
touchableGetLongPressDelayMS: function() {
return this.props.delayLongPress;
},
touchableGetPressOutDelayMS: function() {
return this.props.delayPressOut;
},
_showUnderlay: function() {
if (!this._isMounted || !this._hasPressHandler()) {
return;
}
this.setState({
extraChildStyle: {
opacity: this.props.activeOpacity,
},
extraUnderlayStyle: {
backgroundColor: this.props.underlayColor,
},
});
this.props.onShowUnderlay && this.props.onShowUnderlay();
},
_hideUnderlay: function() {
clearTimeout(this._hideTimeout);
this._hideTimeout = null;
if (this.props.testOnly_pressed) {
return;
}
if (this._hasPressHandler()) {
this.setState({
extraChildStyle: null,
extraUnderlayStyle: null,
});
this.props.onHideUnderlay && this.props.onHideUnderlay();
}
},
_hasPressHandler: function() {
return !!(
this.props.onPress ||
this.props.onPressIn ||
this.props.onPressOut ||
this.props.onLongPress
);
},
render: function() {
const child = React.Children.only(this.props.children);
return (
<View
accessible={this.props.accessible !== false}
accessibilityLabel={this.props.accessibilityLabel}
accessibilityComponentType={this.props.accessibilityComponentType}
accessibilityTraits={this.props.accessibilityTraits}
style={StyleSheet.compose(
this.props.style,
this.state.extraUnderlayStyle,
)}
onLayout={this.props.onLayout}
hitSlop={this.props.hitSlop}
isTVSelectable={true}
tvParallaxProperties={this.props.tvParallaxProperties}
hasTVPreferredFocus={this.props.hasTVPreferredFocus}
onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder}
onResponderTerminationRequest={
this.touchableHandleResponderTerminationRequest
}
onResponderGrant={this.touchableHandleResponderGrant}
onResponderMove={this.touchableHandleResponderMove}
onResponderRelease={this.touchableHandleResponderRelease}
onResponderTerminate={this.touchableHandleResponderTerminate}
nativeID={this.props.nativeID}
testID={this.props.testID}>
{React.cloneElement(child, {
style: StyleSheet.compose(
child.props.style,
this.state.extraChildStyle,
),
})}
{Touchable.renderDebugView({
color: 'green',
hitSlop: this.props.hitSlop,
})}
</View>
);
},
});
module.exports = TouchableHighlight;

View File

@@ -0,0 +1,274 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule TouchableNativeFeedback
*/
'use strict';
const Platform = require('Platform');
const React = require('React');
const PropTypes = require('prop-types');
const ReactNative = require('ReactNative');
const Touchable = require('Touchable');
const TouchableWithoutFeedback = require('TouchableWithoutFeedback');
const UIManager = require('UIManager');
const createReactClass = require('create-react-class');
const ensurePositiveDelayProps = require('ensurePositiveDelayProps');
const processColor = require('processColor');
const rippleBackgroundPropType = PropTypes.shape({
type: PropTypes.oneOf(['RippleAndroid']),
color: PropTypes.number,
borderless: PropTypes.bool,
});
const themeAttributeBackgroundPropType = PropTypes.shape({
type: PropTypes.oneOf(['ThemeAttrAndroid']),
attribute: PropTypes.string.isRequired,
});
const backgroundPropType = PropTypes.oneOfType([
rippleBackgroundPropType,
themeAttributeBackgroundPropType,
]);
type Event = Object;
const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};
/**
* A wrapper for making views respond properly to touches (Android only).
* On Android this component uses native state drawable to display touch
* feedback.
*
* At the moment it only supports having a single View instance as a child
* node, as it's implemented by replacing that View with another instance of
* RCTView node with some additional properties set.
*
* Background drawable of native feedback touchable can be customized with
* `background` property.
*
* Example:
*
* ```
* renderButton: function() {
* return (
* <TouchableNativeFeedback
* onPress={this._onPressButton}
* background={TouchableNativeFeedback.SelectableBackground()}>
* <View style={{width: 150, height: 100, backgroundColor: 'red'}}>
* <Text style={{margin: 30}}>Button</Text>
* </View>
* </TouchableNativeFeedback>
* );
* },
* ```
*/
const TouchableNativeFeedback = createReactClass({
displayName: 'TouchableNativeFeedback',
propTypes: {
...TouchableWithoutFeedback.propTypes,
/**
* Determines the type of background drawable that's going to be used to
* display feedback. It takes an object with `type` property and extra data
* depending on the `type`. It's recommended to use one of the static
* methods to generate that dictionary.
*/
background: backgroundPropType,
/**
* TV preferred focus (see documentation for the View component).
*/
hasTVPreferredFocus: PropTypes.bool,
/**
* Set to true to add the ripple effect to the foreground of the view, instead of the
* background. This is useful if one of your child views has a background of its own, or you're
* e.g. displaying images, and you don't want the ripple to be covered by them.
*
* Check TouchableNativeFeedback.canUseNativeForeground() first, as this is only available on
* Android 6.0 and above. If you try to use this on older versions you will get a warning and
* fallback to background.
*/
useForeground: PropTypes.bool,
},
statics: {
/**
* Creates an object that represents android theme's default background for
* selectable elements (?android:attr/selectableItemBackground).
*/
SelectableBackground: function() {
return {type: 'ThemeAttrAndroid', attribute: 'selectableItemBackground'};
},
/**
* Creates an object that represent android theme's default background for borderless
* selectable elements (?android:attr/selectableItemBackgroundBorderless).
* Available on android API level 21+.
*/
SelectableBackgroundBorderless: function() {
return {type: 'ThemeAttrAndroid', attribute: 'selectableItemBackgroundBorderless'};
},
/**
* Creates an object that represents ripple drawable with specified color (as a
* string). If property `borderless` evaluates to true the ripple will
* render outside of the view bounds (see native actionbar buttons as an
* example of that behavior). This background type is available on Android
* API level 21+.
*
* @param color The ripple color
* @param borderless If the ripple can render outside it's bounds
*/
Ripple: function(color: string, borderless: boolean) {
return {type: 'RippleAndroid', color: processColor(color), borderless: borderless};
},
canUseNativeForeground: function() {
return Platform.OS === 'android' && Platform.Version >= 23;
}
},
mixins: [Touchable.Mixin],
getDefaultProps: function() {
return {
background: this.SelectableBackground(),
};
},
getInitialState: function() {
return this.touchableGetInitialState();
},
componentDidMount: function() {
ensurePositiveDelayProps(this.props);
},
UNSAFE_componentWillReceiveProps: function(nextProps) {
ensurePositiveDelayProps(nextProps);
},
/**
* `Touchable.Mixin` self callbacks. The mixin will invoke these if they are
* defined on your component.
*/
touchableHandleActivePressIn: function(e: Event) {
this.props.onPressIn && this.props.onPressIn(e);
this._dispatchPressedStateChange(true);
if (this.pressInLocation) {
this._dispatchHotspotUpdate(this.pressInLocation.locationX, this.pressInLocation.locationY);
}
},
touchableHandleActivePressOut: function(e: Event) {
this.props.onPressOut && this.props.onPressOut(e);
this._dispatchPressedStateChange(false);
},
touchableHandlePress: function(e: Event) {
this.props.onPress && this.props.onPress(e);
},
touchableHandleLongPress: function(e: Event) {
this.props.onLongPress && this.props.onLongPress(e);
},
touchableGetPressRectOffset: function() {
// Always make sure to predeclare a constant!
return this.props.pressRetentionOffset || PRESS_RETENTION_OFFSET;
},
touchableGetHitSlop: function() {
return this.props.hitSlop;
},
touchableGetHighlightDelayMS: function() {
return this.props.delayPressIn;
},
touchableGetLongPressDelayMS: function() {
return this.props.delayLongPress;
},
touchableGetPressOutDelayMS: function() {
return this.props.delayPressOut;
},
_handleResponderMove: function(e) {
this.touchableHandleResponderMove(e);
this._dispatchHotspotUpdate(e.nativeEvent.locationX, e.nativeEvent.locationY);
},
_dispatchHotspotUpdate: function(destX, destY) {
UIManager.dispatchViewManagerCommand(
ReactNative.findNodeHandle(this),
UIManager.RCTView.Commands.hotspotUpdate,
[destX || 0, destY || 0]
);
},
_dispatchPressedStateChange: function(pressed) {
UIManager.dispatchViewManagerCommand(
ReactNative.findNodeHandle(this),
UIManager.RCTView.Commands.setPressed,
[pressed]
);
},
render: function() {
const child = React.Children.only(this.props.children);
let children = child.props.children;
if (Touchable.TOUCH_TARGET_DEBUG && child.type.displayName === 'View') {
if (!Array.isArray(children)) {
children = [children];
}
children.push(Touchable.renderDebugView({color: 'brown', hitSlop: this.props.hitSlop}));
}
if (this.props.useForeground && !TouchableNativeFeedback.canUseNativeForeground()) {
console.warn(
'Requested foreground ripple, but it is not available on this version of Android. ' +
'Consider calling TouchableNativeFeedback.canUseNativeForeground() and using a different ' +
'Touchable if the result is false.');
}
const drawableProp =
this.props.useForeground && TouchableNativeFeedback.canUseNativeForeground()
? 'nativeForegroundAndroid'
: 'nativeBackgroundAndroid';
const childProps = {
...child.props,
[drawableProp]: this.props.background,
accessible: this.props.accessible !== false,
accessibilityLabel: this.props.accessibilityLabel,
accessibilityComponentType: this.props.accessibilityComponentType,
accessibilityTraits: this.props.accessibilityTraits,
children,
testID: this.props.testID,
onLayout: this.props.onLayout,
hitSlop: this.props.hitSlop,
isTVSelectable: true,
hasTVPreferredFocus: this.props.hasTVPreferredFocus,
onStartShouldSetResponder: this.touchableHandleStartShouldSetResponder,
onResponderTerminationRequest: this.touchableHandleResponderTerminationRequest,
onResponderGrant: this.touchableHandleResponderGrant,
onResponderMove: this._handleResponderMove,
onResponderRelease: this.touchableHandleResponderRelease,
onResponderTerminate: this.touchableHandleResponderTerminate,
};
// We need to clone the actual element so that the ripple background drawable
// can be applied directly to the background of this element rather than to
// a wrapper view as done in other Touchable*
return React.cloneElement(
child,
childProps
);
}
});
module.exports = TouchableNativeFeedback;

View File

@@ -0,0 +1,49 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule TouchableNativeFeedback
*/
'use strict';
const React = require('React');
const StyleSheet = require('StyleSheet');
const Text = require('Text');
const View = require('View');
class DummyTouchableNativeFeedback extends React.Component {
static SelectableBackground = () => ({});
static SelectableBackgroundBorderless = () => ({});
static Ripple = () => ({});
static canUseNativeForeground = () => false;
render() {
return (
<View style={[styles.container, this.props.style]}>
<Text style={styles.info}>TouchableNativeFeedback is not supported on this platform!</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
height: 100,
width: 300,
backgroundColor: '#ffbcbc',
borderWidth: 1,
borderColor: 'red',
alignItems: 'center',
justifyContent: 'center',
margin: 10,
},
info: {
color: '#333333',
margin: 20,
}
});
module.exports = DummyTouchableNativeFeedback;

View File

@@ -0,0 +1,273 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule TouchableOpacity
* @noflow
*/
'use strict';
// Note (avik): add @flow when Flow supports spread properties in propTypes
const Animated = require('Animated');
const Easing = require('Easing');
const NativeMethodsMixin = require('NativeMethodsMixin');
const React = require('React');
const PropTypes = require('prop-types');
const TimerMixin = require('react-timer-mixin');
const Touchable = require('Touchable');
const TouchableWithoutFeedback = require('TouchableWithoutFeedback');
const createReactClass = require('create-react-class');
const ensurePositiveDelayProps = require('ensurePositiveDelayProps');
const flattenStyle = require('flattenStyle');
type Event = Object;
const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};
/**
* A wrapper for making views respond properly to touches.
* On press down, the opacity of the wrapped view is decreased, dimming it.
*
* Opacity is controlled by wrapping the children in an Animated.View, which is
* added to the view hiearchy. Be aware that this can affect layout.
*
* Example:
*
* ```
* renderButton: function() {
* return (
* <TouchableOpacity onPress={this._onPressButton}>
* <Image
* style={styles.button}
* source={require('./myButton.png')}
* />
* </TouchableOpacity>
* );
* },
* ```
* ### Example
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react'
* import {
* AppRegistry,
* StyleSheet,
* TouchableOpacity,
* Text,
* View,
* } from 'react-native'
*
* class App extends Component {
* constructor(props) {
* super(props)
* this.state = { count: 0 }
* }
*
* onPress = () => {
* this.setState({
* count: this.state.count+1
* })
* }
*
* render() {
* return (
* <View style={styles.container}>
* <TouchableOpacity
* style={styles.button}
* onPress={this.onPress}
* >
* <Text> Touch Here </Text>
* </TouchableOpacity>
* <View style={[styles.countContainer]}>
* <Text style={[styles.countText]}>
* { this.state.count !== 0 ? this.state.count: null}
* </Text>
* </View>
* </View>
* )
* }
* }
*
* const styles = StyleSheet.create({
* container: {
* flex: 1,
* justifyContent: 'center',
* paddingHorizontal: 10
* },
* button: {
* alignItems: 'center',
* backgroundColor: '#DDDDDD',
* padding: 10
* },
* countContainer: {
* alignItems: 'center',
* padding: 10
* },
* countText: {
* color: '#FF00FF'
* }
* })
*
* AppRegistry.registerComponent('App', () => App)
* ```
*
*/
const TouchableOpacity = createReactClass({
displayName: 'TouchableOpacity',
mixins: [TimerMixin, Touchable.Mixin, NativeMethodsMixin],
propTypes: {
...TouchableWithoutFeedback.propTypes,
/**
* Determines what the opacity of the wrapped view should be when touch is
* active. Defaults to 0.2.
*/
activeOpacity: PropTypes.number,
/**
* TV preferred focus (see documentation for the View component).
*/
hasTVPreferredFocus: PropTypes.bool,
/**
* Apple TV parallax effects
*/
tvParallaxProperties: PropTypes.object,
},
getDefaultProps: function() {
return {
activeOpacity: 0.2,
};
},
getInitialState: function() {
return {
...this.touchableGetInitialState(),
anim: new Animated.Value(this._getChildStyleOpacityWithDefault()),
};
},
componentDidMount: function() {
ensurePositiveDelayProps(this.props);
},
UNSAFE_componentWillReceiveProps: function(nextProps) {
ensurePositiveDelayProps(nextProps);
},
componentDidUpdate: function(prevProps, prevState) {
if (this.props.disabled !== prevProps.disabled) {
this._opacityInactive(250);
}
},
/**
* Animate the touchable to a new opacity.
*/
setOpacityTo: function(value: number, duration: number) {
Animated.timing(
this.state.anim,
{
toValue: value,
duration: duration,
easing: Easing.inOut(Easing.quad),
useNativeDriver: true,
}
).start();
},
/**
* `Touchable.Mixin` self callbacks. The mixin will invoke these if they are
* defined on your component.
*/
touchableHandleActivePressIn: function(e: Event) {
if (e.dispatchConfig.registrationName === 'onResponderGrant') {
this._opacityActive(0);
} else {
this._opacityActive(150);
}
this.props.onPressIn && this.props.onPressIn(e);
},
touchableHandleActivePressOut: function(e: Event) {
this._opacityInactive(250);
this.props.onPressOut && this.props.onPressOut(e);
},
touchableHandlePress: function(e: Event) {
this.props.onPress && this.props.onPress(e);
},
touchableHandleLongPress: function(e: Event) {
this.props.onLongPress && this.props.onLongPress(e);
},
touchableGetPressRectOffset: function() {
return this.props.pressRetentionOffset || PRESS_RETENTION_OFFSET;
},
touchableGetHitSlop: function() {
return this.props.hitSlop;
},
touchableGetHighlightDelayMS: function() {
return this.props.delayPressIn || 0;
},
touchableGetLongPressDelayMS: function() {
return this.props.delayLongPress === 0 ? 0 :
this.props.delayLongPress || 500;
},
touchableGetPressOutDelayMS: function() {
return this.props.delayPressOut;
},
_opacityActive: function(duration: number) {
this.setOpacityTo(this.props.activeOpacity, duration);
},
_opacityInactive: function(duration: number) {
this.setOpacityTo(
this._getChildStyleOpacityWithDefault(),
duration
);
},
_getChildStyleOpacityWithDefault: function() {
const childStyle = flattenStyle(this.props.style) || {};
return childStyle.opacity == undefined ? 1 : childStyle.opacity;
},
render: function() {
return (
<Animated.View
accessible={this.props.accessible !== false}
accessibilityLabel={this.props.accessibilityLabel}
accessibilityComponentType={this.props.accessibilityComponentType}
accessibilityTraits={this.props.accessibilityTraits}
style={[this.props.style, {opacity: this.state.anim}]}
nativeID={this.props.nativeID}
testID={this.props.testID}
onLayout={this.props.onLayout}
isTVSelectable={true}
hasTVPreferredFocus={this.props.hasTVPreferredFocus}
tvParallaxProperties={this.props.tvParallaxProperties}
hitSlop={this.props.hitSlop}
onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder}
onResponderTerminationRequest={this.touchableHandleResponderTerminationRequest}
onResponderGrant={this.touchableHandleResponderGrant}
onResponderMove={this.touchableHandleResponderMove}
onResponderRelease={this.touchableHandleResponderRelease}
onResponderTerminate={this.touchableHandleResponderTerminate}>
{this.props.children}
{Touchable.renderDebugView({color: 'cyan', hitSlop: this.props.hitSlop})}
</Animated.View>
);
},
});
module.exports = TouchableOpacity;

View File

@@ -0,0 +1,206 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule TouchableWithoutFeedback
* @flow
*/
'use strict';
const EdgeInsetsPropType = require('EdgeInsetsPropType');
const React = require('React');
const PropTypes = require('prop-types');
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */
const TimerMixin = require('react-timer-mixin');
const Touchable = require('Touchable');
const createReactClass = require('create-react-class');
const ensurePositiveDelayProps = require('ensurePositiveDelayProps');
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */
const warning = require('fbjs/lib/warning');
const {
AccessibilityComponentTypes,
AccessibilityTraits,
} = require('ViewAccessibility');
import type {PressEvent} from 'CoreEventTypes';
const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};
/**
* Do not use unless you have a very good reason. All elements that
* respond to press should have a visual feedback when touched.
*
* TouchableWithoutFeedback supports only one child.
* If you wish to have several child components, wrap them in a View.
*/
const TouchableWithoutFeedback = createReactClass({
displayName: 'TouchableWithoutFeedback',
mixins: [TimerMixin, Touchable.Mixin],
propTypes: {
accessible: PropTypes.bool,
accessibilityComponentType: PropTypes.oneOf(
AccessibilityComponentTypes
),
accessibilityTraits: PropTypes.oneOfType([
PropTypes.oneOf(AccessibilityTraits),
PropTypes.arrayOf(PropTypes.oneOf(AccessibilityTraits)),
]),
/**
* If true, disable all interactions for this component.
*/
disabled: PropTypes.bool,
/**
* Called when the touch is released, but not if cancelled (e.g. by a scroll
* that steals the responder lock).
*/
onPress: PropTypes.func,
/**
* Called as soon as the touchable element is pressed and invoked even before onPress.
* This can be useful when making network requests.
*/
onPressIn: PropTypes.func,
/**
* Called as soon as the touch is released even before onPress.
*/
onPressOut: PropTypes.func,
/**
* Invoked on mount and layout changes with
*
* `{nativeEvent: {layout: {x, y, width, height}}}`
*/
onLayout: PropTypes.func,
onLongPress: PropTypes.func,
/**
* Delay in ms, from the start of the touch, before onPressIn is called.
*/
delayPressIn: PropTypes.number,
/**
* Delay in ms, from the release of the touch, before onPressOut is called.
*/
delayPressOut: PropTypes.number,
/**
* Delay in ms, from onPressIn, before onLongPress is called.
*/
delayLongPress: PropTypes.number,
/**
* When the scroll view is disabled, this defines how far your touch may
* move off of the button, before deactivating the button. Once deactivated,
* try moving it back and you'll see that the button is once again
* reactivated! Move it back and forth several times while the scroll view
* is disabled. Ensure you pass in a constant to reduce memory allocations.
*/
pressRetentionOffset: EdgeInsetsPropType,
/**
* This defines how far your touch can start away from the button. This is
* added to `pressRetentionOffset` when moving off of the button.
* ** NOTE **
* The touch area never extends past the parent view bounds and the Z-index
* of sibling views always takes precedence if a touch hits two overlapping
* views.
*/
hitSlop: EdgeInsetsPropType,
},
getInitialState: function() {
return this.touchableGetInitialState();
},
componentDidMount: function() {
ensurePositiveDelayProps(this.props);
},
UNSAFE_componentWillReceiveProps: function(nextProps: Object) {
ensurePositiveDelayProps(nextProps);
},
/**
* `Touchable.Mixin` self callbacks. The mixin will invoke these if they are
* defined on your component.
*/
touchableHandlePress: function(e: PressEvent) {
this.props.onPress && this.props.onPress(e);
},
touchableHandleActivePressIn: function(e: PressEvent) {
this.props.onPressIn && this.props.onPressIn(e);
},
touchableHandleActivePressOut: function(e: PressEvent) {
this.props.onPressOut && this.props.onPressOut(e);
},
touchableHandleLongPress: function(e: PressEvent) {
this.props.onLongPress && this.props.onLongPress(e);
},
touchableGetPressRectOffset: function(): typeof PRESS_RETENTION_OFFSET {
return this.props.pressRetentionOffset || PRESS_RETENTION_OFFSET;
},
touchableGetHitSlop: function(): ?Object {
return this.props.hitSlop;
},
touchableGetHighlightDelayMS: function(): number {
return this.props.delayPressIn || 0;
},
touchableGetLongPressDelayMS: function(): number {
return this.props.delayLongPress === 0 ? 0 :
this.props.delayLongPress || 500;
},
touchableGetPressOutDelayMS: function(): number {
return this.props.delayPressOut || 0;
},
render: function(): React.Element<any> {
// Note(avik): remove dynamic typecast once Flow has been upgraded
// $FlowFixMe(>=0.41.0)
const child = React.Children.only(this.props.children);
let children = child.props.children;
warning(
!child.type || child.type.displayName !== 'Text',
'TouchableWithoutFeedback does not work well with Text children. Wrap children in a View instead. See ' +
((child._owner && child._owner.getName && child._owner.getName()) || '<unknown>')
);
if (Touchable.TOUCH_TARGET_DEBUG && child.type && child.type.displayName === 'View') {
children = React.Children.toArray(children);
children.push(Touchable.renderDebugView({color: 'red', hitSlop: this.props.hitSlop}));
}
const style = (Touchable.TOUCH_TARGET_DEBUG && child.type && child.type.displayName === 'Text') ?
[child.props.style, {color: 'red'}] :
child.props.style;
return (React: any).cloneElement(child, {
accessible: this.props.accessible !== false,
accessibilityLabel: this.props.accessibilityLabel,
accessibilityComponentType: this.props.accessibilityComponentType,
accessibilityTraits: this.props.accessibilityTraits,
nativeID: this.props.nativeID,
testID: this.props.testID,
onLayout: this.props.onLayout,
hitSlop: this.props.hitSlop,
onStartShouldSetResponder: this.touchableHandleStartShouldSetResponder,
onResponderTerminationRequest: this.touchableHandleResponderTerminationRequest,
onResponderGrant: this.touchableHandleResponderGrant,
onResponderMove: this.touchableHandleResponderMove,
onResponderRelease: this.touchableHandleResponderRelease,
onResponderTerminate: this.touchableHandleResponderTerminate,
style,
children,
});
}
});
module.exports = TouchableWithoutFeedback;

View File

@@ -0,0 +1,9 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = () => true;

View File

@@ -0,0 +1,22 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ensureComponentIsNative
* @flow
*/
'use strict';
const invariant = require('fbjs/lib/invariant');
const ensureComponentIsNative = function(component: any) {
invariant(
component && typeof component.setNativeProps === 'function',
'Touchable child must either be native or forward setNativeProps to a ' +
'native component'
);
};
module.exports = ensureComponentIsNative;

View File

@@ -0,0 +1,22 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ensurePositiveDelayProps
* @flow
*/
'use strict';
const invariant = require('fbjs/lib/invariant');
const ensurePositiveDelayProps = function(props: any) {
invariant(
!(props.delayPressIn < 0 || props.delayPressOut < 0 ||
props.delayLongPress < 0),
'Touchable components cannot have negative delay properties'
);
};
module.exports = ensurePositiveDelayProps;

View File

@@ -0,0 +1,48 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule UnimplementedView
* @flow
* @format
*/
'use strict';
const React = require('React');
const StyleSheet = require('StyleSheet');
/**
* Common implementation for a simple stubbed view. Simply applies the view's styles to the inner
* View component and renders its children.
*/
class UnimplementedView extends React.Component<$FlowFixMeProps> {
setNativeProps() {
// Do nothing.
// This method is required in order to use this view as a Touchable* child.
// See ensureComponentIsNative.js for more info
}
render() {
// Workaround require cycle from requireNativeComponent
const View = require('View');
return (
<View style={[styles.unimplementedView, this.props.style]}>
{this.props.children}
</View>
);
}
}
const styles = StyleSheet.create({
unimplementedView: __DEV__
? {
alignSelf: 'flex-start',
borderColor: 'red',
borderWidth: 1,
}
: {},
});
module.exports = UnimplementedView;

View File

@@ -0,0 +1,113 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule FabricView
* @flow
* @format
*/
'use strict';
/**
* This is a temporary fork of View.js for Fabric purpose.
* Do not use outside of Fabric tree.
*/
const Platform = require('Platform');
const React = require('React');
const ReactNativeStyleAttributes = require('ReactNativeStyleAttributes');
const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
const ViewPropTypes = require('ViewPropTypes');
const {NativeMethodsMixin} = require('ReactFabricInternals');
const {ViewContextTypes} = require('ViewContext');
const createReactClass = require('create-react-class');
const invariant = require('fbjs/lib/invariant');
const requireFabricComponent = require('requireFabricComponent');
import type {ViewProps} from 'ViewPropTypes';
import type {ViewChildContext} from 'ViewContext';
export type Props = ViewProps;
/**
* The most fundamental component for building a UI.
*
* See http://facebook.github.io/react-native/docs/view.html
*/
const View = createReactClass({
displayName: 'View',
// TODO: We should probably expose the mixins, viewConfig, and statics publicly. For example,
// one of the props is of type AccessibilityComponentType. That is defined as a const[] above,
// but it is not rendered by the docs, since `statics` below is not rendered. So its Possible
// values had to be hardcoded.
mixins: [NativeMethodsMixin],
// `propTypes` should not be accessed directly on View since this wrapper only
// exists for DEV mode. However it's important for them to be declared.
// If the object passed to `createClass` specifies `propTypes`, Flow will
// create a static type from it.
propTypes: ViewPropTypes,
/**
* `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We
* make `this` look like an actual native component class.
*/
viewConfig: {
uiViewClassName: 'RCTView',
validAttributes: ReactNativeViewAttributes.RCTView,
},
childContextTypes: ViewContextTypes,
getChildContext(): ViewChildContext {
return {
isInAParentText: false,
};
},
render() {
invariant(
!(this.context.isInAParentText && Platform.OS === 'android'),
'Nesting of <View> within <Text> is not supported on Android.',
);
// WARNING: This method will not be used in production mode as in that mode we
// replace wrapper component View with generated native wrapper RCTView. Avoid
// adding functionality this component that you'd want to be available in both
// dev and prod modes.
return <RCTView {...this.props} />;
},
});
const RCTView = requireFabricComponent('RCTView', View, {
nativeOnly: {
nativeBackgroundAndroid: true,
nativeForegroundAndroid: true,
},
fabric: true,
});
if (__DEV__) {
const UIManager = require('UIManager');
const viewConfig =
(UIManager.viewConfigs && UIManager.viewConfigs.RCTView) || {};
for (const prop in viewConfig.nativeProps) {
const viewAny: any = View; // Appease flow
if (!viewAny.propTypes[prop] && !ReactNativeStyleAttributes[prop]) {
throw new Error(
'View is missing propType for native prop `' + prop + '`',
);
}
}
}
let ViewToExport = RCTView;
if (__DEV__) {
ViewToExport = View;
}
// No one should depend on the DEV-mode createClass View wrapper.
module.exports = ((ViewToExport: any): typeof RCTView);

View File

@@ -0,0 +1,21 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule PlatformViewPropTypes
* @flow
*/
const Platform = require('Platform');
let TVViewPropTypes = {};
// We need to always include TVViewPropTypes on Android
// as unlike on iOS we can't detect TV devices at build time
// and hence make view manager export a different list of native properties.
if (Platform.isTV || Platform.OS === 'android') {
TVViewPropTypes = require('TVViewPropTypes');
}
module.exports = TVViewPropTypes;

View File

@@ -0,0 +1,50 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ReactNativeStyleAttributes
* @flow
*/
'use strict';
const ImageStylePropTypes = require('ImageStylePropTypes');
const TextStylePropTypes = require('TextStylePropTypes');
const ViewStylePropTypes = require('ViewStylePropTypes');
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */
const keyMirror = require('fbjs/lib/keyMirror');
const processColor = require('processColor');
const processTransform = require('processTransform');
const sizesDiffer = require('sizesDiffer');
const ReactNativeStyleAttributes = {
...keyMirror(ViewStylePropTypes),
...keyMirror(TextStylePropTypes),
...keyMirror(ImageStylePropTypes),
};
ReactNativeStyleAttributes.transform = { process: processTransform };
ReactNativeStyleAttributes.shadowOffset = { diff: sizesDiffer };
const colorAttributes = { process: processColor };
ReactNativeStyleAttributes.backgroundColor = colorAttributes;
ReactNativeStyleAttributes.borderBottomColor = colorAttributes;
ReactNativeStyleAttributes.borderColor = colorAttributes;
ReactNativeStyleAttributes.borderLeftColor = colorAttributes;
ReactNativeStyleAttributes.borderRightColor = colorAttributes;
ReactNativeStyleAttributes.borderTopColor = colorAttributes;
ReactNativeStyleAttributes.borderStartColor = colorAttributes;
ReactNativeStyleAttributes.borderEndColor = colorAttributes;
ReactNativeStyleAttributes.color = colorAttributes;
ReactNativeStyleAttributes.shadowColor = colorAttributes;
ReactNativeStyleAttributes.textDecorationColor = colorAttributes;
ReactNativeStyleAttributes.tintColor = colorAttributes;
ReactNativeStyleAttributes.textShadowColor = colorAttributes;
ReactNativeStyleAttributes.overlayColor = colorAttributes;
module.exports = ReactNativeStyleAttributes;

View File

@@ -0,0 +1,49 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ReactNativeViewAttributes
* @flow
*/
'use strict';
const ReactNativeStyleAttributes = require('ReactNativeStyleAttributes');
const ReactNativeViewAttributes = {};
ReactNativeViewAttributes.UIView = {
pointerEvents: true,
accessible: true,
accessibilityActions: true,
accessibilityLabel: true,
accessibilityComponentType: true,
accessibilityLiveRegion: true,
accessibilityTraits: true,
importantForAccessibility: true,
nativeID: true,
testID: true,
renderToHardwareTextureAndroid: true,
shouldRasterizeIOS: true,
onLayout: true,
onAccessibilityAction: true,
onAccessibilityTap: true,
onMagicTap: true,
collapsable: true,
needsOffscreenAlphaCompositing: true,
style: ReactNativeStyleAttributes,
};
ReactNativeViewAttributes.RCTView = {
...ReactNativeViewAttributes.UIView,
// This is a special performance property exposed by RCTView and useful for
// scrolling content when there are many subviews, most of which are offscreen.
// For this property to be effective, it must be applied to a view that contains
// many subviews that extend outside its bound. The subviews must also have
// overflow: hidden, as should the containing view (or one of its superviews).
removeClippedSubviews: true,
};
module.exports = ReactNativeViewAttributes;

View File

@@ -0,0 +1,51 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ShadowPropTypesIOS
* @flow
* @format
*/
'use strict';
const ColorPropType = require('ColorPropType');
const ReactPropTypes = require('prop-types');
/**
* These props can be used to dynamically generate shadows on views, images, text, etc.
*
* Because they are dynamically generated, they may cause performance regressions. Static
* shadow image asset may be a better way to go for optimal performance.
*
* These properties are iOS only - for similar functionality on Android, use the [`elevation`
* property](docs/viewstyleproptypes.html#elevation).
*/
const ShadowPropTypesIOS = {
/**
* Sets the drop shadow color
* @platform ios
*/
shadowColor: ColorPropType,
/**
* Sets the drop shadow offset
* @platform ios
*/
shadowOffset: ReactPropTypes.shape({
width: ReactPropTypes.number,
height: ReactPropTypes.number,
}),
/**
* Sets the drop shadow opacity (multiplied by the color's alpha component)
* @platform ios
*/
shadowOpacity: ReactPropTypes.number,
/**
* Sets the drop shadow blur radius
* @platform ios
*/
shadowRadius: ReactPropTypes.number,
};
module.exports = ShadowPropTypesIOS;

View File

@@ -0,0 +1,91 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule View
* @flow
* @format
*/
'use strict';
const Platform = require('Platform');
const React = require('React');
const ReactNative = require('ReactNative');
const ReactNativeStyleAttributes = require('ReactNativeStyleAttributes');
const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
const ViewPropTypes = require('ViewPropTypes');
const {ViewContextTypes} = require('ViewContext');
const invariant = require('fbjs/lib/invariant');
const requireNativeComponent = require('requireNativeComponent');
import type {ViewProps} from 'ViewPropTypes';
import type {ViewChildContext} from 'ViewContext';
export type Props = ViewProps;
/**
* The most fundamental component for building a UI, View is a container that
* supports layout with flexbox, style, some touch handling, and accessibility
* controls.
*
* @see http://facebook.github.io/react-native/docs/view.html
*/
class View extends ReactNative.NativeComponent<Props> {
static propTypes = ViewPropTypes;
static childContextTypes = ViewContextTypes;
viewConfig = {
uiViewClassName: 'RCTView',
validAttributes: ReactNativeViewAttributes.RCTView,
};
getChildContext(): ViewChildContext {
return {
isInAParentText: false,
};
}
render() {
invariant(
!(this.context.isInAParentText && Platform.OS === 'android'),
'Nesting of <View> within <Text> is not supported on Android.',
);
// WARNING: This method will not be used in production mode as in that mode we
// replace wrapper component View with generated native wrapper RCTView. Avoid
// adding functionality this component that you'd want to be available in both
// dev and prod modes.
return <RCTView {...this.props} />;
}
}
const RCTView = requireNativeComponent('RCTView', View, {
nativeOnly: {
nativeBackgroundAndroid: true,
nativeForegroundAndroid: true,
},
});
if (__DEV__) {
const UIManager = require('UIManager');
const viewConfig =
(UIManager.viewConfigs && UIManager.viewConfigs.RCTView) || {};
for (const prop in viewConfig.nativeProps) {
const viewAny: any = View; // Appease flow
if (!viewAny.propTypes[prop] && !ReactNativeStyleAttributes[prop]) {
throw new Error(
'View is missing propType for native prop `' + prop + '`',
);
}
}
}
let ViewToExport = RCTView;
if (__DEV__) {
ViewToExport = View;
}
// No one should depend on the DEV-mode createClass View wrapper.
module.exports = ((ViewToExport: any): typeof View);

View File

@@ -0,0 +1,63 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ViewAccessibility
* @flow
*/
'use strict';
export type AccessibilityTrait =
'none' |
'button' |
'link' |
'header' |
'search' |
'image' |
'selected' |
'plays' |
'key' |
'text' |
'summary' |
'disabled' |
'frequentUpdates' |
'startsMedia' |
'adjustable' |
'allowsDirectInteraction' |
'pageTurn';
export type AccessibilityComponentType =
'none' |
'button' |
'radiobutton_checked' |
'radiobutton_unchecked';
module.exports = {
AccessibilityTraits: [
'none',
'button',
'link',
'header',
'search',
'image',
'selected',
'plays',
'key',
'text',
'summary',
'disabled',
'frequentUpdates',
'startsMedia',
'adjustable',
'allowsDirectInteraction',
'pageTurn',
],
AccessibilityComponentTypes: [
'none',
'button',
'radiobutton_checked',
'radiobutton_unchecked',
],
};

View File

@@ -0,0 +1,21 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ViewContext
* @flow
* @format
*/
'use strict';
const PropTypes = require('prop-types');
export type ViewChildContext = {|
+isInAParentText: boolean,
|};
export const ViewContextTypes = {
isInAParentText: PropTypes.bool,
};

View File

@@ -0,0 +1,431 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ViewPropTypes
* @flow
*/
'use strict';
const React = require('React');
const EdgeInsetsPropType = require('EdgeInsetsPropType');
const PlatformViewPropTypes = require('PlatformViewPropTypes');
const PropTypes = require('prop-types');
const StyleSheetPropType = require('StyleSheetPropType');
const ViewStylePropTypes = require('ViewStylePropTypes');
const {
AccessibilityComponentTypes,
AccessibilityTraits,
} = require('ViewAccessibility');
import type {
AccessibilityComponentType,
AccessibilityTrait,
} from 'ViewAccessibility';
import type {EdgeInsetsProp} from 'EdgeInsetsPropType';
import type {TVViewProps} from 'TVViewPropTypes';
import type {Layout, LayoutEvent} from 'CoreEventTypes';
const stylePropType = StyleSheetPropType(ViewStylePropTypes);
export type ViewLayout = Layout;
export type ViewLayoutEvent = LayoutEvent;
// There's no easy way to create a different type if (Platform.isTVOS):
// so we must include TVViewProps
export type ViewProps = {
accessible?: bool,
accessibilityLabel?: null | React$PropType$Primitive<any> | string | Array<any> | any,
accessibilityActions?: Array<string>,
accessibilityComponentType?: AccessibilityComponentType,
accessibilityLiveRegion?: 'none' | 'polite' | 'assertive',
importantForAccessibility?: 'auto'| 'yes'| 'no'| 'no-hide-descendants',
accessibilityTraits?: AccessibilityTrait | Array<AccessibilityTrait>,
accessibilityViewIsModal?: bool,
accessibilityElementsHidden?: bool,
children?: ?React.Node,
onAccessibilityAction?: Function,
onAccessibilityTap?: Function,
onMagicTap?: Function,
testID?: ?string,
nativeID?: string,
onLayout?: ?(event: LayoutEvent) => void,
onResponderGrant?: ?Function,
onResponderMove?: ?Function,
onResponderReject?: ?Function,
onResponderRelease?: ?Function,
onResponderTerminate?: ?Function,
onResponderTerminationRequest?: ?Function,
onStartShouldSetResponder?: ?Function,
onStartShouldSetResponderCapture?: ?Function,
onMoveShouldSetResponder?: ?Function,
onMoveShouldSetResponderCapture?: ?Function,
hitSlop?: ?EdgeInsetsProp,
pointerEvents?: null | 'box-none'| 'none'| 'box-only'| 'auto',
style?: stylePropType,
removeClippedSubviews?: bool,
renderToHardwareTextureAndroid?: bool,
shouldRasterizeIOS?: bool,
collapsable?: bool,
needsOffscreenAlphaCompositing?: bool,
} & TVViewProps;
module.exports = {
...PlatformViewPropTypes,
/**
* When `true`, indicates that the view is an accessibility element.
* By default, all the touchable elements are accessible.
*
* See http://facebook.github.io/react-native/docs/view.html#accessible
*/
accessible: PropTypes.bool,
/**
* Overrides the text that's read by the screen reader when the user interacts
* with the element. By default, the label is constructed by traversing all
* the children and accumulating all the `Text` nodes separated by space.
*
* See http://facebook.github.io/react-native/docs/view.html#accessibilitylabel
*/
accessibilityLabel: PropTypes.node,
/**
* Provides an array of custom actions available for accessibility.
*
* @platform ios
*/
accessibilityActions: PropTypes.arrayOf(PropTypes.string),
/**
* Indicates to accessibility services to treat UI component like a
* native one. Works for Android only.
*
* @platform android
*
* See http://facebook.github.io/react-native/docs/view.html#accessibilitycomponenttype
*/
accessibilityComponentType: PropTypes.oneOf(AccessibilityComponentTypes),
/**
* Indicates to accessibility services whether the user should be notified
* when this view changes. Works for Android API >= 19 only.
*
* @platform android
*
* See http://facebook.github.io/react-native/docs/view.html#accessibilityliveregion
*/
accessibilityLiveRegion: PropTypes.oneOf([
'none',
'polite',
'assertive',
]),
/**
* Controls how view is important for accessibility which is if it
* fires accessibility events and if it is reported to accessibility services
* that query the screen. Works for Android only.
*
* @platform android
*
* See http://facebook.github.io/react-native/docs/view.html#importantforaccessibility
*/
importantForAccessibility: PropTypes.oneOf([
'auto',
'yes',
'no',
'no-hide-descendants',
]),
/**
* Provides additional traits to screen reader. By default no traits are
* provided unless specified otherwise in element.
*
* You can provide one trait or an array of many traits.
*
* @platform ios
*
* See http://facebook.github.io/react-native/docs/view.html#accessibilitytraits
*/
accessibilityTraits: PropTypes.oneOfType([
PropTypes.oneOf(AccessibilityTraits),
PropTypes.arrayOf(PropTypes.oneOf(AccessibilityTraits)),
]),
/**
* A value indicating whether VoiceOver should ignore the elements
* within views that are siblings of the receiver.
* Default is `false`.
*
* @platform ios
*
* See http://facebook.github.io/react-native/docs/view.html#accessibilityviewismodal
*/
accessibilityViewIsModal: PropTypes.bool,
/**
* A value indicating whether the accessibility elements contained within
* this accessibility element are hidden.
*
* @platform ios
*
* See http://facebook.github.io/react-native/docs/view.html#accessibilityElementsHidden
*/
accessibilityElementsHidden: PropTypes.bool,
/**
* When `accessible` is true, the system will try to invoke this function
* when the user performs an accessibility custom action.
*
* @platform ios
*/
onAccessibilityAction: PropTypes.func,
/**
* When `accessible` is true, the system will try to invoke this function
* when the user performs accessibility tap gesture.
*
* See http://facebook.github.io/react-native/docs/view.html#onaccessibilitytap
*/
onAccessibilityTap: PropTypes.func,
/**
* When `accessible` is `true`, the system will invoke this function when the
* user performs the magic tap gesture.
*
* See http://facebook.github.io/react-native/docs/view.html#onmagictap
*/
onMagicTap: PropTypes.func,
/**
* Used to locate this view in end-to-end tests.
*
* > This disables the 'layout-only view removal' optimization for this view!
*
* See http://facebook.github.io/react-native/docs/view.html#testid
*/
testID: PropTypes.string,
/**
* Used to locate this view from native classes.
*
* > This disables the 'layout-only view removal' optimization for this view!
*
* See http://facebook.github.io/react-native/docs/view.html#nativeid
*/
nativeID: PropTypes.string,
/**
* For most touch interactions, you'll simply want to wrap your component in
* `TouchableHighlight` or `TouchableOpacity`. Check out `Touchable.js`,
* `ScrollResponder.js` and `ResponderEventPlugin.js` for more discussion.
*/
/**
* The View is now responding for touch events. This is the time to highlight
* and show the user what is happening.
*
* `View.props.onResponderGrant: (event) => {}`, where `event` is a synthetic
* touch event as described above.
*
* See http://facebook.github.io/react-native/docs/view.html#onrespondergrant
*/
onResponderGrant: PropTypes.func,
/**
* The user is moving their finger.
*
* `View.props.onResponderMove: (event) => {}`, where `event` is a synthetic
* touch event as described above.
*
* See http://facebook.github.io/react-native/docs/view.html#onrespondermove
*/
onResponderMove: PropTypes.func,
/**
* Another responder is already active and will not release it to that `View`
* asking to be the responder.
*
* `View.props.onResponderReject: (event) => {}`, where `event` is a
* synthetic touch event as described above.
*
* See http://facebook.github.io/react-native/docs/view.html#onresponderreject
*/
onResponderReject: PropTypes.func,
/**
* Fired at the end of the touch.
*
* `View.props.onResponderRelease: (event) => {}`, where `event` is a
* synthetic touch event as described above.
*
* See http://facebook.github.io/react-native/docs/view.html#onresponderrelease
*/
onResponderRelease: PropTypes.func,
/**
* The responder has been taken from the `View`. Might be taken by other
* views after a call to `onResponderTerminationRequest`, or might be taken
* by the OS without asking (e.g., happens with control center/ notification
* center on iOS)
*
* `View.props.onResponderTerminate: (event) => {}`, where `event` is a
* synthetic touch event as described above.
*
* See http://facebook.github.io/react-native/docs/view.html#onresponderterminate
*/
onResponderTerminate: PropTypes.func,
/**
* Some other `View` wants to become responder and is asking this `View` to
* release its responder. Returning `true` allows its release.
*
* `View.props.onResponderTerminationRequest: (event) => {}`, where `event`
* is a synthetic touch event as described above.
*
* See http://facebook.github.io/react-native/docs/view.html#onresponderterminationrequest
*/
onResponderTerminationRequest: PropTypes.func,
/**
* Does this view want to become responder on the start of a touch?
*
* `View.props.onStartShouldSetResponder: (event) => [true | false]`, where
* `event` is a synthetic touch event as described above.
*
* See http://facebook.github.io/react-native/docs/view.html#onstartshouldsetresponder
*/
onStartShouldSetResponder: PropTypes.func,
/**
* If a parent `View` wants to prevent a child `View` from becoming responder
* on a touch start, it should have this handler which returns `true`.
*
* `View.props.onStartShouldSetResponderCapture: (event) => [true | false]`,
* where `event` is a synthetic touch event as described above.
*
* See http://facebook.github.io/react-native/docs/view.html#onstartshouldsetrespondercapture
*/
onStartShouldSetResponderCapture: PropTypes.func,
/**
* Does this view want to "claim" touch responsiveness? This is called for
* every touch move on the `View` when it is not the responder.
*
* `View.props.onMoveShouldSetResponder: (event) => [true | false]`, where
* `event` is a synthetic touch event as described above.
*
* See http://facebook.github.io/react-native/docs/view.html#onmoveshouldsetresponder
*/
onMoveShouldSetResponder: PropTypes.func,
/**
* If a parent `View` wants to prevent a child `View` from becoming responder
* on a move, it should have this handler which returns `true`.
*
* `View.props.onMoveShouldSetResponderCapture: (event) => [true | false]`,
* where `event` is a synthetic touch event as described above.
*
* See http://facebook.github.io/react-native/docs/view.html#onMoveShouldsetrespondercapture
*/
onMoveShouldSetResponderCapture: PropTypes.func,
/**
* This defines how far a touch event can start away from the view.
* Typical interface guidelines recommend touch targets that are at least
* 30 - 40 points/density-independent pixels.
*
* > The touch area never extends past the parent view bounds and the Z-index
* > of sibling views always takes precedence if a touch hits two overlapping
* > views.
*
* See http://facebook.github.io/react-native/docs/view.html#hitslop
*/
hitSlop: EdgeInsetsPropType,
/**
* Invoked on mount and layout changes with:
*
* `{nativeEvent: { layout: {x, y, width, height}}}`
*
* This event is fired immediately once the layout has been calculated, but
* the new layout may not yet be reflected on the screen at the time the
* event is received, especially if a layout animation is in progress.
*
* See http://facebook.github.io/react-native/docs/view.html#onlayout
*/
onLayout: PropTypes.func,
/**
* Controls whether the `View` can be the target of touch events.
*
* See http://facebook.github.io/react-native/docs/view.html#pointerevents
*/
pointerEvents: PropTypes.oneOf([
'box-none',
'none',
'box-only',
'auto',
]),
/**
* See http://facebook.github.io/react-native/docs/style.html
*/
style: stylePropType,
/**
* This is a special performance property exposed by `RCTView` and is useful
* for scrolling content when there are many subviews, most of which are
* offscreen. For this property to be effective, it must be applied to a
* view that contains many subviews that extend outside its bound. The
* subviews must also have `overflow: hidden`, as should the containing view
* (or one of its superviews).
*
* See http://facebook.github.io/react-native/docs/view.html#removeclippedsubviews
*/
removeClippedSubviews: PropTypes.bool,
/**
* Whether this `View` should render itself (and all of its children) into a
* single hardware texture on the GPU.
*
* @platform android
*
* See http://facebook.github.io/react-native/docs/view.html#rendertohardwaretextureandroid
*/
renderToHardwareTextureAndroid: PropTypes.bool,
/**
* Whether this `View` should be rendered as a bitmap before compositing.
*
* @platform ios
*
* See http://facebook.github.io/react-native/docs/view.html#shouldrasterizeios
*/
shouldRasterizeIOS: PropTypes.bool,
/**
* Views that are only used to layout their children or otherwise don't draw
* anything may be automatically removed from the native hierarchy as an
* optimization. Set this property to `false` to disable this optimization and
* ensure that this `View` exists in the native view hierarchy.
*
* @platform android
*
* See http://facebook.github.io/react-native/docs/view.html#collapsable
*/
collapsable: PropTypes.bool,
/**
* Whether this `View` needs to rendered offscreen and composited with an
* alpha in order to preserve 100% correct colors and blending behavior.
*
* @platform android
*
* See http://facebook.github.io/react-native/docs/view.html#needsoffscreenalphacompositing
*/
needsOffscreenAlphaCompositing: PropTypes.bool,
};

View File

@@ -0,0 +1,60 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ViewStylePropTypes
* @flow
*/
'use strict';
const ColorPropType = require('ColorPropType');
const LayoutPropTypes = require('LayoutPropTypes');
const ReactPropTypes = require('prop-types');
const ShadowPropTypesIOS = require('ShadowPropTypesIOS');
const TransformPropTypes = require('TransformPropTypes');
/**
* Warning: Some of these properties may not be supported in all releases.
*/
const ViewStylePropTypes = {
...LayoutPropTypes,
...ShadowPropTypesIOS,
...TransformPropTypes,
backfaceVisibility: ReactPropTypes.oneOf(['visible', 'hidden']),
backgroundColor: ColorPropType,
borderColor: ColorPropType,
borderTopColor: ColorPropType,
borderRightColor: ColorPropType,
borderBottomColor: ColorPropType,
borderLeftColor: ColorPropType,
borderStartColor: ColorPropType,
borderEndColor: ColorPropType,
borderRadius: ReactPropTypes.number,
borderTopLeftRadius: ReactPropTypes.number,
borderTopRightRadius: ReactPropTypes.number,
borderTopStartRadius: ReactPropTypes.number,
borderTopEndRadius: ReactPropTypes.number,
borderBottomLeftRadius: ReactPropTypes.number,
borderBottomRightRadius: ReactPropTypes.number,
borderBottomStartRadius: ReactPropTypes.number,
borderBottomEndRadius: ReactPropTypes.number,
borderStyle: ReactPropTypes.oneOf(['solid', 'dotted', 'dashed']),
borderWidth: ReactPropTypes.number,
borderTopWidth: ReactPropTypes.number,
borderRightWidth: ReactPropTypes.number,
borderBottomWidth: ReactPropTypes.number,
borderLeftWidth: ReactPropTypes.number,
opacity: ReactPropTypes.number,
/**
* (Android-only) Sets the elevation of a view, using Android's underlying
* [elevation API](https://developer.android.com/training/material/shadows-clipping.html#Elevation).
* This adds a drop shadow to the item and affects z-order for overlapping views.
* Only supported on Android 5.0+, has no effect on earlier versions.
* @platform android
*/
elevation: ReactPropTypes.number,
};
module.exports = ViewStylePropTypes;

View File

@@ -0,0 +1,251 @@
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ViewPagerAndroid
* @flow
*/
'use strict';
const React = require('React');
const PropTypes = require('prop-types');
const ReactNative = require('ReactNative');
const UIManager = require('UIManager');
const ViewPropTypes = require('ViewPropTypes');
const dismissKeyboard = require('dismissKeyboard');
const requireNativeComponent = require('requireNativeComponent');
const VIEWPAGER_REF = 'viewPager';
type Event = Object;
export type ViewPagerScrollState = $Enum<{
idle: string,
dragging: string,
settling: string,
}>;
/**
* Container that allows to flip left and right between child views. Each
* child view of the `ViewPagerAndroid` will be treated as a separate page
* and will be stretched to fill the `ViewPagerAndroid`.
*
* It is important all children are `<View>`s and not composite components.
* You can set style properties like `padding` or `backgroundColor` for each
* child. It is also important that each child have a `key` prop.
*
* Example:
*
* ```
* render: function() {
* return (
* <ViewPagerAndroid
* style={styles.viewPager}
* initialPage={0}>
* <View style={styles.pageStyle} key="1">
* <Text>First page</Text>
* </View>
* <View style={styles.pageStyle} key="2">
* <Text>Second page</Text>
* </View>
* </ViewPagerAndroid>
* );
* }
*
* ...
*
* var styles = {
* ...
* viewPager: {
* flex: 1
* },
* pageStyle: {
* alignItems: 'center',
* padding: 20,
* }
* }
* ```
*/
class ViewPagerAndroid extends React.Component<{
initialPage?: number,
onPageScroll?: Function,
onPageScrollStateChanged?: Function,
onPageSelected?: Function,
pageMargin?: number,
peekEnabled?: boolean,
keyboardDismissMode?: 'none' | 'on-drag',
scrollEnabled?: boolean,
}> {
static propTypes = {
...ViewPropTypes,
/**
* Index of initial page that should be selected. Use `setPage` method to
* update the page, and `onPageSelected` to monitor page changes
*/
initialPage: PropTypes.number,
/**
* Executed when transitioning between pages (ether because of animation for
* the requested page change or when user is swiping/dragging between pages)
* The `event.nativeEvent` object for this callback will carry following data:
* - position - index of first page from the left that is currently visible
* - offset - value from range [0,1) describing stage between page transitions.
* Value x means that (1 - x) fraction of the page at "position" index is
* visible, and x fraction of the next page is visible.
*/
onPageScroll: PropTypes.func,
/**
* Function called when the page scrolling state has changed.
* The page scrolling state can be in 3 states:
* - idle, meaning there is no interaction with the page scroller happening at the time
* - dragging, meaning there is currently an interaction with the page scroller
* - settling, meaning that there was an interaction with the page scroller, and the
* page scroller is now finishing it's closing or opening animation
*/
onPageScrollStateChanged: PropTypes.func,
/**
* This callback will be called once ViewPager finish navigating to selected page
* (when user swipes between pages). The `event.nativeEvent` object passed to this
* callback will have following fields:
* - position - index of page that has been selected
*/
onPageSelected: PropTypes.func,
/**
* Blank space to show between pages. This is only visible while scrolling, pages are still
* edge-to-edge.
*/
pageMargin: PropTypes.number,
/**
* Determines whether the keyboard gets dismissed in response to a drag.
* - 'none' (the default), drags do not dismiss the keyboard.
* - 'on-drag', the keyboard is dismissed when a drag begins.
*/
keyboardDismissMode: PropTypes.oneOf([
'none', // default
'on-drag',
]),
/**
* When false, the content does not scroll.
* The default value is true.
*/
scrollEnabled: PropTypes.bool,
/**
* Whether enable showing peekFraction or not. If this is true, the preview of
* last and next page will show in current screen. Defaults to false.
*/
peekEnabled: PropTypes.bool,
};
componentDidMount() {
if (this.props.initialPage != null) {
this.setPageWithoutAnimation(this.props.initialPage);
}
}
getInnerViewNode = (): ReactComponent => {
return this.refs[VIEWPAGER_REF].getInnerViewNode();
};
_childrenWithOverridenStyle = (): Array => {
// Override styles so that each page will fill the parent. Native component
// will handle positioning of elements, so it's not important to offset
// them correctly.
return React.Children.map(this.props.children, function(child) {
if (!child) {
return null;
}
const newProps = {
...child.props,
style: [child.props.style, {
position: 'absolute',
left: 0,
top: 0,
right: 0,
bottom: 0,
width: undefined,
height: undefined,
}],
collapsable: false,
};
if (child.type &&
child.type.displayName &&
(child.type.displayName !== 'RCTView') &&
(child.type.displayName !== 'View')) {
console.warn('Each ViewPager child must be a <View>. Was ' + child.type.displayName);
}
return React.createElement(child.type, newProps);
});
};
_onPageScroll = (e: Event) => {
if (this.props.onPageScroll) {
this.props.onPageScroll(e);
}
if (this.props.keyboardDismissMode === 'on-drag') {
dismissKeyboard();
}
};
_onPageScrollStateChanged = (e: Event) => {
if (this.props.onPageScrollStateChanged) {
this.props.onPageScrollStateChanged(e.nativeEvent.pageScrollState);
}
};
_onPageSelected = (e: Event) => {
if (this.props.onPageSelected) {
this.props.onPageSelected(e);
}
};
/**
* A helper function to scroll to a specific page in the ViewPager.
* The transition between pages will be animated.
*/
setPage = (selectedPage: number) => {
UIManager.dispatchViewManagerCommand(
ReactNative.findNodeHandle(this),
UIManager.AndroidViewPager.Commands.setPage,
[selectedPage],
);
};
/**
* A helper function to scroll to a specific page in the ViewPager.
* The transition between pages will *not* be animated.
*/
setPageWithoutAnimation = (selectedPage: number) => {
UIManager.dispatchViewManagerCommand(
ReactNative.findNodeHandle(this),
UIManager.AndroidViewPager.Commands.setPageWithoutAnimation,
[selectedPage],
);
};
render() {
return (
<NativeAndroidViewPager
{...this.props}
ref={VIEWPAGER_REF}
style={this.props.style}
onPageScroll={this._onPageScroll}
onPageScrollStateChanged={this._onPageScrollStateChanged}
onPageSelected={this._onPageSelected}
children={this._childrenWithOverridenStyle()}
/>
);
}
}
const NativeAndroidViewPager = requireNativeComponent('AndroidViewPager', ViewPagerAndroid);
module.exports = ViewPagerAndroid;

View File

@@ -0,0 +1,11 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule ViewPagerAndroid
*/
'use strict';
module.exports = require('UnimplementedView');

View File

@@ -0,0 +1,456 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule WebView
*/
'use strict';
const EdgeInsetsPropType = require('EdgeInsetsPropType');
const ActivityIndicator = require('ActivityIndicator');
const React = require('React');
const PropTypes = require('prop-types');
const ReactNative = require('ReactNative');
const StyleSheet = require('StyleSheet');
const UIManager = require('UIManager');
const View = require('View');
const ViewPropTypes = require('ViewPropTypes');
const deprecatedPropType = require('deprecatedPropType');
const keyMirror = require('fbjs/lib/keyMirror');
const requireNativeComponent = require('requireNativeComponent');
const resolveAssetSource = require('resolveAssetSource');
const RCT_WEBVIEW_REF = 'webview';
const WebViewState = keyMirror({
IDLE: null,
LOADING: null,
ERROR: null,
});
const defaultRenderLoading = () => (
<View style={styles.loadingView}>
<ActivityIndicator
style={styles.loadingProgressBar}
/>
</View>
);
/**
* Renders a native WebView.
*/
class WebView extends React.Component {
static get extraNativeComponentConfig() {
return {
nativeOnly: {
messagingEnabled: PropTypes.bool,
},
};
}
static propTypes = {
...ViewPropTypes,
renderError: PropTypes.func,
renderLoading: PropTypes.func,
onLoad: PropTypes.func,
onLoadEnd: PropTypes.func,
onLoadStart: PropTypes.func,
onError: PropTypes.func,
automaticallyAdjustContentInsets: PropTypes.bool,
contentInset: EdgeInsetsPropType,
onNavigationStateChange: PropTypes.func,
onMessage: PropTypes.func,
onContentSizeChange: PropTypes.func,
startInLoadingState: PropTypes.bool, // force WebView to show loadingView on first load
style: ViewPropTypes.style,
html: deprecatedPropType(
PropTypes.string,
'Use the `source` prop instead.'
),
url: deprecatedPropType(
PropTypes.string,
'Use the `source` prop instead.'
),
/**
* Loads static html or a uri (with optional headers) in the WebView.
*/
source: PropTypes.oneOfType([
PropTypes.shape({
/*
* The URI to load in the WebView. Can be a local or remote file.
*/
uri: PropTypes.string,
/*
* The HTTP Method to use. Defaults to GET if not specified.
* NOTE: On Android, only GET and POST are supported.
*/
method: PropTypes.oneOf(['GET', 'POST']),
/*
* Additional HTTP headers to send with the request.
* NOTE: On Android, this can only be used with GET requests.
*/
headers: PropTypes.object,
/*
* The HTTP body to send with the request. This must be a valid
* UTF-8 string, and will be sent exactly as specified, with no
* additional encoding (e.g. URL-escaping or base64) applied.
* NOTE: On Android, this can only be used with POST requests.
*/
body: PropTypes.string,
}),
PropTypes.shape({
/*
* A static HTML page to display in the WebView.
*/
html: PropTypes.string,
/*
* The base URL to be used for any relative links in the HTML.
*/
baseUrl: PropTypes.string,
}),
/*
* Used internally by packager.
*/
PropTypes.number,
]),
/**
* Used on Android only, JS is enabled by default for WebView on iOS
* @platform android
*/
javaScriptEnabled: PropTypes.bool,
/**
* Used on Android Lollipop and above only, third party cookies are enabled
* by default for WebView on Android Kitkat and below and on iOS
* @platform android
*/
thirdPartyCookiesEnabled: PropTypes.bool,
/**
* Used on Android only, controls whether DOM Storage is enabled or not
* @platform android
*/
domStorageEnabled: PropTypes.bool,
/**
* Sets the JS to be injected when the webpage loads.
*/
injectedJavaScript: PropTypes.string,
/**
* Sets whether the webpage scales to fit the view and the user can change the scale.
*/
scalesPageToFit: PropTypes.bool,
/**
* Sets the user-agent for this WebView. The user-agent can also be set in native using
* WebViewConfig. This prop will overwrite that config.
*/
userAgent: PropTypes.string,
/**
* Used to locate this view in end-to-end tests.
*/
testID: PropTypes.string,
/**
* Determines whether HTML5 audio & videos require the user to tap before they can
* start playing. The default value is `false`.
*/
mediaPlaybackRequiresUserAction: PropTypes.bool,
/**
* Boolean that sets whether JavaScript running in the context of a file
* scheme URL should be allowed to access content from any origin.
* Including accessing content from other file scheme URLs
* @platform android
*/
allowUniversalAccessFromFileURLs: PropTypes.bool,
/**
* Function that accepts a string that will be passed to the WebView and
* executed immediately as JavaScript.
*/
injectJavaScript: PropTypes.func,
/**
* Specifies the mixed content mode. i.e WebView will allow a secure origin to load content from any other origin.
*
* Possible values for `mixedContentMode` are:
*
* - `'never'` (default) - WebView will not allow a secure origin to load content from an insecure origin.
* - `'always'` - WebView will allow a secure origin to load content from any other origin, even if that origin is insecure.
* - `'compatibility'` - WebView will attempt to be compatible with the approach of a modern web browser with regard to mixed content.
* @platform android
*/
mixedContentMode: PropTypes.oneOf([
'never',
'always',
'compatibility'
]),
/**
* Used on Android only, controls whether form autocomplete data should be saved
* @platform android
*/
saveFormDataDisabled: PropTypes.bool,
/**
* Override the native component used to render the WebView. Enables a custom native
* WebView which uses the same JavaScript as the original WebView.
*/
nativeConfig: PropTypes.shape({
/*
* The native component used to render the WebView.
*/
component: PropTypes.any,
/*
* Set props directly on the native component WebView. Enables custom props which the
* original WebView doesn't pass through.
*/
props: PropTypes.object,
/*
* Set the ViewManager to use for communcation with the native side.
* @platform ios
*/
viewManager: PropTypes.object,
}),
/*
* Used on Android only, controls whether the given list of URL prefixes should
* make {@link com.facebook.react.views.webview.ReactWebViewClient} to launch a
* default activity intent for those URL instead of loading it within the webview.
* Use this to list URLs that WebView cannot handle, e.g. a PDF url.
* @platform android
*/
urlPrefixesForDefaultIntent: PropTypes.arrayOf(PropTypes.string),
};
static defaultProps = {
javaScriptEnabled : true,
thirdPartyCookiesEnabled: true,
scalesPageToFit: true,
saveFormDataDisabled: false
};
state = {
viewState: WebViewState.IDLE,
lastErrorEvent: null,
startInLoadingState: true,
};
UNSAFE_componentWillMount() {
if (this.props.startInLoadingState) {
this.setState({viewState: WebViewState.LOADING});
}
}
render() {
let otherView = null;
if (this.state.viewState === WebViewState.LOADING) {
otherView = (this.props.renderLoading || defaultRenderLoading)();
} else if (this.state.viewState === WebViewState.ERROR) {
const errorEvent = this.state.lastErrorEvent;
otherView = this.props.renderError && this.props.renderError(
errorEvent.domain,
errorEvent.code,
errorEvent.description);
} else if (this.state.viewState !== WebViewState.IDLE) {
console.error('RCTWebView invalid state encountered: ' + this.state.loading);
}
const webViewStyles = [styles.container, this.props.style];
if (this.state.viewState === WebViewState.LOADING ||
this.state.viewState === WebViewState.ERROR) {
// if we're in either LOADING or ERROR states, don't show the webView
webViewStyles.push(styles.hidden);
}
const source = this.props.source || {};
if (this.props.html) {
source.html = this.props.html;
} else if (this.props.url) {
source.uri = this.props.url;
}
if (source.method === 'POST' && source.headers) {
console.warn('WebView: `source.headers` is not supported when using POST.');
} else if (source.method === 'GET' && source.body) {
console.warn('WebView: `source.body` is not supported when using GET.');
}
const nativeConfig = this.props.nativeConfig || {};
let NativeWebView = nativeConfig.component || RCTWebView;
const webView =
<NativeWebView
ref={RCT_WEBVIEW_REF}
key="webViewKey"
style={webViewStyles}
source={resolveAssetSource(source)}
scalesPageToFit={this.props.scalesPageToFit}
injectedJavaScript={this.props.injectedJavaScript}
userAgent={this.props.userAgent}
javaScriptEnabled={this.props.javaScriptEnabled}
thirdPartyCookiesEnabled={this.props.thirdPartyCookiesEnabled}
domStorageEnabled={this.props.domStorageEnabled}
messagingEnabled={typeof this.props.onMessage === 'function'}
onMessage={this.onMessage}
contentInset={this.props.contentInset}
automaticallyAdjustContentInsets={this.props.automaticallyAdjustContentInsets}
onContentSizeChange={this.props.onContentSizeChange}
onLoadingStart={this.onLoadingStart}
onLoadingFinish={this.onLoadingFinish}
onLoadingError={this.onLoadingError}
testID={this.props.testID}
mediaPlaybackRequiresUserAction={this.props.mediaPlaybackRequiresUserAction}
allowUniversalAccessFromFileURLs={this.props.allowUniversalAccessFromFileURLs}
mixedContentMode={this.props.mixedContentMode}
saveFormDataDisabled={this.props.saveFormDataDisabled}
urlPrefixesForDefaultIntent={this.props.urlPrefixesForDefaultIntent}
{...nativeConfig.props}
/>;
return (
<View style={styles.container}>
{webView}
{otherView}
</View>
);
}
goForward = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
UIManager.RCTWebView.Commands.goForward,
null
);
};
goBack = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
UIManager.RCTWebView.Commands.goBack,
null
);
};
reload = () => {
this.setState({
viewState: WebViewState.LOADING
});
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
UIManager.RCTWebView.Commands.reload,
null
);
};
stopLoading = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
UIManager.RCTWebView.Commands.stopLoading,
null
);
};
postMessage = (data) => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
UIManager.RCTWebView.Commands.postMessage,
[String(data)]
);
};
/**
* Injects a javascript string into the referenced WebView. Deliberately does not
* return a response because using eval() to return a response breaks this method
* on pages with a Content Security Policy that disallows eval(). If you need that
* functionality, look into postMessage/onMessage.
*/
injectJavaScript = (data) => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
UIManager.RCTWebView.Commands.injectJavaScript,
[data]
);
};
/**
* We return an event with a bunch of fields including:
* url, title, loading, canGoBack, canGoForward
*/
updateNavigationState = (event) => {
if (this.props.onNavigationStateChange) {
this.props.onNavigationStateChange(event.nativeEvent);
}
};
getWebViewHandle = () => {
return ReactNative.findNodeHandle(this.refs[RCT_WEBVIEW_REF]);
};
onLoadingStart = (event) => {
const onLoadStart = this.props.onLoadStart;
onLoadStart && onLoadStart(event);
this.updateNavigationState(event);
};
onLoadingError = (event) => {
event.persist(); // persist this event because we need to store it
const {onError, onLoadEnd} = this.props;
onError && onError(event);
onLoadEnd && onLoadEnd(event);
console.warn('Encountered an error loading page', event.nativeEvent);
this.setState({
lastErrorEvent: event.nativeEvent,
viewState: WebViewState.ERROR
});
};
onLoadingFinish = (event) => {
const {onLoad, onLoadEnd} = this.props;
onLoad && onLoad(event);
onLoadEnd && onLoadEnd(event);
this.setState({
viewState: WebViewState.IDLE,
});
this.updateNavigationState(event);
};
onMessage = (event: Event) => {
const {onMessage} = this.props;
onMessage && onMessage(event);
}
}
const RCTWebView = requireNativeComponent('RCTWebView', WebView, WebView.extraNativeComponentConfig);
const styles = StyleSheet.create({
container: {
flex: 1,
},
hidden: {
height: 0,
flex: 0, // disable 'flex:1' when hiding a View
},
loadingView: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
loadingProgressBar: {
height: 20,
},
});
module.exports = WebView;

View File

@@ -0,0 +1,669 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule WebView
* @noflow
*/
'use strict';
const ActivityIndicator = require('ActivityIndicator');
const EdgeInsetsPropType = require('EdgeInsetsPropType');
const React = require('React');
const PropTypes = require('prop-types');
const ReactNative = require('ReactNative');
const StyleSheet = require('StyleSheet');
const Text = require('Text');
const UIManager = require('UIManager');
const View = require('View');
const ViewPropTypes = require('ViewPropTypes');
const ScrollView = require('ScrollView');
const deprecatedPropType = require('deprecatedPropType');
const invariant = require('fbjs/lib/invariant');
const keyMirror = require('fbjs/lib/keyMirror');
const processDecelerationRate = require('processDecelerationRate');
const requireNativeComponent = require('requireNativeComponent');
const resolveAssetSource = require('resolveAssetSource');
const RCTWebViewManager = require('NativeModules').WebViewManager;
const BGWASH = 'rgba(255,255,255,0.8)';
const RCT_WEBVIEW_REF = 'webview';
const WebViewState = keyMirror({
IDLE: null,
LOADING: null,
ERROR: null,
});
const NavigationType = keyMirror({
click: true,
formsubmit: true,
backforward: true,
reload: true,
formresubmit: true,
other: true,
});
const JSNavigationScheme = 'react-js-navigation';
type ErrorEvent = {
domain: any,
code: any,
description: any,
}
type Event = Object;
const DataDetectorTypes = [
'phoneNumber',
'link',
'address',
'calendarEvent',
'none',
'all',
];
const defaultRenderLoading = () => (
<View style={styles.loadingView}>
<ActivityIndicator />
</View>
);
const defaultRenderError = (errorDomain, errorCode, errorDesc) => (
<View style={styles.errorContainer}>
<Text style={styles.errorTextTitle}>
Error loading page
</Text>
<Text style={styles.errorText}>
{'Domain: ' + errorDomain}
</Text>
<Text style={styles.errorText}>
{'Error Code: ' + errorCode}
</Text>
<Text style={styles.errorText}>
{'Description: ' + errorDesc}
</Text>
</View>
);
/**
* `WebView` renders web content in a native view.
*
*```
* import React, { Component } from 'react';
* import { WebView } from 'react-native';
*
* class MyWeb extends Component {
* render() {
* return (
* <WebView
* source={{uri: 'https://github.com/facebook/react-native'}}
* style={{marginTop: 20}}
* />
* );
* }
* }
*```
*
* You can use this component to navigate back and forth in the web view's
* history and configure various properties for the web content.
*/
class WebView extends React.Component {
static JSNavigationScheme = JSNavigationScheme;
static NavigationType = NavigationType;
static get extraNativeComponentConfig() {
return {
nativeOnly: {
onLoadingStart: true,
onLoadingError: true,
onLoadingFinish: true,
onMessage: true,
messagingEnabled: PropTypes.bool,
},
};
}
static propTypes = {
...ViewPropTypes,
html: deprecatedPropType(
PropTypes.string,
'Use the `source` prop instead.'
),
url: deprecatedPropType(
PropTypes.string,
'Use the `source` prop instead.'
),
/**
* Loads static html or a uri (with optional headers) in the WebView.
*/
source: PropTypes.oneOfType([
PropTypes.shape({
/*
* The URI to load in the `WebView`. Can be a local or remote file.
*/
uri: PropTypes.string,
/*
* The HTTP Method to use. Defaults to GET if not specified.
* NOTE: On Android, only GET and POST are supported.
*/
method: PropTypes.string,
/*
* Additional HTTP headers to send with the request.
* NOTE: On Android, this can only be used with GET requests.
*/
headers: PropTypes.object,
/*
* The HTTP body to send with the request. This must be a valid
* UTF-8 string, and will be sent exactly as specified, with no
* additional encoding (e.g. URL-escaping or base64) applied.
* NOTE: On Android, this can only be used with POST requests.
*/
body: PropTypes.string,
}),
PropTypes.shape({
/*
* A static HTML page to display in the WebView.
*/
html: PropTypes.string,
/*
* The base URL to be used for any relative links in the HTML.
*/
baseUrl: PropTypes.string,
}),
/*
* Used internally by packager.
*/
PropTypes.number,
]),
/**
* Function that returns a view to show if there's an error.
*/
renderError: PropTypes.func, // view to show if there's an error
/**
* Function that returns a loading indicator.
*/
renderLoading: PropTypes.func,
/**
* Function that is invoked when the `WebView` has finished loading.
*/
onLoad: PropTypes.func,
/**
* Function that is invoked when the `WebView` load succeeds or fails.
*/
onLoadEnd: PropTypes.func,
/**
* Function that is invoked when the `WebView` starts loading.
*/
onLoadStart: PropTypes.func,
/**
* Function that is invoked when the `WebView` load fails.
*/
onError: PropTypes.func,
/**
* Boolean value that determines whether the web view bounces
* when it reaches the edge of the content. The default value is `true`.
* @platform ios
*/
bounces: PropTypes.bool,
/**
* A floating-point number that determines how quickly the scroll view
* decelerates after the user lifts their finger. You may also use the
* string shortcuts `"normal"` and `"fast"` which match the underlying iOS
* settings for `UIScrollViewDecelerationRateNormal` and
* `UIScrollViewDecelerationRateFast` respectively:
*
* - normal: 0.998
* - fast: 0.99 (the default for iOS web view)
* @platform ios
*/
decelerationRate: ScrollView.propTypes.decelerationRate,
/**
* Boolean value that determines whether scrolling is enabled in the
* `WebView`. The default value is `true`.
* @platform ios
*/
scrollEnabled: PropTypes.bool,
/**
* Controls whether to adjust the content inset for web views that are
* placed behind a navigation bar, tab bar, or toolbar. The default value
* is `true`.
*/
automaticallyAdjustContentInsets: PropTypes.bool,
/**
* The amount by which the web view content is inset from the edges of
* the scroll view. Defaults to {top: 0, left: 0, bottom: 0, right: 0}.
* @platform ios
*/
contentInset: EdgeInsetsPropType,
/**
* Function that is invoked when the `WebView` loading starts or ends.
*/
onNavigationStateChange: PropTypes.func,
/**
* A function that is invoked when the webview calls `window.postMessage`.
* Setting this property will inject a `postMessage` global into your
* webview, but will still call pre-existing values of `postMessage`.
*
* `window.postMessage` accepts one argument, `data`, which will be
* available on the event object, `event.nativeEvent.data`. `data`
* must be a string.
*/
onMessage: PropTypes.func,
/**
* Boolean value that forces the `WebView` to show the loading view
* on the first load.
*/
startInLoadingState: PropTypes.bool,
/**
* The style to apply to the `WebView`.
*/
style: ViewPropTypes.style,
/**
* Determines the types of data converted to clickable URLs in the web view's content.
* By default only phone numbers are detected.
*
* You can provide one type or an array of many types.
*
* Possible values for `dataDetectorTypes` are:
*
* - `'phoneNumber'`
* - `'link'`
* - `'address'`
* - `'calendarEvent'`
* - `'none'`
* - `'all'`
*
* @platform ios
*/
dataDetectorTypes: PropTypes.oneOfType([
PropTypes.oneOf(DataDetectorTypes),
PropTypes.arrayOf(PropTypes.oneOf(DataDetectorTypes)),
]),
/**
* Boolean value to enable JavaScript in the `WebView`. Used on Android only
* as JavaScript is enabled by default on iOS. The default value is `true`.
* @platform android
*/
javaScriptEnabled: PropTypes.bool,
/**
* Boolean value to enable third party cookies in the `WebView`. Used on
* Android Lollipop and above only as third party cookies are enabled by
* default on Android Kitkat and below and on iOS. The default value is `true`.
* @platform android
*/
thirdPartyCookiesEnabled: PropTypes.bool,
/**
* Boolean value to control whether DOM Storage is enabled. Used only in
* Android.
* @platform android
*/
domStorageEnabled: PropTypes.bool,
/**
* Set this to provide JavaScript that will be injected into the web page
* when the view loads.
*/
injectedJavaScript: PropTypes.string,
/**
* Sets the user-agent for the `WebView`.
* @platform android
*/
userAgent: PropTypes.string,
/**
* Boolean that controls whether the web content is scaled to fit
* the view and enables the user to change the scale. The default value
* is `true`.
*/
scalesPageToFit: PropTypes.bool,
/**
* Function that allows custom handling of any web view requests. Return
* `true` from the function to continue loading the request and `false`
* to stop loading.
* @platform ios
*/
onShouldStartLoadWithRequest: PropTypes.func,
/**
* Boolean that determines whether HTML5 videos play inline or use the
* native full-screen controller. The default value is `false`.
*
* **NOTE** : In order for video to play inline, not only does this
* property need to be set to `true`, but the video element in the HTML
* document must also include the `webkit-playsinline` attribute.
* @platform ios
*/
allowsInlineMediaPlayback: PropTypes.bool,
/**
* Boolean that determines whether HTML5 audio and video requires the user
* to tap them before they start playing. The default value is `true`.
*/
mediaPlaybackRequiresUserAction: PropTypes.bool,
/**
* Function that accepts a string that will be passed to the WebView and
* executed immediately as JavaScript.
*/
injectJavaScript: PropTypes.func,
/**
* Specifies the mixed content mode. i.e WebView will allow a secure origin to load content from any other origin.
*
* Possible values for `mixedContentMode` are:
*
* - `'never'` (default) - WebView will not allow a secure origin to load content from an insecure origin.
* - `'always'` - WebView will allow a secure origin to load content from any other origin, even if that origin is insecure.
* - `'compatibility'` - WebView will attempt to be compatible with the approach of a modern web browser with regard to mixed content.
* @platform android
*/
mixedContentMode: PropTypes.oneOf([
'never',
'always',
'compatibility'
]),
/**
* Override the native component used to render the WebView. Enables a custom native
* WebView which uses the same JavaScript as the original WebView.
*/
nativeConfig: PropTypes.shape({
/*
* The native component used to render the WebView.
*/
component: PropTypes.any,
/*
* Set props directly on the native component WebView. Enables custom props which the
* original WebView doesn't pass through.
*/
props: PropTypes.object,
/*
* Set the ViewManager to use for communcation with the native side.
* @platform ios
*/
viewManager: PropTypes.object,
}),
};
static defaultProps = {
scalesPageToFit: true,
};
state = {
viewState: WebViewState.IDLE,
lastErrorEvent: (null: ?ErrorEvent),
startInLoadingState: true,
};
UNSAFE_componentWillMount() {
if (this.props.startInLoadingState) {
this.setState({viewState: WebViewState.LOADING});
}
}
render() {
let otherView = null;
if (this.state.viewState === WebViewState.LOADING) {
otherView = (this.props.renderLoading || defaultRenderLoading)();
} else if (this.state.viewState === WebViewState.ERROR) {
const errorEvent = this.state.lastErrorEvent;
invariant(
errorEvent != null,
'lastErrorEvent expected to be non-null'
);
otherView = (this.props.renderError || defaultRenderError)(
errorEvent.domain,
errorEvent.code,
errorEvent.description
);
} else if (this.state.viewState !== WebViewState.IDLE) {
console.error(
'RCTWebView invalid state encountered: ' + this.state.loading
);
}
const webViewStyles = [styles.container, styles.webView, this.props.style];
if (this.state.viewState === WebViewState.LOADING ||
this.state.viewState === WebViewState.ERROR) {
// if we're in either LOADING or ERROR states, don't show the webView
webViewStyles.push(styles.hidden);
}
const nativeConfig = this.props.nativeConfig || {};
const viewManager = nativeConfig.viewManager || RCTWebViewManager;
const onShouldStartLoadWithRequest = this.props.onShouldStartLoadWithRequest && ((event: Event) => {
const shouldStart = this.props.onShouldStartLoadWithRequest &&
this.props.onShouldStartLoadWithRequest(event.nativeEvent);
viewManager.startLoadWithResult(!!shouldStart, event.nativeEvent.lockIdentifier);
});
const decelerationRate = processDecelerationRate(this.props.decelerationRate);
const source = this.props.source || {};
if (this.props.html) {
source.html = this.props.html;
} else if (this.props.url) {
source.uri = this.props.url;
}
const messagingEnabled = typeof this.props.onMessage === 'function';
const NativeWebView = nativeConfig.component || RCTWebView;
const webView =
<NativeWebView
ref={RCT_WEBVIEW_REF}
key="webViewKey"
style={webViewStyles}
source={resolveAssetSource(source)}
injectedJavaScript={this.props.injectedJavaScript}
bounces={this.props.bounces}
scrollEnabled={this.props.scrollEnabled}
decelerationRate={decelerationRate}
contentInset={this.props.contentInset}
automaticallyAdjustContentInsets={this.props.automaticallyAdjustContentInsets}
onLoadingStart={this._onLoadingStart}
onLoadingFinish={this._onLoadingFinish}
onLoadingError={this._onLoadingError}
messagingEnabled={messagingEnabled}
onMessage={this._onMessage}
onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
scalesPageToFit={this.props.scalesPageToFit}
allowsInlineMediaPlayback={this.props.allowsInlineMediaPlayback}
mediaPlaybackRequiresUserAction={this.props.mediaPlaybackRequiresUserAction}
dataDetectorTypes={this.props.dataDetectorTypes}
{...nativeConfig.props}
/>;
return (
<View style={styles.container}>
{webView}
{otherView}
</View>
);
}
/**
* Go forward one page in the web view's history.
*/
goForward = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
UIManager.RCTWebView.Commands.goForward,
null
);
};
/**
* Go back one page in the web view's history.
*/
goBack = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
UIManager.RCTWebView.Commands.goBack,
null
);
};
/**
* Reloads the current page.
*/
reload = () => {
this.setState({viewState: WebViewState.LOADING});
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
UIManager.RCTWebView.Commands.reload,
null
);
};
/**
* Stop loading the current page.
*/
stopLoading = () => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
UIManager.RCTWebView.Commands.stopLoading,
null
);
};
/**
* Posts a message to the web view, which will emit a `message` event.
* Accepts one argument, `data`, which must be a string.
*
* In your webview, you'll need to something like the following.
*
* ```js
* document.addEventListener('message', e => { document.title = e.data; });
* ```
*/
postMessage = (data) => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
UIManager.RCTWebView.Commands.postMessage,
[String(data)]
);
};
/**
* Injects a javascript string into the referenced WebView. Deliberately does not
* return a response because using eval() to return a response breaks this method
* on pages with a Content Security Policy that disallows eval(). If you need that
* functionality, look into postMessage/onMessage.
*/
injectJavaScript = (data) => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
UIManager.RCTWebView.Commands.injectJavaScript,
[data]
);
};
/**
* We return an event with a bunch of fields including:
* url, title, loading, canGoBack, canGoForward
*/
_updateNavigationState = (event: Event) => {
if (this.props.onNavigationStateChange) {
this.props.onNavigationStateChange(event.nativeEvent);
}
};
/**
* Returns the native `WebView` node.
*/
getWebViewHandle = (): any => {
return ReactNative.findNodeHandle(this.refs[RCT_WEBVIEW_REF]);
};
_onLoadingStart = (event: Event) => {
const onLoadStart = this.props.onLoadStart;
onLoadStart && onLoadStart(event);
this._updateNavigationState(event);
};
_onLoadingError = (event: Event) => {
event.persist(); // persist this event because we need to store it
const {onError, onLoadEnd} = this.props;
onError && onError(event);
onLoadEnd && onLoadEnd(event);
console.warn('Encountered an error loading page', event.nativeEvent);
this.setState({
lastErrorEvent: event.nativeEvent,
viewState: WebViewState.ERROR
});
};
_onLoadingFinish = (event: Event) => {
const {onLoad, onLoadEnd} = this.props;
onLoad && onLoad(event);
onLoadEnd && onLoadEnd(event);
this.setState({
viewState: WebViewState.IDLE,
});
this._updateNavigationState(event);
};
_onMessage = (event: Event) => {
const {onMessage} = this.props;
onMessage && onMessage(event);
}
}
const RCTWebView = requireNativeComponent('RCTWebView', WebView, WebView.extraNativeComponentConfig);
const styles = StyleSheet.create({
container: {
flex: 1,
},
errorContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: BGWASH,
},
errorText: {
fontSize: 14,
textAlign: 'center',
marginBottom: 2,
},
errorTextTitle: {
fontSize: 15,
fontWeight: '500',
marginBottom: 10,
},
hidden: {
height: 0,
flex: 0, // disable 'flex:1' when hiding a View
},
loadingView: {
backgroundColor: BGWASH,
flex: 1,
justifyContent: 'center',
alignItems: 'center',
height: 100,
},
webView: {
backgroundColor: '#ffffff',
}
});
module.exports = WebView;