path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/svg-icons/notification/mms.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationMms = (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-2zM5 14l3.5-4.5 2.5 3.01L14.5 8l4.5 6H5z"/> </SvgIcon> ); NotificationMms = pure(NotificationMms); NotificationMms.displayName = 'NotificationMms'; NotificationMms.muiName = 'SvgIcon'; export default NotificationMms;
source/javascripts/routes.js
senthilporunan/packman
import React from 'react' import { Router, Route, Link } from 'react-router' import App from './containers/App' import About from './containers/About' // <Route path="/Users/yhisamatsu/_/js-dev/electron-redux-boilerplate/build/renderer/index.html" component={App}> // 一番はじめのパスは上記のようになるので、*/で待ち構えている // それ以外は基本的に相対パス、相対パスを使わないとパスの構造が変化して、画面遷移ができなくなるため export default ( <Router> {/* for electron */} <Route path="/" component={App}> </Route> {/* for web */} <Route path="/index.html" component={App}> </Route> <Route path="/routing" component={About}> </Route> </Router> )
packages/material-ui-icons/src/EventNote.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M17 10H7v2h10v-2zm2-7h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11zm-5-5H7v2h7v-2z" /></g> , 'EventNote');
app/react-icons/fa/life-bouy.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaLifeBouy extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m20 0q4.1 0 7.8 1.6t6.4 4.2 4.2 6.4 1.6 7.8-1.6 7.8-4.2 6.4-6.4 4.2-7.8 1.6-7.8-1.6-6.4-4.2-4.2-6.4-1.6-7.8 1.6-7.8 4.2-6.4 6.4-4.2 7.8-1.6z m0 2.9q-4.2 0-8.1 2l4.4 4.3q1.8-0.6 3.7-0.6t3.7 0.6l4.4-4.3q-3.9-2-8.1-2z m-15.1 25.2l4.3-4.4q-0.6-1.8-0.6-3.7t0.6-3.7l-4.3-4.4q-2 3.9-2 8.1t2 8.1z m15.1 9q4.2 0 8.1-2l-4.4-4.3q-1.8 0.6-3.7 0.6t-3.7-0.6l-4.4 4.3q3.9 2 8.1 2z m0-8.5q3.6 0 6.1-2.5t2.5-6.1-2.5-6.1-6.1-2.5-6.1 2.5-2.5 6.1 2.5 6.1 6.1 2.5z m10.8-4.9l4.3 4.4q2-3.9 2-8.1t-2-8.1l-4.3 4.4q0.6 1.8 0.6 3.7t-0.6 3.7z"/></g> </IconBase> ); } }
examples/index.js
stackscz/re-app
import React from 'react'; import ReactDOM from 'react-dom'; import ExamplesRouter from './ExamplesRouter'; ReactDOM.render( <ExamplesRouter />, document.getElementById('root') );
src/svg-icons/editor/border-bottom.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorBorderBottom = (props) => ( <SvgIcon {...props}> <path d="M9 11H7v2h2v-2zm4 4h-2v2h2v-2zM9 3H7v2h2V3zm4 8h-2v2h2v-2zM5 3H3v2h2V3zm8 4h-2v2h2V7zm4 4h-2v2h2v-2zm-4-8h-2v2h2V3zm4 0h-2v2h2V3zm2 10h2v-2h-2v2zm0 4h2v-2h-2v2zM5 7H3v2h2V7zm14-4v2h2V3h-2zm0 6h2V7h-2v2zM5 11H3v2h2v-2zM3 21h18v-2H3v2zm2-6H3v2h2v-2z"/> </SvgIcon> ); EditorBorderBottom = pure(EditorBorderBottom); EditorBorderBottom.displayName = 'EditorBorderBottom'; export default EditorBorderBottom;
pages/blog/test-article-one.js
koistya/react-static.tarkus.me
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React, { Component } from 'react'; export default class extends Component { render() { return ( <div> <h1>Test Article 1</h1> <p>Coming soon.</p> </div> ); } }
docs/app/Examples/views/Statistic/Variations/StatisticExampleSizeDivided.js
Rohanhacker/Semantic-UI-React
import React from 'react' import { Divider, Statistic } from 'semantic-ui-react' const StatisticExampleSizeDivided = () => ( <div> <Statistic size='mini' label='Views' value='2,204' /> <Divider /> <Statistic size='tiny' label='Views' value='2,204' /> <Divider /> <Statistic size='small' label='Views' value='2,204' /> <Divider /> <Statistic label='Views' value='2,204' /> <Divider /> <Statistic size='large' label='Views' value='2,204' /> <Divider /> <Statistic size='huge' label='Views' value='2,204' /> </div> ) export default StatisticExampleSizeDivided
src/index.js
michael-mao/lasso
import React from 'react'; import ReactDOM from 'react-dom'; import App from './scripts/App'; import './css/index.css'; ReactDOM.render( <App chrome={chrome}/>, // eslint-disable-line no-undef document.getElementById('root') );
lib/components/Reactable.js
Centiq/meteor-reactable
import React from 'react'; import createReactClass from 'create-react-class'; /** * This is the root component. It handles the configuration */ Reactable = createReactClass({ propTypes: ReactableConfigShape, render () { let props = { ...this.props }; delete props.children; // Convert "paginate" format from simple to advanced if (props.paginate) { if (typeof props.paginate === 'number') { props.paginate = { defaultLimit: props.paginate, }; } if (typeof props.paginate === 'object' && !props.paginate.defaultPage) { props.paginate.defaultPage = 1; } } // Convert "fields" format from simple to advanced props.fields = props.fields.map(origField => { let field = { ...origField }; // Convert "sort" format from simple to advanced if (typeof field.sort === 'number') { field.sort = { direction: field.sort }; } else if (typeof field.sort === 'object' && !field.sort.direction) { field.sort.direction = 1; } // If a label isn't specified, calculate one from the name if (typeof field.label !== 'string' && field.name) { field.label = field.name.split(/[_.]/).map(word => { return word.charAt(0).toUpperCase() + word.slice(1); }).join(' ').trim(); } return field; }); // Apply custom configuration defaults props = Reactable.applyConfigDefaults(props); props.fields = props.fields.map(origField => { let field = { ...origField }; return Reactable.applyFieldDefaults(field); }); // Sanity checks on server side pagination if (props.paginate && props.paginate.serverSide) { if (Array.isArray(props.source.collection)) { throw new Error("Can't use server side pagination with a non-reactive data source"); } let hasSorter = false; props.fields.forEach(field => { if (field.sort) { hasSorter = true; if (field.sort.custom) { throw new Error("Can't use server side pagination with a custom sort function"); } if (field.sort.transform) { throw new Error("Can't use server side pagination with a post-transform sort"); } if (typeof field.name !== 'string' && field.transform) { throw new Error("Can't use server side pagination with a sortable non-named field"); } } }); if (!hasSorter) { throw new Error("Can't use server side pagination without at least one server-side sortable field"); } } props.isReactive = !Array.isArray(props.source.collection); return ( <ReactableState { ...props }/> ); }, statics: (() => { let configDefaults = []; let fieldDefaults = []; return { manageState (obj) { }, setFieldDefaults (callback) { fieldDefaults.push(callback); }, applyFieldDefaults (field) { fieldDefaults.forEach(func => field = func(field)); return field; }, setConfigDefaults (callback) { configDefaults.push(callback); }, applyConfigDefaults (config) { configDefaults.forEach(func => config = func(config)); return config; }, }; })(), });
src/components/App.js
mikejablonski/newo-brew-web
import React from 'react'; import PropTypes from 'prop-types'; import { Link, IndexLink } from 'react-router'; // This is a class-based component because the current // version of hot reloading won't hot reload a stateless // component at the top-level. class App extends React.Component { render() { return ( /*<div> <IndexLink to="/">Home</IndexLink> {' | '} <Link to="/brew">Brew</Link> {' | '} <Link to="/fuel-savings">Recipes</Link> {' | '} <Link to="/about">History</Link> <br/> {this.props.children} </div>*/ <div className="container-fluid"> <ul className="nav nav-tabs"> <li role="presentation"><Link to="/brew">Brew</Link></li> <li role="presentation"><Link to="/history">History</Link></li> </ul> {this.props.children} </div> ); } } App.propTypes = { children: PropTypes.element }; export default App;
app/components/Pagination/Page.js
54vanya/ru-for-you-front
import React from 'react'; import styled from 'styled-components'; import Card from 'components/Card'; const Wrapper = styled.button` padding: 0.25em 0.5em; cursor:pointer; `; const Active = styled(Wrapper)` background-color:#e00024; color:#fff; cursor:default; `; const Page = ({ n, onClick, isActive }) => { const handleClick = () => { onClick(n); }; const Element = isActive ? Active : Wrapper; return ( <Card> <Element onClick={isActive ? false : handleClick}>{n + 1}</Element> </Card> ); }; Page.propTypes = { n: React.PropTypes.number.isRequired, onClick: React.PropTypes.func.isRequired, isActive: React.PropTypes.bool.isRequired, }; export default Page;
src/components/Header/Header.js
contor-cloud/contor-cloud.github.io
import React from 'react' import { colors, media } from '../config' import HeaderNav from './HeaderNav' import HeaderLogo from './HeaderLogo' import HeaderSocialMenu from './HeaderSocialMenu' // const Header = () => ( // <header> // <HeaderLogo /> // <HeaderNav /> // <HeaderSocialMenu /> // </header> // ) const Header = () => ( <header css={{ backgroundColor: colors.headerBackground, color: colors.white, position: 'fixed', top: 0, left: 0, zIndex: 1, width: '100%', height: 42, paddingLeft: 10, paddingRight: 10, display: 'grid', gridTemplateColumns: '1fr 4fr 1fr', alignItems: 'center', [media.greaterThan('medium')]: { gridTemplateColumns: '1fr 3.25fr 1.75fr', }, }}> <HeaderLogo /> <HeaderNav /> <HeaderSocialMenu /> </header> ) export default Header
app/containers/PreschoolProject/PreschoolProject.js
klpdotorg/tada-frontend
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import isEmpty from 'lodash.isempty'; import get from 'lodash.get'; import { PreschoolProjectView } from '../../components/PreschoolProject'; import { getBoundariesEntities } from '../../actions'; import { getEntitiesPath } from '../../utils'; class FetchProjectEntity extends Component { constructor() { super(); this.state = {}; } componentDidMount() { const { params, project, parentId } = this.props; const { districtNodeId, projectNodeId } = params; if (isEmpty(project)) { const entities = [parentId, districtNodeId, projectNodeId].map((id, i) => { return { depth: i, uniqueId: id }; }); this.props.getBoundariesEntities(entities); } } render() { return <PreschoolProjectView {...this.props} />; } } FetchProjectEntity.propTypes = { params: PropTypes.object, project: PropTypes.object, getBoundariesEntities: PropTypes.func, parentId: PropTypes.string, }; const mapStateToProps = (state, ownProps) => { const { projectNodeId, districtNodeId } = ownProps.params; const { isAdmin } = state.profile; const pathname = get(ownProps, ['location', 'pathname'], ''); const paths = getEntitiesPath(pathname, [districtNodeId]); return { project: state.boundaries.boundaryDetails[projectNodeId] || {}, district: state.boundaries.boundaryDetails[districtNodeId] || {}, isLoading: state.appstate.loadingBoundary, isAdmin, paths, parentId: state.profile.parentNodeId, }; }; const PreschoolProject = connect(mapStateToProps, { getBoundariesEntities })(FetchProjectEntity); export default PreschoolProject;
app/containers/AdminFournisseurInfos/components/FournisseurRelais.js
Proxiweb/react-boilerplate
import React from 'react'; import PropTypes from 'prop-types'; import { List, ListItem } from 'material-ui/List'; import styles from './styles.css'; class FournisseurRelais extends React.Component { static propTypes = { fournisseur: PropTypes.object.isRequired, relais: PropTypes.object.isRequired, ajouteRelais: PropTypes.func.isRequired, retireRelais: PropTypes.func.isRequired, }; render() { const { fournisseur, relais, retireRelais, ajouteRelais } = this.props; return ( <div className="col-md-12"> <div className="row"> <div className={`col-md-6 ${styles.listeFournisseur}`}> <p className={styles.titre}>Inactifs</p> <List className={styles.liste}> {Object.keys(relais).map((id, idx) => <ListItem key={idx} primaryText={relais[id].nom.toUpperCase()} onClick={() => this.props.ajouteRelais(id)} /> )} </List> </div> <div className={`col-md-6 ${styles.listeFournisseur}`}> <p className={styles.titre}>Actifs</p> <List className={styles.liste}> {fournisseur.relais.map((relaiFourn, idx) => <ListItem key={idx} primaryText={relais[relaiFourn.id].nom.toUpperCase()} onClick={() => this.props.retireRelais(relaiFourn.id)} /> )} </List> </div> </div> </div> ); } } export default FournisseurRelais;
src/components/StoryPage/index.js
JohnTasto/housing-frontend
/* eslint-disable import/no-extraneous-dependencies */ // This should probably be the core component, containing, nav etc import React from 'react'; import { connect } from 'react-redux'; export function StoryPage() { return ( <div>Placeholder</div> ); } StoryPage.displayName = 'StoryPage'; const mapDispatch = () => ({}); const mapProps = () => ({}); export default connect(mapProps, mapDispatch)(StoryPage);
js/components/loaders/ProgressBar.ios.js
allanrabanillo/Usave
/* @flow */ import React from 'react'; import { ProgressViewIOS } from 'react-native'; import NativeBaseComponent from 'native-base/Components/Base/NativeBaseComponent'; export default class ProgressBarNB extends NativeBaseComponent { render() { const getColor = () => { if (this.props.color) { return this.props.color; } else if (this.props.inverse) { return this.getTheme().inverseProgressColor; } return this.getTheme().defaultProgressColor; }; return ( <ProgressViewIOS progress={this.props.progress ? this.props.progress / 100 : 0.5} progressTintColor={getColor()} /> ); } }
src/components/common/ImageUpload.js
great-design-and-systems/cataloguing-app
import '../../images/upload-image.png'; import Dropzone from 'react-dropzone'; import { Img } from './'; import PropTypes from 'prop-types'; import React from 'react'; export class ImageUpload extends React.Component { constructor(prop) { super(prop); this.state = {}; this.onDrop = this.onDropFiles.bind(this); this.inputProps = { name: prop.name, required: prop.required }; } onDropFiles(accepted) { if (accepted) { this.setState({file: accepted[0]}); } } render() { return (<div className="image-upload books"> <h4>{this.props.required && <span className="text-danger">*&nbsp;</span>}{this.props.label}</h4> <Dropzone multiple={false} accept="image/jpeg, image/png" onDrop={this.onDrop} className="book"> {this.state.file ? <Img src={this.state.file ? this.state.file.preview : '/upload-image.png'}/> : <Img src={[this.props.value, '/upload-image.png']}/>} </Dropzone> <input {...this.inputProps} type="hidden"/> </div>); } } ImageUpload.propTypes = { label: PropTypes.string.isRequired, name: PropTypes.string.isRequired, value: PropTypes.string, required: PropTypes.bool };
app/components/Views/ViewStoryStepper.js
sceneweaver/entwine
import React from 'react'; import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import RaisedButton from 'material-ui/RaisedButton'; import FlatButton from 'material-ui/FlatButton'; import { Step, Stepper, StepButton, } from 'material-ui'; /* ----- COMPONENT ----- */ class ViewStoryStepper extends React.Component { constructor(props) { super(props); this.state = { stepIndex: 0, }; } handleNext() { const {stepIndex} = this.state; if (stepIndex < 2) { this.setState({stepIndex: stepIndex + 1}); } } handlePrev() { const {stepIndex} = this.state; if (stepIndex > 0) { this.setState({stepIndex: stepIndex - 1}); } } renderStepActions(step) { return ( <div style={{margin: '12px 0'}}> <RaisedButton label="Next" disableTouchRipple={true} disableFocusRipple={true} primary={true} onTouchTap={this.handleNext} style={{marginRight: 12}} /> {step > 0 && ( <FlatButton label="Back" disableTouchRipple={true} disableFocusRipple={true} onTouchTap={this.handlePrev} /> )} </div> ); } render() { const {stepIndex} = this.state; return ( <MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}> <div style={{ maxWidth: 380, maxHeight: 400, margin: 'auto', marginTop: 10 }}> <Stepper activeStep={stepIndex} linear={false} orientation="vertical" > { this.props.scenes.length > 1 ? ( this.props.scenes.map((scene, index) => ( <Step key={`${index}: ${scene.title}`}> <StepButton onTouchTap={() => this.setState({stepIndex: index})} onClick={this.props.getNewScene.bind(this, index)} > {scene.title} </StepButton> </Step> )) ) : ( null ) } </Stepper> </div> </MuiThemeProvider> ); } } /* ----- CONTAINER ----- */ import { connect } from 'react-redux'; import { fetchScene } from '../../reducers/displayState'; const mapStateToProps = store => ({ currScene: store.displayState.currScene, scenes: store.displayState.scenes }); const mapDispatchToProps = dispatch => ({ getNewScene(value, event) { event.preventDefault(); dispatch(fetchScene(value)); } }); export default connect(mapStateToProps, mapDispatchToProps)(ViewStoryStepper);
src/components/ui/TabIconRemix.js
npdat/Demo_React_Native
/** * Tabbar Icon * <TabIcon icon={'search'} selected={false} /> * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ import React from 'react'; import PropTypes from 'prop-types'; import { Icon } from 'react-native-elements'; import { AppColors } from '@theme/'; /* Component ==================================================================== */ const TabIconRemix = ({ icon, source, selected }) => ( <Icon name={icon} size={26} color={selected ? AppColors.tabbar.iconSelected : AppColors.tabbar.iconDefault} type={source} /> ); TabIconRemix.propTypes = { icon: PropTypes.string.isRequired, selected: PropTypes.bool, source: PropTypes.string }; TabIconRemix.defaultProps = { icon: 'search', selected: false, source: 'font-awesome' }; /* Export Component ==================================================================== */ export default TabIconRemix;
src/client/routes.js
adeperio/base
'use strict' import 'babel/polyfill'; import React from 'react'; import Router from 'react-router'; import App from './components/app'; import UserHome from './components/user-home'; import SignIn from './components/sign-in'; import SignUp from './components/sign-up'; import Error from './components/error'; var DefaultRoute = Router.DefaultRoute; var Link = Router.Link; var Route = Router.Route; var Redirect = Router.Redirect; var RouteHandler = Router.RouteHandler; var routes = ( <Route name="app" path="/" handler={App}> <Route name="sign-up" path="/sign-up" handler={SignUp}/> <Route name="user-home" path="/user-home" handler={UserHome}/> <Route name="error" path="/error" handler={Error}/> <DefaultRoute handler={SignIn}/> </Route> ); module.exports = routes;
client/component/prevent-leave/index.js
johngodley/redirection
/** * External dependencies */ import React from 'react'; import PropTypes from 'prop-types'; class PreventLeaveWarning extends React.Component { static propTypes = { message: PropTypes.string.isRequired, prevent: PropTypes.bool, }; static defaultProps = { prevent: true, }; componentDidMount() { if ( this.props.prevent ) { this.enable(); } } componentWillUnmount() { if ( this.props.prevent ) { this.disable(); } } componentDidUpdate( prevProps ) { if ( prevProps.prevent !== this.props.prevent ) { if ( this.props.prevent ) { this.enable(); } else { this.disable(); } } } enable() { window.addEventListener( 'beforeunload', this.onWarning ); } disable() { window.removeEventListener( 'beforeunload', this.onWarning ); } onWarning = event => { event.returnValue = this.props.message; return event.returnValue; } render() { return null; } } export default PreventLeaveWarning;
src/client/admin/hometiles/homeTileForm.js
r3dDoX/geekplanet
import Button from '@material-ui/core/Button'; import PropTypes from 'prop-types'; import React from 'react'; import { FormattedMessage } from 'react-intl'; import { connect } from 'react-redux'; import { Link, withRouter } from 'react-router-dom'; import { Field, reduxForm } from 'redux-form'; import actions from 'redux-form/es/actions'; import { createLoadProductCategories, createLoadProducts } from '../../actions'; import AutoCompleteField from '../../formHelpers/autoCompleteField'; import TextField from '../../formHelpers/textField'; import { required } from '../../formHelpers/validations'; import { HomeTilePropType, ProductCategoryPropType, ProductPropType } from '../../propTypes'; import { createSaveTile } from '../adminActions'; import PictureField from './pictureField'; const { initialize } = actions; export const formName = 'homeTiles'; function mapSubCategoriesRecursive(category) { return [ category._id, ...category.subCategories.flatMap(mapSubCategoriesRecursive), ]; } class HomeTileForm extends React.Component { constructor(props) { super(props); this.state = { initWhenLoaded: !!props.selectedTileId, selectedCategory: null, }; } componentWillMount() { if (!this.props.productCategories.length) { this.props.loadProductCategories(); } if (!this.props.products.length) { this.props.loadProducts(); } } componentWillReceiveProps(nextProps) { if (this.state.initWhenLoaded && nextProps.productCategories.length && nextProps.products.length ) { const selectedTile = this.props.tiles.find(tile => tile._id === this.props.selectedTileId); this.setState({ initWhenLoaded: false, selectedCategory: { value: selectedTile.category }, }); this.props.initForm(selectedTile); } } render() { const { selectedTileId, productCategories, products, handleSubmit, saveTile, history, } = this.props; const categoriesToFilter = (this.state.selectedCategory && productCategories.length) ? mapSubCategoriesRecursive( productCategories.find(category => category._id === this.state.selectedCategory.value), ) : []; return ( <form name={formName} onSubmit={handleSubmit((tile) => { saveTile(tile); history.push('/admin/hometiles'); })} > <Field component="input" name="_id" value={selectedTileId} style={{ display: 'none' }} readOnly /> <Field component={AutoCompleteField} name="category" label="Product Category" onSelect={category => this.setState({ selectedCategory: category })} dataSource={productCategories.map(category => ({ value: category._id, name: category.de.name, }))} /> <br /> <Field component={TextField} name="de.name" label="Title" type="text" validate={required} /> <br /> <Field component={PictureField} name="picture" label="Picture" pictures={this.state.selectedCategory ? products .filter(product => categoriesToFilter.includes(product.category)) .map(product => product.files[0]) .filter(picture => !!picture) : products.map(product => product.files[0]).filter(picture => !!picture) } /> <br /> <Button variant="contained" type="button" component={Link} to="/admin/hometiles" > <FormattedMessage id="COMMON.CANCEL" /> </Button> &nbsp;&nbsp; <Button variant="contained" type="submit" color="primary" > <FormattedMessage id="COMMON.SAVE" /> </Button> </form> ); } } HomeTileForm.propTypes = { tiles: HomeTilePropType.isRequired, selectedTileId: PropTypes.string.isRequired, productCategories: PropTypes.arrayOf(ProductCategoryPropType).isRequired, products: PropTypes.arrayOf(ProductPropType).isRequired, loadProducts: PropTypes.func.isRequired, loadProductCategories: PropTypes.func.isRequired, handleSubmit: PropTypes.func.isRequired, initForm: PropTypes.func.isRequired, saveTile: PropTypes.func.isRequired, history: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types }; export default connect( state => ({ tiles: state.home.tiles, productCategories: state.products.productCategories, products: state.products.products, }), dispatch => ({ loadProducts() { dispatch(createLoadProducts()); }, loadProductCategories() { dispatch(createLoadProductCategories()); }, initForm(tile) { dispatch(initialize(formName, tile)); }, saveTile(tile) { dispatch(createSaveTile(tile)); }, }), )(reduxForm({ form: formName, })(withRouter(HomeTileForm)));
packages/reactor-kitchensink/src/examples/PivotGrid/RowStyling/RowStyling.js
sencha/extjs-reactor
import React, { Component } from 'react'; import { PivotGrid } from '@extjs/reactor/modern'; import SaleModel from '../SaleModel'; import { generateData } from '../generateSaleData';
src/components/common/svg-icons/hardware/watch.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareWatch = (props) => ( <SvgIcon {...props}> <path d="M20 12c0-2.54-1.19-4.81-3.04-6.27L16 0H8l-.95 5.73C5.19 7.19 4 9.45 4 12s1.19 4.81 3.05 6.27L8 24h8l.96-5.73C18.81 16.81 20 14.54 20 12zM6 12c0-3.31 2.69-6 6-6s6 2.69 6 6-2.69 6-6 6-6-2.69-6-6z"/> </SvgIcon> ); HardwareWatch = pure(HardwareWatch); HardwareWatch.displayName = 'HardwareWatch'; HardwareWatch.muiName = 'SvgIcon'; export default HardwareWatch;
src/layers/SymbolInstance.js
FourwingsY/react-sketch-viewer
import React from 'react' import PropTypes from 'prop-types' import SymbolStore from '../globals/SymbolStore' import {getPositionStyle} from '../utils/layerUtils' class SymbolInstance extends React.Component { static propTypes = { layer: PropTypes.object, } static contextTypes = { renderLayer: PropTypes.func, } render() { const layer = this.props.layer const {name, symbolID} = layer const symbol = SymbolStore.getSymbol(symbolID) const {layers: childLayers, overrides} = symbol const style = { ...getPositionStyle(layer), } return ( <div className='symbol' data-sketch-name={name} style={style}> {childLayers.map(this.context.renderLayer)} </div> ) } } export default SymbolInstance
src/client/menu.js
ahmadassaf/Hacker-menu
import React from 'react' export default class Menu extends React.Component { handleOnClick (e) { e.preventDefault() this.props.onQuitClick() } render () { var statusText = 'v' + this.props.version var buttonText = 'Quit' if (this.props.status === 'update-available') { statusText += ' (v' + this.props.upgradeVersion + ' available, restart to upgrade)' buttonText = 'Restart' } return ( <div className='bar bar-standard bar-footer'> <em className='status pull-left'>{statusText}</em> <button className='btn pull-right' onClick={this.handleOnClick.bind(this)}> {buttonText} </button> </div> ) } } Menu.propTypes = { status: React.PropTypes.string.isRequired, version: React.PropTypes.string.isRequired, upgradeVersion: React.PropTypes.string.isRequired, onQuitClick: React.PropTypes.func.isRequired }
src/pages/dataTable/exemploDeDataTableComColunaOrdenavel.js
Synchro-TEC/site-apollo-11
import React from 'react'; import { DataTable, DataTableColumn } from 'syntec-apollo-11'; import _cloneDeep from 'lodash/cloneDeep'; import _sortBy from 'lodash/sortBy'; class ExemploDeDataTableComColunaOrdenavel extends React.Component { constructor(props) { super(props); this.state = { dados: [ {tarefa: 'Tarefa 1', prioridade: 'Baixa', dataDeInicio: '28/08/2002'}, {tarefa: 'Tarefa 2', prioridade: 'Crítica', dataDeInicio: '13/05/1996'}, {tarefa: 'Tarefa 3', prioridade: 'Média', dataDeInicio: '31/01/2010'}, {tarefa: 'Tarefa 4', prioridade: 'Crítica', dataDeInicio: '14/02/2017'}, {tarefa: 'Tarefa 5', prioridade: 'Alta', dataDeInicio: '14/01/2016'}, ], } } /** * Função que utiliza as informações de retorno da propriedade onSort para realizar a ordernação. */ realizarOrdenacao(informacoesDoSort) { let clone = _cloneDeep(this.state.dados); let dadosOrdenados; if(informacoesDoSort.direction === 'asc') { dadosOrdenados = _sortBy(clone, (obj) => { if(informacoesDoSort.columnKey === 'dataDeInicio') { let dataAConverter = obj[informacoesDoSort.columnKey]; //RegEx para converter data do formato dd/mm/aaaa para o formato mm/dd/aaaa let dataConvertida = dataAConverter.replace(/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{2,4})/, '$2/$1/$3'); return new Date(dataConvertida); } else { return obj[informacoesDoSort.columnKey]; } }); } else { dadosOrdenados = clone.reverse(); } this.setState({dados: dadosOrdenados}); } render() { return ( <div> <DataTable data={this.state.dados} onSort={(informacoesDoSort) => this.realizarOrdenacao(informacoesDoSort)}> <DataTableColumn dataKey='tarefa' sortable>Tarefa</DataTableColumn> <DataTableColumn dataKey='prioridade' sortable>Prioridade</DataTableColumn> <DataTableColumn dataKey='dataDeInicio' sortable>Data de inicio</DataTableColumn> </DataTable> </div> ); } } ExemploDeDataTableComColunaOrdenavel.displayName = 'ExemploDeDataTableComColunaOrdenavel'; export default DataTableWithSortExample;
src/views/syllabus/VerbPhrase.js
bostontrader/senmaker
// @flow import React from 'react' import LessonNavigator from './LessonNavigator' import VPPanel from '../vp/VPPanel' import {VPPanelLevel} from '../../data/vp/VPConstants' function VerbPhrase(props:Object):Object { const style = { border: '1px solid black', margin: '5px' } const q:Object = props.quiz const s:Object = props.strings.get('strings').vp const sm:Object = props.strings.get('strings').misc const quizInsertVPMark:Object | string = q.getIn(['vp','insertVP']) ? <img id='quizInsertVPMark' className='checkmark' src='/img/Checked.png' alt='checkmark' width='36' height='36'/> : '' const quizUpdateVPVerbMark:Object | string = q.getIn(['vp','changeVPVerbd']) ? <img id='quizUpdateVPVerbMark' className='checkmark' src='/img/Checked.png' alt='checkmark' width='36' height='36'/> : '' const quizUpdateVPDefinitenessMark:Object | string = q.getIn(['vp','changeVerbTime']) ? <img id='quizUpdateVPDefinitenessMark' className='checkmark' src='/img/Checked.png' alt='checkmark' width='36' height='36'/> : '' const quizDeleteVPMark:Object | string = q.getIn(['vp','deleteVP']) ? <img id='quizDeleteVPMark' className='checkmark' src='/img/Checked.png' alt='checkmark' width='36' height='36'/> : '' const quizBox:Object | null = // q.getIn(['vp','passed']) ? null : <div id='quiz' style={style}> <h3>{sm.quiz}</h3> <table> <tbody> <tr> <td><p>{s.quiz1}</p></td> <td>{quizInsertVPMark}</td> </tr> <tr> <td><p>{s.quiz2}</p></td> <td>{quizUpdateVPVerbMark}</td> </tr> <tr> <td><p>{s.quiz3}</p></td> <td>{quizUpdateVPDefinitenessMark}</td> </tr> <tr> <td><p>{s.quiz4}</p></td> <td>{quizDeleteVPMark}</td> </tr> </tbody> </table> </div> return ( <div> <LessonNavigator {...props} /> <div id='help' style={style}> <p>{s.help10}</p> <p>{s.help11}</p> <p>{s.help12}</p> </div> <VPPanel vpPanelLevel={VPPanelLevel.L1} {...props} /> {quizBox} </div> ) } export default VerbPhrase
app/javascript/mastodon/features/notifications/components/setting_toggle.js
RobertRence/Mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Toggle from 'react-toggle'; export default class SettingToggle extends React.PureComponent { static propTypes = { prefix: PropTypes.string, settings: ImmutablePropTypes.map.isRequired, settingKey: PropTypes.array.isRequired, label: PropTypes.node.isRequired, meta: PropTypes.node, onChange: PropTypes.func.isRequired, } onChange = ({ target }) => { this.props.onChange(this.props.settingKey, target.checked); } render () { const { prefix, settings, settingKey, label, meta } = this.props; const id = ['setting-toggle', prefix, ...settingKey].filter(Boolean).join('-'); return ( <div className='setting-toggle'> <Toggle id={id} checked={settings.getIn(settingKey)} onChange={this.onChange} onKeyDown={this.onKeyDown} /> <label htmlFor={id} className='setting-toggle__label'>{label}</label> {meta && <span className='setting-meta__label'>{meta}</span>} </div> ); } }
src/infopages/FAQs.js
VasilyShelkov/scikic-app
import React, { Component } from 'react'; const FAQs = () => ( <div> <h1>FAQs</h1> </div> ); export default FAQs;
app/javascript/mastodon/features/compose/components/autosuggest_account.js
palon7/mastodon
import React from 'react'; import Avatar from '../../../components/avatar'; import DisplayName from '../../../components/display_name'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; export default class AutosuggestAccount extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, }; render () { const { account } = this.props; return ( <div className='autosuggest-account'> <div className='autosuggest-account-icon'><Avatar src={account.get('avatar')} staticSrc={account.get('avatar_static')} size={18} /></div> <DisplayName account={account} /> </div> ); } }
lib/components/TodoForm/TodoFormContainer.js
dpkshrma/beaver
'use babel'; import _ from 'lodash'; import React from 'react'; import TodoForm from './TodoForm'; import { TodoService } from '../../services'; const TODO_TEMPLATE = { project: {}, title: 'something', description: 'somehow', duration: 1, durationUnit: 'minutes', status: 'inactive' }; class TodoFormContainer extends React.Component { constructor(props) { super(props); this.state = { todo: props.todo || TODO_TEMPLATE, projects: [], mode: props.todo ? 'edit' : 'new' }; } componentWillMount() { this.updateProjectList(atom.project.getPaths()); atom.project.onDidChangePaths(this.updateProjectList); } componentDidMount() { // select the first project this.selectProject(_.head(this.state.projects)); } componentWillReceiveProps(nextProps) { if (nextProps.todo) { this.setState({ mode: 'edit', todo: nextProps.todo }); } } selectProject = project => { if (project) { this.setState({ todo: Object.assign({}, this.state.todo, { project }) }); } }; updateProjectList = paths => { const projects = paths.map(path => ({ name: _.last(path.split('/')), path })); const { todo: { project: selectedProject } } = this.state; // no projects present initially or selectet project is removed if ( this.state.projects.length == 0 || (selectedProject.length && !_.includes(paths, selectedProject)) ) { // select the first project this.selectProject(_.head(projects)); } this.setState({ projects }); }; onInputChange = ({ target }) => { let value; if (target.name === 'project') { value = this.getTargetValue(target, { select: this.state.projects }); } else if (target.name === 'status') { const mapping = [ { value: 'active', state: true }, { value: 'inactive', state: false } ]; value = this.getTargetValue(target, { checkbox: mapping }); } else { value = this.getTargetValue(target); } const todo = Object.assign({}, this.state.todo, { [target.name]: value }); this.setState({ todo }); }; getTargetValue = (target, mappings = {}) => { let value = target.value; if (target.type === 'checkbox') { if (mappings.checkbox) { value = _.find(mappings.checkbox, { state: target.checked }).value; } else { value = target.checked; } } else if (target.type === 'select-one' && mappings.select) { const key = target.getAttribute('data-key'); if (key) { value = _.find(mappings.select, { [key]: value }); } } else if (target.type === 'number') { value = parseInt(value); } return value; }; onTodoSubmit = e => { e.preventDefault(); const { todo } = this.state; if (this.state.mode === 'edit') { TodoService.updateTodo(todo) .then(newTodo => { if (newTodo.status === 'active') { TodoService.setTodoStatus(newTodo._id, 'active').catch(e => { throw err; }); } }) .catch(e => { throw err; }); } else { TodoService.addTodo(todo) .then(newTodo => { if (newTodo.status === 'active') { TodoService.setTodoStatus(newTodo._id, 'active').catch(e => { throw err; }); } }) .catch(e => { throw err; }); } }; render() { return ( <TodoForm {...this.props} todo={this.state.todo} mode={this.state.mode} projects={this.state.projects} onInputChange={this.onInputChange} onSubmit={this.onTodoSubmit} /> ); } } export default TodoFormContainer;
website-prototyping-tools/playground.js
SBUtltmedia/relay
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import 'babel/polyfill'; import React from 'react'; window.React = React; import ReactDOM from 'react/lib/ReactDOM'; import RelayPlayground from './RelayPlayground'; import filterObject from 'fbjs/lib/filterObject'; import queryString from 'querystring'; const DEFAULT_CACHE_KEY = 'default'; const IS_TRUSTED = ( ( // Running in an iframe on the Relay website window.self !== window.top && /^https?:\/\/facebook.github.io\//.test(document.referrer) ) || // Running locally /^(127\.0\.0\.1|localhost)/.test(document.location.host) ); var sourceWasInjected = false; function setHash(object) { // Caution: setting it to nothing causes the page to jump to the top, hence /. window.location.hash = queryString.stringify(object) || '/'; } // Don't trust location.hash not to have been unencoded by the browser var hash = window.location.href.split('#')[1]; var queryParams = queryString.parse(hash); var { cacheKey, noCache, } = queryParams; noCache = (noCache !== undefined) && (noCache !== 'false'); if (noCache) { cacheKey = undefined; } else if (!cacheKey) { cacheKey = DEFAULT_CACHE_KEY; } var appSourceCacheKey = `rp-${cacheKey}-source`; var schemaSourceCacheKey = `rp-${cacheKey}-schema`; var initialAppSource; var initialSchemaSource; var storedAppSource = localStorage.getItem(appSourceCacheKey); var storedSchemaSource = localStorage.getItem(schemaSourceCacheKey); if (noCache) { // Use case #1 // We use the noCache param to force a playground to have certain contents. // eg. static example apps initialAppSource = queryParams.source || ''; initialSchemaSource = queryParams.schema || ''; sourceWasInjected = true; queryParams = {}; } else if (cacheKey === DEFAULT_CACHE_KEY) { // Use case #2 // The user loaded the playground without a custom cache key. // Allow code injection via the URL // OR load code from localStorage // OR prime the playground with some default 'hello world' code if (queryParams.source != null) { initialAppSource = queryParams.source; sourceWasInjected = queryParams.source !== storedAppSource; } else if (storedAppSource != null) { initialAppSource = storedAppSource; } else { initialAppSource = require('!raw!./HelloApp'); } if (queryParams.schema != null) { initialSchemaSource = queryParams.schema; sourceWasInjected = queryParams.schema !== storedSchemaSource; } else if (storedSchemaSource != null) { initialSchemaSource = storedSchemaSource; } else { initialSchemaSource = require('!raw!./HelloSchema'); } queryParams = filterObject({ source: queryParams.source, schema: queryParams.schema, }, v => v !== undefined); } else if (cacheKey) { // Use case #3 // Custom cache keys are useful in cases where you want to embed a playground // that features both custom boilerplate code AND saves the developer's // progress, without overwriting the default code cache. eg. a tutorial. if (storedAppSource != null) { initialAppSource = storedAppSource; } else { initialAppSource = queryParams[`source_${cacheKey}`]; if (initialAppSource != null) { sourceWasInjected = true; } } if (storedSchemaSource != null) { initialSchemaSource = storedSchemaSource; } else { initialSchemaSource = queryParams[`schema_${cacheKey}`]; if (initialSchemaSource != null) { sourceWasInjected = true; } } queryParams = {}; } setHash(queryParams); var mountPoint = document.createElement('div'); document.body.appendChild(mountPoint); ReactDOM.render( <RelayPlayground autoExecute={IS_TRUSTED || !sourceWasInjected} initialAppSource={initialAppSource} initialSchemaSource={initialSchemaSource} onSchemaSourceChange={function(source) { localStorage.setItem(schemaSourceCacheKey, source); if (cacheKey === DEFAULT_CACHE_KEY) { queryParams.schema = source; setHash(queryParams); } }} onAppSourceChange={function(source) { localStorage.setItem(appSourceCacheKey, source); if (cacheKey === DEFAULT_CACHE_KEY) { queryParams.source = source; setHash(queryParams); } }} />, mountPoint );
imports/ui/containers/sidenav.js
jiyuu-jin/openlens
import React from 'react'; import {composeWithTracker} from 'react-komposer'; import SideNav from '../components/sidenav.js'; import {Lenses} from '/lib/collections'; const composer = (props, onData) => { if (Meteor.subscribe('lenses').ready()) { const lenses = Lenses.find().fetch(); onData(null, {lenses}); } }; export default composeWithTracker(composer)(SideNav);
views/invocation.js
gastrodia/black-screen
import React from 'react'; import Prompt from './prompt'; export default React.createClass({ componentWillMount() { this.props.invocation .on('data', _ => this.setState({canBeDecorated: this.props.invocation.canBeDecorated()})) .on('status', status => this.setState({status: status})); }, componentDidUpdate: scrollToBottom, getInitialState() { return { status: this.props.invocation.status, decorate: false, canBeDecorated: false }; }, render() { if (this.state.canBeDecorated && this.state.decorate) { var buffer = this.props.invocation.decorate(); } else { buffer = this.props.invocation.getBuffer().render(); } const classNames = 'invocation ' + this.state.status; return ( <div className={classNames}> <Prompt prompt={this.props.invocation.getPrompt()} status={this.state.status} invocation={this.props.invocation} invocationView={this}/> {buffer} </div> ); } });
src/workshops/presentation/attendee/AttendeeBox.js
GrayTurtle/rocket-workshop
import React from 'react'; import PropTypes from 'prop-types'; import './assets/css/AttendeeBox.css'; import rocket from './assets/images/rocket.png'; const AttendeeBox = ({ status, step, username, num, onClick, masterStep, masterStatus }) => { let statusBackground = {}; if (masterStep === step && status === 'WORKING') { statusBackground.background = "rgb(255, 255, 82)"; } else if (masterStep === step && status === 'COMPLETE') { statusBackground.background = "rgb(85, 185, 85)"; } else if (masterStep > step) { statusBackground.background = "rgb(255, 94, 94)"; } else if (masterStep < step) { statusBackground.background = "rgb(191, 81, 191)"; } return ( <div className="attendeeBox" style={statusBackground} onClick={() => onClick(num)}> <div className="top-row"> <div className="username"> {username} </div> <div className="num"> {num} </div> </div> <div className="rocket-wrapper"> {step > masterStep && <img src={rocket} className="rocket-status" alt="rocket-user" />} </div> <div className="attendee-step"> {step + 1} </div> </div> ); } AttendeeBox.propTypes = { }; export default AttendeeBox;
es/components/style/form-number-input.js
dearkaran/react-planner
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import React from 'react'; import FormTextInput from './form-text-input'; export default function FormNumberInput(_ref) { var onChange = _ref.onChange, rest = _objectWithoutProperties(_ref, ['onChange']); var onChangeCustom = function onChangeCustom(event) { var value = event.target.value; rest.min = rest.min ? parseFloat(rest.min) : -Infinity; rest.max = rest.max ? parseFloat(rest.max) : Infinity; if (parseFloat(value) <= (parseFloat(rest.min) || -Infinity) || parseFloat(value) >= (parseFloat(rest.max) || Infinity)) { event.target.value = rest.min; onChange(event); event.target.select(); } else { if (!isNaN(parseFloat(value)) && isFinite(value)) { onChange(event); } else { if (value === '-') { if (rest.min == 0) { event.target.value = '0'; event.target.select(); } onChange(event); } else if (value === '0' || value === '') { event.target.value = rest.min > 0 ? rest.min : '0'; onChange(event); event.target.select(); } } } }; var textProps = _extends({}, rest); delete textProps.state; return React.createElement(FormTextInput, _extends({ onChange: onChangeCustom, autoComplete: 'off' }, textProps)); }
src/index.js
richchurcher/feedbacker
import React from 'react' import {render} from 'react-dom' import {Router, Route, hashHistory} from 'react-router' import App from './components/App' import Students from './components/Students' render(( <Router history={hashHistory}> <Route path='/' component={App}> <Route path='/students' component={Students}/> <Route path='/students/:name' component={Students}/> </Route> </Router> ), document.getElementById('app'))
blueocean-material-icons/src/js/components/svg-icons/image/crop-din.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageCropDin = (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-2zm0 16H5V5h14v14z"/> </SvgIcon> ); ImageCropDin.displayName = 'ImageCropDin'; ImageCropDin.muiName = 'SvgIcon'; export default ImageCropDin;
src/components/home.js
camboio/ibis
import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import Timeline from './timeline'; import * as actions from '../actions'; class Home extends React.Component { componentWillMount(){ if(this.props.authenticated){ this.props.updateTitle('Timeline'); } } componentWillUnmount(){ this.props.clearTitle(); } render(){ if(!this.props.authenticated){ return ( <div className="splash"> <Link to="/signin"> <div className="btn btn-primary"> Sign in! </div> </Link> <img src="./style/ibis.jpg" /> </div> ); } return ( <div className="home"> <Timeline /> </div> ); } } function mapStateToProps(state){ return { authenticated: state.auth.authenticated } } export default connect(mapStateToProps, actions)(Home);
src/svg-icons/device/signal-cellular-null.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellularNull = (props) => ( <SvgIcon {...props}> <path d="M20 6.83V20H6.83L20 6.83M22 2L2 22h20V2z"/> </SvgIcon> ); DeviceSignalCellularNull = pure(DeviceSignalCellularNull); DeviceSignalCellularNull.displayName = 'DeviceSignalCellularNull'; DeviceSignalCellularNull.muiName = 'SvgIcon'; export default DeviceSignalCellularNull;
src/svg-icons/action/shop-two.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionShopTwo = (props) => ( <SvgIcon {...props}> <path d="M3 9H1v11c0 1.11.89 2 2 2h14c1.11 0 2-.89 2-2H3V9zm15-4V3c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H5v11c0 1.11.89 2 2 2h14c1.11 0 2-.89 2-2V5h-5zm-6-2h4v2h-4V3zm0 12V8l5.5 3-5.5 4z"/> </SvgIcon> ); ActionShopTwo = pure(ActionShopTwo); ActionShopTwo.displayName = 'ActionShopTwo'; ActionShopTwo.muiName = 'SvgIcon'; export default ActionShopTwo;
src/main/jsx/client/BuildHistoryPageActions.js
DotCi/DotCi
import ReactDOM from 'react-dom'; import React from 'react'; import BuildHistoryPage from './../pages/BuildHistoryPage.jsx'; import {job} from './../api/Api.jsx'; import {removeFilter,addFilter} from './../api/Api.jsx'; import Drawer from './../Drawer.jsx'; import {Job as AutoRefreshComponent} from './../components/lib/AutoRefreshComponent.js'; function dataChange(buildHistory){ const buildHistoryPage = <BuildHistoryPage buildHistory={buildHistory}/> const refreshFunction =()=>buildHistory.actions.QueryChange(buildHistory.query); ReactDOM.render(<AutoRefreshComponent component={buildHistoryPage} refreshFunction={refreshFunction} refreshInterval={10000} />, document.getElementById('content')); ReactDOM.render(<Drawer menu="job"/>, document.getElementById('nav')); } function queryChange(buildHistory,oldQuery){ const {actions,query} = buildHistory; buildHistory.dirty = true; actions.DataChange({...buildHistory}); job("buildHistoryTabs,builds[*,commit[*],cause[*],parameters[*]]",query.filter ,query.limit).then(data => { actions.DataChange({...data, filters: data.buildHistoryTabs,dirty: false}); }); } export default function(buildHistory){ const actions = buildHistory.actions; actions.DataChange.onAction = dataChange; actions.QueryChange.onAction = queryChange; actions.RemoveFilter.onAction = removeFilter; actions.AddFilter.onAction = addFilter; }
app/javascript/mastodon/features/ui/components/modal_loading.js
Arukas/mastodon
import React from 'react'; import LoadingIndicator from '../../../components/loading_indicator'; // Keep the markup in sync with <BundleModalError /> // (make sure they have the same dimensions) const ModalLoading = () => ( <div className='modal-root__modal error-modal'> <div className='error-modal__body'> <LoadingIndicator /> </div> <div className='error-modal__footer'> <div> <button className='error-modal__nav onboarding-modal__skip' /> </div> </div> </div> ); export default ModalLoading;
src/svg-icons/maps/hotel.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsHotel = (props) => ( <SvgIcon {...props}> <path d="M7 13c1.66 0 3-1.34 3-3S8.66 7 7 7s-3 1.34-3 3 1.34 3 3 3zm12-6h-8v7H3V5H1v15h2v-3h18v3h2v-9c0-2.21-1.79-4-4-4z"/> </SvgIcon> ); MapsHotel = pure(MapsHotel); MapsHotel.displayName = 'MapsHotel'; MapsHotel.muiName = 'SvgIcon'; export default MapsHotel;
src/Parser/Warrior/Arms/CONFIG.js
enragednuke/WoWAnalyzer
import React from 'react'; import { TheBadBossy } from 'MAINTAINERS'; import SPECS from 'common/SPECS'; import SPEC_ANALYSIS_COMPLETENESS from 'common/SPEC_ANALYSIS_COMPLETENESS'; import CombatLogParser from './CombatLogParser'; import CHANGELOG from './CHANGELOG'; export default { spec: SPECS.ARMS_WARRIOR, maintainers: [TheBadBossy], description: ( <div> Hey I've been hard at work making this analyzer for you. I hope the suggestions give you useful pointers to improve your performance. Remember: focus on improving only one or two important things at a time. Improving isn't easy and will need your full focus until it becomes second nature to you.<br /><br /> </div> ), // good = it matches most common manual reviews in class discords, great = it support all important class features completeness: SPEC_ANALYSIS_COMPLETENESS.NEEDS_MORE_WORK, specDiscussionUrl: 'https://github.com/WoWAnalyzer/WoWAnalyzer/issues/579', // Shouldn't have to change these: changelog: CHANGELOG, parser: CombatLogParser, // used for generating a GitHub link directly to your spec path: __dirname, };
src/workplace/ResizeContainer.js
rsamec/react-designer-core
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ItemTypes from '../util/ItemTypes.js'; import { DropTarget } from 'react-dnd'; import _ from 'lodash'; import ResizableHandle from './ResizableHandle.js'; const target = { drop(props, monitor, component) { if (monitor.didDrop()) { // If you want, you can check whether some nested // target already handled drop return; } var item = monitor.getItem().item; var delta = monitor.getDifferenceFromInitialOffset(); if (!!!delta) return; if (monitor.getItemType() === ItemTypes.RESIZABLE_HANDLE) { var left = Math.round(delta.x); var top = Math.round(delta.y); component.resizeContainer(item.parent, left, top); }; } }; const HANDLE_OFFSET = 30; class ResizeContainer extends React.Component { resizeContainer(container, deltaWidth, deltaHeight) { if (container === undefined) return; //TODO: use merge instead of clone var style = _.cloneDeep(container.style); style.width += deltaWidth; style.height += deltaHeight; var updated = container.set({'style': style}); this.props.currentChanged(updated); } render() { const { canDrop, isOver, connectDropTarget} = this.props; var style = this.props.node && this.props.node.style || {}; //resize handle position var useResize = !!style.height && !!style.width; var resizeHandlePosition = {top: (style.height - HANDLE_OFFSET), left: (style.width - HANDLE_OFFSET)}; return connectDropTarget( <div> {this.props.children} {useResize? <ResizableHandle styles={style} left={resizeHandlePosition.left} top={resizeHandlePosition.top} parent={this.props.node} />:null } </div> ); } }; var collect = (connect, monitor) => ({ connectDropTarget: connect.dropTarget(), isOver: monitor.isOver(), canDrop: monitor.canDrop() }); // Export the wrapped component: export default DropTarget(ItemTypes.RESIZABLE_HANDLE, target, collect)(ResizeContainer);
components/wrapper/index.js
blockstack/blockstack-site
import React from 'react' import { Flex } from 'blockstack-ui' const Wrapper = ({ ...rest }) => ( <Flex px={5} width="100%" maxWidth={['1064px']} mx="auto" {...rest} /> ) export { Wrapper }
src/Thumbnail.js
blue68/react-bootstrap
import React from 'react'; import classSet from 'classnames'; import BootstrapMixin from './BootstrapMixin'; import SafeAnchor from './SafeAnchor'; const Thumbnail = React.createClass({ mixins: [BootstrapMixin], propTypes: { alt: React.PropTypes.string, href: React.PropTypes.string, src: React.PropTypes.string }, getDefaultProps() { return { bsClass: 'thumbnail' }; }, render() { let classes = this.getBsClassSet(); if (this.props.href) { return ( <SafeAnchor {...this.props} href={this.props.href} className={classSet(this.props.className, classes)}> <img src={this.props.src} alt={this.props.alt} /> </SafeAnchor> ); } if (this.props.children) { return ( <div {...this.props} className={classSet(this.props.className, classes)}> <img src={this.props.src} alt={this.props.alt} /> <div className="caption"> {this.props.children} </div> </div> ); } return ( <div {...this.props} className={classSet(this.props.className, classes)}> <img src={this.props.src} alt={this.props.alt} /> </div> ); } }); export default Thumbnail;
src/components/detailsComponents/CompanyInfo.js
markgreenburg/acquisitiontracker
// @flow import React from 'react'; import PropTypes from 'prop-types'; import Nav from './Nav'; import CompanyName from './CompanyName'; import CompanyBody from './CompanyBody'; const CompanyInfo = props => ( <div className="row company-info-row"> <div className="col-xs-12 company-info-content"> <div className="row company-header-row"> <Nav changeTab={props.changeTab} /> <CompanyName deal={props.deal} handleChange={props.handleChange} handleSubmit={props.handleSubmit} /> </div> <CompanyBody deal={props.deal} contacts={props.contacts} handleChange={props.handleChange} handleHqChange={props.handleHqChange} handleSubmit={props.handleSubmit} addContact={props.addContact} editContact={props.editContact} deleteContact={props.deleteContact} /> </div> </div> ); CompanyInfo.propTypes = { deal: PropTypes.objectOf(PropTypes.any).isRequired, changeTab: PropTypes.func.isRequired, handleHqChange: PropTypes.func.isRequired, handleChange: PropTypes.func.isRequired, handleSubmit: PropTypes.func.isRequired, addContact: PropTypes.func.isRequired, editContact: PropTypes.func.isRequired, deleteContact: PropTypes.func.isRequired, contacts: PropTypes.arrayOf(PropTypes.object).isRequired, }; export default CompanyInfo;
actor-apps/app-web/src/app/components/sidebar/HeaderSection.react.js
fengchenlianlian/actor-platform
import React from 'react'; import mixpanel from 'utils/Mixpanel'; import MyProfileActions from 'actions/MyProfileActions'; import LoginActionCreators from 'actions/LoginActionCreators'; import AvatarItem from 'components/common/AvatarItem.react'; import MyProfileModal from 'components/modals/MyProfile.react'; import ActorClient from 'utils/ActorClient'; import classNames from 'classnames'; var getStateFromStores = () => { return {dialogInfo: null}; }; class HeaderSection extends React.Component { componentWillMount() { ActorClient.bindUser(ActorClient.getUid(), this.setUser); } constructor() { super(); this.setUser = this.setUser.bind(this); this.toggleHeaderMenu = this.toggleHeaderMenu.bind(this); this.openMyProfile = this.openMyProfile.bind(this); this.setLogout = this.setLogout.bind(this); this.state = getStateFromStores(); } setUser(user) { this.setState({user: user}); } toggleHeaderMenu() { mixpanel.track('Open sidebar menu'); this.setState({isOpened: !this.state.isOpened}); } setLogout() { LoginActionCreators.setLoggedOut(); } render() { var user = this.state.user; if (user) { var headerClass = classNames('sidebar__header', 'sidebar__header--clickable', { 'sidebar__header--opened': this.state.isOpened }); return ( <header className={headerClass}> <div className="sidebar__header__user row" onClick={this.toggleHeaderMenu}> <AvatarItem image={user.avatar} placeholder={user.placeholder} size="small" title={user.name} /> <span className="sidebar__header__user__name col-xs">{user.name}</span> <span className="sidebar__header__user__expand"> <i className="material-icons">keyboard_arrow_down</i> </span> </div> <ul className="sidebar__header__menu"> <li className="sidebar__header__menu__item" onClick={this.openMyProfile}> <i className="material-icons">person</i> <span>Profile</span> </li> {/* <li className="sidebar__header__menu__item" onClick={this.openCreateGroup}> <i className="material-icons">group_add</i> <span>Create group</span> </li> */} <li className="sidebar__header__menu__item hide"> <i className="material-icons">cached</i> <span>Integrations</span> </li> <li className="sidebar__header__menu__item hide"> <i className="material-icons">settings</i> <span>Settings</span> </li> <li className="sidebar__header__menu__item hide"> <i className="material-icons">help</i> <span>Help</span> </li> <li className="sidebar__header__menu__item" onClick={this.setLogout}> <i className="material-icons">power_settings_new</i> <span>Log out</span> </li> </ul> <MyProfileModal/> </header> ); } else { return null; } } openMyProfile() { MyProfileActions.modalOpen(); mixpanel.track('My profile open'); this.setState({isOpened: false}); } } export default HeaderSection;
src/components/listRenderers/Item.js
jung-digital/ringa-example-react
import React from 'react'; import {dispatch} from 'ringa'; import {watch, find } from 'react-ringa'; import AppController from '../../global/AppController'; import AppModel from '../../global/AppModel'; import './Item.scss'; export default class Item extends React.Component { //----------------------------------- // Constructor //----------------------------------- constructor(props) { super(props); /** * The watch() function watches a Model that is already available to us. depend() does a lookup for a model and * a property. * * Both of them by default update the React component when they detect a change. */ watch(this, props.item); this.clickHandler = this.clickHandler.bind(this); this.deleteClickHandler = this.deleteClickHandler.bind(this); this.inputKeyUpHandler = this.inputKeyUpHandler.bind(this); this.mouseBlock = this.mouseBlock.bind(this); this.mouseUpHandler = this.mouseUpHandler.bind(this); } //----------------------------------- // Methods //----------------------------------- tryFocusInput() { if (this.refs.input && this.refs.input !== document.activeElement) { this.refs.input.focus(); } } componentDidUpdate() { this.tryFocusInput(); } componentDidMount() { this.appModel = find(this, AppModel); window.addEventListener('mouseup', this.mouseUpHandler); this.tryFocusInput(); } componentWillUnmount() { window.removeEventListener('mouseup', this.mouseUpHandler); } render() { const {title, editing} = this.props.item; if (editing) { return <div className="item" ref="rootNode" onMouseUp={this.mouseBlock}> <input ref="input" defaultValue={title} onKeyUp={this.inputKeyUpHandler} placeholder="Item Description"/> <div className="item--delete" onClick={this.deleteClickHandler}><i className="fa fa-times-circle" aria-hidden="true"></i></div> </div>; } return <div className="item" ref="rootNode" onClick={this.clickHandler}> <div className="item--title">{title}</div> <div className="item--delete" onClick={this.deleteClickHandler}><i className="fa fa-times-circle" aria-hidden="true"></i></div> </div>; } save(autoAddNewItem = true) { this.props.item.title = this.refs.input.value; this.props.item.editing = false; this.props.item.saving = false; dispatch(AppController.SAVE_ITEM, { item: this.props.item, autoAddNewItem }, this.refs.rootNode); } //----------------------------------- // Events //----------------------------------- clickHandler() { this.appModel.startEditItem(this.props.item); } inputKeyUpHandler(event) { if (event.key === 'Enter') { this.save(); } } deleteClickHandler(event) { event.stopPropagation(); if (this.props.item.editing) { this.appModel.endEditItem(); } dispatch(AppController.REMOVE_ITEM, { item: this.props.item }, this.refs.rootNode); } mouseBlock(event) { event.stopPropagation(); } mouseUpHandler() { if (this.state.item && this.state.item.editing) { this.save(); } } }
src/components/Result.js
rhernandez-applaudostudios/tic-tac-toe
import React from 'react'; function Result({result}) { const stringResult = result === 'X' ? 'The winner is player X!!' : result === '0' ? 'The winner is player O!!' : result === undefined ? '' : result === 'DRAW' ? 'Is a tie :(' : 'Game in progress.. Good luck !'; return ( <div className="results"> {stringResult} </div> ); } export default Result;
client/src/components/PublicationStatus/PublicationStatus.js
wagtail/wagtail
import PropTypes from 'prop-types'; import React from 'react'; /** * Displays the publication status of a page in a pill. */ const PublicationStatus = ({ status }) => ( <span className={`o-pill c-status${status.live ? ' c-status--live' : ''}`}> {status.status} </span> ); PublicationStatus.propTypes = { status: PropTypes.shape({ live: PropTypes.bool.isRequired, status: PropTypes.string.isRequired, }).isRequired, }; export default PublicationStatus;
src/svg-icons/communication/phonelink-lock.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationPhonelinkLock = (props) => ( <SvgIcon {...props}> <path d="M19 1H9c-1.1 0-2 .9-2 2v3h2V4h10v16H9v-2H7v3c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm-8.2 10V9.5C10.8 8.1 9.4 7 8 7S5.2 8.1 5.2 9.5V11c-.6 0-1.2.6-1.2 1.2v3.5c0 .7.6 1.3 1.2 1.3h5.5c.7 0 1.3-.6 1.3-1.2v-3.5c0-.7-.6-1.3-1.2-1.3zm-1.3 0h-3V9.5c0-.8.7-1.3 1.5-1.3s1.5.5 1.5 1.3V11z"/> </SvgIcon> ); CommunicationPhonelinkLock = pure(CommunicationPhonelinkLock); CommunicationPhonelinkLock.displayName = 'CommunicationPhonelinkLock'; CommunicationPhonelinkLock.muiName = 'SvgIcon'; export default CommunicationPhonelinkLock;
src/index.js
testxin/QuestionCollection
/** * Created by xinsw on 2016/1/21. * * 入口js * */ import React from 'react' import ReactDom,{ render } from 'react-dom' import { Provider } from 'react-redux' import { ReduxRouter } from 'redux-router'; import DevTools from './containers/DevTools' import configureStore from './store/configureStore' import routes from './routes'; const store = configureStore(); ReactDom.render( <Provider store={store} key="provider"> <div> <ReduxRouter routes={routes}/> </div> </Provider> , document.getElementById('app') );
src/server.js
nagucc/jkef-web-react
import 'babel-polyfill'; import path from 'path'; import express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import Router from './routes'; import Html from './components/Html'; import assets from './assets'; import { port, title, redisConfig } from './config'; import cookieParser from 'cookie-parser'; import session from 'express-session'; import bodyParser from 'body-parser'; import morgan from 'morgan'; var RedisStore = require('connect-redis')(session); const server = global.server = express(); // // Register Node.js middleware // ----------------------------------------------------------------------------- server.use(express.static(path.join(__dirname, 'public'))); server.use(cookieParser('jkef.nagu.cc cookie key')); server.use(session({ store: new RedisStore({ host: redisConfig.host, port: redisConfig.port }), secret: 'jkef.nagu.cc session key', resave: true, saveUninitialized: false, cookie: { path : '/', httpOnly: false, maxAge : 24*60*60*1000 }, })); server.use(bodyParser.json()); server.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })); server.use(morgan('dev')); server.use('/public',express.static('build/public')); // // Register API middleware // ----------------------------------------------------------------------------- // 连接mongoose require('./api/mongoose'); server.use('/api/auth/wx-ent', require('./api/auth/wx-ent')); server.use('/api/jkef/acceptors', require('./api/jkef/acceptors')); server.use('/api/jkef/stat', require('./api/jkef/stat')); server.use('/api/wx-ent/signup', require('./api/wx-ent/signup')); server.use('/api/gdzc', require('./api/gdzc/rest')); // 开始执行后台操作 require('./api/gdzc/worker'); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- server.get('*', async (req, res, next) => { try { let statusCode = 200; const data = { title: title, description: '', css: '', body: '', entry: assets.main.js }; const css = []; const context = { insertCss: styles => css.push(styles._getCss()), onSetTitle: value => data.title = value, onSetMeta: (key, value) => data[key] = value, onPageNotFound: () => statusCode = 404, }; await Router.dispatch({ path: req.path, query: req.query, context }, (state, component) => { data.body = ReactDOM.renderToString(component); data.css = css.join(''); }); const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); res.status(statusCode).send('<!doctype html>\n' + html); } catch (err) { next(err); } }); // // Launch the server // ----------------------------------------------------------------------------- server.listen(port, () => { /* eslint-disable no-console */ console.log(`The server is running at http://localhost:${port}/`); });
src/containers/OldHome/Home.js
simonghales/mapping
import React, { Component } from 'react'; import { Link } from 'react-router'; import { CounterButton, GithubButton } from 'components'; import config from '../../config'; import Helmet from 'react-helmet'; export default class Home extends Component { render() { const styles = require('./Home.scss'); // require the logo image both from client and server const logoImage = require('./logo.png'); return ( <div className={styles.home}> <Helmet title="Home"/> <div className={styles.masthead}> <div className="container"> <div className={styles.logo}> <p> <img src={logoImage}/> </p> </div> <h1>{config.app.title}</h1> <h2>{config.app.description}</h2> <p> <a className={styles.github} href="https://github.com/erikras/react-redux-universal-hot-example" target="_blank"> <i className="fa fa-github"/> View on Github </a> </p> <GithubButton user="erikras" repo="react-redux-universal-hot-example" type="star" width={160} height={30} count large/> <GithubButton user="erikras" repo="react-redux-universal-hot-example" type="fork" width={160} height={30} count large/> <p className={styles.humility}> Created and maintained by <a href="https://twitter.com/erikras" target="_blank">@erikras</a>. </p> </div> </div> <div className="container"> <div className={styles.counterContainer}> <CounterButton multireducerKey="counter1"/> <CounterButton multireducerKey="counter2"/> <CounterButton multireducerKey="counter3"/> </div> <p>This starter boilerplate app uses the following technologies:</p> <ul> <li> <del>Isomorphic</del> {' '} <a href="https://medium.com/@mjackson/universal-javascript-4761051b7ae9">Universal</a> rendering </li> <li>Both client and server make calls to load data from separate API server</li> <li><a href="https://github.com/facebook/react" target="_blank">React</a></li> <li><a href="https://github.com/rackt/react-router" target="_blank">React Router</a></li> <li><a href="http://expressjs.com" target="_blank">Express</a></li> <li><a href="http://babeljs.io" target="_blank">Babel</a> for ES6 and ES7 magic</li> <li><a href="http://webpack.github.io" target="_blank">Webpack</a> for bundling</li> <li><a href="http://webpack.github.io/docs/webpack-dev-middleware.html" target="_blank">Webpack Dev Middleware</a> </li> <li><a href="https://github.com/glenjamin/webpack-hot-middleware" target="_blank">Webpack Hot Middleware</a></li> <li><a href="https://github.com/rackt/redux" target="_blank">Redux</a>'s futuristic <a href="https://facebook.github.io/react/blog/2014/05/06/flux.html" target="_blank">Flux</a> implementation </li> <li><a href="https://github.com/gaearon/redux-devtools" target="_blank">Redux Dev Tools</a> for next generation DX (developer experience). Watch <a href="https://www.youtube.com/watch?v=xsSnOQynTHs" target="_blank">Dan Abramov's talk</a>. </li> <li><a href="https://github.com/rackt/redux-router" target="_blank">Redux Router</a> Keep your router state in your Redux store </li> <li><a href="http://eslint.org" target="_blank">ESLint</a> to maintain a consistent code style</li> <li><a href="https://github.com/erikras/redux-form" target="_blank">redux-form</a> to manage form state in Redux </li> <li><a href="https://github.com/erikras/multireducer" target="_blank">multireducer</a> combine several identical reducer states into one key-based reducer</li> <li><a href="https://github.com/webpack/style-loader" target="_blank">style-loader</a> and <a href="https://github.com/jtangelder/sass-loader" target="_blank">sass-loader</a> to allow import of stylesheets </li> <li><a href="https://github.com/shakacode/bootstrap-sass-loader" target="_blank">bootstrap-sass-loader</a> and <a href="https://github.com/gowravshekar/font-awesome-webpack" target="_blank">font-awesome-webpack</a> to customize Bootstrap and FontAwesome </li> <li><a href="http://socket.io/">socket.io</a> for real-time communication</li> </ul> <h3>Features demonstrated in this project</h3> <dl> <dt>Multiple components subscribing to same redux store slice</dt> <dd> The <code>App.js</code> that wraps all the pages contains an <code>InfoBar</code> component that fetches data from the server initially, but allows for the user to refresh the data from the client. <code>About.js</code> contains a <code>MiniInfoBar</code> that displays the same data. </dd> <dt>Server-side data loading</dt> <dd> The <Link to="/widgets">Widgets page</Link> demonstrates how to fetch data asynchronously from some source that is needed to complete the server-side rendering. <code>Widgets.js</code>'s <code>asyncConnect()</code> function is called before the widgets page is loaded, on either the server or the client, allowing all the widget data to be loaded and ready for the page to render. </dd> <dt>Data loading errors</dt> <dd> The <Link to="/widgets">Widgets page</Link> also demonstrates how to deal with data loading errors in Redux. The API endpoint that delivers the widget data intentionally fails 33% of the time to highlight this. The <code>clientMiddleware</code> sends an error action which the <code>widgets</code> reducer picks up and saves to the Redux state for presenting to the user. </dd> <dt>Session based login</dt> <dd> On the <Link to="/login">Login page</Link> you can submit a username which will be sent to the server and stored in the session. Subsequent refreshes will show that you are still logged in. </dd> <dt>Redirect after state change</dt> <dd> After you log in, you will be redirected to a Login Success page. This <strike>magic</strike> logic is performed in <code>componentWillReceiveProps()</code> in <code>App.js</code>, but it could be done in any component that listens to the appropriate store slice, via Redux's <code>@connect</code>, and pulls the router from the context. </dd> <dt>Auth-required views</dt> <dd> The aforementioned Login Success page is only visible to you if you are logged in. If you try to <Link to="/loginSuccess">go there</Link> when you are not logged in, you will be forwarded back to this home page. This <strike>magic</strike> logic is performed by the <code>onEnter</code> hook within <code>routes.js</code>. </dd> <dt>Forms</dt> <dd> The <Link to="/survey">Survey page</Link> uses the still-experimental <a href="https://github.com/erikras/redux-form" target="_blank">redux-form</a> to manage form state inside the Redux store. This includes immediate client-side validation. </dd> <dt>WebSockets / socket.io</dt> <dd> The <Link to="/chat">Chat</Link> uses the socket.io technology for real-time communication between clients. You need to <Link to="/login">login</Link> first. </dd> </dl> <h3>From the author</h3> <p> I cobbled this together from a wide variety of similar "starter" repositories. As I post this in June 2015, all of these libraries are right at the bleeding edge of web development. They may fall out of fashion as quickly as they have come into it, but I personally believe that this stack is the future of web development and will survive for several years. I'm building my new projects like this, and I recommend that you do, too. </p> <p>Thanks for taking the time to check this out.</p> <p>– Erik Rasmussen</p> </div> </div> ); } }
app/javascript/mastodon/features/compose/components/action_bar.js
ikuradon/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import DropdownMenuContainer from '../../../containers/dropdown_menu_container'; import { defineMessages, injectIntl } from 'react-intl'; const messages = defineMessages({ edit_profile: { id: 'account.edit_profile', defaultMessage: 'Edit profile' }, pins: { id: 'navigation_bar.pins', defaultMessage: 'Pinned toots' }, preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' }, follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' }, favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' }, lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' }, blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' }, domain_blocks: { id: 'navigation_bar.domain_blocks', defaultMessage: 'Hidden domains' }, mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' }, filters: { id: 'navigation_bar.filters', defaultMessage: 'Muted words' }, logout: { id: 'navigation_bar.logout', defaultMessage: 'Logout' }, bookmarks: { id: 'navigation_bar.bookmarks', defaultMessage: 'Bookmarks' }, }); export default @injectIntl class ActionBar extends React.PureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, onLogout: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleLogout = () => { this.props.onLogout(); } render () { const { intl } = this.props; let menu = []; menu.push({ text: intl.formatMessage(messages.edit_profile), href: '/settings/profile' }); menu.push({ text: intl.formatMessage(messages.preferences), href: '/settings/preferences' }); menu.push({ text: intl.formatMessage(messages.pins), to: '/pinned' }); menu.push(null); menu.push({ text: intl.formatMessage(messages.follow_requests), to: '/follow_requests' }); menu.push({ text: intl.formatMessage(messages.favourites), to: '/favourites' }); menu.push({ text: intl.formatMessage(messages.bookmarks), to: '/bookmarks' }); menu.push({ text: intl.formatMessage(messages.lists), to: '/lists' }); menu.push(null); menu.push({ text: intl.formatMessage(messages.mutes), to: '/mutes' }); menu.push({ text: intl.formatMessage(messages.blocks), to: '/blocks' }); menu.push({ text: intl.formatMessage(messages.domain_blocks), to: '/domain_blocks' }); menu.push({ text: intl.formatMessage(messages.filters), href: '/filters' }); menu.push(null); menu.push({ text: intl.formatMessage(messages.logout), action: this.handleLogout }); return ( <div className='compose__action-bar'> <div className='compose__action-bar-dropdown'> <DropdownMenuContainer items={menu} icon='chevron-down' size={16} direction='right' /> </div> </div> ); } }
src/icons/IosFastforwardOutline.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class IosFastforwardOutline extends React.Component { render() { if(this.props.bare) { return <g> <path d="M48,155l183.5,101L48,356.9V155 M272,155.8L448,256L272,356.4v-95.6v-27.1V156 M256,128v123.2L32,128v256l224-123.2V384 l224-128L256,128L256,128z"></path> </g>; } return <IconBase> <path d="M48,155l183.5,101L48,356.9V155 M272,155.8L448,256L272,356.4v-95.6v-27.1V156 M256,128v123.2L32,128v256l224-123.2V384 l224-128L256,128L256,128z"></path> </IconBase>; } };IosFastforwardOutline.defaultProps = {bare: false}
src/svg-icons/maps/local-pharmacy.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalPharmacy = (props) => ( <SvgIcon {...props}> <path d="M21 5h-2.64l1.14-3.14L17.15 1l-1.46 4H3v2l2 6-2 6v2h18v-2l-2-6 2-6V5zm-5 9h-3v3h-2v-3H8v-2h3V9h2v3h3v2z"/> </SvgIcon> ); MapsLocalPharmacy = pure(MapsLocalPharmacy); MapsLocalPharmacy.displayName = 'MapsLocalPharmacy'; MapsLocalPharmacy.muiName = 'SvgIcon'; export default MapsLocalPharmacy;
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
bash7012/angular-tour-of-heros
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/MainContainer.js
KSMorozov/react-fundamentals-tutorial
import React from 'react'; import { transparent } from '../styles/styles'; const MainContainer = ({ children }) => <div className="jumbotron col-sm-12 text-center" {...transparent}> {children} </div>; export default MainContainer;
src/components/Experience.js
jalcantara90/cv
import React from 'react'; const Experience = (props) => { const myExperience = ( <div> {props.experience.map((exp) => <div className='item' key={exp.jobTitle}> <h3>{exp.jobTitle} @ {exp.company} <span>{exp.startDate} - {exp.endDate}</span></h3> <p>{exp.jobDescription}</p> </div> )} </div> ); return ( <div className='title'> <i className='fa fa-briefcase'></i> <h2>Work Experience</h2> {myExperience} </div> ) }; export default Experience;
docs/src/components/Playground/Atoms/IconButton/IconButton.js
seekinternational/seek-asia-style-guide
import styles from './IconButton.less'; import React from 'react'; import PropTypes from 'prop-types'; import { PlusIcon, DeleteIcon } from 'seek-asia-style-guide/react'; export default function IconButton({ children, icon }) { return ( <button className={styles.root}> {icon === 'plus' ? <PlusIcon /> : null } {icon === 'delete' ? <DeleteIcon /> : null } {children} </button> ); } IconButton.propTypes = { children: PropTypes.node, icon: PropTypes.oneOf(['plus', 'delete']).isRequired };
app/components/EditTask/EditTask.js
Jberivera/pandoras-wall
import React from 'react'; import styles from './EditTask.scss'; import classNames from 'classnames/bind'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { findGroup, findTask } from '../../js/findUp'; import { editTask } from './actions'; const css = classNames.bind(styles); class EditTask extends React.Component { constructor (props) { super(props); this.submitHandler = this.submitHandler.bind(this); } editModeHandler (e) { const editBtn = e.target; const editModeWrapper = editBtn.parentNode; const taskDescription = editModeWrapper.parentNode.querySelector('.js-task-description'); const textArea = editModeWrapper.querySelector('textarea'); const style = window.getComputedStyle(taskDescription); const paddingBottom = (/\d+/).exec(style.getPropertyValue('padding-bottom')).pop(); textArea.style.height = `${taskDescription.offsetHeight - paddingBottom + 10}px`; editModeWrapper.parentNode.classList.add('js-editMode'); } cancelHandler (e) { const task = findTask(e.target); task.classList.remove('js-editMode'); } submitHandler (e) { const { title, description } = e.currentTarget; const { id, editTask } = this.props; const groupFrom = findGroup(e.target); e.preventDefault(); e.currentTarget.parentNode.parentNode.classList.remove('js-editMode'); editTask(id, groupFrom, title.value, description.value); } render () { const { title, description } = this.props; return ( <div className={ css('editMode-wrapper') }> <button className={ css('editMode-btn', 'g-editMode-btn') } onClick={ this.editModeHandler }> edit </button> <form className={ css('edit-form', 'g-edit-form') } onSubmit={ this.submitHandler }> <input className={ css('edit-title') } type="text" name="title" defaultValue={ title }></input> <textarea className={ css('edit-description') } name="description" defaultValue={ description }></textarea> <div className={ css('centered-btns') }> <input className={ css('save-btn', 'btn') } type="submit" name="save" value="save"></input> <span className={ css('cancel-btn', 'btn') } onClick={ this.cancelHandler }>cancel</span> </div> </form> </div> ); } } const mapDispatchToProps = (dispatch) => bindActionCreators({ editTask }, dispatch); export { EditTask }; export default connect(null, mapDispatchToProps)(EditTask);
examples/js/complex/app.js
prajapati-parth/react-bootstrap-table
/* eslint no-unused-vars: 0 */ /* eslint no-console: 0 */ /* eslint space-infix-ops: 0 */ /* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const jobs = []; function addJobs(quantity) { const startId = jobs.length; for (let i = 0; i < quantity; i++) { const id = startId + i; let priority = 'D'; if (i % 2 === 0) priority = 'C'; if (i % 5 === 0) priority = 'B'; if (i % 7 === 0) priority = 'A'; jobs.push({ id: id, name: 'Item name ' + id, priority: priority, active: i%2 === 0 ? 'Y' : 'N' }); } } addJobs(70); function onRowSelect(row, isSelected) { console.log(row); console.log(`selected: ${isSelected}`); } function onSelectAll(isSelected) { console.log(`is select all: ${isSelected}`); } function onAfterSaveCell(row, cellName, cellValue) { console.log(`Save cell ${cellName} with value ${cellValue}`); console.log('The whole row :'); console.log(row); } function onAfterTableComplete() { console.log('Table render complete.'); } function onAfterDeleteRow(rowKeys) { console.log('onAfterDeleteRow'); console.log(rowKeys); } function onAfterInsertRow(row) { console.log('onAfterInsertRow'); console.log(row); } const selectRowProp = { mode: 'checkbox', clickToSelect: true, selected: [], // default select on table bgColor: 'rgb(238, 193, 213)', onSelect: onRowSelect, onSelectAll: onSelectAll }; const cellEditProp = { mode: 'click', blurToSave: true, afterSaveCell: onAfterSaveCell }; const options = { paginationShowsTotal: true, sortName: 'name', // default sort column name sortOrder: 'desc', // default sort order afterTableComplete: onAfterTableComplete, // A hook for after table render complete. afterDeleteRow: onAfterDeleteRow, // A hook for after droping rows. afterInsertRow: onAfterInsertRow // A hook for after insert rows }; function priorityFormatter(cell, row) { if (cell === 'A') return '<font color="red">' + cell + '</font>'; else if (cell === 'B') return '<font color="orange">' + cell + '</font>'; else return cell; } function trClassNameFormat(rowData, rIndex) { return rIndex % 3 === 0 ? 'third-tr' : ''; } function nameValidator(value) { if (!value) { return 'Job Name is required!'; } else if (value.length < 3) { return 'Job Name length must great 3 char'; } return true; } function priorityValidator(value) { if (!value) { return 'Priority is required!'; } return true; } export default class App extends React.Component { render() { return ( <BootstrapTable data={ jobs } trClassName={ trClassNameFormat } selectRow={ selectRowProp } cellEdit={ cellEditProp } options={ options } insertRow deleteRow search columnFilter hover pagination> <TableHeaderColumn dataField='id' dataAlign='center' dataSort isKey autoValue>Job ID</TableHeaderColumn> <TableHeaderColumn dataField='name' className='good' dataSort editable={ { type: 'textarea', validator: nameValidator } }>Job Name</TableHeaderColumn> <TableHeaderColumn dataField='priority' dataSort dataFormat={ priorityFormatter } editable={ { type: 'select', options: { values: [ 'A', 'B', 'C', 'D' ] }, validator: priorityValidator } }>Job Priority</TableHeaderColumn> <TableHeaderColumn dataField='active' editable={ { type: 'checkbox', options: { values: ' Y:N' } } }>Active</TableHeaderColumn> </BootstrapTable> ); } }
src/lib/purecomponent.js
fabriciocolombo/este
import React from 'react'; import shallowEqual from 'react/lib/shallowEqual'; /** * PureRenderMixin replacement for React component ES6 classes. * https://github.com/facebook/react/blob/ed3e6ecb9b86b97c09428f40deb8c3ed695e73e8/src/addons/ReactComponentWithPureRenderMixin.js */ export default class PureComponent extends React.Component { shouldComponentUpdate(nextProps, nextState) { return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState); } }
admin/client/App/shared/Popout/index.js
dryna/keystone-twoje-urodziny
/** * A Popout component. * One can also add a Header (Popout/Header), a Footer * (Popout/Footer), a Body (Popout/Body) and a Pan (Popout/Pane). */ import React from 'react'; import Portal from '../Portal'; import Transition from 'react-addons-css-transition-group'; const SIZES = { arrowHeight: 12, arrowWidth: 16, horizontalMargin: 20, }; var Popout = React.createClass({ displayName: 'Popout', propTypes: { isOpen: React.PropTypes.bool, onCancel: React.PropTypes.func, onSubmit: React.PropTypes.func, relativeToID: React.PropTypes.string.isRequired, width: React.PropTypes.number, }, getDefaultProps () { return { width: 320, }; }, getInitialState () { return {}; }, componentWillReceiveProps (nextProps) { if (!this.props.isOpen && nextProps.isOpen) { window.addEventListener('resize', this.calculatePosition); this.calculatePosition(nextProps.isOpen); } else if (this.props.isOpen && !nextProps.isOpen) { window.removeEventListener('resize', this.calculatePosition); } }, getPortalDOMNode () { return this.refs.portal.getPortalDOMNode(); }, calculatePosition (isOpen) { if (!isOpen) return; let posNode = document.getElementById(this.props.relativeToID); const pos = { top: 0, left: 0, width: posNode.offsetWidth, height: posNode.offsetHeight, }; while (posNode.offsetParent) { pos.top += posNode.offsetTop; pos.left += posNode.offsetLeft; posNode = posNode.offsetParent; } let leftOffset = Math.max(pos.left + (pos.width / 2) - (this.props.width / 2), SIZES.horizontalMargin); let topOffset = pos.top + pos.height + SIZES.arrowHeight; var spaceOnRight = window.innerWidth - (leftOffset + this.props.width + SIZES.horizontalMargin); if (spaceOnRight < 0) { leftOffset = leftOffset + spaceOnRight; } const arrowLeftOffset = leftOffset === SIZES.horizontalMargin ? pos.left + (pos.width / 2) - (SIZES.arrowWidth / 2) - SIZES.horizontalMargin : null; const newStateAvaliable = this.state.leftOffset !== leftOffset || this.state.topOffset !== topOffset || this.state.arrowLeftOffset !== arrowLeftOffset; if (newStateAvaliable) { this.setState({ leftOffset: leftOffset, topOffset: topOffset, arrowLeftOffset: arrowLeftOffset, }); } }, renderPopout () { if (!this.props.isOpen) return; const { arrowLeftOffset, leftOffset, topOffset } = this.state; const arrowStyles = arrowLeftOffset ? { left: 0, marginLeft: arrowLeftOffset } : null; return ( <div className="Popout" style={{ left: leftOffset, top: topOffset, width: this.props.width, }} > <span className="Popout__arrow" style={arrowStyles} /> <div className="Popout__inner"> {this.props.children} </div> </div> ); }, renderBlockout () { if (!this.props.isOpen) return; return <div className="blockout" onClick={this.props.onCancel} />; }, render () { return ( <Portal className="Popout-wrapper" ref="portal"> <Transition className="Popout-animation" transitionEnterTimeout={190} transitionLeaveTimeout={190} transitionName="Popout" component="div" > {this.renderPopout()} </Transition> {this.renderBlockout()} </Portal> ); }, }); module.exports = Popout; // expose the child to the top level export module.exports.Header = require('./PopoutHeader'); module.exports.Body = require('./PopoutBody'); module.exports.Footer = require('./PopoutFooter'); module.exports.Pane = require('./PopoutPane');
src/js/utils/index.js
ClubExpressions/poc-expression.club
import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; export function createConstants(...constants) { let tab= constants.reduce((acc, constant) => { acc[constant] = constant; return acc; }, {}); return tab; } export function createReducer(initialState, reducerMap) { return (state = initialState, action) => { const reducer = reducerMap[action.type]; return reducer ? reducer(state, action.payload) : state; }; } export function checkHttpStatus(response) { if (response.status >= 200 && response.status < 300) { return response } else { var error = new Error(response.statusText) error.response = response throw error } } export function parseJSON(response) { return response.json() }
app/components/ProductRow.js
Heatequation/react-router-redux-todo
import PropTypes from 'prop-types'; import React from 'react'; const ProductRow = ({ data }) => <div> <p>{data.name} = {data.price} </p> </div>; ProductRow.propTypes = { data: PropTypes.object }; export default ProductRow;
src/components/topic/platforms/ManagePlatformsContainer.js
mitmedialab/MediaCloud-Web-Tools
import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import { injectIntl, FormattedMessage, FormattedHTMLMessage } from 'react-intl'; import { Grid, Row, Col } from 'react-flexbox-grid/lib'; import { push } from 'react-router-redux'; import withAsyncData from '../../common/hocs/AsyncDataContainer'; import AvailablePlatformList from './AvailablePlatformList'; import messages from '../../../resources/messages'; import ConfirmationDialog from '../../common/ConfirmationDialog'; import { deleteTopicPlatform, setTopicNeedsNewSnapshot, fetchPlatformsInTopicList, selectPlatform, fetchTopicSummary } from '../../../actions/topicActions'; import { updateFeedback } from '../../../actions/appActions'; import IncompletePlatformWarning from './IncompletePlatformWarning'; import PlatformSizeNotice from './PlatformSizeNotice'; import VersionComparisonContainer from '../versions/VersionComparisonContainer'; import { filteredLinkTo } from '../../util/location'; import { MEDIA_CLOUD_SOURCE } from '../../../lib/platformTypes'; import * as fetchConstants from '../../../lib/fetchConstants'; const localMessages = { listTitle: { id: 'platform.list.title', defaultMessage: 'Platform Details' }, platformManageAbout: { id: 'platform.manage.about', defaultMessage: 'empty' }, removePlatform: { id: 'platform.manage.remove', defaultMessage: 'Remove Platform' }, removeOk: { id: 'platform.manage.remove.ok', defaultMessage: 'Remove It' }, removePlatformSucceeded: { id: 'platform.manage.remove.succeeded', defaultMessage: 'Removed the Platform' }, removePlatformFailed: { id: 'platform.manage.remove.failed', defaultMessage: 'Sorry, but removing the platform failed :-(' }, backToTopic: { id: 'backToTopic', defaultMessage: 'back to the topic' }, }; class ManagePlatformsContainer extends React.Component { state = { removeDialogOpen: false, platformToDelete: null, }; onCancelDeletePlatform = () => { this.setState({ removeDialogOpen: false, platformToDelete: null }); } onDeletePlatform = () => { const { topicId, handleDeletePlatform } = this.props; handleDeletePlatform(topicId, this.state.platformToDelete); this.setState({ removeDialogOpen: false, platformToDelete: null }); } onEditPlatform = (platform) => { const { topicId, filters, handleSelectPlatform } = this.props; // filteredLinkTo link to edit wizard // in edit, we will find latest topic_seed_query for this platform handleSelectPlatform( { ...platform }, filteredLinkTo(`/topics/${topicId}/platforms/${platform.topic_seed_queries_id}/edit`, filters) ); } onNewPlatform = (platform) => { const { topicId, filters, handleSelectNewPlatform } = this.props; handleSelectNewPlatform(platform, filteredLinkTo(`/topics/${topicId}/platforms/create`, filters)); } handleDelete = (platform) => { this.setState({ removeDialogOpen: true, platformToDelete: platform }); } render() { const { platforms, platformsHaveChanged, titleMsg } = this.props; const { formatMessage } = this.props.intl; /* TODO get the latest platform info of each category if exists, relevantPlatforms = platform.map... */ /* and, compare previous version with current to see if new platforms and if so, offer spider and generate */ /* { new vs old platforms are different ? <PlatformComparisonContainer platforms={platforms} onEditClicked={this.onEditPlatform} onAddClicked={this.onNewPlatform} /> : '' } */ let preventAdditions = false; let filteredPlatforms = platforms; // require that the mediasource platform is created first // to 'unlock' other platforms once we have a relevance query const incompleteWebPlatform = platforms.filter(p => p.topic_seed_queries_id !== -1 && p.source === MEDIA_CLOUD_SOURCE && p.query.indexOf('null') > -1); if (incompleteWebPlatform.length > 0) { filteredPlatforms = platforms.map(p => ({ ...p, isEnabled: (p.source === MEDIA_CLOUD_SOURCE) })); preventAdditions = true; } // sort in place so that the enabled platforms show up first filteredPlatforms.sort((p1, p2) => { if (!p1.isEnabled && p2.isEnabled) { return 1; } if (p1.isEnabled && !p2.isEnabled) { return -1; } return 0; }); // sort in place so that the enabled platforms show up first filteredPlatforms.sort((p1, p2) => { if (p2.source === MEDIA_CLOUD_SOURCE) { return 1; } if (p1.source === MEDIA_CLOUD_SOURCE) { return -1; } return 0; }); const h1Msg = titleMsg || messages.managePlatforms; return ( <div> <IncompletePlatformWarning /> <PlatformSizeNotice /> <div className="manage-platforms"> <Grid> <Row> <Col lg={10} xs={12}> <h1> <FormattedMessage {...h1Msg} /> </h1> </Col> </Row> {platformsHaveChanged && <VersionComparisonContainer />} <AvailablePlatformList platforms={filteredPlatforms} onEdit={this.onEditPlatform} onAdd={this.onNewPlatform} onDelete={this.handleDelete} preventAdditions={preventAdditions} /> </Grid> <ConfirmationDialog open={this.state.removeDialogOpen} title={formatMessage(localMessages.removePlatform)} okText={formatMessage(localMessages.removeOk)} onCancel={this.onCancelDeletePlatform} onOk={this.onDeletePlatform} > <FormattedHTMLMessage {...localMessages.removePlatform} /> </ConfirmationDialog> </div> </div> ); } } ManagePlatformsContainer.propTypes = { // from composition intl: PropTypes.object.isRequired, // from parent titleMsg: PropTypes.object, // alternate title // from state topicId: PropTypes.number.isRequired, filters: PropTypes.object.isRequired, platforms: PropTypes.array, fetchStatus: PropTypes.string.isRequired, platformsHaveChanged: PropTypes.bool.isRequired, // from dispatch handleDeletePlatform: PropTypes.func.isRequired, handleSelectPlatform: PropTypes.func.isRequired, handleSelectNewPlatform: PropTypes.func.isRequired, }; const mapStateToProps = state => ({ topicId: state.topics.selected.id, platforms: state.topics.selected.platforms.all.results, platformsHaveChanged: state.topics.selected.info.platformsHaveChanged, fetchStatus: state.topics.selected.platforms.all.fetchStatus, filters: state.topics.selected.filters, }); const mapDispatchToProps = (dispatch, ownProps) => ({ handleDeletePlatform: (topicId, platform) => { // dispatch(selectPlatform({ topic_seed_queries_id: platformId, platformType })); dispatch(deleteTopicPlatform(topicId, platform.topic_seed_queries_id)) .then((res) => { if (res.success === 0) { dispatch(updateFeedback({ classes: 'error-notice', open: true, message: ownProps.intl.formatMessage(localMessages.removePlatformFailed) })); } else { dispatch(updateFeedback({ classes: 'info-notice', open: true, message: ownProps.intl.formatMessage(localMessages.removePlatformSucceeded) })); dispatch(setTopicNeedsNewSnapshot(true)); dispatch(fetchTopicSummary(topicId)); // dispatch(fetchPlatformsInTopicList(topicId)); } }); }, handleSelectPlatform: (args, url) => { dispatch(selectPlatform(args)); dispatch(push(url)); }, handleSelectNewPlatform: (args, url) => { dispatch(selectPlatform(args)); dispatch(push(url)); }, }); const fetchAsyncData = (dispatch, { topicId, fetchStatus }) => { // this is a odd, and necessitates a forced refetch in EditPlatfromContainer and CreatePlatformConatiner if (fetchStatus !== fetchConstants.FETCH_SUCCEEDED) { dispatch(fetchPlatformsInTopicList(topicId)); } }; export default injectIntl( connect(mapStateToProps, mapDispatchToProps)( withAsyncData(fetchAsyncData, ['fetchStatus'])( ManagePlatformsContainer ) ) );
src/svg-icons/alert/error-outline.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AlertErrorOutline = (props) => ( <SvgIcon {...props}> <path d="M11 15h2v2h-2zm0-8h2v6h-2zm.99-5C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"/> </SvgIcon> ); AlertErrorOutline = pure(AlertErrorOutline); AlertErrorOutline.displayName = 'AlertErrorOutline'; AlertErrorOutline.muiName = 'SvgIcon'; export default AlertErrorOutline;
chrome/extension/popup.js
altany/react-new-tab-chrome-extension
import React from 'react'; import ReactDOM from 'react-dom'; import Root from '../../app/containers/PopupRoot'; import './todoapp.css'; chrome.storage.sync.get('state', (obj) => { const { state } = obj; const initialState = JSON.parse(state || '{}'); const createStore = require('../../app/store/configureStore'); ReactDOM.render( <Root store={createStore(initialState)} />, document.querySelector('#root') ); });
public/js/components/admin/feedback/others.react.js
IsuruDilhan/Coupley
/** * Created by Isuru 1 on 07/02/2016. */ import React from 'react'; import Table from 'material-ui/lib/table/table'; import TableHeaderColumn from 'material-ui/lib/table/table-header-column'; import TableRow from 'material-ui/lib/table/table-row'; import TableHeader from 'material-ui/lib/table/table-header'; import TableRowColumn from 'material-ui/lib/table/table-row-column'; import TableBody from 'material-ui/lib/table/table-body'; import FeedActions from '../../../actions/admin/FeedbackActions'; import FeedStore from '../../../stores/admin/FeedbackStore'; import Feed from '../feedback/feed.react'; const ELSE = 'No any other feedbacks.'; const Tables = React.createClass({ getInitialState: function () { return { results: FeedStore.getresults(), }; }, componentDidMount: function () { FeedActions.otherFeeds(); FeedStore.addChangeListener(this._onChange); }, _onChange: function () { if (this.isMounted()) { this.setState({ results: FeedStore.getresults(), }); } }, _renderFeedItem: function () { console.log(this.state.results); if (this.state.results) { return this.state.results.map((result) => { return (<Feed key={result.id} id={result.id} user={result.user} description={result.description} />); });} else { return (<div> No any other feedbacks. </div> ); } }, render: function () { return ( <div> <h1>Other Feedback </h1> <table className="table table-striped table-hover"> <thead> <tr> <th><h2>Id</h2></th> <th><h2>User</h2></th> <th><h2>Description</h2></th> </tr> </thead> <tbody style={{ fontSize: '18px' }}> {this._renderFeedItem()} </tbody> </table> </div> ); }, }); export default Tables;
docs/app/Examples/elements/Input/States/InputExampleLoading.js
mohammed88/Semantic-UI-React
import React from 'react' import { Input } from 'semantic-ui-react' const InputExampleLoading = () => ( <Input loading icon='user' placeholder='Search...' /> ) export default InputExampleLoading
src/GivingChart.js
RubenSandwich/givingChartGenerator
import React, { Component } from 'react'; const styles = { allPadding: { margin: '1rem 10px', }, }; function drawTitle({ ctx, x, y, nextLineOffset, fontSize }, year, month) { ctx.fillStyle = '#000'; const previousFont = ctx.font.replace(/"/g, ''); ctx.font = `${previousFont} Bold`; ctx.fillText('Financial Update', x, y); ctx.font = previousFont; const fiscalString = `Fiscal YTD - ${month} ${year}`; const fiscalStringWidth = ctx.measureText(fiscalString).width; ctx.fillText(fiscalString, x, y + nextLineOffset); return { x, y: y + nextLineOffset, fiscalStringWidth, }; } function drawGraphs({ ctx, x, y, fontSize }, giving, budget, maxBoxWidth) { const barHeight = 40; const barSpacing = 5; const givingRatio = giving / budget; const shortfall = budget - giving; ctx.font = ctx.font.replace(/\d+px/, `${fontSize}px`); ctx.font = ctx.font.replace(/\d+Bold/, ''); // Bar titles const givingX = x - 2; const givingTextY = y; ctx.fillStyle = '#000'; ctx.fillText(`Giving $${giving.toLocaleString()}`, givingX, givingTextY); if (shortfall > 0) { const shortfallTextWidth = ctx.measureText('Shortfall').width; const shortfallX = x + maxBoxWidth - shortfallTextWidth; const shortfallY = y; ctx.fillStyle = '#000'; ctx.fillText( `Shortfall $${shortfall.toLocaleString()}`, shortfallX, shortfallY, ); } // Giving Bar const givingBarY = y + fontSize / 4 + barSpacing / 2; let givingBarWidth = giving / budget * maxBoxWidth; // Always show a little Giving Bar if (givingRatio < 0.01) { givingBarWidth = barSpacing; } ctx.lineWidth = 2; ctx.strokeStyle = '#000'; if (shortfall > 0) { ctx.strokeRect(x, givingBarY, givingBarWidth, barHeight); } else { const overhang = 10; ctx.strokeRect(x, givingBarY, maxBoxWidth + overhang, barHeight); const overPlusTextfontSize = fontSize * 2; const overPlusTextX = x + maxBoxWidth + overhang + barSpacing; // Divided by 4 because font is 2x scaled const overPlusTextY = givingBarY + barHeight / 2 + overPlusTextfontSize / 4; // ctx.fontSize = fontSize; ctx.fillStyle = '#000'; ctx.font = ctx.font.replace(/\d+px/, `${overPlusTextfontSize}px`); ctx.fillText('+', overPlusTextX, overPlusTextY); } // Shortfall Bar const shortfallBarX = x + barSpacing + givingBarWidth; const shortfallBarY = givingBarY; const shortfallBarWidth = maxBoxWidth - givingBarWidth - barSpacing; if (shortfall > 0) { ctx.fillStyle = '#000'; ctx.fillRect(shortfallBarX, shortfallBarY, shortfallBarWidth, barHeight); } // Bottom Bar const bottomBarY = shortfallBarY + barHeight + barSpacing * 1.5; ctx.fillStyle = '#000'; ctx.fillRect(x - 1, bottomBarY, maxBoxWidth + 1, barHeight); const budgetTextX = x + maxBoxWidth + barSpacing; // Divided by 4 because font is 2x scaled const budgetTextY = bottomBarY + barHeight / 2 + fontSize / 4 + 2; ctx.font = ctx.font.replace(/\d+px/, `${fontSize}px`); ctx.fillStyle = '#000'; ctx.fillText(`Budget $${budget.toLocaleString()}`, budgetTextX, budgetTextY); const graphTickWidth = 3; const cutHeight = barHeight / 2 - barSpacing / 2; const bottomCutY = bottomBarY + barHeight - cutHeight; const leftCutX = x + graphTickWidth; // Draw cuts in bottom bar if (shortfall > 0) { const middleGraphTickSpacing = (barSpacing - graphTickWidth) / 2; // 1. Giving Bar Cuts const leftCutWidth = givingBarWidth - graphTickWidth + middleGraphTickSpacing; ctx.fillStyle = '#FFF'; ctx.clearRect(leftCutX, bottomBarY - 1, leftCutWidth, cutHeight + 1); ctx.fillStyle = '#FFF'; ctx.clearRect(leftCutX, bottomCutY, leftCutWidth, cutHeight + 1); // 2. Shortfall Bar Cuts const rightCutX = leftCutX + leftCutWidth + graphTickWidth; const rightCutWidth = shortfallBarWidth - graphTickWidth + middleGraphTickSpacing; ctx.fillStyle = '#FFF'; ctx.clearRect(rightCutX, bottomBarY - 1, rightCutWidth, cutHeight + 1); ctx.fillStyle = '#FFF'; ctx.clearRect(rightCutX, bottomCutY, rightCutWidth, cutHeight + 1); } else { const cutWidth = maxBoxWidth - graphTickWidth * 2; ctx.fillStyle = '#FFF'; ctx.clearRect(leftCutX, bottomBarY - 1, cutWidth, cutHeight + 1); ctx.fillStyle = '#FFF'; ctx.clearRect(leftCutX, bottomCutY, cutWidth, cutHeight + 1); } } function drawCanvas({ ctx }, props, maxBoxWidth, graphMargins, font) { const { width, height } = ctx.canvas; const { year, month, giving, budget } = props; ctx.clearRect(0, 0, width, height); const fontSize = font.size; const elementSpacing = 40; ctx.font = `${fontSize}px ${font.family}`; const titleFinish = drawTitle( { ctx, x: graphMargins, y: fontSize, nextLineOffset: fontSize + 3, fontSize, }, year, month, ); const titleFontWidthOffset = 6; drawGraphs( { ctx, x: graphMargins + titleFontWidthOffset, y: titleFinish.y + elementSpacing, fontSize: fontSize / 2, }, giving, budget, titleFinish.fiscalStringWidth - titleFontWidthOffset, titleFontWidthOffset, ); } function expectedGraphWidth(props, maxBoxWidth, graphMargins, font, scale) { const { budget } = props; const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); ctx.font = `${font.size / 2}px ${font.family}`; // Calculate the budget box line width const boxWidth = graphMargins + maxBoxWidth; const budgetStr = `budget $${budget.toLocaleString()}`; const budgetWidth = ctx.measureText(budgetStr).width; return (boxWidth + budgetWidth) / scale; } class GivingChart extends Component { font = { size: 48, family: 'Quattrocento Sans', }; maxBoxWidth = 500; graphMargins = 20; height = 125; getImageData() { const canvas = this.refs.canvas; return canvas.toDataURL('image/png'); } componentDidMount() { this.updateCanvas(); } componentDidUpdate() { this.updateCanvas(); } updateCanvas() { const { props, maxBoxWidth, graphMargins, font } = this; const ctx = this.refs.canvas.getContext('2d'); drawCanvas( { ctx, }, props, maxBoxWidth, graphMargins, font, ); } render() { const { props, maxBoxWidth, graphMargins, font, height } = this; const scale = 2; const ppi = 300; const width = expectedGraphWidth( props, maxBoxWidth, graphMargins, font, scale, ); // parseFloat to drop the extra 0's const widthPrint = parseFloat((width * scale / ppi).toFixed(2)); const heightPrint = parseFloat((height * scale / ppi).toFixed(2)); return ( <div> <canvas ref="canvas" style={{ width, height }} width={width * scale} height={height * scale} /> <p style={styles.allPadding}> {`Note: Chart is meant to be ${widthPrint}″ wide by ${heightPrint}″ high in print`} </p> </div> ); } } export default GivingChart;
app/src/routes/LoginCallback.js
quiaro/chunches
import React, { Component } from 'react'; import { Redirect } from 'react-router-dom'; import { gql, graphql } from 'react-apollo'; import { getIDToken, setUserSession, isLoggedIn, } from '../common/AuthService'; import ErrorHandler from '../common/ErrorHandler'; class Callback extends Component { constructor(props) { super(props); this.state = { loading: true, // Load data to verify if user is logged in or not isLoggedIn: false, }; } componentWillMount() { getIDToken() .then(idToken => { this.props .authenticateUser({ variables: { idToken, }, }) .then(response => { const { id, token } = response.data.authenticateUser; setUserSession(id, token); this.setState({ loading: false, isLoggedIn: isLoggedIn(), }); }); }) .catch(e => ErrorHandler(e)); } render() { const { loading, isLoggedIn } = this.state; if (loading) return <div>Loading</div>; if (isLoggedIn) return <Redirect to="/home" />; return <Redirect to="/" />; } } const AUTHENTICATE_USER = gql` mutation authenticateUser($idToken: String!) { authenticateUser(idToken: $idToken) { id token } } `; export default graphql(AUTHENTICATE_USER, { name: 'authenticateUser' })( Callback, );
app/components/no-match/no-match.js
dfmcphee/pinnr
import React from 'react'; export default class NoMatch extends React.Component { constructor(props) { super(props); } render() { return ( <div className="no-match"> <h1 className="no-match__title">Page not found</h1> </div> ); } }
packages/react-scripts/fixtures/kitchensink/src/features/syntax/ArraySpread.js
mangomint/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load(users) { return [ { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, ...users, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load([{ id: 42, name: '42' }]); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-array-spread"> {this.state.users.map(user => ( <div key={user.id}>{user.name}</div> ))} </div> ); } }
src/components/Loading.js
diegocasmo/workouter
import React from 'react' export const Loading = () => ( <div className='text-center pt-3 pb-3'> <div className='spinner-border' role='status'/> <p className='wkr-loading__text m-0'>Loading...</p> </div> )
src/components/Post/Post.js
oliveirafabio/wut-blog
import React from 'react' import Paper from 'material-ui/Paper' import Avatar from 'material-ui/Avatar' import Divider from 'material-ui/Divider' import DuckImage from '../../static/assets/Duck.jpg' import classes from './Post.scss' export const Post = (props) => { console.log(props) const { title, content } = props.post return ( <div className={classes['divider']}> <Paper zDepth={2} className={classes['papper']}> <div style={{display: 'flex'}}> <Avatar src={DuckImage} /> <h1>{title}</h1> </div> <section> {content} </section> </Paper> </div> ) } export default Post
app/components/Elements/AddTeamMemberModal.js
alexpell00/FRCUltimateManager
/* * @Author: alexpelletier * @Date: 2016-03-21 16:04:11 * @Last Modified by: alexpelletier * @Last Modified time: 2016-03-21 19:43:48 */ import React from 'react'; import { Link, hashHistory } from 'react-router'; import request from 'superagent'; var AddTeamMemberModal = React.createClass({ componentDidMount() { $('#addTeamMemberModal').modal('show'); }, componentWillUnmount() { $('#addTeamMemberModal').modal('hide'); }, addClicked() { request .post('/Api/Managment/TeamMembers/Add') .send({username: this.refs.emailInput.value,password: 'password', name: this.refs.nameInput.value}) .set('Accept', 'application/json') .end(function(err, res){ let user = JSON.parse(res.text); if (user.username){ this.props.onAddUser(user); hashHistory.push('/Managment/TeamMembers') } }.bind(this)); }, render() { return ( <div id="addTeamMemberModal" className="modal fade" tabIndex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style={{display: "none"}}> <div className="modal-dialog"> <div className="modal-content"> <div className="modal-header"> <button type="button" className="close" data-dismiss="modal" aria-hidden="true">×</button> <h4 className="modal-title" id="myModalLabel">Add Team Member</h4> </div> <div className="modal-body"> <form className="form-horizontal" role="form"> <fieldset> <div className="form-group"> <label for="hint-field" className="col-sm-4 control-label"> Email </label> <div className="col-sm-7"> <input type="text" ref="emailInput" id="transparent-field" className="form-control input-transparent" placeholder=""/> </div> </div> </fieldset> <fieldset> <div className="form-group"> <label for="hint-field" className="col-sm-4 control-label"> Name </label> <div className="col-sm-7"> <input type="text" ref="nameInput" id="transparent-field" className="form-control input-transparent" placeholder=""/> </div> </div> </fieldset> <div className="form-actions"> <div className="row"> <div className="col-sm-offset-5 col-sm-6"> <div className="btn-toolbar"> <input type="button" className="btn btn-primary" value="Add" onClick={this.addClicked}/> </div> </div> </div> </div> </form> </div> <div className="modal-footer"> <Link to='/Managment/TeamMembers/'> <button type="button" className="btn btn-default">Close</button> </Link> </div> </div> </div> </div> ); } }); module.exports = AddTeamMemberModal;
common/components/Nav.js
witt86/ERE
import React from 'react' import IndexLink from 'react-router/lib/IndexLink' import Link from 'react-router/lib/Link' import { StyleSheet, css } from 'aphrodite' const Nav = () => ( <div> <IndexLink to='/' className={css(styles.link)} activeClassName={css(styles.link, styles.activeLink)}> Home </IndexLink> <Link to='/posts' className={css(styles.link)} activeClassName={css(styles.link, styles.activeLink)}> Example Feed </Link> <a href='https://github.com/jaredpalmer/react-production-starter' className={css(styles.link)} target='_blank'>GitHub</a> <a href='https://twitter.com/jaredpalmer' className={css(styles.link)} target='_blank'>Twitter</a> </div> ) const styles = StyleSheet.create({ link: { maxWidth: 700, color: '#999', margin: '1.5rem 1rem 1.5rem 0', display: 'inline-block', textDecoration: 'none', fontWeight: 'bold', transition: '.2s opacity ease', ':hover': { opacity: 0.6 } }, activeLink: { color: '#000' } }) export default Nav
examples/containers/app/navMenu/NavMenu.js
alcedo-ui/alcedo-ui
/** * @file NavMenu.js */ import React from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as actions from 'reduxes/actions'; // Components import TextField from 'src/TextField'; import NavMenuList from './NavMenuList'; // Styles import './NavMenu.scss'; const NavMenu = ({ filter, updateFilter }) => ( <div className="nav-menu"> <TextField className="nav-menu-filter" value={filter} rightIconCls="fas fa-search" onChange={updateFilter}/> <NavMenuList/> </div> ); NavMenu.propTypes = { filter: PropTypes.string, updateFilter: PropTypes.func }; export default connect(state => ({ filter: state.navMenu.filter }), dispatch => bindActionCreators({ updateFilter: actions.updateFilter }, dispatch))(NavMenu);
app/containers/RepoListItem/index.js
gtct/wallet.eine.com
/** * RepoListItem * * Lists the name and the issue count of a repository */ import React from 'react'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import { FormattedNumber } from 'react-intl'; import { makeSelectCurrentUser } from 'containers/App/selectors'; import ListItem from 'components/ListItem'; import IssueIcon from './IssueIcon'; import IssueLink from './IssueLink'; import RepoLink from './RepoLink'; import Wrapper from './Wrapper'; export class RepoListItem extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { const item = this.props.item; let nameprefix = ''; // If the repository is owned by a different person than we got the data for // it's a fork and we should show the name of the owner if (item.owner.login !== this.props.currentUser) { nameprefix = `${item.owner.login}/`; } // Put together the content of the repository const content = ( <Wrapper> <RepoLink href={item.html_url} target="_blank"> {nameprefix + item.name} </RepoLink> <IssueLink href={`${item.html_url}/issues`} target="_blank"> <IssueIcon /> <FormattedNumber value={item.open_issues_count} /> </IssueLink> </Wrapper> ); // Render the content into a list item return ( <ListItem key={`repo-list-item-${item.full_name}`} item={content} /> ); } } RepoListItem.propTypes = { item: React.PropTypes.object, currentUser: React.PropTypes.string, }; export default connect(createStructuredSelector({ currentUser: makeSelectCurrentUser(), }))(RepoListItem);
src/index.js
sievins/stub
import React from 'react' import ReactDOM from 'react-dom' import './index.css' import App from './app' import * as serviceWorker from './serviceWorker' ReactDOM.render(<App />, document.getElementById('root')) // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister()
app/containers/HomePage/index.js
iFatansyReact/react-boilerplate-imagine
/* * HomePage * * This is the first thing users see of our App, at the '/' route */ import React from 'react'; import Helmet from 'react-helmet'; import { FormattedMessage } from 'react-intl'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import { makeSelectRepos, makeSelectLoading, makeSelectError } from 'containers/App/selectors'; import H2 from 'components/H2'; import ReposList from 'components/ReposList'; import AtPrefix from './AtPrefix'; import CenteredSection from './CenteredSection'; import Form from './Form'; import Input from './Input'; import Section from './Section'; import messages from './messages'; import { loadRepos } from '../App/actions'; import { changeUsername } from './actions'; import { makeSelectUsername } from './selectors'; export class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function /** * when initial state username is not null, submit the form to load repos */ componentDidMount() { if (this.props.username && this.props.username.trim().length > 0) { this.props.onSubmitForm(); } } render() { const { loading, error, repos } = this.props; const reposListProps = { loading, error, repos, }; return ( <article> <Helmet title="Home Page" meta={[ { name: 'description', content: 'A React.js Boilerplate application homepage' }, ]} /> <div> <CenteredSection> <H2> <FormattedMessage {...messages.startProjectHeader} /> </H2> <p> <FormattedMessage {...messages.startProjectMessage} /> </p> </CenteredSection> <Section> <H2> <FormattedMessage {...messages.trymeHeader} /> </H2> <Form onSubmit={this.props.onSubmitForm}> <label htmlFor="username"> <FormattedMessage {...messages.trymeMessage} /> <AtPrefix> <FormattedMessage {...messages.trymeAtPrefix} /> </AtPrefix> <Input id="username" type="text" placeholder="mxstbr" value={this.props.username} onChange={this.props.onChangeUsername} /> </label> </Form> <ReposList {...reposListProps} /> </Section> </div> </article> ); } } HomePage.propTypes = { loading: React.PropTypes.bool, error: React.PropTypes.oneOfType([ React.PropTypes.object, React.PropTypes.bool, ]), repos: React.PropTypes.oneOfType([ React.PropTypes.array, React.PropTypes.bool, ]), onSubmitForm: React.PropTypes.func, username: React.PropTypes.string, onChangeUsername: React.PropTypes.func, }; export function mapDispatchToProps(dispatch) { return { onChangeUsername: (evt) => dispatch(changeUsername(evt.target.value)), onSubmitForm: (evt) => { if (evt !== undefined && evt.preventDefault) evt.preventDefault(); dispatch(loadRepos()); }, }; } const mapStateToProps = createStructuredSelector({ repos: makeSelectRepos(), username: makeSelectUsername(), loading: makeSelectLoading(), error: makeSelectError(), }); // Wrap the component to inject dispatch and state into it export default connect(mapStateToProps, mapDispatchToProps)(HomePage);
node_modules/react-router/es6/Route.js
rekyyang/ArtificalLiverCloud
'use strict'; import React from 'react'; import invariant from 'invariant'; import { createRouteFromReactElement } from './RouteUtils'; import { component, components } from './InternalPropTypes'; var _React$PropTypes = React.PropTypes; var string = _React$PropTypes.string; var func = _React$PropTypes.func; /** * A <Route> is used to declare which components are rendered to the * page when the URL matches a given pattern. * * Routes are arranged in a nested tree structure. When a new URL is * requested, the tree is searched depth-first to find a route whose * path matches the URL. When one is found, all routes in the tree * that lead to it are considered "active" and their components are * rendered into the DOM, nested in the same order as in the tree. */ var Route = React.createClass({ displayName: 'Route', statics: { createRouteFromReactElement: createRouteFromReactElement }, propTypes: { path: string, component: component, components: components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Route> elements are for router configuration only and should not be rendered') : invariant(false) : undefined; } }); export default Route;
src/renderer/SearchComponent.js
Maai/markn
import React from 'react' import searchStore from './SearchStore' import dispatcher from './Dispatcher' import classNames from 'classnames' export default class SearchComponent extends React.Component { constructor(props) { super(props); this.state = { current: 0, total: 0, isShown: false, disabled: false }; this.action = new ActionCreator(); this.store = searchStore; this.store.on('openFind', this.show.bind(this)); this.store.on('closeFind', this.hide.bind(this)); this.store.on('updateDisable', this.updateDisable.bind(this)); this.store.on('focus-mark', this.onFocusMark.bind(this)); } show() { this.setState({isShown: true}); let input = React.findDOMNode(this.refs.search); input.focus(); input.select(); } hide() { this.setState({isShown: false}); } updateDisable(disabled) { this.setState({disabled}); } onInput() { let text = React.findDOMNode(this.refs.search).value; this.action.search(text); } onKeyDown(e) { if (e.key != 'Enter') return; this.action.next(); } onFocusMark(_, current, total) { this.setState({current, total}); } render() { return ( <div className={classNames('search-box', {'is-shown': this.state.isShown})}> <div className='search'> <input type='text' ref='search' onInput={this.onInput.bind(this)} onKeyDown={this.onKeyDown.bind(this)}/> <span className='index'>{this.state.total === 0 ? '' : `${this.state.current + 1}/${this.state.total}`}</span> </div> <button className='fa fa-chevron-up button-up' disabled={this.state.disabled}/> <button className='fa fa-chevron-down button-down' disabled={this.state.disabled}/> <button className='fa fa-times button-close' onClick={this.onClickClose.bind(this)}/> </div> ); } onClickClose() { this.action.close(); } } class ActionCreator { close() { dispatcher.emit('closeFind'); } search(text) { dispatcher.emit('search', text); } next() { dispatcher.emit('next-mark'); } }
node_modules/antd/es/table/Table.js
ZSMingNB/react-news
import _typeof from 'babel-runtime/helpers/typeof'; import _defineProperty from 'babel-runtime/helpers/defineProperty'; import _extends from 'babel-runtime/helpers/extends'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; var __rest = this && this.__rest || function (s, e) { var t = {}; for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; }if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]]; }return t; }; import React from 'react'; import { findDOMNode } from 'react-dom'; import RcTable from 'rc-table'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Pagination from '../pagination'; import Icon from '../icon'; import Spin from '../spin'; import warning from '../_util/warning'; import FilterDropdown from './filterDropdown'; import createStore from './createStore'; import SelectionBox from './SelectionBox'; import SelectionCheckboxAll from './SelectionCheckboxAll'; import Column from './Column'; import ColumnGroup from './ColumnGroup'; import { flatArray, treeMap, flatFilter, normalizeColumns } from './util'; function noop() {} function stopPropagation(e) { e.stopPropagation(); if (e.nativeEvent.stopImmediatePropagation) { e.nativeEvent.stopImmediatePropagation(); } } var defaultLocale = { filterTitle: '筛选', filterConfirm: '确定', filterReset: '重置', emptyText: React.createElement( 'span', null, React.createElement(Icon, { type: 'frown-o' }), '\u6682\u65E0\u6570\u636E' ), selectAll: '全选当页', selectInvert: '反选当页' }; var defaultPagination = { onChange: noop, onShowSizeChange: noop }; /** * Avoid creating new object, so that parent component's shouldComponentUpdate * can works appropriately。 */ var emptyObject = {}; var Table = function (_React$Component) { _inherits(Table, _React$Component); function Table(props) { _classCallCheck(this, Table); var _this = _possibleConstructorReturn(this, (Table.__proto__ || Object.getPrototypeOf(Table)).call(this, props)); _this.getCheckboxPropsByItem = function (item, index) { var _this$props$rowSelect = _this.props.rowSelection, rowSelection = _this$props$rowSelect === undefined ? {} : _this$props$rowSelect; if (!rowSelection.getCheckboxProps) { return {}; } var key = _this.getRecordKey(item, index); // Cache checkboxProps if (!_this.CheckboxPropsCache[key]) { _this.CheckboxPropsCache[key] = rowSelection.getCheckboxProps(item); } return _this.CheckboxPropsCache[key]; }; _this.handleFilter = function (column, nextFilters) { var props = _this.props; var pagination = _extends({}, _this.state.pagination); var filters = _extends({}, _this.state.filters, _defineProperty({}, _this.getColumnKey(column), nextFilters)); // Remove filters not in current columns var currentColumnKeys = []; treeMap(_this.columns, function (c) { if (!c.children) { currentColumnKeys.push(_this.getColumnKey(c)); } }); Object.keys(filters).forEach(function (columnKey) { if (currentColumnKeys.indexOf(columnKey) < 0) { delete filters[columnKey]; } }); if (props.pagination) { // Reset current prop pagination.current = 1; pagination.onChange(pagination.current); } var newState = { pagination: pagination, filters: {} }; var filtersToSetState = _extends({}, filters); // Remove filters which is controlled _this.getFilteredValueColumns().forEach(function (col) { var columnKey = _this.getColumnKey(col); if (columnKey) { delete filtersToSetState[columnKey]; } }); if (Object.keys(filtersToSetState).length > 0) { newState.filters = filtersToSetState; } // Controlled current prop will not respond user interaction if (_typeof(props.pagination) === 'object' && 'current' in props.pagination) { newState.pagination = _extends({}, pagination, { current: _this.state.pagination.current }); } _this.setState(newState, function () { _this.store.setState({ selectionDirty: false }); var onChange = _this.props.onChange; if (onChange) { onChange.apply(null, _this.prepareParamsArguments(_extends({}, _this.state, { selectionDirty: false, filters: filters, pagination: pagination }))); } }); }; _this.handleSelect = function (record, rowIndex, e) { var checked = e.target.checked; var defaultSelection = _this.store.getState().selectionDirty ? [] : _this.getDefaultSelection(); var selectedRowKeys = _this.store.getState().selectedRowKeys.concat(defaultSelection); var key = _this.getRecordKey(record, rowIndex); if (checked) { selectedRowKeys.push(_this.getRecordKey(record, rowIndex)); } else { selectedRowKeys = selectedRowKeys.filter(function (i) { return key !== i; }); } _this.store.setState({ selectionDirty: true }); _this.setSelectedRowKeys(selectedRowKeys, { selectWay: 'onSelect', record: record, checked: checked }); }; _this.handleRadioSelect = function (record, rowIndex, e) { var checked = e.target.checked; var defaultSelection = _this.store.getState().selectionDirty ? [] : _this.getDefaultSelection(); var selectedRowKeys = _this.store.getState().selectedRowKeys.concat(defaultSelection); var key = _this.getRecordKey(record, rowIndex); selectedRowKeys = [key]; _this.store.setState({ selectionDirty: true }); _this.setSelectedRowKeys(selectedRowKeys, { selectWay: 'onSelect', record: record, checked: checked }); }; _this.handleSelectRow = function (selectionKey, index, onSelectFunc) { var data = _this.getFlatCurrentPageData(); var defaultSelection = _this.store.getState().selectionDirty ? [] : _this.getDefaultSelection(); var selectedRowKeys = _this.store.getState().selectedRowKeys.concat(defaultSelection); var changeableRowKeys = data.filter(function (item, i) { return !_this.getCheckboxPropsByItem(item, i).disabled; }).map(function (item, i) { return _this.getRecordKey(item, i); }); var changeRowKeys = []; var selectWay = ''; var checked = void 0; // handle default selection switch (selectionKey) { case 'all': changeableRowKeys.forEach(function (key) { if (selectedRowKeys.indexOf(key) < 0) { selectedRowKeys.push(key); changeRowKeys.push(key); } }); selectWay = 'onSelectAll'; checked = true; break; case 'removeAll': changeableRowKeys.forEach(function (key) { if (selectedRowKeys.indexOf(key) >= 0) { selectedRowKeys.splice(selectedRowKeys.indexOf(key), 1); changeRowKeys.push(key); } }); selectWay = 'onSelectAll'; checked = false; break; case 'invert': changeableRowKeys.forEach(function (key) { if (selectedRowKeys.indexOf(key) < 0) { selectedRowKeys.push(key); } else { selectedRowKeys.splice(selectedRowKeys.indexOf(key), 1); } changeRowKeys.push(key); selectWay = 'onSelectInvert'; }); break; default: break; } _this.store.setState({ selectionDirty: true }); // when select custom selection, callback selections[n].onSelect if (index > 1 && typeof onSelectFunc === 'function') { return onSelectFunc(changeableRowKeys); } _this.setSelectedRowKeys(selectedRowKeys, { selectWay: selectWay, checked: checked, changeRowKeys: changeRowKeys }); }; _this.handlePageChange = function (current) { for (var _len = arguments.length, otherArguments = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { otherArguments[_key - 1] = arguments[_key]; } var props = _this.props; var pagination = _extends({}, _this.state.pagination); if (current) { pagination.current = current; } else { pagination.current = pagination.current || 1; } pagination.onChange.apply(pagination, [pagination.current].concat(otherArguments)); var newState = { pagination: pagination }; // Controlled current prop will not respond user interaction if (props.pagination && _typeof(props.pagination) === 'object' && 'current' in props.pagination) { newState.pagination = _extends({}, pagination, { current: _this.state.pagination.current }); } _this.setState(newState); _this.store.setState({ selectionDirty: false }); var onChange = _this.props.onChange; if (onChange) { onChange.apply(null, _this.prepareParamsArguments(_extends({}, _this.state, { selectionDirty: false, pagination: pagination }))); } }; _this.renderSelectionBox = function (type) { return function (_, record, index) { var rowIndex = _this.getRecordKey(record, index); // 从 1 开始 var props = _this.getCheckboxPropsByItem(record, index); var handleChange = function handleChange(e) { type === 'radio' ? _this.handleRadioSelect(record, rowIndex, e) : _this.handleSelect(record, rowIndex, e); }; return React.createElement( 'span', { onClick: stopPropagation }, React.createElement(SelectionBox, { type: type, store: _this.store, rowIndex: rowIndex, disabled: props.disabled, onChange: handleChange, defaultSelection: _this.getDefaultSelection() }) ); }; }; _this.getRecordKey = function (record, index) { var rowKey = _this.props.rowKey; var recordKey = typeof rowKey === 'function' ? rowKey(record, index) : record[rowKey]; warning(recordKey !== undefined, 'Each record in dataSource of table should have a unique `key` prop, or set `rowKey` to an unique primary key,' + 'see http://u.ant.design/table-row-key'); return recordKey === undefined ? index : recordKey; }; _this.getPopupContainer = function () { return findDOMNode(_this); }; _this.handleShowSizeChange = function (current, pageSize) { var pagination = _this.state.pagination; pagination.onShowSizeChange(current, pageSize); var nextPagination = _extends({}, pagination, { pageSize: pageSize, current: current }); _this.setState({ pagination: nextPagination }); var onChange = _this.props.onChange; if (onChange) { onChange.apply(null, _this.prepareParamsArguments(_extends({}, _this.state, { pagination: nextPagination }))); } }; warning(!('columnsPageRange' in props || 'columnsPageSize' in props), '`columnsPageRange` and `columnsPageSize` are removed, please use ' + 'fixed columns instead, see: http://u.ant.design/fixed-columns.'); _this.columns = props.columns || normalizeColumns(props.children); _this.state = _extends({}, _this.getSortStateFromColumns(), { // 减少状态 filters: _this.getFiltersFromColumns(), pagination: _this.getDefaultPagination(props) }); _this.CheckboxPropsCache = {}; _this.store = createStore({ selectedRowKeys: (props.rowSelection || {}).selectedRowKeys || [], selectionDirty: false }); return _this; } _createClass(Table, [{ key: 'getDefaultSelection', value: function getDefaultSelection() { var _this2 = this; var _props$rowSelection = this.props.rowSelection, rowSelection = _props$rowSelection === undefined ? {} : _props$rowSelection; if (!rowSelection.getCheckboxProps) { return []; } return this.getFlatData().filter(function (item, rowIndex) { return _this2.getCheckboxPropsByItem(item, rowIndex).defaultChecked; }).map(function (record, rowIndex) { return _this2.getRecordKey(record, rowIndex); }); } }, { key: 'getDefaultPagination', value: function getDefaultPagination(props) { var pagination = props.pagination || {}; return this.hasPagination(props) ? _extends({}, defaultPagination, pagination, { current: pagination.defaultCurrent || pagination.current || 1, pageSize: pagination.defaultPageSize || pagination.pageSize || 10 }) : {}; } }, { key: 'getLocale', value: function getLocale() { var locale = {}; if (this.context.antLocale && this.context.antLocale.Table) { locale = this.context.antLocale.Table; } return _extends({}, defaultLocale, locale, this.props.locale); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { this.columns = nextProps.columns || normalizeColumns(nextProps.children); if ('pagination' in nextProps || 'pagination' in this.props) { this.setState(function (previousState) { var newPagination = _extends({}, defaultPagination, previousState.pagination, nextProps.pagination); newPagination.current = newPagination.current || 1; newPagination.pageSize = newPagination.pageSize || 10; return { pagination: nextProps.pagination !== false ? newPagination : emptyObject }; }); } if (nextProps.rowSelection && 'selectedRowKeys' in nextProps.rowSelection) { this.store.setState({ selectedRowKeys: nextProps.rowSelection.selectedRowKeys || [] }); var rowSelection = this.props.rowSelection; if (rowSelection && nextProps.rowSelection.getCheckboxProps !== rowSelection.getCheckboxProps) { this.CheckboxPropsCache = {}; } } if ('dataSource' in nextProps && nextProps.dataSource !== this.props.dataSource) { this.store.setState({ selectionDirty: false }); this.CheckboxPropsCache = {}; } if (this.getSortOrderColumns(this.columns).length > 0) { var sortState = this.getSortStateFromColumns(this.columns); if (sortState.sortColumn !== this.state.sortColumn || sortState.sortOrder !== this.state.sortOrder) { this.setState(sortState); } } var filteredValueColumns = this.getFilteredValueColumns(this.columns); if (filteredValueColumns.length > 0) { var filtersFromColumns = this.getFiltersFromColumns(this.columns); var newFilters = _extends({}, this.state.filters); Object.keys(filtersFromColumns).forEach(function (key) { newFilters[key] = filtersFromColumns[key]; }); if (this.isFiltersChanged(newFilters)) { this.setState({ filters: newFilters }); } } } }, { key: 'setSelectedRowKeys', value: function setSelectedRowKeys(selectedRowKeys, _ref) { var _this3 = this; var selectWay = _ref.selectWay, record = _ref.record, checked = _ref.checked, changeRowKeys = _ref.changeRowKeys; var _props$rowSelection2 = this.props.rowSelection, rowSelection = _props$rowSelection2 === undefined ? {} : _props$rowSelection2; if (rowSelection && !('selectedRowKeys' in rowSelection)) { this.store.setState({ selectedRowKeys: selectedRowKeys }); } var data = this.getFlatData(); if (!rowSelection.onChange && !rowSelection[selectWay]) { return; } var selectedRows = data.filter(function (row, i) { return selectedRowKeys.indexOf(_this3.getRecordKey(row, i)) >= 0; }); if (rowSelection.onChange) { rowSelection.onChange(selectedRowKeys, selectedRows); } if (selectWay === 'onSelect' && rowSelection.onSelect) { rowSelection.onSelect(record, checked, selectedRows); } else if (selectWay === 'onSelectAll' && rowSelection.onSelectAll) { var changeRows = data.filter(function (row, i) { return changeRowKeys.indexOf(_this3.getRecordKey(row, i)) >= 0; }); rowSelection.onSelectAll(checked, selectedRows, changeRows); } else if (selectWay === 'onSelectInvert' && rowSelection.onSelectInvert) { rowSelection.onSelectInvert(selectedRowKeys); } } }, { key: 'hasPagination', value: function hasPagination(props) { return (props || this.props).pagination !== false; } }, { key: 'isFiltersChanged', value: function isFiltersChanged(filters) { var _this4 = this; var filtersChanged = false; if (Object.keys(filters).length !== Object.keys(this.state.filters).length) { filtersChanged = true; } else { Object.keys(filters).forEach(function (columnKey) { if (filters[columnKey] !== _this4.state.filters[columnKey]) { filtersChanged = true; } }); } return filtersChanged; } }, { key: 'getSortOrderColumns', value: function getSortOrderColumns(columns) { return flatFilter(columns || this.columns || [], function (column) { return 'sortOrder' in column; }); } }, { key: 'getFilteredValueColumns', value: function getFilteredValueColumns(columns) { return flatFilter(columns || this.columns || [], function (column) { return typeof column.filteredValue !== 'undefined'; }); } }, { key: 'getFiltersFromColumns', value: function getFiltersFromColumns(columns) { var _this5 = this; var filters = {}; this.getFilteredValueColumns(columns).forEach(function (col) { filters[_this5.getColumnKey(col)] = col.filteredValue; }); return filters; } }, { key: 'getSortStateFromColumns', value: function getSortStateFromColumns(columns) { // return fisrt column which sortOrder is not falsy var sortedColumn = this.getSortOrderColumns(columns).filter(function (col) { return col.sortOrder; })[0]; if (sortedColumn) { return { sortColumn: sortedColumn, sortOrder: sortedColumn.sortOrder }; } return { sortColumn: null, sortOrder: null }; } }, { key: 'getSorterFn', value: function getSorterFn() { var _state = this.state, sortOrder = _state.sortOrder, sortColumn = _state.sortColumn; if (!sortOrder || !sortColumn || typeof sortColumn.sorter !== 'function') { return; } return function (a, b) { var result = sortColumn.sorter(a, b); if (result !== 0) { return sortOrder === 'descend' ? -result : result; } return 0; }; } }, { key: 'toggleSortOrder', value: function toggleSortOrder(order, column) { var _state2 = this.state, sortColumn = _state2.sortColumn, sortOrder = _state2.sortOrder; // 只同时允许一列进行排序,否则会导致排序顺序的逻辑问题 var isSortColumn = this.isSortColumn(column); if (!isSortColumn) { sortOrder = order; sortColumn = column; } else { if (sortOrder === order) { sortOrder = ''; sortColumn = null; } else { sortOrder = order; } } var newState = { sortOrder: sortOrder, sortColumn: sortColumn }; // Controlled if (this.getSortOrderColumns().length === 0) { this.setState(newState); } var onChange = this.props.onChange; if (onChange) { onChange.apply(null, this.prepareParamsArguments(_extends({}, this.state, newState))); } } }, { key: 'renderRowSelection', value: function renderRowSelection() { var _this6 = this; var _props = this.props, prefixCls = _props.prefixCls, rowSelection = _props.rowSelection; var columns = this.columns.concat(); if (rowSelection) { var data = this.getFlatCurrentPageData().filter(function (item, index) { if (rowSelection.getCheckboxProps) { return !_this6.getCheckboxPropsByItem(item, index).disabled; } return true; }); var selectionColumnClass = classNames(prefixCls + '-selection-column', _defineProperty({}, prefixCls + '-selection-column-custom', rowSelection.selections)); var selectionColumn = { key: 'selection-column', render: this.renderSelectionBox(rowSelection.type), className: selectionColumnClass }; if (rowSelection.type !== 'radio') { var checkboxAllDisabled = data.every(function (item, index) { return _this6.getCheckboxPropsByItem(item, index).disabled; }); selectionColumn.title = React.createElement(SelectionCheckboxAll, { store: this.store, locale: this.getLocale(), data: data, getCheckboxPropsByItem: this.getCheckboxPropsByItem, getRecordKey: this.getRecordKey, disabled: checkboxAllDisabled, prefixCls: prefixCls, onSelect: this.handleSelectRow, selections: rowSelection.selections, getPopupContainer: this.getPopupContainer }); } if (columns.some(function (column) { return column.fixed === 'left' || column.fixed === true; })) { selectionColumn.fixed = 'left'; } if (columns[0] && columns[0].key === 'selection-column') { columns[0] = selectionColumn; } else { columns.unshift(selectionColumn); } } return columns; } }, { key: 'getColumnKey', value: function getColumnKey(column, index) { return column.key || column.dataIndex || index; } }, { key: 'getMaxCurrent', value: function getMaxCurrent(total) { var _state$pagination = this.state.pagination, current = _state$pagination.current, pageSize = _state$pagination.pageSize; if ((current - 1) * pageSize >= total) { return Math.floor((total - 1) / pageSize) + 1; } return current; } }, { key: 'isSortColumn', value: function isSortColumn(column) { var sortColumn = this.state.sortColumn; if (!column || !sortColumn) { return false; } return this.getColumnKey(sortColumn) === this.getColumnKey(column); } }, { key: 'renderColumnsDropdown', value: function renderColumnsDropdown(columns) { var _this7 = this; var _props2 = this.props, prefixCls = _props2.prefixCls, dropdownPrefixCls = _props2.dropdownPrefixCls; var sortOrder = this.state.sortOrder; var locale = this.getLocale(); return treeMap(columns, function (originColumn, i) { var column = _extends({}, originColumn); var key = _this7.getColumnKey(column, i); var filterDropdown = void 0; var sortButton = void 0; if (column.filters && column.filters.length > 0 || column.filterDropdown) { var colFilters = _this7.state.filters[key] || []; filterDropdown = React.createElement(FilterDropdown, { locale: locale, column: column, selectedKeys: colFilters, confirmFilter: _this7.handleFilter, prefixCls: prefixCls + '-filter', dropdownPrefixCls: dropdownPrefixCls || 'ant-dropdown', getPopupContainer: _this7.getPopupContainer }); } if (column.sorter) { var isSortColumn = _this7.isSortColumn(column); if (isSortColumn) { column.className = column.className || ''; if (sortOrder) { column.className += ' ' + prefixCls + '-column-sort'; } } var isAscend = isSortColumn && sortOrder === 'ascend'; var isDescend = isSortColumn && sortOrder === 'descend'; sortButton = React.createElement( 'div', { className: prefixCls + '-column-sorter' }, React.createElement( 'span', { className: prefixCls + '-column-sorter-up ' + (isAscend ? 'on' : 'off'), title: '\u2191', onClick: function onClick() { return _this7.toggleSortOrder('ascend', column); } }, React.createElement(Icon, { type: 'caret-up' }) ), React.createElement( 'span', { className: prefixCls + '-column-sorter-down ' + (isDescend ? 'on' : 'off'), title: '\u2193', onClick: function onClick() { return _this7.toggleSortOrder('descend', column); } }, React.createElement(Icon, { type: 'caret-down' }) ) ); } column.title = React.createElement( 'span', null, column.title, sortButton, filterDropdown ); return column; }); } }, { key: 'renderPagination', value: function renderPagination() { // 强制不需要分页 if (!this.hasPagination()) { return null; } var size = 'default'; var pagination = this.state.pagination; if (pagination.size) { size = pagination.size; } else if (this.props.size === 'middle' || this.props.size === 'small') { size = 'small'; } var total = pagination.total || this.getLocalData().length; return total > 0 ? React.createElement(Pagination, _extends({ key: 'pagination' }, pagination, { className: classNames(pagination.className, this.props.prefixCls + '-pagination'), onChange: this.handlePageChange, total: total, size: size, current: this.getMaxCurrent(total), onShowSizeChange: this.handleShowSizeChange })) : null; } // Get pagination, filters, sorter }, { key: 'prepareParamsArguments', value: function prepareParamsArguments(state) { var pagination = _extends({}, state.pagination); // remove useless handle function in Table.onChange delete pagination.onChange; delete pagination.onShowSizeChange; var filters = state.filters; var sorter = {}; if (state.sortColumn && state.sortOrder) { sorter.column = state.sortColumn; sorter.order = state.sortOrder; sorter.field = state.sortColumn.dataIndex; sorter.columnKey = this.getColumnKey(state.sortColumn); } return [pagination, filters, sorter]; } }, { key: 'findColumn', value: function findColumn(myKey) { var _this8 = this; var column = void 0; treeMap(this.columns, function (c) { if (_this8.getColumnKey(c) === myKey) { column = c; } }); return column; } }, { key: 'getCurrentPageData', value: function getCurrentPageData() { var data = this.getLocalData(); var current = void 0; var pageSize = void 0; var state = this.state; // 如果没有分页的话,默认全部展示 if (!this.hasPagination()) { pageSize = Number.MAX_VALUE; current = 1; } else { pageSize = state.pagination.pageSize; current = this.getMaxCurrent(state.pagination.total || data.length); } // 分页 // --- // 当数据量少于等于每页数量时,直接设置数据 // 否则进行读取分页数据 if (data.length > pageSize || pageSize === Number.MAX_VALUE) { data = data.filter(function (_, i) { return i >= (current - 1) * pageSize && i < current * pageSize; }); } return data; } }, { key: 'getFlatData', value: function getFlatData() { return flatArray(this.getLocalData()); } }, { key: 'getFlatCurrentPageData', value: function getFlatCurrentPageData() { return flatArray(this.getCurrentPageData()); } }, { key: 'recursiveSort', value: function recursiveSort(data, sorterFn) { var _this9 = this; var _props$childrenColumn = this.props.childrenColumnName, childrenColumnName = _props$childrenColumn === undefined ? 'children' : _props$childrenColumn; return data.sort(sorterFn).map(function (item) { return item[childrenColumnName] ? _extends({}, item, _defineProperty({}, childrenColumnName, _this9.recursiveSort(item[childrenColumnName], sorterFn))) : item; }); } }, { key: 'getLocalData', value: function getLocalData() { var _this10 = this; var state = this.state; var dataSource = this.props.dataSource; var data = dataSource || []; // 优化本地排序 data = data.slice(0); var sorterFn = this.getSorterFn(); if (sorterFn) { data = this.recursiveSort(data, sorterFn); } // 筛选 if (state.filters) { Object.keys(state.filters).forEach(function (columnKey) { var col = _this10.findColumn(columnKey); if (!col) { return; } var values = state.filters[columnKey] || []; if (values.length === 0) { return; } var onFilter = col.onFilter; data = onFilter ? data.filter(function (record) { return values.some(function (v) { return onFilter(v, record); }); }) : data; }); } return data; } }, { key: 'render', value: function render() { var _classNames2, _this11 = this; var _a = this.props, style = _a.style, className = _a.className, prefixCls = _a.prefixCls, showHeader = _a.showHeader, restProps = __rest(_a, ["style", "className", "prefixCls", "showHeader"]); var data = this.getCurrentPageData(); var columns = this.renderRowSelection(); var expandIconAsCell = this.props.expandedRowRender && this.props.expandIconAsCell !== false; var locale = this.getLocale(); var classString = classNames((_classNames2 = {}, _defineProperty(_classNames2, prefixCls + '-' + this.props.size, true), _defineProperty(_classNames2, prefixCls + '-bordered', this.props.bordered), _defineProperty(_classNames2, prefixCls + '-empty', !data.length), _defineProperty(_classNames2, prefixCls + '-without-column-header', !showHeader), _classNames2)); columns = this.renderColumnsDropdown(columns); columns = columns.map(function (column, i) { var newColumn = _extends({}, column); newColumn.key = _this11.getColumnKey(newColumn, i); return newColumn; }); var expandIconColumnIndex = columns[0] && columns[0].key === 'selection-column' ? 1 : 0; if ('expandIconColumnIndex' in restProps) { expandIconColumnIndex = restProps.expandIconColumnIndex; } var table = React.createElement(RcTable, _extends({ key: 'table' }, restProps, { prefixCls: prefixCls, data: data, columns: columns, showHeader: showHeader, className: classString, expandIconColumnIndex: expandIconColumnIndex, expandIconAsCell: expandIconAsCell, emptyText: function emptyText() { return locale.emptyText; } })); // if there is no pagination or no data, // the height of spin should decrease by half of pagination var paginationPatchClass = this.hasPagination() && data && data.length !== 0 ? prefixCls + '-with-pagination' : prefixCls + '-without-pagination'; var loading = this.props.loading; if (typeof loading === 'boolean') { loading = { spinning: loading }; } return React.createElement( 'div', { className: classNames(prefixCls + '-wrapper', className), style: style }, React.createElement( Spin, _extends({}, loading, { className: loading ? paginationPatchClass + ' ' + prefixCls + '-spin-holder' : '' }), table, this.renderPagination() ) ); } }]); return Table; }(React.Component); export default Table; Table.Column = Column; Table.ColumnGroup = ColumnGroup; Table.propTypes = { dataSource: PropTypes.array, columns: PropTypes.array, prefixCls: PropTypes.string, useFixedHeader: PropTypes.bool, rowSelection: PropTypes.object, className: PropTypes.string, size: PropTypes.string, loading: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]), bordered: PropTypes.bool, onChange: PropTypes.func, locale: PropTypes.object, dropdownPrefixCls: PropTypes.string }; Table.defaultProps = { dataSource: [], prefixCls: 'ant-table', useFixedHeader: false, rowSelection: null, className: '', size: 'large', loading: false, bordered: false, indentSize: 20, locale: {}, rowKey: 'key', showHeader: true }; Table.contextTypes = { antLocale: PropTypes.object };
node_modules/react-router/es/Link.js
raskolnikova/infomaps
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import React from 'react'; import createReactClass from 'create-react-class'; import { bool, object, string, func, oneOfType } from 'prop-types'; import invariant from 'invariant'; import { routerShape } from './PropTypes'; import { ContextSubscriber } from './ContextUtils'; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } // TODO: De-duplicate against hasAnyProperties in createTransitionManager. function isEmptyObject(object) { for (var p in object) { if (Object.prototype.hasOwnProperty.call(object, p)) return false; }return true; } function resolveToLocation(to, router) { return typeof to === 'function' ? to(router.location) : to; } /** * A <Link> is used to create an <a> element that links to a route. * When that route is active, the link gets the value of its * activeClassName prop. * * For example, assuming you have the following route: * * <Route path="/posts/:postID" component={Post} /> * * You could use the following component to link to that route: * * <Link to={`/posts/${post.id}`} /> */ var Link = createReactClass({ displayName: 'Link', mixins: [ContextSubscriber('router')], contextTypes: { router: routerShape }, propTypes: { to: oneOfType([string, object, func]), activeStyle: object, activeClassName: string, onlyActiveOnIndex: bool.isRequired, onClick: func, target: string }, getDefaultProps: function getDefaultProps() { return { onlyActiveOnIndex: false, style: {} }; }, handleClick: function handleClick(event) { if (this.props.onClick) this.props.onClick(event); if (event.defaultPrevented) return; var router = this.context.router; !router ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Link>s rendered outside of a router context cannot navigate.') : invariant(false) : void 0; if (isModifiedEvent(event) || !isLeftClickEvent(event)) return; // If target prop is set (e.g. to "_blank"), let browser handle link. /* istanbul ignore if: untestable with Karma */ if (this.props.target) return; event.preventDefault(); router.push(resolveToLocation(this.props.to, router)); }, render: function render() { var _props = this.props, to = _props.to, activeClassName = _props.activeClassName, activeStyle = _props.activeStyle, onlyActiveOnIndex = _props.onlyActiveOnIndex, props = _objectWithoutProperties(_props, ['to', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']); // Ignore if rendered outside the context of router to simplify unit testing. var router = this.context.router; if (router) { // If user does not specify a `to` prop, return an empty anchor tag. if (!to) { return React.createElement('a', props); } var toLocation = resolveToLocation(to, router); props.href = router.createHref(toLocation); if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) { if (router.isActive(toLocation, onlyActiveOnIndex)) { if (activeClassName) { if (props.className) { props.className += ' ' + activeClassName; } else { props.className = activeClassName; } } if (activeStyle) props.style = _extends({}, props.style, activeStyle); } } } return React.createElement('a', _extends({}, props, { onClick: this.handleClick })); } }); export default Link;
client/admin/settings/Section.stories.js
iiet/iiet-chat
import React from 'react'; import { Section } from './Section'; export default { title: 'admin/settings/Section', component: Section, }; export const _default = () => <Section groupId='General' />; export const skeleton = () => <Section.Skeleton />;
src/js/mixins/container_mixin.js
working-minds/realizejs
import React from 'react'; import PropTypes from '../prop_types'; import _ from 'lodash'; export default { propTypes: { forwardedProps: PropTypes.object, ignoreForwarded: PropTypes.array, }, getDefaultProps() { return { forwardedProps: {}, }; }, getChildren() { return this.cloneChildrenWithProps(); }, renderChildren() { return this.cloneChildrenWithProps(); }, filterChildren(childType) { const result = []; React.Children.map(this.props.children, (child) => { if (!!child && child.type === childType) { result.push(child); } }); return result; }, cloneChildrenWithProps(options) { const props = this.buildPropsToForward(); const cloneChildWithProps = this.cloneChildWithProps.bind(this, props); if (!!options && !!options.childrenType) { return React.Children.map(this.filterChildren(options.childrenType), cloneChildWithProps); } return React.Children.map(this.props.children, cloneChildWithProps); }, cloneChildWithProps(props, child) { const forwardedProps = _.merge({}, this.props.forwardedProps, props); if (!child || !child.type) { return null; } return React.cloneElement( child, _.merge({}, forwardedProps, this.buildChildPropsToKeep(child), { forwardedProps }) ); }, buildChildPropsToKeep(child) { const { getDefaultProps } = child.type; const { ignoreForwarded } = child.props; const defaultChildProps = getDefaultProps ? child.type.getDefaultProps() : {}; const keepProps = Array.isArray(ignoreForwarded) ? ignoreForwarded : []; return Object.keys(child.props) .filter((propKey) => ( this.childPropValueIsNotDefault(child.props[propKey], defaultChildProps[propKey]) || this.shouldKeepChildPropValueAnyway(propKey, keepProps) )) .reduce((acc, propKey) => Object.assign(acc, { [propKey]: child.props[propKey] }), {}); }, childPropValueIsNotDefault(propValue, defaultPropValue) { return !_.isEqual(propValue, defaultPropValue); }, shouldKeepChildPropValueAnyway (propName, keepList) { return keepList.indexOf(propName) >= 0; }, buildPropsToForward() { const propsToForward = this.propsToForward ? this.propsToForward() : []; const forwardMapping = this.propsToForwardMapping ? this.propsToForwardMapping() : {}; return _.merge(propsToForward.reduce((acc, propToForward) => ( Object.assign(acc, { [propToForward]: this.props[propToForward] }) ), {}), forwardMapping); }, };
example/src/index.js
Tom910/react-async-loading
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.js'; ReactDOM.render( <App />, document.getElementById('root') );
src/svg-icons/maps/local-printshop.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalPrintshop = (props) => ( <SvgIcon {...props}> <path d="M19 8H5c-1.66 0-3 1.34-3 3v6h4v4h12v-4h4v-6c0-1.66-1.34-3-3-3zm-3 11H8v-5h8v5zm3-7c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm-1-9H6v4h12V3z"/> </SvgIcon> ); MapsLocalPrintshop = pure(MapsLocalPrintshop); MapsLocalPrintshop.displayName = 'MapsLocalPrintshop'; MapsLocalPrintshop.muiName = 'SvgIcon'; export default MapsLocalPrintshop;
src/components/topic/snapshots/foci/builder/FocusForm3DescribeContainer.js
mitmedialab/MediaCloud-Web-Tools
import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import { reduxForm, formValueSelector } from 'redux-form'; import { FormattedMessage, injectIntl } from 'react-intl'; import { Grid, Row, Col } from 'react-flexbox-grid/lib'; import withIntlForm from '../../../../common/hocs/IntlForm'; import AppButton from '../../../../common/AppButton'; import FocusDescriptionForm, { NEW_FOCAL_SET_PLACEHOLDER_ID } from './FocusDescriptionForm'; import { FOCAL_TECHNIQUE_BOOLEAN_QUERY, FOCAL_TECHNIQUE_RETWEET_PARTISANSHIP, FOCAL_TECHNIQUE_TOP_COUNTRIES, FOCAL_TECHNIQUE_NYT_THEME, FOCAL_TECHNIQUE_MEDIA_TYPE } from '../../../../../lib/focalTechniques'; import { goToCreateFocusStep } from '../../../../../actions/topicActions'; import messages from '../../../../../resources/messages'; import FocalSetForm from './FocalSetForm'; const formSelector = formValueSelector('snapshotFocus'); const localMessages = { title: { id: 'focus.create.setup3.title', defaultMessage: 'Step 3: Describe Your Subtopic' }, retweetIntro: { id: 'focus.create.setup3.retweetIntro', defaultMessage: 'This will create a set with one subtopic for each of the partisan quintiles. For example, any story from a media source in the "center left" group will be put into the "center left" subtopic in this set. Name thet set and we will create the subtopics within it. Give it a name that makes these subtopics easy to identify later.' }, topCountriesIntro: { id: 'focus.create.setup3.title', defaultMessage: 'This will create a subtopic containing the stories mentioning the top most tagged countries' }, nytThemeIntro: { id: 'focus.create.setup3.nytTheme.title', defaultMessage: 'This will create a subtopic containing the stories tagged by New York Times Themes' }, mediaTypeIntro: { id: 'focus.create.setup3.mediaType.title', defaultMessage: 'This will create a subtopic containing the stories tagged by media type' }, mediaSearchIntro: { id: 'focus.create.setup3.mediaSearch.title', defaultMessage: 'This will create a subtopic containing the stories tagged by media id' }, duplicateName: { id: 'focus.create.setup3.duplicateName', defaultMessage: 'Duplicate Name' }, }; const FocusForm3DescribeContainer = (props) => { const { topicId, handleSubmit, finishStep, goToStep, initialValues, focalSetDefinitions, formData } = props; const { formatMessage } = props.intl; let introContent; // figure out a which focal set to default to if (focalSetDefinitions.length === 0) { initialValues.focalSetId = NEW_FOCAL_SET_PLACEHOLDER_ID; } else { initialValues.focalSetId = focalSetDefinitions[0].focal_set_definitions_id; } const includeDefsInitialValues = initialValues; includeDefsInitialValues.focalSetDefinitions = focalSetDefinitions; let content; switch (formData.focalTechnique) { case FOCAL_TECHNIQUE_BOOLEAN_QUERY: content = ( <FocusDescriptionForm topicId={topicId} initialValues={initialValues} focalSetDefinitions={focalSetDefinitions} focalTechnique={formData.focalTechnique} currentFocalSetDefinitionId={formData.focalSetDefinitionId} keywords={formData.keywords} /> ); break; case FOCAL_TECHNIQUE_RETWEET_PARTISANSHIP: introContent = ( <p><FormattedMessage {...localMessages.retweetIntro} /></p> ); content = ( <Row> <Col lg={10}> <FocalSetForm initialValues={includeDefsInitialValues} introContent={introContent} focalTechnique={formData.focalTechnique} fullWidth /> </Col> </Row> ); break; case FOCAL_TECHNIQUE_TOP_COUNTRIES: introContent = ( <p><FormattedMessage {...localMessages.topCountriesIntro} /></p> ); content = ( <Row> <Col lg={10}> <FocalSetForm initialValues={includeDefsInitialValues} introContent={introContent} focalTechnique={formData.focalTechnique} fullWidth /> </Col> </Row> ); break; case FOCAL_TECHNIQUE_NYT_THEME: introContent = ( <p><FormattedMessage {...localMessages.nytThemeIntro} /></p> ); content = ( <Row> <Col lg={10}> <FocalSetForm initialValues={includeDefsInitialValues} introContent={introContent} focalTechnique={formData.focalTechnique} fullWidth /> </Col> </Row> ); break; case FOCAL_TECHNIQUE_MEDIA_TYPE: introContent = ( <p><FormattedMessage {...localMessages.mediaTypeIntro} /></p> ); content = ( <Row> <Col lg={10}> <FocalSetForm initialValues={includeDefsInitialValues} introContent={introContent} focalTechnique={formData.focalTechnique} fullWidth /> </Col> </Row> ); break; default: content = <FormattedMessage {...messages.unimplemented} />; } return ( <Grid> <form className="focus-create-details" name="snapshotFocus" onSubmit={handleSubmit(finishStep.bind(this))}> <Row> <Col lg={10}> <h1><FormattedMessage {...localMessages.title} /></h1> </Col> </Row> {content} <Row> <Col lg={12}> <AppButton variant="outlined" color="secondary" label={formatMessage(messages.previous)} onClick={() => goToStep(1)} /> &nbsp; &nbsp; <AppButton type="submit" label={formatMessage(messages.next)} primary /> </Col> </Row> </form> </Grid> ); }; FocusForm3DescribeContainer.propTypes = { // from parent topicId: PropTypes.number.isRequired, initialValues: PropTypes.object, // form composition intl: PropTypes.object.isRequired, renderTextField: PropTypes.func.isRequired, renderSelect: PropTypes.func.isRequired, handleSubmit: PropTypes.func.isRequired, // from state fetchStatus: PropTypes.string.isRequired, focalSetDefinitions: PropTypes.array.isRequired, formData: PropTypes.object, // from dispatch goToStep: PropTypes.func.isRequired, finishStep: PropTypes.func.isRequired, }; const mapStateToProps = state => ({ focalSetDefinitions: state.topics.selected.focalSets.definitions.list, fetchStatus: state.topics.selected.focalSets.definitions.fetchStatus, formData: formSelector(state, 'focalTechnique', 'focalSetDefinitionId', 'keywords'), }); const mapDispatchToProps = dispatch => ({ goToStep: (step) => { dispatch(goToCreateFocusStep(step)); }, }); function mergeProps(stateProps, dispatchProps, ownProps) { return { ...stateProps, ...dispatchProps, ...ownProps, finishStep: () => { dispatchProps.goToStep(3); } }; } function validate(values, props) { const errors = {}; // TODO: figure out if we need to do more validation here, because in theory the // subforms components have already done it if (props.initialValues.focalSetDefinitions) { const nameAlreadyExists = props.initialValues.focalSetDefinitions.filter(fc => fc.name === values.focalSetName); if (nameAlreadyExists.length > 0) { // return dispatch(addNotice({ level: LEVEL_ERROR, message: ownProps.intl.formatMessage(localMessages.duplicateName) })); errors.focalSetName = localMessages.duplicateName; errors.focalSetName = { _error: localMessages.duplicateName }; errors.focusName = localMessages.duplicateName; } } return errors; } const reduxFormConfig = { form: 'snapshotFocus', // make sure this matches the sub-components and other wizard steps destroyOnUnmount: false, // <------ preserve form data forceUnregisterOnUnmount: true, // <------ unregister fields on unmount validate, }; export default injectIntl( withIntlForm( reduxForm(reduxFormConfig)( connect(mapStateToProps, mapDispatchToProps, mergeProps)( FocusForm3DescribeContainer ) ) ) );
src/Connected/inner/View.js
dht/lpm
import React from 'react'; import Base from './Base'; const View = (props) => { const {content} = props, containerStyle = {...styleView, backgroundImage: `url(${content})`} return <Base {...props} containerStyle={containerStyle}> </Base> } export default View; const styleView = { position: 'relative', }
src/pages/App.js
HeliumLau/Hoop-react
import React from 'react' import PropTypes from 'prop-types' import './App.less' import { Link } from 'react-router' import { connect } from 'react-redux' import { loadingShow } from 'store/action.js' class APP extends React.Component { constructor(props) { super(props); this.state = { loading: true }; this.search = this.search.bind(this); } componentDidMount() { console.log(this.props.waitingForLoading); console.log('mounted'); setTimeout(() => { this.setState({ loading: false }) console.log(this.props.waitingForLoading); }, 1000) } search() { console.log(this.context); this.context.router.push('/search'); } render() { const { dispatch, waitingForLoading } = this.props; return ( <div> <header className="header"> <i className="icon-logo"></i> <i className="icon-search" onClick={this.search}></i> </header> <section className="main-content"> {this.state.loading ? <div>加载中</div> : this.props.children} </section> <footer> <ul className="index-navigations"> <li className="index-navigation"><Link to="/app/match" activeClassName="active"><i className="icon-match"></i>比赛</Link></li> <li className="index-navigation"><Link to="/app/news" activeClassName="active"><i className="icon-news"></i>新闻</Link></li> <li className="index-navigation"><Link to="/app/community" activeClassName="active"><i className="icon-community"></i>社区</Link></li> <li className="index-navigation"><Link to="/app/data" activeClassName="active"><i className="icon-data"></i>数据</Link></li> <li className="index-navigation"><Link to="/app/more" activeClassName="active"><i className="icon-more"></i>更多</Link></li> </ul> </footer> </div> ) } } APP.contextTypes = { router: PropTypes.object } APP.propTypes = { waitingForLoading: PropTypes.boolean } function select(state) { return { waitingForLoading: state.waitingForLoading } } export default connect(select)(APP)