path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
web/client/components/composition/modal.js
firewow/firewow
/** * Imports */ import React from 'react'; export default class Modal extends React.Component { render () { var buttons = this.props.buttons.map(function(button, key) { return ( <a href="#!" key={key} className='waves-effect waves-light btn-flat white-text' onClick={button.callback}>{button.text}</a> ); }); return ( <div id={this.props.id} className={'modal modal-fixed-header' + (this.props.className ? ' ' + this.props.className : '')}> <div className={"modal-header " + this.props.headerColor}> <h4>{this.props.title}</h4> </div> <div className="modal-content"> {this.props.content} </div> <div className="modal-footer"> {buttons} </div> </div> ); } }
actor-apps/app-web/src/app/components/modals/invite-user/ContactItem.react.js
VikingDen/actor-platform
import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; import classnames from 'classnames'; import AvatarItem from 'components/common/AvatarItem.react'; const {addons: { PureRenderMixin }} = addons; @ReactMixin.decorate(PureRenderMixin) class ContactItem extends React.Component { static propTypes = { contact: React.PropTypes.object, onSelect: React.PropTypes.func, member: React.PropTypes.bool }; constructor(props) { super(props); } onSelect = () => { this.props.onSelect(this.props.contact); }; render() { const contact = this.props.contact; const contactClassName = classnames('contacts__list__item row', { 'contacts__list__item--member': this.props.member }); let controls; if (!this.props.member) { controls = <a className="material-icons" onClick={this.onSelect}>person_add</a>; } else { controls = <i className="material-icons">check</i>; } return ( <li className={contactClassName}> <AvatarItem image={contact.avatar} placeholder={contact.placeholder} size="small" title={contact.name}/> <div className="col-xs"> <span className="title"> {contact.name} </span> </div> <div className="controls"> {controls} </div> </li> ); } } export default ContactItem;
src/svg-icons/device/screen-rotation.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceScreenRotation = (props) => ( <SvgIcon {...props}> <path d="M16.48 2.52c3.27 1.55 5.61 4.72 5.97 8.48h1.5C23.44 4.84 18.29 0 12 0l-.66.03 3.81 3.81 1.33-1.32zm-6.25-.77c-.59-.59-1.54-.59-2.12 0L1.75 8.11c-.59.59-.59 1.54 0 2.12l12.02 12.02c.59.59 1.54.59 2.12 0l6.36-6.36c.59-.59.59-1.54 0-2.12L10.23 1.75zm4.6 19.44L2.81 9.17l6.36-6.36 12.02 12.02-6.36 6.36zm-7.31.29C4.25 19.94 1.91 16.76 1.55 13H.05C.56 19.16 5.71 24 12 24l.66-.03-3.81-3.81-1.33 1.32z"/> </SvgIcon> ); DeviceScreenRotation = pure(DeviceScreenRotation); DeviceScreenRotation.displayName = 'DeviceScreenRotation'; export default DeviceScreenRotation;
packages/material-ui-icons/src/RecordVoiceOver.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><circle cx="9" cy="9" r="4" /><path d="M9 15c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4zm7.76-9.64l-1.68 1.69c.84 1.18.84 2.71 0 3.89l1.68 1.69c2.02-2.02 2.02-5.07 0-7.27zM20.07 2l-1.63 1.63c2.77 3.02 2.77 7.56 0 10.74L20.07 16c3.9-3.89 3.91-9.95 0-14z" /></g> , 'RecordVoiceOver');
components/accounts/transaction.js
kylecarter/bank
import React from 'react' import Head from 'next/head' import underscore from 'underscore' const _ = underscore; export default class Transaction extends React.Component { constructor( props ) { super(); this.state = _.extend( {}, props ); } render() { return (<li className="panel panel-primary"> <style jsx>{` .panel-body h4 { margin-top: 0 } date { display: block } `}</style> <div className="panel-body"> <div className="row"> <div className="col-xs-6"> <h4>{ this.state.merchant }</h4> <date datetime={ this.state.date.toISOString() }>{ this.state.date.toLocaleDateString( 'en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' } ) }</date> <strong>Transaction Amount: { this.state.amount }</strong> </div> <div className="col-xs-6"> <em style={{ color: this.state.type == 'Credit' ? 'green' : 'red' }}>Current Balance: { this.state.current }</em> </div> </div> </div> </li>) } }
Client/index.android.js
oaml/RApp
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Button, Fetch, AsyncStorage, DeviceEventEmitter } from 'react-native'; export default class RApp extends Component { constructor(props) { super(props); this.IPAddress = '192.168.1.1'; try { AsyncStorage.getItem('@store:ip').then((value) => { if(value != null) { console.log(this.IPAddress); this.IPAddress = value; } }) } catch (error) { console.log(error); } this.checkConnection = this.checkConnection.bind(this); this.findHost = this.findHost.bind(this); } componentDidMount() { DeviceEventEmitter.addListener('link', function(e: Event) { this.sendCommand.bind(this, {command: 'openlink', link: e})(); }.bind(this)); } async checkConnection() { console.log(this.IPAddress); try { let response = await fetch('http://' + this.IPAddress + '/motion?phrase=marco' , { method: 'GET' }) if(response.status !== 200) { return false; } let responseJson = await response.json(); console.log(responseJson); if(responseJson.phrase !== 'polo') { return false; } return true; } catch(error) { console.log(error); } } findHost() { var initialIP = '192.168.1.'; var found = false; console.log('finding'); for(var i = 0;i < 256;i++) { if(found) { break; } fetch('http://' + initialIP + i + '/motion?phrase=marco', { method: 'GET', timeout: 100 }) .then((response) => { if(response.status === 200) { return response.json(); } }) .then((responseData) => { if(responseData.phrase === 'polo') { found = true; console.log(responseData.ip); this.IPAddress = responseData.ip; AsyncStorage.setItem('@store:ip', responseData.ip); } }) .catch((error) => { }) } } async sendCommand(commandObj) { let connectionAlive = await this.checkConnection(); console.log(connectionAlive); if(!connectionAlive) { this.findHost(); return; } fetch('http://' + this.IPAddress + '/command', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(commandObj) }) .then((response) => { //console.log(response) }) .catch((error) => { console.log(error); }) } render() { return ( <View style={styles.container}> <View style={styles.buttonView}> <Button title="Screen on" onPress={this.sendCommand.bind(this, {command: 'scron'})}/> </View> <View style={styles.buttonView}> <Button title="Screen off" onPress={this.sendCommand.bind(this, {command: 'scroff'})}/> </View> <View style={styles.buttonView}> <Button title="Volume+" onPress={this.sendCommand.bind(this, {command: 'volup'})}/> </View> <View style={styles.buttonView}> <Button title="Volume-" onPress={this.sendCommand.bind(this, {command: 'voldown'})}/> </View> <View style={styles.buttonView}> <Button title="Volume mute" onPress={this.sendCommand.bind(this, {command: 'volmute'})}/> </View> <View style={styles.buttonView}> <Button title="Shutdown" onPress={this.sendCommand.bind(this, {command: 'shutdown'})}/> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', backgroundColor: '#F5FCFF', }, buttonView: { width: '100%', marginBottom: 10, marginTop: 10 }, }); AppRegistry.registerComponent('RApp', () => RApp);
test/FormSpec.js
apkiernan/react-bootstrap
import React from 'react'; import $ from 'teaspoon'; import Form from '../src/Form'; import FormGroup from '../src/FormGroup'; describe('<Form>', () => { it('should support horizontal', () => { $( <Form horizontal className="my-form"> <FormGroup /> </Form> ) .shallowRender() .single('form.form-horizontal.my-form') .single(FormGroup); }); it('should support inline', () => { $( <Form inline className="my-form"> <FormGroup /> </Form> ) .shallowRender() .single('form.form-inline.my-form') .single(FormGroup); }); it('should support custom componentClass', () => { $( <Form componentClass="fieldset" horizontal className="my-form"> <FormGroup /> </Form> ) .shallowRender() .single('fieldset.form-horizontal.my-form') .single(FormGroup); }); });
src/components/SelectField.js
willianribeiro/react-selectfield
'use strict' import React from 'react' import ReactDOM from 'react-dom' const events = { pauseEvent (event) { event.stopPropagation() event.preventDefault() }, addEventsToDocument (eventMap) { Object.keys(eventMap).forEach((key) => { document.addEventListener(key, eventMap[key], false) }) }, removeEventsFromDocument (eventMap) { Object.keys(eventMap).forEach((key) => { document.removeEventListener(key, eventMap[key], false) }) }, targetIsDescendant (event, parent) { let node = event.target while (node !== null) { if (node === parent) return true node = node.parentNode } return false } } class SelectField extends React.Component { constructor () { super() this.state = { isOpened: false, selected: '' } this.toggle = this.toggle.bind(this) this.close = this.close.bind(this) this.clear = this.clear.bind(this) this.handleDocumentClick = this.handleDocumentClick.bind(this) this.getDocumentEvents = this.getDocumentEvents.bind(this) this.getLabel = this.getLabel.bind(this) } toggle () { this.setState({isOpened: !this.state.isOpened}) } close () { this.setState({isOpened: false}) } clear () { this.setState( {selected: ''}, this.handleOptionSelected.bind(this, '') ) } handleOptionClick (item) { this.setState( {selected: item}, this.handleOptionSelected.bind(this, item.value) ) } handleOptionSelected (value) { this.props.onChange(value) this.close() } getLabel () { if (this.state.selected) { return this.state.selected.label } } handleDocumentClick (event) { if (this.state.isOpened && !events.targetIsDescendant(event, ReactDOM.findDOMNode(this))) { this.setState({ isOpened: false }) } } getDocumentEvents () { return { click: this.handleDocumentClick, touchend: this.handleDocumentClick } } componentWillUpdate (nextProps, nextState) { if (!this.state.isOpened && nextState.isOpened) { events.addEventsToDocument(this.getDocumentEvents()) } } componentDidUpdate (prevProps, prevState) { if (prevState.isOpened && !this.state.isOpened) { events.removeEventsFromDocument(this.getDocumentEvents()) } } componentWillUnmount () { if (this.state.isOpened) { events.removeEventsFromDocument(this.getDocumentEvents()) } } render () { let { className, source, value, placeholder } = this.props className = className ? `${className} select-field` : 'select-field' className += this.state.isOpened ? ' is-opened' : '' className += this.state.selected ? ' is-selected' : '' const caretDown = ( <svg className='select-field__display-caret' fill='#383838' height='24' viewBox='0 0 24 24' width='24' xmlns='http://www.w3.org/2000/svg'> <path d='M7.41 7.84L12 12.42l4.59-4.58L18 9.25l-6 6-6-6z' /> <path d='M0-.75h24v24H0z' fill='none' /> </svg> ) const clearButton = ( <svg className='select-field__display-clear' onClick={this.clear} fill='#383838' height='18' viewBox='0 0 24 24' width='18' xmlns='http://www.w3.org/2000/svg'> <path d='M0 0h24v24H0z' fill='none' /> <path d='M14.59 8L12 10.59 9.41 8 8 9.41 10.59 12 8 14.59 9.41 16 12 13.41 14.59 16 16 14.59 13.41 12 16 9.41 14.59 8zM12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z' /> </svg> ) return ( <div className={className}> <div className='select-field__display' onClick={this.toggle} tabIndex='-1' ref={(display) => { this.display = display }}> <div className='select-field__display-placeholder'> {placeholder} </div> <div className='select-field__display-label'> {this.getLabel()} </div> <div className='select-field__display-input'> <input readOnly type='text' value={this.state.selected} ref={(input) => { this.input = input }} /> </div> {!this.state.selected && caretDown} {this.state.selected && clearButton} </div> <ul className='select-field__options'> { source.map(item => { let classNameItem classNameItem = 'select-field__option' classNameItem += item.value === value ? ' is-selected' : '' return ( <li key={item.value} className={classNameItem} onClick={this.handleOptionClick.bind(this, item)}> {item.label} </li> ) }) } </ul> </div> ) } } export default SelectField
docs/src/app/components/pages/get-started/RequiredKnowledge.js
w01fgang/material-ui
import React from 'react'; import Title from 'react-title-component'; import MarkdownElement from '../../MarkdownElement'; import requiredKnowledge from './required-knowledge.md'; const RequiredKnowledge = () => ( <div> <Title render={(previousTitle) => `Required Knowledge - ${previousTitle}`} /> <MarkdownElement text={requiredKnowledge} /> </div> ); export default RequiredKnowledge;
client2/src/components/ChannelPreview.js
mehrandabi/graphql-tutorial
import React from 'react'; import { gql, graphql } from 'react-apollo'; const ChannelPreview = ({ data: {loading, error, channel } }) => { if (loading) { return <p>Loading ...</p>; } if (error) { return <p>{error.message}</p>; } return ( <div> <div className="channelName"> {channel.name} </div> <div>Loading Messages</div> </div>); }; export const channelQuery = gql` query ChannelQuery($channelId : ID!) { channel(id: $channelId) { id name } } `; export default (graphql(channelQuery, { options: (props) => ({ variables: { channelId: props.channelId }, }), })(ChannelPreview));
packages/wix-style-react/src/TagList/TagListAction/TagListAction.js
wix/wix-style-react
import React from 'react'; import PropTypes from 'prop-types'; import Button from '../../Button'; import { st, classes } from '../TagList.st.css'; const TagListAction = ({ className, ...rest }) => ( <Button className={st(classes.item, className)} {...rest} /> ); TagListAction.displayName = 'TagListAction'; TagListAction.propTypes = { dataHook: PropTypes.string, children: PropTypes.node, onClick: PropTypes.func, }; TagListAction.defaultProps = { size: 'tiny', skin: 'inverted', }; export default TagListAction;
docs/src/examples/collections/Form/Variations/FormExampleUnstackable.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Button, Form } from 'semantic-ui-react' const FormExampleUnstackable = () => ( <Form unstackable> <Form.Group widths={2}> <Form.Input label='First name' placeholder='First name' /> <Form.Input label='Last name' placeholder='Last name' /> </Form.Group> <Form.Checkbox label='I agree to the Terms and Conditions' /> <Button type='submit'>Submit</Button> </Form> ) export default FormExampleUnstackable
containers/App.js
goominc/goommerce-seller-native
'use strict'; import React from 'react'; import { Dimensions, Image, StatusBar, StyleSheet, View } from 'react-native'; import { connect } from 'react-redux' import { authActions } from 'goommerce-redux'; import _ from 'lodash'; import TabNavigator from 'react-native-tab-navigator'; import Agreement from './Agreement'; import EmptyView from '../components/EmptyView'; import Navigator from '../components/Navigator'; import Signin from '../components/Signin'; import routes from '../routes'; const App = React.createClass({ getInitialState: function() { return { selectedTab: 'orders', showTabBar: true, ordersNavigatorKey: Date.now(), settledNavigatorKey: Date.now(), productsNavigatorKey: Date.now(), }; }, componentDidMount() { const { auth, whoami } = this.props; if (auth.bearer && !auth.email) { whoami(); } }, render() { const { auth: { bearer, email, roles, data } } = this.props; if (!bearer) { return <Signin signin={this.signin} />; } if (!email) { return <EmptyView text={'Loading...'} />; } const brands = _.filter(roles, (r) => r.type === 'owner' || r.type === 'staff').map((r) => r.brand); if (brands.length === 0) { return <EmptyView text={'Not brand owner...'} />; } if (_.get(data, 'agreements.seller', 0) < 1 || _.get(data, 'agreements.personalInfomation', 0) < 1) { return <Agreement />; } const brandId = brands[0].id; const tabBarStyle = [styles.tabBarStyle]; const sceneStyle = []; if (!this.state.showTabBar) { tabBarStyle.push({ position: 'absolute', top: Dimensions.get('window').height }); sceneStyle.push({ paddingBottom: 0 }); } const showTabBar = (show) => this.setState({ showTabBar: show }); return ( <View style={{ flex: 1 }}> <StatusBar barStyle="light-content" /> <TabNavigator tabBarStyle={tabBarStyle} sceneStyle={sceneStyle}> <TabNavigator.Item renderIcon={() => <Image source={require('./images/tab_order.png')} style={styles.icon}/>} title="주문조회" selected={this.state.selectedTab === 'orders'} onPress={() => { this.setState({ selectedTab: 'orders', ordersNavigatorKey: Date.now() }); }}> <Navigator key={this.state.ordersNavigatorKey} initialRoute={routes.orders({ brandId })} /> </TabNavigator.Item> <TabNavigator.Item renderIcon={() => <Image source={require('./images/tab_settled.png')} style={styles.icon}/>} title="정산통계" selected={this.state.selectedTab === 'settled'} onPress={() => { this.setState({ selectedTab: 'settled', settledNavigatorKey: Date.now() }); }}> <Navigator key={this.state.settledNavigatorKey} initialRoute={routes.settled({ brandId })} showTabBar={showTabBar} /> </TabNavigator.Item> <TabNavigator.Item renderIcon={() => <Image source={require('./images/tab_product.png')} style={styles.icon}/>} title="상품관리" selected={this.state.selectedTab === 'products'} onPress={() => { this.setState({ selectedTab: 'products', productsNavigatorKey: Date.now() }); }}> <Navigator key={this.state.productsNavigatorKey} initialRoute={routes.products({ brandId })} /> </TabNavigator.Item> <TabNavigator.Item renderIcon={() => <Image source={require('./images/tab_profile.png')} style={styles.icon}/>} title="내 정보" selected={this.state.selectedTab === 'profile'} onPress={() => { this.setState({ selectedTab: 'profile' }); }}> <Navigator initialRoute={routes.profile({ brandId })} /> </TabNavigator.Item> </TabNavigator> </View> ); } }); const styles = StyleSheet.create({ icon: { transform: [{ translateY: 7 }], tintColor: '#b2b2b2', }, tabBarStyle: { backgroundColor: 'white', } }); export default connect( (state) => ({ auth: state.auth }), authActions )(App);
src/icons/Pound.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class Pound extends React.Component { render() { if(this.props.bare) { return <g> <g> <path d="M125.2,352.3H32v-54.6h101.2l13.1-83.3H47v-54.6h107.2L176,32h63.9l-21.8,127.7h105.6L345.5,32h63.1l-21.8,127.7H480v54.6 H378.1l-12.3,83.3H465v54.6H358.5L336,480h-63.1l21.8-127.7H188.3L166.5,480h-63.1L125.2,352.3z M209.4,214.3L197,297.7h105.6 l12.3-83.3H209.4z"></path> </g> </g>; } return <IconBase> <g> <path d="M125.2,352.3H32v-54.6h101.2l13.1-83.3H47v-54.6h107.2L176,32h63.9l-21.8,127.7h105.6L345.5,32h63.1l-21.8,127.7H480v54.6 H378.1l-12.3,83.3H465v54.6H358.5L336,480h-63.1l21.8-127.7H188.3L166.5,480h-63.1L125.2,352.3z M209.4,214.3L197,297.7h105.6 l12.3-83.3H209.4z"></path> </g> </IconBase>; } };Pound.defaultProps = {bare: false}
pages/_document.js
bmagic/acdh-client
import React from 'react' import Document, { Head, Main, NextScript } from 'next/document' import stylesheet from './styles.scss' export default class MyDocument extends Document { render () { return ( <html> <Head> <meta charSet='utf-8' /> <meta name='viewport' content='width=device-width, initial-scale=1' /> <style dangerouslySetInnerHTML={{ __html: stylesheet }} /> <link rel='icon' type='image/png' href='/static/img/favicon/favicon-16x16.png' sizes='16x16' /> <link rel='icon' type='image/png' href='/static/img/favicon/favicon-32x32.png' sizes='32x32' /> <link rel='icon' type='image/png' href='/static/img/favicon/favicon-96x96.png' sizes='96x96' /> </Head> <body> <Main /> <NextScript /> </body> </html> ) } }
blueocean-material-icons/src/js/components/svg-icons/action/delete.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionDelete = (props) => ( <SvgIcon {...props}> <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/> </SvgIcon> ); ActionDelete.displayName = 'ActionDelete'; ActionDelete.muiName = 'SvgIcon'; export default ActionDelete;
src/index.js
yvanbister/MurielvanCaster
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import App from './components/app'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware()(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <App /> </Provider> , document.querySelector('.container-fluid'));
client/src/javascript/components/sidebar/SidebarFilter.js
stephdewit/flood
import classnames from 'classnames'; import {injectIntl} from 'react-intl'; import React from 'react'; import Badge from '../general/Badge'; const METHODS_TO_BIND = ['handleClick']; class SidebarFilter extends React.Component { constructor() { super(); METHODS_TO_BIND.forEach(method => { this[method] = this[method].bind(this); }); } handleClick() { this.props.handleClick(this.props.slug); } render() { const classNames = classnames('sidebar-filter__item', { 'is-active': this.props.isActive, }); let {name} = this.props; if (this.props.name === 'all') { name = this.props.intl.formatMessage({ id: 'filter.all', defaultMessage: 'All', }); } else if (this.props.name === 'untagged') { name = this.props.intl.formatMessage({ id: 'filter.untagged', defaultMessage: 'Untagged', }); } return ( <li className={classNames} onClick={this.handleClick}> {this.props.icon} {name} <Badge>{this.props.count}</Badge> </li> ); } } export default injectIntl(SidebarFilter);
src/components/Containers.react.js
lzbgt/kitematic
import $ from 'jquery'; import _ from 'underscore'; import React from 'react'; import Router from 'react-router'; import containerStore from '../stores/ContainerStore'; import ContainerList from './ContainerList.react'; import Header from './Header.react'; import metrics from '../utils/MetricsUtil'; import shell from 'shell'; import machine from '../utils/DockerMachineUtil'; var Containers = React.createClass({ contextTypes: { router: React.PropTypes.func }, getInitialState: function () { return { sidebarOffset: 0, containers: containerStore.getState().containers, sorted: this.sorted(containerStore.getState().containers) }; }, componentDidMount: function () { containerStore.listen(this.update); }, componentDidUnmount: function () { containerStore.unlisten(this.update); }, sorted: function (containers) { return _.values(containers).sort(function (a, b) { if (a.State.Downloading && !b.State.Downloading) { return -1; } else if (!a.State.Downloading && b.State.Downloading) { return 1; } else { if (a.State.Running && !b.State.Running) { return -1; } else if (!a.State.Running && b.State.Running) { return 1; } else { return a.Name.localeCompare(b.Name); } } }); }, update: function () { let containers = containerStore.getState().containers; let sorted = this.sorted(containerStore.getState().containers); let name = this.context.router.getCurrentParams().name; if (containerStore.getState().pending) { this.context.router.transitionTo('pull'); } else if (name && !containers[name]) { if (sorted.length) { this.context.router.transitionTo('containerHome', {name: sorted[0].Name}); } else { this.context.router.transitionTo('search'); } } this.setState({ containers: containers, sorted: sorted, pending: containerStore.getState().pending }); }, handleScroll: function (e) { if (e.target.scrollTop > 0 && !this.state.sidebarOffset) { this.setState({ sidebarOffset: e.target.scrollTop }); } else if (e.target.scrollTop === 0 && this.state.sidebarOffset) { this.setState({ sidebarOffset: 0 }); } }, handleNewContainer: function () { $(this.getDOMNode()).find('.new-container-item').parent().fadeIn(); this.context.router.transitionTo('new'); metrics.track('Pressed New Container'); }, handleClickPreferences: function () { metrics.track('Opened Preferences', { from: 'app' }); this.context.router.transitionTo('preferences'); }, handleClickDockerTerminal: function () { metrics.track('Opened Docker Terminal', { from: 'app' }); machine.dockerTerminal(); }, handleClickReportIssue: function () { metrics.track('Opened Issue Reporter', { from: 'app' }); shell.openExternal('https://github.com/kitematic/kitematic/issues/new'); }, handleMouseEnterDockerTerminal: function () { this.setState({ currentButtonLabel: 'Open terminal to use Docker command line.' }); }, handleMouseLeaveDockerTerminal: function () { this.setState({ currentButtonLabel: '' }); }, handleMouseEnterReportIssue: function () { this.setState({ currentButtonLabel: 'Report an issue or suggest feedback.' }); }, handleMouseLeaveReportIssue: function () { this.setState({ currentButtonLabel: '' }); }, handleMouseEnterPreferences: function () { this.setState({ currentButtonLabel: 'Change app preferences.' }); }, handleMouseLeavePreferences: function () { this.setState({ currentButtonLabel: '' }); }, render: function () { var sidebarHeaderClass = 'sidebar-header'; if (this.state.sidebarOffset) { sidebarHeaderClass += ' sep'; } var container = this.context.router.getCurrentParams().name ? this.state.containers[this.context.router.getCurrentParams().name] : {}; return ( <div className="containers"> <Header /> <div className="containers-body"> <div className="sidebar"> <section className={sidebarHeaderClass}> <h4>Containers</h4> <div className="create"> <Router.Link to="new"> <span className="btn btn-new btn-action has-icon btn-hollow"><span className="icon icon-add"></span>New</span> </Router.Link> </div> </section> <section className="sidebar-containers" onScroll={this.handleScroll}> <ContainerList containers={this.state.sorted} newContainer={this.state.newContainer} /> </section> <section className="sidebar-buttons"> <span className="btn-sidebar btn-terminal" onClick={this.handleClickDockerTerminal} onMouseEnter={this.handleMouseEnterDockerTerminal} onMouseLeave={this.handleMouseLeaveDockerTerminal}><span className="icon icon-docker-cli"></span><span className="text">DOCKER CLI</span></span> <span className="btn-sidebar btn-feedback" onClick={this.handleClickReportIssue} onMouseEnter={this.handleMouseEnterDockerTerminal} onMouseLeave={this.handleMouseLeaveDockerTerminal}><span className="icon icon-feedback"></span></span> <span className="btn-sidebar btn-preferences" onClick={this.handleClickPreferences} onMouseEnter={this.handleMouseEnterDockerTerminal} onMouseLeave={this.handleMouseLeaveDockerTerminal}><span className="icon icon-preferences"></span></span> </section> </div> <Router.RouteHandler pending={this.state.pending} containers={this.state.containers} container={container}/> </div> </div> ); } }); module.exports = Containers;
client/src/components/mainContainer.js
dstarr/sb-react-demo
import React from 'react'; import Header from './header'; import Navigation from './navigation'; import Body from './body'; export default class MainContainer extends React.Component { render = () => { return ( <div> <Header text="The Finest Coffee on Earth" /> <Navigation navItemCallback={this.handleNav}/> <Body images={this.getPageImages()}/> </div> ); }; handleNav = (itemId) => { switch (itemId) { case 'responsibility': window.location.href = 'http://www.starbucks.com/responsibility'; break; case 'coffeehouse': window.location.href = 'http://www.starbucks.com/coffeehouse'; break; case 'blog': window.location.href = 'https://1912pike.com/'; break; default: alert('SELECTED NAV ITEM ' + itemId); } }; getPageImages = () => { return [ { path: './images/band1.jpg', link: 'http://www.starbucks.com/promo/tea' }, { path: './images/band2.png', link: 'http://www.starbucks.com/coffeehouse/' }, { path: './images/footer.png', link: '#' } ]; }; }
dist/Route.js
lin2jie2/react-hash-router
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; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React from 'react'; import PropTypes from 'prop-types'; import { observer, history } from './h'; // route var Route = function Route() {}; Route.propTypes = { path: PropTypes.string.isRequired, component: PropTypes.func.isRequired }; export default Route; // route container export var Container = function (_React$Component) { _inherits(Container, _React$Component); function Container() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Container); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Container.__proto__ || Object.getPrototypeOf(Container)).call.apply(_ref, [this].concat(args))), _this), _this.shouldComponentUpdate = function (nextProps) { if (JSON.stringify(nextProps.context) === JSON.stringify(_this.props.context) && nextProps.component === _this.props.component) { if (nextProps.style.transform !== _this.props.style.transform) { Object.keys(nextProps.style).forEach(function (name) { _this.container.style[name] = nextProps.style[name]; }); } return false; } return true; }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Container, [{ key: 'render', value: function render() { var _this2 = this; var _props = this.props, style = _props.style, context = _props.context, component = _props.component; var Component = component; return React.createElement( 'div', { style: style, 'data-uri': context.uri, ref: function ref(_ref2) { _this2.container = _ref2; } }, React.createElement(Component, { context: _extends({}, context, { observer: observer, navigateTo: history.navigateTo, backTo: history.backTo, replaceWith: history.replaceWith }), key: context.uri }) ); } }]); return Container; }(React.Component); Container.propTypes = { component: PropTypes.func.isRequired, context: PropTypes.shape() }; Container.defaultProps = { context: {} };
fixtures/fiber-debugger/src/index.js
tomocchino/react
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render(<App />, document.getElementById('root'));
docs/src/sections/ImageSection.js
mmarcant/react-bootstrap
import React from 'react'; import Anchor from '../Anchor'; import PropTable from '../PropTable'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function ImageSection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="images">Images</Anchor> <small>Image</small> </h2> <h3><Anchor id="image-shape">Shape</Anchor></h3> <p>Use the <code>rounded</code>, <code>circle</code> and <code>thumbnail</code> props to customise the image.</p> <ReactPlayground codeText={Samples.ImageShape} /> <h3><Anchor id="image-responsive">Responsive</Anchor></h3> <p>Use the <code>responsive</code> to scale image nicely to the parent element.</p> <ReactPlayground codeText={Samples.ImageResponsive} /> <h3><Anchor id="image-props">Props</Anchor></h3> <PropTable component="Image"/> </div> ); }
addons/info/src/components/markdown/htags.js
enjoylife/storybook
import React from 'react'; import PropTypes from 'prop-types'; import { baseFonts } from '../theme'; const defaultProps = { children: null, id: null, }; const propTypes = { children: PropTypes.node, id: PropTypes.string, }; export function H1(props) { const styles = { ...baseFonts, borderBottom: '1px solid #eee', fontWeight: 600, margin: 0, padding: 0, fontSize: '40px', }; return <h1 id={props.id} style={styles}>{props.children}</h1>; } H1.defaultProps = defaultProps; H1.propTypes = propTypes; export function H2(props) { const styles = { ...baseFonts, fontWeight: 600, margin: 0, padding: 0, fontSize: '30px', }; return <h2 id={props.id} style={styles}>{props.children}</h2>; } H2.defaultProps = defaultProps; H2.propTypes = propTypes; export function H3(props) { const styles = { ...baseFonts, fontWeight: 600, margin: 0, padding: 0, fontSize: '22px', textTransform: 'uppercase', }; return <h3 id={props.id} style={styles}>{props.children}</h3>; } H3.defaultProps = defaultProps; H3.propTypes = propTypes; export function H4(props) { const styles = { ...baseFonts, fontWeight: 600, margin: 0, padding: 0, fontSize: '20px', }; return <h4 id={props.id} style={styles}>{props.children}</h4>; } H4.defaultProps = defaultProps; H4.propTypes = propTypes; export function H5(props) { const styles = { ...baseFonts, fontWeight: 600, margin: 0, padding: 0, fontSize: '18px', }; return <h5 id={props.id} style={styles}>{props.children}</h5>; } H5.defaultProps = defaultProps; H5.propTypes = propTypes; export function H6(props) { const styles = { ...baseFonts, fontWeight: 400, margin: 0, padding: 0, fontSize: '18px', }; return <h6 id={props.id} style={styles}>{props.children}</h6>; } H6.defaultProps = defaultProps; H6.propTypes = propTypes;
client/src/routes.js
saltypaul/SnipTodo
/** * This module defines route rules within the app. * */ import React from 'react'; import { Provider } from 'react-redux'; import configureStore from './store'; import { Router, Route, hashHistory, IndexRoute } from 'react-router'; import { Home, Welcome, Archive } from './components'; import { TodoListContainer } from './containers'; // THE only store for the whole app. const store = configureStore(); const routes = ( /** * Pass store to Provider, * making store available to all wrapped components. * * The URL structure: * / ==> Home/Welcome * /todolist ==> Archive/TodosContainer */ <Provider store={store}> <Router history={hashHistory}> <Route path="/" component={Home}> <IndexRoute component={Welcome} /> </Route> <Route path="/todolist" component={Archive}> <IndexRoute component={TodoListContainer}/> </Route> </Router> </Provider> ); export default routes;
js/BaseComponents/Input.js
telldus/telldus-live-mobile-v3
/** * Copyright 2016-present Telldus Technologies AB. * * This file is part of the Telldus Live! app. * * Telldus Live! app is free : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Telldus Live! app is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Telldus Live! app. If not, see <http://www.gnu.org/licenses/>. */ // @flow 'use strict'; import React from 'react'; import { View, TextInput } from 'react-native'; import Base from './Base'; import computeProps from './computeProps'; type Props = { placeholderTextColor: ?string, }; export default class Input extends Base { props: Props; getInitialStyle(): Object { return { input: { height: this.getTheme().inputHeightBase, color: this.getTheme().inputColor, paddingLeft: 5, paddingRight: 5, fontSize: this.getTheme().inputFontSize, lineHeight: this.getTheme().inputLineHeight, }, }; } prepareRootProps(): Object { let defaultProps = { style: this.getInitialStyle().input, }; return computeProps(this.props, defaultProps); } render(): React$Element<any> { return ( <View style={{ flex: 1 }}> <TextInput {...this.prepareRootProps()} placeholderTextColor={this.props.placeholderTextColor ? this.props.placeholderTextColor : this.getTheme().inputColorPlaceholder} underlineColorAndroid="rgba(0,0,0,0)"/> </View> ); } }
src/routes/home/index.js
willchertoff/Ben-Kinde
/** * 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 Home from './Home'; import Layout from '../../components/Layout'; async function action() { return { chunks: ['home'], title: 'Ben Kinde', component: <Layout><Home /></Layout>, }; } export default action;
src/index.js
roycejewell/flux-ui-example
import React from 'react'; import ReactDOM from 'react-dom'; import Router from 'react-router'; import createBrowserHistory from 'history/lib/createBrowserHistory'; import routes from './routes.js'; import 'styles/styles.css'; const router = { routes, history: createBrowserHistory(), createElement: (component, props) => { return React.createElement(component, { ...props }); } }; ReactDOM.render( React.createElement(Router, { ...router }), document.getElementById('root') );
src/containers/ChannelData/index.js
TerryCapan/twitchBot
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import SparklineChart from '../../components/SparklineChart'; import { getTone, unsetTone } from '../../actions/index'; /* component styles */ import { styles } from './styles.scss'; class ChannelData extends Component { constructor(props) { super(props); this.state = { currentMsgCount: 0, prevMinMsgCount: 0, prevSecMsgCount: 0, avgMsgPerMin: 0, avgMsgPerSec: 0, charCount: 0, avgLength: 0, lastMsg: '', time: new Date(), msgPerMinArray: [], msgLengthArray: [], msgPerSecArray: [], lastMinTotal: 0, lastSecTotal: 0, watsonString: '', }; } componentDidMount() { this.minuteInt = setInterval(() => { this.msgRateEveryMinute(); }, 60000); this.secondInt = setInterval(() => { this.msgRateEverySecond(); }, 1000); this.watsonInt = setInterval(() => { if (this.state.watsonString.length) { const currentWatsonString = this.state.watsonString; this.setState({ watsonString: '' }); this.props.getTone(currentWatsonString); } else { this.props.unsetTone(); } }, 3000); } componentWillReceiveProps(props) { this.calculateAverages(props); } componentWillUnmount() { clearInterval(this.minuteInt); clearInterval(this.secondInt); clearInterval(this.watsonInt); } msgRateEveryMinute() { const newCurrentCount = this.state.currentMsgCount; const lastMinMsgCount = newCurrentCount - this.state.prevMinMsgCount; const newMsgPerMinArray = this.state.msgPerMinArray.concat([lastMinMsgCount]); if (newMsgPerMinArray.length > 60) { newMsgPerMinArray.shift(); } this.setState({ prevMinMsgCount: newCurrentCount, msgPerMinArray: newMsgPerMinArray, lastMinTotal: lastMinMsgCount, }); } msgRateEverySecond() { const newCurrentCount = this.state.currentMsgCount; const lastSecMsgCount = newCurrentCount - this.state.prevSecMsgCount; const newMsgPerSecArray = this.state.msgPerSecArray.concat([lastSecMsgCount]); if (newMsgPerSecArray.length > 60) { newMsgPerSecArray.shift(); } this.setState({ prevSecMsgCount: newCurrentCount, msgPerSecArray: newMsgPerSecArray, lastSecTotal: lastSecMsgCount, }); } calculateAverages(props) { let newCount; let newAvgLength; let newCharCount; let newWatsonString; const elapsedMinutes = (Math.abs(new Date() - this.state.time)) / 60000; const elapsedSeconds = (Math.abs(new Date() - this.state.time)) / 1000; if (this.state.lastMsg !== props.message) { newWatsonString = this.state.watsonString.concat(props.message); newCount = this.state.currentMsgCount + 1; newCharCount = this.state.charCount + props.message.length; newAvgLength = newCharCount / newCount; } else { newWatsonString = this.state.watsonString; newCount = this.state.currentMsgCount; newCharCount = this.state.charCount; newAvgLength = this.state.avgLength; } const newMsgPerMin = newCount / elapsedMinutes; const newMsgPerSec = newCount / elapsedSeconds; const newMsgLengthArray = this.state.msgLengthArray.concat([props.message.length]); if (newMsgLengthArray.length > 200) { newMsgLengthArray.shift(); } this.setState({ currentMsgCount: newCount, avgMsgPerMin: newMsgPerMin, avgMsgPerSec: newMsgPerSec, charCount: newCharCount, avgLength: newAvgLength, lastMsg: props.message, msgLengthArray: newMsgLengthArray, watsonString: newWatsonString, }); } render() { return ( <section className={`${styles}`}> <div className="row"> <div className="col-md-4 col-md-push-8"> <section className="msg-data"> <h5>Average message length: {Math.round(this.state.avgLength)}</h5> <h5>Last message length: {this.state.lastMsg.length}</h5> <div className="msg-chart"><SparklineChart data={this.state.msgLengthArray} color="blue" limit={200} /></div> </section> </div> <div className="col-md-4"> <section className="msg-data"> <h5>Average Messages per Second: {(this.state.avgMsgPerSec).toFixed(2)}</h5> <h5>Last second's total: {this.state.lastSecTotal}</h5> <div className="msg-chart"><SparklineChart data={this.state.msgPerSecArray} color="green" limit={60} /></div> </section> </div> <div className="col-md-4 col-md-pull-8"> <section className="msg-data"> <h5>Average Messages per Minute: {Math.round(this.state.avgMsgPerMin)}</h5> <h5>Last minute's total: {this.state.lastMinTotal}</h5> <div className="msg-chart"><SparklineChart data={this.state.msgPerMinArray} color="red" limit={60} /></div> </section> </div> </div> <div className="row"> <span>Total Messages since arrival: {this.state.currentMsgCount}</span> </div> </section> ); } } ChannelData.propTypes = { getTone: React.PropTypes.func, unsetTone: React.PropTypes.func, }; function mapDispatchToProps(dispatch) { return bindActionCreators({ getTone, unsetTone }, dispatch); } export default connect(null, mapDispatchToProps)(ChannelData);
blueocean-material-icons/src/js/components/svg-icons/action/card-membership.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionCardMembership = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.11 0-2 .89-2 2v11c0 1.11.89 2 2 2h4v5l4-2 4 2v-5h4c1.11 0 2-.89 2-2V4c0-1.11-.89-2-2-2zm0 13H4v-2h16v2zm0-5H4V4h16v6z"/> </SvgIcon> ); ActionCardMembership.displayName = 'ActionCardMembership'; ActionCardMembership.muiName = 'SvgIcon'; export default ActionCardMembership;
app/components/CarsList/index.js
aditigoel23/React-Car-App
import React from 'react'; import _ from 'lodash'; import CarListItem from '../CarListItem/index'; import Wrapper from './Wrapper'; function CarsList(props) { const carTypes = _.get(props, 'metaData.CarTypes', []); let list = []; if (Array.isArray(props.items)) { list = _.map(props.items, (car) => <CarListItem key={car.ResultId} types={carTypes} item={car} /> ); } return ( <Wrapper> {list} </Wrapper> ); } CarsList.propTypes = { items: React.PropTypes.array, }; export default CarsList;
docs/src/examples/elements/Segment/Variations/SegmentExampleCompact.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Segment } from 'semantic-ui-react' const SegmentExampleCompact = () => <Segment compact>Compact content.</Segment> export default SegmentExampleCompact
imports/client/ui/components/HoursFormatted/index.js
focallocal/fl-maps
import React from 'react' import { formatDateWithWords, formatDate } from '/imports/client/utils/format' import { findNextEvent, calibrateEndWeekday } from '/imports/client/utils/findNextEvent' import './styles.scss' const HoursFormatted = ({ data }) => { const { startingDate, endingDate, startingTime, endingTime } = data if (data.multipleDays) { const isEnding = !!endingDate return ( <div className='hours-formatted multiple-days'> {isEnding && ( <div className='date'> {formatDateWithWords(startingDate)} - {formatDateWithWords(endingDate)} </div> )} {data.days.map((day, index) => ( (day && day.day) && <div key={index} className='day'> <div>{day.day.substr(0, 3)}</div> <span>{day.startingTime} - {day.endingTime}</span> </div> ))} </div> ) } const isSameDay = startingDate.toDateString() === endingDate.toDateString(); if (data.repeat) { const { days, every, forever, type, until, occurences, monthly, recurrenceEndDate } = data.recurring const weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] let daysOrdered = days if (days) daysOrdered = weekDays.filter((e) => days.indexOf(e) >= 0) let nextEventInstance = findNextEvent(startingDate, type, every, days, monthly) // DESCRIPTION: Reusable Fragment with timestamp on Next Occurence const nextOccurence = ( <li className='hours-formatted regular-date'> <span>Next:<br/> {formatDateWithWords(nextEventInstance)}<br/> {startingTime} - </span> {isSameDay ? endingTime : <div> {formatDateWithWords( new Date(Date.parse(nextEventInstance) + (endingDate.getTime() - startingDate.getTime())) )}, {endingTime} </div> } </li> ) // DESCRIPTION: Reusable Fragment with repetition details const repeatTitle = <span>Repeating:<br/></span> const repeatSchedule = `every ${every > 1 ? every : ''} ${type + (every > 1 ? 's' : '')}` const startingWeekday = startingDate.getDay() let endingWeekday = endingDate.getDay() if (daysOrdered) endingWeekday = weekDays.indexOf(daysOrdered[daysOrdered.length - 1]) const adjustedEndDate = calibrateEndWeekday(startingDate, endingDate, days, recurrenceEndDate) const notForeverDay = ( <div className='not-forever'> {(data.repeat && occurences) && `until ${formatDateWithWords(recurrenceEndDate)}`} {(data.repeat && until) && `until ${formatDateWithWords(until)}`} </div> ) const notForeverWeek = ( <div className='not-forever'> {(data.repeat && occurences && startingWeekday === endingWeekday) && `until ${formatDateWithWords(recurrenceEndDate)}`} {(data.repeat && occurences && startingWeekday !== endingWeekday) && `until ${formatDateWithWords(adjustedEndDate)}`} {(data.repeat && until) && `until ${formatDateWithWords(until)}`} </div> ) const notForeverMonth = ( <div className='not-forever'> {(data.repeat && occurences) && `through ${months[recurrenceEndDate.getMonth()]}`} {(data.repeat && until) && `through ${months[until.getMonth()]}`} </div> ) if (type === 'day') { return ( <ul className='hours-formatted repeat'> {(forever === true) && nextOccurence} {(!forever && recurrenceEndDate && new Date() < recurrenceEndDate) && nextOccurence} {(!forever && until && new Date() < until) && nextOccurence} <li>{repeatTitle} {repeatSchedule}, between {startingTime} - {endingTime} </li> {!forever && notForeverDay} </ul> ) } else if (type === 'week') { return ( <ul className='hours-formatted repeat'> {(forever === true) && nextOccurence} {(!forever && recurrenceEndDate && new Date() < recurrenceEndDate) && nextOccurence} {(!forever && until && new Date() < until) && nextOccurence} <li> <span className='every-sentence'>{repeatTitle} {repeatSchedule}</span><br/> {daysOrdered.map((day, index) => ( day && <div key={index} className='day'> <span>on {day.substr(0, 3)}, {startingTime} - {endingTime}</span><br/> </div> ))} </li> {!forever && notForeverWeek} </ul> ) } else if (type === 'month') { return ( <ul className='hours-formatted repeat'> {nextOccurence} <li> <span className='every-sentence'>{repeatTitle} {repeatSchedule} </span><br/> <span> {(monthly.type === 'byDayInMonth' && monthly.value === 1) && `on the ${monthly.value}st`} {(monthly.type === 'byDayInMonth' && monthly.value === 2) && `on the ${monthly.value}nd`} {(monthly.type === 'byDayInMonth' && monthly.value === 3) && `on the ${monthly.value}rd`} {(monthly.type === 'byDayInMonth' && monthly.value > 3) && `on the ${monthly.value}th`} {(monthly.type === 'byPosition' && monthly.value === 1) && `on the ${monthly.value}st ${weekDays[startingDate.getDay()]}`} {(monthly.type === 'byPosition' && monthly.value === 2) && `on the ${monthly.value}nd ${weekDays[startingDate.getDay()]}`} {(monthly.type === 'byPosition' && monthly.value === 3) && `on the ${monthly.value}rd ${weekDays[startingDate.getDay()]}`} {(monthly.type === 'byPosition' && monthly.value > 3) && `on the ${monthly.value}th ${weekDays[startingDate.getDay()]}`} </span> </li> {!forever && notForeverMonth} </ul> ) } } // DESCRIPTION: if !data.repeat then default view is start + end timestamp const endFragment = ( isSameDay ? endingTime : <div> {formatDateWithWords(endingDate)}, {endingTime} </div> ) const ongoing = endingDate.getFullYear() - startingDate.getFullYear() > 5 return ( <div className='hours-formatted regular-date'> <span>{ongoing && `From`} {formatDateWithWords(startingDate)}, {startingTime} - </span> {ongoing ? `until further notice` : endFragment} </div> ) } export default HoursFormatted
packages/icons/src/md/editor/VerticalAlignBottom.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdVerticalAlignBottom(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M32 26h-6V6h-4v20h-6l8 8 8-8zM8 38v4h32v-4H8z" /> </IconBase> ); } export default MdVerticalAlignBottom;
src/App.js
jp7internet/react-apz
import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; import ContactList from './containers/ContactList'; import ContactCreate from './containers/ContactCreate'; import ContactEdit from './containers/ContactEdit'; import './App.css'; class App extends Component { render() { return ( <Router> <div> <nav className="navbar navbar-default"> <div className="container-fluid"> <div className="navbar-header"> <Link className="navbar-brand" to="/">React Apz</Link> </div> </div> </nav> <section id="content" className="container-fluid"> <h2>Contacts Manager</h2> <div className="container"> <Route exact path="/" component={ContactList} /> <Route path="/new" component={ContactCreate} /> <Route path="/edit/:contactId" component={ContactEdit} /> </div> </section> </div> </Router> ); } } export default App;
src/svg-icons/places/golf-course.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesGolfCourse = (props) => ( <SvgIcon {...props}> <circle cx="19.5" cy="19.5" r="1.5"/><path d="M17 5.92L9 2v18H7v-1.73c-1.79.35-3 .99-3 1.73 0 1.1 2.69 2 6 2s6-.9 6-2c0-.99-2.16-1.81-5-1.97V8.98l6-3.06z"/> </SvgIcon> ); PlacesGolfCourse = pure(PlacesGolfCourse); PlacesGolfCourse.displayName = 'PlacesGolfCourse'; PlacesGolfCourse.muiName = 'SvgIcon'; export default PlacesGolfCourse;
src/svg-icons/toggle/star-border.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ToggleStarBorder = (props) => ( <SvgIcon {...props}> <path d="M22 9.24l-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03L22 9.24zM12 15.4l-3.76 2.27 1-4.28-3.32-2.88 4.38-.38L12 6.1l1.71 4.04 4.38.38-3.32 2.88 1 4.28L12 15.4z"/> </SvgIcon> ); ToggleStarBorder = pure(ToggleStarBorder); ToggleStarBorder.displayName = 'ToggleStarBorder'; ToggleStarBorder.muiName = 'SvgIcon'; export default ToggleStarBorder;
src/components/pages/about.js
ranhouxingfu/website-by-react
import React from 'react' import { Grid, Col, Image, Icon } from 'amazeui-react' export default class aboutUs extends React.Component { constructor(props) { super(props); this.state = {} } render() { return( <div className='contain'> <div className='about-box'> <img src='../images/aboutus-bg.jpg'/> <div className='about-designP'> <h2 className='about-title'>欢迎来到Touch餐厅 </h2> </div></div> <p className='aboutus-describe'>高端氛围,奢华环境,精致产品,独特口感,让人流连忘返。高端氛围,奢华环境,精致产品,独特口感,让人流连忘返。高端氛围,奢华环境,精致产品,独特口感,让人流连忘返。</p> <Grid className='about-last-box'> <Col sm={12} md={5} lg={4} mdOffset={1} lgOffset={2}> <Col sm={12} className='about-left-box'> <Col sm={12} md={3} lg={2} className='about-design'> <Image src="../images/food-design3.jpg" width="70" height="70" circle /></Col> <Col sm={12} md={9} lg={9} lgOffset={1}> <h3 className='about-design'>好吃不胖特色菜</h3> <p className='about-design'>您的梦想需要一个非同凡响的网站</p> </Col> </Col> <Col sm={12} className='about-left-box'> <Col sm={12} md={3} lg={2} className='about-design'> <Image src="../images/food-design4.jpg" width="70" height="70" circle /></Col> <Col sm={12} md={9} lg={9} lgOffset={1}> <h3 className='about-design'>安全的原材料</h3> <p className='about-design'>您的梦想需要一个非同凡响的网站</p> </Col> </Col> <Col sm={12} className='about-left-box'> <Col sm={12} md={3} lg={2} className='about-design'> <Image src="../images/food-design4.jpg" width="70" height="70" circle /></Col> <Col sm={12} md={9} lg={9} lgOffset={1}> <h3 className='about-design'>最物美价廉的餐饮</h3> <p className='about-design'>您的梦想需要一个非同凡响的网站</p> </Col> </Col> </Col> <Col sm={12} md={5} lg={4} className='about-rigth-imgbox'> <img src='../images/food-design6.jpg'/> </Col> <Col md={1} lg={2} ></Col> </Grid> <div className='work-box'> <div className='work-content-box'> <h3>餐厅营业时间</h3> <p>午餐:<span><Icon icon='star'/><Icon icon='star'/><Icon icon='star'/><Icon icon='star'/><Icon icon='star'/></span></p> <p className='work-time'>10:00am--14:00pm</p> <p className='work-dinner'>晚餐:<span><Icon icon='star'/><Icon icon='star'/><Icon icon='star'/><Icon icon='star'/><Icon icon='star'/></span></p> <p className='work-time'>17:00pm--22:00pm</p> <p className='work-dinner'>地址:北京市海淀区惠民路1号高端创意科技广场B座25层</p> </div> </div> </div> ) } }
ExampleApp/index.ios.js
joonhocho/react-native-linkedin-sdk
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, TouchableHighlight } from 'react-native'; import LinkedInSDK from 'react-native-linkedin-sdk'; export default class ExampleApp extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.ios.js </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu </Text> <TouchableHighlight onPress={async () => { const token = await LinkedInSDK.signIn({ // https://developer.linkedin.com/docs/oauth2 // iOS (Required) // The "API Key" value generated when you registered your application. clientID: '86ltc4i0wckzvo', // iOS (Required) clientSecret: 'KCPHGyyXOjmGy72S', // iOS (Required) // A unique string value of your choice that is hard to guess. Used to prevent CSRF. state: 'abcde', // iOS, Android (Required) scopes: [ 'r_basicprofile', ], // iOS (Required) // The URI your users will be sent back to after authorization. This value must match one of the defined OAuth 2.0 Redirect URLs in your application configuration. // e.g. https://www.example.com/auth/linkedin redirectUri: 'https://github.com/joonhocho/react-native-linkedin-sdk/oauth2callback', }); const profile = await LinkedInSDK.getRequest('https://api.linkedin.com/v1/people/~?format=json'); setTimeout(() => { alert(JSON.stringify({token, profile}, null, ' ')); }, 1500); }}> <Text style={styles.instructions}> LinkedIn Sign-In </Text> </TouchableHighlight> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('ExampleApp', () => ExampleApp);
test/integration/client-navigation/pages/memo-component.js
flybayer/next.js
import React from 'react' export default React.memo((props) => <span {...props}>Memo component</span>)
apps/marketplace/components/BuyerSpecialist/BuyerSpecialistAboutStage.js
AusDTO/dto-digitalmarketplace-frontend
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { Form } from 'react-redux-form' import Textfield from 'shared/form/Textfield' import Textarea from 'shared/form/Textarea' import CheckboxDetailsField from 'shared/form/CheckboxDetailsField' import formProps from 'shared/form/formPropsSelector' import { required } from 'marketplace/components/validators' import AUheadings from '@gov.au/headings/lib/js/react.js' import ErrorAlert from 'marketplace/components/Alerts/ErrorAlert' import locations from 'marketplace/components/BuyerBriefFlow/Locations' import styles from './BuyerSpecialistAboutStage.scss' const requiredTitle = v => required(v.title) const requiredOrg = v => required(v.organisation) const requiredSummary = v => required(v.summary) const atLeastOneLocation = v => v.location && v.location.length > 0 export const done = v => requiredTitle(v) && requiredOrg(v) && requiredSummary(v) && atLeastOneLocation(v) const BuyerSpecialistAboutStage = props => ( <Form model={props.model} validators={{ '': { requiredTitle, requiredOrg, requiredSummary, atLeastOneLocation } }} onSubmit={props.onSubmit} onSubmitFailed={props.onSubmitFailed} validateOn="submit" > <AUheadings level="1" size="xl"> About </AUheadings> <ErrorAlert model={props.model} messages={{ requiredTitle: 'Enter the title for your opportunity.', requiredOrg: 'Enter the name of your organisation.', requiredSummary: 'You must answer "what will the specialist do".', atLeastOneLocation: 'You must select at least one location.' }} /> <Textfield model={`${props.model}.title`} label="Role title" name="title" id="title" htmlFor="title" defaultValue={props[props.model].title} maxLength={100} validators={{ required }} /> <Textfield model={`${props.model}.organisation`} label="Who will the specialist work for?" description="Write the full name of the organisation." placeholder="For example, Digital Transformation Agency instead of DTA." name="organisation" id="organisation" htmlFor="organisation" defaultValue={props[props.model].organisation} maxLength={150} validators={{ required }} /> <Textarea model={`${props.model}.summary`} label="What will the specialist do?" name="summary" id="summary" htmlFor="summary" defaultValue={props[props.model].summary} controlProps={{ limit: 1000, rows: '10' }} validators={{ required }} messages={{ limitWords: 'Your summary has exceeded the 1000 word limit' }} /> <AUheadings level="2" size="sm"> Where can the work be done? </AUheadings> <div className={styles.locations}> {Object.keys(locations).map(key => ( <CheckboxDetailsField key={key} model={`${props.model}.location[]`} id={`location_${key}`} name={`location_${key}`} label={locations[key]} value={locations[key]} detailsModel={props.model} validators={{}} messages={{}} /> ))} </div> {props.formButtons} </Form> ) BuyerSpecialistAboutStage.defaultProps = { onSubmit: () => {}, onSubmitFailed: () => {} } BuyerSpecialistAboutStage.propTypes = { model: PropTypes.string.isRequired, formButtons: PropTypes.node.isRequired, onSubmit: PropTypes.func, onSubmitFailed: PropTypes.func } const mapStateToProps = (state, props) => ({ ...formProps(state, props.model) }) export default connect(mapStateToProps)(BuyerSpecialistAboutStage)
blueocean-material-icons/src/js/components/svg-icons/action/event-seat.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionEventSeat = (props) => ( <SvgIcon {...props}> <path d="M4 18v3h3v-3h10v3h3v-6H4zm15-8h3v3h-3zM2 10h3v3H2zm15 3H7V5c0-1.1.9-2 2-2h6c1.1 0 2 .9 2 2v8z"/> </SvgIcon> ); ActionEventSeat.displayName = 'ActionEventSeat'; ActionEventSeat.muiName = 'SvgIcon'; export default ActionEventSeat;
pages/notes/index.js
jhanstra/jh-gatsby
import React from 'react' import TopNav from '../../src/components/core/TopNav' class Notes extends React.Component { render () { return ( <div> <div className="full-title"> <h1>Notes</h1> <h3>Notes, reflections, and highlights from my studies and the books I read</h3> </div> <div className="row default"> </div> </div> ) } } export default Notes;
src/index.js
mduleone/crapshoot
import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import {BrowserRouter as Router} from 'react-router-dom'; import injectTapEventPlugin from "react-tap-event-plugin"; import MuiThemeProvider from "material-ui/styles/MuiThemeProvider"; import initializeStore from './config/store'; import RoutingTable from './config/routes'; import './index.css'; injectTapEventPlugin(); const store = initializeStore({}); ReactDOM.render( // @TODO: Update the basename to match your default path, or remove it if you are mounted at `/` <Provider store={store}> <MuiThemeProvider> <Router basename="/crapshoot"> <RoutingTable /> </Router> </MuiThemeProvider> </Provider>, document.getElementById('root') );
frontend/src/Movie/Details/Titles/MovieTitlesTableContentConnector.js
geogolem/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import MovieTitlesTableContent from './MovieTitlesTableContent'; function createMapStateToProps() { return createSelector( (state) => state.movies, (movies) => { return movies; } ); } const mapDispatchToProps = { // fetchMovies }; class MovieTitlesTableContentConnector extends Component { // // Render render() { const movie = this.props.items.filter((obj) => { return obj.id === this.props.movieId; }); return ( <MovieTitlesTableContent {...this.props} items={movie[0].alternateTitles} /> ); } } MovieTitlesTableContentConnector.propTypes = { movieId: PropTypes.number.isRequired, items: PropTypes.arrayOf(PropTypes.object).isRequired }; export default connect(createMapStateToProps, mapDispatchToProps)(MovieTitlesTableContentConnector);
src/components/Logo/index.js
badT/Chatson
import React, { Component } from 'react'; import TimelineMax from 'gsap/src/minified/TimelineMax.min'; /* component styles */ import { styles } from './styles.scss'; export default class Logo extends Component { constructor(props) { super(props); this.state = { logo: new TimelineMax, hatson: new TimelineMax, animating: true, }; } componentDidMount() { const shrink = new TimelineMax; shrink.to('#hhh', 0, { scale: 0.25 }) .to('#aaa', 0, { scale: 0.25 }) .to('#ttt', 0, { scale: 0.25 }) .to('#sss', 0, { scale: 0.25 }) .to('#ooo', 0, { scale: 0.25 }) .to('#nnn', 0, { scale: 0.25 }); setTimeout(() => { this.logoAnimate().forward(); }, 1500); } logoAnimate() { const forward = () => { this.state.logo.to('#mouth', 2, { rotation: 270, x: 5, y: -4, transformOrigin: '10px 5px' }) .to('.eyes', 2, { rotation: 90, x: 41, y: -4 }, '-=2') .to('#left_ball', 0.75, { opacity: 0, x: 5, y: -45 }, '-=1.15') .to('#right_ball', 0.75, { opacity: 0, x: 25, y: -35 }, '-=0.8') .duration(1.5) .eventCallback('onReverseComplete', () => { setTimeout(() => { this.state.logo.timeScale(2.5).play(); }, 300); }); this.state.hatson .to('#hhh', 0.75, { opacity: 100, scale: 1.8, y: 4 }) .to('#aaa', 0.75, { opacity: 100, scale: 1.7, x: 12, y: 3 }, '-=0.5') .to('#ttt', 0.75, { opacity: 100, scale: 1.7, x: 22, y: -0.65 }, '-=0.5') .to('#sss', 0.75, { opacity: 100, scale: 1.7, x: 32, y: 3 }, '-=0.5') .to('#ooo', 0.75, { opacity: 100, scale: 1.7, x: 42, y: 3 }, '-=0.5') .to('#nnn', 0.75, { opacity: 100, scale: 1.7, x: 54, y: 3 }, '-=0.5') .duration(1.5) .eventCallback('onReverseComplete', () => { setTimeout(() => { this.state.hatson.timeScale(2.5).play(); }, 300); }) .eventCallback('onComplete', () => { this.setState({ animating: false }); }); }; const rewind = () => { if (!this.state.animating) { this.setState({ animating: true }); this.state.logo .timeScale(3) .reverse(0); this.state.hatson .timeScale(3) .reverse(0); } }; return { forward, rewind, }; } render() { return ( <div className={`${styles}`}> <span className="logo-holder"> <svg className="logo" width="60" height="60" viewBox="-2 -2 64 74" onMouseEnter={() => { this.logoAnimate().rewind(); }}> <g className="eyes"> <line id="left_eye" fill="none" stroke="#ffffff" strokeWidth="3" stroke-miterlimit="10" x1="12.5" y1="8.9" x2="24.3" y2="8.9" /> <line id="right_eye" fill="none" stroke="#ffffff" strokeWidth="3" stroke-miterlimit="10" x1="35.8" y1="8.9" x2="47.7" y2="8.9" /> <path id="left_ball" fill="#FF1D25" stroke="#FF1D25" strokeWidth="1.35" stroke-miterlimit="10" d="M14.9,10.3c0,1.9,1.4,3.5,3,3.8 c1.9,0.3,4.1-1.4,4.1-3.8" /> <path id="right_ball" fill="#FF1D25" stroke="#FF1D25" strokeWidth="1.35" stroke-miterlimit="10" d="M38.1,10.3c0,1.9,1.4,3.5,3,3.8 c1.9,0.3,4.1-1.4,4.1-3.8" /> </g> <path id="mouth" fill="none" stroke="#ffffff" strokeWidth="5" stroke-miterlimit="10" d="M46.1,47.6c0.3-1.3,1.2-5.4-0.7-9.9 c-1.7-4.2-4.9-6.4-5.8-7.1c-0.6-0.4-1.7-1.2-3.6-1.9c-0.7-0.3-3.6-1.3-7.4-1c-1.3,0.1-4.6,0.4-8,2.5c-1,0.6-3.2,2-4.9,4.6 c-1.6,2.3-1.9,4.5-2.2,5.7c-0.6,3-0.3,5.7,0.1,7.2" /> </svg> <span> <svg className="hatson" width="124.5" height="60" viewBox="0 0 200 100"> <g className="letters"> <path id="hhh" opacity="0" fill="none" stroke="#FF1D25" strokeWidth="2.5" stroke-miterlimit="10" d="M12.7,26.6c0.3-0.5,0.7-1.2,1.5-1.8 c0.8-0.6,1.5-0.9,2.1-1c1.2-0.3,2.1-0.3,2.6-0.3c0.6,0,1.5,0.1,2.5,0.6c0.4,0.2,1.1,0.5,1.7,1.2c0.2,0.2,0.7,0.8,1,1.7 c0.2,0.6,0.3,1.1,0.3,1.4c0.1,0.4,0.1,0.8,0.1,1.1c0,0.2,0,0.4,0,1.1c0,0.4,0,0.6,0,1c0,0.1,0,0.3,0,0.6c0,0.4,0,0.7,0,0.9 c0,0.6,0,0.8,0,1.5c0,0.7,0,1.2,0,1.6c0,0.8,0,2,0,4" /> <path id="aaa" opacity="0" strokeWidth="2" fill="#FF1D25" stroke="#FF1D25" d="M42.2,36.9c0,0.6,0,1.3,0.1,2c0.1,0.7,0.1,1.3,0.2,1.8h-0.8c0-0.2-0.1-0.5-0.1-0.9c0-0.4-0.1-0.7-0.1-1.1 c0-0.4-0.1-0.8-0.1-1.1c0-0.4,0-0.7,0-0.9h-0.1c-0.5,1.5-1.3,2.7-2.5,3.4c-1.2,0.7-2.5,1.1-3.9,1.1c-0.7,0-1.4-0.1-2-0.3 c-0.7-0.2-1.3-0.5-1.8-0.9c-0.5-0.4-1-0.9-1.3-1.5c-0.3-0.6-0.5-1.3-0.5-2.2c0-1.2,0.3-2.2,0.9-2.9c0.6-0.7,1.4-1.3,2.3-1.7 c0.9-0.4,1.9-0.7,3-0.8c1.1-0.1,2-0.2,2.9-0.2h3v-1.4c0-1.9-0.5-3.3-1.5-4.1c-1-0.9-2.3-1.3-3.9-1.3c-1,0-2,0.2-2.8,0.6 c-0.9,0.4-1.7,0.9-2.3,1.5l-0.4-0.6c0.8-0.7,1.7-1.2,2.7-1.6c1-0.4,2-0.5,2.9-0.5c1.9,0,3.5,0.5,4.6,1.5c1.1,1,1.7,2.6,1.7,4.7 V36.9z M41.4,31.5h-2.6c-0.9,0-1.9,0.1-3,0.2c-1,0.1-2,0.3-2.8,0.7c-0.9,0.3-1.6,0.8-2.1,1.5c-0.6,0.6-0.8,1.5-0.8,2.6 c0,0.8,0.2,1.4,0.5,2c0.3,0.5,0.7,1,1.2,1.3c0.5,0.3,1,0.6,1.6,0.7c0.6,0.1,1.1,0.2,1.6,0.2c1.3,0,2.3-0.2,3.1-0.7 c0.8-0.5,1.5-1.1,2-1.8c0.5-0.7,0.9-1.5,1.1-2.4c0.2-0.9,0.3-1.7,0.3-2.6V31.5z" /> <path id="ttt" opacity="0" strokeWidth="2" fill="#FF1D25" stroke="#FF1D25" d="M54.6,41c-0.4,0.1-0.8,0.1-1.1,0.1c-1.3,0-2.3-0.4-2.8-1.1c-0.6-0.7-0.8-1.7-0.8-2.8V24.5h-3.7v-0.7h3.7v-5h0.8v5h5v0.7 h-5v12.8c0,1.2,0.3,2,0.8,2.5c0.6,0.5,1.3,0.8,2.3,0.8c0.7,0,1.3-0.1,1.9-0.3l0.1,0.6C55.3,40.9,55,41,54.6,41z" /> <path id="sss" opacity="0" strokeWidth="2" fill="#FF1D25" stroke="#FF1D25" d="M69.9,36.3c0,0.8-0.1,1.4-0.4,2c-0.3,0.6-0.7,1.1-1.2,1.5c-0.5,0.4-1.1,0.7-1.8,1c-0.7,0.2-1.4,0.3-2.1,0.3 c-1.3,0-2.4-0.2-3.4-0.7c-1-0.5-1.9-1.2-2.5-2.1l0.7-0.4c1.2,1.7,3,2.6,5.3,2.6c0.5,0,1.1-0.1,1.6-0.3c0.6-0.2,1.1-0.4,1.5-0.8 c0.5-0.3,0.8-0.8,1.1-1.3c0.3-0.5,0.4-1.1,0.4-1.8c0-0.8-0.2-1.4-0.5-1.9c-0.4-0.5-0.8-0.9-1.3-1.2c-0.5-0.3-1.1-0.5-1.8-0.7 c-0.7-0.2-1.3-0.4-1.8-0.5c-0.6-0.2-1.2-0.4-1.7-0.6c-0.5-0.2-1-0.5-1.4-0.8c-0.4-0.3-0.7-0.7-1-1.2c-0.2-0.5-0.4-1.1-0.4-1.8 s0.1-1.4,0.4-1.9c0.3-0.5,0.7-1,1.2-1.3c0.5-0.4,1.1-0.6,1.7-0.8c0.6-0.2,1.3-0.3,1.9-0.3c2.3,0,4,0.8,5.2,2.5l-0.7,0.4 c-0.6-0.7-1.2-1.3-1.9-1.6c-0.7-0.4-1.6-0.5-2.6-0.5c-0.5,0-1,0.1-1.5,0.2c-0.5,0.1-1,0.3-1.4,0.6c-0.4,0.3-0.8,0.7-1.1,1.1 c-0.3,0.5-0.4,1-0.4,1.7c0,0.7,0.1,1.3,0.4,1.8c0.2,0.4,0.6,0.8,1,1.1c0.4,0.3,0.9,0.5,1.5,0.7c0.6,0.2,1.2,0.4,2,0.5 c0.7,0.2,1.3,0.4,1.9,0.6c0.6,0.2,1.2,0.5,1.7,0.9c0.5,0.3,0.9,0.8,1.1,1.3C69.7,34.9,69.9,35.5,69.9,36.3z" /> <path id="ooo" opacity="0" strokeWidth="2" fill="#FF1D25" stroke="#FF1D25" d="M91.9,32.2c0,1.3-0.2,2.5-0.6,3.6c-0.4,1.1-1,2.1-1.8,2.9c-0.8,0.8-1.7,1.4-2.8,1.9c-1.1,0.4-2.3,0.7-3.6,0.7 c-1.3,0-2.5-0.2-3.6-0.7c-1.1-0.4-2-1.1-2.8-1.9c-0.8-0.8-1.4-1.8-1.8-2.9c-0.4-1.1-0.6-2.3-0.6-3.6s0.2-2.5,0.6-3.6 c0.4-1.1,1-2,1.8-2.8c0.8-0.8,1.7-1.4,2.8-1.8c1.1-0.4,2.3-0.7,3.6-0.7c1.3,0,2.5,0.2,3.6,0.7c1.1,0.4,2,1.1,2.8,1.8 c0.8,0.8,1.4,1.7,1.8,2.8C91.7,29.7,91.9,30.9,91.9,32.2z M91.1,32.2c0-1.1-0.2-2.2-0.6-3.2c-0.4-1-0.9-1.9-1.6-2.6 c-0.7-0.7-1.6-1.3-2.5-1.8c-1-0.4-2.1-0.6-3.4-0.6c-1.3,0-2.4,0.2-3.4,0.6c-1,0.4-1.8,1-2.5,1.8c-0.7,0.7-1.2,1.6-1.6,2.6 c-0.4,1-0.6,2.1-0.6,3.2c0,1.2,0.2,2.2,0.6,3.2c0.4,1,0.9,1.9,1.6,2.6c0.7,0.7,1.5,1.3,2.5,1.8c1,0.4,2.1,0.7,3.4,0.7 c1.3,0,2.4-0.2,3.4-0.7c1-0.4,1.8-1,2.5-1.8c0.7-0.7,1.2-1.6,1.6-2.6C90.9,34.4,91.1,33.3,91.1,32.2z" /> <path id="nnn" opacity="0" strokeWidth="2" fill="#FF1D25" stroke="#FF1D25" d="M100,26.1c0.5-0.6,1-1.1,1.6-1.6c0.6-0.4,1.2-0.8,1.9-1c0.7-0.2,1.4-0.3,2.1-0.3c1.2,0,2.2,0.2,3,0.6 c0.8,0.4,1.4,1,1.9,1.7c0.5,0.7,0.8,1.5,1,2.3c0.2,0.9,0.3,1.7,0.3,2.6v10.2h-0.8V30.5c0-0.7-0.1-1.4-0.2-2.2 c-0.1-0.8-0.4-1.5-0.8-2.1c-0.4-0.6-1-1.2-1.6-1.6c-0.7-0.4-1.6-0.6-2.6-0.6c-0.9,0-1.8,0.2-2.6,0.6c-0.8,0.4-1.5,0.9-2.1,1.6 c-0.6,0.7-1.1,1.6-1.4,2.6c-0.4,1-0.5,2.2-0.5,3.5v8.5h-0.8V28c0-0.3,0-0.6,0-1c0-0.4,0-0.8,0-1.2c0-0.4,0-0.8-0.1-1.2 c0-0.4,0-0.7-0.1-0.9h0.8c0,0.2,0,0.6,0.1,0.9c0,0.4,0,0.8,0,1.2c0,0.4,0,0.8,0,1.3c0,0.4,0,0.8,0,1.1h0.1 C99.2,27.4,99.5,26.7,100,26.1z" /> </g> </svg> </span> </span> </div> ); } }
src/components/Tabs/Tabs-story.js
wfp/ui
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import { withKnobs, number, text } from '@storybook/addon-knobs'; import Tabs from '../Tabs'; import Tab from '../Tab'; import Tag from '../Tag'; import TabsSkeleton from '../Tabs/Tabs.Skeleton'; const props = { tabs: () => ({ className: 'some-class', selected: number('The index of the selected tab (selected in <Tabs>)', 1), triggerHref: text( 'The href of trigger button for narrow mode (triggerHref in <Tabs>)', '#' ), role: text('ARIA role (role in <Tabs>)', 'navigation'), onClick: action('onClick'), onKeyDown: action('onKeyDown'), onSelectionChange: action('onSelectionChange'), }), tab: () => ({ className: 'another-class', href: text('The href for tab (href in <Tab>)', '#'), label: text('The label for tab (label in <Tab>)', 'Tab label'), role: text('ARIA role (role in <Tab>)', 'presentation'), tabIndex: number('Tab index (tabIndex in <Tab>)', 0), onClick: action('onClick'), onKeyDown: action('onKeyDown'), }), }; const el = ({ href, label }) => { return ( <a href={href}> <span> {label} <Tag type="wfp">renderAnchor</Tag> </span> </a> ); }; const listEl = ({ anchor, className, label, href }) => { return ( <li className={className}> <div className="wfp--tabs__nav-link" role="button" tabIndex={0} onKeyPress={() => { alert('Custom renderListElement keypress'); }} onClick={() => { alert('Custom renderListElement'); }}> {anchor.label} * </div> </li> ); }; /* const TabLink = (props) => ( <Route path={to} exact={exact} children={({ match }) => ( <div className={match ? "wfp--tabs__nav-item wfp--tabs__nav-item--selected" : "wfp--tabs__nav-item"}> <Link className="wfp--tabs__nav-link" to={to}>{children}</Link> </div> )} /> ); */ const FakeRoute = ({ children }) => { const Children = children; return <Children match />; }; const FakeLink = ({ children, className }) => ( <div className={className}>{children}</div> ); const listElReactRouter = ({ anchor, className, to, exact, match }) => ( <FakeRoute to={to} exact={exact} children={({ match }) => ( <li className={ match ? className + ' wfp--tabs__nav-item--selected' : className }> <FakeLink className={anchor.className} to={to}> {anchor.label} </FakeLink> </li> )} /> ); storiesOf('Components|Tabs', module) .addDecorator(withKnobs) .add('Default', () => ( <Tabs {...props.tabs()}> <Tab {...props.tab()} label={`${props.tab().label} 1`}> <div className="some-content">Content for first tab goes here.</div> </Tab> <Tab {...props.tab()} label={`${props.tab().label} 2`}> <div className="some-content">Content for second tab goes here.</div> </Tab> <Tab {...props.tab()} label={`${props.tab().label} 3`}> <div className="some-content">Content for third tab goes here.</div> </Tab> <Tab {...props.tab()} disabled label={`${props.tab().label} 4 disabled`}> <div className="some-content">Content for fourth tab goes here.</div> </Tab> </Tabs> )) .add('Custom Tab Content', () => ( <Tabs {...props.tabs()} customTabContent={true}> <Tab {...props.tab()} label="Tab label 1" href="http://www.de.wfp.org" /> <Tab {...props.tab()} label="Tab label 2" href="http://www.fr.wfp.org" /> <Tab {...props.tab()} label="Tab label 3" href="http://www.fr.wfp.org" to="/path" /> </Tabs> )) .add('Custom Tab Logic', () => ( <Tabs {...props.tabs()} customTabContent={true}> <Tab {...props.tab()} label="Custom" href="http://www.de.wfp.org" renderAnchor={el} /> <Tab {...props.tab()} label="Custom renderListElement" href="http://www.fr.wfp.org" renderListElement={listEl} /> <Tab {...props.tab()} label="React-Router Example" href="http://www.fr.wfp.org" to="/path" renderListElement={listElReactRouter} /> </Tabs> )) .add('skeleton', () => <TabsSkeleton />);
src/TextField/TextFieldLabel.js
igorbt/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import transitions from '../styles/transitions'; function getStyles(props) { const defaultStyles = { position: 'absolute', lineHeight: '22px', top: 38, transition: transitions.easeOut(), zIndex: 1, // Needed to display label above Chrome's autocomplete field background transform: 'scale(1) translate(0, 0)', transformOrigin: 'left top', pointerEvents: 'auto', userSelect: 'none', }; const shrinkStyles = props.shrink ? Object.assign({ transform: 'scale(0.75) translate(0, -28px)', pointerEvents: 'none', }, props.shrinkStyle) : null; return { root: Object.assign(defaultStyles, props.style, shrinkStyles), }; } const TextFieldLabel = (props) => { const { muiTheme, className, children, htmlFor, onClick, } = props; const {prepareStyles} = muiTheme; const styles = getStyles(props); return ( <label className={className} style={prepareStyles(styles.root)} htmlFor={htmlFor} onClick={onClick} > {children} </label> ); }; TextFieldLabel.propTypes = { /** * The label contents. */ children: PropTypes.node, /** * The css class name of the root element. */ className: PropTypes.string, /** * Disables the label if set to true. */ disabled: PropTypes.bool, /** * The id of the target element that this label should refer to. */ htmlFor: PropTypes.string, /** * @ignore * The material-ui theme applied to this component. */ muiTheme: PropTypes.object.isRequired, /** * Callback function for when the label is selected via a click. * * @param {object} event Click event targeting the text field label. */ onClick: PropTypes.func, /** * True if the floating label should shrink. */ shrink: PropTypes.bool, /** * Override the inline-styles of the root element when shrunk. */ shrinkStyle: PropTypes.object, /** * Override the inline-styles of the root element. */ style: PropTypes.object, }; TextFieldLabel.defaultProps = { disabled: false, shrink: false, }; export default TextFieldLabel;
src/svg-icons/device/signal-cellular-off.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellularOff = (props) => ( <SvgIcon {...props}> <path d="M21 1l-8.59 8.59L21 18.18V1zM4.77 4.5L3.5 5.77l6.36 6.36L1 21h17.73l2 2L22 21.73 4.77 4.5z"/> </SvgIcon> ); DeviceSignalCellularOff = pure(DeviceSignalCellularOff); DeviceSignalCellularOff.displayName = 'DeviceSignalCellularOff'; export default DeviceSignalCellularOff;
src/svg-icons/av/replay-5.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvReplay5 = (props) => ( <SvgIcon {...props}> <path d="M12 5V1L7 6l5 5V7c3.3 0 6 2.7 6 6s-2.7 6-6 6-6-2.7-6-6H4c0 4.4 3.6 8 8 8s8-3.6 8-8-3.6-8-8-8zm-1.3 8.9l.2-2.2h2.4v.7h-1.7l-.1.9s.1 0 .1-.1.1 0 .1-.1.1 0 .2 0h.2c.2 0 .4 0 .5.1s.3.2.4.3.2.3.3.5.1.4.1.6c0 .2 0 .4-.1.5s-.1.3-.3.5-.3.2-.4.3-.4.1-.6.1c-.2 0-.4 0-.5-.1s-.3-.1-.5-.2-.2-.2-.3-.4-.1-.3-.1-.5h.8c0 .2.1.3.2.4s.2.1.4.1c.1 0 .2 0 .3-.1l.2-.2s.1-.2.1-.3v-.6l-.1-.2-.2-.2s-.2-.1-.3-.1h-.2s-.1 0-.2.1-.1 0-.1.1-.1.1-.1.1h-.7z"/> </SvgIcon> ); AvReplay5 = pure(AvReplay5); AvReplay5.displayName = 'AvReplay5'; AvReplay5.muiName = 'SvgIcon'; export default AvReplay5;
website/src/components/charts/Tooltip/index.js
jwngr/notreda.me
import React from 'react'; import {TooltipWrapper} from './index.styles'; import {getWindowDimensions} from '../../../utils'; export default ({x, y, children}) => { const tooltipStyles = {}; const windowDimensions = getWindowDimensions(); if (y - window.scrollY < 100) { tooltipStyles.top = y; } else { tooltipStyles.bottom = windowDimensions.height - y; } if (windowDimensions.width - x < 150) { tooltipStyles.right = windowDimensions.width - x; } else { tooltipStyles.left = x; } return <TooltipWrapper style={tooltipStyles}>{children}</TooltipWrapper>; };
modules/TransitionHook.js
tikotzky/react-router
import React from 'react'; import warning from 'warning'; var { object } = React.PropTypes; var TransitionHook = { contextTypes: { router: object.isRequired }, componentDidMount() { warning( typeof this.routerWillLeave === 'function', 'Components that mixin TransitionHook should have a routerWillLeave method, check %s', this.constructor.displayName || this.constructor.name ); if (this.routerWillLeave) this.context.router.addTransitionHook(this.routerWillLeave); }, componentWillUnmount() { if (this.routerWillLeave) this.context.router.removeTransitionHook(this.routerWillLeave); } }; export default TransitionHook;
src/CarouselItem.js
laran/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import TransitionEvents from './utils/TransitionEvents'; const CarouselItem = React.createClass({ propTypes: { direction: React.PropTypes.oneOf(['prev', 'next']), onAnimateOutEnd: React.PropTypes.func, active: React.PropTypes.bool, animateIn: React.PropTypes.bool, animateOut: React.PropTypes.bool, caption: React.PropTypes.node, index: React.PropTypes.number }, getInitialState() { return { direction: null }; }, getDefaultProps() { return { active: false, animateIn: false, animateOut: false }; }, handleAnimateOutEnd() { if (this.props.onAnimateOutEnd && this.isMounted()) { this.props.onAnimateOutEnd(this.props.index); } }, componentWillReceiveProps(nextProps) { if (this.props.active !== nextProps.active) { this.setState({ direction: null }); } }, componentDidUpdate(prevProps) { if (!this.props.active && prevProps.active) { TransitionEvents.addEndEventListener( React.findDOMNode(this), this.handleAnimateOutEnd ); } if (this.props.active !== prevProps.active) { setTimeout(this.startAnimation, 20); } }, startAnimation() { if (!this.isMounted()) { return; } this.setState({ direction: this.props.direction === 'prev' ? 'right' : 'left' }); }, render() { let classes = { item: true, active: (this.props.active && !this.props.animateIn) || this.props.animateOut, next: this.props.active && this.props.animateIn && this.props.direction === 'next', prev: this.props.active && this.props.animateIn && this.props.direction === 'prev' }; if (this.state.direction && (this.props.animateIn || this.props.animateOut)) { classes[this.state.direction] = true; } return ( <div {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} {this.props.caption ? this.renderCaption() : null} </div> ); }, renderCaption() { return ( <div className="carousel-caption"> {this.props.caption} </div> ); } }); export default CarouselItem;
src/views/BootCard/BootCardDeck.js
shengnian/shengnian-ui-react
import React from 'react' import PropTypes from 'prop-types' import cx from 'classnames' import { mapToCssModules } from '../../lib/' const propTypes = { tag: PropTypes.oneOfType([PropTypes.func, PropTypes.string]), className: PropTypes.string, cssModule: PropTypes.object, } const defaultProps = { tag: 'div', } const CardDeck = (props) => { const { className, cssModule, tag: Tag, ...attributes } = props const classes = mapToCssModules(cx( className, 'card-deck', ), cssModule) return ( <Tag {...attributes} className={classes} /> ) } CardDeck.propTypes = propTypes CardDeck.defaultProps = defaultProps export default CardDeck
public/pages/UpdateDynamicFormPage.js
dynamicform/dynamicform-react-client
import React from 'react'; import {connect} from 'react-redux'; import DynamicForm from '../../src/components/DynamicForm'; @connect() export default class UpdateDynamicFormPage extends React.Component{ onSubmit(er){ console.log('回调函数onSubmit'); } onSuccess(){ } //${this.props.match && this.props.match.params.name} //${this.props.match && this.props.match.params.id} render(){ return( <div> <DynamicForm formDefinitionSrc={`http://localhost:3000/api/getdefinition/${this.props.match && this.props.match.params.name}`} formDataSrc={`http://localhost:3000/api/loadformdataById/${this.props.match && this.props.match.params.id}`} _id={this.props.match && this.props.match.params.id} dataPath='data' onSuccess={this.onSuccess} /> </div> ); } }
web/app/layout/header.js
seanhess/serials
// @flow import React from 'react' import {RouteHandler, Link} from 'react-router' import {assign} from 'lodash' import {Users} from '../model/user' import {background, Colors, clickable} from '../style' import {LinkStyle, TitleStyle, NavBar, CenterText} from './style' import {AlertView} from '../alert' import {Alerts} from '../model/alert' import {Routes} from '../router' import {OffCanvas} from './offcanvas' //export class MainContainer extends React.Component { //render():React.Element { //return <div> //<OffCanvas> //hello //</OffCanvas> //</div> //} //} export class Header extends React.Component { logout() { Users.logout().then(function() { window.location.hash = "/login" }) } renderCurrentUser():React.Element { var currentUser = this.props.currentUser; if (currentUser) { return <div style={{display: 'inline-block'}}> <Link style={LinkStyle} to={Routes.bookshelf} params={{id: this.props.currentUser.id}}>My Books</Link> <a style={LinkStyle} onClick={this.logout.bind(this)}>Logout</a> </div> //<p style={LinkStyle}>Hello, {this.props.currentUser.firstName}</p> } else { return <div style={{display: 'inline-block'}}> <Link style={LinkStyle} to={Routes.login}>Login</Link> </div> } } render():React.Element { var isAdmin = false if (this.props.currentUser && this.props.currentUser.admin) { isAdmin = true } var adminStyle = assign({}, LinkStyle, { display: (isAdmin) ? 'inline-block' : 'none' }) var signup = "" if (!this.props.currentUser) { signup = <a style={LinkStyle} href="/hello">Sign Up</a> } var linkTo = {to: Routes.root} if (this.props.currentUser) { linkTo = {to: Routes.bookshelf, params: {id: this.props.currentUser.id}} } return <nav style={NavBar} role="navigation"> <div style={{float: 'right'}}> <Link to={Routes.about} style={LinkStyle}>About</Link> {signup} <Link style={adminStyle} to={Routes.admin}>Admin</Link> {this.renderCurrentUser()} </div> <div style={CenterText}> <Link {...linkTo} style={TitleStyle}> <img src="img/serials-icon-light.png" style={{height: 30, marginRight: 5}}/> <span style={{fontWeight: 'bold', color: Colors.light}}>Web Fiction</span> </Link> </div> </nav> } } export class SiteTitle extends React.Component { render() { var linkTo = {to: Routes.root} if (this.props.currentUser) { linkTo = {to: Routes.bookshelf, params: {id: this.props.currentUser.id}} } return <Link {...linkTo} style={TitleStyle}> <img src="img/serials-icon-light.png" style={{height: 26, marginRight: 5}}/> <span style={{fontWeight: 'bold', color: Colors.light}}>Web Fiction</span> </Link> } }
examples/todomvc/test/components/TodoItem.spec.js
joaomilho/redux
import expect from 'expect' import React from 'react' import TestUtils from 'react-addons-test-utils' import TodoItem from '../../components/TodoItem' import TodoTextInput from '../../components/TodoTextInput' function setup( editing = false ) { const props = { todo: { id: 0, text: 'Use Redux', completed: false }, editTodo: expect.createSpy(), deleteTodo: expect.createSpy(), completeTodo: expect.createSpy() } const renderer = TestUtils.createRenderer() renderer.render( <TodoItem {...props} /> ) let output = renderer.getRenderOutput() if (editing) { const label = output.props.children.props.children[1] label.props.onDoubleClick({}) output = renderer.getRenderOutput() } return { props: props, output: output, renderer: renderer } } describe('components', () => { describe('TodoItem', () => { it('initial render', () => { const { output } = setup() expect(output.type).toBe('li') expect(output.props.className).toBe('') const div = output.props.children expect(div.type).toBe('div') expect(div.props.className).toBe('view') const [ input, label, button ] = div.props.children expect(input.type).toBe('input') expect(input.props.checked).toBe(false) expect(label.type).toBe('label') expect(label.props.children).toBe('Use Redux') expect(button.type).toBe('button') expect(button.props.className).toBe('destroy') }) it('input onChange should call completeTodo', () => { const { output, props } = setup() const input = output.props.children.props.children[0] input.props.onChange({}) expect(props.completeTodo).toHaveBeenCalledWith(0) }) it('button onClick should call deleteTodo', () => { const { output, props } = setup() const button = output.props.children.props.children[2] button.props.onClick({}) expect(props.deleteTodo).toHaveBeenCalledWith(0) }) it('label onDoubleClick should put component in edit state', () => { const { output, renderer } = setup() const label = output.props.children.props.children[1] label.props.onDoubleClick({}) const updated = renderer.getRenderOutput() expect(updated.type).toBe('li') expect(updated.props.className).toBe('editing') }) it('edit state render', () => { const { output } = setup(true) expect(output.type).toBe('li') expect(output.props.className).toBe('editing') const input = output.props.children expect(input.type).toBe(TodoTextInput) expect(input.props.text).toBe('Use Redux') expect(input.props.editing).toBe(true) }) it('TodoTextInput onSave should call editTodo', () => { const { output, props } = setup(true) output.props.children.props.onSave('Use Redux') expect(props.editTodo).toHaveBeenCalledWith(0, 'Use Redux') }) it('TodoTextInput onSave should call deleteTodo if text is empty', () => { const { output, props } = setup(true) output.props.children.props.onSave('') expect(props.deleteTodo).toHaveBeenCalledWith(0) }) it('TodoTextInput onSave should exit component from edit state', () => { const { output, renderer } = setup(true) output.props.children.props.onSave('Use Redux') const updated = renderer.getRenderOutput() expect(updated.type).toBe('li') expect(updated.props.className).toBe('') }) }) })
1m_Redux_Lynda/Ex_Files_Learning_Redux/Exercise Files/Ch05/05_05/finished/src/index.js
yevheniyc/C
import C from './constants' import React from 'react' import { render } from 'react-dom' import routes from './routes' import sampleData from './initialState' import storeFactory from './store' import { Provider } from 'react-redux' import { addError } from './actions' const initialState = (localStorage["redux-store"]) ? JSON.parse(localStorage["redux-store"]) : sampleData const saveState = () => localStorage["redux-store"] = JSON.stringify(store.getState()) const handleError = error => { store.dispatch( addError(error.message) ) } const store = storeFactory(initialState) store.subscribe(saveState) window.React = React window.store = store window.addEventListener("error", handleError) render( <Provider store={store}> {routes} </Provider>, document.getElementById('react-container') )
App.js
Jack3113/edtBordeaux
import React from 'react'; import { Image } from 'react-native'; import { AppLoading, SplashScreen } from 'expo'; import { Asset } from 'expo-asset'; import * as Font from 'expo-font'; import { Entypo, Feather, FontAwesome, Ionicons, MaterialCommunityIcons, MaterialIcons, SimpleLineIcons } from '@expo/vector-icons'; import RootContainer from './containers/rootContainer'; function cacheFonts(fonts) { return fonts.map((font) => Font.loadAsync(font)); } function cacheImages(images) { return images.map((image) => { if (typeof image === 'string') { return Image.prefetch(image); } else { return Asset.fromModule(image).downloadAsync(); } }); } export default class App extends React.Component { state = { isSplashReady: false, }; constructor(props) { super(props); this._loadAssetsAsync = this._loadAssetsAsync.bind(this); } render() { if (!this.state.isSplashReady) { return ( <AppLoading startAsync={this._loadAssetsAsync} onFinish={() => this.setState({ isSplashReady: true })} onError={console.warn} autoHideSplash={false} /> ); } return <RootContainer />; } async _loadAssetsAsync() { const imageAssets = cacheImages([require('./assets/icons/app.png')]); const fontAssets = cacheFonts([ FontAwesome.font, Feather.font, Ionicons.font, MaterialCommunityIcons.font, MaterialIcons.font, SimpleLineIcons.font, Entypo.font, ]); await Promise.all([...imageAssets, ...fontAssets]); SplashScreen.hide(); } }
src/router.js
Huanzhang89/rss-feed-example
import React from 'react'; import { Provider } from 'react-redux'; import history from './history'; import { Router, Route } from 'react-router-dom'; import store from './store' import App from './views/App'; const routes = ( <Route path='/' component={App} /> ) const Routes = () => ( <Provider store={store}> <Router history={history}> {routes} </Router> </Provider> ) export default Routes;
app/src/modules/shared/components/NavigationBar/NavigationBar.js
betofigueiredo/homelibraries.org
import React from 'react'; import PropTypes from 'prop-types'; // import { useSelector } from 'react-redux'; import { Link, withRouter } from 'react-router-dom'; // CSS import CSSModules from 'react-css-modules'; import styles from './style.module.scss'; // Language // import { translate } from '../../languages/translate'; // Components import NavButton from './NavButton'; function NavigationBar({ match }) { // const user = useSelector(store => store.user); // const { locale } = user; const libraries_matches = ['/libraries']; const mybooks_matches = ['/mybooks']; const messages_matches = [ '/messages', '/messages/view/:uuid', ]; const account_matches = [ '/account', '/account/name', '/account/url', '/account/address', '/account/map', '/account/lfl', '/account/email', '/account/password', '/account/language', ]; return ( <div styleName="navigation-wrapper"> <div styleName="menu-top"> <Link to="/libraries">.</Link> </div> <ul styleName="menu"> <NavButton label="Mapa" icon="fa fa-map-marker" link="/libraries" match={match} url_matches={libraries_matches} /> <NavButton label="Meus livros" icon="fa fa-book" link="/mybooks" match={match} url_matches={mybooks_matches} /> <NavButton label="Trocas" icon="fa fa-handshake-o" link="/trades" match={match} url_matches={[]} /> <NavButton label="Mensagens" icon="fa fa-comments" link="/messages" match={match} url_matches={messages_matches} /> <NavButton label="Conta" icon="fa fa-user" link="/account" match={match} url_matches={account_matches} /> </ul> </div> ); } NavigationBar.propTypes = { match: PropTypes.object.isRequired, }; export default withRouter(CSSModules(NavigationBar, styles, { allowMultiple: true }));
src/parser/demonhunter/havoc/modules/talents/Momentum.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS/index'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import { formatPercentage, formatDuration } from 'common/format'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; /* example report: https://www.warcraftlogs.com/reports/1HRhNZa2cCkgK9AV/#fight=48&source=10 * */ class Momentum extends Analyzer { constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.MOMENTUM_TALENT.id); } get buffUptime() { return this.selectedCombatant.getBuffUptime(SPELLS.MOMENTUM_BUFF.id) / this.owner.fightDuration; } get buffDuration() { return this.selectedCombatant.getBuffUptime(SPELLS.MOMENTUM_BUFF.id); } get suggestionThresholds() { return { actual: this.buffUptime, isLessThan: { minor: 0.55, average: 0.45, major: 0.40, }, style: 'percentage', }; } suggestions(when) { when(this.suggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<> Maintain the <SpellLink id={SPELLS.MOMENTUM_TALENT.id} /> buff to maximize damage.</>) .icon(SPELLS.MOMENTUM_TALENT.icon) .actual(`${formatPercentage(actual)}% buff uptime`) .recommended(`${formatPercentage(recommended)}% is recommended.`); }); } statistic() { return ( <StatisticBox position={STATISTIC_ORDER.CORE(3)} icon={<SpellIcon id={SPELLS.MOMENTUM_TALENT.id} />} value={`${formatPercentage(this.buffUptime)}%`} label="Momentum Uptime" tooltip={`The Momentum buff total uptime was ${formatDuration(this.buffDuration / 1000)}.`} /> ); } } export default Momentum;
src/interface/report/Results/EncounterStats.js
sMteX/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import SPECS from 'game/SPECS'; import ROLES from 'game/ROLES'; import ITEMS from 'common/ITEMS'; import fetchWcl from 'common/fetchWclApi'; import Icon from 'common/Icon'; import ItemLink from 'common/ItemLink'; import SpellLink from 'common/SpellLink'; import SpellIcon from 'common/SpellIcon'; import { formatDuration, formatPercentage, formatThousands } from 'common/format'; import ActivityIndicator from 'interface/common/ActivityIndicator'; import { makeItemApiUrl } from 'common/makeApiUrl'; /** * Show statistics (talents and trinkets) for the current boss, specID and difficulty */ const LEVEL_15_TALENT_ROW_INDEX = 0; class EncounterStats extends React.PureComponent { static propTypes = { currentBoss: PropTypes.number.isRequired, spec: PropTypes.number.isRequired, difficulty: PropTypes.number.isRequired, duration: PropTypes.number.isRequired, }; LIMIT = 100; //Currently does nothing but if Kihra reimplements it'd be nice to have SHOW_TOP_ENTRYS = 6; SHOW_TOP_ENTRYS_AZERITE = 10; SHOW_CLOSEST_KILL_TIME_LOGS = 10; metric = 'dps'; amountOfParses = 0; durationVariancePercentage = 0.2; //Marked in % to allow for similiar filtering on long/short fights constructor(props) { super(props); this.state = { mostUsedTrinkets: [], mostUsedTalents: [], similiarKillTimes: [], closestKillTimes: [], items: ITEMS, loaded: false, message: 'Loading statistics...', }; this.load = this.load.bind(this); this.load(); } addItem(array, item) { //add item to arry or increase amount by one if it exists if (item.id === null || item.id === 0) { return array; } const index = array.findIndex(elem => elem.id === item.id); if (index === -1) { array.push({ id: item.id, name: item.name.replace(/\\'/g, '\''), quality: item.quality, icon: item.icon, amount: 1, }); } else { array[index].amount += 1; } return array; } load() { switch (SPECS[this.props.spec].role) { case ROLES.HEALER: this.metric = 'hps'; break; default: this.metric = 'dps'; break; } const now = new Date(); const onejan = new Date(now.getFullYear(), 0, 1); const currentWeek = Math.ceil((((now - onejan) / 86400000) + onejan.getDay() + 1) / 7); // current calendar-week return fetchWcl(`rankings/encounter/${this.props.currentBoss}`, { class: SPECS[this.props.spec].ranking.class, spec: SPECS[this.props.spec].ranking.spec, difficulty: this.props.difficulty, limit: this.LIMIT, //Currently does nothing but if Kihra reimplements it'd be nice to have metric: this.metric, cache: currentWeek, // cache for a week }).then((stats) => { const talentCounter = [[], [], [], [], [], [], []]; const talents = []; let trinkets = []; let azerite = []; const similiarKillTimes = []; //These are the reports within the defined variance of the analyzed log const closestKillTimes = []; //These are the reports closest to the analyzed log regardless of it being within variance or not stats.rankings.forEach(rank => { rank.talents.forEach((talent, index) => { if (talent.id !== null && talent.id !== 0) { talentCounter[index].push(talent.id); } }); rank.gear.forEach((item, itemSlot) => { if (itemSlot === 12 || itemSlot === 13) { trinkets = this.addItem(trinkets, item); } }); rank.azeritePowers.forEach((azeritePower) => { azerite = this.addItem(azerite, azeritePower); }); if (this.props.duration > rank.duration * (1 - this.durationVariancePercentage) && this.props.duration < rank.duration * (1 + this.durationVariancePercentage)) { similiarKillTimes.push({ rank, variance: rank.duration - this.props.duration > 0 ? rank.duration - this.props.duration : this.props.duration - rank.duration }); } closestKillTimes.push({ rank, variance: rank.duration - this.props.duration > 0 ? rank.duration - this.props.duration : this.props.duration - rank.duration }); }); talentCounter.forEach(row => { const talentRow = row.reduce((prev, cur) => { prev[cur] = (prev[cur] || 0) + 1; return prev; }, {}); talents.push(talentRow); }); trinkets.sort((a, b) => { return (a.amount < b.amount) ? 1 : ((b.amount < a.amount) ? -1 : 0); }); azerite.sort((a, b) => { return (a.amount < b.amount) ? 1 : ((b.amount < a.amount) ? -1 : 0); }); similiarKillTimes.sort((a, b) => { return a.variance - b.variance; }); closestKillTimes.sort((a, b) => { return a.variance - b.variance; }); this.setState({ mostUsedTrinkets: trinkets.slice(0, this.SHOW_TOP_ENTRYS), mostUsedAzerite: azerite.slice(0, this.SHOW_TOP_ENTRYS_AZERITE), mostUsedTalents: talents, similiarKillTimes: similiarKillTimes.slice(0, this.SHOW_CLOSEST_KILL_TIME_LOGS), closestKillTimes: closestKillTimes.slice(0, this.SHOW_CLOSEST_KILL_TIME_LOGS), loaded: true, }); //fetch all missing icons from bnet-api and display them this.fillMissingIcons(); }).catch((err) => { this.setState({ message: 'Something went wrong.', }); }); } fillMissingIcons() { this.state.mostUsedTrinkets.forEach(trinket => { if (ITEMS[trinket.id] === undefined) { return fetch(makeItemApiUrl(trinket.id)) .then(response => response.json()) .then(data => { const updatedItems = this.state.items; updatedItems[trinket.id] = { icon: data.icon, id: trinket.id, name: trinket.name, }; this.setState({ items: updatedItems, }); this.forceUpdate(); }) .catch(err => { }); // ignore errors; } return null; }); } singleItem(item) { return ( <div key={item.id} className="col-md-12 flex-main" style={{ textAlign: 'left', margin: '5px auto' }}> <div className="row"> <div className="col-md-2" style={{ opacity: '.8', fontSize: '.9em', lineHeight: '2em', textAlign: 'right' }}> {formatPercentage(item.amount / this.amountOfParses, 0)}% </div> <div className="col-md-10"> <ItemLink id={item.id} className={item.quality} icon={false}> <Icon icon={this.state.items[item.id] === undefined ? this.state.items[0].icon : this.state.items[item.id].icon} className={item.quality} style={{ width: '2em', height: '2em', border: '1px solid', marginRight: 10 }} /> {item.name} </ItemLink> </div> </div> </div> ); } singleTrait(trait) { return ( <div key={trait.id} className="col-md-12 flex-main" style={{ textAlign: 'left', margin: '5px auto' }}> <div className="row"> <div className="col-md-2" style={{ opacity: '.8', fontSize: '.9em', lineHeight: '2em', textAlign: 'right' }}> {trait.amount}x </div> <div className="col-md-10"> <SpellLink id={trait.id} icon={false}> <Icon icon={trait.icon} style={{ width: '2em', height: '2em', border: '1px solid', marginRight: 10 }} /> {trait.name} </SpellLink> </div> </div> </div> ); } singleLog(log) { return ( <div key={log.reportID} className="col-md-12 flex-main" style={{ textAlign: 'left', margin: '5px auto' }}> <div className="row" style={{ opacity: '.8', fontSize: '.9em', lineHeight: '2em' }}> <div className="flex-column col-md-6"> <a href={`https://wowanalyzer.com/report/${log.reportID}/${log.fightID}/`} target="_blank" rel="noopener noreferrer" > <div> {log.name} ({log.itemLevel}) </div> </a> <div> {formatDuration(log.duration / 1000)} ({log.duration > this.props.duration ? ((log.duration - this.props.duration) / 1000).toFixed(1) + 's slower' : ((this.props.duration - log.duration) / 1000).toFixed(1) + 's faster'}) </div> </div> <div className="col-md-6"> {formatThousands(log.total)} {this.metric} </div> </div> </div> ); } similiarLogs() { return ( <div className="col-md-12 flex-main" style={{ textAlign: 'left', margin: '5px auto' }}> {this.state.similiarKillTimes.length > 1 ? 'These are' : 'This is'} {this.state.similiarKillTimes.length} of the top {this.amountOfParses} {this.state.similiarKillTimes.length > 1 ? 'logs' : 'log'} that {this.state.similiarKillTimes.length > 1 ? 'are' : 'is'} closest to your kill-time within {formatPercentage(this.durationVariancePercentage, 0)}% variance. {this.state.similiarKillTimes.map(log => this.singleLog(log.rank))} </div> ); } closestLogs() { return ( <div className="col-md-12 flex-main" style={{ textAlign: 'left', margin: '5px auto' }}> {this.state.closestKillTimes.length > 1 ? 'These are' : 'This is'} {this.state.closestKillTimes.length} of the top {this.amountOfParses} {this.state.closestKillTimes.length > 1 ? 'logs' : 'log'} that {this.state.closestKillTimes.length > 1 ? 'are' : 'is'} closest to your kill-time. Large differences won't be good for comparing. {this.state.closestKillTimes.map(log => this.singleLog(log.rank))} </div> ); } render() { const rows = [15, 30, 45, 60, 75, 90, 100]; if (!this.state.loaded) { return ( <div className="panel-heading" style={{ marginTop: 40, padding: 20, boxShadow: 'none', borderBottom: 0 }}> <ActivityIndicator text={this.state.message} /> </div> ); } // If there are below 100 parses for a given spec, use this amount to divide with to get accurate percentages. // This also enables us to work around certain logs being anonymised - as this will then ignore those, and cause us to divide by 99, making our percentages accurate again. this.amountOfParses = Object.values(this.state.mostUsedTalents[LEVEL_15_TALENT_ROW_INDEX]).reduce((total, parses) => total + parses, 0); return ( <> <h1>Statistics for this fight using the top {this.amountOfParses} logs, ranked by {this.metric.toLocaleUpperCase()}</h1> <div className="row"> <div className="col-md-12" style={{ padding: '0 30px' }}> <div className="row"> <div className="col-md-4"> <div className="row" style={{ marginBottom: '2em' }}> <div className="col-md-12"> <h2>Most used Trinkets</h2> </div> </div> <div className="row" style={{ marginBottom: '2em' }}> {this.state.mostUsedTrinkets.map(trinket => this.singleItem(trinket))} </div> <div className="row" style={{ marginBottom: '2em' }}> <div className="col-md-12"> <h2>Most used Azerite Traits</h2> </div> </div> <div className="row" style={{ marginBottom: '2em' }}> {this.state.mostUsedAzerite.map(azerite => this.singleTrait(azerite))} </div> </div> <div className="col-md-4"> <div className="row" style={{ marginBottom: '2em' }}> <div className="col-md-12"> <h2>Most used Talents</h2> </div> </div> {this.state.mostUsedTalents.map((row, index) => ( <div key={index} className="row" style={{ marginBottom: 15, paddingLeft: 20 }}> <div className="col-lg-1 col-xs-2" style={{ lineHeight: '3em', textAlign: 'right' }}>{rows[index]}</div> {Object.keys(row).sort((a, b) => row[b] - row[a]).map((talent, talentIndex) => ( <div key={talentIndex} className="col-lg-3 col-xs-4" style={{ textAlign: 'center' }}> <SpellLink id={Number(talent)} icon={false}> <SpellIcon style={{ width: '3em', height: '3em' }} id={Number(talent)} noLink /> </SpellLink> <span style={{ textAlign: 'center', display: 'block' }}>{formatPercentage(row[talent] / this.amountOfParses, 0)}%</span> </div> ))} </div> ))} </div> <div className="col-md-4"> <div className="row" style={{ marginBottom: '2em' }}> <div className="col-md-12"> <h2>{this.state.similiarKillTimes.length > 0 ? 'Similiar' : 'Closest'} kill times</h2> </div> </div> <div className="row" style={{ marginBottom: '2em' }}> {this.state.similiarKillTimes.length > 0 ? this.similiarLogs() : ''} {this.state.similiarKillTimes.length === 0 && this.state.closestKillTimes.length > 0 ? this.closestLogs() : ''} </div> </div> </div> </div> </div> </> ); } } export default EncounterStats;
src/components/shared/top-bar/action-items/action-items.spec.js
david-mart/react-boilerplate-edited
import React from 'react'; import { shallow } from 'enzyme'; import { expect } from 'chai'; import ActionItems from './index'; describe('<ActionItems />', () => { it('should have 5 action button', () => { const wrapper = shallow(<ActionItems />); const expected = 5; const actual = wrapper.find('IconButton').length; expect(actual).equals(expected); }); it('should have avatar container', () => { const wrapper = shallow(<ActionItems />); const expected = 1; const actual = wrapper.find('Avatar').length; expect(actual).equals(expected); }); });
views/blocks/Photo/Photo.js
dimastark/team5
import React from 'react'; import './Photo.css'; import b from 'b_'; const photo = b.lock('photo'); function Status(props) { if (props.userIsCreator || props.status === null) { return null; } return ( <div className={['control', photo('checker')].join(' ')}> <i className={`fa ${props.status ? 'fa-check' : 'fa-times'}`} area-hidden="true"></i> </div> ); } function Button(props) { if (props.userIsCreator || props.status) { return null; } return ( <button className={['control', photo('button')].join(' ')} disabled={!props.existGeolocation || props.sending} onClick={props.handleClick}> <i className={`fa fa-crosshairs ${props.sending ? 'fa-spin' : ''}`} aria-hidden="true"></i> </button> ); } function ShowDescriptionButton(props) { if (!(props.userIsCreator || props.status) || !props.description) { return null; } return ( <button className={['control', photo('button')].join(' ')} onClick={props.handleShowDescription}> <i className="fa fa-info" aria-hidden="true"></i> </button> ); } export default class Photo extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); this.handleShowDescription = this.handleShowDescription.bind(this); this.state = { showDescription: false }; } handleShowDescription() { this.setState(prevState => ({showDescription: !prevState.showDescription})); } handleClick() { this.props.canSend(canSend => { if (canSend) { this.props.onAction(); } }); } render() { const { existGeolocation, userIsCreator, description, sending, status, title, src } = this.props; return ( <div className={photo()}> <div className={photo('img', {hidden: this.state.showDescription})}> <Status status={status} userIsCreator={userIsCreator}/> <Button status={status} existGeolocation={existGeolocation} userIsCreator={userIsCreator} sending={sending} handleClick={this.handleClick} /> <ShowDescriptionButton status={status} handleShowDescription={this.handleShowDescription} userIsCreator={userIsCreator} description={description} /> <img src={src}></img> {(userIsCreator || status) && title && <p className={photo('title')}> {title} </p> } </div> {(userIsCreator || status) && description && <div className={photo('description', {show: this.state.showDescription})}> <p>{description}</p> <button className={['control', photo('button', {back: true})].join(' ')} onClick={this.handleShowDescription}> <i className="fa fa-times" aria-hidden="true"></i> </button> </div> } </div> ); } }
packages/react/src/components/molecules/SocialLinks/index.js
massgov/mayflower
/** * SocialLinks module. * @module @massds/mayflower-react/SocialLinks * @requires module:@massds/mayflower-assets/scss/02-molecules/social-links * @requires module:@massds/mayflower-assets/scss/01-atoms/svg-icons * @requires module:@massds/mayflower-assets/scss/01-atoms/svg-loc-icons */ import React from 'react'; import PropTypes from 'prop-types'; // eslint-disable-next-line import/no-unresolved import IconFacebook from 'MayflowerReactBase/Icon/IconFacebook'; // eslint-disable-next-line import/no-unresolved import IconTwitter from 'MayflowerReactBase/Icon/IconTwitter'; // eslint-disable-next-line import/no-unresolved import IconLinkedin from 'MayflowerReactBase/Icon/IconLinkedin'; // eslint-disable-next-line import/no-unresolved import IconYoutube from 'MayflowerReactBase/Icon/IconYoutube'; // eslint-disable-next-line import/no-unresolved import IconInstagram from 'MayflowerReactBase/Icon/IconInstagram'; const SocialLinks = (socialLinks) => ( <section className="ma__social-links"> {socialLinks.label && <span className="ma__social-links__label">{socialLinks.label}</span>} <ul className="ma__social-links__items"> { socialLinks.items.map((socialLink, i) => ( /* eslint-disable-next-line react/no-array-index-key */ <SocialLink {...socialLink} key={`socialLink_${i}`} index={i} /> )) } </ul> </section> ); const SocialLink = (socialLink) => { const icons = { facebook: IconFacebook, twitter: IconTwitter, linkedin: IconLinkedin, youtube: IconYoutube, instagram: IconInstagram }; const IconComponent = socialLink.linkType ? icons[socialLink.linkType] : null; return( <li className="ma__social-links__item"> <a href={socialLink.href} className="ma__social-links__link js-social-share" data-social-share={socialLink.linkType} aria-label={socialLink.altText} > <IconComponent /> </a> </li> ); }; SocialLink.propTypes = { /** The URL for the link */ href: PropTypes.string.isRequired, /** The type of social link and the icon name */ linkType: PropTypes.oneOf(['facebook', 'twitter', 'linkedin', 'youtube', 'instagram']).isRequired, /** Alt text for accessibility */ altText: PropTypes.string.isRequired }; SocialLinks.propTypes = { /** The optional label for the social links */ label: PropTypes.string, /** The social links to display */ items: PropTypes.arrayOf(PropTypes.shape(SocialLink.propTypes)).isRequired }; SocialLinks.defaultProps = { label: '' }; export default SocialLinks;
project/react-ant-multi-pages/src/pages/index/containers/AutoDestination/Item/index.js
FFF-team/generator-earth
import React from 'react' import moment from 'moment' import { DatePicker, Button, Form, Input, Col } from 'antd' import BaseContainer from 'ROOT_SOURCE/base/BaseContainer' import request from 'ROOT_SOURCE/utils/request' import { mapMoment } from 'ROOT_SOURCE/utils/fieldFormatter' import Rules from 'ROOT_SOURCE/utils/validateRules' const FormItem = Form.Item export default Form.create()(class extends BaseContainer { /** * 提交表单 */ submitForm = (e) => { e && e.preventDefault() const { form } = this.props form.validateFieldsAndScroll(async (err, values) => { if (err) { return; } // 提交表单最好新起一个事务,不受其他事务影响 await this.sleep() let _formData = { ...form.getFieldsValue() } // _formData里的一些值需要适配 _formData = mapMoment(_formData, 'YYYY-MM-DD HH:mm:ss') // action await request.post('/asset/updateAsset', _formData) //await this.props.updateForm(_formData) // 提交后返回list页 this.props.history.push(`${this.context.CONTAINER_ROUTE_PREFIX}/list`) }) } constructor(props) { super(props); this.state = {}; } async componentDidMount() { let { data } = await request.get('/asset/viewAsset', {id: this.props.match.params.id /*itemId*/}) this.setState(data) } render() { let { form, formData } = this.props let { getFieldDecorator } = form const { id, assetName, contract, contractDate, contacts, contactsPhone } = this.state return ( <div className="ui-background"> <Form layout="inline" onSubmit={this.submitForm}> {getFieldDecorator('id', { initialValue: id===undefined ? '' : +id})( <Input type="hidden" /> )} <FormItem label="资产方名称"> {getFieldDecorator('assetName', { rules: [{ required: true }], initialValue: assetName || '' })(<Input disabled />)} </FormItem> <FormItem label="签约主体"> {getFieldDecorator('contract', { rules: [{ required: true }], initialValue: contract || '' })(<Input disabled />)} </FormItem> <FormItem label="签约时间"> {getFieldDecorator('contractDate', { rules: [{ type: 'object', required: true }], initialValue: contractDate && moment(contractDate) })(<DatePicker showTime format='YYYY年MM月DD HH:mm:ss' style={{ width: '100%' }} />)} </FormItem> <FormItem label="联系人"> {getFieldDecorator('contacts', { initialValue: contacts || '' })(<Input />)} </FormItem> <FormItem label="联系电话" hasFeedback> {getFieldDecorator('contactsPhone', { rules: [{ pattern: Rules.phone, message: '无效' }], initialValue: contactsPhone || '' })(<Input maxLength="11" />)} </FormItem> <FormItem> <Button type="primary" htmlType="submit"> 提交 </Button> </FormItem> <FormItem> <Button type="primary" onClick={e=>window.history.back()}> 取消/返回 </Button> </FormItem> </Form> </div> ) } })
examples/BorderlessTable.js
15lyfromsaturn/react-materialize
import React from 'react'; import Table from '../src/Table'; export default <Table> <thead> <tr> <th data-field="id">Name</th> <th data-field="name">Item Name</th> <th data-field="price">Item Price</th> </tr> </thead> <tbody> <tr> <td>Alvin</td> <td>Eclair</td> <td>$0.87</td> </tr> <tr> <td>Alan</td> <td>Jellybean</td> <td>$3.76</td> </tr> <tr> <td>Jonathan</td> <td>Lollipop</td> <td>$7.00</td> </tr> </tbody> </Table>;
src/MasterPassword/SetupMasterPassword.js
Lynx-Productions/OPeM
/*** * Copyright 2017 - present Lynx Productions * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // @ts-check import React, { Component } from 'react'; import { connect } from 'react-redux'; import MasterPassword from './MasterPassword'; import { addMasterPassword } from '../actions'; export class SetupMasterPassword extends Component { constructor(props) { super(props); this.createMasterPassword = this.createMasterPassword.bind(this); } createMasterPassword(e, masterPassword) { e.preventDefault(); const { addMasterPassword } = this.props; addMasterPassword(masterPassword); } render() { return ( <MasterPassword title="Create a Master Password" btnTitle="Create" onSubmit={this.createMasterPassword} /> ); } } const mapStateToProps = state => { return {}; }; const mapDispatchToProps = dispatch => { return { addMasterPassword: masterPassword => { dispatch(addMasterPassword(masterPassword)); } }; }; export default connect(mapStateToProps, mapDispatchToProps)( SetupMasterPassword );
src/containers/SigninPage.js
ASIX-ALS/asix-final-project-frontend
import React from 'react'; import SigninPageLayout from '../components/SigninPageLayout'; class SigninPage extends React.Component { render() { return ( <SigninPageLayout /> ); } } export default SigninPage;
admin/client/components/FlashMessages.js
wmertens/keystone
import React from 'react'; import { Alert } from 'elemental'; var FlashMessage = React.createClass({ displayName: 'FlashMessage', propTypes: { message: React.PropTypes.oneOfType([ React.PropTypes.object, React.PropTypes.string, ]), type: React.PropTypes.string, }, renderMessage (message) { if (typeof message === 'string') return <span>{message}</span>; const title = message.title ? <h4>{message.title}</h4> : null; const detail = message.detail ? <p>{message.detail}</p> : null; const list = message.list ? ( <ul style={{ marginBottom: 0 }}> {message.list.map((item, i) => <li key={`i${i}`}>{item}</li>)} </ul> ) : null; return ( <span> {title} {detail} {list} </span> ); }, render () { return <Alert type={this.props.type}>{this.renderMessage(this.props.message)}</Alert>; }, }); var FlashMessages = React.createClass({ displayName: 'FlashMessages', propTypes: { messages: React.PropTypes.oneOfType([ React.PropTypes.bool, React.PropTypes.shape({ error: React.PropTypes.array, hilight: React.PropTypes.array, info: React.PropTypes.array, success: React.PropTypes.array, warning: React.PropTypes.array, }), ]), }, renderMessages (messages, type) { if (!messages || !messages.length) return null; return messages.map((message, i) => { return <FlashMessage message={message} type={type} key={`i${i}`} />; }); }, renderTypes (types) { return Object.keys(types).map(type => this.renderMessages(types[type], type)); }, render () { if (!this.props.messages) return null; return ( <div className="flash-messages"> {this.renderTypes(this.props.messages)} </div> ); }, }); module.exports = FlashMessages;
client/client.js
CityRay/React15-Todo-List
import React from 'react'; import { render } from 'react-dom'; import App from '../components/App'; import configureStore from '../redux/store'; import { Provider } from 'react-redux'; // configure and create our store // createStore(reducres, initialState) const initialState = { todos: [ { id: 0, completed: false, text: 'Initial todo for demo purposes' } ], user: { username: 'Ray Lin', memberId: '69' } }; let store = configureStore(initialState); // Provider 是使用在應用程式的根元件內,負責將唯一的 store 傳下去給其他子元件 const root = ( <Provider store={store}> <App /> </Provider> ); // Render render( root, document.getElementById('app') );
components/AR/ViroARImageMarker.js
viromedia/viro
/** * Copyright (c) 2017-present, Viro Media, 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. * * @providesModule ViroARImageMarker */ 'use strict'; import { requireNativeComponent, View, StyleSheet, findNodeHandle, Platform } from 'react-native'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { checkMisnamedProps } from '../Utilities/ViroProps'; var createReactClass = require('create-react-class'); /** * Container for Viro Components anchored to a detected image. */ var ViroARImageMarker = createReactClass({ propTypes: { ...View.propTypes, target: PropTypes.string, pauseUpdates: PropTypes.bool, renderingOrder: PropTypes.number, visible: PropTypes.bool, opacity: PropTypes.number, ignoreEventHandling: PropTypes.bool, dragType: PropTypes.oneOf(["FixedDistance", "FixedDistanceOrigin", "FixedToWorld", "FixedToPlane"]), dragPlane: PropTypes.shape({ planePoint : PropTypes.arrayOf(PropTypes.number), planeNormal : PropTypes.arrayOf(PropTypes.number), maxDistance : PropTypes.number }), onHover: PropTypes.func, onClick: PropTypes.func, onClickState: PropTypes.func, onTouch: PropTypes.func, onScroll: PropTypes.func, onSwipe: PropTypes.func, onDrag: PropTypes.func, onPinch: PropTypes.func, onRotate: PropTypes.func, onFuse: PropTypes.oneOfType([ PropTypes.shape({ callback: PropTypes.func.isRequired, timeToFuse: PropTypes.number }), PropTypes.func ]), onCollision: PropTypes.func, viroTag: PropTypes.string, onAnchorFound: PropTypes.func, onAnchorUpdated: PropTypes.func, onAnchorRemoved: PropTypes.func, }, _onHover: function(event: Event) { this.props.onHover && this.props.onHover(event.nativeEvent.isHovering, event.nativeEvent.position, event.nativeEvent.source); }, _onClick: function(event: Event) { this.props.onClick && this.props.onClick(event.nativeEvent.position, event.nativeEvent.source); }, _onClickState: function(event: Event) { this.props.onClickState && this.props.onClickState(event.nativeEvent.clickState, event.nativeEvent.position, event.nativeEvent.source); let CLICKED = 3; // Value representation of Clicked ClickState within EventDelegateJni. if (event.nativeEvent.clickState == CLICKED){ this._onClick(event) } }, _onTouch: function(event: Event) { this.props.onTouch && this.props.onTouch(event.nativeEvent.touchState, event.nativeEvent.touchPos, event.nativeEvent.source); }, _onScroll: function(event: Event) { this.props.onScroll && this.props.onScroll(event.nativeEvent.scrollPos, event.nativeEvent.source); }, _onSwipe: function(event: Event) { this.props.onSwipe && this.props.onSwipe(event.nativeEvent.swipeState, event.nativeEvent.source); }, _onDrag: function(event: Event) { this.props.onDrag && this.props.onDrag(event.nativeEvent.dragToPos, event.nativeEvent.source); }, _onPinch: function(event: Event) { this.props.onPinch && this.props.onPinch(event.nativeEvent.pinchState, event.nativeEvent.scaleFactor, event.nativeEvent.source); }, _onRotate: function(event: Event) { this.props.onRotate && this.props.onRotate(event.nativeEvent.rotateState, event.nativeEvent.rotationFactor, event.nativeEvent.source); }, _onFuse: function(event: Event){ if (this.props.onFuse){ if (typeof this.props.onFuse === 'function'){ this.props.onFuse(event.nativeEvent.source); } else if (this.props.onFuse != undefined && this.props.onFuse.callback != undefined){ this.props.onFuse.callback(event.nativeEvent.source); } } }, _onCollision: function(event: Event){ if (this.props.onCollision){ this.props.onCollision(event.nativeEvent.viroTag, event.nativeEvent.collidedPoint, event.nativeEvent.collidedNormal); } }, _onAnchorFound: function(event: Event) { if (this.props.onAnchorFound) { this.props.onAnchorFound(event.nativeEvent.anchorFoundMap); } }, _onAnchorUpdated: function(event: Event) { if (this.props.onAnchorUpdated) { this.props.onAnchorUpdated(event.nativeEvent.anchorUpdatedMap); } }, _onAnchorRemoved: function(event: Event) { if (this.props.onAnchorRemoved) { this.props.onAnchorRemoved(); } }, setNativeProps: function(nativeProps) { this._component.setNativeProps(nativeProps); }, render: function() { // Uncomment this line to check for misnamed props //checkMisnamedProps("ViroARImageMarker", this.props); let timeToFuse = undefined; if (this.props.onFuse != undefined && typeof this.props.onFuse === 'object'){ timeToFuse = this.props.onFuse.timeToFuse; } return ( <VRTARImageMarker {...this.props} ref={ component => {this._component = component; }} canHover={this.props.onHover != undefined} canClick={this.props.onClick != undefined || this.props.onClickState != undefined} canTouch={this.props.onTouch != undefined} canScroll={this.props.onScroll != undefined} canSwipe={this.props.onSwipe != undefined} canDrag={this.props.onDrag != undefined} canPinch={this.props.onPinch != undefined} canRotate={this.props.onRotate != undefined} canFuse={this.props.onFuse != undefined} onHoverViro={this._onHover} onClickViro={this._onClickState} onTouchViro={this._onTouch} onScrollViro={this._onScroll} onSwipeViro={this._onSwipe} onDragViro={this._onDrag} onPinchViro={this._onPinch} onRotateViro={this._onRotate} onFuseViro={this._onFuse} timeToFuse={timeToFuse} canCollide={this.props.onCollision != undefined} onCollisionViro={this._onCollision} onAnchorFoundViro={this._onAnchorFound} onAnchorUpdatedViro={this._onAnchorUpdated} onAnchorRemovedViro={this._onAnchorRemoved} /> ); } }); var VRTARImageMarker = requireNativeComponent( 'VRTARImageMarker', ViroARImageMarker, { nativeOnly: { position : [], scale : [], rotation : [], scalePivot : [], rotationPivot : [], animation : {}, materials: [], physicsBody : {}, transformBehaviors: [], hasTransformDelegate:true, canHover: true, canClick: true, canTouch: true, canScroll: true, canSwipe: true, canDrag: true, canPinch: true, canRotate: true, canFuse: true, onHoverViro:true, onClickViro:true, onTouchViro:true, onScrollViro:true, onSwipeViro:true, onDragViro:true, onPinchViro:true, onRotateViro:true, onFuseViro:true, timeToFuse:true, canCollide:true, onCollisionViro:true, onAnchorFoundViro:true, onAnchorUpdatedViro:true, onAnchorRemovedViro:true, } } ); module.exports = ViroARImageMarker;
node_modules/react-router/es/IndexRoute.js
SpaceyRezum/react-trivia-game
import React from 'react'; import warning from './routerWarning'; import invariant from 'invariant'; import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils'; import { component, components, falsy } from './InternalPropTypes'; var func = React.PropTypes.func; /** * An <IndexRoute> is used to specify its parent's <Route indexRoute> in * a JSX route config. */ /* eslint-disable react/require-render-return */ var IndexRoute = React.createClass({ displayName: 'IndexRoute', statics: { createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = _createRouteFromReactElement(element); } else { process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRoute> does not make sense at the root of your route config') : void 0; } } }, propTypes: { path: falsy, component: component, components: components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRoute> elements are for router configuration only and should not be rendered') : invariant(false) : void 0; } }); export default IndexRoute;
src/pages/providers/lenon.js
gelo592/IntegrativeMed-Site
import React from 'react' import Layout from '../../components/layout' import SEO from '../../components/seo' import lenon from '../../images/lenon.jpg' import Typography from '@material-ui/core/Typography'; import Grid from '@material-ui/core/Grid'; import SubLayout from '../../components/sublayout'; import { withStyles } from '@material-ui/core/styles'; import { colors } from '../../constants/constants'; import withRoot from '../../components/withRoot'; const styles = theme => ({ para: { lineHeight: 2.2, fontSize: 17, paddingBottom: 20, color: colors.text, } }); const LenonPage = ({ classes }) => ( <Layout> <SEO title="Providers : Rachel Lenon" /> <SubLayout title={'Rachel Lenon, FNP-BC,'}> <Grid container justify='center'> <Grid item xs={8}> <img src={lenon} alt="Rachel Lenon" style={{ float: 'left', borderRadius: 12, width: 130, margin: 10 }} /> <Typography className={classes.para}> <b>Rachel Lenon, FNP-BC,</b> is a family nurse practitioner available to provide primary and integrative healthcare to patients of all ages. Rachel received her Master of Science in Nursing in the Family Nurse Practitioner program at the University of Missouri in 2011. She has completed advanced training in integrative and functional medicine including IFM’s (Institute of Functional Medicine) Applying Functional Medicine in Clinical Practice, Advanced Autoimmune Module, and Functional Medicine in Pediatrics Module. She continues on-going advanced training in integrative and functional medicine. </Typography> <Typography className={classes.para}> Rachel's passion for preventative medicine began while working as an RN in the Cardiac ICU. It was there she saw firsthand the value of prevention and healthy lifestyle to avoid chronic disease. Rachel worked as a nurse practitioner in a family medicine clinic, gaining valuable experience in treating a wide range of both acute and chronic illnesses. </Typography> <Typography className={classes.para}> Rachel joined the team at the Integrative Medicine Clinic (IMC) in June of 2014. Her goal is to provide a holistic approach to healthcare that focuses on prevention and looking for the root causes of a patient's health concerns, rather than just treating the symptoms. Lifestyle modifications such as stress management, regular exercise, nutrient dense diet, and quality sleep are foundational aspects of the Integrative Medicine approach. She provides to patients of all ages who prefer an integrative approach to medicine. </Typography> </Grid> </Grid> </SubLayout> </Layout> ) export default withRoot(withStyles(styles)(LenonPage))
demos/function-tree-demos/src/mobx/components/App/index.js
idream3/cerebral
import React from 'react' import run from '../../run' import './styles.css' import AddAssignment from '../AddAssignment' import Assignments from '../Assignments' import appMounted from '../../events/appMounted' class App extends React.Component { componentDidMount () { run('appMounted', appMounted) } render () { return ( <div className='App'> <AddAssignment store={this.props.store} /> <Assignments store={this.props.store} /> </div> ) } } export default App
thingmenn-frontend/src/components/party-details/index.js
baering/thingmenn
import React from 'react' import partyService from '../../services/party-service' import totalsService from '../../services/totals-service' import partySummaryService from '../../services/party-summary-service' import KPI from '../../widgets/key-performance-indicator' import Topics from '../../widgets/topics' import Topic from '../../widgets/topics/topic' import ColorLegend from '../../widgets/color-legend' import DetailsHeader from '../../widgets/details-header' import DetailsMenu from '../../widgets/details-menu' import Piechart from '../../widgets/piechart' import Speeches from '../../widgets/speeches' import BarChart from '../../widgets/bar-chart' import Items from '../../widgets/items' import WeekdayHourMatrix from '../../widgets/weekday-hour-matrix' import './styles.css' export default class PartyDetails extends React.Component { constructor(props) { super(props) this.state = { party: { lthings: [] }, lthing: null, lthings: [], lthingLookup: {}, voteSummary: { votePercentages: [], voteSummary: [] }, speechSummary: [], documentSummary: [], absentSummary: {}, votePositions: [], speechPositions: [], documentPositions: [], } } componentDidMount() { this.getData() } componentWillReceiveProps(nextProps) { this.getData(nextProps.routeParams.partyId, nextProps.routeParams.lthing) } getData(id, lthing) { const partyId = id || this.props.params.partyId const lthingId = lthing || this.props.params.lthing partyService.getPartyDetailsByLthing(partyId, 'allt').then((party) => { this.setState(() => ({ party })) }) partySummaryService .getPartyVoteSummaryByLthing(partyId, lthingId) .then((voteSummary) => { this.setState(() => ({ voteSummary, })) }) partySummaryService .getPartySpeechSummaryByLthing(partyId, lthingId) .then((speechSummary) => { this.setState(() => ({ speechSummary, })) }) partySummaryService .getPartyDocumentSummaryByLthing(partyId, lthingId) .then((documentSummary) => { this.setState(() => ({ documentSummary, })) }) partySummaryService .getPartyAbsentSummaryByLthing(partyId, lthingId) .then((absentSummary) => { this.setState(() => ({ absentSummary, })) }) partySummaryService .getPartyVotePositionsByLthing(partyId, lthingId) .then((votePositions) => { this.setState(() => ({ votePositions, })) }) partySummaryService .getPartySpeechPositionsByLthing(partyId, lthingId) .then((speechPositions) => { this.setState(() => ({ speechPositions, })) }) partySummaryService .getPartyDocumentPositionsByLthing(partyId, lthingId) .then((documentPositions) => { this.setState(() => ({ documentPositions, })) }) totalsService.getLthings().then((lthings) => { const lthingLookup = {} lthings.forEach((lthing) => (lthingLookup[lthing.id] = lthing)) this.setState(() => ({ lthings, lthingLookup, })) }) } generateLthingList(party, lthings, lthingLookup) { const initialList = [ { name: 'Samtölur', url: `/thingflokkar/${party.id}/thing/allt`, }, ] if (!party.lthings.length || !lthings.length) { return initialList } const lthingsFormatted = party.lthings.map((lthingInfo) => { return { year: lthingLookup[lthingInfo.lthing].start.split('.')[2], thing: lthingInfo.lthing, url: `/thingflokkar/${party.id}/thing/${lthingInfo.lthing}`, } }) return initialList.concat(lthingsFormatted) } getDividerSize(tabName, lthing) { if (lthing === 'allt') { if (tabName === 'speeches') { return 15 } else if (tabName === 'documents') { return 3 } } if (tabName === 'speeches') { return 3 } else if (tabName === 'documents') { return 0.4 } return 1 } render() { const { party, lthings, lthingLookup, voteSummary, speechSummary, documentSummary, votePositions, speechPositions, documentPositions, } = this.state const lthing = this.props.params.lthing return ( <div className="fill"> <DetailsMenu menuItems={this.generateLthingList(party, lthings, lthingLookup)} /> <DetailsHeader speechSummary={speechSummary} voteSummary={voteSummary} id={party.id} mpName={party.name} description={party.about} imagePath={party.imagePath} /> <div className="Details"> <KPI voteSummary={voteSummary} speechSummary={speechSummary} documentSummary={documentSummary} /> <div className="Details-item Details-item--large Details-item--no-padding"> <Topics> {(activeTab) => ( <span> <Topic active={activeTab === 0}> <div className="Topic-column"> <h1 className="Topic-heading"> Skipting atkvæða eftir flokkum </h1> <ColorLegend /> {votePositions.map((sectionSummary) => ( <BarChart sectionSummary={sectionSummary} key={sectionSummary.name} /> ))} </div> <div className="Topic-column"> <h1 className="Topic-heading">Skipting atkvæða</h1> <Piechart voteSummary={voteSummary} /> <ColorLegend includeAbsent /> </div> {!!this.state.absentSummary && !!this.state.absentSummary.statistics && ( <div className="Topic-column"> <h1 className="Topic-heading">Hvenær fjarverandi</h1> <WeekdayHourMatrix weekdayHourMatrixSummary={this.state.absentSummary} /> </div> )} </Topic> <Topic active={activeTab === 1}> <div className="Topic-column"> <h1 className="Topic-heading">Ræður eftir flokkum</h1> <Items divider={this.getDividerSize('speeches', lthing)} items={speechPositions} /> </div> <div className="Topic-column"> <h1 className="Topic-heading">Skipting ræðutíma</h1> <Speeches speechSummary={speechSummary} /> </div> </Topic> <Topic active={activeTab === 2}> <div className="Topic-column"> <h1 className="Topic-heading">Þingskjöl eftir flokkum</h1> <Items divider={this.getDividerSize('documents', lthing)} items={documentPositions} /> </div> </Topic> </span> )} </Topics> </div> </div> </div> ) } }
definitions/npm/@storybook/addon-actions_v3.x.x/test_addon-actions_v3.x.x.js
splodingsocks/FlowTyped
// @flow import React from 'react'; import { action, decorateAction } from '@storybook/addon-actions' const Button = (props) => <button {...props} />; const firstArgAction = decorateAction([ args => args.slice(0, 1) ]); // $FlowExpectedError const erroneous = action(123); // $FlowExpectedError const erroneousDecorate = decorateAction([ 'a string' ]); const App = () => ( <div> <Button onClick={action('button-click')}> Hello World! </Button> <Button onClick={firstArgAction('button-click')}> Hello World! </Button> </div> );
packages/react/components/searchbar.js
AdrianV/Framework7
import React from 'react'; import Utils from '../utils/utils'; import Mixins from '../utils/mixins'; import __reactComponentDispatchEvent from '../runtime-helpers/react-component-dispatch-event.js'; import __reactComponentSlots from '../runtime-helpers/react-component-slots.js'; import __reactComponentSetProps from '../runtime-helpers/react-component-set-props.js'; class F7Searchbar extends React.Component { constructor(props, context) { super(props, context); this.__reactRefs = {}; } search(query) { if (!this.f7Searchbar) return undefined; return this.f7Searchbar.search(query); } enable() { if (!this.f7Searchbar) return undefined; return this.f7Searchbar.enable(); } disable() { if (!this.f7Searchbar) return undefined; return this.f7Searchbar.disable(); } toggle() { if (!this.f7Searchbar) return undefined; return this.toggle.disable(); } clear() { if (!this.f7Searchbar) return undefined; return this.f7Searchbar.clear(); } onChange(event) { this.dispatchEvent('change', event); } onInput(event) { this.dispatchEvent('input', event); } onFocus(event) { this.dispatchEvent('focus', event); } onBlur(event) { this.dispatchEvent('blur', event); } onSubmit(event) { this.dispatchEvent('submit', event); } onClearButtonClick(event) { this.dispatchEvent('click:clear clickClear', event); } onDisableButtonClick(event) { this.dispatchEvent('click:disable clickDisable', event); } render() { const self = this; let clearEl; let disableEl; const props = self.props; const { placeholder, clearButton, disableButton, disableButtonText, form, noShadow, noHairline, expandable, className, style, id } = props; if (clearButton) { clearEl = React.createElement('span', { className: 'input-clear-button', onClick: self.onClearButtonClick.bind(self) }); } if (disableButton) { disableEl = React.createElement('span', { className: 'searchbar-disable-button', onClick: self.onDisableButtonClick.bind(self) }, disableButtonText); } const SearchbarTag = form ? 'form' : 'div'; const classes = Utils.classNames(className, 'searchbar', { 'no-shadow': noShadow, 'no-hairline': noHairline, 'searchbar-expandable': expandable }, Mixins.colorClasses(props)); return React.createElement(SearchbarTag, { ref: __reactNode => { this.__reactRefs['el'] = __reactNode; }, id: id, style: style, className: classes }, this.slots['before-inner'], React.createElement('div', { className: 'searchbar-inner' }, this.slots['inner-start'], React.createElement('div', { className: 'searchbar-input-wrap' }, this.slots['input-wrap-start'], React.createElement('input', { placeholder: placeholder, type: 'search', onInput: self.onInput.bind(self), onChange: self.onChange.bind(self), onFocus: self.onFocus.bind(self), onBlur: self.onBlur.bind(self) }), React.createElement('i', { className: 'searchbar-icon' }), clearEl, this.slots['input-wrap-end']), disableEl, this.slots['inner-end'], this.slots['default']), this.slots['after-inner']); } componentDidMount() { const self = this; const { init, searchContainer, searchIn, searchItem, hideOnEnableEl, hideOnSearchEl, foundEl, notFoundEl, backdrop, backdropEl, disableButton, ignore, customSearch, removeDiacritics, hideDividers, hideGroups, form } = self.props; if (!init) return; const el = self.refs.el; if (form && el) { self.onSubmitBound = self.onSubmit.bind(self); el.addEventListener('submit', self.onSubmitBound, false); } self.$f7ready(() => { const params = Utils.noUndefinedProps({ el: self.refs.el, searchContainer, searchIn, searchItem, hideOnEnableEl, hideOnSearchEl, foundEl, notFoundEl, backdrop, backdropEl, disableButton, ignore, customSearch, removeDiacritics, hideDividers, hideGroups, on: { search(searchbar, query, previousQuery) { self.dispatchEvent('searchbar:search searchbarSearch', searchbar, query, previousQuery); }, clear(searchbar, previousQuery) { self.dispatchEvent('searchbar:clear searchbarClear', searchbar, previousQuery); }, enable(searchbar) { self.dispatchEvent('searchbar:enable searchbarEnable', searchbar); }, disable(searchbar) { self.dispatchEvent('searchbar:disable searchbarDisable', searchbar); } } }); Object.keys(params).forEach(key => { if (params[key] === '') { delete params[key]; } }); self.f7Searchbar = self.$f7.searchbar.create(params); }); } componentWillUnmount() { const self = this; if (self.props.form && self.refs.el) { self.refs.el.removeEventListener('submit', self.onSubmitBound, false); } if (self.f7Searchbar && self.f7Searchbar.destroy) self.f7Searchbar.destroy(); } get slots() { return __reactComponentSlots(this.props); } dispatchEvent(events, ...args) { return __reactComponentDispatchEvent(this, events, ...args); } get refs() { return this.__reactRefs; } set refs(refs) {} } __reactComponentSetProps(F7Searchbar, Object.assign({ id: [String, Number], noShadow: Boolean, noHairline: Boolean, form: { type: Boolean, default: true }, placeholder: { type: String, default: 'Search' }, disableButton: { type: Boolean, default: true }, disableButtonText: { type: String, default: 'Cancel' }, clearButton: { type: Boolean, default: true }, expandable: Boolean, searchContainer: [String, Object], searchIn: { type: String, default: '.item-title' }, searchItem: { type: String, default: 'li' }, foundEl: { type: [String, Object], default: '.searchbar-found' }, notFoundEl: { type: [String, Object], default: '.searchbar-not-found' }, backdrop: { type: Boolean, default: true }, backdropEl: [String, Object], hideOnEnableEl: { type: [String, Object], default: '.searchbar-hide-on-enable' }, hideOnSearchEl: { type: [String, Object], default: '.searchbar-hide-on-search' }, ignore: { type: String, default: '.searchbar-ignore' }, customSearch: { type: Boolean, default: false }, removeDiacritics: { type: Boolean, default: false }, hideDividers: { type: Boolean, default: true }, hideGroups: { type: Boolean, default: true }, init: { type: Boolean, default: true } }, Mixins.colorProps)); F7Searchbar.displayName = 'f7-searchbar'; export default F7Searchbar;
app/components/Loading/__tests__/index-test.js
nelsonomuto/budgeting-sample-app-webpack2
import React from 'react'; import renderer from 'react-test-renderer'; import Loading from '../'; it('renders correctly', () => { const tree = renderer.create(<Loading />).toJSON(); expect(tree).toMatchSnapshot(); });
src/pages/settings/settings-email.js
Lokiedu/libertysoil-site
/* This file is a part of libertysoil.org website Copyright (C) 2016 Loki Education (Social Enterprise) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import ApiClient from '../../api/client'; import { API_HOST } from '../../config'; import { ActionsTrigger } from '../../triggers'; import { createSelector, currentUserSelector } from '../../selectors'; class SettingsEmailPage extends React.Component { static displayName = 'SettingsEmailPage'; static propTypes = { dispatch: PropTypes.func.isRequired, }; handleMuteAllPosts = async () => { const client = new ApiClient(API_HOST); const triggers = new ActionsTrigger(client, this.props.dispatch); let comment_notifications; if (this.form.mute_all_posts.checked) { comment_notifications = 'off'; } else { comment_notifications = 'on'; } await triggers.updateUserInfo({ more: { comment_notifications } }); }; render() { const { current_user, is_logged_in, } = this.props; if (!is_logged_in) { return false; } return ( <div className="paper"> <Helmet title="Email Settings on " /> <div className="paper__page"> <h2 className="content__sub_title layout__row layout__row-small">Email settings</h2> <div className="layout__row"> <form className="paper__page" ref={c => this.form = c}> <label className="layout__row layout__row-small" htmlFor="mute_all_posts"> <input checked={current_user.getIn(['user', 'more', 'mute_all_posts'])} id="mute_all_posts" name="mute_all_posts" type="checkbox" onClick={this.handleMuteAllPosts} /> <span className="checkbox__label-right">Turn off all email notifications about new comments</span> </label> </form> </div> </div> </div> ); } } const selector = createSelector( currentUserSelector, state => state.get('messages'), state => state.get('following'), state => state.get('followers'), (current_user, messages, following, followers) => ({ messages, following, followers, ...current_user }) ); export default connect(selector)(SettingsEmailPage);
packages/react-error-overlay/src/containers/RuntimeError.js
0xaio/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React from 'react'; import Header from '../components/Header'; import StackTrace from './StackTrace'; import type { StackFrame } from '../utils/stack-frame'; import type { ErrorLocation } from '../utils/parseCompileError'; const wrapperStyle = { display: 'flex', flexDirection: 'column', }; export type ErrorRecord = {| error: Error, unhandledRejection: boolean, contextSize: number, stackFrames: StackFrame[], |}; type Props = {| errorRecord: ErrorRecord, editorHandler: (errorLoc: ErrorLocation) => void, |}; function RuntimeError({ errorRecord, editorHandler }: Props) { const { error, unhandledRejection, contextSize, stackFrames } = errorRecord; const errorName = unhandledRejection ? 'Unhandled Rejection (' + error.name + ')' : error.name; // Make header prettier const message = error.message; let headerText = message.match(/^\w*:/) || !errorName ? message : errorName + ': ' + message; headerText = headerText // TODO: maybe remove this prefix from fbjs? // It's just scaring people .replace(/^Invariant Violation:\s*/, '') // This is not helpful either: .replace(/^Warning:\s*/, '') // Break the actionable part to the next line. // AFAIK React 16+ should already do this. .replace(' Check the render method', '\n\nCheck the render method') .replace(' Check your code at', '\n\nCheck your code at'); return ( <div style={wrapperStyle}> <Header headerText={headerText} /> <StackTrace stackFrames={stackFrames} errorName={errorName} contextSize={contextSize} editorHandler={editorHandler} /> </div> ); } export default RuntimeError;
packages/cli-adapter/src/saihubot-cli-addon-dialog.js
gasolin/saihubot
'use strict'; import React from 'react'; import {Box, Text, useApp, useInput} from 'ink'; import SelectInput from 'ink-select-input'; const SelectBox = ({handleSelect, title, items}) => { const {exit} = useApp(); useInput((input, key) => { if (input === 'q' || key.escape) { exit(); } }); const options = []; items.forEach((item, idx) => { options.push({ label: item.title, value: idx, }); }); return ( <Box flexDirection="column"> <Text>{title}</Text> <SelectInput items={options} onSelect={handleSelect} /> </Box> ); }; // addon that provide confirm and selection dialog export const addonConfirm = { name: 'confirm', requirements: { adapters: ['cli'], }, action: (robot) => (title, items) => { const handleSelect = (item) => { // `item` = { label: 'First', value: 'first' } if (item && items[item.value] && items[item.value].action) { items[item.value].action(); } }; robot.chatHistory.push( <SelectBox title={title} items={items} handleSelect={handleSelect} /> ); robot.render(); }, }; const addons = [addonConfirm]; export {addons};
template/src/components/Message.js
phonegap/phonegap-template-react-hot-loader
import '../css/message.css'; import React from 'react'; import CSSTransitionGroup from 'react-addons-css-transition-group'; export default React.createClass({ displayName: 'Message', propTypes: { message: React.PropTypes.string, }, render() { const { message } = this.props; const msg = message ? <div className="hello-message" key="has-msg">{ message }</div> : <div key="no-msg"></div> return ( <CSSTransitionGroup transitionName="fade-message" transitionEnterTimeout={ 300 } transitionLeaveTimeout={ 300 }> { msg } </CSSTransitionGroup> ); } });
src/index.js
richgurney/ReactTemperatureApp
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import ReduxPromise from 'redux-promise'; import App from './components/app'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <App /> </Provider> , document.querySelector('.container'));
.history/src/components/InstaCelebs/index_20171001010701.js
oded-soffrin/gkm_viewer
import React from 'react'; import { connect } from 'react-redux' import _ from 'lodash' import '../../styles/insta-stats.scss' const imgMap = { d: 'https://instagram.ftlv1-2.fna.fbcdn.net/t51.2885-19/s150x150/18095129_753964814784600_2717222797960019968_a.jpg', e: 'https://instagram.ftlv1-2.fna.fbcdn.net/t51.2885-19/s150x150/12071219_1640349196212432_2045004332_a.jpg', k: 'https://instagram.ftlv1-2.fna.fbcdn.net/t51.2885-19/s150x150/18512724_1809268792724740_5337121181726146560_a.jpg' } const InstaCelebs = ({instaCeleb}) => { console.log('instaCeleb', instaCeleb) const stats = _.map(instaCeleb.stats, (x, y) => ( <div> <img src={imgMap[y]}/> <div className='data-box'><i className='fa fa-heart'/></div> <div className='data-box'>{x.like || 0}</div> <div className='data-box'><i className='fa fa-comment'/></div> <div className='data-box'>{x.comment || 0}</div> </div> )) return ( <div className="wrapper"> <div className="stats"> <h1><img src='https://static.wixstatic.com/media/8b1232_99ff6bf44fc74a22a9cc5ef7b578c1b1~mv2.png' /> Stats - Last 24h</h1> {stats} </div> </div> ) } const mapStateToProps = (state) => ({ instaCeleb: state.instaCeleb }) const InstaCelebsConnected = connect( mapStateToProps, { } )(InstaCelebs) export default InstaCelebsConnected
src/client/components/loading.react.js
steida/songary
// import './loading.styl'; import Component from '../components/component.react'; import React from 'react'; export default class Loading extends Component { static propTypes = { delay: React.PropTypes.number, msg: React.PropTypes.object.isRequired } // http://www.nngroup.com/articles/response-times-3-important-limits/ static defaultProps = { delay: 3000 } constructor(props) { super(props); this.state = {shown: false}; } componentDidMount() { this.timer = setTimeout(() => { this.setState({shown: true}); }, this.props.delay); } componentWillUnmount() { clearTimeout(this.timer); } render() { const {msg: {components: msg}} = this.props; // TODO: Some animated progress, rule .1s 1s 10s. return ( <div className="components-loading"> <p> {this.state.shown && msg.loading} </p> </div> ); } }
console/src/app/tasklogs/tasklogs.js
alfredking12/hp-scheduler
import React from 'react'; require('rc-pagination/assets/index.css'); require('rc-select/assets/index.css'); import Pagination from 'rc-pagination'; import Select from 'rc-select'; import ActionRefresh from 'material-ui/svg-icons/action/search'; import TextField from 'material-ui/TextField'; import IconButton from 'material-ui/IconButton'; import {Table, TableBody, TableFooter, TableHeader, TableHeaderColumn, TableRow, TableRowColumn} from 'material-ui/Table'; import 'react-date-picker/index.css'; import { DateField } from 'react-date-picker'; import moment from 'moment'; import request from 'superagent/lib/client'; import config from '../config/config'; import BaseComponent from '../libs/BaseComponent'; const styles = { middle: { marginTop: 8 }, middleIcon: { width: 28, height: 28, }, } export default class TaskLogs extends BaseComponent { constructor(props, context) { super(props, context); Object.assign(this.state, { fixedHeader: true, fixedFooter: true, stripedRows: false, showRowHover: false, height: (window.innerHeight - 344) + 'px', tableStyle: null, start: null, end: null, key: '', pageSize: 30, page: 0, count: 0, data: [], expand_index: -1, expand_text: '' }); } handleResize(e) { super.handleResize(e); this.setState({height: (window.innerHeight - 344) + 'px'}); } componentDidMount() { super.componentDidMount(); this.load(); } handleChangeStart(dateString) { this.setState({ start: dateString }); } handleChangeEnd(dateString) { this.setState({ end: dateString }); } handleSearch() { this.load(); } handleChangeKey(e) { this.setState({ key: e.target.value }); } handleRowClick(data) { if (this.state.expand_index == data.index) { this.setState({ expand_text: null, expand_index: -1 }) } else { this.setState({ expand_text: this.status(data.item), expand_index: data.index }) } } status(item) { if (item.progress !== undefined && item.progress !== null) { if(item.progress < 0) { return '[失败] ' + item.message; } else { return '[进度 ' + item.progress + '%] ' + item.message; } } return item.message; } _render() { var _this = this; var page = this.state.page; var per_page = this.state.pageSize; const getTable = () => { var rows = []; for (var index = 0;index< _this.state.data.length;index++) { var row = _this.state.data[index]; var item = ( <TableRow key={index} style={{height: '28px'}} onTouchTap={_this.handleRowClick.bind(_this, {item: row, index: index})} > <TableRowColumn style={{height: '28px', width: '30px'}}>{index + 1 + page * per_page}</TableRowColumn> <TableRowColumn style={{height: '28px',width: '200px'}}>{row.name}</TableRowColumn> <TableRowColumn style={{height: '28px', width: '30px'}}>{row.taskrecord_id}</TableRowColumn> <TableRowColumn style={{height: '28px'}}>{_this.status(row)}</TableRowColumn> <TableRowColumn style={{height: '28px', width: '150px'}}>{row.time}</TableRowColumn> </TableRow> ); rows.push(item); if (index == _this.state.expand_index) { item = ( <TableRow key={'expand_' + index} style={{background: 'rgba(120, 120, 120, 0.1)'}} > <TableRowColumn colSpan="5" style={{ wordWrap: 'break-all', wordBreak: 'normal', whiteSpace: 'break-all' }}> {_this.state.expand_text} </TableRowColumn> </TableRow> ); rows.push(item); } } return ( <div> <Table height={this.state.height} fixedHeader={this.state.fixedHeader} fixedFooter={this.state.fixedFooter} selectable={false} style={this.state.tableStyle} > <TableHeader displaySelectAll={false} adjustForCheckbox={false} > <TableRow displayBorder={true}> <TableHeaderColumn tooltip="序号" style={{width: '30px'}}>#</TableHeaderColumn> <TableHeaderColumn style={{width: '200px'}}>任务名称</TableHeaderColumn> <TableHeaderColumn style={{width: '30px'}}>任务ID</TableHeaderColumn> <TableHeaderColumn>日志信息</TableHeaderColumn> <TableHeaderColumn style={{width: '150px'}}>时间</TableHeaderColumn> </TableRow> </TableHeader> <TableBody displayRowCheckbox={false} showRowHover={this.state.showRowHover} stripedRows={this.state.stripedRows} > {rows} </TableBody> </Table> </div> ); } const pager = (style) => { return ( <div style={{overflow: 'hidden'}}> <div style={style}> <Pagination showSizeChanger className="ant-pagination" current={this.state.page + 1} defaultCurrent={1} total={this.state.count} pageSize={this.state.pageSize} onChange={this.handlePageChange.bind(this)} pageSizeOptions={['30', '50', '100', '200']} selectComponentClass={Select} onShowSizeChange={this.handleSizeChange.bind(this)} /> </div> </div> ); } return ( <div> <div style={{paddingLeft: '20px', paddingRight: '20px'}}> <DateField style={{marginRight: '20px'}} value={this.state.start} placeholder={'开始时间'} dateFormat="YYYY-MM-DD HH:mm:ss" onChange={this.handleChangeStart.bind(this)} /> <DateField style={{marginRight: '20px'}} value={this.state.end} placeholder={'结束时间'} dateFormat="YYYY-MM-DD HH:mm:ss" onChange={this.handleChangeEnd.bind(this)} /> <TextField style={{marginRight: '20px', paddingTop: 0, marginTop: 0}} value={this.state.key} onChange={this.handleChangeKey.bind(this)} floatingLabelText="输入关键字搜索" /> <IconButton iconStyle={styles.middleIcon} style={styles.middle} onTouchTap={this.handleSearch.bind(this)} > <ActionRefresh /> </IconButton> </div> {pager({paddingRight: '10px', float:'right'})} {getTable()} {pager({paddingBottom: '10px', paddingRight: '10px', float:'right'})} </div> ); } handlePageChange(page) { this.setState({ page: page - 1 }); var _this = this; setTimeout(function() { _this.load(); }, 0); } handleSizeChange(current, pageSize) { this.setState({ pageSize: pageSize, page: 0 }); var _this = this; setTimeout(function() { _this.load(); }, 0); } _load(cb) { var page = this.state.page; var per_page = this.state.pageSize; var stime = this.state.start ? moment(this.state.start).valueOf() : ''; var etime = this.state.end ? moment(this.state.end).valueOf() : ''; var key = this.state.key; request .get(config.api_server + '/tasklogs?page=' + page + '&per_page=' + per_page + '&stime=' + stime + '&etime=' + etime + '&key=' + key) .set('Accept', 'application/json') .end(function (err, res) { if (err) { cb(err); } else { cb(null, res.body); } }); } load() { this.setState({ expand_index: -1, expand_text: null }); var _this = this; _this.showLoading(); this._load(function (err, data) { _this.hideLoading(); if (err) { _this.showAlert('提示', '加载任务日志列表失败', '重新加载', function() { setTimeout(function(){ _this.load(); }, 0); }); } else { _this.setState({ data: data.data.data, count: data.data.count }); } }); } }
docs/src/app/components/pages/components/RefreshIndicator/ExampleLoading.js
pomerantsev/material-ui
import React from 'react'; import RefreshIndicator from 'material-ui/RefreshIndicator'; const style = { container: { position: 'relative', }, refresh: { display: 'inline-block', position: 'relative', }, }; const RefreshIndicatorExampleLoading = () => ( <div style={style.container}> <RefreshIndicator size={40} left={10} top={0} status="loading" style={style.refresh} /> <RefreshIndicator size={50} left={70} top={0} loadingColor={"#FF9800"} status="loading" style={style.refresh} /> </div> ); export default RefreshIndicatorExampleLoading;
js/components/leads_old/index.js
aditya-simplecrm/iosReactAppNoresha
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Alert,TouchableHighlight } from 'react-native'; import { Image, AsyncStorage } from 'react-native'; import { Actions } from 'react-native-router-flux'; import { Container, Header, Title, Content, Text, Button, Icon, Left, Right, Body, List, ListItem,Thumbnail, Fab,View} from 'native-base'; import { openDrawer } from '../../actions/drawer'; import styles from './styles'; import ActionButton from 'react-native-action-button'; const call = require('../../../images/call.png'); const meeting = require('../../../images/meeting.png'); const task = require('../../../images/task.png'); class Leads extends Component { static propTypes = { name: React.PropTypes.string, index: React.PropTypes.number, list: React.PropTypes.arrayOf(React.PropTypes.string), openDrawer: React.PropTypes.func, } constructor(props) { super(props); this.state = { active: false }; } render() { const { props: { name, index, list } } = this; const goToView2 = () => { Actions.view2(); console.log('Navigation router run...'); }; return ( <Container style={styles.container}> <Header> <Left> <Button transparent onPress={() => Actions.pop()}> <Icon name="ios-arrow-back" /> </Button> </Left> <Body> <Title>{(name) ? this.props.name : 'Leads'}</Title> </Body> <Right> <Button transparent onPress={this.props.openDrawer}> <Icon name="ios-menu" /> </Button> </Right> </Header> <Content> <List> <ListItem button onPress={() => Actions.view2()}> <Body> <Text>Kumar Pratik</Text> <Text>Kumar@test.com</Text> <Text note>Doing what you like will always keep you happy . .</Text> </Body> <Right> <Text note>3:43 pm</Text> </Right> </ListItem> </List> </Content> </Container> ); } } function bindAction(dispatch) { return { openDrawer: () => dispatch(openDrawer()), }; } const mapStateToProps = state => ({ name: state.user.name, index: state.list.selectedIndex, list: state.list.list, }); export default connect(mapStateToProps, bindAction)(Leads);
electron/app/pages/component/any.js
midsnow/snowelectric
import React from 'react'; import Debug from 'debug' import Gab from '../../common/gab' let debug = Debug('snowstreams:app:pages:component:any'); export default class Any extends React.Component { constructor(props) { super(props) this.displayName = 'Any Component' this.state = { html: props.children || props.html || <span /> } this._update = false debug('Any'); } componentWillReceiveProps(props) { debug('receiveProps'); this.setState({html: props.children || props.html}); this._update = true; } componentDidUpdate() { debug('didUpdate'); } componentDidMount() { debug('did mount'); } render() { debug('any', this.state); if('function' === typeof this.state.html) { // render a component return (<div> <this.state.html /> </div>); } else if('object' === typeof this.state.html) { // this is a rendered componenet return (<div> {this.state.html} </div>); } else { debug('any leftover', this.state); // add anything else return (<div dangerouslySetInnerHTML={{ __html: this.state.html }} />) } } }
src/templates/portfolio-page.js
tannerfiscus/tannerfisc.us
import React from 'react'; import Markdown from 'react-markdown'; import { Helmet } from 'react-helmet'; import { graphql } from 'gatsby'; import Layout from '../components/Layout'; import PreviewCompatibleImage from '../components/PreviewCompatibleImage' import styles from './portfolio-page.module.scss'; import Text from '../components/Text'; export const PortfolioItemTemplate = ({ content, date, featuredHeaderImage, slug, technologies = [], timeline = [], title, }) => { const hasTechnologies = Array.isArray(technologies) && technologies.length > 1; const hasTimeline = Array.isArray(timeline) && timeline.length > 1; const hasSidebarContent = hasTechnologies || hasTimeline; return ( <> <Helmet meta={ [ { name: 'description', content: `Find out what went into building ${title} with a detailed page summary.` }, { property: 'og:title', content: `${title} – a project by Tanner Fiscus` }, { property: 'og:description', content: 'A detailed look at one of the projects I\'ve developed.' }, { property: 'og:type', content: 'website' }, { property: 'og:url', content: `https://tannerfisc.us/${slug}` }, { property: 'og:image', content: 'https://tannerfisc.us/img/og/portfolio.jpg' } ] } title={`${title} – Project Details – Tanner Fiscus`} /> <div className={styles.portfolioCover}> <PreviewCompatibleImage imageInfo={{ image: featuredHeaderImage, alt: `Image showing the ${title} portfolio item on a web browser`, }} /> </div> <main className={styles.portfolioContent}> <div className={styles.portfolioContentLeft}> { content ? content.map(({ description, title }) => ( <section className={styles.portfolioDescription} key={title}> <h2>{ title } </h2> <Markdown source={description} /> </section> )): null } <Text bold className={`${styles.portfolioDate} ${styles.portfolioDateTop}`}> Last updated: {date} </Text> </div> { hasSidebarContent ? <div className={styles.portfolioContentRight}> { hasTechnologies && ( <React.Fragment> <h3>Applicable Technologies</h3> <div className={styles.portfolioPills}> { technologies.map(category => ( <div className={styles.portfolioPill} key={category}> { category } </div> )) } </div> </React.Fragment> ) } { hasTimeline && ( <React.Fragment> <h3>Timeline of Events</h3> <div className={styles.portfolioTimeline}> { timeline.map(timeline => ( <div className={styles.portfolioPill} key={timeline.time}> <div className={styles.portfolioTimelineTime}> { timeline.time } </div> { timeline.description } </div> )) } </div> </React.Fragment> ) } </div> : null } <Text bold className={`${styles.portfolioDate} ${styles.portfolioDateBottom}`}> Last updated: {date} </Text> </main> </> ) }; const BlogPost = ({ data }) => { const { markdownRemark: post } = data return ( <Layout pageTitle={post.frontmatter.title}> <PortfolioItemTemplate {...post.frontmatter} slug={post.fields.slug} /> </Layout> ) }; export default BlogPost; export const pageQuery = graphql` query PortfolioPostByID($id: String!) { markdownRemark(id: { eq: $id }) { id fields { slug } frontmatter { content { description title } date(formatString: "MMMM YYYY") featuredHeaderImage { childImageSharp { fluid(maxWidth: 2000, quality: 100) { ...GatsbyImageSharpFluid } } } technologies title timeline { time description } } } } `
js/src/views/Settings/Views/defaults.js
kushti/mpt
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import React from 'react'; import ActionAccountBalanceWallet from 'material-ui/svg-icons/action/account-balance-wallet'; import ActionTrackChanges from 'material-ui/svg-icons/action/track-changes'; import ActionSettings from 'material-ui/svg-icons/action/settings'; import CommunicationContacts from 'material-ui/svg-icons/communication/contacts'; import ImageGridOn from 'material-ui/svg-icons/image/grid-on'; import NavigationApps from 'material-ui/svg-icons/navigation/apps'; import { SignerIcon } from '../../../ui'; import styles from './views.css'; const defaultViews = { accounts: { active: true, fixed: true, icon: <ActionAccountBalanceWallet />, label: 'Accounts', route: '/accounts', value: 'account', description: 'A list of all the accounts associated to and imported into this Parity instance. Send transactions, receive incoming values, manage your balances and fund your accounts.' }, addresses: { active: true, icon: <CommunicationContacts />, label: 'Addressbook', route: '/addresses', value: 'address', description: 'A list of all contacts and address book entries that is managed by this Parity instance. Watch accounts and have the details available at the click of a button when transacting.' }, apps: { active: true, icon: <NavigationApps />, label: 'Applications', route: '/apps', value: 'app', description: 'Distributed applications that interact with the underlying network. Add applications, manage you application portfolio and interact with application from around the newtork.' }, contracts: { active: false, icon: <ImageGridOn />, label: 'Contracts', route: '/contracts', value: 'contract', description: 'Watch and interact with specific contracts that have been deployed on the network. This is a more technically-focussed environment, specifically for advanced users that understand the inner working of certain contracts.' }, status: { active: false, icon: <ActionTrackChanges />, label: 'Status', route: '/status', value: 'status', description: 'See how the Parity node is performing in terms of connections to the network, logs from the actual running instance and details of mining (if enabled and configured).' }, signer: { active: true, fixed: true, icon: <SignerIcon className={ styles.signerIcon } />, label: 'Signer', route: '/signer', value: 'signer', description: 'The security focussed area of the application where you can approve any outgoing transactions made from the application as well as those placed into the queue by distributed applications.' }, settings: { active: true, fixed: true, icon: <ActionSettings />, label: 'Settings', route: '/settings', value: 'settings', description: 'This view. Allows you to customize the application in term of options, operation and look and feel.' } }; export default defaultViews;
packages/material-ui-icons/src/BatteryCharging80TwoTone.js
lgollut/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V9h4.93L13 7v2h4V5.33C17 4.6 16.4 4 15.67 4z" /><path d="M13 12.5h2L11 20v-5.5H9L11.93 9H7v11.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V9h-4v3.5z" /></React.Fragment> , 'BatteryCharging80TwoTone');
docs/src/app/components/pages/components/IconButton/Page.js
pancho111203/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import iconButtonCode from '!raw!material-ui/IconButton/IconButton'; import iconButtonReadmeText from './README'; import iconButtonExampleSimpleCode from '!raw!./ExampleSimple'; import IconButtonExampleSimple from './ExampleSimple'; import iconButtonExampleComplexCode from '!raw!./ExampleComplex'; import IconButtonExampleComplex from './ExampleComplex'; import iconButtonExampleSizeCode from '!raw!./ExampleSize'; import IconButtonExampleSize from './ExampleSize'; import iconButtonExampleTooltipCode from '!raw!./ExampleTooltip'; import IconButtonExampleTooltip from './ExampleTooltip'; import iconButtonExampleTouchCode from '!raw!./ExampleTouch'; import IconButtonExampleTouch from './ExampleTouch'; const descriptions = { simple: 'An Icon Button using an icon specified with the `iconClassName` property, and a `disabled` example.', tooltip: 'Icon Buttons showing the available `tooltip` positions.', touch: 'The `touch` property adjusts the tooltip size for better visibility on mobile devices.', size: 'Examples of Icon Button in different sizes.', other: 'An Icon Button using a nested [Font Icon](/#/components/font-icon), ' + 'a nested [SVG Icon](/#/components/svg-icon) and an icon font ligature.', }; const IconButtonPage = () => ( <div> <Title render={(previousTitle) => `Icon Button - ${previousTitle}`} /> <MarkdownElement text={iconButtonReadmeText} /> <CodeExample title="Simple example" description={descriptions.simple} code={iconButtonExampleSimpleCode} > <IconButtonExampleSimple /> </CodeExample> <CodeExample title="Further examples" description={descriptions.other} code={iconButtonExampleComplexCode} > <IconButtonExampleComplex /> </CodeExample> <CodeExample title="Size examples" description={descriptions.size} code={iconButtonExampleSizeCode} > <IconButtonExampleSize /> </CodeExample> <CodeExample title="Tooltip examples" description={descriptions.tooltip} code={iconButtonExampleTooltipCode} > <IconButtonExampleTooltip /> </CodeExample> <CodeExample title="Touch example" description={descriptions.touch} code={iconButtonExampleTouchCode} > <IconButtonExampleTouch /> </CodeExample> <PropTypeDescription code={iconButtonCode} /> </div> ); export default IconButtonPage;
admin/client/App/screens/List/components/ItemsTable/ItemsTableDragDropZone.js
naustudio/keystone
/** * THIS IS ORPHANED AND ISN'T RENDERED AT THE MOMENT * THIS WAS DONE TO FINISH THE REDUX INTEGRATION, WILL REWRITE SOON * - @mxstbr */ import React from 'react'; import DropZoneTarget from './ItemsTableDragDropZoneTarget'; import classnames from 'classnames'; var ItemsTableDragDropZone = React.createClass({ displayName: 'ItemsTableDragDropZone', propTypes: { columns: React.PropTypes.array, connectDropTarget: React.PropTypes.func, items: React.PropTypes.object, list: React.PropTypes.object, }, renderPageDrops () { const { items, currentPage, pageSize } = this.props; const totalPages = Math.ceil(items.count / pageSize); const style = { display: totalPages > 1 ? null : 'none' }; const pages = []; for (let i = 0; i < totalPages; i++) { const page = i + 1; const pageItems = '' + (page * pageSize - (pageSize - 1)) + ' - ' + (page * pageSize); const current = (page === currentPage); const className = classnames('ItemList__dropzone--page', { 'is-active': current, }); pages.push( <DropZoneTarget key={'page_' + page} page={page} className={className} pageItems={pageItems} pageSize={pageSize} currentPage={currentPage} drag={this.props.drag} dispatch={this.props.dispatch} /> ); } let cols = this.props.columns.length; if (this.props.list.sortable) cols++; if (!this.props.list.nodelete) cols++; return ( <tr style={style}> <td colSpan={cols} > <div className="ItemList__dropzone" > {pages} <div className="clearfix" /> </div> </td> </tr> ); }, render () { return this.renderPageDrops(); }, }); module.exports = ItemsTableDragDropZone;
js/components/App.js
js-mi/so
import React from 'react'; import Header from './Header'; import Container from './Container'; import Ribbon from './Ribbon'; class App extends React.Component { render () { return ( <div> <Header /> <Container /> <Ribbon /> </div> ); } } export default App;
docs/app/Examples/collections/Message/Types/MessageExampleIcon.js
vageeshb/Semantic-UI-React
import React from 'react' import { Message, Icon } from 'semantic-ui-react' const MessageExampleIcon = () => ( <Message icon> <Icon name='circle notched' loading /> <Message.Content> <Message.Header>Just one second</Message.Header> We are fetching that content for you. </Message.Content> </Message> ) export default MessageExampleIcon
src/svg-icons/av/sort-by-alpha.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvSortByAlpha = (props) => ( <SvgIcon {...props}> <path d="M14.94 4.66h-4.72l2.36-2.36zm-4.69 14.71h4.66l-2.33 2.33zM6.1 6.27L1.6 17.73h1.84l.92-2.45h5.11l.92 2.45h1.84L7.74 6.27H6.1zm-1.13 7.37l1.94-5.18 1.94 5.18H4.97zm10.76 2.5h6.12v1.59h-8.53v-1.29l5.92-8.56h-5.88v-1.6h8.3v1.26l-5.93 8.6z"/> </SvgIcon> ); AvSortByAlpha = pure(AvSortByAlpha); AvSortByAlpha.displayName = 'AvSortByAlpha'; export default AvSortByAlpha;
src/components/Dashboard/index.js
LazyHaus/MyHaus
import React from 'react'; import { Card, } from 'react-mdl'; import './style.css'; import '../../../node_modules/react-grid-layout/css/styles.css'; import '../../../node_modules/react-mdl/extra/material.css'; import '../../../node_modules/react-mdl/extra/material.js'; import {Responsive, WidthProvider} from 'react-grid-layout'; const ResponsiveReactGridLayout = WidthProvider(Responsive); import SensorChart from '../SensorChart'; import {LazyPage} from '../LazyMain' var HausGrid = React.createClass({ render: function() { // layout is an array of objects, see the demo for more complete usage var dict = { isResizable: true, layout: [ {i: 'a', x: 0, y: 0, w: 1, h: 2}, {i: 'b', x: 1, y: 0, w: 3, h: 2, minW: 2, maxW: 4}, {i: 'c', x: 4, y: 0, w: 1, h: 2} ] }; return ( <ResponsiveReactGridLayout {...dict} className="layout" breakpoints={{lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0}} cols={{lg: 12, md: 10, sm: 6, xs: 4, xxs: 2}}> <Card key={'a'} shadow={0}><SensorChart /></Card> <Card key={'b'} shadow={0}> 2 </Card> <Card key={'c'} shadow={0}> 3 </Card> </ResponsiveReactGridLayout> ) } }); class Dashboard extends React.Component { constructor(...props) { super(...props); this.state = {} } render() { return ( <LazyPage title="Dashboard" pageName="Dashboard"> <div className="React-grid"> <HausGrid /> </div> </LazyPage> ) } } export default Dashboard;