path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
App.android.js | atesoriero2000/scout-project | /**
* Chatham Township Historical Society's Driving Tour App
* Created by: Anthony Tesoriero
* https://github.com/atesoriero2000
*
* Powered by React Native
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
View,
Text
} from 'react-native';
export default class App extends Component {
constructor(props){
}
render() {
return(
<View>
<Text>Hello World Im Android</Text>
</View>
);
}
}
|
node_modules/_antd@2.13.4@antd/es/card/Grid.js | ligangwolai/blog | import _extends from 'babel-runtime/helpers/extends';
var __rest = this && this.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]];
}return t;
};
import React from 'react';
import classNames from 'classnames';
export default (function (props) {
var _props$prefixCls = props.prefixCls,
prefixCls = _props$prefixCls === undefined ? 'ant-card' : _props$prefixCls,
className = props.className,
others = __rest(props, ["prefixCls", "className"]);
var classString = classNames(prefixCls + '-grid', className);
return React.createElement('div', _extends({}, others, { className: classString }));
}); |
app/client.js | lolicoin/wallet | import React from 'react'
import { render } from 'react-dom'
class App extends React.Component {
render() {
return (
<div>
<nav className='navbar navbar-expand-lg navbar-dark bg-dark'>
<span className='navbar-brand'>LoliCoin wallet =^_^=</span>
</nav>
</div>
)
}
}
render(<App/>, document.getElementById('app'))
|
generators/mobile-app/templates/Component.js | HsuTing/generator-cat | 'use strict';
import React from 'react';
import {StyleSheet, Text, View} from 'react-native';
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
<Text>Changes you make will automatically reload.</Text>
<Text>Shake your phone to open the developer menu.</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
}
});
|
src/svg-icons/maps/directions-walk.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsDirectionsWalk = (props) => (
<SvgIcon {...props}>
<path d="M13.5 5.5c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zM9.8 8.9L7 23h2.1l1.8-8 2.1 2v6h2v-7.5l-2.1-2 .6-3C14.8 12 16.8 13 19 13v-2c-1.9 0-3.5-1-4.3-2.4l-1-1.6c-.4-.6-1-1-1.7-1-.3 0-.5.1-.8.1L6 8.3V13h2V9.6l1.8-.7"/>
</SvgIcon>
);
MapsDirectionsWalk = pure(MapsDirectionsWalk);
MapsDirectionsWalk.displayName = 'MapsDirectionsWalk';
export default MapsDirectionsWalk;
|
client/modules/Post/__tests__/components/PostList.spec.js | Muisti/muisti | import React from 'react';
import test from 'ava';
import sinon from 'sinon';
import { shallow } from 'enzyme';
import PostList from '../../components/PostList';
import { mountWithIntl, shallowWithIntl } from '../../../../util/react-intl-test-helper';
const posts = [
{ name: 'Prashant', cuid: 'f34gb2bh24b24b2', important: false, content: "All cats meow 'mern!'" },
{ name: 'Mayank', cuid: 'f34gb2bh24b24b3', important: false, content: "All dogs bark 'mern!'" },
{ name: 'Kroshant', cuid: 'f34gb2bh24b24b4', important: true, content: "All cows moo 'mern!'" },
];
test('renders the list', t => {
const wrapper = shallowWithIntl(
<PostList posts={posts} handleShowPost={() => {}} handleDeletePost={() => {}}
handleEditPost={() => {}} />
);
t.is(wrapper.find('PostListItem').length, 3);
});
test('calls delete', t => {
const deleteMessage = sinon.spy();
const wrapper = mountWithIntl(
<PostList posts={posts} handleShowPost={() => {}} handleDeletePost={deleteMessage}
handleEditPost={() => {}}/>
);
wrapper.find('a').first().simulate('click');
t.truthy(deleteMessage.calledOnce);
});
test('confirms delete', t => {
const deletePostRequest = sinon.spy();
const wrapper = mountWithIntl(
<PostList posts={posts} handleShowPost={() => {}} handleDeletePost={deletePostRequest}
handleEditPost={() => {}} />
);
wrapper.find('a').first().simulate('click');
const confirmStub = sinon.stub(window, 'confirm');
confirmStub.returns(true);
t.truthy(confirmStub);
t.truthy(deletePostRequest.called);
confirmStub.restore();
});
|
packages/ringcentral-widgets-docs/src/app/pages/Components/LogIcon/Demo.js | ringcentral/ringcentral-js-widget | import React from 'react';
// eslint-disable-next-line
import LogIcon from 'ringcentral-widgets/components/LogIcon';
const props = {};
props.currentLocale = 'en-US';
/**
* A example of `LogIcon`
*/
const LogIconDemo = () => <LogIcon {...props} />;
export default LogIconDemo;
|
src/index.js | kelsonic/Kelsonic | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
client/src/index.js | marcboeren/millionf1 | import React from 'react';
import ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import './index.css';
import App from './App';
const client = new ApolloClient({
link: new HttpLink({ uri: 'http://localhost:3001/graphql' }),
cache: new InMemoryCache()
});
ReactDOM.render(<ApolloProvider client={client}><App /></ApolloProvider>, document.getElementById('root'));
registerServiceWorker();
|
Example/components/TabView.js | gectorat/react-native-router-flux | import React from 'react';
import {PropTypes} from "react";
import {StyleSheet, Text, View} from "react-native";
import Button from 'react-native-button';
import { Actions } from 'react-native-router-flux';
const contextTypes = {
drawer: React.PropTypes.object,
};
const propTypes = {
name: PropTypes.string,
sceneStyle: View.propTypes.style,
title: PropTypes.string,
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
borderWidth: 2,
borderColor: 'red',
},
});
const TabView = (props, context) => {
const drawer = context.drawer;
return (
<View style={[styles.container, props.sceneStyle ]}>
<Text>Tab {props.title}</Text>
{props.name === 'tab1_1' &&
<Button onPress={Actions.tab1_2}>next screen for tab1_1</Button>
}
{props.name === 'tab2_1' &&
<Button onPress={Actions.tab2_2}>next screen for tab2_1</Button>
}
<Button onPress={Actions.pop}>Back</Button>
<Button onPress={() => { drawer.close(); Actions.tab1(); }}>Switch to tab1</Button>
<Button onPress={() => { drawer.close(); Actions.tab2(); }}>Switch to tab2</Button>
<Button onPress={() => { drawer.close(); Actions.tab3(); }}>Switch to tab3</Button>
<Button onPress={() => { drawer.close(); Actions.tab4(); }}>Switch to tab4</Button>
<Button onPress={() => { drawer.close(); Actions.tab5(); }}>Switch to tab5</Button>
<Button onPress={() => { drawer.close(); Actions.echo(); }}>push new scene</Button>
</View>
);
};
TabView.contextTypes = contextTypes;
TabView.propTypes = propTypes;
export default TabView;
|
src/internal/ClearFix.js | skarnecki/material-ui | import React from 'react';
import BeforeAfterWrapper from './BeforeAfterWrapper';
const styles = {
before: {
content: "' '",
display: 'table',
},
after: {
content: "' '",
clear: 'both',
display: 'table',
},
};
const ClearFix = ({style, children, ...other}) => (
<BeforeAfterWrapper
{...other}
beforeStyle={styles.before}
afterStyle={styles.after}
style={style}
>
{children}
</BeforeAfterWrapper>
);
ClearFix.muiName = 'ClearFix';
ClearFix.propTypes = {
children: React.PropTypes.node,
/**
* Override the inline-styles of the root element.
*/
style: React.PropTypes.object,
};
export default ClearFix;
|
_course_exercises/rfe/_bck/src/ReposList.js | David-Castelli/react-testing | import React from 'react';
import {render} from 'react-dom';
import Repo from './Repo';
class ReposList extends React.Component {
constructor(props) {
super(props);
this.state = {
search: '',
repos: props.repos
};
}
updateSearch(event) {
this.setState({search: event.target.value.substr(0, 20)})
}
addRepo(event) {
event.preventDefault();
let name = this.refs.name.value;
let description = this.refs.description.value;
let id = Math.floor((Math.random() * 100) + 1);
this.setState({
repos: this.state.repos.concat({id, name, description})
})
this.refs.name.value = '';
this.refs.description.value = '';
}
render() {
let filteredRepos = this.state.repos.filter(
(repo) => {
return repo.name.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1;
}
);
return (
<div>
<input type="text"
placeholder='Search'
value={this.state.search}
onChange={this.updateSearch.bind(this)}
/>
<div className='repos-list'>
{filteredRepos.map((repo)=> { //
return <Repo repo={repo} key={repo.id}/>
})}
</div>
</div>
)
}
}
export default ReposList; |
src/components/app.js | vanfvl/JabbaTracker | import React from 'react';
import {Route, Match, Redirect} from 'react-router-dom';
import Header from './header';
import Login from '../containers/login';
import TimeSheet from '../containers/timesheet';
import ThemisSheet from '../containers/themissheet';
import Input from '../containers/input';
import AccountsTab from '../containers/AccountsTab';
import Summary from '../containers/summary';
import { isAuthenticated, auth, storageKey } from '../firebase';
export default class App extends React.Component {
state = {
uid: null
};
componentDidMount() {
auth.onAuthStateChanged(user => {
if (user) {
window.localStorage.setItem(storageKey, user.uid);
this.setState({uid: user.uid});
} else {
window.localStorage.removeItem(storageKey);
this.setState({uid: null});
}
});
}
render() {
return (
<div>
<Header />
<Route path="/login" component={Login}/>
<ProtectedRoute path="/" exact={true} component={TimeSheet}/>
<ProtectedRoute path="/themissheet" exact={true} component={ThemisSheet}/>
<ProtectedRoute path="/input" component={Input}/>
<ProtectedRoute path="/accounts" component={AccountsTab}/>
<ProtectedRoute path="/summary" component={Summary}/>
</div>
)
}
}
const ProtectedRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
isAuthenticated() ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
);
|
packages/mineral-ui-icons/src/IconFolder.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconFolder(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/>
</g>
</Icon>
);
}
IconFolder.displayName = 'IconFolder';
IconFolder.category = 'file';
|
app/javascript/mastodon/containers/card_container.js | PlantsNetwork/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import Card from '../features/status/components/card';
import { fromJS } from 'immutable';
export default class CardContainer extends React.PureComponent {
static propTypes = {
locale: PropTypes.string,
card: PropTypes.array.isRequired,
};
render () {
const { card, ...props } = this.props;
return <Card card={fromJS(card)} {...props} />;
}
}
|
src/index.js | setage/react-kinetic-scrolling | import React from 'react'
const TIME_CONSTANT = 325
const WHEEL_SPEED = 50
const BASE_STYLE = {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
overflow: 'hidden',
}
const VIEW_STYLE = {
position: 'absolute',
top: 0,
left: 0,
}
class Scrolling extends React.Component {
constructor(props) {
super(props)
this.state = {
pressed: false,
reference: null,
offset: 0,
min: 0,
max: 0,
dragging: false,
}
this.prev = this.prev.bind(this)
this.next = this.next.bind(this)
this.handleDrag = this.handleDrag.bind(this)
this.handleRelease = this.props.snap ?
this.handleReleaseWithSnap.bind(this) :
this.handleRelease.bind(this)
this.handleResize = this.handleResize.bind(this)
}
componentDidMount() {
this.update()
window.addEventListener('resize', this.handleResize)
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize)
}
setMaxTransform() {
const max = this.props.horizontal ?
this.refs.view.offsetWidth - this.refs.base.offsetWidth :
this.refs.view.offsetHeight - this.refs.base.offsetHeight
this.setState({ max })
}
update() {
this.setMaxTransform()
this.trackPosition()
const boundAutoscroll = this.autoScroll.bind(this)
requestAnimationFrame(boundAutoscroll)
}
pos(e) {
// touch event
const clientPos = this.props.horizontal ? 'clientX' : 'clientY'
if (e.targetTouches && (e.targetTouches.length >= 1)) {
return e.targetTouches[0][clientPos]
}
// mouse event
return e[clientPos]
}
scroll(x) {
const { min, max } = this.state
let offset = (x > max) ? max : null
if (!offset) {
offset = (x < min) ? min : x
}
this.refs.view.style.transform = this.props.horizontal ?
`translateX(${-offset}px)` :
`translateY(${-offset}px)`
this.setState({ offset })
this.trackPosition()
}
track() {
const now = Date.now()
const elapsed = now - this.state.timestamp
this.setState({
timestamp: now,
})
const delta = this.state.offset - this.state.frame
const v = 1000 * delta / (1 + elapsed)
this.setState({
frame: this.state.offset,
velocity: 0.8 * v + 0.2 * this.state.velocity,
})
}
autoScroll() {
let elapsed
let delta
if (this.state.amplitude) {
elapsed = Date.now() - this.state.timestamp
delta = -this.state.amplitude * Math.exp(-elapsed / TIME_CONSTANT)
if (delta > 5 || delta < -5) {
this.scroll(this.state.target + delta)
const boundAutoscroll = this.autoScroll.bind(this)
requestAnimationFrame(boundAutoscroll)
} else {
this.scroll(this.state.target)
}
}
}
// Public methods
scrollToItem(idx) {
if (this.props.snap) {
const target = idx * this.props.snap
const amplitude = target - this.state.offset
// TODO: Find solution for better enabling animation in this method
this.viewStyle = {
...this.viewStyle,
transition: 'transform .3s',
}
this.setState({
target,
amplitude,
timestamp: Date.now(),
})
this.scroll(target)
}
}
prev() {
if (this.props.snap) {
this.scrollToItem(this.current() - 1)
}
}
next() {
if (this.props.snap) {
this.scrollToItem(this.current() + 1)
}
}
current() {
let current
if (this.state.offset === 0) {
current = 0
} else {
current = Math.round(this.state.offset / this.props.snap)
}
return current
}
atBegin() {
return this.state.offset === 0
}
atEnd() {
return this.state.offset === this.state.max
}
// Events handlers
handleTap(e) {
this.setState({
pressed: true,
reference: this.pos(e),
velocity: 0,
amplitude: 0,
timestamp: Date.now(),
frame: this.state.offset,
})
clearInterval(this.ticker)
const boundTrack = this.track.bind(this)
this.ticker = setInterval(boundTrack, 100)
this.trackPosition()
window.addEventListener('mousemove', this.handleDrag)
window.addEventListener('mouseup', this.handleRelease)
e.preventDefault()
e.stopPropagation()
return false
}
handleDrag(e) {
let x
let delta
if (this.state.pressed) {
x = this.pos(e)
delta = this.state.reference - x
if (delta > 2 || delta < -2) {
this.setState({
reference: x,
dragging: true,
})
this.scroll(this.state.offset + delta)
this.viewStyle = {
...this.viewStyle,
transition: 'none',
}
}
}
e.preventDefault()
e.stopPropagation()
return false
}
handleRelease(e) {
this.setState({
pressed: false,
})
clearInterval(this.ticker)
if (this.state.velocity > 10 || this.state.velocity < -10) {
const amplitude = 0.8 * this.state.velocity
const target = Math.round(this.state.offset + amplitude)
this.setState({
target,
amplitude,
timestamp: Date.now(),
})
const boundAutoscroll = this.autoScroll.bind(this)
requestAnimationFrame(boundAutoscroll)
}
window.removeEventListener('mousemove', this.handleDrag)
window.removeEventListener('mouseup', this.handleRelease)
e.preventDefault()
e.stopPropagation()
return false
}
handleReleaseWithSnap(e) {
this.setState({
pressed: false,
})
clearInterval(this.ticker)
let amplitude
let target = this.state.offset
if (this.state.velocity > 10 || this.state.velocity < -10) {
amplitude = 0.8 * this.state.velocity
target = Math.round(this.state.offset + amplitude)
}
target = Math.round(target / this.props.snap) * this.props.snap
amplitude = target - this.state.offset
this.setState({
target,
amplitude,
timestamp: Date.now(),
})
const boundAutoscroll = this.autoScroll.bind(this)
requestAnimationFrame(boundAutoscroll)
window.removeEventListener('mousemove', this.handleDrag)
window.removeEventListener('mouseup', this.handleRelease)
if (e.currentTarget.getAttribute('id') !== this.refs.view.id) {
this.setState({
dragging: false,
})
}
}
handleWheel(e) {
this.viewStyle = {
...this.viewStyle,
transition: 'none',
}
let target = this.state.offset + e.deltaY * WHEEL_SPEED
if (this.props.snap) {
target = Math.round(target / this.props.snap) * this.props.snap
}
const amplitude = target - this.state.offset
this.setState({
target,
amplitude,
timestamp: Date.now(),
})
const boundAutoscroll = this.autoScroll.bind(this)
requestAnimationFrame(boundAutoscroll)
e.preventDefault()
e.stopPropagation()
return false
}
handleClick() {
this.setState({
dragging: false,
})
}
handleResize() {
this.update()
this.forceUpdate()
}
// Callback returning Kinetic-scroller state
trackPosition() {
if (this.props.trackPosition) {
this.props.trackPosition({
atBegin: this.atBegin(),
atEnd: this.atEnd(),
dragging: this.state.dragging,
})
}
}
render() {
const tapHandler = this.handleTap.bind(this)
const wheelHandler = this.handleWheel.bind(this)
const clickHandler = this.handleClick.bind(this)
let viewStyle = { ...VIEW_STYLE, ...this.viewStyle }
if (this.props.horizontal) {
viewStyle = {
...viewStyle,
whiteSpace: 'nowrap',
}
}
return (
<div style={BASE_STYLE} className={this.props.className} ref="base">
<div
style={viewStyle}
ref="view"
id="js-view"
onMouseDown={tapHandler}
onMouseUp={this.handleRelease}
onClick={clickHandler}
onWheel={wheelHandler}
>
{this.props.children}
</div>
</div>
)
}
}
Scrolling.propTypes = {
children: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.string,
]).isRequired,
className: React.PropTypes.string,
horizontal: React.PropTypes.bool,
snap: React.PropTypes.number,
trackPosition: React.PropTypes.func,
}
export default Scrolling
|
src/media/js/addon/containers/reviewDetail.js | diox/marketplace-content-tools | /*
Single review page for an add-on.
Lists the add-on's versions, each with their own approve and reject buttons.
*/
import React from 'react';
import {connect} from 'react-redux';
import {reverse, ReverseLink} from 'react-router-reverse';
import {bindActionCreators} from 'redux';
import AddonVersionListingContainer from './versionListing';
import {block as blockAddon, fetch as fetchAddon,
unblock as unblockAddon} from '../actions/addon';
import {getInstalled as getInstalledAddons,
install as installAddon} from '../actions/mozApps';
import {AddonForReviewDetail, AddonIcon} from '../components/addon';
import * as constants from '../constants';
import AddonInstall from '../components/install';
import AddonSubnav from '../components/subnav';
import {checkPermissions} from '../../site/login';
import {fxaLoginBegin, login} from '../../site/actions/login';
import ConfirmButton from '../../site/components/confirmButton';
import {LoginButton} from '../../site/components/login';
import {Page, PageSection} from '../../site/components/page';
export class AddonReviewDetail extends React.Component {
static propTypes = {
addon: React.PropTypes.object,
blockAddon: React.PropTypes.func,
checkSession: React.PropTypes.func.isRequired,
fetchAddon: React.PropTypes.func.isRequired,
fxaLoginBegin: React.PropTypes.func,
getInstalledAddons: React.PropTypes.func.isRequired,
hasSession: React.PropTypes.bool,
installAddon: React.PropTypes.func.isRequired,
login: React.PropTypes.func,
siteConfig: React.PropTypes.object,
slug: React.PropTypes.string.isRequired,
unblockAddon: React.PropTypes.func,
user: React.PropTypes.object,
};
constructor(props) {
super(props);
this.props.fetchAddon(this.props.slug);
this.props.getInstalledAddons();
}
blockAddon = () => {
this.props.blockAddon(this.props.addon.slug);
}
loginHandler = authCode => {
// Call login, passing in some extra stuff from siteConfig.
this.props.login(authCode, this.props.siteConfig.authState,
this.props.siteConfig.clientId);
}
unblockAddon = () => {
this.props.unblockAddon(this.props.addon.slug);
}
render() {
const addon = this.props.addon;
if (!addon || !addon.slug) {
return (
<Page subnav={<AddonSubnav user={this.props.user}/>}
title="Loading Firefox OS Add-on..."/>
);
}
const title = (
<div className="addon-page-title">
<AddonIcon icons={addon.icons}/>
{`Reviewing Firefox OS Add-on: ${addon.name}`}
</div>
);
const isBlocked = addon.status === constants.STATUS_BLOCKED;
return (
<Page breadcrumbText="Review Add-ons"
breadcrumbTo="addon-review"
className="addon-review-detail"
title={title}
subnav={<AddonSubnav user={this.props.user}/>}>
{!this.props.hasSession &&
<PageSection title="Log in Again">
<p className="form-msg--error">
Your cookie-based login session with the server has expired.
</p>
<p>
You will need to log in again in order to download or install
add-ons as a reviewer.
</p>
<LoginButton authUrl={this.props.siteConfig.authUrl}
loginBeginHandler={this.props.fxaLoginBegin}
loginHandler={this.loginHandler}/>
</PageSection>
}
<AddonForReviewDetail {...addon}/>
{addon.latest_version &&
<PageSection title="Install Add-on">
<AddonInstall
install={this.props.installAddon}
installErrorMessage={addon.installErrorMessage}
isInstalled={addon.isInstalled}
isInstalling={addon.isInstalling}
manifestUrl={addon.latest_version.reviewer_mini_manifest_url}
slug={addon.slug}/>
</PageSection>
}
<AddonVersionListingContainer className="addon-review-detail-versions"
showReviewActions={true}/>
{checkPermissions(this.props.user, 'admin') &&
<PageSection title={isBlocked ? 'Unblock Add-on' : 'Block Add-on'}>
{isBlocked ?
<p>
This will unblock the add-on. Unblocking will make the add-on
public to users and modifiable to the developer.
</p> :
<p>
This will block the add-on. Blocking will make the add-on
non-public to users and unmodifiable to the developer.
</p>
}
<ConfirmButton
className="button--assertive"
initialText={isBlocked ? 'Unblock add-on' : 'Block add-on'}
isProcessing={addon.isChangingBlockStatus}
onClick={isBlocked ? this.unblockAddon :
this.blockAddon}
processingText={isBlocked ? 'Unblocking add-on...' :
'Blocking add-on...'}
/>
</PageSection>
}
</Page>
);
}
};
export default connect(
state => ({
addon: state.addon.addons[state.router.params.slug],
hasSession: state.user.hasSession,
siteConfig: state.siteConfig,
slug: state.router.params.slug,
user: state.user,
}),
dispatch => bindActionCreators({
blockAddon,
fetchAddon,
fxaLoginBegin,
getInstalledAddons,
installAddon,
login,
unblockAddon,
}, dispatch)
)(AddonReviewDetail);
|
app/components/agents/randomAgents.js | nypl-registry/browse | import React from 'react'
import RandomRecords from '../shared/randomRecords.js'
const RandomAgents = React.createClass({
render () {
return <RandomRecords recordType='agent' records={this.props.agents} onFetch={this.props.onFetch} />
}
})
export default RandomAgents
|
src/components/common/sticky/Sticky.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import ReactDOM from 'react-dom';
export default class Sticky extends React.Component {
static propTypes = {
isActive: React.PropTypes.bool,
className: React.PropTypes.string,
style: React.PropTypes.object,
stickyClassName: React.PropTypes.string,
stickyStyle: React.PropTypes.object,
topOffset: React.PropTypes.number,
bottomOffset: React.PropTypes.number,
onStickyStateChange: React.PropTypes.func
}
static defaultProps = {
isActive: true,
className: '',
style: {},
stickyClassName: 'sticky',
stickyStyle: {},
topOffset: 0,
bottomOffset: 0,
onStickyStateChange: () => {}
}
static contextTypes = {
'sticky-channel': React.PropTypes.any
}
constructor(props) {
super(props);
this.state = {};
}
componentWillMount() {
this.channel = this.context['sticky-channel'];
this.channel.subscribe(this.updateContext);
}
componentDidMount() {
this.on(['resize', 'scroll', 'touchstart', 'touchmove', 'touchend', 'pageshow', 'load'], this.recomputeState);
this.recomputeState();
}
componentWillReceiveProps() {
this.recomputeState();
}
componentWillUnmount() {
this.off(['resize', 'scroll', 'touchstart', 'touchmove', 'touchend', 'pageshow', 'load'], this.recomputeState);
this.channel.unsubscribe(this.updateContext);
}
getXOffset() {
return this.refs.placeholder.getBoundingClientRect().left;
}
getWidth() {
return this.refs.placeholder.getBoundingClientRect().width;
}
getHeight() {
return ReactDOM.findDOMNode(this.refs.children).getBoundingClientRect().height;
}
getDistanceFromTop() {
return this.refs.placeholder.getBoundingClientRect().top;
}
getDistanceFromBottom() {
if (!this.containerNode) return 0;
return this.containerNode.getBoundingClientRect().bottom;
}
isSticky() {
if (!this.props.isActive) return false;
const fromTop = this.getDistanceFromTop();
const fromBottom = this.getDistanceFromBottom();
const topBreakpoint = this.state.containerOffset - this.props.topOffset;
const bottomBreakpoint = this.state.containerOffset + this.props.bottomOffset;
return fromTop <= topBreakpoint && fromBottom >= bottomBreakpoint;
}
updateContext = ({ inherited, node }) => {
this.containerNode = node;
this.setState({
containerOffset: inherited,
distanceFromBottom: this.getDistanceFromBottom()
});
}
recomputeState = () => {
const isSticky = this.isSticky();
const height = this.getHeight();
const width = this.getWidth();
const xOffset = this.getXOffset();
const distanceFromBottom = this.getDistanceFromBottom();
const hasChanged = this.state.isSticky !== isSticky;
this.setState({ isSticky, height, width, xOffset, distanceFromBottom });
if (hasChanged) {
if (this.channel) {
this.channel.update((data) => {
data.offset = (isSticky ? this.state.height : 0);
});
}
this.props.onStickyStateChange(isSticky);
}
}
on(events, callback) {
events.forEach((evt) => {
window.addEventListener(evt, callback);
});
}
off(events, callback) {
events.forEach((evt) => {
window.removeEventListener(evt, callback);
});
}
shouldComponentUpdate(newProps, newState) {
// Have we changed the number of props?
const propNames = Object.keys(this.props);
if (Object.keys(newProps).length != propNames.length) return true;
// Have we changed any prop values?
const valuesMatch = propNames.every((key) => {
return newProps.hasOwnProperty(key) && newProps[key] === this.props[key];
});
if (!valuesMatch) return true;
// Have we changed any state that will always impact rendering?
const state = this.state;
if (newState.isSticky !== state.isSticky) return true;
// If we are sticky, have we changed any state that will impact rendering?
if (state.isSticky) {
if (newState.height !== state.height) return true;
if (newState.width !== state.width) return true;
if (newState.xOffset !== state.xOffset) return true;
if (newState.containerOffset !== state.containerOffset) return true;
if (newState.distanceFromBottom !== state.distanceFromBottom) return true;
}
return false;
}
/*
* The special sauce.
*/
render() {
const placeholderStyle = { paddingBottom: 0 };
let className = this.props.className;
// To ensure that this component becomes sticky immediately on mobile devices instead
// of disappearing until the scroll event completes, we add `transform: translateZ(0)`
// to 'kick' rendering of this element to the GPU
// @see http://stackoverflow.com/questions/32875046
let style = Object.assign({}, { transform: 'translateZ(0)' }, this.props.style);
if (this.state.isSticky) {
const stickyStyle = {
position: 'fixed',
top: this.state.containerOffset,
left: this.state.xOffset,
width: this.state.width
};
const bottomLimit = this.state.distanceFromBottom - this.state.height - this.props.bottomOffset;
if (this.state.containerOffset > bottomLimit) {
stickyStyle.top = bottomLimit;
}
placeholderStyle.paddingBottom = this.state.height;
className += ` ${this.props.stickyClassName}`;
style = Object.assign({}, style, stickyStyle, this.props.stickyStyle);
}
const {
topOffset,
isActive,
stickyClassName,
stickyStyle,
bottomOffset,
onStickyStateChange,
...props
} = this.props;
return (
<div>
<div ref="placeholder" style={placeholderStyle}></div>
<div {...props} ref="children" className={className} style={style}>
{this.props.children}
</div>
</div>
);
}
}
|
test/helpers/shallowRenderHelper.js | sumoli/gallery-by-react | /**
* Function to get the shallow output for a given component
* As we are using phantom.js, we also need to include the fn.proto.bind shim!
*
* @see http://simonsmith.io/unit-testing-react-components-without-a-dom/
* @author somonsmith
*/
import React from 'react';
import TestUtils from 'react-addons-test-utils';
/**
* Get the shallow rendered component
*
* @param {Object} component The component to return the output for
* @param {Object} props [optional] The components properties
* @param {Mixed} ...children [optional] List of children
* @return {Object} Shallow rendered output
*/
export default function createComponent(component, props = {}, ...children) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]));
return shallowRenderer.getRenderOutput();
}
|
website-prototyping-tools/RelayPlayground.js | Shopify/relay | /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/* eslint-disable no-unused-vars, no-eval */
import './RelayPlayground.css';
import 'codemirror/mode/javascript/javascript';
import Codemirror from 'react-codemirror';
import React from 'react';
import ReactDOM from 'react/lib/ReactDOM';
import Relay from 'react-relay'; window.Relay = Relay;
import RelayLocalSchema from 'relay-local-schema';
import babel from 'babel-core/browser';
import babelRelayPlaygroundPlugin from './babelRelayPlaygroundPlugin';
import debounce from 'lodash.debounce';
import defer from 'lodash.defer';
import errorCatcher from 'babel-plugin-react-error-catcher/error-catcher';
import errorCatcherPlugin from 'babel-plugin-react-error-catcher';
import evalSchema from './evalSchema';
import getBabelRelayPlugin from 'babel-relay-plugin';
import {introspectionQuery} from 'graphql/utilities';
import {graphql} from 'graphql';
var {PropTypes} = React;
const CODE_EDITOR_OPTIONS = {
extraKeys: {
Tab(cm) {
// Insert spaces when the tab key is pressed
var spaces = Array(cm.getOption('indentUnit') + 1).join(' ');
cm.replaceSelection(spaces);
},
},
indentWithTabs: false,
lineNumbers: true,
mode: 'javascript',
tabSize: 2,
theme: 'solarized light',
};
const ERROR_TYPES = {
graphql: 'GraphQL Validation',
query: 'Query',
runtime: 'Runtime',
schema: 'Schema',
syntax: 'Syntax',
};
const RENDER_STEP_EXAMPLE_CODE =
`ReactDOM.render(
<Relay.RootContainer
Component={MyRelayContainer}
route={new MyHomeRoute()}
/>,
mountNode
);`;
function errorFromGraphQLResultAndQuery(errors, request) {
var queryString = request.getQueryString();
var variables = request.getVariables();
var errorText = `
${errors.map(e => e.message).join('\n')}
Query: ${queryString}
`;
if (variables) {
errorText += `Variables: ${JSON.stringify(variables)}`;
}
return {stack: errorText.trim()};
}
class PlaygroundRenderer extends React.Component {
componentDidMount() {
this._container = document.createElement('div');
this.refs.mountPoint.appendChild(this._container);
this._updateTimeoutId = defer(this._update);
}
componentDidUpdate(prevProps) {
if (this._updateTimeoutId != null) {
clearTimeout(this._updateTimeoutId);
}
this._updateTimeoutId = defer(this._update);
}
componentWillUnmount() {
if (this._updateTimeoutId != null) {
clearTimeout(this._updateTimeoutId);
}
try {
ReactDOM.unmountComponentAtNode(this._container);
} catch (e) {}
}
_update = () => {
ReactDOM.render(React.Children.only(this.props.children), this._container);
}
render() {
return <div ref="mountPoint" />;
}
}
export default class RelayPlayground extends React.Component {
static defaultProps = {
autoExecute: false,
};
static propTypes = {
autoExecute: PropTypes.bool.isRequired,
initialAppSource: PropTypes.string,
initialSchemaSource: PropTypes.string,
onAppSourceChange: PropTypes.func,
onSchemaSourceChange: PropTypes.func,
};
state = {
appElement: null,
appSource: this.props.initialAppSource,
busy: false,
editTarget: 'app',
error: null,
schemaSource: this.props.initialSchemaSource,
shouldExecuteCode: this.props.autoExecute,
};
componentDidMount() {
// Hijack console.warn to collect GraphQL validation warnings (we hope)
this._originalConsoleWarn = console.warn;
var collectedWarnings = [];
console.warn = (...args) => {
collectedWarnings.push([Date.now(), args]);
this._originalConsoleWarn.apply(console, args);
};
// Hijack window.onerror to catch any stray fatals
this._originalWindowOnerror = window.onerror;
window.onerror = (message, url, lineNumber, something, error) => {
// GraphQL validation warnings are followed closely by a thrown exception.
// Console warnings that appear too far before this exception are probably
// not related to GraphQL. Throw those out.
if (/GraphQL validation error/.test(message)) {
var recentWarnings = collectedWarnings
.filter(([createdAt, args]) => Date.now() - createdAt <= 500)
.reduce((memo, [createdAt, args]) => memo.concat(args), []);
this.setState({
error: {stack: recentWarnings.join('\n')},
errorType: ERROR_TYPES.graphql,
});
} else {
this.setState({error, errorType: ERROR_TYPES.runtime});
}
collectedWarnings = [];
return false;
};
if (this.state.shouldExecuteCode) {
this._updateSchema(this.state.schemaSource, this.state.appSource);
}
}
componentDidUpdate(prevProps, prevState) {
var recentlyEnabledCodeExecution =
!prevState.shouldExecuteCode && this.state.shouldExecuteCode;
var appChanged = this.state.appSource !== prevState.appSource;
var schemaChanged = this.state.schemaSource !== prevState.schemaSource;
if (
this.state.shouldExecuteCode &&
(recentlyEnabledCodeExecution || appChanged || schemaChanged)
) {
this.setState({busy: true});
this._handleSourceCodeChange(
this.state.appSource,
recentlyEnabledCodeExecution || schemaChanged
? this.state.schemaSource
: null,
);
}
}
componentWillUnmount() {
clearTimeout(this._errorReporterTimeout);
clearTimeout(this._warningScrubberTimeout);
this._handleSourceCodeChange.cancel();
console.warn = this._originalConsoleWarn;
window.onerror = this._originalWindowOnerror;
}
_handleExecuteClick = () => {
this.setState({shouldExecuteCode: true});
}
_handleSourceCodeChange = debounce((appSource, schemaSource) => {
if (schemaSource != null) {
this._updateSchema(schemaSource, appSource);
} else {
this._updateApp(appSource);
}
}, 300, {trailing: true})
_updateApp = (appSource) => {
clearTimeout(this._errorReporterTimeout);
// We're running in a browser. Create a require() shim to catch any imports.
var require = (path) => {
switch (path) {
// The errorCatcherPlugin injects a series of import statements into the
// program body. Return locally bound variables in these three cases:
case '//error-catcher.js':
return (React, filename, displayName, reporter) => {
// When it fatals, render an empty <span /> in place of the app.
return errorCatcher(React, filename, <span />, reporter);
};
case 'react':
return React;
case 'reporterProxy':
return (error, instance, filename, displayName) => {
this._errorReporterTimeout = defer(
this.setState.bind(this),
{error, errorType: ERROR_TYPES.runtime}
);
};
default: throw new Error(`Cannot find module "${path}"`);
}
};
try {
var {code} = babel.transform(appSource, {
filename: 'RelayPlayground',
plugins : [
babelRelayPlaygroundPlugin,
this._babelRelayPlugin,
errorCatcherPlugin('reporterProxy'),
],
retainLines: true,
sourceMaps: 'inline',
stage: 0,
});
var result = eval(code);
if (
React.isValidElement(result) &&
result.type.name === 'RelayRootContainer'
) {
this.setState({
appElement: React.cloneElement(result, {forceFetch: true}),
});
} else {
this.setState({
appElement: (
<div>
<h2>
Render a Relay.RootContainer into <code>mountNode</code> to get
started.
</h2>
<p>
Example:
</p>
<pre>{RENDER_STEP_EXAMPLE_CODE}</pre>
</div>
),
});
}
this.setState({error: null});
} catch (error) {
this.setState({error, errorType: ERROR_TYPES.syntax});
}
this.setState({busy: false});
}
_updateCode = (newSource) => {
var sourceStorageKey = `${this.state.editTarget}Source`;
this.setState({[sourceStorageKey]: newSource});
if (this.state.editTarget === 'app' && this.props.onAppSourceChange) {
this.props.onAppSourceChange(newSource);
}
if (this.state.editTarget === 'schema' && this.props.onSchemaSourceChange) {
this.props.onSchemaSourceChange(newSource);
}
}
_updateEditTarget = (editTarget) => {
this.setState({editTarget});
}
_updateSchema = (schemaSource, appSource) => {
try {
var Schema = evalSchema(schemaSource);
} catch (error) {
this.setState({error, errorType: ERROR_TYPES.schema});
return;
}
graphql(Schema, introspectionQuery).then((result) => {
if (
this.state.schemaSource !== schemaSource ||
this.state.appSource !== appSource
) {
// This version of the code is stale. Bail out.
return;
}
this._babelRelayPlugin = getBabelRelayPlugin(result.data);
Relay.injectNetworkLayer(
new RelayLocalSchema.NetworkLayer({
schema: Schema,
onError: (errors, request) => {
this.setState({
error: errorFromGraphQLResultAndQuery(errors, request),
errorType: ERROR_TYPES.query,
});
},
})
);
this._updateApp(appSource);
});
}
renderApp() {
if (!this.state.shouldExecuteCode) {
return (
<div className="rpExecutionGuard">
<div className="rpExecutionGuardMessage">
<h2>For your security, this playground did not auto-execute</h2>
<p>
Clicking <strong>execute</strong> will run the code in the two
tabs to the left.
</p>
<button onClick={this._handleExecuteClick}>Execute</button>
</div>
</div>
);
} else if (this.state.error) {
return (
<div className="rpError">
<h1>{this.state.errorType} Error</h1>
<pre className="rpErrorStack">{this.state.error.stack}</pre>
</div>
);
} else if (this.state.appElement) {
return <PlaygroundRenderer>{this.state.appElement}</PlaygroundRenderer>;
}
return null;
}
render() {
var sourceCode = this.state.editTarget === 'schema'
? this.state.schemaSource
: this.state.appSource;
return (
<div className="rpShell">
<section className="rpCodeEditor">
<nav className="rpCodeEditorNav">
<button
className={this.state.editTarget === 'app' && 'rpButtonActive'}
onClick={this._updateEditTarget.bind(this, 'app')}>
Code
</button>
<button
className={this.state.editTarget === 'schema' && 'rpButtonActive'}
onClick={this._updateEditTarget.bind(this, 'schema')}>
Schema
</button>
</nav>
{/* What is going on with the choice of key in Codemirror?
* https://github.com/JedWatson/react-codemirror/issues/12
*/}
<Codemirror
key={`${this.state.editTarget}-${this.state.shouldExecuteCode}`}
onChange={this._updateCode}
options={{
...CODE_EDITOR_OPTIONS,
readOnly: !this.state.shouldExecuteCode,
}}
value={sourceCode}
/>
</section>
<section className="rpResult">
<h1 className="rpResultHeader">
Relay Playground
<span className={
'rpActivity' + (this.state.busy ? ' rpActivityBusy' : '')
} />
</h1>
<div className="rpResultOutput">
{this.renderApp()}
</div>
</section>
</div>
);
}
}
|
counter-redux/client/js/index.js | synasius/playground-react | import React from 'react';
import ReactDOM from 'react-dom';
import actions from './components/actions.js';
import manager from './components/store.js';
import Counter from './components/counter.js';
import '../sass/main.scss';
const root = document.querySelector('.container');
manager.initStore();
const store = manager.getStore();
const render = () => {
ReactDOM.render(
<Counter
counter={store.getState()}
onIncrement={actions.onIncrement}
onDecrement={actions.onDecrement} />,
root
);
}
store.subscribe(render);
render();
|
src/svg-icons/editor/format-align-right.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatAlignRight = (props) => (
<SvgIcon {...props}>
<path d="M3 21h18v-2H3v2zm6-4h12v-2H9v2zm-6-4h18v-2H3v2zm6-4h12V7H9v2zM3 3v2h18V3H3z"/>
</SvgIcon>
);
EditorFormatAlignRight = pure(EditorFormatAlignRight);
EditorFormatAlignRight.displayName = 'EditorFormatAlignRight';
EditorFormatAlignRight.muiName = 'SvgIcon';
export default EditorFormatAlignRight;
|
blueprints/form/files/__root__/forms/__name__Form/__name__Form.js | mklinga/potatoro | import React from 'react'
import { reduxForm } from 'redux-form'
export const fields = []
const validate = (values) => {
const errors = {}
return errors
}
type Props = {
handleSubmit: Function,
fields: Object,
}
export class <%= pascalEntityName %> extends React.Component {
props: Props;
defaultProps = {
fields: {},
}
render() {
const { fields, handleSubmit } = this.props
return (
<form onSubmit={handleSubmit}>
</form>
)
}
}
<%= pascalEntityName %> = reduxForm({
form: '<%= pascalEntityName %>',
fields,
validate
})(<%= pascalEntityName %>)
export default <%= pascalEntityName %>
|
packages/@vega/feature-checklist/src/ChecklistFullView.js | VegaPublish/vega-studio | // @flow
import React from 'react'
import {distanceInWordsToNow} from 'date-fns'
import {get} from 'lodash'
import Checkbox from 'part:@lyra/components/toggles/checkbox'
import lyraClient from 'part:@lyra/base/client'
import {of as observableOf, combineLatest} from 'rxjs'
import {switchMap, map} from 'rxjs/operators'
import withPropsStream from '@vega/utils/withPropsStream'
import {currentUser$} from 'part:@vega/datastores/user'
import styles from './styles/ChecklistFullView.css'
import {PatchEvent, patches} from 'part:@lyra/form-builder'
const {setIfMissing, insert, unset} = patches
import type {ChecklistFeatureConfig, ChecklistFeatureState} from './types'
type VegaUser = {
_id: string,
_type: 'user',
name: string,
email: string,
externalId: string,
externalProfileImageUrl?: string,
profileImage?: {
asset: {
url: string
}
}
}
type InputProps = {
onChange: PatchEvent => void,
featureConfig: ChecklistFeatureConfig,
featureState: ?ChecklistFeatureState,
user: VegaUser,
itemCompleters: Array<*>,
type: Object
}
type OutputProps = InputProps & {
user: VegaUser,
itemCompleters: VegaUser[]
}
function loadProps(props$) {
return props$.pipe(
switchMap((props: InputProps) => {
const items = (props.featureState || {}).items
const userIds = items
? items.map(item => (item.completedBy || {})._ref).filter(Boolean)
: null
const completers$ = userIds
? lyraClient.observable.fetch(
`*[_type == "user" && _id in ["${userIds.join('","')}"]]{_id,name}`
)
: observableOf([])
return combineLatest([currentUser$, completers$]).pipe(
map(([user, itemCompleters]) => ({...props, user, itemCompleters}))
)
})
)
}
export default withPropsStream(
loadProps,
class ChecklistFullView extends React.Component<OutputProps> {
handleCheck = checklistItem => {
const {name} = checklistItem
const {onChange, user} = this.props
const now = new Date()
const item = {
_type: 'checklistItemResult',
_key: name,
completedItemName: name,
completedAt: now.toISOString(),
completedBy: {
_type: 'reference',
_ref: user._id
}
}
onChange(
PatchEvent.from(
setIfMissing([], ['items']),
insert([item], 'after', ['items', -1])
)
)
}
handleUncheck = checklistItem => {
const {name} = checklistItem
const {onChange} = this.props
onChange(PatchEvent.from(unset(['items', {_key: name}])))
}
handleCheckboxChange = (event, checklistItem, checked) => {
return checked
? this.handleUncheck(checklistItem)
: this.handleCheck(checklistItem)
}
getCompleter = (checklistItem, checkedStateItem) => {
const {itemCompleters} = this.props
if (
checkedStateItem &&
checkedStateItem &&
checkedStateItem.completedBy &&
itemCompleters
) {
const completer = itemCompleters.find(user => {
return user._id === get(checkedStateItem, 'completedBy._ref')
})
return completer
}
return null
}
render() {
const {featureConfig, featureState, user} = this.props
const configuredItems = featureConfig.items || []
if (!user) {
return <div>Loading...</div>
}
return (
<div className={styles.root}>
<ul className={styles.list}>
{configuredItems.map(checklistItem => {
const checkedStateItem =
featureState && featureState.items
? featureState.items.find(
stateItem =>
checklistItem.name === stateItem.completedItemName
)
: null
const checked = !!checkedStateItem
const completer = this.getCompleter(
checklistItem,
checkedStateItem
)
const onCheckboxChange = event => {
this.handleCheckboxChange(event, checklistItem, checked)
}
return (
<li className={styles.item} key={checklistItem.name}>
<Checkbox
name={checklistItem.name}
checked={checked}
onChange={onCheckboxChange}
label={checklistItem.title}
description={
completer &&
`
Completed by ${completer.name}
${distanceInWordsToNow(
new Date(get(checkedStateItem, 'completedAt'))
)}
`
}
/>
</li>
)
})}
</ul>
</div>
)
}
}
)
|
packages/base-shell/src/providers/Online/Context.js | TarikHuber/react-most-wanted | import React from 'react'
export const Context = React.createContext(null)
export default Context
|
src/sheetElems/comment/api.js | lukaszmakuch/quiz | import React from 'react';
import hash from 'hash.js';
const makePreview = comment => (
<div
key={comment.value + comment.index}
style={{
color: '#ddd',
margin: '20px'
}}
className="comment-preview"
>
{comment.value}
</div>
);
export default {
id: comment => ({
...comment,
id: hash.sha256().update(JSON.stringify(comment)).digest('hex')
}),
asText: comment => comment.value + "\n",
makePreview
} |
src/components/Footer/SetButton/index.js | nobus/weaver | import React, { Component } from 'react';
import { Modal, Grid, Row, Col, Button, FormControl, Glyphicon } from 'react-bootstrap';
class SetButton extends Component {
constructor() {
super();
this.state = {showModal: false};
this.handleClick = this.handleClick.bind(this);
this.saveChanges = this.saveChanges.bind(this);
this.close = this.close.bind(this);
}
initialLocalState() {
const {settingsState} = this.props;
this.state = {
showModal: false,
ro: settingsState.ro,
ry: settingsState.ry,
threadingSize: settingsState.threadingSize,
treadlingSize: settingsState.treadlingSize,
elementSize: settingsState.elementSize
};
}
render() {
return (
<div>
<Button onClick={this.handleClick}>
<Glyphicon glyph='cog' />
</Button>
<Modal show={this.state.showModal} onHide={this.close}>
<Modal.Header>
<Modal.Title>Settings</Modal.Title>
</Modal.Header>
<Modal.Body>
<Grid>
<Row>
<Col md={2}>Ro</Col>
<Col md={1}>
<FormControl
type='text'
value={this.state.ro}
onChange={(e) => {this.setState({ro: e.target.value})}} />
</Col>
<Col md={2}>Ry</Col>
<Col md={1}>
<FormControl
type='text'
value={this.state.ry}
onChange={(e) => {this.setState({ry: e.target.value})}} />
</Col>
</Row>
<Row>
<Col md={2}>Threading size</Col>
<Col md={1}>
<FormControl
type='text'
value={this.state.threadingSize}
onChange={(e) => {this.setState({threadingSize: e.target.value})}} />
</Col>
<Col md={2}>Treadling size</Col>
<Col md={1}>
<FormControl
type='text'
value={this.state.treadlingSize}
onChange={(e) => {this.setState({treadlingSize: e.target.value})}} />
</Col>
</Row>
<Row>
<Col md={2}>Element size</Col>
<Col md={1}>
<FormControl
type='text'
value={this.state.elementSize}
onChange={(e) => {this.setState({elementSize: e.target.value})}} />
</Col>
<Col md={2} />
<Col md={1} />
</Row>
</Grid>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.close}>Close</Button>
<Button
bsStyle="primary"
onClick={this.saveChanges}>
Save changes
</Button>
</Modal.Footer>
</Modal>
</div>
);
}
handleClick(e) {
this.initialLocalState();
this.setState({ showModal: true });
}
close() {
this.setState({ showModal: false });
this.initialLocalState();
}
saveChanges() {
this.setState({ showModal: false });
this.props.saveSettings({
ro: this.state.ro,
ry: this.state.ry,
threadingSize: this.state.threadingSize,
treadlingSize: this.state.treadlingSize,
elementSize: this.state.elementSize
});
}
}
export default SetButton;
|
src/stories/index.js | zillding/react-console | import React from 'react'
import { storiesOf, action } from '@kadira/storybook'
import Console from '../index'
storiesOf('React Console', module)
.add('default view', () => (
<Console/>
))
.add('not load fontawesome', () => (
<Console noFontawesome={true} />
))
.add('custom styles', () => {
const style = {
backgroundColor: 'yellow',
width: 500,
height: 300,
}
return (
<Console style={style} />
)
})
|
src/components/header/index.js | neekey/daigou | import React from 'react';
import { Link } from 'react-router';
import style from './header.scss';
import pagesLink from './header.json';
import classnames from 'classnames';
export default class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false,
};
this.toggleMenuOpen = this.toggleMenuOpen.bind(this);
this.handleContainerClick = this.handleContainerClick.bind(this);
this.handleItemClick = this.handleItemClick.bind(this);
}
scrollToTop() {
document.body.scrollTop = 0;
}
toggleMenuOpen() {
this.setState({
open: !this.state.open,
});
}
handleItemClick() {
this.scrollToTop();
this.toggleMenuOpen();
}
handleContainerClick(event) {
if (event.target === event.currentTarget) {
this.toggleMenuOpen();
}
}
render() {
return (<div
onClick={this.handleContainerClick}
className={this.state.open ? style.containerOpen : style.container}>
<div className={style.header}>
<i
className={classnames(
style.headerIcon,
this.state.open ? 'fa fa-close' : 'fa fa-bars')}
onClick={this.toggleMenuOpen} />
<span className={style.headerTitle}>Neekey 澳洲直邮代购</span>
</div>
<div className={style.menu}>
{pagesLink.map((item, index) => (<Link
key={item.name}
className={style.menuItem}
activeClassName={style.menuItemActive}
to={item.path ? item.path : `/list/${index}`}
onClick={this.handleItemClick}>{item.name}</Link>))}
</div>
</div>);
}
}
Header.propTypes = {
children: React.PropTypes.node,
activeIndex: React.PropTypes.number,
};
|
src/routes/UIElement/dataTable/index.js | IssaTan1990/antd-admin | import React from 'react'
import { DataTable } from '../../../components'
import { Table, Row, Col, Card, Select } from 'antd'
class DataTablePage extends React.Component {
constructor (props) {
super(props)
this.state = { filterCase: {
gender: '',
} }
}
handleSelectChange = (gender) => {
this.setState({
filterCase: {
gender,
},
})
}
render () {
const { filterCase } = this.state
const staticDataTableProps = {
dataSource: [{ key: '1', name: 'John Brown', age: 24, address: 'New York' }, { key: '2', name: 'Jim Green', age: 23, address: 'London' }],
columns: [{ title: 'name', dataIndex: 'name' }, { title: 'Age', dataIndex: 'age' }, { title: 'Address', dataIndex: 'address' }],
pagination: false,
}
const fetchDataTableProps = {
fetch: {
url: 'https://randomuser.me/api',
data: {
results: 10,
testPrams: 'test',
},
dataKey: 'results',
},
columns: [
{ title: 'Name', dataIndex: 'name', render: (text) => `${text.first} ${text.last}` },
{ title: 'Phone', dataIndex: 'phone' },
{ title: 'Gender', dataIndex: 'gender' },
],
rowKey: 'registered',
}
const caseChangeDataTableProps = {
fetch: {
url: 'https://randomuser.me/api',
data: {
results: 10,
testPrams: 'test',
...filterCase,
},
dataKey: 'results',
},
columns: [
{ title: 'Name', dataIndex: 'name', render: (text) => `${text.first} ${text.last}` },
{ title: 'Phone', dataIndex: 'phone' },
{ title: 'Gender', dataIndex: 'gender' },
],
rowKey: 'registered',
}
return (<div className="content-inner">
<Row gutter={32}>
<Col lg={12} md={24}>
<Card title="默认">
<DataTable pagination={false} />
</Card>
</Col>
<Col lg={12} md={24}>
<Card title="静态数据">
<DataTable
{...staticDataTableProps}
/>
</Card>
</Col>
<Col lg={12} md={24}>
<Card title="远程数据">
<DataTable
{...fetchDataTableProps}
/>
</Card>
</Col>
<Col lg={12} md={24}>
<Card title="参数变化">
<Select placeholder="Please select gender" allowClear onChange={this.handleSelectChange} style={{ width: 200, marginBottom: 16 }}>
<Select.Option value="male">Male</Select.Option>
<Select.Option value="female">Female</Select.Option>
</Select>
<DataTable
{...caseChangeDataTableProps}
/>
</Card>
</Col>
</Row>
<h2 style={{ margin: '16px 0' }}>Props</h2>
<Row>
<Col lg={18} md={24}>
<Table
rowKey={(record, key) => key}
pagination={false}
bordered
scroll={{ x: 800 }}
columns={[
{
title: '参数',
dataIndex: 'props',
},
{
title: '说明',
dataIndex: 'desciption',
},
{
title: '类型',
dataIndex: 'type',
},
{
title: '默认值',
dataIndex: 'default',
},
]}
dataSource={[
{
props: 'fetch',
desciption: '远程获取数据的参数',
type: 'Object',
default: '后面有空加上',
}]}
/>
</Col>
</Row>
</div>)
}
}
export default DataTablePage
|
node_modules/react-router/es6/withRouter.js | lauracurley/2016-08-ps-react | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
import React from 'react';
import hoistStatics from 'hoist-non-react-statics';
import { routerShape } from './PropTypes';
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
export default function withRouter(WrappedComponent) {
var WithRouter = React.createClass({
displayName: 'WithRouter',
contextTypes: { router: routerShape },
render: function render() {
return React.createElement(WrappedComponent, _extends({}, this.props, { router: this.context.router }));
}
});
WithRouter.displayName = 'withRouter(' + getDisplayName(WrappedComponent) + ')';
WithRouter.WrappedComponent = WrappedComponent;
return hoistStatics(WithRouter, WrappedComponent);
} |
components/tabs/index.js | react-material-design/react-material-design | import '@material/tabs/dist/mdc.tabs.css';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import classNames from 'classnames';
import { MDCTabBar } from '@material/tabs';
/** Tab Bar */
class TabBar extends Component {
static propTypes= {
darkTheme: PropTypes.bool,
children: PropTypes.any,
}
constructor(props) {
super(props);
this.mainRoot = React.createRef();
}
componentDidMount() {
this.tabBar = new MDCTabBar(this.mainRoot.current);
}
render() {
const { darkTheme, children } = this.props;
const childProps = Array.isArray(children) ? children.map(child =>
child.props) : children.props;
const childHasIcon = childProps.filter(child => child.icon);
const childHasIconAndText = childHasIcon.some(child => child.label);
const baseClass = childHasIcon.length > 0 ? 'mdc-tab-bar' : 'basic-tab-bar';
const iconAndTextCheck = childHasIconAndText ? 'mdc-tab-bar--icons-with-text' : childHasIcon.length > 0 && 'mdc-tab-bar--icon-tab-bar';
return (
<nav ref={this.mainRoot} className={classNames(baseClass, { [`${baseClass}--theme-dark`]: darkTheme }, iconAndTextCheck)}>
{ children }
<span className="mdc-tab-bar__indicator" />
</nav>
);
}
}
export default TabBar;
|
redux-form/example-fieldArrays/jsx/index.js | Muzietto/react-playground | 'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import {createStore, combineReducers} from 'redux';
import {reducer as reduxFormReducer} from 'redux-form';
import FieldArraysForm from './FieldArraysForm';
const dest = document.getElementById('container');
const reducer = combineReducers({
form: reduxFormReducer // mounted under "form"
});
const store = createStore(reducer);
window.store = store;
const showResults = values =>
new Promise(resolve => {
setTimeout(() => {
// simulate server latency
window.alert(`You submitted:\n\n${JSON.stringify(values, null, 2)}`);
resolve();
}, 500);
});
let render = () => {
ReactDOM.render(
<Provider store={store}>
<FieldArraysForm onSubmit={showResults}/>
</Provider>,
dest
);
};
render();
|
app/index.js | Nurasael/WeWatch | // @flow
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { Router, hashHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
import routes from './routes'
import configureStore from './store/configureStore'
import './app.global.css'
const store = configureStore()
const history = syncHistoryWithStore(hashHistory, store)
render(
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>,
document.getElementById('root')
)
|
src/index.js | bibleexchange/be-front-new | // core setup
import React from 'react';
import ReactDOM from 'react-dom';
import Relay from 'react-relay';
import MyNetworkLayer from './MyNetworkLayer';
// routing
import Route from './Route';
import { browserHistory, applyRouterMiddleware, Router } from 'react-router';
import useRelay from 'react-router-relay';
// send to dom
const mountNode = document.getElementById('root');
if (process.env.GRAPHQL_SERVER_IS === 'mock') {
// havent fugured this out yet
} else {
Relay.injectNetworkLayer(new MyNetworkLayer(localStorage.getItem('be_token'), process.env.GRAPHQL_ENDPOINT));
}
ReactDOM.render(
<Router
history={browserHistory}
routes={Route}
render={applyRouterMiddleware(useRelay)}
environment={Relay.Store}
/>,
mountNode
);
|
src/svg-icons/notification/folder-special.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationFolderSpecial = (props) => (
<SvgIcon {...props}>
<path d="M20 6h-8l-2-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-2.06 11L15 15.28 12.06 17l.78-3.33-2.59-2.24 3.41-.29L15 8l1.34 3.14 3.41.29-2.59 2.24.78 3.33z"/>
</SvgIcon>
);
NotificationFolderSpecial = pure(NotificationFolderSpecial);
NotificationFolderSpecial.displayName = 'NotificationFolderSpecial';
NotificationFolderSpecial.muiName = 'SvgIcon';
export default NotificationFolderSpecial;
|
src/svg-icons/av/subtitles.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvSubtitles = (props) => (
<SvgIcon {...props}>
<path d="M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zM4 12h4v2H4v-2zm10 6H4v-2h10v2zm6 0h-4v-2h4v2zm0-4H10v-2h10v2z"/>
</SvgIcon>
);
AvSubtitles = pure(AvSubtitles);
AvSubtitles.displayName = 'AvSubtitles';
AvSubtitles.muiName = 'SvgIcon';
export default AvSubtitles;
|
app/components/ListItem/index.js | zuban/zuban-boilerplate | import React from 'react';
import Item from './Item';
import Wrapper from './Wrapper';
function ListItem(props) {
return (
<Wrapper>
<Item>
{props.item}
</Item>
</Wrapper>
);
}
ListItem.propTypes = {
item: React.PropTypes.any,
};
export default ListItem;
|
src/app/index.js | MrJonas/bike-routes | import React from 'react';
import {render} from 'react-dom';
import {Route, HashRouter, withRouter} from 'react-router-dom';
require("./../assets/style.css");
require('es6-object-assign').polyfill();
import 'bootstrap/dist/css/bootstrap.css';
import AboutPage from './pages/about.page';
import MainPage from './pages/main.page';
import RoutePage from './pages/route.page';
import RouteListPage from './pages/route.list.page';
import RouteMapPage from './pages/route.map.page';
import Header from './components/header';
const RouterHeader = withRouter(Header);
window.React = React;
render((
<div>
<HashRouter>
<div>
<RouterHeader/>
<Route exact path="/" component={MainPage}></Route>
<Route exact path="/marsrutai" component={RouteListPage}></Route>
<Route exact path="/zemelapis" component={RouteMapPage} className="map-box"></Route>
<Route exact path="/marsrutas/:url" component={RoutePage}></Route>
<Route exact path="/apie" component={AboutPage}></Route>
</div>
</HashRouter>
</div>
), document.getElementById('content'));
|
src/svg-icons/device/graphic-eq.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceGraphicEq = (props) => (
<SvgIcon {...props}>
<path d="M7 18h2V6H7v12zm4 4h2V2h-2v20zm-8-8h2v-4H3v4zm12 4h2V6h-2v12zm4-8v4h2v-4h-2z"/>
</SvgIcon>
);
DeviceGraphicEq = pure(DeviceGraphicEq);
DeviceGraphicEq.displayName = 'DeviceGraphicEq';
DeviceGraphicEq.muiName = 'SvgIcon';
export default DeviceGraphicEq;
|
src/svg-icons/image/brightness-5.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageBrightness5 = (props) => (
<SvgIcon {...props}>
<path d="M20 15.31L23.31 12 20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69zM12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6z"/>
</SvgIcon>
);
ImageBrightness5 = pure(ImageBrightness5);
ImageBrightness5.displayName = 'ImageBrightness5';
ImageBrightness5.muiName = 'SvgIcon';
export default ImageBrightness5;
|
plugins/Files/js/components/deletedialog.js | NebulousLabs/Sia-UI | import PropTypes from 'prop-types'
import React from 'react'
import { List } from 'immutable'
const DeleteDialog = ({ files, actions }) => {
const onYesClick = () => {
files.map(actions.deleteFile)
actions.hideDeleteDialog()
}
const onNoClick = () => actions.hideDeleteDialog()
return (
<div className='modal'>
<div className='delete-dialog'>
<h3> Confirm Deletion </h3>
<div className='delete-text'>
Are you sure you want to delete {files.size}
{files.size === 1 ? ' file' : ' files'}
</div>
<div className='delete-buttons'>
<button onClick={onYesClick}>Yes</button>
<button onClick={onNoClick}>No</button>
</div>
</div>
</div>
)
}
DeleteDialog.propTypes = {
files: PropTypes.instanceOf(List).isRequired
}
export default DeleteDialog
|
src/tests/components/SelectOption.js | bruderstein/unexpected-react |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class SelectOption extends Component {
render() {
return (
<li id={'unique_' + Math.floor(Math.random()*10000)} className="Select__item--unselected Select__item ">
{this.props.label}
</li>);
}
}
SelectOption.propTypes = {
label: PropTypes.string
};
module.exports = SelectOption; |
examples/03 Nesting/Drop Targets/index.js | wagonhq/react-dnd | import React from 'react';
import Container from './Container';
export default class NestingDropTargets {
render() {
return (
<div>
<p>
<b><a href='https://github.com/gaearon/react-dnd/tree/master/examples/03%20Nesting/Drop%20Targets'>Browse the Source</a></b>
</p>
<p>
Drop targets can, too, be nested in one another.
Unlike the drag sources, several drop targets may react to the same item being dragged.
React DnD by design offers no means of stopping propagation.
Instead, the drop targets may compare <code>monitor.isOver()</code> and <code>monitor.isOver({'{'} shallow: false {'}'})</code> to learn if just them, or their nested targets, are being hovered.
They may also check <code>monitor.didDrop()</code> and <code>monitor.getDropResult()</code> to learn if a nested target has already handled the drop, and even return a different drop result.
</p>
<Container />
</div>
);
}
} |
docs/src/app/components/pages/components/SvgIcon/ExampleSimple.js | verdan/material-ui | import React from 'react';
import {blue500, red500, greenA200} from 'material-ui/styles/colors';
import SvgIcon from 'material-ui/SvgIcon';
const iconStyles = {
marginRight: 24,
};
const HomeIcon = (props) => (
<SvgIcon {...props}>
<path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" />
</SvgIcon>
);
const SvgIconExampleSimple = () => (
<div>
<HomeIcon style={iconStyles} />
<HomeIcon style={iconStyles} color={blue500} />
<HomeIcon style={iconStyles} color={red500} hoverColor={greenA200} />
</div>
);
export default SvgIconExampleSimple;
|
src/pages/index.js | jcmnunes/josenunesxyz | import React from 'react';
import { Link } from 'gatsby';
import styled from 'styled-components';
import Manifest from '../components/Manifest';
import List from '../components/List';
import Contact from '../components/Contact';
import H1 from '../styles/H1';
import Heading from '../styles/Heading';
import TwoColumnGrid from '../styles/TwoColumnGrid';
import Paragraph from '../styles/Paragraph';
import worksData from '../content/works';
import projectsData from '../content/projects';
const H2 = styled.h2`
font-weight: 400;
font-size: 20px;
color: ${props => props.theme.neutral100};
`;
const AboutLink = styled(Link)`
color: ${props => props.theme.neutral100};
text-decoration: underline;
text-decoration-color: ${props => props.theme.primary500};
&:hover {
text-decoration-color: ${props => props.theme.primary500};
}
`;
export default () => (
<>
<H2>
Hello, <br /> I'm <AboutLink to="/about">Jose Nunes</AboutLink>
</H2>
<H1>
<span>Frontend</span> Developer
</H1>
<Manifest />
<TwoColumnGrid>
<div>
<Heading>Recent Work Experiences</Heading>
<List data={worksData} />
</div>
<div>
<div style={{ marginBottom: 48 }}>
<Heading>Recent Projects</Heading>
<Paragraph style={{ fontSize: 14 }}>
Some of the projects I maintain during my free time:
</Paragraph>
<List data={projectsData} />
</div>
<Contact socialLinks />
</div>
</TwoColumnGrid>
</>
);
|
client/src/containers/PatientDetail.js | wilimitis/DoctorIQ | import React, { Component } from 'react';
import { connect } from 'react-redux';
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
withRouter,
Switch
} from 'react-router-dom';
import { Card } from 'material-ui/Card';
import download from 'downloadjs';
import { patientDetailSubmit } from '../actions/patientDetailActions';
import PatientDetailOverview from '../components/PatientDetailOverview';
import PatientDetailSchedule from '../components/PatientDetailSchedule';
import Attachments from '../containers/Attachments';
import { uploadDocumentRequest, deleteDocumentRequest } from '../actions/attachmentUploadActions';
class PatientDetail extends Component {
componentDidMount() {
this.props.dispatch(patientDetailSubmit(this.props.match.params.id));
}
render() {
const id = this.props.match.params.id,
paths = {
patients: "/patients",
overview: `/patients/${id}`,
schedule: `/patients/${id}/schedule`,
attachments: `/patients/${id}/attachments`
};
return (
<div>
<Card>
<div className="navbar">
<ul className="header">
{
this.props.grant === 'doctor'
? <li><Link style={{color: '#777'}} to={paths.patients}>patients</Link></li>
: null
}
<li><Link to={paths.overview}>overview</Link></li>
<li><Link to={paths.schedule}>schedule</Link></li>
<li><Link to={paths.attachments}>attachments</Link></li>
</ul>
</div>
<div style={{padding: '1em'}}>
<Switch>
<Route exact path={`/patients/:id`} render={
() => <PatientDetailOverview patient={this.props.patient} /> } />
<Route exact path={`/patients/:id/schedule`} render={
() => <PatientDetailSchedule patient={this.props.patient} /> } />
<Route exact path={`/patients/:id/attachments`} render={
() => <Attachments
attachments={this.props.attachments}
handleFileUpload={this.props.handleFileUpload}
handleClick={this.props.handleClick}
handleDelete={this.props.handleDelete}
grant={this.props.grant} /> } />
</Switch>
</div>
</Card>
</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
return {
patient: state.patientDetail.patient,
attachments: state.patientDetail.attachments,
grant: state.auth.grant,
id: state.auth.id
};
};
const mapDispatchToProps = (dispatch, ownProps) => {
return {
dispatch,
handleFileUpload: (file) => {
dispatch(uploadDocumentRequest(file, ownProps.match.params.id));
},
handleClick: (e, path, name) => {
download(`${window.location.origin}/${path}`.replace('\\', '/'), name);
},
handleDelete: (e, path) => {
dispatch(deleteDocumentRequest(path, ownProps.match.params.id));
}
};
};
const mergeProps = (stateProps, dispatchProps, ownProps) => {
const { id } = stateProps;
return {
...ownProps,
}
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(PatientDetail);
|
example/examples/AnimatedViews.js | zigbang/react-native-maps | import React from 'react';
import {
StyleSheet,
View,
Dimensions,
Animated,
} from 'react-native';
import {
ProviderPropType,
Animated as AnimatedMap,
AnimatedRegion,
Marker,
} from 'react-native-maps';
import PanController from './PanController';
import PriceMarker from './AnimatedPriceMarker';
const screen = Dimensions.get('window');
const ASPECT_RATIO = screen.width / screen.height;
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
const ITEM_SPACING = 10;
const ITEM_PREVIEW = 10;
const ITEM_WIDTH = screen.width - (2 * ITEM_SPACING) - (2 * ITEM_PREVIEW);
const SNAP_WIDTH = ITEM_WIDTH + ITEM_SPACING;
const ITEM_PREVIEW_HEIGHT = 150;
const SCALE_END = screen.width / ITEM_WIDTH;
const BREAKPOINT1 = 246;
const BREAKPOINT2 = 350;
const ONE = new Animated.Value(1);
function getMarkerState(panX, panY, scrollY, i) {
const xLeft = (-SNAP_WIDTH * i) + (SNAP_WIDTH / 2);
const xRight = (-SNAP_WIDTH * i) - (SNAP_WIDTH / 2);
const xPos = -SNAP_WIDTH * i;
const isIndex = panX.interpolate({
inputRange: [xRight - 1, xRight, xLeft, xLeft + 1],
outputRange: [0, 1, 1, 0],
extrapolate: 'clamp',
});
const isNotIndex = panX.interpolate({
inputRange: [xRight - 1, xRight, xLeft, xLeft + 1],
outputRange: [1, 0, 0, 1],
extrapolate: 'clamp',
});
const center = panX.interpolate({
inputRange: [xPos - 10, xPos, xPos + 10],
outputRange: [0, 1, 0],
extrapolate: 'clamp',
});
const selected = panX.interpolate({
inputRange: [xRight, xPos, xLeft],
outputRange: [0, 1, 0],
extrapolate: 'clamp',
});
const translateY = Animated.multiply(isIndex, panY);
const translateX = panX;
const anim = Animated.multiply(isIndex, scrollY.interpolate({
inputRange: [0, BREAKPOINT1],
outputRange: [0, 1],
extrapolate: 'clamp',
}));
const scale = Animated.add(ONE, Animated.multiply(isIndex, scrollY.interpolate({
inputRange: [BREAKPOINT1, BREAKPOINT2],
outputRange: [0, SCALE_END - 1],
extrapolate: 'clamp',
})));
// [0 => 1]
let opacity = scrollY.interpolate({
inputRange: [BREAKPOINT1, BREAKPOINT2],
outputRange: [0, 1],
extrapolate: 'clamp',
});
// if i === index: [0 => 0]
// if i !== index: [0 => 1]
opacity = Animated.multiply(isNotIndex, opacity);
// if i === index: [1 => 1]
// if i !== index: [1 => 0]
opacity = opacity.interpolate({
inputRange: [0, 1],
outputRange: [1, 0],
});
let markerOpacity = scrollY.interpolate({
inputRange: [0, BREAKPOINT1],
outputRange: [0, 1],
extrapolate: 'clamp',
});
markerOpacity = Animated.multiply(isNotIndex, markerOpacity).interpolate({
inputRange: [0, 1],
outputRange: [1, 0],
});
const markerScale = selected.interpolate({
inputRange: [0, 1],
outputRange: [1, 1.2],
});
return {
translateY,
translateX,
scale,
opacity,
anim,
center,
selected,
markerOpacity,
markerScale,
};
}
class AnimatedViews extends React.Component {
constructor(props) {
super(props);
const panX = new Animated.Value(0);
const panY = new Animated.Value(0);
const scrollY = panY.interpolate({
inputRange: [-1, 1],
outputRange: [1, -1],
});
const scrollX = panX.interpolate({
inputRange: [-1, 1],
outputRange: [1, -1],
});
const scale = scrollY.interpolate({
inputRange: [0, BREAKPOINT1],
outputRange: [1, 1.6],
extrapolate: 'clamp',
});
const translateY = scrollY.interpolate({
inputRange: [0, BREAKPOINT1],
outputRange: [0, -100],
extrapolate: 'clamp',
});
const markers = [
{
id: 0,
amount: 99,
coordinate: {
latitude: LATITUDE,
longitude: LONGITUDE,
},
},
{
id: 1,
amount: 199,
coordinate: {
latitude: LATITUDE + 0.004,
longitude: LONGITUDE - 0.004,
},
},
{
id: 2,
amount: 285,
coordinate: {
latitude: LATITUDE - 0.004,
longitude: LONGITUDE - 0.004,
},
},
];
const animations = markers.map((m, i) =>
getMarkerState(panX, panY, scrollY, i));
this.state = {
panX,
panY,
animations,
index: 0,
canMoveHorizontal: true,
scrollY,
scrollX,
scale,
translateY,
markers,
region: new AnimatedRegion({
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
}),
};
}
componentDidMount() {
const { region, panX, panY, scrollX, markers } = this.state;
panX.addListener(this.onPanXChange);
panY.addListener(this.onPanYChange);
region.stopAnimation();
region.timing({
latitude: scrollX.interpolate({
inputRange: markers.map((m, i) => i * SNAP_WIDTH),
outputRange: markers.map(m => m.coordinate.latitude),
}),
longitude: scrollX.interpolate({
inputRange: markers.map((m, i) => i * SNAP_WIDTH),
outputRange: markers.map(m => m.coordinate.longitude),
}),
duration: 0,
}).start();
}
onStartShouldSetPanResponder = (e) => {
// we only want to move the view if they are starting the gesture on top
// of the view, so this calculates that and returns true if so. If we return
// false, the gesture should get passed to the map view appropriately.
const { panY } = this.state;
const { pageY } = e.nativeEvent;
const topOfMainWindow = ITEM_PREVIEW_HEIGHT + panY.__getValue();
const topOfTap = screen.height - pageY;
return topOfTap < topOfMainWindow;
}
onMoveShouldSetPanResponder = (e) => {
const { panY } = this.state;
const { pageY } = e.nativeEvent;
const topOfMainWindow = ITEM_PREVIEW_HEIGHT + panY.__getValue();
const topOfTap = screen.height - pageY;
return topOfTap < topOfMainWindow;
}
onPanXChange = ({ value }) => {
const { index } = this.state;
const newIndex = Math.floor(((-1 * value) + (SNAP_WIDTH / 2)) / SNAP_WIDTH);
if (index !== newIndex) {
this.setState({ index: newIndex });
}
}
onPanYChange = ({ value }) => {
const { canMoveHorizontal, region, scrollY, scrollX, markers, index } = this.state;
const shouldBeMovable = Math.abs(value) < 2;
if (shouldBeMovable !== canMoveHorizontal) {
this.setState({ canMoveHorizontal: shouldBeMovable });
if (!shouldBeMovable) {
const { coordinate } = markers[index];
region.stopAnimation();
region.timing({
latitude: scrollY.interpolate({
inputRange: [0, BREAKPOINT1],
outputRange: [
coordinate.latitude,
coordinate.latitude - (LATITUDE_DELTA * 0.5 * 0.375),
],
extrapolate: 'clamp',
}),
latitudeDelta: scrollY.interpolate({
inputRange: [0, BREAKPOINT1],
outputRange: [LATITUDE_DELTA, LATITUDE_DELTA * 0.5],
extrapolate: 'clamp',
}),
longitudeDelta: scrollY.interpolate({
inputRange: [0, BREAKPOINT1],
outputRange: [LONGITUDE_DELTA, LONGITUDE_DELTA * 0.5],
extrapolate: 'clamp',
}),
duration: 0,
}).start();
} else {
region.stopAnimation();
region.timing({
latitude: scrollX.interpolate({
inputRange: markers.map((m, i) => i * SNAP_WIDTH),
outputRange: markers.map(m => m.coordinate.latitude),
}),
longitude: scrollX.interpolate({
inputRange: markers.map((m, i) => i * SNAP_WIDTH),
outputRange: markers.map(m => m.coordinate.longitude),
}),
duration: 0,
}).start();
}
}
}
onRegionChange(/* region */) {
// this.state.region.setValue(region);
}
render() {
const {
panX,
panY,
animations,
canMoveHorizontal,
markers,
region,
} = this.state;
return (
<View style={styles.container}>
<PanController
style={styles.container}
vertical
horizontal={canMoveHorizontal}
xMode="snap"
snapSpacingX={SNAP_WIDTH}
yBounds={[-1 * screen.height, 0]}
xBounds={[-screen.width * (markers.length - 1), 0]}
panY={panY}
panX={panX}
onStartShouldSetPanResponder={this.onStartShouldSetPanResponder}
onMoveShouldSetPanResponder={this.onMoveShouldSetPanResponder}
>
<AnimatedMap
provider={this.props.provider}
style={styles.map}
region={region}
onRegionChange={this.onRegionChange}
>
{markers.map((marker, i) => {
const {
selected,
markerOpacity,
markerScale,
} = animations[i];
return (
<Marker
key={marker.id}
coordinate={marker.coordinate}
>
<PriceMarker
style={{
opacity: markerOpacity,
transform: [
{ scale: markerScale },
],
}}
amount={marker.amount}
selected={selected}
/>
</Marker>
);
})}
</AnimatedMap>
<View style={styles.itemContainer}>
{markers.map((marker, i) => {
const {
translateY,
translateX,
scale,
opacity,
} = animations[i];
return (
<Animated.View
key={marker.id}
style={[styles.item, {
opacity,
transform: [
{ translateY },
{ translateX },
{ scale },
],
}]}
/>
);
})}
</View>
</PanController>
</View>
);
}
}
AnimatedViews.propTypes = {
provider: ProviderPropType,
};
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
},
itemContainer: {
backgroundColor: 'transparent',
flexDirection: 'row',
paddingHorizontal: (ITEM_SPACING / 2) + ITEM_PREVIEW,
position: 'absolute',
// top: screen.height - ITEM_PREVIEW_HEIGHT - 64,
paddingTop: screen.height - ITEM_PREVIEW_HEIGHT - 64,
// paddingTop: !ANDROID ? 0 : screen.height - ITEM_PREVIEW_HEIGHT - 64,
},
map: {
backgroundColor: 'transparent',
...StyleSheet.absoluteFillObject,
},
item: {
width: ITEM_WIDTH,
height: screen.height + (2 * ITEM_PREVIEW_HEIGHT),
backgroundColor: 'red',
marginHorizontal: ITEM_SPACING / 2,
overflow: 'hidden',
borderRadius: 3,
borderColor: '#000',
},
});
export default AnimatedViews;
|
src/parser/hunter/survival/modules/talents/FlankingStrike.js | fyruna/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS';
import ItemDamageDone from 'interface/others/ItemDamageDone';
import TalentStatisticBox from 'interface/others/TalentStatisticBox';
/**
* You and your pet leap to the target and strike it as one, dealing a total of X Physical damage.
*
* Generates 30 Focus for you and your pet.
*
* Example log: https://www.warcraftlogs.com/reports/zm8bfNxH9FWTajYV#fight=1&type=summary&source=12&translate=true
*/
const FLANKING_STRIKE_FOCUS_GAIN = 30;
class FlankingStrike extends Analyzer {
damage = 0;
flankingStrikes = [];
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.FLANKING_STRIKE_TALENT.id);
this.flankingStrikes.push({
name: this.selectedCombatant.name,
sourceID: this.owner.playerId,
damage: 0,
effectiveFocus: 0,
possibleFocus: 0,
});
}
get flankingStrikesPlayer() {
return this.flankingStrikes.find(item => item.sourceID === this.owner.playerId);
}
getOrInitializePet(petId) {
const foundPet = this.flankingStrikes.find(pet => pet.sourceID === petId);
if (!foundPet) {
const sourcePet = this.owner.playerPets.find(pet => pet.id === petId);
const pet = {
name: sourcePet.name,
sourceID: petId,
damage: 0,
effectiveFocus: 0,
possibleFocus: 0,
};
this.flankingStrikes.push(pet);
return pet;
}
return foundPet;
}
on_byPlayerPet_damage(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.FLANKING_STRIKE_PET.id) {
return;
}
const damage = event.amount + (event.absorbed || 0);
const pet = this.getOrInitializePet(event.sourceID);
pet.damage += damage;
}
on_byPlayer_damage(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.FLANKING_STRIKE_PLAYER.id) {
return;
}
this.flankingStrikesPlayer.damage += event.amount + (event.absorbed || 0);
}
on_byPlayerPet_energize(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.FLANKING_STRIKE_PET.id) {
return;
}
const effectiveFocus = (event.resourceChange - event.waste) || 0;
const pet = this.getOrInitializePet(event.sourceID);
pet.effectiveFocus += effectiveFocus;
pet.possibleFocus += FLANKING_STRIKE_FOCUS_GAIN;
}
on_byPlayer_energize(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.FLANKING_STRIKE_PLAYER.id) {
return;
}
const foundPlayer = this.flankingStrikesPlayer;
foundPlayer.effectiveFocus += (event.resourceChange - event.waste) || 0;
foundPlayer.possibleFocus += FLANKING_STRIKE_FOCUS_GAIN;
}
statistic() {
const totalDamage = this.flankingStrikes.map(source => source.damage).reduce((total, current) => total + current, 0);
return (
<TalentStatisticBox
talent={SPELLS.FLANKING_STRIKE_TALENT.id}
value={<ItemDamageDone amount={totalDamage} />}
>
<table className="table table-condensed">
<thead>
<tr>
<th>Source</th>
<th>Damage</th>
<th>Focus</th>
</tr>
</thead>
<tbody>
{this.flankingStrikes.map((source, idx) => (
<tr key={idx}>
<td>{source.name}</td>
<td>{<ItemDamageDone amount={source.damage} />}</td>
<td>{source.effectiveFocus}/{source.possibleFocus}</td>
</tr>
))}
</tbody>
</table>
</TalentStatisticBox>
);
}
}
export default FlankingStrike;
|
src/svg-icons/hardware/gamepad.js | spiermar/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareGamepad = (props) => (
<SvgIcon {...props}>
<path d="M15 7.5V2H9v5.5l3 3 3-3zM7.5 9H2v6h5.5l3-3-3-3zM9 16.5V22h6v-5.5l-3-3-3 3zM16.5 9l-3 3 3 3H22V9h-5.5z"/>
</SvgIcon>
);
HardwareGamepad = pure(HardwareGamepad);
HardwareGamepad.displayName = 'HardwareGamepad';
HardwareGamepad.muiName = 'SvgIcon';
export default HardwareGamepad;
|
src/svg-icons/notification/vibration.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationVibration = (props) => (
<SvgIcon {...props}>
<path d="M0 15h2V9H0v6zm3 2h2V7H3v10zm19-8v6h2V9h-2zm-3 8h2V7h-2v10zM16.5 3h-9C6.67 3 6 3.67 6 4.5v15c0 .83.67 1.5 1.5 1.5h9c.83 0 1.5-.67 1.5-1.5v-15c0-.83-.67-1.5-1.5-1.5zM16 19H8V5h8v14z"/>
</SvgIcon>
);
NotificationVibration = pure(NotificationVibration);
NotificationVibration.displayName = 'NotificationVibration';
NotificationVibration.muiName = 'SvgIcon';
export default NotificationVibration;
|
src/routes.js | pppp22591558/ChinaPromotion | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React from 'react';
import Router from 'react-routing/src/Router';
import http from './core/HttpClient';
import App from './components/App';
import ContentPage from './components/ContentPage';
import ContactPage from './components/ContactPage';
import LoginPage from './components/LoginPage';
import NotFoundPage from './components/mobile/NotFoundPage';
import ErrorPage from './components/mobile/ErrorPage';
import SignupPage from './components/SignupPage';
import Content from './components/Content';
import FistLaunch from './components/versions/Launch-v1.0.0';
import { get as getContent } from './constants/ABTest';
const router = new Router(on => {
on('/launch-v1.0.0', async (state) => {
state.context.onSetTitle('China Promotion');
return <FistLaunch context={state.context}/>
});
on('/:version', async(state) => {
let version = state.params.version
const { title } = getContent(version)
state.context.onSetTitle(title);
return <App context={state.context} version={version}/>
});
// on('*', async (state) => {
// const content = await http.get(`/api/content?path=${state.path}`);
// return content && <ContentPage {...content} />;
// });
on('error', (state, error) => state.statusCode === 404 ?
<App context={state.context} error={error}><NotFoundPage /></App> :
<App context={state.context} error={error}><ErrorPage /></App>
);
});
export default router;
|
app/components/LandingPage.js | SynapseNetwork/Synapse-Desktop | /* **************************************************************
* Synapse - Desktop Client
* @author Marco Fernandez Pranno <mfernandezpranno@gmail.com>
* @licence MIT
* @link https://github.com/SynapseNetwork/Synapse-Desktop
* @version 1.0
* ************************************************************** */
'use babel';
import React from 'react';
import { Link } from 'react-router-dom';
export default class LandingPage extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<div className="landing-page">
<h4 className="center-align title-text">
Welcome to Synapse
</h4>
<div className="logo"></div>
<div className="center-align">
<Link className="btn btn-large pulse" to="/login">
Login
</Link>
</div>
</div>
</div>
);
}
}
|
packages/material-ui-icons/src/LockOpen.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M12 17c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm6-9h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6h1.9c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm0 12H6V10h12v10z" /></g>
, 'LockOpen');
|
src/payout-picker/PayoutPickerMobile.js | nuruddeensalihu/binary-next-gen | import React from 'react';
import MobilePage from '../containers/MobilePage';
import PayoutPickerContainer from './PayoutPickerContainer';
export default (props) => (
<MobilePage toolbarShown={false} backBtnBarTitle="Payout">
<PayoutPickerContainer {...props} />
</MobilePage>
);
|
src/index.js | ericyd/surfplot-ui | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.scss';
if (typeof window !== undefined) {
ReactDOM.render(
<App />,
document.getElementById('root')
);
}
|
src/routes.js | aragonwa/kc-restaurant-reviews | import React from 'react';
// Index route is used to set the Root Route
import {Route, IndexRoute, Redirect} from 'react-router';
import App from './components/App';
import RestaurantReviewsPage from './containers/RestaurantReviewsPage'; // eslint-disable-line import/no-named-as-default
import Details from './components/Details';
//Todo: not found page <Route path="*" component={NotFoundPage}/>
const baseDir = (process.env.NODE_ENV === 'production') ? '/depts/health/environmental-health/food-safety/inspection-system/search#' :'';
export default (
<Route path={baseDir + '/'} component={App}>
<IndexRoute component={RestaurantReviewsPage}/>
<Route path="/" component={RestaurantReviewsPage}>
<Redirect from="/details/" to="/" />
<Route path={'/details/:id'} component={Details} />
</Route>
<Route path="/search/:searchTerm" component={RestaurantReviewsPage} />
<Route path="*" component={RestaurantReviewsPage}/>
</Route>
);
|
src/svg-icons/av/fiber-pin.js | spiermar/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvFiberPin = (props) => (
<SvgIcon {...props}>
<path d="M5.5 10.5h2v1h-2zM20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zM9 11.5c0 .85-.65 1.5-1.5 1.5h-2v2H4V9h3.5c.85 0 1.5.65 1.5 1.5v1zm3.5 3.5H11V9h1.5v6zm7.5 0h-1.2l-2.55-3.5V15H15V9h1.25l2.5 3.5V9H20v6z"/>
</SvgIcon>
);
AvFiberPin = pure(AvFiberPin);
AvFiberPin.displayName = 'AvFiberPin';
AvFiberPin.muiName = 'SvgIcon';
export default AvFiberPin;
|
src/svg-icons/social/group-add.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialGroupAdd = (props) => (
<SvgIcon {...props}>
<path d="M8 10H5V7H3v3H0v2h3v3h2v-3h3v-2zm10 1c1.66 0 2.99-1.34 2.99-3S19.66 5 18 5c-.32 0-.63.05-.91.14.57.81.9 1.79.9 2.86s-.34 2.04-.9 2.86c.28.09.59.14.91.14zm-5 0c1.66 0 2.99-1.34 2.99-3S14.66 5 13 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm6.62 2.16c.83.73 1.38 1.66 1.38 2.84v2h3v-2c0-1.54-2.37-2.49-4.38-2.84zM13 13c-2 0-6 1-6 3v2h12v-2c0-2-4-3-6-3z"/>
</SvgIcon>
);
SocialGroupAdd = pure(SocialGroupAdd);
SocialGroupAdd.displayName = 'SocialGroupAdd';
SocialGroupAdd.muiName = 'SvgIcon';
export default SocialGroupAdd;
|
src/frontend/components/Menu.js | ErdMutter92/Project-Atlantis | import React from 'react';
import Bootstrap from 'react-bootstrap';
import axios from 'axios';
import io from 'socket.io-client';
import ServerDataService from '../services/server';
import Online from './status/Online';
import Motd from './status/Motd';
import Weather from './status/Weather';
import Mojang from './status/Mojang';
var Menu = React.createClass({
getInitialState: function () {
return {
servername: 'Offline',
motd: 'Server is currently offline...',
version: '1.7.10',
uptime: undefined,
population: {
max: 0,
online: []
}
};
},
componentDidMount: function () {
axios.get('http://api.bleauweb.net/server/status').then(function (promise) {
this.setState({
servername: promise.data.servername,
motd: promise.data.motd,
version: promise.data.version,
uptime: undefined,
population: {
max: promise.data.maxplayers,
online: (promise.data.users !== undefined) ? promise.data.users : []
}
});
}.bind(this));
},
render: function () {
return (
<div className="col-md-12">
<Online
players={this.state.population.online}
capacity={this.state.population.max} />
<Motd
message={this.state.motd}
serverName={this.state.servername}
version={this.state.version} />
<Mojang />
</div>
);
}
});
export default Menu;
|
ui/src/pages/PeopleManagePage/AttributesEditor/index.js | LearningLocker/learninglocker | import React from 'react';
import PropTypes from 'prop-types';
import { Map } from 'immutable';
import { compose, withProps, setPropTypes, withState } from 'recompose';
import { withModels } from 'ui/utils/hocs';
import AddTextIconButton from 'ui/components/TextIconButton/AddTextIconButton';
import NewRow from './NewRow';
import SavedRow from './SavedRow';
import { TableActionsHeader, TableHeader } from './tableComponents';
const enhance = compose(
setPropTypes({
personaId: PropTypes.string.isRequired,
}),
withProps(({ personaId }) => ({
filter: new Map({ personaId: new Map({ $oid: personaId }) }),
schema: 'personaAttribute',
first: 100,
sort: new Map({ _id: -1 }),
})),
withModels,
withState('isNewAttributeVisible', 'changeNewAttributeVisibility', false)
);
const render = ({
personaId,
models,
isNewAttributeVisible,
changeNewAttributeVisibility,
addModel,
}) => {
const handleNewRowAdd = (key, value) => {
const props = new Map({ key, value, personaId });
addModel({ props });
};
const handleNewRowCancel = () => {
changeNewAttributeVisibility(false);
};
const handleShowNewRow = () => {
changeNewAttributeVisibility(true);
};
return (
<div>
<div style={{ textAlign: 'right', marginBottom: '8px' }}>
<AddTextIconButton text="Add Attribute" onClick={handleShowNewRow} />
</div>
<table style={{ width: '100%' }}>
<thead>
<tr>
<TableHeader>Name</TableHeader>
<TableHeader>Value</TableHeader>
<TableActionsHeader>Actions</TableActionsHeader>
</tr>
</thead>
<tbody>
{!isNewAttributeVisible ? null : (
<NewRow onAdd={handleNewRowAdd} onCancel={handleNewRowCancel} />
)}
{models.map(model => (
<SavedRow
id={model.get('_id')}
key={model.get('_id')} />
)).valueSeq()}
</tbody>
</table>
</div>
);
};
export default enhance(render);
|
node_modules/babel-plugin-react-transform/test/fixtures/code-ignore/actual.js | rafser01/installer_electron | import React from 'react';
const First = React.createNotClass({
displayName: 'First'
});
class Second extends React.NotComponent {}
|
src/views/icons/ShieldCrossedIcon.js | physiii/home-gateway | import React from 'react';
import IconBase from './IconBase.js';
export const ShieldCrossedIcon = (props) => (
<IconBase {...props} viewBox="0 0 20 20">
<path d="M1.9 1.3c.2-.2.5-.2.7 0l15.5 15.5c.2.2.2.5 0 .7-.2.2-.5.2-.7 0L1.8 1.9c-.3-.2.1-.6.1-.6zM14.7 17.3c-1.1 1-2.6 1.8-4.5 2.7h-.4c-8.3-3.5-8.1-8.2-7.7-15.2v-.1l.9.9v.1c-.3 6-.1 10.2 7 13.3 1.7-.7 3-1.5 4-2.4l.7.7zm1.8-4.5c.8-2.6.6-5.6.4-9.2-2.5-.1-4.8-1-6.8-2.4-1.2.7-2.3 1.3-3.5 1.7l-.8-.8C7.2 1.7 8.5 1 9.7.1c.2-.1.4-.1.6 0 2.1 1.5 4.4 2.4 7 2.4.3 0 .5.2.5.5.2 4.2.6 7.7-.5 10.6l-.8-.8z" />
</IconBase>
);
export default ShieldCrossedIcon;
|
Other/styleguide/src/components/Section.js | barretthafner/learning | /* @flow */
import React from 'react';
import { View } from 'react-sketchapp';
import Label from './Label';
type P = {
title: string,
children?: any,
};
const Section = ({ title, children }: P) => (
<View style={{ marginBottom: 96, flexDirection: 'row' }}>
<View style={{ width: 200 }}>
<Label bold>{title}</Label>
</View>
<View>
{children}
</View>
</View>
);
export default Section;
|
src/components/Link/Link.js | utage2002/mm | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import history from '../../history';
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
class Link extends React.Component {
static propTypes = {
to: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
onClick: PropTypes.func,
};
static defaultProps = {
onClick: null,
};
handleClick = event => {
if (this.props.onClick) {
this.props.onClick(event);
}
if (isModifiedEvent(event) || !isLeftClickEvent(event)) {
return;
}
if (event.defaultPrevented === true) {
return;
}
event.preventDefault();
history.push(this.props.to);
};
render() {
const { to, children, ...props } = this.props;
return (
<a href={to} {...props} onClick={this.handleClick}>
{children}
</a>
);
}
}
export default Link;
|
src/utils/reactUtils.js | webroo/react-redux-template | import React from 'react';
/**
* Basic version of react-hyperscript. Acts like an overloaded version of React.createElement()
* Allows you to optionally omit the second `props` argument and put children there instead.
* @example
* h('div') // HTML element
* h(MyElement) // Custom element
* h('div', {className: 'main'}) // With props
* h('div', {className: 'main'}, h('h1', 'Hello')) // With props and children
* h('div', h('h1', 'Hello')) // With just children (props omitted)
* h('div', h('h1', 'Hello'), h('p', 'Lorem ipsum')) // Multiple children (props omitted)
*/
export function h(...args) {
// If there isn't a valid props object in the arguments then insert a null one there instead
const p = args[1];
if (typeof p === 'string' || typeof p === 'number' || Array.isArray(p) || React.isValidElement(p)) {
args.splice(1, 0, null);
}
return React.createElement(...args);
}
|
src/app.js | gthomas-appfolio/appfolio-react-template | import React, { Component } from 'react';
import Message from './components/message.js';
export default class App extends Component {
render() {
return (
<div>
<Message />
</div>
);
}
}
|
storybook/stories/character_counter.story.js | imomix/mastodon | import React from 'react';
import { storiesOf } from '@storybook/react';
import CharacterCounter from 'mastodon/features/compose/components/character_counter';
storiesOf('CharacterCounter', module)
.add('no text', () => {
const text = '';
return <CharacterCounter text={text} max={500} />;
})
.add('a few strings text', () => {
const text = '0123456789';
return <CharacterCounter text={text} max={500} />;
})
.add('the same text', () => {
const text = '01234567890123456789';
return <CharacterCounter text={text} max={20} />;
})
.add('over text', () => {
const text = '01234567890123456789012345678901234567890123456789';
return <CharacterCounter text={text} max={10} />;
});
|
src/components/common/products/ProductList.js | ESTEBANMURUZABAL/my-ecommerce-template | /**
* Imports
*/
import React from 'react';
import {FormattedMessage} from 'react-intl';
import {slugify} from '../../../utils/strings';
// Flux
import IntlStore from '../../../stores/Application/IntlStore';
// Required components
import Heading from '../typography/Heading';
import Pagination from '../navigation/Pagination';
import ProductListItem from './ProductListItem';
import ProductListItemCajonGrande from './ProductListItemCajonGrande';
import ProductListItemCajonMediano from './ProductListItemCajonMediano';
import ProductListItemCajonChico from './ProductListItemCajonChico';
import Text from '../typography/Text';
import TreeMenu from '../navigation/TreeMenu';
import { Link} from 'react-router';
// Translation data for this component
import intlData from './ProductList.intl';
/**
* Component
*/
class ProductList extends React.Component {
static contextTypes = {
getStore: React.PropTypes.func.isRequired
};
//*** Component Lifecycle ***//
componentDidMount() {
// Component styles
require('./ProductList.scss');
}
//*** Template ***//
render() {
let intlStore = this.context.getStore(IntlStore);
let cajonChicoProduct, cajonMedianoProduct, cajonGrandeProduct;
let hasDescription = () => {
return this.props.collection && this.props.collection.description && this.props.collection.description[intlStore.getCurrentLocale()];
};
let isCajonCollection = false;
if (this.props.collection) {
isCajonCollection = this.props.collection.name.es == 'Cajon de F&V' ? true : false;
}
let bannerDiv = () => {
if (this.props.collection) {
if (this.props.collection.name.es == 'Cajon de F&V') {
isCajonCollection = true;
return (
<div className="verduras-banner-container"></div>
);
} else {
if (this.props.collection.name.en == 'Library') {
return (
<Link to="/es/products/d0d496b3-ffaa-4334-98a0-cb5079a5ba1d/pedido-de-impresion-blanco-y-negro/" params={this.props.routeParams}>
<div className="impresiones-banner-container"></div>
</Link>
);
}
}
}
};
if (this.props.products.length > 0) {
this.props.products.map(function (item) {
if (item.name.es == 'Cajón Chico') {
cajonChicoProduct = item;
} if (item.name.es == 'Cajón Mediano') {
cajonMedianoProduct = item;
} if (item.name.es == 'Cajón Grande') {
cajonGrandeProduct = item;
}
})
}
return (
<div className="product-list">
{this.props.filters ?
<div className="product-list__sidebar">
{this.props.filters.map((item, idx) => {
let links = item.collections.map((col) => {
return {
name: intlStore.getMessage(col.name),
to: 'collection-slug',
params: {
locale: intlStore.getCurrentLocale(),
collectionId: col.id,
collectionSlug: slugify(intlStore.getMessage(col.name))
},
selected: this.props.collection ? col.id === this.props.collection.id : false
};
});
if (links.length > 0) {
return (
<div key={idx} className="product-list__filter">
<TreeMenu links={links}>
<FormattedMessage
message={intlStore.getMessage(item.name)}
locales={intlStore.getCurrentLocale()} />
</TreeMenu>
</div>
);
}
})}
</div>
:
null
}
{isCajonCollection ?
<div className="product-list-cajon">
<div className="product-list__container">
<div>
{bannerDiv()}
</div>
<div className="product-list__collection-description">
<Text weight="bold" size="medium" >
IMPORTANTE: Envío gratis adentro de las 4 avenidas principales. Fuera de las 4 avenidas $10. Para ver las zonas de envio haga click <a href="https://goo.gl/fGVXkq" target="_blank"><Text weight="bold" color="red" size="medium" >aquí</Text></a>.
</Text>
</div>
{this.props.children ?
<div className="product-list__content">
{this.props.children}
</div>
:
null
}
<div className="product-list__items">
{cajonChicoProduct ?
<div className="product-list__product-item-cajon-chico">
<ProductListItemCajonChico product={cajonChicoProduct} />
</div>
:
null
}
{cajonMedianoProduct ?
<div className="product-list__product-item-cajon-mediano">
<ProductListItemCajonMediano product={cajonMedianoProduct} />
</div>
:
null
}
{cajonGrandeProduct ?
<div className="product-list__product-item-cajon-grande">
<ProductListItemCajonGrande product={cajonGrandeProduct} />
</div>
:
null
}
</div>
{this.props.totalPages && this.props.currentPage && this.props.routeParams && this.props.totalPages > 1 ?
<div className="product-list__pagination">
<Pagination to={this.props.paginateTo || 'collection'}
params={this.props.routeParams}
totalPages={this.props.totalPages}
currentPage={this.props.currentPage} />
</div>
:
null
}
</div>
<div className="product-list__container">
<div className="product-list__collection-description">
<Text weight="bold" size="medium" >
↓ Personalizá tu cajón agregandole lo que necesites aquí debajo ↓
</Text>
</div>
<div className="product-list__items">
{this.props.products.length > 0 ?
this.props.products.map(function (item, idx) {
if (item.tags.includes('verduras')) {
return (
<div key={idx} className="product-list__product-item">
<ProductListItem product={item} />
</div>
);
}
})
:
<div className="product-list__no-results">
<Text size="medium">
<FormattedMessage
message={intlStore.getMessage(intlData, 'noResults')}
locales={intlStore.getCurrentLocale()} /> :(
</Text>
</div>
}
</div>
{this.props.totalPages && this.props.currentPage && this.props.routeParams && this.props.totalPages > 1 ?
<div className="product-list__pagination">
<Pagination to={this.props.paginateTo || 'collection'}
params={this.props.routeParams}
totalPages={this.props.totalPages}
currentPage={this.props.currentPage} />
</div>
:
null
}
</div>
</div>
:
<div className="product-list__container">
<div>
{bannerDiv()}
</div>
{hasDescription() ?
<div className="product-list__collection-description">
<Text size="small">
{intlStore.getMessage(this.props.collection.description)}
</Text>
</div>
:
null
}
{this.props.children ?
<div className="product-list__content">
{this.props.children}
</div>
:
null
}
<div className="product-list__items">
{this.props.products.length > 0 ?
this.props.products.map(function (item, idx) {
return (
<div key={idx} className="product-list__product-item">
<ProductListItem product={item} />
</div>
);
})
:
<div className="product-list__no-results">
<Text size="medium">
<FormattedMessage
message={intlStore.getMessage(intlData, 'noResults')}
locales={intlStore.getCurrentLocale()} /> :(
</Text>
</div>
}
</div>
{this.props.totalPages && this.props.currentPage && this.props.routeParams && this.props.totalPages > 1 ?
<div className="product-list__pagination">
<Pagination to={this.props.paginateTo || 'collection'}
params={this.props.routeParams}
totalPages={this.props.totalPages}
currentPage={this.props.currentPage} />
</div>
:
null
}
</div>
}
</div>
);
}
}
/**
* Exports
*/
export default ProductList;
|
fields/types/embedly/EmbedlyField.js | wustxing/keystone | import React from 'react';
import Field from '../Field';
import { FormField, FormInput } from 'elemental';
module.exports = Field.create({
displayName: 'EmbedlyField',
// always defers to renderValue; there is no form UI for this field
renderField () {
return this.renderValue();
},
renderValue (path, label, multiline) {
return (
<FormField key={path} label={label} className="form-field--secondary">
<FormInput noedit multiline={multiline}>{this.props.value[path]}</FormInput>
</FormField>
);
},
renderAuthor () {
if (!this.props.value.authorName) return;
return (
<FormField key="author" label="Author" className="form-field--secondary">
<FormInput noedit href={this.props.value.authorUrl && this.props.value.authorUrl} target="_blank">{this.props.value.authorName}</FormInput>
</FormField>
);
},
renderDimensions () {
if (!this.props.value.width || !this.props.value.height) return;
return (
<FormField key="dimensions" label="Dimensions" className="form-field--secondary">
<FormInput noedit>{this.props.value.width} × {this.props.value.height}px</FormInput>
</FormField>
);
},
renderPreview () {
if (!this.props.value.thumbnailUrl) return;
var image = <img width={this.props.value.thumbnailWidth} height={this.props.value.thumbnailHeight} src={this.props.value.thumbnailUrl} />;
var preview = this.props.value.url ? (
<a href={this.props.value.url} target="_blank" className="img-thumbnail">{image}</a>
) : (
<div className="img-thumbnail">{image}</div>
);
return (
<FormField label="Preview" className="form-field--secondary">
{preview}
</FormField>
);
},
renderUI () {
if (!this.props.value.exists) {
return (
<FormField label={this.props.label}>
<FormInput noedit>(not set)</FormInput>
</FormField>
);
}
return (
<div className="field-type-embedly">
<FormField key="provider" label={this.props.label}>
<FormInput noedit>{this.props.value.providerName} {this.props.value.type}</FormInput>
</FormField>
{this.renderValue('title', 'Title')}
{this.renderAuthor()}
{this.renderValue('description', 'Description', true)}
{this.renderPreview()}
{this.renderDimensions()}
</div>
);
}
});
|
app/javascript/mastodon/features/compose/components/compose_form.js | KnzkDev/mastodon | import React from 'react';
import CharacterCounter from './character_counter';
import Button from '../../../components/button';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import ReplyIndicatorContainer from '../containers/reply_indicator_container';
import AutosuggestTextarea from '../../../components/autosuggest_textarea';
import AutosuggestInput from '../../../components/autosuggest_input';
import PollButtonContainer from '../containers/poll_button_container';
import UploadButtonContainer from '../containers/upload_button_container';
import { defineMessages, injectIntl } from 'react-intl';
import SpoilerButtonContainer from '../containers/spoiler_button_container';
import PrivacyDropdownContainer from '../containers/privacy_dropdown_container';
import EmojiPickerDropdown from '../containers/emoji_picker_dropdown_container';
import PollFormContainer from '../containers/poll_form_container';
import UploadFormContainer from '../containers/upload_form_container';
import WarningContainer from '../containers/warning_container';
import { isMobile } from '../../../is_mobile';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { length } from 'stringz';
import { countableText } from '../util/counter';
import Icon from 'mastodon/components/icon';
const allowedAroundShortCode = '><\u0085\u0020\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029\u0009\u000a\u000b\u000c\u000d';
const messages = defineMessages({
placeholder: { id: 'compose_form.placeholder', defaultMessage: 'What is on your mind?' },
spoiler_placeholder: { id: 'compose_form.spoiler_placeholder', defaultMessage: 'Write your warning here' },
publish: { id: 'compose_form.publish', defaultMessage: 'Toot' },
publishLoud: { id: 'compose_form.publish_loud', defaultMessage: '{publish}!' },
});
export default @injectIntl
class ComposeForm extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
intl: PropTypes.object.isRequired,
text: PropTypes.string.isRequired,
suggestions: ImmutablePropTypes.list,
spoiler: PropTypes.bool,
privacy: PropTypes.string,
spoilerText: PropTypes.string,
focusDate: PropTypes.instanceOf(Date),
caretPosition: PropTypes.number,
preselectDate: PropTypes.instanceOf(Date),
isSubmitting: PropTypes.bool,
isChangingUpload: PropTypes.bool,
isUploading: PropTypes.bool,
onChange: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
onClearSuggestions: PropTypes.func.isRequired,
onFetchSuggestions: PropTypes.func.isRequired,
onSuggestionSelected: PropTypes.func.isRequired,
onChangeSpoilerText: PropTypes.func.isRequired,
onPaste: PropTypes.func.isRequired,
onPickEmoji: PropTypes.func.isRequired,
showSearch: PropTypes.bool,
anyMedia: PropTypes.bool,
};
static defaultProps = {
showSearch: false,
};
handleChange = (e) => {
this.props.onChange(e.target.value);
}
handleKeyDown = (e) => {
if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) {
this.handleSubmit();
}
}
handleSubmit = () => {
if (this.props.text !== this.autosuggestTextarea.textarea.value) {
// Something changed the text inside the textarea (e.g. browser extensions like Grammarly)
// Update the state to match the current text
this.props.onChange(this.autosuggestTextarea.textarea.value);
}
// Submit disabled:
const { isSubmitting, isChangingUpload, isUploading, anyMedia } = this.props;
const fulltext = [this.props.spoilerText, countableText(this.props.text)].join('');
if (isSubmitting || isUploading || isChangingUpload || length(fulltext) > 500 || (fulltext.length !== 0 && fulltext.trim().length === 0 && !anyMedia)) {
return;
}
this.props.onSubmit(this.context.router ? this.context.router.history : null);
}
onSuggestionsClearRequested = () => {
this.props.onClearSuggestions();
}
onSuggestionsFetchRequested = (token) => {
this.props.onFetchSuggestions(token);
}
onSuggestionSelected = (tokenStart, token, value) => {
this.props.onSuggestionSelected(tokenStart, token, value, ['text']);
}
onSpoilerSuggestionSelected = (tokenStart, token, value) => {
this.props.onSuggestionSelected(tokenStart, token, value, ['spoiler_text']);
}
handleChangeSpoilerText = (e) => {
this.props.onChangeSpoilerText(e.target.value);
}
handleFocus = () => {
if (this.composeForm) {
this.composeForm.scrollIntoView();
}
}
componentDidUpdate (prevProps) {
// This statement does several things:
// - If we're beginning a reply, and,
// - Replying to zero or one users, places the cursor at the end of the textbox.
// - Replying to more than one user, selects any usernames past the first;
// this provides a convenient shortcut to drop everyone else from the conversation.
if (this.props.focusDate !== prevProps.focusDate) {
let selectionEnd, selectionStart;
if (this.props.preselectDate !== prevProps.preselectDate) {
selectionEnd = this.props.text.length;
selectionStart = this.props.text.search(/\s/) + 1;
} else if (typeof this.props.caretPosition === 'number') {
selectionStart = this.props.caretPosition;
selectionEnd = this.props.caretPosition;
} else {
selectionEnd = this.props.text.length;
selectionStart = selectionEnd;
}
this.autosuggestTextarea.textarea.setSelectionRange(selectionStart, selectionEnd);
this.autosuggestTextarea.textarea.focus();
} else if(prevProps.isSubmitting && !this.props.isSubmitting) {
this.autosuggestTextarea.textarea.focus();
} else if (this.props.spoiler !== prevProps.spoiler) {
if (this.props.spoiler) {
this.spoilerText.input.focus();
} else {
this.autosuggestTextarea.textarea.focus();
}
}
}
setAutosuggestTextarea = (c) => {
this.autosuggestTextarea = c;
}
setSpoilerText = (c) => {
this.spoilerText = c;
}
setRef = c => {
this.composeForm = c;
};
handleEmojiPick = (data) => {
const { text } = this.props;
const position = this.autosuggestTextarea.textarea.selectionStart;
const needsSpace = data.custom && position > 0 && !allowedAroundShortCode.includes(text[position - 1]);
this.props.onPickEmoji(position, data, needsSpace);
}
render () {
const { intl, onPaste, showSearch, anyMedia } = this.props;
const disabled = this.props.isSubmitting;
const text = [this.props.spoilerText, countableText(this.props.text)].join('');
const disabledButton = disabled || this.props.isUploading || this.props.isChangingUpload || length(text) > 500 || (text.length !== 0 && text.trim().length === 0 && !anyMedia);
let publishText = '';
if (this.props.privacy === 'private' || this.props.privacy === 'direct') {
publishText = <span className='compose-form__publish-private'><Icon id='lock' /> {intl.formatMessage(messages.publish)}</span>;
} else {
publishText = this.props.privacy !== 'unlisted' ? intl.formatMessage(messages.publishLoud, { publish: intl.formatMessage(messages.publish) }) : intl.formatMessage(messages.publish);
}
return (
<div className='compose-form' ref={this.setRef}>
<WarningContainer />
<ReplyIndicatorContainer />
<div className={`spoiler-input ${this.props.spoiler ? 'spoiler-input--visible' : ''}`}>
<AutosuggestInput
placeholder={intl.formatMessage(messages.spoiler_placeholder)}
value={this.props.spoilerText}
onChange={this.handleChangeSpoilerText}
onKeyDown={this.handleKeyDown}
disabled={!this.props.spoiler}
ref={this.setSpoilerText}
suggestions={this.props.suggestions}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
onSuggestionSelected={this.onSpoilerSuggestionSelected}
searchTokens={[':']}
id='cw-spoiler-input'
className='spoiler-input__input'
/>
</div>
<div className={`emoji-picker-wrapper ${this.props.showSearch ? 'emoji-picker-wrapper--hidden' : ''}`}>
<EmojiPickerDropdown onPickEmoji={this.handleEmojiPick} />
</div>
<AutosuggestTextarea
ref={this.setAutosuggestTextarea}
placeholder={intl.formatMessage(messages.placeholder)}
disabled={disabled}
value={this.props.text}
onChange={this.handleChange}
suggestions={this.props.suggestions}
onFocus={this.handleFocus}
onKeyDown={this.handleKeyDown}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
onSuggestionSelected={this.onSuggestionSelected}
onPaste={onPaste}
autoFocus={!showSearch && !isMobile(window.innerWidth)}
>
<div className='compose-form__modifiers'>
<UploadFormContainer />
<PollFormContainer />
</div>
</AutosuggestTextarea>
<div className='compose-form__buttons-wrapper'>
<div className='compose-form__buttons'>
<UploadButtonContainer />
<PollButtonContainer />
<PrivacyDropdownContainer />
<SpoilerButtonContainer />
</div>
<div className='character-counter__wrapper'><CharacterCounter max={500} text={text} /></div>
</div>
<div className='compose-form__publish'>
<div className='compose-form__publish-button-wrapper'><Button text={publishText} onClick={this.handleSubmit} disabled={disabledButton} block /></div>
</div>
</div>
);
}
}
|
src/svg-icons/editor/insert-invitation.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorInsertInvitation = (props) => (
<SvgIcon {...props}>
<path d="M17 12h-5v5h5v-5zM16 1v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2h-1V1h-2zm3 18H5V8h14v11z"/>
</SvgIcon>
);
EditorInsertInvitation = pure(EditorInsertInvitation);
EditorInsertInvitation.displayName = 'EditorInsertInvitation';
EditorInsertInvitation.muiName = 'SvgIcon';
export default EditorInsertInvitation;
|
src/svg-icons/image/movie-creation.js | verdan/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageMovieCreation = (props) => (
<SvgIcon {...props}>
<path d="M18 4l2 4h-3l-2-4h-2l2 4h-3l-2-4H8l2 4H7L5 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4h-4z"/>
</SvgIcon>
);
ImageMovieCreation = pure(ImageMovieCreation);
ImageMovieCreation.displayName = 'ImageMovieCreation';
ImageMovieCreation.muiName = 'SvgIcon';
export default ImageMovieCreation;
|
src/svg-icons/maps/local-grocery-store.js | verdan/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalGroceryStore = (props) => (
<SvgIcon {...props}>
<path d="M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zM1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.48 0-.55-.45-1-1-1H5.21l-.94-2H1zm16 16c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2z"/>
</SvgIcon>
);
MapsLocalGroceryStore = pure(MapsLocalGroceryStore);
MapsLocalGroceryStore.displayName = 'MapsLocalGroceryStore';
MapsLocalGroceryStore.muiName = 'SvgIcon';
export default MapsLocalGroceryStore;
|
src/App.js | theCoolKidsJavaScriptMeetup/cuddlyGuacamole | import React, { Component } from 'react';
import { BrowserRouter as Router } from 'react-router-dom'
import Firebase from 'firebase'
import Navigation from './components/Navigation';
import Footer from './components/Footer';
import Main from './components/Main';
import Sponsors from './components/Sponsors';
import Registration from './components/Registration';
import FAQ from './components/FAQ';
import RegistrationForm from './components/RegistrationForm';
import CreateTeamForm from './components/CreateTeamForm';
import JoinTeamForm from './components/JoinTeamForm';
import RegistrationSuccess from './components/RegistrationSuccess';
import ScrollToTopRoute from './components/ScrollToTopRoute';
import './App.css?ver=1.1';
class App extends Component {
componentWillMount () {
var config = {
apiKey: "AIzaSyAR6WiLvKXj9_nS8NZELe7xhHLVxIov70E",
authDomain: "peoria-hackathon-8b9e7.firebaseapp.com",
databaseURL: "https://peoria-hackathon-8b9e7.firebaseio.com",
projectId: "peoria-hackathon-8b9e7",
storageBucket: "peoria-hackathon-8b9e7.appspot.com",
messagingSenderId: "454113892052"
};
Firebase.initializeApp(config);
}
render() {
return (
<Router>
<div className="App">
<Navigation />
<ScrollToTopRoute exact path="/" component={Main}/>
<ScrollToTopRoute exact path="/sponsors" component={Sponsors}/>
<ScrollToTopRoute exact path="/registration" component={Registration}/>
<ScrollToTopRoute exact path="/faq" component={FAQ}/>
<ScrollToTopRoute path='/register/:id' component={RegistrationForm} />
<ScrollToTopRoute path='/registerTeam/join/:id' component={JoinTeamForm} />
<ScrollToTopRoute path='/registerTeam/create' component={CreateTeamForm} />
<ScrollToTopRoute path='/registered/:id' component={RegistrationSuccess} />
<Footer />
</div>
</Router>
);
}
}
export default App;
|
mobile/js/features/home/nav.js | lovelypig5/mock-server | import React from 'react';
import {
Navigator,
Text,
TouchableOpacity
} from 'react-native';
import styles from '../../styles';
import Home from './index';
import LoginButton from '../login/loginButton';
class HomeNav extends React.Component {
render() {
return (<Navigator initialRoute={ this.initialRoute() }
configureScene={ this.configureScene }
renderScene={ this.renderScene }
navigationBar={
<Navigator.NavigationBar routeMapper={ this.getRouteMapper() } style={ styles.common.navigator } />
}
/>)
}
initialRoute() {
return {
title: 'Mock Server',
back: '',
component: Home,
index: 0,
right: LoginButton
}
}
renderScene(route, navigator) {
let RouteView = route.component;
if (route.configureScene) {
navigator.configureScene = route.configureScene;
}
return <RouteView {...route.params} {...this.props} navigator={ navigator } />
}
configureScene(route) {
if (route.sceneConfig) {
return route.sceneConfig;
}
return Navigator.SceneConfigs.FloatFromRight;
}
getRouteMapper() {
let props = this.props;
var routeMapper = {
LeftButton(route, navigator, index, navState) {
if (index === 0) {
return null
}
const previousRoute = navState.routeStack[index - 1]
return (
<TouchableOpacity onPress={ () => navigator.pop() }>
<Text style={ [styles.common.row, styles.layout.text] }>
{ previousRoute.back || ' < ' }
</Text>
</TouchableOpacity>
)
},
RightButton(route, navigator, index, navState) {
var Right = route.right
if (Right) {
return <Right {...props} navigator={ navigator } />
}
},
Title(route, navigator, index, navState) {
return (
<Text style={ [styles.common.row, styles.layout.title] }>
{ route.title }
</Text>
)
}
}
return routeMapper;
}
}
export default HomeNav;
|
js/Details.js | olegk101/test | import React from 'react'
import { connect } from 'react-redux'
import { getOMDBDetails } from './actionCreators'
import Header from './Header'
const { shape, string, func } = React.PropTypes
const Details = React.createClass({
propTypes: {
show: shape({
title: string,
year: string,
poster: string,
trailer: string,
description: string,
imdbID: string
}),
omdbData: shape({
imdbID: string
}),
dispatch: func
},
componentDidMount () {
if (!this.props.omdbData.imdbRating) {
this.props.dispatch(getOMDBDetails(this.props.show.imdbID))
}
},
render () {
const { title, description, year, poster, trailer } = this.props.show
let rating
if (this.props.omdbData.imdbRating) {
rating = <h3>{this.props.omdbData.imdbRating}</h3>
} else {
rating = <img src='/public/img/loading.png' alt='loading indicator' />
}
return (
<div className='details'>
<Header />
<section>
<h1>{title}</h1>
<h2>({year})</h2>
{rating}
<img src={`/public/img/posters/${poster}`} />
<p>{description}</p>
</section>
<div>
<iframe src={`https://www.youtube-nocookie.com/embed/${trailer}?rel=0&controls=0&showinfo=0`} frameBorder='0' allowFullScreen />
</div>
</div>
)
}
})
const mapStateToProps = (state, ownProps) => {
const omdbData = state.omdbData[ownProps.show.imdbID] ? state.omdbData[ownProps.show.imdbID] : {}
// if (state.omdbData[ownProps.show.imdbID]) {
// omdbData = state.omdbData[ownProps.show.imdbID]
// } else {
// omdbData = {}
// }
return {
omdbData
}
}
export default connect(mapStateToProps)(Details)
|
src/components/Item.js | namelos/react-demo | import React, { Component } from 'react';
import { ListItem } from 'material-ui';
export default class Item extends Component {
render = () =>
<ListItem primaryText={ this.props.children } />
} |
src/svg-icons/hardware/smartphone.js | lawrence-yu/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareSmartphone = (props) => (
<SvgIcon {...props}>
<path d="M17 1.01L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z"/>
</SvgIcon>
);
HardwareSmartphone = pure(HardwareSmartphone);
HardwareSmartphone.displayName = 'HardwareSmartphone';
HardwareSmartphone.muiName = 'SvgIcon';
export default HardwareSmartphone;
|
src/routes/NotAuthenticatedRoute.js | Clemson-University-Energizer/energizer-app |
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
const NotAuthenticatedRoute = ({ component, ...rest }) => (
<Route {...rest} render={props => (
sessionStorage.JWT_TOKEN ? (
<Redirect to={{ pathname: '/', state: { from: props.location } }}/>
) : (
(React.createElement(component, props))
)
)}/>
)
export default NotAuthenticatedRoute;
|
src-example/components/pages/GenericPage/index.stories.js | SIB-Colombia/biodiversity_catalogue_v2_frontend | import React from 'react'
import { storiesOf } from '@kadira/storybook'
import { GenericPage } from 'components'
storiesOf('GenericPage', module)
.add('default', () => (
<GenericPage />
))
|
public/js/components/Help.js | hkdnet/GitRec | 'use strict'
import React from 'react';
import { Button, Grid, Row, Col, Label } from 'react-bootstrap';
export default class Help extends React.Component {
render() {
return (
<div>
<h2>How to Use</h2>
<section>
<ul>
<li>GitHubレポジトリを指定します。 例: hkdnet/GitRec</li>
<li>日付フィルタを指定します。デフォルトは直近1週間です。</li>
<li>コミッタフィルタを指定します。ない場合はレポジトリの全ログを取得します。</li>
<li>送信ボタンをクリックします。</li>
</ul>
</section>
</div>
)
}
}
|
src/svg-icons/image/filter-tilt-shift.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageFilterTiltShift = (props) => (
<SvgIcon {...props}>
<path d="M11 4.07V2.05c-2.01.2-3.84 1-5.32 2.21L7.1 5.69c1.11-.86 2.44-1.44 3.9-1.62zm7.32.19C16.84 3.05 15.01 2.25 13 2.05v2.02c1.46.18 2.79.76 3.9 1.62l1.42-1.43zM19.93 11h2.02c-.2-2.01-1-3.84-2.21-5.32L18.31 7.1c.86 1.11 1.44 2.44 1.62 3.9zM5.69 7.1L4.26 5.68C3.05 7.16 2.25 8.99 2.05 11h2.02c.18-1.46.76-2.79 1.62-3.9zM4.07 13H2.05c.2 2.01 1 3.84 2.21 5.32l1.43-1.43c-.86-1.1-1.44-2.43-1.62-3.89zM15 12c0-1.66-1.34-3-3-3s-3 1.34-3 3 1.34 3 3 3 3-1.34 3-3zm3.31 4.9l1.43 1.43c1.21-1.48 2.01-3.32 2.21-5.32h-2.02c-.18 1.45-.76 2.78-1.62 3.89zM13 19.93v2.02c2.01-.2 3.84-1 5.32-2.21l-1.43-1.43c-1.1.86-2.43 1.44-3.89 1.62zm-7.32-.19C7.16 20.95 9 21.75 11 21.95v-2.02c-1.46-.18-2.79-.76-3.9-1.62l-1.42 1.43z"/>
</SvgIcon>
);
ImageFilterTiltShift = pure(ImageFilterTiltShift);
ImageFilterTiltShift.displayName = 'ImageFilterTiltShift';
ImageFilterTiltShift.muiName = 'SvgIcon';
export default ImageFilterTiltShift;
|
src/components/user/menu-item.js | OpenChemistry/mongochemclient | import React, { Component } from 'react';
import { MenuItem } from '@material-ui/core';
import AccountCircleIcon from '@material-ui/icons/AccountCircle';
class UserMenuComponent extends Component {
render() {
const { onClick } = this.props;
return (
<MenuItem onClick={onClick}>
<AccountCircleIcon/> User Profile
</MenuItem>
);
}
}
export default UserMenuComponent;
|
docs/app/Examples/elements/Reveal/index.js | vageeshb/Semantic-UI-React | import React from 'react'
import Types from './Types'
import Content from './Content'
import States from './States'
import Variations from './Variations'
const RevealExamples = () => (
<div>
<Types />
<Content />
<States />
<Variations />
</div>
)
export default RevealExamples
|
src/admin/ControlSidebar.js | rendact/rendact | import React from 'react';
import $ from 'jquery';
import Query from './query';
import _ from 'lodash';
import {disableForm, errorCallback} from '../utils';
import Notification from 'react-notification-system';
import {connect} from 'react-redux';
import {withApollo} from 'react-apollo';
import gql from 'graphql-tag';
window.$ = $;
const mySkins = [
"skin-blue",
"skin-black",
"skin-red",
"skin-yellow",
"skin-purple",
"skin-green",
"skin-blue-light",
"skin-black-light",
"skin-red-light",
"skin-yellow-light",
"skin-purple-light",
"skin-green-light"
];
let ControlSidebar = React.createClass({
getInitialState: function(){
return {
}
},
componentDidMount: function(){
require('./lib/app.js');
this.notification = this.refs.notificationSystem;
this.changeLayout('fixed');
this.setup();
},
changeLayout(cls) {
$("body").toggleClass(cls);
//$.AdminLTE.layout.fixSidebar();
//Fix the problem with right sidebar and layout boxed
if (cls === "layout-boxed")
$.AdminLTE.controlSidebar._fix($(".control-sidebar-bg"));
if ($('body').hasClass('fixed') && cls === 'fixed') {
//AdminLTE.pushMenu.expandOnHover();
//AdminLTE.layout.activate();
}
if (cls === "profile-hide") {
$(".user-panel").toggleClass("user-panel-hidden");
localStorage.setItem("user-panel-box", !$(".user-panel").hasClass("user-panel-hidden"));
}
//AdminLTE.controlSidebar._fix($(".control-sidebar-bg"));
//$.AdminLTE.controlSidebar._fix($(".control-sidebar"));
},
changeSkin: function(cls){
if (cls===null) cls = 'skin-blue';
$.each(mySkins, function (i) {
$("body").removeClass(mySkins[i]);
});
$("body").addClass(cls);
this.setLSValue('skin', cls);
return false;
},
disableForm: function(state){
disableForm(state, this.notification)
},
handleDataSkin: function(e){
if($(this).hasClass('knob'))
return;
e.preventDefault();
var skinName = e.currentTarget.getAttribute("data-skin");
this.changeSkin(skinName);
this.setLSValue('skin', skinName);
},
handleDataLayout: function(e){
var configName = e.target.getAttribute("data-layout");
var checked = e.target.checked;
if (configName==="profile-hide") {
if (checked) $(".user-panel").removeClass("user-panel-hidden");
else $(".user-panel").addClass("user-panel-hidden");
this.setLSValue('user-panel-box', checked);
}
if (configName==="sidebar-collapse") {
if (checked) $("body").addClass("sidebar-collapse");
else $("body").removeClass("sidebar-collapse");
this.setLSValue('sidebar-collapse', checked);
}
if (configName==="expand-on-hover") {
e.target.setAttribute('disabled', checked);
if (checked){
$.AdminLTE.pushMenu.expandOnHover();
if (!$('body').hasClass('sidebar-collapse')) $("body").addClass("sidebar-collapse");
}
else {
$("body").removeClass("sidebar-collapse");
}
this.setLSValue('sidebar-expand-on-hover', checked);
}
if (configName==="control-sidebar-open") {
$.AdminLTE.options.controlSidebarOptions.slide = checked;
if (checked) {
$('.control-sidebar').addClass('control-sidebar-open');
$('body').addClass('control-sidebar-open');
} else {
$('.control-sidebar').removeClass('control-sidebar-open');
$('body').removeClass('control-sidebar-open');
}
this.setLSValue('control-sidebar-open', checked);
}
},
handleSetting: function(e){
var configName = e.target.getAttribute("data-setting");
var checked = e.target.checked;
if (configName==="report-panel-usage") {
this.setLSValue('report-panel-usage', checked);
}
if (configName==="allow-email-redirect") {
this.setLSValue('allow-email-redirect', checked);
}
if (configName==="expose-author-name") {
this.setLSValue('expose-author-name', checked);
}
if (configName==="show-as-online") {
this.setLSValue('show-as-online', checked);
}
if (configName==="turn-off-notification") {
this.setLSValue('turn-off-notification', checked);
}
},
handleSaveBtn: function(event){
this.disableForm(true);
var userPrefConfig = {
"profile-hide": this.getLSValue('user-panel-box'),
"sidebar-collapse": this.getLSValue('sidebar-collapse'),
"sidebar-expand-on-hover": this.getLSValue('sidebar-expand-on-hover'),
"control-sidebar-open": this.getLSValue('control-sidebar-open'),
"skin": this.getLSValue('skin'),
"report-panel-usage": this.getLSValue('report-panel-usage'),
"allow-email-redirect": this.getLSValue('allow-email-redirect'),
"expose-author-name": this.getLSValue('expose-author-name'),
"show-as-online": this.getLSValue('show-as-online'),
"turn-off-notification": this.getLSValue('turn-off-notification')
}
var userPrefConfigStr = JSON.stringify(userPrefConfig);
var p = JSON.parse(localStorage.getItem("profile"));
var me = this;
var qry = '';
var userMetaData = [];
var listOfData = "";
var metaIdList = JSON.parse(localStorage.getItem("metaIdList"));
if (metaIdList.userPrefConfig && metaIdList.userPrefConfig!=="" && metaIdList.userPrefConfig!==null) {
userMetaData = [{id: metaIdList.userPrefConfig, item: "userPrefConfig", value: userPrefConfigStr}]
// qry = Query.saveUserMetaMtn(localStorage.getItem("userId"), userMetaData)
listOfData = me.props.client.mutate({
mutation: gql`${Query.saveUserMetaMtn(localStorage.getItem("userId"), userMetaData).query}`,
variables: Query.saveUserMetaMtn(localStorage.getItem("userId"), userMetaData).variables
})
} else {
userMetaData = [{item: "userPrefConfig", value: userPrefConfigStr}]
// qry = Query.createUserMetaMtn(localStorage.getItem("userId"), userMetaData)
listOfData = me.props.client.mutate({
mutation: gql`${Query.createUserMetaMtn(localStorage.getItem("userId"), userMetaData).query}`,
variables: Query.createUserMetaMtn(localStorage.getItem("userId"), userMetaData).variables
})
}
// riques(qry,
// function(error, response, body){
// if(!error && !body.errors) {
// debugger
// var cfg = _.find(body.data, {changedUserMeta: {item: "userPrefConfig"}});
// debugger
// if (cfg) {
// p["userPrefConfig"] = cfg.changedUserMeta.value;
// debugger
// localStorage.setItem("profile", JSON.stringify(p));
// debugger
// me.disableForm(false);
// }
// } else {
// errorCallback(error, body.errors?body.errors[0].message:null);
// }
// }
// );
listOfData.then(function() {
_.forEach(arguments, function(item){
var cfg = _.find(item.data, {changedUserMeta: {item: "userPrefConfig"}});
if (cfg) {
p["userPrefConfig"] = cfg.changedUserMeta.value;
localStorage.setItem("profile", JSON.stringify(p));
me.disableForm(false);
}
})
})
},
resetOption: function(){
if ($('body').hasClass('sidebar-collapse')) {
$("[data-layout='sidebar-collapse']").attr('checked', 'checked');
}
},
setup: function() {
var skin = this.getLSValue('skin');
if (skin===null || skin==="null" ) {
this.setLSValue("skin", "skin-blue");
skin = "skin-blue";
}
if (skin && $.inArray(skin, mySkins))
this.changeSkin(skin);
//Load profile box config
var profileBox = this.getLSValue('user-panel-box');
$("[data-layout='profile-hide']").prop('checked', profileBox==='true');
if (profileBox==="true" && $(".user-panel").hasClass("user-panel-hidden")) {
$(".user-panel").removeClass("user-panel-hidden")
}
var sidebarCollapse = this.getLSValue('sidebar-collapse');
$("[data-layout='sidebar-collapse']").prop('checked', sidebarCollapse==='true');
if (sidebarCollapse==="true") {
$("body").addClass("sidebar-collapse")
} else if ($("body").hasClass("sidebar-collapse")){
$("body").removeClass("sidebar-collapse")
}
var sidebarExpandHover = this.getLSValue('sidebar-expand-on-hover');
$("[data-layout='expand-on-hover']").prop('checked', sidebarExpandHover==='true');
if (sidebarExpandHover==="true"){
$.AdminLTE.pushMenu.expandOnHover();
if (!$('body').hasClass('sidebar-collapse')) $("body").addClass("sidebar-collapse");
}
else if (sidebarExpandHover==="false") {
$("body").removeClass("sidebar-collapse");
}
},
getLSValue: function(item){
return localStorage.getItem(item)
},
setLSValue: function(item, value){
return localStorage.setItem(item, value)
},
render: function(){
let p = JSON.parse(localStorage.getItem("profile"));
return (
<aside className={this.props.ControlSidebar === true ? "control-sidebar control-sidebar-dark control-sidebar-open" : "control-sidebar control-sidebar-dark"}>
<ul className="nav nav-tabs nav-justified control-sidebar-tabs">
<li className="active"><a href="#control-sidebar-theme-demo-options-tab" data-toggle="tab"><i className="fa fa-wrench"></i></a></li>
{/* <li><a href="#control-sidebar-home-tab" data-toggle="tab"><i className="fa fa-home"></i></a></li> */}
<li><a href="#control-sidebar-settings-tab" data-toggle="tab"><i className="fa fa-gears"></i></a></li>
</ul>
<Notification ref="notificationSystem" />
<div className="tab-content">
<div className="tab-pane active" id="control-sidebar-theme-demo-options-tab">
<h4 className="control-sidebar-heading">Layout Options</h4>
<div className='form-group'>
<label className='control-sidebar-subheading'>
<input type='checkbox' onClick={this.handleDataLayout} data-layout='profile-hide' className='pull-right' />
Show Profile Box
</label>
<p>Show the profile box in the left sidebar</p>
</div>
<div className='form-group'>
<label className='control-sidebar-subheading'>
<input type='checkbox' onClick={this.handleDataLayout} data-layout='sidebar-collapse' className='pull-right'/>
Collapse Sidebar
</label>
<p>Collapse the left sidebars state</p>
</div>
<div className='form-group'>
<label className='control-sidebar-subheading'>
<input type='checkbox' onClick={this.handleDataLayout} data-layout='expand-on-hover' className='pull-right'/>
Sidebar Expand on Hover
</label>
<p>Let the sidebar mini expand on hover</p>
</div>
<div className='form-group'>
<label className='control-sidebar-subheading'>
<input type='checkbox' onClick={this.handleDataLayout} data-layout='control-sidebar-open' className='pull-right'/>
Toggle Right Sidebar Slide
</label>
<p>Toggle between slide over content and push content effects</p>
</div>
<h4 className='control-sidebar-heading'>Skins</h4>
<ul className="list-unstyled clearfix">
<li style={{float:"left", width: "33.33333%", padding: 5}}>
<a href='#' onClick={this.handleDataSkin} data-skin='skin-blue' style={{display: "block", boxShadow: "0 0 3px rgba(0,0,0,0.4)"}} className='clearfix full-opacity-hover'>
<div><span style={{display:"block", width: "20%", float: "left", height: 7, background: "#367fa9"}}></span><span className='bg-light-blue' style={{display:"block", width: "80%", float: "left", height: 7}}></span></div>
<div><span style={{display:"block", width: "20%", float: "left", height: 20, background: "#222d32"}}></span><span style={{display:"block", width: "80%", float: "left", height: 20, background: "#f4f5f7"}}></span></div>
</a>
<p className='text-center no-margin'>Blue</p>
</li>
<li style={{float:"left", width: "33.33333%", padding: 5}}>
<a href='#' onClick={this.handleDataSkin} data-skin='skin-black' style={{display: "block", boxShadow: "0 0 3px rgba(0,0,0,0.4)"}} className='clearfix full-opacity-hover'>
<div style={{boxShadow: "0 0 2px rgba(0,0,0,0.1)"}} className='clearfix'><span style={{display:"block", width: "20%", float: "left", height: 7, background: "#fefefe"}}></span><span style={{display:"block", width: "80%", float: "left", height: 7, background: "#fefefe"}}></span></div>
<div><span style={{display:"block", width: "20%", float: "left", height: 20, background: "#222d32"}}></span><span style={{display:"block", width: "80%", float: "left", height: 20, background: "#f4f5f7"}}></span></div>
</a>
<p className='text-center no-margin'>Black</p>
</li>
<li style={{float:"left", width: "33.33333%", padding: 5}}>
<a href='#' onClick={this.handleDataSkin} data-skin='skin-purple' style={{display: "block", boxShadow: "0 0 3px rgba(0,0,0,0.4)"}} className='clearfix full-opacity-hover'>
<div><span style={{display:"block", width: "20%", float: "left", height: 7}} className='bg-purple-active'></span><span className='bg-purple' style={{display:"block", width: "80%", float: "left", height: 7}}></span></div>
<div><span style={{display:"block", width: "20%", float: "left", height: 20, background: "#222d32"}}></span><span style={{display:"block", width: "80%", float: "left", height: 20, background: "#f4f5f7"}}></span></div>
</a>
<p className='text-center no-margin'>Purple</p>
</li>
<li style={{float:"left", width: "33.33333%", padding: 5}}>
<a href='#' onClick={this.handleDataSkin} data-skin='skin-green' style={{display: "block", boxShadow: "0 0 3px rgba(0,0,0,0.4)"}} className='clearfix full-opacity-hover'>
<div><span style={{display:"block", width: "20%", float: "left", height: 7}} className="bg-green-active"></span><span className='bg-green' style={{display:"block", width: "80%", float: "left", height: 7}}></span></div>
<div><span style={{display:"block", width: "20%", float: "left", height: 20, background: "#222d32"}}></span><span style={{display:"block", width: "80%", float: "left", height: 20, background: "#f4f5f7"}}></span></div>
</a>
<p className='text-center no-margin'>Green</p>
</li>
<li style={{float:"left", width: "33.33333%", padding: 5}}>
<a href='#' onClick={this.handleDataSkin} data-skin='skin-red' style={{display: "block", boxShadow: "0 0 3px rgba(0,0,0,0.4)"}} className='clearfix full-opacity-hover'>
<div><span style={{display:"block", width: "20%", float: "left", height: 7}} className="bg-red-active"></span><span className='bg-red' style={{display:"block", width: "80%", float: "left", height: 7}}></span></div>
<div><span style={{display:"block", width: "20%", float: "left", height: 20, background: "#222d32"}}></span><span style={{display:"block", width: "80%", float: "left", height: 20, background: "#f4f5f7"}}></span></div>
</a>
<p className='text-center no-margin'>Red</p>
</li>
<li style={{float:"left", width: "33.33333%", padding: 5}}>
<a href='#' onClick={this.handleDataSkin} data-skin='skin-yellow' style={{display: "block", boxShadow: "0 0 3px rgba(0,0,0,0.4)"}} className='clearfix full-opacity-hover'>
<div><span style={{display:"block", width: "20%", float: "left", height: 7}} className="bg-yellow-active"></span><span className='bg-yellow' style={{display:"block", width: "80%", float: "left", height: 7}}></span></div>
<div><span style={{display:"block", width: "20%", float: "left", height: 20, background: "#222d32"}}></span><span style={{display:"block", width: "80%", float: "left", height: 20, background: "#f4f5f7"}}></span></div>
</a>
<p className='text-center no-margin'>Yellow</p>
</li>
<li style={{float:"left", width: "33.33333%", padding: 5}}>
<a href='#' onClick={this.handleDataSkin} data-skin='skin-blue-light' style={{display: "block", boxShadow: "0 0 3px rgba(0,0,0,0.4)"}} className='clearfix full-opacity-hover'>
<div><span style={{display:"block", width: "20%", float: "left", height: 7, background: "#367fa9"}}></span><span className='bg-light-blue' style={{display:"block", width: "80%", float: "left", height: 7}}></span></div>
<div><span style={{display:"block", width: "20%", float: "left", height: 20, background: "#f9fafc"}}></span><span style={{display:"block", width: "80%", float: "left", height: 20, background: "#f4f5f7"}}></span></div>
</a>
<p className='text-center no-margin'>Blue Light</p>
</li>
<li style={{float:"left", width: "33.33333%", padding: 5}}>
<a href='#' onClick={this.handleDataSkin} data-skin='skin-black-light' style={{display: "block", boxShadow: "0 0 3px rgba(0,0,0,0.4)"}} className='clearfix full-opacity-hover'>
<div style={{boxShadow: "0 0 2px rgba(0,0,0,0.1)"}} className='clearfix'><span style={{display:"block", width: "20%", float: "left", height: 7, background: "#fefefe"}}></span><span style={{display:"block", width: "80%", float: "left", height: 7, background: "#fefefe"}}></span></div>
<div><span style={{display:"block", width: "20%", float: "left", height: 20, background: "#f9fafc"}}></span><span style={{display:"block", width: "80%", float: "left", height: 20, background: "#f4f5f7"}}></span></div>
</a>
<p className='text-center no-margin'>Black Light</p>
</li>
<li style={{float:"left", width: "33.33333%", padding: 5}}>
<a href='#' onClick={this.handleDataSkin} data-skin='skin-purple-light' style={{display: "block", boxShadow: "0 0 3px rgba(0,0,0,0.4)"}} className='clearfix full-opacity-hover'>
<div><span style={{display:"block", width: "20%", float: "left", height: 7}} className="bg-purple-active"></span><span className='bg-purple' style={{display:"block", width: "80%", float: "left", height: 7}}></span></div>
<div><span style={{display:"block", width: "20%", float: "left", height: 20, background: "#f9fafc"}}></span><span style={{display:"block", width: "80%", float: "left", height: 20, background: "#f4f5f7"}}></span></div>
</a>
<p className='text-center no-margin'>Purple Light</p>
</li>
<li style={{float:"left", width: "33.33333%", padding: 5}}>
<a href='#' onClick={this.handleDataSkin} data-skin='skin-green-light' style={{display: "block", boxShadow: "0 0 3px rgba(0,0,0,0.4)"}} className='clearfix full-opacity-hover'>
<div><span style={{display:"block", width: "20%", float: "left", height: 7}} className="bg-green-active"></span><span className='bg-green' style={{display:"block", width: "80%", float: "left", height: 7}}></span></div>
<div><span style={{display:"block", width: "20%", float: "left", height: 20, background: "#f9fafc"}}></span><span style={{display:"block", width: "80%", float: "left", height: 20, background: "#f4f5f7"}}></span></div>
</a>
<p className='text-center no-margin'>Green Light</p>
</li>
<li style={{float:"left", width: "33.33333%", padding: 5}}>
<a href='#' onClick={this.handleDataSkin} data-skin='skin-red-light' style={{display: "block", boxShadow: "0 0 3px rgba(0,0,0,0.4)"}} className='clearfix full-opacity-hover'>
<div><span style={{display:"block", width: "20%", float: "left", height: 7}} className="bg-red-active"></span><span className='bg-red' style={{display:"block", width: "80%", float: "left", height: 7}}></span></div>
<div><span style={{display:"block", width: "20%", float: "left", height: 20, background: "#f9fafc"}}></span><span style={{display:"block", width: "80%", float: "left", height: 20, background: "#f4f5f7"}}></span></div>
</a>
<p className='text-center no-margin'>Red Light</p>
</li>
<li style={{float:"left", width: "33.33333%", padding: 5}}>
<a href='#' onClick={this.handleDataSkin} data-skin='skin-yellow-light' style={{display: "block", boxShadow: "0 0 3px rgba(0,0,0,0.4)"}} className='clearfix full-opacity-hover'>
<div><span style={{display:"block", width: "20%", float: "left", height: 7}} className="bg-yellow-active"></span><span className='bg-yellow' style={{display:"block", width: "80%", float: "left", height: 7}}></span></div>
<div><span style={{display:"block", width: "20%", float: "left", height: 20, background: "#f9fafc"}}></span><span style={{display:"block", width: "80%", float: "left", height: 20, background: "#f4f5f7"}}></span></div>
</a>
<p className='text-center no-margin'>Yellow Light</p>
</li>
</ul>
<div className="form-group">
<input type="button" onClick={this.handleSaveBtn} className="btn btn-primary" style={{width: "100%"}} value="Save" />
</div>
</div>
{/*
<div className="tab-pane" id="control-sidebar-home-tab">
<h3 className="control-sidebar-heading">Recent Activity</h3>
<ul className="control-sidebar-menu">
<li>
<a href="#">
<i className="menu-icon fa fa-birthday-cake bg-red"></i>
<div className="menu-info">
<h4 className="control-sidebar-subheading">Langdons Birthday</h4>
<p>Will be 23 on April 24th</p>
</div>
</a>
</li>
<li>
<a href="#">
<i className="menu-icon fa fa-user bg-yellow"></i>
<div className="menu-info">
<h4 className="control-sidebar-subheading">Frodo Updated His Profile</h4>
<p>New phone +1(800)555-1234</p>
</div>
</a>
</li>
<li>
<a href="#">
<i className="menu-icon fa fa-envelope-o bg-light-blue"></i>
<div className="menu-info">
<h4 className="control-sidebar-subheading">Nora Joined Mailing List</h4>
<p>nora@example.com</p>
</div>
</a>
</li>
<li>
<a href="#">
<i className="menu-icon fa fa-file-code-o bg-green"></i>
<div className="menu-info">
<h4 className="control-sidebar-subheading">Cron Job 254 Executed</h4>
<p>Execution time 5 seconds</p>
</div>
</a>
</li>
</ul>
<h3 className="control-sidebar-heading">Tasks Progress</h3>
<ul className="control-sidebar-menu">
<li>
<a href="#">
<h4 className="control-sidebar-subheading">
Custom Template Design
<span className="label label-danger pull-right">70%</span>
</h4>
<div className="progress progress-xxs">
<div className="progress-bar progress-bar-danger" style={{width: "70%"}}></div>
</div>
</a>
</li>
<li>
<a href="#">
<h4 className="control-sidebar-subheading">
Update Resume
<span className="label label-success pull-right">95%</span>
</h4>
<div className="progress progress-xxs">
<div className="progress-bar progress-bar-success" style={{width: "95%"}}></div>
</div>
</a>
</li>
<li>
<a href="#">
<h4 className="control-sidebar-subheading">
Laravel Integration
<span className="label label-warning pull-right">50%</span>
</h4>
<div className="progress progress-xxs">
<div className="progress-bar progress-bar-warning" style={{width: "50%"}}></div>
</div>
</a>
</li>
<li>
<a href="#">
<h4 className="control-sidebar-subheading">
Back End Framework
<span className="label label-primary pull-right">68%</span>
</h4>
<div className="progress progress-xxs">
<div className="progress-bar progress-bar-primary" style={{width: "68%"}}></div>
</div>
</a>
</li>
</ul>
</div>
*/}
<div className="tab-pane" id="control-sidebar-stats-tab">Stats Tab Content</div>
<div className="tab-pane" id="control-sidebar-settings-tab">
<form method="post">
<h3 className="control-sidebar-heading">General Settings</h3>
<div className="form-group">
<label className="control-sidebar-subheading">
Report panel usage
<input type="checkbox" className="pull-right setting" data-setting="report-panel-usage" onChange={this.handleSetting} />
</label>
<p>
Some information about this general settings option
</p>
</div>
<div className="form-group">
<label className="control-sidebar-subheading">
Allow mail redirect
<input type="checkbox" className="pull-right setting" data-setting="allow-email-redirect" onChange={this.handleSetting}/>
</label>
<p>
Other sets of options are available
</p>
</div>
<div className="form-group">
<label className="control-sidebar-subheading">
Expose author name in posts
<input type="checkbox" className="pull-right setting" data-setting="expose-author-name" onChange={this.handleSetting}/>
</label>
<p>
Allow the user to show his name in blog posts
</p>
</div>
<h3 className="control-sidebar-heading">Chat Settings</h3>
<div className="form-group">
<label className="control-sidebar-subheading">
Show me as online
<input type="checkbox" className="pull-right setting" data-setting="show-as-online" onChange={this.handleSetting}/>
</label>
</div>
<div className="form-group">
<label className="control-sidebar-subheading">
Turn off notifications
<input type="checkbox" className="pull-right setting" data-setting="turn-off-notification" onChange={this.handleSetting}/>
</label>
</div>
<div className="form-group">
<label className="control-sidebar-subheading">
Delete chat history
<a href="#" className="text-red pull-right"><i className="fa fa-trash-o"></i></a>
</label>
</div>
</form>
</div>
</div>
</aside>
)
}
});
const mapStateToProps = function(state){
if (!_.isEmpty(state.header)) {
return _.head(state.header)
} else return {};
}
ControlSidebar = connect(mapStateToProps)(ControlSidebar);
ControlSidebar = withApollo(ControlSidebar);
export default ControlSidebar; |
app/containers/App/index.js | kenaku/react-boilerplate | /**
*
* App.react.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*/
import React from 'react'
import Helmet from 'react-helmet'
// Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder
import 'sanitize.css/sanitize.css'
import 'react-mdl/extra/material.min.css'
import 'react-mdl/extra/material'
import Footer from 'components/Footer'
import styles from './styles.css'
const App = (props) =>
<div className={styles.wrapper}>
<Helmet
titleTemplate="%s - React.js Boilerplate"
defaultTitle="React.js Boilerplate"
meta={[
{name: 'description', content: 'A React.js Boilerplate application'},
]}
/>
{props.children}
<Footer />
</div>
App.propTypes = {
children: React.PropTypes.node,
}
export default App
|
examples/huge-apps/routes/Course/routes/Announcements/components/Announcements.js | MattSPalmer/react-router | import React from 'react';
class Announcements extends React.Component {
render () {
return (
<div>
<h3>Announcements</h3>
{this.props.children || <p>Choose an announcement from the sidebar.</p>}
</div>
);
}
}
export default Announcements;
|
pootle/static/js/auth/components/SignInForm.js | unho/pootle | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import assign from 'object-assign';
import React from 'react';
import { gotoScreen, signIn } from '../actions';
import FormElement from 'components/FormElement';
import FormMixin from 'mixins/FormMixin';
const SignInForm = React.createClass({
propTypes: {
canRegister: React.PropTypes.bool.isRequired,
dispatch: React.PropTypes.func.isRequired,
formErrors: React.PropTypes.object.isRequired,
isLoading: React.PropTypes.bool.isRequired,
},
mixins: [FormMixin],
/* Lifecycle */
getInitialState() {
// XXX: initialData required by `FormMixin`; this is really OBSCURE
this.initialData = {
login: '',
password: '',
};
return {
formData: assign({}, this.initialData),
};
},
componentWillReceiveProps(nextProps) {
if (this.state.errors !== nextProps.formErrors) {
this.setState({ errors: nextProps.formErrors });
}
},
/* Handlers */
handleRequestPasswordReset(e) {
e.preventDefault();
this.props.dispatch(gotoScreen('requestPasswordReset'));
},
handleSignUp(e) {
e.preventDefault();
this.props.dispatch(gotoScreen('signUp'));
},
handleFormSubmit(e) {
e.preventDefault();
const nextURL = window.location.pathname + window.location.hash;
this.props.dispatch(signIn(this.state.formData, nextURL));
},
/* Others */
hasData() {
const { formData } = this.state;
return formData.login !== '' && formData.password !== '';
},
/* Layout */
render() {
const { errors } = this.state;
const { formData } = this.state;
const signUp = this.props.canRegister ?
<a href="#" onClick={this.handleSignUp}>
{gettext('Sign up as a new user')}
</a> :
<p>{gettext('Creating new user accounts is prohibited.')}</p>;
return (
<form
method="post"
onSubmit={this.handleFormSubmit}
>
<div className="fields">
<FormElement
autoFocus
label={gettext('Username')}
handleChange={this.handleChange}
name="login"
errors={errors.login}
value={formData.login}
dir="ltr"
/>
<FormElement
type="password"
label={gettext('Password')}
handleChange={this.handleChange}
name="password"
errors={errors.password}
value={formData.password}
dir="ltr"
/>
<div className="actions password-forgotten">
<a href="#" onClick={this.handleRequestPasswordReset}>
{gettext('I forgot my password')}
</a>
</div>
{this.renderAllFormErrors()}
</div>
<div className="actions">
<div>
<input
type="submit"
className="btn btn-primary"
disabled={!this.hasData() || this.props.isLoading}
value={gettext('Sign In')}
/>
</div>
<div>
{signUp}
</div>
</div>
</form>
);
},
});
export default SignInForm;
|
src/ButtonLayout/ButtonLayout.js | nirhart/wix-style-react | import React from 'react';
import styles from './ButtonLayout.scss';
import classNames from 'classnames';
const ButtonLayout = props => {
const {theme, hover, active, disabled, height, children} = props;
const className = classNames({
[styles.button]: true,
[styles[theme]]: true,
[styles.hover]: hover,
[styles.active]: active,
[styles.disabled]: disabled,
[styles[`height${height}`]]: height !== 'medium'
}, children.props.className);
const _style = Object.assign({},
children.props.style,
{
height,
display: 'inline-block'
}
);
if (React.Children.count(children) === 1) {
return React.cloneElement(
children,
{className, style: _style},
<div className={styles.inner}>
{children.props.children}
</div>
);
}
};
ButtonLayout.defaultProps = {
theme: 'fullblue',
height: 'medium'
};
ButtonLayout.propTypes = {
theme: React.PropTypes.oneOf([
'transparent',
'fullred',
'fullgreen',
'fullpurple',
'emptyred',
'emptygreen',
'emptybluesecondary',
'emptyblue',
'emptypurple',
'fullblue',
'transparentblue',
'whiteblue',
'whiteblueprimary',
'whitebluesecondary',
'close-standard',
'close-dark',
'close-transparent',
'icon-greybackground',
'icon-standard',
'icon-standardsecondary',
'icon-white',
'icon-whitesecondary'
]),
height: React.PropTypes.oneOf(['small', 'medium', 'large']),
hover: React.PropTypes.bool,
active: React.PropTypes.bool,
disabled: React.PropTypes.bool,
children: React.PropTypes.any,
};
ButtonLayout.displayName = 'ButtonLayout';
export default ButtonLayout;
|
src/svg-icons/device/signal-cellular-2-bar.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalCellular2Bar = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M2 22h20V2z"/><path d="M14 10L2 22h12z"/>
</SvgIcon>
);
DeviceSignalCellular2Bar = pure(DeviceSignalCellular2Bar);
DeviceSignalCellular2Bar.displayName = 'DeviceSignalCellular2Bar';
export default DeviceSignalCellular2Bar;
|
src/public/components/toolbox/item/file/copy.js | Harrns/segta | import React from 'react'
import copy from 'copy-to-clipboard'
import ListItem from '../default'
import { CopyIcon } from '../../../image/svg'
export default class CopyToolboxItem extends React.Component {
constructor (props) {
super(props)
this.state = {}
this.initState(props)
}
initState (props) {
Object.assign(this.state, {
disabled: props.file.download === null
})
}
componentWillReceiveProps (props) {
this.initState(props)
}
handleClick () {
copy(window.location.origin + this.props.file.copy)
}
render () {
return (
<ListItem
disabled={this.state.disabled}
id="copy" text="Copy link"
icon={CopyIcon}
onClick={() => this.handleClick()}/>
)
}
}
CopyToolboxItem.defaultProps = {
file: {
name: 'file',
type: 'file',
locked: true,
downloadCount: 0,
size: 0,
childs: [],
url: '/folder',
download: null
}
}
|
src/components/ShareExperience/common/CompanyQuery.js | goodjoblife/GoodJobShare | import React from 'react';
import PropTypes from 'prop-types';
import AutoCompleteTextInput from 'common/form/AutoCompleteTextInput';
import { debounce } from 'utils/streamUtils';
import InputTitle from './InputTitle';
import { getCompaniesSearch } from '../../../apis/companySearchApi';
const getItemValue = item => item.label;
const mapToAutocompleteList = l => ({
label: Array.isArray(l.name) ? l.name[0] : l.name,
value: l.id,
});
class CompanyQuery extends React.Component {
constructor(props) {
super(props);
this.handleAutocompleteItems = this.handleAutocompleteItems.bind(this);
this.state = {
autocompleteItems: [],
};
}
search = debounce((e, value) => {
if (value) {
return getCompaniesSearch({ key: value })
.then(r =>
Array.isArray(r)
? this.handleAutocompleteItems(r.map(mapToAutocompleteList))
: this.handleAutocompleteItems([]),
)
.catch(() => this.handleAutocompleteItems([]));
}
return this.handleAutocompleteItems([]);
}, 800);
handleOnChange = (e, value) => {
this.props.onChange(e.target.value);
return this.search(e, value);
};
handleAutocompleteItems(autocompleteItems) {
return this.setState(() => ({
autocompleteItems,
}));
}
render() {
const { autocompleteItems } = this.state;
const {
companyQuery,
onChange,
onCompanyId,
validator,
submitted,
} = this.props;
return (
<div>
<InputTitle text="公司名稱" must />
<AutoCompleteTextInput
placeholder="OO 股份有限公司"
value={companyQuery}
getItemValue={getItemValue}
items={autocompleteItems}
onChange={this.handleOnChange}
onSelect={(value, item) => {
this.handleAutocompleteItems([]);
onCompanyId(item.value);
return onChange(value);
}}
isWarning={submitted && !validator(companyQuery)}
warningWording="需填寫公司/單位"
/>
</div>
);
}
}
CompanyQuery.propTypes = {
companyQuery: PropTypes.string,
onChange: PropTypes.func,
onCompanyId: PropTypes.func,
validator: PropTypes.func,
submitted: PropTypes.bool,
};
CompanyQuery.defaultProps = {
validator: () => {},
};
export default CompanyQuery;
|
src/Well.js | Lucifier129/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import bootstrapUtils, { bsSizes, bsClass } from './utils/bootstrapUtils';
import { Sizes } from './styleMaps';
@bsClass('well')
@bsSizes([Sizes.LARGE, Sizes.SMALL])
class Well extends React.Component {
render() {
let classes = bootstrapUtils.getClassSet(this.props);
return (
<div {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
</div>
);
}
}
export default Well;
|
App/Containers/APITestingScreen.js | HyphenateInc/hyphenate-react-native | // @flow
// An All Components Screen is a great way to dev and quick-test components
import React from 'react'
import { ScrollView, View, Text, TouchableOpacity, Image } from 'react-native'
import { Metrics, Images } from '../Themes'
import FullButton from '../Components/FullButton'
// For API
import API from '../Services/Api'
import FJSON from 'format-json'
// Styles
import styles from './Styles/APITestingScreenStyle'
// API buttons here:
const endpoints = [
{ label: 'Get City (Boise)', endpoint: 'getCity', args: ['Boise'] },
{ label: 'Get City (Toronto)', endpoint: 'getCity', args: ['Toronto'] }
];
export default class APITestingScreen extends React.Component {
api: Object;
state: {
visibleHeight: number
};
constructor (props: Object) {
super(props);
this.state = {
visibleHeight: Metrics.screenHeight
};
this.api = API.create()
}
showResult (response: Object, title: string = 'Response') {
this.refs.container.scrollTo({x: 0, y: 0, animated: true});
if (response.ok) {
this.refs.result.setState({message: FJSON.plain(response.data), title: title})
} else {
this.refs.result.setState({message: `${response.problem} - ${response.status}`, title: title})
}
}
tryEndpoint (apiEndpoint: Object) {
const { label, endpoint, args = [''] } = apiEndpoint;
this.api[endpoint].apply(this, args).then((result) => {
this.showResult(result, label || `${endpoint}(${args.join(', ')})`)
})
}
renderButton (apiEndpoint: Object) {
const { label, endpoint, args = [''] } = apiEndpoint;
return (
<FullButton text={label || `${endpoint}(${args.join(', ')})`} onPress={this.tryEndpoint.bind(this, apiEndpoint)} styles={{marginTop: 10}} key={`${endpoint}-${args.join('-')}`} />
)
}
renderButtons () {
return endpoints.map((endpoint) => this.renderButton(endpoint))
}
render () {
return (
<View style={styles.mainContainer}>
<Image source={Images.background} style={styles.backgroundImage} resizeMode='stretch' />
<ScrollView style={styles.container} ref='container'>
<View style={styles.section}>
<Text style={styles.sectionText}>
Testing API with Postman or APIary.io verifies the server works.
The API Test screen is the next step; a simple in-app way to verify and debug your in-app API functions.
</Text>
<Text style={styles.sectionText}>
Create new endpoints in Services/Api.js then add example uses to endpoints array in Containers/APITestingScreen.js
</Text>
</View>
{this.renderButtons()}
<APIResult ref='result' />
</ScrollView>
</View>
)
}
}
class APIResult extends React.Component {
state: {
message: boolean,
title: boolean
};
constructor (props) {
super(props);
this.state = {
message: false,
title: false
}
}
onApiPress = () => {
this.setState({message: false})
};
renderView () {
return (
<ScrollView style={{ top: 0, bottom: 0, left: 0, right: 0, position: 'absolute' }} overflow='hidden'>
<TouchableOpacity
style={{backgroundColor: 'white', padding: 20}}
onPress={this.onApiPress}
>
<Text>{this.state.title} Response:</Text>
<Text allowFontScaling={false} style={{fontFamily: 'CourierNewPS-BoldMT', fontSize: 10}}>
{this.state.message}
</Text>
</TouchableOpacity>
</ScrollView>
)
}
render () {
let messageView = null;
if (this.state.message) {
return this.renderView()
}
return messageView
}
}
|
src/utils/ValidComponentChildren.js | cgvarela/react-bootstrap | import React from 'react';
/**
* Maps children that are typically specified as `props.children`,
* but only iterates over children that are "valid components".
*
* The mapFunction provided index will be normalised to the components mapped,
* so an invalid component would not increase the index.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} mapFunction.
* @param {*} mapContext Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapValidComponents(children, func, context) {
let index = 0;
return React.Children.map(children, child => {
if (React.isValidElement(child)) {
let lastIndex = index;
index++;
return func.call(context, child, lastIndex);
}
return child;
});
}
/**
* Iterates through children that are typically specified as `props.children`,
* but only iterates over children that are "valid components".
*
* The provided forEachFunc(child, index) will be called for each
* leaf child with the index reflecting the position relative to "valid components".
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc.
* @param {*} forEachContext Context for forEachContext.
*/
function forEachValidComponents(children, func, context) {
let index = 0;
return React.Children.forEach(children, child => {
if (React.isValidElement(child)) {
func.call(context, child, index);
index++;
}
});
}
/**
* Count the number of "valid components" in the Children container.
*
* @param {?*} children Children tree container.
* @returns {number}
*/
function numberOfValidComponents(children) {
let count = 0;
React.Children.forEach(children, child => {
if (React.isValidElement(child)) { count++; }
});
return count;
}
/**
* Determine if the Child container has one or more "valid components".
*
* @param {?*} children Children tree container.
* @returns {boolean}
*/
function hasValidComponent(children) {
let hasValid = false;
React.Children.forEach(children, child => {
if (!hasValid && React.isValidElement(child)) {
hasValid = true;
}
});
return hasValid;
}
function find(children, finder) {
let child;
forEachValidComponents(children, (c, idx) => {
if (!child && finder(c, idx, children)) {
child = c;
}
});
return child;
}
export default {
map: mapValidComponents,
forEach: forEachValidComponents,
numberOf: numberOfValidComponents,
find,
hasValidComponent
};
|
src/pages/Charts/UserBehavior.js | chaitanya1375/Myprojects | import React from 'react';
import Chart from 'react-chartist';
let data = {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
series: [
[542, 443, 320, 780, 553, 453, 326, 434, 568, 610, 756, 895],
[412, 243, 280, 580, 453, 353, 300, 364, 368, 410, 636, 695]
]
};
let options = {
seriesBarDistance: 10,
axisX: {
showGrid: false
},
height: "245px"
};
let responsiveOptions = [
['screen and (max-width: 640px)', {
seriesBarDistance: 5,
axisX: {
labelInterpolationFnc: function (value) {
return value[0];
}
}
}]
];
const UserBehaviorChart = () => (
<div className="card ">
<div className="header">
<h4>2014 Sales</h4>
<p className="category">All products including Taxes</p>
</div>
<div className="content">
<Chart data={data} options={options} responsiveOptions={responsiveOptions} type="Bar" className="ct-chart" />
<div className="footer">
<div className="legend">
<i className="fa fa-circle text-info"></i> Tesla Model S
<i className="fa fa-circle text-danger"></i> BMW 5 Series
</div>
<hr />
<div className="stats">
<i className="fa fa-check"></i> Data information certified
</div>
</div>
</div>
</div>
);
export default UserBehaviorChart; |
examples/todos/index.js | mikekidder/redux | import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import todoApp from './reducers'
import App from './components/App'
let store = createStore(todoApp)
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
|
demo/sections/BasicSection.js | affinipay/react-bootstrap-autosuggest | import React from 'react'
import { Alert } from 'react-bootstrap'
import Autosuggest from 'react-bootstrap-autosuggest'
import Anchor from './Anchor'
import Playground from './Playground'
const NamePrefix = require('raw-loader!../examples/NamePrefix').trim()
const scope = { Autosuggest }
export default function BasicSection() {
return (
<div>
<h3><Anchor id="basic">Basic usage</Anchor></h3>
<p>
In its most basic usage, <code><Autosuggest></code> acts like an
<code><input></code> combined with a
<a href="https://www.w3.org/TR/html5/forms.html#the-datalist-element"><code><datalist></code></a>
(introduced in HTML5 but not yet supported by all browsers).
The user is free to type any value, but a drop-down menu is available
that will suggest predefined options containing the input text.
</p>
<p>
In this <a href="http://notes.ericwillis.com/2009/11/common-name-prefixes-titles-and-honorifics/">name prefix</a> example,
typing <kbd>m</kbd> will suggest completions of "Mr.", "Mrs.", or "Ms.",
though you are still free to type less common prefixes like "Maj." or "Msgr.".
Standard <code><input></code> attributes like <code>placeholder</code> are
propagated to the underlying input element.
</p>
<Playground code={NamePrefix} scope={scope} showCode={true}
ribbonText={<a href="#playground">Edit Me!</a>} />
<Alert bsStyle="info">
For instructions on installing and importing Autosuggest within your project,
see the <a href="https://github.com/affinipay/react-bootstrap-autosuggest/blob/master/README.md">README</a>.
</Alert>
<p>
Note that just like a React input element, an Autosuggest without a <code>value</code> property is
an <a href="https://facebook.github.io/react/docs/forms.html#uncontrolled-components">uncontrolled component</a>.
It starts off with an empty value and immediately reflects any user input.
To listen to updates on the value, use the <code>onChange</code> event, as
is done with <a href="https://facebook.github.io/react/docs/forms.html#controlled-components">controlled components</a>.
</p>
</div>
)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.