Prettier the rest of ReactNative

Reviewed By: yungsters

Differential Revision: D7974340

fbshipit-source-id: 5fe457a8a9be4bd360fc3af9acb5c1136b2be0d7
This commit is contained in:
Eli White
2018-05-11 13:32:37 -07:00
committed by Facebook Github Bot
parent aba4ec0c09
commit 36fcbaa56d
170 changed files with 5132 additions and 3995 deletions

View File

@@ -4,11 +4,14 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const __fbBatchedBridge = { // eslint-disable-line no-unused-vars
const __fbBatchedBridge = {
// eslint-disable-line no-unused-vars
flushedQueue: function() {
return null;
}
},
};

View File

@@ -4,76 +4,92 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
ART,
Platform,
View,
} = ReactNative;
const {
Surface,
Path,
Group,
Transform,
Shape,
} = ART;
var {ART, Platform, View} = ReactNative;
const {Surface, Path, Group, Transform, Shape} = ART;
var scale = Platform.isTVOS ? 4 : 1;
class ARTExample extends React.Component<{}> {
render(){
const pathRect = new Path()
.moveTo(scale * 0,scale * 0)
.lineTo(scale * 0,scale * 110)
.lineTo(scale * 110,scale * 110)
.lineTo(scale * 110,scale * 0)
.close();
render() {
const pathRect = new Path()
.moveTo(scale * 0, scale * 0)
.lineTo(scale * 0, scale * 110)
.lineTo(scale * 110, scale * 110)
.lineTo(scale * 110, scale * 0)
.close();
const pathCircle0 = new Path()
.moveTo(scale * 30,scale * 5)
.arc(scale * 0,scale * 50,scale * 25)
.arc(scale * 0,-scale * 50,scale * 25)
.close();
const pathCircle0 = new Path()
.moveTo(scale * 30, scale * 5)
.arc(scale * 0, scale * 50, scale * 25)
.arc(scale * 0, -scale * 50, scale * 25)
.close();
const pathCircle1 = new Path()
.moveTo(scale * 30,scale * 55)
.arc(scale * 0,scale * 50,scale * 25)
.arc(scale * 0,-scale * 50,scale * 25)
.close();
const pathCircle1 = new Path()
.moveTo(scale * 30, scale * 55)
.arc(scale * 0, scale * 50, scale * 25)
.arc(scale * 0, -scale * 50, scale * 25)
.close();
const pathCircle2 = new Path()
.moveTo(scale * 55,scale * 30)
.arc(scale * 50,scale * 0,scale * 25)
.arc(-scale * 50,scale * 0,scale * 25)
.close();
const pathCircle2 = new Path()
.moveTo(scale * 55, scale * 30)
.arc(scale * 50, scale * 0, scale * 25)
.arc(-scale * 50, scale * 0, scale * 25)
.close();
const pathCircle3 = new Path()
.moveTo(scale * 55,scale * 80)
.arc(scale * 50,scale * 0,scale * 25)
.arc(-scale * 50,scale * 0,scale * 25)
.close();
const pathCircle3 = new Path()
.moveTo(scale * 55, scale * 80)
.arc(scale * 50, scale * 0, scale * 25)
.arc(-scale * 50, scale * 0, scale * 25)
.close();
return (
<View>
<Surface width={scale * 200} height={scale * 200}>
<Group>
<Shape d={pathRect} stroke="#000080" fill="#000080" strokeWidth={scale}/>
<Shape d={pathCircle0} stroke="#FF0000" fill="#FF0000" strokeWidth={scale}/>
<Shape d={pathCircle1} stroke="#00FF00" fill="#00FF00" strokeWidth={scale}/>
<Shape d={pathCircle2} stroke="#00FFFF" fill="#00FFFF" strokeWidth={scale}/>
<Shape d={pathCircle3} stroke="#FFFFFF" fill="#FFFFFF" strokeWidth={scale}/>
</Group>
</Surface>
</View>
);
}
return (
<View>
<Surface width={scale * 200} height={scale * 200}>
<Group>
<Shape
d={pathRect}
stroke="#000080"
fill="#000080"
strokeWidth={scale}
/>
<Shape
d={pathCircle0}
stroke="#FF0000"
fill="#FF0000"
strokeWidth={scale}
/>
<Shape
d={pathCircle1}
stroke="#00FF00"
fill="#00FF00"
strokeWidth={scale}
/>
<Shape
d={pathCircle2}
stroke="#00FFFF"
fill="#00FFFF"
strokeWidth={scale}
/>
<Shape
d={pathCircle3}
stroke="#FFFFFF"
fill="#FFFFFF"
strokeWidth={scale}
/>
</Group>
</Surface>
</View>
);
}
}
exports.title = '<ART>';
@@ -84,6 +100,6 @@ exports.examples = [
title: 'ART Example',
render(): React.Element<any> {
return <ARTExample />;
}
},
},
];

View File

@@ -4,7 +4,9 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
var React = require('react');
@@ -21,7 +23,12 @@ var {
var RNTesterBlock = require('./RNTesterBlock');
var RNTesterPage = require('./RNTesterPage');
var importantForAccessibilityValues = ['auto', 'yes', 'no', 'no-hide-descendants'];
var importantForAccessibilityValues = [
'auto',
'yes',
'no',
'no-hide-descendants',
];
class AccessibilityAndroidExample extends React.Component {
static title = 'Accessibility';
@@ -37,11 +44,11 @@ class AccessibilityAndroidExample extends React.Component {
componentDidMount() {
AccessibilityInfo.addEventListener(
'change',
this._handleScreenReaderToggled
this._handleScreenReaderToggled,
);
AccessibilityInfo.fetch().done((isEnabled) => {
AccessibilityInfo.fetch().done(isEnabled => {
this.setState({
screenReaderEnabled: isEnabled
screenReaderEnabled: isEnabled,
});
});
}
@@ -49,15 +56,15 @@ class AccessibilityAndroidExample extends React.Component {
componentWillUnmount() {
AccessibilityInfo.removeEventListener(
'change',
this._handleScreenReaderToggled
this._handleScreenReaderToggled,
);
}
_handleScreenReaderToggled = (isEnabled) => {
_handleScreenReaderToggled = isEnabled => {
this.setState({
screenReaderEnabled: isEnabled,
});
}
};
_addOne = () => {
this.setState({
@@ -80,23 +87,16 @@ class AccessibilityAndroidExample extends React.Component {
render() {
return (
<RNTesterPage title={'Accessibility'}>
<RNTesterBlock title="Nonaccessible view with TextViews">
<View>
<Text style={{color: 'green',}}>
This is
</Text>
<Text style={{color: 'blue'}}>
nontouchable normal view.
</Text>
<Text style={{color: 'green'}}>This is</Text>
<Text style={{color: 'blue'}}>nontouchable normal view.</Text>
</View>
</RNTesterBlock>
<RNTesterBlock title="Accessible view with TextViews wihout label">
<View accessible={true}>
<Text style={{color: 'green',}}>
This is
</Text>
<Text style={{color: 'green'}}>This is</Text>
<Text style={{color: 'blue'}}>
nontouchable accessible view without label.
</Text>
@@ -104,11 +104,10 @@ class AccessibilityAndroidExample extends React.Component {
</RNTesterBlock>
<RNTesterBlock title="Accessible view with TextViews with label">
<View accessible={true}
<View
accessible={true}
accessibilityLabel="I have label, so I read it instead of embedded text.">
<Text style={{color: 'green',}}>
This is
</Text>
<Text style={{color: 'green'}}>This is</Text>
<Text style={{color: 'blue'}}>
nontouchable accessible view with label.
</Text>
@@ -117,7 +116,9 @@ class AccessibilityAndroidExample extends React.Component {
<RNTesterBlock title="Touchable with component type = button">
<TouchableWithoutFeedback
onPress={() => ToastAndroid.show('Toasts work by default', ToastAndroid.SHORT)}
onPress={() =>
ToastAndroid.show('Toasts work by default', ToastAndroid.SHORT)
}
accessibilityComponentType="button">
<View style={styles.embedded}>
<Text>Click me</Text>
@@ -139,7 +140,8 @@ class AccessibilityAndroidExample extends React.Component {
<RNTesterBlock title="Check if the screen reader is enabled">
<Text>
The screen reader is {this.state.screenReaderEnabled ? 'enabled' : 'disabled'}.
The screen reader is{' '}
{this.state.screenReaderEnabled ? 'enabled' : 'disabled'}.
</Text>
</RNTesterBlock>
@@ -152,15 +154,17 @@ class AccessibilityAndroidExample extends React.Component {
top: 10,
right: 10,
height: 100,
backgroundColor: 'green'}}
backgroundColor: 'green',
}}
accessible={true}
accessibilityLabel="First layout"
importantForAccessibility={
importantForAccessibilityValues[this.state.backgroundImportantForAcc]}>
importantForAccessibilityValues[
this.state.backgroundImportantForAcc
]
}>
<View accessible={true}>
<Text style={{fontSize: 25}}>
Hello
</Text>
<Text style={{fontSize: 25}}>Hello</Text>
</View>
</View>
<View
@@ -170,19 +174,23 @@ class AccessibilityAndroidExample extends React.Component {
top: 25,
right: 10,
height: 110,
backgroundColor: 'yellow', opacity: 0.5}}
backgroundColor: 'yellow',
opacity: 0.5,
}}
accessible={true}
accessibilityLabel="Second layout"
importantForAccessibility={
importantForAccessibilityValues[this.state.forgroundImportantForAcc]}>
importantForAccessibilityValues[
this.state.forgroundImportantForAcc
]
}>
<View accessible={true}>
<Text style={{fontSize: 20}}>
world
</Text>
<Text style={{fontSize: 20}}>world</Text>
</View>
</View>
</View>
<TouchableWithoutFeedback onPress={this._changeBackgroundImportantForAcc}>
<TouchableWithoutFeedback
onPress={this._changeBackgroundImportantForAcc}>
<View style={styles.embedded}>
<Text>
Change importantForAccessibility for background layout.
@@ -190,14 +198,17 @@ class AccessibilityAndroidExample extends React.Component {
</View>
</TouchableWithoutFeedback>
<View accessible={true}>
<Text>Background layout importantForAccessibility</Text>
<Text>
Background layout importantForAccessibility
</Text>
<Text>
{importantForAccessibilityValues[this.state.backgroundImportantForAcc]}
{
importantForAccessibilityValues[
this.state.backgroundImportantForAcc
]
}
</Text>
</View>
<TouchableWithoutFeedback onPress={this._changeForgroundImportantForAcc}>
<TouchableWithoutFeedback
onPress={this._changeForgroundImportantForAcc}>
<View style={styles.embedded}>
<Text>
Change importantForAccessibility for forground layout.
@@ -205,30 +216,31 @@ class AccessibilityAndroidExample extends React.Component {
</View>
</TouchableWithoutFeedback>
<View accessible={true}>
<Text>Forground layout importantForAccessibility</Text>
<Text>
Forground layout importantForAccessibility
</Text>
<Text>
{importantForAccessibilityValues[this.state.forgroundImportantForAcc]}
{
importantForAccessibilityValues[
this.state.forgroundImportantForAcc
]
}
</Text>
</View>
</RNTesterBlock>
</RNTesterPage>
);
}
}
var styles = StyleSheet.create({
embedded: {
embedded: {
backgroundColor: 'yellow',
padding:10,
padding: 10,
},
container: {
flex: 1,
backgroundColor: 'white',
padding: 10,
height:150,
height: 150,
},
});

View File

@@ -4,17 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
AccessibilityInfo,
Text,
View,
} = ReactNative;
var {AccessibilityInfo, Text, View} = ReactNative;
class AccessibilityIOSExample extends React.Component<{}> {
render() {
@@ -23,37 +21,28 @@ class AccessibilityIOSExample extends React.Component<{}> {
<View
onAccessibilityTap={() => alert('onAccessibilityTap success')}
accessible={true}>
<Text>
Accessibility normal tap example
</Text>
<Text>Accessibility normal tap example</Text>
</View>
<View onMagicTap={() => alert('onMagicTap success')}
accessible={true}>
<Text>
Accessibility magic tap example
</Text>
<View onMagicTap={() => alert('onMagicTap success')} accessible={true}>
<Text>Accessibility magic tap example</Text>
</View>
<View accessibilityLabel="Some announcement"
accessible={true}>
<Text>
Accessibility label example
</Text>
<View accessibilityLabel="Some announcement" accessible={true}>
<Text>Accessibility label example</Text>
</View>
<View accessibilityTraits={['button', 'selected']}
accessible={true}>
<Text>
Accessibility traits example
</Text>
<View accessibilityTraits={['button', 'selected']} accessible={true}>
<Text>Accessibility traits example</Text>
</View>
<Text>
Text's accessibilityLabel is the raw text itself unless it is set explicitly.
Text's accessibilityLabel is the raw text itself unless it is set
explicitly.
</Text>
<Text accessibilityLabel="Test of accessibilityLabel"
accessible={true}>
<Text accessibilityLabel="Test of accessibilityLabel" accessible={true}>
This text component's accessibilityLabel is set explicitly.
</Text>
<View accessibilityElementsHidden={true}>
<Text>This view's children are hidden from the accessibility tree</Text>
<Text>
This view's children are hidden from the accessibility tree
</Text>
</View>
</View>
);
@@ -63,16 +52,16 @@ class AccessibilityIOSExample extends React.Component<{}> {
class ScreenReaderStatusExample extends React.Component<{}, $FlowFixMeState> {
state = {
screenReaderEnabled: false,
}
};
componentDidMount() {
AccessibilityInfo.addEventListener(
'change',
this._handleScreenReaderToggled
this._handleScreenReaderToggled,
);
AccessibilityInfo.fetch().done((isEnabled) => {
AccessibilityInfo.fetch().done(isEnabled => {
this.setState({
screenReaderEnabled: isEnabled
screenReaderEnabled: isEnabled,
});
});
}
@@ -80,21 +69,22 @@ class ScreenReaderStatusExample extends React.Component<{}, $FlowFixMeState> {
componentWillUnmount() {
AccessibilityInfo.removeEventListener(
'change',
this._handleScreenReaderToggled
this._handleScreenReaderToggled,
);
}
_handleScreenReaderToggled = (isEnabled) => {
_handleScreenReaderToggled = isEnabled => {
this.setState({
screenReaderEnabled: isEnabled,
});
}
};
render() {
return (
<View>
<Text>
The screen reader is {this.state.screenReaderEnabled ? 'enabled' : 'disabled'}.
The screen reader is{' '}
{this.state.screenReaderEnabled ? 'enabled' : 'disabled'}.
</Text>
</View>
);
@@ -102,14 +92,18 @@ class ScreenReaderStatusExample extends React.Component<{}, $FlowFixMeState> {
}
exports.title = 'AccessibilityIOS';
exports.description = 'Interface to show iOS\' accessibility samples';
exports.description = "Interface to show iOS' accessibility samples";
exports.examples = [
{
title: 'Accessibility elements',
render(): React.Element<any> { return <AccessibilityIOSExample />; }
render(): React.Element<any> {
return <AccessibilityIOSExample />;
},
},
{
title: 'Check if the screen reader is enabled',
render(): React.Element<any> { return <ScreenReaderStatusExample />; }
render(): React.Element<any> {
return <ScreenReaderStatusExample />;
},
},
];

View File

@@ -4,27 +4,17 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
ActionSheetIOS,
StyleSheet,
takeSnapshot,
Text,
View,
} = ReactNative;
var {ActionSheetIOS, StyleSheet, takeSnapshot, Text, View} = ReactNative;
var BUTTONS = [
'Option 0',
'Option 1',
'Option 2',
'Delete',
'Cancel',
];
var BUTTONS = ['Option 0', 'Option 1', 'Option 2', 'Delete', 'Cancel'];
var DESTRUCTIVE_INDEX = 3;
var CANCEL_INDEX = 4;
@@ -39,22 +29,22 @@ class ActionSheetExample extends React.Component<{}, $FlowFixMeState> {
<Text onPress={this.showActionSheet} style={style.button}>
Click to show the ActionSheet
</Text>
<Text>
Clicked button: {this.state.clicked}
</Text>
<Text>Clicked button: {this.state.clicked}</Text>
</View>
);
}
showActionSheet = () => {
ActionSheetIOS.showActionSheetWithOptions({
options: BUTTONS,
cancelButtonIndex: CANCEL_INDEX,
destructiveButtonIndex: DESTRUCTIVE_INDEX,
},
(buttonIndex) => {
this.setState({ clicked: BUTTONS[buttonIndex] });
});
ActionSheetIOS.showActionSheetWithOptions(
{
options: BUTTONS,
cancelButtonIndex: CANCEL_INDEX,
destructiveButtonIndex: DESTRUCTIVE_INDEX,
},
buttonIndex => {
this.setState({clicked: BUTTONS[buttonIndex]});
},
);
};
}
@@ -69,29 +59,32 @@ class ActionSheetTintExample extends React.Component<{}, $FlowFixMeState> {
<Text onPress={this.showActionSheet} style={style.button}>
Click to show the ActionSheet
</Text>
<Text>
Clicked button: {this.state.clicked}
</Text>
<Text>Clicked button: {this.state.clicked}</Text>
</View>
);
}
showActionSheet = () => {
ActionSheetIOS.showActionSheetWithOptions({
options: BUTTONS,
cancelButtonIndex: CANCEL_INDEX,
destructiveButtonIndex: DESTRUCTIVE_INDEX,
tintColor: 'green',
},
(buttonIndex) => {
this.setState({ clicked: BUTTONS[buttonIndex] });
});
ActionSheetIOS.showActionSheetWithOptions(
{
options: BUTTONS,
cancelButtonIndex: CANCEL_INDEX,
destructiveButtonIndex: DESTRUCTIVE_INDEX,
tintColor: 'green',
},
buttonIndex => {
this.setState({clicked: BUTTONS[buttonIndex]});
},
);
};
}
class ShareActionSheetExample extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
class ShareActionSheetExample extends React.Component<
$FlowFixMeProps,
$FlowFixMeState,
> {
state = {
text: ''
text: '',
};
render() {
@@ -100,38 +93,36 @@ class ShareActionSheetExample extends React.Component<$FlowFixMeProps, $FlowFixM
<Text onPress={this.showShareActionSheet} style={style.button}>
Click to show the Share ActionSheet
</Text>
<Text>
{this.state.text}
</Text>
<Text>{this.state.text}</Text>
</View>
);
}
showShareActionSheet = () => {
ActionSheetIOS.showShareActionSheetWithOptions({
url: this.props.url,
message: 'message to go with the shared url',
subject: 'a subject to go in the email heading',
excludedActivityTypes: [
'com.apple.UIKit.activity.PostToTwitter'
]
},
(error) => alert(error),
(completed, method) => {
var text;
if (completed) {
text = `Shared via ${method}`;
} else {
text = 'You didn\'t share';
}
this.setState({text});
});
ActionSheetIOS.showShareActionSheetWithOptions(
{
url: this.props.url,
message: 'message to go with the shared url',
subject: 'a subject to go in the email heading',
excludedActivityTypes: ['com.apple.UIKit.activity.PostToTwitter'],
},
error => alert(error),
(completed, method) => {
var text;
if (completed) {
text = `Shared via ${method}`;
} else {
text = "You didn't share";
}
this.setState({text});
},
);
};
}
class ShareScreenshotExample extends React.Component<{}, $FlowFixMeState> {
state = {
text: ''
text: '',
};
render() {
@@ -140,34 +131,34 @@ class ShareScreenshotExample extends React.Component<{}, $FlowFixMeState> {
<Text onPress={this.showShareActionSheet} style={style.button}>
Click to show the Share ActionSheet
</Text>
<Text>
{this.state.text}
</Text>
<Text>{this.state.text}</Text>
</View>
);
}
showShareActionSheet = () => {
// Take the snapshot (returns a temp file uri)
takeSnapshot('window').then((uri) => {
// Share image data
ActionSheetIOS.showShareActionSheetWithOptions({
url: uri,
excludedActivityTypes: [
'com.apple.UIKit.activity.PostToTwitter'
]
},
(error) => alert(error),
(completed, method) => {
var text;
if (completed) {
text = `Shared via ${method}`;
} else {
text = 'You didn\'t share';
}
this.setState({text});
});
}).catch((error) => alert(error));
takeSnapshot('window')
.then(uri => {
// Share image data
ActionSheetIOS.showShareActionSheetWithOptions(
{
url: uri,
excludedActivityTypes: ['com.apple.UIKit.activity.PostToTwitter'],
},
error => alert(error),
(completed, method) => {
var text;
if (completed) {
text = `Shared via ${method}`;
} else {
text = "You didn't share";
}
this.setState({text});
},
);
})
.catch(error => alert(error));
};
}
@@ -175,36 +166,40 @@ var style = StyleSheet.create({
button: {
marginBottom: 10,
fontWeight: '500',
}
},
});
exports.title = 'ActionSheetIOS';
exports.description = 'Interface to show iOS\' action sheets';
exports.description = "Interface to show iOS' action sheets";
exports.examples = [
{
title: 'Show Action Sheet',
render(): React.Element<any> { return <ActionSheetExample />; }
render(): React.Element<any> {
return <ActionSheetExample />;
},
},
{
title: 'Show Action Sheet with tinted buttons',
render(): React.Element<any> { return <ActionSheetTintExample />; }
render(): React.Element<any> {
return <ActionSheetTintExample />;
},
},
{
title: 'Show Share Action Sheet',
render(): React.Element<any> {
return <ShareActionSheetExample url="https://code.facebook.com" />;
}
},
},
{
title: 'Share Local Image',
render(): React.Element<any> {
return <ShareActionSheetExample url="bunny.png" />;
}
},
},
{
title: 'Share Screenshot',
render(): React.Element<any> {
return <ShareScreenshotExample />;
}
}
},
},
];

View File

@@ -4,20 +4,25 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
import React, { Component } from 'react';
import { ActivityIndicator, StyleSheet, View } from 'react-native';
import React, {Component} from 'react';
import {ActivityIndicator, StyleSheet, View} from 'react-native';
/**
* Optional Flowtype state and timer types definition
*/
type State = { animating: boolean; };
type State = {animating: boolean};
type Timer = number;
class ToggleAnimatingActivityIndicator extends Component<$FlowFixMeProps, State> {
class ToggleAnimatingActivityIndicator extends Component<
$FlowFixMeProps,
State,
> {
_timer: Timer;
constructor(props) {
@@ -59,8 +64,6 @@ class ToggleAnimatingActivityIndicator extends Component<$FlowFixMeProps, State>
}
}
exports.displayName = (undefined: ?string);
exports.framework = 'React';
exports.title = '<ActivityIndicator>';
@@ -76,22 +79,20 @@ exports.examples = [
color="white"
/>
);
}
},
},
{
title: 'Gray',
render() {
return (
<View>
<ActivityIndicator
style={[styles.centering]}
/>
<ActivityIndicator style={[styles.centering]} />
<ActivityIndicator
style={[styles.centering, {backgroundColor: '#eeeeee'}]}
/>
</View>
);
}
},
},
{
title: 'Custom colors',
@@ -104,7 +105,7 @@ exports.examples = [
<ActivityIndicator color="#00aa00" />
</View>
);
}
},
},
{
title: 'Large',
@@ -116,38 +117,26 @@ exports.examples = [
color="white"
/>
);
}
},
},
{
title: 'Large, custom colors',
render() {
return (
<View style={styles.horizontal}>
<ActivityIndicator
size="large"
color="#0000ff"
/>
<ActivityIndicator
size="large"
color="#aa00aa"
/>
<ActivityIndicator
size="large"
color="#aa3300"
/>
<ActivityIndicator
size="large"
color="#00aa00"
/>
<ActivityIndicator size="large" color="#0000ff" />
<ActivityIndicator size="large" color="#aa00aa" />
<ActivityIndicator size="large" color="#aa3300" />
<ActivityIndicator size="large" color="#00aa00" />
</View>
);
}
},
},
{
title: 'Start/stop',
render() {
return <ToggleAnimatingActivityIndicator />;
}
},
},
{
title: 'Custom size',
@@ -158,23 +147,17 @@ exports.examples = [
size="large"
/>
);
}
},
},
{
platform: 'android',
title: 'Custom size (size: 75)',
render() {
return (
<ActivityIndicator
style={styles.centering}
size={75}
/>
);
}
return <ActivityIndicator style={styles.centering} size={75} />;
},
},
];
const styles = StyleSheet.create({
centering: {
alignItems: 'center',

View File

@@ -4,25 +4,21 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Alert,
StyleSheet,
Text,
TouchableHighlight,
View,
} = ReactNative;
var {Alert, StyleSheet, Text, TouchableHighlight, View} = ReactNative;
var RNTesterBlock = require('./RNTesterBlock');
// corporate ipsum > lorem ipsum
var alertMessage = 'Credibly reintermediate next-generation potentialities after goal-oriented ' +
'catalysts for change. Dynamically revolutionize.';
var alertMessage =
'Credibly reintermediate next-generation potentialities after goal-oriented ' +
'catalysts for change. Dynamically revolutionize.';
/**
* Simple alert examples.
@@ -31,90 +27,88 @@ class SimpleAlertExampleBlock extends React.Component {
render() {
return (
<View>
<TouchableHighlight style={styles.wrapper}
onPress={() => Alert.alert(
'Alert Title',
alertMessage,
)}>
<TouchableHighlight
style={styles.wrapper}
onPress={() => Alert.alert('Alert Title', alertMessage)}>
<View style={styles.button}>
<Text>Alert with message and default button</Text>
</View>
</TouchableHighlight>
<TouchableHighlight style={styles.wrapper}
onPress={() => Alert.alert(
'Alert Title',
alertMessage,
[
<TouchableHighlight
style={styles.wrapper}
onPress={() =>
Alert.alert('Alert Title', alertMessage, [
{text: 'OK', onPress: () => console.log('OK Pressed!')},
]
)}>
])
}>
<View style={styles.button}>
<Text>Alert with one button</Text>
</View>
</TouchableHighlight>
<TouchableHighlight style={styles.wrapper}
onPress={() => Alert.alert(
'Alert Title',
alertMessage,
[
<TouchableHighlight
style={styles.wrapper}
onPress={() =>
Alert.alert('Alert Title', alertMessage, [
{text: 'Cancel', onPress: () => console.log('Cancel Pressed!')},
{text: 'OK', onPress: () => console.log('OK Pressed!')},
]
)}>
])
}>
<View style={styles.button}>
<Text>Alert with two buttons</Text>
</View>
</TouchableHighlight>
<TouchableHighlight style={styles.wrapper}
onPress={() => Alert.alert(
'Alert Title',
null,
[
<TouchableHighlight
style={styles.wrapper}
onPress={() =>
Alert.alert('Alert Title', null, [
{text: 'Foo', onPress: () => console.log('Foo Pressed!')},
{text: 'Bar', onPress: () => console.log('Bar Pressed!')},
{text: 'Baz', onPress: () => console.log('Baz Pressed!')},
]
)}>
])
}>
<View style={styles.button}>
<Text>Alert with three buttons</Text>
</View>
</TouchableHighlight>
<TouchableHighlight style={styles.wrapper}
onPress={() => Alert.alert(
'Foo Title',
alertMessage,
'..............'.split('').map((dot, index) => ({
text: 'Button ' + index,
onPress: () => console.log('Pressed ' + index)
}))
)}>
<TouchableHighlight
style={styles.wrapper}
onPress={() =>
Alert.alert(
'Foo Title',
alertMessage,
'..............'.split('').map((dot, index) => ({
text: 'Button ' + index,
onPress: () => console.log('Pressed ' + index),
})),
)
}>
<View style={styles.button}>
<Text>Alert with too many buttons</Text>
</View>
</TouchableHighlight>
<TouchableHighlight style={styles.wrapper}
onPress={() => Alert.alert(
'Alert Title',
null,
[
{text: 'OK', onPress: () => console.log('OK Pressed!')},
],
{
cancelable: false
}
)}>
<TouchableHighlight
style={styles.wrapper}
onPress={() =>
Alert.alert(
'Alert Title',
null,
[{text: 'OK', onPress: () => console.log('OK Pressed!')}],
{
cancelable: false,
},
)
}>
<View style={styles.button}>
<Text>Alert that cannot be dismissed</Text>
</View>
</TouchableHighlight>
<TouchableHighlight style={styles.wrapper}
onPress={() => Alert.alert(
'',
alertMessage,
[
<TouchableHighlight
style={styles.wrapper}
onPress={() =>
Alert.alert('', alertMessage, [
{text: 'OK', onPress: () => console.log('OK Pressed!')},
]
)}>
])
}>
<View style={styles.button}>
<Text>Alert without title</Text>
</View>

View File

@@ -4,79 +4,69 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
StyleSheet,
View,
Text,
TouchableHighlight,
AlertIOS,
} = ReactNative;
var {StyleSheet, View, Text, TouchableHighlight, AlertIOS} = ReactNative;
var { SimpleAlertExampleBlock } = require('./AlertExample');
var {SimpleAlertExampleBlock} = require('./AlertExample');
exports.framework = 'React';
exports.title = 'AlertIOS';
exports.description = 'iOS alerts and action sheets';
exports.examples = [{
title: 'Alerts',
render() {
return <SimpleAlertExampleBlock />;
}
},
{
title: 'Prompt Options',
render(): React.Element<any> {
return <PromptOptions />;
}
},
{
title: 'Prompt Types',
render() {
return (
<View>
<TouchableHighlight
style={styles.wrapper}
onPress={() => AlertIOS.prompt('Plain Text Entry')}>
<View style={styles.button}>
<Text>
plain-text
</Text>
</View>
</TouchableHighlight>
<TouchableHighlight
style={styles.wrapper}
onPress={() => AlertIOS.prompt('Secure Text', null, null, 'secure-text')}>
<View style={styles.button}>
<Text>
secure-text
</Text>
</View>
</TouchableHighlight>
<TouchableHighlight
style={styles.wrapper}
onPress={() => AlertIOS.prompt('Login & Password', null, null, 'login-password')}>
<View style={styles.button}>
<Text>
login-password
</Text>
</View>
</TouchableHighlight>
</View>
);
}
}];
exports.examples = [
{
title: 'Alerts',
render() {
return <SimpleAlertExampleBlock />;
},
},
{
title: 'Prompt Options',
render(): React.Element<any> {
return <PromptOptions />;
},
},
{
title: 'Prompt Types',
render() {
return (
<View>
<TouchableHighlight
style={styles.wrapper}
onPress={() => AlertIOS.prompt('Plain Text Entry')}>
<View style={styles.button}>
<Text>plain-text</Text>
</View>
</TouchableHighlight>
<TouchableHighlight
style={styles.wrapper}
onPress={() =>
AlertIOS.prompt('Secure Text', null, null, 'secure-text')
}>
<View style={styles.button}>
<Text>secure-text</Text>
</View>
</TouchableHighlight>
<TouchableHighlight
style={styles.wrapper}
onPress={() =>
AlertIOS.prompt('Login & Password', null, null, 'login-password')
}>
<View style={styles.button}>
<Text>login-password</Text>
</View>
</TouchableHighlight>
</View>
);
},
},
];
class PromptOptions extends React.Component<$FlowFixMeProps, any> {
customButtons: Array<Object>;
@@ -87,13 +77,16 @@ class PromptOptions extends React.Component<$FlowFixMeProps, any> {
// $FlowFixMe this seems to be a Flow bug, `saveResponse` is defined below
this.saveResponse = this.saveResponse.bind(this);
this.customButtons = [{
text: 'Custom OK',
onPress: this.saveResponse
}, {
text: 'Custom Cancel',
style: 'cancel',
}];
this.customButtons = [
{
text: 'Custom OK',
onPress: this.saveResponse,
},
{
text: 'Custom Cancel',
style: 'cancel',
},
];
this.state = {
promptValue: undefined,
@@ -104,57 +97,74 @@ class PromptOptions extends React.Component<$FlowFixMeProps, any> {
return (
<View>
<Text style={{marginBottom: 10}}>
<Text style={{fontWeight: 'bold'}}>Prompt value:</Text> {this.state.promptValue}
<Text style={{fontWeight: 'bold'}}>Prompt value:</Text>{' '}
{this.state.promptValue}
</Text>
<TouchableHighlight
style={styles.wrapper}
onPress={() => AlertIOS.prompt('Type a value', null, this.saveResponse)}>
onPress={() =>
AlertIOS.prompt('Type a value', null, this.saveResponse)
}>
<View style={styles.button}>
<Text>
prompt with title & callback
</Text>
<Text>prompt with title & callback</Text>
</View>
</TouchableHighlight>
<TouchableHighlight
style={styles.wrapper}
onPress={() => AlertIOS.prompt('Type a value', null, this.customButtons)}>
onPress={() =>
AlertIOS.prompt('Type a value', null, this.customButtons)
}>
<View style={styles.button}>
<Text>
prompt with title & custom buttons
</Text>
<Text>prompt with title & custom buttons</Text>
</View>
</TouchableHighlight>
<TouchableHighlight
style={styles.wrapper}
onPress={() => AlertIOS.prompt('Type a phone number', null, null, 'plain-text', undefined, 'phone-pad')}>
onPress={() =>
AlertIOS.prompt(
'Type a phone number',
null,
null,
'plain-text',
undefined,
'phone-pad',
)
}>
<View style={styles.button}>
<Text>
prompt with title & custom keyboard
</Text>
<Text>prompt with title & custom keyboard</Text>
</View>
</TouchableHighlight>
<TouchableHighlight
style={styles.wrapper}
onPress={() => AlertIOS.prompt('Type a value', null, this.saveResponse, undefined, 'Default value')}>
onPress={() =>
AlertIOS.prompt(
'Type a value',
null,
this.saveResponse,
undefined,
'Default value',
)
}>
<View style={styles.button}>
<Text>
prompt with title, callback & default value
</Text>
<Text>prompt with title, callback & default value</Text>
</View>
</TouchableHighlight>
<TouchableHighlight
style={styles.wrapper}
onPress={() => AlertIOS.prompt('Type a value', null, this.customButtons, 'login-password', 'admin@site.com')}>
onPress={() =>
AlertIOS.prompt(
'Type a value',
null,
this.customButtons,
'login-password',
'admin@site.com',
)
}>
<View style={styles.button}>
<Text>
prompt with title, custom buttons, login/password & default value
@@ -166,7 +176,7 @@ class PromptOptions extends React.Component<$FlowFixMeProps, any> {
}
saveResponse(promptValue) {
this.setState({ promptValue: JSON.stringify(promptValue) });
this.setState({promptValue: JSON.stringify(promptValue)});
}
}

View File

@@ -4,31 +4,29 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Animated,
Easing,
StyleSheet,
Text,
View,
} = ReactNative;
var {Animated, Easing, StyleSheet, Text, View} = ReactNative;
var RNTesterButton = require('./RNTesterButton');
exports.framework = 'React';
exports.title = 'Animated - Examples';
exports.description = 'Animated provides a powerful ' +
exports.description =
'Animated provides a powerful ' +
'and easy-to-use API for building modern, ' +
'interactive user experiences.';
exports.examples = [
{
title: 'FadeInView',
description: 'Uses a simple timing animation to ' +
description:
'Uses a simple timing animation to ' +
'bring opacity from 0 to 1 when the component ' +
'mounts.',
render: function() {
@@ -40,19 +38,20 @@ exports.examples = [
};
}
componentDidMount() {
Animated.timing( // Uses easing functions
Animated.timing(
// Uses easing functions
this.state.fadeAnim, // The value to drive
{
toValue: 1, // Target
duration: 2000, // Configuration
toValue: 1, // Target
duration: 2000, // Configuration
},
).start(); // Don't forget start!
).start(); // Don't forget start!
}
render() {
return (
<Animated.View // Special animatable View
<Animated.View // Special animatable View
style={{
opacity: this.state.fadeAnim, // Binds
opacity: this.state.fadeAnim, // Binds
}}>
{this.props.children}
</Animated.View>
@@ -69,19 +68,19 @@ exports.examples = [
render() {
return (
<View>
<RNTesterButton onPress={() => {
this.setState((state) => (
{show: !state.show}
));
<RNTesterButton
onPress={() => {
this.setState(state => ({show: !state.show}));
}}>
Press to {this.state.show ?
'Hide' : 'Show'}
Press to {this.state.show ? 'Hide' : 'Show'}
</RNTesterButton>
{this.state.show && <FadeInView>
<View style={styles.content}>
<Text>FadeInView</Text>
</View>
</FadeInView>}
{this.state.show && (
<FadeInView>
<View style={styles.content}>
<Text>FadeInView</Text>
</View>
</FadeInView>
)}
</View>
);
}
@@ -91,7 +90,8 @@ exports.examples = [
},
{
title: 'Transform Bounce',
description: 'One `Animated.Value` is driven by a ' +
description:
'One `Animated.Value` is driven by a ' +
'spring with custom constants and mapped to an ' +
'ordered set of transforms. Each transform has ' +
'an interpolation to convert the value into the ' +
@@ -100,33 +100,46 @@ exports.examples = [
this.anim = this.anim || new Animated.Value(0);
return (
<View>
<RNTesterButton onPress={() => {
Animated.spring(this.anim, {
toValue: 0, // Returns to the start
velocity: 3, // Velocity makes it move
tension: -10, // Slow
friction: 1, // Oscillate a lot
}).start(); }}>
<RNTesterButton
onPress={() => {
Animated.spring(this.anim, {
toValue: 0, // Returns to the start
velocity: 3, // Velocity makes it move
tension: -10, // Slow
friction: 1, // Oscillate a lot
}).start();
}}>
Press to Fling it!
</RNTesterButton>
<Animated.View
style={[styles.content, {
transform: [ // Array order matters
{scale: this.anim.interpolate({
inputRange: [0, 1],
outputRange: [1, 4],
})},
{translateX: this.anim.interpolate({
inputRange: [0, 1],
outputRange: [0, 500],
})},
{rotate: this.anim.interpolate({
inputRange: [0, 1],
outputRange: [
'0deg', '360deg' // 'deg' or 'rad'
],
})},
]}
style={[
styles.content,
{
transform: [
// Array order matters
{
scale: this.anim.interpolate({
inputRange: [0, 1],
outputRange: [1, 4],
}),
},
{
translateX: this.anim.interpolate({
inputRange: [0, 1],
outputRange: [0, 500],
}),
},
{
rotate: this.anim.interpolate({
inputRange: [0, 1],
outputRange: [
'0deg',
'360deg', // 'deg' or 'rad'
],
}),
},
],
},
]}>
<Text>Transforms!</Text>
</Animated.View>
@@ -136,80 +149,87 @@ exports.examples = [
},
{
title: 'Composite Animations with Easing',
description: 'Sequence, parallel, delay, and ' +
description:
'Sequence, parallel, delay, and ' +
'stagger with different easing functions.',
render: function() {
this.anims = this.anims || [1,2,3].map(
() => new Animated.Value(0)
);
this.anims = this.anims || [1, 2, 3].map(() => new Animated.Value(0));
return (
<View>
<RNTesterButton onPress={() => {
var timing = Animated.timing;
Animated.sequence([ // One after the other
timing(this.anims[0], {
toValue: 200,
easing: Easing.linear,
}),
Animated.delay(400), // Use with sequence
timing(this.anims[0], {
toValue: 0,
easing: Easing.elastic(2), // Springy
}),
Animated.delay(400),
Animated.stagger(200,
this.anims.map((anim) => timing(
anim, {toValue: 200}
)).concat(
this.anims.map((anim) => timing(
anim, {toValue: 0}
))),
),
Animated.delay(400),
Animated.parallel([
Easing.inOut(Easing.quad), // Symmetric
Easing.back(1.5), // Goes backwards first
Easing.ease // Default bezier
].map((easing, ii) => (
timing(this.anims[ii], {
toValue: 320, easing, duration: 3000,
})
))),
Animated.delay(400),
Animated.stagger(200,
this.anims.map((anim) => timing(anim, {
<RNTesterButton
onPress={() => {
var timing = Animated.timing;
Animated.sequence([
// One after the other
timing(this.anims[0], {
toValue: 200,
easing: Easing.linear,
}),
Animated.delay(400), // Use with sequence
timing(this.anims[0], {
toValue: 0,
easing: Easing.bounce, // Like a ball
duration: 2000,
})),
),
]).start(); }}>
easing: Easing.elastic(2), // Springy
}),
Animated.delay(400),
Animated.stagger(
200,
this.anims
.map(anim => timing(anim, {toValue: 200}))
.concat(this.anims.map(anim => timing(anim, {toValue: 0}))),
),
Animated.delay(400),
Animated.parallel(
[
Easing.inOut(Easing.quad), // Symmetric
Easing.back(1.5), // Goes backwards first
Easing.ease, // Default bezier
].map((easing, ii) =>
timing(this.anims[ii], {
toValue: 320,
easing,
duration: 3000,
}),
),
),
Animated.delay(400),
Animated.stagger(
200,
this.anims.map(anim =>
timing(anim, {
toValue: 0,
easing: Easing.bounce, // Like a ball
duration: 2000,
}),
),
),
]).start();
}}>
Press to Animate
</RNTesterButton>
{['Composite', 'Easing', 'Animations!'].map(
(text, ii) => (
<Animated.View
key={text}
style={[styles.content, {
left: this.anims[ii]
}]}>
<Text>{text}</Text>
</Animated.View>
)
)}
{['Composite', 'Easing', 'Animations!'].map((text, ii) => (
<Animated.View
key={text}
style={[
styles.content,
{
left: this.anims[ii],
},
]}>
<Text>{text}</Text>
</Animated.View>
))}
</View>
);
},
},
{
title: 'Continuous Interactions',
description: 'Gesture events, chaining, 2D ' +
description:
'Gesture events, chaining, 2D ' +
'values, interrupting and transitioning ' +
'animations, etc.',
render: () => (
<Text>Checkout the Gratuitous Animation App!</Text>
),
}
render: () => <Text>Checkout the Gratuitous Animation App!</Text>,
},
];
var styles = StyleSheet.create({

View File

@@ -4,19 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Animated,
LayoutAnimation,
PanResponder,
StyleSheet,
View,
} = ReactNative;
var {Animated, LayoutAnimation, PanResponder, StyleSheet, View} = ReactNative;
var AnExSet = require('AnExSet');
@@ -36,55 +32,63 @@ class Circle extends React.Component<any, any> {
this.state = {
isActive: false,
pan: new Animated.ValueXY(), // Vectors reduce boilerplate. (step1: uncomment)
pop: new Animated.Value(0), // Initial value. (step2a: uncomment)
pop: new Animated.Value(0), // Initial value. (step2a: uncomment)
};
}
_onLongPress(): void {
var config = {tension: 40, friction: 3};
this.state.pan.addListener((value) => { // Async listener for state changes (step1: uncomment)
this.state.pan.addListener(value => {
// Async listener for state changes (step1: uncomment)
this.props.onMove && this.props.onMove(value);
});
Animated.spring(this.state.pop, {
toValue: 1, // Pop to larger size. (step2b: uncomment)
...config, // Reuse config for convenient consistency (step2b: uncomment)
toValue: 1, // Pop to larger size. (step2b: uncomment)
...config, // Reuse config for convenient consistency (step2b: uncomment)
}).start();
this.setState({panResponder: PanResponder.create({
onPanResponderMove: Animated.event([
null, // native event - ignore (step1: uncomment)
{dx: this.state.pan.x, dy: this.state.pan.y}, // links pan to gestureState (step1: uncomment)
]),
onPanResponderRelease: (e, gestureState) => {
LayoutAnimation.easeInEaseOut(); // @flowfixme animates layout update as one batch (step3: uncomment)
Animated.spring(this.state.pop, {
toValue: 0, // Pop back to 0 (step2c: uncomment)
...config,
}).start();
this.setState({panResponder: undefined});
this.props.onMove && this.props.onMove({
x: gestureState.dx + this.props.restLayout.x,
y: gestureState.dy + this.props.restLayout.y,
});
this.props.onDeactivate();
this.state.pan.removeAllListeners();
this.setState(
{
panResponder: PanResponder.create({
onPanResponderMove: Animated.event([
null, // native event - ignore (step1: uncomment)
{dx: this.state.pan.x, dy: this.state.pan.y}, // links pan to gestureState (step1: uncomment)
]),
onPanResponderRelease: (e, gestureState) => {
LayoutAnimation.easeInEaseOut(); // @flowfixme animates layout update as one batch (step3: uncomment)
Animated.spring(this.state.pop, {
toValue: 0, // Pop back to 0 (step2c: uncomment)
...config,
}).start();
this.setState({panResponder: undefined});
this.props.onMove &&
this.props.onMove({
x: gestureState.dx + this.props.restLayout.x,
y: gestureState.dy + this.props.restLayout.y,
});
this.props.onDeactivate();
this.state.pan.removeAllListeners();
},
}),
},
})}, () => {
this.props.onActivate();
});
() => {
this.props.onActivate();
},
);
}
render(): React.Node {
if (this.state.panResponder) {
var handlers = this.state.panResponder.panHandlers;
var dragStyle = { // Used to position while dragging
position: 'absolute', // Hoist out of layout (step1: uncomment)
...this.state.pan.getLayout(), // Convenience converter (step1: uncomment)
var dragStyle = {
// Used to position while dragging
position: 'absolute', // Hoist out of layout (step1: uncomment)
...this.state.pan.getLayout(), // Convenience converter (step1: uncomment)
};
} else {
handlers = {
onStartShouldSetResponder: () => !this.state.isActive,
onResponderGrant: () => {
this.state.pan.setValue({x: 0, y: 0}); // reset (step1: uncomment)
this.state.pan.setValue({x: 0, y: 0}); // reset (step1: uncomment)
this.state.pan.setOffset(this.props.restLayout); // offset from onLayout (step1: uncomment)
/* $FlowFixMe(>=0.63.0 site=react_native_fb) This comment suppresses
* an error found when Flow v0.63 was deployed. To see the error
@@ -99,35 +103,64 @@ class Circle extends React.Component<any, any> {
clearTimeout(this.longTimer);
this._toggleIsActive();
}
}
},
};
}
var animatedStyle: Object = {
shadowOpacity: this.state.pop, // no need for interpolation (step2d: uncomment)
shadowOpacity: this.state.pop, // no need for interpolation (step2d: uncomment)
transform: [
{scale: this.state.pop.interpolate({
inputRange: [0, 1],
outputRange: [1, 1.3] // scale up from 1 to 1.3 (step2d: uncomment)
})},
{
scale: this.state.pop.interpolate({
inputRange: [0, 1],
outputRange: [1, 1.3], // scale up from 1 to 1.3 (step2d: uncomment)
}),
},
],
};
var openVal = this.props.openVal;
if (this.props.dummy) {
animatedStyle.opacity = 0;
} else if (this.state.isActive) {
var innerOpenStyle = [styles.open, { // (step4: uncomment)
left: openVal.interpolate({inputRange: [0, 1], outputRange: [this.props.restLayout.x, 0]}),
top: openVal.interpolate({inputRange: [0, 1], outputRange: [this.props.restLayout.y, 0]}),
width: openVal.interpolate({inputRange: [0, 1], outputRange: [CIRCLE_SIZE, this.props.containerLayout.width]}),
height: openVal.interpolate({inputRange: [0, 1], outputRange: [CIRCLE_SIZE, this.props.containerLayout.height]}),
margin: openVal.interpolate({inputRange: [0, 1], outputRange: [CIRCLE_MARGIN, 0]}),
borderRadius: openVal.interpolate({inputRange: [-0.15, 0, 0.5, 1], outputRange: [0, CIRCLE_SIZE / 2, CIRCLE_SIZE * 1.3, 0]}),
}];
var innerOpenStyle = [
styles.open,
{
// (step4: uncomment)
left: openVal.interpolate({
inputRange: [0, 1],
outputRange: [this.props.restLayout.x, 0],
}),
top: openVal.interpolate({
inputRange: [0, 1],
outputRange: [this.props.restLayout.y, 0],
}),
width: openVal.interpolate({
inputRange: [0, 1],
outputRange: [CIRCLE_SIZE, this.props.containerLayout.width],
}),
height: openVal.interpolate({
inputRange: [0, 1],
outputRange: [CIRCLE_SIZE, this.props.containerLayout.height],
}),
margin: openVal.interpolate({
inputRange: [0, 1],
outputRange: [CIRCLE_MARGIN, 0],
}),
borderRadius: openVal.interpolate({
inputRange: [-0.15, 0, 0.5, 1],
outputRange: [0, CIRCLE_SIZE / 2, CIRCLE_SIZE * 1.3, 0],
}),
},
];
}
return (
<Animated.View
onLayout={this.props.onLayout}
style={[styles.dragView, dragStyle, animatedStyle, this.state.isActive ? styles.open : null]}
style={[
styles.dragView,
dragStyle,
animatedStyle,
this.state.isActive ? styles.open : null,
]}
{...handlers}>
<Animated.View style={[styles.circle, innerOpenStyle]}>
<AnExSet
@@ -144,14 +177,15 @@ class Circle extends React.Component<any, any> {
_toggleIsActive(velocity) {
var config = {tension: 30, friction: 7};
if (this.state.isActive) {
Animated.spring(this.props.openVal, {toValue: 0, ...config}).start(() => { // (step4: uncomment)
Animated.spring(this.props.openVal, {toValue: 0, ...config}).start(() => {
// (step4: uncomment)
this.setState({isActive: false}, this.props.onDeactivate);
}); // (step4: uncomment)
}); // (step4: uncomment)
} else {
this.props.onActivate();
this.setState({isActive: true, panResponder: undefined}, () => {
// this.props.openVal.setValue(1); // (step4: comment)
Animated.spring(this.props.openVal, {toValue: 1, ...config}).start(); // (step4: uncomment)
Animated.spring(this.props.openVal, {toValue: 1, ...config}).start(); // (step4: uncomment)
});
}
}
@@ -160,7 +194,7 @@ class Circle extends React.Component<any, any> {
class AnExApp extends React.Component<any, any> {
static title = 'Animated - Gratuitous App';
static description = 'Bunch of Animations - tap a circle to ' +
'open a view with more animations, or longPress and drag to reorder circles.';
'open a view with more animations, or longPress and drag to reorder circles.';
_onMove: (position: Point) => void;
constructor(props: any): void {
@@ -185,7 +219,7 @@ class AnExApp extends React.Component<any, any> {
if (!this.state.restLayouts[idx]) {
var onLayout = function(index, e) {
var layout = e.nativeEvent.layout;
this.setState((state) => {
this.setState(state => {
state.restLayouts[index] = layout;
return state;
});
@@ -208,7 +242,10 @@ class AnExApp extends React.Component<any, any> {
});
if (this.state.activeKey) {
circles.push(
<Animated.View key="dark" style={[styles.darkening, {opacity: this.state.openVal}]} />
<Animated.View
key="dark"
style={[styles.darkening, {opacity: this.state.openVal}]}
/>,
);
circles.push(
<Circle
@@ -218,13 +255,17 @@ class AnExApp extends React.Component<any, any> {
restLayout={this.state.activeInitialLayout}
containerLayout={this.state.layout}
onMove={this._onMove}
onDeactivate={() => { this.setState({activeKey: undefined}); }}
/>
onDeactivate={() => {
this.setState({activeKey: undefined});
}}
/>,
);
}
return (
<View style={styles.container}>
<View style={styles.grid} onLayout={(e) => this.setState({layout: e.nativeEvent.layout})}>
<View
style={styles.grid}
onLayout={e => this.setState({layout: e.nativeEvent.layout})}>
{circles}
</View>
</View>
@@ -234,7 +275,7 @@ class AnExApp extends React.Component<any, any> {
_onMove(position: Point): void {
var newKeys = moveToClosest(this.state, position);
if (newKeys !== this.state.keys) {
LayoutAnimation.easeInEaseOut(); // animates layout update as one batch (step3: uncomment)
LayoutAnimation.easeInEaseOut(); // animates layout update as one batch (step3: uncomment)
this.setState({keys: newKeys});
}
}

View File

@@ -4,27 +4,28 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Animated,
PanResponder,
StyleSheet,
View,
} = ReactNative;
var {Animated, PanResponder, StyleSheet, View} = ReactNative;
var NUM_BOBBLES = 5;
var RAD_EACH = Math.PI / 2 / (NUM_BOBBLES - 2);
var RADIUS = 160;
var BOBBLE_SPOTS = [...Array(NUM_BOBBLES)].map((_, i) => { // static positions
return i === 0 ? {x: 0, y: 0} : { // first bobble is the selector
x: -Math.cos(RAD_EACH * (i - 1)) * RADIUS,
y: -Math.sin(RAD_EACH * (i - 1)) * RADIUS,
};
var BOBBLE_SPOTS = [...Array(NUM_BOBBLES)].map((_, i) => {
// static positions
return i === 0
? {x: 0, y: 0}
: {
// first bobble is the selector
x: -Math.cos(RAD_EACH * (i - 1)) * RADIUS,
y: -Math.sin(RAD_EACH * (i - 1)) * RADIUS,
};
});
class AnExBobble extends React.Component<Object, any> {
@@ -35,18 +36,19 @@ class AnExBobble extends React.Component<Object, any> {
return new Animated.ValueXY();
});
this.state.selectedBobble = null;
var bobblePanListener = (e, gestureState) => { // async events => change selection
var bobblePanListener = (e, gestureState) => {
// async events => change selection
var newSelected = computeNewSelected(gestureState);
if (this.state.selectedBobble !== newSelected) {
if (this.state.selectedBobble !== null) {
var restSpot = BOBBLE_SPOTS[this.state.selectedBobble];
Animated.spring(this.state.bobbles[this.state.selectedBobble], {
toValue: restSpot, // return previously selected bobble to rest position
toValue: restSpot, // return previously selected bobble to rest position
}).start();
}
if (newSelected !== null && newSelected !== 0) {
Animated.spring(this.state.bobbles[newSelected], {
toValue: this.state.bobbles[0], // newly selected should track the selector
toValue: this.state.bobbles[0], // newly selected should track the selector
}).start();
}
this.state.selectedBobble = newSelected;
@@ -55,7 +57,7 @@ class AnExBobble extends React.Component<Object, any> {
var releaseBobble = () => {
this.state.bobbles.forEach((bobble, i) => {
Animated.spring(bobble, {
toValue: {x: 0, y: 0} // all bobbles return to zero
toValue: {x: 0, y: 0}, // all bobbles return to zero
}).start();
});
};
@@ -64,14 +66,14 @@ class AnExBobble extends React.Component<Object, any> {
onPanResponderGrant: () => {
BOBBLE_SPOTS.forEach((spot, idx) => {
Animated.spring(this.state.bobbles[idx], {
toValue: spot, // spring each bobble to its spot
friction: 3, // less friction => bouncier
toValue: spot, // spring each bobble to its spot
friction: 3, // less friction => bouncier
}).start();
});
},
onPanResponderMove: Animated.event(
[ null, {dx: this.state.bobbles[0].x, dy: this.state.bobbles[0].y} ],
{listener: bobblePanListener} // async state changes with arbitrary logic
[null, {dx: this.state.bobbles[0].x, dy: this.state.bobbles[0].y}],
{listener: bobblePanListener}, // async state changes with arbitrary logic
),
onPanResponderRelease: releaseBobble,
onPanResponderTerminate: releaseBobble,
@@ -89,10 +91,13 @@ class AnExBobble extends React.Component<Object, any> {
{...handlers}
key={i}
source={{uri: BOBBLE_IMGS[j]}}
style={[styles.circle, {
backgroundColor: randColor(), // re-renders are obvious
transform: this.state.bobbles[j].getTranslateTransform(), // simple conversion
}]}
style={[
styles.circle,
{
backgroundColor: randColor(), // re-renders are obvious
transform: this.state.bobbles[j].getTranslateTransform(), // simple conversion
},
]}
/>
);
})}
@@ -119,9 +124,7 @@ var styles = StyleSheet.create({
},
});
function computeNewSelected(
gestureState: Object,
): ?number {
function computeNewSelected(gestureState: Object): ?number {
var {dx, dy} = gestureState;
var minDist = Infinity;
var newSelected = null;
@@ -140,7 +143,7 @@ function computeNewSelected(
}
function randColor(): string {
var colors = [0,1,2].map(() => Math.floor(Math.random() * 150 + 100));
var colors = [0, 1, 2].map(() => Math.floor(Math.random() * 150 + 100));
return 'rgb(' + colors.join(',') + ')';
}

View File

@@ -4,56 +4,56 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Animated,
PanResponder,
StyleSheet,
View,
} = ReactNative;
var {Animated, PanResponder, StyleSheet, View} = ReactNative;
class AnExChained extends React.Component<Object, any> {
constructor(props: Object) {
super(props);
this.state = {
stickers: [new Animated.ValueXY()], // 1 leader
stickers: [new Animated.ValueXY()], // 1 leader
};
var stickerConfig = {tension: 2, friction: 3}; // soft spring
for (var i = 0; i < 4; i++) { // 4 followers
var stickerConfig = {tension: 2, friction: 3}; // soft spring
for (var i = 0; i < 4; i++) {
// 4 followers
var sticker = new Animated.ValueXY();
Animated.spring(sticker, {
...stickerConfig,
toValue: this.state.stickers[i], // Animated toValue's are tracked
toValue: this.state.stickers[i], // Animated toValue's are tracked
}).start();
this.state.stickers.push(sticker); // push on the followers
this.state.stickers.push(sticker); // push on the followers
}
var releaseChain = (e, gestureState) => {
this.state.stickers[0].flattenOffset(); // merges offset into value and resets
Animated.sequence([ // spring to start after decay finishes
Animated.decay(this.state.stickers[0], { // coast to a stop
this.state.stickers[0].flattenOffset(); // merges offset into value and resets
Animated.sequence([
// spring to start after decay finishes
Animated.decay(this.state.stickers[0], {
// coast to a stop
velocity: {x: gestureState.vx, y: gestureState.vy},
deceleration: 0.997,
}),
Animated.spring(this.state.stickers[0], {
toValue: {x: 0, y: 0} // return to start
toValue: {x: 0, y: 0}, // return to start
}),
]).start();
};
this.state.chainResponder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onPanResponderGrant: () => {
this.state.stickers[0].stopAnimation((value) => {
this.state.stickers[0].setOffset(value); // start where sticker animated to
this.state.stickers[0].setValue({x: 0, y: 0}); // avoid flicker before next event
this.state.stickers[0].stopAnimation(value => {
this.state.stickers[0].setOffset(value); // start where sticker animated to
this.state.stickers[0].setValue({x: 0, y: 0}); // avoid flicker before next event
});
},
onPanResponderMove: Animated.event(
[null, {dx: this.state.stickers[0].x, dy: this.state.stickers[0].y}] // map gesture to leader
[null, {dx: this.state.stickers[0].x, dy: this.state.stickers[0].y}], // map gesture to leader
),
onPanResponderRelease: releaseChain,
onPanResponderTerminate: releaseChain,
@@ -65,15 +65,18 @@ class AnExChained extends React.Component<Object, any> {
<View style={styles.chained}>
{this.state.stickers.map((_, i) => {
var j = this.state.stickers.length - i - 1; // reverse so leader is on top
var handlers = (j === 0) ? this.state.chainResponder.panHandlers : {};
var handlers = j === 0 ? this.state.chainResponder.panHandlers : {};
return (
<Animated.Image
{...handlers}
key={i}
source={CHAIN_IMGS[j]}
style={[styles.sticker, {
transform: this.state.stickers[j].getTranslateTransform(), // simple conversion
}]}
style={[
styles.sticker,
{
transform: this.state.stickers[j].getTranslateTransform(), // simple conversion
},
]}
/>
);
})}
@@ -86,7 +89,7 @@ var styles = StyleSheet.create({
chained: {
alignSelf: 'flex-end',
top: -160,
right: 126
right: 126,
},
sticker: {
position: 'absolute',
@@ -101,7 +104,7 @@ var CHAIN_IMGS = [
require('../bunny.png'),
require('../relay.png'),
require('../hawk.png'),
require('../bunny.png')
require('../bunny.png'),
];
module.exports = AnExChained;

View File

@@ -4,23 +4,18 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Animated,
Image,
ScrollView,
StyleSheet,
Text,
View,
} = ReactNative;
var {Animated, Image, ScrollView, StyleSheet, Text, View} = ReactNative;
class AnExScroll extends React.Component<$FlowFixMeProps, any> {
state: any = { scrollX: new Animated.Value(0) };
state: any = {scrollX: new Animated.Value(0)};
render() {
var width = this.props.panelWidth;
@@ -28,20 +23,17 @@ class AnExScroll extends React.Component<$FlowFixMeProps, any> {
<View style={styles.container}>
<ScrollView
automaticallyAdjustContentInsets={false}
scrollEventThrottle={16 /* get all events */ }
scrollEventThrottle={16 /* get all events */}
onScroll={Animated.event(
[{nativeEvent: {contentOffset: {x: this.state.scrollX}}}] // nested event mapping
[{nativeEvent: {contentOffset: {x: this.state.scrollX}}}], // nested event mapping
)}
contentContainerStyle={{flex: 1, padding: 10}}
pagingEnabled={true}
horizontal={true}>
<View style={[styles.page, {width}]}>
<Image
style={{width: 180, height: 180}}
source={HAWK_PIC}
/>
<Image style={{width: 180, height: 180}} source={HAWK_PIC} />
<Text style={styles.text}>
{'I\'ll find something to put here.'}
{"I'll find something to put here."}
</Text>
</View>
<View style={[styles.page, {width}]}>
@@ -53,29 +45,34 @@ class AnExScroll extends React.Component<$FlowFixMeProps, any> {
</ScrollView>
<Animated.Image
pointerEvents="none"
style={[styles.bunny, {transform: [
style={[
styles.bunny,
{
translateX: this.state.scrollX.interpolate({
inputRange: [0, width, 2 * width],
outputRange: [0, 0, width / 3],
extrapolate: 'clamp',
}),
transform: [
{
translateX: this.state.scrollX.interpolate({
inputRange: [0, width, 2 * width],
outputRange: [0, 0, width / 3],
extrapolate: 'clamp',
}),
},
{
translateY: this.state.scrollX.interpolate({
inputRange: [0, width, 2 * width],
outputRange: [0, -200, -260],
extrapolate: 'clamp',
}),
},
{
scale: this.state.scrollX.interpolate({
inputRange: [0, width, 2 * width],
outputRange: [0.5, 0.5, 2],
extrapolate: 'clamp',
}),
},
],
},
{
translateY: this.state.scrollX.interpolate({
inputRange: [0, width, 2 * width],
outputRange: [0, -200, -260],
extrapolate: 'clamp',
}),
},
{
scale: this.state.scrollX.interpolate({
inputRange: [0, width, 2 * width],
outputRange: [0.5, 0.5, 2],
extrapolate: 'clamp',
}),
},
]}]}
]}
source={BUNNY_PIC}
/>
</View>
@@ -107,7 +104,13 @@ var styles = StyleSheet.create({
},
});
var HAWK_PIC = {uri: 'https://scontent-sea1-1.xx.fbcdn.net/hphotos-xfa1/t39.1997-6/10734304_1562225620659674_837511701_n.png'};
var BUNNY_PIC = {uri: 'https://scontent-sea1-1.xx.fbcdn.net/hphotos-xaf1/t39.1997-6/851564_531111380292237_1898871086_n.png'};
var HAWK_PIC = {
uri:
'https://scontent-sea1-1.xx.fbcdn.net/hphotos-xfa1/t39.1997-6/10734304_1562225620659674_837511701_n.png',
};
var BUNNY_PIC = {
uri:
'https://scontent-sea1-1.xx.fbcdn.net/hphotos-xaf1/t39.1997-6/851564_531111380292237_1898871086_n.png',
};
module.exports = AnExScroll;

View File

@@ -4,19 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Animated,
PanResponder,
StyleSheet,
Text,
View,
} = ReactNative;
var {Animated, PanResponder, StyleSheet, Text, View} = ReactNative;
var AnExBobble = require('./AnExBobble');
var AnExChained = require('./AnExChained');
@@ -27,7 +23,7 @@ class AnExSet extends React.Component<Object, any> {
constructor(props: Object) {
super(props);
function randColor() {
var colors = [0,1,2].map(() => Math.floor(Math.random() * 150 + 100));
var colors = [0, 1, 2].map(() => Math.floor(Math.random() * 150 + 100));
return 'rgb(' + colors.join(',') + ')';
}
this.state = {
@@ -36,38 +32,35 @@ class AnExSet extends React.Component<Object, any> {
};
}
render(): React.Node {
var backgroundColor = this.props.openVal ?
this.props.openVal.interpolate({
inputRange: [0, 1],
outputRange: [
this.state.closeColor, // interpolates color strings
this.state.openColor
],
}) :
this.state.closeColor;
var panelWidth = this.props.containerLayout && this.props.containerLayout.width || 320;
var backgroundColor = this.props.openVal
? this.props.openVal.interpolate({
inputRange: [0, 1],
outputRange: [
this.state.closeColor, // interpolates color strings
this.state.openColor,
],
})
: this.state.closeColor;
var panelWidth =
(this.props.containerLayout && this.props.containerLayout.width) || 320;
return (
<View style={styles.container}>
<Animated.View
style={[styles.header, { backgroundColor }]}
style={[styles.header, {backgroundColor}]}
{...this.state.dismissResponder.panHandlers}>
<Text style={[styles.text, styles.headerText]}>
{this.props.id}
</Text>
<Text style={[styles.text, styles.headerText]}>{this.props.id}</Text>
</Animated.View>
{this.props.isActive &&
{this.props.isActive && (
<View style={styles.stream}>
<View style={styles.card}>
<Text style={styles.text}>
July 2nd
</Text>
<Text style={styles.text}>July 2nd</Text>
<AnExTilt isActive={this.props.isActive} />
<AnExBobble />
</View>
<AnExScroll panelWidth={panelWidth}/>
<AnExScroll panelWidth={panelWidth} />
<AnExChained />
</View>
}
)}
</View>
);
}
@@ -77,24 +70,26 @@ class AnExSet extends React.Component<Object, any> {
this.state.dismissResponder = PanResponder.create({
onStartShouldSetPanResponder: () => this.props.isActive,
onPanResponderGrant: () => {
Animated.spring(this.props.openVal, { // Animated value passed in.
toValue: this.state.dismissY.interpolate({ // Track dismiss gesture
inputRange: [0, 300], // and interpolate pixel distance
outputRange: [1, 0], // to a fraction.
Animated.spring(this.props.openVal, {
// Animated value passed in.
toValue: this.state.dismissY.interpolate({
// Track dismiss gesture
inputRange: [0, 300], // and interpolate pixel distance
outputRange: [1, 0], // to a fraction.
}),
useNativeDriver: true,
}).start();
},
onPanResponderMove: Animated.event(
[null, {dy: this.state.dismissY}], // track pan gesture
{useNativeDriver: true}
[null, {dy: this.state.dismissY}], // track pan gesture
{useNativeDriver: true},
),
onPanResponderRelease: (e, gestureState) => {
if (gestureState.dy > 100) {
this.props.onDismiss(gestureState.vy); // delegates dismiss action to parent
this.props.onDismiss(gestureState.vy); // delegates dismiss action to parent
} else {
Animated.spring(this.props.openVal, {
toValue: 1, // animate back open if released early
toValue: 1, // animate back open if released early
useNativeDriver: true,
}).start();
}

View File

@@ -4,17 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Animated,
PanResponder,
StyleSheet,
} = ReactNative;
var {Animated, PanResponder, StyleSheet} = ReactNative;
class AnExTilt extends React.Component<Object, any> {
constructor(props: Object) {
@@ -29,14 +27,14 @@ class AnExTilt extends React.Component<Object, any> {
onPanResponderGrant: () => {
Animated.timing(this.state.opacity, {
toValue: this.state.panX.interpolate({
inputRange: [-300, 0, 300], // pan is in pixels
outputRange: [0, 1, 0], // goes to zero at both edges
inputRange: [-300, 0, 300], // pan is in pixels
outputRange: [0, 1, 0], // goes to zero at both edges
}),
duration: 0, // direct tracking
duration: 0, // direct tracking
}).start();
},
onPanResponderMove: Animated.event(
[null, {dx: this.state.panX}] // panX is linked to the gesture
[null, {dx: this.state.panX}], // panX is linked to the gesture
),
onPanResponderRelease: (e, gestureState) => {
var toValue = 0;
@@ -46,19 +44,20 @@ class AnExTilt extends React.Component<Object, any> {
toValue = -500;
}
Animated.spring(this.state.panX, {
toValue, // animate back to center or off screen
velocity: gestureState.vx, // maintain gesture velocity
toValue, // animate back to center or off screen
velocity: gestureState.vx, // maintain gesture velocity
tension: 10,
friction: 3,
}).start();
this.state.panX.removeAllListeners();
var id = this.state.panX.addListener(({value}) => { // listen until offscreen
var id = this.state.panX.addListener(({value}) => {
// listen until offscreen
if (Math.abs(value) > 400) {
this.state.panX.removeListener(id); // offscreen, so stop listening
this.state.panX.removeListener(id); // offscreen, so stop listening
Animated.timing(this.state.opacity, {
toValue: 1, // Fade back in. This unlinks it from tracking this.state.panX
toValue: 1, // Fade back in. This unlinks it from tracking this.state.panX
}).start();
this.state.panX.setValue(0); // Note: stops the spring animation
this.state.panX.setValue(0); // Note: stops the spring animation
toValue !== 0 && this._startBurnsZoom();
}
});
@@ -67,10 +66,10 @@ class AnExTilt extends React.Component<Object, any> {
}
_startBurnsZoom() {
this.state.burns.setValue(1); // reset to beginning
this.state.burns.setValue(1); // reset to beginning
Animated.decay(this.state.burns, {
velocity: 1, // sublte zoom
deceleration: 0.9999, // slow decay
velocity: 1, // sublte zoom
deceleration: 0.9999, // slow decay
}).start();
}
@@ -82,27 +81,37 @@ class AnExTilt extends React.Component<Object, any> {
return (
<Animated.View
{...this.state.tiltPanResponder.panHandlers}
style={[styles.tilt, {
opacity: this.state.opacity,
transform: [
{rotate: this.state.panX.interpolate({
inputRange: [-320, 320],
outputRange: ['-15deg', '15deg']})}, // interpolate string "shapes"
{translateX: this.state.panX},
],
}]}>
style={[
styles.tilt,
{
opacity: this.state.opacity,
transform: [
{
rotate: this.state.panX.interpolate({
inputRange: [-320, 320],
outputRange: ['-15deg', '15deg'],
}),
}, // interpolate string "shapes"
{translateX: this.state.panX},
],
},
]}>
<Animated.Image
pointerEvents="none"
style={{
flex: 1,
transform: [
{translateX: this.state.panX.interpolate({
inputRange: [-3, 3], // small range is extended by default
outputRange: [2, -2]}) // parallax
{
translateX: this.state.panX.interpolate({
inputRange: [-3, 3], // small range is extended by default
outputRange: [2, -2],
}), // parallax
},
{scale: this.state.burns.interpolate({
inputRange: [1, 3000],
outputRange: [1, 1.25]}) // simple multiplier
{
scale: this.state.burns.interpolate({
inputRange: [1, 3000],
outputRange: [1, 1.25],
}), // simple multiplier
},
],
}}

View File

@@ -4,19 +4,20 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
const ReactNative = require('react-native');
const {
AppState,
Text,
View
} = ReactNative;
const {AppState, Text, View} = ReactNative;
class AppStateSubscription extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
class AppStateSubscription extends React.Component<
$FlowFixMeProps,
$FlowFixMeState,
> {
state = {
appState: AppState.currentState,
previousAppStates: [],
@@ -37,7 +38,7 @@ class AppStateSubscription extends React.Component<$FlowFixMeProps, $FlowFixMeSt
this.setState({memoryWarnings: this.state.memoryWarnings + 1});
};
_handleAppStateChange = (appState) => {
_handleAppStateChange = appState => {
var previousAppStates = this.state.previousAppStates.slice();
previousAppStates.push(this.state.appState);
this.setState({
@@ -75,21 +76,31 @@ exports.examples = [
{
title: 'AppState.currentState',
description: 'Can be null on app initialization',
render() { return <Text>{AppState.currentState}</Text>; }
render() {
return <Text>{AppState.currentState}</Text>;
},
},
{
title: 'Subscribed AppState:',
description: 'This changes according to the current state, so you can only ever see it rendered as "active"',
render(): React.Element<any> { return <AppStateSubscription showCurrentOnly={true} />; }
description:
'This changes according to the current state, so you can only ever see it rendered as "active"',
render(): React.Element<any> {
return <AppStateSubscription showCurrentOnly={true} />;
},
},
{
title: 'Previous states:',
render(): React.Element<any> { return <AppStateSubscription showCurrentOnly={false} />; }
render(): React.Element<any> {
return <AppStateSubscription showCurrentOnly={false} />;
},
},
{
platform: 'ios',
title: 'Memory Warnings',
description: 'In the IOS simulator, hit Shift+Command+M to simulate a memory warning.',
render(): React.Element<any> { return <AppStateSubscription showMemoryWarnings={true} />; }
description:
'In the IOS simulator, hit Shift+Command+M to simulate a memory warning.',
render(): React.Element<any> {
return <AppStateSubscription showMemoryWarnings={true} />;
},
},
];

View File

@@ -4,22 +4,22 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Image,
StyleSheet,
View,
ScrollView
} = ReactNative;
var {Image, StyleSheet, View, ScrollView} = ReactNative;
class AssetScaledImageExample extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
class AssetScaledImageExample extends React.Component<
$FlowFixMeProps,
$FlowFixMeState,
> {
state = {
asset: this.props.asset
asset: this.props.asset,
};
render() {
@@ -27,16 +27,16 @@ class AssetScaledImageExample extends React.Component<$FlowFixMeProps, $FlowFixM
return (
<ScrollView>
<View style={styles.row}>
<Image source={image} style={styles.imageWide}/>
<Image source={image} style={styles.imageWide} />
</View>
<View style={styles.row}>
<Image source={image} style={styles.imageThumb}/>
<Image source={image} style={styles.imageThumb}/>
<Image source={image} style={styles.imageThumb}/>
<Image source={image} style={styles.imageThumb} />
<Image source={image} style={styles.imageThumb} />
<Image source={image} style={styles.imageThumb} />
</View>
<View style={styles.row}>
<Image source={image} style={styles.imageT1}/>
<Image source={image} style={styles.imageT2}/>
<Image source={image} style={styles.imageT1} />
<Image source={image} style={styles.imageT2} />
</View>
</ScrollView>
);
@@ -85,5 +85,6 @@ var styles = StyleSheet.create({
});
exports.title = '<AssetScaledImageExample>';
exports.description = 'Example component that displays the automatic scaling capabilities of the <Image /> tag';
exports.description =
'Example component that displays the automatic scaling capabilities of the <Image /> tag';
module.exports = AssetScaledImageExample;

View File

@@ -4,18 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
AsyncStorage,
PickerIOS,
Text,
View
} = ReactNative;
var {AsyncStorage, PickerIOS, Text, View} = ReactNative;
var PickerItemIOS = PickerIOS.Item;
var STORAGE_KEY = '@AsyncStorageExample:key';
@@ -34,7 +31,7 @@ class BasicStorageExample extends React.Component<{}, $FlowFixMeState> {
_loadInitialState = async () => {
try {
var value = await AsyncStorage.getItem(STORAGE_KEY);
if (value !== null){
if (value !== null) {
this.setState({selectedValue: value});
this._appendMessage('Recovered selection from disk: ' + value);
} else {
@@ -49,35 +46,27 @@ class BasicStorageExample extends React.Component<{}, $FlowFixMeState> {
var color = this.state.selectedValue;
return (
<View>
<PickerIOS
selectedValue={color}
onValueChange={this._onValueChange}>
{COLORS.map((value) => (
<PickerItemIOS
key={value}
value={value}
label={value}
/>
<PickerIOS selectedValue={color} onValueChange={this._onValueChange}>
{COLORS.map(value => (
<PickerItemIOS key={value} value={value} label={value} />
))}
</PickerIOS>
<Text>
{'Selected: '}
<Text style={{color}}>
{this.state.selectedValue}
</Text>
<Text style={{color}}>{this.state.selectedValue}</Text>
</Text>
<Text>{' '}</Text>
<Text> </Text>
<Text onPress={this._removeStorage}>
Press here to remove from storage.
</Text>
<Text>{' '}</Text>
<Text> </Text>
<Text>Messages:</Text>
{this.state.messages.map((m) => <Text key={m}>{m}</Text>)}
{this.state.messages.map(m => <Text key={m}>{m}</Text>)}
</View>
);
}
_onValueChange = async (selectedValue) => {
_onValueChange = async selectedValue => {
this.setState({selectedValue});
try {
await AsyncStorage.setItem(STORAGE_KEY, selectedValue);
@@ -96,7 +85,7 @@ class BasicStorageExample extends React.Component<{}, $FlowFixMeState> {
}
};
_appendMessage = (message) => {
_appendMessage = message => {
this.setState({messages: this.state.messages.concat(message)});
};
}
@@ -106,6 +95,8 @@ exports.description = 'Asynchronous local disk storage.';
exports.examples = [
{
title: 'Basics - getItem, setItem, removeItem',
render(): React.Element<any> { return <BasicStorageExample />; }
render(): React.Element<any> {
return <BasicStorageExample />;
},
},
];

View File

@@ -4,15 +4,14 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
StyleSheet,
View
} = ReactNative;
var {StyleSheet, View} = ReactNative;
var styles = StyleSheet.create({
box: {
@@ -84,7 +83,7 @@ var styles = StyleSheet.create({
border7_inner: {
backgroundColor: 'blue',
width: 100,
height: 100
height: 100,
},
border8: {
width: 60,
@@ -158,46 +157,47 @@ var styles = StyleSheet.create({
borderTopRightRadius: 40,
borderBottomRightRadius: 30,
borderBottomLeftRadius: 40,
}
},
});
exports.title = 'Border';
exports.description = 'Demonstrates some of the border styles available to Views.';
exports.description =
'Demonstrates some of the border styles available to Views.';
exports.examples = [
{
title: 'Equal-Width / Same-Color',
description: 'borderWidth & borderColor',
render() {
return <View style={[styles.box, styles.border1]} />;
}
},
},
{
title: 'Equal-Width / Same-Color',
description: 'borderWidth & borderColor & borderRadius',
render() {
return <View style={[styles.box, styles.borderRadius]} />;
}
},
},
{
title: 'Equal-Width Borders',
description: 'borderWidth & border*Color',
render() {
return <View style={[styles.box, styles.border2]} />;
}
},
},
{
title: 'Same-Color Borders',
description: 'border*Width & borderColor',
render() {
return <View style={[styles.box, styles.border3]} />;
}
},
},
{
title: 'Custom Borders',
description: 'border*Width & border*Color',
render() {
return <View style={[styles.box, styles.border4]} />;
}
},
},
{
title: 'Custom Borders',
@@ -205,7 +205,7 @@ exports.examples = [
platform: 'ios',
render() {
return <View style={[styles.box, styles.border5]} />;
}
},
},
{
title: 'Custom Borders',
@@ -213,7 +213,7 @@ exports.examples = [
platform: 'ios',
render() {
return <View style={[styles.box, styles.border6]} />;
}
},
},
{
title: 'Custom Borders',
@@ -225,7 +225,7 @@ exports.examples = [
<View style={styles.border7_inner} />
</View>
);
}
},
},
{
title: 'Single Borders',
@@ -239,14 +239,14 @@ exports.examples = [
<View style={[styles.box, styles.border8, {borderRightWidth: 5}]} />
</View>
);
}
},
},
{
title: 'Corner Radii',
description: 'borderTopLeftRadius & borderBottomRightRadius',
render() {
return <View style={[styles.box, styles.border9]} />;
}
},
},
{
title: 'Corner Radii / Elevation',
@@ -254,34 +254,34 @@ exports.examples = [
platform: 'android',
render() {
return <View style={[styles.box, styles.border10]} />;
}
},
},
{
title: 'CSS Trick - Triangle',
description: 'create a triangle by manipulating border colors and widths',
render() {
return <View style={[styles.border11]} />;
}
},
},
{
title: 'Curved border(Left|Right|Bottom|Top)Width',
description: 'Make a non-uniform width curved border',
render() {
return <View style={[styles.box, styles.border12]} />;
}
},
},
{
title: 'Curved border(Left|Right|Bottom|Top)Color',
description: 'Make a non-uniform color curved border',
render() {
return <View style={[styles.box, styles.border13]} />;
}
},
},
{
title: 'Curved border(Top|Bottom)(Left|Right)Radius',
description: 'Make a non-uniform radius curved border',
render() {
return <View style={[styles.box, styles.border14]} />;
}
}
},
},
];

View File

@@ -4,16 +4,14 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Image,
StyleSheet,
View
} = ReactNative;
var {Image, StyleSheet, View} = ReactNative;
var styles = StyleSheet.create({
box: {
@@ -35,46 +33,72 @@ var styles = StyleSheet.create({
});
exports.title = 'Box Shadow';
exports.description = 'Demonstrates some of the shadow styles available to Views.';
exports.description =
'Demonstrates some of the shadow styles available to Views.';
exports.examples = [
{
title: 'Basic shadow',
description: 'shadowOpacity: 0.5, shadowOffset: {2, 2}',
render() {
return <View style={[styles.box, styles.shadow1]} />;
}
},
},
{
title: 'Colored shadow',
description: 'shadowColor: \'red\', shadowRadius: 0',
description: "shadowColor: 'red', shadowRadius: 0",
render() {
return <View style={[styles.box, styles.shadow2]} />;
}
},
},
{
title: 'Shaped shadow',
description: 'borderRadius: 50',
render() {
return <View style={[styles.box, styles.shadow1, {borderRadius: 50}]} />;
}
},
},
{
title: 'Image shadow',
description: 'Image shadows are derived exactly from the pixels.',
render() {
return <Image
source={require('./hawk.png')}
style={[styles.box, styles.shadow1, {borderWidth: 0, overflow: 'visible'}]}
/>;
}
return (
<Image
source={require('./hawk.png')}
style={[
styles.box,
styles.shadow1,
{borderWidth: 0, overflow: 'visible'},
]}
/>
);
},
},
{
title: 'Child shadow',
description: 'For views without an opaque background color, shadow will be derived from the subviews.',
description:
'For views without an opaque background color, shadow will be derived from the subviews.',
render() {
return <View style={[styles.box, styles.shadow1, {backgroundColor: 'transparent'}]}>
<View style={[styles.box, {width: 80, height: 80, borderRadius: 40, margin: 8, backgroundColor: 'red'}]}/>
</View>;
}
return (
<View
style={[
styles.box,
styles.shadow1,
{backgroundColor: 'transparent'},
]}>
<View
style={[
styles.box,
{
width: 80,
height: 80,
borderRadius: 40,
margin: 8,
backgroundColor: 'red',
},
]}
/>
</View>
);
},
},
];

View File

@@ -4,17 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
const ReactNative = require('react-native');
const {
Alert,
Button,
View,
} = ReactNative;
const {Alert, Button, View} = ReactNative;
const onButtonPress = () => {
Alert.alert('Button has been pressed!');
@@ -28,7 +26,8 @@ exports.description = 'Simple React Native button component.';
exports.examples = [
{
title: 'Simple Button',
description: 'The title and onPress handler are required. It is ' +
description:
'The title and onPress handler are required. It is ' +
'recommended to set accessibilityLabel to help make your app usable by ' +
'everyone.',
render: function() {
@@ -43,7 +42,8 @@ exports.examples = [
},
{
title: 'Adjusted color',
description: 'Adjusts the color in a way that looks standard on each ' +
description:
'Adjusts the color in a way that looks standard on each ' +
'platform. On iOS, the color prop controls the color of the text. On ' +
'Android, the color adjusts the background color of the button.',
render: function() {
@@ -59,8 +59,8 @@ exports.examples = [
},
{
title: 'Fit to text layout',
description: 'This layout strategy lets the title define the width of ' +
'the button',
description:
'This layout strategy lets the title define the width of ' + 'the button',
render: function() {
return (
<View style={{flexDirection: 'row', justifyContent: 'space-between'}}>

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
@@ -58,15 +60,10 @@ var propTypes = {
*/
imagesPerRow: PropTypes.number,
/**
/**
* The asset type, one of 'Photos', 'Videos' or 'All'
*/
assetType: PropTypes.oneOf([
'Photos',
'Videos',
'All',
]),
assetType: PropTypes.oneOf(['Photos', 'Videos', 'All']),
};
var CameraRollView = createReactClass({
@@ -82,12 +79,7 @@ var CameraRollView = createReactClass({
renderImage: function(asset) {
var imageSize = 150;
var imageStyle = [styles.image, {width: imageSize, height: imageSize}];
return (
<Image
source={asset.node.image}
style={imageStyle}
/>
);
return <Image source={asset.node.image} style={imageStyle} />;
},
};
},
@@ -98,7 +90,7 @@ var CameraRollView = createReactClass({
return {
assets: ([]: Array<Image>),
groupTypes: this.props.groupTypes,
lastCursor: (null : ?string),
lastCursor: (null: ?string),
assetType: this.props.assetType,
noMore: false,
loadingMore: false,
@@ -114,7 +106,7 @@ var CameraRollView = createReactClass({
var ds = new ListView.DataSource({rowHasChanged: this._rowHasChanged});
this.state.dataSource = ds.cloneWithRows(
// $FlowFixMe(>=0.41.0)
groupByEveryN(this.state.assets, this.props.imagesPerRow)
groupByEveryN(this.state.assets, this.props.imagesPerRow),
);
},
@@ -178,7 +170,9 @@ var CameraRollView = createReactClass({
*/
fetch: function(clear?: boolean) {
if (!this.state.loadingMore) {
this.setState({loadingMore: true}, () => { this._fetch(clear); });
this.setState({loadingMore: true}, () => {
this._fetch(clear);
});
}
},
@@ -217,8 +211,12 @@ var CameraRollView = createReactClass({
},
// rowData is an array of images
_renderRow: function(rowData: Array<Image>, sectionID: string, rowID: string) {
var images = rowData.map((image) => {
_renderRow: function(
rowData: Array<Image>,
sectionID: string,
rowID: string,
) {
var images = rowData.map(image => {
if (image === null) {
return null;
}
@@ -226,16 +224,12 @@ var CameraRollView = createReactClass({
return this.props.renderImage(image);
});
return (
<View style={styles.row}>
{images}
</View>
);
return <View style={styles.row}>{images}</View>;
},
_appendAssets: function(data: Object) {
var assets = data.edges;
var newState: Object = { loadingMore: false };
var newState: Object = {loadingMore: false};
if (!data.page_info.has_next_page) {
newState.noMore = true;
@@ -246,7 +240,7 @@ var CameraRollView = createReactClass({
newState.assets = this.state.assets.concat(assets);
newState.dataSource = this.state.dataSource.cloneWithRows(
// $FlowFixMe(>=0.41.0)
groupByEveryN(newState.assets, this.props.imagesPerRow)
groupByEveryN(newState.assets, this.props.imagesPerRow),
);
}

View File

@@ -4,21 +4,19 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Clipboard,
View,
Text,
} = ReactNative;
var {Clipboard, View, Text} = ReactNative;
class ClipboardExample extends React.Component<{}, $FlowFixMeState> {
state = {
content: 'Content will appear here'
content: 'Content will appear here',
};
_setClipboardContent = async () => {
@@ -27,7 +25,7 @@ class ClipboardExample extends React.Component<{}, $FlowFixMeState> {
var content = await Clipboard.getString();
this.setState({content});
} catch (e) {
this.setState({content:e.message});
this.setState({content: e.message});
}
};
@@ -37,9 +35,7 @@ class ClipboardExample extends React.Component<{}, $FlowFixMeState> {
<Text onPress={this._setClipboardContent} style={{color: 'blue'}}>
Tap to put "Hello World" in the clipboard
</Text>
<Text style={{color: 'red', marginTop: 20}}>
{this.state.content}
</Text>
<Text style={{color: 'red', marginTop: 20}}>{this.state.content}</Text>
</View>
);
}
@@ -51,7 +47,7 @@ exports.examples = [
{
title: 'Clipboard.setString() and getString()',
render() {
return <ClipboardExample/>;
}
}
return <ClipboardExample />;
},
},
];

View File

@@ -4,7 +4,9 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
var React = require('react');
@@ -62,31 +64,44 @@ class DatePickerAndroidExample extends React.Component {
<RNTesterPage title="DatePickerAndroid">
<RNTesterBlock title="Simple date picker">
<TouchableWithoutFeedback
onPress={this.showPicker.bind(this, 'simple', {date: this.state.simpleDate})}>
onPress={this.showPicker.bind(this, 'simple', {
date: this.state.simpleDate,
})}>
<Text style={styles.text}>{this.state.simpleText}</Text>
</TouchableWithoutFeedback>
</RNTesterBlock>
<RNTesterBlock title="Simple spinner date picker">
<TouchableWithoutFeedback
onPress={this.showPicker.bind(this, 'spinner', {date: this.state.spinnerDate, mode: 'spinner'})}>
onPress={this.showPicker.bind(this, 'spinner', {
date: this.state.spinnerDate,
mode: 'spinner',
})}>
<Text style={styles.text}>{this.state.spinnerText}</Text>
</TouchableWithoutFeedback>
</RNTesterBlock>
<RNTesterBlock title="Simple calendar date picker">
<TouchableWithoutFeedback
onPress={this.showPicker.bind(this, 'calendar', {date: this.state.calendarDate, mode: 'calendar'})}>
onPress={this.showPicker.bind(this, 'calendar', {
date: this.state.calendarDate,
mode: 'calendar',
})}>
<Text style={styles.text}>{this.state.calendarText}</Text>
</TouchableWithoutFeedback>
</RNTesterBlock>
<RNTesterBlock title="Simple default date picker">
<TouchableWithoutFeedback
onPress={this.showPicker.bind(this, 'default', {date: this.state.defaultDate, mode: 'default'})}>
onPress={this.showPicker.bind(this, 'default', {
date: this.state.defaultDate,
mode: 'default',
})}>
<Text style={styles.text}>{this.state.defaultText}</Text>
</TouchableWithoutFeedback>
</RNTesterBlock>
<RNTesterBlock title="Date picker with pre-set date">
<TouchableWithoutFeedback
onPress={this.showPicker.bind(this, 'preset', {date: this.state.presetDate})}>
onPress={this.showPicker.bind(this, 'preset', {
date: this.state.presetDate,
})}>
<Text style={styles.text}>{this.state.presetText}</Text>
</TouchableWithoutFeedback>
</RNTesterBlock>
@@ -117,7 +132,7 @@ class DatePickerAndroidExample extends React.Component {
})}>
<Text style={styles.text}>{this.state.allText}</Text>
</TouchableWithoutFeedback>
</RNTesterBlock>
</RNTesterBlock>
</RNTesterPage>
);
}

View File

@@ -4,24 +4,23 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
DatePickerIOS,
StyleSheet,
Text,
TextInput,
View,
} = ReactNative;
var {DatePickerIOS, StyleSheet, Text, TextInput, View} = ReactNative;
class DatePickerExample extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
class DatePickerExample extends React.Component<
$FlowFixMeProps,
$FlowFixMeState,
> {
static defaultProps = {
date: new Date(),
timeZoneOffsetInHours: (-1) * (new Date()).getTimezoneOffset() / 60,
timeZoneOffsetInHours: -1 * new Date().getTimezoneOffset() / 60,
};
state = {
@@ -29,11 +28,11 @@ class DatePickerExample extends React.Component<$FlowFixMeProps, $FlowFixMeState
timeZoneOffsetInHours: this.props.timeZoneOffsetInHours,
};
onDateChange = (date) => {
onDateChange = date => {
this.setState({date: date});
};
onTimezoneChange = (event) => {
onTimezoneChange = event => {
var offset = parseInt(event.nativeEvent.text, 10);
if (isNaN(offset)) {
return;
@@ -47,11 +46,11 @@ class DatePickerExample extends React.Component<$FlowFixMeProps, $FlowFixMeState
return (
<View>
<WithLabel label="Value:">
<Text>{
this.state.date.toLocaleDateString() +
' ' +
this.state.date.toLocaleTimeString()
}</Text>
<Text>
{this.state.date.toLocaleDateString() +
' ' +
this.state.date.toLocaleTimeString()}
</Text>
</WithLabel>
<WithLabel label="Timezone:">
<TextInput
@@ -93,9 +92,7 @@ class WithLabel extends React.Component<$FlowFixMeProps> {
return (
<View style={styles.labelContainer}>
<View style={styles.labelView}>
<Text style={styles.label}>
{this.props.label}
</Text>
<Text style={styles.label}>{this.props.label}</Text>
</View>
{this.props.children}
</View>
@@ -107,9 +104,7 @@ class Heading extends React.Component<$FlowFixMeProps> {
render() {
return (
<View style={styles.headingContainer}>
<Text style={styles.heading}>
{this.props.label}
</Text>
<Text style={styles.heading}>{this.props.label}</Text>
</View>
);
}
@@ -119,12 +114,13 @@ exports.displayName = (undefined: ?string);
exports.title = '<DatePickerIOS>';
exports.description = 'Select dates and times using the native UIDatePicker.';
exports.examples = [
{
title: '<DatePickerIOS>',
render: function(): React.Element<any> {
return <DatePickerExample />;
{
title: '<DatePickerIOS>',
render: function(): React.Element<any> {
return <DatePickerExample />;
},
},
}];
];
var styles = StyleSheet.create({
textinput: {

View File

@@ -4,19 +4,20 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
const ReactNative = require('react-native');
const {
Dimensions,
Text,
View
} = ReactNative;
const {Dimensions, Text, View} = ReactNative;
class DimensionsSubscription extends React.Component<{dim: string}, {dims: Object}> {
class DimensionsSubscription extends React.Component<
{dim: string},
{dims: Object},
> {
state = {
dims: Dimensions.get(this.props.dim),
};
@@ -29,7 +30,7 @@ class DimensionsSubscription extends React.Component<{dim: string}, {dims: Objec
Dimensions.removeEventListener('change', this._handleDimensionsChange);
}
_handleDimensionsChange = (dimensions) => {
_handleDimensionsChange = dimensions => {
this.setState({
dims: dimensions[this.props.dim],
});
@@ -49,10 +50,14 @@ exports.description = 'Dimensions of the viewport';
exports.examples = [
{
title: 'window',
render(): React.Element<any> { return <DimensionsSubscription dim="window" />; }
render(): React.Element<any> {
return <DimensionsSubscription dim="window" />;
},
},
{
title: 'screen',
render(): React.Element<any> { return <DimensionsSubscription dim="screen" />; }
render(): React.Element<any> {
return <DimensionsSubscription dim="screen" />;
},
},
];

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
/* $FlowFixMe(>=0.53.0 site=react_native_fb,react_native_oss) This comment

View File

@@ -4,19 +4,16 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const Alert = require('Alert');
const React = require('react');
const ReactNative = require('react-native');
const {
Animated,
FlatList,
StyleSheet,
View,
} = ReactNative;
const {Animated, FlatList, StyleSheet, View} = ReactNative;
const RNTesterPage = require('./RNTesterPage');
@@ -61,21 +58,23 @@ class FlatListExample extends React.PureComponent<{}, $FlowFixMeState> {
empty: false,
};
_onChangeFilterText = (filterText) => {
_onChangeFilterText = filterText => {
this.setState({filterText});
};
_onChangeScrollToIndex = (text) => {
this._listRef.getNode().scrollToIndex({viewPosition: 0.5, index: Number(text)});
_onChangeScrollToIndex = text => {
this._listRef
.getNode()
.scrollToIndex({viewPosition: 0.5, index: Number(text)});
};
_scrollPos = new Animated.Value(0);
_scrollSinkX = Animated.event(
[{nativeEvent: { contentOffset: { x: this._scrollPos } }}],
[{nativeEvent: {contentOffset: {x: this._scrollPos}}}],
{useNativeDriver: true},
);
_scrollSinkY = Animated.event(
[{nativeEvent: { contentOffset: { y: this._scrollPos } }}],
[{nativeEvent: {contentOffset: {y: this._scrollPos}}}],
{useNativeDriver: true},
);
@@ -85,14 +84,11 @@ class FlatListExample extends React.PureComponent<{}, $FlowFixMeState> {
render() {
const filterRegex = new RegExp(String(this.state.filterText), 'i');
const filter = (item) => (
filterRegex.test(item.text) || filterRegex.test(item.title)
);
const filter = item =>
filterRegex.test(item.text) || filterRegex.test(item.title);
const filteredData = this.state.data.filter(filter);
return (
<RNTesterPage
noSpacer={true}
noScroll={true}>
<RNTesterPage noSpacer={true} noScroll={true}>
<View style={styles.container}>
<View style={styles.searchRow}>
<View style={styles.options}>
@@ -126,13 +122,13 @@ class FlatListExample extends React.PureComponent<{}, $FlowFixMeState> {
data={this.state.empty ? [] : filteredData}
debug={this.state.debug}
disableVirtualization={!this.state.virtualized}
getItemLayout={this.state.fixedHeight ?
this._getItemLayout :
undefined
getItemLayout={
this.state.fixedHeight ? this._getItemLayout : undefined
}
horizontal={this.state.horizontal}
inverted={this.state.inverted}
key={(this.state.horizontal ? 'h' : 'v') +
key={
(this.state.horizontal ? 'h' : 'v') +
(this.state.fixedHeight ? 'f' : 'd')
}
keyboardShouldPersistTaps="always"
@@ -141,7 +137,9 @@ class FlatListExample extends React.PureComponent<{}, $FlowFixMeState> {
numColumns={1}
onEndReached={this._onEndReached}
onRefresh={this._onRefresh}
onScroll={this.state.horizontal ? this._scrollSinkX : this._scrollSinkY}
onScroll={
this.state.horizontal ? this._scrollSinkX : this._scrollSinkY
}
onViewableItemsChanged={this._onViewableItemsChanged}
ref={this._captureRef}
refreshing={false}
@@ -153,7 +151,9 @@ class FlatListExample extends React.PureComponent<{}, $FlowFixMeState> {
</RNTesterPage>
);
}
_captureRef = (ref) => { this._listRef = ref; };
_captureRef = ref => {
this._listRef = ref;
};
_getItemLayout = (data: any, index: number) => {
return getItemLayout(data, index, this.state.horizontal);
};
@@ -161,7 +161,7 @@ class FlatListExample extends React.PureComponent<{}, $FlowFixMeState> {
if (this.state.data.length >= 1000) {
return;
}
this.setState((state) => ({
this.setState(state => ({
data: state.data.concat(genItemData(100, state.data.length)),
}));
};
@@ -181,20 +181,19 @@ class FlatListExample extends React.PureComponent<{}, $FlowFixMeState> {
// This is called when items change viewability by scrolling into or out of
// the viewable area.
_onViewableItemsChanged = (info: {
changed: Array<{
key: string,
isViewable: boolean,
item: any,
index: ?number,
section?: any,
}>
}
) => {
changed: Array<{
key: string,
isViewable: boolean,
item: any,
index: ?number,
section?: any,
}>,
}) => {
// Impressions can be logged here
if (this.state.logViewable) {
infoLog(
'onViewableItemsChanged: ',
info.changed.map((v) => ({...v, item: '...'})),
info.changed.map(v => ({...v, item: '...'})),
);
}
};
@@ -205,7 +204,6 @@ class FlatListExample extends React.PureComponent<{}, $FlowFixMeState> {
_listRef: AnimatedFlatList;
}
const styles = StyleSheet.create({
container: {
backgroundColor: 'rgb(239, 239, 244)',

View File

@@ -4,18 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
StyleSheet,
Text,
View,
} = ReactNative;
var {StyleSheet, Text, View} = ReactNative;
exports.framework = 'React';
exports.title = 'Geolocation';
@@ -27,7 +24,7 @@ exports.examples = [
render: function(): React.Element<any> {
return <GeolocationExample />;
},
}
},
];
class GeolocationExample extends React.Component<{}, $FlowFixMeState> {
@@ -40,14 +37,14 @@ class GeolocationExample extends React.Component<{}, $FlowFixMeState> {
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
position => {
var initialPosition = JSON.stringify(position);
this.setState({initialPosition});
},
(error) => alert(JSON.stringify(error)),
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
error => alert(JSON.stringify(error)),
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000},
);
this.watchID = navigator.geolocation.watchPosition((position) => {
this.watchID = navigator.geolocation.watchPosition(position => {
var lastPosition = JSON.stringify(position);
this.setState({lastPosition});
});

View File

@@ -4,34 +4,29 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var nativeImageSource = require('nativeImageSource');
var {
Image,
StyleSheet,
Text,
View,
} = ReactNative;
var {Image, StyleSheet, Text, View} = ReactNative;
class ImageCapInsetsExample extends React.Component<{}> {
render() {
return (
<View>
<View style={styles.background}>
<Text>
capInsets: none
</Text>
<Text>capInsets: none</Text>
<Image
source={nativeImageSource({
ios: 'story-background',
width: 60,
height: 60
height: 60,
})}
style={styles.storyBackground}
resizeMode={Image.resizeMode.stretch}
@@ -39,14 +34,12 @@ class ImageCapInsetsExample extends React.Component<{}> {
/>
</View>
<View style={[styles.background, {paddingTop: 10}]}>
<Text>
capInsets: 15
</Text>
<Text>capInsets: 15</Text>
<Image
source={nativeImageSource({
ios: 'story-background',
width: 60,
height: 60
height: 60,
})}
style={styles.storyBackground}
resizeMode={Image.resizeMode.stretch}
@@ -74,7 +67,7 @@ var styles = StyleSheet.create({
},
text: {
fontSize: 13.5,
}
},
});
module.exports = ImageCapInsetsExample;

View File

@@ -4,5 +4,6 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
@@ -21,10 +23,12 @@ var {
ImageBackground,
} = ReactNative;
var base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAQAAACSR7JhAAADtUlEQVR4Ac3YA2Bj6QLH0XPT1Fzbtm29tW3btm3bfLZtv7e2ObZnms7d8Uw098tuetPzrxv8wiISrtVudrG2JXQZ4VOv+qUfmqCGGl1mqLhoA52oZlb0mrjsnhKpgeUNEs91Z0pd1kvihA3ULGVHiQO2narKSHKkEMulm9VgUyE60s1aWoMQUbpZOWE+kaqs4eLEjdIlZTcFZB0ndc1+lhB1lZrIuk5P2aib1NBpZaL+JaOGIt0ls47SKzLC7CqrlGF6RZ09HGoNy1lYl2aRSWL5GuzqWU1KafRdoRp0iOQEiDzgZPnG6DbldcomadViflnl/cL93tOoVbsOLVM2jylvdWjXolWX1hmfZbGR/wjypDjFLSZIRov09BgYmtUqPQPlQrPapecLgTIy0jMgPKtTeob2zWtrGH3xvjUkPCtNg/tm1rjwrMa+mdUkPd3hWbH0jArPGiU9ufCsNNWFZ40wpwn+62/66R2RUtoso1OB34tnLOcy7YB1fUdc9e0q3yru8PGM773vXsuZ5YIZX+5xmHwHGVvlrGPN6ZSiP1smOsMMde40wKv2VmwPPVXNut4sVpUreZiLBHi0qln/VQeI/LTMYXpsJtFiclUN+5HVZazim+Ky+7sAvxWnvjXrJFneVtLWLyPJu9K3cXLWeOlbMTlrIelbMDlrLenrjEQOtIF+fuI9xRp9ZBFp6+b6WT8RrxEpdK64BuvHgDk+vUy+b5hYk6zfyfs051gRoNO1usU12WWRWL73/MMEy9pMi9qIrR4ZpV16Rrvduxazmy1FSvuFXRkqTnE7m2kdb5U8xGjLw/spRr1uTov4uOgQE+0N/DvFrG/Jt7i/FzwxbA9kDanhf2w+t4V97G8lrT7wc08aA2QNUkuTfW/KimT01wdlfK4yEw030VfT0RtZbzjeMprNq8m8tnSTASrTLti64oBNdpmMQm0eEwvfPwRbUBywG5TzjPCsdwk3IeAXjQblLCoXnDVeoAz6SfJNk5TTzytCNZk/POtTSV40NwOFWzw86wNJRpubpXsn60NJFlHeqlYRbslqZm2jnEZ3qcSKgm0kTli3zZVS7y/iivZTweYXJ26Y+RTbV1zh3hYkgyFGSTKPfRVbRqWWVReaxYeSLarYv1Qqsmh1s95S7G+eEWK0f3jYKTbV6bOwepjfhtafsvUsqrQvrGC8YhmnO9cSCk3yuY984F1vesdHYhWJ5FvASlacshUsajFt2mUM9pqzvKGcyNJW0arTKN1GGGzQlH0tXwLDgQTurS8eIQAAAABJRU5ErkJggg==';
var base64Icon =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAQAAACSR7JhAAADtUlEQVR4Ac3YA2Bj6QLH0XPT1Fzbtm29tW3btm3bfLZtv7e2ObZnms7d8Uw098tuetPzrxv8wiISrtVudrG2JXQZ4VOv+qUfmqCGGl1mqLhoA52oZlb0mrjsnhKpgeUNEs91Z0pd1kvihA3ULGVHiQO2narKSHKkEMulm9VgUyE60s1aWoMQUbpZOWE+kaqs4eLEjdIlZTcFZB0ndc1+lhB1lZrIuk5P2aib1NBpZaL+JaOGIt0ls47SKzLC7CqrlGF6RZ09HGoNy1lYl2aRSWL5GuzqWU1KafRdoRp0iOQEiDzgZPnG6DbldcomadViflnl/cL93tOoVbsOLVM2jylvdWjXolWX1hmfZbGR/wjypDjFLSZIRov09BgYmtUqPQPlQrPapecLgTIy0jMgPKtTeob2zWtrGH3xvjUkPCtNg/tm1rjwrMa+mdUkPd3hWbH0jArPGiU9ufCsNNWFZ40wpwn+62/66R2RUtoso1OB34tnLOcy7YB1fUdc9e0q3yru8PGM773vXsuZ5YIZX+5xmHwHGVvlrGPN6ZSiP1smOsMMde40wKv2VmwPPVXNut4sVpUreZiLBHi0qln/VQeI/LTMYXpsJtFiclUN+5HVZazim+Ky+7sAvxWnvjXrJFneVtLWLyPJu9K3cXLWeOlbMTlrIelbMDlrLenrjEQOtIF+fuI9xRp9ZBFp6+b6WT8RrxEpdK64BuvHgDk+vUy+b5hYk6zfyfs051gRoNO1usU12WWRWL73/MMEy9pMi9qIrR4ZpV16Rrvduxazmy1FSvuFXRkqTnE7m2kdb5U8xGjLw/spRr1uTov4uOgQE+0N/DvFrG/Jt7i/FzwxbA9kDanhf2w+t4V97G8lrT7wc08aA2QNUkuTfW/KimT01wdlfK4yEw030VfT0RtZbzjeMprNq8m8tnSTASrTLti64oBNdpmMQm0eEwvfPwRbUBywG5TzjPCsdwk3IeAXjQblLCoXnDVeoAz6SfJNk5TTzytCNZk/POtTSV40NwOFWzw86wNJRpubpXsn60NJFlHeqlYRbslqZm2jnEZ3qcSKgm0kTli3zZVS7y/iivZTweYXJ26Y+RTbV1zh3hYkgyFGSTKPfRVbRqWWVReaxYeSLarYv1Qqsmh1s95S7G+eEWK0f3jYKTbV6bOwepjfhtafsvUsqrQvrGC8YhmnO9cSCk3yuY984F1vesdHYhWJ5FvASlacshUsajFt2mUM9pqzvKGcyNJW0arTKN1GGGzQlH0tXwLDgQTurS8eIQAAAABJRU5ErkJggg==';
var ImageCapInsetsExample = require('./ImageCapInsetsExample');
const IMAGE_PREFETCH_URL = 'http://origami.design/public/images/bird-logo.png?r=1&t=' + Date.now();
const IMAGE_PREFETCH_URL =
'http://origami.design/public/images/bird-logo.png?r=1&t=' + Date.now();
var prefetchTask = Image.prefetch(IMAGE_PREFETCH_URL);
/* $FlowFixMe(>=0.63.0 site=react_native_fb) This comment suppresses an error
@@ -45,19 +49,23 @@ var NetworkImageCallbackExample = createReactClass({
},
render: function() {
var { mountTime } = this.state;
var {mountTime} = this.state;
return (
<View>
<Image
source={this.props.source}
style={[styles.base, {overflow: 'visible'}]}
onLoadStart={() => this._loadEventFired(`✔ onLoadStart (+${new Date() - mountTime}ms)`)}
onLoad={(event) => {
onLoadStart={() =>
this._loadEventFired(`✔ onLoadStart (+${new Date() - mountTime}ms)`)
}
onLoad={event => {
// Currently this image source feature is only available on iOS.
if (event.nativeEvent.source) {
const url = event.nativeEvent.source.url;
this._loadEventFired(`✔ onLoad (+${new Date() - mountTime}ms) for URL ${url}`);
this._loadEventFired(
`✔ onLoad (+${new Date() - mountTime}ms) for URL ${url}`,
);
} else {
this._loadEventFired(`✔ onLoad (+${new Date() - mountTime}ms)`);
}
@@ -65,43 +73,61 @@ var NetworkImageCallbackExample = createReactClass({
onLoadEnd={() => {
this._loadEventFired(`✔ onLoadEnd (+${new Date() - mountTime}ms)`);
this.setState({startLoadPrefetched: true}, () => {
prefetchTask.then(() => {
this._loadEventFired(`✔ Prefetch OK (+${new Date() - mountTime}ms)`);
}, error => {
this._loadEventFired(` Prefetch failed (+${new Date() - mountTime}ms)`);
});
prefetchTask.then(
() => {
this._loadEventFired(
` Prefetch OK (+${new Date() - mountTime}ms)`,
);
},
error => {
this._loadEventFired(
`✘ Prefetch failed (+${new Date() - mountTime}ms)`,
);
},
);
});
}}
/>
{this.state.startLoadPrefetched ?
{this.state.startLoadPrefetched ? (
<Image
source={this.props.prefetchedSource}
style={[styles.base, {overflow: 'visible'}]}
onLoadStart={() => this._loadEventFired(`✔ (prefetched) onLoadStart (+${new Date() - mountTime}ms)`)}
onLoad={(event) => {
onLoadStart={() =>
this._loadEventFired(
`✔ (prefetched) onLoadStart (+${new Date() - mountTime}ms)`,
)
}
onLoad={event => {
// Currently this image source feature is only available on iOS.
if (event.nativeEvent.source) {
const url = event.nativeEvent.source.url;
this._loadEventFired(`✔ (prefetched) onLoad (+${new Date() - mountTime}ms) for URL ${url}`);
this._loadEventFired(
`✔ (prefetched) onLoad (+${new Date() -
mountTime}ms) for URL ${url}`,
);
} else {
this._loadEventFired(`✔ (prefetched) onLoad (+${new Date() - mountTime}ms)`);
this._loadEventFired(
`✔ (prefetched) onLoad (+${new Date() - mountTime}ms)`,
);
}
}}
onLoadEnd={() => this._loadEventFired(`✔ (prefetched) onLoadEnd (+${new Date() - mountTime}ms)`)}
onLoadEnd={() =>
this._loadEventFired(
`✔ (prefetched) onLoadEnd (+${new Date() - mountTime}ms)`,
)
}
/>
: null}
<Text style={{marginTop: 20}}>
{this.state.events.join('\n')}
</Text>
) : null}
<Text style={{marginTop: 20}}>{this.state.events.join('\n')}</Text>
</View>
);
},
_loadEventFired(event) {
this.setState((state) => {
return state.events = [...state.events, event];
this.setState(state => {
return (state.events = [...state.events, event]);
});
}
},
});
var NetworkImageExample = createReactClass({
@@ -109,27 +135,38 @@ var NetworkImageExample = createReactClass({
return {
error: false,
loading: false,
progress: 0
progress: 0,
};
},
render: function() {
var loader = this.state.loading ?
var loader = this.state.loading ? (
<View style={styles.progress}>
<Text>{this.state.progress}%</Text>
<ActivityIndicator style={{marginLeft:5}} />
</View> : null;
return this.state.error ?
<Text>{this.state.error}</Text> :
<ActivityIndicator style={{marginLeft: 5}} />
</View>
) : null;
return this.state.error ? (
<Text>{this.state.error}</Text>
) : (
<ImageBackground
source={this.props.source}
style={[styles.base, {overflow: 'visible'}]}
onLoadStart={(e) => this.setState({loading: true})}
onError={(e) => this.setState({error: e.nativeEvent.error, loading: false})}
onProgress={(e) => this.setState({progress: Math.round(100 * e.nativeEvent.loaded / e.nativeEvent.total)})}
onLoadStart={e => this.setState({loading: true})}
onError={e =>
this.setState({error: e.nativeEvent.error, loading: false})
}
onProgress={e =>
this.setState({
progress: Math.round(
100 * e.nativeEvent.loaded / e.nativeEvent.total,
),
})
}
onLoad={() => this.setState({loading: false, error: false})}>
{loader}
</ImageBackground>;
}
</ImageBackground>
);
},
});
var ImageSizeExample = createReactClass({
@@ -154,7 +191,8 @@ var ImageSizeExample = createReactClass({
backgroundColor: 'transparent',
marginRight: 10,
}}
source={this.props.source} />
source={this.props.source}
/>
<Text>
Actual dimensions:{'\n'}
Width: {this.state.width}, Height: {this.state.height}
@@ -175,26 +213,36 @@ var MultipleSourcesExample = createReactClass({
return (
<View>
<View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
<Text
style={styles.touchableText}
onPress={this.decreaseImageSize} >
<Text style={styles.touchableText} onPress={this.decreaseImageSize}>
Decrease image size
</Text>
<Text
style={styles.touchableText}
onPress={this.increaseImageSize} >
<Text style={styles.touchableText} onPress={this.increaseImageSize}>
Increase image size
</Text>
</View>
<Text>Container image size: {this.state.width}x{this.state.height} </Text>
<View
style={{height: this.state.height, width: this.state.width}} >
<Text>
Container image size: {this.state.width}x{this.state.height}{' '}
</Text>
<View style={{height: this.state.height, width: this.state.width}}>
<Image
style={{flex: 1}}
source={[
{uri: 'https://facebook.github.io/react-native/img/favicon.png', width: 38, height: 38},
{uri: 'https://facebook.github.io/react-native/img/favicon.png', width: 76, height: 76},
{uri: 'https://facebook.github.io/react-native/img/opengraph.png', width: 400, height: 400}
{
uri: 'https://facebook.github.io/react-native/img/favicon.png',
width: 38,
height: 38,
},
{
uri: 'https://facebook.github.io/react-native/img/favicon.png',
width: 76,
height: 76,
},
{
uri:
'https://facebook.github.io/react-native/img/opengraph.png',
width: 400,
height: 400,
},
]}
/>
</View>
@@ -224,33 +272,43 @@ var MultipleSourcesExample = createReactClass({
exports.displayName = (undefined: ?string);
exports.framework = 'React';
exports.title = '<Image>';
exports.description = 'Base component for displaying different types of images.';
exports.description =
'Base component for displaying different types of images.';
exports.examples = [
{
title: 'Plain Network Image',
description: 'If the `source` prop `uri` property is prefixed with ' +
'"http", then it will be downloaded from the network.',
description:
'If the `source` prop `uri` property is prefixed with ' +
'"http", then it will be downloaded from the network.',
render: function() {
return (
<Image
source={fullImage}
style={styles.base}
/>
);
return <Image source={fullImage} style={styles.base} />;
},
},
{
title: 'Plain Static Image',
description: 'Static assets should be placed in the source code tree, and ' +
'required in the same way as JavaScript modules.',
description:
'Static assets should be placed in the source code tree, and ' +
'required in the same way as JavaScript modules.',
render: function() {
return (
<View style={styles.horizontal}>
<Image source={require('./uie_thumb_normal.png')} style={styles.icon} />
<Image source={require('./uie_thumb_selected.png')} style={styles.icon} />
<Image source={require('./uie_comment_normal.png')} style={styles.icon} />
<Image source={require('./uie_comment_highlighted.png')} style={styles.icon} />
<Image
source={require('./uie_thumb_normal.png')}
style={styles.icon}
/>
<Image
source={require('./uie_thumb_selected.png')}
style={styles.icon}
/>
<Image
source={require('./uie_comment_normal.png')}
style={styles.icon}
/>
<Image
source={require('./uie_comment_highlighted.png')}
style={styles.icon}
/>
</View>
);
},
@@ -259,8 +317,14 @@ exports.examples = [
title: 'Image Loading Events',
render: function() {
return (
<NetworkImageCallbackExample source={{uri: 'http://origami.design/public/images/bird-logo.png?r=1&t=' + Date.now()}}
prefetchedSource={{uri: IMAGE_PREFETCH_URL}}/>
<NetworkImageCallbackExample
source={{
uri:
'http://origami.design/public/images/bird-logo.png?r=1&t=' +
Date.now(),
}}
prefetchedSource={{uri: IMAGE_PREFETCH_URL}}
/>
);
},
},
@@ -268,7 +332,11 @@ exports.examples = [
title: 'Error Handler',
render: function() {
return (
<NetworkImageExample source={{uri: 'https://TYPO_ERROR_facebook.github.io/react/logo-og.png'}} />
<NetworkImageExample
source={{
uri: 'https://TYPO_ERROR_facebook.github.io/react/logo-og.png',
}}
/>
);
},
platform: 'ios',
@@ -277,7 +345,11 @@ exports.examples = [
title: 'Image Download Progress',
render: function() {
return (
<NetworkImageExample source={{uri: 'http://origami.design/public/images/bird-logo.png?r=1'}}/>
<NetworkImageExample
source={{
uri: 'http://origami.design/public/images/bird-logo.png?r=1',
}}
/>
);
},
platform: 'ios',
@@ -289,7 +361,9 @@ exports.examples = [
return (
<Image
defaultSource={require('./bunny.png')}
source={{uri: 'https://facebook.github.io/origami/public/images/birds.jpg'}}
source={{
uri: 'https://facebook.github.io/origami/public/images/birds.jpg',
}}
style={styles.base}
/>
);
@@ -298,17 +372,18 @@ exports.examples = [
},
{
title: 'Cache Policy',
description: 'First image has never been loaded before and is instructed not to load unless in cache.' +
'Placeholder image from above will stay. Second image is the same but forced to load regardless of' +
' local cache state.',
render: function () {
description:
'First image has never been loaded before and is instructed not to load unless in cache.' +
'Placeholder image from above will stay. Second image is the same but forced to load regardless of' +
' local cache state.',
render: function() {
return (
<View style={styles.horizontal}>
<Image
defaultSource={require('./bunny.png')}
source={{
uri: smallImage.uri + '?cacheBust=notinCache' + Date.now(),
cache: 'only-if-cached'
cache: 'only-if-cached',
}}
style={styles.base}
/>
@@ -316,7 +391,7 @@ exports.examples = [
defaultSource={require('./bunny.png')}
source={{
uri: smallImage.uri + '?cacheBust=notinCache' + Date.now(),
cache: 'reload'
cache: 'reload',
}}
style={styles.base}
/>
@@ -335,7 +410,7 @@ exports.examples = [
style={[
styles.base,
styles.background,
{borderWidth: 3, borderColor: '#f099f0'}
{borderWidth: 3, borderColor: '#f099f0'},
]}
/>
</View>
@@ -352,7 +427,7 @@ exports.examples = [
style={[
styles.base,
styles.background,
{borderWidth: 5, borderColor: '#f099f0'}
{borderWidth: 5, borderColor: '#f099f0'},
]}
/>
</View>
@@ -364,10 +439,7 @@ exports.examples = [
render: function() {
return (
<View style={styles.horizontal}>
<Image
style={[styles.base, {borderRadius: 5}]}
source={fullImage}
/>
<Image style={[styles.base, {borderRadius: 5}]} source={fullImage} />
<Image
style={[styles.base, styles.leftMargin, {borderRadius: 19}]}
source={fullImage}
@@ -386,7 +458,7 @@ exports.examples = [
style={[
styles.base,
styles.leftMargin,
{backgroundColor: 'rgba(0, 0, 100, 0.25)'}
{backgroundColor: 'rgba(0, 0, 100, 0.25)'},
]}
source={smallImage}
/>
@@ -407,10 +479,7 @@ exports.examples = [
render: function() {
return (
<View style={styles.horizontal}>
<Image
style={[styles.base, {opacity: 1}]}
source={fullImage}
/>
<Image style={[styles.base, {opacity: 1}]} source={fullImage} />
<Image
style={[styles.base, styles.leftMargin, {opacity: 0.8}]}
source={fullImage}
@@ -442,10 +511,9 @@ exports.examples = [
<View style={{width: 60, height: 60}}>
<Image
style={{...StyleSheet.absoluteFillObject}}
source={fullImage}/>
<Text style={styles.nestedText}>
React
</Text>
source={fullImage}
/>
<Text style={styles.nestedText}>React</Text>
</View>
);
},
@@ -457,16 +525,15 @@ exports.examples = [
<ImageBackground
style={{width: 60, height: 60, backgroundColor: 'transparent'}}
source={fullImage}>
<Text style={styles.nestedText}>
React
</Text>
<Text style={styles.nestedText}>React</Text>
</ImageBackground>
);
},
},
{
title: 'Tint Color',
description: 'The `tintColor` style prop changes all the non-alpha ' +
description:
'The `tintColor` style prop changes all the non-alpha ' +
'pixels to the tint color.',
render: function() {
return (
@@ -474,19 +541,31 @@ exports.examples = [
<View style={styles.horizontal}>
<Image
source={require('./uie_thumb_normal.png')}
style={[styles.icon, {borderRadius: 5, tintColor: '#5ac8fa' }]}
style={[styles.icon, {borderRadius: 5, tintColor: '#5ac8fa'}]}
/>
<Image
source={require('./uie_thumb_normal.png')}
style={[styles.icon, styles.leftMargin, {borderRadius: 5, tintColor: '#4cd964' }]}
style={[
styles.icon,
styles.leftMargin,
{borderRadius: 5, tintColor: '#4cd964'},
]}
/>
<Image
source={require('./uie_thumb_normal.png')}
style={[styles.icon, styles.leftMargin, {borderRadius: 5, tintColor: '#ff2d55' }]}
style={[
styles.icon,
styles.leftMargin,
{borderRadius: 5, tintColor: '#ff2d55'},
]}
/>
<Image
source={require('./uie_thumb_normal.png')}
style={[styles.icon, styles.leftMargin, {borderRadius: 5, tintColor: '#8e8e93' }]}
style={[
styles.icon,
styles.leftMargin,
{borderRadius: 5, tintColor: '#8e8e93'},
]}
/>
</View>
<Text style={styles.sectionText}>
@@ -495,19 +574,31 @@ exports.examples = [
<View style={styles.horizontal}>
<Image
source={smallImage}
style={[styles.base, {borderRadius: 5, tintColor: '#5ac8fa' }]}
style={[styles.base, {borderRadius: 5, tintColor: '#5ac8fa'}]}
/>
<Image
source={smallImage}
style={[styles.base, styles.leftMargin, {borderRadius: 5, tintColor: '#4cd964' }]}
style={[
styles.base,
styles.leftMargin,
{borderRadius: 5, tintColor: '#4cd964'},
]}
/>
<Image
source={smallImage}
style={[styles.base, styles.leftMargin, {borderRadius: 5, tintColor: '#ff2d55' }]}
style={[
styles.base,
styles.leftMargin,
{borderRadius: 5, tintColor: '#ff2d55'},
]}
/>
<Image
source={smallImage}
style={[styles.base, styles.leftMargin, {borderRadius: 5, tintColor: '#8e8e93' }]}
style={[
styles.base,
styles.leftMargin,
{borderRadius: 5, tintColor: '#8e8e93'},
]}
/>
</View>
</View>
@@ -516,71 +607,62 @@ exports.examples = [
},
{
title: 'Resize Mode',
description: 'The `resizeMode` style prop controls how the image is ' +
description:
'The `resizeMode` style prop controls how the image is ' +
'rendered within the frame.',
render: function() {
return (
<View>
{[smallImage, fullImage].map((image, index) => {
return (
<View key={index}>
<View style={styles.horizontal}>
<View>
<Text style={[styles.resizeModeText]}>
Contain
</Text>
<Image
style={styles.resizeMode}
resizeMode={Image.resizeMode.contain}
source={image}
/>
<View key={index}>
<View style={styles.horizontal}>
<View>
<Text style={[styles.resizeModeText]}>Contain</Text>
<Image
style={styles.resizeMode}
resizeMode={Image.resizeMode.contain}
source={image}
/>
</View>
<View style={styles.leftMargin}>
<Text style={[styles.resizeModeText]}>Cover</Text>
<Image
style={styles.resizeMode}
resizeMode={Image.resizeMode.cover}
source={image}
/>
</View>
</View>
<View style={styles.leftMargin}>
<Text style={[styles.resizeModeText]}>
Cover
</Text>
<Image
style={styles.resizeMode}
resizeMode={Image.resizeMode.cover}
source={image}
/>
<View style={styles.horizontal}>
<View>
<Text style={[styles.resizeModeText]}>Stretch</Text>
<Image
style={styles.resizeMode}
resizeMode={Image.resizeMode.stretch}
source={image}
/>
</View>
<View style={styles.leftMargin}>
<Text style={[styles.resizeModeText]}>Repeat</Text>
<Image
style={styles.resizeMode}
resizeMode={Image.resizeMode.repeat}
source={image}
/>
</View>
<View style={styles.leftMargin}>
<Text style={[styles.resizeModeText]}>Center</Text>
<Image
style={styles.resizeMode}
resizeMode={Image.resizeMode.center}
source={image}
/>
</View>
</View>
</View>
<View style={styles.horizontal}>
<View>
<Text style={[styles.resizeModeText]}>
Stretch
</Text>
<Image
style={styles.resizeMode}
resizeMode={Image.resizeMode.stretch}
source={image}
/>
</View>
<View style={styles.leftMargin}>
<Text style={[styles.resizeModeText]}>
Repeat
</Text>
<Image
style={styles.resizeMode}
resizeMode={Image.resizeMode.repeat}
source={image}
/>
</View>
<View style={styles.leftMargin}>
<Text style={[styles.resizeModeText]}>
Center
</Text>
<Image
style={styles.resizeMode}
resizeMode={Image.resizeMode.center}
source={image}
/>
</View>
</View>
</View>
);
})}
);
})}
</View>
);
},
@@ -591,7 +673,10 @@ exports.examples = [
return (
<Image
style={styles.gif}
source={{uri: 'https://38.media.tumblr.com/9e9bd08c6e2d10561dd1fb4197df4c4e/tumblr_mfqekpMktw1rn90umo1_500.gif'}}
source={{
uri:
'https://38.media.tumblr.com/9e9bd08c6e2d10561dd1fb4197df4c4e/tumblr_mfqekpMktw1rn90umo1_500.gif',
}}
/>
);
},
@@ -601,10 +686,7 @@ exports.examples = [
title: 'Base64 image',
render: function() {
return (
<Image
style={styles.base64}
source={{uri: base64Icon, scale: 3}}
/>
<Image style={styles.base64} source={{uri: base64Icon, scale: 3}} />
);
},
platform: 'ios',
@@ -642,17 +724,12 @@ exports.examples = [
'Images shipped with the native bundle, but not managed ' +
'by the JS packager',
render: function() {
return (
<Image
source={{uri: 'legacy_image', width: 120, height: 120}}
/>
);
return <Image source={{uri: 'legacy_image', width: 120, height: 120}} />;
},
},
{
title: 'Bundled images',
description:
'Images shipped in a separate native bundle',
description: 'Images shipped in a separate native bundle',
render: function() {
return (
<View style={{flexDirection: 'row'}}>
@@ -684,11 +761,7 @@ exports.examples = [
render: function() {
return (
<View style={styles.horizontal}>
<Image
style={[styles.base,]}
source={fullImage}
blurRadius={0}
/>
<Image style={[styles.base]} source={fullImage} blurRadius={0} />
<Image
style={[styles.base, styles.leftMargin]}
source={fullImage}
@@ -720,8 +793,12 @@ exports.examples = [
},
];
var fullImage = {uri: 'https://facebook.github.io/react-native/img/opengraph.png'};
var smallImage = {uri: 'https://facebook.github.io/react-native/img/favicon.png'};
var fullImage = {
uri: 'https://facebook.github.io/react-native/img/opengraph.png',
};
var smallImage = {
uri: 'https://facebook.github.io/react-native/img/favicon.png',
};
var styles = StyleSheet.create({
base: {
@@ -732,13 +809,13 @@ var styles = StyleSheet.create({
flex: 1,
alignItems: 'center',
flexDirection: 'row',
width: 100
width: 100,
},
leftMargin: {
marginLeft: 10,
},
background: {
backgroundColor: '#222222'
backgroundColor: '#222222',
},
sectionText: {
marginVertical: 6,
@@ -747,13 +824,13 @@ var styles = StyleSheet.create({
marginLeft: 12,
marginTop: 20,
backgroundColor: 'transparent',
color: 'white'
color: 'white',
},
resizeMode: {
width: 90,
height: 60,
borderWidth: 0.5,
borderColor: 'black'
borderColor: 'black',
},
resizeModeText: {
fontSize: 11,

View File

@@ -4,7 +4,9 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const React = require('React');
@@ -40,15 +42,16 @@ class KeyboardAvoidingViewExample extends React.Component {
return (
<View style={styles.outerContainer}>
<Modal animationType="fade" visible={this.state.modalOpen}>
<KeyboardAvoidingView behavior={this.state.behavior} style={styles.container}>
<KeyboardAvoidingView
behavior={this.state.behavior}
style={styles.container}>
<SegmentedControlIOS
onValueChange={this.onSegmentChange}
selectedIndex={this.state.behavior === 'padding' ? 0 : 1}
style={styles.segment}
values={['Padding', 'Position']} />
<TextInput
placeholder="<TextInput />"
style={styles.textInput} />
values={['Padding', 'Position']}
/>
<TextInput placeholder="<TextInput />" style={styles.textInput} />
</KeyboardAvoidingView>
<TouchableHighlight
onPress={() => this.setState({modalOpen: false})}
@@ -98,7 +101,7 @@ const styles = StyleSheet.create({
position: 'absolute',
top: 30,
left: 10,
}
},
});
module.exports = KeyboardAvoidingViewExample;

View File

@@ -4,19 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
const ReactNative = require('react-native');
const {
LayoutAnimation,
StyleSheet,
Text,
View,
TouchableOpacity,
} = ReactNative;
const {LayoutAnimation, StyleSheet, Text, View, TouchableOpacity} = ReactNative;
class AddRemoveExample extends React.Component<{}, $FlowFixMeState> {
state = {
@@ -28,19 +24,19 @@ class AddRemoveExample extends React.Component<{}, $FlowFixMeState> {
}
_onPressAddView = () => {
this.setState((state) => ({views: [...state.views, {}]}));
this.setState(state => ({views: [...state.views, {}]}));
};
_onPressRemoveView = () => {
this.setState((state) => ({views: state.views.slice(0, -1)}));
this.setState(state => ({views: state.views.slice(0, -1)}));
};
render() {
const views = this.state.views.map((view, i) =>
const views = this.state.views.map((view, i) => (
<View key={i} style={styles.view}>
<Text>{i}</Text>
</View>
);
));
return (
<View style={styles.container}>
<TouchableOpacity onPress={this._onPressAddView}>
@@ -53,23 +49,23 @@ class AddRemoveExample extends React.Component<{}, $FlowFixMeState> {
<Text>Remove view</Text>
</View>
</TouchableOpacity>
<View style={styles.viewContainer}>
{views}
</View>
<View style={styles.viewContainer}>{views}</View>
</View>
);
}
}
const GreenSquare = () =>
const GreenSquare = () => (
<View style={styles.greenSquare}>
<Text>Green square</Text>
</View>;
</View>
);
const BlueSquare = () =>
const BlueSquare = () => (
<View style={styles.blueSquare}>
<Text>Blue square</Text>
</View>;
</View>
);
class CrossFadeExample extends React.Component<{}, $FlowFixMeState> {
state = {
@@ -78,7 +74,7 @@ class CrossFadeExample extends React.Component<{}, $FlowFixMeState> {
_onPressToggle = () => {
LayoutAnimation.easeInEaseOut();
this.setState((state) => ({toggled: !state.toggled}));
this.setState(state => ({toggled: !state.toggled}));
};
render() {
@@ -90,11 +86,7 @@ class CrossFadeExample extends React.Component<{}, $FlowFixMeState> {
</View>
</TouchableOpacity>
<View style={styles.viewContainer}>
{
this.state.toggled ?
<GreenSquare /> :
<BlueSquare />
}
{this.state.toggled ? <GreenSquare /> : <BlueSquare />}
</View>
</View>
);
@@ -118,7 +110,7 @@ class LayoutUpdateExample extends React.Component<{}, $FlowFixMeState> {
clearTimeout(this.timeout);
this.timeout = null;
}
}
};
_onPressToggle = () => {
this._clearTimeout();
@@ -145,7 +137,9 @@ class LayoutUpdateExample extends React.Component<{}, $FlowFixMeState> {
</View>
</TouchableOpacity>
<View style={[styles.view, {width, height}]}>
<Text>{width}x{height}</Text>
<Text>
{width}x{height}
</Text>
</View>
</View>
);
@@ -196,19 +190,23 @@ const styles = StyleSheet.create({
exports.title = 'Layout Animation';
exports.description = 'Layout animation';
exports.examples = [{
title: 'Add and remove views',
render(): React.Element<any> {
return <AddRemoveExample />;
exports.examples = [
{
title: 'Add and remove views',
render(): React.Element<any> {
return <AddRemoveExample />;
},
},
}, {
title: 'Cross fade views',
render(): React.Element<any> {
return <CrossFadeExample />;
{
title: 'Cross fade views',
render(): React.Element<any> {
return <CrossFadeExample />;
},
},
}, {
title: 'Layout update during animation',
render(): React.Element<any> {
return <LayoutUpdateExample />;
{
title: 'Layout update during animation',
render(): React.Element<any> {
return <LayoutUpdateExample />;
},
},
}];
];

View File

@@ -4,29 +4,25 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Image,
LayoutAnimation,
StyleSheet,
Text,
View,
} = ReactNative;
var {Image, LayoutAnimation, StyleSheet, Text, View} = ReactNative;
import type {ViewLayout, ViewLayoutEvent} from 'ViewPropTypes';
type State = {
containerStyle?: { width: number },
containerStyle?: {width: number},
extraText?: string,
imageLayout?: ViewLayout,
textLayout?: ViewLayout,
viewLayout?: ViewLayout,
viewStyle: { margin: number },
viewStyle: {margin: number},
};
class LayoutEventExample extends React.Component<{}, State> {
@@ -37,24 +33,21 @@ class LayoutEventExample extends React.Component<{}, State> {
};
animateViewLayout = () => {
LayoutAnimation.configureNext(
LayoutAnimation.Presets.spring,
() => {
console.log('layout animation done.');
this.addWrapText();
}
);
LayoutAnimation.configureNext(LayoutAnimation.Presets.spring, () => {
console.log('layout animation done.');
this.addWrapText();
});
this.setState({
viewStyle: {
margin: this.state.viewStyle.margin > 20 ? 20 : 60,
}
},
});
};
addWrapText = () => {
this.setState(
{extraText: ' And a bunch more text to wrap around a few lines.'},
this.changeContainer
this.changeContainer,
);
};
@@ -84,7 +77,10 @@ class LayoutEventExample extends React.Component<{}, State> {
return (
<View style={this.state.containerStyle}>
<Text>
layout events are called on mount and whenever layout is recalculated. Note that the layout event will typically be received <Text style={styles.italicText}>before</Text> the layout has updated on screen, especially when using layout animations.{' '}
layout events are called on mount and whenever layout is recalculated.
Note that the layout event will typically be received{' '}
<Text style={styles.italicText}>before</Text> the layout has updated
on screen, especially when using layout animations.{' '}
<Text style={styles.pressText} onPress={this.animateViewLayout}>
Press here to change layout.
</Text>
@@ -94,10 +90,14 @@ class LayoutEventExample extends React.Component<{}, State> {
ref="img"
onLayout={this.onImageLayout}
style={styles.image}
source={{uri: 'https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-prn1/t39.1997/p128x128/851561_767334496626293_1958532586_n.png'}}
source={{
uri:
'https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-prn1/t39.1997/p128x128/851561_767334496626293_1958532586_n.png',
}}
/>
<Text>
ViewLayout: {JSON.stringify(this.state.viewLayout, null, ' ') + '\n\n'}
ViewLayout:{' '}
{JSON.stringify(this.state.viewLayout, null, ' ') + '\n\n'}
</Text>
<Text ref="txt" onLayout={this.onTextLayout} style={styles.text}>
A simple piece of text.{this.state.extraText}
@@ -140,12 +140,14 @@ var styles = StyleSheet.create({
});
exports.title = 'Layout Events';
exports.description = 'Examples that show how Layout events can be used to ' +
exports.description =
'Examples that show how Layout events can be used to ' +
'measure view size and position.';
exports.examples = [
{
title: 'LayoutEventExample',
render: function(): React.Element<any> {
return <LayoutEventExample />;
{
title: 'LayoutEventExample',
render: function(): React.Element<any> {
return <LayoutEventExample />;
},
},
}];
];

View File

@@ -4,17 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
StyleSheet,
Text,
View,
} = ReactNative;
var {StyleSheet, Text, View} = ReactNative;
var RNTesterBlock = require('./RNTesterBlock');
var RNTesterPage = require('./RNTesterPage');
@@ -47,9 +45,7 @@ class CircleBlock extends React.Component<$FlowFixMeProps> {
marginBottom: 2,
};
return (
<View style={[circleStyle, this.props.style]}>
{this.props.children}
</View>
<View style={[circleStyle, this.props.style]}>{this.props.children}</View>
);
}
}
@@ -65,7 +61,7 @@ class LayoutExample extends React.Component<$FlowFixMeProps> {
<Circle bgColor="#D443E3" key="violet" />,
<Circle bgColor="#FF9049" key="orange" />,
<Circle bgColor="#FFE649" key="yellow" />,
<Circle bgColor="#7FE040" key="green" />
<Circle bgColor="#7FE040" key="green" />,
];
return (
@@ -87,7 +83,11 @@ class LayoutExample extends React.Component<$FlowFixMeProps> {
<CircleBlock style={{flexDirection: 'column-reverse'}}>
{fiveColoredCircles}
</CircleBlock>
<View style={[styles.overlay, {position: 'absolute', top: 15, left: 160}]}>
<View
style={[
styles.overlay,
{position: 'absolute', top: 15, left: 160},
]}>
<Text>{'top: 15, left: 160'}</Text>
</View>
</RNTesterBlock>
@@ -117,30 +117,63 @@ class LayoutExample extends React.Component<$FlowFixMeProps> {
<RNTesterBlock title="Align Items - Other Direction">
<Text>flex-start</Text>
<CircleBlock style={{alignItems: 'flex-start', height: 30}}>
<Circle size={15} /><Circle size={10} /><Circle size={20} />
<Circle size={17} /><Circle size={12} /><Circle size={15} />
<Circle size={10} /><Circle size={20} /><Circle size={17} />
<Circle size={12} /><Circle size={15} /><Circle size={10} />
<Circle size={20} /><Circle size={17} /><Circle size={12} />
<Circle size={15} /><Circle size={8} />
<Circle size={15} />
<Circle size={10} />
<Circle size={20} />
<Circle size={17} />
<Circle size={12} />
<Circle size={15} />
<Circle size={10} />
<Circle size={20} />
<Circle size={17} />
<Circle size={12} />
<Circle size={15} />
<Circle size={10} />
<Circle size={20} />
<Circle size={17} />
<Circle size={12} />
<Circle size={15} />
<Circle size={8} />
</CircleBlock>
<Text>center</Text>
<CircleBlock style={{alignItems: 'center', height: 30}}>
<Circle size={15} /><Circle size={10} /><Circle size={20} />
<Circle size={17} /><Circle size={12} /><Circle size={15} />
<Circle size={10} /><Circle size={20} /><Circle size={17} />
<Circle size={12} /><Circle size={15} /><Circle size={10} />
<Circle size={20} /><Circle size={17} /><Circle size={12} />
<Circle size={15} /><Circle size={8} />
<Circle size={15} />
<Circle size={10} />
<Circle size={20} />
<Circle size={17} />
<Circle size={12} />
<Circle size={15} />
<Circle size={10} />
<Circle size={20} />
<Circle size={17} />
<Circle size={12} />
<Circle size={15} />
<Circle size={10} />
<Circle size={20} />
<Circle size={17} />
<Circle size={12} />
<Circle size={15} />
<Circle size={8} />
</CircleBlock>
<Text>flex-end</Text>
<CircleBlock style={{alignItems: 'flex-end', height: 30}}>
<Circle size={15} /><Circle size={10} /><Circle size={20} />
<Circle size={17} /><Circle size={12} /><Circle size={15} />
<Circle size={10} /><Circle size={20} /><Circle size={17} />
<Circle size={12} /><Circle size={15} /><Circle size={10} />
<Circle size={20} /><Circle size={17} /><Circle size={12} />
<Circle size={15} /><Circle size={8} />
<Circle size={15} />
<Circle size={10} />
<Circle size={20} />
<Circle size={17} />
<Circle size={12} />
<Circle size={15} />
<Circle size={10} />
<Circle size={20} />
<Circle size={17} />
<Circle size={12} />
<Circle size={15} />
<Circle size={10} />
<Circle size={20} />
<Circle size={17} />
<Circle size={12} />
<Circle size={15} />
<Circle size={8} />
</CircleBlock>
</RNTesterBlock>
<RNTesterBlock title="Flex Wrap">

View File

@@ -4,19 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
var React = require('react');
var PropTypes = require('prop-types');
var ReactNative = require('react-native');
var {
Linking,
StyleSheet,
Text,
TouchableOpacity,
View,
} = ReactNative;
var {Linking, StyleSheet, Text, TouchableOpacity, View} = ReactNative;
var RNTesterBlock = require('./RNTesterBlock');
class OpenURLButton extends React.Component {
@@ -29,15 +25,14 @@ class OpenURLButton extends React.Component {
if (supported) {
Linking.openURL(this.props.url);
} else {
console.log('Don\'t know how to open URI: ' + this.props.url);
console.log("Don't know how to open URI: " + this.props.url);
}
});
};
render() {
return (
<TouchableOpacity
onPress={this.handleClick}>
<TouchableOpacity onPress={this.handleClick}>
<View style={styles.button}>
<Text style={styles.text}>Open {this.props.url}</Text>
</View>

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
@@ -22,7 +24,13 @@ const {
View,
} = ReactNative;
type Item = {title: string, text: string, key: string, pressed: boolean, noImage?: ?boolean};
type Item = {
title: string,
text: string,
key: string,
pressed: boolean,
noImage?: ?boolean,
};
function genItemData(count: number, start: number = 0): Array<Item> {
const dataBlob = [];
@@ -65,12 +73,16 @@ class ItemComponent extends React.PureComponent<{
pressMagnification: 1.1,
}}
style={horizontal ? styles.horizItem : styles.item}>
<View style={[
styles.row, horizontal && {width: HORIZ_WIDTH}, fixedHeight && {height: ITEM_HEIGHT}]}>
<View
style={[
styles.row,
horizontal && {width: HORIZ_WIDTH},
fixedHeight && {height: ITEM_HEIGHT},
]}>
{!item.noImage && <Image style={styles.thumb} source={imgSource} />}
<Text
style={styles.text}
numberOfLines={(horizontal || fixedHeight) ? 3 : undefined}>
numberOfLines={horizontal || fixedHeight ? 3 : undefined}>
{item.title} - {item.text}
</Text>
</View>
@@ -84,7 +96,9 @@ const renderStackedItem = ({item}: {item: Item}) => {
const imgSource = THUMB_URLS[itemHash % THUMB_URLS.length];
return (
<View style={styles.stacked}>
<Text style={styles.stackedText}>{item.title} - {item.text}</Text>
<Text style={styles.stackedText}>
{item.title} - {item.text}
</Text>
<Image style={styles.thumb} source={imgSource} />
</View>
);
@@ -135,7 +149,10 @@ class SeparatorComponent extends React.PureComponent<{}> {
class ItemSeparatorComponent extends React.PureComponent<$FlowFixMeProps> {
render() {
const style = this.props.highlighted
? [styles.itemSeparator, {marginLeft: 0, backgroundColor: 'rgb(217, 217, 217)'}]
? [
styles.itemSeparator,
{marginLeft: 0, backgroundColor: 'rgb(217, 217, 217)'},
]
: styles.itemSeparator;
return <View style={style} />;
}
@@ -144,15 +161,22 @@ class ItemSeparatorComponent extends React.PureComponent<$FlowFixMeProps> {
class Spindicator extends React.PureComponent<$FlowFixMeProps> {
render() {
return (
<Animated.View style={[styles.spindicator, {
transform: [
{rotate: this.props.value.interpolate({
inputRange: [0, 5000],
outputRange: ['0deg', '360deg'],
extrapolate: 'extend',
})}
]
}]} />
<Animated.View
style={[
styles.spindicator,
{
transform: [
{
rotate: this.props.value.interpolate({
inputRange: [0, 5000],
outputRange: ['0deg', '360deg'],
extrapolate: 'extend',
}),
},
],
},
]}
/>
);
}
}
@@ -172,7 +196,8 @@ const THUMB_URLS = [
require('./Thumbnails/victory.png'),
];
const LOREM_IPSUM = 'Lorem ipsum dolor sit amet, ius ad pertinax oportere accommodare, an vix \
const LOREM_IPSUM =
'Lorem ipsum dolor sit amet, ius ad pertinax oportere accommodare, an vix \
civibus corrumpit referrentur. Te nam case ludus inciderint, te mea facilisi adipiscing. Sea id \
integre luptatum. In tota sale consequuntur nec. Erat ocurreret mei ei. Eu paulo sapientem \
vulputate est, vel an accusam intellegam interesset. Nam eu stet pericula reprimique, ea vim illud \
@@ -182,7 +207,7 @@ modus, putant invidunt reprehendunt ne qui.';
function hashCode(str: string): number {
let hash = 15;
for (let ii = str.length - 1; ii >= 0; ii--) {
hash = ((hash << 5) - hash) + str.charCodeAt(ii);
hash = (hash << 5) - hash + str.charCodeAt(ii);
}
return hash;
}
@@ -191,15 +216,16 @@ const HEADER = {height: 30, width: 100};
const SEPARATOR_HEIGHT = StyleSheet.hairlineWidth;
function getItemLayout(data: any, index: number, horizontal?: boolean) {
const [length, separator, header] = horizontal ?
[HORIZ_WIDTH, 0, HEADER.width] : [ITEM_HEIGHT, SEPARATOR_HEIGHT, HEADER.height];
const [length, separator, header] = horizontal
? [HORIZ_WIDTH, 0, HEADER.width]
: [ITEM_HEIGHT, SEPARATOR_HEIGHT, HEADER.height];
return {length, offset: (length + separator) * index + header, index};
}
function pressItem(context: Object, key: string) {
const index = Number(key);
const pressed = !context.state.data[index].pressed;
context.setState((state) => {
context.setState(state => {
const newData = [...state.data];
newData[index] = {
...state.data[index],
@@ -220,7 +246,7 @@ function renderSmallSwitchOption(context: Object, key: string) {
<Switch
style={styles.smallSwitch}
value={context.state[key]}
onValueChange={(value) => context.setState({[key]: value})}
onValueChange={value => context.setState({[key]: value})}
/>
</View>
);

View File

@@ -4,21 +4,16 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var createReactClass = require('create-react-class');
var ReactNative = require('react-native');
var {
Image,
ListView,
TouchableHighlight,
StyleSheet,
Text,
View,
} = ReactNative;
var {Image, ListView, TouchableHighlight, StyleSheet, Text, View} = ReactNative;
var RNTesterPage = require('./RNTesterPage');
@@ -26,7 +21,7 @@ var ListViewSimpleExample = createReactClass({
displayName: 'ListViewSimpleExample',
statics: {
title: '<ListView>',
description: 'Performant, scrollable list of data.'
description: 'Performant, scrollable list of data.',
},
getInitialState: function() {
@@ -57,11 +52,17 @@ var ListViewSimpleExample = createReactClass({
);
},
_renderRow: function(rowData: string, sectionID: number, rowID: number, highlightRow: (sectionID: number, rowID: number) => void) {
_renderRow: function(
rowData: string,
sectionID: number,
rowID: number,
highlightRow: (sectionID: number, rowID: number) => void,
) {
var rowHash = Math.abs(hashCode(rowData));
var imgSource = THUMB_URLS[rowHash % THUMB_URLS.length];
return (
<TouchableHighlight onPress={() => {
<TouchableHighlight
onPress={() => {
this._pressRow(rowID);
highlightRow(sectionID, rowID);
}}>
@@ -88,12 +89,18 @@ var ListViewSimpleExample = createReactClass({
_pressRow: function(rowID: number) {
this._pressData[rowID] = !this._pressData[rowID];
this.setState({dataSource: this.state.dataSource.cloneWithRows(
this._genRows(this._pressData)
)});
this.setState({
dataSource: this.state.dataSource.cloneWithRows(
this._genRows(this._pressData),
),
});
},
_renderSeparator: function(sectionID: number, rowID: number, adjacentRowHighlighted: bool) {
_renderSeparator: function(
sectionID: number,
rowID: number,
adjacentRowHighlighted: boolean,
) {
return (
<View
key={`${sectionID}-${rowID}`}
@@ -103,7 +110,7 @@ var ListViewSimpleExample = createReactClass({
}}
/>
);
}
},
});
var THUMB_URLS = [
@@ -119,14 +126,15 @@ var THUMB_URLS = [
require('./Thumbnails/poke.png'),
require('./Thumbnails/superlike.png'),
require('./Thumbnails/victory.png'),
];
var LOREM_IPSUM = 'Lorem ipsum dolor sit amet, ius ad pertinax oportere accommodare, an vix civibus corrumpit referrentur. Te nam case ludus inciderint, te mea facilisi adipiscing. Sea id integre luptatum. In tota sale consequuntur nec. Erat ocurreret mei ei. Eu paulo sapientem vulputate est, vel an accusam intellegam interesset. Nam eu stet pericula reprimique, ea vim illud modus, putant invidunt reprehendunt ne qui.';
];
var LOREM_IPSUM =
'Lorem ipsum dolor sit amet, ius ad pertinax oportere accommodare, an vix civibus corrumpit referrentur. Te nam case ludus inciderint, te mea facilisi adipiscing. Sea id integre luptatum. In tota sale consequuntur nec. Erat ocurreret mei ei. Eu paulo sapientem vulputate est, vel an accusam intellegam interesset. Nam eu stet pericula reprimique, ea vim illud modus, putant invidunt reprehendunt ne qui.';
/* eslint no-bitwise: 0 */
var hashCode = function(str) {
var hash = 15;
for (var ii = str.length - 1; ii >= 0; ii--) {
hash = ((hash << 5) - hash) + str.charCodeAt(ii);
hash = (hash << 5) - hash + str.charCodeAt(ii);
}
return hash;
};

View File

@@ -4,21 +4,16 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var createReactClass = require('create-react-class');
var ReactNative = require('react-native');
var {
Image,
ListView,
TouchableHighlight,
StyleSheet,
Text,
View,
} = ReactNative;
var {Image, ListView, TouchableHighlight, StyleSheet, Text, View} = ReactNative;
var THUMB_URLS = [
require('./Thumbnails/like.png'),
@@ -40,7 +35,7 @@ var ListViewGridLayoutExample = createReactClass({
statics: {
title: '<ListView> - Grid Layout',
description: 'Flexbox grid layout.'
description: 'Flexbox grid layout.',
},
getInitialState: function() {
@@ -75,13 +70,13 @@ var ListViewGridLayoutExample = createReactClass({
var rowHash = Math.abs(hashCode(rowData));
var imgSource = THUMB_URLS[rowHash % THUMB_URLS.length];
return (
<TouchableHighlight onPress={() => this._pressRow(rowID)} underlayColor="transparent">
<TouchableHighlight
onPress={() => this._pressRow(rowID)}
underlayColor="transparent">
<View>
<View style={styles.row}>
<Image style={styles.thumb} source={imgSource} />
<Text style={styles.text}>
{rowData}
</Text>
<Text style={styles.text}>{rowData}</Text>
</View>
</View>
</TouchableHighlight>
@@ -99,9 +94,11 @@ var ListViewGridLayoutExample = createReactClass({
_pressRow: function(rowID: number) {
this._pressData[rowID] = !this._pressData[rowID];
this.setState({dataSource: this.state.dataSource.cloneWithRows(
this._genRows(this._pressData)
)});
this.setState({
dataSource: this.state.dataSource.cloneWithRows(
this._genRows(this._pressData),
),
});
},
});
@@ -109,7 +106,7 @@ var ListViewGridLayoutExample = createReactClass({
var hashCode = function(str) {
var hash = 15;
for (var ii = str.length - 1; ii >= 0; ii--) {
hash = ((hash << 5) - hash) + str.charCodeAt(ii);
hash = (hash << 5) - hash + str.charCodeAt(ii);
}
return hash;
};
@@ -119,7 +116,7 @@ var styles = StyleSheet.create({
justifyContent: 'space-around',
flexDirection: 'row',
flexWrap: 'wrap',
alignItems: 'flex-start'
alignItems: 'flex-start',
},
row: {
justifyContent: 'center',
@@ -131,16 +128,16 @@ var styles = StyleSheet.create({
alignItems: 'center',
borderWidth: 1,
borderRadius: 5,
borderColor: '#CCC'
borderColor: '#CCC',
},
thumb: {
width: 64,
height: 64
height: 64,
},
text: {
flex: 1,
marginTop: 5,
fontWeight: 'bold'
fontWeight: 'bold',
},
});

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
@@ -21,9 +23,7 @@ var {
} = ReactNative;
var NativeModules = require('NativeModules');
var {
UIManager,
} = NativeModules;
var {UIManager} = NativeModules;
var THUMB_URLS = [
require('./Thumbnails/like.png'),
@@ -53,7 +53,10 @@ class Thumb extends React.Component<{}, $FlowFixMeState> {
};
_onPressThumb = () => {
var config = layoutAnimationConfigs[this.state.thumbIndex % layoutAnimationConfigs.length];
var config =
layoutAnimationConfigs[
this.state.thumbIndex % layoutAnimationConfigs.length
];
LayoutAnimation.configureNext(config);
this.setState({
thumbIndex: this._getThumbIdx(),
@@ -71,13 +74,14 @@ class Thumb extends React.Component<{}, $FlowFixMeState> {
<Image style={styles.img} source={THUMB_URLS[this.state.thumbIndex]} />
<Image style={styles.img} source={THUMB_URLS[this.state.thumbIndex]} />
<Image style={styles.img} source={THUMB_URLS[this.state.thumbIndex]} />
{this.state.dir === 'column' ?
{this.state.dir === 'column' ? (
<Text>
Oooo, look at this new text! So awesome it may just be crazy.
Let me keep typing here so it wraps at least one line.
</Text> :
Oooo, look at this new text! So awesome it may just be crazy. Let me
keep typing here so it wraps at least one line.
</Text>
) : (
<Text />
}
)}
</TouchableOpacity>
);
}
@@ -121,36 +125,43 @@ class ListViewPagingExample extends React.Component<$FlowFixMeProps, *> {
}
this.state = {
dataSource: dataSource.cloneWithRowsAndSections(dataBlob, sectionIDs, rowIDs),
dataSource: dataSource.cloneWithRowsAndSections(
dataBlob,
sectionIDs,
rowIDs,
),
headerPressCount: 0,
};
}
renderRow = (rowData: string, sectionID: string, rowID: string): React.Element<any> => {
return (<Thumb text={rowData}/>);
renderRow = (
rowData: string,
sectionID: string,
rowID: string,
): React.Element<any> => {
return <Thumb text={rowData} />;
};
renderSectionHeader = (sectionData: string, sectionID: string) => {
return (
<View style={styles.section}>
<Text style={styles.text}>
{sectionData}
</Text>
<Text style={styles.text}>{sectionData}</Text>
</View>
);
};
renderHeader = () => {
var headerLikeText = this.state.headerPressCount % 2 ?
<View><Text style={styles.text}>1 Like</Text></View> :
null;
var headerLikeText =
this.state.headerPressCount % 2 ? (
<View>
<Text style={styles.text}>1 Like</Text>
</View>
) : null;
return (
<TouchableOpacity onPress={this._onPressHeader} style={styles.header}>
{headerLikeText}
<View>
<Text style={styles.text}>
Table Header (click me)
</Text>
<Text style={styles.text}>Table Header (click me)</Text>
</View>
</TouchableOpacity>
);
@@ -171,7 +182,9 @@ class ListViewPagingExample extends React.Component<$FlowFixMeProps, *> {
<ListView
style={styles.listview}
dataSource={this.state.dataSource}
onChangeVisibleRows={(visibleRows, changedRows) => console.log({visibleRows, changedRows})}
onChangeVisibleRows={(visibleRows, changedRows) =>
console.log({visibleRows, changedRows})
}
renderHeader={this.renderHeader}
renderFooter={this.renderFooter}
renderSectionHeader={this.renderSectionHeader}
@@ -185,7 +198,11 @@ class ListViewPagingExample extends React.Component<$FlowFixMeProps, *> {
}
_onPressHeader = () => {
var config = layoutAnimationConfigs[Math.floor(this.state.headerPressCount / 2) % layoutAnimationConfigs.length];
var config =
layoutAnimationConfigs[
Math.floor(this.state.headerPressCount / 2) %
layoutAnimationConfigs.length
];
LayoutAnimation.configureNext(config);
this.setState({headerPressCount: this.state.headerPressCount + 1});
};

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
@@ -50,7 +52,7 @@ class MaskedViewExample extends React.Component<{}, $FlowFixMeState> {
timing: 750,
useNativeDriver: true,
}),
])
]),
).start();
Animated.loop(
@@ -58,7 +60,7 @@ class MaskedViewExample extends React.Component<{}, $FlowFixMeState> {
toValue: 360,
timing: 2000,
useNativeDriver: true,
})
}),
).start();
}
@@ -66,18 +68,16 @@ class MaskedViewExample extends React.Component<{}, $FlowFixMeState> {
return (
<RNTesterPage title="<MaskedViewIOS>">
<RNTesterBlock title="Basic Mask">
<View style={{ width: 300, height: 300, alignSelf: 'center' }}>
<View style={{width: 300, height: 300, alignSelf: 'center'}}>
<MaskedViewIOS
style={{ flex: 1 }}
style={{flex: 1}}
maskElement={
<View style={styles.maskContainerStyle}>
<Text style={styles.maskTextStyle}>
Basic Mask
</Text>
<Text style={styles.maskTextStyle}>Basic Mask</Text>
</View>
}>
<View style={{ flex: 1, backgroundColor: 'blue' }} />
<View style={{ flex: 1, backgroundColor: 'red' }} />
<View style={{flex: 1, backgroundColor: 'blue'}} />
<View style={{flex: 1, backgroundColor: 'red'}} />
</MaskedViewIOS>
</View>
</RNTesterBlock>
@@ -90,11 +90,11 @@ class MaskedViewExample extends React.Component<{}, $FlowFixMeState> {
backgroundColor: '#eeeeee',
}}>
<MaskedViewIOS
style={{ flex: 1 }}
style={{flex: 1}}
maskElement={
<View style={styles.maskContainerStyle}>
<Image
style={{ height: 200, width: 200 }}
style={{height: 200, width: 200}}
source={require('./imageMask.png')}
/>
</View>
@@ -102,7 +102,7 @@ class MaskedViewExample extends React.Component<{}, $FlowFixMeState> {
<View style={styles.maskContainerStyle}>
<Image
resizeMode="cover"
style={{ width: 200, height: 200 }}
style={{width: 200, height: 200}}
source={{
uri:
'https://38.media.tumblr.com/9e9bd08c6e2d10561dd1fb4197df4c4e/tumblr_mfqekpMktw1rn90umo1_500.gif',
@@ -113,18 +113,16 @@ class MaskedViewExample extends React.Component<{}, $FlowFixMeState> {
</View>
</RNTesterBlock>
<RNTesterBlock title="Animated Mask">
<View style={{ width: 300, height: 300, alignSelf: 'center' }}>
<View style={{width: 300, height: 300, alignSelf: 'center'}}>
<MaskedViewIOS
style={{ flex: 1 }}
style={{flex: 1}}
maskElement={
<Animated.View
style={[
styles.maskContainerStyle,
{ transform: [{ scale: this._maskScaleAnimatedValue }] },
{transform: [{scale: this._maskScaleAnimatedValue}]},
]}>
<Text style={styles.maskTextStyle}>
Basic Mask
</Text>
<Text style={styles.maskTextStyle}>Basic Mask</Text>
</Animated.View>
}>
<Animated.View
@@ -139,33 +137,25 @@ class MaskedViewExample extends React.Component<{}, $FlowFixMeState> {
},
],
}}>
<View style={{ flex: 1, backgroundColor: 'blue' }} />
<View style={{ flex: 1, backgroundColor: 'red' }} />
<View style={{flex: 1, backgroundColor: 'blue'}} />
<View style={{flex: 1, backgroundColor: 'red'}} />
</Animated.View>
</MaskedViewIOS>
</View>
</RNTesterBlock>
<RNTesterBlock title="Mask w/ Changing Children">
<View style={{ width: 300, height: 300, alignSelf: 'center' }}>
<View style={{width: 300, height: 300, alignSelf: 'center'}}>
<MaskedViewIOS
style={{ flex: 1 }}
style={{flex: 1}}
maskElement={
<View style={styles.maskContainerStyle}>
<Text style={styles.maskTextStyle}>
Basic Mask
</Text>
<Text style={styles.maskTextStyle}>Basic Mask</Text>
</View>
}>
{this.state.alternateChildren
? [
<View
key={1}
style={{ flex: 1, backgroundColor: 'blue' }}
/>,
<View
key={2}
style={{ flex: 1, backgroundColor: 'red' }}
/>,
<View key={1} style={{flex: 1, backgroundColor: 'blue'}} />,
<View key={2} style={{flex: 1, backgroundColor: 'red'}} />,
]
: null}
</MaskedViewIOS>

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
@@ -52,7 +54,9 @@ class Button extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
onShowUnderlay={this._onHighlight}
style={[styles.button, this.props.style]}
underlayColor="#a9d9d4">
<Text style={[styles.buttonText, colorStyle]}>{this.props.children}</Text>
<Text style={[styles.buttonText, colorStyle]}>
{this.props.children}
</Text>
</TouchableHighlight>
);
}
@@ -77,11 +81,11 @@ class ModalExample extends React.Component<{}, $FlowFixMeState> {
currentOrientation: 'unknown',
};
_setModalVisible = (visible) => {
_setModalVisible = visible => {
this.setState({modalVisible: visible});
};
_setAnimationType = (type) => {
_setAnimationType = type => {
this.setState({animationType: type});
};
@@ -94,19 +98,24 @@ class ModalExample extends React.Component<{}, $FlowFixMeState> {
return null;
}
return (
<Switch value={this.state.transparent} onValueChange={this._toggleTransparent} />
<Switch
value={this.state.transparent}
onValueChange={this._toggleTransparent}
/>
);
}
render() {
var modalBackgroundStyle = {
backgroundColor: this.state.transparent ? 'rgba(0, 0, 0, 0.5)' : '#f5fcff',
backgroundColor: this.state.transparent
? 'rgba(0, 0, 0, 0.5)'
: '#f5fcff',
};
var innerContainerTransparentStyle = this.state.transparent
? {backgroundColor: '#fff', padding: 20}
: null;
var activeButtonStyle = {
backgroundColor: '#ddd'
backgroundColor: '#ddd',
};
return (
@@ -117,13 +126,26 @@ class ModalExample extends React.Component<{}, $FlowFixMeState> {
transparent={this.state.transparent}
visible={this.state.modalVisible}
onRequestClose={() => this._setModalVisible(false)}
supportedOrientations={supportedOrientationsPickerValues[this.state.selectedSupportedOrientation]}
onOrientationChange={evt => this.setState({currentOrientation: evt.nativeEvent.orientation})}
>
supportedOrientations={
supportedOrientationsPickerValues[
this.state.selectedSupportedOrientation
]
}
onOrientationChange={evt =>
this.setState({currentOrientation: evt.nativeEvent.orientation})
}>
<View style={[styles.container, modalBackgroundStyle]}>
<View style={[styles.innerContainer, innerContainerTransparentStyle]}>
<Text>This modal was presented {this.state.animationType === 'none' ? 'without' : 'with'} animation.</Text>
<Text>It is currently displayed in {this.state.currentOrientation} mode.</Text>
<View
style={[styles.innerContainer, innerContainerTransparentStyle]}>
<Text>
This modal was presented{' '}
{this.state.animationType === 'none' ? 'without' : 'with'}{' '}
animation.
</Text>
<Text>
It is currently displayed in {this.state.currentOrientation}{' '}
mode.
</Text>
<Button
onPress={this._setModalVisible.bind(this, false)}
style={styles.modalButton}>
@@ -134,13 +156,25 @@ class ModalExample extends React.Component<{}, $FlowFixMeState> {
</Modal>
<View style={styles.row}>
<Text style={styles.rowTitle}>Animation Type</Text>
<Button onPress={this._setAnimationType.bind(this, 'none')} style={this.state.animationType === 'none' ? activeButtonStyle : {}}>
<Button
onPress={this._setAnimationType.bind(this, 'none')}
style={
this.state.animationType === 'none' ? activeButtonStyle : {}
}>
none
</Button>
<Button onPress={this._setAnimationType.bind(this, 'slide')} style={this.state.animationType === 'slide' ? activeButtonStyle : {}}>
<Button
onPress={this._setAnimationType.bind(this, 'slide')}
style={
this.state.animationType === 'slide' ? activeButtonStyle : {}
}>
slide
</Button>
<Button onPress={this._setAnimationType.bind(this, 'fade')} style={this.state.animationType === 'fade' ? activeButtonStyle : {}}>
<Button
onPress={this._setAnimationType.bind(this, 'fade')}
style={
this.state.animationType === 'fade' ? activeButtonStyle : {}
}>
fade
</Button>
</View>
@@ -166,9 +200,10 @@ class ModalExample extends React.Component<{}, $FlowFixMeState> {
<Text style={styles.rowTitle}>Presentation style</Text>
<Picker
selectedValue={this.state.presentationStyle}
onValueChange={(presentationStyle) => this.setState({presentationStyle})}
itemStyle={styles.pickerItem}
>
onValueChange={presentationStyle =>
this.setState({presentationStyle})
}
itemStyle={styles.pickerItem}>
<Item label="Full Screen" value="fullScreen" />
<Item label="Page Sheet" value="pageSheet" />
<Item label="Form Sheet" value="formSheet" />
@@ -181,9 +216,10 @@ class ModalExample extends React.Component<{}, $FlowFixMeState> {
<Text style={styles.rowTitle}>Supported orientations</Text>
<Picker
selectedValue={this.state.selectedSupportedOrientation}
onValueChange={(_, i) => this.setState({selectedSupportedOrientation: i})}
itemStyle={styles.pickerItem}
>
onValueChange={(_, i) =>
this.setState({selectedSupportedOrientation: i})
}
itemStyle={styles.pickerItem}>
<Item label="Portrait" value={0} />
<Item label="Landscape" value={1} />
<Item label="Landscape left" value={2} />
@@ -197,7 +233,6 @@ class ModalExample extends React.Component<{}, $FlowFixMeState> {
}
}
exports.examples = [
{
title: 'Modal Presentation',

View File

@@ -4,18 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
const ReactNative = require('react-native');
const {
FlatList,
StyleSheet,
Text,
View,
} = ReactNative;
const {FlatList, StyleSheet, Text, View} = ReactNative;
const RNTesterPage = require('./RNTesterPage');
@@ -33,7 +30,10 @@ const {
renderSmallSwitchOption,
} = require('./ListExampleShared');
class MultiColumnExample extends React.PureComponent<$FlowFixMeProps, $FlowFixMeState> {
class MultiColumnExample extends React.PureComponent<
$FlowFixMeProps,
$FlowFixMeState,
> {
static title = '<FlatList> - MultiColumn';
static description = 'Performant, scrollable grid of data.';
@@ -45,15 +45,16 @@ class MultiColumnExample extends React.PureComponent<$FlowFixMeProps, $FlowFixMe
numColumns: 2,
virtualized: true,
};
_onChangeFilterText = (filterText) => {
_onChangeFilterText = filterText => {
this.setState(() => ({filterText}));
};
_onChangeNumColumns = (numColumns) => {
_onChangeNumColumns = numColumns => {
this.setState(() => ({numColumns: Number(numColumns)}));
};
render() {
const filterRegex = new RegExp(String(this.state.filterText), 'i');
const filter = (item) => (filterRegex.test(item.text) || filterRegex.test(item.title));
const filter = item =>
filterRegex.test(item.text) || filterRegex.test(item.title);
const filteredData = this.state.data.filter(filter);
return (
<RNTesterPage
@@ -67,7 +68,7 @@ class MultiColumnExample extends React.PureComponent<$FlowFixMeProps, $FlowFixMe
placeholder="Search..."
value={this.state.filterText}
/>
<Text> numColumns: </Text>
<Text> numColumns: </Text>
<PlainInput
clearButtonMode="never"
onChangeText={this._onChangeNumColumns}
@@ -84,7 +85,9 @@ class MultiColumnExample extends React.PureComponent<$FlowFixMeProps, $FlowFixMe
<FlatList
ListFooterComponent={FooterComponent}
ListHeaderComponent={HeaderComponent}
getItemLayout={this.state.fixedHeight ? this._getItemLayout : undefined}
getItemLayout={
this.state.fixedHeight ? this._getItemLayout : undefined
}
data={filteredData}
key={this.state.numColumns + (this.state.fixedHeight ? 'f' : 'v')}
numColumns={this.state.numColumns || 1}
@@ -98,8 +101,12 @@ class MultiColumnExample extends React.PureComponent<$FlowFixMeProps, $FlowFixMe
</RNTesterPage>
);
}
_getItemLayout(data: any, index: number): {length: number, offset: number, index: number} {
const length = getItemLayout(data, index).length + 2 * (CARD_MARGIN + BORDER_WIDTH);
_getItemLayout(
data: any,
index: number,
): {length: number, offset: number, index: number} {
const length =
getItemLayout(data, index).length + 2 * (CARD_MARGIN + BORDER_WIDTH);
return {length, offset: length * index, index};
}
_renderItemComponent = ({item}) => {
@@ -116,12 +123,19 @@ class MultiColumnExample extends React.PureComponent<$FlowFixMeProps, $FlowFixMe
// This is called when items change viewability by scrolling into or out of the viewable area.
_onViewableItemsChanged = (info: {
changed: Array<{
key: string, isViewable: boolean, item: {columns: Array<*>}, index: ?number, section?: any
}>},
) => {
key: string,
isViewable: boolean,
item: {columns: Array<*>},
index: ?number,
section?: any,
}>,
}) => {
// Impressions can be logged here
if (this.state.logViewable) {
infoLog('onViewableItemsChanged: ', info.changed.map((v) => ({...v, item: '...'})));
infoLog(
'onViewableItemsChanged: ',
info.changed.map(v => ({...v, item: '...'})),
);
}
};
_pressItem = (key: string) => {

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
@@ -30,9 +32,10 @@ class Tester extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
current = 0;
onPress = () => {
const animConfig = this.current && this.props.reverseConfig
? this.props.reverseConfig
: this.props.config;
const animConfig =
this.current && this.props.reverseConfig
? this.props.reverseConfig
: this.props.config;
this.current = this.current ? 0 : 1;
const config: Object = {
...animConfig,
@@ -62,9 +65,7 @@ class Tester extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
<View>
<Text>JavaScript:</Text>
</View>
<View style={styles.row}>
{this.props.children(this.state.js)}
</View>
<View style={styles.row}>{this.props.children(this.state.js)}</View>
</View>
</TouchableWithoutFeedback>
);
@@ -155,7 +156,10 @@ class LoopExample extends React.Component<{}, $FlowFixMeState> {
}
const RNTesterSettingSwitchRow = require('RNTesterSettingSwitchRow');
class InternalSettings extends React.Component<{}, {busyTime: number | string, filteredStall: number}> {
class InternalSettings extends React.Component<
{},
{busyTime: number | string, filteredStall: number},
> {
_stallInterval: ?number;
render() {
return (
@@ -170,8 +174,7 @@ class InternalSettings extends React.Component<{}, {busyTime: number | string, f
this._stallInterval = setInterval(() => {
const start = Date.now();
console.warn('burn CPU');
while (Date.now() - start < 100) {
}
while (Date.now() - start < 100) {}
}, 300);
}}
onDisable={() => {
@@ -191,8 +194,8 @@ class InternalSettings extends React.Component<{}, {busyTime: number | string, f
onStall: ({busyTime}) =>
this.setState(state => ({
busyTime,
filteredStall: (state.filteredStall || 0) * 0.97 +
busyTime * 0.03,
filteredStall:
(state.filteredStall || 0) * 0.97 + busyTime * 0.03,
})),
});
}}
@@ -200,11 +203,12 @@ class InternalSettings extends React.Component<{}, {busyTime: number | string, f
console.warn('Cannot disable yet....');
}}
/>
{this.state &&
{this.state && (
<Text>
{`JS Stall filtered: ${Math.round(this.state.filteredStall)}, `}
{`last: ${this.state.busyTime}`}
</Text>}
</Text>
)}
</View>
);
}
@@ -252,7 +256,10 @@ class EventExample extends React.Component<{}, $FlowFixMeState> {
}
}
class TrackingExample extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
class TrackingExample extends React.Component<
$FlowFixMeProps,
$FlowFixMeState,
> {
state = {
native: new Animated.Value(0),
toNative: new Animated.Value(0),
@@ -287,9 +294,15 @@ class TrackingExample extends React.Component<$FlowFixMeProps, $FlowFixMeState>
};
renderBlock = (anim, dest) => [
<Animated.View key="line" style={[styles.line, { transform: [{ translateX: dest }]}]}/>,
<Animated.View key="block" style={[styles.block, { transform: [{ translateX: anim }]}]}/>,
]
<Animated.View
key="line"
style={[styles.line, {transform: [{translateX: dest}]}]}
/>,
<Animated.View
key="block"
style={[styles.block, {transform: [{translateX: anim}]}]}
/>,
];
render() {
return (
@@ -572,7 +585,7 @@ exports.examples = [
title: 'translateX => Animated.spring (stiffness/damping/mass)',
render: function() {
return (
<Tester type="spring" config={{stiffness: 1000, damping: 500, mass: 3 }}>
<Tester type="spring" config={{stiffness: 1000, damping: 500, mass: 3}}>
{anim => (
<Animated.View
style={[

View File

@@ -16,19 +16,14 @@
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @format
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
NavigatorIOS,
StatusBar,
StyleSheet,
Text,
View
} = ReactNative;
var {NavigatorIOS, StatusBar, StyleSheet, Text, View} = ReactNative;
class EmptyPage extends React.Component<{
text: string,
@@ -36,9 +31,7 @@ class EmptyPage extends React.Component<{
render() {
return (
<View style={styles.emptyPage}>
<Text style={styles.emptyPageText}>
{this.props.text}
</Text>
<Text style={styles.emptyPageText}>{this.props.text}</Text>
</View>
);
}

View File

@@ -4,26 +4,20 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
NavigatorIOS,
StatusBar,
StyleSheet,
Text,
View
} = ReactNative;
var {NavigatorIOS, StatusBar, StyleSheet, Text, View} = ReactNative;
class EmptyPage extends React.Component {
render() {
return (
<View style={styles.emptyPage}>
<Text style={styles.emptyPageText}>
{this.props.text}
</Text>
<Text style={styles.emptyPageText}>{this.props.text}</Text>
</View>
);
}
@@ -49,7 +43,8 @@ class NavigatorIOSColors extends React.Component {
this.props.onExampleExit();
},
passProps: {
text: 'The nav bar has custom colors with tintColor, ' +
text:
'The nav bar has custom colors with tintColor, ' +
'barTintColor and titleTextColor props.',
},
}}

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
@@ -28,9 +30,7 @@ class EmptyPage extends React.Component<$FlowFixMeProps> {
render() {
return (
<View style={styles.emptyPage}>
<Text style={styles.emptyPageText}>
{this.props.text}
</Text>
<Text style={styles.emptyPageText}>{this.props.text}</Text>
</View>
);
}
@@ -44,7 +44,7 @@ class NavigatorIOSExamplePage extends React.Component<$FlowFixMeProps> {
}
return (
<ScrollView style={styles.list}>
<View style={styles.line}/>
<View style={styles.line} />
<View style={styles.group}>
{this._renderRow(recurseTitle, () => {
this.props.navigator.push({
@@ -75,7 +75,7 @@ class NavigatorIOSExamplePage extends React.Component<$FlowFixMeProps> {
onRightButtonPress: () => this.props.navigator.pop(),
passProps: {
text: 'This page has a right button in the nav bar',
}
},
});
})}
{this._renderRow('Custom Right System Button', () => {
@@ -86,7 +86,7 @@ class NavigatorIOSExamplePage extends React.Component<$FlowFixMeProps> {
onRightButtonPress: () => this.props.navigator.pop(),
passProps: {
text: 'This page has a right system button in the nav bar',
}
},
});
})}
{this._renderRow('Custom Left & Right Icons', () => {
@@ -98,7 +98,7 @@ class NavigatorIOSExamplePage extends React.Component<$FlowFixMeProps> {
rightButtonIcon: nativeImageSource({
ios: 'NavBarButtonPlus',
width: 17,
height: 17
height: 17,
}),
onRightButtonPress: () => {
AlertIOS.alert(
@@ -109,12 +109,13 @@ class NavigatorIOSExamplePage extends React.Component<$FlowFixMeProps> {
text: 'OK',
onPress: () => console.log('Tapped OK'),
},
]
],
);
},
passProps: {
text: 'This page has an icon for the right button in the nav bar',
}
text:
'This page has an icon for the right button in the nav bar',
},
});
})}
{this._renderRow('Custom Left & Right System Icons', () => {
@@ -133,12 +134,13 @@ class NavigatorIOSExamplePage extends React.Component<$FlowFixMeProps> {
text: 'OK',
onPress: () => console.log('Tapped OK'),
},
]
],
);
},
passProps: {
text: 'This page has an icon for the right button in the nav bar',
}
text:
'This page has an icon for the right button in the nav bar',
},
});
})}
{this._renderRow('Pop', () => {
@@ -150,9 +152,12 @@ class NavigatorIOSExamplePage extends React.Component<$FlowFixMeProps> {
{this._renderReplace()}
{this._renderReplacePrevious()}
{this._renderReplacePreviousAndPop()}
{this._renderRow('Exit NavigatorIOS Example', this.props.onExampleExit)}
{this._renderRow(
'Exit NavigatorIOS Example',
this.props.onExampleExit,
)}
</View>
<View style={styles.line}/>
<View style={styles.line} />
</ScrollView>
);
}
@@ -170,9 +175,10 @@ class NavigatorIOSExamplePage extends React.Component<$FlowFixMeProps> {
rightButtonTitle: 'Undo',
onRightButtonPress: () => this.props.navigator.replace(prevRoute),
passProps: {
text: 'The component is replaced, but there is currently no ' +
text:
'The component is replaced, but there is currently no ' +
'way to change the right button or title of the current route',
}
},
});
});
};
@@ -216,9 +222,7 @@ class NavigatorIOSExamplePage extends React.Component<$FlowFixMeProps> {
<View>
<TouchableHighlight onPress={onPress}>
<View style={styles.row}>
<Text style={styles.rowText}>
{title}
</Text>
<Text style={styles.rowText}>{title}</Text>
</View>
</TouchableHighlight>
<View style={styles.separator} />

View File

@@ -4,18 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
const ReactNative = require('react-native');
const {
NetInfo,
Text,
View,
TouchableWithoutFeedback,
} = ReactNative;
const {NetInfo, Text, View, TouchableWithoutFeedback} = ReactNative;
class ConnectionInfoSubscription extends React.Component<{}, $FlowFixMeState> {
state = {
@@ -23,20 +20,14 @@ class ConnectionInfoSubscription extends React.Component<{}, $FlowFixMeState> {
};
componentDidMount() {
NetInfo.addEventListener(
'change',
this._handleConnectionInfoChange
);
NetInfo.addEventListener('change', this._handleConnectionInfoChange);
}
componentWillUnmount() {
NetInfo.removeEventListener(
'change',
this._handleConnectionInfoChange
);
NetInfo.removeEventListener('change', this._handleConnectionInfoChange);
}
_handleConnectionInfoChange = (connectionInfo) => {
_handleConnectionInfoChange = connectionInfo => {
const connectionInfoHistory = this.state.connectionInfoHistory.slice();
connectionInfoHistory.push(connectionInfo);
this.setState({
@@ -46,9 +37,9 @@ class ConnectionInfoSubscription extends React.Component<{}, $FlowFixMeState> {
render() {
return (
<View>
<Text>{JSON.stringify(this.state.connectionInfoHistory)}</Text>
</View>
<View>
<Text>{JSON.stringify(this.state.connectionInfoHistory)}</Text>
</View>
);
}
}
@@ -59,23 +50,17 @@ class ConnectionInfoCurrent extends React.Component<{}, $FlowFixMeState> {
};
componentDidMount() {
NetInfo.addEventListener(
'change',
this._handleConnectionInfoChange
);
NetInfo.fetch().done(
(connectionInfo) => { this.setState({connectionInfo}); }
);
NetInfo.addEventListener('change', this._handleConnectionInfoChange);
NetInfo.fetch().done(connectionInfo => {
this.setState({connectionInfo});
});
}
componentWillUnmount() {
NetInfo.removeEventListener(
'change',
this._handleConnectionInfoChange
);
NetInfo.removeEventListener('change', this._handleConnectionInfoChange);
}
_handleConnectionInfoChange = (connectionInfo) => {
_handleConnectionInfoChange = connectionInfo => {
this.setState({
connectionInfo,
});
@@ -83,9 +68,9 @@ class ConnectionInfoCurrent extends React.Component<{}, $FlowFixMeState> {
render() {
return (
<View>
<Text>{this.state.connectionInfo}</Text>
</View>
<View>
<Text>{this.state.connectionInfo}</Text>
</View>
);
}
}
@@ -97,22 +82,22 @@ class IsConnected extends React.Component<{}, $FlowFixMeState> {
componentDidMount() {
NetInfo.isConnected.addEventListener(
'change',
this._handleConnectivityChange
);
NetInfo.isConnected.fetch().done(
(isConnected) => { this.setState({isConnected}); }
'change',
this._handleConnectivityChange,
);
NetInfo.isConnected.fetch().done(isConnected => {
this.setState({isConnected});
});
}
componentWillUnmount() {
NetInfo.isConnected.removeEventListener(
'change',
this._handleConnectivityChange
'change',
this._handleConnectivityChange,
);
}
_handleConnectivityChange = (isConnected) => {
_handleConnectivityChange = isConnected => {
this.setState({
isConnected,
});
@@ -120,37 +105,40 @@ class IsConnected extends React.Component<{}, $FlowFixMeState> {
render() {
return (
<View>
<Text>{this.state.isConnected ? 'Online' : 'Offline'}</Text>
</View>
<View>
<Text>{this.state.isConnected ? 'Online' : 'Offline'}</Text>
</View>
);
}
}
class IsConnectionExpensive extends React.Component<{}, $FlowFixMeState> {
state = {
isConnectionExpensive: (null : ?boolean),
isConnectionExpensive: (null: ?boolean),
};
_checkIfExpensive = () => {
NetInfo.isConnectionExpensive().then(
isConnectionExpensive => { this.setState({isConnectionExpensive}); }
);
NetInfo.isConnectionExpensive().then(isConnectionExpensive => {
this.setState({isConnectionExpensive});
});
};
render() {
return (
<View>
<TouchableWithoutFeedback onPress={this._checkIfExpensive}>
<View>
<Text>Click to see if connection is expensive:
{this.state.isConnectionExpensive === true ? 'Expensive' :
this.state.isConnectionExpensive === false ? 'Not expensive'
: 'Unknown'}
</Text>
</View>
</TouchableWithoutFeedback>
</View>
<View>
<TouchableWithoutFeedback onPress={this._checkIfExpensive}>
<View>
<Text>
Click to see if connection is expensive:
{this.state.isConnectionExpensive === true
? 'Expensive'
: this.state.isConnectionExpensive === false
? 'Not expensive'
: 'Unknown'}
</Text>
</View>
</TouchableWithoutFeedback>
</View>
);
}
}
@@ -161,22 +149,30 @@ exports.examples = [
{
title: 'NetInfo.isConnected',
description: 'Asynchronously load and observe connectivity',
render(): React.Element<any> { return <IsConnected />; }
render(): React.Element<any> {
return <IsConnected />;
},
},
{
title: 'NetInfo.update',
description: 'Asynchronously load and observe connectionInfo',
render(): React.Element<any> { return <ConnectionInfoCurrent />; }
render(): React.Element<any> {
return <ConnectionInfoCurrent />;
},
},
{
title: 'NetInfo.updateHistory',
description: 'Observed updates to connectionInfo',
render(): React.Element<any> { return <ConnectionInfoSubscription />; }
render(): React.Element<any> {
return <ConnectionInfoSubscription />;
},
},
{
platform: 'android',
title: 'NetInfo.isConnectionExpensive (Android)',
description: 'Asynchronously check isConnectionExpensive',
render(): React.Element<any> { return <IsConnectionExpensive />; }
render(): React.Element<any> {
return <IsConnectionExpensive />;
},
},
];

View File

@@ -4,17 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
const ReactNative = require('react-native');
const {
DeviceEventEmitter,
Text,
View,
} = ReactNative;
const {DeviceEventEmitter, Text, View} = ReactNative;
import type EmitterSubscription from 'EmitterSubscription';
@@ -29,7 +27,8 @@ class OrientationChangeExample extends React.Component<{}, $FlowFixMeState> {
componentDidMount() {
this._orientationSubscription = DeviceEventEmitter.addListener(
'namedOrientationDidChange', this._onOrientationChange,
'namedOrientationDidChange',
this._onOrientationChange,
);
}
@@ -43,7 +42,7 @@ class OrientationChangeExample extends React.Component<{}, $FlowFixMeState> {
orientationDegrees: orientation.rotationDegrees,
isLandscape: orientation.isLandscape,
});
}
};
render() {
return (
@@ -60,6 +59,8 @@ exports.examples = [
{
title: 'OrientationChangeExample',
description: 'listening to device orientation changes',
render() { return <OrientationChangeExample />; },
render() {
return <OrientationChangeExample />;
},
},
];

View File

@@ -4,18 +4,16 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow weak
*/
'use strict';
var React = require('react');
var createReactClass = require('create-react-class');
var ReactNative = require('react-native');
var {
PanResponder,
StyleSheet,
View,
} = ReactNative;
var {PanResponder, StyleSheet, View} = ReactNative;
var CIRCLE_SIZE = 80;
@@ -24,14 +22,15 @@ var PanResponderExample = createReactClass({
statics: {
title: 'PanResponder Sample',
description: 'Shows the use of PanResponder to provide basic gesture handling.',
description:
'Shows the use of PanResponder to provide basic gesture handling.',
},
_panResponder: {},
_previousLeft: 0,
_previousTop: 0,
_circleStyles: {},
circle: (null : ?{ setNativeProps(props: Object): void }),
circle: (null: ?{setNativeProps(props: Object): void}),
UNSAFE_componentWillMount: function() {
this._panResponder = PanResponder.create({
@@ -49,7 +48,7 @@ var PanResponderExample = createReactClass({
left: this._previousLeft,
top: this._previousTop,
backgroundColor: 'green',
}
},
};
},
@@ -59,10 +58,9 @@ var PanResponderExample = createReactClass({
render: function() {
return (
<View
style={styles.container}>
<View style={styles.container}>
<View
ref={(circle) => {
ref={circle => {
this.circle = circle;
}}
style={styles.circle}
@@ -86,12 +84,18 @@ var PanResponderExample = createReactClass({
this.circle && this.circle.setNativeProps(this._circleStyles);
},
_handleStartShouldSetPanResponder: function(e: Object, gestureState: Object): boolean {
_handleStartShouldSetPanResponder: function(
e: Object,
gestureState: Object,
): boolean {
// Should we become active when the user presses down on the circle?
return true;
},
_handleMoveShouldSetPanResponder: function(e: Object, gestureState: Object): boolean {
_handleMoveShouldSetPanResponder: function(
e: Object,
gestureState: Object,
): boolean {
// Should we become active when the user moves a touch over the circle?
return true;
},

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
@@ -40,19 +42,34 @@ class PermissionsExample extends React.Component<{}, $FlowFixMeState> {
style={styles.picker}
selectedValue={this.state.permission}
onValueChange={this._onSelectPermission.bind(this)}>
<Item label={PermissionsAndroid.PERMISSIONS.CAMERA} value={PermissionsAndroid.PERMISSIONS.CAMERA} />
<Item label={PermissionsAndroid.PERMISSIONS.READ_CALENDAR} value={PermissionsAndroid.PERMISSIONS.READ_CALENDAR} />
<Item label={PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION} value={PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION} />
<Item
label={PermissionsAndroid.PERMISSIONS.CAMERA}
value={PermissionsAndroid.PERMISSIONS.CAMERA}
/>
<Item
label={PermissionsAndroid.PERMISSIONS.READ_CALENDAR}
value={PermissionsAndroid.PERMISSIONS.READ_CALENDAR}
/>
<Item
label={PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION}
value={PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION}
/>
</Picker>
<TouchableWithoutFeedback onPress={this._checkPermission}>
<View>
<Text style={[styles.touchable, styles.text]}>Check Permission</Text>
<Text style={[styles.touchable, styles.text]}>
Check Permission
</Text>
</View>
</TouchableWithoutFeedback>
<Text style={styles.text}>Permission Status: {this.state.hasPermission}</Text>
<Text style={styles.text}>
Permission Status: {this.state.hasPermission}
</Text>
<TouchableWithoutFeedback onPress={this._requestPermission}>
<View>
<Text style={[styles.touchable, styles.text]}>Request Permission</Text>
<Text style={[styles.touchable, styles.text]}>
Request Permission
</Text>
</View>
</TouchableWithoutFeedback>
</View>
@@ -68,25 +85,22 @@ class PermissionsExample extends React.Component<{}, $FlowFixMeState> {
_checkPermission = async () => {
let result = await PermissionsAndroid.check(this.state.permission);
this.setState({
hasPermission: (result ? 'Granted' : 'Revoked') + ' for ' +
this.state.permission,
hasPermission:
(result ? 'Granted' : 'Revoked') + ' for ' + this.state.permission,
});
};
_requestPermission = async () => {
let result = await PermissionsAndroid.request(
this.state.permission,
{
title: 'Permission Explanation',
message:
'The app needs the following permission ' + this.state.permission +
' because of reasons. Please approve.'
},
);
let result = await PermissionsAndroid.request(this.state.permission, {
title: 'Permission Explanation',
message:
'The app needs the following permission ' +
this.state.permission +
' because of reasons. Please approve.',
});
this.setState({
hasPermission: result + ' for ' +
this.state.permission,
hasPermission: result + ' for ' + this.state.permission,
});
};
}
@@ -94,7 +108,8 @@ class PermissionsExample extends React.Component<{}, $FlowFixMeState> {
exports.examples = [
{
title: 'Permissions Example',
description: 'Short example of how to use the runtime permissions API introduced in Android M.',
description:
'Short example of how to use the runtime permissions API introduced in Android M.',
render: () => <PermissionsExample />,
},
];
@@ -116,5 +131,5 @@ var styles = StyleSheet.create({
},
picker: {
flex: 1,
}
},
});

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
@@ -14,10 +16,7 @@ const StyleSheet = require('StyleSheet');
const RNTesterBlock = require('RNTesterBlock');
const RNTesterPage = require('RNTesterPage');
const {
Picker,
Text,
} = ReactNative;
const {Picker, Text} = ReactNative;
const Item = Picker.Item;
@@ -46,7 +45,10 @@ class PickerExample extends React.Component<{}, $FlowFixMeState> {
</Picker>
</RNTesterBlock>
<RNTesterBlock title="Disabled picker">
<Picker style={styles.picker} enabled={false} selectedValue={this.state.selected1}>
<Picker
style={styles.picker}
enabled={false}
selectedValue={this.state.selected1}>
<Item label="hello" value="key0" />
<Item label="world" value="key1" />
</Picker>
@@ -77,7 +79,8 @@ class PickerExample extends React.Component<{}, $FlowFixMeState> {
<Item label="world" value="key1" />
</Picker>
<Text>
Cannot change the value of this picker because it doesn't update selectedValue.
Cannot change the value of this picker because it doesn't update
selectedValue.
</Text>
</RNTesterBlock>
<RNTesterBlock title="Colorful pickers">
@@ -105,7 +108,8 @@ class PickerExample extends React.Component<{}, $FlowFixMeState> {
}
changeMode = () => {
const newMode = this.state.mode === Picker.MODE_DIALOG
const newMode =
this.state.mode === Picker.MODE_DIALOG
? Picker.MODE_DROPDOWN
: Picker.MODE_DIALOG;
this.setState({mode: newMode});

View File

@@ -4,17 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
PickerIOS,
Text,
View,
} = ReactNative;
var {PickerIOS, Text, View} = ReactNative;
var PickerItemIOS = PickerIOS.Item;
@@ -25,7 +23,16 @@ var CAR_MAKES_AND_MODELS = {
},
alfa: {
name: 'Alfa-Romeo',
models: ['159', '4C', 'Alfasud', 'Brera', 'GTV6', 'Giulia', 'MiTo', 'Spider'],
models: [
'159',
'4C',
'Alfasud',
'Brera',
'GTV6',
'Giulia',
'MiTo',
'Spider',
],
},
aston: {
name: 'Aston Martin',
@@ -33,7 +40,19 @@ var CAR_MAKES_AND_MODELS = {
},
audi: {
name: 'Audi',
models: ['90', '4000', '5000', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'Q5', 'Q7'],
models: [
'90',
'4000',
'5000',
'A3',
'A4',
'A5',
'A6',
'A7',
'A8',
'Q5',
'Q7',
],
},
austin: {
name: 'Austin',
@@ -45,8 +64,15 @@ var CAR_MAKES_AND_MODELS = {
},
buick: {
name: 'Buick',
models: ['Electra', 'LaCrosse', 'LeSabre', 'Park Avenue', 'Regal',
'Roadmaster', 'Skylark'],
models: [
'Electra',
'LaCrosse',
'LeSabre',
'Park Avenue',
'Regal',
'Roadmaster',
'Skylark',
],
},
cadillac: {
name: 'Cadillac',
@@ -54,8 +80,21 @@ var CAR_MAKES_AND_MODELS = {
},
chevrolet: {
name: 'Chevrolet',
models: ['Astro', 'Aveo', 'Bel Air', 'Captiva', 'Cavalier', 'Chevelle',
'Corvair', 'Corvette', 'Cruze', 'Nova', 'SS', 'Vega', 'Volt'],
models: [
'Astro',
'Aveo',
'Bel Air',
'Captiva',
'Cavalier',
'Chevelle',
'Corvair',
'Corvette',
'Cruze',
'Nova',
'SS',
'Vega',
'Volt',
],
},
};
@@ -73,8 +112,8 @@ class PickerExample extends React.Component<{}, $FlowFixMeState> {
<Text>Please choose a make for your car:</Text>
<PickerIOS
selectedValue={this.state.carMake}
onValueChange={(carMake) => this.setState({carMake, modelIndex: 0})}>
{Object.keys(CAR_MAKES_AND_MODELS).map((carMake) => (
onValueChange={carMake => this.setState({carMake, modelIndex: 0})}>
{Object.keys(CAR_MAKES_AND_MODELS).map(carMake => (
<PickerItemIOS
key={carMake}
value={carMake}
@@ -86,14 +125,16 @@ class PickerExample extends React.Component<{}, $FlowFixMeState> {
<PickerIOS
selectedValue={this.state.modelIndex}
key={this.state.carMake}
onValueChange={(modelIndex) => this.setState({modelIndex})}>
{CAR_MAKES_AND_MODELS[this.state.carMake].models.map((modelName, modelIndex) => (
<PickerItemIOS
key={this.state.carMake + '_' + modelIndex}
value={modelIndex}
label={modelName}
/>
))}
onValueChange={modelIndex => this.setState({modelIndex})}>
{CAR_MAKES_AND_MODELS[this.state.carMake].models.map(
(modelName, modelIndex) => (
<PickerItemIOS
key={this.state.carMake + '_' + modelIndex}
value={modelIndex}
label={modelName}
/>
),
)}
</PickerIOS>
<Text>You selected: {selectionString}</Text>
</View>
@@ -110,10 +151,15 @@ class PickerStyleExample extends React.Component<{}, $FlowFixMeState> {
render() {
return (
<PickerIOS
itemStyle={{fontSize: 25, color: 'red', textAlign: 'left', fontWeight: 'bold'}}
itemStyle={{
fontSize: 25,
color: 'red',
textAlign: 'left',
fontWeight: 'bold',
}}
selectedValue={this.state.carMake}
onValueChange={(carMake) => this.setState({carMake, modelIndex: 0})}>
{Object.keys(CAR_MAKES_AND_MODELS).map((carMake) => (
onValueChange={carMake => this.setState({carMake, modelIndex: 0})}>
{Object.keys(CAR_MAKES_AND_MODELS).map(carMake => (
<PickerItemIOS
key={carMake}
value={carMake}
@@ -129,15 +175,16 @@ exports.displayName = (undefined: ?string);
exports.title = '<PickerIOS>';
exports.description = 'Render lists of selectable options with UIPickerView.';
exports.examples = [
{
title: '<PickerIOS>',
render: function(): React.Element<any> {
return <PickerExample />;
{
title: '<PickerIOS>',
render: function(): React.Element<any> {
return <PickerExample />;
},
},
},
{
title: '<PickerIOS> with custom styling',
render: function(): React.Element<any> {
return <PickerStyleExample />;
{
title: '<PickerIOS> with custom styling',
render: function(): React.Element<any> {
return <PickerStyleExample />;
},
},
}];
];

View File

@@ -4,24 +4,22 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
StyleSheet,
Text,
View,
} = ReactNative;
var {StyleSheet, Text, View} = ReactNative;
class ExampleBox extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
state = {
log: [],
};
handleLog = (msg) => {
handleLog = msg => {
this.state.log = this.state.log.concat([msg]);
};
@@ -48,8 +46,7 @@ class ExampleBox extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
* React. To see the error delete this comment and run Flow. */}
<this.props.Component onLog={this.handleLog} />
</View>
<View
style={styles.logBox}>
<View style={styles.logBox}>
<DemoText style={styles.logText}>
{this.state.log.join('\n')}
</DemoText>
@@ -65,9 +62,7 @@ class NoneExample extends React.Component<$FlowFixMeProps> {
<View
onTouchStart={() => this.props.onLog('A unspecified touched')}
style={styles.box}>
<DemoText style={styles.text}>
A: unspecified
</DemoText>
<DemoText style={styles.text}>A: unspecified</DemoText>
<View
pointerEvents="none"
onTouchStart={() => this.props.onLog('B none touched')}
@@ -96,10 +91,7 @@ class DemoText extends React.Component<$FlowFixMeProps> {
render() {
return (
<View pointerEvents="none">
<Text
style={this.props.style}>
{this.props.children}
</Text>
<Text style={this.props.style}>{this.props.children}</Text>
</View>
);
}
@@ -111,9 +103,7 @@ class BoxNoneExample extends React.Component<$FlowFixMeProps> {
<View
onTouchStart={() => this.props.onLog('A unspecified touched')}
style={styles.box}>
<DemoText style={styles.text}>
A: unspecified
</DemoText>
<DemoText style={styles.text}>A: unspecified</DemoText>
<View
pointerEvents="box-none"
onTouchStart={() => this.props.onLog('B box-none touched')}
@@ -124,17 +114,15 @@ class BoxNoneExample extends React.Component<$FlowFixMeProps> {
<View
onTouchStart={() => this.props.onLog('C unspecified touched')}
style={styles.box}>
<DemoText style={styles.text}>
C: unspecified
</DemoText>
<DemoText style={styles.text}>C: unspecified</DemoText>
</View>
<View
pointerEvents="auto"
onTouchStart={() => this.props.onLog('C explicitly unspecified touched')}
onTouchStart={() =>
this.props.onLog('C explicitly unspecified touched')
}
style={[styles.box]}>
<DemoText style={[styles.text]}>
C: explicitly unspecified
</DemoText>
<DemoText style={[styles.text]}>C: explicitly unspecified</DemoText>
</View>
</View>
</View>
@@ -148,16 +136,12 @@ class BoxOnlyExample extends React.Component<$FlowFixMeProps> {
<View
onTouchStart={() => this.props.onLog('A unspecified touched')}
style={styles.box}>
<DemoText style={styles.text}>
A: unspecified
</DemoText>
<DemoText style={styles.text}>A: unspecified</DemoText>
<View
pointerEvents="box-only"
onTouchStart={() => this.props.onLog('B box-only touched')}
style={styles.box}>
<DemoText style={styles.text}>
B: box-only
</DemoText>
<DemoText style={styles.text}>B: box-only</DemoText>
<View
onTouchStart={() => this.props.onLog('C unspecified touched')}
style={[styles.box, styles.boxPassedThrough]}>
@@ -167,7 +151,9 @@ class BoxOnlyExample extends React.Component<$FlowFixMeProps> {
</View>
<View
pointerEvents="auto"
onTouchStart={() => this.props.onLog('C explicitly unspecified touched')}
onTouchStart={() =>
this.props.onLog('C explicitly unspecified touched')
}
style={[styles.box, styles.boxPassedThrough]}>
<DemoText style={[styles.text, styles.textPassedThrough]}>
C: explicitly unspecified
@@ -189,21 +175,24 @@ var exampleClasses: Array<ExampleClass> = [
{
Component: NoneExample,
title: '`none`',
description: '`none` causes touch events on the container and its child components to pass through to the parent container.',
description:
'`none` causes touch events on the container and its child components to pass through to the parent container.',
},
{
Component: BoxNoneExample,
title: '`box-none`',
description: '`box-none` causes touch events on the container to pass through and will only detect touch events on its child components.',
description:
'`box-none` causes touch events on the container to pass through and will only detect touch events on its child components.',
},
{
Component: BoxOnlyExample,
title: '`box-only`',
description: '`box-only` causes touch events on the container\'s child components to pass through and will only detect touch events on the container itself.',
}
description:
"`box-only` causes touch events on the container's child components to pass through and will only detect touch events on the container itself.",
},
];
var infoToExample = (info) => {
var infoToExample = info => {
return {
title: info.title,
description: info.description,
@@ -248,7 +237,8 @@ var styles = StyleSheet.create({
exports.framework = 'React';
exports.title = 'Pointer Events';
exports.description = 'Demonstrates the use of the pointerEvents prop of a ' +
exports.description =
'Demonstrates the use of the pointerEvents prop of a ' +
'View to control how touches should be handled.';
/* $FlowFixMe(>=0.70.0 site=react_native_fb) This comment suppresses an error
* found when Flow v0.70 was deployed. To see the error delete this comment

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var ProgressBar = require('ProgressBarAndroid');
@@ -22,17 +24,15 @@ var MovingBar = createReactClass({
getInitialState: function() {
return {
progress: 0
progress: 0,
};
},
componentDidMount: function() {
this.setInterval(
() => {
var progress = (this.state.progress + 0.02) % 1;
this.setState({progress: progress});
}, 50
);
this.setInterval(() => {
var progress = (this.state.progress + 0.02) % 1;
this.setState({progress: progress});
}, 50);
},
render: function() {
@@ -60,7 +60,11 @@ class ProgressBarAndroidExample extends React.Component<{}> {
</RNTesterBlock>
<RNTesterBlock title="Horizontal Blue ProgressBar">
<MovingBar styleAttr="Horizontal" indeterminate={false} color="blue" />
<MovingBar
styleAttr="Horizontal"
indeterminate={false}
color="blue"
/>
</RNTesterBlock>
</RNTesterPage>
);

View File

@@ -4,18 +4,16 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var createReactClass = require('create-react-class');
var ReactNative = require('react-native');
var {
ProgressViewIOS,
StyleSheet,
View,
} = ReactNative;
var {ProgressViewIOS, StyleSheet, View} = ReactNative;
/* $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. */
@@ -37,7 +35,7 @@ var ProgressViewExample = createReactClass({
updateProgress() {
var progress = this.state.progress + 0.01;
this.setState({ progress });
this.setState({progress});
this.requestAnimationFrame(() => this.updateProgress());
},
@@ -49,11 +47,30 @@ var ProgressViewExample = createReactClass({
render() {
return (
<View style={styles.container}>
<ProgressViewIOS style={styles.progressView} progress={this.getProgress(0)}/>
<ProgressViewIOS style={styles.progressView} progressTintColor="purple" progress={this.getProgress(0.2)}/>
<ProgressViewIOS style={styles.progressView} progressTintColor="red" progress={this.getProgress(0.4)}/>
<ProgressViewIOS style={styles.progressView} progressTintColor="orange" progress={this.getProgress(0.6)}/>
<ProgressViewIOS style={styles.progressView} progressTintColor="yellow" progress={this.getProgress(0.8)}/>
<ProgressViewIOS
style={styles.progressView}
progress={this.getProgress(0)}
/>
<ProgressViewIOS
style={styles.progressView}
progressTintColor="purple"
progress={this.getProgress(0.2)}
/>
<ProgressViewIOS
style={styles.progressView}
progressTintColor="red"
progress={this.getProgress(0.4)}
/>
<ProgressViewIOS
style={styles.progressView}
progressTintColor="orange"
progress={this.getProgress(0.6)}
/>
<ProgressViewIOS
style={styles.progressView}
progressTintColor="yellow"
progress={this.getProgress(0.8)}
/>
</View>
);
},
@@ -63,14 +80,14 @@ exports.displayName = (undefined: ?string);
exports.framework = 'React';
exports.title = 'ProgressViewIOS';
exports.description = 'ProgressViewIOS';
exports.examples = [{
title: 'ProgressViewIOS',
render() {
return (
<ProgressViewExample/>
);
}
}];
exports.examples = [
{
title: 'ProgressViewIOS',
render() {
return <ProgressViewExample />;
},
},
];
var styles = StyleSheet.create({
container: {
@@ -79,5 +96,5 @@ var styles = StyleSheet.create({
},
progressView: {
marginTop: 20,
}
},
});

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
@@ -26,9 +28,7 @@ class Button extends React.Component<$FlowFixMeProps> {
underlayColor={'white'}
style={styles.button}
onPress={this.props.onPress}>
<Text style={styles.buttonLabel}>
{this.props.label}
</Text>
<Text style={styles.buttonLabel}>{this.props.label}</Text>
</TouchableHighlight>
);
}
@@ -37,18 +37,36 @@ class Button extends React.Component<$FlowFixMeProps> {
class NotificationExample extends React.Component<{}> {
UNSAFE_componentWillMount() {
PushNotificationIOS.addEventListener('register', this._onRegistered);
PushNotificationIOS.addEventListener('registrationError', this._onRegistrationError);
PushNotificationIOS.addEventListener('notification', this._onRemoteNotification);
PushNotificationIOS.addEventListener('localNotification', this._onLocalNotification);
PushNotificationIOS.addEventListener(
'registrationError',
this._onRegistrationError,
);
PushNotificationIOS.addEventListener(
'notification',
this._onRemoteNotification,
);
PushNotificationIOS.addEventListener(
'localNotification',
this._onLocalNotification,
);
PushNotificationIOS.requestPermissions();
}
componentWillUnmount() {
PushNotificationIOS.removeEventListener('register', this._onRegistered);
PushNotificationIOS.removeEventListener('registrationError', this._onRegistrationError);
PushNotificationIOS.removeEventListener('notification', this._onRemoteNotification);
PushNotificationIOS.removeEventListener('localNotification', this._onLocalNotification);
PushNotificationIOS.removeEventListener(
'registrationError',
this._onRegistrationError,
);
PushNotificationIOS.removeEventListener(
'notification',
this._onRemoteNotification,
);
PushNotificationIOS.removeEventListener(
'localNotification',
this._onLocalNotification,
);
}
render() {
@@ -86,7 +104,7 @@ class NotificationExample extends React.Component<{}> {
alert: 'Sample local notification',
badge: '+1',
sound: 'default',
category: 'REACT_NATIVE'
category: 'REACT_NATIVE',
},
});
}
@@ -95,10 +113,12 @@ class NotificationExample extends React.Component<{}> {
AlertIOS.alert(
'Registered For Remote Push',
`Device Token: ${deviceToken}`,
[{
text: 'Dismiss',
onPress: null,
}]
[
{
text: 'Dismiss',
onPress: null,
},
],
);
}
@@ -106,10 +126,12 @@ class NotificationExample extends React.Component<{}> {
AlertIOS.alert(
'Failed To Register For Remote Push',
`Error (${error.code}): ${error.message}`,
[{
text: 'Dismiss',
onPress: null,
}]
[
{
text: 'Dismiss',
onPress: null,
},
],
);
}
@@ -120,29 +142,32 @@ class NotificationExample extends React.Component<{}> {
category: ${notification.getCategory()};\n
content-available: ${notification.getContentAvailable()}.`;
AlertIOS.alert(
'Push Notification Received',
result,
[{
AlertIOS.alert('Push Notification Received', result, [
{
text: 'Dismiss',
onPress: null,
}]
);
},
]);
}
_onLocalNotification(notification){
_onLocalNotification(notification) {
AlertIOS.alert(
'Local Notification Received',
'Alert message: ' + notification.getMessage(),
[{
text: 'Dismiss',
onPress: null,
}]
[
{
text: 'Dismiss',
onPress: null,
},
],
);
}
}
class NotificationPermissionExample extends React.Component<$FlowFixMeProps, any> {
class NotificationPermissionExample extends React.Component<
$FlowFixMeProps,
any,
> {
constructor(props) {
super(props);
this.state = {permissions: null};
@@ -155,15 +180,13 @@ class NotificationPermissionExample extends React.Component<$FlowFixMeProps, any
onPress={this._showPermissions.bind(this)}
label="Show enabled permissions"
/>
<Text>
{JSON.stringify(this.state.permissions)}
</Text>
<Text>{JSON.stringify(this.state.permissions)}</Text>
</View>
);
}
_showPermissions() {
PushNotificationIOS.checkPermissions((permissions) => {
PushNotificationIOS.checkPermissions(permissions => {
this.setState({permissions});
});
}
@@ -183,32 +206,35 @@ var styles = StyleSheet.create({
exports.title = 'PushNotificationIOS';
exports.description = 'Apple PushNotification and badge value';
exports.examples = [
{
title: 'Badge Number',
render(): React.Element<any> {
return (
<View>
<Button
onPress={() => PushNotificationIOS.setApplicationIconBadgeNumber(42)}
label="Set app's icon badge to 42"
/>
<Button
onPress={() => PushNotificationIOS.setApplicationIconBadgeNumber(0)}
label="Clear app's icon badge"
/>
</View>
);
{
title: 'Badge Number',
render(): React.Element<any> {
return (
<View>
<Button
onPress={() =>
PushNotificationIOS.setApplicationIconBadgeNumber(42)
}
label="Set app's icon badge to 42"
/>
<Button
onPress={() => PushNotificationIOS.setApplicationIconBadgeNumber(0)}
label="Clear app's icon badge"
/>
</View>
);
},
},
},
{
title: 'Push Notifications',
render(): React.Element<any> {
return <NotificationExample />;
}
},
{
title: 'Notifications Permissions',
render(): React.Element<any> {
return <NotificationPermissionExample />;
}
}];
{
title: 'Push Notifications',
render(): React.Element<any> {
return <NotificationExample />;
},
},
{
title: 'Notifications Permissions',
render(): React.Element<any> {
return <NotificationPermissionExample />;
},
},
];

View File

@@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
@@ -11,22 +12,21 @@
const React = require('react');
const ReactNative = require('react-native');
const {
StyleSheet,
Text,
View,
} = ReactNative;
const {StyleSheet, Text, View} = ReactNative;
const requireNativeComponent = require('requireNativeComponent');
class AppPropertiesUpdateExample extends React.Component<{}> {
render() {
// Do not require this unless we are actually rendering.
const UpdatePropertiesExampleView = requireNativeComponent('UpdatePropertiesExampleView');
const UpdatePropertiesExampleView = requireNativeComponent(
'UpdatePropertiesExampleView',
);
return (
<View style={styles.container}>
<Text style={styles.text}>
Press the button to update the field below by passing new properties to the RN app.
Press the button to update the field below by passing new properties
to the RN app.
</Text>
<UpdatePropertiesExampleView style={styles.nativeView}>
<Text style={styles.text}>
@@ -41,11 +41,14 @@ class AppPropertiesUpdateExample extends React.Component<{}> {
class RootViewSizeFlexibilityExample extends React.Component<{}> {
render() {
// Do not require this unless we are actually rendering.
const FlexibleSizeExampleView = requireNativeComponent('FlexibleSizeExampleView');
const FlexibleSizeExampleView = requireNativeComponent(
'FlexibleSizeExampleView',
);
return (
<View style={styles.container}>
<Text style={styles.text}>
Press the button to resize it. On resize, RCTRootViewDelegate is notified. You can use it to handle content size updates.
Press the button to resize it. On resize, RCTRootViewDelegate is
notified. You can use it to handle content size updates.
</Text>
<FlexibleSizeExampleView style={styles.nativeView}>
<Text style={styles.text}>
@@ -63,30 +66,28 @@ const styles = StyleSheet.create({
backgroundColor: '#F5FCFF',
},
text: {
marginBottom: 20
marginBottom: 20,
},
nativeView: {
height: 140,
width: 280
}
width: 280,
},
});
exports.title = 'RCTRootView';
exports.description = 'Examples that show useful methods when embedding React Native in a native application';
exports.description =
'Examples that show useful methods when embedding React Native in a native application';
exports.examples = [
{
title: 'Updating app properties in runtime',
render(): React.Element<any> {
return (
<AppPropertiesUpdateExample/>
);
{
title: 'Updating app properties in runtime',
render(): React.Element<any> {
return <AppPropertiesUpdateExample />;
},
},
},
{
title: 'RCTRootView\'s size flexibility',
render(): React.Element<any> {
return (
<RootViewSizeFlexibilityExample/>
);
{
title: "RCTRootView's size flexibility",
render(): React.Element<any> {
return <RootViewSizeFlexibilityExample />;
},
},
}];
];

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
export type RNTesterBackAction = {
@@ -21,12 +23,10 @@ export type RNTesterExampleAction = {
openExample: string,
};
export type RNTesterAction = (
RNTesterBackAction |
RNTesterListAction |
RNTesterExampleAction
);
export type RNTesterAction =
| RNTesterBackAction
| RNTesterListAction
| RNTesterExampleAction;
function Back(): RNTesterBackAction {
return {

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const AppRegistry = require('AppRegistry');
@@ -29,7 +31,7 @@ const View = require('View');
const nativeImageSource = require('nativeImageSource');
import type { RNTesterNavigationState } from './RNTesterNavigationReducer';
import type {RNTesterNavigationState} from './RNTesterNavigationReducer';
UIManager.setLayoutAnimationEnabledExperimental(true);
@@ -44,24 +46,29 @@ const APP_STATE_KEY = 'RNTesterAppState.v2';
const HEADER_LOGO_ICON = nativeImageSource({
android: 'launcher_icon',
width: 132,
height: 144
height: 144,
});
const HEADER_NAV_ICON = nativeImageSource({
android: 'ic_menu_black_24dp',
width: 48,
height: 48
height: 48,
});
class RNTesterApp extends React.Component<Props, RNTesterNavigationState> {
UNSAFE_componentWillMount() {
BackHandler.addEventListener('hardwareBackPress', this._handleBackButtonPress);
BackHandler.addEventListener(
'hardwareBackPress',
this._handleBackButtonPress,
);
}
componentDidMount() {
Linking.getInitialURL().then((url) => {
Linking.getInitialURL().then(url => {
AsyncStorage.getItem(APP_STATE_KEY, (err, storedString) => {
const exampleAction = URIActionMap(this.props.exampleFromAppetizeParams);
const exampleAction = URIActionMap(
this.props.exampleFromAppetizeParams,
);
const urlAction = URIActionMap(url);
const launchAction = exampleAction || urlAction;
if (err || !storedString) {
@@ -94,7 +101,9 @@ class RNTesterApp extends React.Component<Props, RNTesterNavigationState> {
onDrawerClose={() => {
this._overrideBackPressForDrawerLayout = false;
}}
ref={(drawer) => { this.drawer = drawer; }}
ref={drawer => {
this.drawer = drawer;
}}
renderNavigationView={this._renderDrawerContent}
statusBarBackgroundColor="#589c90">
{this._renderApp()}
@@ -116,9 +125,7 @@ class RNTesterApp extends React.Component<Props, RNTesterNavigationState> {
};
_renderApp() {
const {
openExample,
} = this.state;
const {openExample} = this.state;
if (openExample) {
const ExampleModule = RNTesterList.Modules[openExample];
@@ -128,7 +135,9 @@ class RNTesterApp extends React.Component<Props, RNTesterNavigationState> {
onExampleExit={() => {
this._handleAction(RNTesterActions.Back());
}}
ref={(example) => { this._exampleRef = example; }}
ref={example => {
this._exampleRef = example;
}}
/>
);
} else if (ExampleModule) {
@@ -143,7 +152,9 @@ class RNTesterApp extends React.Component<Props, RNTesterNavigationState> {
/>
<RNTesterExampleContainer
module={ExampleModule}
ref={(example) => { this._exampleRef = example; }}
ref={example => {
this._exampleRef = example;
}}
/>
</View>
);
@@ -171,9 +182,8 @@ class RNTesterApp extends React.Component<Props, RNTesterNavigationState> {
this.drawer && this.drawer.closeDrawer();
const newState = RNTesterNavigationReducer(this.state, action);
if (this.state !== newState) {
this.setState(
newState,
() => AsyncStorage.setItem(APP_STATE_KEY, JSON.stringify(this.state))
this.setState(newState, () =>
AsyncStorage.setItem(APP_STATE_KEY, JSON.stringify(this.state)),
);
return true;
}

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const AsyncStorage = require('AsyncStorage');
@@ -27,12 +29,12 @@ const {
StyleSheet,
Text,
View,
SafeAreaView
SafeAreaView,
} = ReactNative;
import type { RNTesterExample } from './RNTesterList.ios';
import type { RNTesterAction } from './RNTesterActions';
import type { RNTesterNavigationState } from './RNTesterNavigationReducer';
import type {RNTesterExample} from './RNTesterList.ios';
import type {RNTesterAction} from './RNTesterActions';
import type {RNTesterNavigationState} from './RNTesterNavigationReducer';
type Props = {
exampleFromAppetizeParams: string,
@@ -40,15 +42,17 @@ type Props = {
const APP_STATE_KEY = 'RNTesterAppState.v2';
const Header = ({ onBack, title }: { onBack?: () => mixed, title: string }) => (
const Header = ({onBack, title}: {onBack?: () => mixed, title: string}) => (
<SafeAreaView style={styles.headerContainer}>
<View style={styles.header}>
<View style={styles.headerCenter}>
<Text style={styles.title}>{title}</Text>
</View>
{onBack && <View style={styles.headerLeft}>
<Button title="Back" onPress={onBack} />
</View>}
{onBack && (
<View style={styles.headerLeft}>
<Button title="Back" onPress={onBack} />
</View>
)}
</View>
</SafeAreaView>
);
@@ -59,9 +63,11 @@ class RNTesterApp extends React.Component<Props, RNTesterNavigationState> {
}
componentDidMount() {
Linking.getInitialURL().then((url) => {
Linking.getInitialURL().then(url => {
AsyncStorage.getItem(APP_STATE_KEY, (err, storedString) => {
const exampleAction = URIActionMap(this.props.exampleFromAppetizeParams);
const exampleAction = URIActionMap(
this.props.exampleFromAppetizeParams,
);
const urlAction = URIActionMap(url);
const launchAction = exampleAction || urlAction;
if (err || !storedString) {
@@ -78,14 +84,14 @@ class RNTesterApp extends React.Component<Props, RNTesterNavigationState> {
});
});
Linking.addEventListener('url', (url) => {
Linking.addEventListener('url', url => {
this._handleAction(URIActionMap(url));
});
}
_handleBack = () => {
this._handleAction(RNTesterActions.Back());
}
};
_handleAction = (action: ?RNTesterAction) => {
if (!action) {
@@ -93,12 +99,11 @@ class RNTesterApp extends React.Component<Props, RNTesterNavigationState> {
}
const newState = RNTesterNavigationReducer(this.state, action);
if (this.state !== newState) {
this.setState(
newState,
() => AsyncStorage.setItem(APP_STATE_KEY, JSON.stringify(this.state))
this.setState(newState, () =>
AsyncStorage.setItem(APP_STATE_KEY, JSON.stringify(this.state)),
);
}
}
};
render() {
if (!this.state) {
@@ -107,11 +112,7 @@ class RNTesterApp extends React.Component<Props, RNTesterNavigationState> {
if (this.state.openExample) {
const Component = RNTesterList.Modules[this.state.openExample];
if (Component.external) {
return (
<Component
onExampleExit={this._handleBack}
/>
);
return <Component onExampleExit={this._handleBack} />;
} else {
return (
<View style={styles.exampleContainer}>
@@ -120,7 +121,6 @@ class RNTesterApp extends React.Component<Props, RNTesterNavigationState> {
</View>
);
}
}
return (
<View style={styles.exampleContainer}>
@@ -145,10 +145,9 @@ const styles = StyleSheet.create({
},
header: {
height: 40,
flexDirection: 'row'
},
headerLeft: {
flexDirection: 'row',
},
headerLeft: {},
headerCenter: {
flex: 1,
position: 'absolute',
@@ -166,26 +165,35 @@ const styles = StyleSheet.create({
},
});
AppRegistry.registerComponent('SetPropertiesExampleApp', () => require('./SetPropertiesExampleApp'));
AppRegistry.registerComponent('RootViewSizeFlexibilityExampleApp', () => require('./RootViewSizeFlexibilityExampleApp'));
AppRegistry.registerComponent('SetPropertiesExampleApp', () =>
require('./SetPropertiesExampleApp'),
);
AppRegistry.registerComponent('RootViewSizeFlexibilityExampleApp', () =>
require('./RootViewSizeFlexibilityExampleApp'),
);
AppRegistry.registerComponent('RNTesterApp', () => RNTesterApp);
// Register suitable examples for snapshot tests
RNTesterList.ComponentExamples.concat(RNTesterList.APIExamples).forEach((Example: RNTesterExample) => {
const ExampleModule = Example.module;
if (ExampleModule.displayName) {
class Snapshotter extends React.Component<{}> {
render() {
return (
<SnapshotViewIOS>
<RNTesterExampleContainer module={ExampleModule} />
</SnapshotViewIOS>
);
RNTesterList.ComponentExamples.concat(RNTesterList.APIExamples).forEach(
(Example: RNTesterExample) => {
const ExampleModule = Example.module;
if (ExampleModule.displayName) {
class Snapshotter extends React.Component<{}> {
render() {
return (
<SnapshotViewIOS>
<RNTesterExampleContainer module={ExampleModule} />
</SnapshotViewIOS>
);
}
}
}
AppRegistry.registerComponent(ExampleModule.displayName, () => Snapshotter);
}
});
AppRegistry.registerComponent(
ExampleModule.displayName,
() => Snapshotter,
);
}
},
);
module.exports = RNTesterApp;

View File

@@ -4,23 +4,24 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var PropTypes = require('prop-types');
var ReactNative = require('react-native');
var {
StyleSheet,
Text,
View,
} = ReactNative;
var {StyleSheet, Text, View} = ReactNative;
class RNTesterBlock extends React.Component<{
title?: string,
description?: string,
}, $FlowFixMeState> {
class RNTesterBlock extends React.Component<
{
title?: string,
description?: string,
},
$FlowFixMeState,
> {
static propTypes = {
title: PropTypes.string,
description: PropTypes.string,
@@ -31,24 +32,22 @@ class RNTesterBlock extends React.Component<{
render() {
var description;
if (this.props.description) {
description =
<Text style={styles.descriptionText}>
{this.props.description}
</Text>;
description = (
<Text style={styles.descriptionText}>{this.props.description}</Text>
);
}
return (
<View style={styles.container}>
<View style={styles.titleContainer}>
<Text style={styles.titleText}>
{this.props.title}
</Text>
<Text style={styles.titleText}>{this.props.title}</Text>
{description}
</View>
<View style={styles.children}>
{
// $FlowFixMe found when converting React.createClass to ES6
this.props.children}
this.props.children
}
</View>
</View>
);
@@ -93,7 +92,7 @@ var styles = StyleSheet.create({
},
children: {
margin: 10,
}
},
});
module.exports = RNTesterBlock;

View File

@@ -4,18 +4,16 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var PropTypes = require('prop-types');
var ReactNative = require('react-native');
var {
StyleSheet,
Text,
TouchableHighlight,
} = ReactNative;
var {StyleSheet, Text, TouchableHighlight} = ReactNative;
class RNTesterButton extends React.Component<{onPress?: Function}> {
static propTypes = {
@@ -31,7 +29,8 @@ class RNTesterButton extends React.Component<{onPress?: Function}> {
<Text>
{
// $FlowFixMe found when converting React.createClass to ES6
this.props.children}
this.props.children
}
</Text>
</TouchableHighlight>
);

View File

@@ -4,13 +4,13 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const React = require('react');
const {
Platform,
} = require('react-native');
const {Platform} = require('react-native');
const RNTesterBlock = require('./RNTesterBlock');
const RNTesterPage = require('./RNTesterPage');
@@ -25,10 +25,7 @@ class RNTesterExampleContainer extends React.Component {
title += ' (' + platform + ' only)';
}
return (
<RNTesterBlock
key={i}
title={title}
description={description}>
<RNTesterBlock key={i} title={title} description={description}>
{example.render()}
</RNTesterBlock>
);

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const Platform = require('Platform');
@@ -53,34 +55,29 @@ class RowComponent extends React.PureComponent<{
return (
<TouchableHighlight {...this.props} onPress={this._onPress}>
<View style={styles.row}>
<Text style={styles.rowTitleText}>
{item.module.title}
</Text>
<Text style={styles.rowDetailText}>
{item.module.description}
</Text>
<Text style={styles.rowTitleText}>{item.module.title}</Text>
<Text style={styles.rowDetailText}>{item.module.description}</Text>
</View>
</TouchableHighlight>
);
}
}
const renderSectionHeader = ({section}) =>
<Text style={styles.sectionHeader}>
{section.title}
</Text>;
const renderSectionHeader = ({section}) => (
<Text style={styles.sectionHeader}>{section.title}</Text>
);
class RNTesterExampleList extends React.Component<Props, $FlowFixMeState> {
render() {
const filterText = this.props.persister.state.filter;
const filterRegex = new RegExp(String(filterText), 'i');
const filter = (example) =>
const filter = example =>
/* $FlowFixMe(>=0.68.0 site=react_native_fb) This comment suppresses an
* error found when Flow v0.68 was deployed. To see the error delete this
* comment and run Flow. */
this.props.disableSearch ||
filterRegex.test(example.module.title) &&
(!Platform.isTVOS || example.supportsTVOS);
(filterRegex.test(example.module.title) &&
(!Platform.isTVOS || example.supportsTVOS));
const sections = [
{
@@ -138,10 +135,12 @@ class RNTesterExampleList extends React.Component<Props, $FlowFixMeState> {
}
return (
<RowComponent
item={{module: {
title: 'RNTester',
description: 'React Native Examples',
}}}
item={{
module: {
title: 'RNTester',
description: 'React Native Examples',
},
}}
onNavigate={this.props.onNavigate}
onPress={() => {
this.props.onNavigate(RNTesterActions.ExampleList());
@@ -185,10 +184,13 @@ const ItemSeparator = ({highlighted}) => (
<View style={highlighted ? styles.separatorHighlighted : styles.separator} />
);
RNTesterExampleList = RNTesterStatePersister.createContainer(RNTesterExampleList, {
cacheKeySuffix: () => 'mainList',
getInitialState: () => ({filter: ''}),
});
RNTesterExampleList = RNTesterStatePersister.createContainer(
RNTesterExampleList,
{
cacheKeySuffix: () => 'mainList',
getInitialState: () => ({filter: ''}),
},
);
const styles = StyleSheet.create({
listContainer: {

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
export type RNTesterExample = {
@@ -84,11 +86,11 @@ const ComponentExamples: Array<RNTesterExample> = [
},
{
key: 'SwipeableFlatListExample',
module: require('./SwipeableFlatListExample')
module: require('./SwipeableFlatListExample'),
},
{
key: 'SwipeableListViewExample',
module: require('./SwipeableListViewExample')
module: require('./SwipeableListViewExample'),
},
{
key: 'SwitchExample',

View File

@@ -4,14 +4,16 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
export type RNTesterExample = {
key: string,
module: Object,
supportsTVOS: boolean
supportsTVOS: boolean,
};
const ComponentExamples: Array<RNTesterExample> = [

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
// $FlowFixMe : This is a platform-forked component, and flow seems to only run on iOS?
@@ -17,16 +19,13 @@ export type RNTesterNavigationState = {
function RNTesterNavigationReducer(
state: ?RNTesterNavigationState,
action: any
action: any,
): RNTesterNavigationState {
if (
// Default value is to see example list
!state ||
// Handle the explicit list action
action.type === 'RNTesterListAction' ||
// Handle requests to go back to the list when an example is open
(state.openExample && action.type === 'RNTesterBackAction')
) {
@@ -37,7 +36,6 @@ function RNTesterNavigationReducer(
}
if (action.type === 'RNTesterExampleAction') {
// Make sure we see the module before returning the new state
const ExampleModule = RNTesterList.Modules[action.openExample];

View File

@@ -4,18 +4,16 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var PropTypes = require('prop-types');
var React = require('react');
var ReactNative = require('react-native');
var {
ScrollView,
StyleSheet,
View,
} = ReactNative;
var {ScrollView, StyleSheet, View} = ReactNative;
var RNTesterTitle = require('./RNTesterTitle');
@@ -43,20 +41,19 @@ class RNTesterPage extends React.Component<{
/* $FlowFixMe(>=0.68.0 site=react_native_fb) This comment suppresses an
* error found when Flow v0.68 was deployed. To see the error delete this
* comment and run Flow. */
var title = this.props.title ?
<RNTesterTitle title={this.props.title} /> :
null;
var title = this.props.title ? (
<RNTesterTitle title={this.props.title} />
) : null;
var spacer = this.props.noSpacer ? null : <View style={styles.spacer} />;
return (
<View style={styles.container}>
{title}
<ContentWrapper
style={styles.wrapper}
{...wrapperProps}>
{
// $FlowFixMe found when converting React.createClass to ES6
this.props.children}
{spacer}
<ContentWrapper style={styles.wrapper} {...wrapperProps}>
{
// $FlowFixMe found when converting React.createClass to ES6
this.props.children
}
{spacer}
</ContentWrapper>
</View>
);

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('React');
@@ -15,7 +17,10 @@ const Text = require('Text');
const RNTesterStatePersister = require('./RNTesterStatePersister');
const View = require('View');
class RNTesterSettingSwitchRow extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
class RNTesterSettingSwitchRow extends React.Component<
$FlowFixMeProps,
$FlowFixMeState,
> {
UNSAFE_componentWillReceiveProps(newProps) {
const {onEnable, onDisable, persister} = this.props;
if (newProps.persister.state !== persister.state) {
@@ -29,7 +34,7 @@ class RNTesterSettingSwitchRow extends React.Component<$FlowFixMeProps, $FlowFix
<Text>{label}</Text>
<Switch
value={persister.state}
onValueChange={(value) => {
onValueChange={value => {
persister.setState(() => value);
}}
/>
@@ -44,8 +49,11 @@ const styles = StyleSheet.create({
justifyContent: 'space-between',
},
});
RNTesterSettingSwitchRow = RNTesterStatePersister.createContainer(RNTesterSettingSwitchRow, {
cacheKeySuffix: ({label}) => 'Switch:' + label,
getInitialState: ({initialValue}) => initialValue,
});
RNTesterSettingSwitchRow = RNTesterStatePersister.createContainer(
RNTesterSettingSwitchRow,
{
cacheKeySuffix: ({label}) => 'Switch:' + label,
getInitialState: ({initialValue}) => initialValue,
},
);
module.exports = RNTesterSettingSwitchRow;

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const AsyncStorage = require('AsyncStorage');
@@ -34,13 +36,19 @@ function createContainer<Props: Object, State>(
version?: string,
},
): React.ComponentType<Props> {
return class ComponentWithPersistedState extends React.Component<Props, $FlowFixMeState> {
return class ComponentWithPersistedState extends React.Component<
Props,
$FlowFixMeState,
> {
/* $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. */
static displayName = `RNTesterStatePersister(${Component.displayName || Component.name})`;
static displayName = `RNTesterStatePersister(${Component.displayName ||
Component.name})`;
state = {value: spec.getInitialState(this.props)};
_cacheKey = `RNTester:${spec.version || 'v1'}:${spec.cacheKeySuffix(this.props)}`;
_cacheKey = `RNTester:${spec.version || 'v1'}:${spec.cacheKeySuffix(
this.props,
)}`;
componentDidMount() {
AsyncStorage.getItem(this._cacheKey, (err, value) => {
if (!err && value) {
@@ -49,7 +57,7 @@ function createContainer<Props: Object, State>(
});
}
_passSetState = (stateLamda: (state: State) => State): void => {
this.setState((state) => {
this.setState(state => {
const value = stateLamda(state.value);
AsyncStorage.setItem(this._cacheKey, JSON.stringify(value));
return {value};

View File

@@ -4,25 +4,21 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
StyleSheet,
Text,
View,
} = ReactNative;
var {StyleSheet, Text, View} = ReactNative;
class RNTesterTitle extends React.Component<$FlowFixMeProps> {
render() {
return (
<View style={styles.container}>
<Text style={styles.text}>
{this.props.title}
</Text>
<Text style={styles.text}>{this.props.title}</Text>
</View>
);
}

View File

@@ -4,7 +4,9 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const React = require('react');
@@ -42,7 +44,7 @@ class Row extends React.Component {
render() {
return (
<TouchableWithoutFeedback onPress={this._onClick} >
<TouchableWithoutFeedback onPress={this._onClick}>
<View style={styles.row}>
<Text style={styles.text}>
{this.props.data.text + ' (' + this.props.data.clicks + ' clicks)'}
@@ -60,11 +62,13 @@ class RefreshControlExample extends React.Component {
state = {
isRefreshing: false,
loaded: 0,
rowData: Array.from(new Array(20)).map(
(val, i) => ({text: 'Initial row ' + i, clicks: 0})),
rowData: Array.from(new Array(20)).map((val, i) => ({
text: 'Initial row ' + i,
clicks: 0,
})),
};
_onClick = (row) => {
_onClick = row => {
row.clicks++;
this.setState({
rowData: this.state.rowData,
@@ -73,7 +77,7 @@ class RefreshControlExample extends React.Component {
render() {
const rows = this.state.rowData.map((row, ii) => {
return <Row key={ii} data={row} onClick={this._onClick}/>;
return <Row key={ii} data={row} onClick={this._onClick} />;
});
return (
<ScrollView
@@ -99,11 +103,11 @@ class RefreshControlExample extends React.Component {
setTimeout(() => {
// prepend 10 items
const rowData = Array.from(new Array(10))
.map((val, i) => ({
text: 'Loaded row ' + (+this.state.loaded + i),
clicks: 0,
}))
.concat(this.state.rowData);
.map((val, i) => ({
text: 'Loaded row ' + (+this.state.loaded + i),
clicks: 0,
}))
.concat(this.state.rowData);
this.setState({
loaded: this.state.loaded + 10,

View File

@@ -4,39 +4,39 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
const ReactNative = require('react-native');
const {
StyleSheet,
Text,
TouchableHighlight,
View,
} = ReactNative;
const {StyleSheet, Text, TouchableHighlight, View} = ReactNative;
class RootViewSizeFlexibilityExampleApp extends React.Component<{toggled: boolean}, any> {
class RootViewSizeFlexibilityExampleApp extends React.Component<
{toggled: boolean},
any,
> {
constructor(props: {toggled: boolean}) {
super(props);
this.state = { toggled: false };
this.state = {toggled: false};
}
_onPressButton() {
this.setState({ toggled: !this.state.toggled });
this.setState({toggled: !this.state.toggled});
}
render() {
const viewStyle = this.state.toggled ? styles.bigContainer : styles.smallContainer;
const viewStyle = this.state.toggled
? styles.bigContainer
: styles.smallContainer;
return (
<TouchableHighlight onPress={this._onPressButton.bind(this)}>
<View style={viewStyle}>
<View style={styles.center}>
<Text style={styles.whiteText}>
React Native Button
</Text>
<Text style={styles.whiteText}>React Native Button</Text>
</View>
</View>
</TouchableHighlight>
@@ -62,7 +62,7 @@ const styles = StyleSheet.create({
},
whiteText: {
color: 'white',
}
},
});
module.exports = RootViewSizeFlexibilityExampleApp;

View File

@@ -4,18 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
ScrollView,
StyleSheet,
Text,
TouchableOpacity
} = ReactNative;
var {ScrollView, StyleSheet, Text, TouchableOpacity} = ReactNative;
var NUM_ITEMS = 20;
@@ -26,11 +23,11 @@ class ScrollViewSimpleExample extends React.Component<{}> {
makeItems = (nItems: number, styles): Array<any> => {
var items = [];
for (var i = 0; i < nItems; i++) {
items[i] = (
<TouchableOpacity key={i} style={styles}>
<Text>{'Item ' + i}</Text>
</TouchableOpacity>
);
items[i] = (
<TouchableOpacity key={i} style={styles}>
<Text>{'Item ' + i}</Text>
</TouchableOpacity>
);
}
return items;
};
@@ -40,7 +37,10 @@ class ScrollViewSimpleExample extends React.Component<{}> {
var items = this.makeItems(NUM_ITEMS, styles.itemWrapper);
items[4] = (
<ScrollView key={'scrollView'} horizontal={true}>
{this.makeItems(NUM_ITEMS, [styles.itemWrapper, styles.horizontalItemWrapper])}
{this.makeItems(NUM_ITEMS, [
styles.itemWrapper,
styles.horizontalItemWrapper,
])}
</ScrollView>
);
items.push(
@@ -48,20 +48,17 @@ class ScrollViewSimpleExample extends React.Component<{}> {
key={'scrollViewSnap'}
horizontal
snapToInterval={210.0}
pagingEnabled
>
pagingEnabled>
{this.makeItems(NUM_ITEMS, [
styles.itemWrapper,
styles.horizontalItemWrapper,
styles.horizontalPagingItemWrapper,
])}
</ScrollView>
</ScrollView>,
);
var verticalScrollView = (
<ScrollView style={styles.verticalScrollView}>
{items}
</ScrollView>
<ScrollView style={styles.verticalScrollView}>{items}</ScrollView>
);
return verticalScrollView;
@@ -82,7 +79,7 @@ var styles = StyleSheet.create({
margin: 5,
},
horizontalItemWrapper: {
padding: 50
padding: 50,
},
horizontalPagingItemWrapper: {
width: 200,

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
@@ -60,7 +62,11 @@ const renderSectionFooter = ({section}) => (
);
const CustomSeparatorComponent = ({highlighted, text}) => (
<View style={[styles.customSeparator, highlighted && {backgroundColor: 'rgb(217, 217, 217)'}]}>
<View
style={[
styles.customSeparator,
highlighted && {backgroundColor: 'rgb(217, 217, 217)'},
]}>
<Text style={styles.separatorText}>{text}</Text>
</View>
);
@@ -80,39 +86,38 @@ class SectionListExample extends React.PureComponent<{}, $FlowFixMeState> {
_scrollPos = new Animated.Value(0);
_scrollSinkY = Animated.event(
[{nativeEvent: { contentOffset: { y: this._scrollPos } }}],
[{nativeEvent: {contentOffset: {y: this._scrollPos}}}],
{useNativeDriver: true},
);
_sectionListRef: any;
_captureRef = (ref) => { this._sectionListRef = ref; };
_captureRef = ref => {
this._sectionListRef = ref;
};
_scrollToLocation(sectionIndex: number, itemIndex: number) {
this._sectionListRef
.getNode()
.scrollToLocation({ sectionIndex, itemIndex });
this._sectionListRef.getNode().scrollToLocation({sectionIndex, itemIndex});
}
render() {
const filterRegex = new RegExp(String(this.state.filterText), 'i');
const filter = (item) => (
filterRegex.test(item.text) || filterRegex.test(item.title)
);
const filter = item =>
filterRegex.test(item.text) || filterRegex.test(item.title);
const filteredData = this.state.data.filter(filter);
const filteredSectionData = [];
let startIndex = 0;
const endIndex = filteredData.length - 1;
for (let ii = 10; ii <= endIndex + 10; ii += 10) {
filteredSectionData.push({
key: `${filteredData[startIndex].key} - ${filteredData[Math.min(ii - 1, endIndex)].key}`,
key: `${filteredData[startIndex].key} - ${
filteredData[Math.min(ii - 1, endIndex)].key
}`,
data: filteredData.slice(startIndex, ii),
});
startIndex = ii;
}
return (
<RNTesterPage
noSpacer={true}
noScroll={true}>
<RNTesterPage noSpacer={true} noScroll={true}>
<View style={styles.searchRow}>
<PlainInput
onChangeText={filterText => {
@@ -130,9 +135,18 @@ class SectionListExample extends React.PureComponent<{}, $FlowFixMeState> {
</View>
<View style={styles.scrollToRow}>
<Text>scroll to:</Text>
<Button title="Item A" onPress={() => this._scrollToLocation(2, 1)}/>
<Button title="Item B" onPress={() => this._scrollToLocation(3, 6)}/>
<Button title="Item C" onPress={() => this._scrollToLocation(6, 3)}/>
<Button
title="Item A"
onPress={() => this._scrollToLocation(2, 1)}
/>
<Button
title="Item B"
onPress={() => this._scrollToLocation(3, 6)}
/>
<Button
title="Item C"
onPress={() => this._scrollToLocation(6, 3)}
/>
</View>
</View>
<SeparatorComponent />
@@ -140,12 +154,12 @@ class SectionListExample extends React.PureComponent<{}, $FlowFixMeState> {
ref={this._captureRef}
ListHeaderComponent={HeaderComponent}
ListFooterComponent={FooterComponent}
SectionSeparatorComponent={(info) =>
SectionSeparatorComponent={info => (
<CustomSeparatorComponent {...info} text="SECTION SEPARATOR" />
}
ItemSeparatorComponent={(info) =>
)}
ItemSeparatorComponent={info => (
<CustomSeparatorComponent {...info} text="ITEM SEPARATOR" />
}
)}
debug={this.state.debug}
inverted={this.state.inverted}
enableVirtualization={this.state.virtualized}
@@ -166,14 +180,28 @@ class SectionListExample extends React.PureComponent<{}, $FlowFixMeState> {
renderItem: renderStackedItem,
key: 's1',
data: [
{title: 'Item In Header Section', text: 'Section s1', key: 'header item'},
{
title: 'Item In Header Section',
text: 'Section s1',
key: 'header item',
},
],
},
{
key: 's2',
data: [
{noImage: true, title: '1st item', text: 'Section s2', key: 'noimage0'},
{noImage: true, title: '2nd item', text: 'Section s2', key: 'noimage1'},
{
noImage: true,
title: '1st item',
text: 'Section s2',
key: 'noimage0',
},
{
noImage: true,
title: '2nd item',
text: 'Section s2',
key: 'noimage1',
},
],
},
...filteredSectionData,
@@ -202,14 +230,19 @@ class SectionListExample extends React.PureComponent<{}, $FlowFixMeState> {
isViewable: boolean,
item: {columns: Array<*>},
index: ?number,
section?: any
}>},
) => {
section?: any,
}>,
}) => {
// Impressions can be logged here
if (this.state.logViewable) {
infoLog('onViewableItemsChanged: ', info.changed.map((v: Object) => (
{...v, item: '...', section: v.section.key}
)));
infoLog(
'onViewableItemsChanged: ',
info.changed.map((v: Object) => ({
...v,
item: '...',
section: v.section.key,
})),
);
}
};

View File

@@ -4,18 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
SegmentedControlIOS,
Text,
View,
StyleSheet
} = ReactNative;
var {SegmentedControlIOS, Text, View, StyleSheet} = ReactNative;
class BasicSegmentedControlExample extends React.Component<{}> {
render() {
@@ -25,7 +22,9 @@ class BasicSegmentedControlExample extends React.Component<{}> {
<SegmentedControlIOS values={['One', 'Two']} />
</View>
<View>
<SegmentedControlIOS values={['One', 'Two', 'Three', 'Four', 'Five']} />
<SegmentedControlIOS
values={['One', 'Two', 'Three', 'Four', 'Five']}
/>
</View>
</View>
);
@@ -61,7 +60,11 @@ class DisabledSegmentedControlExample extends React.Component<{}> {
return (
<View>
<View>
<SegmentedControlIOS enabled={false} values={['One', 'Two']} selectedIndex={1} />
<SegmentedControlIOS
enabled={false}
values={['One', 'Two']}
selectedIndex={1}
/>
</View>
</View>
);
@@ -73,48 +76,56 @@ class ColorSegmentedControlExample extends React.Component<{}> {
return (
<View>
<View style={{marginBottom: 10}}>
<SegmentedControlIOS tintColor="#ff0000" values={['One', 'Two', 'Three', 'Four']} selectedIndex={0} />
<SegmentedControlIOS
tintColor="#ff0000"
values={['One', 'Two', 'Three', 'Four']}
selectedIndex={0}
/>
</View>
<View>
<SegmentedControlIOS tintColor="#00ff00" values={['One', 'Two', 'Three']} selectedIndex={1} />
<SegmentedControlIOS
tintColor="#00ff00"
values={['One', 'Two', 'Three']}
selectedIndex={1}
/>
</View>
</View>
);
}
}
class EventSegmentedControlExample extends React.Component<{}, $FlowFixMeState> {
class EventSegmentedControlExample extends React.Component<
{},
$FlowFixMeState,
> {
state = {
values: ['One', 'Two', 'Three'],
value: 'Not selected',
selectedIndex: undefined
selectedIndex: undefined,
};
render() {
return (
<View>
<Text style={styles.text} >
Value: {this.state.value}
</Text>
<Text style={styles.text} >
Index: {this.state.selectedIndex}
</Text>
<Text style={styles.text}>Value: {this.state.value}</Text>
<Text style={styles.text}>Index: {this.state.selectedIndex}</Text>
<SegmentedControlIOS
values={this.state.values}
selectedIndex={this.state.selectedIndex}
onChange={this._onChange}
onValueChange={this._onValueChange} />
onValueChange={this._onValueChange}
/>
</View>
);
}
_onChange = (event) => {
_onChange = event => {
this.setState({
selectedIndex: event.nativeEvent.selectedSegmentIndex,
});
};
_onValueChange = (value) => {
_onValueChange = value => {
this.setState({
value: value,
});
@@ -136,26 +147,38 @@ exports.description = 'Native segmented control';
exports.examples = [
{
title: 'Segmented controls can have values',
render(): React.Element<any> { return <BasicSegmentedControlExample />; }
render(): React.Element<any> {
return <BasicSegmentedControlExample />;
},
},
{
title: 'Segmented controls can have a pre-selected value',
render(): React.Element<any> { return <PreSelectedSegmentedControlExample />; }
render(): React.Element<any> {
return <PreSelectedSegmentedControlExample />;
},
},
{
title: 'Segmented controls can be momentary',
render(): React.Element<any> { return <MomentarySegmentedControlExample />; }
render(): React.Element<any> {
return <MomentarySegmentedControlExample />;
},
},
{
title: 'Segmented controls can be disabled',
render(): React.Element<any> { return <DisabledSegmentedControlExample />; }
render(): React.Element<any> {
return <DisabledSegmentedControlExample />;
},
},
{
title: 'Custom colors can be provided',
render(): React.Element<any> { return <ColorSegmentedControlExample />; }
render(): React.Element<any> {
return <ColorSegmentedControlExample />;
},
},
{
title: 'Change events can be detected',
render(): React.Element<any> { return <EventSegmentedControlExample />; }
}
render(): React.Element<any> {
return <EventSegmentedControlExample />;
},
},
];

View File

@@ -4,36 +4,31 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
const ReactNative = require('react-native');
const {
Text,
View,
} = ReactNative;
const {Text, View} = ReactNative;
class SetPropertiesExampleApp extends React.Component<$FlowFixMeProps> {
render() {
const wrapperStyle = {
backgroundColor: this.props.color,
flex: 1,
alignItems: 'center',
justifyContent: 'center'
justifyContent: 'center',
};
return (
<View style={wrapperStyle}>
<Text>
Embedded React Native view
</Text>
<Text>Embedded React Native view</Text>
</View>
);
}
}
module.exports = SetPropertiesExampleApp;

View File

@@ -4,29 +4,27 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
StyleSheet,
View,
Text,
TouchableHighlight,
Share,
} = ReactNative;
var {StyleSheet, View, Text, TouchableHighlight, Share} = ReactNative;
exports.framework = 'React';
exports.title = 'Share';
exports.description = 'Share data with other Apps.';
exports.examples = [{
title: 'Share Text Content',
render() {
return <ShareMessageExample />;
}
}];
exports.examples = [
{
title: 'Share Text Content',
render() {
return <ShareMessageExample />;
},
},
];
class ShareMessageExample extends React.Component<$FlowFixMeProps, any> {
_shareMessage: Function;
@@ -41,21 +39,19 @@ class ShareMessageExample extends React.Component<$FlowFixMeProps, any> {
this._showResult = this._showResult.bind(this);
this.state = {
result: ''
result: '',
};
}
render() {
return (
<View>
<TouchableHighlight style={styles.wrapper}
onPress={this._shareMessage}>
<TouchableHighlight style={styles.wrapper} onPress={this._shareMessage}>
<View style={styles.button}>
<Text>Click to share message</Text>
</View>
</TouchableHighlight>
<TouchableHighlight style={styles.wrapper}
onPress={this._shareText}>
<TouchableHighlight style={styles.wrapper} onPress={this._shareText}>
<View style={styles.button}>
<Text>Click to share message, URL and title</Text>
</View>
@@ -67,33 +63,37 @@ class ShareMessageExample extends React.Component<$FlowFixMeProps, any> {
_shareMessage() {
Share.share({
message: 'React Native | A framework for building native apps using React'
message:
'React Native | A framework for building native apps using React',
})
.then(this._showResult)
.catch((error) => this.setState({result: 'error: ' + error.message}));
.then(this._showResult)
.catch(error => this.setState({result: 'error: ' + error.message}));
}
_shareText() {
Share.share({
message: 'A framework for building native apps using React',
url: 'http://facebook.github.io/react-native/',
title: 'React Native'
}, {
subject: 'A subject to go in the email heading',
dialogTitle: 'Share React Native website',
excludedActivityTypes: [
'com.apple.UIKit.activity.PostToTwitter'
],
tintColor: 'green'
})
.then(this._showResult)
.catch((error) => this.setState({result: 'error: ' + error.message}));
Share.share(
{
message: 'A framework for building native apps using React',
url: 'http://facebook.github.io/react-native/',
title: 'React Native',
},
{
subject: 'A subject to go in the email heading',
dialogTitle: 'Share React Native website',
excludedActivityTypes: ['com.apple.UIKit.activity.PostToTwitter'],
tintColor: 'green',
},
)
.then(this._showResult)
.catch(error => this.setState({result: 'error: ' + error.message}));
}
_showResult(result) {
if (result.action === Share.sharedAction) {
if (result.activityType) {
this.setState({result: 'shared with an activityType: ' + result.activityType});
this.setState({
result: 'shared with an activityType: ' + result.activityType,
});
} else {
this.setState({result: 'shared'});
}
@@ -103,7 +103,6 @@ class ShareMessageExample extends React.Component<$FlowFixMeProps, any> {
}
}
var styles = StyleSheet.create({
wrapper: {
borderRadius: 5,

View File

@@ -4,18 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Slider,
Text,
StyleSheet,
View,
} = ReactNative;
var {Slider, Text, StyleSheet, View} = ReactNative;
class SliderExample extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
static defaultProps = {
@@ -29,18 +26,22 @@ class SliderExample extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
render() {
return (
<View>
<Text style={styles.text} >
<Text style={styles.text}>
{this.state.value && +this.state.value.toFixed(3)}
</Text>
<Slider
{...this.props}
onValueChange={(value) => this.setState({value: value})} />
onValueChange={value => this.setState({value: value})}
/>
</View>
);
}
}
class SlidingCompleteExample extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
class SlidingCompleteExample extends React.Component<
$FlowFixMeProps,
$FlowFixMeState,
> {
state = {
slideCompletionValue: 0,
slideCompletionCount: 0,
@@ -51,11 +52,16 @@ class SlidingCompleteExample extends React.Component<$FlowFixMeProps, $FlowFixMe
<View>
<SliderExample
{...this.props}
onSlidingComplete={(value) => this.setState({
onSlidingComplete={value =>
this.setState({
slideCompletionValue: value,
slideCompletionCount: this.state.slideCompletionCount + 1})} />
slideCompletionCount: this.state.slideCompletionCount + 1,
})
}
/>
<Text>
Completions: {this.state.slideCompletionCount} Value: {this.state.slideCompletionValue}
Completions: {this.state.slideCompletionCount} Value:{' '}
{this.state.slideCompletionValue}
</Text>
</View>
);
@@ -83,38 +89,31 @@ exports.examples = [
title: 'Default settings',
render(): React.Element<any> {
return <SliderExample />;
}
},
},
{
title: 'Initial value: 0.5',
render(): React.Element<any> {
return <SliderExample value={0.5} />;
}
},
},
{
title: 'minimumValue: -1, maximumValue: 2',
render(): React.Element<any> {
return (
<SliderExample
minimumValue={-1}
maximumValue={2}
/>
);
}
return <SliderExample minimumValue={-1} maximumValue={2} />;
},
},
{
title: 'step: 0.25',
render(): React.Element<any> {
return <SliderExample step={0.25} />;
}
},
},
{
title: 'onSlidingComplete',
render(): React.Element<any> {
return (
<SlidingCompleteExample />
);
}
return <SlidingCompleteExample />;
},
},
{
title: 'Custom min/max track tint color',
@@ -126,28 +125,28 @@ exports.examples = [
value={0.5}
/>
);
}
},
},
{
title: 'Custom thumb color',
platform: 'android',
render(): React.Element<any> {
return <SliderExample thumbTintColor={'blue'} />;
}
},
},
{
title: 'Custom thumb image',
platform: 'ios',
render(): React.Element<any> {
return <SliderExample thumbImage={require('./uie_thumb_big.png')} />;
}
},
},
{
title: 'Custom track image',
platform: 'ios',
render(): React.Element<any> {
return <SliderExample trackImage={require('./slider.png')} />;
}
},
},
{
title: 'Custom min/max track image',
@@ -159,6 +158,6 @@ exports.examples = [
maximumTrackImage={require('./slider-right.png')}
/>
);
}
},
},
];

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
@@ -23,22 +25,11 @@ exports.framework = 'React';
exports.title = '<StatusBar>';
exports.description = 'Component for controlling the status bar';
const colors = [
'#ff0000',
'#00ff00',
'#0000ff',
'rgba(0, 0, 0, 0.4)',
];
const colors = ['#ff0000', '#00ff00', '#0000ff', 'rgba(0, 0, 0, 0.4)'];
const barStyles = [
'default',
'light-content',
];
const barStyles = ['default', 'light-content'];
const showHideTransitions = [
'fade',
'slide',
];
const showHideTransitions = ['fade', 'slide'];
function getValue<T>(values: Array<T>, index: number): T {
return values[index % values.length];
@@ -64,7 +55,10 @@ class StatusBarHiddenExample extends React.Component<{}, $FlowFixMeState> {
_onChangeTransition = () => {
this._showHideTransitionIndex++;
this.setState({
showHideTransition: getValue(showHideTransitions, this._showHideTransitionIndex),
showHideTransition: getValue(
showHideTransitions,
this._showHideTransitionIndex,
),
});
};
@@ -87,7 +81,9 @@ class StatusBarHiddenExample extends React.Component<{}, $FlowFixMeState> {
style={styles.wrapper}
onPress={this._onChangeAnimated}>
<View style={styles.button}>
<Text>animated (ios only): {this.state.animated ? 'true' : 'false'}</Text>
<Text>
animated (ios only): {this.state.animated ? 'true' : 'false'}
</Text>
</View>
</TouchableHighlight>
<TouchableHighlight
@@ -95,8 +91,10 @@ class StatusBarHiddenExample extends React.Component<{}, $FlowFixMeState> {
onPress={this._onChangeTransition}>
<View style={styles.button}>
<Text>
showHideTransition (ios only):
'{getValue(showHideTransitions, this._showHideTransitionIndex)}'
showHideTransition (ios only): '{getValue(
showHideTransitions,
this._showHideTransitionIndex,
)}'
</Text>
</View>
</TouchableHighlight>
@@ -149,14 +147,18 @@ class StatusBarStyleExample extends React.Component<{}, $FlowFixMeState> {
}
}
class StatusBarNetworkActivityExample extends React.Component<{}, $FlowFixMeState> {
class StatusBarNetworkActivityExample extends React.Component<
{},
$FlowFixMeState,
> {
state = {
networkActivityIndicatorVisible: false,
};
_onChangeNetworkIndicatorVisible = () => {
this.setState({
networkActivityIndicatorVisible: !this.state.networkActivityIndicatorVisible,
networkActivityIndicatorVisible: !this.state
.networkActivityIndicatorVisible,
});
};
@@ -164,7 +166,9 @@ class StatusBarNetworkActivityExample extends React.Component<{}, $FlowFixMeStat
return (
<View>
<StatusBar
networkActivityIndicatorVisible={this.state.networkActivityIndicatorVisible}
networkActivityIndicatorVisible={
this.state.networkActivityIndicatorVisible
}
/>
<TouchableHighlight
style={styles.wrapper}
@@ -181,7 +185,10 @@ class StatusBarNetworkActivityExample extends React.Component<{}, $FlowFixMeStat
}
}
class StatusBarBackgroundColorExample extends React.Component<{}, $FlowFixMeState> {
class StatusBarBackgroundColorExample extends React.Component<
{},
$FlowFixMeState,
> {
state = {
animated: true,
backgroundColor: getValue(colors, 0),
@@ -238,14 +245,14 @@ class StatusBarTranslucentExample extends React.Component<{}, $FlowFixMeState> {
render() {
return (
<View>
<StatusBar
translucent={this.state.translucent}
/>
<StatusBar translucent={this.state.translucent} />
<TouchableHighlight
style={styles.wrapper}
onPress={this._onChangeTranslucent}>
<View style={styles.button}>
<Text>translucent: {this.state.translucent ? 'true' : 'false'}</Text>
<Text>
translucent: {this.state.translucent ? 'true' : 'false'}
</Text>
</View>
</TouchableHighlight>
</View>
@@ -363,7 +370,10 @@ class StatusBarStaticAndroidExample extends React.Component<{}> {
StatusBar.setBackgroundColor('rgba(0, 0, 0, 0.4)', true);
}}>
<View style={styles.button}>
<Text>setTranslucent(true) and setBackgroundColor('rgba(0, 0, 0, 0.4)', true)</Text>
<Text>
setTranslucent(true) and setBackgroundColor('rgba(0, 0, 0, 0.4)',
true)
</Text>
</View>
</TouchableHighlight>
<TouchableHighlight
@@ -373,7 +383,9 @@ class StatusBarStaticAndroidExample extends React.Component<{}> {
StatusBar.setBackgroundColor('black', true);
}}>
<View style={styles.button}>
<Text>setTranslucent(false) and setBackgroundColor('black', true)</Text>
<Text>
setTranslucent(false) and setBackgroundColor('black', true)
</Text>
</View>
</TouchableHighlight>
</View>
@@ -381,7 +393,6 @@ class StatusBarStaticAndroidExample extends React.Component<{}> {
}
}
class ModalExample extends React.Component<{}, $FlowFixMeState> {
state = {
modalVisible: false,
@@ -423,58 +434,67 @@ class ModalExample extends React.Component<{}, $FlowFixMeState> {
}
}
const examples = [{
title: 'StatusBar hidden',
render() {
return <StatusBarHiddenExample />;
const examples = [
{
title: 'StatusBar hidden',
render() {
return <StatusBarHiddenExample />;
},
},
}, {
title: 'StatusBar style',
render() {
return <StatusBarStyleExample />;
{
title: 'StatusBar style',
render() {
return <StatusBarStyleExample />;
},
platform: 'ios',
},
platform: 'ios',
}, {
title: 'StatusBar network activity indicator',
render() {
return <StatusBarNetworkActivityExample />;
{
title: 'StatusBar network activity indicator',
render() {
return <StatusBarNetworkActivityExample />;
},
platform: 'ios',
},
platform: 'ios',
}, {
title: 'StatusBar background color',
render() {
return <StatusBarBackgroundColorExample />;
{
title: 'StatusBar background color',
render() {
return <StatusBarBackgroundColorExample />;
},
platform: 'android',
},
platform: 'android',
}, {
title: 'StatusBar translucent',
render() {
return <StatusBarTranslucentExample />;
{
title: 'StatusBar translucent',
render() {
return <StatusBarTranslucentExample />;
},
platform: 'android',
},
platform: 'android',
}, {
title: 'StatusBar static API',
render() {
return <StatusBarStaticIOSExample />;
{
title: 'StatusBar static API',
render() {
return <StatusBarStaticIOSExample />;
},
platform: 'ios',
},
platform: 'ios',
}, {
title: 'StatusBar static API',
render() {
return <StatusBarStaticAndroidExample />;
{
title: 'StatusBar static API',
render() {
return <StatusBarStaticAndroidExample />;
},
platform: 'android',
},
platform: 'android',
}, {
title: 'StatusBar dimensions',
render() {
return (
<View>
<Text>Height (Android only): {StatusBar.currentHeight} pts</Text>
</View>
);
{
title: 'StatusBar dimensions',
render() {
return (
<View>
<Text>Height (Android only): {StatusBar.currentHeight} pts</Text>
</View>
);
},
platform: 'android',
},
platform: 'android',
}];
];
exports.examples = examples;
@@ -483,7 +503,7 @@ var styles = StyleSheet.create({
flex: 1,
justifyContent: 'center',
padding: 20,
backgroundColor: '#f5fcff'
backgroundColor: '#f5fcff',
},
innerContainer: {
borderRadius: 10,

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
@@ -27,7 +29,7 @@ var SwipeableListViewSimpleExample = createReactClass({
displayName: 'SwipeableListViewSimpleExample',
statics: {
title: '<SwipeableListView>',
description: 'Performant, scrollable, swipeable list of data.'
description: 'Performant, scrollable, swipeable list of data.',
},
getInitialState: function() {
@@ -52,15 +54,24 @@ var SwipeableListViewSimpleExample = createReactClass({
<SwipeableListView
dataSource={this.state.dataSource}
maxSwipeDistance={100}
renderQuickActions={
(rowData: Object, sectionID: string, rowID: string) => {
return (<View style={styles.actionsContainer}>
<TouchableHighlight onPress={() => {
Alert.alert('Tips', 'You could do something with this row: ' + rowData.text);
}}>
<Text>Remove</Text>
</TouchableHighlight>
</View>);
renderQuickActions={(
rowData: Object,
sectionID: string,
rowID: string,
) => {
return (
<View style={styles.actionsContainer}>
<TouchableHighlight
onPress={() => {
Alert.alert(
'Tips',
'You could do something with this row: ' + rowData.text,
);
}}>
<Text>Remove</Text>
</TouchableHighlight>
</View>
);
}}
renderRow={this._renderRow}
renderSeparator={this._renderSeperator}
@@ -69,7 +80,12 @@ var SwipeableListViewSimpleExample = createReactClass({
);
},
_renderRow: function(rowData: Object, sectionID: number, rowID: number, highlightRow: (sectionID: number, rowID: number) => void) {
_renderRow: function(
rowData: Object,
sectionID: number,
rowID: number,
highlightRow: (sectionID: number, rowID: number) => void,
) {
var rowHash = Math.abs(hashCode(rowData.id));
var imgSource = THUMB_URLS[rowHash % THUMB_URLS.length];
return (
@@ -109,13 +125,20 @@ var SwipeableListViewSimpleExample = createReactClass({
dataBlob['Section 0'] = {};
for (var ii = 0; ii < 100; ii++) {
var pressedText = pressData[ii] ? ' (pressed)' : '';
dataBlob[sectionIDs[0]]['Row ' + ii] = {id: 'Row ' + ii, text: 'Row ' + ii + pressedText};
dataBlob[sectionIDs[0]]['Row ' + ii] = {
id: 'Row ' + ii,
text: 'Row ' + ii + pressedText,
};
rowIDs[0].push('Row ' + ii);
}
return [dataBlob, sectionIDs, rowIDs];
},
_renderSeperator: function(sectionID: number, rowID: number, adjacentRowHighlighted: bool) {
_renderSeperator: function(
sectionID: number,
rowID: number,
adjacentRowHighlighted: boolean,
) {
return (
<View
key={`${sectionID}-${rowID}`}
@@ -125,7 +148,7 @@ var SwipeableListViewSimpleExample = createReactClass({
}}
/>
);
}
},
});
var THUMB_URLS = [
@@ -141,14 +164,15 @@ var THUMB_URLS = [
require('./Thumbnails/poke.png'),
require('./Thumbnails/superlike.png'),
require('./Thumbnails/victory.png'),
];
var LOREM_IPSUM = 'Lorem ipsum dolor sit amet, ius ad pertinax oportere accommodare, an vix civibus corrumpit referrentur. Te nam case ludus inciderint, te mea facilisi adipiscing. Sea id integre luptatum. In tota sale consequuntur nec. Erat ocurreret mei ei. Eu paulo sapientem vulputate est, vel an accusam intellegam interesset. Nam eu stet pericula reprimique, ea vim illud modus, putant invidunt reprehendunt ne qui.';
];
var LOREM_IPSUM =
'Lorem ipsum dolor sit amet, ius ad pertinax oportere accommodare, an vix civibus corrumpit referrentur. Te nam case ludus inciderint, te mea facilisi adipiscing. Sea id integre luptatum. In tota sale consequuntur nec. Erat ocurreret mei ei. Eu paulo sapientem vulputate est, vel an accusam intellegam interesset. Nam eu stet pericula reprimique, ea vim illud modus, putant invidunt reprehendunt ne qui.';
/* eslint no-bitwise: 0 */
var hashCode = function(str) {
var hash = 15;
for (var ii = str.length - 1; ii >= 0; ii--) {
hash = ((hash << 5) - hash) + str.charCodeAt(ii);
hash = (hash << 5) - hash + str.charCodeAt(ii);
}
return hash;
};

View File

@@ -4,18 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Platform,
Switch,
Text,
View
} = ReactNative;
var {Platform, Switch, Text, View} = ReactNative;
class BasicSwitchExample extends React.Component<{}, $FlowFixMeState> {
state = {
@@ -27,12 +24,14 @@ class BasicSwitchExample extends React.Component<{}, $FlowFixMeState> {
return (
<View>
<Switch
onValueChange={(value) => this.setState({falseSwitchIsOn: value})}
onValueChange={value => this.setState({falseSwitchIsOn: value})}
style={{marginBottom: 10}}
value={this.state.falseSwitchIsOn} />
value={this.state.falseSwitchIsOn}
/>
<Switch
onValueChange={(value) => this.setState({trueSwitchIsOn: value})}
value={this.state.trueSwitchIsOn} />
onValueChange={value => this.setState({trueSwitchIsOn: value})}
value={this.state.trueSwitchIsOn}
/>
</View>
);
}
@@ -42,13 +41,8 @@ class DisabledSwitchExample extends React.Component<{}> {
render() {
return (
<View>
<Switch
disabled={true}
style={{marginBottom: 10}}
value={true} />
<Switch
disabled={true}
value={false} />
<Switch disabled={true} style={{marginBottom: 10}} value={true} />
<Switch disabled={true} value={false} />
</View>
);
}
@@ -64,18 +58,20 @@ class ColorSwitchExample extends React.Component<{}, $FlowFixMeState> {
return (
<View>
<Switch
onValueChange={(value) => this.setState({colorFalseSwitchIsOn: value})}
onValueChange={value => this.setState({colorFalseSwitchIsOn: value})}
onTintColor="#00ff00"
style={{marginBottom: 10}}
thumbTintColor="#0000ff"
tintColor="#ff0000"
value={this.state.colorFalseSwitchIsOn} />
value={this.state.colorFalseSwitchIsOn}
/>
<Switch
onValueChange={(value) => this.setState({colorTrueSwitchIsOn: value})}
onValueChange={value => this.setState({colorTrueSwitchIsOn: value})}
onTintColor="#00ff00"
thumbTintColor="#0000ff"
tintColor="#ff0000"
value={this.state.colorTrueSwitchIsOn} />
value={this.state.colorTrueSwitchIsOn}
/>
</View>
);
}
@@ -89,27 +85,35 @@ class EventSwitchExample extends React.Component<{}, $FlowFixMeState> {
render() {
return (
<View style={{ flexDirection: 'row', justifyContent: 'space-around' }}>
<View style={{flexDirection: 'row', justifyContent: 'space-around'}}>
<View>
<Switch
onValueChange={(value) => this.setState({eventSwitchIsOn: value})}
onValueChange={value => this.setState({eventSwitchIsOn: value})}
style={{marginBottom: 10}}
value={this.state.eventSwitchIsOn} />
value={this.state.eventSwitchIsOn}
/>
<Switch
onValueChange={(value) => this.setState({eventSwitchIsOn: value})}
onValueChange={value => this.setState({eventSwitchIsOn: value})}
style={{marginBottom: 10}}
value={this.state.eventSwitchIsOn} />
value={this.state.eventSwitchIsOn}
/>
<Text>{this.state.eventSwitchIsOn ? 'On' : 'Off'}</Text>
</View>
<View>
<Switch
onValueChange={(value) => this.setState({eventSwitchRegressionIsOn: value})}
onValueChange={value =>
this.setState({eventSwitchRegressionIsOn: value})
}
style={{marginBottom: 10}}
value={this.state.eventSwitchRegressionIsOn} />
value={this.state.eventSwitchRegressionIsOn}
/>
<Switch
onValueChange={(value) => this.setState({eventSwitchRegressionIsOn: value})}
onValueChange={value =>
this.setState({eventSwitchRegressionIsOn: value})
}
style={{marginBottom: 10}}
value={this.state.eventSwitchRegressionIsOn} />
value={this.state.eventSwitchRegressionIsOn}
/>
<Text>{this.state.eventSwitchRegressionIsOn ? 'On' : 'Off'}</Text>
</View>
</View>
@@ -120,24 +124,34 @@ class EventSwitchExample extends React.Component<{}, $FlowFixMeState> {
var examples = [
{
title: 'Switches can be set to true or false',
render(): React.Element<any> { return <BasicSwitchExample />; }
render(): React.Element<any> {
return <BasicSwitchExample />;
},
},
{
title: 'Switches can be disabled',
render(): React.Element<any> { return <DisabledSwitchExample />; }
render(): React.Element<any> {
return <DisabledSwitchExample />;
},
},
{
title: 'Change events can be detected',
render(): React.Element<any> { return <EventSwitchExample />; }
render(): React.Element<any> {
return <EventSwitchExample />;
},
},
{
title: 'Switches are controlled components',
render(): React.Element<any> { return <Switch />; }
render(): React.Element<any> {
return <Switch />;
},
},
{
title: 'Custom colors can be provided',
render(): React.Element<any> { return <ColorSwitchExample />; }
}
render(): React.Element<any> {
return <ColorSwitchExample />;
},
},
];
exports.title = '<Switch>';

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
@@ -23,18 +25,25 @@ var {
exports.framework = 'React';
exports.title = 'TVEventHandler example';
exports.description = 'iOS alerts and action sheets';
exports.examples = [{
title: 'TVEventHandler',
render() {return <TVEventHandlerView/>;}
}];
exports.examples = [
{
title: 'TVEventHandler',
render() {
return <TVEventHandlerView />;
},
},
];
class TVEventHandlerView extends React.Component<$FlowFixMeProps, {
lastEventType: string
}> {
class TVEventHandlerView extends React.Component<
$FlowFixMeProps,
{
lastEventType: string,
},
> {
constructor(props) {
super(props);
this.state = {
lastEventType: ''
lastEventType: '',
};
}
@@ -44,7 +53,7 @@ class TVEventHandlerView extends React.Component<$FlowFixMeProps, {
this._tvEventHandler = new TVEventHandler();
this._tvEventHandler.enable(this, function(cmp, evt) {
cmp.setState({
lastEventType: evt.eventType
lastEventType: evt.eventType,
});
});
}
@@ -65,26 +74,23 @@ class TVEventHandlerView extends React.Component<$FlowFixMeProps, {
}
render() {
if (Platform.isTVOS) {
return (
<View>
<TouchableOpacity onPress={() => {}}>
<Text>
This example enables an instance of TVEventHandler to show the last event detected from the Apple TV Siri remote or from a keyboard.
</Text>
<Text>
This example enables an instance of TVEventHandler to show the
last event detected from the Apple TV Siri remote or from a
keyboard.
</Text>
</TouchableOpacity>
<Text style={{color: 'blue'}}>
{this.state.lastEventType}
</Text>
<Text style={{color: 'blue'}}>{this.state.lastEventType}</Text>
</View>
);
} else {
return (
<View>
<Text>
This example is intended to be run on Apple TV.
</Text>
<Text>This example is intended to be run on Apple TV.</Text>
</View>
);
}

View File

@@ -16,6 +16,7 @@
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @format
* @flow
*/
@@ -23,14 +24,10 @@
var React = require('react');
var ReactNative = require('react-native');
var {
StyleSheet,
TabBarIOS,
Text,
View,
} = ReactNative;
var {StyleSheet, TabBarIOS, Text, View} = ReactNative;
var base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAQAAACSR7JhAAADtUlEQVR4Ac3YA2Bj6QLH0XPT1Fzbtm29tW3btm3bfLZtv7e2ObZnms7d8Uw098tuetPzrxv8wiISrtVudrG2JXQZ4VOv+qUfmqCGGl1mqLhoA52oZlb0mrjsnhKpgeUNEs91Z0pd1kvihA3ULGVHiQO2narKSHKkEMulm9VgUyE60s1aWoMQUbpZOWE+kaqs4eLEjdIlZTcFZB0ndc1+lhB1lZrIuk5P2aib1NBpZaL+JaOGIt0ls47SKzLC7CqrlGF6RZ09HGoNy1lYl2aRSWL5GuzqWU1KafRdoRp0iOQEiDzgZPnG6DbldcomadViflnl/cL93tOoVbsOLVM2jylvdWjXolWX1hmfZbGR/wjypDjFLSZIRov09BgYmtUqPQPlQrPapecLgTIy0jMgPKtTeob2zWtrGH3xvjUkPCtNg/tm1rjwrMa+mdUkPd3hWbH0jArPGiU9ufCsNNWFZ40wpwn+62/66R2RUtoso1OB34tnLOcy7YB1fUdc9e0q3yru8PGM773vXsuZ5YIZX+5xmHwHGVvlrGPN6ZSiP1smOsMMde40wKv2VmwPPVXNut4sVpUreZiLBHi0qln/VQeI/LTMYXpsJtFiclUN+5HVZazim+Ky+7sAvxWnvjXrJFneVtLWLyPJu9K3cXLWeOlbMTlrIelbMDlrLenrjEQOtIF+fuI9xRp9ZBFp6+b6WT8RrxEpdK64BuvHgDk+vUy+b5hYk6zfyfs051gRoNO1usU12WWRWL73/MMEy9pMi9qIrR4ZpV16Rrvduxazmy1FSvuFXRkqTnE7m2kdb5U8xGjLw/spRr1uTov4uOgQE+0N/DvFrG/Jt7i/FzwxbA9kDanhf2w+t4V97G8lrT7wc08aA2QNUkuTfW/KimT01wdlfK4yEw030VfT0RtZbzjeMprNq8m8tnSTASrTLti64oBNdpmMQm0eEwvfPwRbUBywG5TzjPCsdwk3IeAXjQblLCoXnDVeoAz6SfJNk5TTzytCNZk/POtTSV40NwOFWzw86wNJRpubpXsn60NJFlHeqlYRbslqZm2jnEZ3qcSKgm0kTli3zZVS7y/iivZTweYXJ26Y+RTbV1zh3hYkgyFGSTKPfRVbRqWWVReaxYeSLarYv1Qqsmh1s95S7G+eEWK0f3jYKTbV6bOwepjfhtafsvUsqrQvrGC8YhmnO9cSCk3yuY984F1vesdHYhWJ5FvASlacshUsajFt2mUM9pqzvKGcyNJW0arTKN1GGGzQlH0tXwLDgQTurS8eIQAAAABJRU5ErkJggg==';
var base64Icon =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAQAAACSR7JhAAADtUlEQVR4Ac3YA2Bj6QLH0XPT1Fzbtm29tW3btm3bfLZtv7e2ObZnms7d8Uw098tuetPzrxv8wiISrtVudrG2JXQZ4VOv+qUfmqCGGl1mqLhoA52oZlb0mrjsnhKpgeUNEs91Z0pd1kvihA3ULGVHiQO2narKSHKkEMulm9VgUyE60s1aWoMQUbpZOWE+kaqs4eLEjdIlZTcFZB0ndc1+lhB1lZrIuk5P2aib1NBpZaL+JaOGIt0ls47SKzLC7CqrlGF6RZ09HGoNy1lYl2aRSWL5GuzqWU1KafRdoRp0iOQEiDzgZPnG6DbldcomadViflnl/cL93tOoVbsOLVM2jylvdWjXolWX1hmfZbGR/wjypDjFLSZIRov09BgYmtUqPQPlQrPapecLgTIy0jMgPKtTeob2zWtrGH3xvjUkPCtNg/tm1rjwrMa+mdUkPd3hWbH0jArPGiU9ufCsNNWFZ40wpwn+62/66R2RUtoso1OB34tnLOcy7YB1fUdc9e0q3yru8PGM773vXsuZ5YIZX+5xmHwHGVvlrGPN6ZSiP1smOsMMde40wKv2VmwPPVXNut4sVpUreZiLBHi0qln/VQeI/LTMYXpsJtFiclUN+5HVZazim+Ky+7sAvxWnvjXrJFneVtLWLyPJu9K3cXLWeOlbMTlrIelbMDlrLenrjEQOtIF+fuI9xRp9ZBFp6+b6WT8RrxEpdK64BuvHgDk+vUy+b5hYk6zfyfs051gRoNO1usU12WWRWL73/MMEy9pMi9qIrR4ZpV16Rrvduxazmy1FSvuFXRkqTnE7m2kdb5U8xGjLw/spRr1uTov4uOgQE+0N/DvFrG/Jt7i/FzwxbA9kDanhf2w+t4V97G8lrT7wc08aA2QNUkuTfW/KimT01wdlfK4yEw030VfT0RtZbzjeMprNq8m8tnSTASrTLti64oBNdpmMQm0eEwvfPwRbUBywG5TzjPCsdwk3IeAXjQblLCoXnDVeoAz6SfJNk5TTzytCNZk/POtTSV40NwOFWzw86wNJRpubpXsn60NJFlHeqlYRbslqZm2jnEZ3qcSKgm0kTli3zZVS7y/iivZTweYXJ26Y+RTbV1zh3hYkgyFGSTKPfRVbRqWWVReaxYeSLarYv1Qqsmh1s95S7G+eEWK0f3jYKTbV6bOwepjfhtafsvUsqrQvrGC8YhmnO9cSCk3yuY984F1vesdHYhWJ5FvASlacshUsajFt2mUM9pqzvKGcyNJW0arTKN1GGGzQlH0tXwLDgQTurS8eIQAAAABJRU5ErkJggg==';
class TabBarIOSBarStyleExample extends React.Component<{}> {
static title = '<TabBarIOS> - Custom Bar Style';
@@ -40,10 +37,7 @@ class TabBarIOSBarStyleExample extends React.Component<{}> {
render() {
return (
<TabBarIOS barStyle="black">
<TabBarIOS.Item
title="Tab"
icon={{uri: base64Icon, scale: 3}}
selected>
<TabBarIOS.Item title="Tab" icon={{uri: base64Icon, scale: 3}} selected>
<View style={styles.tabContent}>
<Text style={styles.tabText}>Single page</Text>
</View>

View File

@@ -4,20 +4,18 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
StyleSheet,
TabBarIOS,
Text,
View,
} = ReactNative;
var {StyleSheet, TabBarIOS, Text, View} = ReactNative;
var base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAQAAACSR7JhAAADtUlEQVR4Ac3YA2Bj6QLH0XPT1Fzbtm29tW3btm3bfLZtv7e2ObZnms7d8Uw098tuetPzrxv8wiISrtVudrG2JXQZ4VOv+qUfmqCGGl1mqLhoA52oZlb0mrjsnhKpgeUNEs91Z0pd1kvihA3ULGVHiQO2narKSHKkEMulm9VgUyE60s1aWoMQUbpZOWE+kaqs4eLEjdIlZTcFZB0ndc1+lhB1lZrIuk5P2aib1NBpZaL+JaOGIt0ls47SKzLC7CqrlGF6RZ09HGoNy1lYl2aRSWL5GuzqWU1KafRdoRp0iOQEiDzgZPnG6DbldcomadViflnl/cL93tOoVbsOLVM2jylvdWjXolWX1hmfZbGR/wjypDjFLSZIRov09BgYmtUqPQPlQrPapecLgTIy0jMgPKtTeob2zWtrGH3xvjUkPCtNg/tm1rjwrMa+mdUkPd3hWbH0jArPGiU9ufCsNNWFZ40wpwn+62/66R2RUtoso1OB34tnLOcy7YB1fUdc9e0q3yru8PGM773vXsuZ5YIZX+5xmHwHGVvlrGPN6ZSiP1smOsMMde40wKv2VmwPPVXNut4sVpUreZiLBHi0qln/VQeI/LTMYXpsJtFiclUN+5HVZazim+Ky+7sAvxWnvjXrJFneVtLWLyPJu9K3cXLWeOlbMTlrIelbMDlrLenrjEQOtIF+fuI9xRp9ZBFp6+b6WT8RrxEpdK64BuvHgDk+vUy+b5hYk6zfyfs051gRoNO1usU12WWRWL73/MMEy9pMi9qIrR4ZpV16Rrvduxazmy1FSvuFXRkqTnE7m2kdb5U8xGjLw/spRr1uTov4uOgQE+0N/DvFrG/Jt7i/FzwxbA9kDanhf2w+t4V97G8lrT7wc08aA2QNUkuTfW/KimT01wdlfK4yEw030VfT0RtZbzjeMprNq8m8tnSTASrTLti64oBNdpmMQm0eEwvfPwRbUBywG5TzjPCsdwk3IeAXjQblLCoXnDVeoAz6SfJNk5TTzytCNZk/POtTSV40NwOFWzw86wNJRpubpXsn60NJFlHeqlYRbslqZm2jnEZ3qcSKgm0kTli3zZVS7y/iivZTweYXJ26Y+RTbV1zh3hYkgyFGSTKPfRVbRqWWVReaxYeSLarYv1Qqsmh1s95S7G+eEWK0f3jYKTbV6bOwepjfhtafsvUsqrQvrGC8YhmnO9cSCk3yuY984F1vesdHYhWJ5FvASlacshUsajFt2mUM9pqzvKGcyNJW0arTKN1GGGzQlH0tXwLDgQTurS8eIQAAAABJRU5ErkJggg==';
var base64Icon =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAQAAACSR7JhAAADtUlEQVR4Ac3YA2Bj6QLH0XPT1Fzbtm29tW3btm3bfLZtv7e2ObZnms7d8Uw098tuetPzrxv8wiISrtVudrG2JXQZ4VOv+qUfmqCGGl1mqLhoA52oZlb0mrjsnhKpgeUNEs91Z0pd1kvihA3ULGVHiQO2narKSHKkEMulm9VgUyE60s1aWoMQUbpZOWE+kaqs4eLEjdIlZTcFZB0ndc1+lhB1lZrIuk5P2aib1NBpZaL+JaOGIt0ls47SKzLC7CqrlGF6RZ09HGoNy1lYl2aRSWL5GuzqWU1KafRdoRp0iOQEiDzgZPnG6DbldcomadViflnl/cL93tOoVbsOLVM2jylvdWjXolWX1hmfZbGR/wjypDjFLSZIRov09BgYmtUqPQPlQrPapecLgTIy0jMgPKtTeob2zWtrGH3xvjUkPCtNg/tm1rjwrMa+mdUkPd3hWbH0jArPGiU9ufCsNNWFZ40wpwn+62/66R2RUtoso1OB34tnLOcy7YB1fUdc9e0q3yru8PGM773vXsuZ5YIZX+5xmHwHGVvlrGPN6ZSiP1smOsMMde40wKv2VmwPPVXNut4sVpUreZiLBHi0qln/VQeI/LTMYXpsJtFiclUN+5HVZazim+Ky+7sAvxWnvjXrJFneVtLWLyPJu9K3cXLWeOlbMTlrIelbMDlrLenrjEQOtIF+fuI9xRp9ZBFp6+b6WT8RrxEpdK64BuvHgDk+vUy+b5hYk6zfyfs051gRoNO1usU12WWRWL73/MMEy9pMi9qIrR4ZpV16Rrvduxazmy1FSvuFXRkqTnE7m2kdb5U8xGjLw/spRr1uTov4uOgQE+0N/DvFrG/Jt7i/FzwxbA9kDanhf2w+t4V97G8lrT7wc08aA2QNUkuTfW/KimT01wdlfK4yEw030VfT0RtZbzjeMprNq8m8tnSTASrTLti64oBNdpmMQm0eEwvfPwRbUBywG5TzjPCsdwk3IeAXjQblLCoXnDVeoAz6SfJNk5TTzytCNZk/POtTSV40NwOFWzw86wNJRpubpXsn60NJFlHeqlYRbslqZm2jnEZ3qcSKgm0kTli3zZVS7y/iivZTweYXJ26Y+RTbV1zh3hYkgyFGSTKPfRVbRqWWVReaxYeSLarYv1Qqsmh1s95S7G+eEWK0f3jYKTbV6bOwepjfhtafsvUsqrQvrGC8YhmnO9cSCk3yuY984F1vesdHYhWJ5FvASlacshUsajFt2mUM9pqzvKGcyNJW0arTKN1GGGzQlH0tXwLDgQTurS8eIQAAAABJRU5ErkJggg==';
class TabBarExample extends React.Component<{}, $FlowFixMeState> {
static title = '<TabBarIOS>';
@@ -34,7 +32,9 @@ class TabBarExample extends React.Component<{}, $FlowFixMeState> {
return (
<View style={[styles.tabContent, {backgroundColor: color}]}>
<Text style={styles.tabText}>{pageText}</Text>
<Text style={styles.tabText}>{num} re-renders of the {pageText}</Text>
<Text style={styles.tabText}>
{num} re-renders of the {pageText}
</Text>
</View>
);
};
@@ -79,7 +79,7 @@ class TabBarExample extends React.Component<{}, $FlowFixMeState> {
onPress={() => {
this.setState({
selectedTab: 'greenTab',
presses: this.state.presses + 1
presses: this.state.presses + 1,
});
}}>
{this._renderContent('#21551C', 'Green Tab', this.state.presses)}

View File

@@ -4,18 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Image,
StyleSheet,
Text,
View,
} = ReactNative;
var {Image, StyleSheet, Text, View} = ReactNative;
var RNTesterBlock = require('./RNTesterBlock');
var RNTesterPage = require('./RNTesterPage');
@@ -34,25 +31,31 @@ class AttributeToggler extends React.Component<{}, $FlowFixMeState> {
toggleWeight = () => {
this.setState({
fontWeight: this.state.fontWeight === 'bold' ? 'normal' : 'bold'
fontWeight: this.state.fontWeight === 'bold' ? 'normal' : 'bold',
});
};
increaseSize = () => {
this.setState({
fontSize: this.state.fontSize + 1
fontSize: this.state.fontSize + 1,
});
};
render() {
var curStyle = {fontWeight: this.state.fontWeight, fontSize: this.state.fontSize};
var curStyle = {
fontWeight: this.state.fontWeight,
fontSize: this.state.fontSize,
};
return (
<View>
<Text style={curStyle}>
Tap the controls below to change attributes.
</Text>
<Text>
<Text>See how it will even work on <Text style={curStyle}>this nested text</Text></Text>
<Text>
See how it will even work on{' '}
<Text style={curStyle}>this nested text</Text>
</Text>
</Text>
<Text>
<Text onPress={this.toggleWeight}>Toggle Weight</Text>
@@ -75,8 +78,8 @@ class TextExample extends React.Component<{}> {
<RNTesterPage title="<Text>">
<RNTesterBlock title="Wrap">
<Text>
The text should wrap if it goes on multiple lines.
See, this is going to the next line.
The text should wrap if it goes on multiple lines. See, this is
going to the next line.
</Text>
</RNTesterBlock>
<RNTesterBlock title="Padding">
@@ -85,21 +88,15 @@ class TextExample extends React.Component<{}> {
</Text>
</RNTesterBlock>
<RNTesterBlock title="Font Family">
<Text style={{fontFamily: 'sans-serif'}}>
Sans-Serif
</Text>
<Text style={{fontFamily: 'sans-serif'}}>Sans-Serif</Text>
<Text style={{fontFamily: 'sans-serif', fontWeight: 'bold'}}>
Sans-Serif Bold
</Text>
<Text style={{fontFamily: 'serif'}}>
Serif
</Text>
<Text style={{fontFamily: 'serif'}}>Serif</Text>
<Text style={{fontFamily: 'serif', fontWeight: 'bold'}}>
Serif Bold
</Text>
<Text style={{fontFamily: 'monospace'}}>
Monospace
</Text>
<Text style={{fontFamily: 'monospace'}}>Monospace</Text>
<Text style={{fontFamily: 'monospace', fontWeight: 'bold'}}>
Monospace Bold (After 5.0)
</Text>
@@ -107,49 +104,63 @@ class TextExample extends React.Component<{}> {
<RNTesterBlock title="Android Material Design fonts">
<View style={{flexDirection: 'row', alignItems: 'flex-start'}}>
<View style={{flex: 1}}>
<Text style={{fontFamily: 'sans-serif'}}>
Roboto Regular
</Text>
<Text style={{fontFamily: 'sans-serif'}}>Roboto Regular</Text>
<Text style={{fontFamily: 'sans-serif', fontStyle: 'italic'}}>
Roboto Italic
</Text>
<Text style={{fontFamily: 'sans-serif', fontWeight: 'bold'}}>
Roboto Bold
</Text>
<Text style={{fontFamily: 'sans-serif', fontStyle: 'italic', fontWeight: 'bold'}}>
<Text
style={{
fontFamily: 'sans-serif',
fontStyle: 'italic',
fontWeight: 'bold',
}}>
Roboto Bold Italic
</Text>
<Text style={{fontFamily: 'sans-serif-light'}}>
Roboto Light
</Text>
<Text style={{fontFamily: 'sans-serif-light', fontStyle: 'italic'}}>
<Text style={{fontFamily: 'sans-serif-light'}}>Roboto Light</Text>
<Text
style={{fontFamily: 'sans-serif-light', fontStyle: 'italic'}}>
Roboto Light Italic
</Text>
<Text style={{fontFamily: 'sans-serif-thin'}}>
Roboto Thin (After 4.2)
</Text>
<Text style={{fontFamily: 'sans-serif-thin', fontStyle: 'italic'}}>
<Text
style={{fontFamily: 'sans-serif-thin', fontStyle: 'italic'}}>
Roboto Thin Italic (After 4.2)
</Text>
<Text style={{fontFamily: 'sans-serif-condensed'}}>
Roboto Condensed
</Text>
<Text style={{fontFamily: 'sans-serif-condensed', fontStyle: 'italic'}}>
Roboto Condensed Italic
</Text>
<Text style={{fontFamily: 'sans-serif-condensed', fontWeight: 'bold'}}>
Roboto Condensed Bold
</Text>
<Text style={{
<Text
style={{
fontFamily: 'sans-serif-condensed',
fontStyle: 'italic',
fontWeight: 'bold'}}>
}}>
Roboto Condensed Italic
</Text>
<Text
style={{
fontFamily: 'sans-serif-condensed',
fontWeight: 'bold',
}}>
Roboto Condensed Bold
</Text>
<Text
style={{
fontFamily: 'sans-serif-condensed',
fontStyle: 'italic',
fontWeight: 'bold',
}}>
Roboto Condensed Bold Italic
</Text>
<Text style={{fontFamily: 'sans-serif-medium'}}>
Roboto Medium (After 5.0)
</Text>
<Text style={{fontFamily: 'sans-serif-medium', fontStyle: 'italic'}}>
<Text
style={{fontFamily: 'sans-serif-medium', fontStyle: 'italic'}}>
Roboto Medium Italic (After 5.0)
</Text>
</View>
@@ -158,10 +169,13 @@ class TextExample extends React.Component<{}> {
<RNTesterBlock title="Custom Fonts">
<View style={{flexDirection: 'row', alignItems: 'flex-start'}}>
<View style={{flex: 1}}>
<Text style={{fontFamily: 'notoserif'}}>
NotoSerif Regular
</Text>
<Text style={{fontFamily: 'notoserif', fontStyle: 'italic', fontWeight: 'bold'}}>
<Text style={{fontFamily: 'notoserif'}}>NotoSerif Regular</Text>
<Text
style={{
fontFamily: 'notoserif',
fontStyle: 'italic',
fontWeight: 'bold',
}}>
NotoSerif Bold Italic
</Text>
<Text style={{fontFamily: 'notoserif', fontStyle: 'italic'}}>
@@ -172,36 +186,20 @@ class TextExample extends React.Component<{}> {
</RNTesterBlock>
<RNTesterBlock title="Font Size">
<Text style={{fontSize: 23}}>
Size 23
</Text>
<Text style={{fontSize: 8}}>
Size 8
</Text>
<Text style={{fontSize: 23}}>Size 23</Text>
<Text style={{fontSize: 8}}>Size 8</Text>
</RNTesterBlock>
<RNTesterBlock title="Color">
<Text style={{color: 'red'}}>
Red color
</Text>
<Text style={{color: 'blue'}}>
Blue color
</Text>
<Text style={{color: 'red'}}>Red color</Text>
<Text style={{color: 'blue'}}>Blue color</Text>
</RNTesterBlock>
<RNTesterBlock title="Font Weight">
<Text style={{fontWeight: 'bold'}}>
Move fast and be bold
</Text>
<Text style={{fontWeight: 'normal'}}>
Move fast and be bold
</Text>
<Text style={{fontWeight: 'bold'}}>Move fast and be bold</Text>
<Text style={{fontWeight: 'normal'}}>Move fast and be bold</Text>
</RNTesterBlock>
<RNTesterBlock title="Font Style">
<Text style={{fontStyle: 'italic'}}>
Move fast and be bold
</Text>
<Text style={{fontStyle: 'normal'}}>
Move fast and be bold
</Text>
<Text style={{fontStyle: 'italic'}}>Move fast and be bold</Text>
<Text style={{fontStyle: 'normal'}}>Move fast and be bold</Text>
</RNTesterBlock>
<RNTesterBlock title="Font Style and Weight">
<Text style={{fontStyle: 'italic', fontWeight: 'bold'}}>
@@ -209,20 +207,25 @@ class TextExample extends React.Component<{}> {
</Text>
</RNTesterBlock>
<RNTesterBlock title="Text Decoration">
<Text style={{textDecorationLine: 'underline'}}>
Solid underline
</Text>
<Text style={{textDecorationLine: 'none'}}>
None textDecoration
</Text>
<Text style={{textDecorationLine: 'line-through', textDecorationStyle: 'solid'}}>
<Text style={{textDecorationLine: 'underline'}}>Solid underline</Text>
<Text style={{textDecorationLine: 'none'}}>None textDecoration</Text>
<Text
style={{
textDecorationLine: 'line-through',
textDecorationStyle: 'solid',
}}>
Solid line-through
</Text>
<Text style={{textDecorationLine: 'underline line-through'}}>
Both underline and line-through
</Text>
<Text>
Mixed text with <Text style={{textDecorationLine: 'underline'}}>underline</Text> and <Text style={{textDecorationLine: 'line-through'}}>line-through</Text> text nodes
Mixed text with{' '}
<Text style={{textDecorationLine: 'underline'}}>underline</Text> and{' '}
<Text style={{textDecorationLine: 'line-through'}}>
line-through
</Text>{' '}
text nodes
</Text>
</RNTesterBlock>
<RNTesterBlock title="Nested">
@@ -249,11 +252,17 @@ class TextExample extends React.Component<{}> {
</Text>
</Text>
</Text>
<Text style={{fontWeight: 'bold'}} onPress={() => console.log('2nd')}>
<Text
style={{fontWeight: 'bold'}}
onPress={() => console.log('2nd')}>
(and bold
<Text style={{fontStyle: 'italic', fontSize: 11, color: '#527fe4'}} onPress={() => console.log('3rd')}>
<Text
style={{fontStyle: 'italic', fontSize: 11, color: '#527fe4'}}
onPress={() => console.log('3rd')}>
(and tiny bold italic blue
<Text style={{fontWeight: 'normal', fontStyle: 'normal'}} onPress={() => console.log('4th')}>
<Text
style={{fontWeight: 'normal', fontStyle: 'normal'}}
onPress={() => console.log('4th')}>
(and tiny normal blue)
</Text>
)
@@ -262,19 +271,29 @@ class TextExample extends React.Component<{}> {
</Text>
)
</Text>
<Text style={{fontFamily: 'serif'}} onPress={() => console.log('1st')}>
<Text
style={{fontFamily: 'serif'}}
onPress={() => console.log('1st')}>
(Serif
<Text style={{fontStyle: 'italic', fontWeight: 'bold'}} onPress={() => console.log('2nd')}>
<Text
style={{fontStyle: 'italic', fontWeight: 'bold'}}
onPress={() => console.log('2nd')}>
(Serif Bold Italic
<Text
style={{fontFamily: 'monospace', fontStyle: 'normal', fontWeight: 'normal'}}
style={{
fontFamily: 'monospace',
fontStyle: 'normal',
fontWeight: 'normal',
}}
onPress={() => console.log('3rd')}>
(Monospace Normal
<Text
style={{fontFamily: 'sans-serif', fontWeight: 'bold'}}
onPress={() => console.log('4th')}>
(Sans-Serif Bold
<Text style={{fontWeight: 'normal'}} onPress={() => console.log('5th')}>
<Text
style={{fontWeight: 'normal'}}
onPress={() => console.log('5th')}>
(and Sans-Serif Normal)
</Text>
)
@@ -290,20 +309,19 @@ class TextExample extends React.Component<{}> {
</Text>
</RNTesterBlock>
<RNTesterBlock title="Text Align">
<Text>
auto (default) - english LTR
</Text>
<Text>
أحب اللغة العربية auto (default) - arabic RTL
</Text>
<Text>auto (default) - english LTR</Text>
<Text>أحب اللغة العربية auto (default) - arabic RTL</Text>
<Text style={{textAlign: 'left'}}>
left left left left left left left left left left left left left left left
left left left left left left left left left left left left left
left left
</Text>
<Text style={{textAlign: 'center'}}>
center center center center center center center center center center center
center center center center center center center center center
center center
</Text>
<Text style={{textAlign: 'right'}}>
right right right right right right right right right right right right right
right right right right right right right right right right right
right right
</Text>
</RNTesterBlock>
<RNTesterBlock title="Unicode">
@@ -332,19 +350,19 @@ class TextExample extends React.Component<{}> {
</RNTesterBlock>
<RNTesterBlock title="Spaces">
<Text>
A {'generated'} {' '} {'string'} and some &nbsp;&nbsp;&nbsp; spaces
A {'generated'} {'string'} and some &nbsp;&nbsp;&nbsp; spaces
</Text>
</RNTesterBlock>
<RNTesterBlock title="Line Height">
<Text style={{lineHeight: 35}}>
Holisticly formulate inexpensive ideas before best-of-breed benefits. <Text style={{fontSize: 20}}>Continually</Text> expedite magnetic potentialities rather than client-focused interfaces.
Holisticly formulate inexpensive ideas before best-of-breed
benefits. <Text style={{fontSize: 20}}>Continually</Text> expedite
magnetic potentialities rather than client-focused interfaces.
</Text>
</RNTesterBlock>
<RNTesterBlock title="Letter Spacing">
<View>
<Text style={{letterSpacing: 0}}>
letterSpacing = 0
</Text>
<Text style={{letterSpacing: 0}}>letterSpacing = 0</Text>
<Text style={{letterSpacing: 2, marginTop: 5}}>
letterSpacing = 2
</Text>
@@ -352,14 +370,25 @@ class TextExample extends React.Component<{}> {
letterSpacing = 9
</Text>
<View style={{flexDirection: 'row'}}>
<Text style={{fontSize: 12, letterSpacing: 2, backgroundColor: 'fuchsia', marginTop: 5}}>
<Text
style={{
fontSize: 12,
letterSpacing: 2,
backgroundColor: 'fuchsia',
marginTop: 5,
}}>
With size and background color
</Text>
</View>
<Text style={{letterSpacing: -1, marginTop: 5}}>
letterSpacing = -1
</Text>
<Text style={{letterSpacing: 3, backgroundColor: '#dddddd', marginTop: 5}}>
<Text
style={{
letterSpacing: 3,
backgroundColor: '#dddddd',
marginTop: 5,
}}>
[letterSpacing = 3]
<Text style={{letterSpacing: 0, backgroundColor: '#bbbbbb'}}>
[Nested letterSpacing = 0]
@@ -380,11 +409,14 @@ class TextExample extends React.Component<{}> {
<Text style={{backgroundColor: '#ffaaaa'}}>
Red background,
<Text style={{backgroundColor: '#aaaaff'}}>
{' '}blue background,
{' '}
blue background,
<Text>
{' '}inherited blue background,
{' '}
inherited blue background,
<Text style={{backgroundColor: '#aaffaa'}}>
{' '}nested green background.
{' '}
nested green background.
</Text>
</Text>
</Text>
@@ -407,24 +439,32 @@ class TextExample extends React.Component<{}> {
<Text style={[styles.backgroundColorText, {top: -80}]}>
Default containerBackgroundColor (inherited) + backgroundColor wash
</Text>
<Text style={[styles.backgroundColorText, {top: -70, backgroundColor: 'transparent'}]}>
<Text
style={[
styles.backgroundColorText,
{top: -70, backgroundColor: 'transparent'},
]}>
{"containerBackgroundColor: 'transparent' + backgroundColor wash"}
</Text>
</RNTesterBlock>
<RNTesterBlock title="numberOfLines attribute">
<Text numberOfLines={1}>
Maximum of one line no matter now much I write here. If I keep writing it{"'"}ll just truncate after one line
Maximum of one line no matter now much I write here. If I keep
writing it{"'"}ll just truncate after one line
</Text>
<Text numberOfLines={2} style={{marginTop: 20}}>
Maximum of two lines no matter now much I write here. If I keep writing it{"'"}ll just truncate after two lines
Maximum of two lines no matter now much I write here. If I keep
writing it{"'"}ll just truncate after two lines
</Text>
<Text style={{marginTop: 20}}>
No maximum lines specified no matter now much I write here. If I keep writing it{"'"}ll just keep going and going
No maximum lines specified no matter now much I write here. If I
keep writing it{"'"}ll just keep going and going
</Text>
</RNTesterBlock>
<RNTesterBlock title="selectable attribute">
<Text selectable>
This text is selectable if you click-and-hold, and will offer the native Android selection menus.
This text is selectable if you click-and-hold, and will offer the
native Android selection menus.
</Text>
</RNTesterBlock>
<RNTesterBlock title="selectionColor attribute">
@@ -434,11 +474,18 @@ class TextExample extends React.Component<{}> {
</RNTesterBlock>
<RNTesterBlock title="Inline images">
<Text>
This text contains an inline image <Image source={require('./flux.png')}/>. Neat, huh?
This text contains an inline image{' '}
<Image source={require('./flux.png')} />. Neat, huh?
</Text>
</RNTesterBlock>
<RNTesterBlock title="Text shadow">
<Text style={{fontSize: 20, textShadowOffset: {width: 2, height: 2}, textShadowRadius: 1, textShadowColor: '#00cccc'}}>
<Text
style={{
fontSize: 20,
textShadowOffset: {width: 2, height: 2},
textShadowRadius: 1,
textShadowColor: '#00cccc',
}}>
Demo text shadow
</Text>
</RNTesterBlock>
@@ -457,21 +504,32 @@ class TextExample extends React.Component<{}> {
</Text>
</RNTesterBlock>
<RNTesterBlock title="Include Font Padding">
<View style={{flexDirection: 'row', justifyContent: 'space-around', marginBottom: 10}}>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-around',
marginBottom: 10,
}}>
<View style={{alignItems: 'center'}}>
<Text style={styles.includeFontPaddingText}>
Ey
</Text>
<Text style={styles.includeFontPaddingText}>Ey</Text>
<Text>Default</Text>
</View>
<View style={{alignItems: 'center'}}>
<Text style={[styles.includeFontPaddingText, {includeFontPadding: false, marginLeft: 10}]}>
<Text
style={[
styles.includeFontPaddingText,
{includeFontPadding: false, marginLeft: 10},
]}>
Ey
</Text>
<Text>includeFontPadding: false</Text>
</View>
</View>
<Text>By default Android will put extra space above text to allow for upper-case accents or other ascenders. With some fonts, this can make text look slightly misaligned when centered vertically.</Text>
<Text>
By default Android will put extra space above text to allow for
upper-case accents or other ascenders. With some fonts, this can
make text look slightly misaligned when centered vertically.
</Text>
</RNTesterBlock>
</RNTesterPage>
);
@@ -481,7 +539,7 @@ class TextExample extends React.Component<{}> {
var styles = StyleSheet.create({
backgroundColorText: {
left: 5,
backgroundColor: 'rgba(100, 100, 100, 0.3)'
backgroundColor: 'rgba(100, 100, 100, 0.3)',
},
includeFontPaddingText: {
fontSize: 120,
@@ -490,7 +548,7 @@ var styles = StyleSheet.create({
color: '#000000',
textAlignVertical: 'center',
alignSelf: 'center',
}
},
});
module.exports = TextExample;

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const Platform = require('Platform');
@@ -225,10 +227,16 @@ class TextBaseLineLayoutExample extends React.Component<*, *> {
render() {
var texts = [];
for (var i = 9; i >= 0; i--) {
texts.push(<Text key={i} style={{fontSize: 8 + i * 5, backgroundColor: '#eee'}}>{i}</Text>);
texts.push(
<Text key={i} style={{fontSize: 8 + i * 5, backgroundColor: '#eee'}}>
{i}
</Text>,
);
}
const marker = <View style={{width: 20, height: 20, backgroundColor: 'gray'}} />;
const marker = (
<View style={{width: 20, height: 20, backgroundColor: 'gray'}} />
);
const subtitleStyle = {fontSize: 16, marginTop: 8, fontWeight: 'bold'};
return (
@@ -236,9 +244,7 @@ class TextBaseLineLayoutExample extends React.Component<*, *> {
<Text style={subtitleStyle}>{'Nested <Text/>s:'}</Text>
<View style={{flexDirection: 'row', alignItems: 'baseline'}}>
{marker}
<Text>
{texts}
</Text>
<Text>{texts}</Text>
{marker}
</View>
@@ -254,7 +260,12 @@ class TextBaseLineLayoutExample extends React.Component<*, *> {
{marker}
<Text selectable={true}>
Some text.
<View style={{flexDirection: 'row', alignItems: 'baseline', backgroundColor: '#eee'}}>
<View
style={{
flexDirection: 'row',
alignItems: 'baseline',
backgroundColor: '#eee',
}}>
{marker}
<Text>Text inside View.</Text>
{marker}
@@ -266,9 +277,7 @@ class TextBaseLineLayoutExample extends React.Component<*, *> {
<Text style={subtitleStyle}>{'<TextInput/>:'}</Text>
<View style={{flexDirection: 'row', alignItems: 'baseline'}}>
{marker}
<TextInput style={{margin: 0, padding: 0}}>
{texts}
</TextInput>
<TextInput style={{margin: 0, padding: 0}}>{texts}</TextInput>
{marker}
</View>
@@ -575,14 +584,25 @@ exports.examples = [
letterSpacing = 9
</Text>
<View style={{flexDirection: 'row'}}>
<Text style={{fontSize: 12, letterSpacing: 2, backgroundColor: 'fuchsia', marginTop: 5}}>
<Text
style={{
fontSize: 12,
letterSpacing: 2,
backgroundColor: 'fuchsia',
marginTop: 5,
}}>
With size and background color
</Text>
</View>
<Text style={{letterSpacing: -1, marginTop: 5}}>
letterSpacing = -1
</Text>
<Text style={{letterSpacing: 3, backgroundColor: '#dddddd', marginTop: 5}}>
<Text
style={{
letterSpacing: 3,
backgroundColor: '#dddddd',
marginTop: 5,
}}>
[letterSpacing = 3]
<Text style={{letterSpacing: 0, backgroundColor: '#bbbbbb'}}>
[Nested letterSpacing = 0]
@@ -600,7 +620,7 @@ exports.examples = [
render: function() {
return (
<Text>
A {'generated'} {' '} {'string'} and some &nbsp;&nbsp;&nbsp; spaces
A {'generated'} {'string'} and some &nbsp;&nbsp;&nbsp; spaces
</Text>
);
},
@@ -719,8 +739,9 @@ exports.examples = [
</Text>
</Text>
<Text style={{marginTop: 10}}>
You can disable scaling for your Text component by passing {'"'}allowFontScaling={'{'}false{'}"'}{' '}
prop.
You can disable scaling for your Text component by passing {'"'}allowFontScaling={
'{'
}false{'}"'} prop.
</Text>
<Text allowFontScaling={false} style={{marginTop: 20}}>
This text will not scale.
@@ -830,11 +851,15 @@ exports.examples = [
This text has a view
<View style={{borderColor: 'red', borderWidth: 1}}>
<Text style={{borderColor: 'blue', borderWidth: 1}}>which has</Text>
<Text style={{borderColor: 'green', borderWidth: 1}}>another text inside.</Text>
<Text style={{borderColor: 'green', borderWidth: 1}}>
another text inside.
</Text>
<Text style={{borderColor: 'yellow', borderWidth: 1}}>
And moreover, it has another view
<View style={{borderColor: 'red', borderWidth: 1}}>
<Text style={{borderColor: 'blue', borderWidth: 1}}>with another text inside!</Text>
<Text style={{borderColor: 'blue', borderWidth: 1}}>
with another text inside!
</Text>
</View>
</Text>
</View>
@@ -856,42 +881,43 @@ exports.examples = [
},
},
{
title: 'Text `alignItems: \'baseline\'` style',
title: "Text `alignItems: 'baseline'` style",
render: function() {
return <TextBaseLineLayoutExample />;
}
},
},
{
title: 'Transform',
render: function() {
return (
<View>
<Text style={{ textTransform: 'uppercase'}}>
<Text style={{textTransform: 'uppercase'}}>
This text should be uppercased.
</Text>
<Text style={{ textTransform: 'lowercase'}}>
<Text style={{textTransform: 'lowercase'}}>
This TEXT SHOULD be lowercased.
</Text>
<Text style={{ textTransform: 'capitalize'}}>
<Text style={{textTransform: 'capitalize'}}>
This text should be CAPITALIZED.
</Text>
<Text style={{ textTransform: 'capitalize'}}>
Mixed:{' '}
<Text style={{ textTransform: 'uppercase'}}>
uppercase{' '}
</Text>
<Text style={{ textTransform: 'lowercase'}}>
LoWeRcAsE{' '}
</Text>
<Text style={{ textTransform: 'capitalize'}}>
<Text style={{textTransform: 'capitalize'}}>
Mixed: <Text style={{textTransform: 'uppercase'}}>uppercase </Text>
<Text style={{textTransform: 'lowercase'}}>LoWeRcAsE </Text>
<Text style={{textTransform: 'capitalize'}}>
capitalize each word
</Text>
</Text>
<Text>Should be "ABC":
<Text style={{ textTransform: 'uppercase' }}>a<Text>b</Text>c</Text>
<Text>
Should be "ABC":
<Text style={{textTransform: 'uppercase'}}>
a<Text>b</Text>c
</Text>
</Text>
<Text>Should be "AbC":
<Text style={{ textTransform: 'uppercase' }}>a<Text style={{ textTransform: 'none' }}>b</Text>c</Text>
<Text>
Should be "AbC":
<Text style={{textTransform: 'uppercase'}}>
a<Text style={{textTransform: 'none'}}>b</Text>c
</Text>
</Text>
</View>
);

View File

@@ -4,20 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Text,
TextInput,
View,
StyleSheet,
Slider,
Switch,
} = ReactNative;
var {Text, TextInput, View, StyleSheet, Slider, Switch} = ReactNative;
class TextEventsExample extends React.Component<{}, $FlowFixMeState> {
state = {
@@ -27,8 +22,8 @@ class TextEventsExample extends React.Component<{}, $FlowFixMeState> {
prev3Text: '<No Event>',
};
updateText = (text) => {
this.setState((state) => {
updateText = text => {
this.setState(state => {
return {
curText: text,
prevText: state.curText,
@@ -48,25 +43,28 @@ class TextEventsExample extends React.Component<{}, $FlowFixMeState> {
multiline
onFocus={() => this.updateText('onFocus')}
onBlur={() => this.updateText('onBlur')}
onChange={(event) => this.updateText(
'onChange text: ' + event.nativeEvent.text
)}
onContentSizeChange={(event) => this.updateText(
'onContentSizeChange size: ' + event.nativeEvent.contentSize
)}
onEndEditing={(event) => this.updateText(
'onEndEditing text: ' + event.nativeEvent.text
)}
onSubmitEditing={(event) => this.updateText(
'onSubmitEditing text: ' + event.nativeEvent.text
)}
onKeyPress={(event) => this.updateText(
'onKeyPress key: ' + event.nativeEvent.key
)}
onChange={event =>
this.updateText('onChange text: ' + event.nativeEvent.text)
}
onContentSizeChange={event =>
this.updateText(
'onContentSizeChange size: ' + event.nativeEvent.contentSize,
)
}
onEndEditing={event =>
this.updateText('onEndEditing text: ' + event.nativeEvent.text)
}
onSubmitEditing={event =>
this.updateText('onSubmitEditing text: ' + event.nativeEvent.text)
}
onKeyPress={event =>
this.updateText('onKeyPress key: ' + event.nativeEvent.key)
}
style={styles.singleLine}
/>
<Text style={styles.eventLabel}>
{this.state.curText}{'\n'}
{this.state.curText}
{'\n'}
(prev: {this.state.prevText}){'\n'}
(prev2: {this.state.prev2Text}){'\n'}
(prev3: {this.state.prev3Text})
@@ -90,7 +88,7 @@ class RewriteExample extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
<TextInput
multiline={false}
maxLength={limit}
onChangeText={(text) => {
onChangeText={text => {
text = text.replace(/ /g, '_');
this.setState({text});
}}
@@ -105,19 +103,23 @@ class RewriteExample extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
}
}
class TokenizedTextExample extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
class TokenizedTextExample extends React.Component<
$FlowFixMeProps,
$FlowFixMeState,
> {
constructor(props) {
super(props);
this.state = {text: 'Hello #World'};
}
render() {
//define delimiter
let delimiter = /\s+/;
//split string
let _text = this.state.text;
let token, index, parts = [];
let token,
index,
parts = [];
while (_text) {
delimiter.lastIndex = 0;
token = delimiter.exec(_text);
@@ -136,9 +138,13 @@ class TokenizedTextExample extends React.Component<$FlowFixMeProps, $FlowFixMeSt
parts.push(_text);
//highlight hashtags
parts = parts.map((text) => {
parts = parts.map(text => {
if (/^#/.test(text)) {
return <Text key={text} style={styles.hashtag}>{text}</Text>;
return (
<Text key={text} style={styles.hashtag}>
{text}
</Text>
);
} else {
return text;
}
@@ -149,7 +155,7 @@ class TokenizedTextExample extends React.Component<$FlowFixMeProps, $FlowFixMeSt
<TextInput
multiline={true}
style={styles.multiline}
onChangeText={(text) => {
onChangeText={text => {
this.setState({text});
}}>
<Text>{parts}</Text>
@@ -160,7 +166,7 @@ class TokenizedTextExample extends React.Component<$FlowFixMeProps, $FlowFixMeSt
}
class BlurOnSubmitExample extends React.Component<{}> {
focusNextField = (nextField) => {
focusNextField = nextField => {
this.refs[nextField].focus();
};
@@ -213,7 +219,10 @@ class BlurOnSubmitExample extends React.Component<{}> {
}
}
class ToggleDefaultPaddingExample extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
class ToggleDefaultPaddingExample extends React.Component<
$FlowFixMeProps,
$FlowFixMeState,
> {
constructor(props) {
super(props);
this.state = {hasPadding: false};
@@ -221,8 +230,9 @@ class ToggleDefaultPaddingExample extends React.Component<$FlowFixMeProps, $Flow
render() {
return (
<View>
<TextInput style={this.state.hasPadding ? { padding: 0 } : null}/>
<Text onPress={() => this.setState({hasPadding: !this.state.hasPadding})}>
<TextInput style={this.state.hasPadding ? {padding: 0} : null} />
<Text
onPress={() => this.setState({hasPadding: !this.state.hasPadding})}>
Toggle padding
</Text>
</View>
@@ -232,20 +242,23 @@ class ToggleDefaultPaddingExample extends React.Component<$FlowFixMeProps, $Flow
type SelectionExampleState = {
selection: {
start: number;
end: number;
};
value: string;
start: number,
end: number,
},
value: string,
};
class SelectionExample extends React.Component<$FlowFixMeProps, SelectionExampleState> {
class SelectionExample extends React.Component<
$FlowFixMeProps,
SelectionExampleState,
> {
_textInput: any;
constructor(props) {
super(props);
this.state = {
selection: {start: 0, end: 0},
value: props.value
value: props.value,
};
}
@@ -283,7 +296,7 @@ class SelectionExample extends React.Component<$FlowFixMeProps, SelectionExample
<View>
<TextInput
multiline={this.props.multiline}
onChangeText={(value) => this.setState({value})}
onChangeText={value => this.setState({value})}
onSelectionChange={this.onSelectionChange.bind(this)}
ref={textInput => (this._textInput = textInput)}
selection={this.state.selection}
@@ -291,24 +304,16 @@ class SelectionExample extends React.Component<$FlowFixMeProps, SelectionExample
value={this.state.value}
/>
<View>
<Text>
selection = {JSON.stringify(this.state.selection)}
</Text>
<Text>selection = {JSON.stringify(this.state.selection)}</Text>
<Text onPress={this.placeAt.bind(this, 0)}>
Place at Start (0, 0)
</Text>
<Text onPress={this.placeAt.bind(this, length)}>
Place at End ({length}, {length})
</Text>
<Text onPress={this.placeAtRandom.bind(this)}>
Place at Random
</Text>
<Text onPress={this.select.bind(this, 0, length)}>
Select All
</Text>
<Text onPress={this.selectRandom.bind(this)}>
Select Random
</Text>
<Text onPress={this.placeAtRandom.bind(this)}>Place at Random</Text>
<Text onPress={this.select.bind(this, 0, length)}>Select All</Text>
<Text onPress={this.selectRandom.bind(this)}>Select Random</Text>
</View>
</View>
);
@@ -316,7 +321,6 @@ class SelectionExample extends React.Component<$FlowFixMeProps, SelectionExample
}
class AutogrowingTextInputExample extends React.Component<{}> {
constructor(props) {
super(props);
@@ -347,19 +351,21 @@ class AutogrowingTextInputExample extends React.Component<{}> {
minimumValue={0}
maximumValue={100}
step={10}
onValueChange={(value) => this.setState({width: value})}
onValueChange={value => this.setState({width: value})}
/>
<Text>Multiline:</Text>
<Switch
value={this.state.multiline}
onValueChange={(value) => this.setState({multiline: value})}
onValueChange={value => this.setState({multiline: value})}
/>
<Text>TextInput:</Text>
<TextInput
multiline={this.state.multiline}
style={[style, {width: this.state.width + '%'}]}
onChangeText={(value) => this.setState({text: value})}
onContentSizeChange={(event) => this.setState({contentSize: event.nativeEvent.contentSize})}
onChangeText={value => this.setState({text: value})}
onContentSizeChange={event =>
this.setState({contentSize: event.nativeEvent.contentSize})
}
{...props}
/>
<Text>Plain text value representation:</Text>
@@ -405,24 +411,19 @@ exports.examples = [
accessibilityLabel="I am the accessibility label for text input"
/>
);
}
},
},
{
title: "Live Re-Write (<sp> -> '_')",
render: function() {
return <RewriteExample />;
}
},
},
{
title: 'Auto-capitalize',
render: function() {
var autoCapitalizeTypes = [
'none',
'sentences',
'words',
'characters',
];
var examples = autoCapitalizeTypes.map((type) => {
var autoCapitalizeTypes = ['none', 'sentences', 'words', 'characters'];
var examples = autoCapitalizeTypes.map(type => {
return (
<TextInput
key={type}
@@ -433,7 +434,7 @@ exports.examples = [
);
});
return <View>{examples}</View>;
}
},
},
{
title: 'Auto-correct',
@@ -452,18 +453,13 @@ exports.examples = [
/>
</View>
);
}
},
},
{
title: 'Keyboard types',
render: function() {
var keyboardTypes = [
'default',
'email-address',
'numeric',
'phone-pad',
];
var examples = keyboardTypes.map((type) => {
var keyboardTypes = ['default', 'email-address', 'numeric', 'phone-pad'];
var examples = keyboardTypes.map(type => {
return (
<TextInput
key={type}
@@ -474,15 +470,19 @@ exports.examples = [
);
});
return <View>{examples}</View>;
}
},
},
{
title: 'Blur on submit',
render: function(): React.Element<any> { return <BlurOnSubmitExample />; },
render: function(): React.Element<any> {
return <BlurOnSubmitExample />;
},
},
{
title: 'Event handling',
render: function(): React.Element<any> { return <TextEventsExample />; },
render: function(): React.Element<any> {
return <TextEventsExample />;
},
},
{
title: 'Colors and text inputs',
@@ -517,7 +517,10 @@ exports.examples = [
/>
<TextInput
defaultValue="Same BackgroundColor as View "
style={[styles.singleLine, {backgroundColor: 'rgba(100, 100, 100, 0.3)'}]}>
style={[
styles.singleLine,
{backgroundColor: 'rgba(100, 100, 100, 0.3)'},
]}>
<Text style={{backgroundColor: 'rgba(100, 100, 100, 0.3)'}}>
Darker backgroundColor
</Text>
@@ -525,10 +528,11 @@ exports.examples = [
<TextInput
defaultValue="Highlight Color is red"
selectionColor={'red'}
style={styles.singleLine} />
style={styles.singleLine}
/>
</View>
);
}
},
},
{
title: 'Text input, themes and heights',
@@ -539,7 +543,7 @@ exports.examples = [
style={[styles.singleLineWithHeightTextInput]}
/>
);
}
},
},
{
title: 'fontFamily, fontWeight and fontStyle',
@@ -551,11 +555,17 @@ exports.examples = [
placeholder="Custom fonts like Sans-Serif are supported"
/>
<TextInput
style={[styles.singleLine, {fontFamily: 'sans-serif', fontWeight: 'bold'}]}
style={[
styles.singleLine,
{fontFamily: 'sans-serif', fontWeight: 'bold'},
]}
placeholder="Sans-Serif bold"
/>
<TextInput
style={[styles.singleLine, {fontFamily: 'sans-serif', fontStyle: 'italic'}]}
style={[
styles.singleLine,
{fontFamily: 'sans-serif', fontStyle: 'italic'},
]}
placeholder="Sans-Serif italic"
/>
<TextInput
@@ -564,7 +574,7 @@ exports.examples = [
/>
</View>
);
}
},
},
{
title: 'letterSpacing',
@@ -589,7 +599,7 @@ exports.examples = [
/>
</View>
);
}
},
},
{
title: 'Passwords',
@@ -609,19 +619,19 @@ exports.examples = [
/>
</View>
);
}
},
},
{
title: 'Editable',
render: function() {
return (
<TextInput
defaultValue="Can't touch this! (>'-')> ^(' - ')^ <('-'<) (>'-')> ^(' - ')^"
editable={false}
style={styles.singleLine}
/>
defaultValue="Can't touch this! (>'-')> ^(' - ')^ <('-'<) (>'-')> ^(' - ')^"
editable={false}
style={styles.singleLine}
/>
);
}
},
},
{
title: 'Multiline',
@@ -633,24 +643,36 @@ exports.examples = [
placeholder="multiline, aligned top-left"
placeholderTextColor="red"
multiline={true}
style={[styles.multiline, {textAlign: 'left', textAlignVertical: 'top'}]}
style={[
styles.multiline,
{textAlign: 'left', textAlignVertical: 'top'},
]}
/>
<TextInput
autoCorrect={true}
placeholder="multiline, aligned center"
placeholderTextColor="green"
multiline={true}
style={[styles.multiline, {textAlign: 'center', textAlignVertical: 'center'}]}
style={[
styles.multiline,
{textAlign: 'center', textAlignVertical: 'center'},
]}
/>
<TextInput
autoCorrect={true}
multiline={true}
style={[styles.multiline, {color: 'blue'}, {textAlign: 'right', textAlignVertical: 'bottom'}]}>
<Text style={styles.multiline}>multiline with children, aligned bottom-right</Text>
style={[
styles.multiline,
{color: 'blue'},
{textAlign: 'right', textAlignVertical: 'bottom'},
]}>
<Text style={styles.multiline}>
multiline with children, aligned bottom-right
</Text>
</TextInput>
</View>
);
}
},
},
{
title: 'Fixed number of lines',
@@ -658,17 +680,19 @@ exports.examples = [
render: function() {
return (
<View>
<TextInput numberOfLines={2}
<TextInput
numberOfLines={2}
multiline={true}
placeholder="Two line input"
/>
<TextInput numberOfLines={5}
<TextInput
numberOfLines={5}
multiline={true}
placeholder="Five line input"
/>
</View>
);
}
},
},
{
title: 'Auto-expanding',
@@ -679,8 +703,7 @@ exports.examples = [
enablesReturnKeyAutomatically={true}
returnKeyType="done"
multiline={true}
style={{maxHeight: 400, minHeight: 20, backgroundColor: '#eeeeee'}}
>
style={{maxHeight: 400, minHeight: 20, backgroundColor: '#eeeeee'}}>
generic generic generic
<Text style={{fontSize: 6, color: 'red'}}>
small small small small small small
@@ -693,13 +716,13 @@ exports.examples = [
</AutogrowingTextInputExample>
</View>
);
}
},
},
{
title: 'Attributed text',
render: function() {
return <TokenizedTextExample />;
}
},
},
{
title: 'Return key',
@@ -713,11 +736,8 @@ exports.examples = [
'previous',
'next',
];
var returnKeyLabels = [
'Compile',
'React Native',
];
var examples = returnKeyTypes.map((type) => {
var returnKeyLabels = ['Compile', 'React Native'];
var examples = returnKeyTypes.map(type => {
return (
<TextInput
key={type}
@@ -727,7 +747,7 @@ exports.examples = [
/>
);
});
var types = returnKeyLabels.map((type) => {
var types = returnKeyLabels.map(type => {
return (
<TextInput
key={type}
@@ -737,8 +757,13 @@ exports.examples = [
/>
);
});
return <View>{examples}{types}</View>;
}
return (
<View>
{examples}
{types}
</View>
);
},
},
{
title: 'Inline Images',
@@ -762,11 +787,13 @@ exports.examples = [
/>
</View>
);
}
},
},
{
title: 'Toggle Default Padding',
render: function(): React.Element<any> { return <ToggleDefaultPaddingExample />; },
render: function(): React.Element<any> {
return <ToggleDefaultPaddingExample />;
},
},
{
title: 'Text selection & cursor placement',
@@ -784,6 +811,6 @@ exports.examples = [
/>
</View>
);
}
},
},
];

View File

@@ -4,22 +4,17 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const Button = require('Button');
const InputAccessoryView = require('InputAccessoryView');
var React = require('react');
var ReactNative = require('react-native');
var {
Text,
TextInput,
View,
StyleSheet,
Slider,
Switch,
} = ReactNative;
var {Text, TextInput, View, StyleSheet, Slider, Switch} = ReactNative;
class WithLabel extends React.Component<$FlowFixMeProps> {
render() {
@@ -42,8 +37,8 @@ class TextEventsExample extends React.Component<{}, $FlowFixMeState> {
prev3Text: '<No Event>',
};
updateText = (text) => {
this.setState((state) => {
updateText = text => {
this.setState(state => {
return {
curText: text,
prevText: state.curText,
@@ -62,27 +57,31 @@ class TextEventsExample extends React.Component<{}, $FlowFixMeState> {
autoCorrect={false}
onFocus={() => this.updateText('onFocus')}
onBlur={() => this.updateText('onBlur')}
onChange={(event) => this.updateText(
'onChange text: ' + event.nativeEvent.text
)}
onEndEditing={(event) => this.updateText(
'onEndEditing text: ' + event.nativeEvent.text
)}
onSubmitEditing={(event) => this.updateText(
'onSubmitEditing text: ' + event.nativeEvent.text
)}
onSelectionChange={(event) => this.updateText(
'onSelectionChange range: ' +
event.nativeEvent.selection.start + ',' +
event.nativeEvent.selection.end
)}
onKeyPress={(event) => {
onChange={event =>
this.updateText('onChange text: ' + event.nativeEvent.text)
}
onEndEditing={event =>
this.updateText('onEndEditing text: ' + event.nativeEvent.text)
}
onSubmitEditing={event =>
this.updateText('onSubmitEditing text: ' + event.nativeEvent.text)
}
onSelectionChange={event =>
this.updateText(
'onSelectionChange range: ' +
event.nativeEvent.selection.start +
',' +
event.nativeEvent.selection.end,
)
}
onKeyPress={event => {
this.updateText('onKeyPress key: ' + event.nativeEvent.key);
}}
style={styles.default}
/>
<Text style={styles.eventLabel}>
{this.state.curText}{'\n'}
{this.state.curText}
{'\n'}
(prev: {this.state.prevText}){'\n'}
(prev2: {this.state.prev2Text}){'\n'}
(prev3: {this.state.prev3Text})
@@ -135,7 +134,7 @@ class RewriteExample extends React.Component<$FlowFixMeProps, any> {
<TextInput
multiline={false}
maxLength={limit}
onChangeText={(text) => {
onChangeText={text => {
text = text.replace(/ /g, '_');
this.setState({text});
}}
@@ -150,7 +149,10 @@ class RewriteExample extends React.Component<$FlowFixMeProps, any> {
}
}
class RewriteExampleInvalidCharacters extends React.Component<$FlowFixMeProps, any> {
class RewriteExampleInvalidCharacters extends React.Component<
$FlowFixMeProps,
any,
> {
constructor(props) {
super(props);
this.state = {text: ''};
@@ -160,7 +162,7 @@ class RewriteExampleInvalidCharacters extends React.Component<$FlowFixMeProps, a
<View style={styles.rewriteContainer}>
<TextInput
multiline={false}
onChangeText={(text) => {
onChangeText={text => {
this.setState({text: text.replace(/\s/g, '')});
}}
style={styles.default}
@@ -177,13 +179,14 @@ class TokenizedTextExample extends React.Component<$FlowFixMeProps, any> {
this.state = {text: 'Hello #World'};
}
render() {
//define delimiter
let delimiter = /\s+/;
//split string
let _text = this.state.text;
let token, index, parts = [];
let token,
index,
parts = [];
while (_text) {
delimiter.lastIndex = 0;
token = delimiter.exec(_text);
@@ -202,9 +205,13 @@ class TokenizedTextExample extends React.Component<$FlowFixMeProps, any> {
parts.push(_text);
//highlight hashtags
parts = parts.map((text) => {
parts = parts.map(text => {
if (/^#/.test(text)) {
return <Text key={text} style={styles.hashtag}>{text}</Text>;
return (
<Text key={text} style={styles.hashtag}>
{text}
</Text>
);
} else {
return text;
}
@@ -215,7 +222,7 @@ class TokenizedTextExample extends React.Component<$FlowFixMeProps, any> {
<TextInput
multiline={true}
style={styles.multiline}
onChangeText={(text) => {
onChangeText={text => {
this.setState({text});
}}>
<Text>{parts}</Text>
@@ -226,7 +233,7 @@ class TokenizedTextExample extends React.Component<$FlowFixMeProps, any> {
}
class BlurOnSubmitExample extends React.Component<{}> {
focusNextField = (nextField) => {
focusNextField = nextField => {
this.refs[nextField].focus();
};
@@ -282,20 +289,23 @@ class BlurOnSubmitExample extends React.Component<{}> {
type SelectionExampleState = {
selection: {
start: number;
end?: number;
};
value: string;
start: number,
end?: number,
},
value: string,
};
class SelectionExample extends React.Component<$FlowFixMeProps, SelectionExampleState> {
class SelectionExample extends React.Component<
$FlowFixMeProps,
SelectionExampleState,
> {
_textInput: any;
constructor(props) {
super(props);
this.state = {
selection: {start: 0, end: 0},
value: props.value
value: props.value,
};
}
@@ -314,7 +324,9 @@ class SelectionExample extends React.Component<$FlowFixMeProps, SelectionExample
}
selectRandom() {
var positions = [this.getRandomPosition(), this.getRandomPosition()].sort((a, b) => a - b);
var positions = [this.getRandomPosition(), this.getRandomPosition()].sort(
(a, b) => a - b,
);
this.select(...positions);
}
@@ -333,7 +345,7 @@ class SelectionExample extends React.Component<$FlowFixMeProps, SelectionExample
<View>
<TextInput
multiline={this.props.multiline}
onChangeText={(value) => this.setState({value})}
onChangeText={value => this.setState({value})}
onSelectionChange={this.onSelectionChange.bind(this)}
ref={textInput => (this._textInput = textInput)}
selection={this.state.selection}
@@ -341,31 +353,26 @@ class SelectionExample extends React.Component<$FlowFixMeProps, SelectionExample
value={this.state.value}
/>
<View>
<Text>
selection = {JSON.stringify(this.state.selection)}
</Text>
<Text>selection = {JSON.stringify(this.state.selection)}</Text>
<Text onPress={this.placeAt.bind(this, 0)}>
Place at Start (0, 0)
</Text>
<Text onPress={this.placeAt.bind(this, length)}>
Place at End ({length}, {length})
</Text>
<Text onPress={this.placeAtRandom.bind(this)}>
Place at Random
</Text>
<Text onPress={this.select.bind(this, 0, length)}>
Select All
</Text>
<Text onPress={this.selectRandom.bind(this)}>
Select Random
</Text>
<Text onPress={this.placeAtRandom.bind(this)}>Place at Random</Text>
<Text onPress={this.select.bind(this, 0, length)}>Select All</Text>
<Text onPress={this.selectRandom.bind(this)}>Select Random</Text>
</View>
</View>
);
}
}
class AutogrowingTextInputExample extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
class AutogrowingTextInputExample extends React.Component<
$FlowFixMeProps,
$FlowFixMeState,
> {
constructor(props) {
super(props);
@@ -396,20 +403,22 @@ class AutogrowingTextInputExample extends React.Component<$FlowFixMeProps, $Flow
minimumValue={0}
maximumValue={100}
step={10}
onValueChange={(value) => this.setState({width: value})}
onValueChange={value => this.setState({width: value})}
/>
<Text>Multiline:</Text>
<Switch
value={this.state.multiline}
onValueChange={(value) => this.setState({multiline: value})}
onValueChange={value => this.setState({multiline: value})}
/>
<Text>TextInput:</Text>
<TextInput
value="prop"
multiline={this.state.multiline}
style={[style, {width: this.state.width + '%'}]}
onChangeText={(value) => this.setState({text: value})}
onContentSizeChange={(event) => this.setState({contentSize: event.nativeEvent.contentSize})}
onChangeText={value => this.setState({text: value})}
onContentSizeChange={event =>
this.setState({contentSize: event.nativeEvent.contentSize})
}
{...props}
/>
<Text>Plain text value representation:</Text>
@@ -501,25 +510,25 @@ exports.examples = [
accessibilityLabel="I am the accessibility label for text input"
/>
);
}
},
},
{
title: "Live Re-Write (<sp> -> '_') + maxLength",
render: function() {
return <RewriteExample />;
}
},
},
{
title: 'Live Re-Write (no spaces allowed)',
render: function() {
return <RewriteExampleInvalidCharacters />;
}
},
},
{
title: 'Keyboard Accessory View',
render: function() {
return <TextInputAccessoryViewExample />;
}
},
},
{
title: 'Auto-capitalize',
@@ -527,32 +536,20 @@ exports.examples = [
return (
<View>
<WithLabel label="none">
<TextInput
autoCapitalize="none"
style={styles.default}
/>
<TextInput autoCapitalize="none" style={styles.default} />
</WithLabel>
<WithLabel label="sentences">
<TextInput
autoCapitalize="sentences"
style={styles.default}
/>
<TextInput autoCapitalize="sentences" style={styles.default} />
</WithLabel>
<WithLabel label="words">
<TextInput
autoCapitalize="words"
style={styles.default}
/>
<TextInput autoCapitalize="words" style={styles.default} />
</WithLabel>
<WithLabel label="characters">
<TextInput
autoCapitalize="characters"
style={styles.default}
/>
<TextInput autoCapitalize="characters" style={styles.default} />
</WithLabel>
</View>
);
}
},
},
{
title: 'Auto-correct',
@@ -567,7 +564,7 @@ exports.examples = [
</WithLabel>
</View>
);
}
},
},
{
title: 'Nested content and `value` property',
@@ -582,7 +579,10 @@ exports.examples = [
</TextInput>
</WithLabel>
<WithLabel label="multiline">
<TextInput style={styles.default} multiline={true} value="(value property)">
<TextInput
style={styles.default}
multiline={true}
value="(value property)">
(first raw text node)
<Text color="red">(internal raw text node)</Text>
(last raw text node)
@@ -590,7 +590,7 @@ exports.examples = [
</WithLabel>
</View>
);
}
},
},
{
title: 'Keyboard types',
@@ -609,39 +609,29 @@ exports.examples = [
'web-search',
'numeric',
];
var examples = keyboardTypes.map((type) => {
var examples = keyboardTypes.map(type => {
return (
<WithLabel key={type} label={type}>
<TextInput
keyboardType={type}
style={styles.default}
/>
<TextInput keyboardType={type} style={styles.default} />
</WithLabel>
);
});
return <View>{examples}</View>;
}
},
},
{
title: 'Keyboard appearance',
render: function() {
var keyboardAppearance = [
'default',
'light',
'dark',
];
var examples = keyboardAppearance.map((type) => {
var keyboardAppearance = ['default', 'light', 'dark'];
var examples = keyboardAppearance.map(type => {
return (
<WithLabel key={type} label={type}>
<TextInput
keyboardAppearance={type}
style={styles.default}
/>
<TextInput keyboardAppearance={type} style={styles.default} />
</WithLabel>
);
});
return <View>{examples}</View>;
}
},
},
{
title: 'Return key types',
@@ -659,18 +649,15 @@ exports.examples = [
'done',
'emergency-call',
];
var examples = returnKeyTypes.map((type) => {
var examples = returnKeyTypes.map(type => {
return (
<WithLabel key={type} label={type}>
<TextInput
returnKeyType={type}
style={styles.default}
/>
<TextInput returnKeyType={type} style={styles.default} />
</WithLabel>
);
});
return <View>{examples}</View>;
}
},
},
{
title: 'Enable return key automatically',
@@ -678,11 +665,14 @@ exports.examples = [
return (
<View>
<WithLabel label="true">
<TextInput enablesReturnKeyAutomatically={true} style={styles.default} />
<TextInput
enablesReturnKeyAutomatically={true}
style={styles.default}
/>
</WithLabel>
</View>
);
}
},
},
{
title: 'Secure text entry',
@@ -690,15 +680,21 @@ exports.examples = [
return (
<View>
<WithLabel label="true">
<TextInput secureTextEntry={true} style={styles.default} defaultValue="abc" />
<TextInput
secureTextEntry={true}
style={styles.default}
defaultValue="abc"
/>
</WithLabel>
</View>
);
}
},
},
{
title: 'Event handling',
render: function(): React.Element<any> { return <TextEventsExample />; },
render: function(): React.Element<any> {
return <TextEventsExample />;
},
},
{
title: 'Colored input text',
@@ -715,7 +711,7 @@ exports.examples = [
/>
</View>
);
}
},
},
{
title: 'Colored highlight/cursor for text input',
@@ -734,24 +730,18 @@ exports.examples = [
/>
</View>
);
}
},
},
{
title: 'Clear button mode',
render: function () {
render: function() {
return (
<View>
<WithLabel label="never">
<TextInput
style={styles.default}
clearButtonMode="never"
/>
<TextInput style={styles.default} clearButtonMode="never" />
</WithLabel>
<WithLabel label="while editing">
<TextInput
style={styles.default}
clearButtonMode="while-editing"
/>
<TextInput style={styles.default} clearButtonMode="while-editing" />
</WithLabel>
<WithLabel label="unless editing">
<TextInput
@@ -760,14 +750,11 @@ exports.examples = [
/>
</WithLabel>
<WithLabel label="always">
<TextInput
style={styles.default}
clearButtonMode="always"
/>
<TextInput style={styles.default} clearButtonMode="always" />
</WithLabel>
</View>
);
}
},
},
{
title: 'Clear and select',
@@ -810,11 +797,13 @@ exports.examples = [
</WithLabel>
</View>
);
}
},
},
{
title: 'Blur on submit',
render: function(): React.Element<any> { return <BlurOnSubmitExample />; },
render: function(): React.Element<any> {
return <BlurOnSubmitExample />;
},
},
{
title: 'Multiline blur on submit',
@@ -831,7 +820,7 @@ exports.examples = [
/>
</View>
);
}
},
},
{
title: 'Multiline',
@@ -874,7 +863,7 @@ exports.examples = [
/>
</View>
);
}
},
},
{
title: 'TextInput Intrinsic Size',
@@ -914,7 +903,7 @@ exports.examples = [
borderBottomRightRadius: 20,
padding: 10,
paddingTop: 20,
maxHeight: 100
maxHeight: 100,
}}
testID="multiline_textinput"
multiline={true}
@@ -941,7 +930,7 @@ exports.examples = [
</View>
</View>
);
}
},
},
{
title: 'Auto-expanding',
@@ -958,7 +947,7 @@ exports.examples = [
/>
</View>
);
}
},
},
{
title: 'Auto-expanding',
@@ -969,11 +958,14 @@ exports.examples = [
enablesReturnKeyAutomatically={true}
returnKeyType="done"
multiline={true}
style={{maxHeight: 400, minHeight: 20, paddingTop: 0, backgroundColor: '#eeeeee', color: 'blue'}}
>
<Text style={{fontSize: 30, color: 'green'}}>
huge
</Text>
style={{
maxHeight: 400,
minHeight: 20,
paddingTop: 0,
backgroundColor: '#eeeeee',
color: 'blue',
}}>
<Text style={{fontSize: 30, color: 'green'}}>huge</Text>
generic generic generic
<Text style={{fontSize: 6, color: 'red'}}>
small small small small small small
@@ -986,13 +978,13 @@ exports.examples = [
</AutogrowingTextInputExample>
</View>
);
}
},
},
{
title: 'Attributed text',
render: function() {
return <TokenizedTextExample />;
}
},
},
{
title: 'Text selection & cursor placement',
@@ -1010,7 +1002,7 @@ exports.examples = [
/>
</View>
);
}
},
},
{
title: 'TextInput maxLength',
@@ -1018,10 +1010,7 @@ exports.examples = [
return (
<View>
<WithLabel label="maxLength: 5">
<TextInput
maxLength={5}
style={styles.default}
/>
<TextInput maxLength={5} style={styles.default} />
</WithLabel>
<WithLabel label="maxLength: 5 with placeholder">
<TextInput
@@ -1046,6 +1035,6 @@ exports.examples = [
</WithLabel>
</View>
);
}
},
},
];

View File

@@ -4,7 +4,9 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
var React = require('react');
@@ -116,4 +118,3 @@ var styles = StyleSheet.create({
});
module.exports = TimePickerAndroidExample;

View File

@@ -4,20 +4,16 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var createReactClass = require('create-react-class');
var ReactNative = require('react-native');
var {
AlertIOS,
Platform,
ToastAndroid,
Text,
View,
} = ReactNative;
var {AlertIOS, Platform, ToastAndroid, Text, View} = ReactNative;
/* $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. */
@@ -30,7 +26,7 @@ var performanceNow = require('fbjs/lib/performanceNow');
function burnCPU(milliseconds) {
const start = performanceNow();
while (performanceNow() < (start + milliseconds)) {}
while (performanceNow() < start + milliseconds) {}
}
class RequestIdleCallbackTester extends React.Component<{}, $FlowFixMeState> {
@@ -73,35 +69,45 @@ class RequestIdleCallbackTester extends React.Component<{}, $FlowFixMeState> {
);
}
_run = (shouldBurnCPU) => {
_run = shouldBurnCPU => {
cancelIdleCallback(this._idleTimer);
this._idleTimer = requestIdleCallback((deadline) => {
this._idleTimer = requestIdleCallback(deadline => {
let message = '';
if (shouldBurnCPU) {
burnCPU(10);
message = 'Burned CPU for 10ms,';
}
this.setState({message: `${message} ${deadline.timeRemaining()}ms remaining in frame`});
this.setState({
message: `${message} ${deadline.timeRemaining()}ms remaining in frame`,
});
});
};
_runWithTimeout = () => {
cancelIdleCallback(this._idleTimer);
this._idleTimer = requestIdleCallback((deadline) => {
this.setState({
message: `${deadline.timeRemaining()}ms remaining in frame, it did timeout: ${deadline.didTimeout ? 'yes' : 'no'}`
});
}, { timeout: 100 });
this._idleTimer = requestIdleCallback(
deadline => {
this.setState({
message: `${deadline.timeRemaining()}ms remaining in frame, it did timeout: ${
deadline.didTimeout ? 'yes' : 'no'
}`,
});
},
{timeout: 100},
);
burnCPU(100);
};
_runBackground = () => {
cancelIdleCallback(this._idleTimer);
const handler = (deadline) => {
const handler = deadline => {
while (deadline.timeRemaining() > 5) {
burnCPU(5);
this.setState({message: `Burned CPU for 5ms ${this._iters++} times, ${deadline.timeRemaining()}ms remaining in frame`});
this.setState({
message: `Burned CPU for 5ms ${this
._iters++} times, ${deadline.timeRemaining()}ms remaining in frame`,
});
}
this._idleTimer = requestIdleCallback(handler);
@@ -122,8 +128,8 @@ var TimerTester = createReactClass({
_ii: 0,
_iters: 0,
_start: 0,
_timerFn: (null : ?(() => any)),
_handle: (null : any),
_timerFn: (null: ?() => any),
_handle: (null: any),
render: function() {
var args = 'fn' + (this.props.dt !== undefined ? ', ' + this.props.dt : '');
@@ -160,9 +166,18 @@ var TimerTester = createReactClass({
}
if (this._ii >= this._iters && !this._handle) {
var d = new Date();
var e = (d.getTime() - this._start);
var msg = 'Finished ' + this._ii + ' ' + this.props.type + ' calls.\n' +
'Elapsed time: ' + e + ' ms\n' + (e / this._ii) + ' ms / iter';
var e = d.getTime() - this._start;
var msg =
'Finished ' +
this._ii +
' ' +
this.props.type +
' calls.\n' +
'Elapsed time: ' +
e +
' ms\n' +
e / this._ii +
' ms / iter';
console.log(msg);
if (Platform.OS === 'ios') {
AlertIOS.alert(msg);
@@ -170,7 +185,9 @@ var TimerTester = createReactClass({
ToastAndroid.show(msg, ToastAndroid.SHORT);
}
this._start = 0;
this.forceUpdate(() => { this._ii = 0; });
this.forceUpdate(() => {
this._ii = 0;
});
return;
}
this._ii++;
@@ -194,13 +211,15 @@ var TimerTester = createReactClass({
exports.framework = 'React';
exports.title = 'Timers, TimerMixin';
exports.description = 'The TimerMixin provides timer functions for executing ' +
exports.description =
'The TimerMixin provides timer functions for executing ' +
'code in the future that are safely cleaned up when the component unmounts.';
exports.examples = [
{
title: 'this.setTimeout(fn, t)',
description: 'Execute function fn t milliseconds in the future. If ' +
description:
'Execute function fn t milliseconds in the future. If ' +
't === 0, it will be enqueued immediately in the next event loop. ' +
'Larger values will fire on the closest frame.',
render: function() {
@@ -248,7 +267,8 @@ exports.examples = [
},
{
title: 'this.setInterval(fn, t)',
description: 'Execute function fn every t milliseconds until cancelled ' +
description:
'Execute function fn every t milliseconds until cancelled ' +
'or component is unmounted.',
render: function(): React.Element<any> {
class IntervalExample extends React.Component<{}, $FlowFixMeState> {
@@ -271,7 +291,7 @@ exports.examples = [
return (
<View>
<TimerTester ref="interval" dt={25} type="setInterval" />
<RNTesterButton onPress={() => this.refs.interval.clear() }>
<RNTesterButton onPress={() => this.refs.interval.clear()}>
Clear interval
</RNTesterButton>
</View>

View File

@@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
@@ -11,12 +12,7 @@
var React = require('react');
var ReactNative = require('react-native');
var {
StyleSheet,
Text,
ToastAndroid,
TouchableWithoutFeedback,
} = ReactNative;
var {StyleSheet, Text, ToastAndroid, TouchableWithoutFeedback} = ReactNative;
var RNTesterBlock = require('RNTesterBlock');
var RNTesterPage = require('RNTesterPage');
@@ -32,14 +28,22 @@ class ToastExample extends React.Component<{}, $FlowFixMeState> {
<RNTesterBlock title="Simple toast">
<TouchableWithoutFeedback
onPress={() =>
ToastAndroid.show('This is a toast with short duration', ToastAndroid.SHORT)}>
ToastAndroid.show(
'This is a toast with short duration',
ToastAndroid.SHORT,
)
}>
<Text style={styles.text}>Click me.</Text>
</TouchableWithoutFeedback>
</RNTesterBlock>
<RNTesterBlock title="Toast with long duration">
<TouchableWithoutFeedback
onPress={() =>
ToastAndroid.show('This is a toast with long duration', ToastAndroid.LONG)}>
ToastAndroid.show(
'This is a toast with long duration',
ToastAndroid.LONG,
)
}>
<Text style={styles.text}>Click me.</Text>
</TouchableWithoutFeedback>
</RNTesterBlock>

View File

@@ -4,19 +4,17 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var nativeImageSource = require('nativeImageSource');
var {
StyleSheet,
Text,
View,
} = ReactNative;
var {StyleSheet, Text, View} = ReactNative;
var RNTesterBlock = require('./RNTesterBlock');
var RNTesterPage = require('./RNTesterPage');
@@ -45,13 +43,14 @@ class ToolbarAndroidExample extends React.Component<{}, $FlowFixMeState> {
navIcon={nativeImageSource({
android: 'ic_menu_black_24dp',
width: 48,
height: 48
height: 48,
})}
onActionSelected={this._onActionSelected}
onIconClicked={() => this.setState({actionText: 'Icon clicked'})}
style={styles.toolbar}
subtitle={this.state.actionText}
title="Toolbar" />
title="Toolbar"
/>
<Text>{this.state.actionText}</Text>
</RNTesterBlock>
<RNTesterBlock title="Toolbar with logo & custom title view (a View with Switch+Text)">
@@ -59,14 +58,16 @@ class ToolbarAndroidExample extends React.Component<{}, $FlowFixMeState> {
logo={nativeImageSource({
android: 'launcher_icon',
width: 132,
height: 144
height: 144,
})}
style={styles.toolbar}>
<View style={{height: 56, flexDirection: 'row', alignItems: 'center'}}>
<View
style={{height: 56, flexDirection: 'row', alignItems: 'center'}}>
<Switch
value={this.state.toolbarSwitch}
onValueChange={(value) => this.setState({'toolbarSwitch': value})} />
<Text>{'\'Tis but a switch'}</Text>
onValueChange={value => this.setState({toolbarSwitch: value})}
/>
<Text>{"'Tis but a switch"}</Text>
</View>
</ToolbarAndroid>
</RNTesterBlock>
@@ -74,7 +75,8 @@ class ToolbarAndroidExample extends React.Component<{}, $FlowFixMeState> {
<ToolbarAndroid
actions={toolbarActions}
style={styles.toolbar}
subtitle="There be no icon here" />
subtitle="There be no icon here"
/>
</RNTesterBlock>
<RNTesterBlock title="Toolbar with navIcon & logo, no title">
<ToolbarAndroid
@@ -82,50 +84,57 @@ class ToolbarAndroidExample extends React.Component<{}, $FlowFixMeState> {
logo={nativeImageSource({
android: 'launcher_icon',
width: 132,
height: 144
height: 144,
})}
navIcon={nativeImageSource({
android: 'ic_menu_black_24dp',
width: 48,
height: 48
height: 48,
})}
style={styles.toolbar} />
style={styles.toolbar}
/>
</RNTesterBlock>
<RNTesterBlock title="Toolbar with custom title colors">
<ToolbarAndroid
navIcon={nativeImageSource({
android: 'ic_menu_black_24dp',
width: 48,
height: 48
height: 48,
})}
onIconClicked={() => this.setState({colorProps: {}})}
title="Wow, such toolbar"
style={styles.toolbar}
subtitle="Much native"
{...this.state.colorProps} />
{...this.state.colorProps}
/>
<Text>
Touch the icon to reset the custom colors to the default (theme-provided) ones.
Touch the icon to reset the custom colors to the default
(theme-provided) ones.
</Text>
</RNTesterBlock>
<RNTesterBlock title="Toolbar with remote logo & navIcon">
<ToolbarAndroid
actions={[{title: 'Bunny', icon: require('./bunny.png'), show: 'always'}]}
actions={[
{title: 'Bunny', icon: require('./bunny.png'), show: 'always'},
]}
logo={require('./hawk.png')}
navIcon={require('./bunny.png')}
title="Bunny and Hawk"
style={styles.toolbar} />
style={styles.toolbar}
/>
</RNTesterBlock>
<RNTesterBlock title="Toolbar with custom overflowIcon">
<ToolbarAndroid
actions={toolbarActions}
overflowIcon={require('./bunny.png')}
style={styles.toolbar} />
style={styles.toolbar}
/>
</RNTesterBlock>
</RNTesterPage>
);
}
_onActionSelected = (position) => {
_onActionSelected = position => {
this.setState({
actionText: 'Selected ' + toolbarActions[position].title,
});
@@ -133,17 +142,25 @@ class ToolbarAndroidExample extends React.Component<{}, $FlowFixMeState> {
}
var toolbarActions = [
{title: 'Create', icon: nativeImageSource({
android: 'ic_create_black_48dp',
width: 96,
height: 96
}), show: 'always'},
{
title: 'Create',
icon: nativeImageSource({
android: 'ic_create_black_48dp',
width: 96,
height: 96,
}),
show: 'always',
},
{title: 'Filter'},
{title: 'Settings', icon: nativeImageSource({
android: 'ic_settings_black_48dp',
width: 96,
height: 96
}), show: 'always'},
{
title: 'Settings',
icon: nativeImageSource({
android: 'ic_settings_black_48dp',
width: 96,
height: 96,
}),
show: 'always',
},
];
var styles = StyleSheet.create({

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
// Not applicable to iOS.

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
@@ -24,115 +26,130 @@ var {
const NativeModules = require('NativeModules');
const forceTouchAvailable = (NativeModules.PlatformConstants &&
NativeModules.PlatformConstants.forceTouchAvailable) || false;
const forceTouchAvailable =
(NativeModules.PlatformConstants &&
NativeModules.PlatformConstants.forceTouchAvailable) ||
false;
exports.displayName = (undefined: ?string);
exports.description = 'Touchable and onPress examples.';
exports.title = '<Touchable*> and onPress';
exports.examples = [
{
title: '<TouchableHighlight>',
description: 'TouchableHighlight works by adding an extra view with a ' +
'black background under the single child view. This works best when the ' +
'child view is fully opaque, although it can be made to work as a simple ' +
'background color change as well with the activeOpacity and ' +
'underlayColor props.',
render: function() {
return (
<View>
<View style={styles.row}>
<TouchableHighlight
style={styles.wrapper}
onPress={() => console.log('stock THW image - highlight')}>
<Image
source={heartImage}
style={styles.image}
/>
</TouchableHighlight>
<TouchableHighlight
style={styles.wrapper}
activeOpacity={1}
animationVelocity={0}
tvParallaxProperties={{pressMagnification: 1.3, pressDuration: 0.6}}
underlayColor="rgb(210, 230, 255)"
onPress={() => console.log('custom THW text - highlight')}>
<View style={styles.wrapperCustom}>
<Text style={styles.text}>
Tap Here For Custom Highlight!
</Text>
</View>
</TouchableHighlight>
{
title: '<TouchableHighlight>',
description:
'TouchableHighlight works by adding an extra view with a ' +
'black background under the single child view. This works best when the ' +
'child view is fully opaque, although it can be made to work as a simple ' +
'background color change as well with the activeOpacity and ' +
'underlayColor props.',
render: function() {
return (
<View>
<View style={styles.row}>
<TouchableHighlight
style={styles.wrapper}
onPress={() => console.log('stock THW image - highlight')}>
<Image source={heartImage} style={styles.image} />
</TouchableHighlight>
<TouchableHighlight
style={styles.wrapper}
activeOpacity={1}
animationVelocity={0}
tvParallaxProperties={{
pressMagnification: 1.3,
pressDuration: 0.6,
}}
underlayColor="rgb(210, 230, 255)"
onPress={() => console.log('custom THW text - highlight')}>
<View style={styles.wrapperCustom}>
<Text style={styles.text}>Tap Here For Custom Highlight!</Text>
</View>
</TouchableHighlight>
</View>
</View>
</View>
);
);
},
},
}, {
title: 'TouchableNativeFeedback with Animated child',
description: 'TouchableNativeFeedback can have an AnimatedComponent as a' +
'direct child.',
platform: 'android',
render: function() {
const mScale = new Animated.Value(1);
Animated.timing(mScale, {toValue: 0.3, duration: 1000}).start();
const style = {
backgroundColor: 'rgb(180, 64, 119)',
width: 200,
height: 100,
transform: [{scale: mScale}]
};
return (
<View>
<View style={styles.row}>
<TouchableNativeFeedback>
<Animated.View style={style}/>
</TouchableNativeFeedback>
{
title: 'TouchableNativeFeedback with Animated child',
description:
'TouchableNativeFeedback can have an AnimatedComponent as a' +
'direct child.',
platform: 'android',
render: function() {
const mScale = new Animated.Value(1);
Animated.timing(mScale, {toValue: 0.3, duration: 1000}).start();
const style = {
backgroundColor: 'rgb(180, 64, 119)',
width: 200,
height: 100,
transform: [{scale: mScale}],
};
return (
<View>
<View style={styles.row}>
<TouchableNativeFeedback>
<Animated.View style={style} />
</TouchableNativeFeedback>
</View>
</View>
</View>
);
);
},
},
}, {
title: '<Text onPress={fn}> with highlight',
render: function(): React.Element<any> {
return <TextOnPressBox />;
{
title: '<Text onPress={fn}> with highlight',
render: function(): React.Element<any> {
return <TextOnPressBox />;
},
},
}, {
title: 'Touchable feedback events',
description: '<Touchable*> components accept onPress, onPressIn, ' +
'onPressOut, and onLongPress as props.',
render: function(): React.Element<any> {
return <TouchableFeedbackEvents />;
{
title: 'Touchable feedback events',
description:
'<Touchable*> components accept onPress, onPressIn, ' +
'onPressOut, and onLongPress as props.',
render: function(): React.Element<any> {
return <TouchableFeedbackEvents />;
},
},
}, {
title: 'Touchable delay for events',
description: '<Touchable*> components also accept delayPressIn, ' +
'delayPressOut, and delayLongPress as props. These props impact the ' +
'timing of feedback events.',
render: function(): React.Element<any> {
return <TouchableDelayEvents />;
{
title: 'Touchable delay for events',
description:
'<Touchable*> components also accept delayPressIn, ' +
'delayPressOut, and delayLongPress as props. These props impact the ' +
'timing of feedback events.',
render: function(): React.Element<any> {
return <TouchableDelayEvents />;
},
},
}, {
title: '3D Touch / Force Touch',
description: 'iPhone 6s and 6s plus support 3D touch, which adds a force property to touches',
render: function(): React.Element<any> {
return <ForceTouchExample />;
{
title: '3D Touch / Force Touch',
description:
'iPhone 6s and 6s plus support 3D touch, which adds a force property to touches',
render: function(): React.Element<any> {
return <ForceTouchExample />;
},
platform: 'ios',
},
platform: 'ios',
}, {
title: 'Touchable Hit Slop',
description: '<Touchable*> components accept hitSlop prop which extends the touch area ' +
'without changing the view bounds.',
render: function(): React.Element<any> {
return <TouchableHitSlop />;
},
}, {
title: 'Disabled Touchable*',
description: '<Touchable*> components accept disabled prop which prevents ' +
'any interaction with component',
render: function(): React.Element<any> {
return <TouchableDisabled />;
},
}];
{
title: 'Touchable Hit Slop',
description:
'<Touchable*> components accept hitSlop prop which extends the touch area ' +
'without changing the view bounds.',
render: function(): React.Element<any> {
return <TouchableHitSlop />;
},
},
{
title: 'Disabled Touchable*',
description:
'<Touchable*> components accept disabled prop which prevents ' +
'any interaction with component',
render: function(): React.Element<any> {
return <TouchableDisabled />;
},
},
];
class TextOnPressBox extends React.Component<{}, $FlowFixMeState> {
state = {
@@ -155,15 +172,11 @@ class TextOnPressBox extends React.Component<{}, $FlowFixMeState> {
return (
<View>
<Text
style={styles.textBlock}
onPress={this.textOnPress}>
<Text style={styles.textBlock} onPress={this.textOnPress}>
Text has built-in onPress handling
</Text>
<View style={styles.logBox}>
<Text>
{textLog}
</Text>
<Text>{textLog}</Text>
</View>
</View>
);
@@ -189,19 +202,19 @@ class TouchableFeedbackEvents extends React.Component<{}, $FlowFixMeState> {
onPressIn={() => this._appendEvent('pressIn')}
onPressOut={() => this._appendEvent('pressOut')}
onLongPress={() => this._appendEvent('longPress')}>
<Text style={styles.button}>
Press Me
</Text>
<Text style={styles.button}>Press Me</Text>
</TouchableOpacity>
</View>
<View testID="touchable_feedback_events_console" style={styles.eventLogBox}>
<View
testID="touchable_feedback_events_console"
style={styles.eventLogBox}>
{this.state.eventLog.map((e, ii) => <Text key={ii}>{e}</Text>)}
</View>
</View>
);
}
_appendEvent = (eventName) => {
_appendEvent = eventName => {
var limit = 6;
var eventLog = this.state.eventLog.slice(0, limit - 1);
eventLog.unshift(eventName);
@@ -228,19 +241,19 @@ class TouchableDelayEvents extends React.Component<{}, $FlowFixMeState> {
onPressOut={() => this._appendEvent('pressOut - 1000ms delay')}
delayLongPress={800}
onLongPress={() => this._appendEvent('longPress - 800ms delay')}>
<Text style={styles.button}>
Press Me
</Text>
<Text style={styles.button}>Press Me</Text>
</TouchableOpacity>
</View>
<View style={styles.eventLogBox} testID="touchable_delay_events_console">
<View
style={styles.eventLogBox}
testID="touchable_delay_events_console">
{this.state.eventLog.map((e, ii) => <Text key={ii}>{e}</Text>)}
</View>
</View>
);
}
_appendEvent = (eventName) => {
_appendEvent = eventName => {
var limit = 6;
var eventLog = this.state.eventLog.slice(0, limit - 1);
eventLog.unshift(eventName);
@@ -254,9 +267,9 @@ class ForceTouchExample extends React.Component<{}, $FlowFixMeState> {
};
_renderConsoleText = () => {
return forceTouchAvailable ?
'Force: ' + this.state.force.toFixed(3) :
'3D Touch is not available on this device';
return forceTouchAvailable
? 'Force: ' + this.state.force.toFixed(3)
: '3D Touch is not available on this device';
};
render() {
@@ -270,11 +283,11 @@ class ForceTouchExample extends React.Component<{}, $FlowFixMeState> {
style={styles.wrapper}
testID="touchable_3dtouch_button"
onStartShouldSetResponder={() => true}
onResponderMove={(event) => this.setState({force: event.nativeEvent.force})}
onResponderRelease={(event) => this.setState({force: 0})}>
<Text style={styles.button}>
Press Me
</Text>
onResponderMove={event =>
this.setState({force: event.nativeEvent.force})
}
onResponderRelease={event => this.setState({force: 0})}>
<Text style={styles.button}>Press Me</Text>
</View>
</View>
</View>
@@ -309,15 +322,11 @@ class TouchableHitSlop extends React.Component<{}, $FlowFixMeState> {
style={styles.hitSlopWrapper}
hitSlop={{top: 30, bottom: 30, left: 60, right: 60}}
testID="touchable_hit_slop_button">
<Text style={styles.hitSlopButton}>
Press Outside This View
</Text>
<Text style={styles.hitSlopButton}>Press Outside This View</Text>
</TouchableOpacity>
</View>
</View>
<View style={styles.logBox}>
<Text>
{log}
</Text>
<Text>{log}</Text>
</View>
</View>
);
@@ -343,9 +352,7 @@ class TouchableDisabled extends React.Component<{}> {
underlayColor="rgb(210, 230, 255)"
style={[styles.row, styles.block]}
onPress={() => console.log('custom THW text - highlight')}>
<Text style={styles.disabledButton}>
Disabled TouchableHighlight
</Text>
<Text style={styles.disabledButton}>Disabled TouchableHighlight</Text>
</TouchableHighlight>
<TouchableHighlight
@@ -354,12 +361,10 @@ class TouchableDisabled extends React.Component<{}> {
underlayColor="rgb(210, 230, 255)"
style={[styles.row, styles.block]}
onPress={() => console.log('custom THW text - highlight')}>
<Text style={styles.button}>
Enabled TouchableHighlight
</Text>
<Text style={styles.button}>Enabled TouchableHighlight</Text>
</TouchableHighlight>
{Platform.OS === 'android' &&
{Platform.OS === 'android' && (
<TouchableNativeFeedback
style={[styles.row, styles.block]}
onPress={() => console.log('custom TNF has been clicked')}
@@ -370,21 +375,22 @@ class TouchableDisabled extends React.Component<{}> {
</Text>
</View>
</TouchableNativeFeedback>
}
)}
{Platform.OS === 'android' &&
{Platform.OS === 'android' && (
<TouchableNativeFeedback
disabled={true}
style={[styles.row, styles.block]}
onPress={() => console.log('custom TNF has been clicked')}
background={TouchableNativeFeedback.SelectableBackground()}>
<View>
<Text style={[styles.disabledButton, styles.nativeFeedbackButton]}>
<Text
style={[styles.disabledButton, styles.nativeFeedbackButton]}>
Disabled TouchableNativeFeedback
</Text>
</View>
</TouchableNativeFeedback>
}
)}
</View>
);
}

View File

@@ -4,18 +4,15 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Animated,
StyleSheet,
Text,
View,
} = ReactNative;
var {Animated, StyleSheet, Text, View} = ReactNative;
class Flip extends React.Component<{}, $FlowFixMeState> {
state = {
@@ -37,33 +34,42 @@ class Flip extends React.Component<{}, $FlowFixMeState> {
render() {
return (
<View style={styles.flipCardContainer}>
<Animated.View style={[
styles.flipCard,
{transform: [
{perspective: 850},
{rotateX: this.state.theta.interpolate({
inputRange: [0, 180],
outputRange: ['0deg', '180deg']
})},
]}]}>
<Text style={styles.flipText}>
This text is flipping great.
</Text>
<Animated.View
style={[
styles.flipCard,
{
transform: [
{perspective: 850},
{
rotateX: this.state.theta.interpolate({
inputRange: [0, 180],
outputRange: ['0deg', '180deg'],
}),
},
],
},
]}>
<Text style={styles.flipText}>This text is flipping great.</Text>
</Animated.View>
<Animated.View style={[styles.flipCard, {
position: 'absolute',
top: 0,
backgroundColor: 'red',
transform: [
{perspective: 850},
{rotateX: this.state.theta.interpolate({
inputRange: [0, 180],
outputRange: ['180deg', '360deg']
})},
]}]}>
<Text style={styles.flipText}>
On the flip side...
</Text>
<Animated.View
style={[
styles.flipCard,
{
position: 'absolute',
top: 0,
backgroundColor: 'red',
transform: [
{perspective: 850},
{
rotateX: this.state.theta.interpolate({
inputRange: [0, 180],
outputRange: ['180deg', '360deg'],
}),
},
],
},
]}>
<Text style={styles.flipText}>On the flip side...</Text>
</Animated.View>
</View>
);
@@ -110,9 +116,7 @@ var styles = StyleSheet.create({
height: 50,
position: 'absolute',
top: 0,
transform: [
{rotate: '30deg'},
],
transform: [{rotate: '30deg'}],
width: 50,
},
box3step2: {
@@ -122,11 +126,7 @@ var styles = StyleSheet.create({
opacity: 0.5,
position: 'absolute',
top: 0,
transform: [
{rotate: '30deg'},
{scaleX: 2},
{scaleY: 2},
],
transform: [{rotate: '30deg'}, {scaleX: 2}, {scaleY: 2}],
width: 50,
},
box3step3: {
@@ -151,11 +151,7 @@ var styles = StyleSheet.create({
height: 50,
position: 'absolute',
top: 0,
transform: [
{translate: [200, 350]},
{scale: 2.5},
{rotate: '-0.2rad'},
],
transform: [{translate: [200, 350]}, {scale: 2.5}, {rotate: '-0.2rad'}],
width: 100,
},
box5: {
@@ -167,11 +163,7 @@ var styles = StyleSheet.create({
width: 50,
},
box5Transform: {
transform: [
{translate: [-50, 35]},
{rotate: '50deg'},
{scale: 2},
],
transform: [{translate: [-50, 35]}, {rotate: '50deg'}, {scale: 2}],
},
flipCardContainer: {
marginVertical: 40,
@@ -191,7 +183,7 @@ var styles = StyleSheet.create({
fontSize: 20,
color: 'white',
fontWeight: 'bold',
}
},
});
exports.title = 'Transforms';
@@ -200,29 +192,33 @@ exports.examples = [
{
title: 'Perspective, Rotate, Animation',
description: 'perspective: 850, rotateX: Animated.timing(0 -> 360)',
render(): React.Element<any> { return <Flip />; }
render(): React.Element<any> {
return <Flip />;
},
},
{
title: 'Translate, Rotate, Scale',
description: "translateX: 100, translateY: 50, rotate: '30deg', scaleX: 2, scaleY: 2",
description:
"translateX: 100, translateY: 50, rotate: '30deg', scaleX: 2, scaleY: 2",
render() {
return (
<View style={styles.container}>
<View style={styles.box1} />
</View>
);
}
},
},
{
title: 'Scale, Translate, Rotate, ',
description: "scaleX: 2, scaleY: 2, translateX: 100, translateY: 50, rotate: '30deg'",
description:
"scaleX: 2, scaleY: 2, translateX: 100, translateY: 50, rotate: '30deg'",
render() {
return (
<View style={styles.container}>
<View style={styles.box2} />
</View>
);
}
},
},
{
title: 'Rotate',
@@ -233,7 +229,7 @@ exports.examples = [
<View style={styles.box3step1} />
</View>
);
}
},
},
{
title: 'Rotate, Scale',
@@ -244,18 +240,19 @@ exports.examples = [
<View style={styles.box3step2} />
</View>
);
}
},
},
{
title: 'Rotate, Scale, Translate ',
description: "rotate: '30deg', scaleX: 2, scaleY: 2, translateX: 100, translateY: 50",
description:
"rotate: '30deg', scaleX: 2, scaleY: 2, translateX: 100, translateY: 50",
render() {
return (
<View style={styles.container}>
<View style={styles.box3step3} />
</View>
);
}
},
},
{
title: 'Translate, Scale, Rotate',
@@ -266,7 +263,7 @@ exports.examples = [
<View style={styles.box4} />
</View>
);
}
},
},
{
title: 'Translate, Rotate, Scale',
@@ -277,6 +274,6 @@ exports.examples = [
<View style={[styles.box5, styles.box5Transform]} />
</View>
);
}
}
},
},
];

View File

@@ -4,6 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
@@ -11,11 +12,7 @@
var React = require('react');
var ReactNative = require('react-native');
var {
Text,
View,
TouchableOpacity,
} = ReactNative;
var {Text, View, TouchableOpacity} = ReactNative;
class TransparentHitTestExample extends React.Component<{}> {
render() {
@@ -25,14 +22,17 @@ class TransparentHitTestExample extends React.Component<{}> {
<Text>HELLO!</Text>
</TouchableOpacity>
<View style={{
position: 'absolute',
backgroundColor: 'green',
top: 0,
left: 0,
bottom: 0,
right: 0,
opacity: 0.0}} />
<View
style={{
position: 'absolute',
backgroundColor: 'green',
top: 0,
left: 0,
bottom: 0,
right: 0,
opacity: 0.0,
}}
/>
</View>
);
}
@@ -44,6 +44,8 @@ exports.description = 'Transparent view receiving touch events';
exports.examples = [
{
title: 'TransparentHitTestExample',
render(): React.Element<any> { return <TransparentHitTestExample />; }
}
render(): React.Element<any> {
return <TransparentHitTestExample />;
},
},
];

View File

@@ -4,8 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const ReactNative = require('react-native');
@@ -13,11 +15,9 @@ const RNTesterActions = require('./RNTesterActions');
// $FlowFixMe : This is a platform-forked component, and flow seems to only run on iOS?
const RNTesterList = require('./RNTesterList');
const {
Alert,
} = ReactNative;
const {Alert} = ReactNative;
import type { RNTesterAction } from './RNTesterActions';
import type {RNTesterAction} from './RNTesterActions';
function PathActionMap(path: string): ?RNTesterAction {
// Warning! Hacky parsing for example code. Use a library for this!

Some files were not shown because too many files have changed in this diff Show More