path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
example/examples/CustomTiles.js
athaeryn/react-native-maps
import React from 'react'; import { StyleSheet, View, Text, Dimensions, } from 'react-native'; import MapView, { MAP_TYPES, PROVIDER_DEFAULT } from 'react-native-maps'; const { width, height } = Dimensions.get('window'); const ASPECT_RATIO = width / height; const LATITUDE = 37.78825; const LONGITUDE = -122.4324; const LATITUDE_DELTA = 0.0922; const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; class CustomTiles extends React.Component { constructor(props, context) { super(props, context); this.state = { region: { latitude: LATITUDE, longitude: LONGITUDE, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA, }, }; } get mapType() { // MapKit does not support 'none' as a base map return this.props.provider === PROVIDER_DEFAULT ? MAP_TYPES.STANDARD : MAP_TYPES.NONE; } render() { const { region } = this.state; return ( <View style={styles.container}> <MapView provider={this.props.provider} mapType={this.mapType} style={styles.map} initialRegion={region} > <MapView.UrlTile urlTemplate="http://c.tile.stamen.com/watercolor/{z}/{x}/{y}.jpg" zIndex={-1} /> </MapView> <View style={styles.buttonContainer}> <View style={styles.bubble}> <Text>Custom Tiles</Text> </View> </View> </View> ); } } CustomTiles.propTypes = { provider: MapView.ProviderPropType, }; const styles = StyleSheet.create({ container: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, justifyContent: 'flex-end', alignItems: 'center', }, map: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, }, bubble: { flex: 1, backgroundColor: 'rgba(255,255,255,0.7)', paddingHorizontal: 18, paddingVertical: 12, borderRadius: 20, }, latlng: { width: 200, alignItems: 'stretch', }, button: { width: 80, paddingHorizontal: 12, alignItems: 'center', marginHorizontal: 10, }, buttonContainer: { flexDirection: 'row', marginVertical: 20, backgroundColor: 'transparent', }, }); module.exports = CustomTiles;
examples/quick-start/app.js
maludwig/react-redux-form
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; // We'll create this in Step 5. import store from './store.js'; // We'll create this in Step 6. import UserForm from './components/user-form.js'; class App extends React.Component { render() { return ( <Provider store={store}> <UserForm /> </Provider> ); } } ReactDOM.render(<App />, document.getElementById('app'));
examples/real-world/server.js
ipluser/redux-saga
/* eslint-disable no-console */ import "babel-polyfill" import webpack from 'webpack' import webpackDevMiddleware from 'webpack-dev-middleware' import webpackHotMiddleware from 'webpack-hot-middleware' import config from './webpack.config' import express from 'express' import path from 'path' import favicon from 'serve-favicon' import routes from './routes' import React from 'react' import Root from './containers/Root' import { renderToString } from 'react-dom/server' import { match, createMemoryHistory } from 'react-router' import configureStore from './store/configureStore' import rootSaga from './sagas' var app = express() var port = 3000 app.use(favicon(path.join(__dirname, 'favicon.ico'))) var compiler = webpack(config) app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })) app.use(webpackHotMiddleware(compiler)) const layout = (body, initialState) => (` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <title>Redux-saga real-world universal example</title> </head> <body> <div id="root"><div>${body}</div></div> <script type="text/javascript" charset="utf-8"> window.__INITIAL_STATE__ = ${initialState}; </script> <script src="/static/bundle.js"></script> </body> </html> `) app.use(function(req, res) { console.log('req', req.url) const store = configureStore() // Note that req.url here should be the full URL path from // the original request, including the query string. match({routes, location: req.url}, (error, redirectLocation, renderProps) => { if (error) { res.status(500).send(error.message) } else if (redirectLocation) { res.redirect(302, redirectLocation.pathname + redirectLocation.search) } else if (renderProps && renderProps.components) { const rootComp = <Root store={store} routes={routes} history={createMemoryHistory()} renderProps={renderProps} type="server"/> store.runSaga(rootSaga).done.then(() => { console.log('sagas complete') res.status(200).send( layout( renderToString(rootComp), JSON.stringify(store.getState()) ) ) }).catch((e) => { console.log(e.message) res.status(500).send(e.message) }) renderToString(rootComp) store.close() //res.status(200).send(layout('','{}')) } else { res.status(404).send('Not found') } }) }) app.listen(port, function(error) { if (error) { console.error(error) } else { console.info("==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port) } })
react-flux-mui/js/material-ui/src/svg-icons/action/play-for-work.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPlayForWork = (props) => ( <SvgIcon {...props}> <path d="M11 5v5.59H7.5l4.5 4.5 4.5-4.5H13V5h-2zm-5 9c0 3.31 2.69 6 6 6s6-2.69 6-6h-2c0 2.21-1.79 4-4 4s-4-1.79-4-4H6z"/> </SvgIcon> ); ActionPlayForWork = pure(ActionPlayForWork); ActionPlayForWork.displayName = 'ActionPlayForWork'; ActionPlayForWork.muiName = 'SvgIcon'; export default ActionPlayForWork;
app/javascript/chitchat/containers/App/index.js
fcbajao/chitchat
// @flow import React from 'react' import { connect } from 'react-redux' import { BrowserRouter as Router, Route } from 'react-router-dom' import PrivateRoute from '../../components/PrivateRoute' import Login from '../Login' import Room from '../../containers/Room' import type { Auth } from '../../ducks/auth/flowTypes' const App = (props: { auth: Auth }) => ( <Router> <div className='app'> <PrivateRoute exact path='/' auth={props.auth} component={Room} /> <Route path='/login' component={Login} /> </div> </Router> ) const mapStateToProps = (state) => { return { auth: state.auth } } export default connect(mapStateToProps)(App)
src/components/icons/LondonIcon.js
fathomlondon/fathomlondon.github.io
import React from 'react'; import { Icon } from './Icon'; export const LondonIcon = props => ( <Icon {...props} viewBox="0 0 180 209"> <g stroke="currentColor" fill="none" fillRule="evenodd" strokeDasharray="3,2" > <path d="M137.485 208.755V64.353h5.42v144.402M179.351 208.755L143.033 69.62M143.626 97.82h6.7M143.626 131.221h16.272M143.626 164.623h24.887M143.626 197.07h32.545" /> <path d="M63.699 207.801c-4.925-43.42-3.831-80.448 3.28-108.41C74.092 71.43 83.584 57.73 95.787 57.73" /> <path d="M125.966 207.801c4.925-43.42 3.83-80.448-3.28-108.41C115.572 71.43 106.08 57.73 93.878 57.73M73.568 79.135h42.457M97.294 78.988l23.729 23.614M55.273 207.801L34.783.896l-6.584 13.328-6.19-6.37-20.67 199.947M29.312 12.53s3.176 68.815 9.529 195.27M26.228 12.53s-7.232 194.057-7.232 195.27M48.838 143.283h-9.594M50.278 156.623h-9.595M51.717 169.488H42.12M52.676 182.828h-9.595M54.115 195.693H44.52M47.879 130.419h-9.595M46.44 117.078h-9.595M45.48 104.214h-9.595M43.562 90.873h-6.715M42.602 78.01h-7.129M41.163 64.668h-6.308M39.06 51.804h-5.487M38.285 38.464H32.8M74.408 79.392l53.691 53.41M68.406 96.584l59.693 59.378M63.685 115.05l64.414 64.072M61.844 136.38l64.814 64.469M60.676 158.38l49.684 49.423M61.453 182.312l25.618 25.494" /> </g> </Icon> ); LondonIcon.defaultProps = { width: 180, };
app/config/routes.js
JoeDahle/fic
// core import React from 'react'; import { ReactRouter } from 'react-router'; import { Router } from 'react-router'; import { Route } from 'react-router'; import { hashHistory } from 'react-router'; import { IndexRoute } from 'react-router'; import { IndexRedirect } from 'react-router'; // components import MainContainer from '../containers/main/MainContainer'; import HomeContainer from '../containers/home/HomeContainer'; import ShareContainer from '../containers/share/ShareContainer'; var routes = ( <Router history={hashHistory}> <Route path='/' component={MainContainer}> <IndexRedirect to='/home' /> <Route path='home' component={HomeContainer} /> <Route path='spreadtheword' component={ShareContainer} /> </Route> </Router> ); export default routes;
docs/app/Examples/elements/Icon/Groups/IconExampleIconGroup.js
aabustamante/Semantic-UI-React
import React from 'react' import { Icon } from 'semantic-ui-react' const IconExampleIconGroup = () => ( <Icon.Group size='huge'> <Icon size='big' name='thin circle' /> <Icon name='user' /> </Icon.Group> ) export default IconExampleIconGroup
src/svg-icons/navigation/fullscreen.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationFullscreen = (props) => ( <SvgIcon {...props}> <path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/> </SvgIcon> ); NavigationFullscreen = pure(NavigationFullscreen); NavigationFullscreen.displayName = 'NavigationFullscreen'; NavigationFullscreen.muiName = 'SvgIcon'; export default NavigationFullscreen;
src/tools/code-template/ui/UserTable.js
steem/qwp-antd
import React from 'react' import PropTypes from 'prop-types' import { Modal, Button, Form, message } from 'antd' import styles from './UserTable.less' import classnames from 'classnames' import DateTable from 'components/DataTable' import { DropOption } from 'components' import { Link } from 'dva/router' import RandomAvatar from 'components/Helper/RandomAvatar' import { l } from 'utils/localization' import { uriOfList } from 'requests/user' import layout from 'utils/layout' import { createOkHander } from 'utils/form' import { HorizontalFormGenerator } from 'components/Helper/FormGenerator' import UserDialog from './UserDialog' const confirm = Modal.confirm let searchContent = { inline: true, formItems:{ name: 'user', fields: [{ id: 'createTime', datePicker: true, placeholder: l('Create time'), inputProps: { size: 'medium', }, itemProps: { style: { width: 100 }, } }, { id: 'name', input: 'text', placeholder: l('Name'), inputProps: { size: 'medium', }, }, ], } } function createColOptions(handleMenuClick, handleClickUser) { return { render: { avatar (text, record) { return (<RandomAvatar text={record.nickName.substr(0, 1)}/>) }, name (text, record) { return (<Link title={l('Click to update user information')} onClick={e => handleClickUser(record)}>{text}</Link>) }, isMale (text, record) { return (<span>{ text ? 'Male' : 'Female' }</span>) }, operation (text, record) { return (<DropOption onMenuClick={e => handleMenuClick(record, e)} menuOptions={[{ key: '1', name: 'Update' }, { key: '2', name: 'Delete' }]} />) }, }, className: { avatar: styles.avatar }, } } let UserTable = React.createClass({ getInitialState () { this.colOptions = createColOptions(this.handleMenuClick, this.showEditUserDialog) this.tableColumns = layout.getTableColumn(this.props.tables, this.colOptions) searchContent.form = this.props.form searchContent.appSettings = this.props.appSettings return { createUserDialogVisible: false, editUserDialogVisible: false, } }, showCreateUserDialog () { this.setState({ createUserDialogVisible: true, }) }, hideCreateUserDialog () { this.setState({ createUserDialogVisible: false, }) }, createUser (data) { this.hideCreateUserDialog() this.props.dispatch({ type: 'user/create', payload: data, }) }, showEditUserDialog (user) { this.setState({ editUserDialogVisible: true, selectedUser: user, }) }, hideEditUserDialog () { this.setState({ editUserDialogVisible: false, }) }, editUser (data) { this.hideEditUserDialog() data.id = this.state.selectedUser.id this.props.dispatch({ type: 'user/update', payload: data, }) }, handleEditUser () { if (this.props.user.selectedUserKeys.length === 0) { message.warning(l('No users are selected, please selected users first')) return } if (this.props.user.selectedUserKeys.length > 1) { message.warning(l('Please select just one user to edit')) return } this.showEditUserDialog(this.state.selectedUser) }, updateModalUsersSelection (selectedUserKeys) { this.props.dispatch({ type: 'user/updateState', payload: { selectedUserKeys, }, }) }, onSelectionChanged (selectedUserKeys, selectedRows) { this.updateModalUsersSelection(selectedUserKeys) this.setState({ selectedUser: selectedRows.length > 0 ? selectedRows[0] : 0 }) }, onDataUpdated () { this.updateModalUsersSelection([]) }, handleDeleteUser () { this.deleteUsers() }, deleteUsers (id, title) { if (!id) { if (this.props.user.selectedUserKeys.length === 0) { message.warning(l('No users are selected, please selected users first')) return } id = this.props.user.selectedUserKeys.join(',') } let dispatch = this.props.dispatch confirm({ title: title || l('Are you sure to delete the selected users?'), onOk () { dispatch({ type: 'user/delete', payload: {f: id}, }) }, }) }, handleMenuClick (record, e) { if (e.key === '1') { this.showEditUserDialog(record) } else if (e.key === '2') { this.deleteUsers(record.id, l('Are you sure to delete this user?')) } }, render () { const { location, keyId, tables, appSettings, dispatch, loading, user, } = this.props const createUserDialogProps = { visible: this.state.createUserDialogVisible, onOk: this.createUser, onCancel: this.hideCreateUserDialog, appSettings, create: true, formData: user.lastCreateUserData, } const editUserDialogProps = { visible: this.state.editUserDialogVisible, onOk: this.editUser, onCancel: this.hideEditUserDialog, appSettings, create: false, formData: this.state.selectedUser, } let tableProps = { fetch: uriOfList(), columns: this.tableColumns, operations: (<div className="qwp-table-perations"> <Button.Group size="medium"> <Button type="primary" onClick={this.showCreateUserDialog} loading={loading.effects['user/create']} icon="plus-circle-o">{l('Create')}</Button> <Button className="btn-warning" onClick={this.handleEditUser} loading={loading.effects['user/update']} icon="edit">{l('Edit')}</Button> <Button className="btn-danger" onClick={this.handleDeleteUser} loading={loading.effects['user/delete']} icon="minus-circle-o">{l('Delete')}</Button> </Button.Group> {this.state.createUserDialogVisible && <UserDialog {...createUserDialogProps}/>} {this.state.editUserDialogVisible && <UserDialog {...editUserDialogProps}/>} </div>), fetchData: { _t: user._t, }, searchContent, onDataUpdated: this.onDataUpdated, rowSelection: { type: 'checkbox', onChange: this.onSelectionChanged, selectedRowKeys: user.selectedUserKeys, }, } if (location.query.org) { tableProps.fetchData.s = { org: location.query.org, } } return ( <DateTable {...tableProps} className={styles.table} rowKey={record => keyId ? record[keyId] : record.id} /> ) } }) UserTable.propTypes = { location: PropTypes.object, appSettings: PropTypes.object, dispatch: PropTypes.func, loading: PropTypes.object, user: PropTypes.object, form: PropTypes.object, } export default Form.create()(UserTable)
src/svg-icons/image/looks-one.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageLooksOne = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-5 14h-2V9h-2V7h4v10z"/> </SvgIcon> ); ImageLooksOne = pure(ImageLooksOne); ImageLooksOne.displayName = 'ImageLooksOne'; ImageLooksOne.muiName = 'SvgIcon'; export default ImageLooksOne;
src/Footer.js
battaile/time-tracking
import React from 'react'; const Footer = () => ( <div className="footer"> <a href="https://github.com/battaile/time-tracking" target="_blank"> View on Github </a> </div> ); export default Footer;
src/components/calendar/Calendar.js
reichert621/log-book
import React from 'react' import moment from 'moment' import classes from './Calendar.scss' import CalendarHeader from './CalendarHeader.js' import CalendarDay from './CalendarDay.js' const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] // TODO: move to container component? const generateWeeks = (month, year) => { let weeks = [] let _current = new Date(year, month, 1) const offset = _current.getDay() - 1 while (_current.getMonth() === month) { let dayIndex = _current.getDay() let _month = _current.getMonth() let _date = _current.getDate() let weekIndex = Math.floor((_date + offset) / 7) weeks[weekIndex] = weeks[weekIndex] || [] weeks[weekIndex][dayIndex] = { day: _date, month: _month, date: _current } _current = new Date(year, month, _date + 1) } // Ensure each week row includes 7 elements for (let i = 0; i < weeks.length; i++) { let _week = weeks[i] for (let j = 0; j < 7; j++) { _week[j] = _week[j] || {} } } return weeks } const Calendar = ({ month, year, entries }) => { const _month = month - 1 const weeks = generateWeeks(_month, year) let weekRows = weeks.map((week, key) => { return ( <tr key={key}> { week.map((date, _key) => { date.dateId = moment(date.date).format('YYYYMMDD') let entry = entries[date.dateId] let isDisabled = (moment().diff(moment(date.date)) < 0) return ( <CalendarDay key={_key} entry={entry} date={date} month={month} year={year} isDisabled={isDisabled} /> ) }) } </tr> ) }) let columns = DAYS.map((day, key) => { return ( <th key={key} className={classes['calendar-day-label']}> {day} </th> ) }) return ( <div className={classes['calendar-container']}> <CalendarHeader month={month} year={year}/> <table className={classes['calendar-table']}> <tbody> <tr>{columns}</tr> {weekRows} </tbody> </table> </div> ) } Calendar.propTypes = { year: React.PropTypes.number.isRequired, month: React.PropTypes.number.isRequired, weeks: React.PropTypes.array } export default Calendar
app/javascript/mastodon/features/mutes/index.js
theoria24/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { debounce } from 'lodash'; import LoadingIndicator from '../../components/loading_indicator'; import Column from '../ui/components/column'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import AccountContainer from '../../containers/account_container'; import { fetchMutes, expandMutes } from '../../actions/mutes'; import ScrollableList from '../../components/scrollable_list'; const messages = defineMessages({ heading: { id: 'column.mutes', defaultMessage: 'Muted users' }, }); const mapStateToProps = state => ({ accountIds: state.getIn(['user_lists', 'mutes', 'items']), hasMore: !!state.getIn(['user_lists', 'mutes', 'next']), isLoading: state.getIn(['user_lists', 'mutes', 'isLoading'], true), }); export default @connect(mapStateToProps) @injectIntl class Mutes extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, hasMore: PropTypes.bool, isLoading: PropTypes.bool, accountIds: ImmutablePropTypes.list, intl: PropTypes.object.isRequired, multiColumn: PropTypes.bool, }; componentWillMount () { this.props.dispatch(fetchMutes()); } handleLoadMore = debounce(() => { this.props.dispatch(expandMutes()); }, 300, { leading: true }); render () { const { intl, hasMore, accountIds, multiColumn, isLoading } = this.props; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } const emptyMessage = <FormattedMessage id='empty_column.mutes' defaultMessage="You haven't muted any users yet." />; return ( <Column bindToDocument={!multiColumn} icon='volume-off' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <ScrollableList scrollKey='mutes' onLoadMore={this.handleLoadMore} hasMore={hasMore} isLoading={isLoading} emptyMessage={emptyMessage} bindToDocument={!multiColumn} > {accountIds.map(id => <AccountContainer key={id} id={id} />, )} </ScrollableList> </Column> ); } }
src/scripts/playground/react-router.js
lenshq/lens_front
import React, { Component } from 'react'; import Router, { Route, Link, DefaultRoute } from 'react-router'; import { history } from 'react-router/lib/HashHistory'; import { routerStateReducer, reduxRouteComponent, transitionTo } from 'redux-react-router'; class App extends Component { render() { return ( <div> <h1>Hey! It's me, app!</h1> <ul> <li><Link to='/hey'>hey</Link></li> <li><Link to='/ho'>ho</Link></li> </ul> {this.props.children} </div> ) } } class Hey { render() { return <div>hey!</div> } } class Ho { render() { return <div>ho!</div> } } const routes = ( <Route path='/' component={App}> <Route path='/hey' component={Hey} /> <Route path='/ho' component={Ho} /> </Route> ); React.render(( <Router history={history}>{routes}</Router> ), document.getElementById('root'));
src/components/users/PortfolioCard.js
jackson-/colorforcode
import React from 'react' import { Col, Image } from 'react-bootstrap' import PropTypes from 'prop-types' import Chips from '../utilities/chips/Chips' import './UserProfile.css' const PortfolioCard = ({opacity, title, src, skills, handleClick, handleOnLoad}) => ( <Col className='portfolio-card-container' xs={12} sm={6} md={6} lg={6}> <button className='portfolio-card' onClick={handleClick}> <div className='screenshot-placeholder'> <Image style={{opacity}} className='UserDetail__project-screenshot' src={src} alt={`Screenshot of ${title}`} responsive onLoad={handleOnLoad} /> </div> <div className='portfolio-card__text'> <h4>{title}</h4> <Chips words={skills} type={'square-bordered'} align={'center'} justify={'flex-start'} margin={'10px 0'} /> </div> </button> </Col> ) PortfolioCard.propTypes = { skills: PropTypes.array, handleClick: PropTypes.func, handleOnLoad: PropTypes.func, title: PropTypes.string, src: PropTypes.string, opacity: PropTypes.string } export default PortfolioCard
react-flux-mui/js/material-ui/docs/src/app/components/pages/components/IconButton/ExampleSimple.js
pbogdan/react-flux-mui
import React from 'react'; import IconButton from 'material-ui/IconButton'; const IconButtonExampleSimple = () => ( <div> <IconButton iconClassName="muidocs-icon-custom-github" /> <IconButton iconClassName="muidocs-icon-custom-github" disabled={true} /> </div> ); export default IconButtonExampleSimple;
src/index.js
kiley0/personal-site
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import 'skeleton-css/css/normalize.css'; import 'skeleton-css/css/skeleton.css'; import './bootstrap-utils.css'; import './index.css'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
src/icons/SlideshowIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class SlideshowIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M20 16v16l10-8-10-8zM38 6H10c-2.21 0-4 1.79-4 4v28c0 2.21 1.79 4 4 4h28c2.21 0 4-1.79 4-4V10c0-2.21-1.79-4-4-4zm0 32H10V10h28v28z"/></svg>;} };
client/components/preview/Checkbox.react.js
blueberryapps/react-bluekit-web
import Component from 'react-pure-render/component'; import ErrorMessage from './ErrorMessage.react'; import Radium from 'radium'; import React from 'react'; import ToolTip from './ToolTip.react'; @Radium export default class Checkbox extends Component { static propTypes = { error: React.PropTypes.string, label: React.PropTypes.string.isRequired, name: React.PropTypes.string.isRequired, onChange: React.PropTypes.func, tooltip: React.PropTypes.string, value: React.PropTypes.bool } render() { const {name, onChange, label, value, tooltip} = this.props; const focused = Radium.getState(this.state, 'input', ':focus'); return ( <div style={styles.wrapper}> <label style={styles.label}> <div style={[styles.base, focused && styles.baseFocused]}> <div style={[styles.unchecked, value && styles.checked]} /> </div> <input checked={value} key='input' name={name} onChange={onChange} style={styles.input} type='checkbox' /> <div style={styles.checkboxLabel}>{label}</div> {tooltip && <ToolTip inheritedStyles={styles.tooltip}> {tooltip} </ToolTip> } </label> {this.renderError()} </div> ); } renderError() { const {error} = this.props; if (!error) return null; return <ErrorMessage>{error}</ErrorMessage>; } }; const styles = { wrapper: { height: '50px', display: 'inline-block', verticalAlign: 'top', padding: '12px 0' }, label: { position: 'relative', paddingLeft: '25px', paddingRight: '20px', userSelect: 'none', cursor: 'pointer' }, checkboxLabel: { fontWeight: 'normal', padding: '0 6px', display: 'inline-block', position: 'relative', top: '3px' }, input: { position: 'absolute', left: '-9999px', ':focus': {} }, base: { width: '24px', height: '24px', borderWidth: '1px', borderStyle: 'solid', borderColor: 'hsl(0, 0%, 80%)', position: 'absolute', left: 0, top: 0 }, baseFocused: { borderColor: 'hsl(0, 0%, 50%)', backgroundColor: 'hsl(0, 0%, 95%)' }, unchecked: { width: '18px', height: '18px', backgroundColor: '#6dad0d', backgroundImage: 'linear-gradient(bottom, #6dad0d 0%, #81d10b 100%)', position: 'absolute', top: '3px', left: '3px', transform: 'scale(0, 0)' }, checked: { transform: 'scale(1, 1)', transition: 'transform .2s' }, tooltip: { bottom: 'calc(100% + 10px)', top: 'auto' }, form: { input: { base: { fontWeight: '300', borderWidth: '1px', borderStyle: 'solid', borderColor: 'hsl(0, 0%, 80%)', outline: 'none', WebkitAppearance: 'none', borderRadius: 0, transition: 'border-color .2s', ':focus': { borderColor: 'hsl(0, 0%, 40%)' } }, size: { regular: { height: '50px', padding: '0 20px', fontSize: '16px', '@media (max-width: 480px)': { height: '40px' } }, large: { fontSize: '18px', padding: '20px 20px', '@media (max-width: 480px)': { padding: '10px 15px', fontSize: '15px' } } } } } };
catalog/app/containers/Auth/PassReset.js
quiltdata/quilt-compiler
import * as FF from 'final-form' import React from 'react' import * as RF from 'react-final-form' import * as redux from 'react-redux' import * as Config from 'utils/Config' import * as NamedRoutes from 'utils/NamedRoutes' import * as Sentry from 'utils/Sentry' import Link from 'utils/StyledLink' import defer from 'utils/defer' import * as validators from 'utils/validators' import { resetPassword } from './actions' import * as errors from './errors' import * as Layout from './Layout' const Container = Layout.mkLayout('Reset Password') export default function PassReset() { const [done, setDone] = React.useState(false) const sentry = Sentry.use() const dispatch = redux.useDispatch() const cfg = Config.useConfig() const { urls } = NamedRoutes.use() const onSubmit = React.useCallback( // eslint-disable-next-line consistent-return async (values) => { try { const result = defer() dispatch(resetPassword(values.email, result.resolver)) await result.promise setDone(true) } catch (e) { if (e instanceof errors.SMTPError) { return { [FF.FORM_ERROR]: 'smtp', } } sentry('captureException', e) return { [FF.FORM_ERROR]: 'unexpected', } } }, [dispatch, sentry, setDone], ) if (done) { return ( <Container> <Layout.Message> You have requested a password reset. Check your email for further instructions. </Layout.Message> </Container> ) } return ( <Container> <RF.Form onSubmit={onSubmit}> {({ error, handleSubmit, hasSubmitErrors, hasValidationErrors, modifiedSinceLastSubmit, submitFailed, submitting, }) => ( <form onSubmit={handleSubmit}> <RF.Field component={Layout.Field} name="email" validate={validators.required} disabled={submitting} floatingLabelText="Email" errors={{ required: 'Enter your email', }} /> <Layout.Error {...{ submitFailed, error }} errors={{ unexpected: 'Something went wrong. Try again later.', smtp: 'SMTP error: contact your administrator', }} /> <Layout.Actions> <Layout.Submit label="Reset" disabled={ submitting || (hasValidationErrors && submitFailed) || (hasSubmitErrors && !modifiedSinceLastSubmit) } busy={submitting} /> </Layout.Actions> {(cfg.passwordAuth === true || cfg.ssoAuth === true) && ( <Layout.Hint> <> Don&apos;t have an account? <Link to={urls.signUp()}>Sign up</Link> </> </Layout.Hint> )} </form> )} </RF.Form> </Container> ) }
client/src/components/helpers/form/BlockSaveWrapper.js
pahosler/freecodecamp
import React from 'react'; import PropTypes from 'prop-types'; const propTypes = { children: PropTypes.node }; const style = { padding: '0 15px' }; function BlockSaveWrapper({ children, ...restProps }) { return ( <div style={style} {...restProps}> {children} </div> ); } BlockSaveWrapper.displayName = 'BlockSaveWrapper'; BlockSaveWrapper.propTypes = propTypes; export default BlockSaveWrapper;
redux/todoList/src/test/app.js
yuanzhaokang/myAwesomeSimpleDemo
import React, { Component } from 'react'; import { connect } from 'react-redux'; import types from './actions'; class App extends Component { constructor(props) { super(props); } render() { let { dispatch, value } = this.props; return ( <div> {value} <div onClick={() => { dispatch({ type: types.ADD }) }}>add</div> <div onClick={() => { dispatch({ type: types.REDUCE }) }}>reduce</div> <div>s</div> </div> ); } } const mapStateToProps = state => ({ ...state.add }); export default connect(mapStateToProps)(App);
app/javascript/flavours/glitch/features/lists/index.js
Kirishima21/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import LoadingIndicator from 'flavours/glitch/components/loading_indicator'; import Column from 'flavours/glitch/features/ui/components/column'; import ColumnBackButtonSlim from 'flavours/glitch/components/column_back_button_slim'; import { fetchLists } from 'flavours/glitch/actions/lists'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ColumnLink from 'flavours/glitch/features/ui/components/column_link'; import ColumnSubheading from 'flavours/glitch/features/ui/components/column_subheading'; import NewListForm from './components/new_list_form'; import { createSelector } from 'reselect'; import ScrollableList from 'flavours/glitch/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, 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='bars' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <NewListForm /> <ColumnSubheading text={intl.formatMessage(messages.subheading)} /> <ScrollableList scrollKey='lists' emptyMessage={emptyMessage} bindToDocument={!multiColumn} > {lists.map(list => <ColumnLink key={list.get('id')} to={`/lists/${list.get('id')}`} icon='list-ul' text={list.get('title')} />, )} </ScrollableList> </Column> ); } }
client/src/containers/pages/Home.js
shmilky/node-react-template
'use strict'; import React from 'react'; import {Link} from 'react-router-dom'; import routingHelpers from 'react-router-routing-helpers'; import {demoPages as demoPagesRoutes, modalNames} from '../../routes'; import {SharedComponent} from '../../components'; import styleGuide from '../../styleMain/styleGuide.global.sass'; export default class extends React.Component { openModal () { const {pathname, search} = this.props.location; const urlWithNoModal = routingHelpers.addQueryParam(pathname, search, {modal: modalNames.DEMO_MODAL}); this.props.history.push(urlWithNoModal); } render () { return ( <div> <h1>Home Page</h1> <h2 className="only-mobile">Mobile Only</h2> <h2 className="only-desktop">Desktop Only</h2> <p>For data using demo go to - <Link to={demoPagesRoutes.DEMO_PAGE}>Demo Page</Link></p> <p>To see modal behavior click on - <button onClick={this.openModal.bind(this)}>Open Modal</button></p> <SharedComponent/> </div> ); } }
examples/mobx/src/App.js
gaearon/react-hot-loader
import React from 'react'; import { hot, setConfig } from 'react-hot-loader'; import Counter from './Counter'; const Element1 = ({ children }) => <div>Block1 {children}</div>; const Element2 = () => ( <div> Block2 <Counter /> </div> ); const App = () => ( <h1> Hello, mobx<br /> <Counter /> <Element1> <Counter /> </Element1> <Element2 /> </h1> ); setConfig({ logLevel: 'debug' }); export default hot(module)(App);
fields/types/markdown/MarkdownColumn.js
jacargentina/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var MarkdownColumn = React.createClass({ displayName: 'MarkdownColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; return (value && Object.keys(value).length) ? value.md.substr(0, 100) : null; }, render () { return ( <ItemsTableCell> <ItemsTableValue field={this.props.col.type}> {this.renderValue()} </ItemsTableValue> </ItemsTableCell> ); }, }); module.exports = MarkdownColumn;
app/components/widgets/ResizeblePanel.js
sheldhur/Vector
// @flow import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { numberIsBetween } from '../../utils/helper'; export class ResizeblePanel extends Component { state = { size: this.props.defaultSize }; sendResizeEvent = () => { window.dispatchEvent(new CustomEvent('resize')); console.info('EVENT RESIZE'); }; handleResize = (event) => { event.preventDefault(); // if (this.props.eventWhen === 'mousemove') { // this.sendResizeEvent(); // } let size = 0; if (this.props.type === 'horizontal') { size = numberIsBetween(100 * event.clientX / document.body.clientWidth, this.props.resizeRange, true, false); } else if (this.props.type === 'vertical') { size = numberIsBetween(100 * event.clientY / document.body.clientHeight, this.props.resizeRange, true, false); } if (size !== this.state.size) { this.setState({ size }); } if (this.props.eventWhen === 'mousemove') { this.sendResizeEvent(); } }; handleResizeStart = (event) => { if (event.button === 0) { event.preventDefault(); document.addEventListener('mousemove', this.handleResize); document.addEventListener('mouseup', this.handleResizeEnd); } }; handleResizeEnd = (event) => { if (event.button === 0) { event.preventDefault(); if (this.props.eventWhen === 'mouseup') { this.sendResizeEvent(); } document.removeEventListener('mousemove', this.handleResize); document.removeEventListener('mouseup', this.handleResizeEnd); } }; render = () => { let delimiterPos; let sizeFirst; let sizeSecond; if (this.props.type === 'horizontal') { delimiterPos = { left: `${this.state.size}%` }; sizeFirst = { width: `${this.state.size}%` }; sizeSecond = { width: `${100 - this.state.size}%` }; } else if (this.props.type === 'vertical') { delimiterPos = { top: `${this.state.size}%` }; sizeFirst = { height: `${this.state.size}%` }; sizeSecond = { height: `${100 - this.state.size}%` }; } return ( <div className={`resizeble-panel ${this.props.type}`}> {React.cloneElement(this.props.children[0], { size: sizeFirst })} {React.cloneElement(this.props.children[1], { size: sizeSecond })} <div onMouseDown={this.handleResizeStart} style={delimiterPos} /> </div> ); }; } ResizeblePanel.propTypes = { type: PropTypes.string, resizeRange: PropTypes.array, defaultSize: PropTypes.number, eventWhen: PropTypes.string }; ResizeblePanel.defaultProps = { type: 'horizontal', resizeRange: [20, 80], eventWhen: 'mousemove' }; export class Panel extends Component { constructor(props) { super(props); } render() { return ( <div style={this.props.size} className={this.props.className}>{this.props.children}</div> ); } }
templates/bootstrap/imports/startup/client/index.js
Batistleman/mgb
import { Meteor } from 'meteor/meteor'; import React from 'react'; import { render } from 'react-dom'; import HelloWorld from '/imports/ui/components/HelloWorld'; import './routes'; Meteor.startup(() => { render(<HelloWorld />, document.getElementById('app')); });
src/js/index.js
janjakubnanista/dnes.fetujem
import React from 'react'; import Game from './game'; React.render(<Game/>, document.getElementById('container'));
client/src/Home.js
ruslan2k/web-password
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Redirect } from 'react-router'; import { Button } from 'semantic-ui-react'; import { fetchGroups } from './actions'; class Home extends Component { componentDidMount() { const isLoggedIn = this.props.user.isLoggedIn; if (isLoggedIn) { this.props.fetchGroups(); } } render() { const isLoggedIn = this.props.user.isLoggedIn; if (!isLoggedIn) { return <Redirect to='/login' />; } const groups = this.props.groups.map(group => <Button key={group.id}>{group.name}</Button>); return ( <div> <h1>Groups</h1> {groups} </div> ); } } const mapStateToProps = state => ({ user: state.user, groups: state.groups }); const mapDispatchToProps = dispatch => ({ fetchGroups: () => dispatch(fetchGroups()), }); export default connect(mapStateToProps, mapDispatchToProps)(Home);
fields/types/text/TextFilter.js
w01fgang/keystone
import React from 'react'; import { findDOMNode } from 'react-dom'; import { FormField, FormInput, FormSelect, SegmentedControl, } from '../../../admin/client/App/elemental'; const INVERTED_OPTIONS = [ { label: 'Matches', value: false }, { label: 'Does NOT Match', value: true }, ]; const MODE_OPTIONS = [ { label: 'Contains', value: 'contains' }, { label: 'Exactly', value: 'exactly' }, { label: 'Begins with', value: 'beginsWith' }, { label: 'Ends with', value: 'endsWith' }, ]; function getDefaultValue () { return { mode: MODE_OPTIONS[0].value, inverted: INVERTED_OPTIONS[0].value, value: '', }; } var TextFilter = React.createClass({ propTypes: { filter: React.PropTypes.shape({ mode: React.PropTypes.oneOf(MODE_OPTIONS.map(i => i.value)), inverted: React.PropTypes.boolean, value: React.PropTypes.string, }), }, statics: { getDefaultValue: getDefaultValue, }, getDefaultProps () { return { filter: getDefaultValue(), }; }, updateFilter (value) { this.props.onChange({ ...this.props.filter, ...value }); }, selectMode (e) { const mode = e.target.value; this.updateFilter({ mode }); findDOMNode(this.refs.focusTarget).focus(); }, toggleInverted (inverted) { this.updateFilter({ inverted }); findDOMNode(this.refs.focusTarget).focus(); }, updateValue (e) { this.updateFilter({ value: e.target.value }); }, render () { const { field, filter } = this.props; const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0]; const placeholder = field.label + ' ' + mode.label.toLowerCase() + '...'; return ( <div> <FormField> <SegmentedControl equalWidthSegments onChange={this.toggleInverted} options={INVERTED_OPTIONS} value={filter.inverted} /> </FormField> <FormField> <FormSelect onChange={this.selectMode} options={MODE_OPTIONS} value={mode.value} /> </FormField> <FormInput autoFocus onChange={this.updateValue} placeholder={placeholder} ref="focusTarget" value={this.props.filter.value} /> </div> ); }, }); module.exports = TextFilter;
lib/Selection/DefaultOptionFormatter.js
folio-org/stripes-components
import React from 'react'; import PropTypes from 'prop-types'; import OptionSegment from './OptionSegment'; const propTypes = { option: PropTypes.object, searchTerm: PropTypes.string, }; const DefaultOptionFormatter = ({ option, searchTerm }) => { if (option) { return <OptionSegment searchTerm={searchTerm}>{option.label}</OptionSegment>; } return null; }; DefaultOptionFormatter.propTypes = propTypes; export default DefaultOptionFormatter;
src/containers/Form/DateTimePage.js
Aus0049/react-component
/** * Created by Aus on 2017/7/26. */ import React from 'react' import ListTitle from '../../components/DataDisplay/ListTitle/' import {DateTime} from '../../components/Form/' import Tools from '../../components/Tools/Tools' import moment from 'moment' class DateTimePage extends React.Component { constructor (props) { super(props); this.state = { value1: {required: true, labelName: '日期', value: moment()}, value2: {required: false, labelName: '日期时间', value: moment(), kind: 'datetime'}, value3: {required: false, labelName: '日期时间', value: undefined, kind: 'datetime'}, value4: {readOnly: true, required: false, labelName: '日期时间', value: moment(), kind: 'datetime'}, value5: {readOnly: true, required: false, labelName: '日期时间', value: moment(), kind: 'datetime'}, }; } handleChange (type, value) { this.setState((previousState)=>{ previousState[type] = Object.assign(previousState[type], value); return {...previousState}; }); } render () { const {value1, value2, value3, value4, value5} = this.state; return ( <div className="page date-range"> <h1 className="title"> <i className="fa fa-home" onClick={()=>{Tools.linkTo('/index')}} /> DateTime </h1> <ListTitle title="普通" /> <div className='zby-form-box'> <DateTime {...value1} onChange={this.handleChange.bind(this, 'value1')} /> <DateTime {...value2} onChange={this.handleChange.bind(this, 'value2')} /> <DateTime {...value3} onChange={this.handleChange.bind(this, 'value3')} /> </div> <ListTitle title="readonly" /> <div className='zby-form-box'> <DateTime {...value4} /> <DateTime {...value5} /> </div> </div> ) } } export default DateTimePage
app/components/H3/index.js
anhldbk/react-boilerplate
import React from 'react'; function H3(props) { return ( <h3 {...props} /> ); } export default H3;
tools/render.js
patmood/svg-jsx-online
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import glob from 'glob'; import { join, dirname } from 'path'; import React from 'react'; import ReactDOM from 'react-dom/server'; import Html from '../components/Html'; import task from './lib/task'; import fs from './lib/fs'; const DEBUG = !process.argv.includes('release'); function getPages() { return new Promise((resolve, reject) => { glob('**/*.js', { cwd: join(__dirname, '../pages') }, (err, files) => { if (err) { reject(err); } else { const result = files.map(file => { let path = '/' + file.substr(0, file.lastIndexOf('.')); if (path === '/index') { path = '/'; } else if (path.endsWith('/index')) { path = path.substr(0, path.lastIndexOf('/index')); } return { path, file }; }); resolve(result); } }); }); } async function renderPage(page, component) { const data = { body: ReactDOM.renderToString(component), }; const file = join(__dirname, '../build', page.file.substr(0, page.file.lastIndexOf('.')) + '.html'); const html = '<!doctype html>\n' + ReactDOM.renderToStaticMarkup(<Html debug={DEBUG} {...data} />); await fs.mkdir(dirname(file)); await fs.writeFile(file, html); } export default task(async function render() { const pages = await getPages(); const { route } = require('../build/app.node'); for (const page of pages) { await route(page.path, renderPage.bind(undefined, page)); } });
node_modules/react-bootstrap/es/BreadcrumbItem.js
newphew92/newphew92.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 classNames from 'classnames'; import React from 'react'; import SafeAnchor from './SafeAnchor'; var propTypes = { /** * If set to true, renders `span` instead of `a` */ active: React.PropTypes.bool, /** * `href` attribute for the inner `a` element */ href: React.PropTypes.string, /** * `title` attribute for the inner `a` element */ title: React.PropTypes.node, /** * `target` attribute for the inner `a` element */ target: React.PropTypes.string }; var defaultProps = { active: false }; var BreadcrumbItem = function (_React$Component) { _inherits(BreadcrumbItem, _React$Component); function BreadcrumbItem() { _classCallCheck(this, BreadcrumbItem); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } BreadcrumbItem.prototype.render = function render() { var _props = this.props; var active = _props.active; var href = _props.href; var title = _props.title; var target = _props.target; var className = _props.className; var props = _objectWithoutProperties(_props, ['active', 'href', 'title', 'target', 'className']); // Don't try to render these props on non-active <span>. var linkProps = { href: href, title: title, target: target }; return React.createElement( 'li', { className: classNames(className, { active: active }) }, active ? React.createElement('span', props) : React.createElement(SafeAnchor, _extends({}, props, linkProps)) ); }; return BreadcrumbItem; }(React.Component); BreadcrumbItem.propTypes = propTypes; BreadcrumbItem.defaultProps = defaultProps; export default BreadcrumbItem;
app/containers/VideoViewerContainer.js
MutatedBread/binary-academy-rn
import React, { Component } from 'react'; import { bindActionCreators } from 'redux' import { connect } from 'react-redux'; import VideoViewer from './../components/views/VideoViewer.js' const mapStateToProps = state => ({ }); const mapDispatchToProps = (dispatch) => ({ goBackToRoot: () => { dispatch({type: 'VIEW_ROOT'}); }, }); export default connect(mapStateToProps, mapDispatchToProps)(VideoViewer);
src/svg-icons/action/feedback.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionFeedback = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 12h-2v-2h2v2zm0-4h-2V6h2v4z"/> </SvgIcon> ); ActionFeedback = pure(ActionFeedback); ActionFeedback.displayName = 'ActionFeedback'; ActionFeedback.muiName = 'SvgIcon'; export default ActionFeedback;
src/routes/contact/Contact.js
rameshrr/dicomviewer
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Contact.css'; class Contact extends React.Component { static propTypes = { title: PropTypes.string.isRequired, }; render() { return ( <div className={s.root}> <div className={s.container}> <h1>{this.props.title}</h1> <p>...</p> </div> </div> ); } } export default withStyles(s)(Contact);
data-browser-ui/public/app/components/tableComponents/td/fileTdComponent.js
CloudBoost/cloudboost
import React from 'react'; import ReactDOM from 'react-dom'; import LinearProgress from 'material-ui/LinearProgress'; import FilePicker from './filePicker' import CONFIG from '../../../config/app.js' import Axios from 'axios' import ReactTooltip from 'react-tooltip' class FileTdComponent extends React.Component { constructor() { super() this.state = { isModalOpen: false, file: {}, isFilePickerOpen:false } } componentDidMount() { this.fetchImageFromCB(this.props) } componentWillReceiveProps(props) { this.fetchImageFromCB(props) } addFile(file) { this.setState({ file: file, isFilePickerOpen:false}) this.props.updateElement(file) this.props.updateObject() } downloadFile() { if (!this.checkIfPrivateFile(this.state.file)) { // for public files let win = window.open(this.state.file.url, '_blank') win.focus() } else { // for private files Axios({ method: 'post', data: { key: CB.appKey }, url: this.state.file.url, withCredentials: false, responseType: 'blob' }).then(function (res) { var blob = res.data; saveAs(blob, this.state.file.name) }.bind(this), function (err) { console.log(err) }) } } checkIfPrivateFile(file) { let fileACL = file.ACL.document || file.ACL return fileACL.read.allow.user.indexOf('all') === -1 } deleteFile(permanent) { this.props.updateElement(null) this.props.updateObject() if(permanent){ this.state.file.delete() } this.setState({ file: {}, isModalOpen:false }) } fetchImageFromCB(props) { if (props.elementData) { props.elementData.fetch({ success: function (file) { file = file || {} this.setState({ file: file }) //received file Object }.bind(this), error: function (err) { //error in getting file Object } }); } } getFileIcon(file) { if (file.type) { let fileType = file.type.split("/")[1] if (fileType) { if (['png', 'jpeg', 'jpg', 'gif'].indexOf(fileType) > -1) { return <img src={ this.checkIfPrivateFile(file) ? 'public/app/assets/images/file/file.png' : file.url } className={ this.checkIfPrivateFile(file) ? 'fsmimagenf' : 'fsmimage' } /> } else if (CONFIG.iconTypes.indexOf(fileType) > -1) { return <img src={"public/app/assets/images/file/" + fileType + ".png"} className="fsmimagenf" /> } else { return <img src={"public/app/assets/images/file/file.png"} className="fsmimagenf" /> } } else { return <img src={"public/app/assets/images/file/file.png"} className="fsmimagenf" /> } } } getPreviewIcon(file) { if (file.type) { let fileType = file.type.split("/")[1] if (fileType) { if (['png', 'jpeg', 'jpg', 'gif'].indexOf(fileType) > -1) { return <img className={file.document ? 'previewSmallImage' : 'hide'} src={this.checkIfPrivateFile(file) ? 'public/app/assets/images/file/file.png' : file.url} /> } else if (CONFIG.iconTypes.indexOf(fileType) > -1) { return <img src={"public/app/assets/images/file/" + fileType + ".png"} className={file.document ? 'previewSmallImage' : 'hide'} /> } else { return <img className={file.document ? 'previewSmallImage' : 'hide'} src={'public/app/assets/images/file/file.png'} /> } } else { return <img className={file.document ? 'previewSmallImage' : 'hide'} src={'public/app/assets/images/file/file.png'} /> } } } cancelFileSave() { this.props.fetchObject() this.openCloseModal(false) } openCloseModal(what) { this.state.isModalOpen = what //open filepicker if no file is attachced if(what === true && !this.state.file.document){ this.state.isModalOpen = false this.state.isFilePickerOpen = true } this.setState(this.state) } openCloseFilePicker(what){ this.state.isFilePickerOpen = what this.setState(this.state) } render() { let requiredClass = this.props.isRequired ? " requiredred" : "" let dialogTitle = <div className="modaltitle"> <span className="diadlogTitleText">File Editor</span> <i className='fa fa-paperclip iconmodal'></i> </div> return ( <td className={'mdl-data-table__cell--non-numeric pointer' + requiredClass} onDoubleClick={this.openCloseModal.bind(this, true)}> <span className={this.state.file.document ? 'hide' : 'color888 expandleftpspan'}>Upload File</span> {this.getPreviewIcon(this.state.file)} <i className={this.state.file.document ? 'fa fa-expand fr expandCircle' : 'fa fa-expand fr expandCircle'} aria-hidden="true" onClick={this.openCloseModal.bind(this, true)}></i> { //open modal only when filepicker is closed and open modal is true this.state.isModalOpen && !this.state.isFilePickerOpen ? <div className={this.state.isModalOpen ? 'fsmodal':'hide'}> <div className="fsmheading"> <span className="filenamefsm">{this.state.file.name || ""}</span> <i className="ion-android-close closeiconfsm" onClick={this.cancelFileSave.bind(this, false)}></i> </div> { this.getFileIcon(this.state.file) } <div className="fsmfooter"> <i data-tip={ "Delete Permanently" } className="ion-ios-trash-outline deleteiconfsm" onClick={this.deleteFile.bind(this,true)}></i> <i data-tip={ "Delete Reference From CloudObject" } className="ion-android-remove-circle deleteiconfsm" onClick={this.deleteFile.bind(this,false)}></i> <i data-tip={ "Download" } className="ion-ios-download-outline downloadiconfsm" onClick={this.downloadFile.bind(this)}></i> <i data-tip={ "Edit" } className="ion-edit editiconfsm" onClick={this.openCloseFilePicker.bind(this,true)}></i> </div> <ReactTooltip place="top" border={true} offset={{top: 10, left: 10}}/> </div> : '' } { this.state.isFilePickerOpen ? <FilePicker chooseFile={this.addFile.bind(this)} isFilePickerOpen={this.state.isFilePickerOpen} openCloseFilePicker={this.openCloseFilePicker.bind(this)}> </FilePicker> : '' } </td> ); } } export default FileTdComponent;
src/views/HomeView/HomeView.js
gramulos/noteapp
import React from 'react' import { NoteInput, Notes } from '../../containers' const HomeView = () => { return ( <div className='container'> <h1>NotesApp</h1> <NoteInput /> <Notes /> </div> ) } export default HomeView
client/ui/button/index.js
marioblas/neptune
import React from 'react'; import PropTypes from 'prop-types'; import StyledA from './styled-a'; import StyledButton from './styled-button'; /** * Renders a link if href is specified, otherwise renders a button */ const Button = (props) => { const Component = props.href ? StyledA : StyledButton; return ( <Component {...props}> {props.children} </Component> ); }; Button.propTypes = { children: PropTypes.node.isRequired, href: PropTypes.string, }; Button.defaultProps = { href: null, }; export default Button;
src/packages/@ncigdc/modern_components/ClinicalAnalysis/ClinicalVariableCard/modals/ContinuousCustomBinsModal/RangeInput.js
NCI-GDC/portal-ui
import React from 'react'; import styles from './styles'; const { column, input: { inputDisabled, inputError, inputInTable, inputInvalid, }, } = styles; const RangeInput = ({ disabled, error, errorVisible, handleChange, id, value, }) => { return ( <div style={column} > <input readOnly={disabled} id={id} onChange={handleChange} style={{ ...inputInTable, ...(disabled ? inputDisabled : {}), ...(error !== '' && errorVisible ? inputInvalid : {}), }} type="text" value={value} /> {error !== '' && errorVisible && <div style={inputError}>{error}</div>} </div> ); }; export default RangeInput;
contracts/src/deprecated/SellerForm.js
merlox/dapp-transactions
import React from 'react' import './../stylus/index.styl' class SellerForm extends React.Component { constructor(props){ super(props) } handleSubmitForm(event){ event.preventDefault() const data = { sellerGpsLocation: this.refs['seller-gps-location'].value, sellerVatNumber: this.refs['seller-vat-number'].value, transactionVat: this.refs['transaction-vat'].value, sellerCashLedgerHashAddress: this.refs['seller-cash-ledger-hash-address'].value, sellerAssetsLedgerHashAddress: this.refs['seller-assets-ledger-hash-address'].value, } let newCashLedgerAmount = this.refs['seller-new-cash-ledger-amount'].value let newAssetsLedgerAmount = this.refs['seller-new-assets-ledger-amount'].value if(data.sellerCashLedgerHashAddress.length <= 0 && newCashLedgerAmount <= 0){ alert('You need to specify the hash of the cash ledger or the amount of cash for the new cash ledger') return } if(data.sellerAssetsLedgerHashAddress.length <= 0 && newAssetsLedgerAmount <= 0){ alert('You need to specify the hash of the assets ledger or the amount of assets for the new cash ledger') return } this.props.submitSellerForm( data, parseInt(newCashLedgerAmount), parseInt(newAssetsLedgerAmount), ) } render(){ if(this.props.displaySellerForm != false){ return( <div> <h1>Complete the transaction data</h1> <button onClick={() => { this.props.handleState({ displaySellerForm: false }) }}>Back</button> <form className="main-form" ref="main-form" onSubmit={e => { this.handleSubmitForm(e) }}> <label> Seller's GPS location: <input ref="seller-gps-location" type="text" placeholder="GPS location"/> </label> <label> Seller's VAT number: <input ref="seller-vat-number" type="number" placeholder="VAT number"/> </label> <label> VAT for the transaction: <input ref="transaction-vat" type="number" placeholder="VAT amount"/> </label> <label> Sellers's cash ledger hash address: <div> <input ref="seller-cash-ledger-hash-address" type="text" style={{display: this.props.hasCashLedgerAddress ? 'block' : 'none'}} placeholder="IPFS hash address"/> <p ref="seller-new-cash-ledger-hash-address" style={{display: this.props.hasNotCashLedgerAddress ? 'block' : 'none'}}> If you don't have a cash ledger hash address, a new one will be created and you'll get the hash address. If so, please specify how much cash will be stored in it: <input ref="seller-new-cash-ledger-amount" type="number" placeholder="Cash in Ether" defaultValue="0"/> </p> </div> <div> <button type="button" onClick={() => { this.props.handleState({ hasNotCashLedgerAddress: false, hasCashLedgerAddress: true }) }}>I have a cash ledger IPFS hash address</button> <button type="button" onClick={() => { this.props.handleState({ hasNotCashLedgerAddress: true, hasCashLedgerAddress: false }) }}>I don't have a cash ledger IPFS hash address</button> </div> </label> <label> Seller's assets ledger hash address: <div> <input ref="seller-assets-ledger-hash-address" type="text" style={{display: this.props.hasAssetsLedgerAddress ? 'block' : 'none'}} placeholder="IPFS hash address"/> <p ref="seller-new-assets-ledger-hash-address" style={{display: this.props.hasNotAssetsLedgerAddress ? 'block' : 'none'}}> If you don't have an assets ledger hash address, a new one will be created and you'll get the hash address. If so, please specify how many assets will be stored in it, only numbers: <input ref="seller-new-assets-ledger-amount" type="number" placeholder="Cash in Ether" defaultValue="0"/> </p> </div> <div> <button type="button" onClick={() => { this.props.handleState({ hasNotAssetsLedgerAddress: false, hasAssetsLedgerAddress: true }) }}>I have an assets ledger IPFS hash address</button> <button type="button" onClick={() => { this.props.handleState({ hasNotAssetsLedgerAddress: true, hasAssetsLedgerAddress: false }) }}>I don't have an assets ledger IPFS hash address</button> </div> </label> <input type="submit" value="Submit form and confirm transaction" /> <p>After submiting the form you'll have to pay for the gas of saving the transaction data on the blockchain, then you'll be redirected to eSign the invoice. You'll get the Ether from the transaction when both sign. An email will be sent to the buyer to counter-sign the invoice.</p> </form> </div> ) }else{ return( <div> <h1>You have an incoming transaction</h1> <p>Here is the data of the interested buyer, choose to accept or decline the transaction:</p> <ul> <li>From buyer name: {this.props.buyerName}</li> <li>Buyer wallet address: {this.props.buyerAddress}</li> <li>Buyer email: {this.props.buyerEmail}</li> <li>Buyer GPS location: {this.props.buyerGPSLocation}</li> <li>Buyer VAT number: {this.props.buyerVatNumber}</li> <li>Buyer cash ledger link: &nbsp; <a href={"https://gateway.ipfs.io/ipfs/" + this.props.buyerCashLedgerHashAddress}> {"https://gateway.ipfs.io/ipfs/" + this.props.buyerCashLedgerHashAddress} </a> </li> <li>Buyer assets ledger link: &nbsp; <a href={"https://gateway.ipfs.io/ipfs/" + this.props.buyerAssetsLedgerHashAddress}> {"https://gateway.ipfs.io/ipfs/" + this.props.buyerAssetsLedgerHashAddress} </a> </li> <li>Price per item: {this.props.pricePerItem}</li> <li>Quantity bought: {this.props.quantityBought}</li> <li>Amount paid in Ether: {this.props.amountPayEther}</li> <li>Invoice link: &nbsp; <a href={"https://gateway.ipfs.io/ipfs/" + this.props.invoiceHashAddress}> {"https://gateway.ipfs.io/ipfs/" + this.props.invoiceHashAddress} </a> </li> <li>Your name (seller name): {this.props.sellerName}</li> <li>Your address (seller address): {this.props.sellerAddress}</li> <li>Your email (seller email): {this.props.sellerEmail}</li> </ul> <div style={{display: this.props.displayAreYouSure ? 'none' : 'block'}}> <button onClick={() => { this.props.handleState({ displaySellerForm: true }) }}>Accept transaction</button> <button onClick={() => { this.props.handleState({ displayAreYouSure: true }) }}>Decline transaction</button> </div> <div style={{display: this.props.displayAreYouSure ? 'block' : 'none'}}> Are you sure that you want to cancel the transaction? (irreversible) &nbsp; <button onClick={() => { this.props.declineTransaction() }}>Yes</button> <button onClick={() => { this.props.handleState({ displayAreYouSure: false }) }}>No</button> </div> <p>After accepting the transaction, you'll receive the ether and you'll have to complete the order. Also, you'll have to sing the invoice.</p> <p>If you decline the transaction, the ether will be reverted to the buyer and it'll be cancelled.</p> </div> ) } } } export default SellerForm
src/counter.js
giltayar/react-starter-pack
import {Component} from 'react'; import React from 'react'; export default class Counter extends Component { constructor() { super() this.state = {counter: 0}; } render() { return ( <div> <div onClick={(() => this.setState({counter: this.state.counter - 3})).bind(this)}>-</div> <div>{this.state.counter}</div> <div onClick={(() => this.setState({counter: this.state.counter + 3})).bind(this)}>+</div> </div> ); } }
js/src/dapps/githubhint.js
kushti/mpt
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import ReactDOM from 'react-dom'; import React from 'react'; import injectTapEventPlugin from 'react-tap-event-plugin'; injectTapEventPlugin(); import Application from './githubhint/Application'; import '../../assets/fonts/Roboto/font.css'; import '../../assets/fonts/RobotoMono/font.css'; import './style.css'; import './githubhint.html'; ReactDOM.render( <Application />, document.querySelector('#container') );
pages/_document.js
tgrecojs/tgrecojs-static
// @flow import React from 'react'; import Document, { Head, Main, NextScript } from 'next/document'; import { ServerStyleSheet } from 'styled-components'; import styledNormalize from 'styled-normalize'; export default class MyDocument extends Document { render() { const sheet = new ServerStyleSheet(); const main = sheet.collectStyles(<Main />); const styleTags = sheet.getStyleElement(); return ( <html lang="en-US"> <Head> {styleTags} <style type="text/css"> {styledNormalize} </style> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="manifest" href="./static/manifest.json" /> <meta name="theme-color" content="#56a5b7" /> <link rel="shortcut icon" type="image/png" href="/static/tg-logo.png" /> </Head> <body> <div className="root"> {main} </div> <NextScript /> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/prism/1.6.0/themes/prism-coy.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato" /> <link rel="stylesheet" href="http://secure.acuityscheduling.com/embed/button/13089768.css" id="acuity-button-styles" /> <script src="http://secure.acuityscheduling.com/embed/button/13089768.js" async></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" /> </body> </html> ); } }
src/v0/demo/react-native-indicator/index.js
huanganqi/wsapp
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, } from 'react-native'; import { TextLoader, PulseLoader, DotsLoader, BubblesLoader, CirclesLoader, BreathingLoader, RippleLoader, LinesLoader, MusicBarLoader, EatBeanLoader, DoubleCircleLoader, RotationCircleLoader, RotationHoleLoader, CirclesRotationScaleLoader, NineCubesLoader, LineDotsLoader, ColorDotsLoader, } from 'react-native-indicator'; console.disableYellowBox = true class wsapp extends Component { render() { return ( <View> <BubblesLoader /> <PulseLoader /> <TextLoader text="Loading" /> <TextLoader text="Loading" /> <TextLoader text="Loading" /> <TextLoader text="Loading" /> <DotsLoader /> <TextLoader text="Loading" /> <TextLoader text="Loading" /> <TextLoader text="Loading" /> <TextLoader text="Loading" /> <BubblesLoader /> <TextLoader text="Loading" /> <TextLoader text="Loading" /> <TextLoader text="Loading" /> <TextLoader text="Loading" /> <CirclesLoader /> <TextLoader text="Loading" /> <TextLoader text="Loading" /> <TextLoader text="Loading" /> <TextLoader text="Loading" /> <BreathingLoader /> <RippleLoader /> <LinesLoader /> <MusicBarLoader /> <EatBeanLoader /> <DoubleCircleLoader /> <RotationCircleLoader /> <RotationHoleLoader /> <CirclesRotationScaleLoader /> <NineCubesLoader /> <LineDotsLoader /> <ColorDotsLoader /> </View> ) } } export default wsapp
examples/todomvc/index.js
dmin/redux
import 'babel-core/polyfill'; import React from 'react'; import { Provider } from 'react-redux'; import App from './containers/App'; import configureStore from './store/configureStore'; import 'todomvc-app-css/index.css'; const store = configureStore(); React.render( <Provider store={store}> {() => <App />} </Provider>, document.getElementById('root') );
fields/types/datearray/DateArrayField.js
sendyhalim/keystone
import ArrayFieldMixin from '../../mixins/ArrayField'; import DateInput from '../../components/DateInput'; import Field from '../Field'; import React from 'react'; import moment from 'moment'; const DEFAULT_INPUT_FORMAT = 'YYYY-MM-DD'; const DEFAULT_FORMAT_STRING = 'Do MMM YYYY'; module.exports = Field.create({ displayName: 'DateArrayField', statics: { type: 'DateArray', }, mixins: [ArrayFieldMixin], propTypes: { formatString: React.PropTypes.string, inputFormat: React.PropTypes.string, }, getDefaultProps () { return { formatString: DEFAULT_FORMAT_STRING, inputFormat: DEFAULT_INPUT_FORMAT, }; }, processInputValue (value) { if (!value) return; const m = moment(value); return m.isValid() ? m.format(this.props.inputFormat) : value; }, formatValue (value) { return value ? moment(value).format(this.props.formatString) : ''; }, getInputComponent () { return DateInput; }, });
src/components/blog/routes/PostEdit.js
sivael/simpleBlogThingie
import React from 'react' import PostEdit from 'containers/blog/PostEdit' export default class PostEditFromRouter extends React.Component { render() { return( <PostEdit id={this.props.params.id} /> ) } }
client/modules/MenuNews/components/MenuNewsNavBar/MenuNewsNavBar.js
lordknight1904/bigvnadmin
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Navbar, Nav, NavItem, MenuItem, Pagination, FormControl, Button } from 'react-bootstrap'; import { fetchMenuNews, setCurrentPage } from '../../MenuNewsActions'; import { getCurrentPage, getMenuNews } from '../../MenuNewsReducer'; import styles from '../../../../main.css'; class MenuNewsNavBar extends Component { constructor(props) { super(props); } hanldePage = (eventKey) => { this.props.dispatch(setCurrentPage(eventKey - 1)); this.props.dispatch(fetchMenuNews(eventKey - 1)); }; search = () => { this.props.dispatch(fetchMenuNews(this.props.currentPage -1)); }; render() { return ( <Navbar className={styles.cointain}> <Nav> <NavItem componentClass="span" className={styles.navPageItem}> <Pagination bsSize="small" first last boundaryLinks activePage={this.props.currentPage} items={(this.props.menuNews.length === 0) ? 1 : Math.ceil(this.props.menuNews.length / 10)} maxButtons={5} onSelect={this.hanldePage} bsClass={`pagination pagination-sm ${styles.pageInfo}`} /> </NavItem> <NavItem className={styles.navPageItem}> <Button bsStyle="success" onClick={this.search}>Tìm kiếm</Button> </NavItem> </Nav> <Nav pullRight> <NavItem className={styles.navPageItem}> <Button bsStyle="success" onClick={this.props.onCreateMenuNews}>Tạo mới</Button> </NavItem> </Nav> </Navbar> ); } } // Retrieve data from store as props function mapStateToProps(state) { return { currentPage: getCurrentPage(state), menuNews: getMenuNews(state), }; } MenuNewsNavBar.propTypes = { dispatch: PropTypes.func.isRequired, onCreateMenuNews: PropTypes.func.isRequired, currentPage: PropTypes.number.isRequired, menuNews: PropTypes.array.isRequired, }; MenuNewsNavBar.contextTypes = { router: PropTypes.object, }; export default connect(mapStateToProps)(MenuNewsNavBar);
src/components/Scheduler/Days/Views/Mobile/tpl.js
HopeUA/tv.hope.ua-react
import React from 'react'; import cx from 'classnames'; import Styles from './Styles/main.scss'; export default function Common() { const dayClasses = cx({ [Styles.active]: true, [Styles.day]: true }); const dateClasses = cx({ [Styles.date]: true, [Styles.toDay]: true }); return ( <section className={ Styles.daysComponent }> <ul className={ Styles.days }> <li className={ Styles.day }> <span className={ Styles.dayOfWeek }>ПН</span> <span className={ Styles.date }>17.06</span> </li> <li className={ Styles.day }> <span className={ Styles.dayOfWeek }>ВТ</span> <span className={ Styles.date }>18.06</span> </li> <li className={ dayClasses }> <span className={ Styles.dayOfWeek }>СР</span> <span className={ Styles.date }>вчера</span> </li> <li className={ Styles.day }> <span className={ Styles.dayOfWeek }>ЧТ</span> <span className={ dateClasses }>сегодня</span> </li> <li className={ Styles.day }> <span className={ Styles.dayOfWeek }>ПТ</span> <span className={ Styles.date }>завтра</span> </li> <li className={ Styles.day }> <span className={ Styles.dayOfWeek }>СБ</span> <span className={ Styles.date }>22.06</span> </li> <li className={ Styles.day }> <span className={ Styles.dayOfWeek }>ВС</span> <span className={ Styles.date }>23.06</span> </li> </ul> </section> ); }
app/src/components/Header/index.js
civa86/web-synth
import React from 'react'; import { ActionHandler } from '../../components/ActionHandler'; import icon from '../../../img/icon.png'; const Header = (props) => { const { height, repoUrl, libVersion, actions, linkMode, visiblePanel, numSelectedNodes, synthModules } = props; return ( <div id="header" style={{ height: height }}> <div className="header-top container-fluid"> <div className="logo no-select cursor-default pull-left"> <div className="pull-left icon"> <img src={icon} alt="icon"/> </div> <div className="pull-left"> <span className="capital">E</span>lectro<span className="capital">P</span>hone <span className="version visible-xs-block visible-sm-inline visible-md-inline visible-lg-inline"> {libVersion} </span> </div> </div> <div className="links pull-right"> <a className="link-left" href="./docs" target="_blank" data-toggle="tooltip" data-placement="bottom" title="Documentation"> <i className="ion-ios-book"></i> </a> <a href={repoUrl} target="_blank" data-toggle="tooltip" data-placement="bottom" title="GitHub"> <i className="ion-social-github"></i> </a> </div> </div> <div className="menu"> <ul className="container-fluid no-select"> <li className="pull-left"> <a className="cursor-pointer" onClick={() => actions.launchTutorial()} data-toggle="tooltip" data-placement="bottom" title="Help"> <i className="ion-help-circled"></i> <span className="menu-label hidden-xs">Help</span> </a> </li> <li className="pull-left"> <a className="cursor-pointer" onClick={() => actions.resetApplication()} data-toggle="tooltip" data-placement="bottom" title="Reset"> <i className="ion-android-refresh"></i> <span className="menu-label hidden-xs">Reset</span> </a> </li> <li className="pull-left"> <a className="cursor-pointer" onClick={() => actions.openSaveModal()} data-toggle="tooltip" data-placement="bottom" title="Save"> <i className="ion-android-download"></i> <span className="menu-label hidden-xs">Save</span> </a> </li> <li className="pull-left"> <a className="cursor-pointer" onClick={() => actions.openLoadModal()} data-toggle="tooltip" data-placement="bottom" title="Load"> <i className="ion-android-upload"></i> <span className="menu-label hidden-xs">Load</span> </a> </li> <li className="pull-left dropdown module-builder" data-toggle="tooltip" data-placement="top" title="Create New Modules"> <a className="cursor-pointer dropdown-toggle" role="button" data-toggle="dropdown"> <i className="ion-fork-repo"></i> <span className="menu-label hidden-xs">Add</span> </a> <ul className="dropdown-menu"> {synthModules.map(e => { return ( <li key={e.type}> <a className="cursor-pointer" onClick={() => actions.addSynthModule(e.type)}> {e.type} </a> </li> ); })} </ul> </li> <li className="pull-left" data-toggle="tooltip" data-placement="top" title="Toggle Link Mode (SHIFT)"> <a className={'cursor-pointer' + ((linkMode) ? ' selected' : '')} onClick={() => actions.toggleLinkMode()}> <i className="ion-pull-request"></i> <span className="menu-label hidden-xs">Link</span> </a> </li> <li className="pull-left" style={{ display: (visiblePanel === 'graph' && numSelectedNodes > 0) ? 'block' : 'none' }} data-toggle="tooltip" data-placement="top" title="Delete Selected Nodes"> <a className="cursor-pointer" onClick={() => actions.deleteSynthSelectedNodes()}> <i className="ion-trash-b"></i> <span className="menu-label hidden-xs">Delete</span> <span className="delete-counter" style={{ display: (numSelectedNodes > 1) ? 'inline-block' : 'none' }}>&nbsp; {'(' + numSelectedNodes + ')'} </span> </a> </li> <li className="pull-right last-right-item"> <a className={'cursor-pointer' + ((visiblePanel === 'control') ? ' selected' : '')} onClick={() => actions.setViewPanel('control')} data-toggle="tooltip" data-placement="bottom" title="Control view (TAB)"><i className="ion-levels"></i></a> </li> <li className="pull-right"> <a className={'cursor-pointer' + ((visiblePanel === 'graph') ? ' selected' : '')} onClick={() => actions.setViewPanel('graph')} data-toggle="tooltip" data-placement="bottom" title="Graph view (TAB)"><i className="ion-network"></i></a> </li> </ul> </div> </div> ); }; export default ActionHandler(Header);
src/components/Main.js
univa-new-user/my-app
require('normalize.css'); require('styles/App.css'); import React from 'react'; let yeomanImage = require('../images/yeoman.png'); const colors = ['red', 'white', 'green', 'black', 'gray']; let currentIndex = 0; function nextColor() { let color = colors[currentIndex % colors.length]; currentIndex++; return color; } class AppComponent extends React.Component { constructor(props, context) { super(props, context); this.state = { background: nextColor() }; } componentDidMount() { let self = this; this.interval = setInterval(() => self.setState({background: nextColor()}), 3000); } componentDidUnmount() { clearInterval(this.interval); } render() { return ( <div className="index"> <img src={yeomanImage} alt="Yeoman Generator" /> <div className="notice" style={{ background: this.state.background }}>Please edit <code>src/components/Main.js</code> to get started!</div> </div> ); } } AppComponent.defaultProps = { }; export default AppComponent;
src/svg-icons/av/recent-actors.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvRecentActors = (props) => ( <SvgIcon {...props}> <path d="M21 5v14h2V5h-2zm-4 14h2V5h-2v14zM14 5H2c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zM8 7.75c1.24 0 2.25 1.01 2.25 2.25S9.24 12.25 8 12.25 5.75 11.24 5.75 10 6.76 7.75 8 7.75zM12.5 17h-9v-.75c0-1.5 3-2.25 4.5-2.25s4.5.75 4.5 2.25V17z"/> </SvgIcon> ); AvRecentActors = pure(AvRecentActors); AvRecentActors.displayName = 'AvRecentActors'; AvRecentActors.muiName = 'SvgIcon'; export default AvRecentActors;
src/server.js
Restry/vendornew
import Express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import config from './config'; import favicon from 'serve-favicon'; import compression from 'compression'; import httpProxy from 'http-proxy'; import path from 'path'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import Html from './helpers/Html'; import PrettyError from 'pretty-error'; import http from 'http'; import { match } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { ReduxAsyncConnect, loadOnServer } from 'redux-async-connect'; import createHistory from 'react-router/lib/createMemoryHistory'; import {Provider} from 'react-redux'; import getRoutes from './routes'; const targetUrl = 'http://' + config.apiHost + ':' + config.apiPort; const pretty = new PrettyError(); const app = new Express(); const server = new http.Server(app); const proxy = httpProxy.createProxyServer({ target: targetUrl, ws: true }); app.use(compression()); app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico'))); app.use(Express.static(path.join(__dirname, '..', 'static'))); // Proxy to API server app.use('/api', (req, res) => { proxy.web(req, res, {target: targetUrl}); }); // app.use('/ws', (req, res) => { // proxy.web(req, res, {target: targetUrl + '/ws'}); // }); // server.on('upgrade', (req, socket, head) => { // proxy.ws(req, socket, head); // }); // added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527 proxy.on('error', (error, req, res) => { let json; if (error.code !== 'ECONNRESET') { console.error('proxy error', error); } if (!res.headersSent) { res.writeHead(500, {'content-type': 'application/json'}); } json = {error: 'proxy_error', reason: error.message}; res.end(JSON.stringify(json)); }); app.use((req, res) => { if (__DEVELOPMENT__) { // Do not cache webpack stats: the script file would change since // hot module replacement is enabled in the development env webpackIsomorphicTools.refresh(); } const client = new ApiClient(req); const memoryHistory = createHistory(req.originalUrl); const store = createStore(memoryHistory, client); const history = syncHistoryWithStore(memoryHistory, store); function hydrateOnClient() { res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} store={store}/>)); } if (__DISABLE_SSR__) { hydrateOnClient(); return; } match({ history, routes: getRoutes(store), location: req.originalUrl }, (error, redirectLocation, renderProps) => { if (redirectLocation) { res.redirect(redirectLocation.pathname + redirectLocation.search); } else if (error) { console.error('ROUTER ERROR:', pretty.render(error)); res.status(500); hydrateOnClient(); } else if (renderProps) { console.log(`Attached : ${req.originalUrl}`); loadOnServer({...renderProps, store, helpers: {client}}).then(() => { const component = ( <Provider store={store} key="provider"> <ReduxAsyncConnect {...renderProps} /> </Provider> ); res.status(200); global.navigator = {userAgent: req.headers['user-agent']}; res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>)); }); } else { console.log(`[Attach Not found] : ${req.originalUrl}`); res.status(404).send('Not found'); } }); }); if (config.port) { server.listen(config.port, (err) => { if (err) { console.error(err); } console.info('----\n==> ✅ %s is running, talking to API server on %s.', config.app.title, config.apiPort); console.info('==> 💻 Open http://%s:%s in a browser to view the app.', config.host, config.port); }); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }
docs/src/app/components/pages/components/DropDownMenu/ExampleLabeled.js
ngbrown/material-ui
import React from 'react'; import DropDownMenu from 'material-ui/DropDownMenu'; import MenuItem from 'material-ui/MenuItem'; export default class DropDownMenuLabeledExample extends React.Component { constructor(props) { super(props); this.state = {value: 2}; } handleChange = (event, index, value) => this.setState({value}); render() { return ( <DropDownMenu value={this.state.value} onChange={this.handleChange}> <MenuItem value={1} label="5 am - 12 pm" primaryText="Morning" /> <MenuItem value={2} label="12 pm - 5 pm" primaryText="Afternoon" /> <MenuItem value={3} label="5 pm - 9 pm" primaryText="Evening" /> <MenuItem value={4} label="9 pm - 5 am" primaryText="Night" /> </DropDownMenu> ); } }
src/svg-icons/action/view-carousel.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionViewCarousel = (props) => ( <SvgIcon {...props}> <path d="M7 19h10V4H7v15zm-5-2h4V6H2v11zM18 6v11h4V6h-4z"/> </SvgIcon> ); ActionViewCarousel = pure(ActionViewCarousel); ActionViewCarousel.displayName = 'ActionViewCarousel'; ActionViewCarousel.muiName = 'SvgIcon'; export default ActionViewCarousel;
src/components/views/author-user-list-view.js
HuangXingBin/goldenEast
import React from 'react'; import { Table, Button, Popconfirm } from 'antd'; import weiGuDong from '../../appConstants/assets/images/微股东.png'; import normalCard from '../../appConstants/assets/images/普卡.png'; import silverCard from '../../appConstants/assets/images/银卡.png'; import goldenCard from '../../appConstants/assets/images/金卡.png'; import superGoldenCard from '../../appConstants/assets/images/白金卡.png'; import { Link } from 'react-router'; // In the fifth row, other columns are merged into first column // by setting it's colSpan to be 0 const UserListTable = React.createClass({ jinLevels() { return ['注册用户(0%)', weiGuDong, normalCard, silverCard, goldenCard, superGoldenCard]; }, getColumns(){ const jinLevels = this.jinLevels(); const columns = [{ title: '姓名', dataIndex: 'user_name', key : 'user_name', render(text, row, index) { var firstName = !row.wechat_avatar ? text.slice(0,1) : ''; return ( <div className="user-avatar-bar"> <span className="user-avatar" style={{backgroundImage:'url('+ row.wechat_avatar +')'}}> {firstName} </span> <div className="user-avatar-bar-text"> <p className="name">{text}</p> {/*<span>微信昵称</span>*/} </div> </div> ); }, }, { title: '级别', dataIndex: 'level', key : 'level', render(text) { // console.log(text); if(text == '0'){ return <span>{jinLevels[text]}</span> } else { return <img src={jinLevels[text]}/> } } }, { title: '手机号', dataIndex: 'cellphone', key : 'cellphone' }, { title: '邀请人', dataIndex: 'inv_user_name', key : 'inv_user_name', }, { title: '邀请人手机', dataIndex: 'inv_cellphone', key : 'inv_cellphone' }, { title: '注册时间', dataIndex: 'register_date', key : 'register_date' }, { title: '操作', render : function(text, record, index) { return ( <div> <Link style={{color : 'white'}} to={`/author_user_list/set_authorization/${record.user_sn}`}> <Button type="primary" size="small" icon="setting">分配权限</Button> </Link> &nbsp;&nbsp; <Popconfirm title="确认要删除此用户的所有权限?" onConfirm={this.props.deleteUserAuthor(record.user_sn)}> <Button className="btn-orange" type="primary" size="small">取消权限</Button> </Popconfirm> </div> ) }.bind(this), }]; return columns; }, onChange(page){ this.props.onPageChange(page) }, render(){ const columns = this.getColumns(); const pagination = { defaultPageSize : 12, onChange : this.onChange, total : this.props.total, current : parseInt(this.props.currentPage) }; return( <Table pagination={pagination} size="middle"columns={columns} dataSource={this.props.data} bordered /> ) } }); export default UserListTable;
src/Parser/Druid/Balance/Modules/Items/Tier21_4set.js
enragednuke/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import Combatants from 'Parser/Core/Modules/Combatants'; import Analyzer from 'Parser/Core/Analyzer'; import getDamageBonus from 'Parser/Mage/Shared/Modules/GetDamageBonus'; import ItemDamageDone from 'Main/ItemDamageDone'; import { formatPercentage } from 'common/format'; import Wrapper from 'common/Wrapper'; const DAMAGE_BONUS = 0.2; /** * Balance Druid Tier21 4set * Increases the damage of Moonfire and Sunfire for 6 seconds after casting Starfall or Starsurge. */ class Tier21_4set extends Analyzer { static dependencies = { combatants: Combatants, }; moonfireDamage = 0; sunfireDamage = 0; on_initialized() { this.active = this.combatants.selected.hasBuff(SPELLS.BALANCE_DRUID_T21_4SET_BONUS_BUFF.id); } on_byPlayer_damage(event) { if (!this.combatants.selected.hasBuff(SPELLS.SOLAR_SOLSTICE.id)){ return; } if (event.ability.guid === SPELLS.MOONFIRE_BEAR.id) { this.moonfireDamage += getDamageBonus(event, DAMAGE_BONUS); } if (event.ability.guid === SPELLS.SUNFIRE.id){ this.sunfireDamage += getDamageBonus(event, DAMAGE_BONUS); } } get uptime(){ return this.combatants.selected.getBuffUptime(SPELLS.SOLAR_SOLSTICE.id) / this.owner.fightDuration; } item() { return { id: SPELLS.BALANCE_DRUID_T21_4SET_BONUS_BUFF.id, icon: <SpellIcon id={SPELLS.BALANCE_DRUID_T21_4SET_BONUS_BUFF.id} />, title: <SpellLink id={SPELLS.BALANCE_DRUID_T21_4SET_BONUS_BUFF.id} />, result: ( <dfn data-tip={`Damage Breakdown: <ul> <li>Moonfire: <b>${this.owner.formatItemDamageDone(this.moonfireDamage)}</b></li> <li>Sunfire: <b>${this.owner.formatItemDamageDone(this.sunfireDamage)}</b></li> </ul> `}> <Wrapper><ItemDamageDone amount={this.moonfireDamage + this.sunfireDamage} /> <br /> Uptime: {formatPercentage(this.uptime)}%</Wrapper> </dfn> ), }; } } export default Tier21_4set;
src/components/played_cards.js
camboio/yooneau
import React from 'react'; import Card from './card'; export default class PlayedCards extends React.Component{ displayPlayedCards(){ let pc = [...this.props.cards]; pc.reverse(); const cards = pc.map((card, index) => <Card key={index} card={card} />); const amount = cards.length > 5 ? 5 : cards.length; let stack = []; for(let i = 0; i < amount; i++){ stack.unshift(cards[i]); } return stack; } render(){ const cards = this.displayPlayedCards(); return ( <div className="played-cards-component"> {cards && cards} </div> ); } }
src/client/pages/app/CBlocksAppBar.js
doemski/cblocks
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import Typography from '@material-ui/core/Typography'; import IconButton from '@material-ui/core/IconButton'; import MenuIcon from '@material-ui/icons/Menu'; import * as action from '../../action'; import { connect } from 'react-redux'; const styles = { root: { flexGrow: 1 }, flex: { flex: 1 }, menuButton: { marginLeft: -12, marginRight: 20 } }; class ButtonAppBar extends React.Component { render () { const { classes } = this.props; return ( <div className={classes.root}> <AppBar position="static"> <Toolbar> <IconButton className={classes.menuButton} color="inherit" aria-label="Menu" onClick={this.props.openDrawer} > <MenuIcon /> </IconButton> <Typography variant="title" color="inherit" className={classes.flex} > cBlocks Visualizer </Typography> </Toolbar> </AppBar> </div> ); } } ButtonAppBar.propTypes = { classes: PropTypes.object.isRequired, openDrawer: PropTypes.func }; const mapDispatchToProps = dispatch => { return { openDrawer: () => dispatch(action.openMenuDrawer()) }; }; const connectedAppbar = connect( null, mapDispatchToProps )(ButtonAppBar); export default withStyles(styles)(connectedAppbar);
docs/src/app/components/pages/components/Snackbar/Page.js
kittyjumbalaya/material-components-web
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import SnackbarReadmeText from './README'; import SnackbarExampleSimple from './ExampleSimple'; import SnackbarExampleSimpleCode from '!raw!./ExampleSimple'; import SnackbarExampleAction from './ExampleAction'; import SnackbarExampleActionCode from '!raw!./ExampleAction'; import SnackbarExampleTwice from './ExampleTwice'; import SnackbarExampleTwiceCode from '!raw!./ExampleTwice'; import SnackbarCode from '!raw!material-ui/Snackbar/Snackbar'; const descriptions = { simple: '`Snackbar` is a controlled component, and is displayed when `open` is `true`. Click away from the ' + 'Snackbar to close it, or wait for `autoHideDuration` to expire.', action: 'A single `action` can be added to the Snackbar, and triggers `onActionTouchTap`. Edit the textfield to ' + 'change `autoHideDuration`', consecutive: 'Changing `message` causes the Snackbar to animate - it isn\'t necessary to close and reopen the ' + 'Snackbar with the open prop.', }; const SnackbarPage = () => { return ( <div> <Title render={(previousTitle) => `Snackbar - ${previousTitle}`} /> <MarkdownElement text={SnackbarReadmeText} /> <CodeExample title="Simple example" description={descriptions.simple} code={SnackbarExampleSimpleCode} > <SnackbarExampleSimple /> </CodeExample> <CodeExample title="Example action" description={descriptions.action} code={SnackbarExampleActionCode} > <SnackbarExampleAction /> </CodeExample> <CodeExample title="Consecutive Snackbars" description={descriptions.consecutive} code={SnackbarExampleTwiceCode} > <SnackbarExampleTwice /> </CodeExample> <PropTypeDescription code={SnackbarCode} /> </div> ); }; export default SnackbarPage;
tests/lib/rules/vars-on-top.js
Akkuma/eslint
/** * @fileoverview Tests for vars-on-top rule. * @author Danny Fritz * @author Gyandeep Singh * @copyright 2014 Danny Fritz. All rights reserved. * @copyright 2014 Gyandeep Singh. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var rule = require("../../../lib/rules/vars-on-top"), EslintTester = require("../../../lib/testers/rule-tester"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ var ruleTester = new EslintTester(); ruleTester.run("vars-on-top", rule, { valid: [ [ "var first = 0;", "function foo() {", " first = 2;", "}" ].join("\n"), [ "function foo() {", "}" ].join("\n"), [ "function foo() {", " var first;", " if (true) {", " first = true;", " } else {", " first = 1;", " }", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " var third;", " var fourth = 1, fifth, sixth = third;", " var seventh;", " if (true) {", " third = true;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var i;", " for (i = 0; i < 10; i++) {", " alert(i);", " }", "}" ].join("\n"), [ "function foo() {", " var outer;", " function inner() {", " var inner = 1;", " var outer = inner;", " }", " outer = 1;", "}" ].join("\n"), [ "function foo() {", " var first;", " //Hello", " var second = 1;", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " /*", " Hello Clarice", " */", " var second = 1;", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " function bar(){", " var first;", " first = 5;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " function bar(){", " var third;", " third = 5;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var bar = function(){", " var third;", " third = 5;", " }", " first = 5;", "}" ].join("\n"), [ "function foo() {", " var first;", " first.onclick(function(){", " var third;", " third = 5;", " });", " first = 5;", "}" ].join("\n"), { code: [ "function foo() {", " var i = 0;", " for (let j = 0; j < 10; j++) {", " alert(j);", " }", " i = i + 1;", "}" ].join("\n"), ecmaFeatures: { blockBindings: true } }, "'use strict'; var x; f();", "'use strict'; 'directive'; var x; var y; f();", "function f() { 'use strict'; var x; f(); }", "function f() { 'use strict'; 'directive'; var x; var y; f(); }", {code: "import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "'use strict'; import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import React from 'react'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import * as foo from 'mod.js'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import { square, diag } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import { default as foo } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import theDefault, { named1, named2 } from 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }} ], invalid: [ { code: [ "var first = 0;", "function foo() {", " first = 2;", " second = 2;", "}", "var second = 0;" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first;", " first = 1;", " first = 2;", " first = 3;", " first = 4;", " var second = 1;", " second = 2;", " first = second;", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first;", " if (true) {", " var second = true;", " }", " first = second;", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " for (var i = 0; i < 10; i++) {", " alert(i);", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " for (i = 0; i < first; i ++) {", " var second = i;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " switch (first) {", " case 10:", " var hello = 1;", " break;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " try {", " var hello = 1;", " } catch (e) {", " alert('error');", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " try {", " asdf;", " } catch (e) {", " var hello = 1;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " while (first) {", " var hello = 1;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " do {", " var hello = 1;", " } while (first == 10);", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = [1,2,3];", " for (var item in first) {", " item++;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = [1,2,3];", " var item;", " for (item in first) {", " var hello = item;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "var foo = () => {", " var first = [1,2,3];", " var item;", " for (item in first) {", " var hello = item;", " }", "}" ].join("\n"), ecmaFeatures: { arrowFunctions: true }, errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: "'use strict'; 0; var x; f();", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] }, { code: "'use strict'; var x; 'directive'; var y; f();", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] }, { code: "function f() { 'use strict'; 0; var x; f(); }", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] }, { code: "function f() { 'use strict'; var x; 'directive'; var y; f(); }", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] } ] });
src/svg-icons/action/alarm-on.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAlarmOn = (props) => ( <SvgIcon {...props}> <path d="M22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm-1.46-5.47L8.41 12.4l-1.06 1.06 3.18 3.18 6-6-1.06-1.06-4.93 4.95z"/> </SvgIcon> ); ActionAlarmOn = pure(ActionAlarmOn); ActionAlarmOn.displayName = 'ActionAlarmOn'; ActionAlarmOn.muiName = 'SvgIcon'; export default ActionAlarmOn;
examples/js/selection/all-select.js
AllenFang/react-bootstrap-table
/* eslint max-len: 0 */ /* eslint no-alert: 0 */ /* eslint guard-for-in: 0 */ /* eslint no-console: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(50); export default class SelectAllOnAllPage extends React.Component { onSelectAll = (isSelected) => { if (isSelected) { return products.map(row => row.id); } else { return []; } } render() { const selectRowProp = { mode: 'checkbox', clickToSelect: true, onSelectAll: this.onSelectAll }; return ( <BootstrapTable ref='table' data={ products } selectRow={ selectRowProp } pagination> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
src/client/components/search/GridSelectionActions.js
gearz-lab/hypersonic
import React from 'react'; import clone from 'clone'; import {ButtonGroup, Button, DropdownButton, MenuItem} from 'react-bootstrap'; import _ from 'underscore'; export default React.createClass({ propTypes: { selection: React.PropTypes.object, rows: React.PropTypes.array, handleSelectionChange: React.PropTypes.func, handleActionRefresh: React.PropTypes.func.isRequired }, handleActionRefresh: function () { let {handleActionRefresh} = this.props; handleActionRefresh(); }, handleSelectionDropdownChange: function (eventKey, event) { let { selection, rows, handleSelectionChange } = this.props; let newSelection = clone(selection); switch (eventKey) { case 'check-all-this-page': _.each(rows, r => { newSelection[r['id']] = true; }); break; case 'uncheck-all-this-page': _.each(rows, r => { delete newSelection[r['id']]; }); break; case 'uncheck-all': newSelection = {}; break; } handleSelectionChange(newSelection); }, /** * Returns whether all the items in this page are selected */ areAllInThisPageSelected: function () { let { selection, rows, } = this.props; let allInPage = rows.map(r => r.id); for (let i = 0; i < allInPage.length; i++) { if (!_.has(selection, allInPage[i])) return false; } return true; }, render: function () { return <ButtonGroup className="button-bar"> <DropdownButton title={<i className={ this.areAllInThisPageSelected() ? "fa fa-check-square-o" : "fa fa-square-o" }></i>} id="input-dropdown-addon"> <MenuItem eventKey="check-all-this-page" onSelect={this.handleSelectionDropdownChange}> <i className="fa fa-check-square-o"></i>Check all on this page </MenuItem> <MenuItem eventKey="uncheck-all-this-page" onSelect={this.handleSelectionDropdownChange}> <i className="fa fa-square-o"></i>Uncheck all on this page </MenuItem> <MenuItem eventKey="uncheck-all" onSelect={this.handleSelectionDropdownChange}> <i className="fa fa-square-o"></i>Uncheck all </MenuItem> </DropdownButton> <Button onClick={this.handleActionRefresh}><i className="fa fa-refresh"></i>&nbsp;</Button> </ButtonGroup> } })
thingmenn-frontend/src/components/mp-details/index.js
baering/thingmenn
import React from 'react' import mpService from '../../services/mp-service' import totalsService from '../../services/totals-service' import mpSummaryService from '../../services/mp-summary-service' import KPI from '../../widgets/key-performance-indicator' import Topics from '../../widgets/topics' import Topic from '../../widgets/topics/topic' import ColorLegend from '../../widgets/color-legend' import DetailsHeader from '../../widgets/details-header' import DetailsMenu from '../../widgets/details-menu' import Friends from '../../widgets/friends' import Piechart from '../../widgets/piechart' import Speeches from '../../widgets/speeches' import Documents from '../../widgets/documents' import BarChart from '../../widgets/bar-chart' import Items from '../../widgets/items' import WeekdayHourMatrix from '../../widgets/weekday-hour-matrix' import '../mp-details/styles.css' export default class MpDetails extends React.Component { constructor(props) { super(props) this.state = { mp: { description: {}, lthings: [] }, lthing: null, lthings: [], lthingLookup: {}, voteSummary: { votePercentages: [], voteSummary: [] }, speechSummary: [], documentSummary: [], absentSummary: {}, votePositions: [], speechPositions: [], documentPositions: [], similarMps: [], differentMps: [], } } componentWillMount() { this.getData() } componentWillReceiveProps(nextProps) { this.getData(nextProps.routeParams.mpId, nextProps.routeParams.lthing) } getData(id, lthing) { // TODO: HOC withData that injects correct props into components const mpId = id || this.props.params.mpId const lthingId = lthing || this.props.params.lthing if (this.state.mp.id === mpId) return mpService.getMpDetailsByLthing(mpId, lthingId).then((mp) => { this.setState(() => ({ mp, })) }) mpSummaryService .getMpVoteSummaryByLthing(mpId, lthingId) .then((voteSummary) => { this.setState(() => ({ voteSummary, })) }) mpSummaryService .getMpSpeechSummaryByLthing(mpId, lthingId) .then((speechSummary) => { this.setState(() => ({ speechSummary, })) }) mpSummaryService .getMpDocumentSummaryByLthing(mpId, lthingId) .then((documentSummary) => { this.setState(() => ({ documentSummary, })) }) mpSummaryService .getMpVotePositionsByLthing(mpId, lthingId) .then((votePositions) => { this.setState(() => ({ votePositions, })) }) mpSummaryService .getMpSpeechPositionsByLthing(mpId, lthingId) .then((speechPositions) => { this.setState(() => ({ speechPositions, })) }) mpSummaryService .getMpDocumentPositionsByLthing(mpId, lthingId) .then((documentPositions) => { this.setState(() => ({ documentPositions, })) }) mpSummaryService .getMpAbsentSummaryByLthing(mpId, lthingId) .then((absentSummary) => { this.setState(() => ({ absentSummary, })) }) mpService.getSimilarMpsByLthing(mpId, lthingId).then((similarMps) => { this.setState(() => ({ similarMps, })) }) mpService.getDifferentMpsByLthing(mpId, lthingId).then((differentMps) => { this.setState(() => ({ differentMps, })) }) totalsService.getLthings().then((lthings) => { const lthingLookup = {} lthings.forEach((lthing) => (lthingLookup[lthing.id] = lthing)) this.setState(() => ({ lthings, lthingLookup, })) }) } generateLthingList(mp, lthings, lthingLookup) { const initialList = [ { name: 'Samtölur', url: `/thingmenn/${mp.id}/thing/allt`, }, ] if (!mp.lthings.length || !lthings.length) { return initialList } const lthingsFormatted = mp.lthings.map((lthingInfo) => ({ year: lthingLookup[lthingInfo.lthing].start.split('.')[2], thing: lthingInfo.lthing, url: `/thingmenn/${mp.id}/thing/${lthingInfo.lthing}`, })) return initialList.concat(lthingsFormatted) } getDividerSize(tabName, lthing) { if (lthing === 'allt') { if (tabName === 'speeches') { return 3 } else if (tabName === 'documents') { return 0.4 } } if (tabName === 'speeches') { return 0.5 } else if (tabName === 'documents') { return 0.1 } return 1 } render() { const { mp, lthings, lthingLookup, voteSummary, speechSummary, documentSummary, votePositions, speechPositions, documentPositions, similarMps, differentMps, } = this.state const lthing = this.props.params.lthing return ( <div className="fill"> <DetailsMenu menuItems={this.generateLthingList(mp, lthings, lthingLookup)} /> <DetailsHeader {...mp} description={mp.description.asMp} /> <div className="Details"> <KPI voteSummary={voteSummary} speechSummary={speechSummary} documentSummary={documentSummary} /> <div className="Details-item"> <Friends title="Samherjar" subTitle="Eins greidd atkvæði" friends={similarMps.slice(0, 10)} lthing={lthing} isDisplayingFriends={true} /> </div> <div className="Details-item"> <Friends title="Mótherjar" subTitle="Ólík greidd atkvæði" friends={differentMps.slice(0, 10)} /> </div> <div className="Details-item Details-item--large Details-item--no-padding"> <Topics> {(activeTab) => ( <span> <Topic active={activeTab === 0}> <div className="Topic-column"> <h1 className="Topic-heading"> Skipting atkvæða eftir flokkum </h1> <ColorLegend /> {votePositions.map((sectionSummary) => ( <BarChart sectionSummary={sectionSummary} key={sectionSummary.name} /> ))} </div> <div className="Topic-column"> <h1 className="Topic-heading">Skipting atkvæða</h1> <Piechart voteSummary={voteSummary} /> <ColorLegend includeAbsent /> </div> {!!this.state.absentSummary && !!this.state.absentSummary.statistics && ( <div className="Topic-column"> <h1 className="Topic-heading">Hvenær fjarverandi</h1> <WeekdayHourMatrix weekdayHourMatrixSummary={this.state.absentSummary} /> </div> )} </Topic> <Topic active={activeTab === 1}> <div className="Topic-column"> <h1 className="Topic-heading">Ræður eftir flokkum</h1> <Items divider={this.getDividerSize('speeches', lthing)} items={speechPositions} /> </div> <div className="Topic-column"> <h1 className="Topic-heading">Skipting ræðutíma</h1> <Speeches speechSummary={speechSummary} /> </div> </Topic> <Topic active={activeTab === 2}> <div className="Topic-column"> <h1 className="Topic-heading">Þingskjöl eftir flokkum</h1> <Items divider={this.getDividerSize('documents', lthing)} items={documentPositions} /> </div> <div className="Topic-column"> <h1 className="Topic-heading">Skipting þingskjala</h1> <Documents documentSummary={documentSummary} /> </div> </Topic> </span> )} </Topics> </div> </div> </div> ) } }
src/client/story_list.js
kevinnguy/hacker-menu
import React from 'react' import Story from './story.js' import _ from 'lodash' export default class StoryList extends React.Component { render () { var onUrlClick = this.props.onUrlClick var onMarkAsRead = this.props.onMarkAsRead var storyNodes = _.map(this.props.stories, function (story, index) { return ( <li key={index} className='table-view-cell media'> <Story story={story} onUrlClick={onUrlClick} onMarkAsRead={onMarkAsRead}/> </li> ) }) return ( <ul className='content table-view'> {storyNodes} </ul> ) } } StoryList.propTypes = { onUrlClick: React.PropTypes.func.isRequired, onMarkAsRead: React.PropTypes.func.isRequired, stories: React.PropTypes.array.isRequired }
src/js/components/breadcrumb.js
mdibaiee/Hawk
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { connect } from 'react-redux'; import changedir from 'actions/changedir'; import { bind } from 'store'; import Hammer from 'react-hammerjs'; @connect(props) export default class Breadcrumb extends Component { render() { let els = []; if (this.props.search) { els = [ <span key='000'>Search: {this.props.search}</span> ] } else { let directories = this.props.cwd.split('/').filter(a => a); let lastDirectories = this.props.lwd.split('/').filter(a => a); directories.unshift('sdcard'); let sumLength = directories.length + lastDirectories.length; els = els.concat(directories.map((dir, index, arr) => { let path = arr.slice(1, index + 1).join('/'); let style = { zIndex: sumLength - index }; return ( <Hammer onTap={bind(changedir(path))} key={index}> <span style={style}>{dir}</span> </Hammer> ); })); if (lastDirectories.length > directories.length - 1) { lastDirectories.splice(0, directories.length - 1); let history = lastDirectories.map((dir, index, arr) => { let current = directories.slice(1).concat(arr.slice(0, index + 1)); let path = current.join('/').replace(/^\//, ''); // remove starting slash let key = directories.length + index; let style = { zIndex: arr.length - index}; return ( <Hammer onTap={bind(changedir(path))} key={key}> <span className='history' style={style}>{dir}</span> </Hammer> ) }); els = els.concat(history); } } return ( <div className='breadcrumb' ref='container'> <div> {els} </div> </div> ); } componentDidUpdate() { let container = this.refs.container; let currents = container.querySelectorAll('span:not(.history)'); container.scrollLeft = currents[currents.length - 1].offsetLeft; } } function props(state) { return { lwd: state.get('lwd'), // last working directory cwd: state.get('cwd'), search: state.get('search') } }
src/svg-icons/image/brush.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBrush = (props) => ( <SvgIcon {...props}> <path d="M7 14c-1.66 0-3 1.34-3 3 0 1.31-1.16 2-2 2 .92 1.22 2.49 2 4 2 2.21 0 4-1.79 4-4 0-1.66-1.34-3-3-3zm13.71-9.37l-1.34-1.34c-.39-.39-1.02-.39-1.41 0L9 12.25 11.75 15l8.96-8.96c.39-.39.39-1.02 0-1.41z"/> </SvgIcon> ); ImageBrush = pure(ImageBrush); ImageBrush.displayName = 'ImageBrush'; ImageBrush.muiName = 'SvgIcon'; export default ImageBrush;
local-cli/server/middleware/heapCapture/src/heapCapture.js
satya164/react-native
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /*eslint no-console-disallow: "off"*/ /*global preLoadedCapture:true*/ import ReactDOM from 'react-dom'; import React from 'react'; import { Aggrow, AggrowData, AggrowTable, StringInterner, StackRegistry, } from './index.js'; function RefVisitor(refs, id) { this.refs = refs; this.id = id; } RefVisitor.prototype = { moveToEdge: function moveToEdge(name) { const ref = this.refs[this.id]; if (ref && ref.edges) { const edges = ref.edges; for (const edgeId in edges) { if (edges[edgeId] === name) { this.id = edgeId; return this; } } } this.id = undefined; return this; }, moveToFirst: function moveToFirst(callback) { const ref = this.refs[this.id]; if (ref && ref.edges) { const edges = ref.edges; for (const edgeId in edges) { this.id = edgeId; if (callback(edges[edgeId], this)) { return this; } } } this.id = undefined; return this; }, forEachEdge: function forEachEdge(callback) { const ref = this.refs[this.id]; if (ref && ref.edges) { const edges = ref.edges; const visitor = new RefVisitor(this.refs, undefined); for (const edgeId in edges) { visitor.id = edgeId; callback(edges[edgeId], visitor); } } }, getType: function getType() { const ref = this.refs[this.id]; if (ref) { return ref.type; } return undefined; }, getRef: function getRef() { return this.refs[this.id]; }, clone: function clone() { return new RefVisitor(this.refs, this.id); }, isDefined: function isDefined() { return !!this.id; }, getValue: function getValue() { const ref = this.refs[this.id]; if (ref) { if (ref.type === 'string') { if (ref.value) { return ref.value; } else { const rope = []; this.forEachEdge((name, visitor) => { if (name && name.startsWith('[') && name.endsWith(']')) { const index = parseInt(name.substring(1, name.length - 1), 10); rope[index] = visitor.getValue(); } }); return rope.join(''); } } else if (ref.type === 'ScriptExecutable' || ref.type === 'EvalExecutable' || ref.type === 'ProgramExecutable') { return ref.value.url + ':' + ref.value.line + ':' + ref.value.col; } else if (ref.type === 'FunctionExecutable') { return ref.value.name + '@' + ref.value.url + ':' + ref.value.line + ':' + ref.value.col; } else if (ref.type === 'NativeExecutable') { return ref.value.function + ' ' + ref.value.constructor + ' ' + ref.value.name; } else if (ref.type === 'Function') { const executable = this.clone().moveToEdge('@Executable'); if (executable.id) { return executable.getRef().type + ' ' + executable.getValue(); } } } return '#none'; } }; function forEachRef(refs, callback) { const visitor = new RefVisitor(refs, undefined); for (const id in refs) { visitor.id = id; callback(visitor); } } function firstRef(refs, callback) { for (const id in refs) { const ref = refs[id]; if (callback(id, ref)) { return new RefVisitor(refs, id); } } return new RefVisitor(refs, undefined); } function getInternalInstanceName(visitor) { const type = visitor.clone().moveToEdge('_currentElement').moveToEdge('type'); if (type.getType() === 'string') { // element.type is string return type.getValue(); } else if (type.getType() === 'Function') { // element.type is function const displayName = type.clone().moveToEdge('displayName'); if (displayName.isDefined()) { return displayName.getValue(); // element.type.displayName } const name = type.clone().moveToEdge('name'); if (name.isDefined()) { return name.getValue(); // element.type.name } type.moveToEdge('@Executable'); if (type.getType() === 'FunctionExecutable') { return type.getRef().value.name; // element.type symbolicated name } } return '#unknown'; } function buildReactComponentTree(visitor, registry, strings) { const ref = visitor.getRef(); if (ref.reactTree || ref.reactParent === undefined) { return; // has one or doesn't need one } const parentVisitor = ref.reactParent; if (parentVisitor === null) { ref.reactTree = registry.insert(registry.root, strings.intern(getInternalInstanceName(visitor))); } else if (parentVisitor) { const parentRef = parentVisitor.getRef(); buildReactComponentTree(parentVisitor, registry, strings); let relativeName = getInternalInstanceName(visitor); if (ref.reactKey) { relativeName = ref.reactKey + ': ' + relativeName; } ref.reactTree = registry.insert(parentRef.reactTree, strings.intern(relativeName)); } else { throw 'non react instance parent of react instance'; } } function markReactComponentTree(refs, registry, strings) { // annotate all refs that are react internal instances with their parent and name // ref.reactParent = visitor that points to parent instance, // null if we know it's an instance, but don't have a parent yet // ref.reactKey = if a key is used to distinguish siblings forEachRef(refs, (visitor) => { const visitorClone = visitor.clone(); // visitor will get stomped on next iteration const ref = visitor.getRef(); visitor.forEachEdge((edgeName, edgeVisitor) => { const edgeRef = edgeVisitor.getRef(); if (edgeRef) { if (edgeName === '_renderedChildren') { if (ref.reactParent === undefined) { // ref is react component, even if we don't have a parent yet ref.reactParent = null; } edgeVisitor.forEachEdge((childName, childVisitor) => { const childRef = childVisitor.getRef(); if (childRef && childName.startsWith('.')) { childRef.reactParent = visitorClone; childRef.reactKey = childName; } }); } else if (edgeName === '_renderedComponent') { if (ref.reactParent === undefined) { ref.reactParent = null; } edgeRef.reactParent = visitorClone; } } }); }); // build tree of react internal instances (since that's what has the structure) // fill in ref.reactTree = path registry node forEachRef(refs, (visitor) => { buildReactComponentTree(visitor, registry, strings); }); // hook in components by looking at their _reactInternalInstance fields forEachRef(refs, (visitor) => { const ref = visitor.getRef(); const instanceRef = visitor.moveToEdge('_reactInternalInstance').getRef(); if (instanceRef) { ref.reactTree = instanceRef.reactTree; } }); } function functionUrlFileName(visitor) { const executable = visitor.clone().moveToEdge('@Executable'); const ref = executable.getRef(); if (ref && ref.value && ref.value.url) { const url = ref.value.url; let file = url.substring(url.lastIndexOf('/') + 1); if (file.endsWith('.js')) { file = file.substring(0, file.length - 3); } return file; } return undefined; } function markModules(refs) { const modules = firstRef(refs, (id, ref) => ref.type === 'CallbackGlobalObject'); modules.moveToEdge('require'); modules.moveToFirst((name, visitor) => visitor.getType() === 'JSActivation'); modules.moveToEdge('modules'); modules.forEachEdge((name, visitor) => { const ref = visitor.getRef(); visitor.moveToEdge('exports'); if (visitor.getType() === 'Object') { visitor.moveToFirst((memberName, member) => member.getType() === 'Function'); if (visitor.isDefined()) { ref.module = functionUrlFileName(visitor); } } else if (visitor.getType() === 'Function') { const displayName = visitor.clone().moveToEdge('displayName'); if (displayName.isDefined()) { ref.module = displayName.getValue(); } ref.module = functionUrlFileName(visitor); } if (ref && !ref.module) { ref.module = '#unknown ' + name; } }); } function registerPathToRoot(refs, registry, strings) { markReactComponentTree(refs, registry, strings); markModules(refs); let breadth = []; forEachRef(refs, (visitor) => { const ref = visitor.getRef(); if (ref.type === 'CallbackGlobalObject') { ref.rootPath = registry.insert(registry.root, strings.intern(ref.type)); breadth.push(visitor.clone()); } }); while (breadth.length > 0) { const nextBreadth = []; for (let i = 0; i < breadth.length; i++) { const visitor = breadth[i]; const ref = visitor.getRef(); visitor.forEachEdge((edgeName, edgeVisitor) => { const edgeRef = edgeVisitor.getRef(); if (edgeRef && edgeRef.rootPath === undefined) { let pathName = edgeRef.type; if (edgeName) { pathName = edgeName + ': ' + pathName; } edgeRef.rootPath = registry.insert(ref.rootPath, strings.intern(pathName)); nextBreadth.push(edgeVisitor.clone()); // copy module and react tree forward if (edgeRef.module === undefined) { edgeRef.module = ref.module; } if (edgeRef.reactTree === undefined) { edgeRef.reactTree = ref.reactTree; } } }); } breadth = nextBreadth; } } function registerCapture(data, captureId, capture, stacks, strings) { // NB: capture.refs is potentially VERY large, so we try to avoid making // copies, even if iteration is a bit more annoying. let rowCount = 0; for (const id in capture.refs) { // eslint-disable-line no-unused-vars rowCount++; } for (const id in capture.markedBlocks) { // eslint-disable-line no-unused-vars rowCount++; } const inserter = data.rowInserter(rowCount); registerPathToRoot(capture.refs, stacks, strings); const noneString = strings.intern('#none'); const noneStack = stacks.insert(stacks.root, noneString); forEachRef(capture.refs, (visitor) => { // want to data.append(value, value, value), not IDs const ref = visitor.getRef(); const id = visitor.id; inserter.insertRow( parseInt(id, 16), ref.type, ref.size, captureId, ref.rootPath === undefined ? noneStack : ref.rootPath, ref.reactTree === undefined ? noneStack : ref.reactTree, visitor.getValue(), ref.module === undefined ? '#none' : ref.module, ); }); for (const id in capture.markedBlocks) { const block = capture.markedBlocks[id]; inserter.insertRow( parseInt(id, 16), 'Marked Block Overhead', block.capacity - block.size, captureId, noneStack, noneStack, 'capacity: ' + block.capacity + ', size: ' + block.size + ', granularity: ' + block.cellSize, '#none', ); } inserter.done(); } if (preLoadedCapture) { const strings = new StringInterner(); const stacks = new StackRegistry(); const columns = [ { name: 'id', type: 'int' }, { name: 'type', type: 'string', strings: strings }, { name: 'size', type: 'int' }, { name: 'trace', type: 'string', strings: strings }, { name: 'path', type: 'stack', stacks: stacks, getter: x => strings.get(x), formatter: x => x }, { name: 'react', type: 'stack', stacks: stacks, getter: x => strings.get(x), formatter: x => x }, { name: 'value', type: 'string', strings: strings }, { name: 'module', type: 'string', strings: strings }, ]; const data = new AggrowData(columns); registerCapture(data, 'trace', preLoadedCapture, stacks, strings); preLoadedCapture = undefined; // let GG clean up the capture const aggrow = new Aggrow(data); aggrow.addPointerExpander('Id', 'id'); const typeExpander = aggrow.addStringExpander('Type', 'type'); aggrow.addNumberExpander('Size', 'size'); aggrow.addStringExpander('Trace', 'trace'); const pathExpander = aggrow.addStackExpander('Path', 'path'); const reactExpander = aggrow.addStackExpander('React Tree', 'react'); const valueExpander = aggrow.addStringExpander('Value', 'value'); const moduleExpander = aggrow.addStringExpander('Module', 'module'); aggrow.expander.setActiveExpanders([ pathExpander, reactExpander, moduleExpander, typeExpander, valueExpander, ]); const sizeAggregator = aggrow.addSumAggregator('Size', 'size'); const countAggregator = aggrow.addCountAggregator('Count'); aggrow.expander.setActiveAggregators([ sizeAggregator, countAggregator, ]); ReactDOM.render(<AggrowTable aggrow={aggrow} />, document.body); }
lib/components/Spinner.js
gramakri/filepizza
import React from 'react' import classnames from 'classnames' import { formatSize } from '../util' export default class Spinner extends React.Component { render() { const classes = classnames('spinner', { 'spinner-animated': this.props.animated }) return <div className={classes}> <div className="spinner-content"> <img alt={this.props.name || this.props.dir} src={`/images/${this.props.dir}.png`} className="spinner-image" /> {this.props.name === null ? null : <div className="spinner-name">{this.props.name}</div>} {this.props.size === null ? null : <div className="spinner-size">{formatSize(this.props.size)}</div>} </div> <img src="/images/pizza.png" className="spinner-background" /> </div> } } Spinner.propTypes = { dir: React.PropTypes.oneOf(['up', 'down']).isRequired, name: React.PropTypes.string, size: React.PropTypes.number, animated: React.PropTypes.bool } Spinner.defaultProps = { name: null, size: null, animated: false }
Console/app/node_modules/rc-table/es/ColumnManager.js
RisenEsports/RisenEsports.github.io
import _toConsumableArray from 'babel-runtime/helpers/toConsumableArray'; import _extends from 'babel-runtime/helpers/extends'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import React from 'react'; var ColumnManager = function () { function ColumnManager(columns, elements) { _classCallCheck(this, ColumnManager); this._cached = {}; this.columns = columns || this.normalize(elements); } _createClass(ColumnManager, [{ key: 'isAnyColumnsFixed', value: function isAnyColumnsFixed() { var _this = this; return this._cache('isAnyColumnsFixed', function () { return _this.columns.some(function (column) { return !!column.fixed; }); }); } }, { key: 'isAnyColumnsLeftFixed', value: function isAnyColumnsLeftFixed() { var _this2 = this; return this._cache('isAnyColumnsLeftFixed', function () { return _this2.columns.some(function (column) { return column.fixed === 'left' || column.fixed === true; }); }); } }, { key: 'isAnyColumnsRightFixed', value: function isAnyColumnsRightFixed() { var _this3 = this; return this._cache('isAnyColumnsRightFixed', function () { return _this3.columns.some(function (column) { return column.fixed === 'right'; }); }); } }, { key: 'leftColumns', value: function leftColumns() { var _this4 = this; return this._cache('leftColumns', function () { return _this4.groupedColumns().filter(function (column) { return column.fixed === 'left' || column.fixed === true; }); }); } }, { key: 'rightColumns', value: function rightColumns() { var _this5 = this; return this._cache('rightColumns', function () { return _this5.groupedColumns().filter(function (column) { return column.fixed === 'right'; }); }); } }, { key: 'leafColumns', value: function leafColumns() { var _this6 = this; return this._cache('leafColumns', function () { return _this6._leafColumns(_this6.columns); }); } }, { key: 'leftLeafColumns', value: function leftLeafColumns() { var _this7 = this; return this._cache('leftLeafColumns', function () { return _this7._leafColumns(_this7.leftColumns()); }); } }, { key: 'rightLeafColumns', value: function rightLeafColumns() { var _this8 = this; return this._cache('rightLeafColumns', function () { return _this8._leafColumns(_this8.rightColumns()); }); } // add appropriate rowspan and colspan to column }, { key: 'groupedColumns', value: function groupedColumns() { var _this9 = this; return this._cache('groupedColumns', function () { var _groupColumns = function _groupColumns(columns) { var currentRow = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var parentColumn = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var rows = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; // track how many rows we got rows[currentRow] = rows[currentRow] || []; var grouped = []; var setRowSpan = function setRowSpan(column) { var rowSpan = rows.length - currentRow; if (column && !column.children && // parent columns are supposed to be one row rowSpan > 1 && (!column.rowSpan || column.rowSpan < rowSpan)) { column.rowSpan = rowSpan; } }; columns.forEach(function (column, index) { var newColumn = _extends({}, column); rows[currentRow].push(newColumn); parentColumn.colSpan = parentColumn.colSpan || 0; if (newColumn.children && newColumn.children.length > 0) { newColumn.children = _groupColumns(newColumn.children, currentRow + 1, newColumn, rows); parentColumn.colSpan = parentColumn.colSpan + newColumn.colSpan; } else { parentColumn.colSpan++; } // update rowspan to all same row columns for (var i = 0; i < rows[currentRow].length - 1; ++i) { setRowSpan(rows[currentRow][i]); } // last column, update rowspan immediately if (index + 1 === columns.length) { setRowSpan(newColumn); } grouped.push(newColumn); }); return grouped; }; return _groupColumns(_this9.columns); }); } }, { key: 'normalize', value: function normalize(elements) { var _this10 = this; var columns = []; React.Children.forEach(elements, function (element) { if (!React.isValidElement(element)) { return; } var column = _extends({}, element.props); if (element.key) { column.key = element.key; } if (element.type.isTableColumnGroup) { column.children = _this10.normalize(column.children); } columns.push(column); }); return columns; } }, { key: 'reset', value: function reset(columns, elements) { this.columns = columns || this.normalize(elements); this._cached = {}; } }, { key: '_cache', value: function _cache(name, fn) { if (name in this._cached) { return this._cached[name]; } this._cached[name] = fn(); return this._cached[name]; } }, { key: '_leafColumns', value: function _leafColumns(columns) { var _this11 = this; var leafColumns = []; columns.forEach(function (column) { if (!column.children) { leafColumns.push(column); } else { leafColumns.push.apply(leafColumns, _toConsumableArray(_this11._leafColumns(column.children))); } }); return leafColumns; } }]); return ColumnManager; }(); export default ColumnManager;
app/routes.js
rfarine/ArtistRanking
import React from 'react'; import {Route} from 'react-router'; import App from './components/App'; import Home from './components/Home'; import AddArtist from './components/AddArtist'; export default ( <Route handler={App}> <Route path='/' handler={Home} /> <Route path='/add' handler={AddArtist} /> </Route> );
cpat-client/src/components/target-types/person/forms/form-arrays/PersonOrganizationsFormArray.js
meddlin/CPAT
import React from 'react'; import { withFormik, Form, FieldArray } from 'formik'; import { Button, TextInput, Heading } from 'evergreen-ui'; import { validations } from '../../../../../data/form-helpers/formArray-property-validation'; import styled from 'styled-components'; export const PersonOrganizationsFormArray = ({ move, swap, push, insert, remove, unshift, pop, form }) => ( <Form> <div>Organizations</div> {/** * Inserts the initial values to the beginning of the array * - Check initial values is an Array * - Check form values is an Array * - **Only perform this 'unshift()' operation if the initial.values is "longer" than the form.values** * -- NOTE: Formik will re-render the form a few times. This piece is key to NOT having multiple duplicates of intial.values left in the form! */} {/* {Array.isArray(form.initialValues.organizations) && Array.isArray(form.values.organizations) && (form.initialValues.organizations.length > form.values.organizations.length) ? ( form.initialValues.organizations.map(init => ( form.values.organizations.unshift(init) )) ) : ''} */} {validations.emptyFormValues(form.initialValues.organizations, form.values.organizations) || validations.initialLongerThanValues(form.initialValues.organizations, form.values.organizations) ? ( form.initialValues.organizations.map((init, idx) => ( form.values.organizations.unshift(init) )) ) : ''} {form.values.organizations && form.values.organizations.length > 0 ? ( form.values.organizations.map((r, index) => ( <div key={index}> <div> <div> <label>Name</label> <TextInput name={`organizations.${index}.name`} label="Name" onChange={form.handleChange} value={r.name} /> </div> <div> <label>Meta Info</label> <TextInput name={`organizations.${index}.metaInfo`} label="Meta Info" onChange={form.handleChange} value={r.metaInfo} /> </div> <div> <Button type="button" onClick={() => remove(index)}> - </Button> <Button type="button" onClick={() => insert((index + 1), {name: "", metaInfo: ""})}> + </Button> </div> </div> </div> )) ) : ( <Button type="button" onClick={() => push({name: "", metaInfo: ""})}>Add an Organization</Button> )} </Form> );
examples/components/Input.js
yesmeck/formsy-react
import React from 'react'; import Formsy from 'formsy-react'; const MyInput = React.createClass({ // Add the Formsy Mixin mixins: [Formsy.Mixin], // setValue() will set the value of the component, which in // turn will validate it and the rest of the form changeValue(event) { this.setValue(event.currentTarget[this.props.type === 'checkbox' ? 'checked' : 'value']); }, render() { // Set a specific className based on the validation // state of this component. showRequired() is true // when the value is empty and the required prop is // passed to the input. showError() is true when the // value typed is invalid const className = this.props.className + ' ' + (this.showRequired() ? 'required' : this.showError() ? 'error' : null); // An error message is returned ONLY if the component is invalid // or the server has returned an error message const errorMessage = this.getErrorMessage(); return ( <div className='form-group'> <label htmlFor={this.props.name}>{this.props.title}</label> <input type={this.props.type || 'text'} name={this.props.name} onChange={this.changeValue} value={this.getValue()} checked={this.props.type === 'checkbox' && this.getValue() ? 'checked' : null} /> <span className='validation-error'>{errorMessage}</span> </div> ); } }); export default MyInput;
app/components/AddQuestion.js
jayteesanchez/project-4
import React from 'react'; import AddQuestionStore from '../stores/AddQuestionStore'; import AddQuestionActions from '../actions/AddQuestionActions'; class AddQuestion extends React.Component { constructor(props) { super(props); this.state = AddQuestionStore.getState(); this.onChange = this.onChange.bind(this); } componentDidMount() { AddQuestionStore.listen(this.onChange); } componentWillUnmount() { AddQuestionStore.unlisten(this.onChange); } onChange(state) { this.setState(state); } handleSubmit(event) { event.preventDefault(); var q = this.state.question.trim(); var c1 = this.state.choice1; var c1_img = this.state.choice1_img; var c2 = this.state.choice2; var c2_img = this.state.choice2_img; if (!q) { AddQuestionActions.invalidQuestion(); this.refs.questionTextField.getDOMNode().focus(); } if (!c1) { AddQuestionActions.invalidChoice1(); } if (!c1_img) { AddQuestionActions.invalidChoice1_img(); } if (!c2) { AddQuestionActions.invalidChoice2(); } if (!c2_img) { AddQuestionActions.invalidChoice2_img(); } if (q && c1 && c1_img && c2 && c2_img) { AddQuestionActions.addQuestion(q, c1, c1_img, c2, c2_img); } } render() { return ( <div className='container'> <div className='row fadeInUp animated'> <div className='col-sm-8 col-sm-offset-2'> <div className='panel panel-default'> <div className='panel-heading'>Add your Question!</div> <div className='panel-body'> <form onSubmit={this.handleSubmit.bind(this)}> <div className={'form-group ' + this.state.questionValidationState}> <label className='control-label'>Question</label> <input type='text' className='form-control' ref='questionTextField' value={this.state.question} onChange={AddQuestionActions.updateQuestion} autoFocus/> <span className='help-block'>{this.state.helpBlock}</span> </div> <div className={'form-group ' + this.state.choice1ValidationState}> <label className='control-label'>Choice 1</label> <input type='text' className='form-control' ref='choice1TextField' value={this.state.choice1} onChange={AddQuestionActions.updateChoice1} /> <span className='help-block'>{this.state.helpBlock}</span> </div> <div className={'form-group ' + this.state.choice1_imgValidationState}> <label className='control-label'>Choice 1 Image URL</label> <input type='text' className='form-control' ref='choice1_imgTextField' value={this.state.choice1_img} onChange={AddQuestionActions.updateChoice1_img} /> <span className='help-block'>{this.state.helpBlock}</span> </div> <div className={'form-group ' + this.state.choice2ValidationState}> <label className='control-label'>Choice 2</label> <input type='text' className='form-control' ref='choice2TextField' value={this.state.choice2} onChange={AddQuestionActions.updateChoice2} /> <span className='help-block'>{this.state.helpBlock}</span> </div> <div className={'form-group ' + this.state.choice2_imgValidationState}> <label className='control-label'>Choice 2 Image URL</label> <input type='text' className='form-control' ref='choice2_imgTextField' value={this.state.choice2_img} onChange={AddQuestionActions.updateChoice2_img} /> <span className='help-block'>{this.state.helpBlock}</span> </div> <button type='submit' className='btn btn-success flipInX animated'>Submit</button> </form> </div> </div> </div> </div> </div> ); } } export default AddQuestion;
src/components/Login/LoginButton.js
niekert/soundify
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import SoundcloudLogo from 'components/TopBar/SoundCloudLogo'; import styled from 'styled-components'; const Button = styled.button` background: #ff7700; color: white; cursor: pointer; padding: 5px 15px; margin: 0 auto; border-radius: 5px; display: flex; align-items: center; font-size: 16px; svg { color: white; height: 50px; width: 50px; margin-right: 15px; } `; class LoginButton extends Component { static propTypes = { onLoginClicked: PropTypes.func.isRequired, }; render() { return ( <Button onClick={this.props.onLoginClicked}> <SoundcloudLogo /> Connect to SoundCloud </Button> ); } } export default LoginButton;
src/components/Result/Result.js
GovWizely/trade-event-search-app
import React from 'react'; import PropTypes from 'prop-types'; import { map } from 'lodash'; import Item from './SimpleCard'; import './Result.scss'; const Result = ({ results }) => { if (results.isFetching) return null; const items = map(results.items, result => ( <Item key={result.id} result={result} /> )); return ( <div className="explorer__result"> {items} </div> ); }; Result.propTypes = { results: PropTypes.object.isRequired, }; export default Result;
src/Containers/Logout.js
mad-pirate/dashboard-example-frontend
import React from 'react'; import LogoutLink from '../Components/Layouts/Shared/LogoutLink'; /** Storage */ import Store from '../Controll/Store'; import * as Actions from '../Controll/Actions/Authorization'; class Logout extends React.Component { onClick(event) { event.preventDefault(); Store.dispatch(Actions.logout()); } render() { return( <LogoutLink onClick={ this.onClick.bind(this) } username={ Store.getState().Authorization.username } /> ); } } export default Logout;
src/svg-icons/maps/local-florist.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalFlorist = (props) => ( <SvgIcon {...props}> <path d="M12 22c4.97 0 9-4.03 9-9-4.97 0-9 4.03-9 9zM5.6 10.25c0 1.38 1.12 2.5 2.5 2.5.53 0 1.01-.16 1.42-.44l-.02.19c0 1.38 1.12 2.5 2.5 2.5s2.5-1.12 2.5-2.5l-.02-.19c.4.28.89.44 1.42.44 1.38 0 2.5-1.12 2.5-2.5 0-1-.59-1.85-1.43-2.25.84-.4 1.43-1.25 1.43-2.25 0-1.38-1.12-2.5-2.5-2.5-.53 0-1.01.16-1.42.44l.02-.19C14.5 2.12 13.38 1 12 1S9.5 2.12 9.5 3.5l.02.19c-.4-.28-.89-.44-1.42-.44-1.38 0-2.5 1.12-2.5 2.5 0 1 .59 1.85 1.43 2.25-.84.4-1.43 1.25-1.43 2.25zM12 5.5c1.38 0 2.5 1.12 2.5 2.5s-1.12 2.5-2.5 2.5S9.5 9.38 9.5 8s1.12-2.5 2.5-2.5zM3 13c0 4.97 4.03 9 9 9 0-4.97-4.03-9-9-9z"/> </SvgIcon> ); MapsLocalFlorist = pure(MapsLocalFlorist); MapsLocalFlorist.displayName = 'MapsLocalFlorist'; MapsLocalFlorist.muiName = 'SvgIcon'; export default MapsLocalFlorist;
src/parser/monk/brewmaster/modules/spells/CelestialFortune.js
fyruna/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import StatTracker from 'parser/shared/modules/StatTracker'; import Combatants from 'parser/shared/modules/Combatants'; import StatisticBox from 'interface/others/StatisticBox'; import SPELLS from 'common/SPELLS'; import SPECS from 'game/SPECS'; import SpellIcon from 'common/SpellIcon'; import SpecIcon from 'common/SpecIcon'; import SpellLink from 'common/SpellLink'; import Icon from 'common/Icon'; import Panel from 'interface/others/Panel'; import {formatNumber} from 'common/format'; /** * Celestial Fortune * * CF has two effects: * * 1. Any non-absorb heal has a chance equal to your crit% to trigger * CF, healing you for an additional 65% * * 2. Any absorb is increased by a factor of (1 + crit%) * * This module tracks both and breaks down the healing done by source * player. */ class CelestialFortune extends Analyzer { static dependencies = { stats: StatTracker, combatants: Combatants, }; critBonusHealing = 0; _totalHealing = 0; _overhealing = 0; _healingByEntityBySpell = { /* * spellId: { * logged: Number, * absorb: Boolean, * }, */ }; _lastMaxHp = 0; get hps() { return this._totalHealing / (this.owner.fightDuration / 1000); } get totalHealing() { return this._totalHealing; } get bonusCritRatio() { return 1 - this.stats.baseCritPercentage / this.stats.currentCritPercentage; } on_toPlayer_heal(event) { this._lastMaxHp = event.maxHitPoints ? event.maxHitPoints : this._lastMaxHp; if(event.ability.guid === SPELLS.CELESTIAL_FORTUNE_HEAL.id) { const amount = event.amount + (event.absorbed || 0); const overheal = event.overheal || 0; this._totalHealing += amount; this.critBonusHealing += Math.max(0, amount * this.bonusCritRatio); this._overhealing += overheal; this._queueHealing(event); return; } else { // only adds if a CF heal is queued this._addHealing(event); } } on_toPlayer_applybuff(event) { if(event.absorb === undefined) { return; } this._addAbsorb(event); } _nextCFHeal = null; _queueHealing(event) { if(this._nextCFHeal !== null) { console.warn("Resetting CF healing", event); } this._nextCFHeal = event; } _initHealing(sourceId, id, absorb) { if(!this._healingByEntityBySpell[sourceId]) { this._healingByEntityBySpell[sourceId] = { _totalHealing: 0, }; } if(!this._healingByEntityBySpell[sourceId][id]) { this._healingByEntityBySpell[sourceId][id] = { amount: 0, absorb, }; } } _addHealing(event) { if(this._nextCFHeal === null) { return; } const totalCFAmount = this._nextCFHeal.amount + (this._nextCFHeal.overheal || 0); const totalAmount = event.amount + (event.overheal || 0); if(Math.abs(totalCFAmount - 0.65 * totalAmount) > 0.1 * totalAmount && totalAmount > 100) { console.warn("Potential CF misalignment", event, this._nextCFHeal); } const spellId = event.ability.guid; const sourceId = event.sourceID; this._initHealing(sourceId, spellId, false); this._healingByEntityBySpell[sourceId][spellId].amount += this._nextCFHeal.amount; this._healingByEntityBySpell[sourceId]._totalHealing += this._nextCFHeal.amount; this._nextCFHeal = null; } _addAbsorb(event) { const crit = this.stats.currentCritPercentage; const sourceId = event.sourceID; const spellId = event.ability.guid; this._initHealing(sourceId, spellId, true); const amount = event.absorb * crit / (1 + crit); // assuming 0 overhealing by absorbs, which isn't a *huge* // assumption, but less than ideal. this._healingByEntityBySpell[sourceId][spellId].amount += amount; this._healingByEntityBySpell[sourceId]._totalHealing += amount; this._totalHealing += amount; this.critBonusHealing += amount * this.bonusCritRatio; } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.CELESTIAL_FORTUNE_HEAL.id} />} value={`${formatNumber(this.hps)} HPS`} label="Celestial Fortune Healing" /> ); } entries() { function playerSpan(id, style={float: 'left'}) { const combatant = this.combatants.players[id]; if(!combatant) { return ''; } const spec = SPECS[combatant.specId]; const specClassName = spec.className.replace(' ', ''); return ( <span style={style} className={specClassName}><SpecIcon id={spec.id} />{` ${combatant.name}`}</span> ); } const playerTable = ([sourceId, obj]) => { const tableEntries = Object.entries(obj) .filter(([id, {amount}]) => amount > this._lastMaxHp * 0.01) .sort(([idA, objA], [idB, objB]) => objB.amount - objA.amount); if(tableEntries.length === 0) { return null; // a few small healing sources, skipping } return ( <tbody key={sourceId}> <tr> <th style={{width: '20%'}}>{playerSpan.call(this, sourceId)}</th> <th style={{width: '20%'}}>Spell</th> <th style={{width: '10%'}}>HPS</th> <th>Fraction of CF Healing</th> <th /> </tr> {tableEntries .filter(([id, obj]) => id !== '_totalHealing') .map(([id, {absorb, amount}]) => ( <tr key={id}> <td /> <td> <SpellLink id={Number(id)} icon={false}> {SPELLS[id] ? <><Icon icon={SPELLS[id].icon} /> {SPELLS[id].name}</> : id} </SpellLink> </td> <td>{absorb ? '≈': ''}{`${formatNumber(amount / (this.owner.fightDuration / 1000))} HPS`}</td> <td style={{width: '20%'}}> <div className="flex performance-bar-container"> <div className="flex-sub performance-bar" style={{ width: `${amount / this._totalHealing * 100}%`, backgroundColor: '#70b570' }} /> </div> </td> <td className="text-left"> {`${(amount / this._totalHealing * 100).toFixed(2)}%`} </td> </tr> ))} <tr> <td /> <td>Total from {playerSpan.call(this, sourceId, {})}</td> <td>{`${formatNumber(obj._totalHealing / (this.owner.fightDuration / 1000))} HPS`}</td> <td style={{width: '20%'}}> <div className="flex performance-bar-container"> <div className="flex-sub performance-bar" style={{ width: `${obj._totalHealing / this._totalHealing * 100}%`, backgroundColor: '#ff8000' }} /> </div> </td> <td className="text-left"> {`${(obj._totalHealing / this._totalHealing * 100).toFixed(2)}%`} </td> </tr> </tbody> ); }; const entries = Object.entries(this._healingByEntityBySpell) .sort(([idA, objA], [idB, objB]) => objB._totalHealing - objA._totalHealing) .map(playerTable); return entries; } tab() { return { title: 'Celestial Fortune', url: 'celestial-fortune', render: () => ( <Panel> <div style={{ marginTop: -10, marginBottom: -10 }}> <div style={{padding: '1em'}}>Bonus healing provided by <SpellLink id={SPELLS.CELESTIAL_FORTUNE_HEAL.id} />, broken down by triggering spell and which player cast that spell.</div> <table className="data-table" style={{ marginTop: 10, marginBottom: 10 }}> {this.entries()} </table> </div> </Panel> ), }; } } export default CelestialFortune;
ReactJS/class-2017-11-19/my-app/src/index.js
tahashahid/cloud-computing-2017
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; // import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App data1="hello" />, document.getElementById('root')); // registerServiceWorker(); // import React from 'react'; // import ReactDOM from 'react-dom'; // class App extends React.Component { // render() { // return ( // <div> // <Header /> // <Footer /> // </div> // ); // } // } // class Header extends React.Component { // render(){ // let a = 1; // let cssStyles = {color : "blue" , fontSize : "50px" } // return ( // <div style={ cssStyles } > // Header!! {a} // <Menu /> // </div> // ) // } // } // class Footer extends React.Component { // render(){ // return ( // <div> // Footer!! // </div> // ) // } // } // class Menu extends React.Component { // render(){ // return ( // <div> // Menu!! // </div> // ) // } // } // ReactDOM.render(<App />, document.getElementById('root')); // import { a, b } from './a'; // import c1, {a, b} from './a'; // import * as obj from './a'; // let a; // console.log('test'); // console.log(a + 10); // console.log(obj);
src/native/app/Header.js
reedlaw/read-it
// @flow import type { State } from '../../common/types'; import Icon from 'react-native-vector-icons/Ionicons'; import React from 'react'; import color from 'color'; import { Box, Button, Text } from '../../common/components'; import { Platform, StyleSheet } from 'react-native'; import { appShowMenu } from '../../common/app/actions'; import { connect } from 'react-redux'; type HeaderProps = { appShowMenu: typeof appShowMenu, menuShown: boolean, title: string, }; // iOS status bar is an overlay with default height 20px. We add one baseline // to preserve the vertical rhythm. We also set height to ensure hairline // border height (various) is included. const platformStyles = () => Platform.OS === 'ios' ? { paddingTop: 1, height: 3, } : { height: 2, }; const HeaderButton = ( { right, ...props }, ) => ( <Box alignSelf="stretch" flex={1} flexDirection="row" justifyContent={right ? 'flex-end' : 'flex-start'} > <Button // backgroundColor="danger" // To test. color="white" flexDirection="column" paddingHorizontal={0.5} {...props} /> </Box> ); const HeaderIcon = props => ( <Text as={Icon} color="white" size={1} {...props} /> ); const Header = ( { appShowMenu, menuShown, title, }: HeaderProps, ) => ( <Box {...platformStyles()} backgroundColor="primary" flexDirection="row" alignItems="center" style={theme => ({ borderBottomColor: color(theme.colors.primary).lighten(0.2).string(), borderBottomWidth: StyleSheet.hairlineWidth, })} > <HeaderButton onPress={() => appShowMenu(!menuShown)}> <HeaderIcon name="ios-menu" /> </HeaderButton> <Text color="white" size={1}> {title} </Text> <HeaderButton right> {/* A placeholder for the right side button. */} {/* <HeaderIcon name="ios-menu" /> */} {/* Foo */} </HeaderButton> </Box> ); export default connect( (state: State) => ({ menuShown: state.app.menuShown, }), { appShowMenu }, )(Header);
packages/react-devtools-shared/src/devtools/views/Button.js
Simek/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import React from 'react'; import Tooltip from '@reach/tooltip'; import styles from './Button.css'; import tooltipStyles from './Tooltip.css'; type Props = { children: React$Node, className?: string, title?: string, }; export default function Button({ children, className = '', title = '', ...rest }: Props) { let button = ( <button className={`${styles.Button} ${className}`} {...rest}> <span className={`${styles.ButtonContent} ${className}`} tabIndex={-1}> {children} </span> </button> ); if (title) { button = ( <Tooltip className={tooltipStyles.Tooltip} label={title}> {button} </Tooltip> ); } return button; }
app/modules/layout/components/Footer/index.js
anton-drobot/frontend-starter
import React, { Component } from 'react'; import { observer } from 'mobx-react'; import { bem } from 'app/libs/bem'; import Copyright from 'app/modules/layout/components/Copyright'; const b = bem('Footer'); @observer export default class Footer extends Component { render() { return ( <footer className={b()}> <div className={b('wrapper')}> <Copyright /> </div> </footer> ); } }
src/components/PartiesPage/PartiesPage.js
cbellino/roster
import React, { Component } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './PartiesPage.scss'; import PartyListContainer from '../../containers/PartyListContainer/PartyListContainer'; const PartiesPage = () => ( <div className={s.root}> <PartyListContainer /> </div> ) export default withStyles(PartiesPage, s);
packages/node_modules/@ciscospark/react-component-avatar/src/index.js
bzang/react-ciscospark
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Icon, {ICON_TYPE_MESSAGE} from '@ciscospark/react-component-icon'; import styles from './styles.css'; function Avatar({baseColor, name, image, isSelfAvatar, size}) { let avatarClass, avatarContents; let backgroundStyle = {}; if (baseColor) { backgroundStyle.backgroundColor = baseColor; avatarClass = [styles.avatarColorLetter, styles.avatarLetter]; avatarContents = <span>{name.substr(0, 1)}</span>; } else if (isSelfAvatar) { avatarContents = <span className={classNames(`ciscospark-avatar-self`, styles.avatarSelf)}><Icon type={ICON_TYPE_MESSAGE} /></span>; } else if (image) { backgroundStyle = {backgroundImage: `url('${image}')`}; } else if (name) { const letter = name.split(` `).slice(0, 2).map((n) => n.substr(0, 1)).join(``); avatarClass = styles.avatarLetter; avatarContents = <span>{letter}</span>; } return ( <div className={classNames(`ciscospark-avatar`, styles.avatar, `avatar-${size}`, styles[size], avatarClass)} style={backgroundStyle}> {avatarContents} </div> ); } Avatar.propTypes = { baseColor: PropTypes.string, image: PropTypes.string, isSelfAvatar: PropTypes.bool, name: PropTypes.string, size: PropTypes.oneOf([`small`, `medium`, `large`]) }; export default Avatar;
src/parser/shaman/restoration/modules/talents/Torrent.js
FaideWW/WoWAnalyzer
import React from 'react'; import SpellLink from 'common/SpellLink'; import SPELLS from 'common/SPELLS'; import { formatPercentage } from 'common/format'; import Analyzer from 'parser/core/Analyzer'; import calculateEffectiveHealing from 'parser/core/calculateEffectiveHealing'; import StatisticListBoxItem from 'interface/others/StatisticListBoxItem'; const TORRENT_HEALING_INCREASE = 0.3; class Torrent extends Analyzer { healing = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.TORRENT_TALENT.id); } on_byPlayer_heal(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.RIPTIDE.id || event.tick) { return; } this.healing += calculateEffectiveHealing(event, TORRENT_HEALING_INCREASE); } on_feed_heal(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.RIPTIDE.id || event.tick) { return; } this.healing += event.feed * TORRENT_HEALING_INCREASE; } subStatistic() { return ( <StatisticListBoxItem title={<SpellLink id={SPELLS.TORRENT_TALENT.id} />} value={`${formatPercentage(this.owner.getPercentageOfTotalHealingDone(this.healing))} %`} /> ); } } export default Torrent;
client/components/GalleryComponent.js
spectralsun/reactgur
import React from 'react'; import {Glyphicon} from 'react-bootstrap'; import xhttp from 'xhttp'; import MediaComponent from './../components/MediaComponent.js'; import ee from '../Emitter.js'; import Scroll from '../Scroll.js'; export default class GalleryComponent extends React.Component { constructor(props) { super(props); this.state = {images: []} this.columns = 5; } componentWillMount() { this.calculateMaxSize(); } componentDidMount() { ee.addListener('resize', this.handleWindowResize.bind(this)); ee.addListener('wrapper_scroll', this.handleScroll.bind(this)); ee.addListener('media_uploaded', this.handleMediaUploaded.bind(this)); this.csrfToken = document.querySelector('meta[name="csrf-token"]').content; this.page_wrapper = React.findDOMNode(this.refs.mainContainer).parentNode; this.scroll = new Scroll(page_wrapper); this.createIsoContainer(); } componentDidUpdate() { this.createIsoContainer(); if (!this.refs.isoContainer) return; var new_media = []; var items = this.refs.isoContainer.getDOMNode().children; for (var x = 0; x < items.length; x++) { if (items[x].style.top === "") new_media.push(items[x]); } if (new_media.length > 0) this.prependMedia ? this.iso.prepended(new_media) : this.iso.appended(new_media); this.iso.arrange(); this.prependMedia = false; } calculateExpandedPosition() { var item_column = ((parseInt(this.expanded.item.style.left) - 74) + 198) / 198; if (item_column >= (this.columns - 2)) { var offset = 0; if (item_column < this.columns) { offset = this.columns - item_column; while ((this.expanded_width + (this.expanded_margin_lr * 2) + 18) > (198 * (this.columns - offset))) { offset --; } } this.expanded.item.style.right = (74 + (198 * (offset))) + 'px'; this.expanded.item.style.left = ''; } } calculateExpandedSize() { if (!this.expanded) return; var img = this.expanded.img; var item = this.expanded.item; var width = parseInt(item.dataset.width); var height = parseInt(item.dataset.height); if (width > this.max_width) { height = (this.max_width * height)/width; width = this.max_width; } if (height > this.max_height) { width = (this.max_height * width)/height; height = this.max_height; } var total_width = width + 18; var total_height = height + 18; var margin_lr = 0; var margin_tb = 0; if (width < 380 && height < 380) margin_tb = ((380 - height) / 2); else margin_tb = Math.floor((((Math.ceil(total_height / 198) * 198) - total_height) / 2)); if (item.dataset.width >= 380) margin_lr = Math.floor((((Math.ceil(total_width / 198) * 198) - total_width) / 2)); if ((width + (margin_lr * 2)) >= this.max_width) margin_tb = 4; this.setExpandedSize(margin_tb, margin_lr, height, width) // Save for preparing expanded item position this.expanded_margin_lr = margin_lr; this.expanded_width = width; } calculateMaxSize() { this.mobile = false; this.columns = 5; if (window.innerWidth <= 1200) this.columns = 4; else if (window.innerWidth <= 992) this.columns = 3; else if (window.innerWidth <= 768) this.mobile = true; this.max_width = (this.columns * 192) + 4; this.max_height = window.innerHeight - 130; } createIsoContainer() { if (this.iso || !this.refs.isoContainer) return; this.iso = new Isotope(this.refs.isoContainer.getDOMNode(), { layoutMode: 'packery', sortBy:'created', sortAscending: false, getSortData: { created: '[data-created] parseInt' } }); this.iso.on('layoutComplete', this.handleLayoutComplete.bind(this)); this.iso.arrange(); } closeExpanded() { this.expanded.item.className = 'media-item well'; this.expanded.img.src = this.expanded.item.dataset.thumbnail; this.setExpandedSize(0, 0, 180, 180); this.expanded.item.style.right = ''; } expand(item) { if (this.expanded) { this.closeExpanded(); if (this.expanded.id === item.dataset.id) { this.scrollTo = this.expanded; this.shrunkTo = this.expanded.img.src; this.expanded = null; return; } } this.expanded = this.scrollTo = { id: item.dataset.id, item: item, img: item.firstChild } this.expanded.item.className = 'media-item well expanded'; this.expanded.img.src = this.expanded.item.dataset.href; this.calculateExpandedSize(); this.calculateExpandedPosition(); this.iso.arrange(); } handleImageLoad(e) { if (this.expanded || this.shrunkTo) { this.shrunkTo = null; this.iso.arrange(); } } handleItemClick(e) { var node = e.target; var bottom_overlay = null; var item = null; while (!item) { if (node.className.indexOf('media-api-button') !== -1) return; if (node.className.indexOf('media-overlay-bottom') !== -1) bottom_overlay = node; if (node.className.indexOf('media-item') !== -1) item = node; node = node.parentNode; } if (bottom_overlay && item.className.indexOf('expanded') !== -1) return; this.expand(item); } handleItemDelete(mediaItemNode) { mediaItemNode.style.display = 'none'; this.iso.arrange(); } handleLayoutComplete() { if (this.scrollTo) { var height = this.scrollTo.item.getBoundingClientRect().height; var marginTop = parseInt(this.scrollTo.img.style.marginTop); var topPos = parseInt(this.scrollTo.item.style.top) var scrollPos = topPos - ((window.innerHeight - (height + (marginTop * 2))) / 2) + 42; if (this.scrollTo.img.height == this.max_height) scrollPos = topPos + marginTop - 4; this.scroll.scrollToPos(scrollPos); this.scrollTo = false; } if (this.expanded) { this.expanded.item.style.right = ''; } } handleLoadError(data) { this.loadLock = false; } handleLoadSuccess(data) { this.refs.loadingBar.getDOMNode().style.display = 'none'; this.setState({images: this.state.images.concat(data)}); this.loadLock = false; } handleMediaUploaded(data) { this.prependMedia = true; this.setState({images: data.concat(this.state.images)}) } handleScroll(e, page_wrapper) { var container = this.refs.isoContainer.getDOMNode(); var height = container.getBoundingClientRect().height + 61; if (this.scroll.position() >= height - window.innerHeight) { this.fetchMedia(); } } handleWindowResize() { this.calculateMaxSize(); this.calculateExpandedSize(); this.iso.arrange(); } fetchMedia() { if (this.loadLock) return; this.refs.loadingBar.getDOMNode().style.display = 'block'; this.loadLock = true; xhttp({ url: '/api/v1/media', method: 'get', headers: { 'X-CSRFToken': this.csrfToken }, params: { after: this.state.images[this.state.images.length - 1].href } }) .then(this.handleLoadSuccess.bind(this)) .catch(this.handleLoadError.bind(this)); } prependMedia(media) { this.setState({images: [].concat(media, this.state.images)}); } setExpandedSize(margin_tb, margin_lr, height, width) { this.expanded.img.style.marginTop = margin_tb + 'px'; this.expanded.img.style.marginBottom = margin_tb + 'px'; this.expanded.img.style.marginLeft = margin_lr + 'px'; this.expanded.img.style.marginRight = margin_lr + 'px'; this.expanded.img.style.height = height + 'px'; this.expanded.img.style.width = width + 'px'; } render() { return this.state.images.length == 0 ? ( <div ref="mainContainer" className="jumbotron text-center"> <h1 className="text-center">{"There's no images here!"}</h1> <p>Upload some images!</p> <p> <a href="/upload" className="btn btn-success btn-lg"> <Glyphicon glyp='cloud-upload' /> <span> Upload Images</span> </a> </p> </div> ) : ( <div ref="mainContainer"> <div ref="isoContainer" className="panel media-component text-center" onScroll={this.handleScroll.bind(this)}> {this.state.images.map((image) => { return ( <MediaComponent key={image.href} image={image} onClick={this.handleItemClick.bind(this)} onDelete={this.handleItemDelete.bind(this)} onImageLoad={this.handleImageLoad.bind(this)} user={this.props.user} /> ); })} </div> <div id="loading_bar" className="text-center" ref='loadingBar'> <Glyphicon glyph='refresh' className='glyphicon-spin' /> </div> </div> ); } }
src/js/components/LocationListItem.js
grommet/grommet-people-finder
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React from 'react'; import PropTypes from 'prop-types'; import ListItem from 'grommet/components/ListItem'; import config from '../config'; const LocationListItem = (props) => { const { item } = props; return ( <ListItem justify='between' align='center' pad='medium' onClick={props.onClick} > <strong>{item[config.scopes.locations.attributes.name]}</strong> <span className='secondary'> {item[config.scopes.locations.attributes.city]} </span> </ListItem> ); }; LocationListItem.defaultProps = { item: undefined, onClick: undefined, }; LocationListItem.propTypes = { item: PropTypes.object, onClick: PropTypes.func, }; export default LocationListItem;
src/containers/header/Header.js
Gullskatten/react-seating-map-webapp
import './Header.css'; import React, { Component } from 'react'; import Title from '../../components/title/Title'; import FontAwesome from 'react-fontawesome'; import Modal from '../../components/modal/Modal'; import { UrlAddTeam, UrlAddFloor } from '../constants/UrlConstants'; import axios from 'axios'; import { inject, observer } from 'mobx-react'; @inject('store') @observer class Header extends Component { newTeamLocationChanged = e => { this.props.store.newTeamLocation = e.target.value; }; newTeamChanged = e => { this.props.store.newTeamName = e.target.value; }; saveNewTeam = () => { return axios .post(`${UrlAddTeam}`, { teamName: this.props.store.newTeamName, floor_id: this.props.store.currentFloor._id, members: [] }) .then(response => { this.props.store.fetchTeams(this.props.store.currentFloor._id); this.props.store.hideModal(); }) .catch(err => { console.log(err); }); }; displayNewTeamModal() { this.props.store.isNewTeamModalOpen = true; } displayNewFloorModal() { this.props.store.isNewFloorModalOpen = true; } renderNewTeamModal = () => { if (this.props.store.isNewTeamModalOpen) { return ( <Modal onExit={this.props.store.hideModal} height="275px"> <div className="ModalHeader"> Add new Team </div> <div className="ModalBody"> <p>Type in the name of the new team</p> <input type="text" placeholder="Enter team name.." onChange={this.newTeamChanged} /> <select className="select-style" onChange={this.newTeamLocationChanged} > <option value="D4 - Øst (Funksjonell + Markedsoperasjon) "> D4 - Øst (Funksjonell + Markedsoperasjon){' '} </option> <option value="D4 - Vest (Admin., Infrastruktur &amp; Edielportal)" > D4 - Vest (Admin., Infrastruktur & Edielportal) </option> <option value="D4 - Midt (Prosjekt, Test &amp; Migrering) "> D4 - Midt (Prosjekt, Test & Migrering){' '} </option> </select> <button onClick={this.saveNewTeam}>Save</button> </div> </Modal> ); } }; renderNewFloorModal() { if (this.props.store.isNewFloorModalOpen) { return ( <Modal onExit={this.props.store.hideModal} height="210px"> <div className="ModalHeader"> Add a new floor </div> <div className="ModalBody"> <p>Type in the name of the floor</p> <input type="text" placeholder="Enter a name.. (e.g. Floor 1.. Section A..)" onChange={this.newFloorNameChanged} /> <button onClick={this.saveNewFloor}>Save</button> </div> </Modal> ); } } newFloorNameChanged = event => { this.props.store.newFloorName = event.target.value; }; saveNewFloor = () => { axios .post(`${UrlAddFloor}`, { name: this.props.store.newFloorName }) .then(response => { this.props.store.fetchAllFloors(); this.props.store.currentFloor = response.data; this.props.store.hideModal(); //TODO: this.props.store.goToSlide(this.props.store.floors.length + 1); }) .catch(error => { console.log(error); }); }; render() { const toggleMenuIcon = this.props.store.isMenuOpen ? 'remove' : 'bars'; return ( <header className="Header"> {this.renderNewTeamModal()} {this.renderNewFloorModal()} <Title title={this.props.store.title} /> <span onClick={this.props.onClick}> <FontAwesome name={toggleMenuIcon} className="icon" /> </span> <div className="Header-addFloor" onClick={() => this.displayNewFloorModal()} > + New floor </div> <div className="Header-addTeam" onClick={() => this.displayNewTeamModal()} > + New team </div> </header> ); } } export default Header;
fixtures/packaging/systemjs-builder/prod/input.js
chicoxyzzy/react
import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render( React.createElement('h1', null, 'Hello World!'), document.getElementById('container') );
node_modules/lite-server/node_modules/browser-sync/node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
ghanvatpriyanka/angular2demo
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
src/components/dialog/demos/FullWidthActions.js
isogon/styled-mdl
import React from 'react' import { withStateHandlers } from 'recompose' import { Dialog, DialogTitle, DialogActions, DialogContent, Button, } from '../../../' const mdSpecLink = 'https://www.google.com/design/spec/components/dialogs.html#dialogs-specs' export default withStateHandlers( { isShowingDialog: false }, { showDialog: () => () => ({ isShowingDialog: true }), hideDialog: () => () => ({ isShowingDialog: false }), }, )(({ showDialog, hideDialog, isShowingDialog }) => ( <React.Fragment> <Button raised onClick={showDialog} text="Show" /> <Dialog isOpen={isShowingDialog} onRequestClose={hideDialog} contentLabel="My Dialog" appElement={document.getElementById('root')} size="5" > <DialogTitle>MDL Dialog</DialogTitle> <DialogContent> This is an example of the MDL Dialog being used as a modal. It is using the full width action design intended for use with buttons that do not fit within the specified <a href={mdSpecLink}>length metrics</a> . </DialogContent> <DialogActions fullWidth> <Button onClick={hideDialog}>Agree</Button> <Button disabled>Inactive Action</Button> </DialogActions> </Dialog> </React.Fragment> ))
demo/components/confirmation/ConfirmationDemo.js
f0zze/rosemary-ui
import DemoWithSnippet from '../../../demo/layout/DemoWithSnippet'; import Confirmation from '../../../src/components/Confirmation'; import React from 'react'; export default class ConfirmationDemo extends React.Component { constructor(props) { super(props); this.state = { open: false }; } render() { return ( <DemoWithSnippet> <Confirmation title="Do you really want to delete this activity?" body="Keep in mind that deleted activity can't be restored." /> </DemoWithSnippet> ); } }
packages/zensroom/lib/components/reviews/ReviewsList.js
SachaG/Zensroom
/* List of reviews, wrapped with withList http://docs.vulcanjs.org/data-loading.html#List-Resolver */ import React from 'react'; import { Components, registerComponent, withList, withCurrentUser, Loading } from 'meteor/vulcan:core'; import { FormattedMessage } from 'meteor/vulcan:i18n'; import Reviews from '../../modules/reviews/collection'; import ReviewsItem from './ReviewsItem'; const ReviewsList = ({results = [], currentUser, loading, loadMore, count, totalCount}) => <div> {loading ? <Loading /> : <div className="reviews"> <h3><FormattedMessage id="reviews.reviews"/></h3> {results.map(review => <Components.ReviewsItem key={review._id} review={review} currentUser={currentUser} />)} {totalCount > results.length ? <a href="#" onClick={e => {e.preventDefault(); loadMore();}}>Load More ({count}/{totalCount})</a> : null} </div> } </div> const options = { collection: Reviews }; registerComponent('ReviewsList', ReviewsList, [withList, options], withCurrentUser); // export default withList(options)(withCurrentUser(ReviewsList));