Fix lint errors in 'examples' directory

This commit is contained in:
Nicolas Gallagher
2017-05-25 10:40:54 -07:00
parent 61356a786b
commit 6525d9d84a
19 changed files with 482 additions and 431 deletions

View File

@@ -1,6 +1,6 @@
import { Clipboard, Text, TextInput, View } from 'react-native';
import React, { Component } from 'react';
import { action, storiesOf } from '@kadira/storybook';
import { storiesOf } from '@kadira/storybook';
class ClipboardExample extends Component {
render() {

View File

@@ -1,6 +1,6 @@
import { Linking, StyleSheet, Text, View } from 'react-native';
import React, { Component } from 'react';
import { storiesOf, action } from '@kadira/storybook';
import { storiesOf } from '@kadira/storybook';
const url = 'https://mathiasbynens.github.io/rel-noopener/malicious.html';

View File

@@ -1,15 +1,13 @@
'use strict';
/* eslint-disable react/jsx-no-bind */
import createReactClass from 'create-react-class';
import { storiesOf, action } from '@kadira/storybook';
import React from 'react';
import { storiesOf } from '@kadira/storybook';
import { PanResponder, StyleSheet, View } from 'react-native';
var React = require('react');
var ReactNative = require('react-native');
var { PanResponder, StyleSheet, View } = ReactNative;
const CIRCLE_SIZE = 80;
var CIRCLE_SIZE = 80;
var PanResponderExample = createReactClass({
const PanResponderExample = createReactClass({
_panResponder: {},
_previousLeft: 0,
_previousTop: 0,
@@ -93,7 +91,7 @@ var PanResponderExample = createReactClass({
}
});
var styles = StyleSheet.create({
const styles = StyleSheet.create({
circle: {
width: CIRCLE_SIZE,
height: CIRCLE_SIZE,

View File

@@ -1,9 +1,3 @@
import createReactClass from 'create-react-class';
import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import { ActivityIndicator, StyleSheet, View } from 'react-native';
import TimerMixin from 'react-timer-mixin';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
@@ -27,6 +21,12 @@ import TimerMixin from 'react-timer-mixin';
* @flow
*/
import createReactClass from 'create-react-class';
import React from 'react';
import { storiesOf } from '@kadira/storybook';
import { ActivityIndicator, StyleSheet, View } from 'react-native';
import TimerMixin from 'react-timer-mixin';
const ToggleAnimatingActivityIndicator = createReactClass({
mixins: [TimerMixin],
@@ -51,9 +51,9 @@ const ToggleAnimatingActivityIndicator = createReactClass({
return (
<ActivityIndicator
animating={this.state.animating}
style={styles.centering}
hidesWhenStopped={this.props.hidesWhenStopped}
size="large"
style={styles.centering}
/>
);
}
@@ -83,7 +83,7 @@ const examples = [
title: 'Large',
render() {
return (
<ActivityIndicator style={[styles.centering, styles.gray]} color="white" size="large" />
<ActivityIndicator color="white" size="large" style={[styles.centering, styles.gray]} />
);
}
},
@@ -92,10 +92,10 @@ const examples = [
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 color="#0000ff" size="large" />
<ActivityIndicator color="#aa00aa" size="large" />
<ActivityIndicator color="#aa3300" size="large" />
<ActivityIndicator color="#00aa00" size="large" />
</View>
);
}
@@ -117,7 +117,7 @@ const examples = [
return (
<View style={[styles.horizontal, styles.centering]}>
<ActivityIndicator size={40} />
<ActivityIndicator style={{ marginLeft: 20, transform: [{ scale: 1.5 }] }} size="large" />
<ActivityIndicator size="large" style={{ marginLeft: 20, transform: [{ scale: 1.5 }] }} />
</View>
);
}

View File

@@ -1,6 +1,6 @@
import React from 'react';
import { action, storiesOf } from '@kadira/storybook';
import { Button, StyleSheet, View } from 'react-native';
import { Button, View } from 'react-native';
const onButtonPress = action('Button has been pressed!');
@@ -13,9 +13,9 @@ const examples = [
render: function() {
return (
<Button
accessibilityLabel="See an informative alert"
onPress={onButtonPress}
title="Press Me"
accessibilityLabel="See an informative alert"
/>
);
}
@@ -28,30 +28,30 @@ const examples = [
render: function() {
return (
<Button
accessibilityLabel="Learn more about purple"
color="#841584"
onPress={onButtonPress}
title="Press Purple"
color="#841584"
accessibilityLabel="Learn more about purple"
/>
);
}
},
{
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' }}>
<Button
accessibilityLabel="This sounds great!"
onPress={onButtonPress}
title="This looks great!"
accessibilityLabel="This sounds great!"
/>
<Button
accessibilityLabel="Ok, Great!"
color="#841584"
onPress={onButtonPress}
title="Ok!"
color="#841584"
accessibilityLabel="Ok, Great!"
/>
</View>
);
@@ -63,10 +63,10 @@ const examples = [
render: function() {
return (
<Button
accessibilityLabel="See an informative alert"
disabled
onPress={onButtonPress}
title="I Am Disabled"
accessibilityLabel="See an informative alert"
/>
);
}

View File

@@ -1,7 +1,4 @@
import createReactClass from 'create-react-class';
import React from 'react';
import { storiesOf, action, addDecorator } from '@kadira/storybook';
import { ActivityIndicator, Image, Platform, StyleSheet, Text, View } from 'react-native';
/* eslint-disable react/jsx-no-bind */
/**
* Copyright (c) 2013-present, Facebook, Inc.
@@ -26,14 +23,19 @@ import { ActivityIndicator, Image, Platform, StyleSheet, Text, View } from 'reac
* @flow
*/
var base64Icon =
import createReactClass from 'create-react-class';
import React from 'react';
import { storiesOf } from '@kadira/storybook';
import { ActivityIndicator, Image, StyleSheet, Text, View } from 'react-native';
const 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();
var prefetchTask = Image.prefetch(IMAGE_PREFETCH_URL);
const prefetchTask = Image.prefetch(IMAGE_PREFETCH_URL);
var NetworkImageCallbackExample = createReactClass({
const NetworkImageCallbackExample = createReactClass({
getInitialState: function() {
return {
events: [],
@@ -47,14 +49,11 @@ var NetworkImageCallbackExample = createReactClass({
},
render: function() {
var { mountTime } = this.state;
const { mountTime } = this.state;
return (
<View>
<Image
source={this.props.source}
style={[styles.base, { overflow: 'visible' }]}
onLoadStart={() => this._loadEventFired(`✔ onLoadStart (+${new Date() - mountTime}ms)`)}
onLoad={() => this._loadEventFired(`✔ onLoad (+${new Date() - mountTime}ms)`)}
onLoadEnd={() => {
this._loadEventFired(`✔ onLoadEnd (+${new Date() - mountTime}ms)`);
@@ -65,21 +64,25 @@ var NetworkImageCallbackExample = createReactClass({
},
error => {
this._loadEventFired(`✘ Prefetch failed (+${new Date() - mountTime}ms)`);
console.log(error);
}
);
});
}}
onLoadStart={() => this._loadEventFired(`✔ onLoadStart (+${new Date() - mountTime}ms)`)}
source={this.props.source}
style={[styles.base, { overflow: 'visible' }]}
/>
{this.state.startLoadPrefetched
? <Image
source={this.props.prefetchedSource}
style={[styles.base, { overflow: 'visible' }]}
onLoadStart={() =>
this._loadEventFired(`✔ (prefetched) onLoadStart (+${new Date() - mountTime}ms)`)}
onLoad={() =>
this._loadEventFired(`✔ (prefetched) onLoad (+${new Date() - mountTime}ms)`)}
onLoadEnd={() =>
this._loadEventFired(`✔ (prefetched) onLoadEnd (+${new Date() - mountTime}ms)`)}
onLoadStart={() =>
this._loadEventFired(`✔ (prefetched) onLoadStart (+${new Date() - mountTime}ms)`)}
source={this.props.prefetchedSource}
style={[styles.base, { overflow: 'visible' }]}
/>
: null}
<Text style={{ marginTop: 20 }}>
@@ -96,7 +99,7 @@ var NetworkImageCallbackExample = createReactClass({
}
});
var NetworkImageExample = createReactClass({
const NetworkImageExample = createReactClass({
getInitialState: function() {
return {
error: false,
@@ -105,7 +108,7 @@ var NetworkImageExample = createReactClass({
};
},
render: function() {
var loader = this.state.loading
const loader = this.state.loading
? <View style={styles.progress}>
<Text>{this.state.progress}%</Text>
<ActivityIndicator style={{ marginLeft: 5 }} />
@@ -114,22 +117,22 @@ var NetworkImageExample = createReactClass({
return this.state.error
? <Text>{this.state.error}</Text>
: <Image
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 })}
onLoad={() => this.setState({ loading: false, error: false })}
onLoadStart={e => this.setState({ loading: true })}
onProgress={e =>
this.setState({
progress: Math.round(100 * e.nativeEvent.loaded / e.nativeEvent.total)
})}
onLoad={() => this.setState({ loading: false, error: false })}
source={this.props.source}
style={[styles.base, { overflow: 'visible' }]}
>
{loader}
</Image>;
}
});
var ImageSizeExample = createReactClass({
const ImageSizeExample = createReactClass({
getInitialState: function() {
return {
width: 0,
@@ -259,8 +262,8 @@ const examples = [
render: function() {
return (
<NetworkImageCallbackExample
source={{ uri: 'http://origami.design/public/images/bird-logo.png?r=1&t=' + Date.now() }}
prefetchedSource={{ uri: IMAGE_PREFETCH_URL }}
source={{ uri: 'http://origami.design/public/images/bird-logo.png?r=1&t=' + Date.now() }}
/>
);
}
@@ -332,10 +335,10 @@ const examples = [
render: function() {
return (
<View style={styles.horizontal}>
<Image style={[styles.base, { borderRadius: 5 }]} source={fullImage} />
<Image source={fullImage} style={[styles.base, { borderRadius: 5 }]} />
<Image
style={[styles.base, styles.leftMargin, { borderRadius: 19 }]}
source={fullImage}
style={[styles.base, styles.leftMargin, { borderRadius: 19 }]}
/>
</View>
);
@@ -348,16 +351,16 @@ const examples = [
<View style={styles.horizontal}>
<Image source={smallImage} style={styles.base} />
<Image
source={smallImage}
style={[styles.base, styles.leftMargin, { backgroundColor: 'rgba(0, 0, 100, 0.25)' }]}
source={smallImage}
/>
<Image
source={smallImage}
style={[styles.base, styles.leftMargin, { backgroundColor: 'red' }]}
source={smallImage}
/>
<Image
style={[styles.base, styles.leftMargin, { backgroundColor: 'black' }]}
source={smallImage}
style={[styles.base, styles.leftMargin, { backgroundColor: 'black' }]}
/>
</View>
);
@@ -368,12 +371,12 @@ const examples = [
render: function() {
return (
<View style={styles.horizontal}>
<Image style={[styles.base, { opacity: 1 }]} source={fullImage} />
<Image style={[styles.base, styles.leftMargin, { opacity: 0.8 }]} source={fullImage} />
<Image style={[styles.base, styles.leftMargin, { opacity: 0.6 }]} source={fullImage} />
<Image style={[styles.base, styles.leftMargin, { opacity: 0.4 }]} source={fullImage} />
<Image style={[styles.base, styles.leftMargin, { opacity: 0.2 }]} source={fullImage} />
<Image style={[styles.base, styles.leftMargin, { opacity: 0 }]} source={fullImage} />
<Image source={fullImage} style={[styles.base, { opacity: 1 }]} />
<Image source={fullImage} style={[styles.base, styles.leftMargin, { opacity: 0.8 }]} />
<Image source={fullImage} style={[styles.base, styles.leftMargin, { opacity: 0.6 }]} />
<Image source={fullImage} style={[styles.base, styles.leftMargin, { opacity: 0.4 }]} />
<Image source={fullImage} style={[styles.base, styles.leftMargin, { opacity: 0.2 }]} />
<Image source={fullImage} style={[styles.base, styles.leftMargin, { opacity: 0 }]} />
</View>
);
}
@@ -382,7 +385,7 @@ const examples = [
title: 'Nesting',
render: function() {
return (
<Image style={{ width: 60, height: 60, backgroundColor: 'transparent' }} source={fullImage}>
<Image source={fullImage} style={{ width: 60, height: 60, backgroundColor: 'transparent' }}>
<Text style={styles.nestedText}>
React
</Text>
@@ -458,9 +461,9 @@ const examples = [
Contain
</Text>
<Image
style={styles.resizeMode}
resizeMode={Image.resizeMode.contain}
source={image}
style={styles.resizeMode}
/>
</View>
<View style={styles.leftMargin}>
@@ -468,9 +471,9 @@ const examples = [
Cover
</Text>
<Image
style={styles.resizeMode}
resizeMode={Image.resizeMode.cover}
source={image}
style={styles.resizeMode}
/>
</View>
</View>
@@ -480,22 +483,22 @@ const examples = [
Stretch
</Text>
<Image
style={styles.resizeMode}
resizeMode={Image.resizeMode.stretch}
source={image}
style={styles.resizeMode}
/>
</View>
<View style={styles.leftMargin}>
<Text style={[styles.resizeModeText]}>
Repeat
</Text>
<Image style={styles.resizeMode} resizeMode={'repeat'} source={image} />
<Image resizeMode={'repeat'} source={image} style={styles.resizeMode} />
</View>
<View style={styles.leftMargin}>
<Text style={[styles.resizeModeText]}>
Center
</Text>
<Image style={styles.resizeMode} resizeMode={'center'} source={image} />
<Image resizeMode={'center'} source={image} style={styles.resizeMode} />
</View>
</View>
</View>
@@ -510,10 +513,10 @@ const examples = [
render: function() {
return (
<Image
style={styles.gif}
source={{
uri: 'http://38.media.tumblr.com/9e9bd08c6e2d10561dd1fb4197df4c4e/tumblr_mfqekpMktw1rn90umo1_500.gif'
}}
style={styles.gif}
/>
);
},
@@ -522,7 +525,7 @@ const examples = [
{
title: 'Base64 image',
render: function() {
return <Image style={styles.base64} source={{ uri: base64Icon, scale: 3 }} />;
return <Image source={{ uri: base64Icon, scale: 3 }} style={styles.base64} />;
},
platform: 'ios'
},
@@ -566,10 +569,10 @@ const examples = [
*/
];
var fullImage = { uri: 'http://facebook.github.io/react/img/logo_og.png' };
var smallImage = { uri: 'http://facebook.github.io/react/img/logo_small_2x.png' };
const fullImage = { uri: 'http://facebook.github.io/react/img/logo_og.png' };
const smallImage = { uri: 'http://facebook.github.io/react/img/logo_small_2x.png' };
var styles = StyleSheet.create({
const styles = StyleSheet.create({
base: {
width: 38,
height: 38

View File

@@ -1,7 +1,7 @@
import createReactClass from 'create-react-class';
import { ProgressBar, StyleSheet, View } from 'react-native';
import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import { storiesOf } from '@kadira/storybook';
import TimerMixin from 'react-timer-mixin';
/**
@@ -27,7 +27,7 @@ import TimerMixin from 'react-timer-mixin';
* @flow
*/
var ProgressBarExample = createReactClass({
const ProgressBarExample = createReactClass({
mixins: [TimerMixin],
getInitialState() {
@@ -41,23 +41,23 @@ var ProgressBarExample = createReactClass({
},
updateProgress() {
var progress = this.state.progress + 0.01;
const progress = this.state.progress + 0.01;
this.setState({ progress });
this.requestAnimationFrame(() => this.updateProgress());
},
getProgress(offset) {
var progress = this.state.progress + offset;
const progress = this.state.progress + offset;
return Math.sin(progress % Math.PI) % 1;
},
render() {
return (
<View style={styles.container}>
<ProgressBar style={styles.progressView} color="purple" progress={this.getProgress(0.2)} />
<ProgressBar style={styles.progressView} color="red" progress={this.getProgress(0.4)} />
<ProgressBar style={styles.progressView} color="orange" progress={this.getProgress(0.6)} />
<ProgressBar style={styles.progressView} color="yellow" progress={this.getProgress(0.8)} />
<ProgressBar color="purple" progress={this.getProgress(0.2)} style={styles.progressView} />
<ProgressBar color="red" progress={this.getProgress(0.4)} style={styles.progressView} />
<ProgressBar color="orange" progress={this.getProgress(0.6)} style={styles.progressView} />
<ProgressBar color="yellow" progress={this.getProgress(0.8)} style={styles.progressView} />
</View>
);
}
@@ -78,7 +78,7 @@ const examples = [
}
];
var styles = StyleSheet.create({
const styles = StyleSheet.create({
container: {
minWidth: 200,
marginTop: -20,

View File

@@ -1,3 +1,5 @@
/* eslint-disable react/jsx-no-bind */
import React from 'react';
import { action, storiesOf } from '@kadira/storybook';
import { ScrollView, StyleSheet, Text, TouchableHighlight, View } from 'react-native';

View File

@@ -1,7 +1,4 @@
import createReactClass from 'create-react-class';
import { Platform, Switch, Text, View } from 'react-native';
import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
/* eslint-disable react/jsx-no-bind */
/**
* Copyright (c) 2013-present, Facebook, Inc.
@@ -26,7 +23,12 @@ import { storiesOf, action } from '@kadira/storybook';
* @flow
*/
var BasicSwitchExample = createReactClass({
import createReactClass from 'create-react-class';
import { Switch, Text, View } from 'react-native';
import React from 'react';
import { storiesOf } from '@kadira/storybook';
const BasicSwitchExample = createReactClass({
getInitialState() {
return {
trueSwitchIsOn: true,
@@ -50,7 +52,7 @@ var BasicSwitchExample = createReactClass({
}
});
var DisabledSwitchExample = createReactClass({
const DisabledSwitchExample = createReactClass({
render() {
return (
<View>
@@ -61,7 +63,7 @@ var DisabledSwitchExample = createReactClass({
}
});
var ColorSwitchExample = createReactClass({
const ColorSwitchExample = createReactClass({
getInitialState() {
return {
colorTrueSwitchIsOn: true,
@@ -91,7 +93,7 @@ var ColorSwitchExample = createReactClass({
}
});
var EventSwitchExample = createReactClass({
const EventSwitchExample = createReactClass({
getInitialState() {
return {
eventSwitchIsOn: false,
@@ -132,7 +134,7 @@ var EventSwitchExample = createReactClass({
}
});
var SizeSwitchExample = createReactClass({
const SizeSwitchExample = createReactClass({
getInitialState() {
return {
trueSwitchIsOn: true,
@@ -157,40 +159,40 @@ var SizeSwitchExample = createReactClass({
}
});
var examples = [
const examples = [
{
title: 'set to true or false',
render(): ReactElement<any> {
render() {
return <BasicSwitchExample />;
}
},
{
title: 'disabled',
render(): ReactElement<any> {
render() {
return <DisabledSwitchExample />;
}
},
{
title: 'change events',
render(): ReactElement<any> {
render() {
return <EventSwitchExample />;
}
},
{
title: 'custom colors',
render(): ReactElement<any> {
render() {
return <ColorSwitchExample />;
}
},
{
title: 'custom size',
render(): ReactElement<any> {
render() {
return <SizeSwitchExample />;
}
},
{
title: 'controlled component',
render(): ReactElement<any> {
render() {
return <Switch />;
}
}

View File

@@ -1,7 +1,4 @@
import createReactClass from 'create-react-class';
import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import { Image, StyleSheet, Text, View } from 'react-native';
/* eslint-disable react/jsx-no-bind */
/**
* Copyright (c) 2013-present, Facebook, Inc.
@@ -26,7 +23,12 @@ import { Image, StyleSheet, Text, View } from 'react-native';
* @flow
*/
var Entity = createReactClass({
import createReactClass from 'create-react-class';
import React from 'react';
import { storiesOf } from '@kadira/storybook';
import { Image, Text, View } from 'react-native';
const Entity = createReactClass({
render: function() {
return (
<Text style={{ fontWeight: '500', color: '#527fe4' }}>
@@ -36,7 +38,7 @@ var Entity = createReactClass({
}
});
var AttributeToggler = createReactClass({
const AttributeToggler = createReactClass({
getInitialState: function() {
return { fontWeight: 'bold', fontSize: 15 };
},
@@ -51,7 +53,7 @@ var AttributeToggler = createReactClass({
});
},
render: function() {
var curStyle = { fontWeight: this.state.fontWeight, fontSize: this.state.fontSize };
const curStyle = { fontWeight: this.state.fontWeight, fontSize: this.state.fontSize };
return (
<View>
<Text style={curStyle}>
@@ -60,10 +62,10 @@ var AttributeToggler = createReactClass({
<Text>
<Text>See how it will even work on <Text style={curStyle}>this nested text</Text></Text>
</Text>
<Text style={{ backgroundColor: '#ffaaaa', marginTop: 5 }} onPress={this.toggleWeight}>
<Text onPress={this.toggleWeight} style={{ backgroundColor: '#ffaaaa', marginTop: 5 }}>
Toggle Weight
</Text>
<Text style={{ backgroundColor: '#aaaaff', marginTop: 5 }} onPress={this.increaseSize}>
<Text onPress={this.increaseSize} style={{ backgroundColor: '#aaaaff', marginTop: 5 }}>
Increase Size
</Text>
</View>
@@ -387,7 +389,7 @@ const examples = [
},
{
title: 'Toggling Attributes',
render: function(): ReactElement<any> {
render: function() {
return <AttributeToggler />;
}
},
@@ -447,9 +449,9 @@ const examples = [
Lorem ipsum dolor sit amet,
{' '}
<Text
suppressHighlighting={false}
style={{ backgroundColor: 'white', textDecorationLine: 'underline', color: 'blue' }}
onPress={() => null}
style={{ backgroundColor: 'white', textDecorationLine: 'underline', color: 'blue' }}
suppressHighlighting={false}
>
consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
</Text>
@@ -556,14 +558,6 @@ const examples = [
}
];
var styles = StyleSheet.create({
backgroundColorText: {
margin: 5,
marginBottom: 0,
backgroundColor: 'rgba(100, 100, 100, 0.3)'
}
});
examples.forEach(example => {
storiesOf('component: Text', module)
.addDecorator(renderStory => <View style={{ width: 320 }}>{renderStory()}</View>)

View File

@@ -1,6 +1,4 @@
import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import { StyleSheet, Text, TextInput, View } from 'react-native';
/* eslint-disable react/jsx-no-bind */
/**
* Copyright (c) 2013-present, Facebook, Inc.
@@ -25,7 +23,17 @@ import { StyleSheet, Text, TextInput, View } from 'react-native';
* @flow
*/
import React from 'react';
import { storiesOf } from '@kadira/storybook';
import { any, bool, object, string } from 'prop-types';
import { StyleSheet, Text, TextInput, View } from 'react-native';
class WithLabel extends React.Component {
static propTypes = {
children: any,
label: string
};
render() {
return (
<View style={styles.labelContainer}>
@@ -62,14 +70,14 @@ class TextEventsExample extends React.Component {
<View style={{ alignItems: 'center' }}>
<TextInput
autoCapitalize="none"
placeholder="Enter text to see events"
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)}
onFocus={() => this.updateText('onFocus')}
onKeyPress={event => {
this.updateText('onKeyPress key: ' + event.nativeEvent.key);
}}
onSelectionChange={event =>
this.updateText(
'onSelectionChange range: ' +
@@ -77,9 +85,9 @@ class TextEventsExample extends React.Component {
',' +
event.nativeEvent.selection.end
)}
onKeyPress={event => {
this.updateText('onKeyPress key: ' + event.nativeEvent.key);
}}
onSubmitEditing={event =>
this.updateText('onSubmitEditing text: ' + event.nativeEvent.text)}
placeholder="Enter text to see events"
style={[styles.default, { maxWidth: 200 }]}
/>
<Text style={styles.eventLabel}>
@@ -103,6 +111,7 @@ class AutoExpandingTextInput extends React.Component {
height: 0
};
}
render() {
return (
<TextInput
@@ -128,15 +137,16 @@ class RewriteExample extends React.Component {
super(props);
this.state = { text: '' };
}
render() {
var limit = 20;
var remainder = limit - this.state.text.length;
var remainderColor = remainder > 5 ? 'blue' : 'red';
const limit = 20;
const remainder = limit - this.state.text.length;
const remainderColor = remainder > 5 ? 'blue' : 'red';
return (
<View style={styles.rewriteContainer}>
<TextInput
multiline={false}
maxLength={limit}
multiline={false}
onChangeText={text => {
text = text.replace(/ /g, '_');
this.setState({ text });
@@ -159,6 +169,7 @@ class RewriteExampleInvalidCharacters extends React.Component {
super(props);
this.state = { text: '' };
}
render() {
return (
<View style={styles.rewriteContainer}>
@@ -182,13 +193,15 @@ class TokenizedTextExample extends React.Component {
super(props);
this.state = { text: 'Hello #World' };
}
render() {
//define delimiter
let delimiter = /\s+/;
const delimiter = /\s+/;
//split string
let _text = this.state.text;
let token, index, parts = [];
let token, index;
const parts = [];
while (_text) {
delimiter.lastIndex = 0;
token = delimiter.exec(_text);
@@ -209,12 +222,12 @@ class TokenizedTextExample extends React.Component {
return (
<View>
<TextInput
value={parts.join('')}
multiline={true}
style={styles.multiline}
onChangeText={text => {
this.setState({ text });
}}
style={styles.multiline}
value={parts.join('')}
/>
</View>
);
@@ -222,53 +235,68 @@ class TokenizedTextExample extends React.Component {
}
class BlurOnSubmitExample extends React.Component {
constructor(props) {
super(props);
this._nodes = {};
}
focusNextField = nextField => {
this.refs[nextField].focus();
this._nodes[nextField].focus();
};
render() {
return (
<View>
<TextInput
ref="1"
style={styles.default}
placeholder="blurOnSubmit = false"
returnKeyType="next"
blurOnSubmit={false}
onSubmitEditing={() => this.focusNextField('2')}
placeholder="blurOnSubmit = false"
ref={c => {
this._nodes['1'] = c;
}}
returnKeyType="next"
style={styles.default}
/>
<TextInput
ref="2"
style={styles.default}
blurOnSubmit={false}
keyboardType="email-address"
placeholder="blurOnSubmit = false"
returnKeyType="next"
blurOnSubmit={false}
onSubmitEditing={() => this.focusNextField('3')}
/>
<TextInput
ref="3"
style={styles.default}
keyboardType="url"
placeholder="blurOnSubmit = false"
ref={c => {
this._nodes['2'] = c;
}}
returnKeyType="next"
style={styles.default}
/>
<TextInput
blurOnSubmit={false}
keyboardType="url"
onSubmitEditing={() => this.focusNextField('4')}
/>
<TextInput
ref="4"
style={styles.default}
keyboardType="numeric"
placeholder="blurOnSubmit = false"
blurOnSubmit={false}
onSubmitEditing={() => this.focusNextField('5')}
ref={c => {
this._nodes['3'] = c;
}}
returnKeyType="next"
style={styles.default}
/>
<TextInput
ref="5"
blurOnSubmit={false}
keyboardType="numeric"
onSubmitEditing={() => this.focusNextField('5')}
placeholder="blurOnSubmit = false"
ref={c => {
this._nodes['4'] = c;
}}
style={styles.default}
/>
<TextInput
keyboardType="numeric"
placeholder="blurOnSubmit = true"
ref={c => {
this._nodes['5'] = c;
}}
returnKeyType="done"
style={styles.default}
/>
</View>
);
@@ -288,6 +316,12 @@ class SelectionExample extends React.Component {
_textInput: any;
static propTypes = {
multiline: bool,
style: object,
value: string
};
constructor(props) {
super(props);
this.state = {
@@ -301,7 +335,7 @@ class SelectionExample extends React.Component {
}
getRandomPosition() {
var length = this.state.value.length;
const length = this.state.value.length;
return Math.round(Math.random() * length);
}
@@ -311,7 +345,7 @@ class SelectionExample extends React.Component {
}
selectRandom() {
var positions = [this.getRandomPosition(), this.getRandomPosition()].sort();
const positions = [this.getRandomPosition(), this.getRandomPosition()].sort();
this.select(...positions);
}
@@ -324,7 +358,7 @@ class SelectionExample extends React.Component {
}
render() {
var length = this.state.value.length;
const length = this.state.value.length;
return (
<View>
@@ -362,7 +396,7 @@ class SelectionExample extends React.Component {
}
}
var styles = StyleSheet.create({
const styles = StyleSheet.create({
page: {
paddingBottom: 300
},
@@ -433,9 +467,9 @@ const examples = [
return (
<View>
<TextInput
accessibilityLabel="I am the accessibility label for text input"
autoFocus={true}
style={styles.default}
accessibilityLabel="I am the accessibility label for text input"
/>
</View>
);
@@ -492,7 +526,7 @@ const examples = [
{
title: 'Keyboard types',
render: function() {
var keyboardTypes = [
const keyboardTypes = [
'default',
//'ascii-capable',
//'numbers-and-punctuation',
@@ -506,7 +540,7 @@ const examples = [
'web-search',
'numeric'
];
var examples = keyboardTypes.map(type => {
const examples = keyboardTypes.map(type => {
return (
<WithLabel key={type} label={type}>
<TextInput keyboardType={type} style={styles.default} />
@@ -519,8 +553,8 @@ const examples = [
{
title: 'Keyboard appearance',
render: function() {
var keyboardAppearance = ['default', 'light', 'dark'];
var examples = keyboardAppearance.map(type => {
const keyboardAppearance = ['default', 'light', 'dark'];
const examples = keyboardAppearance.map(type => {
return (
<WithLabel key={type} label={type}>
<TextInput keyboardAppearance={type} style={styles.default} />
@@ -533,7 +567,7 @@ const examples = [
{
title: 'Return key types',
render: function() {
var returnKeyTypes = [
const returnKeyTypes = [
'default',
'go',
'google',
@@ -546,7 +580,7 @@ const examples = [
'done',
'emergency-call'
];
var examples = returnKeyTypes.map(type => {
const examples = returnKeyTypes.map(type => {
return (
<WithLabel key={type} label={type}>
<TextInput returnKeyType={type} style={styles.default} />
@@ -574,7 +608,7 @@ const examples = [
return (
<View>
<WithLabel label="true">
<TextInput secureTextEntry={true} style={styles.default} defaultValue="abc" />
<TextInput defaultValue="abc" secureTextEntry={true} style={styles.default} />
</WithLabel>
</View>
);
@@ -591,8 +625,8 @@ const examples = [
render: function() {
return (
<View>
<TextInput style={[styles.default, { color: 'blue' }]} defaultValue="Blue" />
<TextInput style={[styles.default, { color: 'green' }]} defaultValue="Green" />
<TextInput defaultValue="Blue" style={[styles.default, { color: 'blue' }]} />
<TextInput defaultValue="Green" style={[styles.default, { color: 'green' }]} />
</View>
);
}
@@ -602,11 +636,11 @@ const examples = [
render: function() {
return (
<View>
<TextInput style={styles.default} selectionColor={'green'} defaultValue="Highlight me" />
<TextInput defaultValue="Highlight me" selectionColor={'green'} style={styles.default} />
<TextInput
style={styles.default}
selectionColor={'rgba(86, 76, 205, 1)'}
defaultValue="Highlight me"
selectionColor={'rgba(86, 76, 205, 1)'}
style={styles.default}
/>
</View>
);
@@ -618,16 +652,16 @@ const examples = [
return (
<View>
<WithLabel label="never">
<TextInput style={styles.default} clearButtonMode="never" />
<TextInput clearButtonMode="never" style={styles.default} />
</WithLabel>
<WithLabel label="while editing">
<TextInput style={styles.default} clearButtonMode="while-editing" />
<TextInput clearButtonMode="while-editing" style={styles.default} />
</WithLabel>
<WithLabel label="unless editing">
<TextInput style={styles.default} clearButtonMode="unless-editing" />
<TextInput clearButtonMode="unless-editing" style={styles.default} />
</WithLabel>
<WithLabel label="always">
<TextInput style={styles.default} clearButtonMode="always" />
<TextInput clearButtonMode="always" style={styles.default} />
</WithLabel>
</View>
);
@@ -640,18 +674,18 @@ const examples = [
<View>
<WithLabel label="clearTextOnFocus">
<TextInput
placeholder="text is cleared on focus"
defaultValue="text is cleared on focus"
style={styles.default}
clearTextOnFocus={true}
defaultValue="text is cleared on focus"
placeholder="text is cleared on focus"
style={styles.default}
/>
</WithLabel>
<WithLabel label="selectTextOnFocus">
<TextInput
placeholder="text is selected on focus"
defaultValue="text is selected on focus"
style={styles.default}
placeholder="text is selected on focus"
selectTextOnFocus={true}
style={styles.default}
/>
</WithLabel>
</View>
@@ -670,12 +704,14 @@ const examples = [
return (
<View>
<TextInput
style={styles.multiline}
placeholder="blurOnSubmit = true"
returnKeyType="next"
blurOnSubmit={true}
multiline={true}
onSubmitEditing={event => alert(event.nativeEvent.text)}
onSubmitEditing={event => {
console.log(event.nativeEvent.text);
}}
placeholder="blurOnSubmit = true"
returnKeyType="next"
style={styles.multiline}
/>
</View>
);
@@ -686,35 +722,35 @@ const examples = [
render: function() {
return (
<View>
<TextInput placeholder="multiline text input" multiline={true} style={styles.multiline} />
<TextInput multiline={true} placeholder="multiline text input" style={styles.multiline} />
<TextInput
placeholder="multiline text input with font styles and placeholder"
multiline={true}
clearTextOnFocus={true}
autoCorrect={true}
autoCapitalize="words"
placeholderTextColor="red"
autoCorrect={true}
clearTextOnFocus={true}
keyboardType="url"
multiline={true}
placeholder="multiline text input with font styles and placeholder"
placeholderTextColor="red"
style={[styles.multiline, styles.multilineWithFontStyles]}
/>
<TextInput
placeholder="multiline text input with max length"
maxLength={5}
multiline={true}
placeholder="multiline text input with max length"
style={styles.multiline}
/>
<TextInput
placeholder="uneditable multiline text input"
editable={false}
multiline={true}
placeholder="uneditable multiline text input"
style={styles.multiline}
/>
<TextInput
dataDetectorTypes="phoneNumber"
defaultValue="uneditable multiline text input with phone number detection: 88888888."
editable={false}
multiline={true}
style={styles.multiline}
dataDetectorTypes="phoneNumber"
/>
</View>
);
@@ -740,8 +776,8 @@ const examples = [
return (
<View>
<AutoExpandingTextInput
placeholder="height increases with content"
enablesReturnKeyAutomatically={true}
placeholder="height increases with content"
returnKeyType="default"
/>
</View>
@@ -781,10 +817,10 @@ const examples = [
<TextInput maxLength={5} placeholder="ZIP code entry" style={styles.default} />
</WithLabel>
<WithLabel label="maxLength: 5 with default value already set">
<TextInput maxLength={5} defaultValue="94025" style={styles.default} />
<TextInput defaultValue="94025" maxLength={5} style={styles.default} />
</WithLabel>
<WithLabel label="maxLength: 5 with very long default value already set">
<TextInput maxLength={5} defaultValue="9402512345" style={styles.default} />
<TextInput defaultValue="9402512345" maxLength={5} style={styles.default} />
</WithLabel>
</View>
);

View File

@@ -1,16 +1,4 @@
import createReactClass from 'create-react-class';
import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import {
Image,
StyleSheet,
Text,
TouchableHighlight,
TouchableOpacity,
Platform,
TouchableNativeFeedback,
View
} from 'react-native';
/* eslint-disable react/jsx-no-bind */
/**
* Copyright (c) 2013-present, Facebook, Inc.
@@ -35,6 +23,19 @@ import {
* @flow
*/
import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import {
Image,
StyleSheet,
Text,
TouchableHighlight,
TouchableOpacity,
Platform,
TouchableNativeFeedback,
View
} from 'react-native';
const examples = [
{
title: '<TouchableHighlight>',
@@ -48,16 +49,16 @@ const examples = [
<View>
<View style={styles.row}>
<TouchableHighlight
style={styles.wrapper}
onPress={() => console.log('stock THW image - highlight')}
style={styles.wrapper}
>
<Image source={heartImage} style={styles.image} />
</TouchableHighlight>
<TouchableHighlight
style={styles.wrapper}
activeOpacity={1}
underlayColor="rgb(210, 230, 255)"
onPress={() => console.log('custom THW text - highlight')}
style={styles.wrapper}
underlayColor="rgb(210, 230, 255)"
>
<View style={styles.wrapperCustom}>
<Text style={styles.text}>
@@ -72,7 +73,7 @@ const examples = [
},
{
title: '<Text onPress={fn}> with highlight',
render: function(): ReactElement<any> {
render: function() {
return <TextOnPressBox />;
}
},
@@ -80,7 +81,7 @@ const examples = [
title: 'Touchable feedback events',
description: '<Touchable*> components accept onPress, onPressIn, ' +
'onPressOut, and onLongPress as props.',
render: function(): ReactElement<any> {
render: function() {
return <TouchableFeedbackEvents />;
}
},
@@ -89,14 +90,14 @@ const examples = [
description: '<Touchable*> components also accept delayPressIn, ' +
'delayPressOut, and delayLongPress as props. These props impact the ' +
'timing of feedback events.',
render: function(): ReactElement<any> {
render: function() {
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(): ReactElement<any> {
render: function() {
return <ForceTouchExample />;
},
platform: 'ios'
@@ -105,7 +106,7 @@ const examples = [
title: 'Touchable Hit Slop',
description: '<Touchable*> components accept hitSlop prop which extends the touch area ' +
'without changing the view bounds.',
render: function(): ReactElement<any> {
render: function() {
return <TouchableHitSlop />;
}
},
@@ -113,25 +114,26 @@ const examples = [
title: 'Disabled Touchable*',
description: '<Touchable*> components accept disabled prop which prevents ' +
'any interaction with component',
render: function(): ReactElement<any> {
render: function() {
return <TouchableDisabled />;
}
}
];
var TextOnPressBox = createReactClass({
getInitialState: function() {
return {
timesPressed: 0
};
},
textOnPress: function() {
class TextOnPressBox extends React.Component {
constructor(props) {
super(props);
this.state = { timesPressed: 0 };
}
_handlePress = () => {
this.setState({
timesPressed: this.state.timesPressed + 1
});
},
render: function() {
var textLog = '';
};
render() {
let textLog = '';
if (this.state.timesPressed > 1) {
textLog = this.state.timesPressed + 'x text onPress';
} else if (this.state.timesPressed > 0) {
@@ -140,79 +142,80 @@ var TextOnPressBox = createReactClass({
return (
<View>
<Text style={styles.textBlock} onPress={this.textOnPress}>
<Text onPress={this._handlePress} style={styles.textBlock}>
Text has built-in onPress handling
</Text>
<View style={styles.logBox}>
<Text>
{textLog}
</Text>
<Text>{textLog}</Text>
</View>
</View>
);
}
});
}
var TouchableFeedbackEvents = createReactClass({
getInitialState: function() {
return {
eventLog: []
};
},
render: function() {
class TouchableFeedbackEvents extends React.Component {
constructor(props) {
super(props);
this.state = { eventLog: [] };
}
render() {
return (
<View testID="touchable_feedback_events">
<View style={[styles.row, { justifyContent: 'center' }]}>
<TouchableOpacity
style={styles.wrapper}
testID="touchable_feedback_events_button"
accessibilityComponentType="button"
accessibilityLabel="touchable feedback events"
accessibilityTraits="button"
accessibilityComponentType="button"
onPress={() => this._appendEvent('press')}
onPressIn={() => this._appendEvent('pressIn')}
onPressOut={() => this._appendEvent('pressOut')}
onLongPress={() => this._appendEvent('longPress')}
onLongPress={this._createPressHandler('longPress')}
onPress={this._createPressHandler('press')}
onPressIn={this._createPressHandler('pressIn')}
onPressOut={this._createPressHandler('pressOut')}
style={styles.wrapper}
testID="touchable_feedback_events_button"
>
<Text style={styles.button}>
Press Me
</Text>
</TouchableOpacity>
</View>
<View testID="touchable_feedback_events_console" style={styles.eventLogBox}>
<View style={styles.eventLogBox} testID="touchable_feedback_events_console">
{this.state.eventLog.map((e, ii) => <Text key={ii}>{e}</Text>)}
</View>
</View>
);
},
_appendEvent: function(eventName) {
var limit = 6;
var eventLog = this.state.eventLog.slice(0, limit - 1);
eventLog.unshift(eventName);
this.setState({ eventLog });
}
});
var TouchableDelayEvents = createReactClass({
getInitialState: function() {
return {
eventLog: []
_createPressHandler = eventName => {
return () => {
const limit = 6;
const eventLog = this.state.eventLog.slice(0, limit - 1);
eventLog.unshift(eventName);
this.setState({ eventLog });
};
},
render: function() {
};
}
class TouchableDelayEvents extends React.Component {
constructor(props) {
super(props);
this.state = { eventLog: [] };
}
render() {
return (
<View testID="touchable_delay_events">
<View style={[styles.row, { justifyContent: 'center' }]}>
<TouchableOpacity
delayLongPress={800}
delayPressIn={400}
delayPressOut={1000}
onLongPress={this._createPressHandler('longPress - 800ms delay')}
onPress={this._createPressHandler('press')}
onPressIn={this._createPressHandler('pressIn - 400ms delay')}
onPressOut={this._createPressHandler('pressOut - 1000ms delay')}
style={styles.wrapper}
testID="touchable_delay_events_button"
onPress={() => this._appendEvent('press')}
delayPressIn={400}
onPressIn={() => this._appendEvent('pressIn - 400ms delay')}
delayPressOut={1000}
onPressOut={() => this._appendEvent('pressOut - 1000ms delay')}
delayLongPress={800}
onLongPress={() => this._appendEvent('longPress - 800ms delay')}
>
<Text style={styles.button}>
Press Me
@@ -224,27 +227,31 @@ var TouchableDelayEvents = createReactClass({
</View>
</View>
);
},
_appendEvent: function(eventName) {
var limit = 6;
var eventLog = this.state.eventLog.slice(0, limit - 1);
eventLog.unshift(eventName);
this.setState({ eventLog });
}
});
var ForceTouchExample = createReactClass({
getInitialState: function() {
return {
force: 0
_createPressHandler = eventName => {
return () => {
const limit = 6;
const eventLog = this.state.eventLog.slice(0, limit - 1);
eventLog.unshift(eventName);
this.setState({ eventLog });
};
},
_renderConsoleText: function() {
};
}
class ForceTouchExample extends React.Component {
constructor(props) {
super(props);
this.state = { force: 0 };
}
_renderConsoleText() {
return View.forceTouchAvailable
? 'Force: ' + this.state.force.toFixed(3)
: '3D Touch is not available on this device';
},
render: function() {
}
render() {
return (
<View testID="touchable_3dtouch_event">
<View style={styles.forceTouchBox} testID="touchable_3dtouch_output">
@@ -252,11 +259,11 @@ var ForceTouchExample = createReactClass({
</View>
<View style={[styles.row, { justifyContent: 'center' }]}>
<View
style={styles.wrapper}
testID="touchable_3dtouch_button"
onStartShouldSetResponder={() => true}
onResponderMove={event => this.setState({ force: event.nativeEvent.force })}
onResponderRelease={event => this.setState({ force: 0 })}
onStartShouldSetResponder={() => true}
style={styles.wrapper}
testID="touchable_3dtouch_button"
>
<Text style={styles.button}>
Press Me
@@ -266,21 +273,22 @@ var ForceTouchExample = createReactClass({
</View>
);
}
});
}
var TouchableHitSlop = createReactClass({
getInitialState: function() {
return {
timesPressed: 0
};
},
onPress: function() {
class TouchableHitSlop extends React.Component {
constructor(props) {
super(props);
this.state = { timesPressed: 0 };
}
_handlePress = () => {
this.setState({
timesPressed: this.state.timesPressed + 1
});
},
render: function() {
var log = '';
};
render() {
let log = '';
if (this.state.timesPressed > 1) {
log = this.state.timesPressed + 'x onPress';
} else if (this.state.timesPressed > 0) {
@@ -291,9 +299,9 @@ var TouchableHitSlop = createReactClass({
<View testID="touchable_hit_slop">
<View style={[styles.row, { justifyContent: 'center' }]}>
<TouchableOpacity
onPress={this.onPress}
style={styles.hitSlopWrapper}
hitSlop={{ top: 30, bottom: 30, left: 60, right: 60 }}
onPress={this._handlePress}
style={styles.hitSlopWrapper}
testID="touchable_hit_slop_button"
>
<Text style={styles.hitSlopButton}>
@@ -309,24 +317,24 @@ var TouchableHitSlop = createReactClass({
</View>
);
}
});
}
var TouchableDisabled = createReactClass({
render: function() {
class TouchableDisabled extends React.Component {
render() {
return (
<View>
<TouchableOpacity
disabled={true}
style={[styles.row, styles.block]}
onPress={action('TouchableOpacity')}
style={[styles.row, styles.block]}
>
<Text style={styles.disabledButton}>Disabled TouchableOpacity</Text>
</TouchableOpacity>
<TouchableOpacity
disabled={false}
style={[styles.row, styles.block]}
onPress={action('TouchableOpacity')}
style={[styles.row, styles.block]}
>
<Text style={styles.button}>Enabled TouchableOpacity</Text>
</TouchableOpacity>
@@ -334,9 +342,9 @@ var TouchableDisabled = createReactClass({
<TouchableHighlight
activeOpacity={1}
disabled={true}
underlayColor="rgb(210, 230, 255)"
style={[styles.row, styles.block]}
onPress={action('TouchableHighlight')}
style={[styles.row, styles.block]}
underlayColor="rgb(210, 230, 255)"
>
<Text style={styles.disabledButton}>
Disabled TouchableHighlight
@@ -345,9 +353,9 @@ var TouchableDisabled = createReactClass({
<TouchableHighlight
activeOpacity={1}
underlayColor="rgb(210, 230, 255)"
style={[styles.row, styles.block]}
onPress={action('TouchableHighlight')}
style={[styles.row, styles.block]}
underlayColor="rgb(210, 230, 255)"
>
<Text style={styles.button}>
Enabled TouchableHighlight
@@ -356,9 +364,9 @@ var TouchableDisabled = createReactClass({
{Platform.OS === 'android' &&
<TouchableNativeFeedback
style={[styles.row, styles.block]}
onPress={() => console.log('custom TNF has been clicked')}
background={TouchableNativeFeedback.SelectableBackground()}
onPress={() => console.log('custom TNF has been clicked')}
style={[styles.row, styles.block]}
>
<View>
<Text style={[styles.button, styles.nativeFeedbackButton]}>
@@ -369,10 +377,10 @@ var TouchableDisabled = createReactClass({
{Platform.OS === 'android' &&
<TouchableNativeFeedback
disabled={true}
style={[styles.row, styles.block]}
onPress={() => console.log('custom TNF has been clicked')}
background={TouchableNativeFeedback.SelectableBackground()}
disabled={true}
onPress={() => console.log('custom TNF has been clicked')}
style={[styles.row, styles.block]}
>
<View>
<Text style={[styles.disabledButton, styles.nativeFeedbackButton]}>
@@ -383,11 +391,11 @@ var TouchableDisabled = createReactClass({
</View>
);
}
});
}
var heartImage = { uri: 'https://pbs.twimg.com/media/BlXBfT3CQAA6cVZ.png:small' };
const heartImage = { uri: 'https://pbs.twimg.com/media/BlXBfT3CQAA6cVZ.png:small' };
var styles = StyleSheet.create({
const styles = StyleSheet.create({
row: {
justifyContent: 'center',
flexDirection: 'row'

View File

@@ -1,6 +1,6 @@
import createReactClass from 'create-react-class';
import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import { storiesOf } from '@kadira/storybook';
import { StyleSheet, Text, TouchableWithoutFeedback, View } from 'react-native';
/**
@@ -26,7 +26,7 @@ import { StyleSheet, Text, TouchableWithoutFeedback, View } from 'react-native';
* @flow
*/
var styles = StyleSheet.create({
const styles = StyleSheet.create({
box: {
backgroundColor: '#527FE4',
borderColor: '#000033',
@@ -51,7 +51,7 @@ var styles = StyleSheet.create({
}
});
var ViewBorderStyleExample = createReactClass({
const ViewBorderStyleExample = createReactClass({
getInitialState() {
return {
showBorder: true
@@ -96,7 +96,7 @@ var ViewBorderStyleExample = createReactClass({
}
});
var ZIndexExample = createReactClass({
const ZIndexExample = createReactClass({
getInitialState() {
return {
flipped: false

View File

@@ -1,6 +1,6 @@
import createReactClass from 'create-react-class';
import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import { storiesOf } from '@kadira/storybook';
import { Animated, StyleSheet, Text, View } from 'react-native';
/**
@@ -25,7 +25,7 @@ import { Animated, StyleSheet, Text, View } from 'react-native';
* @flow
*/
var Flip = createReactClass({
const Flip = createReactClass({
getInitialState() {
return {
theta: new Animated.Value(45)
@@ -95,7 +95,7 @@ var Flip = createReactClass({
}
});
var styles = StyleSheet.create({
const styles = StyleSheet.create({
box1: {
left: 0,
backgroundColor: 'green',
@@ -199,7 +199,7 @@ const examples = [
{
title: 'Perspective',
description: 'perspective: 850, rotateX: Animated.timing(0 -> 360)',
render(): ReactElement<any> {
render() {
return <Flip />;
}
},

View File

@@ -16,15 +16,14 @@
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var { Animated, AppRegistry, StyleSheet, Text, TouchableOpacity, View } = ReactNative;
import { any, func, object } from 'prop-types';
import GameBoard from './GameBoard';
import React from 'react';
import { Animated, AppRegistry, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
var GameBoard = require('./GameBoard');
var BOARD_PADDING = 3;
var CELL_MARGIN = 4;
var CELL_SIZE = 60;
const BOARD_PADDING = 3;
const CELL_MARGIN = 4;
const CELL_SIZE = 60;
class Cell extends React.Component {
render() {
@@ -33,6 +32,10 @@ class Cell extends React.Component {
}
class Board extends React.Component {
static propTypes = {
children: any
};
render() {
return (
<View style={styles.board}>
@@ -49,6 +52,10 @@ class Board extends React.Component {
class Tile extends React.Component {
state: any;
static propTypes = {
tile: object
};
static _getPosition(index): number {
return BOARD_PADDING + (index * (CELL_SIZE + CELL_MARGIN * 2) + CELL_MARGIN);
}
@@ -56,7 +63,7 @@ class Tile extends React.Component {
constructor(props: {}) {
super(props);
var tile = this.props.tile;
const tile = this.props.tile;
this.state = {
opacity: new Animated.Value(0),
@@ -66,9 +73,9 @@ class Tile extends React.Component {
}
calculateOffset(): { top: number, left: number, opacity: number } {
var tile = this.props.tile;
const tile = this.props.tile;
var offset = {
const offset = {
top: this.state.top,
left: this.state.left,
opacity: this.state.opacity
@@ -95,11 +102,11 @@ class Tile extends React.Component {
}
render() {
var tile = this.props.tile;
const tile = this.props.tile;
var tileStyles = [styles.tile, styles['tile' + tile.value], this.calculateOffset()];
const tileStyles = [styles.tile, styles['tile' + tile.value], this.calculateOffset()];
var textStyles = [
const textStyles = [
styles.value,
tile.value > 4 && styles.whiteText,
tile.value > 100 && styles.threeDigits,
@@ -115,14 +122,19 @@ class Tile extends React.Component {
}
class GameEndOverlay extends React.Component {
static propTypes = {
board: object,
onRestart: func
};
render() {
var board = this.props.board;
const board = this.props.board;
if (!board.hasWon() && !board.hasLost()) {
return <View />;
}
var message = board.hasWon() ? 'Good Job!' : 'Game Over';
const message = board.hasWon() ? 'Good Job!' : 'Game Over';
return (
<View style={styles.overlay}>
@@ -149,28 +161,28 @@ class Game2048 extends React.Component {
this.startY = 0;
}
restartGame() {
_handleRestart = () => {
this.setState({ board: new GameBoard() });
}
};
handleTouchStart(event: Object) {
_handleTouchStart = (event: Object) => {
if (this.state.board.hasWon()) {
return;
}
this.startX = event.nativeEvent.pageX;
this.startY = event.nativeEvent.pageY;
}
};
handleTouchEnd(event: Object) {
_handleTouchEnd = (event: Object) => {
if (this.state.board.hasWon()) {
return;
}
var deltaX = event.nativeEvent.pageX - this.startX;
var deltaY = event.nativeEvent.pageY - this.startY;
const deltaX = event.nativeEvent.pageX - this.startX;
const deltaY = event.nativeEvent.pageY - this.startY;
var direction = -1;
let direction = -1;
if (Math.abs(deltaX) > 3 * Math.abs(deltaY) && Math.abs(deltaX) > 30) {
direction = deltaX > 0 ? 2 : 0;
} else if (Math.abs(deltaY) > 3 * Math.abs(deltaX) && Math.abs(deltaY) > 30) {
@@ -180,29 +192,29 @@ class Game2048 extends React.Component {
if (direction !== -1) {
this.setState({ board: this.state.board.move(direction) });
}
}
};
render() {
var tiles = this.state.board.tiles
const tiles = this.state.board.tiles
.filter(tile => tile.value)
.map(tile => <Tile ref={tile.id} key={tile.id} tile={tile} />);
.map(tile => <Tile key={tile.id} ref={tile.id} tile={tile} />);
return (
<View
onTouchEnd={this._handleTouchEnd}
onTouchStart={this._handleTouchStart}
style={styles.container}
onTouchStart={event => this.handleTouchStart(event)}
onTouchEnd={event => this.handleTouchEnd(event)}
>
<Board>
{tiles}
</Board>
<GameEndOverlay board={this.state.board} onRestart={() => this.restartGame()} />
<GameEndOverlay board={this.state.board} onRestart={this._handleRestart} />
</View>
);
}
}
var styles = StyleSheet.create({
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',

View File

@@ -1,5 +1,5 @@
import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import { storiesOf } from '@kadira/storybook';
import Game2048 from './Game2048';
storiesOf('demo: Game2048', module).add('the game', () => <Game2048 />);

View File

@@ -19,20 +19,20 @@
// NB: Taken straight from: https://github.com/IvanVergiliev/2048-react/blob/master/src/board.js
// with no modification except to format it for CommonJS and fix lint/flow errors
var rotateLeft = function(matrix) {
var rows = matrix.length;
var columns = matrix[0].length;
var res = [];
for (var row = 0; row < rows; ++row) {
const rotateLeft = function(matrix) {
const rows = matrix.length;
const columns = matrix[0].length;
const res = [];
for (let row = 0; row < rows; ++row) {
res.push([]);
for (var column = 0; column < columns; ++column) {
for (let column = 0; column < columns; ++column) {
res[row][column] = matrix[column][columns - row - 1];
}
}
return res;
};
var Tile = function(value?: number, row?: number, column?: number) {
const Tile = function(value?: number, row?: number, column?: number) {
this.value = value || 0;
this.row = row || -1;
@@ -81,10 +81,10 @@ Tile.prototype.toColumn = function() {
return this.mergedInto ? this.mergedInto.column : this.column;
};
var Board = function() {
const Board = function() {
this.tiles = [];
this.cells = [];
for (var i = 0; i < Board.size; ++i) {
for (let i = 0; i < Board.size; ++i) {
this.cells[i] = [this.addTile(), this.addTile(), this.addTile(), this.addTile()];
}
this.addRandomTile();
@@ -92,9 +92,9 @@ var Board = function() {
this.won = false;
};
Board.prototype.addTile = function() {
var res = new Tile();
Tile.apply(res, arguments);
Board.prototype.addTile = function(...args) {
const res = new Tile();
Tile.apply(res, args);
this.tiles.push(res);
return res;
};
@@ -102,19 +102,19 @@ Board.prototype.addTile = function() {
Board.size = 4;
Board.prototype.moveLeft = function() {
var hasChanged = false;
for (var row = 0; row < Board.size; ++row) {
var currentRow = this.cells[row].filter(function(tile) {
let hasChanged = false;
for (let row = 0; row < Board.size; ++row) {
const currentRow = this.cells[row].filter(function(tile) {
return tile.value !== 0;
});
var resultRow = [];
for (var target = 0; target < Board.size; ++target) {
var targetTile = currentRow.length ? currentRow.shift() : this.addTile();
const resultRow = [];
for (let target = 0; target < Board.size; ++target) {
let targetTile = currentRow.length ? currentRow.shift() : this.addTile();
if (currentRow.length > 0 && currentRow[0].value === targetTile.value) {
var tile1 = targetTile;
const tile1 = targetTile;
targetTile = this.addTile(targetTile.value);
tile1.mergedInto = targetTile;
var tile2 = currentRow.shift();
const tile2 = currentRow.shift();
tile2.mergedInto = targetTile;
targetTile.value += tile2.value;
}
@@ -142,28 +142,28 @@ Board.prototype.setPositions = function() {
Board.fourProbability = 0.1;
Board.prototype.addRandomTile = function() {
var emptyCells = [];
for (var r = 0; r < Board.size; ++r) {
for (var c = 0; c < Board.size; ++c) {
const emptyCells = [];
for (let r = 0; r < Board.size; ++r) {
for (let c = 0; c < Board.size; ++c) {
if (this.cells[r][c].value === 0) {
emptyCells.push({ r: r, c: c });
}
}
}
var index = Math.floor(Math.random() * emptyCells.length);
var cell = emptyCells[index];
var newValue = Math.random() < Board.fourProbability ? 4 : 2;
const index = Math.floor(Math.random() * emptyCells.length);
const cell = emptyCells[index];
const newValue = Math.random() < Board.fourProbability ? 4 : 2;
this.cells[cell.r][cell.c] = this.addTile(newValue);
};
Board.prototype.move = function(direction) {
// 0 -> left, 1 -> up, 2 -> right, 3 -> down
this.clearOldTiles();
for (var i = 0; i < direction; ++i) {
for (let i = 0; i < direction; ++i) {
this.cells = rotateLeft(this.cells);
}
var hasChanged = this.moveLeft();
for (var i = direction; i < 4; ++i) {
const hasChanged = this.moveLeft();
for (let i = direction; i < 4; ++i) {
this.cells = rotateLeft(this.cells);
}
if (hasChanged) {
@@ -190,13 +190,13 @@ Board.deltaX = [-1, 0, 1, 0];
Board.deltaY = [0, -1, 0, 1];
Board.prototype.hasLost = function() {
var canMove = false;
for (var row = 0; row < Board.size; ++row) {
for (var column = 0; column < Board.size; ++column) {
let canMove = false;
for (let row = 0; row < Board.size; ++row) {
for (let column = 0; column < Board.size; ++column) {
canMove = canMove || this.cells[row][column].value === 0;
for (var dir = 0; dir < 4; ++dir) {
var newRow = row + Board.deltaX[dir];
var newColumn = column + Board.deltaY[dir];
for (let dir = 0; dir < 4; ++dir) {
const newRow = row + Board.deltaX[dir];
const newColumn = column + Board.deltaY[dir];
if (newRow < 0 || newRow >= Board.size || newColumn < 0 || newColumn >= Board.size) {
continue;
}

View File

@@ -17,20 +17,20 @@
'use strict';
import createReactClass from 'create-react-class';
var React = require('react');
var ReactNative = require('react-native');
var { AppRegistry, StyleSheet, Text, TouchableHighlight, View } = ReactNative;
const React = require('react');
const ReactNative = require('react-native');
const { AppRegistry, StyleSheet, Text, TouchableHighlight, View } = ReactNative;
class Board {
grid: Array<Array<number>>;
turn: number;
constructor() {
var size = 3;
var grid = Array(size);
for (var i = 0; i < size; i++) {
var row = Array(size);
for (var j = 0; j < size; j++) {
const size = 3;
const grid = Array(size);
for (let i = 0; i < size; i++) {
const row = Array(size);
for (let j = 0; j < size; j++) {
row[j] = 0;
}
grid[i] = row;
@@ -50,7 +50,7 @@ class Board {
}
winner(): ?number {
for (var i = 0; i < 3; i++) {
for (let i = 0; i < 3; i++) {
if (
this.grid[i][0] !== 0 &&
this.grid[i][0] === this.grid[i][1] &&
@@ -60,7 +60,7 @@ class Board {
}
}
for (var i = 0; i < 3; i++) {
for (let i = 0; i < 3; i++) {
if (
this.grid[0][i] !== 0 &&
this.grid[0][i] === this.grid[1][i] &&
@@ -90,8 +90,8 @@ class Board {
}
tie(): boolean {
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (this.grid[i][j] === 0) {
return false;
}
@@ -101,7 +101,7 @@ class Board {
}
}
var Cell = createReactClass({
const Cell = createReactClass({
cellStyle() {
switch (this.props.player) {
case 1:
@@ -138,9 +138,9 @@ var Cell = createReactClass({
render() {
return (
<TouchableHighlight
activeOpacity={0.5}
onPress={this.props.onPress}
underlayColor="transparent"
activeOpacity={0.5}
>
<View style={[styles.cell, this.cellStyle()]}>
<Text style={[styles.cellText, this.textStyle()]}>
@@ -152,17 +152,17 @@ var Cell = createReactClass({
}
});
var GameEndOverlay = createReactClass({
const GameEndOverlay = createReactClass({
render() {
var board = this.props.board;
const board = this.props.board;
var tie = board.tie();
var winner = board.winner();
const tie = board.tie();
const winner = board.winner();
if (!winner && !tie) {
return <View />;
}
var message;
let message;
if (tie) {
message = "It's a tie!";
} else {
@@ -173,9 +173,9 @@ var GameEndOverlay = createReactClass({
<View style={styles.overlay}>
<Text style={styles.overlayMessage}>{message}</Text>
<TouchableHighlight
activeOpacity={0.5}
onPress={this.props.onRestart}
underlayColor="transparent"
activeOpacity={0.5}
>
<View style={styles.newGame}>
<Text style={styles.newGameText}>New Game</Text>
@@ -186,9 +186,9 @@ var GameEndOverlay = createReactClass({
}
});
var TicTacToeApp = createReactClass({
const TicTacToeApp = createReactClass({
getInitialState() {
return { board: new Board(), player: 1 };
return { board: new Board(), player: 1 }
},
restartGame() {
@@ -211,14 +211,10 @@ var TicTacToeApp = createReactClass({
},
render() {
var rows = this.state.board.grid.map((cells, row) => (
const rows = this.state.board.grid.map((cells, row) => (
<View key={'row' + row} style={styles.row}>
{cells.map((player, col) => (
<Cell
key={'cell' + col}
player={player}
onPress={this.handleCellPress.bind(this, row, col)}
/>
<Cell key={'cell' + col} onPress={this.handleCellPress.bind(this, row, col)} player={player} />
))}
</View>
));
@@ -235,7 +231,7 @@ var TicTacToeApp = createReactClass({
}
});
var styles = StyleSheet.create({
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',

View File

@@ -1,5 +1,5 @@
import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import { storiesOf } from '@kadira/storybook';
import TicTacToe from './TicTacToe';
storiesOf('demo: TicTacToe', module).add('the game', () => <TicTacToe />);