path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/components/UserAvatar.js
afonsobarros/reactnd-project-readable
import React, { Component } from 'react'; import { Avatar } from 'material-ui'; import themeDefault from '../theme-default'; class UserAvatar extends Component { render() { const { username, small } = this.props; let firstLetters = username.substring(0, 1).toUpperCase(); if (username.split(" ").length > 1) firstLetters += username.split(" ")[1].substring(0, 1).toUpperCase(); return ( <Avatar style={small ? themeDefault.avatarSmall : themeDefault.avatar}> {firstLetters} </Avatar> ); } } export default UserAvatar;
src/components/MainIngredient.js
ataylorme/hazels-heritage-frontend
import React from 'react'; import axios from 'axios'; import Recipe from './Recipe'; import Config from '../Config'; import GoHomeButton from './GoHomeButton'; class MainIngredient extends React.Component { constructor() { super(); // Set initial state this.state = { data: {} }; this.unmounted = false; this.fetchRecipes = this.fetchRecipes.bind(this); } fetchRecipes() { this.serverRequest = axios .get(`${Config.restURL}/main-ingredients/${this.props.params.termID}`) .then(function (result) { if (this.unmounted) { return; } this.setState({ data: result.data }); }.bind(this)) .catch(function (response) { // something went wrong }) } componentWillMount() { this.fetchRecipes(); } componentDidUpdate(prevProps) { if (this.props.params.termID !== prevProps.params.termID) { this.fetchRecipes(); } } componentWillUnmount() { this.unmounted = true; } render() { // if data is empty if (Object.keys(this.state.data).length === 0) { return (<div id="recipes" className="loading"></div>); } return ( <div id="recipes"> <GoHomeButton /> <h1 className="headline"> <span className="text"> {this.state.data.total} <em>{this.state.data.name}</em> Recipes </span> </h1> { Object .keys(this.state.data.recipes) .map(key => <Recipe key={key} index={key} recipe={this.state.data.recipes[key]}/>) } </div> ) } } MainIngredient.propTypes = { params: React.PropTypes.object.isRequired }; export default MainIngredient
src/svg-icons/action/accessibility.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAccessibility = (props) => ( <SvgIcon {...props}> <path d="M12 2c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm9 7h-6v13h-2v-6h-2v6H9V9H3V7h18v2z"/> </SvgIcon> ); ActionAccessibility = pure(ActionAccessibility); ActionAccessibility.displayName = 'ActionAccessibility'; export default ActionAccessibility;
client/components/MultiplayerInfo.js
jordanallen98/nimblecode
import React, { Component } from 'react'; class MultiplayerInfo extends Component { constructor(props) { super(props); this.link = "http://nimblecode.io/#/multigame/" + this.props.gameId; } render() { return ( <div className="col-sm-12"> <h3 className="text-center no-top-margin">Multiplayer Game {this.props.gameId}</h3> </div> ); } } export default MultiplayerInfo;
src/svg-icons/image/camera-front.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCameraFront = (props) => ( <SvgIcon {...props}> <path d="M10 20H5v2h5v2l3-3-3-3v2zm4 0v2h5v-2h-5zM12 8c1.1 0 2-.9 2-2s-.9-2-2-2-1.99.9-1.99 2S10.9 8 12 8zm5-8H7C5.9 0 5 .9 5 2v14c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V2c0-1.1-.9-2-2-2zM7 2h10v10.5c0-1.67-3.33-2.5-5-2.5s-5 .83-5 2.5V2z"/> </SvgIcon> ); ImageCameraFront = pure(ImageCameraFront); ImageCameraFront.displayName = 'ImageCameraFront'; ImageCameraFront.muiName = 'SvgIcon'; export default ImageCameraFront;
src/components/App.js
lmammino/judo-heroes-2
import React from 'react'; import { Route, Switch } from 'react-router-dom'; import { Layout } from './Layout'; import { IndexPage } from './IndexPage'; import { AthletePage } from './AthletePage'; import { NotFoundPage } from './NotFoundPage'; import athletes from '../data/athletes'; const renderIndex = () => <IndexPage athletes={athletes} />; const renderAthlete = ({ match, staticContext }) => { const id = match.params.id; const athlete = athletes.find(current => current.id === id); if (!athlete) { return <NotFoundPage staticContext={staticContext} />; } return <AthletePage athlete={athlete} athletes={athletes} />; }; export const App = () => ( <Layout> <Switch> <Route exact path="/" render={renderIndex} /> <Route exact path="/athlete/:id" render={renderAthlete} /> <Route component={NotFoundPage} /> </Switch> </Layout> ); export default App;
docs/src/BrowserRouter.js
seekinternational/seek-asia-style-guide
import React from 'react'; import { BrowserRouter } from 'react-router-dom'; import App from 'App/App'; export default () => ( <BrowserRouter basename={process.env.BASE_HREF}> <App /> </BrowserRouter> );
app/components/Header/index.js
pavel06081991/SPWorld
/** * * Header * */ import React from 'react'; import styles from './styles.css'; class Header extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <header className={styles.header}> <div className="container"> <div className="row"> <div className="col-xs-12"> header </div> </div> </div> </header> ); } } export default Header;
electron/renderer/src/components/Webviews.js
ConorIA/wire-desktop
/* * Wire * Copyright (C) 2017 Wire Swiss GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. * */ import React, { Component } from 'react'; import Webview from './Webview'; import badgeCount from '../lib/badgeCount'; import './Webviews.css'; class Webviews extends Component { constructor(props) { super(props); } shouldComponentUpdate(nextProps) { for (const account of nextProps.accounts) { const match = this.props.accounts.find((_account) => account.id === _account.id); if (!match || match.visible !== account.visible) { return true; } } return false; } _getEnvironmentUrl(account) { const envParam = decodeURIComponent(new URL(window.location).searchParams.get('env')); const url = new URL(envParam); // pass account id to webview so we can access it in the preload script url.searchParams.set('id', account.id); // when landing on auth page for login mode url.hash = 'login'; return url.href; } _accumulateBadgeCount(accounts) { return accounts.reduce((accumulated, account) => { return accumulated + account.badgeCount; }, 0); } _onPageTitleUpdated(account, { title }) { const count = badgeCount(title); this.props.updateAccountBadgeCount(account.id, count); const accumulatedCount = this._accumulateBadgeCount(this.props.accounts); window.sendBadgeCount(accumulatedCount); } _onIpcMessage(account, {channel, args}) { switch (channel) { case 'notification-click': this.props.switchAccount(account.id); break; case 'team-info': this.props.updateAccountData(account.id, args[0]); break; case 'signed-out': this._deleteWebview(account); break; } } _onWebviewClose(account) { this._deleteWebview(account); } _deleteWebview(account) { window.sendDeleteAccount(account.id, account.sessionID); this.props.abortAccountCreation(account.id); } _canDeleteWebview(account) { return !account.userID && account.sessionID; } render() { return ( <ul className="Webviews"> {this.props.accounts.map((account) => ( <div className="Webviews-container" key={account.id}> <Webview className={'Webview ' + (account.visible ? '' : 'hide')} visible={account.visible} src={this._getEnvironmentUrl(account)} partition={account.sessionID} preload='./static/webview-preload.js' onPageTitleUpdated={(event) => this._onPageTitleUpdated(account, event)} onIpcMessage={(event) => this._onIpcMessage(account, event)} /> {(this._canDeleteWebview(account)) && <div className="Webviews-close" onClick={() => this._onWebviewClose(account)}> <svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"> <path d="M2.757 14.657L8 9.414l5.243 5.243 1.414-1.414L9.414 8l5.243-5.243-1.414-1.414L8 6.586 2.757 1.343 1.343 2.757 6.586 8l-5.243 5.243" fillRule="evenodd"/> </svg> </div> } </div> ))} </ul> ); } } export default Webviews;
src/js/components/icons/base/PlatformSkype.js
codeswan/grommet
import React from 'react'; import SocialSkype from './SocialSkype'; export default (props) => { console.warn( 'PlatformSkype has been renamed to SocialSkype.' + ' Plese update your import statement.' ); return <SocialSkype {...props} />; };
src/js/components/blog/articlepaging.js
axuebin/react-blog
import React from 'react'; import PropTypes from 'prop-types'; import { Pagination } from 'antd'; export default class ArticlePaging extends React.Component { constructor() { super(); this.onChangePage = this.onChangePage.bind(this); } onChangePage(pageNumber) { this.props.handlePageChange(pageNumber); } render() { return ( <div className="blog-article-paging"> <Pagination onChange={this.onChangePage} defaultPageSize={this.props.defaultPageSize} total={this.props.total} /> </div> ); } } ArticlePaging.defaultProps = { handlePageChange: null, defaultPageSize: 5, total: 10, }; ArticlePaging.propTypes = { handlePageChange: PropTypes.func, defaultPageSize: PropTypes.number, total: PropTypes.number, };
public/src/user/Profile.js
thomasjosephgreco/rejection
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router' import UserInfo from './UserInfo'; import IterateQuestions from '../questions/components/IterateQuestions'; import * as Selectors from '../questions/state/selectors'; class Profile extends Component { componentWillReceiveProps(nextProps) { if (nextProps.userState.isAuthenticated === 'yes') { this.context.router.push('/'); } } render() { // console.log('User', this.props.userState); const { questions } = this.props.questionsList; const userEmail = this.props.userState.email; const userQuestions = questions.filter(q => q._createdBy === userEmail); const userScore = userQuestions.reduce((sum, val) => sum + val.answerWorth , 0); return ( <div> <h3><Link to='/'>Back To Questions Page</Link></h3> <UserInfo {...this.props.userState} /> <h3>Existing Question Log</h3> <p>Current Score: {userScore} </p> <IterateQuestions questions={userQuestions} /> </div> ); } } const mapStateToProps = (state) => { return { userState: state.userState.user, questionsList: Selectors.getAllQuestions(state) } } export default connect(mapStateToProps)(Profile);
src/js/app.js
heymexa/react-test
import React from 'react'; import ReactDOM from 'react-dom'; import App from './Components/App'; let data = [ ['A', 'B', 'C'], ['1', '2', '3'], ['X', 'Y', 'Z'] ]; ReactDOM.render( <App data={data} />, document.getElementById('app') );
example/react-native-camera-roll-picker/camera-roll-picker.js
jnuine/react-native-photos-framework
import React, { Component } from 'react'; import { CameraRoll, Platform, StyleSheet, View, Text, ListView, ActivityIndicator } from 'react-native'; import ImageItem from './ImageItem'; import RNPhotosFramework from '../react-native-photos-framework'; var simple_timer = require('simple-timer') class CameraRollPicker extends Component { constructor(props) { super(props); this.state = { images: [], selected: this.props.selected, lastCursor: null, loadingMore: false, noMore: false, dataSource: new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }) }; } componentWillReceiveProps(nextProps) { this.setState({ selected: nextProps.selected }); if (nextProps.album !== this.props.album) { this.setState({ images: [], loadingMore: false, dataSource: this .state .dataSource .cloneWithRows([]) }); this._fetch(true, nextProps); } } fetch() { if (!this.state.loadingMore) { this.setState({ loadingMore: true }, () => { this._fetch(); }); } } componentWillMount() { this.fetch(); this.unsubscribe = this .props .album .onChange((changeDetails, update) => { update(this.state.images, (images) => { console.log(images[0]); this.state.images = images; this.state.dataSource = this .state .dataSource .cloneWithRows(this._nEveryRow(this.state.images, this.props.imagesPerRow)); this.setState({ images: this.state.images, dataSource: this.state.dataSource }); }, { includeMetadata: true }); }); } componentWillUnmount() { this .props .album .stopTracking(); this.unsubscribe && this.unsubscribe(); } _fetch(reset, nextProps) { let props = nextProps || this.props; simple_timer.start('fetch_timer'); props .album .getAssets({ includeMetadata: true, trackInsertsAndDeletes: true, // trackChanges: true, startIndex: this.state.images.length, endIndex: this.state.images.length + 20, fetchOptions: { // includeHiddenAssets: true, sortDescriptors: [{ key: 'creationDate', ascending: true }] }, assetDisplayBottomUp: false, assetDisplayStartToEnd: false }) .then((data) => { console.log(data.assets.map(x => x.collectionIndex)); simple_timer.stop('fetch_timer'); console.log('react-native-photos-framework fetch request took %s milliseconds.', simple_timer.get('fetch_timer').delta) this._appendImages(data); }, (e) => console.log(e)); } _appendImages(data) { var assets = data.assets; var newState = { loadingMore: false }; if (data.includesLastAsset) { newState.noMore = true; } if (assets.length > 0) { newState.images = this .state .images .concat(assets); newState.dataSource = this .state .dataSource .cloneWithRows(this._nEveryRow(newState.images, this.props.imagesPerRow)); } this.setState(newState); } render() { var {dataSource} = this.state; var { scrollRenderAheadDistance, initialListSize, pageSize, removeClippedSubviews, imageMargin, backgroundColor, emptyText, emptyTextStyle } = this.props; var listViewOrEmptyText = dataSource.getRowCount() > 0 ? (<ListView style={{ flex: 1 }} scrollRenderAheadDistance={scrollRenderAheadDistance} initialListSize={initialListSize} pageSize={pageSize} removeClippedSubviews={removeClippedSubviews} renderFooter={this ._renderFooterSpinner .bind(this)} onEndReached={this ._onEndReached .bind(this)} onEndReachedThreshold={2000} dataSource={dataSource} renderRow={rowData => this._renderRow(rowData)} />) : ( <Text style={[ { textAlign: 'center' }, emptyTextStyle ]}>{emptyText}</Text> ); return ( <View style={[ styles.wrapper, { padding: imageMargin, paddingRight: 0, backgroundColor: backgroundColor } ]}> {listViewOrEmptyText} </View> ); } _renderImage(item) { var {selected} = this.state; var {imageMargin, selectedMarker, imagesPerRow, containerWidth} = this.props; var uri = item.uri; var isSelected = (this._arrayObjectIndexOf(selected, 'uri', uri) >= 0) ? true : false; return (<ImageItem key={uri} displayDates={true} item={item} selected={isSelected} imageMargin={imageMargin} selectedMarker={selectedMarker} imagesPerRow={imagesPerRow} containerWidth={containerWidth} onClick={this ._selectImage .bind(this)} />); } _renderRow(rowData) { var items = rowData.map((item) => { if (item === null) { return null; } return this._renderImage(item); }); return ( <View style={styles.row}> {items} </View> ); } _renderFooterSpinner() { if (!this.state.noMore) { return <ActivityIndicator style={styles.spinner} />; } return null; } _onEndReached() { if (!this.state.noMore) { this.fetch(); } } _selectImage(image) { var {maximum, imagesPerRow, callback} = this.props; var selected = this.state.selected, index = this._arrayObjectIndexOf(selected, 'uri', image.uri); if (index >= 0) { selected.splice(index, 1); } else { if (selected.length < maximum) { selected.push(image); } } this.setState({ selected: selected, dataSource: this .state .dataSource .cloneWithRows(this._nEveryRow(this.state.images, imagesPerRow)) }); callback(this.state.selected, image); } _nEveryRow(data, n) { var result = [], temp = []; for (var i = 0; i < data.length; ++i) { if (i > 0 && i % n === 0) { result.push(temp); temp = []; } temp.push(data[i]); } if (temp.length > 0) { while (temp.length !== n) { temp.push(null); } result.push(temp); } return result; } _arrayObjectIndexOf(array, property, value) { return array.map((o) => { return o[property]; }).indexOf(value); } } const styles = StyleSheet.create({ wrapper: { flex: 1 }, row: { flexDirection: 'row', flex: 1 }, marker: { position: 'absolute', top: 5, backgroundColor: 'transparent' } }) CameraRollPicker.propTypes = { scrollRenderAheadDistance: React.PropTypes.number, initialListSize: React.PropTypes.number, pageSize: React.PropTypes.number, removeClippedSubviews: React.PropTypes.bool, groupTypes: React .PropTypes .oneOf([ 'Album', 'All', 'Event', 'Faces', 'Library', 'PhotoStream', 'SavedPhotos' ]), maximum: React.PropTypes.number, assetType: React .PropTypes .oneOf(['Photos', 'Videos', 'All']), imagesPerRow: React.PropTypes.number, imageMargin: React.PropTypes.number, containerWidth: React.PropTypes.number, callback: React.PropTypes.func, selected: React.PropTypes.array, selectedMarker: React.PropTypes.element, backgroundColor: React.PropTypes.string, emptyText: React.PropTypes.string, emptyTextStyle: Text.propTypes.style } CameraRollPicker.defaultProps = { scrollRenderAheadDistance: 800, initialListSize: 1, pageSize: 12, removeClippedSubviews: true, groupTypes: 'SavedPhotos', maximum: 15, imagesPerRow: 3, imageMargin: 5, assetType: 'Photos', backgroundColor: 'white', selected: [], callback: function (selectedImages, currentImage) { console.log(currentImage); console.log(selectedImages); }, emptyText: 'No photos.' } export default CameraRollPicker;
src/components/overview-table/overview-table.js
mpigsley/sectors-without-number
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import { intlShape, FormattedMessage } from 'react-intl'; import Pluralize from 'pluralize'; import EmptyOverview from 'components/empty-overview'; import Header, { HeaderType } from 'primitives/text/header'; import FlexContainer from 'primitives/container/flex-container'; import Table from 'primitives/other/table'; import Button from 'primitives/other/button'; import Entities from 'constants/entities'; import { generateCSV, createCSVDownload } from 'utils/export'; import { sortByKey } from 'utils/common'; import { values, size } from 'constants/lodash'; import './style.scss'; export default function OverviewTable({ customTags, entities, match, currentSector, intl, }) { const pluralName = intl.formatMessage({ id: Pluralize(Entities[match.params.entityType].name), }); const getColumnsFromType = entityType => { const common = [ { accessor: 'name', Header: 'misc.name', Cell: (name, { link }) => ( <Link className="OverviewTable-Link" to={link}> {name} </Link> ), }, { accessor: 'location', Header: 'misc.location', centered: true }, { accessor: 'tags', Header: 'misc.tags', Cell: tags => tags .map(tag => intl.formatMessage({ id: `tags.${tag}`, defaultMessage: (customTags[tag] || {}).name, }), ) .filter(tag => tag) .join(', ') || '-', }, ]; const attributes = Entities[entityType].attributes.map(({ key, name }) => ({ accessor: key, Header: name, })); if (Entities[entityType].topLevel) { return [ ...common, { accessor: 'children', Header: 'misc.children', centered: true }, { accessor: 'neighbors', Header: 'misc.neighbors' }, ...attributes, ]; } const columns = [ ...common, { accessor: 'parent', Header: 'misc.parent', Cell: (parent, { parentLink, parentType }) => ( <Link className="OverviewTable-Link" to={parentLink}> {parent} ({intl.formatMessage({ id: parentType })}) </Link> ), }, ]; if (Entities[entityType].children.length) { columns.splice(2, 0, { accessor: 'children', Header: 'misc.children', centered: true, }); } attributes.map(attr => columns.push(attr)); return columns; }; if (!size(entities[match.params.entityType])) { return ( <EmptyOverview> <FormattedMessage id="misc.noEntities" values={{ entities: pluralName, }} /> </EmptyOverview> ); } const columns = getColumnsFromType(match.params.entityType); const tableData = values(entities[match.params.entityType]).sort( sortByKey('name'), ); const exportTable = () => { const table = [ columns.map(col => intl.formatMessage({ id: col.Header })), ].concat( tableData.map(data => columns.map(({ accessor }) => { if (!data[accessor]) { return ''; } return accessor === 'tags' ? data[accessor] .map(tag => intl.formatMessage({ id: `tags.${tag}`, defaultMessage: (customTags[tag] || {}).name, }), ) .filter(tag => tag) .join(', ') : intl.formatMessage({ id: data[accessor], defaultMessage: `${data[accessor]}` || '', }); }), ), ); return createCSVDownload( generateCSV(table), `${currentSector.name} - ${pluralName}`, ); }; return ( <FlexContainer flex="3" direction="column" align="flexStart" className="OverviewTable" > <div className="OverviewTable-FlexWrap"> <FlexContainer justify="spaceBetween" align="baseline"> <Header type={HeaderType.header3}> {intl.formatMessage({ id: Entities[match.params.entityType].name })} </Header> <Button minimal onClick={exportTable}> <FormattedMessage id="misc.exportEntity" values={{ entity: pluralName, }} /> </Button> </FlexContainer> </div> <Table sortable className="OverviewTable-Table" dataIdAccessor="key" columns={columns} data={tableData} /> </FlexContainer> ); } OverviewTable.propTypes = { customTags: PropTypes.shape().isRequired, entities: PropTypes.shape().isRequired, currentSector: PropTypes.shape({ name: PropTypes.string, }), match: PropTypes.shape({ params: PropTypes.shape({ entityType: PropTypes.string.isRequired, }).isRequired, }).isRequired, intl: intlShape.isRequired, }; OverviewTable.defaultProps = { currentSector: {}, };
public/js/components/admin/Cards.react.js
IsuruDilhan/Coupley
/** * Created by Isuru 1 on 21/01/2016. */ import React from 'react'; import { Link } from 'react-router'; import Tabs from './graphs/tab.react'; import CustomerGraph from './graphs/customers.react'; import PieGraph from './graphs/pieChartCustomers.react'; import GraphActions from './../../actions/admin/GraphActions'; import GraphStore from './../../stores/admin/GraphStore'; import PathStore from './../../stores/admin/PathStore'; const Cards = React.createClass({ getInitialState: function () { return { status: GraphStore.getresults(), path:PathStore.getpath(), }; }, componentDidMount: function () { GraphActions.userStats(); GraphStore.addChangeListener(this._onChange); PathStore.addChangeListener(this._onChange); }, _onChange: function () { if (this.isMounted()) { this.setState({ status: GraphStore.getresults(), path:PathStore.getpath(), }); } }, retireveLikebacks:function () { for (var i in this.state.status) { var flirts = this.state.status[i].count; return flirts; } }, retireveNumberOfUsers:function () { for (var i in this.state.status) { var users = this.state.status[i].users; return users; } }, retireveNumberOfAdmins:function () { for (var i in this.state.status) { var admins = this.state.status[i].admins; return admins; } }, retrieveLikebackRate:function () { var i;var n; var j = 1; var couples = 1; var users = this.retireveNumberOfUsers(); n = users - 2; for (i = 1; i <= n; i++) { j = j + 1; couples = couples + j; } var likebacks = this.retireveLikebacks(); return (((likebacks / couples) * 100).toFixed(2)); }, render: function () { return ( <div className="row"> <div className="col-lg-3 col-xs-6"> <div className="small-box bg-aqua"> <div className="inner"> <h3>{this.retireveLikebacks(this)}</h3> <p>Total Likebacks</p> </div> <div className="icon"> <i className="ion ion-heart"></i> </div> <a className="small-box-footer"> </a> </div> </div> <div className="col-lg-3 col-xs-6"> <div className="small-box bg-green"> <div className="inner"> <h3>{this.retrieveLikebackRate(this)} <sup styles={'font-size: 20px'}>%</sup> </h3> <p>Likeback Rate</p> </div> <div className="icon"> <i className="ion ion-arrow-graph-up-right"></i> </div> <a className="small-box-footer"> </a> </div> </div> <div className="col-lg-3 col-xs-6"> <div className="small-box bg-yellow"> <div className="inner"> <h3>{this.retireveNumberOfUsers()}</h3> <p>Total Users</p> </div> <div className="icon"> <i className="ion ion-person-stalker"></i> </div> <a className="small-box-footer"> </a> </div> </div> <div className="col-lg-3 col-xs-6"> <div className="small-box bg-red"> <div className="inner"> <h3>{this.retireveNumberOfAdmins()}</h3> <p>Total Administrators</p> </div> <div className="icon"> <i className="ion ion-person"></i> </div> <a className="small-box-footer"> </a> </div> </div> <Tabs/> </div> ); }, }); export default Cards;
docs/src/app/components/pages/components/IconMenu/ExampleNested.js
pomerantsev/material-ui
import React from 'react'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; import IconButton from 'material-ui/IconButton'; import Divider from 'material-ui/Divider'; import Download from 'material-ui/svg-icons/file/file-download'; import ArrowDropRight from 'material-ui/svg-icons/navigation-arrow-drop-right'; import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert'; const IconMenuExampleNested = () => ( <div> <IconMenu iconButtonElement={<IconButton><MoreVertIcon /></IconButton>} anchorOrigin={{horizontal: 'left', vertical: 'top'}} targetOrigin={{horizontal: 'left', vertical: 'top'}} > <MenuItem primaryText="Copy & Paste" rightIcon={<ArrowDropRight />} menuItems={[ <MenuItem primaryText="Cut" />, <MenuItem primaryText="Copy" />, <Divider />, <MenuItem primaryText="Paste" />, ]} /> <MenuItem primaryText="Case Tools" rightIcon={<ArrowDropRight />} menuItems={[ <MenuItem primaryText="UPPERCASE" />, <MenuItem primaryText="lowercase" />, <MenuItem primaryText="CamelCase" />, <MenuItem primaryText="Propercase" />, ]} /> <Divider /> <MenuItem primaryText="Download" leftIcon={<Download />} /> <Divider /> <MenuItem value="Del" primaryText="Delete" /> </IconMenu> </div> ); export default IconMenuExampleNested;
src/ModalFooter.js
JimiHFord/react-bootstrap
import React from 'react'; import classNames from 'classnames'; class ModalFooter extends React.Component { render() { return ( <div {...this.props} className={classNames(this.props.className, this.props.modalClassName)}> {this.props.children} </div> ); } } ModalFooter.propTypes = { /** * A css class applied to the Component */ modalClassName: React.PropTypes.string }; ModalFooter.defaultProps = { modalClassName: 'modal-footer' }; export default ModalFooter;
app/packs/src/components/generic/FieldSelect.js
ComPlat/chemotion_ELN
/* eslint-disable react/forbid-prop-types */ import React from 'react'; import PropTypes from 'prop-types'; import GridSelect from './GridSelect'; const FieldSelect = (props) => { const { allLayers, selField, types, node, tableText } = props; const allFileds = ((allLayers.find(e => e.key === node.data.layer) || {}).fields || []).filter(e => (types || ['text']).includes(e.type)); const all = allFileds.map(e => ({ key: e.field, val: e.field, lab: e.field })); if (tableText && tableText === true) { const tableFileds = ((allLayers.find(e => e.key === node.data.layer) || {}).fields || []).filter(e => e.type === 'table'); tableFileds.forEach((tbl) => { ((tbl.sub_fields || []).filter(e => e.type === 'text') || []).forEach((sf) => { const tfl = { key: `${tbl.field}${sf.id}`, val: `${tbl.field}[@@]${sf.id}`, lab: `${tbl.field}.${sf.col_name}` }; all.push(tfl); }); }); } const dVal = node.data.field; return <GridSelect all={all} onChange={selField} node={node} dVal={dVal} />; }; FieldSelect.propTypes = { allLayers: PropTypes.arrayOf(PropTypes.object).isRequired, types: PropTypes.arrayOf(String).isRequired, tableText: PropTypes.bool, selField: PropTypes.func.isRequired, node: PropTypes.object.isRequired, }; FieldSelect.defaultProps = { tableText: false }; export default FieldSelect;
node_modules/react-bootstrap/es/Jumbotron.js
skinsshark/skinsshark.github.io
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import classNames from 'classnames'; import elementType from 'react-prop-types/lib/elementType'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType }; var defaultProps = { componentClass: 'div' }; var Jumbotron = function (_React$Component) { _inherits(Jumbotron, _React$Component); function Jumbotron() { _classCallCheck(this, Jumbotron); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Jumbotron.prototype.render = function render() { var _props = this.props; var Component = _props.componentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return Jumbotron; }(React.Component); Jumbotron.propTypes = propTypes; Jumbotron.defaultProps = defaultProps; export default bsClass('jumbotron', Jumbotron);
src/parser/priest/shadow/modules/spells/VampiricTouch.js
fyruna/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import Enemies from 'parser/shared/modules/Enemies'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import SpellIcon from 'common/SpellIcon'; import { formatPercentage } from 'common/format'; import SmallStatisticBox, { STATISTIC_ORDER } from 'interface/others/SmallStatisticBox'; class VampiricTouch extends Analyzer { static dependencies = { enemies: Enemies, }; get uptime() { return this.enemies.getBuffUptime(SPELLS.VAMPIRIC_TOUCH.id) / this.owner.fightDuration; } get suggestionThresholds() { return { actual: this.uptime, isLessThan: { minor: 0.95, average: 0.90, major: 0.8, }, style: 'percentage', }; } suggestions(when) { const { isLessThan: { minor, average, major, }, } = this.suggestionThresholds; when(this.uptime).isLessThan(minor) .addSuggestion((suggest, actual, recommended) => { return suggest(<span>Your <SpellLink id={SPELLS.VAMPIRIC_TOUCH.id} /> uptime can be improved. Try to pay more attention to your <SpellLink id={SPELLS.VAMPIRIC_TOUCH.id} /> on the boss.</span>) .icon(SPELLS.VAMPIRIC_TOUCH.icon) .actual(`${formatPercentage(actual)}% Vampiric Touch uptime`) .recommended(`>${formatPercentage(recommended)}% is recommended`) .regular(average).major(major); }); } statistic() { return ( <SmallStatisticBox position={STATISTIC_ORDER.CORE(3)} icon={<SpellIcon id={SPELLS.VAMPIRIC_TOUCH.id} />} value={`${formatPercentage(this.uptime)} %`} label="Vampiric Touch uptime" /> ); } } export default VampiricTouch;
src/store/provider.js
growcss/docs
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Provider } from './createContext'; // The provider, which holds the page-wide store and its actions. // Feel free to abstract actions and state away from this file. class AppProvider extends Component { state = { open: false, showModal: () => this.setState({ open: true }), hideModal: () => this.setState({ open: false }), }; render() { return <Provider value={this.state}>{this.props.children}</Provider>; } } AppProvider.propTypes = { children: PropTypes.node.isRequired, }; export default AppProvider;
packages/react-scripts/fixtures/kitchensink/src/features/syntax/ArrayDestructuring.js
christiantinauer/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load() { return [[1, '1'], [2, '2'], [3, '3'], [4, '4']]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load(); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-array-destructuring"> {this.state.users.map(user => { const [id, name] = user; return <div key={id}>{name}</div>; })} </div> ); } }
src/routes/User/Register.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, { Component } from 'react'; import { connect } from 'dva'; import { routerRedux, Link } from 'dva/router'; import { Form, Input, Button, Select, Row, Col, Popover, Progress } from 'antd'; import styles from './Register.less'; const FormItem = Form.Item; const { Option } = Select; const InputGroup = Input.Group; const passwordStatusMap = { ok: <div className={styles.success}>强度:强</div>, pass: <div className={styles.warning}>强度:中</div>, poor: <div className={styles.error}>强度:太短</div>, }; const passwordProgressMap = { ok: 'success', pass: 'normal', poor: 'exception', }; @connect(({ register, loading }) => ({ register, submitting: loading.effects['register/submit'], })) @Form.create() export default class Register extends Component { state = { count: 0, confirmDirty: false, visible: false, help: '', prefix: '86', }; componentWillReceiveProps(nextProps) { const account = this.props.form.getFieldValue('mail'); if (nextProps.register.status === 'ok') { this.props.dispatch(routerRedux.push({ pathname: '/user/register-result', state: { account, }, })); } } componentWillUnmount() { clearInterval(this.interval); } onGetCaptcha = () => { let count = 59; this.setState({ count }); this.interval = setInterval(() => { count -= 1; this.setState({ count }); if (count === 0) { clearInterval(this.interval); } }, 1000); }; getPasswordStatus = () => { const { form } = this.props; const value = form.getFieldValue('password'); if (value && value.length > 9) { return 'ok'; } if (value && value.length > 5) { return 'pass'; } return 'poor'; }; handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFields({ force: true }, (err, values) => { if (!err) { this.props.dispatch({ type: 'register/submit', payload: { ...values, prefix: this.state.prefix, }, }); } }); }; handleConfirmBlur = (e) => { const { value } = e.target; this.setState({ confirmDirty: this.state.confirmDirty || !!value }); }; checkConfirm = (rule, value, callback) => { const { form } = this.props; if (value && value !== form.getFieldValue('password')) { callback('两次输入的密码不匹配!'); } else { callback(); } }; checkPassword = (rule, value, callback) => { if (!value) { this.setState({ help: '请输入密码!', visible: !!value, }); callback('error'); } else { this.setState({ help: '', }); if (!this.state.visible) { this.setState({ visible: !!value, }); } if (value.length < 6) { callback('error'); } else { const { form } = this.props; if (value && this.state.confirmDirty) { form.validateFields(['confirm'], { force: true }); } callback(); } } }; changePrefix = (value) => { this.setState({ prefix: value, }); }; renderPasswordProgress = () => { const { form } = this.props; const value = form.getFieldValue('password'); const passwordStatus = this.getPasswordStatus(); return value && value.length ? ( <div className={styles[`progress-${passwordStatus}`]}> <Progress status={passwordProgressMap[passwordStatus]} className={styles.progress} strokeWidth={6} percent={value.length * 10 > 100 ? 100 : value.length * 10} showInfo={false} /> </div> ) : null; }; render() { const { form, submitting } = this.props; const { getFieldDecorator } = form; const { count, prefix } = this.state; return ( <div className={styles.main}> <h3>注册</h3> <Form onSubmit={this.handleSubmit}> <FormItem> {getFieldDecorator('mail', { rules: [ { required: true, message: '请输入邮箱地址!', }, { type: 'email', message: '邮箱地址格式错误!', }, ], })(<Input size="large" placeholder="邮箱" />)} </FormItem> <FormItem help={this.state.help}> <Popover content={ <div style={{ padding: '4px 0' }}> {passwordStatusMap[this.getPasswordStatus()]} {this.renderPasswordProgress()} <div style={{ marginTop: 10 }}> 请至少输入 6 个字符。请不要使用容易被猜到的密码。 </div> </div> } overlayStyle={{ width: 240 }} placement="right" visible={this.state.visible} > {getFieldDecorator('password', { rules: [ { validator: this.checkPassword, }, ], })( <Input size="large" type="password" placeholder="至少6位密码,区分大小写" /> )} </Popover> </FormItem> <FormItem> {getFieldDecorator('confirm', { rules: [ { required: true, message: '请确认密码!', }, { validator: this.checkConfirm, }, ], })(<Input size="large" type="password" placeholder="确认密码" />)} </FormItem> <FormItem> <InputGroup compact> <Select size="large" value={prefix} onChange={this.changePrefix} style={{ width: '20%' }} > <Option value="86">+86</Option> <Option value="87">+87</Option> </Select> {getFieldDecorator('mobile', { rules: [ { required: true, message: '请输入手机号!', }, { pattern: /^1\d{10}$/, message: '手机号格式错误!', }, ], })( <Input size="large" style={{ width: '80%' }} placeholder="11位手机号" /> )} </InputGroup> </FormItem> <FormItem> <Row gutter={8}> <Col span={16}> {getFieldDecorator('captcha', { rules: [ { required: true, message: '请输入验证码!', }, ], })(<Input size="large" placeholder="验证码" />)} </Col> <Col span={8}> <Button size="large" disabled={count} className={styles.getCaptcha} onClick={this.onGetCaptcha} > {count ? `${count} s` : '获取验证码'} </Button> </Col> </Row> </FormItem> <FormItem> <Button size="large" loading={submitting} className={styles.submit} type="primary" htmlType="submit" > 注册 </Button> <Link className={styles.login} to="/user/login"> 使用已有账户登录 </Link> </FormItem> </Form> </div> ); } }
packages/slate-react/src/components/default-placeholder.js
6174/slate
import React from 'react' import SlateTypes from 'slate-prop-types' import Types from 'prop-types' /** * Default placeholder. * * @type {Component} */ class DefaultPlaceholder extends React.Component { /** * Property types. * * @type {Object} */ static propTypes = { editor: Types.object.isRequired, isSelected: Types.bool.isRequired, node: SlateTypes.node.isRequired, parent: SlateTypes.node.isRequired, readOnly: Types.bool.isRequired, state: SlateTypes.state.isRequired, } /** * Render. * * @return {Element} */ render() { const { editor, state } = this.props if (!editor.props.placeholder) return null if (state.document.getBlocks().size > 1) return null const style = { pointerEvents: 'none', display: 'inline-block', width: '0', maxWidth: '100%', whiteSpace: 'nowrap', opacity: '0.333', } return ( <span contentEditable={false} style={style}> {editor.props.placeholder} </span> ) } } /** * Export. * * @type {Component} */ export default DefaultPlaceholder
analysis/paladinprotection/src/modules/features/WordOfGloryTiming.js
anom0ly/WoWAnalyzer
import SPELLS from 'common/SPELLS'; import SelfHealTimingGraph from 'parser/shared/modules/features/SelfHealTimingGraph'; import React from 'react'; class WordOfGloryTiming extends SelfHealTimingGraph { constructor(...args) { super(...args); this.selfHealSpell = SPELLS.WORD_OF_GLORY; this.tabTitle = 'Selfheal Timing'; this.tabURL = 'selfheal-timings'; } render() { return <SelfHealTimingGraph />; } } export default WordOfGloryTiming;
src/components/CurrentWeather/index.js
Junicus/fcc-localweather
import React from 'react'; import './currentweather.css'; export function CurrentWeather(props) { const { temp, city, summary, apparentTemp } = props; return ( <div className="currentweather"> <div className="currentweather-weather-container"> <div className="currentweather-temp">{temp.toFixed()}&deg;</div> <div className="currentweather-summary-container"> <div className="currentweather-summary">{summary}</div> <div className="currentweather-appears">Feels like: {apparentTemp.toFixed()}&deg;</div> </div> </div> <div className="currentweather-city">{city}</div> </div> ); }
src/components/date-picker/index.js
summerstream/react-practise
import React, { Component } from 'react'; import styles from './styles.js'; import Mask from '../mask/index' import DateUtil from '../../util/date.js'; import DatePickerCore from './core.js'; class DatePicker extends Component{ constructor(props){ super(props); this.state={ hidden:this.props.hidden, current:this.props.current || new Date() } this.onCancel=this.onCancel.bind(this); this.onConfirm = this.onConfirm.bind(this); this.onChange = this.onChange.bind(this); } onCancel(e){ this.setState({ hidden:true }); this.props.onCancel && this.props.onCancel(); } onConfirm(e){ this.setState({ hidden:true }); this.props.onConfirm && this.props.onConfirm(this.state.current); } onChange(d){ this.setState({ current:d }); this.props.onChange && this.props.onChange(d); } componentWillReceiveProps(nextProps){ this.setState({ hidden:nextProps.hidden, current:this.props.current || new Date() }); } render(){ return ( <div> <Mask hidden={this.state.hidden} onClick={this.onCancel} /> <div ref="container" style={{...styles.container, transform:this.state.hidden?'translate(0,100%)':'translate(0,0)' }}> <div style={styles.header}> <div style={{flex:'1',textAlign:'left'}} onClick={this.onCancel} >取消</div> <div style={{flex:'1',textAlign:'right'}} onClick={this.onConfirm} >确定</div> </div> { <DatePickerCore current={this.props.current} onChange={(d)=>this.onChange(d)} /> } </div> </div> ); } } export default DatePicker;
src/App.js
sansetty2510/bootStrap
import React from 'react'; import { Button, ButtonToolbar, Modal } from 'react-bootstrap'; import Child from './ChildPopUp'; import ButtonGroups from './ButtonGroups'; import MultiSelect from './MultiSelect'; import StatusMenuBar from './StatusMenuBar'; import BootStrapSwitch from './BootStrapSwitch'; import style from '../css/test.css'; const divStyle = { color: '#fff', backgroundColor: '#337ab7', borderColor: '#2e6da4' }; export default class App extends React.Component { constructor(props){ super(props); this.state = { showModal : false, statusMenuBarData : [ { 'id': 1, 'displayName' : 'Menu 1', 'type': 1 }, { 'id': 2, 'displayName' : 'Menu 2', 'type': 2 }, { 'id': 3, 'displayName' : 'Menu 3', 'type': 1 }, { 'id': 4, 'displayName' : 'Menu 4', 'type': 2 }, { 'id': 5, 'displayName' : 'Menu 5', 'type': 2 }, { 'id': 6, 'displayName' : 'Menu 6', 'type': 1 }, { 'id': 7, 'displayName' : 'Menu 7', 'type': 3 }, { 'id': 8, 'displayName' : 'Menu 8', 'type': 1 }, { 'id': 9, 'displayName' : 'Menu 9', 'type': 2 }, { 'id': 10, 'displayName' : 'Menu 10', 'type': 1 }, { 'id': 11, 'displayName' : 'Menu 11', 'type': 2 }, { 'id': 12, 'displayName' : 'Menu 12', 'type': 2 }, { 'id': 13, 'displayName' : 'Menu 13', 'type': 1 }, { 'id': 14, 'displayName' : 'Menu 14', 'type': 3 } ] }; this.close = this.close.bind(this); this.open = this.open.bind(this); this.menuClickItems = this.menuClickItems.bind(this); } close() { this.setState({ showModal: false }); } open() { this.setState({ showModal: true }); } menuClickItems(indexVal){ console.log(indexVal); } render() { return ( <div> <p className={style.chk}>Click to get the full Modal experience!</p> <Button bsStyle="primary" bsSize="small" onClick={this.open}> Launch demo modal </Button> <Modal show={this.state.showModal} onHide={this.close}> <Modal.Header closeButton> <Modal.Title>Modal heading</Modal.Title> </Modal.Header> <Modal.Body> <h4 className="chk">Text in a modal</h4> <p>Duis mollis, est non commodo luctus, nisi erat porttitor ligula.</p> <h4>Popover in a modal</h4> <h4>Tooltips in a modal</h4> <hr /> <h4>Overflowing text to show scroll behavior</h4> <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p> <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p> <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p> <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p> <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p> <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p> <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p> <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p> <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p> <Child/> </Modal.Body> <Modal.Footer> <Button onClick={this.close}>Close</Button> </Modal.Footer> </Modal> <br/> <br/> <BootStrapSwitch/> <ButtonGroups/> <MultiSelect/> <StatusMenuBar dataMenu = {this.state.statusMenuBarData} menuClickItems = {this.menuClickItems} /> </div> ); } }
docs/src/app/components/pages/components/Menu/ExampleSimple.js
ichiohta/material-ui
import React from 'react'; import Paper from 'material-ui/Paper'; import Menu from 'material-ui/Menu'; import MenuItem from 'material-ui/MenuItem'; const style = { display: 'inline-block', margin: '16px 32px 16px 0', }; const MenuExampleSimple = () => ( <div> <Paper style={style}> <Menu> <MenuItem primaryText="Maps" /> <MenuItem primaryText="Books" /> <MenuItem primaryText="Flights" /> <MenuItem primaryText="Apps" /> </Menu> </Paper> <Paper style={style}> <Menu> <MenuItem primaryText="Refresh" /> <MenuItem primaryText="Help &amp; feedback" /> <MenuItem primaryText="Settings" /> <MenuItem primaryText="Sign out" /> </Menu> </Paper> </div> ); export default MenuExampleSimple;
src/components/app.js
priyankasarma/ReduxPart2SimpleStarter
import React, { Component } from 'react'; import BookList from './../containers/book-list'; import BookDetail from './../containers/book-detail'; export default class App extends Component { render() { return ( <div> <BookList /> <BookDetail /> </div> ); } }
example/Example.js
ClearScholar/react-native-htmlview
import React from 'react'; import {StyleSheet, View, Text, ScrollView} from 'react-native'; import HTMLView from '../'; function renderNode(node, index) { if (node.name == 'iframe') { return ( <View key={index} style={{width: 200, height: 200}}> <Text> {node.attribs.src} </Text> </View> ); } } const htmlContent = ` <div class="comment"> <span class="c00"> <b><i>&gt; Dwayne’s only companion at night was a Labrador retriever named Sparky.</i></b> <p> <i>Sparky could not wag his tail-because of an automobile accident many years ago, so he had no way of telling other dogs how friendly he was. He opened the door of the cage, something Bill couldn’t have done in a thousand years. Bill flew over to a windowsill. <b>The undippable flag was a beauty, and the anthem and the vacant motto might not have mattered much, if it weren’t for this: a lot of citizens were so ignored and cheated and insulted that they thought they might be in the wrong country, or even on the wrong planet, that some terrible mistake had been made. </p> <p> [1] <a href="https://code.facebook.com/posts/1505962329687926/flow-a-new-static-type-checker-for-javascript/" rel="nofollow">https://code.facebook.com/posts/1505962329687926/flow-a-new-...</a> </p> <img src="https://i.redd.it/1l01wjsv22my.jpg" width="400" height="400" /> <h1>Dwayne’s only companion at night</h1> <h2>Dwayne’s only companion at night</h2> <h3>Dwayne’s only companion at night</h3> <h4>Dwayne’s only companion at night</h4> <h5>Dwayne’s only companion at night</h5> <h6>Dwayne’s only companion at night</h6> ayyy <iframe src="google.com" /> </span> </div> `; export default class App extends React.Component { render() { return ( <ScrollView style={styles.container}> <HTMLView value={htmlContent} renderNode={renderNode} /> </ScrollView> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', }, });
higher-demo/dva-antd/todo-list/src/router.js
CFshuming/react-demo-gather
import React from 'react'; import { Router, Route } from 'dva/router'; import IndexPage from './routes/IndexPage'; import List from './routes/List.js'; function RouterConfig({ history }) { return ( <Router history={history}> <Route path="/" component={IndexPage} /> <Route path="/list" component={List} /> </Router> ); } export default RouterConfig;
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
olhakhomyak/cvMaker
import React from 'react'; import { render } from 'react-dom'; // 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'; render(<HelloWorld />, document.getElementById('react-root'));
app/javascript/mastodon/features/notifications/components/notification.js
esetomo/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import StatusContainer from '../../../containers/status_container'; import AccountContainer from '../../../containers/account_container'; import { FormattedMessage } from 'react-intl'; import Permalink from '../../../components/permalink'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { HotKeys } from 'react-hotkeys'; export default class Notification extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { notification: ImmutablePropTypes.map.isRequired, hidden: PropTypes.bool, onMoveUp: PropTypes.func.isRequired, onMoveDown: PropTypes.func.isRequired, onMention: PropTypes.func.isRequired, }; handleMoveUp = () => { const { notification, onMoveUp } = this.props; onMoveUp(notification.get('id')); } handleMoveDown = () => { const { notification, onMoveDown } = this.props; onMoveDown(notification.get('id')); } handleOpen = () => { const { notification } = this.props; if (notification.get('status')) { this.context.router.history.push(`/statuses/${notification.get('status')}`); } else { this.handleOpenProfile(); } } handleOpenProfile = () => { const { notification } = this.props; this.context.router.history.push(`/accounts/${notification.getIn(['account', 'id'])}`); } handleMention = e => { e.preventDefault(); const { notification, onMention } = this.props; onMention(notification.get('account'), this.context.router.history); } getHandlers () { return { moveUp: this.handleMoveUp, moveDown: this.handleMoveDown, open: this.handleOpen, openProfile: this.handleOpenProfile, mention: this.handleMention, reply: this.handleMention, }; } renderFollow (account, link) { return ( <HotKeys handlers={this.getHandlers()}> <div className='notification notification-follow focusable' tabIndex='0'> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <i className='fa fa-fw fa-user-plus' /> </div> <FormattedMessage id='notification.follow' defaultMessage='{name} followed you' values={{ name: link }} /> </div> <AccountContainer id={account.get('id')} withNote={false} hidden={this.props.hidden} /> </div> </HotKeys> ); } renderMention (notification) { return ( <StatusContainer id={notification.get('status')} withDismiss hidden={this.props.hidden} onMoveDown={this.handleMoveDown} onMoveUp={this.handleMoveUp} /> ); } renderFavourite (notification, link) { return ( <HotKeys handlers={this.getHandlers()}> <div className='notification notification-favourite focusable' tabIndex='0'> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <i className='fa fa-fw fa-iine star-icon' /> </div> <FormattedMessage id='notification.favourite' defaultMessage='{name} favourited your status' values={{ name: link }} /> </div> <StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={!!this.props.hidden} /> </div> </HotKeys> ); } renderReblog (notification, link) { return ( <HotKeys handlers={this.getHandlers()}> <div className='notification notification-reblog focusable' tabIndex='0'> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <i className='fa fa-fw fa-retweet' /> </div> <FormattedMessage id='notification.reblog' defaultMessage='{name} boosted your status' values={{ name: link }} /> </div> <StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={this.props.hidden} /> </div> </HotKeys> ); } render () { const { notification } = this.props; const account = notification.get('account'); const displayNameHtml = { __html: account.get('display_name_html') }; const link = <Permalink className='notification__display-name' href={account.get('url')} title={account.get('acct')} to={`/accounts/${account.get('id')}`} dangerouslySetInnerHTML={displayNameHtml} />; switch(notification.get('type')) { case 'follow': return this.renderFollow(account, link); case 'mention': return this.renderMention(notification); case 'favourite': return this.renderFavourite(notification, link); case 'reblog': return this.renderReblog(notification, link); } return null; } }
src/main/js/builder/views/components/SponsorAssetsForm.js
Bernardo-MG/dreadball-toolkit-webpage
import React from 'react'; import PropTypes from 'prop-types'; import { injectIntl } from 'react-intl'; import Columns from 'grommet/components/Columns'; import FormField from 'grommet/components/FormField'; import CheerleadersInput from 'builder/assets/containers/CheerleadersInput'; import CoachingDiceInput from 'builder/assets/containers/CoachingDiceInput'; import MediBotInput from 'builder/assets/containers/MediBotInput'; import NastySurpriseCardInput from 'builder/assets/containers/NastySurpriseCardInput'; import SpecialMoveCardInput from 'builder/assets/containers/SpecialMoveCardInput'; import WagerInput from 'builder/assets/containers/WagerInput'; import teamBuilderMessages from 'i18n/teamBuilder'; const SponsorAssetsForm = (props) => <Columns> <FormField label={props.intl.formatMessage(teamBuilderMessages.coaching_dice)}> <CoachingDiceInput id='coaching_dice' name='coaching_dice' min={0} max={100}/> </FormField> <FormField label={props.intl.formatMessage(teamBuilderMessages.special_move_cards)}> <SpecialMoveCardInput id='special_move_cards' name='special_move_cards' min={0} max={100}/> </FormField> <FormField label={props.intl.formatMessage(teamBuilderMessages.nasty_surprise_cards)}> <NastySurpriseCardInput id='nasty_surprise_cards' name='nasty_surprise_cards' min={0} max={100}/> </FormField> <FormField label={props.intl.formatMessage(teamBuilderMessages.wagers)}> <WagerInput id='wagers' name='wagers' min={0} max={100}/> </FormField> <FormField label={props.intl.formatMessage(teamBuilderMessages.medibots)}> <MediBotInput id='medibots' name='medibots' min={0} max={100}/> </FormField> <FormField label={props.intl.formatMessage(teamBuilderMessages.cheerleaders)}> <CheerleadersInput id='cheerleaders' name='cheerleaders' min={0} max={100}/> </FormField> </Columns>; SponsorAssetsForm.propTypes = { intl: PropTypes.object.isRequired }; export default injectIntl(SponsorAssetsForm);
jenkins-design-language/src/js/components/material-ui/svg-icons/action/settings.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionSettings = (props) => ( <SvgIcon {...props}> <path d="M19.43 12.98c.04-.32.07-.64.07-.98s-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.12-.22-.39-.3-.61-.22l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.23-.09-.49 0-.61.22l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98s.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.12.22.39.3.61.22l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1c.23.09.49 0 .61-.22l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zM12 15.5c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5 3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z"/> </SvgIcon> ); ActionSettings.displayName = 'ActionSettings'; ActionSettings.muiName = 'SvgIcon'; export default ActionSettings;
app/javascript/mastodon/features/account_timeline/index.js
masarakki/mastodon
import React from 'react'; import { connect } from 'react-redux'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { fetchAccount } from '../../actions/accounts'; import { expandAccountFeaturedTimeline, expandAccountTimeline } from '../../actions/timelines'; import StatusList from '../../components/status_list'; import LoadingIndicator from '../../components/loading_indicator'; import Column from '../ui/components/column'; import HeaderContainer from './containers/header_container'; import ColumnBackButton from '../../components/column_back_button'; import { List as ImmutableList } from 'immutable'; import ImmutablePureComponent from 'react-immutable-pure-component'; const mapStateToProps = (state, { params: { accountId }, withReplies = false }) => { const path = withReplies ? `${accountId}:with_replies` : accountId; return { statusIds: state.getIn(['timelines', `account:${path}`, 'items'], ImmutableList()), featuredStatusIds: withReplies ? ImmutableList() : state.getIn(['timelines', `account:${accountId}:pinned`, 'items'], ImmutableList()), isLoading: state.getIn(['timelines', `account:${path}`, 'isLoading']), hasMore: state.getIn(['timelines', `account:${path}`, 'hasMore']), }; }; export default @connect(mapStateToProps) class AccountTimeline extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, statusIds: ImmutablePropTypes.list, featuredStatusIds: ImmutablePropTypes.list, isLoading: PropTypes.bool, hasMore: PropTypes.bool, withReplies: PropTypes.bool, }; componentWillMount () { const { params: { accountId }, withReplies } = this.props; this.props.dispatch(fetchAccount(accountId)); if (!withReplies) { this.props.dispatch(expandAccountFeaturedTimeline(accountId)); } this.props.dispatch(expandAccountTimeline(accountId, { withReplies })); } componentWillReceiveProps (nextProps) { if ((nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) || nextProps.withReplies !== this.props.withReplies) { this.props.dispatch(fetchAccount(nextProps.params.accountId)); if (!nextProps.withReplies) { this.props.dispatch(expandAccountFeaturedTimeline(nextProps.params.accountId)); } this.props.dispatch(expandAccountTimeline(nextProps.params.accountId, { withReplies: nextProps.params.withReplies })); } } handleLoadMore = maxId => { this.props.dispatch(expandAccountTimeline(this.props.params.accountId, { maxId, withReplies: this.props.withReplies })); } render () { const { shouldUpdateScroll, statusIds, featuredStatusIds, isLoading, hasMore } = this.props; if (!statusIds && isLoading) { return ( <Column> <LoadingIndicator /> </Column> ); } return ( <Column> <ColumnBackButton /> <StatusList prepend={<HeaderContainer accountId={this.props.params.accountId} />} scrollKey='account_timeline' statusIds={statusIds} featuredStatusIds={featuredStatusIds} isLoading={isLoading} hasMore={hasMore} onLoadMore={this.handleLoadMore} shouldUpdateScroll={shouldUpdateScroll} /> </Column> ); } }
node_modules/react-bootstrap/src/SplitButton.js
gitoneman/react-home
import React from 'react'; import classSet from 'classnames'; import BootstrapMixin from './BootstrapMixin'; import DropdownStateMixin from './DropdownStateMixin'; import Button from './Button'; import ButtonGroup from './ButtonGroup'; import DropdownMenu from './DropdownMenu'; const SplitButton = React.createClass({ mixins: [BootstrapMixin, DropdownStateMixin], propTypes: { pullRight: React.PropTypes.bool, title: React.PropTypes.node, href: React.PropTypes.string, id: React.PropTypes.string, target: React.PropTypes.string, dropdownTitle: React.PropTypes.node, onClick: React.PropTypes.func, onSelect: React.PropTypes.func, disabled: React.PropTypes.bool }, getDefaultProps() { return { dropdownTitle: 'Toggle dropdown' }; }, render() { let groupClasses = { 'open': this.state.open, 'dropup': this.props.dropup }; let button = ( <Button {...this.props} ref="button" onClick={this.handleButtonClick} title={null} id={null}> {this.props.title} </Button> ); let dropdownButton = ( <Button {...this.props} ref="dropdownButton" className={classSet(this.props.className, 'dropdown-toggle')} onClick={this.handleDropdownClick} title={null} href={null} target={null} id={null}> <span className="sr-only">{this.props.dropdownTitle}</span> <span className="caret" /> <span style={{letterSpacing: '-.3em'}}>&nbsp;</span> </Button> ); return ( <ButtonGroup bsSize={this.props.bsSize} className={classSet(groupClasses)} id={this.props.id}> {button} {dropdownButton} <DropdownMenu ref="menu" onSelect={this.handleOptionSelect} aria-labelledby={this.props.id} pullRight={this.props.pullRight}> {this.props.children} </DropdownMenu> </ButtonGroup> ); }, handleButtonClick(e) { if (this.state.open) { this.setDropdownState(false); } if (this.props.onClick) { this.props.onClick(e, this.props.href, this.props.target); } }, handleDropdownClick(e) { e.preventDefault(); this.setDropdownState(!this.state.open); }, handleOptionSelect(key) { if (this.props.onSelect) { this.props.onSelect(key); } this.setDropdownState(false); } }); export default SplitButton;
src/Input.js
deerawan/react-bootstrap
import React from 'react'; import InputBase from './InputBase'; import * as FormControls from './FormControls'; import deprecationWarning from './utils/deprecationWarning'; class Input extends InputBase { render() { if (this.props.type === 'static') { deprecationWarning('Input type=static', 'StaticText'); return <FormControls.Static {...this.props} />; } return super.render(); } } Input.propTypes = { type: React.PropTypes.string }; export default Input;
packages/wix-style-react/src/Grid/docs/ExampleTwoHalfWidthRows.js
wix/wix-style-react
import React from 'react'; import { Container, Row, Col, Card, Box } from 'wix-style-react'; export default () => ( <Container> <Row> <Col span={6}> <Card showShadow> <Card.Header title="Card Title" /> <Card.Content> <Box height="100px" /> </Card.Content> </Card> </Col> </Row> <Row> <Col span={6}> <Card showShadow> <Card.Header title="Card Title" /> <Card.Content> <Box height="100px" /> </Card.Content> </Card> </Col> </Row> </Container> );
app/javascript/packs/app.js
tamouse/r5api-react-starter
import React from 'react' import {render} from 'react-dom' import Main from './app/' const App = () => (<div><Main /></div>) document.addEventListener('DOMContentLoaded', () => (render(<App/>, document.body.appendChild(document.createElement('div')))))
app/javascript/mastodon/features/lists/index.js
lynlynlynx/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 Column from '../ui/components/column'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import { fetchLists } from '../../actions/lists'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ColumnLink from '../ui/components/column_link'; import ColumnSubheading from '../ui/components/column_subheading'; import NewListForm from './components/new_list_form'; import { createSelector } from 'reselect'; import ScrollableList from '../../components/scrollable_list'; const messages = defineMessages({ heading: { id: 'column.lists', defaultMessage: 'Lists' }, subheading: { id: 'lists.subheading', defaultMessage: 'Your lists' }, }); const getOrderedLists = createSelector([state => state.get('lists')], lists => { if (!lists) { return lists; } return lists.toList().filter(item => !!item).sort((a, b) => a.get('title').localeCompare(b.get('title'))); }); const mapStateToProps = state => ({ lists: getOrderedLists(state), }); export default @connect(mapStateToProps) @injectIntl class Lists extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, lists: ImmutablePropTypes.list, intl: PropTypes.object.isRequired, multiColumn: PropTypes.bool, }; componentWillMount () { this.props.dispatch(fetchLists()); } render () { const { intl, shouldUpdateScroll, lists, multiColumn } = this.props; if (!lists) { return ( <Column> <LoadingIndicator /> </Column> ); } const emptyMessage = <FormattedMessage id='empty_column.lists' defaultMessage="You don't have any lists yet. When you create one, it will show up here." />; return ( <Column bindToDocument={!multiColumn} icon='list-ul' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <NewListForm /> <ScrollableList scrollKey='lists' shouldUpdateScroll={shouldUpdateScroll} emptyMessage={emptyMessage} prepend={<ColumnSubheading text={intl.formatMessage(messages.subheading)} />} bindToDocument={!multiColumn} > {lists.map(list => <ColumnLink key={list.get('id')} to={`/timelines/list/${list.get('id')}`} icon='list-ul' text={list.get('title')} />, )} </ScrollableList> </Column> ); } }
templates/webapp/client/scripts/router.js
pwlmaciejewski/slush-fragphace-webapp
import React from 'react'; import { IndexRoute, Route } from 'react-router'; import App from './containers/App.jsx'; export default function router(store) { return ( <Route path="/" component={ App }> </Route> ); }
src/neuralNetwork/networkModals/DigitModal.js
csenn/nn-visualizer
import _ from 'lodash'; import React from 'react'; import Dialog from 'material-ui/lib/dialog'; import RaisedButton from 'material-ui/lib/raised-button'; import { connect } from 'react-redux'; import { setDigitModal } from '../data/neuralNetworkActions'; import DigitModalChart from './DigitModalChart'; class LayerModal extends React.Component { constructor(props) { super(props); this._onClose = this._onClose.bind(this); this._renderChart = this._renderChart.bind(this); this._renderChartTitle = this._renderChartTitle.bind(this); } _onClose() { this.props.dispatch(setDigitModal(null)); } _renderChart(isOpen) { if (!isOpen) { return false; } const { testResults } = this.props.selectedSnapshot; const count = testResults[this.props.digitModalIndex]; const data = []; for (let i = 0; i < 10; i++) { data.push(count.wrong[i] ? count.wrong[i].length : 0); } return <DigitModalChart data={data}/>; } _renderChartTitle(isOpen) { if (!isOpen) { return false; } const { testResults } = this.props.selectedSnapshot; const count = testResults[this.props.digitModalIndex]; const correct = count.correct.length; const wrong = _.flattenDeep(_.values(count.wrong)).length; const accuracy = Math.round(correct / (correct + wrong) * 1000) / 10; return ( <div> <div style={{ marginBottom: '5px', fontSize: '17px'}}> <strong>{correct} / {correct + wrong}</strong> ({accuracy}%) were categorized correctly </div> <div style={{color: 'rgb(160,160,160)', marginBottom: '15px'}}> Wrong guesses by digit shown below </div> </div> ); } render() { const isOpen = _.isNumber(this.props.digitModalIndex); const title = ( <div style={{ padding: '20px', fontSize: '24px', fontFamily: 'raleway', borderBottom: '1px solid rgb(230,230,230)', marginBottom: '15px' }}> Network accuracy of digit: <span style={{fontSize: '35px', fontWeight: 'bold', marginLeft: '10px'}}> {this.props.digitModalIndex} </span> </div> ); const actions = [ <RaisedButton label="Done" secondary onClick={this._onClose} /> ]; return ( <Dialog title={title} actions={actions} modal={false} open={isOpen} bodyStyle={{ minHeight: '600px', position: 'relative', padding: 0, fontFamily: 'raleway', textAlign: 'center' }} onRequestClose={this.handleClose} > {this._renderChartTitle(isOpen)} {this._renderChart(isOpen)} </Dialog> ); } } function mapStateToProps(state) { return { digitModalIndex: state.neuralNetwork.digitModal }; } export default connect(mapStateToProps)(LayerModal);
app/containers/FeaturePage/index.js
jwarning/react-ci-test
/* * FeaturePage * * List all the features */ import React from 'react'; import Helmet from 'react-helmet'; import { FormattedMessage } from 'react-intl'; import H1 from 'components/H1'; import messages from './messages'; import List from './List'; import ListItem from './ListItem'; import ListItemTitle from './ListItemTitle'; export default class FeaturePage extends React.Component { // eslint-disable-line react/prefer-stateless-function // Since state and props are static, // there's no need to re-render this component shouldComponentUpdate() { return false; } render() { return ( <div> <Helmet title="Feature Page" meta={[ { name: 'description', content: 'Feature page of React.js Boilerplate application' }, ]} /> <H1> <FormattedMessage {...messages.header} /> </H1> <List> <ListItem> <ListItemTitle> <FormattedMessage {...messages.scaffoldingHeader} /> </ListItemTitle> <p> <FormattedMessage {...messages.scaffoldingMessage} /> </p> </ListItem> <ListItem> <ListItemTitle> <FormattedMessage {...messages.feedbackHeader} /> </ListItemTitle> <p> <FormattedMessage {...messages.feedbackMessage} /> </p> </ListItem> <ListItem> <ListItemTitle> <FormattedMessage {...messages.routingHeader} /> </ListItemTitle> <p> <FormattedMessage {...messages.routingMessage} /> </p> </ListItem> <ListItem> <ListItemTitle> <FormattedMessage {...messages.networkHeader} /> </ListItemTitle> <p> <FormattedMessage {...messages.networkMessage} /> </p> </ListItem> <ListItem> <ListItemTitle> <FormattedMessage {...messages.intlHeader} /> </ListItemTitle> <p> <FormattedMessage {...messages.intlMessage} /> </p> </ListItem> </List> </div> ); } }
src/svg-icons/hardware/gamepad.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareGamepad = (props) => ( <SvgIcon {...props}> <path d="M15 7.5V2H9v5.5l3 3 3-3zM7.5 9H2v6h5.5l3-3-3-3zM9 16.5V22h6v-5.5l-3-3-3 3zM16.5 9l-3 3 3 3H22V9h-5.5z"/> </SvgIcon> ); HardwareGamepad = pure(HardwareGamepad); HardwareGamepad.displayName = 'HardwareGamepad'; HardwareGamepad.muiName = 'SvgIcon'; export default HardwareGamepad;
src/js/components/icons/base/FormUpload.js
kylebyerly-hp/grommet
// (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}-form-upload`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'form-upload'); 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="M6,14.1818182 L6,17.4545455 L18,17.4545455 L18,14.1818182 M12,6 L12,14 M8.18181818,9.81818182 L12,6 L15.8181818,9.81818182"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'FormUpload'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/js/components/navigation/right-menu.js
v3rt1go/jsse-client
'use strict'; import React from 'react'; import LanguageNavItem from './language-nav-item'; import UserNavItem from './user-nav-item'; import CartNavItem from './cart-nav-item'; const LeftMenu = () => { return ( <div className="right menu"> <LanguageNavItem /> <UserNavItem /> <CartNavItem /> </div> ); }; export default LeftMenu;
src/mSupplyMobileApp.js
sussol/mobile
/* eslint-disable react/forbid-prop-types */ /* eslint-disable no-undef */ /** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import React from 'react'; import PropTypes from 'prop-types'; import DeviceInfo from 'react-native-device-info'; import { connect } from 'react-redux'; import { BluetoothStatus } from 'react-native-bluetooth-status'; import { AppState, View } from 'react-native'; import { Scheduler } from 'sussol-utilities'; import { BleManager, DevBleManager } from '@openmsupply/msupply-ble-service'; import Settings from './settings/MobileAppSettings'; import Database from './database/BaseDatabase'; import { UIDatabase } from './database'; import { SETTINGS_KEYS } from './settings'; import { MainStackNavigator, Pages } from './navigation/Navigator'; import { ROUTES } from './navigation'; import { Synchroniser, PostSyncProcessor, SyncModal } from './sync'; import { migrateDataToVersion } from './dataMigration'; import { SyncAuthenticator, UserAuthenticator } from './authentication'; import { LoadingIndicatorContext } from './context/LoadingIndicatorContext'; import { selectTitle } from './selectors/supplierCredit'; import { selectCurrentUser } from './selectors/user'; import { selectUsingVaccines } from './selectors/modules'; import { version as appVersion } from '../package.json'; import { syncCompleteTransaction, setSyncError, openSyncModal } from './actions/SyncActions'; import { FinaliseActions } from './actions/FinaliseActions'; import { UserActions } from './actions'; import { SupplierCreditActions } from './actions/SupplierCreditActions'; import { Spinner } from './widgets'; import { ModalContainer, FinaliseModal, LoginModal } from './widgets/modals'; import { FirstUsePage } from './pages'; import { SupplierCredit } from './widgets/modalChildren/SupplierCredit'; import globalStyles, { SUSSOL_ORANGE } from './globalStyles'; import { BreachDisplay } from './widgets/modalChildren/BreachDisplay'; import { selectIsBreachModalOpen, selectBreachModalTitle } from './selectors/breach'; import { BreachActions } from './actions/BreachActions'; import { RowDetail } from './widgets/RowDetail'; import { PermissionActions } from './actions/PermissionActions'; import BleService from './bluetooth/BleService'; import TemperatureLogManager from './bluetooth/TemperatureLogManager'; import SensorManager from './bluetooth/SensorManager'; import { VaccineDataAccess } from './bluetooth/VaccineDataAccess'; import { UtilService } from './database/utilities/utilService'; import { SensorDownloadActions } from './actions/Bluetooth/SensorDownloadActions'; import BreachManager from './bluetooth/BreachManager'; import { selectIsPassivelyDownloadingTemps } from './selectors/Bluetooth/sensorDownload'; import LoggerService from './utilities/logging'; const BLUETOOTH_SYNC_INTERVAL = 60 * 1000; // 1 minute in milliseconds. const AUTHENTICATION_INTERVAL = 10 * 60 * 1000; // 10 minutes in milliseconds. SensorManager(new VaccineDataAccess(UIDatabase), new UtilService()); TemperatureLogManager(new VaccineDataAccess(UIDatabase), new UtilService()); BreachManager(new VaccineDataAccess(UIDatabase), new UtilService()); (async () => { const isEmulator = await DeviceInfo.isEmulator(); if (isEmulator) { // eslint-disable-next-line no-console console.log('Emulator detected - Init Dev BleManager'); BleService(new DevBleManager()); } else { BleService(new BleManager(), LoggerService.createLogger('BleService')); } })(); class MSupplyMobileAppContainer extends React.Component { constructor(props, ...otherArgs) { super(props, ...otherArgs); migrateDataToVersion(UIDatabase, Settings); this.databaseVersion = Settings.get(SETTINGS_KEYS.APP_VERSION); this.userAuthenticator = new UserAuthenticator(UIDatabase, Settings); this.syncAuthenticator = new SyncAuthenticator(Settings); this.synchroniser = new Synchroniser( Database, this.syncAuthenticator, Settings, props.dispatch ); this.postSyncProcessor = new PostSyncProcessor(UIDatabase, Settings); this.scheduler = new Scheduler(); const isInitialised = this.synchroniser.isInitialised(); this.scheduler.schedule(this.synchronise, this.synchroniser.syncInterval()); this.scheduler.schedule(() => { const { currentUser } = this.props; if (currentUser !== null) { // Only re-authenticate if currently logged in. this.userAuthenticator.reauthenticate(this.onAuthentication); } }, AUTHENTICATION_INTERVAL); this.state = { isInitialised, isLoading: false, appState: null, }; } componentDidUpdate() { const { dispatch, requestBluetooth } = this.props; this.startTemperatureDownload(); BluetoothStatus.addListener(requestBluetooth); dispatch(PermissionActions.checkPermissions()); } componentDidMount = () => { this.startTemperatureDownload(); AppState.addEventListener('change', this.onAppStateChange); }; componentWillUnmount = () => { const { usingVaccines, dispatch } = this.props; dispatch(SensorDownloadActions.stopPassiveDownloadJob()); if (usingVaccines) BluetoothStatus.removeListener(); AppState.removeEventListener('change', this.onAppStateChange); this.scheduler.clearAll(); }; onAppStateChange = nextAppState => { const { appState } = this.state; const { dispatch } = this.props; if (nextAppState?.match(/inactive|background/)) dispatch(UserActions.setTime()); if (appState?.match(/inactive|background/) && nextAppState === 'active') { dispatch(PermissionActions.checkPermissions()); dispatch(UserActions.active()); } this.setState({ appState: nextAppState }); }; onAuthentication = user => { const { dispatch } = this.props; dispatch(UserActions.login(user)); this.postSyncProcessor.setUser(user); }; onInitialised = () => { this.setState({ isInitialised: true }); this.postSyncProcessor.processAnyUnprocessedRecords(); }; runWithLoadingIndicator = async functionToRun => { // We here set up an asynchronous promise that will be resolved after a timeout // of 1 millisecond. This allows a fraction of a delay for the javascript thread // to unblock and allow the spinner animation to start up. The |functionToRun| should // not be run inside a |setTimeout| as that relegates to a lower priority, resulting // in very slow performance. await new Promise(resolve => { this.setState({ isLoading: true }, () => setTimeout(resolve, 1)); }); await functionToRun(); this.setState({ isLoading: false }); }; synchronise = async () => { const { dispatch } = this.props; const { isInitialised } = this.state; if (!isInitialised) return; try { const syncUrl = UIDatabase.getSetting(SETTINGS_KEYS.SYNC_URL); const syncSiteName = UIDatabase.getSetting(SETTINGS_KEYS.SYNC_SITE_NAME); const syncSitePasswordHash = UIDatabase.getSetting(SETTINGS_KEYS.SYNC_SITE_PASSWORD_HASH); await this.syncAuthenticator.authenticate(syncUrl, syncSiteName, null, syncSitePasswordHash); // True if most recent call to |this.synchroniser.synchronise()| failed. const lastSyncFailed = this.synchroniser.lastSyncFailed(); const lastPostSyncProcessingFailed = this.postSyncProcessor.lastPostSyncProcessingFailed(); await this.synchroniser.synchronise(); if (lastSyncFailed || lastPostSyncProcessingFailed) { // If last sync was interrupted, it did not enter this block. If the app was closed, it did // not store any records left in the sync queue, so tables should be checked for unprocessed // records. If the last processing of the record queue was interrupted by app crash then all // records need to be checked. this.postSyncProcessor.processAnyUnprocessedRecords(); } else { this.postSyncProcessor.processRecordQueue(); } dispatch(syncCompleteTransaction()); } catch (error) { dispatch(setSyncError(error.message)); } }; startTemperatureDownload() { const { dispatch, usingVaccines, syncTemperatures } = this.props; if (usingVaccines) { const { isPassivelyDownloadingTemps } = this.props; if (!isPassivelyDownloadingTemps) { this.scheduler.schedule(syncTemperatures, BLUETOOTH_SYNC_INTERVAL); dispatch(SensorDownloadActions.startPassiveDownloadJob()); } } } renderLoadingIndicator = () => { const { isLoading } = this.state; return ( <View style={globalStyles.loadingIndicatorContainer}> <Spinner isSpinning={isLoading} color={SUSSOL_ORANGE} /> </View> ); }; render() { const { currentUser, closeSupplierCreditModal, supplierCreditModalOpen, creditTitle, isBreachModalOpen, closeBreachModal, breachModalTitle, } = this.props; const { isInitialised, isLoading } = this.state; if (!isInitialised) { return <FirstUsePage synchroniser={this.synchroniser} onInitialised={this.onInitialised} />; } // If this database hasn't got any version setup then update with the current app's version. if (this.databaseVersion.length === 0) { Settings.set(SETTINGS_KEYS.APP_VERSION, appVersion); } return ( <LoadingIndicatorContext.Provider value={this.runWithLoadingIndicator}> <View style={globalStyles.appBackground}> <MainStackNavigator.Navigator initialRouteName={ROUTES.MENU}> {Pages} </MainStackNavigator.Navigator> <FinaliseModal /> <SyncModal onPressManualSync={this.synchronise} /> <LoginModal authenticator={this.userAuthenticator} settings={Settings} isAuthenticated={!!currentUser} onAuthentication={this.onAuthentication} /> {isLoading && this.renderLoadingIndicator()} <ModalContainer isVisible={supplierCreditModalOpen} onClose={closeSupplierCreditModal} title={creditTitle} > <SupplierCredit /> </ModalContainer> <ModalContainer isVisible={isBreachModalOpen} onClose={closeBreachModal} title={breachModalTitle} > <BreachDisplay /> </ModalContainer> <RowDetail /> </View> </LoadingIndicatorContext.Provider> ); } } const mapDispatchToProps = dispatch => { const openFinaliseModal = () => dispatch(FinaliseActions.openModal()); const closeFinaliseModal = () => dispatch(FinaliseActions.closeModal()); const closeSupplierCreditModal = () => dispatch(SupplierCreditActions.close()); const onOpenSyncModal = () => dispatch(openSyncModal()); const closeBreachModal = () => dispatch(BreachActions.close()); const syncTemperatures = () => dispatch(SensorDownloadActions.startDownloadAll()); const requestBluetooth = newStatus => dispatch(PermissionActions.requestBluetooth(newStatus)); return { requestBluetooth, syncTemperatures, dispatch, onOpenSyncModal, openFinaliseModal, closeFinaliseModal, closeSupplierCreditModal, closeBreachModal, }; }; const mapStateToProps = state => { const { finalise, supplierCredit } = state; const { open: supplierCreditModalOpen } = supplierCredit; const { finaliseModalOpen } = finalise; const usingVaccines = selectUsingVaccines(state); const isBreachModalOpen = selectIsBreachModalOpen(state); const currentUser = selectCurrentUser(state); const isPassivelyDownloadingTemps = selectIsPassivelyDownloadingTemps(state); const breachModalTitle = selectBreachModalTitle(state); return { usingVaccines, isPassivelyDownloadingTemps, currentUser, finaliseModalOpen, supplierCreditModalOpen, isBreachModalOpen, breachModalTitle, creditTitle: selectTitle(state), }; }; MSupplyMobileAppContainer.defaultProps = { currentUser: null, creditTitle: '', }; MSupplyMobileAppContainer.propTypes = { usingVaccines: PropTypes.bool.isRequired, requestBluetooth: PropTypes.func.isRequired, syncTemperatures: PropTypes.func.isRequired, isPassivelyDownloadingTemps: PropTypes.bool.isRequired, dispatch: PropTypes.func.isRequired, currentUser: PropTypes.object, closeSupplierCreditModal: PropTypes.func.isRequired, supplierCreditModalOpen: PropTypes.bool.isRequired, creditTitle: PropTypes.string, isBreachModalOpen: PropTypes.bool.isRequired, closeBreachModal: PropTypes.func.isRequired, breachModalTitle: PropTypes.string.isRequired, }; export default connect(mapStateToProps, mapDispatchToProps)(MSupplyMobileAppContainer);
app/containers/UGTourPage/AttendantImportPopover.js
perry-ugroop/ugroop-react-dup2
/** * Created by yunzhou on 26/11/2016. */ import React from 'react'; import A from 'components/A'; import { OverlayTrigger, Popover } from 'react-bootstrap'; import messages from './messages'; function AttendantImportpopover(props) { const tourId = props.tourId; const attendType = props.attendType; let title = ''; if (attendType === 'participant') { title = messages.importParticipantsLink.defaultMessage; } else if (attendType === 'organizer') { title = messages.importOrganizerLink.defaultMessage; } else if (attendType === 'viewer') { title = messages.importViewersLink.defaultMessage; } const attendantPopover = ( <Popover id={`add+${attendType}+_popover+${tourId}`} title={title}> <strong>This is tab import {attendType}</strong> Check this info. </Popover> ); return ( <OverlayTrigger trigger="click" placement="bottom" overlay={attendantPopover}> <A href="#">{title}</A> </OverlayTrigger> ); } AttendantImportpopover.propTypes = { tourId: React.PropTypes.any, attendType: React.PropTypes.any, }; export default AttendantImportpopover;
modules/gui/src/app/home/body/process/recipe/opticalMosaic/sceneAreaMarker.js
openforis/sepal
import {MapObject} from 'app/home/map/mapLayer' import {RecipeActions} from 'app/home/body/process/recipe/opticalMosaic/opticalMosaicRecipe' import {compose} from 'compose' import PropTypes from 'prop-types' import React from 'react' import styles from './sceneAreasLayer.module.css' class _SceneAreaMarker extends React.Component { constructor(props) { super(props) const {map, recipeId, polygon} = props const {google} = map.getGoogle() this.recipeActions = RecipeActions(recipeId) const gPolygon = new google.maps.Polygon({ paths: polygon.map(([lat, lng]) => new google.maps.LatLng(lat, lng)), fillColor: '#000000', fillOpacity: 0.4, strokeColor: '#636363', strokeOpacity: 0.6, strokeWeight: 1 }) const bounds = new google.maps.LatLngBounds() gPolygon.getPaths().getArray().forEach(path => path.getArray().forEach(latLng => bounds.extend(latLng) )) this.polygon = gPolygon this.center = bounds.getCenter() } renderSceneAreaCount(fontSize) { const {map, selectedSceneCount} = this.props const zoom = map.getZoom() return zoom > 4 ? <text x={0} y={0} fontSize={fontSize} textAnchor='middle' dominantBaseline='middle'>{selectedSceneCount}</text> : null } render() { const {map, loading} = this.props const zoom = map.getZoom() const scale = Math.min(1, Math.pow(zoom, 2.5) / Math.pow(8, 2.5)) const size = `${1.5 * 4 * scale}em` const {googleMap} = map.getGoogle() return ( <MapObject map={map} lat={this.center.lat()} lng={this.center.lng()} width={size} height={size} className={[styles.sceneArea, loading ? styles.loading : null].join(' ')}> <svg height={size} width={size} viewBox={'-100 -100 200 200'} onMouseOver={() => !loading && this.polygon.setMap(googleMap)} onMouseLeave={() => this.polygon.setMap(null)} onClick={() => loading ? null : this.selectScenes()}> <circle cx={0} cy={0} r={80}/> {this.renderSceneAreaCount(20 + 20 / scale)} </svg> </MapObject> ) } // shouldComponentUpdate(nextProps) { // return !isEqualIgnoreFunctions(nextProps, this.props) // } selectScenes() { const {sceneAreaId, sceneSelection} = this.props this.recipeActions.setSceneSelection(sceneAreaId).dispatch() sceneSelection.activate() } } export const SceneAreaMarker = compose( _SceneAreaMarker ) SceneAreaMarker.propTypes = { polygon: PropTypes.array, recipeId: PropTypes.string, sceneAreaId: PropTypes.string, sceneSelection: PropTypes.object, selectedSceneCount: PropTypes.number }
src/routes/app/routes/xdashboard/components/AquisitionChart.js
ahthamrin/kbri-admin2
import React from 'react'; import ReactEcharts from 'components/ReactECharts'; import CHARTCONFIG from 'constants/ChartConfig'; const data = [{ value: 350, name: 'Display', }, { value: 560, name: 'Social' }, { value: 980, name: 'Direct' }, { value: 760, name: 'Search' }, { value: 320, name: 'Referrals' }]; const pie = {}; pie.options = { tooltip: { show: true, trigger: 'item', formatter: '{b}: {c} ({d}%)' }, legend: { show: false, orient: 'vertical', x: 'right', data: ['Display', 'Social', 'Direct', 'Search', 'Referrals'], }, series: [{ type: 'pie', selectedMode: 'single', radius: ['40%', '52%'], color: [ '#EFE04C', '#69D361', '#47DAB5', '#4AC3D6', '#5EA1DA', ], label: { normal: { position: 'outside', formatter: '{b}', textStyle: { fontSize: 12 } } }, labelLine: { normal: { show: true } }, data, markPint: { symbol: 'diamond', data: [{symbol: 'diamond', }] } }] }; const Chart = () => ( <ReactEcharts style={{height: '400px'}} option={pie.options} showLoading={false} /> ); module.exports = Chart;
src/views/ContractBusiness/Payment/PaymentDetails.js
bruceli1986/contract-react
import React from 'react' import PageHeader from 'components/PageHeader' import PaymentBasicInfo from 'components/PaymentBasicInfo' import PaymentDetailsInfo from 'components/PaymentDetails' import FileListTable from 'components/FileListTable' import TaskHistory from 'components/TaskHistory' import WithdrawButton from 'components/WithdrawButton' import {Modal} from 'react-bootstrap' import FlowDiagram from 'components/FlowDiagram' import ReportForm from 'components/ReportForm' /** 支付单明细页面*/ class PaymentDetails extends React.Component { constructor (props, context) { super(props, context) this.state = { paymentInfo: null, poItemCost: [], history: [], loadHistory: false, loadAssociateFile: false, associateFile: [], showFlowDiagram: false, showReportForm: false, canWithDraw: false } } componentDidMount () { this.fetchPaymentInfo() this.fetchPaymentDetails() this.fetchAssociateFile() this.fetchTaskHistory() this.fetchWithDrawStatus() } hideFlowDiagram = () => { this.setState({showFlowDiagram: false}) } hideReportForm = () => { this.setState({showReportForm: false}) } showFlowDiagram = () => { this.setState({showFlowDiagram: true}) } showReportForm = () => { this.setState({showReportForm: true}) } fetchPaymentInfo () { var businessId = this.props.location.query.businessId var param = businessId.split('||') var systemCode = param[0] var poNo = param[1] var invoiceNo = param[2] this.serverRequest = $.get('/qdp/payment/invoice/info', { systemCode: systemCode, poNo: poNo, invoiceNo: invoiceNo }, function (result) { this.setState({ paymentInfo: result }) }.bind(this)) } fetchPaymentDetails () { var businessId = this.props.location.query.businessId var param = businessId.split('||') var systemCode = param[0] var poNo = param[1] var invoiceNo = param[2] this.serverRequest = $.get('/qdp/payment/invoice/poItem', { systemCode: systemCode, poNo: poNo, invoiceNo: invoiceNo, type: 'read' }, function (result) { this.setState({ poItemCost: result }) }.bind(this)) } fetchTaskHistory () { this.setState({ loadHistory: false }) this.serverRequest = $.get('/qdp/payment/bpm/task/history', this.props.location.query, function (result) { this.setState({ history: result, loadHistory: true }) }.bind(this)) } fetchAssociateFile () { this.setState({ loadAssociateFile: false }) this.serverRequest = $.get('/qdp/payment/file/associate', this.props.location.query, function (result) { this.setState({ associateFile: result, loadAssociateFile: true }) }.bind(this)) } fetchWithDrawStatus () { var param = { taskId: this.props.location.query.taskId, processDefinitionId: this.props.location.query.processDefinitionId, activityId: this.props.location.query.activityId } if (param.taskId && param.processDefinitionId && param.activityId) { this.serverRequest = $.get('/qdp/payment/bpm/task/canWithdraw', param, function (result) { this.setState({ canWithDraw: result }) }.bind(this)) } } renderButtons () { if (this.props.location.isComplete) { return ( <div> <div className='col-md-3 col-md-offset-3'> <button type='button' className='btn btn-default payment-button' onClick={this.showFlowDiagram} >查看流程图</button> </div> <div className='col-md-3'> <button type='button' className='btn btn-default payment-button' onClick={this.showReportForm} >打印支付单</button> </div> </div> ) } else if (this.state.canWithDraw && !this.props.location.isComplete) { return ( <div> <div className='col-md-3 col-md-offset-3'> <button type='button' className='btn btn-default payment-button' onClick={this.showFlowDiagram} >查看流程图</button> </div> <div className='col-md-3'> <WithdrawButton taskId={this.props.location.query.taskId} /> </div> </div> ) } else if (!this.state.canWithDraw && !this.props.location.isComplete) { return ( <div className='col-md-4 col-md-offset-4'> <button type='button' className='btn btn-default payment-button' onClick={this.showFlowDiagram} >查看流程图</button> </div> ) } } render () { var businessId = this.props.location.query.businessId var param = businessId.split('||') var systemCode = param[0] var systemId = param[3] return ( <div className='container'> <div className='row'> <div className='col-md-12'> <PageHeader title='合同支付审签流程' subTitle='支付单明细' /> </div> </div> <div className='row'> <div className='col-md-12'> <h3 className='form-section-header'>1.支付单基本信息</h3> <PaymentBasicInfo payment={this.state.paymentInfo} system={{id: systemId, code: systemCode}} /> </div> </div> <div className='row'> <div className='col-md-12'> <h3 className='form-section-header'>2.支付单明细</h3> <PaymentDetailsInfo items={this.state.poItemCost} /> </div> </div> <div className='row'> <div className='col-md-12'> <h3 className='form-section-header'>3.相关附件</h3> <FileListTable files={this.state.associateFile} loaded={this.state.loadAssociateFile} deletable={false} /> </div> </div> <div className='row'> <div className='col-md-12'> <h3 className='form-section-header'>4.流转历史</h3> <TaskHistory history={this.state.history} loaded={this.state.loadHistory} /> </div> </div> <div className='row'> { this.renderButtons() } </div> <Modal bsSize='large' show={this.state.showFlowDiagram} onHide={this.hideFlowDiagram}> <Modal.Header closeButton> <Modal.Title>流程图</Modal.Title> </Modal.Header> <Modal.Body> <FlowDiagram processInstanceId={this.props.location.query.processInstanceId} processDefinitionId={this.props.location.query.processDefinitionId} appName='informationCenterPayment' /> </Modal.Body> </Modal> <Modal bsSize='large' show={this.state.showReportForm} onHide={this.hideReportForm}> <Modal.Header closeButton> <Modal.Title>选择打印参数</Modal.Title> </Modal.Header> <Modal.Body> <ReportForm processInstanceId={this.props.location.query.processInstanceId + ''} businessId={this.props.location.query.businessId} onClickCancel={this.hideReportForm} /> </Modal.Body> </Modal> </div> ) } } export default PaymentDetails
src/client/react/user/views/Challenge/ResponsePhrase.js
bwyap/ptc-amazing-g-race
import React from 'react'; import PropTypes from 'prop-types'; import autobind from 'core-decorators/es/autobind'; import { connect } from 'react-redux'; import { graphql } from 'react-apollo'; import { Button, Dialog } from '@blueprintjs/core'; import FormInput from '../../../../../../lib/react/components/forms/FormInput'; import { addResponse } from '../../../../graphql/response'; @graphql(addResponse('ok'), { name: 'MutationAddResponse' }) @autobind class ResponsePhrase extends React.Component { static propTypes = { itemKey: PropTypes.string.isRequired, challengeKey: PropTypes.string.isRequired, teamName: PropTypes.string, onSuccess: PropTypes.func } state = { showWindow: false, phrase: '', uploading: false, uploadError: null } async uploadPhrase() { this.setState({ uploading: true, uploadError: null }); const { MutationAddResponse, challengeKey, itemKey } = this.props; const variables = { challengeKey: challengeKey, itemKey: itemKey, responseType: 'phrase', responseValue: this.state.phrase }; try { await MutationAddResponse({variables}); this.setState({ uploading: false, showWindow: false }); if (this.props.onSuccess) this.props.onSuccess(); } catch (err) { this.setState({ uploading: false, uploadError: err.toString() }); } } toggleWindow() { if (!this.state.uploading) { this.setState((prevState) => { return { showWindow: !prevState.showWindow, uploadError: null }; }); } } handlePhraseChange(e) { this.setState({phrase: e.target.value }); } render() { return ( <div style={{marginTop:'0.5rem'}}> <Button text='Enter a phrase' className='pt-fill pt-intent-primary' iconName='highlight' onClick={this.toggleWindow}/> <Dialog title='Enter a phrase' isOpen={this.state.showWindow} onClose={this.toggleWindow}> <div className='pt-dialog-body'> { this.state.uploadError ? <div className='pt-callout pt-intent-danger pt-icon-error'> <h5>Upload error</h5> {this.state.uploadError} </div> :null } <FormInput id='phrase' value={this.state.phrase} onChange={this.handlePhraseChange} large disabled={this.state.uploading}/> <Button className='pt-fill pt-intent-primary' text='Confirm' onClick={this.uploadPhrase} loading={this.state.uploading} disabled={!this.state.phrase}/> </div> </Dialog> </div> ); } } export default ResponsePhrase;
src/Components/Header/Menu/index.js
AdamSoucie/Ignis
import React from 'react'; import MenuItem from './MenuItem'; import './style.css'; class Menu extends React.Component { render() { return( <nav className="menu-container"> <ul className="menu"> <MenuItem text="About" link="/about" /> <MenuItem text="Blog" link="/blog" /> <MenuItem text="Contact" link="/contact" /> </ul> </nav> ); } } export default Menu;
src/app/components/TestCardNumber.js
blobor/buka
import React from 'react' import { IconMenu, MenuItem, IconButton } from 'material-ui' import { NavigationMoreVert } from 'material-ui/svg-icons' const TEST_CARD_NUMBERS = [ '01-2167-30-92545', '26-2167-19-35623', '29-2167-26-31433' ] const renredCardNumbers = () => { return TEST_CARD_NUMBERS .map((number, index) => <MenuItem key={index} value={number} primaryText={number} />) } const TestCardNumber = ({ onChange }) => { return ( <IconMenu onChange={onChange} iconButtonElement={ <IconButton> <NavigationMoreVert /> </IconButton> } anchorOrigin={{horizontal: 'right', vertical: 'top'}} targetOrigin={{horizontal: 'right', vertical: 'top'}}> { renredCardNumbers() } </IconMenu> ) } export default TestCardNumber
examples/todomvc/index.js
dsimmons/redux
import 'babel-core/polyfill'; import React from 'react'; import Root from './containers/Root'; import 'todomvc-app-css/index.css'; React.render( <Root />, document.getElementById('root') );
docs/src/app/components/pages/components/Slider/ExampleAxis.js
w01fgang/material-ui
import React from 'react'; import Slider from 'material-ui/Slider'; const styles = { root: { display: 'flex', height: 124, flexDirection: 'row', justifyContent: 'space-around', }, }; /** * The orientation of the slider can be reversed and rotated using the `axis` prop. */ const SliderExampleAxis = () => ( <div style={styles.root}> <Slider style={{height: 100}} axis="y" defaultValue={0.5} /> <Slider style={{width: 200}} axis="x-reverse" /> <Slider style={{height: 100}} axis="y-reverse" defaultValue={1} /> </div> ); export default SliderExampleAxis;
amp-stories/src/component/view/MediaComponentsStoryView/pages/StoryPage5.js
ampproject/samples
import React from 'react'; import styled from 'styled-components'; import AmpStoryPage from '/component/amp/AmpStoryPage'; import AmpImage from '/component/amp/AmpImage'; import {TextHighlightBanner} from '../shared'; import {BannerWrapper} from '/component/base/TextHighlight'; const PhotoPileWrapper = styled.div` grid-row-start: upper-third; grid-row-end: middle-third; display: grid; grid-template-columns: 1fr; justify-items: center; align-items: center; position: relative; `; const PilePhoto = ({width, height, delay, id, src, rotate, after}) => { return ( <div id={id} animate-in="fade-in" animate-in-duration="0.4s" animate-in-delay={delay} animate-in-after={after} animate-in-timing-function="ease-in-out" style={{gridArea: '1 / 1 / 1 / 1', width, height}} > <div animate-in="zoom-out" animate-in-duration="0.4s" animate-in-delay={delay} animate-in-after={after} animate-in-timing-function="ease-in-out" scale-start="2" scale-end="1" style={{width, height}} > <AmpImage src={src} style={{transform: `rotate(${rotate})`, border: '5px solid white'}} height={height} width={width} layout="fixed" /> </div> </div> ); }; const StoryPage5 = () => ( <AmpStoryPage id="photo-pile" backgroundColor="storiesBkLightBlue"> <amp-story-grid-layer template="thirds"> <PhotoPileWrapper> <PilePhoto id="art3" src="/static/stories/story3/3E-abstract-art3.jpg" delay="0.1s" rotate="347deg" height="322px" width="214px" /> <PilePhoto id="art2" src="/static/stories/story3/3E-abstract-art2.jpg" rotate="350deg" after="art3" height="210px" width="315px" /> <PilePhoto id="art1" src="/static/stories/story3/3E-abstract-art1.jpg" rotate="9deg" after="art2" height="246px" width="246px" /> </PhotoPileWrapper> <BannerWrapper grid-area="lower-third" style={{alignSelf: 'end'}}> <TextHighlightBanner>You have all the</TextHighlightBanner> <TextHighlightBanner>freedom you need</TextHighlightBanner> <TextHighlightBanner>to be creative</TextHighlightBanner> </BannerWrapper> </amp-story-grid-layer> </AmpStoryPage> ); export default StoryPage5;
admin/client/App/shared/Popout/PopoutPane.js
trentmillar/keystone
/** * Render a popout pane, calls props.onLayout when the component mounts */ import React from 'react'; import blacklist from 'blacklist'; import classnames from 'classnames'; var PopoutPane = React.createClass({ displayName: 'PopoutPane', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, onLayout: React.PropTypes.func, }, getDefaultProps () { return { onLayout: () => {}, }; }, componentDidMount () { this.props.onLayout(this.refs.el.offsetHeight); }, render () { const className = classnames('Popout__pane', this.props.className); const props = blacklist(this.props, 'className', 'onLayout'); return ( <div ref="el" className={className} {...props} /> ); }, }); module.exports = PopoutPane;
apps/mk-app-home/apps/mk-app-home-shortcuts/action.js
ziaochina/mk-demo
import React from 'react' import { action as MetaAction, AppLoader } from 'mk-meta-engine' import config from './config' import funImg from './img/photo.png' class action { constructor(option) { this.metaAction = option.metaAction this.config = config.current } onInit = ({ component, injections }) => { this.component = component this.injections = injections injections.reduce('init') } getFunImg = () => funImg openList = () => { this.open('列表','mk-app-person-list') } openCard = () => { this.open('卡片', 'mk-app-person-card') } openVoucher = () => { this.open('单据','mk-app-voucher') } openComplexTable = () => { this.open('复杂表格','mk-app-complex-table') } openEditableTable = () => { this.open('可编辑表格','mk-app-editable-table') } open = (name,appName) => { this.component.props.setPortalContent && this.component.props.setPortalContent(name, appName) } } export default function creator(option) { const metaAction = new MetaAction(option), o = new action({ ...option, metaAction }), ret = { ...metaAction, ...o } metaAction.config({ metaHandlers: ret }) return ret }
src/components/Loading/Loading.js
markwylde/react-demo
import React from 'react'; const Loading = () => <div className="container text-center loading"> <i className="fa fa-spinner fa-spin"></i> Loading... </div>; Loading.displayName = 'Loading'; module.exports = Loading;
client/modules/Post/__tests__/components/PostListItem.spec.js
thanhdatvo/tuoihoctro.react
import React from 'react'; import test from 'ava'; import sinon from 'sinon'; import PostListItem from '../../components/Post/PostListItem/PostListItem'; import { mountWithIntl, shallowWithIntl } from '../../../../util/react-intl-test-helper'; const post = { name: 'Prashant', title: 'Hello Mern', slug: 'hello-mern', cuid: 'f34gb2bh24b24b2', content: "All cats meow 'mern!'" }; const props = { post, onDelete: () => {}, }; test('renders properly', t => { const wrapper = shallowWithIntl( <PostListItem {...props} /> ); t.truthy(wrapper.hasClass('single-post')); t.is(wrapper.find('Link').first().prop('children'), post.title); t.regex(wrapper.find('.author-name').first().text(), new RegExp(post.name)); t.is(wrapper.find('.post-desc').first().text(), post.content); }); test('has correct props', t => { const wrapper = mountWithIntl( <PostListItem {...props} /> ); t.deepEqual(wrapper.prop('post'), props.post); t.is(wrapper.prop('onClick'), props.onClick); t.is(wrapper.prop('onDelete'), props.onDelete); }); test('calls onDelete', t => { const onDelete = sinon.spy(); const wrapper = shallowWithIntl( <PostListItem post={post} onDelete={onDelete} /> ); wrapper.find('.post-action > a').first().simulate('click'); t.truthy(onDelete.calledOnce); });
pages/home/index.js
lifeiscontent/OpenPoGoUI
import React from 'react'; import io from 'socket.io-client'; import Map from '../../components/Map'; import { ConfigModal, PokemonModal } from '../../components/Modal'; import './style.css'; let noop = () => { console.log('no op'); }; class HomePage extends React.Component { constructor(props) { super(props); noop = noop.bind(this); // bind dom callbacks to `this` component this.handleChangeConfigModal = this.handleChangeConfigModal.bind(this); this.handleSaveConfigModal = this.handleSaveConfigModal.bind(this); this.handleClickSettings = this.handleClickSettings.bind(this); this.handleClickPokemon = this.handleClickPokemon.bind(this); this.handleCloseModal = this.handleCloseModal.bind(this); this.handleTransferPokemon = this.handleTransferPokemon.bind(this); this.handleFavoritePokemon = this.handleFavoritePokemon.bind(this); } componentWillMount() { const defaults = { candy: {}, currentModal: 'config', eggs_count: 0, followPlayer: true, isConnected: false, isInitialized: false, level: 0, player: {}, pokemon: [], pokemonCaught: [], pokestops: [], position: [], positions: [], socketUrl: 'http://localhost:8000', storage: {}, username: 'Anonymous', }; let state = localStorage.getItem('OpenPoGoUI'); if (state) { state = JSON.parse(state); } else { state = { ...defaults }; } this.state = state; } componentDidMount() { this.initSocket(); this.socket.emit('pokemon_list'); } componentWillUnmount() { this.socket.disconnect(); } getModal(state) { switch (state.currentModal) { case 'pokemon': return ( <PokemonModal handleClose={this.handleCloseModal} handleFavoritePokemon={this.handleFavoritePokemon} handleTransferPokemon={this.handleTransferPokemon} pokemon={state.pokemon} /> ); case 'eggs': return ( <ConfigModal followPlayer={state.followPlayer} handleChange={this.handleChangeConfigModal} handleClose={this.handleCloseModal} handleSave={this.handleSaveConfigModal} socketUrl={state.socketUrl} /> ); case 'items': return ( <ConfigModal followPlayer={state.followPlayer} handleChange={this.handleChangeConfigModal} handleClose={this.handleCloseModal} handleSave={this.handleSaveConfigModal} socketUrl={state.socketUrl} /> ); case 'config': return ( <ConfigModal followPlayer={state.followPlayer} handleChange={this.handleChangeConfigModal} handleClose={this.handleCloseModal} handleSave={this.handleSaveConfigModal} socketUrl={state.socketUrl} /> ); default: return null; } } handleChangeConfigModal(event) { const { target } = event; const state = {}; if (target.type === 'checkbox' || target.type === 'radio') { state[target.name] = target.checked; } else { state[target.name] = target.value; } this.setState(state); } handleSaveConfigModal() { if (this.socket.io.uri !== this.state.socketUrl) { this.socket.disconnect(); localStorage.setItem('socketUrl', this.state.socketUrl); this.initSocket(); } } handleClickPokemon() { this.setState({ currentModal: this.state.currentModal !== 'pokemon' ? 'pokemon' : null, }); } handleClickSettings() { this.setState({ currentModal: this.state.currentModal !== 'config' ? 'config' : null, }); } handleCloseModal(event) { if (event.target !== event.currentTarget) { return; } console.dir(event); this.setState({ currentModal: null }); } handleTransferPokemon(id) { console.log('transfer_pokemon', id); this.socket.emit('transfer_pokemon', { id }); } handleFavoritePokemon(id, favorite) { console.log('favorite_pokemon', id, favorite); this.socket.emit('favorite_pokemon', { id, favorite }); } initSocket() { const self = this; this.socket = io(`${this.state.socketUrl}/event`); this.socket.on('connect', (message) => { console.log('connect', message); self.setState({ isConnected: true, currentModal: null }); }); this.socket.on('disconnect', (message) => { console.log('disconnect', message); self.setState({ isConnected: false }); }); this.socket.on('bot_initialized', (message) => { const state = { position: message.coordinates, positions: [message.coordinates], player: { ...message.player, username: message.username, }, storage: message.storage, isInitialized: true, }; console.log('bot_initialized', message, state); self.setState(state); }); this.socket.on('pokemon_settings', (message) => { console.log('pokemon_settings', message); self.setState(message); }); this.socket.on('player_stats', (message) => { console.log('player_stats', message); self.setState(message); }); this.socket.on('position', (message) => { console.log('position', message); const state = { positions: [...self.state.positions, message.coordinates], position: message.coordinates, }; self.setState(state); }); this.socket.on('pokestops', (message) => { console.log('pokestops', message); self.setState(message); }); this.socket.on('pokestops_visited', (message) => { console.log('pokestops_visited', message); self.setState(message); }); this.socket.on('pokemon_caught', (message) => { const pokemon = { ...message.pokemon, ...message.position }; console.log('pokemon_caught', message, pokemon); self.setState({ pokemonCaught: [...self.state.pokemonCaught, pokemon] }); self.socket.emit('pokemon_list'); // fetch new list }); this.socket.on('transfered_pokemon', (message) => { console.log('transfered_pokemon', message); self.socket.emit('pokemon_list'); // fetch new list }); this.socket.on('pokemon_evolved', (message) => { const monster = { ...message.pokemon, evolution: message.evolution }; console.log('pokemon_evolved', message, monster); self.socket.emit('pokemon_list'); // fetch new list }); this.socket.on('inventory_list', (message) => { console.log('inventory_list', message); self.setState(message); }); this.socket.on('pokemon_list', (message) => { const state = { ...message }; state.pokemon = state.pokemon.map(pokemon => ( { ...pokemon, favorite: pokemon.favorite === 'True', } )); console.log('pokemon_list', state); self.setState(state); }); this.socket.on('eggs_list', (message) => { console.log('eggs_list', message); self.setState(message); }); this.socket.on('pokemon_found', (message) => { console.log('pokemon_found', message); self.setState(message); }); this.socket.on('player_update', (message) => { console.log('player_update', message); self.setState(message); }); } render() { localStorage.setItem('OpenPoGoUI', JSON.stringify(this.state)); const { followPlayer, isInitialized, player, pokemonCaught, pokestops, position, positions, } = this.state; let map = isInitialized > 0 ? <Map followPlayer={followPlayer} handleClickAvatar={noop} handleClickEggs={noop} handleClickInventory={noop} handleClickPokemon={this.handleClickPokemon} handleClickSettings={this.handleClickSettings} player={player} pokemonCaught={pokemonCaught} pokestops={pokestops} position={position} positions={positions} /> : null; let modal = this.getModal(this.state); return ( <div className="wrapper"> {map} {modal} </div> ); } } export default HomePage;
src/parser/shaman/restoration/modules/talents/AncestralVigor.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import fetchWcl from 'common/fetchWclApi'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import Icon from 'common/Icon'; import { formatDuration, formatPercentage } from 'common/format'; import SPECS from 'game/SPECS'; import StatisticBox from 'interface/others/StatisticBox'; import LazyLoadStatisticBox, { STATISTIC_ORDER } from 'interface/others/LazyLoadStatisticBox'; import STATISTIC_CATEGORY from 'interface/others/STATISTIC_CATEGORY'; import Analyzer from 'parser/core/Analyzer'; import Combatants from 'parser/shared/modules/Combatants'; import { EventType } from 'parser/core/Events'; const ANCESTRAL_VIGOR_INCREASED_MAX_HEALTH = 0.1; const HP_THRESHOLD = 1 - 1 / (1 + ANCESTRAL_VIGOR_INCREASED_MAX_HEALTH); class AncestralVigor extends Analyzer { static dependencies = { combatants: Combatants, }; loaded = false; lifeSavingEvents = []; disableStatistics = false; constructor(...args) { super(...args); this.active = !!this.selectedCombatant.hasTalent(SPELLS.ANCESTRAL_VIGOR_TALENT.id); if (!this.active) { return; } const restoShamans = Object.values(this.combatants.players).filter(combatant => (combatant._combatantInfo.specID === SPECS.RESTORATION_SHAMAN.id) && (combatant !== this.selectedCombatant)); if (restoShamans && restoShamans.some(shaman => shaman.hasTalent(SPELLS.ANCESTRAL_VIGOR_TALENT.id))) { this.disableStatistics = true; } } // recursively fetch events until no nextPageTimestamp is returned fetchAll(pathname, query) { const checkAndFetch = async _query => { const json = await fetchWcl(pathname, _query); this.lifeSavingEvents.push(...json.events); if (json.nextPageTimestamp) { return checkAndFetch(Object.assign(query, { start: json.nextPageTimestamp, })); } this.loaded = true; return null; }; return checkAndFetch(query); } load() { // clear array to avoid duplicate entries after switching tabs and clicking it again this.lifeSavingEvents = []; const query = { start: this.owner.fight.start_time, end: this.owner.fight.end_time, filter: `( IN RANGE WHEN type='${EventType.Damage}' AND target.disposition='friendly' AND resources.hitPoints>0 AND 100*resources.hpPercent<=${Math.ceil(10000 * HP_THRESHOLD)} AND 10000*(resources.hitPoints+effectiveDamage)/resources.maxHitPoints>=${Math.floor(10000 * HP_THRESHOLD)} FROM type='${EventType.ApplyBuff}' AND ability.id=${SPELLS.ANCESTRAL_VIGOR.id} AND source.name='${this.selectedCombatant.name}' TO type='${EventType.RemoveBuff}' AND ability.id=${SPELLS.ANCESTRAL_VIGOR.id} AND source.name='${this.selectedCombatant.name}' END )`, }; return this.fetchAll(`report/events/${this.owner.report.code}`, query); } statistic() { // filter out non-players this.loaded && (this.lifeSavingEvents = this.lifeSavingEvents.filter(event => !!this.combatants.players[event.targetID])); const tooltip = this.loaded ? 'The amount of players that would have died without your Ancestral Vigor buff.' : 'Click to analyze how many lives were saved by the ancestral vigor buff.'; if (this.disableStatistics) { return ( <StatisticBox icon={<SpellIcon id={SPELLS.ANCESTRAL_VIGOR.id} />} label="Lives saved" value="Module disabled" tooltip="There were multiple Restoration Shamans with Ancestral Vigor in your raid group, this causes major issues with buff tracking. As the results from this module would be very inaccurate, it was disabled." category={STATISTIC_CATEGORY.TALENTS} position={STATISTIC_ORDER.OPTIONAL(60)} /> ); } else { return ( <LazyLoadStatisticBox loader={this.load.bind(this)} icon={<SpellIcon id={SPELLS.ANCESTRAL_VIGOR.id} />} value={`≈${this.lifeSavingEvents.length}`} label="Lives saved" tooltip={tooltip} category={STATISTIC_CATEGORY.TALENTS} position={STATISTIC_ORDER.OPTIONAL(60)} > <table className="table table-condensed" style={{ fontWeight: 'bold' }}> <thead> <tr> <th>Time</th> <th>Player</th> <th style={{ textAlign: 'center' }}>Ability</th> <th>Health</th> </tr> </thead> <tbody> { this.lifeSavingEvents .map((event, index) => { const combatant = this.combatants.players[event.targetID]; const spec = SPECS[combatant.specId]; const specClassName = spec.className.replace(' ', ''); return ( <tr key={index}> <th scope="row">{formatDuration((event.timestamp - this.owner.fight.start_time) / 1000, 0)}</th> <td className={specClassName}>{combatant.name}</td> <td style={{ textAlign: 'center' }}> <SpellLink id={event.ability.guid} icon={false}> <Icon icon={event.ability.abilityIcon} /> </SpellLink></td> <td>{formatPercentage(event.hitPoints / event.maxHitPoints)}%</td> </tr> ); }, ) } </tbody> </table> </LazyLoadStatisticBox> ); } } } export default AncestralVigor;
examples/basic/src/App.js
azuqua/react-dnd-scrollzone
import React, { Component } from 'react'; import HTML5Backend from 'react-dnd-html5-backend'; import { DragDropContextProvider } from 'react-dnd'; import withScrolling from 'react-dnd-scrollzone'; import DragItem from './DragItem'; import './App.css'; const ScrollingComponent = withScrolling('div'); const ITEMS = [1,2,3,4,5,6,7,8,9,10]; export default class App extends Component { render() { return ( <DragDropContextProvider backend={HTML5Backend}> <ScrollingComponent className="App"> {ITEMS.map(n => ( <DragItem key={n} label={`Item ${n}`} /> ))} </ScrollingComponent> </DragDropContextProvider> ); } }
app/javascript/mastodon/features/list_adder/index.js
tootsuite/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { injectIntl } from 'react-intl'; import { setupListAdder, resetListAdder } from '../../actions/lists'; import { createSelector } from 'reselect'; import List from './components/list'; import Account from './components/account'; import NewListForm from '../lists/components/new_list_form'; // hack const getOrderedLists = createSelector([state => state.get('lists')], lists => { if (!lists) { return lists; } return lists.toList().filter(item => !!item).sort((a, b) => a.get('title').localeCompare(b.get('title'))); }); const mapStateToProps = state => ({ listIds: getOrderedLists(state).map(list=>list.get('id')), }); const mapDispatchToProps = dispatch => ({ onInitialize: accountId => dispatch(setupListAdder(accountId)), onReset: () => dispatch(resetListAdder()), }); export default @connect(mapStateToProps, mapDispatchToProps) @injectIntl class ListAdder extends ImmutablePureComponent { static propTypes = { accountId: PropTypes.string.isRequired, onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, onInitialize: PropTypes.func.isRequired, onReset: PropTypes.func.isRequired, listIds: ImmutablePropTypes.list.isRequired, }; componentDidMount () { const { onInitialize, accountId } = this.props; onInitialize(accountId); } componentWillUnmount () { const { onReset } = this.props; onReset(); } render () { const { accountId, listIds } = this.props; return ( <div className='modal-root__modal list-adder'> <div className='list-adder__account'> <Account accountId={accountId} /> </div> <NewListForm /> <div className='list-adder__lists'> {listIds.map(ListId => <List key={ListId} listId={ListId} />)} </div> </div> ); } }
wail-ui/loadingScreens/notFirstTime/notFirstLoad.js
N0taN3rd/wail
import 'babel-polyfill' import 'react-flex/index.css' import '../../css/wail.css' import React from 'react' import { render } from 'react-dom' import injectTapEventPlugin from 'react-tap-event-plugin' import NotFirstTime from './containers/notFirstTime' import configureStore from '../store/notFirstTime' window.React = React injectTapEventPlugin() const store = configureStore() render(<NotFirstTime store={store} />, document.getElementById('loading'))
src/higherOrders/Pagination.js
Lobos/react-ui
import React from 'react' import { objectAssign } from '../utils/objects' import PropTypes from '../utils/proptypes' import PureRender from '../mixins/PureRender' export default function (Component) { class Pagination extends React.Component { constructor (props) { super(props) this.state = { page: 1 } this.handleChange = this.handleChange.bind(this) } getData (pagination) { let data = this.props.data if (pagination) { const { page, size } = pagination data = data.slice((page - 1) * size, page * size) } return data } handleChange (page) { const { onChange } = this.props.pagination if (typeof onChange === 'function') { onChange(page) } else { this.setState({ page }) } } getPagination (pagination) { if (!pagination || !Array.isArray(this.props.data)) return let props = objectAssign( { page: this.state.page, size: 20, position: 'center', total: this.props.data.length }, pagination.props || pagination ) props.onChange = this.handleChange return props } render () { const { pagination, ...props } = this.props let pagi = this.getPagination(pagination) return ( <Component {...props} data={this.getData(pagi)} pagination={pagi} /> ) } } Pagination.propTypes = { data: PropTypes.array_element_string, pagination: PropTypes.element_object } Pagination.defaultProps = { data: [] } return PureRender()(Pagination) }
src/FAB/NewTaskDialog.js
mkermani144/wanna
import React, { Component } from 'react'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import DatePicker from 'material-ui/DatePicker'; import TextField from 'material-ui/TextField'; import DropDownMenu from 'material-ui/DropDownMenu'; import MenuItem from 'material-ui/MenuItem'; import { green600, grey50 } from 'material-ui/styles/colors'; import persianUtils from 'material-ui-persian-date-picker-utils'; import { HotKeys } from 'react-hotkeys'; import { parse, dayStart, todayStart, dayEnd, } from '../lib/date'; import './NewTaskDialog.css'; class NewTaskDialog extends Component { state = { estimationValue: 1, repetitionValue: 1, task: '', start: todayStart(), end: null, estimation: '', repetition: '', }; keyMap = { confirmAddNewTaskAndFinish: 'shift+enter', confirmAddNewTaskAndContinue: 'enter', }; buttonDisabled = () => !( this.state.task && this.state.end && this.state.estimation && /^[0-9]*$/.test(this.state.estimation) && /^[0-9]*$/.test(this.state.repetition) ); handleEstimationMenuChange = (e, i, value) => { this.setState({ estimationValue: value, }); } handleRepetitionMenuChange = (e, i, value) => { this.setState({ repetitionValue: value, }); } handleTaskChange = (e) => { this.setState({ task: e.target.value, }); } handleStartChange = (e, start) => { this.setState({ start: dayStart(parse(start)), }); } handleEndChange = (e, end) => { this.setState({ end: dayEnd(parse(end)), }); } handleEstimationChange = (e) => { this.setState({ estimation: e.target.value, }); } handleRepetitionChange = (e) => { this.setState({ repetition: e.target.value, }); } handleRequestClose = () => { this.setState({ estimationValue: 1, repetitionValue: 1, task: '', start: todayStart(), end: null, estimation: '', repetition: '', }); this.props.onRequestClose(); } handleRequestAdd = () => { this.props.onRequestAdd(this.state); this.setState({ estimationValue: 1, repetitionValue: 1, task: '', start: todayStart(), end: null, estimation: '', repetition: '', }); } handleRequestFinish = () => { this.handleRequestAdd(); this.handleRequestClose(); } render() { const actions = [ <FlatButton id="add-and-finish" label="Add and finish" primary disabled={this.buttonDisabled()} onClick={this.handleRequestFinish} />, <FlatButton id="add-and-continue" label="Add and continue" primary disabled={this.buttonDisabled()} onClick={this.handleRequestAdd} />, <FlatButton label="Cancel" primary onClick={this.handleRequestClose} />, ]; const dialogTitleStyle = { backgroundColor: green600, color: grey50, cursor: 'default', }; const textFieldStyles = { underlineFocusStyle: { borderColor: green600, }, floatingLabelFocusStyle: { color: green600, }, }; const datePickerStyles = { textFieldStyle: { flex: 1, }, }; const { DateTimeFormat } = global.Intl; const localeProps = this.props.calendarSystem === 'fa-IR' ? { utils: persianUtils, DateTimeFormat } : {}; const handlers = { confirmAddNewTaskAndFinish: () => { !this.buttonDisabled() && this.handleRequestFinish(); }, confirmAddNewTaskAndContinue: () => { !this.buttonDisabled() && this.handleRequestAdd(); }, }; return ( <Dialog className="NewTaskDialog" title="Add new task" actions={actions} titleStyle={dialogTitleStyle} open={this.props.open} onRequestClose={this.props.onRequestClose} > <br /> <p>What do you wanna do?</p> <br /> <div className="textfields"> <HotKeys keyMap={this.keyMap} handlers={handlers} > <TextField floatingLabelText="Task title" fullWidth underlineFocusStyle={textFieldStyles.underlineFocusStyle} floatingLabelFocusStyle={textFieldStyles.floatingLabelFocusStyle} value={this.state.task} onChange={this.handleTaskChange} autoFocus /> <div className="datepicker" id="start"> <DatePicker defaultDate={new Date()} hintText="Start" autoOk locale={this.props.calendarSystem} {...localeProps} firstDayOfWeek={this.props.firstDayOfWeek} textFieldStyle={datePickerStyles.textFieldStyle} minDate={new Date()} onChange={this.handleStartChange} /> </div> <div className="datepicker" id="end"> <DatePicker id="end" hintText="End" autoOk locale={this.props.calendarSystem} {...localeProps} firstDayOfWeek={this.props.firstDayOfWeek} textFieldStyle={datePickerStyles.textFieldStyle} minDate={new Date(this.state.start)} onChange={this.handleEndChange} /> </div> <div className="row"> <TextField id="estimated-time" floatingLabelText="Estimated time" underlineFocusStyle={textFieldStyles.underlineFocusStyle} floatingLabelFocusStyle={textFieldStyles.floatingLabelFocusStyle} value={this.state.estimation} onChange={this.handleEstimationChange} errorText={ /^[0-9]*$/.test(this.state.estimation) ? '' : 'Estimated time should be a number' } /> <DropDownMenu value={this.state.estimationValue} onChange={this.handleEstimationMenuChange} > <MenuItem value={1} primaryText="Minutes" /> <MenuItem value={60} primaryText="Hours" /> </DropDownMenu> </div> <div className="row"> <TextField floatingLabelText="Repetition period" underlineFocusStyle={textFieldStyles.underlineFocusStyle} floatingLabelFocusStyle={textFieldStyles.floatingLabelFocusStyle} value={this.state.repetition} onChange={this.handleRepetitionChange} errorText={ /^[0-9]*$/.test(this.state.repetition) ? '' : 'Repetition period should be a number' } /> <DropDownMenu value={this.state.repetitionValue} onChange={this.handleRepetitionMenuChange} > <MenuItem value={1} primaryText="Days" /> <MenuItem value={7} primaryText="Weeks" /> </DropDownMenu> </div> </HotKeys> </div> </Dialog> ); } } export default NewTaskDialog;
src/bundles/SellerRegistration/components/DisclosuresForm/DisclosuresForm.js
AusDTO/dto-digitalmarketplace-frontend
import React from 'react'; import PropTypes from 'prop-types' import {connect} from 'react-redux'; import { Form } from 'react-redux-form'; import { required } from '../../../../validators'; import Layout from '../../../../shared/Layout'; import BaseForm from '../../../../shared/form/BaseForm'; import SubmitForm from '../../../../shared/form/SubmitForm'; import ErrorBox from '../../../../shared/form/ErrorBox'; import YesNoDetails from '../../../../shared/form/YesNoDetailsField'; import formProps from '../../../../shared/reduxModules/formPropsSelector'; import questions from './questions'; import StepNav from '../StepNav'; import ValidationSummary from '../ValidationSummary'; class DisclosuresForm extends BaseForm { static propTypes = { action: PropTypes.string, csrf_token: PropTypes.string, form: PropTypes.object.isRequired, returnLink: PropTypes.string } render() { const {action, csrf_token, model, form, title, children, onSubmit, onSubmitFailed, nextRoute, submitClicked, applicationErrors, type } = this.props; let hasFocused = false const setFocus = e => { if (!hasFocused) { hasFocused = true e.focus() } } return ( <Layout> <header> <ValidationSummary form={form} applicationErrors={applicationErrors} filterFunc={(ae) => ae.step === 'disclosures' && type === 'edit'} /> <h1 className="au-display-xl" tabIndex="-1">{title}</h1> <p>These responses are not visible on your profile but may be provided to buyers who are considering awarding you a contract. </p> <p>Please note, answering ‘yes’ to any question will not automatically disqualify you from the Digital Marketplace, however our assessors may contact you to request more information.</p> </header> <article role="main"> <ErrorBox submitClicked={submitClicked} model={model} setFocus={setFocus}/> <Form model={model} action={action} method="post" id="Disclosures__create" valid={form.valid} component={SubmitForm} onCustomSubmit={onSubmit} onSubmitFailed={onSubmitFailed} > {csrf_token && ( <input type="hidden" name="csrf_token" id="csrf_token" value={csrf_token}/> )} <YesNoDetails name="structual_changes" id="structual_changes" model={`${model}.disclosures.structual_changes`} label={questions["structual_changes"]} validators={{ required }} messages={{ required: 'Please provide an answer to the Structual Changes question', }} /> <YesNoDetails name="investigations" id="investigations" model={`${model}.disclosures.investigations`} label={questions["investigations"]} validators={{ required }} messages={{ required: 'Please provide an answer to the Investigations question', }} /> <YesNoDetails name="legal_proceedings" id="legal_proceedings" model={`${model}.disclosures.legal_proceedings`} label={questions["legal_proceedings"]} validators={{ required }} messages={{ required: 'Please provide an answer to the Legal Proceedings question', }} /> <YesNoDetails name="insurance_claims" id="insurance_claims" model={`${model}.disclosures.insurance_claims`} label={questions["insurance_claims"]} validators={{ required }} messages={{ required: 'Please provide an answer to the Insurance Claims question', }} /> <YesNoDetails name="conflicts_of_interest" id="conflicts_of_interest" model={`${model}.disclosures.conflicts_of_interest`} label={questions["conflicts_of_interest"]} validators={{ required }} messages={{ required: 'Please provide an answer to the Conflicts of interest question', }} /> <YesNoDetails name="other_circumstances" id="other_circumstances" model={`${model}.disclosures.other_circumstances`} label={questions["other_circumstances"]} validators={{ required }} messages={{ required: 'Please provide an answer to the Other circumstances question', }} /> {children} <StepNav buttonText="Save and continue" to={nextRoute}/> </Form> </article> </Layout> ) } } DisclosuresForm.defaultProps = { title: 'Select any descriptions that apply to your business' } const mapStateToProps = (state) => { return { ...formProps(state, 'disclosuresForm'), applicationErrors: state.application_errors } } export { mapStateToProps, DisclosuresForm as Form } export default connect(mapStateToProps)(DisclosuresForm);
src/table/TableGroup.js
HarvestProfit/harvest-profit-ui
import React from 'react'; import PropTypes from 'prop-types'; /** * Renders a table group used in condensing tables down to smaller screens. */ const TableGroup = (props) => { const classList = ['group', `group-${props.group}`, props.className, props.align, props.size, `grp-${props.condensedSize}`]; return ( <div className={classList.join(' ')} style={props.style}> {props.children} </div> ); }; TableGroup.propTypes = { /** Optional additional class names to apply at the table group level */ className: PropTypes.string, /** One of 3 break point groups */ group: PropTypes.oneOf(['1', '2', '3']), /** Aligns all items under the group */ align: PropTypes.oneOf(['right', 'left', 'center']), /** Sets the size of the group */ size: PropTypes.oneOf(['', 'exsmall', 'small', 'medium', 'large']), /** Optionally set a different size when the column is condensed */ condensedSize: PropTypes.oneOf(['', 'exsmall', 'small', 'medium', 'large']), /** Either TableHeaderItems or TableItems */ children: PropTypes.node, /** Optional styles */ style: PropTypes.shape({}), }; TableGroup.defaultProps = { className: '', group: '1', align: 'left', size: '', condensedSize: '', children: null, style: {}, }; export default TableGroup;
src/entypo/Dribbble.js
cox-auto-kc/react-entypo
import React from 'react'; import EntypoIcon from '../EntypoIcon'; const iconClass = 'entypo-svgicon entypo--Dribbble'; let EntypoDribbble = (props) => ( <EntypoIcon propClass={iconClass} {...props}> <path d="M9.565,7.421C8.207,5.007,6.754,3.038,6.648,2.893C4.457,3.929,2.822,5.948,2.311,8.38C2.517,8.384,5.793,8.423,9.565,7.421z M10.543,10.061c0.102-0.033,0.206-0.064,0.309-0.094c-0.197-0.447-0.412-0.895-0.637-1.336C6.169,9.843,2.287,9.755,2.15,9.751c-0.003,0.084-0.007,0.166-0.007,0.25c0,2.019,0.763,3.861,2.016,5.252l-0.005-0.006C4.154,15.247,6.304,11.433,10.543,10.061z M5.171,16.194V16.19c-0.058-0.045-0.12-0.086-0.178-0.135C5.099,16.14,5.171,16.194,5.171,16.194z M8.118,2.372C8.111,2.374,8.103,2.376,8.103,2.376c0.006-0.002,0.014-0.002,0.014-0.002L8.118,2.372z M15.189,4.104C13.805,2.886,11.99,2.143,10,2.143c-0.639,0-1.258,0.078-1.852,0.221c0.12,0.16,1.595,2.119,2.938,4.584C14.048,5.839,15.167,4.136,15.189,4.104z M10,19.2c-5.08,0-9.199-4.119-9.199-9.199C0.8,4.919,4.919,0.8,10,0.8c5.082,0,9.2,4.119,9.2,9.201C19.2,15.081,15.082,19.2,10,19.2z M11.336,11.286c-4.611,1.607-6.134,4.838-6.165,4.904c1.334,1.041,3.006,1.666,4.828,1.666c1.088,0,2.125-0.221,3.067-0.621c-0.116-0.689-0.573-3.096-1.679-5.967C11.371,11.274,11.354,11.28,11.336,11.286z M11.69,8.12c0.184,0.373,0.358,0.754,0.523,1.139c0.059,0.135,0.114,0.272,0.17,0.406c2.713-0.342,5.385,0.238,5.473,0.256c-0.019-1.863-0.686-3.572-1.787-4.912C16.051,5.032,14.79,6.852,11.69,8.12z M12.861,10.905c1.031,2.836,1.449,5.142,1.529,5.611c1.764-1.191,3.018-3.08,3.367-5.27C17.601,11.196,15.401,10.499,12.861,10.905z"/> </EntypoIcon> ); export default EntypoDribbble;
webapp/app/components/Save/Table/index.js
EIP-SAM/SAM-Solution-Node-js
// // Table page save // import React from 'react'; import { Table } from 'react-bootstrap'; import SaveInstantSaveModal from 'containers/Save/Table/ModalInstantSave'; import SaveInstantRestoreModal from 'containers/Save/Table/ModalInstantRestore'; import ButtonPopover from 'components/ButtonPopover'; import Tr from 'components/Tr'; import Th from 'components/Th'; import Td from 'components/Td'; import styles from './styles.css'; const moment = require('moment'); /* eslint-disable react/prefer-stateless-function */ export default class SaveTable extends React.Component { handleSaveClick(save) { this.props.showInstantSaveModal(); this.props.listUsers([{ id: save.id }]); this.props.dateSave(moment().format('DD/MM/YYYY')); this.props.timeSave(moment().format('HH:mm')); this.props.frequencySave('No Repeat'); this.props.addAllFiles(save.save_scheduleds.files); } handleScheduledSaveClick(save) { this.props.listUsers([{ id: save.id, name: save.name }]); this.props.addAllFiles(save.save_scheduleds.files); } handleRestoreClick(save) { this.props.instantRestore(save.id, save.save_scheduleds.files, save.save_scheduleds.saves[0].id); this.props.showInstantRestoreModal(); } render() { const names = ['#', 'Username', 'Last save date', 'State', 'Files', 'Actions']; return ( <div> <Table responsive hover striped> <thead> <Tr items={names} component={Th} /> </thead> <tbody> {this.props.saves.map((save, index) => { if (typeof save.save_scheduleds.length === 'undefined') { const actions = []; const displayButtonRestore = ((save.save_scheduleds.saves[0].isSuccess) ? '' : styles.undisplay); actions.push(<ButtonPopover key={`action-${0}`} id="launch_save_action" trigger={['focus', 'hover']} placement="bottom" popoverContent="Relaunch save" buttonType="link" icon="floppy-disk" onClick={() => this.handleSaveClick(save)} />); actions.push(<ButtonPopover key={`action-${1}`} id="launch_save_scheduled_action" trigger={['focus', 'hover']} placement="bottom" popoverContent="Relaunch save at a specific time" buttonType="link" icon="calendar" onClick={() => this.handleScheduledSaveClick(save)} link="/create-save" />); actions.push(<ButtonPopover key={`action-${2}`} id="launch_restore_action" trigger={['focus', 'hover']} placement="bottom" popoverContent="Restore" buttonType="link" icon="repeat" buttonStyle={displayButtonRestore} onClick={() => this.handleRestoreClick(save)} />); return ( <Tr key={`item-${index}`} items={[ { isLink: false, value: save.id }, { isLink: true, link: `/save/${save.name}/${save.id}`, value: save.name }, { isLink: false, value: moment(save.save_scheduleds.saves[0].execDate).format('DD/MM/YYYY HH:mm') }, { isLink: false, value: (save.save_scheduleds.saves[0].isSuccess) ? 'Succeeded' : 'Failed' }, { isLink: false, value: save.save_scheduleds.files }, { isLink: false, value: actions }]} component={Td} /> ); } return ( <Tr key={`item-${index}`} items={[ { isLink: false, value: save.id }, { isLink: true, link: `/save/${save.name}/${save.id}`, value: save.name }, { isLink: false, value: '' }, { isLink: false, value: '' }, { isLink: false, value: '' }, { isLink: false, value: '' }, ]} component={Td} /> ); })} </tbody> </Table> <SaveInstantSaveModal /> <SaveInstantRestoreModal /> </div> ); } } SaveTable.propTypes = { saves: React.PropTypes.arrayOf(React.PropTypes.object), listUsers: React.PropTypes.func, dateSave: React.PropTypes.func, timeSave: React.PropTypes.func, frequencySave: React.PropTypes.func, addAllFiles: React.PropTypes.func, showInstantSaveModal: React.PropTypes.func, showInstantRestoreModal: React.PropTypes.func, instantRestore: React.PropTypes.func, };
src/svg-icons/editor/format-underlined.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatUnderlined = (props) => ( <SvgIcon {...props}> <path d="M12 17c3.31 0 6-2.69 6-6V3h-2.5v8c0 1.93-1.57 3.5-3.5 3.5S8.5 12.93 8.5 11V3H6v8c0 3.31 2.69 6 6 6zm-7 2v2h14v-2H5z"/> </SvgIcon> ); EditorFormatUnderlined = pure(EditorFormatUnderlined); EditorFormatUnderlined.displayName = 'EditorFormatUnderlined'; EditorFormatUnderlined.muiName = 'SvgIcon'; export default EditorFormatUnderlined;
src/App.js
henriqueadonai/flux
import React, { Component } from 'react'; import logo from './logo.svg'; import TopicsScreen from './containers/TopicsScreen'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <TopicsScreen /> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to React</h2> </div> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); } } export default App;
src/svg-icons/action/swap-vertical-circle.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSwapVerticalCircle = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM6.5 9L10 5.5 13.5 9H11v4H9V9H6.5zm11 6L14 18.5 10.5 15H13v-4h2v4h2.5z"/> </SvgIcon> ); ActionSwapVerticalCircle = pure(ActionSwapVerticalCircle); ActionSwapVerticalCircle.displayName = 'ActionSwapVerticalCircle'; ActionSwapVerticalCircle.muiName = 'SvgIcon'; export default ActionSwapVerticalCircle;
lib/components/Uploader.js
Ribeiro/filepizza
import Arrow from '@app/components/Arrow'; import React from 'react'; import UploadActions from '@app/actions/UploadActions'; export default class UploadPage extends React.Component { uploadFile(file) { UploadActions.uploadFile(file); } render() { switch (this.props.status) { case 'ready': return <div> <DropZone onDrop={this.uploadFile.bind(this)} /> <Arrow dir="up" /> </div>; break; case 'processing': return <div> <Arrow dir="up" animated /> <FileDescription file={this.props.file} /> </div>; break; case 'uploading': return <div> <Arrow dir="up" animated /> <FileDescription file={this.props.file} /> <Temaplink token={this.props.token} /> </div>; break; } } }
InstitutionalApp/index.ios.js
michelmarcondes/ReactNativeStudies
import React, { Component } from 'react'; import { AppRegistry, } from 'react-native'; import App from './app'; export default class InstitutionalApp extends Component { render() { return ( <App /> ); } } AppRegistry.registerComponent('InstitutionalApp', () => InstitutionalApp);
src/js/components/icons/base/LocationPin.js
kylebyerly-hp/grommet
// (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}-location-pin`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'location-pin'); 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="M12,10 C14.209139,10 16,8.209139 16,6 C16,3.790861 14.209139,2 12,2 C9.790861,2 8,3.790861 8,6 C8,8.209139 9.790861,10 12,10 Z M12,10 L12,22"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'LocationPin'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
ui/app/components/PfIcon/index.js
StamusNetworks/scirius
/** * * PfIcon * */ import React from 'react'; import PropTypes from 'prop-types'; // import styled from 'styled-components'; import './style.css'; export const PfIcon = ({ type, style }) => <i className={`pficon-${type}`} style={style} />; PfIcon.defaultProps = { style: {}, }; PfIcon.propTypes = { style: PropTypes.object, type: PropTypes.oneOf([ 'add-circle-o', 'applications', 'arrow', 'asleep', 'automation', 'build', 'builder-image', 'bundle', 'blueprint', 'catalog', 'chat', 'close', 'cloud-security', 'cloud-tenant', 'cluster', 'connected', 'container-node', 'cpu', 'degraded', 'delete', 'disconnected', 'domain', 'edit', 'enhancement', 'enterprise', 'equalizer', 'error-circle-o', 'export', 'flag', 'messages', 'flavor', 'filter', 'folder-close', 'folder-open', 'help', 'history', 'home', 'image', 'import', 'in-progress', 'info', 'infrastructure', 'integration', 'key', 'locked', 'maintenance', 'memory', 'middleware', 'migration', 'monitoring', 'network', 'network-range', 'on', 'on-running', 'optimize', 'orders', 'off', 'ok', 'paused', 'pending', 'plugged', 'port', 'print', 'process-automation', 'private', 'project', 'rebalance', 'rebooting', 'refresh', 'restart', 'regions', 'registry', 'remove', 'replicator', 'repository', 'resource-pool', 'resources-almost-empty', 'resources-almost-full', 'resources-full', 'route', 'running', 'satellite', 'save', 'screen', 'search', 'security', 'server', 'server-group', 'service', 'services', 'service-catalog', 'settings', 'sort-common-asc', 'sort-common-desc', 'spinner', 'spinner2', 'storage-domain', 'template', 'tenant', 'thumb-tack-o', 'topology', 'trend-down', 'trend-up', 'unknown', 'user', 'users', 'unlocked', 'unplugged', 'vcenter', 'virtual-machine', 'volume', 'warning-triangle-o', 'zone', ]).isRequired, }; export default PfIcon;
src/components/Collection/Entries/EntriesCollection.js
Aloomaio/netlify-cms
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { connect } from 'react-redux'; import { loadEntries as actionLoadEntries } from 'Actions/entries'; import { selectEntries } from 'Reducers'; import Entries from './Entries'; class EntriesCollection extends React.Component { static propTypes = { collection: ImmutablePropTypes.map.isRequired, publicFolder: PropTypes.string.isRequired, page: PropTypes.number, entries: ImmutablePropTypes.list, isFetching: PropTypes.bool.isRequired, viewStyle: PropTypes.string, }; componentDidMount() { const { collection, loadEntries } = this.props; if (collection) { loadEntries(collection); } } componentWillReceiveProps(nextProps) { const { collection, loadEntries } = this.props; if (nextProps.collection !== collection) { loadEntries(nextProps.collection); } } handleLoadMore = page => { const { collection, loadEntries } = this.props; loadEntries(collection, page); } render () { const { collection, entries, publicFolder, page, isFetching, viewStyle } = this.props; return ( <Entries collections={collection} entries={entries} publicFolder={publicFolder} page={page} onPaginate={this.handleLoadMore} isFetching={isFetching} collectionName={collection.get('label')} viewStyle={viewStyle} /> ); } } function mapStateToProps(state, ownProps) { const { name, collection, viewStyle } = ownProps; const { config } = state; const publicFolder = config.get('public_folder'); const page = state.entries.getIn(['pages', collection.get('name'), 'page']); const entries = selectEntries(state, collection.get('name')); const isFetching = state.entries.getIn(['pages', collection.get('name'), 'isFetching'], false); return { publicFolder, collection, page, entries, isFetching, viewStyle }; } const mapDispatchToProps = { loadEntries: actionLoadEntries, }; export default connect(mapStateToProps, mapDispatchToProps)(EntriesCollection);
app/javascript/mastodon/components/status.js
esetomo/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import Avatar from './avatar'; import AvatarOverlay from './avatar_overlay'; import RelativeTimestamp from './relative_timestamp'; import DisplayName from './display_name'; import StatusContent from './status_content'; import StatusActionBar from './status_action_bar'; import { FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { MediaGallery, Video } from '../features/ui/util/async-components'; import { HotKeys } from 'react-hotkeys'; import classNames from 'classnames'; // We use the component (and not the container) since we do not want // to use the progress bar to show download progress import Bundle from '../features/ui/components/bundle'; export default class Status extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map, account: ImmutablePropTypes.map, onReply: PropTypes.func, onFavourite: PropTypes.func, onReblog: PropTypes.func, onDelete: PropTypes.func, onPin: PropTypes.func, onOpenMedia: PropTypes.func, onOpenVideo: PropTypes.func, onBlock: PropTypes.func, onEmbed: PropTypes.func, onHeightChange: PropTypes.func, muted: PropTypes.bool, hidden: PropTypes.bool, onMoveUp: PropTypes.func, onMoveDown: PropTypes.func, }; state = { isExpanded: false, } // Avoid checking props that are functions (and whose equality will always // evaluate to false. See react-immutable-pure-component for usage. updateOnProps = [ 'status', 'account', 'muted', 'hidden', ] updateOnStates = ['isExpanded'] handleClick = () => { if (!this.context.router) { return; } const { status } = this.props; this.context.router.history.push(`/statuses/${status.getIn(['reblog', 'id'], status.get('id'))}`); } handleAccountClick = (e) => { if (this.context.router && e.button === 0) { const id = e.currentTarget.getAttribute('data-id'); e.preventDefault(); this.context.router.history.push(`/accounts/${id}`); } } handleExpandedToggle = () => { this.setState({ isExpanded: !this.state.isExpanded }); }; renderLoadingMediaGallery () { return <div className='media_gallery' style={{ height: '110px' }} />; } renderLoadingVideoPlayer () { return <div className='media-spoiler-video' style={{ height: '110px' }} />; } handleOpenVideo = startTime => { this.props.onOpenVideo(this._properStatus().getIn(['media_attachments', 0]), startTime); } handleHotkeyReply = e => { e.preventDefault(); this.props.onReply(this._properStatus(), this.context.router.history); } handleHotkeyFavourite = () => { this.props.onFavourite(this._properStatus()); } handleHotkeyBoost = e => { this.props.onReblog(this._properStatus(), e); } handleHotkeyMention = e => { e.preventDefault(); this.props.onMention(this._properStatus().get('account'), this.context.router.history); } handleHotkeyOpen = () => { this.context.router.history.push(`/statuses/${this._properStatus().get('id')}`); } handleHotkeyOpenProfile = () => { this.context.router.history.push(`/accounts/${this._properStatus().getIn(['account', 'id'])}`); } handleHotkeyMoveUp = () => { this.props.onMoveUp(this.props.status.get('id')); } handleHotkeyMoveDown = () => { this.props.onMoveDown(this.props.status.get('id')); } _properStatus () { const { status } = this.props; if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') { return status.get('reblog'); } else { return status; } } render () { let media = null; let statusAvatar, prepend; const { hidden } = this.props; const { isExpanded } = this.state; let { status, account, ...other } = this.props; if (status === null) { return null; } if (hidden) { return ( <div> {status.getIn(['account', 'display_name']) || status.getIn(['account', 'username'])} {status.get('content')} </div> ); } if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') { const display_name_html = { __html: status.getIn(['account', 'display_name_html']) }; prepend = ( <div className='status__prepend'> <div className='status__prepend-icon-wrapper'><i className='fa fa-fw fa-retweet status__prepend-icon' /></div> <FormattedMessage id='status.reblogged_by' defaultMessage='{name} boosted' values={{ name: <a onClick={this.handleAccountClick} data-id={status.getIn(['account', 'id'])} href={status.getIn(['account', 'url'])} className='status__display-name muted'><strong dangerouslySetInnerHTML={display_name_html} /></a> }} /> </div> ); account = status.get('account'); status = status.get('reblog'); } if (status.get('media_attachments').size > 0 && !this.props.muted) { if (status.get('media_attachments').some(item => item.get('type') === 'unknown')) { } else if (status.getIn(['media_attachments', 0, 'type']) === 'video') { const video = status.getIn(['media_attachments', 0]); media = ( <Bundle fetchComponent={Video} loading={this.renderLoadingVideoPlayer} > {Component => <Component preview={video.get('preview_url')} src={video.get('url')} width={239} height={110} sensitive={status.get('sensitive')} onOpenVideo={this.handleOpenVideo} />} </Bundle> ); } else { media = ( <Bundle fetchComponent={MediaGallery} loading={this.renderLoadingMediaGallery} > {Component => <Component media={status.get('media_attachments')} sensitive={status.get('sensitive')} height={110} onOpenMedia={this.props.onOpenMedia} />} </Bundle> ); } } if (account === undefined || account === null) { statusAvatar = <Avatar account={status.get('account')} size={48} />; }else{ statusAvatar = <AvatarOverlay account={status.get('account')} friend={account} />; } const handlers = this.props.muted ? {} : { reply: this.handleHotkeyReply, favourite: this.handleHotkeyFavourite, boost: this.handleHotkeyBoost, mention: this.handleHotkeyMention, open: this.handleHotkeyOpen, openProfile: this.handleHotkeyOpenProfile, moveUp: this.handleHotkeyMoveUp, moveDown: this.handleHotkeyMoveDown, }; return ( <HotKeys handlers={handlers}> <div className={classNames('status__wrapper', `status__wrapper-${status.get('visibility')}`, { focusable: !this.props.muted })} tabIndex={this.props.muted ? null : 0}> {prepend} <div className={classNames('status', `status-${status.get('visibility')}`, { muted: this.props.muted })} data-id={status.get('id')}> <div className='status__info'> <a href={status.get('url')} className='status__relative-time' target='_blank' rel='noopener'><RelativeTimestamp timestamp={status.get('created_at')} /></a> <a onClick={this.handleAccountClick} target='_blank' data-id={status.getIn(['account', 'id'])} href={status.getIn(['account', 'url'])} title={status.getIn(['account', 'acct'])} className='status__display-name'> <div className='status__avatar'> {statusAvatar} </div> <DisplayName account={status.get('account')} /> </a> </div> <StatusContent status={status} onClick={this.handleClick} expanded={isExpanded} onExpandedToggle={this.handleExpandedToggle} /> {media} <StatusActionBar status={status} account={account} {...other} /> </div> </div> </HotKeys> ); } }
examples/basic/src/index.js
tannerlinsley/react-table
import React from 'react' import ReactDOM from 'react-dom' import './index.css' import App from './App' ReactDOM.render(<App />, document.getElementById('root'))
web/src/components/Loading.js
slice/dogbot
import React from 'react' import styled, { keyframes } from 'styled-components' const loadingAnimation = keyframes` 0% { transform: scale(1); } 50% { transform: scale(0.5); } 100% { transform: scale(1); } ` export const Pulser = styled.div` display: inline-block; width: 2rem; height: 2rem; border-radius: 100%; background: ${(props) => props.theme.accent}; animation: 1s ease infinite ${loadingAnimation}; ` const StyledLoading = styled.div` display: inline-flex; align-items: center; margin: 1rem 0; ` const LoadingText = styled.div` margin-left: 1rem; text-transform: uppercase; font-size: 0.8rem; ` export default function Loading() { return ( <StyledLoading> <Pulser /> <LoadingText>Loading...</LoadingText> </StyledLoading> ) }
client/app/components/ContentEditor/customPlugins/link-plugin/Link.js
bryanph/Geist
import React from 'react'; import { Entity } from 'draft-js'; const Link = (props) => { const { href } = props.contentState.getEntity(props.entityKey).getData(); return ( <a href={href} target="_blank"> {props.children} </a> ); }; export default Link;
resources/assets/javascript/components/calendarAddBox.js
colinjeanne/garden
import React from 'react'; import SelectBox from './selectBox'; export default class CalendarAddBox extends React.Component { static get propTypes() { return { onAdd: React.PropTypes.func.isRequired, plantNames: React.PropTypes.arrayOf( React.PropTypes.string).isRequired }; } render() { const plantOptions = this.props.plantNames.map(plantName => { return { value: plantName, label: plantName }; }); return ( <div className="plantCalendarAddBox"> <SelectBox options={plantOptions} ref={r => this.select = r} /> <button onClick={() => this.props.onAdd(this.select.selectedValue())} type="button"> Add </button> </div> ); } }
jsx/todo_list_redux/src/components/Footer.js
NickTaporuk/webpack_starterkit_project
import React from 'react' import FilterLink from '../containers/FilterLink' const Footer = () => ( <p> Show: {" "} <FilterLink filter="SHOW_ALL"> All </FilterLink> {", "} <FilterLink filter="SHOW_ACTIVE"> Active </FilterLink> {", "} <FilterLink filter="SHOW_COMPLETED"> Completed </FilterLink> </p> ) export default Footer
src/components/icons/TagsIcon.js
austinknight/ui-components
import React from 'react'; import PropTypes from 'prop-types'; import { generateFillFromProps } from '../styles/colors.js'; const TagsIcon = props => ( <svg {...props.size || { width: '24px', height: '24px' }} {...props} {...props.color || {...generateFillFromProps(props, '#FFFFFF')}} viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"> {props.title && <title>{props.title}</title>} <path d="M0 0h24v24H0z" fill="none" /> <path d="M17.63 5.84C17.27 5.33 16.67 5 16 5L5 5.01C3.9 5.01 3 5.9 3 7v10c0 1.1.9 1.99 2 1.99L16 19c.67 0 1.27-.33 1.63-.84L22 12l-4.37-6.16z" /> </svg> ); TagsIcon.propTypes = { size: PropTypes.object, color: PropTypes.string }; export default TagsIcon;
src/containers/Equate/Equate.js
sadafk831/React-Native-Simple-Calculator
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; import store from '../../redux/store'; import { equate } from '../../redux/modules/calculator'; import NormalButton from '../../components/NormalButton/NormalButton'; export default class Equate extends Component { render() { return ( <NormalButton onClick = {this._onClick} label = '=' customTextStyle = {styles.buttonText} customContainerStyle = {styles.buttonContainer} /> ); }; _onClick = (value) => { store.dispatch(equate(store.getState().calculator.value)); } } const styles = StyleSheet.create({ buttonContainer:{ backgroundColor: 'orange' }, buttonText: { color: '#fff' } });
example/src/pages/Lens.js
ethanselzer/react-image-magnify
import React, { Component } from 'react'; import { Col, Grid, Jumbotron, Row } from 'react-bootstrap'; import Helmet from 'react-helmet'; import Header from '../components/Header'; import Lens from '../components/Lens'; import 'bootstrap/dist/css/bootstrap.css'; import '../styles/app.css'; export default class extends Component { render() { return ( <div> <Helmet title="React Image Magnify" /> <Header {...this.props}/> <Jumbotron> <Grid> <Row> <Col sm={12}> </Col> </Row> </Grid> </Jumbotron> <Grid> <Row> <Col sm={12}> <Lens /> </Col> </Row> </Grid> </div> ); } }
src/containers/Login/container/WeChatLoginTransition.js
MeetDay/dreampark-web
import React from 'react' import { asyncConnect } from 'redux-async-connect' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { push } from 'react-router-redux' import * as Constant from '../../../utils/constant' import { jumpToWeChatAuthorizationUrl } from '../../../utils/wechat' import { isWechatInfoLoaded, wechatLogin } from '../../Login/module/login' import { isFullUser } from '../../../utils/wechat' @asyncConnect([{ deferred: false, promise: ({ params, store:{ dispatch, getState }, location, helpers }) => { const getQueryValueOf = key => decodeURIComponent(location.search.replace(new RegExp('^(?:.*[&\\?]' + escape(key).replace(/[.+*]/g, '\\$&') + '(?:\\=([^&]*))?)?.*$', 'i'), '$1')) if (!helpers.serverSide && !isWechatInfoLoaded(getState())) { const wechatCode = getQueryValueOf('code') if (wechatCode) { return dispatch(wechatLogin(wechatCode)) } } } }]) @connect( state => ({ user: state.login.user, weChatInfo: state.login.weChatInfo, weChatInfoError: state.login.weChatInfoError }), dispatch => bindActionCreators({ push }, dispatch) ) export default class WeChatLoginTransition extends React.Component { componentDidMount() { const getQueryValueOf = key => decodeURIComponent(this.props.location.search.replace(new RegExp('^(?:.*[&\\?]' + escape(key).replace(/[.+*]/g, '\\$&') + '(?:\\=([^&]*))?)?.*$', 'i'), '$1')) const wechatCode = getQueryValueOf('code') const callbackUrl = getQueryValueOf('callbackUrl') if (!wechatCode) { jumpToWeChatAuthorizationUrl(location, callbackUrl) } } componentWillReceiveProps(nextProps) { const { user, weChatInfo, weChatInfoError } = nextProps if (weChatInfo && weChatInfoError && weChatInfoError.code === 10080) { this.props.push('/register#stepone') } else if (weChatInfo && user && !isFullUser(user)) { this.props.push('/register#stepthree') } else if (weChatInfo && !weChatInfoError && user) { const forwardUrl = sessionStorage.getItem(Constant.URL_BEFORE_LEAVE) console.log('forwardUrl:', forwardUrl) this.props.push(forwardUrl || '/tickets') } else { console.log(weChatInfoError) this.props.push('/login#launching') } } render() { const styles = require('./WeChatLoginTransition.scss') return ( <div className={styles.wechat}> <span className={styles.description}>正在登录...</span> </div> ); } }
react/Apps/todolist-app/src/components/app.js
rcapde/reactjs-Apps
import React, { Component } from 'react'; import TodoList from './todolist'; export default class App extends Component { render() { return ( <TodoList /> ); } }
node_modules/@exponent/ex-navigation/src/ExNavigationConnect.js
Helena-High/school-app
/** * @flow */ import React from 'react'; import { connect } from 'react-redux'; import storeShape from 'react-redux/lib/utils/storeShape'; import hoistStatics from 'hoist-non-react-statics'; import invariant from 'invariant'; function getDisplayName(WrappedComponent: ReactClass<*>) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } export default function exNavConnect(...args: any) { return function wrap(WrappedComponent: ReactClass<*>) { const ConnectedComponent = connect(...args)(WrappedComponent); const connectDisplayName = `ExNavConnect(${getDisplayName(WrappedComponent)})`; class ExNavConnect extends React.Component { navigationStore: Object; constructor(props, context) { super(props, context); this.navigationStore = props.navigationStore || context.navigationStore; invariant(this.navigationStore, `Could not find "navigationStore" in either the context or ` + `props of "${connectDisplayName}". ` + `Either wrap the root component in a <Provider>, ` + `or explicitly pass "store" as a prop to "${connectDisplayName}".` ); } static contextTypes = { navigationStore: storeShape, }; render() { return ( <ConnectedComponent store={this.navigationStore} {...this.props} /> ); } } return hoistStatics(ExNavConnect, ConnectedComponent); }; }
packages/react-ui-components/src/Headline/index.story.js
grebaldi/PackageFactory.Guevara
import React from 'react'; import {storiesOf} from '@storybook/react'; import {withKnobs, select} from '@storybook/addon-knobs'; import {StoryWrapper} from './../_lib/storyUtils'; import Headline from '.'; storiesOf('Headline', module) .addDecorator(withKnobs) .addWithInfo( 'default', () => { const type = select('Headline type', ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'], 'h1'); return ( <StoryWrapper> <Headline type={type}>Heading level: {type}</Headline> </StoryWrapper> ); }, {inline: true} );
packages/es-components/src/components/controls/DismissButton.js
TWExchangeSolutions/es-components
import React from 'react'; import styled from 'styled-components'; import screenReaderOnly from '../patterns/screenReaderOnly/screenReaderOnly'; import Icon from '../base/icons/Icon'; const DismissButtonBase = styled.button` background-color: transparent; border: 0; cursor: pointer; display: flex; font-weight: bold; opacity: 0.2; padding: 0; &:hover, &:focus { opacity: 0.5; } `; const ScreenReaderText = screenReaderOnly('span'); const DismissButton = React.forwardRef(function DismissButton(props, ref) { return ( <DismissButtonBase aria-label="Close" type="button" {...props} ref={ref}> <Icon name="remove" /> <ScreenReaderText>Close</ScreenReaderText> </DismissButtonBase> ); }); export default DismissButton;
src/components/common/svg-icons/notification/confirmation-number.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationConfirmationNumber = (props) => ( <SvgIcon {...props}> <path d="M22 10V6c0-1.11-.9-2-2-2H4c-1.1 0-1.99.89-1.99 2v4c1.1 0 1.99.9 1.99 2s-.89 2-2 2v4c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2v-4c-1.1 0-2-.9-2-2s.9-2 2-2zm-9 7.5h-2v-2h2v2zm0-4.5h-2v-2h2v2zm0-4.5h-2v-2h2v2z"/> </SvgIcon> ); NotificationConfirmationNumber = pure(NotificationConfirmationNumber); NotificationConfirmationNumber.displayName = 'NotificationConfirmationNumber'; NotificationConfirmationNumber.muiName = 'SvgIcon'; export default NotificationConfirmationNumber;
src/app/containers/app.js
skratchdot/ble-midi
import React, { Component } from 'react'; import { blueA400, blueA700 } from 'material-ui/styles/colors'; import Footer from '../components/footer'; import Header from '../components/header'; import Main from '../components/main'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import NoBluetoothSupport from '../components/no-bluetooth-support'; import { VBox } from 'react-layout-components'; import { connect } from 'react-redux'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; const muiTheme = getMuiTheme({ palette: { primary1Color: blueA400, primary2Color: blueA700 } }); export class App extends Component { static propTypes = { bluetooth: React.PropTypes.obj }; render() { const { bluetooth } = this.props; const alerts = []; if (!bluetooth.get('supported')) { alerts.push(<NoBluetoothSupport key="no-support" />); } return ( <MuiThemeProvider muiTheme={muiTheme}> <VBox style={{ minHeight: '100vh' }}> <VBox> <Header /> </VBox> <VBox flexGrow={1} style={{ padding: 54 }}> {alerts} <Main /> </VBox> <VBox> <Footer /> </VBox> </VBox> </MuiThemeProvider> ); } } export default connect(state => ({ bluetooth: state.bluetooth }))(App);
public/src/games/lobby/lobby.container.js
MaciejSzaflik/CharadesAndStuff
import React from 'react'; import {Table, TableBody, TableFooter, TableHeader, TableHeaderColumn, TableRow, TableRowColumn} from 'material-ui/Table'; import TextField from 'material-ui/TextField'; import Toggle from 'material-ui/Toggle'; import RaisedButton from 'material-ui/RaisedButton'; const WEBSOCKET_URL = "ws://localhost:9000/ws/lobby"; var socket = new WebSocket(WEBSOCKET_URL); export class Lobby extends React.Component { constructor(props) { super(props); this.state = { fixedHeader: true, fixedFooter: true, stripedRows: false, showRowHover: false, selectable: false, multiSelectable: false, enableSelectAll: false, deselectOnClickaway: true, showCheckboxes: false, height: '500px', lastColumnValue: "", text: { columns: { id: 'ID', dateCreation: 'Data utworzenia', dateUpdate: 'Ostatnia aktualizacja', status: 'Status', playersLength: 'Ilość graczy', joinToRoom: '' }, status: { isRunning: 'W trakcje rozgrywki', notRunning: 'Oczekiwanie na graczy' }, button: { create: "Utwórz pokój", join: "Dołącz" }, lastUpdade: "Ostatnia aktualizacja: ?" }, styles: { button: { margin: 12, } }, lobby: { gameType: "checkers", lastUpdate: new Date(), isValid: false, maxPlayer: 2, rooms: [], getLastUpdate: function() { var hour = this.lastUpdate.getHours(); var minutes = this.lastUpdate.getMinutes(); var seconds = this.lastUpdate.getSeconds(); hour = hour < 9 ? "0" + hour : hour; minutes = minutes < 9 ? "0" + minutes : minutes; seconds = seconds < 9 ? "0" + seconds : seconds; return hour + ":" + minutes + ":" + seconds; }, dateFormat: function(date) { var hour = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); hour = hour < 9 ? "0" + hour : hour; minutes = minutes < 9 ? "0" + minutes : minutes; seconds = seconds < 9 ? "0" + seconds : seconds; return hour + ":" + minutes + ":" + seconds; }, }, pollInterval: 1000, tableColumns: [] }; this.state.tableColumns = [ this.state.text.columns.id, this.state.text.columns.dateCreation, this.state.text.columns.dateUpdate, this.state.text.columns.status, this.state.text.columns.playersLength, this.state.lastColumnValue]; } componentWillMount() { this.loadDataFromServer(); var pollInterval = this.props.pollInterval; //window.setInterval(this.loadDataFromServer, pollInterval); } loadDataFromServer() { var lobbyDto = { gameType: "checkers", lastUpdate: new Date(), isValid: false, maxPlayer: 2, rooms: [], getLastUpdate: function() { var hour = this.lastUpdate.getHours(); var minutes = this.lastUpdate.getMinutes(); var seconds = this.lastUpdate.getSeconds(); hour = hour < 9 ? "0" + hour : hour; minutes = minutes < 9 ? "0" + minutes : minutes; seconds = seconds < 9 ? "0" + seconds : seconds; return hour + ":" + minutes + ":" + seconds; }, dateFormat: function(date) { var hour = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); hour = hour < 9 ? "0" + hour : hour; minutes = minutes < 9 ? "0" + minutes : minutes; seconds = seconds < 9 ? "0" + seconds : seconds; return hour + ":" + minutes + ":" + seconds; }, setDate(data) { this.gameType = data.gameType; this.lastUpdate = new Date(data.lastUpdate.replace("2016", "2014")); this.isValid = data.isValid; this.maxPlayer = data.maxPlayer; this.rooms = data.rooms; } }; socket.onopen = function(event) { if (socket.readyState === 1) { socket.send('checkers'); console.log("send"); } }; socket.onerror = function (evt) { console.log(evt); }; } waitForSocketConnection(socket, callback) { setTimeout( function () { if (socket.readyState === 1) { console.log("Connection is made") if(callback != null){ callback(); } return; } else { console.log("wait for connection...") waitForSocketConnection(socket, callback); } }, 5); } render() { return ( <div> <div> <div> <ButtonLobbyCreateRoom text={this.state.text.button.create} styles={this.state.styles.button} /> </div> <div> <RoomList state={this.state} tableColumns={this.state.tableColumns} lobby={this.state.lobby} text={this.state.text} styles={this.state.styles} /> </div> </div> <ChatApp /> </div> ) } } var ButtonLobbyCreateRoom = React.createClass({ render() { return ( <RaisedButton label={this.props.text} style={this.props.styles}/> ) } }); var RoomList = React.createClass({ render() { return ( <div> <Table height={this.props.state.height} fixedHeader={this.props.state.fixedHeader} fixedFooter={this.props.state.fixedFooter} selectable={this.props.state.selectable} multiSelectable={this.props.state.multiSelectable}> <TableHeader displaySelectAll={this.props.state.showCheckboxes} adjustForCheckbox={this.props.state.showCheckboxes} enableSelectAll={this.props.state.enableSelectAll}> <TableRow displayRowCheckbox={false}> {this.props.tableColumns.map( (row, index) => ( <TableHeaderColumn key={index} tooltip={row}>{row}</TableHeaderColumn> ))} </TableRow> </TableHeader> <TableBody displayRowCheckbox={this.props.state.showCheckboxes} deselectOnClickaway={this.props.state.deselectOnClickaway} showRowHover={this.props.state.showRowHover} stripedRows={this.props.state.stripedRows}> {this.props.lobby.rooms.map( (row, index) => ( <TableRow key={index}> <TableRowColumn>{row.id}</TableRowColumn> <TableRowColumn>{this.props.lobby.dateFormat(row.dateCreation)}</TableRowColumn> <TableRowColumn>{this.props.lobby.dateFormat(row.dateUpdate)}</TableRowColumn> {row.isRunning ? <TableRowColumn>{this.props.text.status.isRunning}</TableRowColumn> : <TableRowColumn>{this.props.text.status.notRunning}</TableRowColumn> } <TableRowColumn>{row.players.length} / {this.props.lobby.maxPlayer}</TableRowColumn> <TableRowColumn> <RaisedButton label={this.props.text.button.join} style={this.props.styles.button}/> </TableRowColumn> </TableRow> ))} </TableBody> </Table> </div> ) } }); var ChatApp = React.createClass({ render: function() { return ( <div className="chat"> Hello, world! I am a CommentForm. </div> ); } });