path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
Example/components/Launch.js
aksonov/react-native-router-native
import React from 'react'; import {View, Text, StyleSheet} from "react-native"; import Button from "react-native-button"; import {Actions} from "react-native-router-native"; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: "transparent", borderWidth: 2, borderColor: 'red', } }); class Launch extends React.Component { render(){ return ( <View {...this.props} style={styles.container}> <Text>Launch page</Text> <Button onPress={()=>Actions.login({data:"Custom data", title:"Custom title" })}>Go to Login page</Button> <Button onPress={Actions.register}>Go to Register page</Button> <Button onPress={()=>Actions.error("Error message")}>Popup error</Button> <Button onPress={Actions.tabbar}>Go to TabBar page</Button> </View> ); } } module.exports = Launch;
src/components/docs/tabs.js
nordsoftware/react-foundation-docs
import React from 'react'; import Playground from 'component-playground'; import { StatelessComponentWarning } from '../app/warnings'; import { Grid, Cell, Tabs, TabItem, TabsContent, TabPanel } from 'react-foundation'; export const TabsDocs = () => ( <section className="tabs-docs"> <Grid> <Cell large={12}> <h2>Tabs</h2> <StatelessComponentWarning /> <Playground codeText={require('raw-loader!../examples/tabs/basics').default} scope={{ React, Tabs, TabItem, TabsContent, TabPanel }} theme="eiffel" /> </Cell> </Grid> </section> ); export default TabsDocs;
packages/rmw-shell/src/providers/Firebase/Messaging/Context.js
TarikHuber/react-most-wanted
import React from 'react' export const Context = React.createContext(null) export default Context
examples/huge-apps/routes/Course/routes/Assignments/components/Sidebar.js
mattkrick/react-router
/*globals COURSES:true */ import React from 'react' import { Link } from 'react-router' class Sidebar extends React.Component { render() { let { assignments } = COURSES[this.props.params.courseId] return ( <div> <h3>Sidebar Assignments</h3> <ul> {assignments.map(assignment => ( <li key={assignment.id}> <Link to={`/course/${this.props.params.courseId}/assignments/${assignment.id}`}> {assignment.title} </Link> </li> ))} </ul> </div> ) } } module.exports = Sidebar
examples/validation/app.js
maludwig/react-redux-form
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import store from './store.js'; import UserForm from './components/user-form.js'; class App extends React.Component { render() { return ( <Provider store={store}> <UserForm /> </Provider> ); } } ReactDOM.render(<App />, document.getElementById('app'));
src/svg-icons/content/reply-all.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentReplyAll = (props) => ( <SvgIcon {...props}> <path d="M7 8V5l-7 7 7 7v-3l-4-4 4-4zm6 1V5l-7 7 7 7v-4.1c5 0 8.5 1.6 11 5.1-1-5-4-10-11-11z"/> </SvgIcon> ); ContentReplyAll = pure(ContentReplyAll); ContentReplyAll.displayName = 'ContentReplyAll'; ContentReplyAll.muiName = 'SvgIcon'; export default ContentReplyAll;
modules/TransitionHook.js
jepezi/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;
App/components/GalleryInternal.js
cguirunas/reactJS_brazilgranites
import React, { Component } from 'react'; import {Motion,spring} from 'react-motion'; var GalleryJSON = []; GalleryJSON['en'] = require('../data/en/gallery.json'); GalleryJSON['pt'] = require('../data/pt/gallery.json'); GalleryJSON['es'] = require('../data/es/gallery.json'); GalleryJSON['fr'] = require('../data/fr/gallery.json'); const GenericJSON = []; GenericJSON['en'] = require('../data/en/generic_words.json'); GenericJSON['pt'] = require('../data/pt/generic_words.json'); GenericJSON['es'] = require('../data/es/generic_words.json'); GenericJSON['fr'] = require('../data/fr/generic_words.json'); //All Images import {getInternalImage,getArrowImage} from "./GalleryImages" const springSettings = { stiffness: 100, damping: 40 }; const widthInit = 1280; const heightInit = 677; class GalleryInternal extends Component { countdown = null; constructor() { super(); this.state = { photos: [], currPhoto: 0, } } getInnerWidth(){ return window.innerWidth; } getAutoHeight() { // 1280 = 500 // 677 = x return this.getInnerWidth() * heightInit / widthInit; } next(max_img) { var photoIndex = this.state.currPhoto + 1; if(photoIndex > (max_img - 1)) photoIndex = 0; this.setState({ currPhoto: photoIndex, }); this.stopTimer(); } previous(max_img) { var photoIndex = this.state.currPhoto - 1; if(photoIndex < 0) photoIndex = (max_img - 1); this.setState({ currPhoto: photoIndex, }); this.stopTimer(); } stopTimer() { clearInterval(this.countdown); } componentWillMount() { let max_img = GalleryJSON[this.props.params.LANG_SELECTED][this.props.params.STONE].max_img; let photosMount = []; photosMount.push([1000, 546]); for(let i = 0; i < max_img; i++) { photosMount.push([1000, 666]); } this.setState({ photos: photosMount, }); } getInnerHeight(){ return window.innerHeight; } getScreenHeight(){ return window.screen.height; } componentDidMount(){ window.scrollTo(0,0); this.countdown = setInterval(this.next.bind(this), 7000); } componentWillUnmount() { clearInterval(this.countdown); } proportionsOfWidth(val) { // 1280 = 500 // 677 = x return val * this.getAutoHeight() / widthInit; } render() { var buttonPrev = { top: `${this.proportionsOfWidth(850)}px`,//top: 450+'px', zIndex: 50, padding: 1+'px', position: 'absolute', left: 20+'px', }; var buttonNext = { top: `${this.proportionsOfWidth(850)}px`,//top: 450+'px', zIndex: 50, padding: 1+'px', position: 'absolute', right: 20+'px', }; let name = GalleryJSON[this.props.params.LANG_SELECTED][this.props.params.STONE].name; let mat = GalleryJSON[this.props.params.LANG_SELECTED][this.props.params.STONE].mat; let cat = GalleryJSON[this.props.params.LANG_SELECTED][this.props.params.STONE].cat; let dir_name = GalleryJSON[this.props.params.LANG_SELECTED][this.props.params.STONE].dir_name; let max_img = GalleryJSON[this.props.params.LANG_SELECTED][this.props.params.STONE].max_img; //REACT MOTION const { photos, currPhoto} = this.state; const [currWidth, currHeight] = photos[currPhoto]; const widths = photos.map( ([origW, origH]) => currHeight / origH * origW ); const leftStartCoords = widths.slice(0, currPhoto).reduce((sum, width) => sum - width, 0); let configs = []; photos.reduce((prevLeft, [origW, origH], i) => { configs.push({ left: spring(prevLeft, springSettings), height: spring(currHeight, springSettings), width: spring(widths[i], springSettings), }); return prevLeft + widths[i]; }, leftStartCoords); return ( <div> <section className="page-header dark page-header-xs" id="index_gallery_internal-top"> <div className="container"> <h1>{name}</h1> <span className="font-lato size-18 hidden-xs">{GenericJSON[this.props.params.LANG_SELECTED][[mat]]}, {GenericJSON[this.props.params.LANG_SELECTED][[cat]]}</span> </div> </section> <button style={buttonPrev} onClick={() => this.previous(max_img)}><img role="presentation" src={getArrowImage('left')}/></button> <button style={buttonNext} onClick={() => this.next(max_img)}><img role="presentation" src={getArrowImage('right')}/></button> <div className="slider fullwidthbanner-container roundedcorners" style={{overflow: 'visible',backgroundColor:'black'}} > <div className="fullwidthbanner revslider-initialised tp-simpleresponsive"> <Motion style={{height: spring(currHeight), width: spring(currWidth)}}> {container => <div className="demo4-inner" style={container}> {configs.map((style, i) => <Motion key={i} style={style}> {style => <img role="presentation" className="demo4-photo" src={getInternalImage(i,dir_name)} style={style} />} </Motion> )} </div> } </Motion> </div> </div> <section> <div className="container"> <div className="row nomargin"> <div className="col-md-8 col-sm-8"> <div className="heading-title heading-border"> <h2>{name} <span>Details</span></h2> <ul className="list-inline categories nomargin"> <li><a href="#">{GenericJSON[this.props.params.LANG_SELECTED][[mat]]}</a></li> <li><a href="#">{GenericJSON[this.props.params.LANG_SELECTED][[cat]]}</a></li> </ul> </div> <p>Donec sed odio dui. Nulla vitae elit libero, a pharetra augue. Nullam id dolor id nibh ultricies vehicula ut id elit. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Duis mollis, est non commodo luctus. Aenean lacinia bibendum nulla sed consectetur. Cras mattis consectetur purus sit amet fermentum.</p> <p className="font-lato size-18">Aenean lacinia bibendum nulla sed consectetur. Cras mattis consectetur purus sit amet fermentum. Donec id elit non mi porta gravida at eget metus. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </div> <div className="col-md-4 col-sm-4"> <div className="panel panel-default"> <div className="panel-body"> <p className="font-lato size-18">Integer posuere erat a ante venenatis dapibus posuere velit aliquet nulla sed consectetur.</p> <ul className="portfolio-detail-list list-unstyled nomargin"> <li><span><i className="fa fa-user"></i>Author:</span> Smarty Inc.</li> <li><span><i className="fa fa-calendar"></i>Released:</span> 29th June 2015</li> <li><span><i className="fa fa-lightbulb-o"></i>Technologies:</span> HTML / CSS / JAVASCRIPT</li> <li><span><i className="fa fa-link"></i>Website:</span> <a href="#">www.stepofweb.com</a></li> </ul> </div> <div className="panel-footer"> <a href="#" className="social-icon social-icon-sm social-icon-transparent social-facebook" data-toggle="tooltip" data-placement="top" title="Facebook"> <i className="icon-facebook"></i> <i className="icon-facebook"></i> </a> <a href="#" className="social-icon social-icon-sm social-icon-transparent social-twitter" data-toggle="tooltip" data-placement="top" title="Twitter"> <i className="icon-twitter"></i> <i className="icon-twitter"></i> </a> <a href="#" className="social-icon social-icon-sm social-icon-transparent social-gplus" data-toggle="tooltip" data-placement="top" title="Google plus"> <i className="icon-gplus"></i> <i className="icon-gplus"></i> </a> <a href="#" className="social-icon social-icon-sm social-icon-transparent social-linkedin" data-toggle="tooltip" data-placement="top" title="Linkedin"> <i className="icon-linkedin"></i> <i className="icon-linkedin"></i> </a> <a href="#" className="social-icon social-icon-sm social-icon-transparent social-pinterest" data-toggle="tooltip" data-placement="top" title="Pinterest"> <i className="icon-pinterest"></i> <i className="icon-pinterest"></i> </a> </div> </div> </div> </div> </div> </section> </div> ); } } export default GalleryInternal;
client/index.js
Frostimage/Frostimage
import React from 'react'; import { render } from 'react-dom'; import * as THREE from 'three'; import OrbitControls from './public/dist/OrbitControls' import Main from './components/Main/Main'; import TestView from './components/TestView'; import Header from './components/header/Header'; // import App from './components/App'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; class App extends React.Component { render(){ return ( <div> <Header /> <Main /> <p> Hello REACT!!</p> </div> ) } } render(<App />, document.getElementById('app'));
application/components/user/paymentmethods/index.js
ronanamsterdam/squaredcoffee
import React, { Component } from 'react'; import { Text, View,ScrollView } from 'react-native'; import Button from 'react-native-button'; import { Card, CardImage, CardTitle, CardContent, CardAction } from 'react-native-card-view'; import { ADDING_CARD, REMOVING_CARD, MAKING_ORDER } from '../../../statics/actions/user'; import styles from '../../../statics/styles'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import AppActions from '../../../actions'; import PaymentMethodsView from '../../shared/paymentMethodsView'; import CheckoutWebView from '../../shared/checkoutWebView'; class PaymentMethods extends Component { componentWillMount = () => {} componentWillUpdate = () => { // this.props.actions.getUserCards() } addCard = (isUserAddingCard, hasCards) => { if (isUserAddingCard) { this.props.actions.saveCard(); } else { this.props.actions.addCard(); if (!hasCards) { this.props.actions.saveCard(); } } } render = () => { const {cards, persistPaymentMethod, paymentInstrument, userAction } = this.props.user; const {navigation} = this.props; const selectedCardId = paymentInstrument && paymentInstrument.card && paymentInstrument.card.id; const isUserAddingCard = userAction === ADDING_CARD; const hasCards = cards.length > 0; isAbleToAddCard = true; return ( <View style={{ ...styles.container, flex: 1, justifyContent: 'center' }} > <ScrollView style={{ flex: 1 }} > <PaymentMethodsView /> </ScrollView> <CheckoutWebView navigation={navigation} /> </View> ); } }; const mapState = (state) => { return { user: state.user, cart: state.cart }; }; const mapDispatch = dispatch => ({ actions: bindActionCreators(AppActions, dispatch) }); export default connect(mapState, mapDispatch)(PaymentMethods);
frontend/src/components/applications/partnerApplicationsHeader.js
unicef/un-partner-portal
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { browserHistory as history } from 'react-router'; import HeaderNavigation from '../common/headerNavigation'; import { PROJECT_TYPES } from '../../helpers/constants'; import NewCfeiModalButton from '../eois/modals/newCfei/newCfeiModalButton'; const messages = { applications: 'Your Applications', noCfei: 'Sorry but this cfei doesn\'t exist', }; class PartnerApplicationsHeader extends Component { constructor(props) { super(props); this.state = { index: 0, }; this.handleChange = this.handleChange.bind(this); } updatePath() { const { tabs, location } = this.props; if (tabs.findIndex(tab => location.match(`^/applications/${tab.path}`)) === -1) { history.push('/'); } return tabs.findIndex(tab => location.match(`^/applications/${tab.path}`)); } handleChange(event, index) { const { tabs } = this.props; history.push(`/applications/${tabs[index].path}`); } render() { const { tabs, children, params: { id }, location, } = this.props; const index = this.updatePath(); return ( <HeaderNavigation index={index} title={messages.applications} tabs={tabs} handleChange={this.handleChange} header={!id && location.match('^/applications/unsolicited') && <NewCfeiModalButton type={PROJECT_TYPES.UNSOLICITED} />} defaultReturn="/" backButton > {children} </HeaderNavigation> ); } } PartnerApplicationsHeader.propTypes = { tabs: PropTypes.array.isRequired, children: PropTypes.node, location: PropTypes.string, params: PropTypes.object, }; const mapStateToProps = (state, ownProps) => ({ location: ownProps.location.pathname, tabs: state.partnerApplicationsNav.tabs, }); export default connect( mapStateToProps, )(PartnerApplicationsHeader);
src/js/components/Notification/stories/Status.js
grommet/grommet
import React from 'react'; import { Notification } from 'grommet'; import { Box } from '../../Box'; import { Text } from '../../Text'; const StatusNotification = () => ( <Box pad="large" justify="center" gap="large"> <Box gap="xsmall"> <Text size="medium">Default (No status prop)</Text> <Notification title="Status Title" message="This is an example of message text" /> </Box> <Box gap="xsmall"> <Text size="medium">Normal</Text> <Notification status="normal" title="Status Title" message="This is an example of message text" /> </Box> <Box gap="xsmall"> <Text size="medium">Warning</Text> <Notification status="warning" title="Status Title" message="This is an example of message text" /> </Box> <Box gap="xsmall"> <Text size="medium">Critical</Text> <Notification status="critical" title="Status Title" message="This is an example of message text" /> </Box> <Box gap="xsmall"> <Text size="medium">Unknown</Text> <Notification status="unknown" title="Status Title" message="This is an example of message text" /> </Box> </Box> ); export const Status = () => <StatusNotification />; export default { title: 'Visualizations/Notification/Status', };
modules/plugins/quote/QuoteButton.js
devrieda/arc-reactor
import React from 'react'; import MenuButton from '../../components/MenuButton'; import ToggleBlockType from '../../helpers/Manipulation/ToggleBlockType'; const QuoteButton = React.createClass({ statics: { getName: () => "quote", isVisible: () => true }, propTypes: MenuButton.propTypes, getDefaultProps() { return { type: "blockquote", text: "Quote", icon: "fa-quote-left" }; }, handlePress() { const guids = this.props.selection.guids(); const offsets = this.props.selection.offsets(); const position = this.props.selection.position(); const result = this._toggleBlockType().execute(guids, offsets, { type: this.props.type }); return { content: result.content, position: position }; }, _toggleBlockType() { return new ToggleBlockType(this.props.content); }, render() { return ( <MenuButton {...this.props} onPress={this.handlePress} /> ); } }); export default QuoteButton;
src/Components/WalletApp.js
dylanbathurst/bacon-mobile
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { AppRegistry, StatusBar, View, ScrollView, FlatList, StyleSheet, Image, Text } from 'react-native'; import { connect } from 'react-redux' import async from 'async'; import Account from './Account.js'; import AccountNav from './AccountNav.js'; import Header from './Header.js'; import TotalBalance from './TotalBalance.js'; import NewsTicker from './NewsTicker.js'; import TransactionNav from './TransactionNav.js'; import HeaderStyle from '../Styles/HeaderStyle.js'; import { FormattedWrapper } from 'react-native-globalize'; import { syncWallets } from '../Actions'; class WalletApp extends Component { render () { const hasAccounts = (this.props.accounts.length) ? true : false; const hasBalance = (this.props.accounts.length && this.props.accounts[0].accountAmount) ? true : false; return ( <View style={styles.mainContainer}> <ScrollView style={styles.accountListNavGroup}> { (hasAccounts && hasBalance) && <TotalBalance accounts={this.props.accounts} /> } <NewsTicker navigation={this.props.navigation} /> { hasAccounts ? ( <FlatList keyExtractor={ (item) => item.publicKey } data={this.props.accounts} style={styles.accountList} renderItem={({item}) => <Account data={item} />} /> ) : ( <Text style={styles.noAccounts}> You haven&apos;t created any accounts yet. Tap the button below to create your first account! </Text> )} <AccountNav /> </ScrollView> { hasAccounts && <TransactionNav navigation={this.props.navigation} /> } </View> ); } } const styles = StyleSheet.create({ mainContainer: { flex: 1, flexDirection: 'column', justifyContent: 'flex-start', backgroundColor: '#598a7a' }, accountList: { marginTop: 25, }, accountListNavGroup: { flex: 1, backgroundColor: '#598a7a' }, noAccounts: { color: 'white', fontSize: 16, textAlign: 'center', paddingLeft: 60, paddingRight: 60, marginTop: 30, color: '#aac3b9' } }); WalletApp.propTypes = { accounts: PropTypes.arrayOf(PropTypes.shape({})).isRequired }; mapStateToProps = (state) => ({ accounts: state.accounts }); export default connect(mapStateToProps)(WalletApp);
docs/src/app/components/pages/components/List/ExampleNested.js
igorbt/material-ui
import React from 'react'; import MobileTearSheet from '../../../MobileTearSheet'; import {List, ListItem} from 'material-ui/List'; import ActionGrade from 'material-ui/svg-icons/action/grade'; import ContentInbox from 'material-ui/svg-icons/content/inbox'; import ContentDrafts from 'material-ui/svg-icons/content/drafts'; import ContentSend from 'material-ui/svg-icons/content/send'; import Subheader from 'material-ui/Subheader'; import Toggle from 'material-ui/Toggle'; export default class ListExampleNested extends React.Component { state = { open: false, }; handleToggle = () => { this.setState({ open: !this.state.open, }); }; handleNestedListToggle = (item) => { this.setState({ open: item.state.open, }); }; render() { return ( <div> <Toggle toggled={this.state.open} onToggle={this.handleToggle} labelPosition="right" label="This toggle controls the expanded state of the submenu item." /> <br /> <MobileTearSheet> <List> <Subheader>Nested List Items</Subheader> <ListItem primaryText="Sent mail" leftIcon={<ContentSend />} /> <ListItem primaryText="Drafts" leftIcon={<ContentDrafts />} /> <ListItem primaryText="Inbox" leftIcon={<ContentInbox />} initiallyOpen={true} primaryTogglesNestedList={true} nestedItems={[ <ListItem key={1} primaryText="Starred" leftIcon={<ActionGrade />} />, <ListItem key={2} primaryText="Sent Mail" leftIcon={<ContentSend />} disabled={true} nestedItems={[ <ListItem key={1} primaryText="Drafts" leftIcon={<ContentDrafts />} />, ]} />, <ListItem key={3} primaryText="Inbox" leftIcon={<ContentInbox />} open={this.state.open} onNestedListToggle={this.handleNestedListToggle} nestedItems={[ <ListItem key={1} primaryText="Drafts" leftIcon={<ContentDrafts />} />, ]} />, ]} /> </List> </MobileTearSheet> </div> ); } }
src/svg-icons/notification/drive-eta.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationDriveEta = (props) => ( <SvgIcon {...props}> <path d="M18.92 5.01C18.72 4.42 18.16 4 17.5 4h-11c-.66 0-1.21.42-1.42 1.01L3 11v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 15c-.83 0-1.5-.67-1.5-1.5S5.67 12 6.5 12s1.5.67 1.5 1.5S7.33 15 6.5 15zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 10l1.5-4.5h11L19 10H5z"/> </SvgIcon> ); NotificationDriveEta = pure(NotificationDriveEta); NotificationDriveEta.displayName = 'NotificationDriveEta'; NotificationDriveEta.muiName = 'SvgIcon'; export default NotificationDriveEta;
src/svg-icons/image/grid-on.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageGridOn = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM8 20H4v-4h4v4zm0-6H4v-4h4v4zm0-6H4V4h4v4zm6 12h-4v-4h4v4zm0-6h-4v-4h4v4zm0-6h-4V4h4v4zm6 12h-4v-4h4v4zm0-6h-4v-4h4v4zm0-6h-4V4h4v4z"/> </SvgIcon> ); ImageGridOn = pure(ImageGridOn); ImageGridOn.displayName = 'ImageGridOn'; ImageGridOn.muiName = 'SvgIcon'; export default ImageGridOn;
src/js/components/nodes/Nodes.js
knowncitizen/tripleo-ui
/** * Copyright 2017 Red Hat Inc. * * 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. */ import { defineMessages, FormattedMessage, injectIntl } from 'react-intl'; import { connect } from 'react-redux'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; import React from 'react'; import { Route } from 'react-router-dom'; import { getFilterByName } from '../../selectors/filters'; import { getFilteredNodes, nodesInProgress } from '../../selectors/nodes'; import { Loader, InlineLoader } from '../ui/Loader'; import NodeDrives from './NodeDrives/NodeDrives'; import { fetchNodes, fetchNodeIntrospectionData } from '../../actions/NodesActions'; import NodesListForm from './NodesListView/NodesListForm'; import NodesListView from './NodesListView/NodesListView'; import NodesToolbar from './NodesToolbar/NodesToolbar'; import NodesTableView from './NodesTableView'; import RegisterNodesDialog from './registerNodes/RegisterNodesDialog'; import { fetchStacks } from '../../actions/StacksActions'; const messages = defineMessages({ loadingNodes: { id: 'Nodes.loadingNodes', defaultMessage: 'Loading Nodes...' }, refreshResults: { id: 'Nodes.refreshResults', defaultMessage: 'Refresh Results' }, registerNodes: { id: 'Nodes.registerNodes', defaultMessage: 'Register Nodes' }, registeringNodes: { id: 'Nodes.registeringNodes', defaultMessage: 'Registering Nodes...' }, nodes: { id: 'Nodes.nodes', defaultMessage: 'Nodes' } }); class Nodes extends React.Component { componentDidMount() { const { fetchNodes, fetchStacks, fetchingStacks, fetchingNodes } = this.props; fetchingNodes || fetchNodes(); fetchingStacks || fetchStacks(); } refreshResults(e) { e.preventDefault(); this.props.fetchNodes(); this.props.fetchStacks(); } renderContentView() { return this.props.contentView === 'table' ? ( <NodesTableView /> ) : ( <NodesListForm> <NodesListView fetchNodeIntrospectionData={this.props.fetchNodeIntrospectionData} nodes={this.props.nodes} nodesInProgress={this.props.nodesInProgress} /> </NodesListForm> ); } render() { const { fetchingNodes, fetchingStacks, nodesLoaded, intl: { formatMessage }, isRegistering, stacksLoaded } = this.props; return ( <div> <div className="page-header"> <div className="pull-right"> <InlineLoader loaded={!(fetchingNodes || fetchingStacks)} content={formatMessage(messages.loadingNodes)} component="span" > <a id="Nodes__refreshResultsLink" className="link btn btn-link" onClick={this.refreshResults.bind(this)} > <span className="pficon pficon-refresh" />&nbsp; <FormattedMessage {...messages.refreshResults} /> </a> </InlineLoader> &nbsp; <Link to="/nodes/register" className="btn btn-primary" id="Nodes__registerNodesLink" > <FormattedMessage {...messages.registerNodes} /> </Link> </div> <h1> <FormattedMessage {...messages.nodes} /> </h1> </div> <Loader loaded={nodesLoaded && stacksLoaded} content={formatMessage(messages.loadingNodes)} height={80} > <NodesToolbar /> <Loader loaded={!isRegistering} content={formatMessage(messages.registeringNodes)} height={80} /> {this.renderContentView()} </Loader> <Route path="/nodes/register" component={RegisterNodesDialog} /> <Route path="/nodes/:nodeId/drives" component={NodeDrives} /> </div> ); } } Nodes.propTypes = { contentView: PropTypes.string.isRequired, fetchNodeIntrospectionData: PropTypes.func.isRequired, fetchNodes: PropTypes.func.isRequired, fetchStacks: PropTypes.func.isRequired, fetchingNodes: PropTypes.bool.isRequired, fetchingStacks: PropTypes.bool.isRequired, intl: PropTypes.object.isRequired, isRegistering: PropTypes.bool.isRequired, nodes: ImmutablePropTypes.map.isRequired, nodesInProgress: ImmutablePropTypes.set.isRequired, nodesLoaded: PropTypes.bool.isRequired, stacksLoaded: PropTypes.bool.isRequired }; const mapStateToProps = state => ({ contentView: getFilterByName(state, 'nodesToolbar').get( 'contentView', 'list' ), isRegistering: state.registerNodes.get('isRegistering'), fetchingNodes: state.nodes.get('isFetching'), nodes: getFilteredNodes(state), nodesInProgress: nodesInProgress(state), nodesLoaded: state.nodes.get('isLoaded'), fetchingStacks: state.stacks.isFetching, stacksLoaded: state.stacks.isLoaded }); export default injectIntl( connect(mapStateToProps, { fetchStacks, fetchNodes, fetchNodeIntrospectionData })(Nodes) );
src/react/LogMonitorButton.js
rrrene/redux-devtools
import React from 'react'; import brighten from '../utils/brighten'; const styles = { base: { cursor: 'pointer', fontWeight: 'bold', borderRadius: 3, padding: 4, marginLeft: 3, marginRight: 3, marginTop: 5, marginBottom: 5, flexGrow: 1, display: 'inline-block', fontSize: '0.8em', color: 'white', textDecoration: 'none' } }; export default class LogMonitorButton extends React.Component { constructor(props) { super(props); this.state = { hovered: false, active: false }; } handleMouseEnter() { this.setState({ hovered: true }); } handleMouseLeave() { this.setState({ hovered: false }); } handleMouseDown() { this.setState({ active: true }); } handleMouseUp() { this.setState({ active: false }); } onClick() { if (!this.props.enabled) { return; } if (this.props.onClick) { this.props.onClick(); } } render() { let style = { ...styles.base, backgroundColor: this.props.theme.base02 }; if (this.props.enabled && this.state.hovered) { style = { ...style, backgroundColor: brighten(this.props.theme.base02, 0.2) }; } if (!this.props.enabled) { style = { ...style, opacity: 0.2, cursor: 'text', backgroundColor: 'transparent' }; } return ( <a onMouseEnter={::this.handleMouseEnter} onMouseLeave={::this.handleMouseLeave} onMouseDown={::this.handleMouseDown} onMouseUp={::this.handleMouseUp} style={style} onClick={::this.onClick}> {this.props.children} </a> ); } }
src/routes/Todos/components/TodoItem.js
aibolik/my-todomvc
import React from 'react' import './Todoitem.scss' class TodoItem extends React.Component { constructor (props) { super(props) this.state = { editMode: false } } toggleEditMode = () => { this.setState((prevState) => { return { editMode: !prevState.editMode } }) this.refs.input.style.display = 'inline' this.refs.input.focus() } onKeyDown = (e) => { let { todo, updateTodo } = this.props if (e.keyCode === 13) { updateTodo({ id: todo.id, text: e.target.value }) this.setState({ editMode: false }) this.refs.input.style.display = 'none' } } onBlur = (e) => { let { todo, updateTodo } = this.props updateTodo({ id: todo.id, text: e.target.value }) this.setState({ editMode: false }) this.refs.input.style.display = 'none' } render () { let { todo, toggleTodo, removeTodo } = this.props return <div className={'todos__list__item' + (todo.done ? ' todos__list__item--done' : '')}> <input className="todos__list__item__checkbox" type="checkbox" checked={todo.done} onClick={() => toggleTodo(todo.id)} /> <input style={{display: 'none'}} onFocus={(e) => console.log(e)} ref='input' type="text" defaultValue={todo.text} onKeyDown={this.onKeyDown} onBlur={this.onBlur} /> <label className={'todos__list__item__label' + (this.state.editMode ? ' hidden' : '')} onDoubleClick={() => this.toggleEditMode()}> {todo.text} </label> <div className="todos__list__item__close" onClick={() => removeTodo(todo.id)} /> </div> } } TodoItem.propTypes = { todo: React.PropTypes.object, toggleTodo: React.PropTypes.func, removeTodo: React.PropTypes.func, updateTodo: React.PropTypes.func } export default TodoItem
src/js/index.js
jdd1260/react-project-starter
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import { HashRouter, Route, Switch } from 'react-router-dom'; import promise from 'redux-promise'; import reducers from './reducers'; import Example from './components/example'; const middleWareStore = applyMiddleware(promise)(createStore); ReactDOM.render( <Provider store={middleWareStore(reducers)}> <HashRouter> <div> <Switch> <Route exact path="/" component={Example} /> </Switch> </div> </HashRouter> </Provider> , document.querySelector('.container'));
ReactToDo/src/index.js
michaelgichia/TODO-List
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
src/common/components/Routes.js
viltsu/FDB
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import { browserHistory } from 'react-router'; import App from './App'; import CalendarPage from '../../pages/calendar/page'; import QuotePage from '../../pages/quote/page'; import WeatherPage from '../../pages/weather/page'; import TransportationPage from '../../pages/transportation/page'; const routes = [ '/calendar', '/quote', '/weather', '/transportation' ]; /* var idx = 0; var changer = setInterval(function() { idx++; if (idx >= routes.length) { idx = 0; } browserHistory.push(routes[idx]); }, 10000); */ export default ( <Route path="/" component={App}> <IndexRoute component={WeatherPage} /> <Route path="calendar" component={CalendarPage} /> <Route path="quote" component={QuotePage} /> <Route path="weather" component={WeatherPage} /> <Route path="transportation" component={TransportationPage} /> </Route> );
test/test_helper.js
brenotx/simple-react-blog
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
components/description.js
volodalexey/spachat
import React from 'react' import extend_core from '../js/extend_core.js' import dom_core from '../js/dom_core.js' const Description = React.createClass({ getInitialState() { return { left: '0px', top: '0px', show: false, content: '' } }, componentDidMount() { this.descriptionContainer = document.querySelector('[data-role="description"]'); }, componentWillUnmount() { this.descriptionContainer = null; }, showDescription(event) { let description = this.descriptionContainer, element, target; switch (event.type) { case 'mousedown': case 'touchstart': if (event.type === 'touchstart' && event.changedTouches) { element = this.getDataParameter(event.changedTouches[0].target, 'description'); } else { element = this.getDataParameter(event.target, 'description'); } if (element && element.dataset.description) { this.curDescriptionElement = element; this.checkReorderClientX = event.clientX; this.checkReorderClientY = event.clientY; if (event.type === 'touchstart') { this.checkReorderClientX = event.changedTouches[0].clientX; this.checkReorderClientY = event.changedTouches[0].clientY; } } break; case 'mousemove': case 'touchmove': if (this.curDescriptionElement) { element = this.curDescriptionElement; let clientX = event.clientX, clientY = event.clientY; if (event.type === 'touchmove' && event.changedTouches) { clientX = event.changedTouches[0].clientX; clientY = event.changedTouches[0].clientY; } let radius = 5, deltaX = Math.abs(this.checkReorderClientX - clientX), deltaY = Math.abs(this.checkReorderClientY - clientY), current_radius = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2)); if (current_radius > radius && !this.descriptionShow) { event.stopPropagation(); event.preventDefault(); this.descriptionShow = true; description.innerHTML = element.dataset.description; let result = this.getOffset(element), positionFound = false, checkLeft, checkTop, futureTop = result.offsetTop - description.offsetHeight, futureLeft = result.offsetLeft + element.offsetWidth / 2 - description.offsetWidth / 2, futureRight = result.offsetLeft + element.offsetWidth / 2 + description.offsetWidth / 2, documentHeight = document.documentElement.clientHeight, documentWidth = document.body.offsetWidth, documentTop = document.body.offsetTop, documentLeft = document.body.offsetLeft; // if we have enough place on top of current target if (documentTop < futureTop) { checkLeft = futureLeft; if (documentLeft < checkLeft) { if (checkLeft + description.offsetWidth < documentWidth) { futureLeft = checkLeft; positionFound = true; } else { // not found } } if (result.offsetLeft + element.offsetWidth / 2 > documentWidth / 2) { if (!positionFound) { checkLeft = documentWidth - 5 - element.offsetWidth; if (documentLeft < checkLeft) { if (checkLeft + description.offsetWidth < documentWidth) { futureLeft = checkLeft; positionFound = true; } else { // not found } } } if (!positionFound) { checkLeft = result.offsetLeft - description.offsetWidth; if (checkLeft + description.offsetWidth < documentWidth) { if (documentLeft < checkLeft) { futureLeft = checkLeft; positionFound = true; } else { // not found } } } if (!positionFound) { checkLeft = documentLeft + 5; if (checkLeft + description.offsetWidth < documentWidth) { if (documentLeft < checkLeft) { futureLeft = checkLeft; positionFound = true; } else { // not found } } } } else { if (!positionFound) { checkLeft = documentLeft + 5; if (checkLeft + description.offsetWidth < documentWidth) { if (documentLeft < checkLeft) { futureLeft = checkLeft; positionFound = true; } else { // not found } } } if (!positionFound) { checkLeft = documentWidth - 5 - description.offsetHeight; if (documentLeft < checkLeft) { if (checkLeft + description.offsetWidth < documentWidth) { futureLeft = checkLeft; positionFound = true; } else { // not found } } } } } // if we have enough place on the left of current target if (!positionFound) { futureLeft = result.offsetLeft - description.offsetWidth; futureTop = result.offsetTop + element.offsetHeight / 2 - description.offsetHeight / 2; if (documentLeft < futureLeft) { checkTop = futureTop; if (documentTop < checkTop) { if (checkTop + description.offsetHeight < documentHeight) { futureTop = checkTop; positionFound = true; } else { // not found } } if (!positionFound) { checkTop = documentTop + 5; if (checkTop + description.offsetHeight < documentHeight) { if (documentTop < checkTop) { futureTop = checkTop; positionFound = true; } else { // not found } } } if (!positionFound) { checkTop = documentHeight - 5 - description.offsetHeight; if (documentTop < checkTop) { if (checkTop + description.offsetHeight < documentHeight) { futureTop = checkTop; positionFound = true; } else { // not found } } } } } // if we have enough place on the right of current target if (!positionFound) { futureRight = result.offsetLeft + element.offsetWidth + description.offsetWidth; futureLeft = result.offsetLeft + element.offsetWidth; futureTop = result.offsetTop + element.offsetHeight / 2 - description.offsetHeight / 2; if (documentWidth > futureRight) { checkTop = futureTop; if (documentTop < checkTop) { if (checkTop + description.offsetHeight < documentHeight) { futureTop = checkTop; positionFound = true; } else { // not found } } if (!positionFound) { checkTop = result.offsetTop + 5; if (checkTop + description.offsetHeight < documentHeight) { if (documentTop < checkTop) { futureTop = checkTop; positionFound = true; } else { // not found } } } } } // if we have enough place on bottom of current target if (documentTop > result.offsetTop - description.offsetHeight) { if (!positionFound) { checkTop = result.offsetTop + element.offsetHeight; if (documentHeight > checkTop + description.offsetHeight) { futureTop = checkTop; if (documentWidth > result.offsetLeft + description.offsetWidth) { futureLeft = result.offsetLeft; positionFound = true; } else { if (documentWidth > description.offsetWidth) { futureLeft = 0; positionFound = true; } else { // not found futureLeft = result.offsetLeft + element.offsetWidth / 2 - description.offsetWidth / 2; } } } } } if (!positionFound) { futureLeft = 0; futureTop = result.offsetTop; } this.setState({ left: futureLeft + "px", top: futureTop + "px", show: true, content: description.innerHTML }); } } break; case 'click': if (event.target !== description) { this.releaseDescription(event, description, true); } this.curDescriptionElement = null; break; case 'touchend': target = document.elementFromPoint(event.changedTouches[0].clientX, event.changedTouches[0].clientY); if (target !== description) { this.releaseDescription(event, description, true); } this.curDescriptionElement = null; break; case 'mouseup': target = document.elementFromPoint(event.clientX, event.clientY); if (target !== description) { this.releaseDescription(event, description, true); } this.curDescriptionElement = null; break; } }, releaseDescription(event, description, prevent) { if (this.descriptionShow) { if (prevent) { if (event.cancelable) { event.preventDefault(); } event.stopPropagation(); } this.descriptionShow = false; this.setState({ left: "0px", top: "0px", show: false, content: "" }); } }, render() { let className = this.state.opacity_0 ? "description opacity-0" : "description"; return ( <div data-role="description" className={className} style={{left: this.state.left, top: this.state.top}}>{this.state.content}</div> ) } }); extend_core.prototype.inherit(Description, dom_core); export default Description;
src/client.js
nick/boulder-vote
import React from 'react' import ReactDOM from 'react-dom' import { BrowserRouter } from 'react-router-dom' import Routes from './Routes' import { ApolloProvider } from 'react-apollo' import ApolloClient, { InMemoryCache } from 'apollo-client-preset' const client = new ApolloClient({ cache: new InMemoryCache().restore(window.__STATE__) }); ReactDOM.hydrate(( <ApolloProvider client={client}> <BrowserRouter> <Routes /> </BrowserRouter> </ApolloProvider> ), document.getElementById('app'))
src/route/index.js
kobe1314/react_kobe
// ========================= // Base router // ========================= // =================== // Libs // =================== import React from 'react'; import { Route, Redirect, IndexRedirect } from 'react-router'; // =================== // Containers // =================== import RootContainer from '../a_container/root'; import TestContainer from '../a_container/home/index'; //import TestContainer2 from '../a_container/home2/index'; // =================== // 异步加载container 代码分割按需加载 // =================== // 如果某个路由页面需要代码分割,就像下面这样配置 // 最下面<Route>标签中,就不是component={...},而要用getComponent={...} //而下面的TestContainer就要定义成一个方法 const TestContainer2 = (nextState, cb) => { require.ensure([], require => { //如果使用的是ES6的模块,那么模块中肯定有一个export default,所以下面第2个参数后面就是要加载这个default对象 cb(null, require('../a_container/home2/index').default); }, 'home2'); }; /* require.ensure 参数 1:一个字符串数组,在所有的回调函数执行前,可以将所有依赖的模块在这个数组中声明 2:回调函数,当第1个参数依赖的模块加载完后,就执行此方法 3:生成的js文件的名字 */ // =================== // Exports // =================== // 可以在这里写一些在路由即将被改变时触发的函数 // 可以用参数replace改变接下来的路由地址 const requireAuth = (nextState, replace) => { // replace({ pathname: '/home2' }); }; export default ( <Route path="/" component={RootContainer}> <IndexRedirect to="/home" /> <Route onEnter={requireAuth} path="/home" component={TestContainer} /> <Route onEnter={requireAuth} path="/home2" getComponent={TestContainer2} /> <Redirect from='*' to='/' /> </Route> );
public/js/components/admin/graphs/piechart.react.js
MadushikaPerera/Coupley
/** * Created by Isuru 1 on 22/02/2016. */ import React from 'react'; import { Link } from 'react-router'; import GraphActions from './../../../actions/admin/GraphActions'; import GraphStore from './../../../stores/admin/GraphStore'; const pieChart = React.createClass({ getInitialState: function () { return { status: GraphStore.getresults(), }; }, componentDidMount: function () { GraphActions.userStatus(); GraphStore.addChangeListener(this._onChange); }, _onChange: function () { if (this.isMounted()) { this.setState({ status: GraphStore.getresults(), }); } }, graph: function () { for (var i in this.state.status) { var deactive = this.state.status[i].deactive; //Deactive key's value var active = this.state.status[i].active; //Active key's value var rogue = this.state.status[i].rogue; //Rogue key's value } active = parseInt(active); deactive = parseInt(deactive); rogue = parseInt(rogue); var chart = new CanvasJS.Chart('chartContainer1', { title: { text: 'Users all the time', fontFamily: 'arial black', }, animationEnabled: true, legend: { verticalAlign: 'bottom', horizontalAlign: 'center', }, theme: 'theme1', data: [ { type: 'pie', indexLabelFontFamily: 'Garamond', indexLabelFontSize: 20, indexLabelFontWeight: 'bold', startAngle: 0, indexLabelFontColor: 'MistyRose', indexLabelLineColor: 'darkgrey', indexLabelPlacement: 'inside', toolTipContent: '{y} {name}', indexLabel: '#percent %', showInLegend: true, dataPoints: [ { y: active, name: 'Active Users', legendMarkerType: 'square' }, { y: deactive, name: 'Deactivated Users', legendMarkerType: 'square' }, { y: rogue, name: 'Users Blocked Out of the System', legendMarkerType: 'square' }, ], }, ], }); chart.render(); }, render: function () { return ( <div> <div onLoad={this.graph(this)}></div> </div> ); }, }); export default pieChart;
app/javascript/mastodon/features/following/index.js
esetomo/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import LoadingIndicator from '../../components/loading_indicator'; import { fetchAccount, fetchFollowing, expandFollowing, } from '../../actions/accounts'; import { ScrollContainer } from 'react-router-scroll-4'; import AccountContainer from '../../containers/account_container'; import Column from '../ui/components/column'; import HeaderContainer from '../account_timeline/containers/header_container'; import LoadMore from '../../components/load_more'; import ColumnBackButton from '../../components/column_back_button'; import ImmutablePureComponent from 'react-immutable-pure-component'; const mapStateToProps = (state, props) => ({ accountIds: state.getIn(['user_lists', 'following', props.params.accountId, 'items']), hasMore: !!state.getIn(['user_lists', 'following', props.params.accountId, 'next']), }); @connect(mapStateToProps) export default class Following extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, accountIds: ImmutablePropTypes.list, hasMore: PropTypes.bool, }; componentWillMount () { this.props.dispatch(fetchAccount(this.props.params.accountId)); this.props.dispatch(fetchFollowing(this.props.params.accountId)); } componentWillReceiveProps (nextProps) { if (nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) { this.props.dispatch(fetchAccount(nextProps.params.accountId)); this.props.dispatch(fetchFollowing(nextProps.params.accountId)); } } handleScroll = (e) => { const { scrollTop, scrollHeight, clientHeight } = e.target; if (scrollTop === scrollHeight - clientHeight && this.props.hasMore) { this.props.dispatch(expandFollowing(this.props.params.accountId)); } } handleLoadMore = (e) => { e.preventDefault(); this.props.dispatch(expandFollowing(this.props.params.accountId)); } render () { const { accountIds, hasMore } = this.props; let loadMore = null; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } if (hasMore) { loadMore = <LoadMore onClick={this.handleLoadMore} />; } return ( <Column> <ColumnBackButton /> <ScrollContainer scrollKey='following'> <div className='scrollable' onScroll={this.handleScroll}> <div className='following'> <HeaderContainer accountId={this.props.params.accountId} /> {accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />)} {loadMore} </div> </div> </ScrollContainer> </Column> ); } }
packages/kitchen-sink/src/AppShell/Hamburger/Hamburger.js
spearwolf/blitpunk
import PropTypes from 'prop-types'; import React from 'react'; import styled from 'styled-components'; import './hamburger.scss'; const Container = styled.div` transition-duration: 0.2s; transition-timing-function: ease; transition-property: transform; .hamburger-inner, .hamburger-inner::before, .hamburger-inner::after { background-color: ${(props) => `${props.active ? props.activeColor : props.color}`}; } `; const Button = styled.button` outline: none; `; const Hamburger = ({type, active, className, onClick, color, activeColor}) => ( <Container className={className} active={active} color={color} activeColor={activeColor} > <Button onClick={onClick} className={`hamburger hamburger--${type}${active ? ' is-active' : ''}`} type="button" > <span className="hamburger-box"> <span className="hamburger-inner" /> </span> </Button> </Container> ); Hamburger.propTypes = { type: PropTypes.string, active: PropTypes.bool, className: PropTypes.string, onClick: PropTypes.func.isRequired, color: PropTypes.string, activeColor: PropTypes.string, }; Hamburger.defaultProps = { type: 'collapse', active: false, className: '', color: '#fff', activeColor: '#333', }; export default Hamburger;
blueocean-material-icons/src/js/components/svg-icons/image/camera-rear.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageCameraRear = (props) => ( <SvgIcon {...props}> <path d="M10 20H5v2h5v2l3-3-3-3v2zm4 0v2h5v-2h-5zm3-20H7C5.9 0 5 .9 5 2v14c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V2c0-1.1-.9-2-2-2zm-5 6c-1.11 0-2-.9-2-2s.89-2 1.99-2 2 .9 2 2C14 5.1 13.1 6 12 6z"/> </SvgIcon> ); ImageCameraRear.displayName = 'ImageCameraRear'; ImageCameraRear.muiName = 'SvgIcon'; export default ImageCameraRear;
src/templates/fpv-news.js
jumpalottahigh/blog.georgi-yanev.com
import React from 'react' import { graphql, Link } from 'gatsby' import { Helmet } from 'react-helmet' import Layout from '../components/structure/layout' import FeedbackSection from '../components/FeedbackSection' import AskAQuestion from '../components/AskAQuestion' import SupportSection from '../components/SupportSection' class FpvNewsTemplate extends React.Component { render() { const { markdownRemark: post } = this.props.data // If post doesn't have a defined og image, fall back to default defined here const ogImage = `https://blog.georgi-yanev.com/quick-tips-og-image.jpg` const description = 'Monthly FPV News. Tips, articles, DIY and set up guides. All things FPV.' return ( <Layout location={this.props.location}> <Helmet title={`${post.frontmatter.title} - Georgi Yanev`} meta={[ { name: 'description', content: description, }, { name: 'keywords', content: 'fpv, quad, drone, custom drone build, how to build a quadcopter, how to fly fpv drones, fpv freestyle, fpv racing, quick tips, fpv tips, fpvtips, how to mod fpv drones, guides', }, { property: 'og:type', content: 'website' }, { property: 'og:url', content: `https://blog.georgi-yanev.com${post.frontmatter.path}`, }, { property: 'og:image', content: ogImage, }, { property: 'og:title', content: `${post.frontmatter.title} | Georgi Yanev`, }, { property: 'og:description', content: description, }, { name: 'twitter:card', content: 'summary', }, { name: 'twitter:site', content: '@jumpalottahigh', }, { name: 'twitter:image', content: ogImage, }, { name: 'twitter:creator', content: '@jumpalottahigh', }, { name: 'twitter:title', content: `${post.frontmatter.title} | Georgi Yanev`, }, { name: 'twitter:description', content: description, }, ]} > {/* Google Structured Data */} <script type="application/ld+json">{` { "@context": "http://schema.org", "@type": "NewsArticle", "mainEntityOfPage": { "@type": "WebPage", "@id": "https://blog.georgi-yanev.com${post.frontmatter.path}" }, "headline": "${post.frontmatter.title}", "name": "${post.frontmatter.title}", "author": { "@type": "Person", "name": "Georgi Yanev" }, "datePublished": "${post.frontmatter.dateUnformatted}", "dateModified": "${post.frontmatter.dateUnformatted}", "image": [ "${ogImage}", "${ogImage}", "${ogImage}" ], "publisher": { "@type": "Organization", "name": "Georgi's Blog", "logo": { "@type": "ImageObject", "url": "https://blog.georgi-yanev.com/default-ogimage.png" } }, "description": "${description}", "articleSection": "${description}", "url": "https://blog.georgi-yanev.com${post.frontmatter.path}" } `}</script> </Helmet> <div className="blog-post-container"> <div className="blog-post"> <h1>{post.frontmatter.title}</h1> <div className="disclaimer-container"> <div> <div className="disclaimer"> <a href="https://www.youtube.com/channel/UC2gwYMcfb0Oz_fl9W1uTV2Q" target="_blank" rel="noopener noreferrer" > Georgi Yanev </a> </div> <div className="year">{post.frontmatter.date}</div> </div> </div> <div dangerouslySetInnerHTML={{ __html: post.html }} /> <div style={{ marginTop: '1rem', marginBottom: '2rem' }}> <Link to="/fpv-news/"> <button className="category fpv">More FPV news</button> </Link> </div> <FeedbackSection /> <AskAQuestion /> <SupportSection /> </div> </div> </Layout> ) } } export default FpvNewsTemplate export const pageQuery = graphql` query FpvNewsByPath($path: String!) { markdownRemark(frontmatter: { path: { eq: $path } }) { html frontmatter { date(formatString: "MMMM DD, YYYY") dateUnformatted: date path title } } } `
client/modules/App/__tests__/Components/Footer.spec.js
Cathje/KLP
import React from 'react'; import test from 'ava'; import { shallow } from 'enzyme'; import { Footer } from '../../components/Footer/Footer'; test('renders the footer properly', t => { const wrapper = shallow( <Footer /> ); t.is(wrapper.find('p').length, 2); t.is(wrapper.find('p').first().text(), '© 2016 · Hashnode · LinearBytes Inc.'); });
src/containers/skills.js
ereide/home_page_react
import React from 'react'; import { Row, Col, Image } from 'react-bootstrap'; import DetailedBox from './../components/detailedbox.js'; //importing images import c_cpp from './../assets/c_cpp.jpg'; import csharp from './../assets/csharp.jpg'; import git from './../assets/git.png'; import html_css from './../assets/html_css.png'; import latex from './../assets/latex.png'; import leadership from './../assets/leadership.jpg'; import matlab from './../assets/matlab.png'; import nodejs from './../assets/nodejs.png'; import python from './../assets/python.jpg'; import unix from './../assets/unix.png'; import feedback from './../assets/feedback.png'; import entrepreneur from './../assets/entrepreneur.jpg'; //Importing css import './containers.css'; //Functions function imgText(image, heading, text) { return ( <div> <Image src={image} height={140} /> <h2> {heading} </h2> <p> {text} </p> </div> ); } function three_col(left, mid, right) { return ( <Row> <Col md={4}> {left} </Col> <Col md={4}> {mid} </Col> <Col md={4}> {right} </Col> </Row> ); } //Content const python_skillbox = ( <DetailedBox leftImage={false} image={python} heading={'Python'} mutedheading={'- Professional'} subheading={''} > <p> I have a strong foundation with Python through my various internships and classes at MIT and Cambridge. Python is my preferred language for personal use and prototyping. During my internship at Swift Navigation I learned to write fast, reliable and scalable Python </p> <h3 class="featurette-heading">Packages:</h3> <p> I have used numpy and scipy extensively for writing fast code computations in Python. I have also experience with building web servers with Flask, Bootstrap, SQL databases. </p> </DetailedBox> ); const c_cpp_skillbox = ( <DetailedBox leftImage={true} image={c_cpp} heading={'C/C++'} mutedheading={'- Experienced'} subheading={''} > <p> I have written several programs in C and C++ through my involvement in student societies. In particular I have written firmware for various flight computers during my time in Cambridge University Spaceflight. I have also learned C++ through programming exercises at Cambridge University </p> </DetailedBox> ); const csharp_skillbox = ( <DetailedBox leftImage={false} image={csharp} heading={'C#'} mutedheading={'- Experienced'} subheading={''} > <p> {' '}During my time at Nexans I wrote several programs for calculating various physical properties in underwater cables in C#. I also got introduced to writing GUIs with the .NET framework for C#. </p> </DetailedBox> ); const html_css_skillbox = imgText( html_css, 'HTML/CSS', 'Through various web development projects I have had some exposure to writing CSS and HTML pages' ); const node_js_skillbox = imgText( nodejs, 'Node.js', 'I have had some experience writing server and client side scripts using Node and Javascript. In this context I have made Databases using the noSQL database framework MongoDB' ); const matlab_skillbox = imgText( matlab, 'MATLAB and Simulink', 'I have used MATLAB extensively for creating scripts to do calculations involving matrix operations as well as prototyping machine learning algorithms. I have also some experience with image processing using MATLAB. I have also designed feedback control systems with Simulink.' ); const prog_lang_area = three_col( html_css_skillbox, node_js_skillbox, matlab_skillbox ); const leadership_skillbox = ( <DetailedBox leftImage={false} image={leadership} heading={'Leadership and Teamwork'} mutedheading={'- Experienced'} subheading={''} > <p> I have throughout my education and extra curriculars had experience with working in teams, and often leading teams. This includes both technical and non technical roles. I communicate well with others and I am also used to speaking in public. </p> </DetailedBox> ); const control_skillbox = ( <DetailedBox leftImage={true} image={feedback} heading={'Feedback Control Systems and Estimation '} > <p> One of my main areas of focus at University has been feedback control systems and estimation. I have written control loops for a drone as well as having had exposure to estimation techniques during my time at Swift Navigation. I have also worked on several kalman filters and similar through my involvement in Cambridge University Spaceflight </p> </DetailedBox> ); const entrepeneur_skillbox = ( <DetailedBox leftImage={false} image={entrepreneur} heading={'Entrepreneurship'} > <p> During my time at MIT I had the opportunity to take an advanced entrepreneurship project class exposing me to the inner workings on how to start a business. This, combined with my time in San Francisco, has helped me develop an entrepreneurial mindset. </p> </DetailedBox> ); const git_skillbox = imgText( git, 'Git', 'Both through my internships and my participation in various student societies I have used Git extensively for version control.' ); const unix_skillbox = imgText( unix, 'UNIX and Linux development', 'I am used to working with Linux for development purposes' ); const latex_skillbox = imgText( latex, 'LaTeX', 'I have used LaTeX extensively to write reports at school and at work.' ); const other_skills_area = three_col( git_skillbox, unix_skillbox, latex_skillbox ); class Skills extends React.Component { render() { return ( <div> <h1> Programming languages </h1> <hr /> {python_skillbox} <hr /> {c_cpp_skillbox} <hr /> {csharp_skillbox} <hr /> {prog_lang_area} <h1> Other skills </h1> <hr /> {leadership_skillbox} <hr /> {control_skillbox} <hr /> {entrepeneur_skillbox} <hr /> {other_skills_area} </div> ); } } export default Skills;
landing_mobx/src/employer/CandidateList.js
1a2a3a4a/PONTUS
/** * Created by tonyw on 2017-06-03. */ import React, { Component } from 'react'; import Avatar from 'material-ui/Avatar'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import People from 'material-ui/svg-icons/social/people' import List from 'material-ui/List/List'; import ListItem from 'material-ui/List/ListItem'; class CandidateList extends Component{ generateCandidates(length){ let candidateArray = []; for(let i = 0; i < length; i++){ candidateArray.push(<ListItem key={i} leftAvatar={ <Candidate/>}/>) } return candidateArray; } render(){ const candidateListItems = this.generateCandidates(10) const scrollBar = { overflow: 'scroll', height: '30em', overflowX:'hidden', }; return( <div style={scrollBar}> <MuiThemeProvider> <List> {candidateListItems} </List> </MuiThemeProvider> </div> ) } } class Candidate extends Component{ render(){ const style = {margin: 5}; return( <div> <MuiThemeProvider> <Avatar icon={<People/>} size={45} style={style} /> </MuiThemeProvider> <CandidateInformation/> </div> ) } } class CandidateInformation extends Component{ render(){ const styles ={ display: 'inline-block', margin: '0.6em', position: 'absolute', float: 'right', }; return( <div style={styles}> <span>Lorum Ipsum etc.</span> <br/> <span>More latin words etc.</span> </div> ) } } export default CandidateList
public/js/cat_source/es6/components/modals/DQFCredentials.js
matecat/MateCat
import update from 'immutability-helper' import React from 'react' import TextField from '../common/TextField' import * as RuleRunner from '../common/ruleRunner' import * as FormRules from '../common/formRules' import {getMatecatApiDomain} from '../../utils/getMatecatApiDomain' import { clearDqfCredentials as clearDqfCredentialsApi, submitDqfCredentials as submitDqfCredentialsApi, } from '../../api/dqfCredentials' class DQFCredentials extends React.Component { constructor(props) { super(props) this.state = { dqfCredentials: { dqfUsername: this.props.metadata.dqf_username, dqfPassword: this.props.metadata.dqf_password, }, dqfValid: false, showErrors: false, validationErrors: {}, } this.state.validationErrors = RuleRunner.run(this.state, fieldValidations) } handleDQFFieldChanged(field) { return (e) => { var newState = update(this.state, { [field]: {$set: e.target.value}, }) newState.validationErrors = RuleRunner.run(newState, fieldValidations) newState.generalError = '' this.setState(newState) } } handleDQFSubmitClicked() { this.setState({showErrors: true}) if ($.isEmptyObject(this.state.validationErrors) == false) return null this.submitDQFCredentials() } errorFor(field) { return this.state.validationErrors[field] } submitDQFCredentials() { let self = this submitDqfCredentialsApi(this.state.dqfUsername, this.state.dqfPassword) .then((data) => { if (data) { APP.USER.STORE.metadata = data self.setState({ dqfValid: true, dqfCredentials: { dqfUsername: self.state.dqfUsername, dqfPassword: self.state.dqfPassword, }, }) } else { self.setState({ dqfError: 'Invalid credentials', }) } }) .catch(() => { self.setState({ dqfError: 'Invalid credentials', }) }) } clearDQFCredentials() { let self = this let dqfCheck = $('.dqf-box #dqf_switch') clearDqfCredentialsApi().then((data) => { APP.USER.STORE.metadata = data dqfCheck.trigger('dqfDisable') if (self.saveButton) { self.saveButton.classList.remove('disabled') } self.setState({ dqfValid: false, dqfCredentials: {}, dqfOptions: {}, }) }) } getDqfHtml() { if (this.state.dqfValid || this.state.dqfCredentials.dqfUsername) { return ( <div className="user-dqf"> <input type="text" name="dqfUsername" defaultValue={this.state.dqfCredentials.dqfUsername} disabled /> <br /> <input type="password" name="dqfPassword" defaultValue={this.state.dqfCredentials.dqfPassword} disabled style={{marginTop: '15px'}} /> <br /> <div className="ui primary button" style={{marginTop: '15px', marginLeft: '82%'}} onClick={this.clearDQFCredentials.bind(this)} > Clear </div> </div> ) } else { return ( <div className="user-dqf"> <TextField showError={this.state.showErrors} onFieldChanged={this.handleDQFFieldChanged('dqfUsername')} placeholder="Username" name="dqfUsername" errorText={this.errorFor('dqfUsername')} tabindex={1} onKeyPress={(e) => { e.key === 'Enter' ? this.handleDQFSubmitClicked() : null }} /> <TextField type="password" showError={this.state.showErrors} onFieldChanged={this.handleDQFFieldChanged('dqfPassword')} placeholder="Password (minimum 8 characters)" name="dqfPassword" errorText={this.errorFor('dqfPassword')} tabindex={2} onKeyPress={(e) => { e.key === 'Enter' ? this.handleDQFSubmitClicked() : null }} /> <div className="ui primary button" onClick={this.handleDQFSubmitClicked.bind(this)} > Sign in </div> <div className="dqf-message"> <span style={{ color: 'red', fontSize: '14px', position: 'absolute', right: '27%', lineHeight: '24px', }} className="coupon-message" > {this.state.dqfError} </span> </div> </div> ) } } componentDidMount() {} render() { return this.getDqfHtml() } } const fieldValidations = [ RuleRunner.ruleRunner('dqfUsername', 'Username', FormRules.requiredRule), RuleRunner.ruleRunner( 'dqfPassword', 'Password', FormRules.requiredRule, FormRules.minLength(8), ), ] export default DQFCredentials
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/DefaultPropsInferred.js
jamesgpearce/flow
// @flow import React from 'react'; class MyComponent extends React.Component { static defaultProps = {}; props: Props; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} } const expression = () => class extends React.Component { static defaultProps = {}; props: Props; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} }
examples/universal/server/server.js
kevinold/redux
/* eslint-disable no-console, no-use-before-define */ import path from 'path'; import Express from 'express'; import qs from 'qs'; import webpack from 'webpack'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; import webpackConfig from '../webpack.config'; import React from 'react'; import { Provider } from 'react-redux'; import configureStore from '../common/store/configureStore'; import App from '../common/containers/App'; import { fetchCounter } from '../common/api/counter'; const app = new Express(); const port = 3000; // Use this middleware to set up hot module reloading via webpack. const compiler = webpack(webpackConfig); app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath })); app.use(webpackHotMiddleware(compiler)); // This is fired every time the server side receives a request app.use(handleRender); function handleRender(req, res) { // Query our mock API asynchronously fetchCounter(apiResult => { // Read the counter from the request, if provided const params = qs.parse(req.query); const counter = parseInt(params.counter, 10) || apiResult || 0; // Compile an initial state const initialState = { counter }; // Create a new Redux store instance const store = configureStore(initialState); // Render the component to a string const html = React.renderToString( <Provider store={store}> { () => <App/> } </Provider>); // Grab the initial state from our Redux store const finalState = store.getState(); // Send the rendered page back to the client res.send(renderFullPage(html, finalState)); }); } function renderFullPage(html, initialState) { return ` <!doctype html> <html> <head> <title>Redux Universal Example</title> </head> <body> <div id="app">${html}</div> <script> window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}; </script> <script src="/static/bundle.js"></script> </body> </html> `; } app.listen(port, (error) => { if (error) { console.error(error); } else { console.info(`==> 🌎 Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`); } });
app/static/src/performer/NewTestForm.js
SnowBeaver/Vision
import React from 'react'; import FormControl from 'react-bootstrap/lib/FormControl'; import FormGroup from 'react-bootstrap/lib/FormGroup'; import ControlLabel from 'react-bootstrap/lib/ControlLabel'; import Button from 'react-bootstrap/lib/Button'; import DateTimeField from 'react-bootstrap-datetimepicker/lib/DateTimeField' import Panel from 'react-bootstrap/lib/Panel'; import Radio from 'react-bootstrap/lib/Radio'; import Checkbox from 'react-bootstrap/lib/Checkbox'; import Modal from 'react-bootstrap/lib/Modal'; import {findDOMNode} from 'react-dom'; import NewUserForm from './CampaignForm_modules/NewUserForm'; import ElectricalProfileForm from './ElectricalProfileForm'; import FluidProfileForm from './FluidProfileForm'; import NewMaterialForm from './NewTestForm_modules/NewMaterialForm'; import NewContractForm from './CampaignForm_modules/NewContractForm'; import NewLabForm from './CampaignForm_modules/NewLabForm'; import NewFluidForm from './NewTestForm_modules/NewFluidForm'; import NewSyringeForm from './NewTestForm_modules/NewSyringeForm'; import {NotificationContainer, NotificationManager} from 'react-notifications'; import HelpBlock from 'react-bootstrap/lib/HelpBlock'; import {DATETIMEPICKER_FORMAT} from './appConstants.js'; var items = []; var TestProfileSelectField = React.createClass({ getInitialState: function () { return { isVisible: true, value: this.props.value }; }, handleChange: function (event) { this.setState({ value: event.target.value }); }, componentDidMount: function () { this.serverRequest = $.authorizedGet(this.props.source, function (result) { this.setState({ items: result['result'] }); }.bind(this), 'json'); }, componentWillUnmount: function () { this.serverRequest.abort(); }, setVisible: function () { this.state.isVisible = true; }, render: function () { var options = []; for (var key in this.state.items) { var index = Math.random() + '_' + this.state.items[key].id; options.push(<option key={index} value={this.state.items[key].id}>{`${this.state.items[key].name}`}</option>); } return ( <FormGroup> <FormControl componentClass="select" placeholder="select" value={this.props.value} onChange={this.handleChange} name="profile_type_id"> <option value="select_prof">Choose profile from saved</option> {options} </FormControl> </FormGroup> ) } }); var PerformedBySelectField = React.createClass({ handleChange: function (event, index, value) { this.setState({ value: event.target.value }); }, getInitialState: function () { return { items: [], isVisible: false, value: this.props.value }; }, isVisible: function () { return this.state.isVisible; }, componentDidMount: function () { this.serverRequest = $.authorizedGet(this.props.source, function (result) { var items = (result['result']); this.setState({ items: items }); }.bind(this), 'json'); }, componentWillUnmount: function () { this.serverRequest.abort(); }, setVisible: function () { this.state.isVisible = true; }, setSelected: function (data) { this.componentDidMount(); this.setState({ selected: data.result }); }, render: function () { var menuItems = []; for (var key in this.state.items) { menuItems.push(<option key={this.state.items[key].id} value={this.state.items[key].id}>{`${this.state.items[key].name}`}</option>); } return ( <div> <FormGroup validationState={this.props.errors.performed_by_id ? 'error' : null}> <FormControl componentClass="select" placeholder="select" onChange={this.handleChange} value={this.props.value} name="performed_by_id" required={this.props.required}> <option key="0" value="">Performed by{this.props.required ? " *": ""}</option> {menuItems} </FormControl> <HelpBlock className="warning">{this.props.errors.performed_by_id}</HelpBlock> </FormGroup> </div> ); } }); var MaterialSelectField = React.createClass({ handleChange: function (event, index, value) { this.setState({ value: event.target.value }); }, getInitialState: function () { return { items: [], isVisible: false, value: this.props.value }; }, isVisible: function () { return this.state.isVisible; }, componentDidMount: function () { this.serverRequest = $.authorizedGet(this.props.source, function (result) { var items = (result['result']); this.setState({ items: items }); }.bind(this), 'json'); }, componentWillUnmount: function () { this.serverRequest.abort(); }, setVisible: function () { this.state.isVisible = true; }, setSelected: function (data) { this.componentDidMount(); this.setState({ selected: data.result }); }, render: function () { var menuItems = []; for (var key in this.state.items) { menuItems.push(<option key={this.state.items[key].id} value={this.state.items[key].id}>{`${this.state.items[key].name}`}</option>); } return ( <div> <FormGroup validationState={this.props.errors.material_id ? 'error' : null}> <FormControl componentClass="select" placeholder="select material" onChange={this.handleChange} value={this.props.value} name="material_id" required={this.props.required}> <option key="0" value="">Material{this.props.required ? " *" : ""}</option> {menuItems} </FormControl> <HelpBlock className="warning">{this.props.errors.material_id}</HelpBlock> </FormGroup> </div> ); } }); var FluidTypeSelectField = React.createClass({ handleChange: function (event, index, value) { this.setState({ value: event.target.value }); }, getInitialState: function () { return { items: [], isVisible: false, value: this.props.value }; }, isVisible: function () { return this.state.isVisible; }, componentDidMount: function () { this.serverRequest = $.authorizedGet(this.props.source, function (result) { var items = (result['result']); this.setState({ items: items }); }.bind(this), 'json'); }, componentWillUnmount: function () { this.serverRequest.abort(); }, setVisible: function () { this.state.isVisible = true; }, setSelected: function (data) { this.componentDidMount(); this.setState({ selected: data.result }); }, render: function () { var menuItems = []; for (var key in this.state.items) { menuItems.push(<option key={this.state.items[key].id} value={this.state.items[key].id}>{`${this.state.items[key].name}`}</option>); } return ( <div> <FormGroup validationState={this.props.errors.fluid_type_id ? 'error' : null}> <FormControl componentClass="select" placeholder="select" onChange={this.handleChange} value={this.props.value} name="fluid_type_id" > <option key="0" value="">Fluid Type</option> {menuItems} </FormControl> <HelpBlock className="warning">{this.props.errors.fluid_type_id}</HelpBlock> </FormGroup> </div> ); } }); var LabAnalyserSelectField = React.createClass({ handleChange: function (event, index, value) { this.setState({ value: event.target.value }); }, getInitialState: function () { return { items: [], isVisible: false, value: this.props.value }; }, isVisible: function () { return this.state.isVisible; }, componentDidMount: function () { this.serverRequest = $.authorizedGet(this.props.source, function (result) { var items = (result['result']); this.setState({ items: items }); }.bind(this), 'json'); }, componentWillUnmount: function () { this.serverRequest.abort(); }, setVisible: function () { this.state.isVisible = true; }, setSelected: function (data) { this.componentDidMount(); this.setState({ selected: data.result }); }, render: function () { var menuItems = []; for (var key in this.state.items) { menuItems.push(<option key={this.state.items[key].id} value={this.state.items[key].id}>{`${this.state.items[key].name}`}</option>); } return ( <div> <FormGroup validationState={this.props.errors.lab_id ? 'error' : null}> <FormControl componentClass="select" placeholder="select" onChange={this.handleChange} value={this.props.value} name="lab_id" required={this.props.required}> <option key="0" value="">Lab/On-Line Analyser{this.props.required ? " *" : ""}</option> {menuItems} </FormControl> <HelpBlock className="warning">{this.props.errors.lab_id}</HelpBlock> </FormGroup> </div> ); } }); var LabContractSelectField = React.createClass({ handleChange: function (event, index, value) { this.setState({ value: event.target.value, }); }, getInitialState: function () { return { items: [], isVisible: false, value: this.props.value }; }, isVisible: function () { return this.state.isVisible; }, componentDidMount: function () { this.serverRequest = $.authorizedGet(this.props.source, function (result) { var items = (result['result']); this.setState({ items: items }); }.bind(this), 'json'); }, componentWillUnmount: function () { this.serverRequest.abort(); }, setVisible: function () { this.state.isVisible = true; }, setSelected: function (data) { this.componentDidMount(); this.setState({ selected: data.result }); }, render: function () { var menuItems = []; for (var key in this.state.items) { menuItems.push(<option key={this.state.items[key].id} value={this.state.items[key].id}>{`${this.state.items[key].name}`}</option>); } return ( <div> <FormGroup validationState={this.props.errors.lab_contract_id ? 'error' : null}> <FormControl componentClass="select" placeholder="select" onChange={this.handleChange} value={this.props.value} name="lab_contract_id" required={this.props.required}> <option key="0" value="">Lab Contract{this.props.required ? " *" : ""}</option> {menuItems} </FormControl> <HelpBlock className="warning">{this.props.errors.lab_contract_id}</HelpBlock> </FormGroup> </div> ); } }); var SyringeNumberSelectField = React.createClass({ handleChange: function (event, index, value) { this.setState({ value: event.target.value, }); }, getInitialState: function () { return { items: [], isVisible: false, value: this.props.value }; }, isVisible: function () { return this.state.isVisible; }, componentDidMount: function () { this.serverRequest = $.authorizedGet(this.props.source, function (result) { var items = (result['result']); this.setState({ items: items }); }.bind(this), 'json'); }, componentWillUnmount: function () { this.serverRequest.abort(); }, setVisible: function () { this.state.isVisible = true; }, setSelected: function (data) { this.componentDidMount(); this.setState({ selected: data.result }); }, render: function () { var menuItems = []; for (var key in this.state.items) { menuItems.push(<option key={this.state.items[key].id} value={this.state.items[key].id}>{`${this.state.items[key].serial}`}</option>); } return ( <div> <FormGroup validationState={this.props.errors.seringe_num ? 'error' : null}> <FormControl componentClass="select" placeholder="select" onChange={this.handleChange} value={this.props.value} name="seringe_num" data-len={this.props["data-len"]}> <option key="0" value="">Syringe Number</option> {menuItems} </FormControl> <HelpBlock className="warning">{this.props.errors.seringe_num}</HelpBlock> </FormGroup> </div> ); } }); var TestReasonSelectField = React.createClass({ handleChange: function (event) { this.setState({ value: event.target.value }); }, getInitialState: function () { return { items: [], isVisible: false, value: this.props.value }; }, isVisible: function () { return this.state.isVisible; }, componentDidMount: function () { this.serverRequest = $.authorizedGet(this.props.source, function (result) { var items = (result['result']); this.setState({ items: items }); }.bind(this), 'json'); }, componentWillUnmount: function () { this.serverRequest.abort(); }, setVisible: function () { this.state.isVisible = true; }, setSelected: function (selected) { this.setState({ selected: selected }) }, render: function () { var menuItems = []; for (var key in this.state.items) { menuItems.push(<option key={this.state.items[key].id} value={this.state.items[key].id}>{`${this.state.items[key].name}`}</option>); } return ( <FormGroup validationState={this.props.errors.test_reason_id ? 'error' : null}> <FormControl componentClass="select" placeholder="select" value={this.props.value} name="test_reason_id" onChange={this.handleChange} required={this.props.required} > <option key="0" value="">Reason for Testing{this.props.required ? " *": ""}</option> {menuItems} </FormControl> <HelpBlock className="warning">{this.props.errors.test_reason_id}</HelpBlock> </FormGroup> ); } }); var NewTestForm = React.createClass({ //test_sampling_card //test_status_id - should be set separate //test_recommendation getInitialState: function () { return { loading: false, errors: {}, showFluidProfileForm: false, showElectroProfileForm: false, showNewUserForm: false, showNewMaterialForm: false, showNewFluidForm: false, showNewContractForm: false, showNewLabForm: false, showNewSyringeForm: false, date_analyse: new Date().toISOString(), fields: [ 'test_reason_id', 'status_id', 'equipment_id', 'date_analyse', 'test_type_id', 'test_status_id', 'material_id', 'fluid_type_id', 'performed_by_id', 'lab_id', 'lab_contract_id', 'analysis_number', 'mws', 'temperature', 'seringe_num', 'transmission', 'charge', 'remark', 'repair_date', 'repair_description', 'ambient_air_temperature' ], test_reason_id: '', changedFields: [] } }, componentDidMount: function () { if ((this.props.data != null) && (typeof this.props.data.id != 'undefined')) { this._edit(this.props.data.id); } }, _edit: function (id) { // fill up form with data var url = '/api/v1.0/test_result/' + id; // edit this.serverRequest = $.authorizedGet(url, function (result) { var data = (result['result']); var fields = this.state.fields; var form = {}; for (var i = 0; i < fields.length; i++) { var key = fields[i]; form[key] = (data[key] !== null) ? data[key] : ""; } form['id'] = id; if (!form['date_analyse']) { form['date_analyse'] = new Date().toISOString(); form.changedFields = this.state.changedFields.concat(['date_analyse']); } form.errors = {}; this.setState(form); }.bind(this), 'json'); }, _add: function () { var fields = this.state.fields; var form = {}; for (var i = 0; i < fields.length; i++) { var key = fields[i]; form[key] = ''; } form['id'] = ''; form['campaign_id'] = this.props.data['campaign_id']; form['equipment_id'] = this.props.data['equipment_id']; form['date_analyse'] = new Date().toISOString(); form.changedFields = this.state.changedFields.concat(['date_analyse']); form.errors = {}; this.setState(form); }, _save: function () { var fields = this.state.changedFields; var data = {}; for (var i = 0; i < fields.length; i++) { var key = fields[i]; var value = this.state[key]; if (value == ""){ value = null; } data[key] = value; } var url = '/api/v1.0/test_result/' + this.state.id; // edit when id is set delete data['analysis_number']; data['campaign_id'] = this.props.data['campaign_id']; data['equipment_id'] = this.props.data['equipment_id']; return $.authorizedAjax({ url: url, type: 'POST', dataType: 'json', contentType: 'application/json', data: JSON.stringify(data), beforeSend: function () { this.setState({loading: true}); }.bind(this) }) }, _onSubmit: function (e) { e.preventDefault(); if (!this.is_valid()){ NotificationManager.error('Please correct the errors'); return false; } var xhr = this._save(); if (!xhr) { NotificationManager.error('Something went wrong.'); } xhr.done(this._onSuccess) .fail(this._onError) .always(this.hideLoading) }, is_valid: function () { return (Object.keys(this.state.errors).length <= 0); }, hideLoading: function () { this.setState({loading: false}); }, _onSuccess: function (data) { this.setState({ analysis_number: data['result']['analysis_number'] }); NotificationManager.success('Test saved', null, 4000); this.props.reloadList(); }, _onError: function (data) { var message = "Failed to create"; var res = data.responseJSON; if (res.message) { message = data.responseJSON.message; } if (res.error) { // We get list of errors if (data.status >= 500) { message = res.error.join(". "); } else if (res.error instanceof Object){ // We get object of errors with field names as key for (var field in res.error) { var errorMessage = res.error[field]; if (Array.isArray(errorMessage)) { errorMessage = errorMessage.join(". "); } res.error[field] = errorMessage; } this.setState({ errors: res.error }); } else { message = res.error; } } NotificationManager.error(message); }, _onChange: function (e) { var state = {}; if (e.target.type == 'checkbox') { state[e.target.name] = e.target.checked; } else if (e.target.type == 'select-one') { state[e.target.name] = e.target.value; } else if (e.target.type == 'radio') { state[e.target.name] = e.target.value; // fluid if ('1' === e.target.value) { this.setState({ showFluidProfileForm: true, showElectroProfileForm: false }); //electrical } else if ('2' === e.target.value) { this.setState({ showElectroProfileForm: true, showFluidProfileForm: false }); } } else { // Ignore this method when user deletes manually date from the DateTime input // Let the special method for setting the date be called if (["date_analyse", "repair_date"].indexOf(e.target.name) == -1){ state[e.target.name] = e.target.value; } } state.changedFields = this.state.changedFields.concat([e.target.name]); var errors = this._validate(e); state = this._updateFieldErrors(e.target.name, state, errors); this.setState(state); }, _validate: function (e) { var errors = []; var error; error = this._validateFieldType(e.target.value, e.target.getAttribute("data-type")); if (error){ errors.push(error); } error = this._validateFieldLength(e.target.value, e.target.getAttribute("data-len")); if (error){ errors.push(error); } return errors; }, _validateFieldType: function (value, type){ var error = ""; if (type != undefined && value){ var typePatterns = { "float": /^(-|\+?)[0-9]+(\.)?[0-9]*$/, "int": /^(-|\+)?(0|[1-9]\d*)$/ }; if (!typePatterns[type].test(value)){ error = "Invalid " + type + " value"; } } return error; }, _validateFieldLength: function (value, length){ var error = ""; if (value && length){ if (value.length > length){ error = "Value should be maximum " + length + " characters long" } } return error; }, _updateFieldErrors: function (fieldName, state, errors){ // Clear existing errors related to the current field as it has been edited state.errors = this.state.errors; delete state.errors[fieldName]; // Update errors with new ones, if present if (Object.keys(errors).length){ state.errors[fieldName] = errors.join(". "); } return state; }, setRepairDate: function (timestamp){ this._setDateTimeFieldDate(timestamp, "repair_date"); }, setDateAnalyse: function (timestamp){ this._setDateTimeFieldDate(timestamp, "date_analyse"); }, _setDateTimeFieldDate(timestamp, fieldName){ var state = {}; // If date is not valid (for example, date is deleted) string "Invalid date" is received if (timestamp == "Invalid date"){ timestamp = null; } else if (timestamp){ // It is UNIX timestamp in milliseconds if dateTimeField was empty on load // Format date here instead of specifying format in DateTimeField, // because error is raised when format is specified, but date is null/undefined/empty string. if (/^\d+$/.test(timestamp)){ timestamp = parseInt(timestamp); timestamp = moment(timestamp).toISOString(); } state[fieldName] = timestamp; // Already formatted to ISO string } state.changedFields = this.state.changedFields.concat([fieldName]); this.setState(state); }, _formGroupClass: function (field) { var className = "form-group "; if (field) { className += " has-error" } return className; }, closeElectricalProfileForm: function () { this.setState({ showElectroProfileForm: false }) }, closeFluidProfileForm: function () { this.setState({ showFluidProfileForm: false }) }, closeNewFluidForm: function () { this.setState({ showNewFluidForm: false }) }, closeNewMaterialForm: function () { this.setState({ showNewMaterialForm: false }) }, closeNewUserForm: function () { this.setState({ showNewUserForm: false }) }, closeNewContractForm: function () { this.setState({ showNewContractForm: false }) }, closeNewLabForm: function () { this.setState({ showNewLabForm: false }) }, closeNewSyringeForm: function () { this.setState({ showNewSyringeForm: false }) }, onContractCreate: function (response) { this.refs.contract.setSelected(response); this.setState({lab_contract_id: response.result, changedFields: this.state.changedFields.concat(["lab_contract_id"])}); this.closeNewContractForm(); NotificationManager.success('Contract added', null, 2000); }, onPerformerCreate: function (response) { this.refs.performed_by.setSelected(response); this.setState({performed_by_id: response.result, changedFields: this.state.changedFields.concat(["performed_by_id"])}); this.closeNewUserForm(); NotificationManager.success('User added', null, 2000); }, onLabCreate: function (response) { this.refs.lab.setSelected(response); this.setState({lab_id: response.result, changedFields: this.state.changedFields.concat(["lab_id"])}); this.closeNewLabForm(); NotificationManager.success('Laboratory added', null, 2000); }, onMaterialCreate: function (response) { this.refs.material.setSelected(response); this.setState({material_id: response.result, changedFields: this.state.changedFields.concat(["material_id"])}); this.closeNewMaterialForm(); NotificationManager.success('Material added', null, 2000); }, onFluidTypeCreate: function (response) { this.refs.fluid_type.setSelected(response); this.setState({fluid_type_id: response.result, changedFields: this.state.changedFields.concat(["fluid_type_id"])}); this.closeNewFluidForm(); NotificationManager.success('Fluid type added', null, 2000); }, onSyringeCreate: function (response) { this.refs.syringe.setSelected(response); this.setState({seringe_num: response.result, changedFields: this.state.changedFields.concat(["seringe_num"])}); this.closeNewSyringeForm(); NotificationManager.success('Syringe added', null, 2000); }, onNewButtonClick: function (e) { if (e.target.id === 'material') { this.setState({ showNewMaterialForm: true, showNewFluidForm: false, showNewUserForm: false, showNewContractForm: false, showNewLabForm: false, showNewSyringeForm: false }) } else if (e.target.id === 'fluid_type') { this.setState({ showNewMaterialForm: false, showNewFluidForm: true, showNewUserForm: false, showNewContractForm: false, showNewLabForm: false, showNewSyringeForm: false }) } else if (e.target.id === 'performed_by') { this.setState({ showNewMaterialForm: false, showNewFluidForm: false, showNewUserForm: true, showNewContractForm: false, showNewLabForm: false, showNewSyringeForm: false }) } else if (e.target.id === 'lab_analyser') { this.setState({ showNewMaterialForm: false, showNewFluidForm: false, showNewUserForm: false, showNewContractForm: false, showNewLabForm: true, showNewSyringeForm: false }) } else if (e.target.id === 'lab_contract') { this.setState({ showNewMaterialForm: false, showNewFluidForm: false, showNewUserForm: false, showNewContractForm: true, showNewLabForm: false, showNewSyringeForm: false }) } else if (e.target.id === 'syringe') { this.setState({ showNewMaterialForm: false, showNewFluidForm: false, showNewUserForm: false, showNewContractForm: false, showNewLabForm: false, showNewSyringeForm: true }) } }, render: function () { var title = (this.state.id) ? "Edit test" : 'New test'; // Do not set dateTime property if date is null/undefined/empty string, calendar will be broken var dateRepair = this.state.repair_date; dateRepair = (dateRepair) ? {dateTime: dateRepair, format: DATETIMEPICKER_FORMAT} : {defaultText: "Please select a date"}; var dateAnalyse = this.state.date_analyse; dateAnalyse = (dateAnalyse) ? {dateTime: dateAnalyse, format: DATETIMEPICKER_FORMAT} : {defaultText: "Please select a date"}; return ( this.props.show ? <div className="form-container"> <form method="post" action="#" onSubmit={this._onSubmit} onChange={this._onChange}> <Panel header={title}> <div className="maxwidth"> <div className="col-md-12"> <div className="maxwidth"> <FormGroup validationState={this.state.errors.analysis_number ? 'error' : null}> <FormControl type="text" placeholder="Analysis Number" name="analysis_number" readOnly="readOnly" value={this.state.analysis_number} /> <HelpBlock className="warning">{this.state.errors.analysis_number}</HelpBlock> <FormControl.Feedback /> </FormGroup> </div> <div className="row"> <div className="col-md-10"> <TestReasonSelectField ref="test_reason" source="/api/v1.0/test_reason" handleChange={this.handleChange} value={this.state.test_reason_id} errors={this.state.errors} required /> </div> </div> <div className="row"> <div className="col-md-11"> <MaterialSelectField ref="material" source="/api/v1.0/material/" handleChange={this.handleChange} value={this.state.material_id} errors={this.state.errors} required /> </div> <div className="col-md-1"> <a id="material" className="btn btn-primary" onClick={this.onNewButtonClick} >New</a> </div> </div> <div className="row"> <div className="col-md-11"> <FluidTypeSelectField ref="fluid_type" source="/api/v1.0/fluid_type/" value={this.state.fluid_type_id} errors={this.state.errors} /> </div> <div className="col-md-1"> <a id="fluid_type" className="btn btn-primary" onClick={this.onNewButtonClick} >New</a> </div> </div> <div className="row"> <div className="col-md-11"> <PerformedBySelectField ref="performed_by" source="/api/v1.0/user" handleChange={this.handleChange} value={this.state.performed_by_id} errors={this.state.errors} required /> </div> <div className="col-md-1"> <a id="performed_by" className="btn btn-primary" onClick={this.onNewButtonClick} >New</a> </div> </div> <div className="row"> <div className="col-md-11"> <LabAnalyserSelectField ref="lab" source="/api/v1.0/lab/" value={this.state.lab_id} errors={this.state.errors} required /> </div> <div className="col-md-1"> <a id="lab_analyser" className="btn btn-primary" onClick={this.onNewButtonClick} >New</a> </div> </div> <div className="row"> <div className="col-md-11"> <LabContractSelectField ref="contract" source="/api/v1.0/contract/" handleChange={this.handleChange} value={this.state.lab_contract_id} errors={this.state.errors} required /> </div> <div className="col-md-1"> <a id="lab_contract" className="btn btn-primary" onClick={this.onNewButtonClick} >New</a> </div> </div> <div className="row"> <div className="col-md-12"> <FormGroup validationState={this.state.errors.charge ? 'error' : null}> <FormControl type="text" placeholder="Charge" name="charge" value={this.state.charge} data-type="float" /> <HelpBlock className="warning">{this.state.errors.charge}</HelpBlock> <FormControl.Feedback /> </FormGroup> </div> </div> <div className="row"> <div className="col-md-12"> <FormGroup validationState={this.state.errors.remark ? 'error' : null}> <ControlLabel>Remark</ControlLabel> <FormControl componentClass="textarea" placeholder="remark" name="remark" value={this.state.remark} /> <HelpBlock className="warning">{this.state.errors.remark}</HelpBlock> <FormControl.Feedback /> </FormGroup> </div> </div> <div className="maxwidth"> <div className="col-md-4 nopadding padding-right-xs"> <Checkbox name="transmission" checked={this.state.transmission ? "checked" :null}> Sent to Laboratory </Checkbox> </div> </div> <div className="maxwidth"> <div className="datetimepicker input-group date col-md-3"> <FormGroup validationState={this.state.errors.repair_date ? 'error' : null} key={this.state.repair_date}> <ControlLabel>Repair Date</ControlLabel> <DateTimeField name="repair_date" onChange={this.setRepairDate} inputProps={{"name": "repair_date"}} {...dateRepair} /> <HelpBlock className="warning">{this.state.errors.repair_date}</HelpBlock> </FormGroup> </div> </div> <div className="row"> <div className="col-md-12"> <FormGroup validationState={this.state.errors.repair_description ? 'error' : null}> <ControlLabel>Repair Description</ControlLabel> <FormControl componentClass="textarea" placeholder="repair description" name="repair_description" value={this.state.repair_description} /> <HelpBlock className="warning">{this.state.errors.repair_description}</HelpBlock> <FormControl.Feedback /> </FormGroup> </div> </div> <div className="maxwidth"> <div className="datetimepicker input-group date col-md-3"> <FormGroup validationState={this.state.errors.date_analyse ? 'error' : null} key={this.state.date_analyse}> <ControlLabel>Date Applied *</ControlLabel> <DateTimeField name="date_analyse" onChange={this.setDateAnalyse} inputProps={{"required":"required", "name": "date_analyse"}} {...dateAnalyse}/> <HelpBlock className="warning">{this.state.errors.date_analyse}</HelpBlock> </FormGroup> </div> </div> <div className="row"> <div className="col-md-12"> <FormGroup validationState={this.state.errors.mws ? 'error' : null}> <FormControl type="text" placeholder="Equipment Load mW" name="mws" value={this.state.mws} data-type="float" /> <HelpBlock className="warning">{this.state.errors.mws}</HelpBlock> <FormControl.Feedback /> </FormGroup> </div> </div> <div className="row"> <div className="col-md-12"> <FormGroup validationState={this.state.errors.temperature ? 'error' : null}> <FormControl type="text" placeholder="Temperature" name="temperature" value={this.state.temperature} data-type="float" /> <HelpBlock className="warning">{this.state.errors.temperature}</HelpBlock> <FormControl.Feedback /> </FormGroup> </div> </div> <div className="row"> <div className="col-md-11"> <SyringeNumberSelectField ref="syringe" source="/api/v1.0/syringe/" handleChange={this.handleChange} value={this.state.seringe_num} errors={this.state.errors} data-len="50" /> </div> <div className="col-md-1"> <a id="syringe" className="btn btn-primary" onClick={this.onNewButtonClick} >New</a> </div> </div> <div className="row"> <div className="col-md-12"> <FormGroup validationState={this.state.errors.ambient_air_temperature ? 'error' : null}> <FormControl type="text" placeholder="Ambient Air Temperature" name="ambient_air_temperature" value={this.state.ambient_air_temperature} data-type="float" /> <HelpBlock className="warning">{this.state.errors.ambient_air_temperature}</HelpBlock> <FormControl.Feedback /> </FormGroup> </div> </div> <fieldset className="scheduler-border"> <legend className="scheduler-border">Choose test type *</legend> <div className="maxwidth"> <Radio name="test_type_id" value="1" required checked={this.state.test_type_id == 1}> Fluid Profile </Radio> <Radio name="test_type_id" value="2" required checked={this.state.test_type_id == 2}> Electrical Profile </Radio> </div> </fieldset> <div className="row"> <div className="col-md-12"> <Button bsStyle="success" type="submit" className="pull-right" >Save</Button> <Button bsStyle="danger" className="pull-right margin-right-xs" >Cancel</Button> </div> </div> </div> </div> </Panel> </form> <Modal show={this.state.showElectroProfileForm}> <ElectricalProfileForm data={this.state} handleClose={this.closeElectricalProfileForm}/> </Modal> <Modal show={this.state.showFluidProfileForm}> <FluidProfileForm testResultId={this.state.id} equipmentId={this.state.equipment_id} campaignId={this.state.campaign_id} fluidProfileId={this.state.fluid_profile_id} handleClose={this.closeFluidProfileForm}/> </Modal> <Modal show={this.state.showNewLabForm}> <Modal.Header> <Modal.Title>New Laboratory Profile</Modal.Title> </Modal.Header> <Modal.Body> <NewLabForm handleClose={this.closeNewLabForm} onCreate={this.onLabCreate} /> </Modal.Body> </Modal> <Modal show={this.state.showNewContractForm}> <Modal.Header> <Modal.Title>New Contract</Modal.Title> </Modal.Header> <Modal.Body> <NewContractForm onCreate={this.onContractCreate} handleClose={this.closeNewContractForm}/> </Modal.Body> </Modal> <Modal show={this.state.showNewMaterialForm}> <Modal.Header> <Modal.Title>New Material Profile</Modal.Title> </Modal.Header> <Modal.Body> <NewMaterialForm handleClose={this.closeNewMaterialForm} onCreate={this.onMaterialCreate}/> </Modal.Body> </Modal> <Modal show={this.state.showNewFluidForm}> <Modal.Header> <Modal.Title>New Fluid Profile</Modal.Title> </Modal.Header> <Modal.Body> <NewFluidForm handleClose={this.closeNewFluidForm} onCreate={this.onFluidTypeCreate}/> </Modal.Body> </Modal> <Modal show={this.state.showNewUserForm}> <Modal.Header> <Modal.Title>New User Profile</Modal.Title> </Modal.Header> <Modal.Body> <NewUserForm data={this.props.data} handleClose={this.closeNewUserForm} onCreate={this.onPerformerCreate} /> </Modal.Body> </Modal> <Modal show={this.state.showNewSyringeForm}> <Modal.Header> <Modal.Title>New Syringe</Modal.Title> </Modal.Header> <Modal.Body> <NewSyringeForm handleClose={this.closeNewSyringeForm} onCreate={this.onSyringeCreate} /> </Modal.Body> </Modal> </div> : null ); } }); export default NewTestForm;
src/ListButton.js
PythEch/ruc-scheduler
import React, { Component } from 'react'; import { observer } from 'mobx-react'; import { observable, computed, action } from 'mobx'; import store from './Store'; import ReactDOM from 'react-dom'; import { TransitionMotion, spring, presets } from 'react-motion'; import { UnmountClosed } from 'react-collapse'; let globalTop = 0; let globalMarginTop = 0; class ListButton extends Component { @observable height = 61; ref = null; render() { return ( <li ref={ this._setRef } className={ this.getClassName() } style={ { top: this.getTop()} } onClick={ this.onClick.bind(this) } > { this.props.text } </li> ); } getTop() { // FIXME: REALLY BAD CODE, FIX MUTATIONS PROPERLY if (this.isActive()) { this.ref.parentNode.style.paddingBottom = (5.0 + this.height / 2.0) + 'px'; } if (this.props.index === 0) globalTop = 0; if (this.isHidden()) return globalTop; let ret = globalTop; globalTop += this.height; return ret; } _setRef = (ref) => { if (!ref) return; //if (this.isHidden()) return; this.height = ref.offsetHeight; this.ref = ref; }; _getSelectedIndex() { return store[this.indexProperty]; } _setSelectedIndex(val) { if (val === -1) { globalMarginTop -= this.height; } else { globalMarginTop += this.height; } store[this.indexProperty] = val; } onClick() { let newIndex = this.isActive() ? - 1 : this.props.index; this._setSelectedIndex(newIndex); }; isActive() { return this._getSelectedIndex() === this.props.index; } isHidden() { return this._getSelectedIndex() !== -1 && !this.isActive(); } getClassName() { let className = this.className; if (this.isActive()) className += ' active'; else if (this.isHidden()) className += ' hidden'; return className; } } @observer class SelectedCourseListView extends Component { render() { let shouldShowTooltip = store.selectedCourses.filter(x => !x.isOpened).length === store.selectedCourses.length; return ( <ul className='selected-courses-list'> <UnmountClosed isOpened={ shouldShowTooltip } springConfig={presets.wobbly} forceInitialAnimation={ true } key={ "course-tooltip" }> <li className='course-tooltip'>Choose the courses you're attending from the menu below...</li> </UnmountClosed> { store.selectedCourses.map((course, index) => { return ( <UnmountClosed isOpened={ !!course.isOpened } springConfig={presets.wobbly} forceInitialAnimation={ true } key={ course.url }> <SelectedCourseButton course={course} /> </UnmountClosed> ); }) } </ul> ); } } @observer class SelectedCourseButton extends Component { render() { return ( <li className="course" onClick={ this.onClick }> { this.props.course.name } </li> ); } onClick = () => { this.props.course.isOpened = false; /* FIXME: hack to trigger mobx observable */ let temp = store.selectedCourses; store.selectedCourses = []; store.selectedCourses = temp; }; componentWillUnmount() { store.removeCourse(this.props.course); } } @observer class UnselectedCourseButton extends ListButton { isHidden() { for (let c of store.selectedCourses) { if (c.url === this.props.course.url) { return c.isOpened; } } return false; } isActive() { return false; } onClick() { store.addCourse(this.props.course) }; } export { ListButton, SelectedCourseListView, UnselectedCourseButton };
src/App.js
ashwinath/personal-website-2.0
import React, { Component } from 'react'; import './App.css'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import SideBar from './Pages/SideBar'; import About from './Pages/About'; import Portfolio from './Pages/Portfolio'; import Experience from './Pages/Experience'; import LandingPage from './Pages/LandingPage'; import Contact from './Pages/Contact'; import Workflow from './Pages/Workflow'; import NotFound from './Pages/NotFound'; class App extends Component { render() { return ( <Router> <div id="router"> <SideBar/> <Switch> <Route exact path="/" component={LandingPage}/> <Route exact path="/Home" component={LandingPage}/> <Route exact path="/About" component={About}/> <Route exact path="/Portfolio" component={Portfolio}/> <Route exact path="/Experience" component={Experience}/> <Route exact path="/Contact" component={Contact}/> <Route exact path="/Workflow" component={Workflow}/> <Route component={NotFound}/> </Switch> </div> </Router> ); } } export default App;
demo/containers/buttons.js
nbonamy/react-native-app-components
import React, { Component } from 'react'; import { StyleSheet, Alert, ScrollView, View, Text } from 'react-native'; import { theme, Button, SlideButton } from 'react-native-app-components'; export default class Buttons extends Component { constructor(props) { super(props); } render() { return ( <ScrollView style={{paddingBottom: 32, paddingLeft: 16, paddingRight: 16}}> <View style={{flexDirection: 'column'}}> <Text style={styles.title}>SLIDE BUTTON</Text> <SlideButton onUnlock={() => this.onUnlock()} label="Scroll to unlock" ref={(ref) => this.slide = ref}/> </View> <View style={{flexDirection: 'column'}}> <Text style={styles.title}>BUTTONS</Text> <View style={{flexDirection: 'row', flexWrap: 'wrap'}}> <Button primary style={styles.button} onPress={() => this.onButton()}>{'Primary'}</Button> <Button info style={styles.button} onPress={() => this.onButton()}>{'Info'}</Button> <Button success style={styles.button} onPress={() => this.onButton()}>{'Success'}</Button> <Button warning style={styles.button} onPress={() => this.onButton()}>{'Warning'}</Button> <Button danger style={styles.button} onPress={() => this.onButton()}>{'Danger'}</Button> <Button backgroundColor='#000000' textColor='#FFFFFF' style={styles.button} onPress={() => this.onButton()}>Custom</Button> </View> </View> </ScrollView> ); } onButton() { Alert.alert('Button pressed'); } onUnlock() { Alert.alert('Congratulations!'); this.slide.reset(); } } const styles = StyleSheet.create({ title: { fontSize: 18, marginTop: 32, marginBottom: 16, color: theme.colors.dark, }, button: { margin: 8, }, });
DatePicker.js
WaffleStudios/react-native-json-form
import React from 'react'; import { DatePickerAndroid, DatePickerIOS, Platform, ScrollView, Text, TimePickerAndroid, TouchableOpacity, View } from 'react-native'; import styles from './FormStyles'; export default class JSONForm extends React.Component { static defaultProps = { mode: "date" } constructor(props) { super(props); this.state = {} } // Android and iOS do date picker handling differently. iOS displays the picker inline, and Android has a separate popup to handle it. // In an attempt to unify the functionality, I use a button that, when pressed, displays the date picker. // On Android, it's handled by the window. // On iOS, I have added "submit" and "clear" buttons to set and remove the dates. datePicker() { if(Platform.OS === 'ios') { if(!this.state.showPicker) { return( <View style={styles.indent}> <TouchableOpacity onPress={() => this.setState({showPicker: true})}> <Text>{this.props.date != undefined ? this.formattedDate() : "Add Date"}</Text> </TouchableOpacity> </View> ); } else { return( <View> <DatePickerIOS date={this.props.date != undefined ? this.props.date : new Date()} mode={this.props.mode} onDateChange={(date) => this.props.setDate(this.formatDate(date, "datetime")) } /> <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between', }}> <TouchableOpacity onPress={() => { this.props.setDate(undefined); this.setState({showPicker: false}) }}> <Text style={{color: "red"}}>Clear</Text> </TouchableOpacity> <TouchableOpacity onPress={() => this.setState({showPicker: false})}> <Text>Submit</Text> </TouchableOpacity> </View> </View> ); } } else { return( <View style={styles.indent}> <TouchableOpacity onPress={this.showPicker.bind(this, {date: this.props.date})}> <Text>{this.props.date != undefined ? this.formattedDate() : "Add Date"}</Text> </TouchableOpacity> </View> ); } } // Date.toLocaleDateString() causes issues past the year 2038 (https://en.wikipedia.org/wiki/Year_2038_problem ?) // This formats a date string in a way that is compatible to the year 9999. // By that point, I am dead, and this code is someone else's problem formatDate(date, mode) { // console.log(date); if(date === undefined) { date = new Date(); } var month = date.getMonth() + 1; var day = date.getDate(); var year = date.getFullYear(); var formattedDate = month + '/' + day + '/' + year; var hours = date.getHours(); var minutes = date.getMinutes(); var amPm = hours < 12 ? "AM" : "PM"; if(hours == 0) { hours = 12; } else if(hours > 12) { hours -= 12; } if(minutes < 10) { minutes = "0" + minutes; } var formattedTime = hours + ':' + minutes + ' ' + amPm; // console.log(formattedDate); // console.log(formattedTime); if(mode == "date") { return formattedDate; } else if(mode == "time") { return formattedTime; } else { return formattedDate + " " + formattedTime; } } formattedDate() { return this.formatDate(this.props.date, this.props.mode) } // Android only. Handles date picking. Selecting a date, then hitting "OK" will save the date, selecting "Cancel" will clear the date. showPicker(options) { if(["date", "datetime"].includes(this.props.mode)) { this.showDatePicker(options); } else { this.showTimePicker(options); } } showDatePicker = async (options) => { if(["date", "datetime"].includes(this.props.mode)) { try { const {action, year, month, day} = await DatePickerAndroid.open(options); if (action === DatePickerAndroid.dismissedAction) { this.props.setDate(undefined); } else { var date = new Date(year, month, day); if(this.props.mode == "date") { this.props.setDate(date); } else { this.showTimePicker({date: date}); } } } catch ({code, message}) { console.warn('Cannot Open Date Picker: ', message); } } } showTimePicker = async (options) => { try { var date = options.date; if(!date) { date = new Date(); } const {action, hour, minute} = await TimePickerAndroid.open({ hour: date.getHours(), minute: date.getMinutes(), is24Hour: false }); if (action == TimePickerAndroid.dismissedAction) { if(this.props.mode == "time") { this.props.setDate(undefined) } else { this.showDatePicker({date: date}) } } else { date.setHours(hour); date.setMinutes(minute); date.setSeconds(0); date.setMilliseconds(0); this.props.setDate(this.formatDate(date, "datetime")); } } catch ({code, message}) { console.warn('Cannot Open Time Picker: ', message); }; } render() { return this.datePicker(); } }
Week04-UseSiteTools/client/src/App.js
bmeansjd/ISIT320_means2017
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h1 className="App-title">Welcome to React</h1> </header> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); } } export default App;
src/hav/apps/theme/src/mdx/components/index.js
whav/hav
import React from 'react'; import Media from "./media"; import Folder from "./folder"; import Wrapper from "./Wrapper"; const components = { HAVMedia: (props) => <Media {...props} />, HAVFolder: (props) => <Folder {...props} />, Media: (props) => <Media {...props} />, wrapper: (props) => <Wrapper {...props} /> }; export { components };
src/containers/app/index.js
chuckharmston/testpilot-contribute
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { Route } from 'react-router'; import { ConnectedRouter } from 'react-router-redux'; import Footer from '../../components/footer'; import { HomeNav } from '../../components/header'; import ScrollToTop from '../../components/scroll-to-top'; import { docs } from '../../config.json'; import Home from '../home'; import Tasks from '../tasks'; import './index.css'; export default class App extends Component { static propTypes = { repos: PropTypes.arrayOf(PropTypes.object) }; static defaultProps = { repos: [] }; renderDocsRoutes() { return ( <Route path="/docs" render={() => ( <div> {docs.map((doc, index) => { const Component = require(`../docs-page/content/${doc.slug}`) .default; const path = `/docs/${doc.slug}/`; return ( <Route exact path={path} component={Component} key={index} /> ); })} </div> )} /> ); } getNav(pathname) { const navMap = { '/': HomeNav }; return navMap.hasOwnProperty(pathname) ? navMap[pathname] : null; } render() { const { history } = this.props; return ( <ConnectedRouter history={history}> <ScrollToTop location={history.location}> <div className="app"> <Route exact path="/" component={Home} /> <Route exact path="/tasks/" component={Tasks} /> {this.renderDocsRoutes()} <Footer /> </div> </ScrollToTop> </ConnectedRouter> ); } }
packages/website/storybook/axis-story.js
uber-common/react-vis
/* eslint-env node */ import React from 'react'; import {storiesOf} from '@storybook/react'; import {withKnobs, number, select} from '@storybook/addon-knobs/react'; import {LineSeries, VerticalBarSeries, XAxis, YAxis} from 'react-vis'; import {generateLinearData, getTime, getWord} from './storybook-data.js'; import {SimpleChartWrapperNoAxes} from './storybook-utils'; storiesOf('Axes and scales/Axis Formatting/Base', module) .addDecorator(withKnobs) .addWithJSX('Axis orientation', () => { const XAxisOrientation = select( 'XAxis.orientation', {bottom: 'bottom', top: 'top'}, 'bottom', 'XAxis' ); const YAxisOrientation = select( 'YAxis.orientation', {left: 'left', right: 'right'}, 'left', 'YAxis' ); return ( <SimpleChartWrapperNoAxes margin={{ ...(XAxisOrientation === 'top' ? {bottom: 20, top: 40} : {}), ...(YAxisOrientation === 'right' ? {left: 10, right: 40} : {}) }} > <XAxis orientation={XAxisOrientation} /> <YAxis orientation={YAxisOrientation} /> <LineSeries data={generateLinearData({key: 'line1'})} /> </SimpleChartWrapperNoAxes> ); }) .addWithJSX('Axis titles', () => { const XAxisPosition = select( 'XAxis.position', {start: 'start', middle: 'middle', end: 'end'}, 'end', 'XAxis' ); const YAxisPosition = select( 'YAxis.position', {start: 'start', middle: 'middle', end: 'end'}, 'end', 'YAxis' ); return ( <SimpleChartWrapperNoAxes> <XAxis title="x-axis" position={XAxisPosition} /> <YAxis title="y-axis" position={YAxisPosition} /> <LineSeries data={generateLinearData({key: 'line1'})} /> </SimpleChartWrapperNoAxes> ); }) .addWithJSX('Tick total', () => { const xTickTotal = number( 'XAxis.tickTotal', 10, {max: 20, min: 0, range: true}, 'XAxis' ); const yTickTotal = number( 'YAxis.tickTotal', 10, {max: 20, min: 0, range: true}, 'YAxis' ); return ( <SimpleChartWrapperNoAxes> <XAxis tickTotal={xTickTotal} /> <YAxis tickTotal={yTickTotal} /> <LineSeries data={generateLinearData({key: 'line1'})} /> </SimpleChartWrapperNoAxes> ); }) .addWithJSX('Tick Size', () => { const xTickSize = number( 'XAxis.tickSize', 6, {max: 10, min: 0, range: true}, 'XAxis' ); const yTickSize = number( 'YAxis.tickSize', 6, {max: 10, min: 0, range: true}, 'YAxis' ); return ( <SimpleChartWrapperNoAxes noHorizontalGridLines noVerticalGridLines> <XAxis tickSize={xTickSize} /> <YAxis tickSize={yTickSize} /> <LineSeries data={generateLinearData({key: 'line1'})} /> </SimpleChartWrapperNoAxes> ); }) .addWithJSX('Tick Size (Inner)', () => { const xTickSize = number( 'XAxis.tickSizeInner', 6, {max: 10, min: 0, range: true}, 'XAxis' ); const yTickSize = number( 'YAxis.tickSizeInner', 6, {max: 10, min: 0, range: true}, 'YAxis' ); return ( <SimpleChartWrapperNoAxes noHorizontalGridLines noVerticalGridLines> <XAxis tickSizeInner={xTickSize} /> <YAxis tickSizeInner={yTickSize} /> <LineSeries data={generateLinearData({key: 'line1'})} /> </SimpleChartWrapperNoAxes> ); }) .addWithJSX('Tick Size (Outer)', () => { const xTickSize = number( 'XAxis.tickSizeOuter', 6, {max: 10, min: 0, range: true}, 'XAxis' ); const yTickSize = number( 'YAxis.tickSizeOuter', 6, {max: 10, min: 0, range: true}, 'YAxis' ); return ( <SimpleChartWrapperNoAxes noHorizontalGridLines noVerticalGridLines> <XAxis tickSizeOuter={xTickSize} /> <YAxis tickSizeOuter={yTickSize} /> <LineSeries data={generateLinearData({key: 'line1'})} /> </SimpleChartWrapperNoAxes> ); }) .addWithJSX('Tick orientation', () => { const tickLabelAngle = number( 'tickLabelAngle', 0, {max: 90, min: -90, range: true}, 'XAxis' ); return ( <SimpleChartWrapperNoAxes margin={{bottom: 80}}> <XAxis tickFormat={d => new Date(d).toLocaleDateString()} tickLabelAngle={tickLabelAngle} /> <YAxis /> <LineSeries data={generateLinearData({ key: 'line-with-time', extraParams: [['x', getTime({})]] })} /> </SimpleChartWrapperNoAxes> ); }); storiesOf('Axes and scales/Scales', module) .addDecorator(withKnobs) .addWithJSX('time Scale', () => { return ( <SimpleChartWrapperNoAxes margin={{right: 20}}> <XAxis tickFormat={d => new Date(d).toLocaleDateString()} /> <YAxis /> <LineSeries data={generateLinearData({ key: 'line-with-time', extraParams: [['x', getTime({})]] })} /> </SimpleChartWrapperNoAxes> ); }) .addWithJSX('category scale', () => { const data = generateLinearData({ nbPoints: 8, changeRatio: 0.4, key: 'bar1' }); return ( <SimpleChartWrapperNoAxes xType="ordinal"> <XAxis /> <YAxis /> <VerticalBarSeries data={data} /> </SimpleChartWrapperNoAxes> ); }) .addWithJSX('ordinal scale', () => { const data = generateLinearData({ nbPoints: 8, changeRatio: 0.4, key: 'bar-with-words', extraParams: [['x', getWord({})]] }); return ( <SimpleChartWrapperNoAxes xType="ordinal"> <XAxis /> <YAxis /> <VerticalBarSeries data={data} /> </SimpleChartWrapperNoAxes> ); });
src/components/Ending/Ending.js
goldylucks/adamgoldman.me
// @flow import React from 'react' import Link from '../Link' import Avatar from '../Avatar' type Props = { nick?: string, } const Ending = ({ nick, ...restProps }: Props) => ( <section {...restProps} className='clearfix'> <Link to='/' className='avatar-with-text'> <Avatar alt={`Adam Goldman ${nick}`} /> </Link> <div className='avatar-text'> <Link to='/' style={{ color: 'inherit' }}> <strong>Adam {nick && `“${nick}”`} Goldman</strong> </Link> <p> <small>Relax, it&apos;s just life ...</small> </p> </div> </section> ) Ending.defaultProps = { nick: '' } export default Ending
src/components/Authorized/AuthorizedRoute.js
ascrutae/sky-walking-ui
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ import React from 'react'; import { Route, Redirect } from 'react-router-dom'; import Authorized from './Authorized'; class AuthorizedRoute extends React.Component { render() { const { component: Component, render, authority, redirectPath, ...rest } = this.props; return ( <Authorized authority={authority} noMatch={<Route {...rest} render={() => <Redirect to={{ pathname: redirectPath }} />} />} > <Route {...rest} render={props => (Component ? <Component {...props} /> : render(props))} /> </Authorized> ); } } export default AuthorizedRoute;
MyBlog/BaymaxBlogFrontEnd/modules/Collect.js
tyhtao1990/BaymaxHome
import React from 'react' export default React.createClass({ render() { return ( <div> <Grid> <Row className="show-grid"> <Col xs={2} md={4}> <ControlLabel>Search data</ControlLabel> <FormControl type="text" placeholder="Enter text"/> </Col> </Row> <br/> <Row> <Col xs={1} md={4} > <ControlLabel>type select</ControlLabel> <FormControl componentClass="select" placeholder="select"> <option value="select">hupu</option> <option value="other">other</option> </FormControl> </Col> </Row> </Grid> </div> ); } })
src/client/components/auth/Authenticated.js
josebalius/react-isomorphic-starter
import React from 'react'; import {connect} from 'react-redux'; import {Router} from 'react-router'; @connect(state => ({session: state.session})) class Authenticated extends React.Component { static contextTypes = { router: React.PropTypes.object }; constructor(props, context) { super(props, context); if(!props.session || !props.session.token) { if(process.browser) { context.router.transitionTo('login'); } else { Router.transitionTo('/login'); } } } componentWillReceiveProps(nextProps) { if(!nextProps.session.token) { this.context.router.transitionTo('login'); } } render() { return this.props.children; } } export default Authenticated;
assets/jqwidgets/demos/react/app/rangeselector/rangeselectorasafilter/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxRangeSelector from '../../../jqwidgets-react/react_jqxrangeselector.js'; import JqxGrid from '../../../jqwidgets-react/react_jqxgrid.js'; class App extends React.Component { componentDidMount() { // update filter on 'change' event. this.refs.myRangeSelector.on('change', (event) => { let range = event.args; let min = this.refs.myRangeSelector.min(); let max = this.refs.myRangeSelector.max(); min = new Date(min); max = new Date(max); if (range.from.getTime() == min.getTime() && range.to.getTime() == max.getTime()) { this.refs.myGrid.clearfilters(); } else { applyFilter(range.from, range.to); }; }); let applyFilter = (from, to) => { this.refs.myGrid.clearfilters(); let filtertype = 'datefilter'; let filtergroup = new $.jqx.filter(); let filter_or_operator = 0; let filtervalueFrom = from; let filterconditionFrom = 'GREATER_THAN_OR_EQUAL'; let filterFrom = filtergroup.createfilter(filtertype, filtervalueFrom, filterconditionFrom); filtergroup.addfilter(filter_or_operator, filterFrom); let filtervalueTo = to; let filterconditionTo = 'LESS_THAN_OR_EQUAL'; let filterTo = filtergroup.createfilter(filtertype, filtervalueTo, filterconditionTo); filtergroup.addfilter(filter_or_operator, filterTo); this.refs.myGrid.addfilter('year', filtergroup); this.refs.myGrid.applyfilters(); }; } render() { let source = { datatype: 'json', datafields: [ { name: 'discovery', type: 'string' }, { name: 'scientist', type: 'string' }, { name: 'year', type: 'date' } ], id: 'id', url: '../sampledata/discoveries.txt' }; let dataAdapter = new $.jqx.dataAdapter(source); let columns = [ { text: 'Discovery', columngroup: 'header', datafield: 'discovery', width: 250 }, { text: 'Scientist', columngroup: 'header', datafield: 'scientist', width: 210 }, { text: 'Year', columngroup: 'header', datafield: 'year', cellsformat: 'yyyy' } ] let columngroups = [ { text: 'Major scientific discoveries in the 19th century', align: 'center', name: 'header' } ]; return ( <div> <label style={{ fontSize: 13, fontFamily: 'Verdana' }}>Major scientific discoveries in selected period:</label> <JqxGrid ref='myGrid' style={{ marginTop: 10 }} width={850} height={300} source={dataAdapter} filterable={true} columns={columns} columngroups={columngroups} /> <br /> <label style={{ fontSize: 13, marginTop: 10, fontFamily: 'Verdana' }}>Select period:</label> <br /> <JqxRangeSelector ref='myRangeSelector' width={750} height={80} min={'January 01, 1800'} max={'January 01, 1900'} range={{ from: 10, to: 50 }} majorTicksInterval={{ years: 10 }} minorTicksInterval={'year'} labelsFormat={'yyyy'} markersFormat={'yyyy'} /> </div> ) } } ReactDOM.render(<App />, document.getElementById('app'));
app/changelog.js
mvasilkov/mvasilkov.ovh
import React from 'react' import Link from 'next/link' import { date } from './functions' const Line = ({ path, pubdate, title }) => ( <li> <Link href={`/${path}`}><a>{title}</a></Link> <span className="date"> {date(pubdate)}</span> </li> ) const Changelog = ({ changes, orderBy }) => ( <ul> {changes.map(ch => <Line key={ch.path} {...ch} pubdate={ch[orderBy]} />)} </ul> ) export default Changelog
daily-frontend/src/components/DataTable/DataTable.js
zooyalove/dailynote
import React, { Component } from 'react'; import classNames from 'classnames'; import styles from './DataTable.scss'; import DataList from 'components/DataList'; import Pager from 'components/Pager'; const cx = classNames.bind(styles); class DataTable extends Component { constructor(props) { super(props); this.state = { currentPage: 1, datas: ((props.datas.length > 0) ? props.datas : []) }; } componentWillReceiveProps(nextProps) { const { datas } = this.state; if (datas !== nextProps.datas) { this.setState({ currentPage: 1, datas: nextProps.datas }); } } handlePageClick = (page) => { this.setState({ currentPage: page }); } render() { const { handlePageClick, state: { currentPage, datas } } = this; const { countPerPage, displayPage, ordererView, animation, hide } = this.props; let datalist; let startIndex = 0; if (datas.length === 0) { datalist = []; } else { startIndex = datas.length - ((currentPage-1) * countPerPage); if (currentPage === 1) { if (datas.length <= countPerPage) { datalist = datas; } else { datalist = datas.slice(0, 10); } } else { const pageOffset = (currentPage-1) * countPerPage; datalist = datas.slice(pageOffset, (pageOffset + countPerPage)); } } return ( <div className={cx('data-table')}> <DataList startIndex={startIndex} datalist={datalist} ordererView={ordererView ? true : false} animation={animation ? true : false} hide={hide ? true : false} /> <Pager dataLength={datas.length} current={currentPage} countPerPage={countPerPage} displayPage={displayPage} hide={hide ? true : false} onPageClick={handlePageClick} /> </div> ); } } export default DataTable;
src/components/Navigation/Navigation.js
ACPK/react-starter-kit
/** * 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 cx from 'classnames'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Navigation.css'; import Link from '../Link'; class Navigation extends React.Component { render() { return ( <div className={s.root} role="navigation"> <Link className={s.link} to="/about"> About </Link> <Link className={s.link} to="/contact"> Contact </Link> <span className={s.spacer}> | </span> <Link className={s.link} to="/login"> Log in </Link> <span className={s.spacer}>or</span> <Link className={cx(s.link, s.highlight)} to="/register"> Sign up </Link> </div> ); } } export default withStyles(s)(Navigation);
app/javascript/mastodon/components/avatar.js
kazh98/social.arnip.org
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { autoPlayGif } from '../initial_state'; export default class Avatar extends React.PureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, size: PropTypes.number.isRequired, style: PropTypes.object, inline: PropTypes.bool, animate: PropTypes.bool, }; static defaultProps = { animate: autoPlayGif, size: 20, inline: false, }; state = { hovering: false, }; handleMouseEnter = () => { if (this.props.animate) return; this.setState({ hovering: true }); } handleMouseLeave = () => { if (this.props.animate) return; this.setState({ hovering: false }); } render () { const { account, size, animate, inline } = this.props; const { hovering } = this.state; const src = account.get('avatar'); const staticSrc = account.get('avatar_static'); let className = 'account__avatar'; if (inline) { className = className + ' account__avatar-inline'; } const style = { ...this.props.style, width: `${size}px`, height: `${size}px`, backgroundSize: `${size}px ${size}px`, }; if (hovering || animate) { style.backgroundImage = `url(${src})`; } else { style.backgroundImage = `url(${staticSrc})`; } return ( <div className={className} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} style={style} /> ); } }
app/src/containers/UserDetailsScreen.js
joshlevy89/the-book-thing
import React, { Component } from 'react'; import { connect } from 'react-redux'; import UserField from '../components/UserField'; import { retrieve_user_details } from '../actions' require('../../styles/UserDetailsScreen.scss') require('../../styles/index.scss') class UserDetailsScreen extends Component { componentDidMount() { const {dispatch} = this.props dispatch(retrieve_user_details()) } render() { const { user_details } = this.props const labels = ["Last Name","First Name","City","State"]; return ( <div style={{'marginLeft':'10px'}} className="mainLayout"> <h2>Profile</h2> <div> {labels.map(label=>{ return <UserField key={label} user_details={user_details} label={label}/> })} </div> </div> ) } } function mapStateToProps(state) { return { user_details: state.user.user_details } } UserDetailsScreen = connect( mapStateToProps )(UserDetailsScreen) export default UserDetailsScreen
client/src/components/search/searchBar/SearchBar.js
jonathanihm/freeCodeCamp
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { createSelector } from 'reselect'; import { SearchBox } from 'react-instantsearch-dom'; import { HotKeys, ObserveKeys } from 'react-hotkeys'; import { isEqual } from 'lodash'; import { isSearchDropdownEnabledSelector, isSearchBarFocusedSelector, toggleSearchDropdown, toggleSearchFocused, updateSearchQuery } from '../redux'; import SearchHits from './SearchHits'; import './searchbar-base.css'; import './searchbar.css'; const propTypes = { innerRef: PropTypes.object, isDropdownEnabled: PropTypes.bool, isSearchFocused: PropTypes.bool, toggleSearchDropdown: PropTypes.func.isRequired, toggleSearchFocused: PropTypes.func.isRequired, updateSearchQuery: PropTypes.func.isRequired }; const mapStateToProps = createSelector( isSearchDropdownEnabledSelector, isSearchBarFocusedSelector, (isDropdownEnabled, isSearchFocused) => ({ isDropdownEnabled, isSearchFocused }) ); const mapDispatchToProps = dispatch => bindActionCreators( { toggleSearchDropdown, toggleSearchFocused, updateSearchQuery }, dispatch ); const placeholder = 'Search 6,000+ tutorials'; export class SearchBar extends Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.handleSearch = this.handleSearch.bind(this); this.handleMouseEnter = this.handleMouseEnter.bind(this); this.handleMouseLeave = this.handleMouseLeave.bind(this); this.handleFocus = this.handleFocus.bind(this); this.handleHits = this.handleHits.bind(this); this.state = { index: -1, hits: [] }; } componentDidMount() { document.addEventListener('click', this.handleFocus); } componentWillUnmount() { document.removeEventListener('click', this.handleFocus); } handleChange() { const { isSearchFocused, toggleSearchFocused } = this.props; if (!isSearchFocused) { toggleSearchFocused(true); } this.setState({ index: -1 }); } handleFocus(e) { const { toggleSearchFocused } = this.props; const isSearchFocused = this.props.innerRef.current.contains(e.target); if (!isSearchFocused) { // Reset if user clicks outside of // search bar / closes dropdown this.setState({ index: -1 }); } return toggleSearchFocused(isSearchFocused); } handleSearch(e, query) { e.preventDefault(); const { toggleSearchDropdown, updateSearchQuery } = this.props; const { index, hits } = this.state; const selectedHit = hits[index]; // Disable the search dropdown toggleSearchDropdown(false); if (selectedHit) { // Redirect to hit / footer selected by arrow keys return window.location.assign(selectedHit.url); } else if (!query) { // Set query to value in search bar if enter is pressed query = e.currentTarget.children[0].value; } updateSearchQuery(query); // For Learn search results page // return navigate('/search'); // Temporary redirect to News search results page // when non-empty search input submitted and there // are hits besides the footer return query && hits.length > 1 ? window.location.assign( `https://www.freecodecamp.org/news/search/?query=${encodeURIComponent( query )}` ) : false; } handleMouseEnter(e) { e.persist(); const hoveredText = e.currentTarget.innerText; this.setState(({ hits }) => { const hitsTitles = hits.map(hit => hit.title); const hoveredIndex = hitsTitles.indexOf(hoveredText); return { index: hoveredIndex }; }); } handleMouseLeave() { this.setState({ index: -1 }); } handleHits(currHits) { const { hits } = this.state; if (!isEqual(hits, currHits)) { this.setState({ index: -1, hits: currHits }); } } keyMap = { INDEX_UP: ['up'], INDEX_DOWN: ['down'] }; keyHandlers = { INDEX_UP: e => { e.preventDefault(); this.setState(({ index, hits }) => ({ index: index === -1 ? hits.length - 1 : index - 1 })); }, INDEX_DOWN: e => { e.preventDefault(); this.setState(({ index, hits }) => ({ index: index === hits.length - 1 ? -1 : index + 1 })); } }; render() { const { isDropdownEnabled, isSearchFocused, innerRef } = this.props; const { index } = this.state; return ( <div className='fcc_searchBar' data-testid='fcc_searchBar' ref={innerRef}> <HotKeys handlers={this.keyHandlers} keyMap={this.keyMap}> <div className='fcc_search_wrapper'> <label className='fcc_sr_only' htmlFor='fcc_instantsearch'> Search </label> <ObserveKeys> <SearchBox focusShortcuts={[83, 191]} onChange={this.handleChange} onFocus={this.handleFocus} onSubmit={this.handleSearch} showLoadingIndicator={false} translations={{ placeholder }} /> </ObserveKeys> {isDropdownEnabled && isSearchFocused && ( <SearchHits handleHits={this.handleHits} handleMouseEnter={this.handleMouseEnter} handleMouseLeave={this.handleMouseLeave} selectedIndex={index} /> )} </div> </HotKeys> </div> ); } } SearchBar.displayName = 'SearchBar'; SearchBar.propTypes = propTypes; export default connect( mapStateToProps, mapDispatchToProps )(SearchBar);
packages/reactor-conference-app/src/schedule/ScheduleList.js
dbuhrman/extjs-reactor
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { List } from '@extjs/ext-react'; import { toggleFavorite } from './actions'; import { connect } from 'react-redux'; import days from '../util/days'; import { push } from 'react-router'; import { createTpl } from './EventTpl'; class ScheduleList extends Component { static propTypes = { dataStore: PropTypes.any.isRequired, onFavoriteClick: PropTypes.func, showTime: PropTypes.bool, flex: PropTypes.number, onSelect: PropTypes.func, eagerLoad: PropTypes.bool } constructor({ showTime }) { super(); this.itemTpl = createTpl({ getQuery: this.getQuery, showTime, onFavoriteClick: this.onFavoriteClick }); } getQuery = () => { return this.props.query; } onItemTap = (list, index, target, record) => { if (record) { self.location.hash = `/schedule/${record.id}`; } if (this.props.onSelect) { this.props.onSelect(record); } } onFavoriteClick = (data, e) => { this.props.dispatch(toggleFavorite(data.id)); } listRef = list => this.list = list; render() { const { event, query, dataStore, onSelect, pinHeaders, ...listProps } = this.props; return ( <List ref={this.listRef} hideMode="offsets" {...listProps} store={dataStore} selection={event} itemTpl={this.itemTpl} grouped rowLines itemCls={`app-list-item ${Ext.os.is.Phone ? 'x-item-no-select' : ''}`} cls="app-list" onItemTap={this.onItemTap} pinHeaders={pinHeaders} infinite={pinHeaders} variableHeights={pinHeaders} emptyText="No events found." /> ) } } const mapStateToProps = (state) => { return {}; } export default connect(mapStateToProps)(ScheduleList);
src/components/Layout/ImageBlock/index.js
jmikrut/keen-2017
import React from 'react'; import './ImageBlock.css'; const ImageBlock = (props) => { const className = props.className ? `image-block ${props.className}` : 'image-block'; return ( <div className={className}> {props.children} </div> ); } export default ImageBlock;
src/js/components/icons/base/Workshop.js
odedre/grommet-final
/** * @description Workshop SVG Icon. * @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon. * @property {string} colorIndex - The color identifier to use for the stroke color. * If not specified, this component will default to muiTheme.palette.textColor. * @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small. * @property {boolean} responsive - Allows you to redefine what the coordinates. * @example * <svg width="24" height="24" ><path d="M19,7 C19,7 14,14 6.5,14 C4.5,14 1,15 1,19 L1,23 L12,23 L12,19 C12,16.5 15,18 19,11 L17.5,9.5 M3,5 L3,2 L23,2 L23,16 L20,16 M11,1 L15,1 L15,3 L11,3 L11,1 Z M6.5,14 C8.43299662,14 10,12.4329966 10,10.5 C10,8.56700338 8.43299662,7 6.5,7 C4.56700338,7 3,8.56700338 3,10.5 C3,12.4329966 4.56700338,14 6.5,14 Z"/></svg> */ // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-workshop`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'workshop'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M19,7 C19,7 14,14 6.5,14 C4.5,14 1,15 1,19 L1,23 L12,23 L12,19 C12,16.5 15,18 19,11 L17.5,9.5 M3,5 L3,2 L23,2 L23,16 L20,16 M11,1 L15,1 L15,3 L11,3 L11,1 Z M6.5,14 C8.43299662,14 10,12.4329966 10,10.5 C10,8.56700338 8.43299662,7 6.5,7 C4.56700338,7 3,8.56700338 3,10.5 C3,12.4329966 4.56700338,14 6.5,14 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Workshop'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
components/Main.js
dkfann/cinesythesia
import React from 'react'; const Main = (props) => { return ( <div className="o-main-container"> { props.children } </div> ) }; export default Main;
aaf-enrollment/src/components/enrollment/method-authenticators/VoiceOTPMethod.js
MicroFocus/CX
import React from 'react'; import Authenticator from '../Authenticator'; import {generateFormChangeHandler} from '../../../utils/form-handler'; import TextField from '../../TextField'; import t from '../../../i18n/locale-keys'; class VoiceOTPMethod extends React.PureComponent { constructor(props) { super(props); const {isEnrolled, data} = props.template; let mobilePhone = ''; if (isEnrolled && data) { mobilePhone = data.mobilePhone || ''; } const initialOtherState = { defaultRecipient: null }; generateFormChangeHandler(this, { mobilePhone }, initialOtherState); this.props.getDefaultRecipient(this.props.template.methodId).then(({defaultRecipient}) => { this.setState({defaultRecipient}); }); } authenticationInfoChanged() { return this.state.dataDirty; } authenticationInfoSavable() { return !this.props.template.isEnrolled || this.authenticationInfoChanged(); } finishEnroll() { const {mobilePhone} = this.state.form; if (!mobilePhone.length && !this.state.defaultRecipient) { return Promise.reject(this.props.policies.voiceOTPMethod.data.enrollNoRecipientMsg); } const formData = mobilePhone ? { mobilePhone } : null; return this.props.doEnrollWithBeginProcess(formData) .then((response) => { if (response.status !== 'FAILED') { return Promise.resolve(response); } else { throw response.msg; } }); } renderOverrideElements() { return ( <React.Fragment> <div> <label>{t.phoneOverride()}</label> </div> <TextField disabled={this.props.readonlyMode} id="Mobile_Phone_Field" label={t.phoneOverrideLabel()} name="mobilePhone" onChange={this.handleChange} value={this.state.form.mobilePhone} /> </React.Fragment> ); } render() { const userMobilePhone = this.state.defaultRecipient || t.recipientUnknown(); const overrideElements = this.props.policies.voiceOTPMethod.data.allowOverrideRecipient ? this.renderOverrideElements() : null; return ( <Authenticator description={t.voiceOTPMethodDescription()} {...this.props} > <div> <label>{t.phonePosessive()}</label> <span className="directory-data">{userMobilePhone}</span> </div> <div> <label>{t.directoryFrom()}</label> </div> {overrideElements} </Authenticator> ); } } export default VoiceOTPMethod;
geonode/contrib/monitoring/frontend/src/components/atoms/map/index.js
timlinux/geonode
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Datamap from 'datamaps'; import * as d3 from 'd3'; import styles from './styles'; import actions from './actions'; const mapStateToProps = (state) => ({ countryData: state.mapData.response, interval: state.interval.interval, timestamp: state.interval.timestamp, }); @connect(mapStateToProps, actions) class WorldMap extends React.Component { static propTypes = { countryData: PropTypes.object, get: PropTypes.func.isRequired, interval: PropTypes.number, reset: PropTypes.func.isRequired, timestamp: PropTypes.instanceOf(Date), } constructor(props) { super(props); this.renderMap = ( { data, fills } = this.parse(this.props.countryData), ) => { while (this.d3Element.hasChildNodes()) { this.d3Element.removeChild(this.d3Element.lastChild); } const basicChoropleth = new Datamap({ data, fills, element: this.d3Element, width: '100%', height: '200', setProjection: (element) => { const x = element.offsetWidth / 2; const y = element.offsetHeight / 2 + 40; const projection = d3.geoMercator().scale(50).translate([x, y]); const path = d3.geoPath().projection(projection); return { path, projection }; }, geographyConfig: { popupTemplate: (geography, popupData) => { let popup = '<div class="hoverinfo"><strong>'; popup += `${geography.properties.name}: ${popupData.val}`; popup += '</strong></div>'; return popup; }, }, }); basicChoropleth.legend(); }; this.get = (interval = this.props.interval) => { this.props.get(interval); }; this.parseCountries = (data) => { if (!data || !data.data) { return undefined; } const realData = data.data.data[0]; if (realData.data.length === 0) { return undefined; } const result = {}; realData.data.forEach((country) => { result[country.label] = { val: country.val }; }); return result; }; this.calculateFills = (data) => { const defaultFill = '#ccc'; const fills = { defaultFill, 'no data': defaultFill, }; if (!data) { return { data, fills }; } const realCountries = {}; Object.keys(data).forEach((countryName) => { if (countryName.length === 3) { realCountries[countryName] = data[countryName]; realCountries[countryName].val = Number(data[countryName].val); } }); const max = Object.keys(realCountries).reduce((currentMax, countryName) => { const val = realCountries[countryName].val; return val > currentMax ? val : currentMax; }, 0); if (max === 0) { return { data, fills }; } const step = Math.floor(max / 5); let color = 7; const countryData = {}; if (step === 0) { const identifier = `0-${max}`; fills[identifier] = `#${color}${color}c`; Object.keys(realCountries).forEach((countryName) => { const newCountry = JSON.parse(JSON.stringify(realCountries[countryName])); newCountry.fillKey = identifier; countryData[countryName] = newCountry; }); } else { for (let multiplier = 0; multiplier < 4; ++multiplier) { const low = multiplier * step; const hi = (multiplier + 1) * step; const identifier = `${low}-${hi}`; fills[identifier] = `#${color}${color}c`; --color; } const highestLow = 4 * step; const identifier = `>${highestLow}`; fills[identifier] = `#${color}${color}c`; Object.keys(realCountries).forEach((countryName) => { const val = Number(realCountries[countryName].val); const newCountry = JSON.parse(JSON.stringify(realCountries[countryName])); for (let multiplier = 1; multiplier < 5; ++multiplier) { if (multiplier * step >= val) { const low = (multiplier - 1) * step; const hi = multiplier * step; newCountry.fillKey = `${low}-${hi}`; break; } } if (!newCountry.fillKey) { const low = 4 * step; newCountry.fillKey = `>${low}`; } countryData[countryName] = newCountry; }); } return { data: countryData, fills }; }; this.parse = (rawData) => { const { data, fills } = this.calculateFills( this.parseCountries(rawData), ); return { data, fills }; }; } componentWillMount() { this.get(); } componentDidMount() { this.renderMap(); } componentWillReceiveProps(nextProps) { if (nextProps) { if (nextProps.timestamp && nextProps.timestamp !== this.props.timestamp) { this.get(nextProps.interval); } } } componentDidUpdate() { this.renderMap(); } componentWillUnmount() { this.props.reset(); } render() { return ( <div> <h3>Number of requests</h3> <div style={styles.root} ref={(node) => {this.d3Element = node;}} /> </div> ); } } export default WorldMap;
packages/website/src/components/content/Article.js
mucsi96/w3c-webdriver
import React from 'react'; import Markdown from 'react-markdown'; import Heading from './Heading'; import Link from './Link'; import Code from './Code'; import Image from './Image'; import InlineCode from './InlineCode'; import Emoji from './Emoji'; import Paragraph from './Paragraph'; import Contributors from './Contributors'; import Debug from '../utils/Debug'; import BrowserStackLogo from './BrowserStackLogo'; import YouTubeVideo from './YouTubeVideo'; const EMOJI_MAP_REGEX = /<--EMOJI-MAP--(.*?)--EMOJI-MAP-->/; const Article = ({ markdown }) => { const emojiMap = JSON.parse(EMOJI_MAP_REGEX.exec(markdown)[1]); return ( <article> <Markdown escapeHtml={true} source={markdown.replace(EMOJI_MAP_REGEX, '')} renderers={{ heading: Heading, link: ({ href, children }) => { if (href === '#contributors') { return <Contributors />; } if (href === '#browserstack') { return <BrowserStackLogo />; } if (href === '#emoji') { return <Emoji svg={emojiMap[children[0].props.value]} />; } if (href.includes('www.youtube.com/embed')) { return <YouTubeVideo src={href} />; } return <Link href={href}>{children}</Link>; }, inlineCode: InlineCode, code: Code, image: Image, paragraph: Paragraph }} /> </article> ); }; export default Article;
docs/app/Examples/collections/Breadcrumb/Content/BreadcrumbExampleLink.js
ben174/Semantic-UI-React
import React from 'react' import { Breadcrumb } from 'semantic-ui-react' const BreadcrumbExampleLink = () => ( <Breadcrumb> <Breadcrumb.Section link>Home</Breadcrumb.Section> <Breadcrumb.Divider /> <Breadcrumb.Section link>Store</Breadcrumb.Section> <Breadcrumb.Divider icon='right angle' /> <Breadcrumb.Section active>Search for: <a href='#'>paper towels</a></Breadcrumb.Section> </Breadcrumb> ) export default BreadcrumbExampleLink
js/components/inputgroup/underline.js
YeisonGomez/RNAmanda
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { actions } from 'react-native-navigation-redux-helpers'; import { Container, Header, Title, Content, Button, Icon, Text, Body, Left, Right, IconNB, Item, Input, Form } from 'native-base'; import { Actions } from 'react-native-router-flux'; import styles from './styles'; const { popRoute, } = actions; class Underline extends Component { static propTypes = { popRoute: React.PropTypes.func, navigation: React.PropTypes.shape({ key: React.PropTypes.string, }), } popRoute() { this.props.popRoute(this.props.navigation.key); } render() { return ( <Container style={styles.container}> <Header> <Left> <Button transparent onPress={() => Actions.pop()}> <Icon name="arrow-back" /> </Button> </Left> <Body> <Title>Underline</Title> </Body> <Right /> </Header> <Content> <Form> <Item> <Input placeholder="Underline Textbox" /> </Item> </Form> </Content> </Container> ); } } function bindAction(dispatch) { return { popRoute: key => dispatch(popRoute(key)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(Underline);
app/app.js
Frizi/amciu
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ import 'babel-polyfill'; /* eslint-disable import/no-unresolved */ // Load the manifest.json file and the .htaccess file import '!file?name=[name].[ext]!./manifest.json'; import 'file?name=[name].[ext]!./.htaccess'; /* eslint-enable import/no-unresolved */ // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import LanguageProvider from 'containers/LanguageProvider'; import { GatewayProvider } from 'react-gateway'; import configureStore from './store'; // Import i18n messages import { translationMessages } from './i18n'; // Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder import 'sanitize.css/sanitize.css'; // Create redux store const initialState = {}; const store = configureStore(initialState); // Set up the router, wrapping all Routes in the App component import App from './containers/App'; const render = (translatedMessages) => { ReactDOM.render( <Provider store={store}> <LanguageProvider messages={translatedMessages}> <GatewayProvider> <App /> </GatewayProvider> </LanguageProvider> </Provider>, document.getElementById('app') ); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { (new Promise((resolve) => { resolve(System.import('intl')); })) .then(() => Promise.all([ System.import('intl/locale-data/jsonp/en.js'), ])) .then(() => render(translationMessages)) .catch((err) => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed import { install } from 'offline-plugin/runtime'; install();
src/routes/register/index.js
koistya/react-starter-kit
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 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 Register from './Register'; const title = 'New User Registration'; export default { path: '/register', action() { return { title, component: <Register title={title} />, }; }, };
src/svg-icons/hardware/devices-other.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareDevicesOther = (props) => ( <SvgIcon {...props}> <path d="M3 6h18V4H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h4v-2H3V6zm10 6H9v1.78c-.61.55-1 1.33-1 2.22s.39 1.67 1 2.22V20h4v-1.78c.61-.55 1-1.34 1-2.22s-.39-1.67-1-2.22V12zm-2 5.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM22 8h-6c-.5 0-1 .5-1 1v10c0 .5.5 1 1 1h6c.5 0 1-.5 1-1V9c0-.5-.5-1-1-1zm-1 10h-4v-8h4v8z"/> </SvgIcon> ); HardwareDevicesOther = pure(HardwareDevicesOther); HardwareDevicesOther.displayName = 'HardwareDevicesOther'; HardwareDevicesOther.muiName = 'SvgIcon'; export default HardwareDevicesOther;
app/javascript/mastodon/components/permalink.js
summoners-riftodon/mastodon
import React from 'react'; import PropTypes from 'prop-types'; export default class Permalink extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { className: PropTypes.string, href: PropTypes.string.isRequired, to: PropTypes.string.isRequired, children: PropTypes.node, onInterceptClick: PropTypes.func, }; handleClick = e => { if (this.props.onInterceptClick && this.props.onInterceptClick()) { e.preventDefault(); return; } if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); this.context.router.history.push(this.props.to); } } render () { const { href, children, className, onInterceptClick, ...other } = this.props; return ( <a target='_blank' href={href} onClick={this.handleClick} {...other} className={`permalink${className ? ' ' + className : ''}`}> {children} </a> ); } }
src/Messages.js
alaarmann/infracc
import React from 'react'; export default ({message, ...props}) => ( <div className="Messages" hidden={message === null}> <span> {message} </span> </div> )
src/components/UserWidget.js
chriswitko/idiomatic-redux-app
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { withRouter } from 'react-router'; import * as actions from '../actions'; import { getCurrentUser } from '../reducers'; import TodoList from '../components/TodoList'; import FetchError from '../components/FetchError'; import { loginUser, authorizeUser } from '../actions'; let createHandlers = function(dispatch) { let onClick = function() { dispatch(loginUser()) }; return { onClick, // other handlers }; } class UserWidget extends Component { constructor(props) { super(props); console.log('this.props.dispatch', this.props.dispatch) // this.handlers = createHandlers(this.props.dispatch); // this.myClick = loginUser() } fetchData() { const { filter, isLoggedIn } = this.props; // authorizeUser() } componentDidMount() { console.log('componentDidMount') // this.fetchData() // this.fetchData(); } componentDidUpdate(prevProps) { console.log('componentDidUpdate', prevProps) // this.fetchData() // if (this.props.filter !== prevProps.filter) { // this.fetchData(); // } // const { isLoggedInUser } = this.props; // isLoggedInUser = this.props.isLoggedIn } // login({ dispatch }) { // loginUser() // // dispatch(loginUser()); // // const { filter, fetchTodos } = this.props; // console.log('UserWidget:this.props', this) // } render() { const { myClick, myLogoutClick, user } = this.props; return ( <div> <p> {"("} {user.isLoggedIn} {")"} {user.isLoggedIn ? "Logged In" : "Not logged In"} {" "} <button type="button" onClick={user.isLoggedIn ? myLogoutClick : myClick} >{user.isLoggedIn ? "Log Out" : "Log In"} </button> </p> </div> ); } } const mapDispatchToProps = (dispatch) => { return { myClick: () => dispatch(actions.loginUser()), myLogoutClick: () => dispatch(actions.logoutUser()), }; }; const mapStateToProps = (state) => { return { user: getCurrentUser(state) }; }; UserWidget = connect( mapStateToProps, // actions mapDispatchToProps )(UserWidget); export default UserWidget; // import React from 'react'; // import { connect } from 'react-redux'; // import { loginUser } from '../actions'; // let UserWidget = ({ dispatch }) => { // let input; // return ( // <div> // <p> // Not logged In // {" "} // <button // type="button" // onClick={e => { // e.preventDefault(); // dispatch(loginUser()) // }} // >LogIn</button> // </p> // </div> // ); // }; // UserWidget = connect()(UserWidget); // export default UserWidget;
src/components/_archive/_archive/ResultsListItem.js
mgoodenough/estimator
'use strict'; /* * Module Definition * */ import React from 'react'; import { isEqual } from '../utils/index'; /* * Class Definition * */ class ResultsListItem extends React.Component { constructor(props) { super(props); this.onClick = props.onClick.bind(null, props.idx); } /* * componentDidUpdate * */ componentDidUpdate(prevProps, prevState) { const isSelectedEntityChanged = !isEqual(prevProps.selectedEntity, this.props.selectedEntity); isSelectedEntityChanged && this.toggle(); } /* * isSelected * */ isSelected() { return this.props.idx === this.props.selectedEntity } /* * toggleItem * */ toggle() { console.log(this.isSelected()); } /* * renderPhoneNumbers * */ renderPhoneNumbers(phones) { return ( <ul> {phones.map((phone, idx) => <p key={ idx }>{ phone.type }: <a href="{phone.telNumber}">{ phone.phoneNumber }</a></p>)} </ul> ) } /* * render * */ render() { const { item } = this.props; return ( <li onClick={ this.onClick }> <div className="row"> <div className="col-xs-3 distance"> { item.dist }<span>miles</span> </div> <div className="col-xs-9 details"> <a href="#"> <h3>{ item.title }</h3> {/*<p>{ item.address.address1}</p> { item.address.address2 != '' && <p>{ item.address.address2 }</p> } <p>{ item.address.city }, { item.address.state } { item.address.zip }</p>*/} </a> <div> {/*{ this.renderPhoneNumbers(item.phones) }*/} </div> </div> </div> </li> ) } } /* * Module Export * */ export default ResultsListItem;
src/shared/components/PortfolioPage.js
Grace951/grace951.github.io
import React from 'react'; import {Switch} from "react-router-dom"; import {RouteWithSubRoutes} from '../route/index'; function PortfolioPage({ routes }) { return ( <div> <Switch> {routes.map((route, i) => ( <RouteWithSubRoutes key={route.path} {...route} /> ))} </Switch> </div> ); } export default PortfolioPage;
app/components/Github/UserProfile.js
joshuar500/repository-notes
import React from 'react'; class UserProfile extends React.Component { render(){ console.log('BIO: ', this.props.bio); return ( <div> <h3>Profile</h3> {this.props.bio.avatar_url && <li className="list-group-item"> <img src={this.props.bio.avatar_url} className="img-rounded img-responsive"/></li>} {this.props.bio.name && <li className="list-group-item">Name: {this.props.bio.name}</li>} {this.props.bio.login && <li className="list-group-item">Username: {this.props.bio.login}</li>} {this.props.bio.email && <li className="list-group-item">Email: {this.props.bio.email}</li>} {this.props.bio.location && <li className="list-group-item">Location: {this.props.bio.location}</li>} {this.props.bio.company && <li className="list-group-item">Company: {this.props.bio.company}</li>} {this.props.bio.followers && <li className="list-group-item">Followers: {this.props.bio.followers}</li>} {this.props.bio.following && <li className="list-group-item">Following: {this.props.bio.following}</li>} {this.props.bio.following && <li className="list-group-item">Public Repos: {this.props.bio.public_repos}</li>} {this.props.bio.blog && <li className="list-group-item">Blog: <a href={this.props.bio.blog}> {this.props.bio.blog}</a></li>} </div> ) } } UserProfile.propTypes = { username: React.PropTypes.string.isRequired, bio: React.PropTypes.object.isRequired } export default UserProfile;
src/shared/components/ErrorModal.js
devteamreims/4me.react
// @flow import React, { Component } from 'react'; import { Card, CardActions, CardTitle, CardText, } from 'material-ui/Card'; const style = { wrapper: { width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', }, inside: { flexGrow: 0, minWidth: 400, }, }; class ErrorModal extends Component { props: { title?: string, children?: ?React.Element<*>, actions?: React.Element<*>, }; static defaultProps = { children: null, }; render() { const { title, children, actions, } = this.props; return ( <div style={style.wrapper}> <Card style={style.inside}> {title && <CardTitle title={title} /> } <CardText>{children}</CardText> {actions && <CardActions>{actions}</CardActions> } </Card> </div> ); } } export default ErrorModal;
examples/with-scoped-stylesheets-and-postcss/pages/index.js
nahue/next.js
import React from 'react' import Head from 'next/head' import {stylesheet, classNames} from './styles.css' export default () => ( <p className={classNames.paragraph}> <Head><style dangerouslySetInnerHTML={{__html: stylesheet}} /></Head> bazinga </p> )
packages/examples/src/knobs/index.js
diegomura/react-pdf
import React from 'react'; import { Document, Page, View, Text, StyleSheet } from '@react-pdf/renderer'; const styles = StyleSheet.create({ select: { height: '9%', alignItems: 'center', flexDirection: 'row', paddingHorizontal: '30px', }, bar: { flexGrow: 1, height: '10px', backgroundColor: 'gray', }, barMiddle: { width: '50%', height: '100%', backgroundColor: 'lightgray', margin: 'auto', }, knob: { alignItems: 'center', justifyContent: 'center', width: '20px', height: '20px', borderRadius: 10, borderWidth: 3, borderColor: 'orange', position: 'absolute', backgroundColor: 'white', fontSize: 8, top: -6, }, text: { fontSize: 10, }, }); const Knob = ({ value }) => ( <View style={[styles.knob, { left: `${value - 3}%` }]}> <Text style={{ fontSize: 8, marginTop: 4 }}>{value}</Text> </View> ); const Select = props => ( <View style={styles.select}> <Text style={[styles.text, { marginRight: '15px' }]}>0%</Text> <View style={styles.bar}> <View style={styles.barMiddle} /> <Knob {...props} /> </View> <Text style={[styles.text, { marginLeft: '15px' }]}>100%</Text> </View> ); export default () => ( <Document> <Page size="A5"> <Select value={0} /> <Select value={10} /> <Select value={20} /> <Select value={30} /> <Select value={40} /> <Select value={50} /> <Select value={60} /> <Select value={70} /> <Select value={80} /> <Select value={90} /> <Select value={100} /> </Page> </Document> );
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
basquith16/EtsyClone
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
src/containers/ReportGenerator.js
blaqbern/report-generator
import React from 'react' import { connect } from 'react-redux' import { fetchFolders } from '../redux/modules/folders' import Folders from '../components/Folders' import Spinner from '../components/Spinner' function ReportGenerator({ children, fetchError, fetchingFolders, handleFetchClick, activeFolders, }) { return ( <div> {fetchingFolders ? <Spinner fetching item={'folders'} /> : null } {fetchError ? <div>{fetchError}</div> : ( <div> <div style={{ float: 'left', borderRight: '1px solid gray' }}> <Folders listName={'Active Folders'} folders={activeFolders} /> </div> <div> {children} </div> </div> ) } <button onClick={handleFetchClick}>Get Recent Folders</button> </div> ) } const { array, bool, func, object } = React.PropTypes ReportGenerator.propTypes = { children: object, fetchError: bool, fetchingFolders: bool, handleFetchClick: func, activeFolders: array, } function mapStateToProps(state) { return { fetchError: state.folders.error, fetchingFolders: state.folders.isFetching, activeFolders: state.folders.list, } } function mapDispatchToProps(dispatch) { return { handleFetchClick: () => dispatch(fetchFolders('Blackburn')) } } export default connect( mapStateToProps, mapDispatchToProps )(ReportGenerator)
packages/material-ui-icons/src/BatteryCharging30.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v9.17h2L13 7v5.5h2l-1.07 2H17V5.33C17 4.6 16.4 4 15.67 4z" /><path d="M11 20v-5.5H7v6.17C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V14.5h-3.07L11 20z" /></g> , 'BatteryCharging30');
client/src/index.js
hellstad/hjem
import { Provider } from 'react-redux' import ReactDOM from 'react-dom' import React from 'react' import AppRouter from 'views/AppRouter' import store from 'store' import './styles/index.scss' import './index.html' ReactDOM.render( <Provider store={store}> <AppRouter /> </Provider>, document.getElementById('root') )
src/components/custom-components/Dialogs/ToPlayListDialog/ToPlayListDialog.js
ArtyomVolkov/music-search
import React from 'react'; // MU components import { Dialog, Tabs, Tab, FlatButton, Checkbox, Avatar } from 'material-ui'; import ActionDone from 'material-ui/svg-icons/action/done'; import ActionInput from 'material-ui/svg-icons/action/input'; import { List, ListItem } from 'material-ui/List'; // Components import IncludeTracks from './IncludeTracks/IncludeTracks'; import FormData from '../../FormData/FormData'; // Styles import './ToPlayListDialog.scss'; class ToPlayListDialog extends React.Component { constructor (props) { super(props); this.initDialogData(); } initDialogData () { this.dialog = { title: 'Add track to Playlist', style: { width: '500px' }, bodyStyle: { padding: 0 }, formData: {} }; this.styles = { list: { padding: 0 }, listItem: { padding: 0, border: '1px solid #dcdcdc' }, listItemInnerDiv: { padding: '18px 0 18px 65px' }, avatar: { borderRadius: 0, top: 1, left: 1 } }; // TODO: custom storage const playLists = window.localStorage.getItem('playlists'); this.playlists = playLists ? JSON.parse(playLists) : []; this.formData = [ { key: 'name', validation: [{ key: 'required', value: true, message: 'This value is required' }, { key: 'minLength', value: 3, message: 'Min length must be more then 2 symbols' }, { key: 'reservedNames', value: this.playlists.map((item) => item.name), message: 'Playlist with such name has already exists' }], type: 'textField', label: 'New play list name' }, { key: 'image', type: 'textField', label: 'Image URL' } ]; this.state = { loading: false, activeTab: this.playlists.length ? 'playlists' : 'add-new', checkedPlayLists: [], trackIds: this.props.data.tracks.map((track) => track.fileId), validForm: true }; } onAddTracks = () => { const { dialog, props, state } = this; const selectedTracks = props.data.tracks.filter((track) => { return state.trackIds.indexOf(track.fileId) !== -1; }); if (state.activeTab === 'add-new') { this.playlists.push(Object.assign(dialog.formData, { tracks: selectedTracks })); } if (state.activeTab === 'playlists') { this.playlists.map((list) => { if (state.checkedPlayLists.indexOf(list.name) === -1) { return; } selectedTracks.map((track) => { if (list.tracks.find((item) => track.mbid === item.mbid)) { return; } list.tracks.push(track); }); }); } // TODO: custom data storage window.localStorage.setItem('playlists', JSON.stringify(this.playlists)); props.onClose(); }; onCloseDialog = () => { this.props.onClose(); }; onChangeField = (key, value, formData) => { if (formData.valid) { this.dialog.formData = formData.fields; } this.setState({ validForm: formData.valid }); }; onTabChange = (value) => { this.setState({ activeTab: value }); }; onTogglePlaylist (name) { const { checkedPlayLists } = this.state; const indexPlayList = checkedPlayLists.indexOf(name); indexPlayList === -1 ? checkedPlayLists.push(name) : checkedPlayLists.splice(indexPlayList, 1); this.setState({ checkedPlayLists: checkedPlayLists }); } onChangeTracksNumber = (trackIds) => { this.setState({ trackIds: trackIds }); }; isDisabled () { const { checkedPlayLists, trackIds, activeTab, validForm } = this.state; if (activeTab === 'add-new') { return !validForm || !trackIds.length; } return !checkedPlayLists.length || !trackIds.length; } render () { const { dialog, state, styles } = this; const { data } = this.props; return ( <Dialog title={dialog.title} contentStyle={dialog.style} bodyStyle={dialog.bodyStyle} actions={[ <FlatButton label="Cancel" primary={false} onTouchTap={this.onCloseDialog} />, <FlatButton label="Proceed" disabled={this.isDisabled()} primary={true} onTouchTap={this.onAddTracks} /> ]} open={true} modal={false}> <div className="playlist-container"> <Tabs onChange={this.onTabChange} value={state.activeTab}> <Tab className={!this.playlists.length ? 'disabled' : ''} icon={<i className="fa fa-th-list"/>} label={'Add to PlayList'} value={'playlists'} > <div className="tab-content"> { !!this.playlists.length && <div> <div className="play-lists"> <List style={styles.list}> { this.playlists.map((item, index) => { return ( <div key={index} className="play-list-item"> <ListItem style={styles.listItem} innerDivStyle={styles.listItemInnerDiv} onTouchTap={this.onTogglePlaylist.bind(this, item.name)} leftAvatar={ <Avatar src={item.image} size={50} style={styles.avatar}/> } rightIcon={ <Checkbox checked={state.checkedPlayLists.indexOf(item.name) !== -1} checkedIcon={<ActionDone />} uncheckedIcon={<ActionInput />} /> } primaryText={<span>{item.name}</span>} /> </div> ) }) } </List> </div> </div> } </div> </Tab> <Tab icon={<i className="fa fa-plus-circle"/>} label={'Create new'} value={'add-new'}> <div className="tab-content"> <FormData data={this.formData} onChange={this.onChangeField} classNameForm="form"/> </div> </Tab> </Tabs> <IncludeTracks tracks={data.tracks} limit={true} onChange={this.onChangeTracksNumber} /> </div> </Dialog> ) } } export default ToPlayListDialog;
src/Table/components/TableRow.js
Pearson-Higher-Ed/compounds
import React from 'react'; import PropTypes from 'prop-types'; const TableRow = ({ children }) => { const selectedRow = () => { const tables = document.querySelectorAll('.pe-table--selectable'); for (let i=0; i<tables.length; i++) { let table = tables[i]; let tbody = table.getElementsByTagName('tbody')[0]; let trs = [].slice.call(tbody.getElementsByTagName('TR')); trs.forEach((tr) => { let input = tr.getElementsByTagName('INPUT')[0]; if (input && input.type === 'checkbox') { if (input.checked) { tr.classList.add('selected'); } else { tr.classList.remove('selected'); } } }); } } return ( <tr onClick={selectedRow}> {children} </tr> ) } export default TableRow; TableRow.propTypes = { children: PropTypes.node }
app/javascript/flavours/glitch/components/autosuggest_input.js
im-in-space/mastodon
import React from 'react'; import AutosuggestAccountContainer from 'flavours/glitch/features/compose/containers/autosuggest_account_container'; import AutosuggestEmoji from './autosuggest_emoji'; import AutosuggestHashtag from './autosuggest_hashtag'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import ImmutablePureComponent from 'react-immutable-pure-component'; import classNames from 'classnames'; const textAtCursorMatchesToken = (str, caretPosition, searchTokens) => { let word; let left = str.slice(0, caretPosition).search(/[^\s\u200B]+$/); let right = str.slice(caretPosition).search(/[\s\u200B]/); if (right < 0) { word = str.slice(left); } else { word = str.slice(left, right + caretPosition); } if (!word || word.trim().length < 3 || searchTokens.indexOf(word[0]) === -1) { return [null, null]; } word = word.trim().toLowerCase(); if (word.length > 0) { return [left, word]; } else { return [null, null]; } }; export default class AutosuggestInput extends ImmutablePureComponent { static propTypes = { value: PropTypes.string, suggestions: ImmutablePropTypes.list, disabled: PropTypes.bool, placeholder: PropTypes.string, onSuggestionSelected: PropTypes.func.isRequired, onSuggestionsClearRequested: PropTypes.func.isRequired, onSuggestionsFetchRequested: PropTypes.func.isRequired, onChange: PropTypes.func.isRequired, onKeyUp: PropTypes.func, onKeyDown: PropTypes.func, autoFocus: PropTypes.bool, className: PropTypes.string, id: PropTypes.string, searchTokens: PropTypes.arrayOf(PropTypes.string), maxLength: PropTypes.number, }; static defaultProps = { autoFocus: true, searchTokens: ['@', ':', '#'], }; state = { suggestionsHidden: true, focused: false, selectedSuggestion: 0, lastToken: null, tokenStart: 0, }; onChange = (e) => { const [ tokenStart, token ] = textAtCursorMatchesToken(e.target.value, e.target.selectionStart, this.props.searchTokens); if (token !== null && this.state.lastToken !== token) { this.setState({ lastToken: token, selectedSuggestion: 0, tokenStart }); this.props.onSuggestionsFetchRequested(token); } else if (token === null) { this.setState({ lastToken: null }); this.props.onSuggestionsClearRequested(); } this.props.onChange(e); } onKeyDown = (e) => { const { suggestions, disabled } = this.props; const { selectedSuggestion, suggestionsHidden } = this.state; if (disabled) { e.preventDefault(); return; } if (e.which === 229 || e.isComposing) { // Ignore key events during text composition // e.key may be a name of the physical key even in this case (e.x. Safari / Chrome on Mac) return; } switch(e.key) { case 'Escape': if (suggestions.size === 0 || suggestionsHidden) { document.querySelector('.ui').parentElement.focus(); } else { e.preventDefault(); this.setState({ suggestionsHidden: true }); } break; case 'ArrowDown': if (suggestions.size > 0 && !suggestionsHidden) { e.preventDefault(); this.setState({ selectedSuggestion: Math.min(selectedSuggestion + 1, suggestions.size - 1) }); } break; case 'ArrowUp': if (suggestions.size > 0 && !suggestionsHidden) { e.preventDefault(); this.setState({ selectedSuggestion: Math.max(selectedSuggestion - 1, 0) }); } break; case 'Enter': case 'Tab': // Select suggestion if (this.state.lastToken !== null && suggestions.size > 0 && !suggestionsHidden) { e.preventDefault(); e.stopPropagation(); this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestions.get(selectedSuggestion)); } break; } if (e.defaultPrevented || !this.props.onKeyDown) { return; } this.props.onKeyDown(e); } onBlur = () => { this.setState({ suggestionsHidden: true, focused: false }); } onFocus = () => { this.setState({ focused: true }); } onSuggestionClick = (e) => { const suggestion = this.props.suggestions.get(e.currentTarget.getAttribute('data-index')); e.preventDefault(); this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestion); this.input.focus(); } componentWillReceiveProps (nextProps) { if (nextProps.suggestions !== this.props.suggestions && nextProps.suggestions.size > 0 && this.state.suggestionsHidden && this.state.focused) { this.setState({ suggestionsHidden: false }); } } setInput = (c) => { this.input = c; } renderSuggestion = (suggestion, i) => { const { selectedSuggestion } = this.state; let inner, key; if (suggestion.type === 'emoji') { inner = <AutosuggestEmoji emoji={suggestion} />; key = suggestion.id; } else if (suggestion.type ==='hashtag') { inner = <AutosuggestHashtag tag={suggestion} />; key = suggestion.name; } else if (suggestion.type === 'account') { inner = <AutosuggestAccountContainer id={suggestion.id} />; key = suggestion.id; } return ( <div role='button' tabIndex='0' key={key} data-index={i} className={classNames('autosuggest-textarea__suggestions__item', { selected: i === selectedSuggestion })} onMouseDown={this.onSuggestionClick}> {inner} </div> ); } render () { const { value, suggestions, disabled, placeholder, onKeyUp, autoFocus, className, id, maxLength } = this.props; const { suggestionsHidden } = this.state; return ( <div className='autosuggest-input'> <label> <span style={{ display: 'none' }}>{placeholder}</span> <input type='text' ref={this.setInput} disabled={disabled} placeholder={placeholder} autoFocus={autoFocus} value={value} onChange={this.onChange} onKeyDown={this.onKeyDown} onKeyUp={onKeyUp} onFocus={this.onFocus} onBlur={this.onBlur} dir='auto' aria-autocomplete='list' id={id} className={className} maxLength={maxLength} /> </label> <div className={`autosuggest-textarea__suggestions ${suggestionsHidden || suggestions.isEmpty() ? '' : 'autosuggest-textarea__suggestions--visible'}`}> {suggestions.map(this.renderSuggestion)} </div> </div> ); } }
benchmarks/src/implementations/react-fela/View.js
rofrischmann/fela
/* eslint-disable react/prop-types */ import React from 'react' import { useFela } from 'react-fela' const style = () => ({ alignItems: 'stretch', borderWidth: 0, borderStyle: 'solid', boxSizing: 'border-box', display: 'flex', flexBasis: 'auto', flexDirection: 'column', flexShrink: 0, margin: 0, padding: 0, position: 'relative', // fix flexbox bugs minHeight: 0, minWidth: 0, }) const View = ({ children }) => { const { css } = useFela() return <div className={css(style)}>{children}</div> } export default View
app/components/resources/owiLinks.js
nypl-registry/browse
import React from 'react' import { Link } from 'react-router' const OWILinks = React.createClass({ render () { // var id = this.props.id var related = this.props.item.getRelated('owi').map((item) => { var url = `/resources/${item.id}` if (item.dateStart && item.title) { return <Link to={url}> ({item.dateStart}) {item.firstTitle()} </Link> } else if (item.title) { return <Link to={url}> {item.firstTitle()} </Link> } }) return ( <div className='resource-owi-box'> <ul> <lh><b>Related Editions</b></lh> {related.map((el, i) => <li key={i}>{el}</li>)} </ul> </div> ) } }) export default OWILinks
example/examples/LiteMapView.js
azt3k/react-native-maps
import React from 'react'; import { StyleSheet, Dimensions, ScrollView, } from 'react-native'; import MapView from 'react-native-maps'; const { width, height } = Dimensions.get('window'); const ASPECT_RATIO = width / height; const LATITUDE = 37.78825; const LONGITUDE = -122.4324; const LATITUDE_DELTA = 0.0922; const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; const SAMPLE_REGION = { latitude: LATITUDE, longitude: LONGITUDE, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA, }; class LiteMapView extends React.Component { render() { const maps = []; for (let i = 0; i < 10; i++) { maps.push( <MapView liteMode key={`map_${i}`} style={styles.map} initialRegion={SAMPLE_REGION} /> ); } return ( <ScrollView style={StyleSheet.absoluteFillObject}> {maps} </ScrollView> ); } } const styles = StyleSheet.create({ map: { height: 200, marginVertical: 50, }, }); module.exports = LiteMapView;
webapp/src/app/planning/containers/PlanContainer.js
cpollet/itinerants
import React from 'react'; import {connect} from 'react-redux'; import moment from 'moment'; import {push} from 'react-router-redux'; import Planning from '../screens/Planning'; import {fetchPlanProposal, savePlan, toggleSelection} from '../actions'; import Spinner from '../../../widgets/Spinner'; class PlanContainer extends React.Component { render() { return ( <div> {this.props.ready || <Spinner/> } {this.props.ready && <Planning {...this.props}/>} </div> ); } componentDidMount() { this.props.request(this.props.eventIds); } } PlanContainer.defaultProps = { ready: false, }; PlanContainer.propTypes = { request: React.PropTypes.func.isRequired, eventIds: React.PropTypes.array.isRequired, ready: React.PropTypes.bool.isRequired, }; function mapStateToProps(state) { function attendancesCount(proposals, person) { return proposals.attendees[person].pastAttendancesCount + proposals.events.filter(e => e.selectedPeople.indexOf(person) > -1).length; } return { eventIds: state.app.planning.eventsToPlan, proposal: ((proposals) => proposals.events.map(event => ({ eventId: event.eventId, eventName: event.name, eventSize: event.eventSize, dateTime: moment(event.dateTime), selectedPeople: event.selectedPeople, savedAttendances: event.savedAttendances, availablePeople: event.availablePeople.map(p => ({ personId: p, name: proposals.attendees[p].name, attendancesCount: attendancesCount(proposals, p), ratio: attendancesCount(proposals, p) / (proposals.pastEventsCount + proposals.events.length), targetRatio: proposals.attendees[p].targetRatio, })).sort((p1, p2) => (p1.name > p2.name)) })))(state.app.planning.proposal).sort((e1, e2) => (e1.dateTime > e2.dateTime)), saving: state.app.planning.sync.pending, ready: state.app.planning.sync.ready, }; } function mapDispatchToProps(dispatch) { return { request: (eventIds) => dispatch(fetchPlanProposal(eventIds)), back: () => dispatch(push('/future')), save: () => dispatch(savePlan()), toggleSelection: (eventId, personId) => dispatch(toggleSelection(eventId, personId)) }; } export default connect(mapStateToProps, mapDispatchToProps)(PlanContainer);
src/components/Page/Page.js
bmatthews/haze-lea
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Page.css'; class Page extends React.Component { static propTypes = { title: PropTypes.string.isRequired, html: PropTypes.string.isRequired, }; render() { const { title, html } = this.props; return ( <div className={s.root}> <div className={s.container}> <h1> {title} </h1> <div // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: html }} /> </div> </div> ); } } export default withStyles(s)(Page);
src/Parser/Monk/Brewmaster/CHANGELOG.js
hasseboulen/WoWAnalyzer
import React from 'react'; import { WOPR, emallson } from 'CONTRIBUTORS'; import Wrapper from 'common/Wrapper'; import ITEMS from 'common/ITEMS'; import ItemLink from 'common/ItemLink'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; export default [ { date: new Date('2018-01-29'), changes: 'Added plot of damage in Stagger pool over time.', contributors: [emallson], }, { date: new Date('2018-01-27'), changes: <Wrapper>Added statistic for <SpellLink id={SPELLS.MASTERY_ELUSIVE_BRAWLER.id} icon /> effectiveness</Wrapper>, contributors: [emallson], }, { date: new Date('2018-01-22'), changes: 'Added \'Damage Taken by Ability\' table.', contributors: [emallson], }, { date: new Date('2018-01-18'), changes: 'Added High Tolerance haste statistic & changed Brew CDR to use average haste to determine target CDR value.', contributors: [emallson], }, { date: new Date('2018-01-12'), changes: <Wrapper>Added <SpellLink id={SPELLS.PURIFYING_BREW.id} /> statistic.</Wrapper>, contributors: [emallson], }, { date: new Date('2018-01-02'), changes: 'Added brew cooldown reduction tracking.', contributors: [emallson], }, { date: new Date('2017-12-30'), changes: <Wrapper>Added stats for <ItemLink id={ITEMS.STORMSTOUTS_LAST_GASP.id} icon /> and <ItemLink id={ITEMS.SALSALABIMS_LOST_TUNIC.id} icon />; updated the <SpellLink id={SPELLS.BREATH_OF_FIRE.id} /> suggestion and checklist item.</Wrapper>, contributors: [emallson], }, { date: new Date('2017-12-29'), changes: <Wrapper>Changed <SpellLink id={SPELLS.RUSHING_JADE_WIND_TALENT.id} /> suggestion from cast efficiency to uptime.</Wrapper>, contributors: [emallson], }, { date: new Date('2017-12-24'), changes: <Wrapper>Added <SpellLink id={SPELLS.IRONSKIN_BREW_BUFF.id} /> uptime and clipping checklist items.</Wrapper>, contributors: [emallson], }, { date: new Date('2017-08-24'), changes: <Wrapper>Added <SpellLink id={SPELLS.BLACKOUT_COMBO_BUFF.id} /> statistic.</Wrapper>, contributors: [WOPR], }, { date: new Date('2017-08-21'), changes: 'Fixed bug with stagger if a tick of the dot is absorbed it will calculate correctly.', contributors: [WOPR], }, { date: new Date('2017-08-21'), changes: 'Added T20 2pc and 4pc stats.', contributors: [WOPR], }, { date: new Date('2017-08-20'), changes: <Wrapper>Added more information about what occured while <SpellLink id={SPELLS.IRONSKIN_BREW_BUFF.id} /> was up or not.</Wrapper>, contributors: [WOPR], }, { date: new Date('2017-08-20'), changes: 'This is an initial implementation, will be updated soon', contributors: [WOPR], }, ];
src/client.js
alexanderchan/react-redux-universal-hot-example
/** * THIS IS THE ENTRY POINT FOR THE CLIENT, JUST LIKE server.js IS THE ENTRY POINT FOR THE SERVER. */ import 'babel/polyfill'; import React from 'react'; import BrowserHistory from 'react-router/lib/BrowserHistory'; import Location from 'react-router/lib/Location'; import queryString from 'query-string'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import universalRouter from './helpers/universalRouter'; const history = new BrowserHistory(); const client = new ApiClient(); const dest = document.getElementById('content'); const store = createStore(client, window.__data); const search = document.location.search; const query = search && queryString.parse(search); const location = new Location(document.location.pathname, query); universalRouter(location, history, store) .then(({component}) => { if (__DEVTOOLS__) { const { DevTools, DebugPanel, LogMonitor } = require('redux-devtools/lib/react'); console.info('You will see a "Warning: React attempted to reuse markup in a container but the checksum was' + ' invalid." message. That\'s because the redux-devtools are enabled.'); React.render(<div> {component} <DebugPanel top right bottom key="debugPanel"> <DevTools store={store} monitor={LogMonitor}/> </DebugPanel> </div>, dest); } else { React.render(component, dest); } }, (error) => { console.error(error); }); if (process.env.NODE_ENV !== 'production') { window.React = React; // enable debugger const reactRoot = window.document.getElementById('content'); if (!reactRoot || !reactRoot.firstChild || !reactRoot.firstChild.attributes || !reactRoot.firstChild.attributes['data-react-checksum']) { console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.'); } }
src/libraries/notResolved.js
blueberryapps/react-bluekit
import React from 'react'; export default (data) => () => (<div>Unable to resolve: {JSON.stringify(data)}</div>)
client/modals/UploadModal.js
spectralsun/reactgur
import EventEmitter from 'events'; import React from 'react'; import xhttp from 'xhttp'; import {Modal, Button, Input, Alert} from 'react-bootstrap'; import ee from './../Emitter.js'; import ModalComponent from './../components/ModalComponent.js'; import UploadComponent from './../components/UploadComponent.js'; export default class UploadModal extends ModalComponent { constructor(props) { super(props) this.uploads = [] this.uploaded = [] this.state = { uploads: 0 } ee.addListener('route:/upload', this.checkUploadPrivilege.bind(this)); } checkUploadPrivilege() { if (APP_CONF.upload_requires_login && !this.props.user.username) return; this.open(); } handleInputChange(e) { for (var x = 0; x < e.target.files.length; x++) { var emitter = new EventEmitter(); var upload = <UploadComponent key={x} ee={emitter} file={e.target.files[x]} />; emitter.addListener('load', this.handleLoad.bind(this)); emitter.addListener('uploaded', this.handleUploaded.bind(this)); this.uploads.push(upload); } this.setState({uploads: this.uploads.length }) } handleLoad() { var upload_count = this.state.uploads - 1; this.setState({ show: upload_count > 0, uploads: upload_count }); } handleUploaded(upload) { this.uploaded.push(upload) if (this.state.uploads == 0) { ee.emit('media_uploaded', this.uploaded); this.uploads = []; this.uploaded = []; } } cancel() { } close(props) { if (this.state.uploads > 0) return; super.close(props) } render() { return ( <Modal show={this.state.show} onHide={this.close.bind(this)}> {this.state.uploads > 0 ? ( <Modal.Header> <Modal.Title>Uploading Images...</Modal.Title> </Modal.Header> ) : ( <Modal.Header closeButton> <Modal.Title className="text-center"> <span className="glyphicon glyphicon-cloud-upload"></span> <span> Upload Images</span> </Modal.Title> </Modal.Header> )} <Modal.Body className="text-center"> {this.state.uploads == 0 ? ( <span id="upload_button" className="btn btn-success btn-lg"> <i className="glyphicon glyphicon-plus"/> <span> Select files...</span> <input type="file" name="file" multiple onChange={this.handleInputChange.bind(this)} /> </span> ) : null} <div> {this.uploads} </div> </Modal.Body> <Modal.Footer> {this.state.uploads == 0 ? ( <Button onClick={this.close.bind(this)}>Close</Button> ) : ( <Button bsStyle="danger" onClick={this.cancel.bind(this)}>Cancel</Button> )} </Modal.Footer> </Modal> ) } }
actor-apps/app-web/src/app/utils/require-auth.js
ganquan0910/actor-platform
import React from 'react'; import LoginStore from 'stores/LoginStore'; export default (Component) => { return class Authenticated extends React.Component { static willTransitionTo(transition) { if (!LoginStore.isLoggedIn()) { transition.redirect('/auth', {}, {'nextPath': transition.path}); } } render() { return <Component {...this.props}/>; } }; };
src/svg-icons/notification/wc.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationWc = (props) => ( <SvgIcon {...props}> <path d="M5.5 22v-7.5H4V9c0-1.1.9-2 2-2h3c1.1 0 2 .9 2 2v5.5H9.5V22h-4zM18 22v-6h3l-2.54-7.63C18.18 7.55 17.42 7 16.56 7h-.12c-.86 0-1.63.55-1.9 1.37L12 16h3v6h3zM7.5 6c1.11 0 2-.89 2-2s-.89-2-2-2-2 .89-2 2 .89 2 2 2zm9 0c1.11 0 2-.89 2-2s-.89-2-2-2-2 .89-2 2 .89 2 2 2z"/> </SvgIcon> ); NotificationWc = pure(NotificationWc); NotificationWc.displayName = 'NotificationWc'; NotificationWc.muiName = 'SvgIcon'; export default NotificationWc;
example/components/sample.js
chetstone/react-native-palette
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { Alert, Button, ImageBackground, NativeModules, Platform, StyleSheet, Text, View } from 'react-native'; var createReactClass = require('create-react-class'); import imagePicker from '../utils/ImagePicker' export default Sample = createReactClass( { getInitialState: function() { return { colors: {}, api: 'v1', //Platform.OS === 'ios' ? 'v0' : 'v1', diag: "", useNamed: false, leftButton: Platform.OS === 'ios' ? 'v0 API' : 'getAllSwatches', rightButton: Platform.OS === 'ios' ? 'v1 API' : 'getNamedSwatches', } } , storeImage(colors) { console.log("In sample", typeof this.state.colors.swatches === 'string' ? this.state.colors.swatches : colors.swatches[0].swatchInfo ); this.setState({colors}); }, pressLeft() { if (Platform.OS === 'ios') { this.setState({api: 'v0'}); } else { this.setState({useNamed: false}); } }, pressRight() { if (Platform.OS === 'ios') { this.setState({api: 'v1'}); } else { this.setState({useNamed: true}); } }, onPress(useUri) { console.log("Button pressed"); if (this.state.api === 'v1') { imagePicker(this.storeImage, this.state.useNamed, useUri); } else { imagePicker(this.storeImage, this.state.useNamed, useUri); } }, render() { //console.log(this.state.colors); let isImage = this.state.colors && this.state.colors.image; let buttonText = `Load ${isImage? "Another":""} Image` let textColor = this.state.colors && this.state.colors.swatches && this.state.colors.swatches[0].bodyTextColor ? this.state.colors.swatches[0].bodyTextColor : 'white' let domColor = this.state.colors && this.state.colors.swatches && this.state.colors.swatches[0].color let buttonColor = domColor? domColor: "#841584" const button = <View> <Button onPress={() => this.onPress(false)} title={buttonText} color={buttonColor} accessibilityLabel="Learn more about this purple button" /> <Button onPress={() => this.onPress(true)} title={"Load Image and Use URI"} color={buttonColor} accessibilityLabel="Learn more about this purple button" /> </View>; const imagewrapped = isImage ? <ImageBackground style={styles.image} source={{uri: 'data:image/jpeg;base64,' + this.state.colors.image, isStatic: true}}> {button} </ImageBackground> : <View>{button}<Text>{this.state.diag}</Text></View> const buttons = Platform.OS === 'ios' ? <View/> : <View style={styles.optionContainer}> <Button onPress={this.pressLeft} title={this.state.leftButton} /> <Button onPress={this.pressRight} title={this.state.rightButton} /> </View>; return ( <View style={styles.container}> <View style={styles.imageContainer}> {imagewrapped} </View> <View style={styles.swatchContainer}> {isImage && typeof this.state.colors.swatches !== 'string' ? this.state.colors.swatches.map((swatch, index) => { return ( <View key={index} style={[styles.swatch,{backgroundColor: swatch.color}]}> <Text style={{color: swatch.bodyTextColor}}>{swatch.name ? swatch.name: (swatch.population*(Platform.OS === 'ios'?1000:1)).toFixed()}</Text> </View>) } ) : <Text>{typeof this.state.colors.swatches === 'string'? this.state.colors.swatches : "Placeholder"}</Text>} </View> {buttons} </View> ); } }); const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, imageContainer: { flex: 2, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', borderBottomWidth: 1, }, swatchContainer: { flex: .75, flexDirection: 'row', justifyContent: 'center', alignItems: 'flex-start', flexWrap: 'wrap', }, optionContainer: { flex: .25, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', }, swatch: { width: 70, height: 50, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', }, image: { flex: 1, alignItems: 'center', justifyContent: 'center', /* overflow: 'hidden', /* don't let bounce obscure the navbar */ alignSelf: 'stretch', resizeMode: 'cover', }, });
app/routes.js
firewenda/testwebsite
import React from 'react'; import {Route} from 'react-router'; import App from './components/App'; import Home from './components/Home'; import Stats from './components/Stats'; import Character from './components/Character'; import CharacterList from './components/CharacterList'; import AddCharacter from './components/AddCharacter'; export default ( <Route component={App}> <Route path='/' component={Home} /> <Route path='/stats' component={Stats} /> <Route path='/characters/:id' component={Character} /> <Route path='/add' component={AddCharacter} /> <Route path=':category' component={CharacterList}> <Route path=':race' component={CharacterList}> <Route path=':bloodline' component={CharacterList} /> </Route> </Route> </Route> );
packages/reactor-kitchensink/src/examples/Charts/Area/StackedArea/StackedArea.js
sencha/extjs-reactor
import React, { Component } from 'react'; import { Container } from '@extjs/ext-react'; import { Cartesian } from '@extjs/ext-react-charts'; import ChartToolbar from '../../ChartToolbar'; export default class StackedAreaChartExample extends Component { constructor(){ super(); } store = Ext.create('Ext.data.Store', { fields:['month', 'data1', 'data2', 'data3', 'data4', 'other'], data:[ { month: 'Jan', data1: 20, data2: 37, data3: 35, data4: 4, other: 4 }, { month: 'Feb', data1: 20, data2: 37, data3: 36, data4: 5, other: 2 }, { month: 'Mar', data1: 19, data2: 36, data3: 37, data4: 4, other: 4 }, { month: 'Apr', data1: 18, data2: 36, data3: 38, data4: 5, other: 3 }, { month: 'May', data1: 18, data2: 35, data3: 39, data4: 4, other: 4 }, { month: 'Jun', data1: 17, data2: 34, data3: 42, data4: 4, other: 3 }, { month: 'Jul', data1: 16, data2: 34, data3: 43, data4: 4, other: 3 }, { month: 'Aug', data1: 16, data2: 33, data3: 44, data4: 4, other: 3 }, { month: 'Sep', data1: 16, data2: 32, data3: 44, data4: 4, other: 4 }, { month: 'Oct', data1: 16, data2: 32, data3: 45, data4: 4, other: 3 }, { month: 'Nov', data1: 15, data2: 31, data3: 46, data4: 4, other: 4 }, { month: 'Dec', data1: 15, data2: 31, data3: 47, data4: 4, other: 3 }] }); state = { theme: 'default' }; changeTheme = theme => this.setState({ theme }) onAxisLabelRender = (axis, label) => { return label.toFixed(label < 10 ? 1 : 0) + '%'; } onSeriesTooltipRender = (tooltip, record, item) => { var fieldIndex = Ext.Array.indexOf(item.series.getYField(), item.field), browser = item.series.getTitle()[fieldIndex]; tooltip.setHtml(`${browser} on ${record.get('month')}: ${record.get(item.field)}%`) } render() { const { theme } = this.state; return ( <Container padding={!Ext.os.is.Phone && 10} layout="fit"> <ChartToolbar onThemeChange={this.changeTheme} theme={theme} /> <Cartesian shadow store={this.store} theme={theme} insetPadding={'20 20 10 10'} legend={{type:'sprite'}} axes={[{ type: 'numeric', fields: 'data1', position: 'left', grid: true, minimum: 0, renderer: this.onAxisLabelRender }, { type: 'category', fields: 'month', position: 'bottom', grid: true, label: { rotate: { degrees: -90 } } }]} series={[{ type: 'area', title: [ 'IE', 'Firefox', 'Chrome', 'Safari' ], xField: 'month', yField: [ 'data1', 'data2', 'data3', 'data4' ], style: { opacity: 0.80 }, marker: { opacity: 0, scaling: 0.01, animation: { duration: 200, easing: 'easeOut' } }, highlightCfg: { opacity: 1, scaling: 1.5 }, tooltip: { trackMouse: true, renderer: this.onSeriesTooltipRender } }]} /> </Container> ) } }